hyprstream_rpc_build/schema/types.rs
1//! Type definitions for parsed Cap'n Proto schemas.
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Serialize, Deserialize)]
6pub struct ParsedSchema {
7 /// Request union variants
8 pub request_variants: Vec<UnionVariant>,
9 /// Response union variants
10 pub response_variants: Vec<UnionVariant>,
11 /// Struct definitions referenced by variants
12 pub structs: Vec<StructDef>,
13 /// Scoped clients detected from nested union patterns
14 pub scoped_clients: Vec<ScopedClient>,
15 /// Enum definitions parsed from schema
16 pub enums: Vec<EnumDef>,
17 /// Root request struct (wire format needed for builder codegen).
18 /// `None` when parsed from text (no CGR wire format info).
19 pub request_struct: Option<StructDef>,
20 /// Root response struct (wire format needed for parser codegen).
21 /// `None` when parsed from text (no CGR wire format info).
22 pub response_struct: Option<StructDef>,
23}
24
25#[derive(Debug, Serialize, Deserialize)]
26pub struct UnionVariant {
27 pub name: String,
28 pub type_name: String,
29 pub description: String,
30 /// Authorization action from `$scope`/`$capability` (e.g. "write"). Empty
31 /// only when `scope_exempt` is true (S3, #547): every other method must
32 /// declare a scope or the build fails.
33 pub scope: String,
34 /// Explicit, audited exemption from mandatory scope (`$scopeExempt`, S3 #547).
35 /// True iff the method declares `$scopeExempt("<reason>")` instead of a scope.
36 #[serde(default)]
37 pub scope_exempt: bool,
38 /// Whether this method is hidden from CLI (internal-only).
39 pub cli_hidden: bool,
40 /// VFS usage example from `$docExample` annotation. Empty = no example.
41 pub doc_example: String,
42 /// Mount-relative VFS path from `$vfsPath` (epic #539, T1). Empty = unset
43 /// (the mount generator, T2, infers a default from scope + arg shape).
44 #[serde(default)]
45 pub vfs_path: String,
46 /// VFS node kind override from `$vfsKind` — the enumerant name
47 /// ("file"/"dir"/"ctl"/"stream"/"query"). Empty = unset (kind is inferred).
48 #[serde(default)]
49 pub vfs_kind: String,
50 /// `$vfsBulk`: read path returns raw mmap bytes, bypassing capnp (DMA path).
51 #[serde(default)]
52 pub vfs_bulk: bool,
53 /// `$vfsHidden`: exclude this method from the generated mount.
54 #[serde(default)]
55 pub vfs_hidden: bool,
56 /// `$vfsMac` annotation text — the MAC security label this generated node
57 /// carries (#699 carrier (a); a property of the node's type, derived at
58 /// generation). Empty = unset ⇒ the node is unlabeled ⇒ deny ⇒ a
59 /// genesis-coverage finding (no permissive default).
60 #[serde(default)]
61 pub vfs_mac: String,
62 /// `$dispatchMac` annotation text — the method's target dispatch MAC label
63 /// in the strict `<level>:<assurance>[:<compartments>]` grammar (v16 §6,
64 /// WS-D). Empty = not declared (a leaf with neither dispatch annotation is
65 /// a build error; a scoped dispatcher carries neither).
66 #[serde(default)]
67 pub dispatch_mac: String,
68 /// Whether `$dispatchMac` was present, including an explicitly empty value.
69 #[serde(default)]
70 pub dispatch_mac_present: bool,
71 /// `$dispatchPublic` annotation text — the mandatory, reviewable reason a
72 /// leaf may be dispatched unauthenticated (v16 §6). Empty = not declared.
73 /// Expands to exactly system low; public is never inherited.
74 #[serde(default)]
75 pub dispatch_public: String,
76 /// Whether `$dispatchPublic` was present, including an explicitly empty value.
77 #[serde(default)]
78 pub dispatch_public_present: bool,
79 /// `$mutationSemantics` declaration for a mutating leaf (v16 §4.8/§6.1).
80 /// Empty only for read-class, scope-exempt, or dispatcher variants.
81 #[serde(default)]
82 pub mutation_semantics: String,
83 /// Whether `$mutationSemantics` was present, including an explicitly empty value.
84 #[serde(default)]
85 pub mutation_semantics_present: bool,
86}
87
88/// Payload carried by a tagged-union arm.
89///
90/// Distinguishes the three shapes a Cap'n Proto union member can take:
91/// a `Void` arm (no payload), a single-type arm (scalar/Text/Data/enum/struct),
92/// and a `group` arm (an inlined anonymous struct with its own leaf fields).
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub enum ArmPayload {
95 /// `arm @N :Void;` — unit variant, no payload.
96 Void,
97 /// `arm @N :T;` — carries a single value of capnp type `T`
98 /// (a scalar, `Text`, `Data`, an enum, or a struct).
99 Type(String),
100 /// `arm @N :group { ... }` — carries an inlined anonymous struct;
101 /// the leaf fields are the group's slots (all non-union).
102 Group(Vec<FieldDef>),
103}
104
105/// A single arm of a tagged union (one member of a capnp `union { ... }`).
106///
107/// Populated for pure-union structs so Rust codegen can emit a native `enum`
108/// (one variant per arm) instead of an empty struct. The flat `fields` list on
109/// `StructDef` still carries every union member (for the TS/wire-format path);
110/// `union_arms` is the structured view layered on top.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct UnionArm {
113 /// capnp arm name (camelCase, e.g. `atLeastOnce`).
114 pub name: String,
115 /// Union discriminant ordinal for this arm.
116 pub discriminant_value: u16,
117 /// Description from `$paramDescription`/`$mcpDescription` (may be empty).
118 pub description: String,
119 /// `$dispatchMac` metadata carried by a pure-union arm.
120 #[serde(default)]
121 pub dispatch_mac: String,
122 #[serde(default)]
123 pub dispatch_mac_present: bool,
124 /// `$dispatchPublic` metadata carried by a pure-union arm.
125 #[serde(default)]
126 pub dispatch_public: String,
127 #[serde(default)]
128 pub dispatch_public_present: bool,
129 /// `$mutationSemantics` metadata carried by a pure-union arm.
130 #[serde(default)]
131 pub mutation_semantics: String,
132 #[serde(default)]
133 pub mutation_semantics_present: bool,
134 /// The payload this arm carries.
135 pub payload: ArmPayload,
136}
137
138#[derive(Debug, Serialize, Deserialize)]
139pub struct StructDef {
140 pub name: String,
141 pub fields: Vec<FieldDef>,
142 pub has_union: bool,
143 /// Domain type path from `$domainType` annotation (e.g., "runtime::VersionResponse").
144 /// When set, the generated client returns this type via `FromCapnp::read_from()`.
145 pub domain_type: Option<String>,
146 /// Origin file stem for imported types (e.g., `Some("streaming")` for types from streaming.capnp).
147 /// `None` means the type is local to the service's own schema file.
148 pub origin_file: Option<String>,
149 /// Number of data words in the struct section (from CGR).
150 /// Used by TypeScript codegen for correct wire format offsets.
151 pub data_words: u16,
152 /// Number of pointer words in the struct section (from CGR).
153 pub pointer_words: u16,
154 /// Discriminant count (number of union members).
155 pub discriminant_count: u16,
156 /// Offset of the discriminant in the data section (in u16 units).
157 pub discriminant_offset: u32,
158 /// Structured view of the union arms (when `discriminant_count > 0`).
159 ///
160 /// Empty for non-union structs. Layered on top of the flat `fields` list:
161 /// `fields` still carries every union member for the wire-format/TS path,
162 /// while `union_arms` carries the per-arm payload shape (Void / single-type /
163 /// group) that Rust enum codegen consumes.
164 #[serde(default)]
165 pub union_arms: Vec<UnionArm>,
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct FieldDef {
170 pub name: String,
171 pub type_name: String,
172 pub description: String,
173 /// From `$fixedSize(N)` annotation: generates `[u8; N]` instead of `Vec<u8>` for Data fields.
174 pub fixed_size: Option<u32>,
175 /// From `$maxLen(N)` annotation: Text fields reject decoded values longer
176 /// than N at the borrowed reader, before any owned String is allocated.
177 pub max_len: Option<u32>,
178 /// From `$optional` annotation: field is optional in MCP tool schemas and uses
179 /// type-appropriate zero-value defaults when absent at runtime.
180 pub optional: bool,
181 /// Slot offset from CGR (field::slot::get_offset()).
182 /// For data section fields, this is the word-level offset.
183 /// For pointer section fields, this is the pointer index.
184 pub slot_offset: u32,
185 /// Which section this field lives in (data section or pointer section).
186 pub section: FieldSection,
187 /// Discriminant value for union fields (0xFFFF means non-union).
188 pub discriminant_value: u16,
189 /// From `$serdeRename("...")` annotation: generates `#[serde(rename = "...")]` on the Rust field.
190 pub serde_rename: Option<String>,
191 /// From a field-level `$domainType("path::Type")` annotation: the field maps to this
192 /// Rust newtype while keeping its capnp wire type (e.g. `Text`). The generated struct
193 /// uses this type; ToCapnp writes via `.as_str()` and FromCapnp reads via `Type::new(...)`.
194 #[serde(default)]
195 pub domain_type: Option<String>,
196}
197
198/// Which section of a Cap'n Proto struct a field resides in.
199#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
200pub enum FieldSection {
201 /// Data section (fixed-size scalars: bool, ints, floats, enum ordinals)
202 #[default]
203 Data,
204 /// Pointer section (variable-length: Text, Data, List, Struct)
205 Pointer,
206 /// Group (inlined, no slot)
207 Group,
208}
209
210impl StructDef {
211 /// Fields that are NOT union members (discriminant_value == 0xFFFF).
212 ///
213 /// Use this for Rust codegen which should not generate `get_*()` / `set_*()`
214 /// calls for union members (Cap'n Proto Rust uses `which()` for those).
215 /// TypeScript codegen should use `.fields` directly since it needs all fields
216 /// including union members for wire format slot offsets and discriminant values.
217 pub fn non_union_fields(&self) -> impl Iterator<Item = &FieldDef> {
218 self.fields
219 .iter()
220 .filter(|f| f.discriminant_value == 0xFFFF)
221 }
222
223 /// Fields that ARE union members (discriminant_value != 0xFFFF).
224 ///
225 /// These are the variant arms of a union within the struct.
226 /// Each has a distinct `discriminant_value` that identifies which arm is active.
227 pub fn union_fields(&self) -> impl Iterator<Item = &FieldDef> {
228 self.fields
229 .iter()
230 .filter(|f| f.discriminant_value != 0xFFFF)
231 }
232
233 /// True if this struct is a pure union (has_union and no non-union fields).
234 pub fn is_pure_union(&self) -> bool {
235 self.has_union && self.non_union_fields().count() == 0
236 }
237
238 /// Returns the inner type name `T` if this struct is a valid `Option<T>` wrapper.
239 ///
240 /// Validates that the struct is a pure union with exactly two variants:
241 /// `none @0 :Void` and `some @1 :T`.
242 ///
243 /// This is more reliable than checking `name.starts_with("Option")` alone,
244 /// because it validates the actual structure rather than just the name.
245 pub fn option_inner_type(&self) -> Option<&str> {
246 if !self.is_pure_union() {
247 return None;
248 }
249 if self.discriminant_count != 2 {
250 return None;
251 }
252 let mut union_fields: Vec<&FieldDef> = self.union_fields().collect();
253 if union_fields.len() != 2 {
254 return None;
255 }
256 union_fields.sort_by_key(|f| f.discriminant_value);
257 let none_field = union_fields[0];
258 let some_field = union_fields[1];
259 if none_field.name != "none" || none_field.type_name != "Void" {
260 return None;
261 }
262 if some_field.name != "some" {
263 return None;
264 }
265 Some(&some_field.type_name)
266 }
267}
268
269/// Check if a Cap'n Proto type name is a primitive (not a struct reference).
270///
271/// Returns true for all scalar types, `Void`, `Text`, `Data`, and `List(...)`.
272/// Includes `Void` — callers that need to exclude it (e.g., setter dispatch)
273/// should additionally check `type_name != "Void"`.
274pub fn is_primitive_capnp_type(type_name: &str) -> bool {
275 matches!(
276 type_name,
277 "Void"
278 | "Bool"
279 | "Text"
280 | "Data"
281 | "UInt8"
282 | "UInt16"
283 | "UInt32"
284 | "UInt64"
285 | "Int8"
286 | "Int16"
287 | "Int32"
288 | "Int64"
289 | "Float32"
290 | "Float64"
291 ) || type_name.starts_with("List(")
292}
293
294#[derive(Debug, Serialize, Deserialize)]
295pub struct EnumDef {
296 pub name: String,
297 pub variants: Vec<(String, u32)>,
298 /// Origin file stem for imported types (e.g., `Some("streaming")` for types from streaming.capnp).
299 /// `None` means the type is local to the service's own schema file.
300 pub origin_file: Option<String>,
301}
302
303/// A scoped client detected from nested union patterns in the schema.
304#[derive(Debug, Serialize, Deserialize)]
305pub struct ScopedClient {
306 /// Factory method name on parent client (e.g., "repo", "session")
307 pub factory_name: String,
308 /// Generated client struct name (e.g., "RepositoryClient", "ModelSessionClient")
309 pub client_name: String,
310 /// Curried scope fields from the inner struct
311 pub scope_fields: Vec<FieldDef>,
312 /// Inner union variants from the request struct
313 pub inner_request_variants: Vec<UnionVariant>,
314 /// Inner union variants from the response struct
315 pub inner_response_variants: Vec<UnionVariant>,
316 /// Cap'n Proto module name for the inner response struct (snake_case)
317 pub capnp_inner_response: String,
318 /// Nested scoped clients detected within this scope (e.g., Fs within Repository)
319 pub nested_clients: Vec<ScopedClient>,
320}
321
322#[cfg(test)]
323mod vfs_metadata_tests {
324 #![allow(clippy::expect_used, clippy::unwrap_used)]
325 use super::*;
326
327 /// The VFS projection fields (epic #539, T1) survive a serde round-trip —
328 /// this is the JSON-metadata contract the mount generator (T2) consumes.
329 #[test]
330 fn vfs_fields_round_trip() {
331 let v = UnionVariant {
332 name: "getByName".into(),
333 type_name: "Text".into(),
334 description: String::new(),
335 scope: "query".into(),
336 scope_exempt: false,
337 cli_hidden: false,
338 doc_example: String::new(),
339 vfs_path: "{name}".into(),
340 vfs_kind: "file".into(),
341 vfs_bulk: false,
342 vfs_hidden: false,
343 vfs_mac: String::new(),
344 dispatch_mac: String::new(),
345 dispatch_public: String::new(),
346 mutation_semantics: String::new(),
347 dispatch_mac_present: false,
348 dispatch_public_present: false,
349 mutation_semantics_present: false,
350 };
351 let json = serde_json::to_string(&v).expect("serialize");
352 let back: UnionVariant = serde_json::from_str(&json).expect("deserialize");
353 assert_eq!(back.vfs_path, "{name}");
354 assert_eq!(back.vfs_kind, "file");
355 assert!(!back.vfs_bulk);
356 assert!(!back.vfs_hidden);
357 }
358
359 /// Metadata predating the VFS fields still deserializes — the `#[serde(default)]`
360 /// keeps the capture additive (no forced schema break).
361 #[test]
362 fn legacy_metadata_defaults_vfs_fields() {
363 let legacy = r#"{
364 "name": "list",
365 "type_name": "Void",
366 "description": "",
367 "scope": "query",
368 "scope_exempt": false,
369 "cli_hidden": false,
370 "doc_example": ""
371 }"#;
372 let v: UnionVariant = serde_json::from_str(legacy).expect("deserialize legacy");
373 assert_eq!(v.vfs_path, "");
374 assert_eq!(v.vfs_kind, "");
375 assert!(!v.vfs_bulk);
376 assert!(!v.vfs_hidden);
377 }
378}