Skip to main content

hyprstream_rpc_derive/codegen/
leaf.rs

1//! Full method-leaf tree computation and the generated single-decode body
2//! decoder (v16 §5.1/§5.2).
3//!
4//! One shared tree walk ([`collect_method_leaves`]) drives both:
5//!
6//! - [`generate_body_decoder`] — the generated
7//!   `decode_<service>_request_body` function performing the ONE bounded
8//!   Cap'n Proto decode and deriving the full nested union-discriminant leaf
9//!   path from the signed body; and
10//! - the generated method-policy inventory rows (one row per leaf).
11//!
12//! Because both are produced from the same walk, the decoder can never derive
13//! a leaf the inventory does not list, and the inventory can never list a
14//! leaf the decoder cannot derive — the agreement is by construction, not by
15//! review.
16//!
17//! The walk descends exactly the unions that select handlers:
18//!
19//! - the root request union (always);
20//! - scoped-client subtrees (`ScopedClient`, recursively through
21//!   `nested_clients`) — these are the nested method unions generated scope
22//!   dispatch routes on; and
23//! - local pure-union struct payloads that are not `Option<T>` wrappers —
24//!   these are inner method selectors dispatched from raw bytes.
25//!
26//! Everything else — struct parameters (even union-bearing ones), imported
27//! types, groups — is method *payload*, not method identity, and terminates
28//! the leaf.
29
30use proc_macro2::TokenStream;
31use quote::{format_ident, quote};
32
33use hyprstream_rpc_build::schema::dispatch_label::{
34    parse_dispatch_mac, parse_dispatch_public_reason, InitialLabelMap, READ_CLASS_ACTIONS,
35};
36use hyprstream_rpc_build::schema::mutation_policy::{
37    parse_mutation_semantics, DeclaredMutationSemantics,
38};
39
40use crate::resolve::ResolvedSchema;
41use crate::schema::types::*;
42use crate::util::*;
43
44/// One method leaf discovered by the shared tree walk.
45pub struct MethodLeaf {
46    /// Full union-discriminant chain from the root request union.
47    pub path: Vec<u16>,
48    /// Dotted human-readable path (review metadata, e.g. `repo.create`).
49    pub symbolic: String,
50    /// `$scope`/`$capability` action of the leaf variant. Empty when the leaf
51    /// is scope-exempt or sits below a hand-dispatched pure union whose
52    /// arms carry no annotations.
53    pub scope: String,
54    /// Whether the leaf variant is `$scopeExempt` (control-plane exemption).
55    pub scope_exempt: bool,
56    /// `$dispatchMac` label text (strict grammar, v16 §6). Empty when the leaf
57    /// is `$dispatchPublic` or the annotation is inherited from a selector.
58    pub dispatch_mac: String,
59    pub dispatch_mac_present: bool,
60    /// `$dispatchPublic` reason text. Empty for `$dispatchMac` leaves.
61    pub dispatch_public: String,
62    pub dispatch_public_present: bool,
63    /// Explicit `$mutationSemantics` metadata for a mutating executable leaf:
64    /// the leaf's own annotation when present, else the declaration inherited
65    /// from its nearest annotated ancestor selector. Never a default — a leaf
66    /// left with nothing still fails the closed parser at row generation.
67    pub mutation_semantics: String,
68    pub mutation_semantics_present: bool,
69    /// Validation failure found on this leaf or an ancestor selector.
70    pub validation_error: Option<String>,
71}
72
73/// Per-arm metadata resolved during the walk.
74struct ArmMeta<'a> {
75    name: &'a str,
76    discriminant: u16,
77    type_name: &'a str,
78    scope: &'a str,
79    scope_exempt: bool,
80    dispatch_mac: &'a str,
81    dispatch_mac_present: bool,
82    dispatch_public: &'a str,
83    dispatch_public_present: bool,
84    mutation_semantics: &'a str,
85    mutation_semantics_present: bool,
86}
87
88/// Annotation state inherited from the nearest annotated ancestor selector.
89/// Only hand-dispatched pure-union selectors propagate annotations downward
90/// (scoped-client dispatchers carry none by rule); arms below them may carry
91/// their own, and a local annotation always wins over the inherited one.
92/// `$dispatchPublic` is **never** inherited — it is legal only on leaves — so
93/// only the MAC label and the mutation-semantics declaration flow through
94/// here; an inherited public reason is surfaced as the build error it is
95/// (see `walk_level`).
96#[derive(Clone, Default)]
97struct Inherited {
98    scope: String,
99    scope_exempt: bool,
100    dispatch_mac: String,
101    dispatch_mac_present: bool,
102    dispatch_public: String,
103    dispatch_public_present: bool,
104    mutation_semantics: String,
105    mutation_semantics_present: bool,
106    validation_error: Option<String>,
107}
108
109/// The arms of one union level, in schema declaration order.
110///
111/// Root level: `request_variants` + discriminants from `request_struct`
112/// (index fallback for text-parsed schemas without wire info, matching the
113/// existing dispatch discriminator behavior). Scope level: the scope struct's
114/// union fields, with metadata joined from `inner_request_variants`.
115fn level_arms<'a>(sdef: Option<&'a StructDef>, variants: &'a [UnionVariant]) -> Vec<ArmMeta<'a>> {
116    match sdef {
117        Some(sdef) => sdef
118            .union_fields()
119            .map(|f| {
120                let meta = variants.iter().find(|v| v.name == f.name);
121                let union_arm = sdef.union_arms.iter().find(|a| a.name == f.name);
122                ArmMeta {
123                    name: &f.name,
124                    discriminant: f.discriminant_value,
125                    type_name: &f.type_name,
126                    scope: meta.map(|v| v.scope.as_str()).unwrap_or(""),
127                    scope_exempt: meta.map(|v| v.scope_exempt).unwrap_or(false),
128                    dispatch_mac: meta
129                        .map(|v| v.dispatch_mac.as_str())
130                        .or_else(|| union_arm.map(|a| a.dispatch_mac.as_str()))
131                        .unwrap_or(""),
132                    dispatch_mac_present: meta.map(|v| v.dispatch_mac_present).unwrap_or_else(
133                        || union_arm.map(|a| a.dispatch_mac_present).unwrap_or(false),
134                    ),
135                    dispatch_public: meta
136                        .map(|v| v.dispatch_public.as_str())
137                        .or_else(|| union_arm.map(|a| a.dispatch_public.as_str()))
138                        .unwrap_or(""),
139                    dispatch_public_present: meta
140                        .map(|v| v.dispatch_public_present)
141                        .unwrap_or_else(|| {
142                            union_arm
143                                .map(|a| a.dispatch_public_present)
144                                .unwrap_or(false)
145                        }),
146                    mutation_semantics: meta
147                        .map(|v| v.mutation_semantics.as_str())
148                        .or_else(|| union_arm.map(|a| a.mutation_semantics.as_str()))
149                        .unwrap_or(""),
150                    mutation_semantics_present: meta
151                        .map(|v| v.mutation_semantics_present)
152                        .unwrap_or_else(|| {
153                            union_arm
154                                .map(|a| a.mutation_semantics_present)
155                                .unwrap_or(false)
156                        }),
157                }
158            })
159            .collect(),
160        None => variants
161            .iter()
162            .enumerate()
163            .map(|(index, v)| ArmMeta {
164                name: &v.name,
165                discriminant: u16::try_from(index).unwrap_or(u16::MAX),
166                type_name: &v.type_name,
167                scope: &v.scope,
168                scope_exempt: v.scope_exempt,
169                dispatch_mac: &v.dispatch_mac,
170                dispatch_mac_present: v.dispatch_mac_present,
171                dispatch_public: &v.dispatch_public,
172                dispatch_public_present: v.dispatch_public_present,
173                mutation_semantics: &v.mutation_semantics,
174                mutation_semantics_present: v.mutation_semantics_present,
175            })
176            .collect(),
177    }
178}
179
180/// Whether a union arm's payload is itself a method-selecting union to
181/// descend into (a local, non-`Option` pure-union struct).
182fn descend_struct<'a>(resolved: &'a ResolvedSchema, type_name: &str) -> Option<&'a StructDef> {
183    let sdef = resolved.find_struct(type_name)?;
184    if sdef.origin_file.is_some() {
185        return None; // imported type: payload, not local method identity
186    }
187    if sdef.is_pure_union() && sdef.option_inner_type().is_none() {
188        Some(sdef)
189    } else {
190        None
191    }
192}
193
194/// Recursively collect every method leaf of the service's request tree.
195pub fn collect_method_leaves(resolved: &ResolvedSchema) -> Vec<MethodLeaf> {
196    let mut out = Vec::new();
197    let label_map = InitialLabelMap::load().ok();
198    walk_level(
199        resolved,
200        label_map.as_ref(),
201        resolved.raw.request_struct.as_ref(),
202        &resolved.raw.request_variants,
203        &resolved.raw.scoped_clients,
204        &[],
205        "",
206        &Inherited::default(),
207        &mut out,
208    );
209    out
210}
211
212#[allow(clippy::too_many_arguments)]
213fn walk_level(
214    resolved: &ResolvedSchema,
215    label_map: Option<&InitialLabelMap>,
216    sdef: Option<&StructDef>,
217    variants: &[UnionVariant],
218    scopes: &[ScopedClient],
219    prefix: &[u16],
220    prefix_sym: &str,
221    // Annotation inherited from the nearest annotated ancestor selector: the
222    // arms below a hand-dispatched pure union carry no `$scope` metadata of
223    // their own, so they inherit their selector's annotation instead of
224    // producing an unannotated (build-failing) row. `$dispatchMac` inherits
225    // the same way, and so does `$mutationSemantics` — a local declaration
226    // always takes precedence over the inherited one, and no default is ever
227    // substituted. `$dispatchPublic` NEVER inherits (public is legal only on
228    // leaves) — an ancestor public annotation marks `public_ancestor` so the
229    // descendant leaf fails the build rather than silently inheriting public.
230    inherited: &Inherited,
231    out: &mut Vec<MethodLeaf>,
232) {
233    for arm in level_arms(sdef, variants) {
234        let mut path = prefix.to_vec();
235        path.push(arm.discriminant);
236        let symbolic = if prefix_sym.is_empty() {
237            arm.name.to_owned()
238        } else {
239            format!("{prefix_sym}.{}", arm.name)
240        };
241        let nested = scopes
242            .iter()
243            .find(|sc| sc.factory_name == arm.name)
244            .is_some()
245            || descend_struct(resolved, arm.type_name).is_some();
246        let mut effective = inherited.clone();
247        if arm.scope.is_empty() && !arm.scope_exempt {
248            // scope (and its exemption) inherit from the selector unchanged.
249        } else {
250            effective.scope = arm.scope.to_owned();
251            effective.scope_exempt = arm.scope_exempt;
252        }
253
254        // Validate every declaration at its own selector/leaf before applying
255        // inheritance. A valid descendant must never shadow an invalid parent.
256        if arm.dispatch_mac_present {
257            if let Some(label_map) = label_map {
258                if let Err(error) = parse_dispatch_mac(arm.dispatch_mac, label_map) {
259                    effective.validation_error.get_or_insert_with(|| {
260                        format!(
261                            "method leaf '{}': $dispatchMac {:?}: {error}",
262                            symbolic, arm.dispatch_mac
263                        )
264                    });
265                }
266            }
267        }
268        if arm.dispatch_mac_present && arm.dispatch_public_present {
269            effective.validation_error.get_or_insert_with(|| {
270                format!(
271                    "method '{}' carries BOTH $dispatchMac and $dispatchPublic",
272                    symbolic
273                )
274            });
275        } else if arm.dispatch_public_present && nested {
276            effective.validation_error.get_or_insert_with(|| {
277                format!("method dispatcher '{}' carries $dispatchPublic; public is never inherited and is legal only on leaves", symbolic)
278            });
279        }
280        if arm.mutation_semantics_present {
281            if let Err(error) = parse_mutation_semantics(arm.mutation_semantics) {
282                effective
283                    .validation_error
284                    .get_or_insert_with(|| format!("method '{}': {error}", symbolic));
285            }
286        }
287
288        if arm.dispatch_public_present {
289            // A local public leaf is an explicit scope-exempt override and
290            // clears any inherited MAC state. Public never propagates.
291            effective.dispatch_mac.clear();
292            effective.dispatch_mac_present = false;
293            effective.dispatch_public = arm.dispatch_public.to_owned();
294            effective.dispatch_public_present = true;
295        } else if arm.dispatch_mac_present {
296            effective.dispatch_mac = arm.dispatch_mac.to_owned();
297            effective.dispatch_mac_present = true;
298            effective.dispatch_public.clear();
299            effective.dispatch_public_present = false;
300        } else {
301            effective.dispatch_public.clear();
302            effective.dispatch_public_present = false;
303        }
304        if arm.mutation_semantics_present {
305            // Local `$mutationSemantics` wins over inherited state.
306            effective.mutation_semantics = arm.mutation_semantics.to_owned();
307            effective.mutation_semantics_present = true;
308        }
309        // An unannotated arm keeps the nearest annotated ancestor selector's
310        // declaration — the one it reaches here through a hand-dispatched
311        // pure union. No default policy is ever invented: a leaf left with no
312        // declaration at all still fails the closed parser at row generation
313        // (and stays policy-free only where the schema gate already allows
314        // it — read-class scopes and scope-exempt leaves).
315
316        if let Some(sc) = scopes.iter().find(|sc| sc.factory_name == arm.name) {
317            // A scope selector: descend into its inner method union. Scoped
318            // dispatchers carry neither dispatch annotation (v16 §6); the
319            // inheritance they propagate is whatever THEY inherited (a scoped
320            // selector nested inside a hand-dispatched pure union).
321            walk_level(
322                resolved,
323                label_map,
324                resolved.find_struct(arm.type_name),
325                &sc.inner_request_variants,
326                &sc.nested_clients,
327                &path,
328                &symbolic,
329                &effective,
330                out,
331            );
332        } else if let Some(inner) = descend_struct(resolved, arm.type_name) {
333            // A hand-dispatched pure union: its arms are method identity.
334            walk_level(
335                resolved,
336                label_map,
337                Some(inner),
338                &[],
339                &[],
340                &path,
341                &symbolic,
342                &effective,
343                out,
344            );
345        } else {
346            out.push(MethodLeaf {
347                path,
348                symbolic,
349                scope: effective.scope.clone(),
350                scope_exempt: effective.scope_exempt,
351                dispatch_mac: effective.dispatch_mac.clone(),
352                dispatch_mac_present: effective.dispatch_mac_present,
353                dispatch_public: effective.dispatch_public.clone(),
354                dispatch_public_present: effective.dispatch_public_present,
355                mutation_semantics: effective.mutation_semantics.clone(),
356                mutation_semantics_present: effective.mutation_semantics_present,
357                validation_error: effective.validation_error.clone(),
358            });
359        }
360    }
361}
362
363/// Generate `decode_<service>_request_body`: the ONE bounded decode of the
364/// signed request body, deriving the full nested leaf path (v16 §5.2 step 4).
365///
366/// The generated function performs exactly one `read_message` under the
367/// reviewed caps ([`hyprstream_rpc::service::body::bounded_reader_options`]),
368/// walks the method unions of the decoded message to the executed leaf, and
369/// returns a `DecodedRequestBody` carrying the decoded message itself — the
370/// same message generated dispatch later reads the typed request from. An
371/// unknown discriminant at any level is an error (deny), never a truncated
372/// or coarser path.
373pub fn generate_body_decoder(service_name: &str, resolved: &ResolvedSchema) -> TokenStream {
374    let pascal = to_pascal_case(service_name);
375    let capnp_mod = format_ident!("{}_capnp", service_name);
376    let req_snake = format_ident!("{}", to_snake_case(&format!("{pascal}Request")));
377    let decode_fn = format_ident!("decode_{}_request_body", to_snake_case(&pascal));
378    let root_mod = quote! { #capnp_mod::#req_snake };
379
380    let arms = decoder_arms(
381        resolved,
382        &capnp_mod,
383        &root_mod,
384        resolved.raw.request_struct.as_ref(),
385        &resolved.raw.request_variants,
386        &resolved.raw.scoped_clients,
387    );
388
389    let doc = format!(
390        "Decode a {pascal} signed request body **exactly once** (bounded) and derive\n\
391         the full numeric method leaf path (v16 §5.2).\n\n\
392         Returns the one `DecodedRequestBody` that feeds the generated method\n\
393         policy, the dispatch MAC PEP, and `dispatch_{}` — there is no second\n\
394         `read_message` between admission and handler. An undecodable body, a\n\
395         discriminant absent from this schema revision, or a body exceeding the\n\
396         reviewed decode caps is an error, which denies — never a coarser path.",
397        to_snake_case(&pascal)
398    );
399
400    quote! {
401        #[doc = #doc]
402        pub fn #decode_fn(
403            signed_body: &[u8],
404        ) -> anyhow::Result<hyprstream_rpc::service::DecodedRequestBody> {
405            let message = capnp::serialize::read_message(
406                &mut std::io::Cursor::new(signed_body),
407                hyprstream_rpc::service::body::bounded_reader_options(),
408            )?;
409            let mut __path: Vec<u16> = Vec::new();
410            {
411                let req = message.get_root::<#root_mod::Reader>()?;
412                match req.which()? {
413                    #(#arms)*
414                    #[allow(unreachable_patterns)]
415                    _ => anyhow::bail!(
416                        "unknown request union discriminant (not in this schema revision)"
417                    ),
418                }
419            }
420            hyprstream_rpc::service::DecodedRequestBody::from_message(
421                signed_body.to_vec(),
422                message,
423                __path,
424            )
425        }
426    }
427}
428
429/// Generate the service's method-policy inventory rows (v16 §6.1) from the
430/// same leaf-tree walk that produced its signed-body decoder.
431///
432/// Emits `method_policy_rows()` plus an `inventory` submission, so startup
433/// installation ([`hyprstream_rpc::proof::policy::install_generated_method_policy`])
434/// aggregates every linked service's rows into the one deterministic table.
435///
436/// Row derivation from the checked schema annotations (v16 §6 — the strict
437/// `$dispatchMac`/`$dispatchPublic` pair REPLACES the `$scope`/`$scopeExempt`
438/// stand-in as the dispatch-policy source; `$scope` remains the control-plane
439/// vocabulary feeding `scope_action`):
440///
441/// - a `$dispatchPublic("<reason>")` leaf is publicly dispatchable:
442///   `UnauthenticatedAllowed` + `UnauthenticatedOrTokenBound` with the
443///   mandatory Hybrid suite, target label exactly system low, and the
444///   annotation's trimmed reason as its public reason;
445/// - a `$dispatchMac("<level>:<assurance>[:<compartments>]")` leaf requires a
446///   credential: `CredentialRequired` + `TokenBound` with the mandatory
447///   Hybrid suite, and a target label parsed HERE against the checked-in
448///   `InitialLabelMap` (stable bit assignments) — never at runtime;
449/// - every row carries the fixed system-low `transitional_label` (v16 §7.3)
450///   and checked per-leaf `MutationSemantics` metadata (an explicit declared
451///   variant for every non-read action and any stateful read-class leaf).
452///   (Credentials are Reusable-only per the 2026-08-20 operator deferral;
453///   a use-profile field returns only with a future amendment that allocates
454///   its claim key — it is not carried dormant here.)
455///
456/// Any annotation failure — a leaf with neither annotation or both, a public
457/// leaf with an empty reason or a coexisting `$scope`, a label that fails the
458/// strict grammar (unknown level/assurance, empty components, duplicate or
459/// unknown compartments, noncanonical ordering, or system low spelled through
460/// `$dispatchMac`) — is a **compile error**: an annotation failure can never
461/// produce an unlabeled runtime row.
462pub fn generate_method_policy_rows(service_name: &str, resolved: &ResolvedSchema) -> TokenStream {
463    let leaves = collect_method_leaves(resolved);
464    let decode_fn = format_ident!(
465        "decode_{}_request_body",
466        to_snake_case(&to_pascal_case(service_name))
467    );
468
469    let label_map = match InitialLabelMap::load() {
470        Ok(map) => map,
471        Err(e) => {
472            let msg = format!("InitialLabelMap failed to load: {e}");
473            return quote! { ::core::compile_error!(#msg); };
474        }
475    };
476
477    let mut row_tokens: Vec<TokenStream> = Vec::new();
478    for leaf in &leaves {
479        if let Some(error) = &leaf.validation_error {
480            return quote! { ::core::compile_error!(#error); };
481        }
482        let path = &leaf.path;
483        let symbolic = &leaf.symbolic;
484        let scope = &leaf.scope;
485        let scope_exempt = leaf.scope_exempt;
486
487        let has_mac = leaf.dispatch_mac_present;
488        let has_public = leaf.dispatch_public_present;
489        let (authentication, signature_policy, public_reason, target_label) = match (
490            has_mac, has_public,
491        ) {
492            (false, false) => {
493                let msg = format!(
494                    "method leaf '{}.{}' has neither a $dispatchMac nor a \
495                         $dispatchPublic annotation; every generated dispatch-policy \
496                         row must derive from exactly one of the pair (v16 §6). Public \
497                         is never inherited from a selector.",
498                    service_name, leaf.symbolic
499                );
500                return quote! { ::core::compile_error!(#msg); };
501            }
502            (true, true) => {
503                let msg = format!(
504                    "method leaf '{}.{}' carries BOTH $dispatchMac and $dispatchPublic; \
505                         exactly one dispatch annotation per leaf (v16 §6)",
506                    service_name, leaf.symbolic
507                );
508                return quote! { ::core::compile_error!(#msg); };
509            }
510            (false, true) => {
511                let reason = match parse_dispatch_public_reason(&leaf.dispatch_public) {
512                    Ok(r) => r,
513                    Err(e) => {
514                        return quote! { ::core::compile_error!(#e); };
515                    }
516                };
517                if !leaf.scope.is_empty() {
518                    let msg = format!(
519                        "method leaf '{}.{}' is $dispatchPublic but also declares the \
520                             $scope({}) action; a control-plane-scoped method cannot be \
521                             dispatch-public (v16 §6)",
522                        service_name, leaf.symbolic, leaf.scope
523                    );
524                    return quote! { ::core::compile_error!(#msg); };
525                }
526                (
527                    quote! { hyprstream_rpc::proof::policy::AuthenticationRequirement::UnauthenticatedAllowed },
528                    quote! {
529                        hyprstream_rpc::proof::policy::SignaturePolicy::UnauthenticatedOrTokenBound {
530                            suite: hyprstream_rpc::proof::policy::CryptoSuite::Hybrid,
531                        }
532                    },
533                    quote! { Some(#reason) },
534                    quote! { hyprstream_rpc::proof::policy::SYSTEM_LOW_LABEL },
535                )
536            }
537            (true, false) => {
538                let label = match parse_dispatch_mac(&leaf.dispatch_mac, &label_map) {
539                    Ok(l) => l,
540                    Err(e) => {
541                        let msg = format!(
542                            "method leaf '{}.{}' $dispatchMac {:?}: {e}",
543                            service_name, leaf.symbolic, leaf.dispatch_mac
544                        );
545                        return quote! { ::core::compile_error!(#msg); };
546                    }
547                };
548                let level = level_tokens(label.level);
549                let assurance = assurance_tokens(label.assurance);
550                let bits = &label.compartment_bits;
551                (
552                    quote! { hyprstream_rpc::proof::policy::AuthenticationRequirement::CredentialRequired },
553                    quote! {
554                        hyprstream_rpc::proof::policy::SignaturePolicy::TokenBound {
555                            suite: hyprstream_rpc::proof::policy::CryptoSuite::Hybrid,
556                        }
557                    },
558                    quote! { None },
559                    quote! {
560                        hyprstream_rpc::proof::policy::dispatch_label(#level, #assurance, &[#(#bits),*])
561                    },
562                )
563            }
564        };
565
566        // §4.8/§6.1: authorization scope and application effects are separate
567        // axes. A query/subscribe leaf may explicitly classify bounded session
568        // or subscription state, while every non-read scope needs a declaration.
569        // This is a second gate after the CGR parser validation.
570        let mutation_semantics = if !leaf.mutation_semantics_present
571            && (READ_CLASS_ACTIONS.contains(&leaf.scope.as_str()) || leaf.scope.is_empty())
572        {
573            // Ordinary read leaves and scope-exempt public/control-plane reads
574            // remain policy-free. An explicitly classified leaf follows the
575            // checked parser below; authorization never implies retry safety.
576            quote! { None }
577        } else {
578            match parse_mutation_semantics(&leaf.mutation_semantics) {
579                Ok(DeclaredMutationSemantics::NaturallyIdempotent) => quote! {
580                    Some(hyprstream_rpc::proof::policy::MutationSemantics::NaturallyIdempotent)
581                },
582                Ok(DeclaredMutationSemantics::IdempotencyKeyRequired) => quote! {
583                    Some(hyprstream_rpc::proof::policy::MutationSemantics::IdempotencyKeyRequired)
584                },
585                Ok(DeclaredMutationSemantics::TransactionLedgerRequired) => quote! {
586                    Some(hyprstream_rpc::proof::policy::MutationSemantics::TransactionLedgerRequired)
587                },
588                Err(e) => {
589                    let msg = format!(
590                        "method leaf '{}.{}' (scope '{}') {e}; mutation retry policy is explicit per leaf",
591                        service_name, leaf.symbolic, leaf.scope
592                    );
593                    return quote! { ::core::compile_error!(#msg); };
594                }
595            }
596        };
597
598        row_tokens.push(quote! {
599            hyprstream_rpc::proof::policy::GeneratedMethodPolicyRow {
600                service: #service_name,
601                leaf_path: &[#(#path),*],
602                symbolic_path: #symbolic,
603                scope_action: #scope,
604                scope_exempt: #scope_exempt,
605                authentication: #authentication,
606                signature_policy: #signature_policy,
607                mutation_semantics: #mutation_semantics,
608                transitional_label: hyprstream_rpc::proof::policy::SYSTEM_LOW_LABEL,
609                target_label: #target_label,
610                public_reason: #public_reason,
611            }
612        });
613    }
614
615    let doc = format!(
616        "Generated dispatch method-policy rows for the {service_name} service (v16 §6.1).\n\n\
617         One row per method leaf, derived from the same tree walk as the\n\
618         signed-body decoder — the decoder cannot derive a leaf this inventory\n\
619         does not list, and vice versa."
620    );
621
622    quote! {
623        #[doc = #doc]
624        pub fn method_policy_rows() -> Vec<hyprstream_rpc::proof::policy::GeneratedMethodPolicyRow> {
625            vec![ #(#row_tokens),* ]
626        }
627
628        // Aggregated by `install_generated_method_policy()` at startup. Same
629        // native-only inventory pattern as `VfsNodeTable` (#1305): linker
630        // section registration does not resolve on wasm32.
631        #[cfg(not(target_arch = "wasm32"))]
632        hyprstream_rpc::metadata::inventory::submit! {
633            hyprstream_rpc::proof::policy::GeneratedMethodPolicyProvider {
634                service: #service_name,
635                rows_fn: method_policy_rows,
636                decode_fn: #decode_fn,
637            }
638        }
639    }
640}
641
642/// Runtime `Level` enum tokens for one grammar level name.
643fn level_tokens(level: &str) -> TokenStream {
644    match level {
645        "public" => quote! { hyprstream_rpc::auth::mac::Level::Public },
646        "internal" => quote! { hyprstream_rpc::auth::mac::Level::Internal },
647        "confidential" => quote! { hyprstream_rpc::auth::mac::Level::Confidential },
648        "secret" => quote! { hyprstream_rpc::auth::mac::Level::Secret },
649        other => unreachable!("grammar parser accepted unknown level {other:?}"),
650    }
651}
652
653/// Runtime `Assurance` enum tokens for one grammar assurance name.
654fn assurance_tokens(assurance: &str) -> TokenStream {
655    match assurance {
656        "unverified" => quote! { hyprstream_rpc::auth::mac::Assurance::Unverified },
657        "classical" => quote! { hyprstream_rpc::auth::mac::Assurance::Classical },
658        "pq-hybrid" => quote! { hyprstream_rpc::auth::mac::Assurance::PqHybrid },
659        other => unreachable!("grammar parser accepted unknown assurance {other:?}"),
660    }
661}
662
663/// Build the match arms for one union level of the generated decoder.
664fn decoder_arms(
665    resolved: &ResolvedSchema,
666    capnp_mod: &syn::Ident,
667    mod_path: &TokenStream,
668    sdef: Option<&StructDef>,
669    variants: &[UnionVariant],
670    scopes: &[ScopedClient],
671) -> Vec<TokenStream> {
672    level_arms(sdef, variants)
673        .into_iter()
674        .map(|arm| {
675            let pascal = resolved.name(arm.name).pascal_ident.clone();
676            let disc = arm.discriminant;
677
678            let descend_target = if let Some(sc) =
679                scopes.iter().find(|sc| sc.factory_name == arm.name)
680            {
681                resolved.find_struct(arm.type_name).map(|inner_sdef| {
682                    (
683                        inner_sdef,
684                        sc.inner_request_variants.as_slice(),
685                        sc.nested_clients.as_slice(),
686                    )
687                })
688            } else {
689                descend_struct(resolved, arm.type_name)
690                    .map(|inner_sdef| (inner_sdef, &[] as &[UnionVariant], &[] as &[ScopedClient]))
691            };
692
693            match descend_target {
694                Some((inner_sdef, inner_variants, inner_scopes)) => {
695                    let inner_mod_ident =
696                        format_ident!("{}", to_capnp_module_name(&inner_sdef.name));
697                    let inner_mod = quote! { #capnp_mod::#inner_mod_ident };
698                    let inner_arms = decoder_arms(
699                        resolved,
700                        capnp_mod,
701                        &inner_mod,
702                        Some(inner_sdef),
703                        inner_variants,
704                        inner_scopes,
705                    );
706                    quote! {
707                        #mod_path::Which::#pascal(r) => {
708                            __path.push(#disc);
709                            let r = r?;
710                            match r.which()? {
711                                #(#inner_arms)*
712                                #[allow(unreachable_patterns)]
713                                _ => anyhow::bail!(
714                                    "unknown request union discriminant (not in this schema revision)"
715                                ),
716                            }
717                        }
718                    }
719                }
720                None => quote! {
721                    #mod_path::Which::#pascal(_) => {
722                        __path.push(#disc);
723                    }
724                },
725            }
726        })
727        .collect()
728}
729
730#[cfg(test)]
731#[allow(clippy::expect_used)]
732mod tests {
733    use super::*;
734    use crate::resolve::ResolvedSchema;
735
736    fn variant(name: &str, type_name: &str, scope: &str, exempt: bool) -> UnionVariant {
737        UnionVariant {
738            name: name.to_owned(),
739            type_name: type_name.to_owned(),
740            description: String::new(),
741            scope: scope.to_owned(),
742            scope_exempt: exempt,
743            cli_hidden: false,
744            doc_example: String::new(),
745            vfs_path: String::new(),
746            vfs_kind: String::new(),
747            vfs_bulk: false,
748            vfs_hidden: false,
749            vfs_mac: String::new(),
750            dispatch_mac: String::new(),
751            dispatch_public: String::new(),
752            mutation_semantics: String::new(),
753            dispatch_mac_present: false,
754            dispatch_public_present: false,
755            mutation_semantics_present: false,
756        }
757    }
758
759    fn union_field(name: &str, type_name: &str, disc: u16) -> FieldDef {
760        FieldDef {
761            name: name.to_owned(),
762            type_name: type_name.to_owned(),
763            description: String::new(),
764            fixed_size: None,
765            max_len: None,
766            optional: false,
767            slot_offset: 0,
768            section: FieldSection::Pointer,
769            discriminant_value: disc,
770            serde_rename: None,
771            domain_type: None,
772        }
773    }
774
775    fn plain_field(name: &str, type_name: &str) -> FieldDef {
776        FieldDef {
777            discriminant_value: 0xFFFF,
778            ..union_field(name, type_name, 0)
779        }
780    }
781
782    fn union_struct(name: &str, fields: Vec<FieldDef>) -> StructDef {
783        let discriminant_count = fields
784            .iter()
785            .filter(|f| f.discriminant_value != 0xFFFF)
786            .count() as u16;
787        StructDef {
788            name: name.to_owned(),
789            fields,
790            has_union: true,
791            domain_type: None,
792            origin_file: None,
793            data_words: 1,
794            pointer_words: 2,
795            discriminant_count,
796            discriminant_offset: 0,
797            union_arms: vec![],
798        }
799    }
800
801    /// A root union with a scope subtree and a nested scope below it derives
802    /// full multi-level numeric paths, and every leaf appears exactly once.
803    #[test]
804    fn nested_scope_leaves_get_full_paths() {
805        let schema = ParsedSchema {
806            request_variants: vec![
807                variant("status", "Void", "query", false),
808                variant("repo", "RepositoryRequest", "", false),
809            ],
810            response_variants: vec![],
811            structs: vec![
812                union_struct(
813                    "RepositoryRequest",
814                    vec![
815                        plain_field("id", "Text"),
816                        union_field("create", "Text", 0),
817                        union_field("worktree", "WorktreeRequest", 1),
818                    ],
819                ),
820                union_struct(
821                    "WorktreeRequest",
822                    vec![
823                        plain_field("name", "Text"),
824                        union_field("add", "Text", 0),
825                        union_field("remove", "Void", 1),
826                    ],
827                ),
828            ],
829            scoped_clients: vec![ScopedClient {
830                factory_name: "repo".into(),
831                client_name: "RepositoryClient".into(),
832                scope_fields: vec![plain_field("id", "Text")],
833                inner_request_variants: vec![variant("create", "Text", "write", false)],
834                inner_response_variants: vec![],
835                capnp_inner_response: "repository_response".into(),
836                nested_clients: vec![ScopedClient {
837                    factory_name: "worktree".into(),
838                    client_name: "WorktreeClient".into(),
839                    scope_fields: vec![plain_field("name", "Text")],
840                    inner_request_variants: vec![
841                        variant("add", "Text", "write", false),
842                        variant("remove", "Void", "manage", false),
843                    ],
844                    inner_response_variants: vec![],
845                    capnp_inner_response: "worktree_response".into(),
846                    nested_clients: vec![],
847                }],
848            }],
849            enums: vec![],
850            request_struct: Some(union_struct(
851                "RegistryRequest",
852                vec![
853                    plain_field("id", "UInt64"),
854                    union_field("status", "Void", 0),
855                    union_field("repo", "RepositoryRequest", 1),
856                ],
857            )),
858            response_struct: None,
859        };
860        let resolved = ResolvedSchema::from(&schema);
861        let leaves = collect_method_leaves(&resolved);
862
863        let by_symbol: std::collections::HashMap<&str, &MethodLeaf> =
864            leaves.iter().map(|l| (l.symbolic.as_str(), l)).collect();
865        assert_eq!(
866            by_symbol.len(),
867            leaves.len(),
868            "no duplicate symbolic leaves"
869        );
870
871        assert_eq!(by_symbol["status"].path, vec![0]);
872        assert_eq!(by_symbol["repo.create"].path, vec![1, 0]);
873        assert_eq!(by_symbol["repo.worktree.add"].path, vec![1, 1, 0]);
874        assert_eq!(by_symbol["repo.worktree.remove"].path, vec![1, 1, 1]);
875        assert_eq!(by_symbol["repo.worktree.add"].scope, "write");
876        assert!(
877            !by_symbol.contains_key("repo"),
878            "a scope selector is not a leaf"
879        );
880
881        // The generated decoder descends the same tree: nested Which paths
882        // and every discriminant push must appear in the emitted code.
883        let generated = generate_body_decoder("registry", &resolved).to_string();
884        for needle in [
885            "registry_request :: Which :: Status",
886            "repository_request :: Which :: Create",
887            "worktree_request :: Which :: Add",
888            "bounded_reader_options",
889            "from_message",
890        ] {
891            assert!(
892                generated.contains(needle),
893                "generated decoder must contain `{needle}`:\n{generated}"
894            );
895        }
896    }
897
898    /// An `Option<T>`-shaped pure union is payload, not method identity.
899    #[test]
900    fn option_shaped_unions_do_not_extend_the_leaf() {
901        let option_struct = StructDef {
902            name: "OptionText".into(),
903            fields: vec![
904                union_field("none", "Void", 0),
905                union_field("some", "Text", 1),
906            ],
907            has_union: true,
908            domain_type: None,
909            origin_file: None,
910            data_words: 1,
911            pointer_words: 1,
912            discriminant_count: 2,
913            discriminant_offset: 0,
914            union_arms: vec![],
915        };
916        let schema = ParsedSchema {
917            request_variants: vec![variant("lookup", "OptionText", "query", false)],
918            response_variants: vec![],
919            structs: vec![option_struct],
920            scoped_clients: vec![],
921            enums: vec![],
922            request_struct: Some(union_struct(
923                "LookupRequest",
924                vec![union_field("lookup", "OptionText", 0)],
925            )),
926            response_struct: None,
927        };
928        let resolved = ResolvedSchema::from(&schema);
929        let leaves = collect_method_leaves(&resolved);
930        assert_eq!(leaves.len(), 1);
931        assert_eq!(leaves[0].path, vec![0]);
932        assert_eq!(leaves[0].symbolic, "lookup");
933    }
934
935    // ── Strict dispatch pair (v16 §6, WS-D) ────────────────────────────────
936
937    const MAC: &str = "internal:pq-hybrid";
938
939    fn dispatch_variant(
940        name: &str,
941        type_name: &str,
942        scope: &str,
943        mac: &str,
944        public: &str,
945    ) -> UnionVariant {
946        let mut v = variant(name, type_name, scope, false);
947        v.dispatch_mac = mac.to_owned();
948        v.dispatch_public = public.to_owned();
949        v.dispatch_mac_present = !mac.is_empty();
950        v.dispatch_public_present = !public.is_empty();
951        if !scope.is_empty() && !READ_CLASS_ACTIONS.contains(&scope) {
952            v.mutation_semantics = "transaction-ledger-required".to_owned();
953            v.mutation_semantics_present = true;
954        }
955        v
956    }
957
958    fn simple_schema(variants: Vec<UnionVariant>) -> ResolvedSchema<'static> {
959        // Leak a box: test schemas live for the process lifetime anyway.
960        let schema = Box::leak(Box::new(ParsedSchema {
961            request_variants: variants,
962            response_variants: vec![],
963            structs: vec![],
964            scoped_clients: vec![],
965            enums: vec![],
966            request_struct: None,
967            response_struct: None,
968        }));
969        ResolvedSchema::from(schema)
970    }
971
972    /// A leaf with neither dispatch annotation is a compile error — an
973    /// unannotated runtime row can never exist, and nothing inherits public.
974    #[test]
975    fn an_unannotated_leaf_is_a_compile_error() {
976        let resolved = simple_schema(vec![dispatch_variant("load", "Void", "write", "", "")]);
977        let generated = generate_method_policy_rows("model", &resolved).to_string();
978        assert!(generated.contains("compile_error"), "{generated}");
979        assert!(generated.contains("neither a $dispatchMac"), "{generated}");
980    }
981
982    #[test]
983    fn both_annotations_on_one_leaf_is_a_compile_error() {
984        let resolved = simple_schema(vec![dispatch_variant(
985            "load", "Void", "write", MAC, "reason",
986        )]);
987        let generated = generate_method_policy_rows("model", &resolved).to_string();
988        assert!(generated.contains("BOTH $dispatchMac"), "{generated}");
989    }
990
991    /// `$dispatchPublic` is legal only on leaves: an unannotated arm below a
992    /// public selector does NOT inherit public — it fails the build instead.
993    #[test]
994    fn public_never_inherits_through_a_hand_dispatched_selector() {
995        let selector = union_struct(
996            "InnerRequest",
997            vec![union_field("a", "Text", 0), union_field("b", "Void", 1)],
998        );
999        let schema = Box::leak(Box::new(ParsedSchema {
1000            request_variants: vec![dispatch_variant(
1001                "outer",
1002                "InnerRequest",
1003                "",
1004                "",
1005                "leaf-level reason",
1006            )],
1007            response_variants: vec![],
1008            structs: vec![selector],
1009            scoped_clients: vec![],
1010            enums: vec![],
1011            request_struct: Some(union_struct(
1012                "SvcRequest",
1013                vec![union_field("outer", "InnerRequest", 0)],
1014            )),
1015            response_struct: None,
1016        }));
1017        let resolved = ResolvedSchema::from(schema);
1018        let leaves = collect_method_leaves(&resolved);
1019        assert_eq!(leaves.len(), 2, "both pure-union arms are leaves");
1020        for leaf in &leaves {
1021            assert!(
1022                leaf.dispatch_mac.is_empty() && leaf.dispatch_public.is_empty(),
1023                "public must not flow to {}",
1024                leaf.symbolic
1025            );
1026        }
1027        let generated = generate_method_policy_rows("svc", &resolved).to_string();
1028        assert!(generated.contains("compile_error"), "{generated}");
1029        assert!(generated.contains("never inherited"), "{generated}");
1030    }
1031
1032    /// A `$dispatchMac` label DOES inherit through a hand-dispatched pure
1033    /// union: unannotated arms resolve to their selector's label.
1034    #[test]
1035    fn a_mac_label_inherits_through_a_hand_dispatched_selector() {
1036        let selector = union_struct(
1037            "InnerRequest",
1038            vec![union_field("a", "Text", 0), union_field("b", "Void", 1)],
1039        );
1040        let schema = Box::leak(Box::new(ParsedSchema {
1041            request_variants: vec![dispatch_variant("outer", "InnerRequest", "", MAC, "")],
1042            response_variants: vec![],
1043            structs: vec![selector],
1044            scoped_clients: vec![],
1045            enums: vec![],
1046            request_struct: Some(union_struct(
1047                "SvcRequest",
1048                vec![union_field("outer", "InnerRequest", 0)],
1049            )),
1050            response_struct: None,
1051        }));
1052        let resolved = ResolvedSchema::from(schema);
1053        let leaves = collect_method_leaves(&resolved);
1054        assert_eq!(leaves.len(), 2);
1055        assert!(leaves.iter().all(|l| l.dispatch_mac == MAC));
1056
1057        // And both inherited leaves generate real rows — no compile_error.
1058        let generated = generate_method_policy_rows("svc", &resolved).to_string();
1059        assert!(!generated.contains("compile_error"), "{generated}");
1060        assert!(generated.contains("Level :: Internal"), "{generated}");
1061    }
1062
1063    #[test]
1064    fn a_local_public_leaf_clears_inherited_mac_for_that_leaf_only() {
1065        let mut inner = union_struct(
1066            "InnerRequest",
1067            vec![
1068                union_field("public_leaf", "Void", 0),
1069                union_field("mac_leaf", "Void", 1),
1070            ],
1071        );
1072        inner.union_arms = vec![
1073            UnionArm {
1074                name: "public_leaf".into(),
1075                discriminant_value: 0,
1076                description: String::new(),
1077                dispatch_mac: String::new(),
1078                dispatch_mac_present: false,
1079                dispatch_public: "liveness".into(),
1080                dispatch_public_present: true,
1081                mutation_semantics: String::new(),
1082                mutation_semantics_present: false,
1083                payload: ArmPayload::Void,
1084            },
1085            UnionArm {
1086                name: "mac_leaf".into(),
1087                discriminant_value: 1,
1088                description: String::new(),
1089                dispatch_mac: String::new(),
1090                dispatch_mac_present: false,
1091                dispatch_public: String::new(),
1092                dispatch_public_present: false,
1093                mutation_semantics: String::new(),
1094                mutation_semantics_present: false,
1095                payload: ArmPayload::Void,
1096            },
1097        ];
1098        let schema = Box::leak(Box::new(ParsedSchema {
1099            request_variants: vec![dispatch_variant("outer", "InnerRequest", "", MAC, "")],
1100            response_variants: vec![],
1101            structs: vec![inner],
1102            scoped_clients: vec![],
1103            enums: vec![],
1104            request_struct: Some(union_struct(
1105                "SvcRequest",
1106                vec![union_field("outer", "InnerRequest", 0)],
1107            )),
1108            response_struct: None,
1109        }));
1110        let leaves = collect_method_leaves(&ResolvedSchema::from(schema));
1111        let public = leaves
1112            .iter()
1113            .find(|leaf| leaf.symbolic == "outer.public_leaf")
1114            .expect("public leaf");
1115        let mac = leaves
1116            .iter()
1117            .find(|leaf| leaf.symbolic == "outer.mac_leaf")
1118            .expect("MAC leaf");
1119        assert!(public.dispatch_public_present && !public.dispatch_mac_present);
1120        assert!(!mac.dispatch_public_present && mac.dispatch_mac_present);
1121        let generated =
1122            generate_method_policy_rows("svc", &ResolvedSchema::from(schema)).to_string();
1123        assert!(!generated.contains("compile_error"), "{generated}");
1124    }
1125
1126    /// P2 (`PRRT_kwDONmv2Pc6gGRV2`) causal regression: a nonread selector's
1127    /// `$mutationSemantics` inherits through a hand-dispatched pure union to
1128    /// every descendant leaf, exactly like its scope and MAC label — the
1129    /// schema gate accepts the selector-level declaration, so the walk must
1130    /// carry it instead of dropping it and failing the closed per-leaf gate.
1131    #[test]
1132    fn mutation_semantics_inherits_through_a_hand_dispatched_selector() {
1133        let selector = union_struct(
1134            "InnerRequest",
1135            vec![union_field("a", "Text", 0), union_field("b", "Void", 1)],
1136        );
1137        let mut outer = dispatch_variant("outer", "InnerRequest", "write", MAC, "");
1138        outer.mutation_semantics = "idempotency-key-required".to_owned();
1139        let schema = Box::leak(Box::new(ParsedSchema {
1140            request_variants: vec![outer],
1141            response_variants: vec![],
1142            structs: vec![selector],
1143            scoped_clients: vec![],
1144            enums: vec![],
1145            request_struct: Some(union_struct(
1146                "SvcRequest",
1147                vec![union_field("outer", "InnerRequest", 0)],
1148            )),
1149            response_struct: None,
1150        }));
1151        let resolved = ResolvedSchema::from(schema);
1152        let leaves = collect_method_leaves(&resolved);
1153        assert_eq!(leaves.len(), 2, "both pure-union arms are leaves");
1154        for leaf in &leaves {
1155            assert_eq!(leaf.scope, "write", "scope inheritance is unchanged");
1156            assert_eq!(leaf.dispatch_mac, MAC, "MAC inheritance is unchanged");
1157            assert_eq!(
1158                leaf.mutation_semantics, "idempotency-key-required",
1159                "the selector's declaration must reach {}",
1160                leaf.symbolic
1161            );
1162        }
1163
1164        // The rows are real: the inherited declaration satisfies the closed
1165        // per-leaf gate for BOTH descendants — no compile_error, no invented
1166        // default (the emitted class is the declared one).
1167        let generated = generate_method_policy_rows("svc", &resolved).to_string();
1168        assert!(!generated.contains("compile_error"), "{generated}");
1169        assert_eq!(
1170            generated
1171                .matches("MutationSemantics :: IdempotencyKeyRequired")
1172                .count(),
1173            2,
1174            "both descendant rows carry the inherited declaration:\n{generated}"
1175        );
1176    }
1177
1178    /// The inheritance must not paper over the mandatory gate: a mutating
1179    /// pure-union selector with NO declaration at any level still fails the
1180    /// build on every descendant leaf.
1181    #[test]
1182    fn a_pure_union_selector_without_a_declaration_still_fails_closed() {
1183        let selector = union_struct("InnerRequest", vec![union_field("a", "Text", 0)]);
1184        let mut outer = dispatch_variant("outer", "InnerRequest", "write", MAC, "");
1185        outer.mutation_semantics.clear();
1186        let schema = Box::leak(Box::new(ParsedSchema {
1187            request_variants: vec![outer],
1188            response_variants: vec![],
1189            structs: vec![selector],
1190            scoped_clients: vec![],
1191            enums: vec![],
1192            request_struct: Some(union_struct(
1193                "SvcRequest",
1194                vec![union_field("outer", "InnerRequest", 0)],
1195            )),
1196            response_struct: None,
1197        }));
1198        let resolved = ResolvedSchema::from(schema);
1199        let leaves = collect_method_leaves(&resolved);
1200        assert_eq!(leaves.len(), 1);
1201        assert!(
1202            leaves[0].mutation_semantics.is_empty(),
1203            "nothing may be invented for an undeclared selector"
1204        );
1205        let generated = generate_method_policy_rows("svc", &resolved).to_string();
1206        assert!(generated.contains("compile_error"), "{generated}");
1207        assert!(generated.contains("missing required"), "{generated}");
1208    }
1209
1210    /// Local annotation precedence: a descendant leaf's own declaration wins
1211    /// over the inherited one, while unannotated siblings inherit. (Pipeline
1212    /// schemas reject dispatcher-carried metadata at parse time; this pins
1213    /// the walk's precedence contract itself — the P2 fix must let a local
1214    /// annotation override, not let inheritance shadow it.)
1215    #[test]
1216    fn a_local_declaration_beats_the_inherited_one() {
1217        let mut repo = variant("repo", "RepositoryRequest", "", false);
1218        repo.mutation_semantics = "transaction-ledger-required".to_owned();
1219        repo.mutation_semantics_present = true;
1220        let mut create = dispatch_variant("create", "Text", "write", MAC, "");
1221        create.mutation_semantics = "naturally-idempotent".to_owned();
1222        create.mutation_semantics_present = true;
1223        let mut remove = dispatch_variant("remove", "Void", "manage", MAC, "");
1224        remove.mutation_semantics.clear();
1225        remove.mutation_semantics_present = false;
1226        let schema = Box::leak(Box::new(ParsedSchema {
1227            request_variants: vec![repo],
1228            response_variants: vec![],
1229            structs: vec![union_struct(
1230                "RepositoryRequest",
1231                vec![
1232                    plain_field("id", "Text"),
1233                    union_field("create", "Text", 0),
1234                    union_field("remove", "Void", 1),
1235                ],
1236            )],
1237            scoped_clients: vec![ScopedClient {
1238                factory_name: "repo".into(),
1239                client_name: "RepositoryClient".into(),
1240                scope_fields: vec![plain_field("id", "Text")],
1241                inner_request_variants: vec![create, remove],
1242                inner_response_variants: vec![],
1243                capnp_inner_response: "repository_response".into(),
1244                nested_clients: vec![],
1245            }],
1246            enums: vec![],
1247            request_struct: Some(union_struct(
1248                "SvcRequest",
1249                vec![union_field("repo", "RepositoryRequest", 0)],
1250            )),
1251            response_struct: None,
1252        }));
1253        let resolved = ResolvedSchema::from(schema);
1254        let leaves = collect_method_leaves(&resolved);
1255        let by_symbol: std::collections::HashMap<&str, &MethodLeaf> =
1256            leaves.iter().map(|l| (l.symbolic.as_str(), l)).collect();
1257        assert_eq!(
1258            by_symbol["repo.create"].mutation_semantics, "naturally-idempotent",
1259            "the leaf's local declaration must win"
1260        );
1261        assert_eq!(
1262            by_symbol["repo.remove"].mutation_semantics, "transaction-ledger-required",
1263            "an unannotated sibling must inherit"
1264        );
1265        let generated = generate_method_policy_rows("svc", &resolved).to_string();
1266        assert!(!generated.contains("compile_error"), "{generated}");
1267        assert!(generated.contains("MutationSemantics :: NaturallyIdempotent"));
1268        assert!(generated.contains("MutationSemantics :: TransactionLedgerRequired"));
1269    }
1270
1271    /// Grammar failures at codegen are compile errors, never runtime rows:
1272    /// unknown axes, malformed grammar, and system low through `$dispatchMac`.
1273    #[test]
1274    fn invalid_label_grammar_is_a_compile_error() {
1275        for bad in [
1276            "internal",
1277            "internal:",
1278            "topsecret:pq-hybrid",
1279            "internal:pq",
1280            "internal:pq-hybrid:",
1281            " internal:pq-hybrid",
1282            "public:unverified", // system low through the MAC path
1283        ] {
1284            let resolved = simple_schema(vec![dispatch_variant("load", "Void", "write", bad, "")]);
1285            let generated = generate_method_policy_rows("model", &resolved).to_string();
1286            assert!(generated.contains("compile_error"), "{bad}: {generated}");
1287        }
1288    }
1289
1290    /// A public leaf needs a nonempty trimmed reason and no `$scope`.
1291    #[test]
1292    fn a_public_leaf_requires_a_real_reason_and_no_scope() {
1293        let empty_reason = simple_schema(vec![dispatch_variant("ping", "Void", "", "", "   ")]);
1294        let generated = generate_method_policy_rows("mcp", &empty_reason).to_string();
1295        assert!(generated.contains("compile_error"), "{generated}");
1296
1297        let scoped_public = simple_schema(vec![dispatch_variant(
1298            "ping", "Void", "query", "", "reason",
1299        )]);
1300        let generated = generate_method_policy_rows("mcp", &scoped_public).to_string();
1301        assert!(
1302            generated.contains("cannot be dispatch-public"),
1303            "{generated}"
1304        );
1305    }
1306
1307    /// The generated row carries every §6.1 field: auth requirement, Hybrid
1308    /// signature policy, credential use, mutation semantics keyed off the
1309    /// checked scope-action block, system-low transitional label, parsed
1310    /// target label, and (only for public) the reason.
1311    #[test]
1312    fn generated_rows_carry_the_full_section_6_1_policy() {
1313        let resolved = simple_schema(vec![
1314            dispatch_variant("status", "Void", "query", MAC, ""),
1315            dispatch_variant("commit", "Text", "write", "secret:pq-hybrid", ""),
1316            dispatch_variant("ping", "Void", "", "", "genuinely unauthenticated leaf"),
1317        ]);
1318        let generated = generate_method_policy_rows("model", &resolved).to_string();
1319
1320        assert!(!generated.contains("compile_error"), "{generated}");
1321        for needle in [
1322            "AuthenticationRequirement :: CredentialRequired",
1323            "AuthenticationRequirement :: UnauthenticatedAllowed",
1324            "SignaturePolicy :: TokenBound",
1325            "SignaturePolicy :: UnauthenticatedOrTokenBound",
1326            "CryptoSuite :: Hybrid",
1327            "MutationSemantics :: TransactionLedgerRequired",
1328            "SYSTEM_LOW_LABEL",
1329            "dispatch_label",
1330            "Level :: Internal",
1331            "Assurance :: PqHybrid",
1332            "Level :: Secret",
1333            "\"genuinely unauthenticated leaf\"",
1334        ] {
1335            assert!(
1336                generated.contains(needle),
1337                "missing `{needle}`:\n{generated}"
1338            );
1339        }
1340
1341        // Read-class rows carry no mutation semantics; the declared ledger
1342        // requirement is preserved rather than inferred from `write`.
1343        let mutation_count = generated
1344            .matches("MutationSemantics :: TransactionLedgerRequired")
1345            .count();
1346        assert_eq!(mutation_count, 1, "only `commit` (write) is mutating");
1347    }
1348
1349    /// A mutating scope without checked per-leaf metadata never gets a
1350    /// retry-safe default; it fails the code-generation boundary.
1351    #[test]
1352    fn missing_mutating_policy_is_a_compile_error() {
1353        let mut missing = dispatch_variant("sendInput", "Text", "write", MAC, "");
1354        missing.mutation_semantics.clear();
1355        let generated =
1356            generate_method_policy_rows("tui", &simple_schema(vec![missing])).to_string();
1357        assert!(generated.contains("compile_error"), "{generated}");
1358        assert!(generated.contains("missing required"), "{generated}");
1359    }
1360
1361    /// Each declared authoritative value reaches the generated inventory
1362    /// unchanged; codegen does not collapse them to NaturallyIdempotent.
1363    #[test]
1364    fn declared_mutation_policy_is_preserved() {
1365        let mut natural = dispatch_variant("focus", "Void", "write", MAC, "");
1366        natural.mutation_semantics = "naturally-idempotent".to_owned();
1367        let mut keyed = dispatch_variant("update", "Text", "write", MAC, "");
1368        keyed.mutation_semantics = "idempotency-key-required".to_owned();
1369        let ledger = dispatch_variant("sendInput", "Text", "write", MAC, "");
1370        let generated =
1371            generate_method_policy_rows("tui", &simple_schema(vec![natural, keyed, ledger]))
1372                .to_string();
1373        for variant in [
1374            "MutationSemantics :: NaturallyIdempotent",
1375            "MutationSemantics :: IdempotencyKeyRequired",
1376            "MutationSemantics :: TransactionLedgerRequired",
1377        ] {
1378            assert!(
1379                generated.contains(variant),
1380                "missing {variant}: {generated}"
1381            );
1382        }
1383    }
1384
1385    /// Opus #1518 F-J drift coverage: an IMPORTED pure-union payload
1386    /// (`origin_file` set) terminates the leaf at its annotated arm — the
1387    /// decoder and the inventory share that one row by construction, so the
1388    /// coarsening can never produce an unannotated or unlisted leaf.
1389    #[test]
1390    fn an_imported_pure_union_terminates_on_the_annotated_arm() {
1391        let imported = StructDef {
1392            name: "ImportedChoice".into(),
1393            fields: vec![union_field("x", "Text", 0), union_field("y", "Void", 1)],
1394            has_union: true,
1395            domain_type: None,
1396            origin_file: Some("streaming".into()),
1397            data_words: 1,
1398            pointer_words: 1,
1399            discriminant_count: 2,
1400            discriminant_offset: 0,
1401            union_arms: vec![],
1402        };
1403        let schema = Box::leak(Box::new(ParsedSchema {
1404            request_variants: vec![dispatch_variant(
1405                "fetch",
1406                "ImportedChoice",
1407                "query",
1408                MAC,
1409                "",
1410            )],
1411            response_variants: vec![],
1412            structs: vec![imported],
1413            scoped_clients: vec![],
1414            enums: vec![],
1415            request_struct: Some(union_struct(
1416                "FetchRequest",
1417                vec![union_field("fetch", "ImportedChoice", 0)],
1418            )),
1419            response_struct: None,
1420        }));
1421        let resolved = ResolvedSchema::from(schema);
1422        let leaves = collect_method_leaves(&resolved);
1423        assert_eq!(
1424            leaves.len(),
1425            1,
1426            "imported union arms are payload, not identity"
1427        );
1428        assert_eq!(leaves[0].path, vec![0]);
1429        assert_eq!(leaves[0].dispatch_mac, MAC);
1430
1431        // The shared tree walk drives the decoder identically: the imported
1432        // arm is a terminal decoder arm, and its single inventory row derives
1433        // from the same walk — one row, one decoder arm, no drift.
1434        let decoder = generate_body_decoder("fetch", &resolved).to_string();
1435        assert!(
1436            decoder.contains("fetch_request :: Which :: Fetch"),
1437            "{decoder}"
1438        );
1439        let rows = generate_method_policy_rows("fetch", &resolved).to_string();
1440        assert!(!rows.contains("compile_error"), "{rows}");
1441    }
1442}