Skip to main content

hyprstream_rpc_build/schema/
cgr_reader.rs

1//! CGR-based Cap'n Proto schema parser.
2//!
3//! Reads binary CodeGeneratorRequest (CGR) files produced by `capnp compile`
4//! via build.rs, and produces `ParsedSchema` with full wire format info.
5//!
6//! Advantages over text parsing:
7//! - Full type resolution (struct names resolved via node graph)
8//! - Native annotation extraction (no text stripping hacks)
9//! - Deterministic output (BTreeMap for node ordering)
10//! - Wire format offsets (data_words, pointer_words, slot_offset) for codegen
11//! - Discriminant values available directly
12
13use std::collections::BTreeMap;
14use std::path::Path;
15
16use super::mutation_policy::parse_mutation_semantics;
17use super::types::*;
18use crate::util::{to_pascal_case, to_snake_case};
19
20/// Parse a schema from a CGR binary file at a given path.
21pub fn parse_from_cgr_path(cgr_path: &Path, name: &str) -> Result<ParsedSchema, String> {
22    let file = std::fs::File::open(cgr_path)
23        .map_err(|e| format!("Failed to open {}: {e}", cgr_path.display()))?;
24
25    let reader = capnp::serialize::read_message(
26        std::io::BufReader::new(file),
27        capnp::message::ReaderOptions::new(),
28    )
29    .map_err(|e| format!("Failed to read CGR for '{name}': {e}"))?;
30
31    let cgr = reader
32        .get_root::<capnp::schema_capnp::code_generator_request::Reader>()
33        .map_err(|e| format!("Failed to parse CGR root for '{name}': {e}"))?;
34
35    parse_cgr(cgr, name)
36}
37
38/// Parse a schema from a CGR binary file in OUT_DIR (for proc-macro use).
39///
40/// The CGR file is generated by build.rs via `capnpc::CompilerCommand::raw_code_generator_request_path()`.
41pub fn parse_from_cgr(name: &str) -> Result<ParsedSchema, String> {
42    let out_dir = std::env::var("OUT_DIR")
43        .map_err(|_| "OUT_DIR not set — CGR files require build.rs to run first".to_owned())?;
44    let cgr_path = Path::new(&out_dir).join(format!("{name}.cgr"));
45
46    if cgr_path.exists() {
47        return parse_from_cgr_path(&cgr_path, name);
48    }
49
50    // Fall back to dependency crate OUT_DIRs.
51    // Cargo exposes DEP_<CRATE>_<KEY> from dependency build scripts.
52    // hyprstream-rpc-std exports its OUT_DIR via `cargo:out_dir=...`
53    for env_key in [
54        "DEP_HYPRSTREAM_RPC_STD_OUT_DIR",
55        "DEP_HYPRSTREAM_RPC_OUT_DIR",
56    ] {
57        if let Ok(dep_out_dir) = std::env::var(env_key) {
58            let dep_cgr = Path::new(&dep_out_dir).join(format!("{name}.cgr"));
59            if dep_cgr.exists() {
60                return parse_from_cgr_path(&dep_cgr, name);
61            }
62        }
63    }
64
65    parse_from_cgr_path(&cgr_path, name) // will produce the original error
66}
67
68// ---------------------------------------------------------------------------
69// Internal: CGR parsing
70// ---------------------------------------------------------------------------
71
72/// A resolved node from the CGR node graph.
73struct NodeInfo {
74    id: u64,
75    display_name: String,
76    /// Short name extracted from display_name (after last ':')
77    short_name: String,
78    /// Index into the CGR nodes list (for re-reading)
79    index: u32,
80    /// Parent node ID (scope_id)
81    #[allow(dead_code)]
82    parent_id: u64,
83}
84
85/// Parse the CodeGeneratorRequest into a ParsedSchema.
86fn parse_cgr(
87    cgr: capnp::schema_capnp::code_generator_request::Reader,
88    service_name: &str,
89) -> Result<ParsedSchema, String> {
90    let nodes = cgr.get_nodes().map_err(|e| format!("{e}"))?;
91
92    // Build node map: id -> NodeInfo (BTreeMap for deterministic iteration)
93    let mut node_map: BTreeMap<u64, NodeInfo> = BTreeMap::new();
94    for i in 0..nodes.len() {
95        let node = nodes.get(i);
96        let display_name = node
97            .get_display_name()
98            .map_err(|e| format!("{e}"))?
99            .to_str()
100            .map_err(|e| format!("{e}"))?
101            .to_owned();
102        let short_name = display_name
103            .rsplit(':')
104            .next()
105            .unwrap_or(&display_name)
106            .to_owned();
107        node_map.insert(
108            node.get_id(),
109            NodeInfo {
110                id: node.get_id(),
111                display_name,
112                short_name,
113                index: i,
114                parent_id: node.get_scope_id(),
115            },
116        );
117    }
118
119    // Find annotation node IDs by display_name
120    let mcp_desc_id = find_annotation_id(&nodes, &node_map, "mcpDescription");
121    let param_desc_id = find_annotation_id(&nodes, &node_map, "paramDescription");
122    // S3 (#547): the mandatory scope annotation is `$scope` (alias `$capability`).
123    // Either annotation id (whichever the schema imports) feeds the same extraction.
124    let mcp_scope_id = find_annotation_id(&nodes, &node_map, "scope")
125        .or_else(|| find_annotation_id(&nodes, &node_map, "capability"));
126    let cli_hidden_id = find_annotation_id(&nodes, &node_map, "cliHidden");
127    let domain_type_id = find_annotation_id(&nodes, &node_map, "domainType");
128    let fixed_size_id = find_annotation_id(&nodes, &node_map, "fixedSize");
129    let optional_id = find_annotation_id(&nodes, &node_map, "optional");
130    let serde_rename_id = find_annotation_id(&nodes, &node_map, "serdeRename");
131    let doc_example_id = find_annotation_id(&nodes, &node_map, "docExample");
132    let max_len_id = find_annotation_id(&nodes, &node_map, "maxLen");
133
134    let pascal = to_pascal_case(service_name);
135    let request_name = format!("{pascal}Request");
136    let response_name = format!("{pascal}Response");
137
138    // Extract all structs (for type resolution in codegen)
139    let all_structs = extract_all_structs(
140        &nodes,
141        &node_map,
142        service_name,
143        mcp_desc_id,
144        param_desc_id,
145        domain_type_id,
146        fixed_size_id,
147        max_len_id,
148        optional_id,
149        serde_rename_id,
150    )?;
151
152    // Extract all enums (pass all_structs for imported type resolution)
153    let enums = extract_all_enums(&nodes, &node_map, service_name, &all_structs)?;
154
155    // Find request and response struct node IDs — data-only schemas may not have them
156    let request_node_id = find_struct_node_id(&node_map, &request_name);
157    let response_node_id = find_struct_node_id(&node_map, &response_name);
158
159    let (request_variants, response_variants) = match (request_node_id, response_node_id) {
160        (Some(req_id), Some(resp_id)) => {
161            let request_node = nodes.get(node_map[&req_id].index);
162            let response_node = nodes.get(node_map[&resp_id].index);
163
164            let rv = extract_union_variants(
165                request_node,
166                &nodes,
167                &node_map,
168                mcp_desc_id,
169                param_desc_id,
170                mcp_scope_id,
171                cli_hidden_id,
172                doc_example_id,
173            )?;
174            let rs = extract_union_variants(
175                response_node,
176                &nodes,
177                &node_map,
178                mcp_desc_id,
179                param_desc_id,
180                mcp_scope_id,
181                cli_hidden_id,
182                doc_example_id,
183            )?;
184
185            if rv.is_empty() || rs.is_empty() {
186                (vec![], vec![])
187            } else {
188                (rv, rs)
189            }
190        }
191        _ => (vec![], vec![]),
192    };
193
194    let is_data_only = request_variants.is_empty();
195
196    // Detect scoped clients (nested union pattern) — skip for data-only schemas
197    let scoped_clients = if is_data_only {
198        Vec::new()
199    } else {
200        let mut sc = detect_scoped_clients(
201            &request_variants,
202            &response_variants,
203            &all_structs,
204            &nodes,
205            &node_map,
206            mcp_desc_id,
207            param_desc_id,
208            mcp_scope_id,
209            cli_hidden_id,
210            doc_example_id,
211        )?;
212
213        // Recursively detect nested scoped clients (3rd level)
214        for s in &mut sc {
215            detect_nested_scoped_clients_cgr(
216                s,
217                &all_structs,
218                &nodes,
219                &node_map,
220                mcp_desc_id,
221                param_desc_id,
222                mcp_scope_id,
223                cli_hidden_id,
224                doc_example_id,
225            )?;
226        }
227        sc
228    };
229
230    // Validate policy metadata while the complete local struct graph is available.
231    validate_mandatory_dispatch_with_structs(
232        service_name,
233        &request_variants,
234        &scoped_clients,
235        &all_structs,
236    )?;
237    validate_mandatory_mutation_policy_with_structs(
238        service_name,
239        &request_variants,
240        &scoped_clients,
241        &all_structs,
242    )?;
243
244    // Partition: for data-only schemas keep all structs; otherwise separate request/response
245    let (referenced, request_struct, response_struct) = if is_data_only {
246        (all_structs, None, None)
247    } else {
248        let mut req = None;
249        let mut resp = None;
250        let mut refs = Vec::new();
251        for s in all_structs {
252            if s.name == request_name {
253                req = Some(s);
254            } else if s.name == response_name {
255                resp = Some(s);
256            } else {
257                refs.push(s);
258            }
259        }
260        (refs, req, resp)
261    };
262
263    // S3 (#547): scope is MANDATORY on every leaf method. Validate after scoped-
264    // client detection so dispatcher variants (which carry no scope of their own;
265    // their leaves do) are correctly exempt.
266    validate_mandatory_scope(service_name, &request_variants, &scoped_clients)?;
267
268    Ok(ParsedSchema {
269        request_variants,
270        response_variants,
271        structs: referenced,
272        scoped_clients,
273        enums,
274        request_struct,
275        response_struct,
276    })
277}
278
279/// S3 (#547): enforce that every leaf RPC method declares a `$scope`/`$capability`.
280///
281/// A method with no scope is a BUILD ERROR — there are no silently-public methods.
282/// Dispatcher variants (whose payload is a nested scoped `*Request` union) are exempt:
283/// they route into a sub-client whose own leaf methods carry the scope. Such a
284/// dispatcher is recognized by its variant name matching a detected scoped client's
285/// `factory_name`; its leaves are validated recursively.
286fn validate_mandatory_scope(
287    service_name: &str,
288    request_variants: &[UnionVariant],
289    scoped_clients: &[ScopedClient],
290) -> Result<(), String> {
291    fn err(service_name: &str, path: &str, name: &str) -> String {
292        format!(
293            "service `{service_name}`: method `{path}{name}` has no `$scope`/`$capability` annotation \
294             — scope is mandatory (S3, epic #547). Add e.g. `$scope(query)` for query/read authorization \
295             or `$scope(write)` for a mutating authority boundary; separately declare any application effect; or, only if the method \
296             genuinely cannot require authorization, declare `$scopeExempt(\"<reason>\")`."
297        )
298    }
299
300    // Recurse into a scoped client's leaves + nested dispatchers.
301    fn check_scoped(service_name: &str, path: &str, sc: &ScopedClient) -> Result<(), String> {
302        let here = format!("{path}{} ", sc.factory_name);
303        let nested_names: Vec<&str> = sc
304            .nested_clients
305            .iter()
306            .map(|n| n.factory_name.as_str())
307            .collect();
308        for v in &sc.inner_request_variants {
309            // A nested dispatcher inside this scope is itself exempt; recurse instead.
310            if nested_names.contains(&v.name.as_str()) {
311                continue;
312            }
313            if v.scope.is_empty() && !v.scope_exempt {
314                return Err(err(service_name, &here, &v.name));
315            }
316        }
317        for n in &sc.nested_clients {
318            check_scoped(service_name, &here, n)?;
319        }
320        Ok(())
321    }
322
323    let dispatcher_names: Vec<&str> = scoped_clients
324        .iter()
325        .map(|sc| sc.factory_name.as_str())
326        .collect();
327    for v in request_variants {
328        if dispatcher_names.contains(&v.name.as_str()) {
329            continue; // dispatcher: leaves validated via check_scoped below
330        }
331        if v.scope.is_empty() && !v.scope_exempt {
332            return Err(err(service_name, "", &v.name));
333        }
334    }
335    for sc in scoped_clients {
336        check_scoped(service_name, "", sc)?;
337    }
338    Ok(())
339}
340
341/// v16 §6 (WS-D, #1505): enforce the strict dispatch-policy pair on every leaf.
342///
343/// Structural rules checked here (the label GRAMMAR itself is parsed later, in
344/// codegen, against the checked-in `InitialLabelMap` — see
345/// `schema::dispatch_label`):
346///
347/// - every leaf carries **exactly one** of `$dispatchMac` / `$dispatchPublic`
348///   (neither is a build error; both are a build error);
349/// - a scoped dispatcher carries **neither** (its leaves do — an annotation on
350///   a dispatcher would be dead, misleading metadata);
351/// - `$dispatchPublic` never coexists with a `$scope` action (a leaf the
352///   control plane scopes cannot be dispatch-public);
353/// - `$dispatchPublic` requires a nonempty, already-trimmed reason (padding is
354///   a schema error — the recorded reason is the exact annotation text).
355///
356/// This runs at schema-parse time (build.rs / proc-macro), so an unannotated
357/// or doubly-annotated leaf fails the build of the schema's own crate — the
358/// earliest possible gate. The leaf-tree walk in the derive macro re-derives
359/// the same facts and emits `compile_error!` for any leaf this walk cannot
360/// reach (hand-dispatched pure-union arms), so no annotation failure can ever
361/// produce an unlabeled runtime row.
362#[cfg(test)]
363fn validate_mandatory_dispatch(
364    service_name: &str,
365    request_variants: &[UnionVariant],
366    scoped_clients: &[ScopedClient],
367) -> Result<(), String> {
368    validate_mandatory_dispatch_with_structs(service_name, request_variants, scoped_clients, &[])
369}
370
371fn validate_mandatory_dispatch_with_structs(
372    service_name: &str,
373    request_variants: &[UnionVariant],
374    scoped_clients: &[ScopedClient],
375    all_structs: &[StructDef],
376) -> Result<(), String> {
377    let labels = crate::schema::dispatch_label::InitialLabelMap::load()
378        .map_err(|e| format!("service `{service_name}`: {e}"))?;
379
380    fn pure<'a>(all: &'a [StructDef], name: &str) -> Option<&'a StructDef> {
381        all.iter().find(|s| {
382            s.origin_file.is_none()
383                && s.name == name
384                && s.is_pure_union()
385                && s.option_inner_type().is_none()
386        })
387    }
388
389    fn leaf(
390        service: &str,
391        path: &str,
392        name: &str,
393        scope: &str,
394        mac: &str,
395        mac_present: bool,
396        public: &str,
397        public_present: bool,
398        labels: &crate::schema::dispatch_label::InitialLabelMap,
399    ) -> Result<(), String> {
400        match (mac_present, public_present) {
401            (false, false) => Err(format!(
402                "service `{service}`: method `{path}{name}` has neither a `$dispatchMac` nor a `$dispatchPublic` annotation — the dispatch-policy pair is mandatory on every leaf (v16 §6)."
403            )),
404            (true, true) => Err(format!(
405                "service `{service}`: method `{path}{name}` carries BOTH `$dispatchMac` and `$dispatchPublic` — exactly one dispatch annotation per leaf (v16 §6)."
406            )),
407            (false, true) => {
408                if !scope.is_empty() {
409                    return Err(format!(
410                        "service `{service}`: method `{path}{name}` is `$dispatchPublic` but also declares `$scope({scope})`; cannot be dispatch-public"
411                    ));
412                }
413                crate::schema::dispatch_label::parse_dispatch_public_reason(public)
414                    .map(|_| ())
415                    .map_err(|e| format!("service `{service}`: method `{path}{name}`: {e}"))
416            }
417            (true, false) => crate::schema::dispatch_label::parse_dispatch_mac(mac, labels)
418                .map(|_| ())
419                .map_err(|e| {
420                    format!(
421                        "service `{service}`: method `{path}{name}` $dispatchMac {mac:?}: {e}"
422                    )
423                }),
424        }
425    }
426
427    fn selector<'a>(
428        service: &str,
429        path: &str,
430        name: &str,
431        _scope: &str,
432        mac: &'a str,
433        mac_present: bool,
434        _public: &str,
435        public_present: bool,
436        labels: &crate::schema::dispatch_label::InitialLabelMap,
437    ) -> Result<Option<&'a str>, String> {
438        if mac_present && public_present {
439            return Err(format!(
440                "service `{service}`: dispatcher `{path}{name}` carries BOTH `$dispatchMac` and `$dispatchPublic`"
441            ));
442        }
443        if public_present {
444            return Err(format!(
445                "service `{service}`: dispatcher `{path}{name}` carries `$dispatchPublic`; public is legal only on leaves"
446            ));
447        }
448        if mac_present {
449            crate::schema::dispatch_label::parse_dispatch_mac(mac, labels).map_err(|e| {
450                format!("service `{service}`: dispatcher `{path}{name}` $dispatchMac {mac:?}: {e}")
451            })?;
452            return Ok(Some(mac));
453        }
454        Ok(None)
455    }
456
457    fn walk(
458        service: &str,
459        path: &str,
460        scope: &str,
461        inherited_mac: Option<&str>,
462        sdef: &StructDef,
463        all: &[StructDef],
464        labels: &crate::schema::dispatch_label::InitialLabelMap,
465    ) -> Result<(), String> {
466        for arm in &sdef.union_arms {
467            let arm_path = format!("{path}{}.", arm.name);
468            let nested = match &arm.payload {
469                ArmPayload::Type(name) => pure(all, name),
470                _ => None,
471            };
472            let local_mac = arm
473                .dispatch_mac_present
474                .then_some(arm.dispatch_mac.as_str());
475            let inherited_or_local = local_mac.or(inherited_mac);
476            if let Some(inner) = nested {
477                let next = selector(
478                    service,
479                    &arm_path,
480                    "",
481                    scope,
482                    arm.dispatch_mac.as_str(),
483                    arm.dispatch_mac_present,
484                    arm.dispatch_public.as_str(),
485                    arm.dispatch_public_present,
486                    labels,
487                )?;
488                walk(
489                    service,
490                    &arm_path,
491                    scope,
492                    next.or(inherited_mac),
493                    inner,
494                    all,
495                    labels,
496                )?;
497            } else {
498                let (mac, mac_present) = if arm.dispatch_public_present {
499                    // A local MAC remains present so a local MAC/Public pair
500                    // is rejected; a public-only leaf clears inherited MAC.
501                    if arm.dispatch_mac_present {
502                        (arm.dispatch_mac.as_str(), true)
503                    } else {
504                        ("", false)
505                    }
506                } else {
507                    (
508                        inherited_or_local.unwrap_or(""),
509                        inherited_or_local.is_some(),
510                    )
511                };
512                leaf(
513                    service,
514                    &arm_path,
515                    "",
516                    scope,
517                    mac,
518                    mac_present,
519                    &arm.dispatch_public,
520                    arm.dispatch_public_present,
521                    labels,
522                )?;
523            }
524        }
525        Ok(())
526    }
527
528    fn scoped(
529        service: &str,
530        path: &str,
531        client: &ScopedClient,
532        all: &[StructDef],
533        labels: &crate::schema::dispatch_label::InitialLabelMap,
534    ) -> Result<(), String> {
535        let here = format!("{path}{} ", client.factory_name);
536        let nested_names: Vec<&str> = client
537            .nested_clients
538            .iter()
539            .map(|n| n.factory_name.as_str())
540            .collect();
541        for variant in &client.inner_request_variants {
542            if nested_names.contains(&variant.name.as_str()) {
543                if variant.dispatch_mac_present || variant.dispatch_public_present {
544                    return Err(format!(
545                        "service `{service}`: dispatcher `{here}{}` carries a dispatch annotation",
546                        variant.name
547                    ));
548                }
549            } else if let Some(inner) = pure(all, &variant.type_name) {
550                let inherited = selector(
551                    service,
552                    &here,
553                    &variant.name,
554                    &variant.scope,
555                    &variant.dispatch_mac,
556                    variant.dispatch_mac_present,
557                    &variant.dispatch_public,
558                    variant.dispatch_public_present,
559                    labels,
560                )?;
561                walk(
562                    service,
563                    &format!("{here}{}.", variant.name),
564                    &variant.scope,
565                    inherited,
566                    inner,
567                    all,
568                    labels,
569                )?;
570            } else {
571                leaf(
572                    service,
573                    &here,
574                    &variant.name,
575                    &variant.scope,
576                    &variant.dispatch_mac,
577                    variant.dispatch_mac_present,
578                    &variant.dispatch_public,
579                    variant.dispatch_public_present,
580                    labels,
581                )?;
582            }
583        }
584        for nested in &client.nested_clients {
585            scoped(service, &here, nested, all, labels)?;
586        }
587        Ok(())
588    }
589
590    let dispatcher_names: Vec<&str> = scoped_clients
591        .iter()
592        .map(|client| client.factory_name.as_str())
593        .collect();
594    for variant in request_variants {
595        if dispatcher_names.contains(&variant.name.as_str()) {
596            if variant.dispatch_mac_present || variant.dispatch_public_present {
597                return Err(format!(
598                    "service `{service_name}`: dispatcher `{}` carries a dispatch annotation",
599                    variant.name
600                ));
601            }
602        } else if let Some(inner) = pure(all_structs, &variant.type_name) {
603            let inherited = selector(
604                service_name,
605                "",
606                &variant.name,
607                &variant.scope,
608                &variant.dispatch_mac,
609                variant.dispatch_mac_present,
610                &variant.dispatch_public,
611                variant.dispatch_public_present,
612                &labels,
613            )?;
614            walk(
615                service_name,
616                &format!("{}.", variant.name),
617                &variant.scope,
618                inherited,
619                inner,
620                all_structs,
621                &labels,
622            )?;
623        } else {
624            leaf(
625                service_name,
626                "",
627                &variant.name,
628                &variant.scope,
629                &variant.dispatch_mac,
630                variant.dispatch_mac_present,
631                &variant.dispatch_public,
632                variant.dispatch_public_present,
633                &labels,
634            )?;
635        }
636    }
637    for client in scoped_clients {
638        scoped(service_name, "", client, all_structs, &labels)?;
639    }
640    Ok(())
641}
642
643#[cfg(test)]
644fn validate_mandatory_mutation_policy(
645    service_name: &str,
646    request_variants: &[UnionVariant],
647    scoped_clients: &[ScopedClient],
648) -> Result<(), String> {
649    validate_mandatory_mutation_policy_with_structs(
650        service_name,
651        request_variants,
652        scoped_clients,
653        &[],
654    )
655}
656
657fn validate_mandatory_mutation_policy_with_structs(
658    service_name: &str,
659    request_variants: &[UnionVariant],
660    scoped_clients: &[ScopedClient],
661    all_structs: &[StructDef],
662) -> Result<(), String> {
663    fn pure<'a>(all: &'a [StructDef], name: &str) -> Option<&'a StructDef> {
664        all.iter().find(|s| {
665            s.origin_file.is_none()
666                && s.name == name
667                && s.is_pure_union()
668                && s.option_inner_type().is_none()
669        })
670    }
671    fn leaf(
672        service: &str,
673        path: &str,
674        name: &str,
675        scope: &str,
676        semantics: &str,
677        present: bool,
678    ) -> Result<(), String> {
679        let read = crate::schema::dispatch_label::READ_CLASS_ACTIONS.contains(&scope);
680        if !present {
681            if !read && !scope.is_empty() {
682                return Err(format!("service `{service}`: method `{path}{name}` (scope `{scope}`) is missing required `$mutationSemantics`; declare its actual retry/application-effect policy"));
683            }
684            return Ok(());
685        }
686        parse_mutation_semantics(semantics).map(|_| ()).map_err(|e| format!("service `{service}`: method `{path}{name}` (scope `{scope}`) {e}; declare its actual retry/application-effect policy"))
687    }
688    fn walk(
689        service: &str,
690        path: &str,
691        scope: &str,
692        inherited: Option<&str>,
693        sdef: &StructDef,
694        all: &[StructDef],
695    ) -> Result<(), String> {
696        for arm in &sdef.union_arms {
697            let semantics = if arm.mutation_semantics_present {
698                Some(arm.mutation_semantics.as_str())
699            } else {
700                inherited
701            };
702            if let Some(inner) = match &arm.payload {
703                ArmPayload::Type(name) => pure(all, name),
704                _ => None,
705            } {
706                if arm.mutation_semantics_present {
707                    parse_mutation_semantics(arm.mutation_semantics.as_str()).map_err(|e| {
708                        format!(
709                            "service `{service}`: dispatcher `{path}{}` $mutationSemantics: {e}",
710                            arm.name
711                        )
712                    })?;
713                }
714                walk(
715                    service,
716                    &format!("{path}{}.", arm.name),
717                    scope,
718                    semantics,
719                    inner,
720                    all,
721                )?;
722            } else {
723                leaf(
724                    service,
725                    &format!("{path}{}.", arm.name),
726                    "",
727                    scope,
728                    semantics.unwrap_or(""),
729                    semantics.is_some(),
730                )?;
731            }
732        }
733        Ok(())
734    }
735    fn scoped(
736        service: &str,
737        path: &str,
738        client: &ScopedClient,
739        all: &[StructDef],
740    ) -> Result<(), String> {
741        let here = format!("{path}{} ", client.factory_name);
742        let nested_names: Vec<&str> = client
743            .nested_clients
744            .iter()
745            .map(|n| n.factory_name.as_str())
746            .collect();
747        for variant in &client.inner_request_variants {
748            if nested_names.contains(&variant.name.as_str()) {
749                if variant.mutation_semantics_present {
750                    return Err(format!(
751                        "service `{service}`: dispatcher `{here}{}` carries `$mutationSemantics`",
752                        variant.name
753                    ));
754                }
755            } else if let Some(inner) = pure(all, &variant.type_name) {
756                if variant.mutation_semantics_present {
757                    parse_mutation_semantics(&variant.mutation_semantics).map_err(|e| {
758                        format!(
759                            "service `{service}`: dispatcher `{here}{}` $mutationSemantics: {e}",
760                            variant.name
761                        )
762                    })?;
763                }
764                walk(
765                    service,
766                    &format!("{here}{}.", variant.name),
767                    &variant.scope,
768                    variant
769                        .mutation_semantics_present
770                        .then_some(variant.mutation_semantics.as_str()),
771                    inner,
772                    all,
773                )?;
774            } else {
775                leaf(
776                    service,
777                    &here,
778                    &variant.name,
779                    &variant.scope,
780                    &variant.mutation_semantics,
781                    variant.mutation_semantics_present,
782                )?;
783            }
784        }
785        for nested in &client.nested_clients {
786            scoped(service, &here, nested, all)?;
787        }
788        Ok(())
789    }
790    let names: Vec<&str> = scoped_clients
791        .iter()
792        .map(|client| client.factory_name.as_str())
793        .collect();
794    for variant in request_variants {
795        if names.contains(&variant.name.as_str()) {
796            if variant.mutation_semantics_present {
797                return Err(format!(
798                    "service `{service_name}`: dispatcher `{}` carries `$mutationSemantics`",
799                    variant.name
800                ));
801            }
802        } else if let Some(inner) = pure(all_structs, &variant.type_name) {
803            if variant.mutation_semantics_present {
804                parse_mutation_semantics(&variant.mutation_semantics).map_err(|e| {
805                    format!(
806                        "service `{service_name}`: dispatcher `{}` $mutationSemantics: {e}",
807                        variant.name
808                    )
809                })?;
810            }
811            walk(
812                service_name,
813                &format!("{}.", variant.name),
814                &variant.scope,
815                variant
816                    .mutation_semantics_present
817                    .then_some(variant.mutation_semantics.as_str()),
818                inner,
819                all_structs,
820            )?;
821        } else {
822            leaf(
823                service_name,
824                "",
825                &variant.name,
826                &variant.scope,
827                &variant.mutation_semantics,
828                variant.mutation_semantics_present,
829            )?;
830        }
831    }
832    for client in scoped_clients {
833        scoped(service_name, "", client, all_structs)?;
834    }
835    Ok(())
836}
837
838// Node lookup helpers
839// ---------------------------------------------------------------------------
840
841/// Find a struct node ID by short name.
842fn find_struct_node_id(node_map: &BTreeMap<u64, NodeInfo>, short_name: &str) -> Option<u64> {
843    node_map
844        .values()
845        .find(|n| n.short_name == short_name)
846        .map(|n| n.id)
847}
848
849/// Find an annotation node ID by its short name (e.g., "mcpDescription").
850fn find_annotation_id(
851    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
852    node_map: &BTreeMap<u64, NodeInfo>,
853    annotation_name: &str,
854) -> Option<u64> {
855    for info in node_map.values() {
856        let node = nodes.get(info.index);
857        if let Ok(capnp::schema_capnp::node::Annotation(_)) = node.which() {
858            if info.short_name == annotation_name {
859                return Some(info.id);
860            }
861        }
862    }
863    None
864}
865
866/// Resolve a type ID to a short struct/enum name using the node map.
867fn resolve_type_name(
868    type_reader: capnp::schema_capnp::type_::Reader,
869    node_map: &BTreeMap<u64, NodeInfo>,
870) -> String {
871    use capnp::schema_capnp::type_;
872    match type_reader.which() {
873        Ok(type_::Void(())) => "Void".into(),
874        Ok(type_::Bool(())) => "Bool".into(),
875        Ok(type_::Int8(())) => "Int8".into(),
876        Ok(type_::Int16(())) => "Int16".into(),
877        Ok(type_::Int32(())) => "Int32".into(),
878        Ok(type_::Int64(())) => "Int64".into(),
879        Ok(type_::Uint8(())) => "UInt8".into(),
880        Ok(type_::Uint16(())) => "UInt16".into(),
881        Ok(type_::Uint32(())) => "UInt32".into(),
882        Ok(type_::Uint64(())) => "UInt64".into(),
883        Ok(type_::Float32(())) => "Float32".into(),
884        Ok(type_::Float64(())) => "Float64".into(),
885        Ok(type_::Text(())) => "Text".into(),
886        Ok(type_::Data(())) => "Data".into(),
887        Ok(type_::List(list_type)) => {
888            if let Ok(element_type) = list_type.get_element_type() {
889                format!("List({})", resolve_type_name(element_type, node_map))
890            } else {
891                "List".into()
892            }
893        }
894        Ok(type_::Enum(enum_type)) => {
895            let type_id = enum_type.get_type_id();
896            node_map
897                .get(&type_id)
898                .map(|n| n.short_name.clone())
899                .unwrap_or_else(|| "Enum".into())
900        }
901        Ok(type_::Struct(struct_type)) => {
902            let type_id = struct_type.get_type_id();
903            node_map
904                .get(&type_id)
905                .map(|n| n.short_name.clone())
906                .unwrap_or_else(|| "Struct".into())
907        }
908        Ok(type_::Interface(_)) => "Interface".into(),
909        Ok(type_::AnyPointer(_)) => "AnyPointer".into(),
910        Err(_) => "Unknown".into(),
911    }
912}
913
914/// Determine the FieldSection from a Cap'n Proto type.
915fn field_section_from_type(type_reader: capnp::schema_capnp::type_::Reader) -> FieldSection {
916    use capnp::schema_capnp::type_;
917    match type_reader.which() {
918        Ok(type_::Text(()))
919        | Ok(type_::Data(()))
920        | Ok(type_::List(_))
921        | Ok(type_::Struct(_))
922        | Ok(type_::Interface(_))
923        | Ok(type_::AnyPointer(_)) => FieldSection::Pointer,
924        Ok(type_::Void(()))
925        | Ok(type_::Bool(()))
926        | Ok(type_::Int8(()))
927        | Ok(type_::Int16(()))
928        | Ok(type_::Int32(()))
929        | Ok(type_::Int64(()))
930        | Ok(type_::Uint8(()))
931        | Ok(type_::Uint16(()))
932        | Ok(type_::Uint32(()))
933        | Ok(type_::Uint64(()))
934        | Ok(type_::Float32(()))
935        | Ok(type_::Float64(()))
936        | Ok(type_::Enum(_))
937        | Err(_) => FieldSection::Data,
938    }
939}
940
941/// Extract text from an annotation value.
942fn extract_annotation_text(
943    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
944    target_id: Option<u64>,
945) -> String {
946    let target_id = match target_id {
947        Some(id) => id,
948        None => return String::new(),
949    };
950    for i in 0..annotations.len() {
951        let ann = annotations.get(i);
952        if ann.get_id() == target_id {
953            if let Ok(value) = ann.get_value() {
954                if let Ok(capnp::schema_capnp::value::Text(Ok(text))) = value.which() {
955                    if let Ok(s) = text.to_str() {
956                        return s.to_owned();
957                    }
958                }
959            }
960        }
961    }
962    String::new()
963}
964
965/// Extract a UInt32 annotation value (e.g., `$fixedSize(32)`).
966fn extract_annotation_u32(
967    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
968    target_id: Option<u64>,
969) -> Option<u32> {
970    let target_id = target_id?;
971    for i in 0..annotations.len() {
972        let ann = annotations.get(i);
973        if ann.get_id() == target_id {
974            if let Ok(value) = ann.get_value() {
975                if let Ok(capnp::schema_capnp::value::Uint32(n)) = value.which() {
976                    return Some(n);
977                }
978            }
979        }
980    }
981    None
982}
983
984/// Extract an enum annotation value by resolving the ordinal to a variant name.
985///
986/// Matches by the annotation node's short name (`scope` or its alias `capability`)
987/// rather than a single id, so either spelling resolves to the same action vocabulary.
988/// `target_id` is retained only as a hint for the common single-annotation case.
989fn extract_annotation_enum(
990    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
991    target_id: Option<u64>,
992    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
993    node_map: &BTreeMap<u64, NodeInfo>,
994    scope_ann_ids: &std::collections::BTreeSet<u64>,
995) -> String {
996    let _ = target_id;
997    // `scope_ann_ids` (the annotation ids whose node short-name is `scope` or its
998    // alias `capability`) is computed once per struct by the caller, NOT rebuilt
999    // per field — this runs on the build hot path (once per union variant).
1000    if scope_ann_ids.is_empty() {
1001        return String::new();
1002    }
1003    for i in 0..annotations.len() {
1004        let ann = annotations.get(i);
1005        let ann_id = ann.get_id();
1006        if scope_ann_ids.contains(&ann_id) {
1007            if let Ok(value) = ann.get_value() {
1008                if let Ok(capnp::schema_capnp::value::Enum(ordinal)) = value.which() {
1009                    if let Some(ann_info) = node_map.get(&ann_id) {
1010                        let ann_node = nodes.get(ann_info.index);
1011                        if let Ok(capnp::schema_capnp::node::Annotation(ann_reader)) =
1012                            ann_node.which()
1013                        {
1014                            if let Ok(type_reader) = ann_reader.get_type() {
1015                                if let Ok(capnp::schema_capnp::type_::Enum(enum_type)) =
1016                                    type_reader.which()
1017                                {
1018                                    let enum_type_id = enum_type.get_type_id();
1019                                    if let Some(enum_info) = node_map.get(&enum_type_id) {
1020                                        let enum_node = nodes.get(enum_info.index);
1021                                        if let Ok(capnp::schema_capnp::node::Enum(enum_reader)) =
1022                                            enum_node.which()
1023                                        {
1024                                            if let Ok(enumerants) = enum_reader.get_enumerants() {
1025                                                for j in 0..enumerants.len() {
1026                                                    let enumerant = enumerants.get(j);
1027                                                    if enumerant.get_code_order() == ordinal {
1028                                                        if let Ok(name) = enumerant.get_name() {
1029                                                            if let Ok(s) = name.to_str() {
1030                                                                return s.to_owned();
1031                                                            }
1032                                                        }
1033                                                    }
1034                                                }
1035                                            }
1036                                        }
1037                                    }
1038                                }
1039                            }
1040                        }
1041                    }
1042                }
1043                // Fallback: also try Text for backward compatibility
1044                if let Ok(capnp::schema_capnp::value::Text(Ok(text))) = value.which() {
1045                    if let Ok(s) = text.to_str() {
1046                        return s.to_owned();
1047                    }
1048                }
1049            }
1050        }
1051    }
1052    String::new()
1053}
1054
1055/// Check if a Void annotation is present (e.g., $cliHidden).
1056fn has_annotation(
1057    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
1058    target_id: Option<u64>,
1059) -> bool {
1060    let target_id = match target_id {
1061        Some(id) => id,
1062        None => return false,
1063    };
1064    for i in 0..annotations.len() {
1065        if annotations.get(i).get_id() == target_id {
1066            return true;
1067        }
1068    }
1069    false
1070}
1071
1072/// Resolve the annotation node id whose short name matches `short_name`.
1073///
1074/// Self-contained lookup used for the VFS projection annotations (epic #539),
1075/// mirroring the inline `scopeExempt` id resolution — avoids threading a new id
1076/// through every extraction signature for annotations captured in one place.
1077fn annotation_id_by_short_name(
1078    node_map: &BTreeMap<u64, NodeInfo>,
1079    short_name: &str,
1080) -> Option<u64> {
1081    node_map
1082        .values()
1083        .find(|info| info.short_name == short_name)
1084        .map(|info| info.id)
1085}
1086
1087/// Extract a `VfsKind` enum annotation as its enumerant name (e.g. "ctl").
1088///
1089/// Resolves the annotation's enum type from the node graph and maps the stored
1090/// ordinal back to the enumerant name, mirroring `extract_annotation_enum`.
1091/// Empty string when the annotation is absent.
1092fn extract_vfs_kind(
1093    annotations: capnp::struct_list::Reader<capnp::schema_capnp::annotation::Owned>,
1094    target_id: Option<u64>,
1095    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1096    node_map: &BTreeMap<u64, NodeInfo>,
1097) -> String {
1098    let target_id = match target_id {
1099        Some(id) => id,
1100        None => return String::new(),
1101    };
1102    for i in 0..annotations.len() {
1103        let ann = annotations.get(i);
1104        if ann.get_id() != target_id {
1105            continue;
1106        }
1107        let Ok(value) = ann.get_value() else { continue };
1108        if let Ok(capnp::schema_capnp::value::Enum(ordinal)) = value.which() {
1109            let Some(ann_info) = node_map.get(&target_id) else {
1110                continue;
1111            };
1112            let ann_node = nodes.get(ann_info.index);
1113            let Ok(capnp::schema_capnp::node::Annotation(ann_reader)) = ann_node.which() else {
1114                continue;
1115            };
1116            let Ok(type_reader) = ann_reader.get_type() else {
1117                continue;
1118            };
1119            let Ok(capnp::schema_capnp::type_::Enum(enum_type)) = type_reader.which() else {
1120                continue;
1121            };
1122            let enum_type_id = enum_type.get_type_id();
1123            let Some(enum_info) = node_map.get(&enum_type_id) else {
1124                continue;
1125            };
1126            let enum_node = nodes.get(enum_info.index);
1127            let Ok(capnp::schema_capnp::node::Enum(enum_reader)) = enum_node.which() else {
1128                continue;
1129            };
1130            let Ok(enumerants) = enum_reader.get_enumerants() else {
1131                continue;
1132            };
1133            for j in 0..enumerants.len() {
1134                let enumerant = enumerants.get(j);
1135                if enumerant.get_code_order() == ordinal {
1136                    if let Ok(name) = enumerant.get_name() {
1137                        if let Ok(s) = name.to_str() {
1138                            return s.to_owned();
1139                        }
1140                    }
1141                }
1142            }
1143        }
1144    }
1145    String::new()
1146}
1147
1148// ---------------------------------------------------------------------------
1149// Union variant extraction
1150// ---------------------------------------------------------------------------
1151
1152/// Extract union variants from a struct node.
1153///
1154/// Union fields have discriminant != 0xFFFF.
1155fn extract_union_variants(
1156    struct_node: capnp::schema_capnp::node::Reader,
1157    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1158    node_map: &BTreeMap<u64, NodeInfo>,
1159    mcp_desc_id: Option<u64>,
1160    _param_desc_id: Option<u64>,
1161    mcp_scope_id: Option<u64>,
1162    cli_hidden_id: Option<u64>,
1163    doc_example_id: Option<u64>,
1164) -> Result<Vec<UnionVariant>, String> {
1165    let struct_reader = match struct_node.which() {
1166        Ok(capnp::schema_capnp::node::Struct(s)) => s,
1167        _ => return Ok(Vec::new()),
1168    };
1169
1170    let fields = struct_reader.get_fields().map_err(|e| format!("{e}"))?;
1171    let mut variants = Vec::new();
1172
1173    // Annotation ids whose node short-name is `scope` or its alias `capability`.
1174    // Computed once per struct (not per field) — `extract_annotation_enum` runs on
1175    // the build hot path (once per union variant).
1176    let scope_ann_ids: std::collections::BTreeSet<u64> = node_map
1177        .values()
1178        .filter(|info| info.short_name == "scope" || info.short_name == "capability")
1179        .map(|info| info.id)
1180        .collect();
1181
1182    // Collect union fields (discriminant != 0xFFFF), sorted by discriminant for determinism
1183    let mut union_fields: Vec<(u16, u32)> = Vec::new();
1184    for i in 0..fields.len() {
1185        let field = fields.get(i);
1186        let disc = field.get_discriminant_value();
1187        if disc != 0xFFFF {
1188            union_fields.push((disc, i));
1189        }
1190    }
1191    union_fields.sort_by_key(|(disc, _)| *disc);
1192
1193    for (_disc, idx) in union_fields {
1194        let field = fields.get(idx);
1195        let name = field
1196            .get_name()
1197            .map_err(|e| format!("{e}"))?
1198            .to_str()
1199            .map_err(|e| format!("{e}"))?
1200            .to_owned();
1201
1202        let type_name = match field.which() {
1203            Ok(capnp::schema_capnp::field::Slot(slot)) => {
1204                let type_reader = slot.get_type().map_err(|e| format!("{e}"))?;
1205                resolve_type_name(type_reader, node_map)
1206            }
1207            Ok(capnp::schema_capnp::field::Group(_)) => "Group".into(),
1208            Err(e) => return Err(format!("Field error: {e}")),
1209        };
1210
1211        let annotations = field.get_annotations().map_err(|e| format!("{e}"))?;
1212        let description = extract_annotation_text(annotations, mcp_desc_id);
1213        let scope = extract_annotation_enum(
1214            field.get_annotations().map_err(|e| format!("{e}"))?,
1215            mcp_scope_id,
1216            nodes,
1217            node_map,
1218            &scope_ann_ids,
1219        );
1220        // S3 (#547): scope is MANDATORY on leaf methods — enforced in
1221        // `validate_mandatory_scope` after scoped-client dispatchers are detected
1222        // (a dispatcher variant carries no scope; its leaves do).
1223        // `$scopeExempt("reason")` is the explicit, audited exemption from
1224        // mandatory scope. Resolve its annotation id by name from the node graph.
1225        let scope_exempt_id = node_map
1226            .values()
1227            .find(|info| info.short_name == "scopeExempt")
1228            .map(|info| info.id);
1229        let scope_exempt = has_annotation(
1230            field.get_annotations().map_err(|e| format!("{e}"))?,
1231            scope_exempt_id,
1232        );
1233        let cli_hidden = has_annotation(
1234            field.get_annotations().map_err(|e| format!("{e}"))?,
1235            cli_hidden_id,
1236        );
1237        let doc_example = extract_annotation_text(
1238            field.get_annotations().map_err(|e| format!("{e}"))?,
1239            doc_example_id,
1240        );
1241
1242        // VFS projection annotations (epic #539, T1). Ids resolved inline by
1243        // node short-name — captured only here, so no signature threading.
1244        let vfs_path_id = annotation_id_by_short_name(node_map, "vfsPath");
1245        let vfs_kind_id = annotation_id_by_short_name(node_map, "vfsKind");
1246        let vfs_bulk_id = annotation_id_by_short_name(node_map, "vfsBulk");
1247        let vfs_hidden_id = annotation_id_by_short_name(node_map, "vfsHidden");
1248        let vfs_mac_id = annotation_id_by_short_name(node_map, "vfsMac");
1249        let vfs_path = extract_annotation_text(
1250            field.get_annotations().map_err(|e| format!("{e}"))?,
1251            vfs_path_id,
1252        );
1253        let vfs_kind = extract_vfs_kind(
1254            field.get_annotations().map_err(|e| format!("{e}"))?,
1255            vfs_kind_id,
1256            nodes,
1257            node_map,
1258        );
1259        let vfs_bulk = has_annotation(
1260            field.get_annotations().map_err(|e| format!("{e}"))?,
1261            vfs_bulk_id,
1262        );
1263        let vfs_hidden = has_annotation(
1264            field.get_annotations().map_err(|e| format!("{e}"))?,
1265            vfs_hidden_id,
1266        );
1267        // $vfsMac (#699 carrier (a)): the MAC label this generated node carries.
1268        // Empty when absent ⇒ the node is unlabeled ⇒ a genesis finding.
1269        let vfs_mac = extract_annotation_text(
1270            field.get_annotations().map_err(|e| format!("{e}"))?,
1271            vfs_mac_id,
1272        );
1273        // Dispatch-policy annotations (v16 §6, WS-D): the strict label /
1274        // public-reason pair that generates the method-policy inventory rows.
1275        // Ids resolved inline by node short-name, same as the VFS set above.
1276        let dispatch_mac_id = annotation_id_by_short_name(node_map, "dispatchMac");
1277        let dispatch_public_id = annotation_id_by_short_name(node_map, "dispatchPublic");
1278        let mutation_semantics_id = annotation_id_by_short_name(node_map, "mutationSemantics");
1279        let dispatch_mac = extract_annotation_text(
1280            field.get_annotations().map_err(|e| format!("{e}"))?,
1281            dispatch_mac_id,
1282        );
1283        let dispatch_mac_present = has_annotation(
1284            field.get_annotations().map_err(|e| format!("{e}"))?,
1285            dispatch_mac_id,
1286        );
1287        let dispatch_public_present = has_annotation(
1288            field.get_annotations().map_err(|e| format!("{e}"))?,
1289            dispatch_public_id,
1290        );
1291        let dispatch_public = extract_annotation_text(
1292            field.get_annotations().map_err(|e| format!("{e}"))?,
1293            dispatch_public_id,
1294        );
1295        let mutation_semantics = extract_annotation_text(
1296            field.get_annotations().map_err(|e| format!("{e}"))?,
1297            mutation_semantics_id,
1298        );
1299        let mutation_semantics_present = has_annotation(
1300            field.get_annotations().map_err(|e| format!("{e}"))?,
1301            mutation_semantics_id,
1302        );
1303
1304        variants.push(UnionVariant {
1305            name,
1306            type_name,
1307            description,
1308            scope,
1309            scope_exempt,
1310            cli_hidden,
1311            doc_example,
1312            vfs_path,
1313            vfs_kind,
1314            vfs_bulk,
1315            vfs_hidden,
1316            vfs_mac,
1317            dispatch_mac,
1318            dispatch_mac_present,
1319            dispatch_public,
1320            dispatch_public_present,
1321            mutation_semantics,
1322            mutation_semantics_present,
1323        });
1324    }
1325
1326    Ok(variants)
1327}
1328
1329// ---------------------------------------------------------------------------
1330// Field / union-arm extraction
1331// ---------------------------------------------------------------------------
1332
1333/// Annotation node IDs used when building a `FieldDef` from a slot.
1334///
1335/// Bundled into a struct so the same set can be threaded through the struct-field
1336/// loop and the union-arm group-leaf loop without drift.
1337#[derive(Clone, Copy)]
1338struct FieldAnnotationIds {
1339    mcp_desc_id: Option<u64>,
1340    param_desc_id: Option<u64>,
1341    fixed_size_id: Option<u64>,
1342    max_len_id: Option<u64>,
1343    optional_id: Option<u64>,
1344    serde_rename_id: Option<u64>,
1345    domain_type_id: Option<u64>,
1346}
1347
1348/// Build a `FieldDef` from a `Slot` field reader.
1349///
1350/// Shared by the struct-field loop and the union-arm group-leaf loop so the two
1351/// can't drift in how they resolve type names, sections, offsets, and annotations.
1352/// Schema-contract error marker for a `$maxLen(0)` violation. compile_schemas
1353/// promotes parse errors carrying this marker to a hard build failure (the
1354/// maxLen contract says the build fails), while generic parse errors stay
1355/// non-fatal warnings.
1356pub const MAXLEN_ZERO_CONTRACT_ERROR: &str = "$maxLen(0) is invalid";
1357
1358/// Validate the `$maxLen` annotation for one field: absent or positive is
1359/// valid; zero is a contract violation named for the offending field.
1360fn validate_max_len(field_name: &str, max_len: Option<u32>) -> Result<(), String> {
1361    match max_len {
1362        Some(0) => Err(format!(
1363            "field '{field_name}': {MAXLEN_ZERO_CONTRACT_ERROR} \u{2014} the maximum decoded length must be at least 1 (annotations.capnp maxLen contract)"
1364        )),
1365        _ => Ok(()),
1366    }
1367}
1368
1369fn field_def_from_slot(
1370    field: capnp::schema_capnp::field::Reader,
1371    slot: capnp::schema_capnp::field::slot::Reader,
1372    node_map: &BTreeMap<u64, NodeInfo>,
1373    ann: FieldAnnotationIds,
1374) -> Result<FieldDef, String> {
1375    let field_name = field
1376        .get_name()
1377        .map_err(|e| format!("{e}"))?
1378        .to_str()
1379        .map_err(|e| format!("{e}"))?
1380        .to_owned();
1381
1382    let type_reader = slot.get_type().map_err(|e| format!("{e}"))?;
1383    let type_name = resolve_type_name(type_reader, node_map);
1384    let slot_offset = slot.get_offset();
1385    let section = field_section_from_type(type_reader);
1386    let disc = field.get_discriminant_value();
1387
1388    let description = {
1389        let annotations = field.get_annotations().map_err(|e| format!("{e}"))?;
1390        let desc = extract_annotation_text(annotations, ann.param_desc_id);
1391        if desc.is_empty() {
1392            extract_annotation_text(
1393                field.get_annotations().map_err(|e| format!("{e}"))?,
1394                ann.mcp_desc_id,
1395            )
1396        } else {
1397            desc
1398        }
1399    };
1400
1401    let fixed_size = extract_annotation_u32(
1402        field.get_annotations().map_err(|e| format!("{e}"))?,
1403        ann.fixed_size_id,
1404    );
1405    let max_len = extract_annotation_u32(
1406        field.get_annotations().map_err(|e| format!("{e}"))?,
1407        ann.max_len_id,
1408    );
1409    // Bot finding 4136451007 (P2): the maxLen contract (annotations.capnp)
1410    // declares 0 invalid — "the build fails if a schema sets maxLen(0)".
1411    // Reject at parse time with a FIELD-NAMED schema error; fixedSize(0)
1412    // semantics elsewhere are untouched.
1413    validate_max_len(&field_name, max_len)?;
1414
1415    let optional = has_annotation(
1416        field.get_annotations().map_err(|e| format!("{e}"))?,
1417        ann.optional_id,
1418    );
1419
1420    let serde_rename = {
1421        let sr = extract_annotation_text(
1422            field.get_annotations().map_err(|e| format!("{e}"))?,
1423            ann.serde_rename_id,
1424        );
1425        if sr.is_empty() {
1426            None
1427        } else {
1428            Some(sr)
1429        }
1430    };
1431
1432    // Field-level `$domainType("path::Type")`: maps this field to a Rust newtype while
1433    // keeping its capnp wire type. Mirrors the struct-level read in `extract_struct_from_node`.
1434    let domain_type = {
1435        let dt = extract_annotation_text(
1436            field.get_annotations().map_err(|e| format!("{e}"))?,
1437            ann.domain_type_id,
1438        );
1439        if dt.is_empty() {
1440            None
1441        } else {
1442            Some(dt)
1443        }
1444    };
1445
1446    Ok(FieldDef {
1447        name: field_name,
1448        type_name,
1449        description,
1450        fixed_size,
1451        max_len,
1452        optional,
1453        slot_offset,
1454        section,
1455        discriminant_value: disc,
1456        serde_rename,
1457        domain_type,
1458    })
1459}
1460
1461/// Extract the structured union arms from a struct node.
1462///
1463/// For each field with `discriminant_value != 0xFFFF` (sorted by discriminant),
1464/// classify the arm payload:
1465/// - `Slot` of `Void`  → `ArmPayload::Void`
1466/// - `Slot` of any other type → `ArmPayload::Type(name)`
1467/// - `Group` → `ArmPayload::Group(leaf FieldDefs)`, resolved by looking up the
1468///   synthetic nested struct node via `Group::get_type_id()`.
1469///
1470/// Returns an error on a missing group node id or a nested `Group` inside a group
1471/// arm (unsupported — capnp groups don't nest in a way this codegen models).
1472fn extract_union_arms(
1473    struct_reader: capnp::schema_capnp::node::struct_::Reader,
1474    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1475    node_map: &BTreeMap<u64, NodeInfo>,
1476    ann: FieldAnnotationIds,
1477) -> Result<Vec<UnionArm>, String> {
1478    let fields = struct_reader.get_fields().map_err(|e| format!("{e}"))?;
1479
1480    // Collect union fields (discriminant != 0xFFFF), sorted by discriminant.
1481    let mut union_fields: Vec<(u16, u32)> = Vec::new();
1482    for i in 0..fields.len() {
1483        let field = fields.get(i);
1484        let disc = field.get_discriminant_value();
1485        if disc != 0xFFFF {
1486            union_fields.push((disc, i));
1487        }
1488    }
1489    union_fields.sort_by_key(|(disc, _)| *disc);
1490
1491    let mut arms = Vec::with_capacity(union_fields.len());
1492    for (disc, idx) in union_fields {
1493        let field = fields.get(idx);
1494        let name = field
1495            .get_name()
1496            .map_err(|e| format!("{e}"))?
1497            .to_str()
1498            .map_err(|e| format!("{e}"))?
1499            .to_owned();
1500
1501        let description = {
1502            let annotations = field.get_annotations().map_err(|e| format!("{e}"))?;
1503            let desc = extract_annotation_text(annotations, ann.param_desc_id);
1504            if desc.is_empty() {
1505                extract_annotation_text(
1506                    field.get_annotations().map_err(|e| format!("{e}"))?,
1507                    ann.mcp_desc_id,
1508                )
1509            } else {
1510                desc
1511            }
1512        };
1513
1514        let dispatch_mac_id = annotation_id_by_short_name(node_map, "dispatchMac");
1515        let dispatch_public_id = annotation_id_by_short_name(node_map, "dispatchPublic");
1516        let mutation_semantics_id = annotation_id_by_short_name(node_map, "mutationSemantics");
1517        let annotations = field.get_annotations().map_err(|e| format!("{e}"))?;
1518        let dispatch_mac_present = has_annotation(annotations, dispatch_mac_id);
1519        let dispatch_mac = extract_annotation_text(annotations, dispatch_mac_id);
1520        let dispatch_public_present = has_annotation(annotations, dispatch_public_id);
1521        let dispatch_public = extract_annotation_text(annotations, dispatch_public_id);
1522        let mutation_semantics_present = has_annotation(annotations, mutation_semantics_id);
1523        let mutation_semantics = extract_annotation_text(annotations, mutation_semantics_id);
1524
1525        let payload = match field.which() {
1526            Ok(capnp::schema_capnp::field::Slot(slot)) => {
1527                let type_reader = slot.get_type().map_err(|e| format!("{e}"))?;
1528                let tn = resolve_type_name(type_reader, node_map);
1529                if tn == "Void" {
1530                    ArmPayload::Void
1531                } else {
1532                    ArmPayload::Type(tn)
1533                }
1534            }
1535            Ok(capnp::schema_capnp::field::Group(g)) => {
1536                let group_type_id = g.get_type_id();
1537                let group_info = node_map.get(&group_type_id).ok_or_else(|| {
1538                    format!(
1539                        "union arm '{name}': group type id {group_type_id} not found in node map"
1540                    )
1541                })?;
1542                let group_node = nodes.get(group_info.index);
1543                let group_struct = match group_node.which() {
1544                    Ok(capnp::schema_capnp::node::Struct(s)) => s,
1545                    _ => {
1546                        return Err(format!(
1547                            "union arm '{name}': group type id {group_type_id} is not a struct node"
1548                        ))
1549                    }
1550                };
1551                let group_fields = group_struct.get_fields().map_err(|e| format!("{e}"))?;
1552                let mut leaves = Vec::with_capacity(group_fields.len() as usize);
1553                for k in 0..group_fields.len() {
1554                    let leaf = group_fields.get(k);
1555                    match leaf.which() {
1556                        Ok(capnp::schema_capnp::field::Slot(leaf_slot)) => {
1557                            leaves.push(field_def_from_slot(leaf, leaf_slot, node_map, ann)?);
1558                        }
1559                        Ok(capnp::schema_capnp::field::Group(_)) => {
1560                            return Err(format!(
1561                            "union arm '{name}': nested groups inside a group arm are unsupported"
1562                        ))
1563                        }
1564                        Err(e) => return Err(format!("group leaf error in arm '{name}': {e}")),
1565                    }
1566                }
1567                ArmPayload::Group(leaves)
1568            }
1569            Err(e) => return Err(format!("union arm '{name}' field error: {e}")),
1570        };
1571
1572        arms.push(UnionArm {
1573            name,
1574            discriminant_value: disc,
1575            description,
1576            dispatch_mac,
1577            dispatch_mac_present,
1578            dispatch_public,
1579            dispatch_public_present,
1580            mutation_semantics,
1581            mutation_semantics_present,
1582            payload,
1583        });
1584    }
1585
1586    Ok(arms)
1587}
1588
1589// ---------------------------------------------------------------------------
1590// Struct extraction
1591// ---------------------------------------------------------------------------
1592
1593/// Extract a single struct definition from a CGR node, including wire format info.
1594#[allow(clippy::too_many_arguments)]
1595fn extract_struct_from_node(
1596    node: capnp::schema_capnp::node::Reader,
1597    info: &NodeInfo,
1598    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1599    node_map: &BTreeMap<u64, NodeInfo>,
1600    mcp_desc_id: Option<u64>,
1601    param_desc_id: Option<u64>,
1602    domain_type_id: Option<u64>,
1603    fixed_size_id: Option<u64>,
1604    max_len_id: Option<u64>,
1605    optional_id: Option<u64>,
1606    serde_rename_id: Option<u64>,
1607    origin_file: Option<String>,
1608) -> Result<Option<StructDef>, String> {
1609    let struct_reader = match node.which() {
1610        Ok(capnp::schema_capnp::node::Struct(s)) => s,
1611        _ => return Ok(None),
1612    };
1613
1614    // Synthetic group nodes (capnp emits one per `:group { ... }` arm, named
1615    // `Parent.armName`) are NOT standalone types in any language binding — their
1616    // leaf fields are inlined into the parent. Their dotted name is also not a
1617    // valid Rust/TS identifier. Skip them: their structured shape is captured in
1618    // the parent union's `union_arms`.
1619    if struct_reader.get_is_group() {
1620        return Ok(None);
1621    }
1622
1623    let domain_type = {
1624        let annotations = node.get_annotations().map_err(|e| format!("{e}"))?;
1625        let dt = extract_annotation_text(annotations, domain_type_id);
1626        if dt.is_empty() {
1627            None
1628        } else {
1629            Some(dt)
1630        }
1631    };
1632
1633    // Wire format info from CGR
1634    let data_words = struct_reader.get_data_word_count();
1635    let pointer_words = struct_reader.get_pointer_count();
1636    let discriminant_count = struct_reader.get_discriminant_count();
1637    let discriminant_offset = struct_reader.get_discriminant_offset();
1638
1639    let fields_reader = struct_reader.get_fields().map_err(|e| format!("{e}"))?;
1640    let mut fields = Vec::new();
1641    let mut has_union = false;
1642
1643    let ann = FieldAnnotationIds {
1644        mcp_desc_id,
1645        param_desc_id,
1646        fixed_size_id,
1647        max_len_id,
1648        optional_id,
1649        serde_rename_id,
1650        domain_type_id,
1651    };
1652
1653    for j in 0..fields_reader.len() {
1654        let field = fields_reader.get(j);
1655        let disc = field.get_discriminant_value();
1656
1657        if disc != 0xFFFF {
1658            has_union = true;
1659        }
1660
1661        // Slot fields go through the shared `field_def_from_slot` helper (also used
1662        // by the union-arm group-leaf loop) so the two can't drift. Group fields
1663        // keep the flat `("Group", 0, Group)` fallback so the TS/wire-format path is
1664        // byte-for-byte unchanged — their structured shape lives in `union_arms`.
1665        let field_def = match field.which() {
1666            Ok(capnp::schema_capnp::field::Slot(slot)) => {
1667                field_def_from_slot(field, slot, node_map, ann)?
1668            }
1669            Ok(capnp::schema_capnp::field::Group(_)) => {
1670                let field_name = field
1671                    .get_name()
1672                    .map_err(|e| format!("{e}"))?
1673                    .to_str()
1674                    .map_err(|e| format!("{e}"))?
1675                    .to_owned();
1676                let description = {
1677                    let annotations = field.get_annotations().map_err(|e| format!("{e}"))?;
1678                    let desc = extract_annotation_text(annotations, param_desc_id);
1679                    if desc.is_empty() {
1680                        extract_annotation_text(
1681                            field.get_annotations().map_err(|e| format!("{e}"))?,
1682                            mcp_desc_id,
1683                        )
1684                    } else {
1685                        desc
1686                    }
1687                };
1688                let fixed_size = extract_annotation_u32(
1689                    field.get_annotations().map_err(|e| format!("{e}"))?,
1690                    fixed_size_id,
1691                );
1692                let optional = has_annotation(
1693                    field.get_annotations().map_err(|e| format!("{e}"))?,
1694                    optional_id,
1695                );
1696                let serde_rename = {
1697                    let sr = extract_annotation_text(
1698                        field.get_annotations().map_err(|e| format!("{e}"))?,
1699                        serde_rename_id,
1700                    );
1701                    if sr.is_empty() {
1702                        None
1703                    } else {
1704                        Some(sr)
1705                    }
1706                };
1707                FieldDef {
1708                    name: field_name,
1709                    type_name: "Group".into(),
1710                    description,
1711                    fixed_size,
1712                    max_len: None,
1713                    optional,
1714                    slot_offset: 0,
1715                    section: FieldSection::Group,
1716                    discriminant_value: disc,
1717                    serde_rename,
1718                    // Group fields carry no field-level $domainType (they are inlined unions).
1719                    domain_type: None,
1720                }
1721            }
1722            Err(e) => return Err(format!("Field error: {e}")),
1723        };
1724
1725        // We include ALL fields (including union members) for wire-format completeness.
1726        fields.push(field_def);
1727    }
1728
1729    if struct_reader.get_discriminant_count() > 0 {
1730        has_union = true;
1731    }
1732
1733    // Structured union-arm view (Void / single-type / group) for Rust enum codegen.
1734    // Only populated for unions; non-union structs leave this empty so the flat
1735    // `fields` path is byte-for-byte unchanged.
1736    let union_arms = if discriminant_count > 0 {
1737        extract_union_arms(
1738            struct_reader,
1739            nodes,
1740            node_map,
1741            FieldAnnotationIds {
1742                mcp_desc_id,
1743                param_desc_id,
1744                fixed_size_id,
1745                max_len_id,
1746                optional_id,
1747                serde_rename_id,
1748                domain_type_id,
1749            },
1750        )?
1751    } else {
1752        Vec::new()
1753    };
1754
1755    Ok(Some(StructDef {
1756        name: info.short_name.clone(),
1757        fields,
1758        has_union,
1759        domain_type,
1760        origin_file,
1761        data_words,
1762        pointer_words,
1763        discriminant_count,
1764        discriminant_offset,
1765        union_arms,
1766    }))
1767}
1768
1769/// Extract all struct definitions from the schema (for the given service file).
1770///
1771/// Two-pass extraction:
1772/// 1. First pass: extract local types from this schema file
1773/// 2. Second pass: find imported types referenced by variants/fields but not in the local set
1774#[allow(clippy::too_many_arguments)]
1775fn extract_all_structs(
1776    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1777    node_map: &BTreeMap<u64, NodeInfo>,
1778    service_name: &str,
1779    mcp_desc_id: Option<u64>,
1780    param_desc_id: Option<u64>,
1781    domain_type_id: Option<u64>,
1782    fixed_size_id: Option<u64>,
1783    max_len_id: Option<u64>,
1784    optional_id: Option<u64>,
1785    serde_rename_id: Option<u64>,
1786) -> Result<Vec<StructDef>, String> {
1787    let file_prefix = format!("{service_name}.capnp:");
1788    let mut structs = Vec::new();
1789
1790    // Pass 1: extract local types
1791    for info in node_map.values() {
1792        if !info.display_name.starts_with(&file_prefix) {
1793            continue;
1794        }
1795
1796        let node = nodes.get(info.index);
1797        if let Some(s) = extract_struct_from_node(
1798            node,
1799            info,
1800            nodes,
1801            node_map,
1802            mcp_desc_id,
1803            param_desc_id,
1804            domain_type_id,
1805            fixed_size_id,
1806            max_len_id,
1807            optional_id,
1808            serde_rename_id,
1809            None,
1810        )? {
1811            structs.push(s);
1812        }
1813    }
1814
1815    // Pass 2 (iterative): find imported structs transitively referenced by any
1816    // already-known struct (local or previously discovered imported).  We loop
1817    // until no new types are added — typically 2–3 rounds for nested imports
1818    // (e.g. ChatMessage → ToolCall → ToolCallFunction).
1819    let mut known_names: std::collections::HashSet<String> =
1820        structs.iter().map(|s| s.name.clone()).collect();
1821
1822    loop {
1823        let mut referenced_names: std::collections::HashSet<String> =
1824            std::collections::HashSet::new();
1825
1826        // Collect refs from fields of all known structs (local + imported).
1827        for s in &structs {
1828            for f in &s.fields {
1829                collect_type_refs(&f.type_name, &mut referenced_names);
1830            }
1831            // Group-arm leaf types are not in the flat `fields` list, so feed them
1832            // (and single-type arm payloads, for robustness) into the ref collector.
1833            for arm in &s.union_arms {
1834                match &arm.payload {
1835                    ArmPayload::Type(name) => collect_type_refs(name, &mut referenced_names),
1836                    ArmPayload::Group(leaves) => {
1837                        for leaf in leaves {
1838                            collect_type_refs(&leaf.type_name, &mut referenced_names);
1839                        }
1840                    }
1841                    ArmPayload::Void => {}
1842                }
1843            }
1844        }
1845
1846        // Also collect from union variant fields of local CGR nodes.
1847        for info in node_map.values() {
1848            if !info.display_name.starts_with(&file_prefix) {
1849                continue;
1850            }
1851            let node = nodes.get(info.index);
1852            if let Ok(capnp::schema_capnp::node::Struct(s)) = node.which() {
1853                if let Ok(fields) = s.get_fields() {
1854                    for i in 0..fields.len() {
1855                        let field = fields.get(i);
1856                        if field.get_discriminant_value() != 0xFFFF {
1857                            if let Ok(capnp::schema_capnp::field::Slot(slot)) = field.which() {
1858                                if let Ok(type_reader) = slot.get_type() {
1859                                    let type_name = resolve_type_name(type_reader, node_map);
1860                                    collect_type_refs(&type_name, &mut referenced_names);
1861                                }
1862                            }
1863                        }
1864                    }
1865                }
1866            }
1867        }
1868
1869        // Add any referenced types not yet in the known set.
1870        let mut added = false;
1871        for ref_name in &referenced_names {
1872            if known_names.contains(ref_name) || is_primitive_type(ref_name) {
1873                continue;
1874            }
1875            if let Some(info) = node_map.values().find(|n| n.short_name == *ref_name) {
1876                if !info.display_name.starts_with(&file_prefix) {
1877                    let origin = extract_file_stem(&info.display_name);
1878                    let node = nodes.get(info.index);
1879                    if let Some(s) = extract_struct_from_node(
1880                        node,
1881                        info,
1882                        nodes,
1883                        node_map,
1884                        mcp_desc_id,
1885                        param_desc_id,
1886                        domain_type_id,
1887                        fixed_size_id,
1888                        max_len_id,
1889                        optional_id,
1890                        serde_rename_id,
1891                        Some(origin),
1892                    )? {
1893                        known_names.insert(ref_name.clone());
1894                        structs.push(s);
1895                        added = true;
1896                    }
1897                } else {
1898                    // Type is local — just mark it known so we don't revisit.
1899                    known_names.insert(ref_name.clone());
1900                }
1901            }
1902        }
1903
1904        if !added {
1905            break;
1906        }
1907    }
1908
1909    Ok(structs)
1910}
1911
1912/// Extract file stem from a CGR display_name (e.g., "streaming.capnp:StreamInfo" -> "streaming").
1913fn extract_file_stem(display_name: &str) -> String {
1914    display_name
1915        .split(':')
1916        .next()
1917        .unwrap_or("")
1918        .strip_suffix(".capnp")
1919        .unwrap_or("")
1920        .to_owned()
1921}
1922
1923/// Collect struct/enum type references from a capnp type name string.
1924fn collect_type_refs(type_name: &str, refs: &mut std::collections::HashSet<String>) {
1925    if let Some(inner) = type_name
1926        .strip_prefix("List(")
1927        .and_then(|s| s.strip_suffix(')'))
1928    {
1929        collect_type_refs(inner, refs);
1930    } else if !is_primitive_type(type_name) {
1931        refs.insert(type_name.to_owned());
1932    }
1933}
1934
1935// ---------------------------------------------------------------------------
1936// Enum extraction
1937// ---------------------------------------------------------------------------
1938
1939/// Extract a single enum definition from a CGR node.
1940fn extract_enum_from_node(
1941    node: capnp::schema_capnp::node::Reader,
1942    info: &NodeInfo,
1943    origin_file: Option<String>,
1944) -> Result<Option<EnumDef>, String> {
1945    let enum_reader = match node.which() {
1946        Ok(capnp::schema_capnp::node::Enum(e)) => e,
1947        _ => return Ok(None),
1948    };
1949
1950    let enumerants = enum_reader.get_enumerants().map_err(|e| format!("{e}"))?;
1951    let mut variants = Vec::new();
1952
1953    for j in 0..enumerants.len() {
1954        let enumerant = enumerants.get(j);
1955        let variant_name = enumerant
1956            .get_name()
1957            .map_err(|e| format!("{e}"))?
1958            .to_str()
1959            .map_err(|e| format!("{e}"))?
1960            .to_owned();
1961        let code_order = enumerant.get_code_order() as u32;
1962        variants.push((variant_name, code_order));
1963    }
1964
1965    Ok(Some(EnumDef {
1966        name: info.short_name.clone(),
1967        variants,
1968        origin_file,
1969    }))
1970}
1971
1972/// Extract all enum definitions from the schema.
1973fn extract_all_enums(
1974    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
1975    node_map: &BTreeMap<u64, NodeInfo>,
1976    service_name: &str,
1977    all_structs: &[StructDef],
1978) -> Result<Vec<EnumDef>, String> {
1979    let file_prefix = format!("{service_name}.capnp:");
1980    let mut enums = Vec::new();
1981
1982    // Pass 1: local enums
1983    for info in node_map.values() {
1984        if !info.display_name.starts_with(&file_prefix) {
1985            continue;
1986        }
1987
1988        let node = nodes.get(info.index);
1989        if let Some(e) = extract_enum_from_node(node, info, None)? {
1990            enums.push(e);
1991        }
1992    }
1993
1994    // Pass 2: imported enums referenced by local struct fields
1995    let local_enum_names: std::collections::HashSet<String> =
1996        enums.iter().map(|e| e.name.clone()).collect();
1997    let local_struct_names: std::collections::HashSet<String> =
1998        all_structs.iter().map(|s| s.name.clone()).collect();
1999
2000    let mut referenced_names: std::collections::HashSet<String> = std::collections::HashSet::new();
2001    for s in all_structs {
2002        for f in &s.fields {
2003            collect_type_refs(&f.type_name, &mut referenced_names);
2004        }
2005    }
2006
2007    for ref_name in &referenced_names {
2008        if local_enum_names.contains(ref_name)
2009            || local_struct_names.contains(ref_name)
2010            || is_primitive_type(ref_name)
2011        {
2012            continue;
2013        }
2014        if let Some(info) = node_map.values().find(|n| n.short_name == *ref_name) {
2015            if !info.display_name.starts_with(&file_prefix) {
2016                let origin = extract_file_stem(&info.display_name);
2017                let node = nodes.get(info.index);
2018                if let Some(e) = extract_enum_from_node(node, info, Some(origin))? {
2019                    enums.push(e);
2020                }
2021            }
2022        }
2023    }
2024
2025    Ok(enums)
2026}
2027
2028// ---------------------------------------------------------------------------
2029// Scoped client detection
2030// ---------------------------------------------------------------------------
2031
2032/// Try to build a `ScopedClient` for a single request variant.
2033///
2034/// Returns `Ok(Some(client))` when the variant matches the scoped-client pattern:
2035/// the variant's type is a struct with a union, and a matching `{name}Result`
2036/// response variant exists with non-empty inner union variants.
2037///
2038/// Returns `Ok(None)` for any variant that doesn't match (primitive types,
2039/// structs without unions, missing response counterparts, etc.).
2040///
2041/// `require_scope_fields` — when `true`, skips structs whose non-union field
2042/// list is empty.  Used for nested client detection: a nested scope must have
2043/// at least one curried field to distinguish it from a plain method.
2044#[allow(clippy::too_many_arguments)]
2045fn build_scoped_client_for_variant(
2046    req_variant: &UnionVariant,
2047    response_variants: &[UnionVariant],
2048    all_structs: &[StructDef],
2049    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
2050    node_map: &BTreeMap<u64, NodeInfo>,
2051    mcp_desc_id: Option<u64>,
2052    param_desc_id: Option<u64>,
2053    mcp_scope_id: Option<u64>,
2054    cli_hidden_id: Option<u64>,
2055    doc_example_id: Option<u64>,
2056    require_scope_fields: bool,
2057) -> Result<Option<ScopedClient>, String> {
2058    if is_primitive_capnp_type(&req_variant.type_name) {
2059        return Ok(None);
2060    }
2061
2062    let inner_struct = match all_structs.iter().find(|s| s.name == req_variant.type_name) {
2063        Some(s) => s,
2064        None => return Ok(None),
2065    };
2066
2067    if !inner_struct.has_union {
2068        return Ok(None);
2069    }
2070
2071    // Nested scoped clients must have at least one non-union scope field.
2072    if require_scope_fields && inner_struct.non_union_fields().next().is_none() {
2073        return Ok(None);
2074    }
2075
2076    let resp_variant_name = format!("{}Result", req_variant.name);
2077    let resp_variant = match response_variants
2078        .iter()
2079        .find(|v| v.name == resp_variant_name)
2080    {
2081        Some(v) => v,
2082        None => return Ok(None),
2083    };
2084
2085    let inner_node_id = match find_struct_node_id(node_map, &req_variant.type_name) {
2086        Some(id) => id,
2087        None => return Ok(None),
2088    };
2089    let inner_node = nodes.get(node_map[&inner_node_id].index);
2090    let inner_req_variants = extract_union_variants(
2091        inner_node,
2092        nodes,
2093        node_map,
2094        mcp_desc_id,
2095        param_desc_id,
2096        mcp_scope_id,
2097        cli_hidden_id,
2098        doc_example_id,
2099    )?;
2100
2101    let resp_node_id = match find_struct_node_id(node_map, &resp_variant.type_name) {
2102        Some(id) => id,
2103        None => return Ok(None),
2104    };
2105    let resp_node = nodes.get(node_map[&resp_node_id].index);
2106    let inner_resp_variants = extract_union_variants(
2107        resp_node,
2108        nodes,
2109        node_map,
2110        mcp_desc_id,
2111        param_desc_id,
2112        mcp_scope_id,
2113        cli_hidden_id,
2114        doc_example_id,
2115    )?;
2116
2117    if inner_req_variants.is_empty() || inner_resp_variants.is_empty() {
2118        return Ok(None);
2119    }
2120
2121    let client_name = if req_variant.type_name.ends_with("Request") {
2122        format!(
2123            "{}Client",
2124            &req_variant.type_name[..req_variant.type_name.len() - 7]
2125        )
2126    } else {
2127        format!("{}Client", req_variant.type_name)
2128    };
2129
2130    // Scope fields = non-union fields from the inner struct
2131    let scope_fields: Vec<FieldDef> = inner_struct.non_union_fields().cloned().collect();
2132
2133    Ok(Some(ScopedClient {
2134        factory_name: req_variant.name.clone(),
2135        client_name,
2136        scope_fields,
2137        inner_request_variants: inner_req_variants,
2138        inner_response_variants: inner_resp_variants,
2139        capnp_inner_response: to_snake_case(&resp_variant.type_name),
2140        nested_clients: Vec::new(),
2141    }))
2142}
2143
2144/// Detect scoped clients from the request/response pattern.
2145#[allow(clippy::too_many_arguments)]
2146fn detect_scoped_clients(
2147    request_variants: &[UnionVariant],
2148    response_variants: &[UnionVariant],
2149    all_structs: &[StructDef],
2150    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
2151    node_map: &BTreeMap<u64, NodeInfo>,
2152    mcp_desc_id: Option<u64>,
2153    param_desc_id: Option<u64>,
2154    mcp_scope_id: Option<u64>,
2155    cli_hidden_id: Option<u64>,
2156    doc_example_id: Option<u64>,
2157) -> Result<Vec<ScopedClient>, String> {
2158    let mut scoped = Vec::new();
2159
2160    for req_variant in request_variants {
2161        if let Some(sc) = build_scoped_client_for_variant(
2162            req_variant,
2163            response_variants,
2164            all_structs,
2165            nodes,
2166            node_map,
2167            mcp_desc_id,
2168            param_desc_id,
2169            mcp_scope_id,
2170            cli_hidden_id,
2171            doc_example_id,
2172            false, // top-level: don't require non-empty scope fields
2173        )? {
2174            scoped.push(sc);
2175        }
2176    }
2177
2178    Ok(scoped)
2179}
2180
2181/// Recursively detect nested scoped clients within a scoped client.
2182#[allow(clippy::too_many_arguments)]
2183fn detect_nested_scoped_clients_cgr(
2184    parent: &mut ScopedClient,
2185    all_structs: &[StructDef],
2186    nodes: &capnp::struct_list::Reader<capnp::schema_capnp::node::Owned>,
2187    node_map: &BTreeMap<u64, NodeInfo>,
2188    mcp_desc_id: Option<u64>,
2189    param_desc_id: Option<u64>,
2190    mcp_scope_id: Option<u64>,
2191    cli_hidden_id: Option<u64>,
2192    doc_example_id: Option<u64>,
2193) -> Result<(), String> {
2194    let mut nested = Vec::new();
2195    let mut nested_factory_names = Vec::new();
2196
2197    for req_variant in &parent.inner_request_variants {
2198        if let Some(sc) = build_scoped_client_for_variant(
2199            req_variant,
2200            &parent.inner_response_variants,
2201            all_structs,
2202            nodes,
2203            node_map,
2204            mcp_desc_id,
2205            param_desc_id,
2206            mcp_scope_id,
2207            cli_hidden_id,
2208            doc_example_id,
2209            true, // nested: require at least one non-union scope field
2210        )? {
2211            nested_factory_names.push(req_variant.name.clone());
2212            nested.push(sc);
2213        }
2214    }
2215
2216    // Filter out nested-scope variants from parent's inner variants
2217    if !nested_factory_names.is_empty() {
2218        parent
2219            .inner_request_variants
2220            .retain(|v| !nested_factory_names.contains(&v.name));
2221        parent.inner_response_variants.retain(|v| {
2222            let result_name = v.name.strip_suffix("Result").unwrap_or(&v.name);
2223            !nested_factory_names.contains(&result_name.to_owned())
2224        });
2225    }
2226
2227    parent.nested_clients = nested;
2228
2229    // Recurse into newly detected nested clients for deeper nesting
2230    for nested_client in &mut parent.nested_clients {
2231        detect_nested_scoped_clients_cgr(
2232            nested_client,
2233            all_structs,
2234            nodes,
2235            node_map,
2236            mcp_desc_id,
2237            param_desc_id,
2238            mcp_scope_id,
2239            cli_hidden_id,
2240            doc_example_id,
2241        )?;
2242    }
2243
2244    Ok(())
2245}
2246
2247/// Check if a type name is a primitive (not a struct reference).
2248///
2249/// Delegates to `is_primitive_capnp_type` in `schema::types` — the canonical
2250/// implementation. Kept for backward compatibility with existing callers.
2251pub fn is_primitive_type(type_name: &str) -> bool {
2252    is_primitive_capnp_type(type_name)
2253}
2254
2255#[cfg(test)]
2256#[allow(clippy::unwrap_used)]
2257mod mandatory_scope_tests {
2258    use super::*;
2259
2260    fn variant(name: &str, scope: &str, exempt: bool) -> UnionVariant {
2261        UnionVariant {
2262            name: name.to_owned(),
2263            type_name: "Void".to_owned(),
2264            description: String::new(),
2265            scope: scope.to_owned(),
2266            scope_exempt: exempt,
2267            cli_hidden: false,
2268            doc_example: String::new(),
2269            vfs_path: String::new(),
2270            vfs_kind: String::new(),
2271            vfs_bulk: false,
2272            vfs_hidden: false,
2273            vfs_mac: String::new(),
2274            dispatch_mac: String::new(),
2275            dispatch_public: String::new(),
2276            mutation_semantics: String::new(),
2277            dispatch_mac_present: false,
2278            dispatch_public_present: false,
2279            mutation_semantics_present: false,
2280        }
2281    }
2282
2283    fn scoped(factory: &str, inner: Vec<UnionVariant>, nested: Vec<ScopedClient>) -> ScopedClient {
2284        ScopedClient {
2285            factory_name: factory.to_owned(),
2286            client_name: format!("{factory}Client"),
2287            scope_fields: vec![],
2288            inner_request_variants: inner,
2289            inner_response_variants: vec![],
2290            capnp_inner_response: String::new(),
2291            nested_clients: nested,
2292        }
2293    }
2294
2295    #[test]
2296    fn scoped_method_passes() {
2297        let reqs = vec![
2298            variant("load", "write", false),
2299            variant("status", "query", false),
2300        ];
2301        assert!(validate_mandatory_scope("model", &reqs, &[]).is_ok());
2302    }
2303
2304    #[test]
2305    fn unscoped_leaf_is_build_error() {
2306        let reqs = vec![variant("load", "write", false), variant("oops", "", false)];
2307        let err = validate_mandatory_scope("model", &reqs, &[]).unwrap_err();
2308        assert!(err.contains("oops"), "{err}");
2309        assert!(err.contains("mandatory"), "{err}");
2310    }
2311
2312    #[test]
2313    fn scope_exempt_satisfies_requirement() {
2314        let reqs = vec![variant("check", "", true)];
2315        assert!(validate_mandatory_scope("policy", &reqs, &[]).is_ok());
2316    }
2317
2318    #[test]
2319    fn dispatcher_variant_is_exempt_but_its_leaves_are_checked() {
2320        // Top-level `ttt` is a dispatcher (matches scoped_clients factory_name) and
2321        // carries no scope — that's fine. Its leaves must each carry a scope.
2322        let reqs = vec![variant("ttt", "", false)];
2323        let good = scoped("ttt", vec![variant("train", "train", false)], vec![]);
2324        assert!(validate_mandatory_scope("model", &reqs, &[good]).is_ok());
2325
2326        let bad = scoped("ttt", vec![variant("train", "", false)], vec![]);
2327        let err = validate_mandatory_scope("model", &reqs, &[bad]).unwrap_err();
2328        assert!(err.contains("ttt train"), "{err}");
2329    }
2330
2331    #[test]
2332    fn nested_dispatcher_leaves_are_checked() {
2333        // worktree -> ctl (nested dispatcher); ctl's leaf must carry a scope.
2334        let reqs = vec![variant("worktree", "", false)];
2335        let ctl_bad = scoped("ctl", vec![variant("log", "", false)], vec![]);
2336        let worktree = scoped(
2337            "worktree",
2338            vec![variant("read", "query", false), variant("ctl", "", false)],
2339            vec![ctl_bad],
2340        );
2341        let err = validate_mandatory_scope("registry", &reqs, &[worktree]).unwrap_err();
2342        assert!(err.contains("log"), "{err}");
2343    }
2344}
2345
2346#[cfg(test)]
2347#[allow(clippy::unwrap_used, clippy::expect_used)]
2348mod mandatory_dispatch_tests {
2349    use super::*;
2350
2351    /// `scope`/`exempt` feed the cross-plane rule (`$dispatchPublic` must not
2352    /// carry a scope); `mac`/`public` are the dispatch pair under test.
2353    fn variant(name: &str, scope: &str, mac: &str, public: &str) -> UnionVariant {
2354        UnionVariant {
2355            name: name.to_owned(),
2356            type_name: "Void".to_owned(),
2357            description: String::new(),
2358            scope: scope.to_owned(),
2359            scope_exempt: false,
2360            cli_hidden: false,
2361            doc_example: String::new(),
2362            vfs_path: String::new(),
2363            vfs_kind: String::new(),
2364            vfs_bulk: false,
2365            vfs_hidden: false,
2366            vfs_mac: String::new(),
2367            dispatch_mac: mac.to_owned(),
2368            dispatch_public: public.to_owned(),
2369            mutation_semantics: String::new(),
2370            dispatch_mac_present: !mac.is_empty(),
2371            dispatch_public_present: !public.is_empty(),
2372            mutation_semantics_present: false,
2373        }
2374    }
2375
2376    fn scoped(factory: &str, inner: Vec<UnionVariant>, nested: Vec<ScopedClient>) -> ScopedClient {
2377        ScopedClient {
2378            factory_name: factory.to_owned(),
2379            client_name: format!("{factory}Client"),
2380            scope_fields: vec![],
2381            inner_request_variants: inner,
2382            inner_response_variants: vec![],
2383            capnp_inner_response: String::new(),
2384            nested_clients: nested,
2385        }
2386    }
2387
2388    const MAC: &str = "internal:pq-hybrid";
2389
2390    #[test]
2391    fn a_fully_annotated_leaf_set_passes() {
2392        let reqs = vec![
2393            variant("load", "write", MAC, ""),
2394            variant("status", "query", MAC, ""),
2395            variant(
2396                "check",
2397                "",
2398                "",
2399                "the authz check itself cannot require authz",
2400            ),
2401        ];
2402        assert!(validate_mandatory_dispatch("model", &reqs, &[]).is_ok());
2403    }
2404
2405    #[test]
2406    fn an_unannotated_leaf_is_a_build_error() {
2407        let reqs = vec![
2408            variant("load", "write", MAC, ""),
2409            variant("oops", "query", "", ""),
2410        ];
2411        let err = validate_mandatory_dispatch("model", &reqs, &[]).unwrap_err();
2412        assert!(err.contains("oops"), "{err}");
2413        assert!(err.contains("neither"), "{err}");
2414    }
2415
2416    #[test]
2417    fn both_annotations_on_one_leaf_is_a_build_error() {
2418        let reqs = vec![variant("x", "query", MAC, "reason")];
2419        let err = validate_mandatory_dispatch("model", &reqs, &[]).unwrap_err();
2420        assert!(err.contains("BOTH"), "{err}");
2421    }
2422
2423    #[test]
2424    fn a_scoped_dispatcher_carries_neither_and_its_leaves_are_checked() {
2425        let reqs = vec![variant("ttt", "", "", "")];
2426        let good = scoped("ttt", vec![variant("train", "train", MAC, "")], vec![]);
2427        assert!(validate_mandatory_dispatch("model", &reqs, &[good]).is_ok());
2428
2429        // An annotated dispatcher is itself a build error, even with good leaves.
2430        let annotated_dispatcher = vec![variant("ttt", "", MAC, "")];
2431        let leaves = scoped("ttt", vec![variant("train", "train", MAC, "")], vec![]);
2432        let err =
2433            validate_mandatory_dispatch("model", &annotated_dispatcher, &[leaves]).unwrap_err();
2434        assert!(err.contains("dispatcher"), "{err}");
2435
2436        // And the unannotated deep leaf still fails.
2437        let bad = scoped("ttt", vec![variant("train", "train", "", "")], vec![]);
2438        let err = validate_mandatory_dispatch("model", &reqs, &[bad]).unwrap_err();
2439        assert!(err.contains("ttt train"), "{err}");
2440    }
2441
2442    #[test]
2443    fn public_never_coexists_with_a_scope_action() {
2444        let reqs = vec![variant("p", "query", "", "genuinely public")];
2445        let err = validate_mandatory_dispatch("model", &reqs, &[]).unwrap_err();
2446        assert!(err.contains("cannot be dispatch-public"), "{err}");
2447    }
2448
2449    #[test]
2450    fn an_empty_public_reason_is_a_build_error() {
2451        let reqs = vec![variant("p", "", "", "   ")];
2452        let err = validate_mandatory_dispatch("model", &reqs, &[]).unwrap_err();
2453        assert!(err.contains("reason"), "{err}");
2454    }
2455}
2456
2457#[cfg(test)]
2458#[allow(clippy::unwrap_used)]
2459mod mandatory_mutation_policy_tests {
2460    use super::*;
2461
2462    fn variant(name: &str, scope: &str, semantics: &str) -> UnionVariant {
2463        UnionVariant {
2464            name: name.to_owned(),
2465            type_name: "Void".to_owned(),
2466            description: String::new(),
2467            scope: scope.to_owned(),
2468            scope_exempt: false,
2469            cli_hidden: false,
2470            doc_example: String::new(),
2471            vfs_path: String::new(),
2472            vfs_kind: String::new(),
2473            vfs_bulk: false,
2474            vfs_hidden: false,
2475            vfs_mac: String::new(),
2476            dispatch_mac: "internal:pq-hybrid".to_owned(),
2477            dispatch_public: String::new(),
2478            mutation_semantics: semantics.to_owned(),
2479            dispatch_mac_present: true,
2480            dispatch_public_present: false,
2481            mutation_semantics_present: !semantics.is_empty(),
2482        }
2483    }
2484
2485    #[test]
2486    fn mutating_leaves_require_checked_explicit_policy() {
2487        let missing = variant("sendInput", "write", "");
2488        let err = validate_mandatory_mutation_policy("tui", &[missing], &[]).unwrap_err();
2489        assert!(err.contains("missing required"), "{err}");
2490
2491        let unsupported = variant("sendInput", "write", "automatic");
2492        let err = validate_mandatory_mutation_policy("tui", &[unsupported], &[]).unwrap_err();
2493        assert!(err.contains("unknown"), "{err}");
2494
2495        for semantics in [
2496            "naturally-idempotent",
2497            "idempotency-key-required",
2498            "transaction-ledger-required",
2499        ] {
2500            validate_mandatory_mutation_policy(
2501                "tui",
2502                &[variant("method", "write", semantics)],
2503                &[],
2504            )
2505            .unwrap_or_else(|err| panic!("{semantics}: {err}"));
2506        }
2507    }
2508
2509    #[test]
2510    fn scope_exempt_mutator_can_declare_policy() {
2511        let mut exempt = variant("registerServiceKey", "", "naturally-idempotent");
2512        exempt.scope_exempt = true;
2513        validate_mandatory_mutation_policy("policy", &[exempt], &[]).unwrap();
2514    }
2515
2516    #[test]
2517    fn stateful_read_leaves_can_declare_checked_policy() {
2518        let read = variant("walk", "query", "idempotency-key-required");
2519        validate_mandatory_mutation_policy("registry", &[read], &[]).unwrap();
2520
2521        let plain_read = variant("list", "query", "");
2522        validate_mandatory_mutation_policy("registry", &[plain_read], &[]).unwrap();
2523    }
2524
2525    // ── Bot finding 4136451007: $maxLen(0) contract enforcement ────────────
2526    //
2527    // annotations.capnp: "0 is invalid; the build fails if a schema sets
2528    // maxLen(0)". The validation must name the offending FIELD and must not
2529    // touch fixedSize(0) semantics (validated elsewhere).
2530
2531    #[test]
2532    fn maxlen_zero_is_rejected_with_field_named_schema_error() {
2533        let error = match validate_max_len("policyText", Some(0)) {
2534            Err(error) => error,
2535            Ok(()) => panic!("maxLen(0) violates the schema contract"),
2536        };
2537        assert!(
2538            error.contains("field 'policyText'"),
2539            "field-named: {error:#}"
2540        );
2541        assert!(error.contains(MAXLEN_ZERO_CONTRACT_ERROR), "{error:#}");
2542        assert!(error.contains("at least 1"), "{error:#}");
2543    }
2544
2545    #[test]
2546    fn maxlen_positive_and_absent_are_valid() {
2547        assert!(
2548            validate_max_len("policyText", Some(1)).is_ok(),
2549            "lower bound"
2550        );
2551        assert!(validate_max_len("policyText", Some(u32::MAX)).is_ok());
2552        assert!(
2553            validate_max_len("policyText", None).is_ok(),
2554            "annotation absent"
2555        );
2556    }
2557
2558    #[test]
2559    fn maxlen_validation_is_scoped_to_max_len_only() {
2560        // The helper receives ONLY the maxLen value: a fixedSize(0) field with
2561        // a valid (or absent) maxLen is untouched by this validation.
2562        assert!(validate_max_len("fixedSizeZeroField", None).is_ok());
2563        assert!(validate_max_len("fixedSizeZeroField", Some(64)).is_ok());
2564    }
2565}