Skip to main content

hyprstream_rpc_derive/codegen/
vfs.rs

1//! VFS/9P projection generation (epic #539, T2).
2//!
3//! Emits a `vfs_nodes() -> (&str, &[VfsNode])` table per service — the 4th
4//! codegen projection alongside client/handler/dispatch/metadata. Each node is
5//! derived from a method's [`UnionVariant`] (the SAME data the MCP/metadata
6//! surface reads) plus the `$vfs*` annotations captured in T1.
7//!
8//! The runtime mount engine (T3) consumes the table to serve `/srv/{service}`.
9//! This module only emits the table + the read/write-vs-scope guard; it wires
10//! no behavior.
11//!
12//! ## Mapping rules (method shape → node kind; `$vfsKind` overrides)
13//!
14//! | shape                          | default kind |
15//! |--------------------------------|--------------|
16//! | query, Void, name "list*"      | `Dir`        |
17//! | query, Text/scalar arg         | `File` @ `{arg}` |
18//! | query, Void                    | `File`       |
19//! | query, struct (rich args)      | `Query`      |
20//! | write / manage                 | `Ctl`        |
21//! | streaming (any)                | `Stream`     |
22//!
23//! ## Guard (compile-time)
24//!
25//! A read-only kind (`File`/`Dir`/`Query`) on a write/manage scope, or a `Ctl`
26//! on a query scope, is a contradiction — a 9P read must be side-effect-free.
27//! [`validate_node`] returns the error; [`generate_mount`] turns it into a
28//! `compile_error!`.
29
30use proc_macro2::TokenStream;
31use quote::quote;
32
33use crate::resolve::ResolvedSchema;
34use crate::schema::types::UnionVariant;
35use crate::util::{to_snake_case, CapnpType};
36
37/// The VFS node kind, mirrored from the runtime `hyprstream_rpc::metadata::VfsNodeKind`.
38/// Kept as a plain derive-crate enum so inference/guard logic is unit-testable
39/// without depending on the runtime crate.
40#[derive(Copy, Clone, Debug, PartialEq, Eq)]
41pub enum NodeKind {
42    File,
43    Dir,
44    Ctl,
45    Stream,
46    Query,
47}
48
49impl NodeKind {
50    /// Parse the `$vfsKind` enumerant name (as captured in `UnionVariant::vfs_kind`).
51    fn parse(s: &str) -> Option<Self> {
52        match s {
53            "file" => Some(Self::File),
54            "dir" => Some(Self::Dir),
55            "ctl" => Some(Self::Ctl),
56            "stream" => Some(Self::Stream),
57            "query" => Some(Self::Query),
58            _ => None,
59        }
60    }
61
62    /// A read of this node must be side-effect-free (9P read invariant).
63    fn is_read_only(self) -> bool {
64        matches!(self, Self::File | Self::Dir | Self::Query)
65    }
66
67    /// The runtime-crate variant tokens for this kind.
68    fn to_tokens(self) -> TokenStream {
69        match self {
70            Self::File => quote! { hyprstream_rpc::metadata::VfsNodeKind::File },
71            Self::Dir => quote! { hyprstream_rpc::metadata::VfsNodeKind::Dir },
72            Self::Ctl => quote! { hyprstream_rpc::metadata::VfsNodeKind::Ctl },
73            Self::Stream => quote! { hyprstream_rpc::metadata::VfsNodeKind::Stream },
74            Self::Query => quote! { hyprstream_rpc::metadata::VfsNodeKind::Query },
75        }
76    }
77}
78
79/// Whether the method's scope action denotes write/authority vs the schema's
80/// read class (`query`/`subscribe`).
81///
82/// Scopes come from `$scope`/`$capability` (S3, #547). A `query` (or read-shaped)
83/// scope must project to a read-only node; anything else is treated as authority.
84/// Empty scope (a `$scopeExempt` method) is treated as read (least authority).
85fn scope_is_write_class(scope: &str) -> bool {
86    !matches!(scope, "" | "query" | "subscribe")
87}
88
89/// Whether a method name denotes a listing (projects to a directory by default).
90fn is_list_name(name: &str) -> bool {
91    let snake = to_snake_case(name);
92    snake == "list" || snake.starts_with("list_")
93}
94
95/// Infer the default node kind from a method's scope + argument shape + streaming.
96///
97/// `$vfsKind` (when present) overrides this — see [`resolve_kind`].
98pub fn infer_kind(scope: &str, arg: &CapnpType, name: &str, is_streaming: bool) -> NodeKind {
99    if is_streaming {
100        return NodeKind::Stream;
101    }
102    if scope_is_write_class(scope) {
103        return NodeKind::Ctl;
104    }
105    // Read-shaped (query/exempt): pick by argument shape.
106    match arg {
107        // A `list*` method with no args reads as a directory.
108        CapnpType::Void if is_list_name(name) => NodeKind::Dir,
109        // A struct / rich args → a synthetic query file (write spec, read result).
110        // Void and single-scalar args both read as a file (the `{arg}` binding is
111        // decided from arg shape in `infer_path`, not the kind).
112        arg if is_query_file_arg(arg) => NodeKind::Query,
113        _ => NodeKind::File,
114    }
115}
116
117/// Whether a read-shaped method's argument is "rich" (a struct/list needing a
118/// written query spec) rather than Void or a single bindable scalar.
119fn is_query_file_arg(arg: &CapnpType) -> bool {
120    matches!(
121        arg,
122        CapnpType::Struct(_)
123            | CapnpType::Unknown(_)
124            | CapnpType::ListText
125            | CapnpType::ListData
126            | CapnpType::ListPrimitive(_)
127            | CapnpType::ListStruct(_)
128            | CapnpType::Data
129    )
130}
131
132/// Resolve the effective node kind: `$vfsKind` override, else inference.
133///
134/// Returns an `Err(message)` if `$vfsKind` names an unknown enumerant.
135pub fn resolve_kind(
136    v: &UnionVariant,
137    arg: &CapnpType,
138    is_streaming: bool,
139) -> Result<NodeKind, String> {
140    if v.vfs_kind.is_empty() {
141        Ok(infer_kind(&v.scope, arg, &v.name, is_streaming))
142    } else {
143        NodeKind::parse(&v.vfs_kind).ok_or_else(|| {
144            format!(
145                "method `{}`: `$vfsKind(\"{}\")` is not a valid VFS node kind \
146                 (expected one of file/dir/ctl/stream/query)",
147                to_snake_case(&v.name),
148                v.vfs_kind
149            )
150        })
151    }
152}
153
154/// The compile-time guard: a node's kind must not contradict its scope.
155///
156/// - A write/manage scope must NOT project to a read-only node
157///   (`file`/`dir`/`query`) — a mutation behind a side-effect-free 9P read.
158/// - A query/read scope must NOT project to a `ctl` — a read that invokes a verb.
159///
160/// Returns `Err(message)` on contradiction, naming the offending method.
161pub fn validate_node(method_snake: &str, scope: &str, kind: NodeKind) -> Result<(), String> {
162    let write_class = scope_is_write_class(scope);
163    if write_class && kind.is_read_only() {
164        return Err(format!(
165            "method `{method_snake}`: write/authority-class scope `{scope}` cannot project to a \
166             read-only VFS node (`{kind:?}`) — a 9P read must be side-effect-free; \
167             use `$vfsKind(ctl)` or `$vfsKind(stream)`"
168        ));
169    }
170    if !write_class && matches!(kind, NodeKind::Ctl) {
171        return Err(format!(
172            "method `{method_snake}`: read-class scope `{scope}` cannot project to a `ctl` node \
173             — a control-file write invokes the method; use a read kind \
174             (`$vfsKind(file|dir|query)`) or give the method a write scope"
175        ));
176    }
177    Ok(())
178}
179
180/// Infer the default mount-relative path for a node when `$vfsPath` is unset.
181///
182/// `dir_is_sole_listing` distinguishes the common single-listing case (the
183/// listing IS the directory root, path `.`) from a struct with several `Dir`
184/// listings (e.g. registry's `repo/{repoId}` scope: `listBranches`/`listTags`/
185/// `listRemotes`/`listWorktrees` are all `query`+`Void` `list*` methods). In
186/// the latter case `.` would silently collide across every listing, so each
187/// gets a name-derived path instead: strip a leading `list_` from the method's
188/// snake-case name if present, else use the name as-is.
189fn infer_path(
190    kind: NodeKind,
191    method_snake: &str,
192    arg: &CapnpType,
193    dir_is_sole_listing: bool,
194) -> String {
195    match kind {
196        // The lone directory listing in this scope is the mount root by
197        // convention. When there's more than one, each needs its own name so
198        // they don't all collide at ".".
199        NodeKind::Dir if dir_is_sole_listing => ".".to_owned(),
200        NodeKind::Dir => method_snake
201            .strip_prefix("list_")
202            .unwrap_or(method_snake)
203            .to_owned(),
204        // A scalar-arg file binds the arg from the path segment.
205        NodeKind::File if !matches!(arg, CapnpType::Void) => "{arg}".to_owned(),
206        // A control file lands at the conventional `ctl` node.
207        NodeKind::Ctl => "ctl".to_owned(),
208        // Everything else (a Void read file like `health`, a stream, or a query
209        // file) is served under the method's own name.
210        NodeKind::Stream | NodeKind::Query | NodeKind::File => method_snake.to_owned(),
211    }
212}
213
214/// Build the `VfsNode` entry token stream for one set of request variants.
215///
216/// Shared by the top-level table and each scoped-client subdir table. Returns
217/// `Err(compile_error_tokens)` on a bad `$vfsKind`, a scope/kind contradiction,
218/// or two methods landing on the same path.
219///
220/// Two passes: the first resolves each method's kind (needed to count how
221/// many un-annotated `Dir` listings this scope has, which decides whether the
222/// lone-listing "." default applies — see [`infer_path`]); the second
223/// resolves paths with that count in hand, then builds the entries and checks
224/// for any same-path collision across the whole scope.
225fn build_node_entries(
226    variants: &[UnionVariant],
227    scoped_names: &[&str],
228    response_variants: &[UnionVariant],
229    resolved: &ResolvedSchema,
230) -> Result<Vec<TokenStream>, TokenStream> {
231    struct Resolved<'a> {
232        variant: &'a UnionVariant,
233        method_snake: String,
234        arg: CapnpType,
235        kind: NodeKind,
236    }
237
238    let mut resolved_variants: Vec<Resolved> = Vec::new();
239    for v in variants {
240        // Scoped clients project as subdirectories with their own tables; skip
241        // them in the flat node list. `$vfsHidden` excludes a method entirely.
242        if scoped_names.contains(&v.name.as_str()) || v.vfs_hidden {
243            continue;
244        }
245
246        let method_snake = to_snake_case(&v.name);
247        let arg = resolved.resolve_type(&v.type_name).capnp_type.clone();
248        let is_streaming = is_streaming_variant(&v.name, response_variants);
249
250        // Resolve kind ($vfsKind override or inference) — bad annotation ⇒ compile_error.
251        let kind = resolve_kind(v, &arg, is_streaming).map_err(|msg| compile_error(&msg))?;
252
253        // The guard: kind must not contradict scope.
254        if let Err(msg) = validate_node(&method_snake, &v.scope, kind) {
255            return Err(compile_error(&msg));
256        }
257
258        resolved_variants.push(Resolved {
259            variant: v,
260            method_snake,
261            arg,
262            kind,
263        });
264    }
265
266    // How many un-annotated methods in this scope infer to `Dir` — decides
267    // whether the sole one gets "." or each gets a name-derived path.
268    let unannotated_dir_count = resolved_variants
269        .iter()
270        .filter(|r| r.kind == NodeKind::Dir && r.variant.vfs_path.is_empty())
271        .count();
272    let dir_is_sole_listing = unannotated_dir_count <= 1;
273
274    let mut node_entries: Vec<TokenStream> = Vec::new();
275    // (path, method_snake) — `Ctl` entries are intentionally excluded: several
276    // write/manage methods sharing one `ctl` file, dispatched by the verb text
277    // written to it, is the designed multiplexing convention (see the module
278    // doc's mapping table), not a collision.
279    let mut seen_paths: Vec<(String, String)> = Vec::new();
280
281    for r in &resolved_variants {
282        let v = r.variant;
283        let path = if v.vfs_path.is_empty() {
284            infer_path(r.kind, &r.method_snake, &r.arg, dir_is_sole_listing)
285        } else {
286            v.vfs_path.clone()
287        };
288
289        // The guard: two non-`Ctl` methods must not project to the same path
290        // — a 9P read node can only be served by one method. Fires regardless
291        // of whether the collision came from inference or explicit `$vfsPath`.
292        if r.kind != NodeKind::Ctl {
293            if let Some((_, other)) = seen_paths.iter().find(|(p, _)| *p == path) {
294                return Err(compile_error(&format!(
295                    "method `{}` and method `{other}` both project to VFS path `{path}` — set an explicit `$vfsPath` on at least one to disambiguate",
296                    r.method_snake
297                )));
298            }
299            seen_paths.push((path.clone(), r.method_snake.clone()));
300        }
301
302        let kind_tokens = r.kind.to_tokens();
303        let method_snake = r.method_snake.as_str();
304        let scope = v.scope.as_str();
305        let bulk = v.vfs_bulk;
306        // $vfsMac (#699 carrier (a)): schema-derived MAC label for this generated
307        // node. Empty string when the annotation is absent (→ unlabeled → deny →
308        // a genesis finding); decoded at runtime by `VfsNode::mac_label`.
309        let mac = v.vfs_mac.as_str();
310
311        node_entries.push(quote! {
312            hyprstream_rpc::metadata::VfsNode {
313                method: #method_snake,
314                path: #path,
315                kind: #kind_tokens,
316                scope: #scope,
317                bulk: #bulk,
318                mac: #mac,
319            }
320        });
321    }
322
323    Ok(node_entries)
324}
325
326/// Generate the per-service `vfs_nodes()` table (plus a `vfs_nodes_<scoped>()`
327/// subdir table for each nested scoped client).
328///
329/// Emits `pub fn vfs_nodes() -> (&'static str, &'static [VfsNode])`. On a
330/// scope/kind contradiction (or bad `$vfsKind`), emits a `compile_error!`
331/// naming the offending method instead. Each scoped client (e.g. `repo`,
332/// which projects as the `repo/{repoId}/` subdir) gets its own
333/// `vfs_nodes_<factory>()` table over its inner variants — mount-relative to
334/// that subdir root — so the projection is recursive, not flat.
335pub fn generate_mount(service_name: &str, resolved: &ResolvedSchema) -> TokenStream {
336    // Data-only schemas (no request variants) get no mount.
337    if resolved.raw.request_variants.is_empty() {
338        return TokenStream::new();
339    }
340
341    let scoped_names: Vec<&str> = resolved
342        .raw
343        .scoped_clients
344        .iter()
345        .map(|sc| sc.factory_name.as_str())
346        .collect();
347
348    let node_entries = match build_node_entries(
349        &resolved.raw.request_variants,
350        &scoped_names,
351        &resolved.raw.response_variants,
352        resolved,
353    ) {
354        Ok(entries) => entries,
355        Err(err) => return err,
356    };
357
358    // One subdir table per scoped client. A scoped client's inner variants are
359    // themselves the leaves of its `{prefix}/` subdir; nested scoped clients
360    // within it recurse the same way (their own `vfs_nodes_<name>()`). The
361    // subdir's mount-relative prefix is the parent variant's `$vfsPath` (e.g.
362    // `repo/{repoId}`) — inferred to the factory name when unannotated.
363    let mut scoped_tables: Vec<TokenStream> = Vec::new();
364    for sc in &resolved.raw.scoped_clients {
365        let inner_scoped: Vec<&str> = sc
366            .nested_clients
367            .iter()
368            .map(|n| n.factory_name.as_str())
369            .collect();
370        let inner_entries = match build_node_entries(
371            &sc.inner_request_variants,
372            &inner_scoped,
373            &sc.inner_response_variants,
374            resolved,
375        ) {
376            Ok(entries) => entries,
377            Err(err) => return err,
378        };
379        // The subdir prefix lives on the parent variant that projects this
380        // scope (the `$vfsPath` on e.g. the `repo` union field).
381        let prefix = resolved
382            .raw
383            .request_variants
384            .iter()
385            .find(|v| v.name == sc.factory_name)
386            .filter(|v| !v.vfs_path.is_empty())
387            .map(|v| v.vfs_path.clone())
388            .unwrap_or_else(|| to_snake_case(&sc.factory_name));
389        let fn_ident = quote::format_ident!("vfs_nodes_{}", to_snake_case(&sc.factory_name));
390        let sub_doc = format!(
391            "Generated 9P/VFS subdir node table for the `{}` scope of the {service_name} service (epic #539). Mount-relative prefix returned alongside the nodes.",
392            sc.factory_name
393        );
394        scoped_tables.push(quote! {
395            #[doc = #sub_doc]
396            pub fn #fn_ident() -> (&'static str, &'static [hyprstream_rpc::metadata::VfsNode]) {
397                static NODES: &[hyprstream_rpc::metadata::VfsNode] = &[
398                    #(#inner_entries,)*
399                ];
400                (#prefix, NODES)
401            }
402        });
403    }
404
405    let doc = format!("Generated 9P/VFS node table for the {service_name} service (epic #539).");
406
407    quote! {
408        #[doc = #doc]
409        pub fn vfs_nodes() -> (&'static str, &'static [hyprstream_rpc::metadata::VfsNode]) {
410            static NODES: &[hyprstream_rpc::metadata::VfsNode] = &[
411                #(#node_entries,)*
412            ];
413            (#service_name, NODES)
414        }
415
416        // #699 carrier (a) inventory: register this table so the genesis
417        // coverage gate can walk every reachable generated node (annotated or
418        // not) at startup. Submitted at module scope via the `inventory`
419        // re-export on `hyprstream_rpc::metadata` (same pattern as
420        // `ScopeDefinition`), so consumer crates need not declare an `inventory`
421        // dep directly. The gate iterates this to build the startup activation
422        // gate; a node missing a `$vfsMac` surfaces as a finding (unlabeled ⇒
423        // deny) rather than being silently absent.
424        //
425        // Native-only (#1305): inventory's linker-section registration does not
426        // resolve on wasm32, so the submit is gated off there. The generated
427        // `vfs_nodes()` fn above stays available on all targets — it is the
428        // wasm-compatible path for any browser client that needs the table.
429        #[cfg(not(target_arch = "wasm32"))]
430        hyprstream_rpc::metadata::inventory::submit! {
431            hyprstream_rpc::metadata::VfsNodeTable {
432                name: #service_name,
433                nodes_fn: vfs_nodes,
434            }
435        }
436
437        #(#scoped_tables)*
438    }
439}
440
441/// Emit a `compile_error!` carrying `msg`.
442fn compile_error(msg: &str) -> TokenStream {
443    quote! { ::core::compile_error!(#msg); }
444}
445
446/// Whether a request variant's response is a `StreamInfo` (a streaming method).
447/// Mirrors `metadata::is_streaming_variant` for the non-scoped case.
448fn is_streaming_variant(variant_name: &str, response_variants: &[UnionVariant]) -> bool {
449    let expected = format!("{variant_name}Result");
450    response_variants
451        .iter()
452        .find(|v| v.name == expected)
453        .map(|v| v.type_name == "StreamInfo")
454        .unwrap_or(false)
455}
456
457#[cfg(test)]
458#[allow(clippy::expect_used, clippy::unwrap_used)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn infers_dir_for_void_list_query() {
464        let k = infer_kind("query", &CapnpType::Void, "list", false);
465        assert_eq!(k, NodeKind::Dir);
466    }
467
468    #[test]
469    fn infers_file_for_void_query() {
470        let k = infer_kind("query", &CapnpType::Void, "healthCheck", false);
471        assert_eq!(k, NodeKind::File);
472    }
473
474    #[test]
475    fn infers_parameterized_file_for_text_query() {
476        let k = infer_kind("query", &CapnpType::Text, "getByName", false);
477        assert_eq!(k, NodeKind::File);
478        assert_eq!(
479            infer_path(k, "get_by_name", &CapnpType::Text, true),
480            "{arg}"
481        );
482    }
483
484    #[test]
485    fn infers_query_for_struct_query() {
486        let k = infer_kind(
487            "query",
488            &CapnpType::Struct("SearchRequest".into()),
489            "search",
490            false,
491        );
492        assert_eq!(k, NodeKind::Query);
493    }
494
495    #[test]
496    fn infers_ctl_for_write() {
497        let k = infer_kind(
498            "write",
499            &CapnpType::Struct("CloneRequest".into()),
500            "clone",
501            false,
502        );
503        assert_eq!(k, NodeKind::Ctl);
504        assert_eq!(
505            infer_path(k, "clone", &CapnpType::Struct("CloneRequest".into()), true),
506            "ctl"
507        );
508    }
509
510    #[test]
511    fn infers_stream_for_streaming() {
512        let k = infer_kind(
513            "write",
514            &CapnpType::Struct("CloneRequest".into()),
515            "cloneStream",
516            true,
517        );
518        assert_eq!(k, NodeKind::Stream);
519    }
520
521    #[test]
522    fn guard_rejects_write_scope_on_read_only_node() {
523        // A write method forced to a read-only `file` must be rejected.
524        let err = validate_node("clone", "write", NodeKind::File).unwrap_err();
525        assert!(err.contains("clone"), "error names the method: {err}");
526        assert!(
527            err.contains("side-effect-free"),
528            "error explains why: {err}"
529        );
530    }
531
532    #[test]
533    fn guard_rejects_query_scope_on_ctl_node() {
534        let err = validate_node("get_by_name", "query", NodeKind::Ctl).unwrap_err();
535        assert!(err.contains("get_by_name"));
536        assert!(err.contains("ctl"));
537    }
538
539    #[test]
540    fn guard_permits_consistent_pairings() {
541        assert!(validate_node("clone", "write", NodeKind::Ctl).is_ok());
542        assert!(validate_node("list", "query", NodeKind::Dir).is_ok());
543        assert!(validate_node("get", "query", NodeKind::File).is_ok());
544        assert!(validate_node("search", "query", NodeKind::Query).is_ok());
545        assert!(validate_node("watch", "subscribe", NodeKind::Stream).is_ok());
546        assert!(validate_node("snapshot", "subscribe", NodeKind::File).is_ok());
547        assert!(validate_node("watch", "subscribe", NodeKind::Ctl).is_err());
548        // A scope-exempt method (empty scope) is treated as read — ctl still rejected.
549        assert!(validate_node("ping", "", NodeKind::File).is_ok());
550        assert!(validate_node("ping", "", NodeKind::Ctl).is_err());
551    }
552
553    #[test]
554    fn bad_vfs_kind_annotation_is_reported() {
555        let v = UnionVariant {
556            name: "clone".into(),
557            type_name: "CloneRequest".into(),
558            description: String::new(),
559            scope: "write".into(),
560            scope_exempt: false,
561            cli_hidden: false,
562            doc_example: String::new(),
563            vfs_path: String::new(),
564            vfs_kind: "bogus".into(),
565            vfs_bulk: false,
566            vfs_hidden: false,
567            vfs_mac: String::new(),
568            dispatch_mac: String::new(),
569            dispatch_public: String::new(),
570            mutation_semantics: String::new(),
571            dispatch_mac_present: false,
572            dispatch_public_present: false,
573            mutation_semantics_present: false,
574        };
575        let err = resolve_kind(&v, &CapnpType::Struct("CloneRequest".into()), false).unwrap_err();
576        assert!(err.contains("bogus"));
577        assert!(err.contains("clone"));
578    }
579
580    #[test]
581    fn vfs_kind_override_wins_over_inference() {
582        // A query method explicitly annotated as a query file (rich-args override).
583        let v = UnionVariant {
584            name: "getByName".into(),
585            type_name: "Text".into(),
586            description: String::new(),
587            scope: "query".into(),
588            scope_exempt: false,
589            cli_hidden: false,
590            doc_example: String::new(),
591            vfs_path: String::new(),
592            vfs_kind: "query".into(),
593            vfs_bulk: false,
594            vfs_hidden: false,
595            vfs_mac: String::new(),
596            dispatch_mac: String::new(),
597            dispatch_public: String::new(),
598            mutation_semantics: String::new(),
599            dispatch_mac_present: false,
600            dispatch_public_present: false,
601            mutation_semantics_present: false,
602        };
603        let k = resolve_kind(&v, &CapnpType::Text, false).expect("valid kind");
604        assert_eq!(k, NodeKind::Query);
605    }
606
607    // ── End-to-end token generation over a fixture service ───────────────────
608
609    use crate::schema::types::{ParsedSchema, StructDef};
610
611    fn variant(name: &str, type_name: &str, scope: &str) -> UnionVariant {
612        UnionVariant {
613            name: name.into(),
614            type_name: type_name.into(),
615            description: String::new(),
616            scope: scope.into(),
617            scope_exempt: false,
618            cli_hidden: false,
619            doc_example: String::new(),
620            vfs_path: String::new(),
621            vfs_kind: String::new(),
622            vfs_bulk: false,
623            vfs_hidden: false,
624            vfs_mac: String::new(),
625            dispatch_mac: String::new(),
626            dispatch_public: String::new(),
627            mutation_semantics: String::new(),
628            dispatch_mac_present: false,
629            dispatch_public_present: false,
630            mutation_semantics_present: false,
631        }
632    }
633
634    fn empty_struct(name: &str) -> StructDef {
635        StructDef {
636            name: name.into(),
637            fields: vec![],
638            has_union: false,
639            domain_type: None,
640            origin_file: None,
641            data_words: 0,
642            pointer_words: 0,
643            discriminant_count: 0,
644            discriminant_offset: 0,
645            union_arms: vec![],
646        }
647    }
648
649    fn schema_with(request_variants: Vec<UnionVariant>, structs: Vec<StructDef>) -> ParsedSchema {
650        ParsedSchema {
651            request_variants,
652            response_variants: vec![],
653            structs,
654            scoped_clients: vec![],
655            enums: vec![],
656            request_struct: None,
657            response_struct: None,
658        }
659    }
660
661    #[test]
662    fn generates_a_sensible_node_table() {
663        // A registry-like service: list (dir), getByName (param file), health
664        // (void read file), clone (ctl).
665        let schema = schema_with(
666            vec![
667                variant("list", "Void", "query"),
668                variant("getByName", "Text", "query"),
669                variant("healthCheck", "Void", "query"),
670                variant("clone", "CloneRequest", "write"),
671            ],
672            vec![empty_struct("CloneRequest")],
673        );
674        let resolved = ResolvedSchema::from(&schema);
675        let out = generate_mount("registry", &resolved).to_string();
676
677        assert!(out.contains("fn vfs_nodes"), "emits vfs_nodes(): {out}");
678        // list → Dir at "."
679        assert!(out.contains("VfsNodeKind :: Dir"), "list is a Dir: {out}");
680        // getByName → File at "{arg}"
681        assert!(out.contains("\"{arg}\""), "param file binds {{arg}}: {out}");
682        // clone → Ctl at "ctl"
683        assert!(out.contains("VfsNodeKind :: Ctl"), "clone is a Ctl: {out}");
684        assert!(out.contains("\"ctl\""), "ctl node path: {out}");
685        // health → File node present
686        assert!(out.contains("\"health_check\""), "health file path: {out}");
687        // No compile_error emitted for a consistent schema.
688        assert!(!out.contains("compile_error"), "no guard error: {out}");
689    }
690
691    #[test]
692    fn contradiction_emits_compile_error() {
693        // A write method forced to a read-only `file` via $vfsKind must fail the build.
694        let mut bad = variant("clone", "CloneRequest", "write");
695        bad.vfs_kind = "file".into();
696        let schema = schema_with(vec![bad], vec![empty_struct("CloneRequest")]);
697        let resolved = ResolvedSchema::from(&schema);
698        let out = generate_mount("registry", &resolved).to_string();
699
700        assert!(out.contains("compile_error"), "emits compile_error: {out}");
701        assert!(out.contains("clone"), "names the offending method: {out}");
702    }
703
704    #[test]
705    fn vfs_mac_annotation_flows_onto_emitted_node() {
706        // Carrier (a) (#699): a `$vfsMac`-annotated method projects a node whose
707        // `mac` field carries the annotation text verbatim — the label is a
708        // property of the node's type, derived at generation.
709        let mut health = variant("healthCheck", "Void", "query");
710        health.vfs_mac = "internal:pq-hybrid".into();
711        let mut clone = variant("clone", "CloneRequest", "write");
712        clone.vfs_mac = "secret:pq-hybrid:0".into();
713        // A node with NO `$vfsMac` carries the empty string (→ unlabeled → deny).
714        let list = variant("list", "Void", "query");
715        let schema = schema_with(
716            vec![health, clone, list],
717            vec![empty_struct("CloneRequest")],
718        );
719        let resolved = ResolvedSchema::from(&schema);
720        let out = generate_mount("registry", &resolved).to_string();
721
722        // Annotated labels land verbatim on their nodes.
723        assert!(
724            out.contains("mac : \"internal:pq-hybrid\""),
725            "health node carries its $vfsMac label: {out}"
726        );
727        assert!(
728            out.contains("mac : \"secret:pq-hybrid:0\""),
729            "clone node carries its $vfsMac label: {out}"
730        );
731        // An unannotated node carries the empty string — never a guessed label.
732        assert!(
733            out.contains("mac : \"\""),
734            "an unannotated node is emitted unlabeled (empty mac): {out}"
735        );
736    }
737
738    #[test]
739    fn vfs_hidden_excludes_a_method() {
740        let mut hidden = variant("internalPing", "Void", "query");
741        hidden.vfs_hidden = true;
742        let schema = schema_with(vec![variant("list", "Void", "query"), hidden], vec![]);
743        let resolved = ResolvedSchema::from(&schema);
744        let out = generate_mount("registry", &resolved).to_string();
745
746        assert!(out.contains("\"list\"") || out.contains("VfsNodeKind :: Dir"));
747        assert!(
748            !out.contains("internal_ping"),
749            "hidden method excluded: {out}"
750        );
751    }
752
753    #[test]
754    fn data_only_schema_emits_no_mount() {
755        let schema = schema_with(vec![], vec![empty_struct("SomeData")]);
756        let resolved = ResolvedSchema::from(&schema);
757        let out = generate_mount("dataonly", &resolved).to_string();
758        assert!(out.is_empty(), "data-only schema has no mount: {out}");
759    }
760
761    // ── #669: multiple Void-arg listings in one struct must not collide ──────
762
763    #[test]
764    fn multiple_listings_get_distinct_name_derived_paths() {
765        // Mirrors registry's `repo/{repoId}` scope: four query+Void `list*`
766        // methods, none annotated — all would infer to "." without the fix.
767        let schema = schema_with(
768            vec![
769                variant("listBranches", "Void", "query"),
770                variant("listTags", "Void", "query"),
771                variant("listRemotes", "Void", "query"),
772                variant("listWorktrees", "Void", "query"),
773            ],
774            vec![],
775        );
776        let resolved = ResolvedSchema::from(&schema);
777        let out = generate_mount("repo", &resolved).to_string();
778
779        assert!(
780            !out.contains("compile_error"),
781            "no collision guard error: {out}"
782        );
783        assert!(out.contains("\"branches\""), "list_ prefix stripped: {out}");
784        assert!(out.contains("\"tags\""), "list_ prefix stripped: {out}");
785        assert!(out.contains("\"remotes\""), "list_ prefix stripped: {out}");
786        assert!(
787            out.contains("\"worktrees\""),
788            "list_ prefix stripped: {out}"
789        );
790        // None of the four should still be the bare "." (the pre-fix collision).
791        assert!(
792            !out.contains("path : \".\""),
793            "no method landed on the bare root: {out}"
794        );
795    }
796
797    #[test]
798    fn single_listing_still_defaults_to_dot() {
799        // The common case (one Dir-kind listing in the scope) is unaffected.
800        let schema = schema_with(vec![variant("list", "Void", "query")], vec![]);
801        let resolved = ResolvedSchema::from(&schema);
802        let out = generate_mount("registry", &resolved).to_string();
803
804        assert!(!out.contains("compile_error"), "no guard error: {out}");
805        assert!(
806            out.contains("path : \".\""),
807            "sole listing is still the scope root: {out}"
808        );
809    }
810
811    #[test]
812    fn explicit_vfs_path_overrides_even_with_multiple_listings() {
813        // Three listings: two explicitly annotated (never collide, whatever
814        // they're set to), one bare. Only the un-annotated ones count toward
815        // "how many listings default in this scope" — with just one bare
816        // listing left, it still gets the sole-listing "." default, and the
817        // explicit paths win over inference for the other two.
818        let mut branches = variant("listBranches", "Void", "query");
819        branches.vfs_path = "custom-branches".into();
820        let mut remotes = variant("listRemotes", "Void", "query");
821        remotes.vfs_path = "custom-remotes".into();
822        let schema = schema_with(
823            vec![branches, remotes, variant("listTags", "Void", "query")],
824            vec![],
825        );
826        let resolved = ResolvedSchema::from(&schema);
827        let out = generate_mount("repo", &resolved).to_string();
828
829        assert!(!out.contains("compile_error"), "no guard error: {out}");
830        assert!(
831            out.contains("\"custom-branches\""),
832            "explicit path wins: {out}"
833        );
834        assert!(
835            out.contains("\"custom-remotes\""),
836            "explicit path wins: {out}"
837        );
838        assert!(
839            out.contains("path : \".\""),
840            "the sole un-annotated listing still gets the root: {out}"
841        );
842    }
843
844    #[test]
845    fn collision_guard_fires_on_same_path() {
846        // Two distinct methods that would both resolve to the same explicit path.
847        let mut a = variant("getByName", "Text", "query");
848        a.vfs_path = "dup".into();
849        let mut b = variant("getById", "Text", "query");
850        b.vfs_path = "dup".into();
851        let schema = schema_with(vec![a, b], vec![]);
852        let resolved = ResolvedSchema::from(&schema);
853        let out = generate_mount("registry", &resolved).to_string();
854
855        assert!(
856            out.contains("compile_error"),
857            "collision is a build error: {out}"
858        );
859        assert!(
860            out.contains("get_by_name") && out.contains("get_by_id"),
861            "names both methods: {out}"
862        );
863        assert!(out.contains("dup"), "names the colliding path: {out}");
864    }
865}