Skip to main content

subc_protocol/
manifest.rs

1//! Capability manifest schema for subc modules.
2//!
3//! All v1 modules are supervised singletons: one long-lived process per
4//! per-user machine. The manifest intentionally has **no `cardinality` field**.
5//! subc routes by module kind plus channel, while any finer demultiplexing
6//! (for example, AFT's per-project actor map) remains internal to the singleton
7//! module.
8
9use std::{
10    collections::{BTreeMap, HashSet},
11    fmt,
12};
13
14use serde::{de::Error as _, Deserialize, Deserializer, Serialize};
15use serde_json::Value;
16
17use crate::provider_declarations::{deserialize_provider_declarations, ProviderDeclarations};
18use crate::PROTOCOL_VERSION;
19
20pub use crate::provider_declarations::{
21    validate_hello_provider_declarations, ProviderDeclarationsError,
22};
23
24/// Maximum compact JSON size of the complete per-role declaration map.
25pub const MAX_ROLE_DECLARATIONS_BYTES: usize = 16_384;
26
27/// Maximum number of names in [`ModuleManifest::flow_operations`].
28pub const MAX_FLOW_OPERATIONS: usize = 256;
29
30/// Maximum number of names in [`ModuleManifest::confirm_operations`].
31pub const MAX_CONFIRM_OPERATIONS: usize = 256;
32
33/// A module that implements the local `doctor` command declares this capability.
34pub const DOCTOR_CAPABILITY: &str = "doctor/v1";
35
36/// A module's full declared participation in the subc mesh.
37///
38/// Construct via [`ModuleManifest::builder()`], never a struct literal. Adding a
39/// field to this struct would break every direct construction site; builder methods
40/// are additive, so constructors written against an older revision continue
41/// compiling when later fields land.
42#[derive(Serialize, Debug, Clone, PartialEq)]
43#[non_exhaustive]
44pub struct ModuleManifest {
45    pub module_id: String,
46    /// Human-readable module name. Apps fall back to `module_id` when absent.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub display_name: Option<String>,
49    /// Lucide icon name. Apps use a generic icon when absent or unknown.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub icon: Option<String>,
52    /// Only an explicit `false` says the module does not host third-party code.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub hosts_third_party_code: Option<bool>,
55    pub module_version: String,
56    pub protocol_ver: u8,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub trust_tier: Option<TrustTier>,
59    /// Whether this registered module is ready to receive new route binds.
60    ///
61    /// Absence means ready, preserving the behavior of manifests emitted before
62    /// this field existed. This is a best-effort admission hint, not an invariant:
63    /// the daemon reads readiness separately from reserving a relay, so modules
64    /// must still tolerate an `on_bind` while not ready.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub ready: Option<bool>,
67    /// Declares SDK support for the private registration connection inherited
68    /// from the supervising daemon at spawn. Absence is unknown support, not
69    /// permission to use a nonce when admission requires that private channel.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub registration_channel: Option<bool>,
72    /// Existing role declarations; capability grammar claims deliberately live in
73    /// the separate [`CapabilityDeclarations`] block below.
74    pub provides: Vec<ProviderRole>,
75    #[serde(default, skip_serializing_if = "Vec::is_empty")]
76    pub consumes: Vec<ConsumerRole>,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub bindings: Option<Bindings>,
79    /// Optional capability-grammar declarations.
80    ///
81    /// Omitting this block preserves the manifest contract used before capability
82    /// grammar was introduced. A present block is static discovery metadata that
83    /// the daemon validates before accepting a HELLO.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub capabilities: Option<CapabilityDeclarations>,
86    /// Events published as notices on `ck.{acct}.event.{module_id}.{event}.v{N}`.
87    /// The publisher serves the body; declared headers are filter hints, never authority.
88    ///
89    /// `None` means the module has not declared events. `Some(vec![])` affirmatively
90    /// declares that it publishes none. Absence remains absent on the wire.
91    ///
92    /// Declarations are validated at HELLO and retained in the daemon registry,
93    /// but no client can read them yet: `catalog.list`, `server.describe` and
94    /// `ck catalog` do not return them, because subc-control's `CatalogEntry`
95    /// has no field for them and adding one is a breaking change. A daemon built
96    /// before this field existed drops it silently. So a flow engine cannot yet
97    /// discover a module's events from the catalog, and a module must not depend
98    /// on that discovery until a daemon that serves declarations is running.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub events: Option<Vec<EventDeclaration>>,
101    /// Periodic or event-driven behavior this module performs against an external
102    /// surface, so later analysts can account for the resulting self-shaped time
103    /// series.
104    ///
105    /// Declarations describe the EFFECTIVE values in force at HELLO time. In
106    /// particular, a compile-time cadence constant belongs in
107    /// [`SignalCadence::Literal`], while a cadence resolved from configuration
108    /// belongs in [`SignalCadence::Derived`] with a pointer to that effective
109    /// source. Both provenance stories are honest; copying a stale configured
110    /// value into a literal is not.
111    ///
112    /// Ephemeral signals are out of scope for v1 because they are not durably
113    /// declarable, not because they are harmless. A v2 reader must not interpret
114    /// this field's absence in a v1 manifest as a judgement about ephemerals.
115    ///
116    /// `None` and `Some(vec![])` are deliberately distinct on the wire: an
117    /// absent block means the module has not adopted this vocabulary (readers
118    /// treat it as zero signals but must not treat it as a survey answer),
119    /// while an empty list is an affirmative declaration that the module
120    /// examined its effects and claims none are declarable. Modules that mean
121    /// "no signals" should declare the empty list; `None` is what an
122    /// un-adopted manifest looks like, not a statement.
123    ///
124    /// Convention for mutate-effect entries: where the mutation leaves a
125    /// per-observation tell on the surface itself (insula publishes the
126    /// relaxed `usedPercent` beside the raw figure, so any single reading
127    /// self-reports whether it was touched), name that tell in the
128    /// declaration's note. A standing registry row says the module sometimes
129    /// mutates; the tell says whether THIS observation was mutated — a
130    /// consumer holding one sample can act on the second, not the first.
131    /// A named tell must exist on the wire independently of this registry:
132    /// the declaration points at evidence, it is never the evidence. A tell
133    /// that exists only because the manifest describes it is a claim
134    /// vouching for itself.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub self_signals: Option<Vec<SelfSignalDeclaration>>,
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub provenance: Option<ManifestProvenance>,
139    /// Delivery hints keyed by management operation name; absent entries are unary.
140    /// Only `"watch"` on a declared query is subscribable; see [`Self::is_watch_operation`].
141    /// Unknown strings are retained. A malformed map is dropped as a whole rather
142    /// than refusing HELLO. Older daemons silently drop this field.
143    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
144    pub operation_delivery: BTreeMap<String, OperationDelivery>,
145    /// Human-readable titles keyed by declared management operation name.
146    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
147    pub operation_titles: BTreeMap<String, String>,
148    /// Groups of declared management operations, keyed by group id.
149    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
150    pub operation_groups: BTreeMap<String, OperationGroup>,
151    /// Additional operations a caller needs, keyed by declared operation name.
152    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
153    pub operation_requires: BTreeMap<String, Vec<String>>,
154    /// Raw request payload limits keyed by declared management operation name.
155    /// Watch operations cannot accept payloads. Empty maps preserve legacy bytes.
156    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
157    pub operation_payload: BTreeMap<String, OperationPayload>,
158    /// Management operations this module serves to a flow-scoped call.
159    ///
160    /// `Some(list)` says the module admits a call under a scope carrying
161    /// `flow_id` only for the named operations and refuses every other one;
162    /// `Some(vec![])` admits none. `None` means the module has not said, so a
163    /// reader (such as an install check) treats the answer as unknown and keeps
164    /// the module-wide view given by `flow-scopes/v1` or `call-modes/v1`; it never
165    /// means "none".
166    ///
167    /// Meaningful only beside one of those capabilities in
168    /// `capabilities.provides`. Decoding drops the whole list, without refusing
169    /// HELLO, when the manifest declares neither capability, when the list is not
170    /// an array of strings, holds more than [`MAX_FLOW_OPERATIONS`] names, repeats
171    /// a name, or names something that is not a management operation of this same
172    /// manifest; see [`ModuleManifest::validate_flow_operations`]. The daemon only
173    /// relays the list through `catalog.list` and never enforces it: each module
174    /// refuses the operations it does not admit. Absence preserves legacy bytes,
175    /// and older daemons silently drop the field.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub flow_operations: Option<Vec<String>>,
178    /// Operations safe to defer, keyed by `tool:<name>` or `management:<name>`.
179    /// Invalid maps are dropped whole; HELLO remains accepted. Only meaningful
180    /// with scope-federated/v1. The daemon relays, but never enforces, this map.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub operation_deferral: Option<BTreeMap<String, bool>>,
183    /// Management operations this module guards by asking the person through
184    /// `operator.confirm` before it acts.
185    ///
186    /// `Some(list)` names them; `Some(vec![])` names none. `None` means the
187    /// module has not said, which a reader treats as unknown. A module asking
188    /// `operator.confirm` with kind `operation` names one of these in the
189    /// request's `operation`; the daemon may answer without a prompt only for an
190    /// operation listed here, and prompts for everything else.
191    ///
192    /// Decoding drops the whole list, without refusing HELLO, when it is not an
193    /// array of strings, holds more than [`MAX_CONFIRM_OPERATIONS`] names,
194    /// repeats a name, or names something that is not a management operation of
195    /// this same manifest; see [`ModuleManifest::validate_confirm_operations`].
196    /// The daemon relays a valid list through `catalog.list` and refuses nothing
197    /// on its basis. Absence preserves legacy bytes, and older daemons silently
198    /// drop the field.
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub confirm_operations: Option<Vec<String>>,
201    /// An opaque rich-UI manifest descriptor discoverable from `catalog.list`.
202    ///
203    /// The daemon validates the descriptor's shape at HELLO and relays it without
204    /// interpreting its schema or content. Absence preserves existing manifest bytes.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub rich_ui: Option<RichUiDescriptor>,
207    /// Opaque declarations keyed by role name, using the capability-name grammar.
208    ///
209    /// Each role's contract owns its entry's schema. The daemon never interprets
210    /// the content: it checks object shape, keys and the whole-map size limit,
211    /// then relays the map through `catalog.list`. Malformed or oversized maps
212    /// are dropped whole at HELLO with a warning, without refusing registration.
213    /// Older daemons silently drop unknown manifest fields, so modules may declare
214    /// entries before every daemon understands this slot.
215    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
216    pub role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
217    /// Requested provider-owned entries, immutable for the spawn. Absence grants
218    /// nothing. Invalid shapes and sizes refuse HELLO rather than being dropped.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub provider_declarations: Option<ProviderDeclarations>,
221}
222
223/// Incrementally constructs a [`ModuleManifest`] without fabricating absent facts.
224#[derive(Debug, Clone)]
225pub struct ModuleManifestBuilder {
226    module_id: String,
227    display_name: Option<String>,
228    icon: Option<String>,
229    hosts_third_party_code: Option<bool>,
230    module_version: String,
231    protocol_ver: u8,
232    trust_tier: Option<TrustTier>,
233    ready: Option<bool>,
234    registration_channel: Option<bool>,
235    provides: Vec<ProviderRole>,
236    consumes: Vec<ConsumerRole>,
237    bindings: Option<Bindings>,
238    capabilities: Option<CapabilityDeclarations>,
239    events: Option<Vec<EventDeclaration>>,
240    self_signals: Option<Vec<SelfSignalDeclaration>>,
241    provenance: Option<ManifestProvenance>,
242    operation_delivery: BTreeMap<String, OperationDelivery>,
243    operation_titles: BTreeMap<String, String>,
244    operation_groups: BTreeMap<String, OperationGroup>,
245    operation_requires: BTreeMap<String, Vec<String>>,
246    operation_payload: BTreeMap<String, OperationPayload>,
247    flow_operations: Option<Vec<String>>,
248    operation_deferral: Option<BTreeMap<String, bool>>,
249    confirm_operations: Option<Vec<String>>,
250    rich_ui: Option<RichUiDescriptor>,
251    role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
252    provider_declarations: Option<ProviderDeclarations>,
253}
254
255impl ModuleManifest {
256    /// Starts a manifest builder with the minimal identification fields.
257    ///
258    /// `protocol_ver` defaults to the protocol version linked into this crate;
259    /// `provides` and `consumes` default to empty declarations. `trust_tier`
260    /// and `bindings` default to `None` because the daemon reads neither on any
261    /// production path; a required unread field forces producers to invent
262    /// fabricated values.
263    pub fn builder(
264        module_id: impl Into<String>,
265        module_version: impl Into<String>,
266    ) -> ModuleManifestBuilder {
267        ModuleManifestBuilder {
268            module_id: module_id.into(),
269            display_name: None,
270            icon: None,
271            hosts_third_party_code: None,
272            module_version: module_version.into(),
273            protocol_ver: PROTOCOL_VERSION,
274            trust_tier: None,
275            ready: None,
276            registration_channel: None,
277            provides: Vec::new(),
278            consumes: Vec::new(),
279            bindings: None,
280            capabilities: None,
281            events: None,
282            self_signals: None,
283            provenance: None,
284            operation_delivery: BTreeMap::new(),
285            operation_titles: BTreeMap::new(),
286            operation_groups: BTreeMap::new(),
287            operation_requires: BTreeMap::new(),
288            operation_payload: BTreeMap::new(),
289            flow_operations: None,
290            operation_deferral: None,
291            confirm_operations: None,
292            rich_ui: None,
293            role_declarations: BTreeMap::new(),
294            provider_declarations: None,
295        }
296    }
297
298    /// Whether a management query explicitly declares watch delivery.
299    ///
300    /// Missing operations, non-query operations and unknown delivery strings are
301    /// not watches. Such declarations are discovery hints, not HELLO refusals.
302    pub fn is_watch_operation(&self, name: &str) -> bool {
303        self.operation_delivery
304            .get(name)
305            .is_some_and(OperationDelivery::is_watch)
306            && self.provides.iter().any(|role| match role {
307                ProviderRole::ManagementSurface { operations, .. } => operations
308                    .iter()
309                    .any(|op| op.name == name && op.kind == ManagementOperationKind::Query),
310                _ => false,
311            })
312    }
313}
314
315impl ModuleManifestBuilder {
316    /// Sets an optional display name, refusing invalid text without normalizing it.
317    pub fn display_name(mut self, display_name: Option<String>) -> Result<Self, DisplayNameError> {
318        if let Some(value) = &display_name {
319            validate_display_name(value)?;
320        }
321        self.display_name = display_name;
322        Ok(self)
323    }
324
325    /// Sets the Lucide icon name without checking it against any app's icon set.
326    pub fn icon(mut self, icon: impl Into<String>) -> Result<Self, IconError> {
327        let icon = icon.into();
328        validate_icon(&icon)?;
329        self.icon = Some(icon);
330        Ok(self)
331    }
332
333    /// Declares whether the module hosts third-party code.
334    pub fn hosts_third_party_code(mut self, hosts_third_party_code: bool) -> Self {
335        self.hosts_third_party_code = Some(hosts_third_party_code);
336        self
337    }
338
339    /// Overrides the linked protocol version for compatibility fixtures.
340    pub fn protocol_ver(mut self, protocol_ver: u8) -> Self {
341        self.protocol_ver = protocol_ver;
342        self
343    }
344
345    /// Declares the optional trust tier of this module.
346    ///
347    /// The daemon does not evaluate this field on any production path.
348    pub fn trust_tier(mut self, trust_tier: Option<TrustTier>) -> Self {
349        self.trust_tier = trust_tier;
350        self
351    }
352
353    /// Declares whether the module is ready to receive new route binds.
354    pub fn ready(mut self, ready: bool) -> Self {
355        self.ready = Some(ready);
356        self
357    }
358
359    /// Declare whether the module supports the inherited registration channel.
360    pub fn registration_channel(mut self, supported: bool) -> Self {
361        self.registration_channel = Some(supported);
362        self
363    }
364
365    /// Declares the provider roles this module exposes.
366    pub fn provides(mut self, provides: Vec<ProviderRole>) -> Self {
367        self.provides = provides;
368        self
369    }
370
371    /// Declares the consumer roles this module requests.
372    pub fn consumes(mut self, consumes: Vec<ConsumerRole>) -> Self {
373        self.consumes = consumes;
374        self
375    }
376
377    /// Declares the optional resource and subsystem bindings of this module.
378    ///
379    /// The daemon does not evaluate this field on any production path.
380    pub fn bindings(mut self, bindings: Option<Bindings>) -> Self {
381        self.bindings = bindings;
382        self
383    }
384
385    /// Adds optional capability-grammar declarations.
386    pub fn capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
387        self.capabilities = capabilities;
388        self
389    }
390
391    /// Adds optional bus event declarations; an empty list declares no events.
392    pub fn events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
393        self.events = events;
394        self
395    }
396
397    /// Adds optional periodic or event-driven behavior declarations.
398    pub fn self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
399        self.self_signals = self_signals;
400        self
401    }
402
403    /// Adds optional build provenance declared by the module.
404    pub fn provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
405        self.provenance = provenance;
406        self
407    }
408
409    /// Sets delivery hints; an empty map preserves the legacy unary wire shape.
410    pub fn operation_delivery(
411        mut self,
412        operation_delivery: BTreeMap<String, OperationDelivery>,
413    ) -> Self {
414        self.operation_delivery = operation_delivery;
415        self
416    }
417
418    /// Sets a human-readable title without normalizing it. Set the management
419    /// operations with [`Self::provides`] before adding their titles.
420    pub fn operation_title(
421        mut self,
422        name: impl Into<String>,
423        title: impl Into<String>,
424    ) -> Result<Self, OperationTitleError> {
425        let name = name.into();
426        let title = title.into();
427        validate_operation_title(&self.provides, &name, &title)?;
428        self.operation_titles.insert(name, title);
429        Ok(self)
430    }
431
432    /// Adds or replaces a group after its management operations have been set
433    /// with [`Self::provides`]. An operation can belong to at most one group.
434    pub fn operation_group(
435        mut self,
436        id: impl Into<String>,
437        group: OperationGroup,
438    ) -> Result<Self, OperationMetadataError> {
439        let id = id.into();
440        let assigned = self
441            .operation_groups
442            .iter()
443            .filter(|(other_id, _)| other_id.as_str() != id)
444            .flat_map(|(_, other)| other.operations.iter().map(String::as_str))
445            .collect();
446        validate_operation_group(&self.provides, &id, &group, &assigned)?;
447        self.operation_groups.insert(id, group);
448        Ok(self)
449    }
450
451    /// Declares the operations required by a management operation already set
452    /// with [`Self::provides`]. Foreign references use `module_id/operation`.
453    pub fn operation_requires(
454        mut self,
455        name: impl Into<String>,
456        requires: Vec<String>,
457    ) -> Result<Self, OperationMetadataError> {
458        let name = name.into();
459        validate_operation_requires(&self.provides, &name, &requires)?;
460        self.operation_requires.insert(name, requires);
461        Ok(self)
462    }
463
464    /// Sets raw request payload limits; an empty map preserves legacy wire bytes.
465    pub fn operation_payload(
466        mut self,
467        operation_payload: BTreeMap<String, OperationPayload>,
468    ) -> Self {
469        self.operation_payload = operation_payload;
470        self
471    }
472
473    /// Declares the management operations served to a flow-scoped call.
474    ///
475    /// `None` (the default) leaves the answer unknown and preserves legacy wire
476    /// bytes; `Some(vec![])` admits no operation under a flow scope. Check the
477    /// result with [`ModuleManifest::validate_flow_operations`], because an
478    /// invalid list is dropped when the manifest is decoded.
479    pub fn flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
480        self.flow_operations = flow_operations;
481        self
482    }
483
484    /// Declares operations that may run after a paired computer reconnects.
485    pub fn operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
486        self.operation_deferral = operations;
487        self
488    }
489
490    /// Declares the management operations guarded with `operator.confirm`.
491    ///
492    /// `None` (the default) leaves the answer unknown and preserves legacy wire
493    /// bytes. Check the result with
494    /// [`ModuleManifest::validate_confirm_operations`], because an invalid list
495    /// is dropped when the manifest is decoded.
496    pub fn confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
497        self.confirm_operations = confirm_operations;
498        self
499    }
500
501    /// Adds an opaque rich-UI manifest descriptor to this module's manifest.
502    pub fn rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
503        self.rich_ui = rich_ui;
504        self
505    }
506
507    /// Sets opaque declarations owned by each role's contract.
508    pub fn role_declarations(
509        mut self,
510        role_declarations: BTreeMap<String, serde_json::Map<String, Value>>,
511    ) -> Self {
512        self.role_declarations = role_declarations;
513        self
514    }
515
516    /// Sets requested provider entries. HELLO validates their bounds before
517    /// registration; the provider, not the daemon, owns each entry's schema.
518    pub fn provider_declarations(mut self, declarations: Option<ProviderDeclarations>) -> Self {
519        self.provider_declarations = declarations;
520        self
521    }
522
523    /// Finishes the manifest.
524    pub fn build(self) -> ModuleManifest {
525        ModuleManifest {
526            module_id: self.module_id,
527            display_name: self.display_name,
528            icon: self.icon,
529            hosts_third_party_code: self.hosts_third_party_code,
530            module_version: self.module_version,
531            protocol_ver: self.protocol_ver,
532            trust_tier: self.trust_tier,
533            ready: self.ready,
534            registration_channel: self.registration_channel,
535            provides: self.provides,
536            consumes: self.consumes,
537            bindings: self.bindings,
538            capabilities: self.capabilities,
539            events: self.events,
540            self_signals: self.self_signals,
541            provenance: self.provenance,
542            operation_delivery: self.operation_delivery,
543            operation_titles: self.operation_titles,
544            operation_groups: self.operation_groups,
545            operation_requires: self.operation_requires,
546            operation_payload: self.operation_payload,
547            flow_operations: self.flow_operations,
548            operation_deferral: self.operation_deferral,
549            confirm_operations: self.confirm_operations,
550            rich_ui: self.rich_ui,
551            role_declarations: self.role_declarations,
552            provider_declarations: self.provider_declarations,
553        }
554    }
555}
556
557/// DELIBERATELY LENIENT: unknown top-level manifest keys are DROPPED at this
558/// parse boundary, not rejected and not retained. This is forward
559/// compatibility across version skew — a module built against a newer
560/// subc-protocol must still HELLO into an older daemon, and strictness here
561/// would turn every additive manifest field into a daemon-first flag day.
562/// The costs, so nobody re-derives them the hard way (CEREB found both):
563/// - A key you add module-side is INVISIBLE to the daemon until a typed field
564///   lands here. Producing it is honest; assuming a daemon-side reader exists
565///   is not. Say who the audience is next to any such producer.
566/// - There is deliberately NO untyped extension bag on this struct: a
567///   retained-verbatim Value map becomes an unversioned de-facto wire
568///   contract nobody authored (the drift class module-owned payload crates
569///   exist to prevent). The explicit `role_declarations` slot is bounded and
570///   schema-owned by each role, not a catch-all for unknown manifest keys.
571///   If the daemon needs to interpret a value, expose it as a typed optional
572///   field in a dedicated change rather than reading it from `role_declarations`.
573///
574/// `CapabilityDeclarations` below is strict by contrast because claims are
575/// routed on: an unparseable claim must refuse loudly, never partially apply.
576#[derive(Deserialize)]
577struct ModuleManifestWire {
578    module_id: String,
579    #[serde(default)]
580    display_name: Option<String>,
581    #[serde(default)]
582    icon: Option<String>,
583    #[serde(default)]
584    hosts_third_party_code: Option<Value>,
585    module_version: String,
586    protocol_ver: u8,
587    #[serde(default)]
588    trust_tier: Option<TrustTier>,
589    #[serde(default)]
590    ready: Option<bool>,
591    #[serde(default)]
592    registration_channel: Option<bool>,
593    provides: Vec<ProviderRole>,
594    #[serde(default)]
595    consumes: Vec<ConsumerRole>,
596    #[serde(default)]
597    bindings: Option<Bindings>,
598    #[serde(default)]
599    capabilities: Option<CapabilityDeclarations>,
600    #[serde(default)]
601    events: Option<Value>,
602    #[serde(default)]
603    self_signals: Option<Vec<SelfSignalDeclaration>>,
604    #[serde(default)]
605    provenance: Option<ManifestProvenance>,
606    #[serde(default)]
607    operation_delivery: Option<Value>,
608    #[serde(default)]
609    operation_titles: BTreeMap<String, String>,
610    #[serde(default)]
611    operation_groups: BTreeMap<String, OperationGroup>,
612    #[serde(default)]
613    operation_requires: BTreeMap<String, Vec<String>>,
614    #[serde(default)]
615    operation_payload: BTreeMap<String, OperationPayload>,
616    // Kept raw so an invalid list can be dropped rather than refusing HELLO.
617    #[serde(default)]
618    flow_operations: Option<Value>,
619    #[serde(default)]
620    operation_deferral: Option<Value>,
621    // Kept raw for the same reason as `flow_operations`.
622    #[serde(default)]
623    confirm_operations: Option<Value>,
624    #[serde(default)]
625    rich_ui: Option<RichUiDescriptor>,
626    // `runtime_computed` belongs to --manifest output rather than the retained
627    // manifest model. Deserialize it only long enough to enforce that capability
628    // declarations cannot be omitted as runtime-varying data.
629    #[serde(default)]
630    runtime_computed: Option<Value>,
631    #[serde(default)]
632    role_declarations: Option<Value>,
633    #[serde(default, deserialize_with = "deserialize_provider_declarations")]
634    provider_declarations: Option<ProviderDeclarations>,
635}
636
637impl<'de> Deserialize<'de> for ModuleManifest {
638    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
639    where
640        D: Deserializer<'de>,
641    {
642        let wire = ModuleManifestWire::deserialize(deserializer)?;
643        validate_runtime_computed(wire.runtime_computed.as_ref(), "runtime_computed")
644            .map_err(D::Error::custom)?;
645        validate_events_value(wire.events.as_ref()).map_err(D::Error::custom)?;
646        let events = wire
647            .events
648            .map(serde_json::from_value)
649            .transpose()
650            .map_err(D::Error::custom)?;
651        let mut builder = Self::builder(wire.module_id, wire.module_version)
652            .display_name(wire.display_name)
653            .map_err(D::Error::custom)?
654            .protocol_ver(wire.protocol_ver)
655            .trust_tier(wire.trust_tier);
656        if let Some(icon) = wire.icon {
657            builder = builder.icon(icon).map_err(D::Error::custom)?;
658        }
659        if let Some(hosts) = wire
660            .hosts_third_party_code
661            .as_ref()
662            .and_then(Value::as_bool)
663        {
664            builder = builder.hosts_third_party_code(hosts);
665        }
666        if let Some(ready) = wire.ready {
667            builder = builder.ready(ready);
668        }
669        if let Some(supported) = wire.registration_channel {
670            builder = builder.registration_channel(supported);
671        }
672        builder = builder.provides(wire.provides);
673        validate_operation_metadata(
674            &builder.provides,
675            &wire.operation_titles,
676            &wire.operation_groups,
677            &wire.operation_requires,
678        )
679        .map_err(D::Error::custom)?;
680        builder.operation_titles = wire.operation_titles;
681        builder.operation_groups = wire.operation_groups;
682        builder.operation_requires = wire.operation_requires;
683        let mut manifest = builder
684            .consumes(wire.consumes)
685            .bindings(wire.bindings)
686            .capabilities(wire.capabilities)
687            .events(events)
688            .self_signals(wire.self_signals)
689            .provenance(wire.provenance)
690            .operation_delivery(
691                wire.operation_delivery
692                    .and_then(|value| serde_json::from_value(value).ok())
693                    .unwrap_or_default(),
694            )
695            .rich_ui(wire.rich_ui)
696            .role_declarations(
697                wire.role_declarations
698                    .filter(|value| validate_role_declarations_value(Some(value)).is_ok())
699                    .and_then(|value| serde_json::from_value(value).ok())
700                    .unwrap_or_default(),
701            )
702            .operation_payload(wire.operation_payload)
703            .provider_declarations(wire.provider_declarations)
704            .build();
705        manifest
706            .validate_operation_payload()
707            .map_err(D::Error::custom)?;
708        // Checked against the rest of the decoded manifest, so it runs after
709        // `provides` and `capabilities` are in place. Invalid lists are dropped.
710        manifest.flow_operations = wire
711            .flow_operations
712            .and_then(|value| decode_flow_operations(&manifest, &value).ok());
713        manifest.operation_deferral = wire
714            .operation_deferral
715            .and_then(|value| decode_operation_deferral(&manifest, &value).ok());
716        manifest.confirm_operations = wire
717            .confirm_operations
718            .and_then(|value| decode_confirm_operations(&manifest, &value).ok());
719        manifest
720            .validate_capability_grammar()
721            .map_err(D::Error::custom)?;
722        if let Some(rich_ui) = &manifest.rich_ui {
723            rich_ui.validate().map_err(D::Error::custom)?;
724        }
725        Ok(manifest)
726    }
727}
728
729/// Why a role-declaration map is invalid. HELLO drops it; live updates refuse it.
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct RoleDeclarationsError(&'static str);
732
733impl fmt::Display for RoleDeclarationsError {
734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735        f.write_str(self.0)
736    }
737}
738
739impl std::error::Error for RoleDeclarationsError {}
740
741/// Checks raw HELLO declarations so the daemon can warn before lenient decoding.
742pub fn validate_hello_role_declarations(hello: &Value) -> Result<(), RoleDeclarationsError> {
743    validate_role_declarations_value(
744        hello
745            .get("manifest")
746            .and_then(|manifest| manifest.get("role_declarations")),
747    )
748}
749
750/// Check object shape, capability-name keys and the compact whole-map byte cap.
751/// An absent value is allowed for manifests that omit declarations.
752pub fn validate_role_declarations_value(
753    value: Option<&Value>,
754) -> Result<(), RoleDeclarationsError> {
755    let Some(value) = value else {
756        return Ok(());
757    };
758    let map = value
759        .as_object()
760        .ok_or(RoleDeclarationsError("role_declarations must be an object"))?;
761    for (role, declaration) in map {
762        if !is_valid_capability_identifier(role) {
763            return Err(RoleDeclarationsError(
764                "role_declarations key must use capability-name grammar",
765            ));
766        }
767        if !declaration.is_object() {
768            return Err(RoleDeclarationsError(
769                "role_declarations values must be objects",
770            ));
771        }
772    }
773    let bytes = serde_json::to_vec(value)
774        .map_err(|_| RoleDeclarationsError("role_declarations could not be serialized"))?;
775    if bytes.len() > MAX_ROLE_DECLARATIONS_BYTES {
776        return Err(RoleDeclarationsError(
777            "role_declarations exceeds 16384 compact JSON bytes",
778        ));
779    }
780    Ok(())
781}
782
783/// Opaque metadata locating a provider's rich-UI manifest.
784///
785/// The daemon validates the bounds and lexical shape of each field, then copies
786/// this value unchanged into its catalog. It does not fetch or interpret the
787/// referenced manifest.
788#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
789#[non_exhaustive]
790pub struct RichUiDescriptor {
791    /// Versioned media/schema identifier, such as `ckios.richui.manifest/1`.
792    pub schema: String,
793    /// SHA-256 digest of the provider's encoded rich-UI manifest.
794    pub manifest_digest: String,
795    /// Exact encoded manifest size in bytes.
796    pub bytes: u64,
797    /// Number of chunks required to retrieve the encoded manifest.
798    pub chunks: u32,
799}
800
801impl RichUiDescriptor {
802    /// Constructs a descriptor. The daemon validates it when admitting HELLO.
803    pub fn new(
804        schema: impl Into<String>,
805        manifest_digest: impl Into<String>,
806        bytes: u64,
807        chunks: u32,
808    ) -> Self {
809        Self {
810            schema: schema.into(),
811            manifest_digest: manifest_digest.into(),
812            bytes,
813            chunks,
814        }
815    }
816
817    /// Validate the descriptor's lexical forms and size bounds before relay.
818    pub fn validate(&self) -> Result<(), RichUiDescriptorError> {
819        validate_rich_ui_fields(
820            &self.schema,
821            &self.manifest_digest,
822            self.bytes,
823            u64::from(self.chunks),
824        )
825    }
826}
827
828/// A malformed display name, reported without echoing untrusted text.
829#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct DisplayNameError(&'static str);
831
832impl fmt::Display for DisplayNameError {
833    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834        write!(f, "invalid manifest display_name: {}", self.0)
835    }
836}
837
838impl std::error::Error for DisplayNameError {}
839
840/// Validates display text without trimming or truncating it.
841///
842/// Names contain 1–40 Unicode scalar values, are already trimmed, and contain
843/// neither Unicode Cc controls nor bidi formatting characters.
844pub fn validate_display_name(value: &str) -> Result<(), DisplayNameError> {
845    if value.trim() != value || !(1..=40).contains(&value.chars().count()) {
846        return Err(DisplayNameError(
847            "must be trimmed text of 1 to 40 characters",
848        ));
849    }
850    validate_plain_text(value, 40)
851}
852
853/// Check the module-id rule used at daemon registration, without sanitizing it.
854pub fn validate_module_id(module_id: &str) -> Result<(), String> {
855    if module_id.is_empty() {
856        return Err("empty".to_string());
857    }
858    if module_id.contains('/') || module_id.contains('\\') {
859        return Err("contains a path separator".to_string());
860    }
861    if module_id == "." || module_id == ".." {
862        return Err("is a dot path component".to_string());
863    }
864    if module_id.chars().any(|c| c.is_control()) {
865        return Err("contains a control character".to_string());
866    }
867    if module_id.len() > 255 {
868        return Err("is longer than 255 bytes".to_string());
869    }
870    Ok(())
871}
872
873pub(crate) fn validate_plain_text(value: &str, max: usize) -> Result<(), DisplayNameError> {
874    if value.is_empty() || value.chars().count() > max {
875        return Err(DisplayNameError(
876            "text length is outside the permitted bounds",
877        ));
878    }
879    if value.chars().any(|ch| {
880        ch.is_control()
881            || matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
882    }) {
883        return Err(DisplayNameError("must not contain control or bidi formatting characters"));
884    }
885    Ok(())
886}
887
888/// Checks the display name before HELLO decoding, retaining malformed-field context.
889pub fn validate_hello_display_name(hello: &Value) -> Result<(), DisplayNameError> {
890    match hello
891        .get("manifest")
892        .and_then(|manifest| manifest.get("display_name"))
893    {
894        None | Some(Value::Null) => Ok(()),
895        Some(Value::String(value)) => validate_display_name(value),
896        Some(_) => Err(DisplayNameError("must be a string")),
897    }
898}
899
900/// A malformed icon name, reported without echoing untrusted text.
901#[derive(Debug, Clone, PartialEq, Eq)]
902pub struct IconError(&'static str);
903
904impl fmt::Display for IconError {
905    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906        write!(f, "invalid manifest icon: {}", self.0)
907    }
908}
909
910impl std::error::Error for IconError {}
911
912fn validate_icon(value: &str) -> Result<(), IconError> {
913    if !(1..=64).contains(&value.len())
914        || !value.split('-').all(|part| {
915            !part.is_empty()
916                && part
917                    .bytes()
918                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
919        })
920    {
921        return Err(IconError(
922            "must be 1 to 64 characters matching ^[a-z0-9]+(-[a-z0-9]+)*$",
923        ));
924    }
925    Ok(())
926}
927
928/// Checks the icon before HELLO decoding so a wrong JSON type identifies the field.
929pub fn validate_hello_icon(hello: &Value) -> Result<(), IconError> {
930    match hello
931        .get("manifest")
932        .and_then(|manifest| manifest.get("icon"))
933    {
934        None | Some(Value::Null) => Ok(()),
935        Some(Value::String(value)) => validate_icon(value),
936        Some(_) => Err(IconError("must be a string")),
937    }
938}
939
940/// A malformed operation title, reported without echoing untrusted text.
941#[derive(Debug, Clone, PartialEq, Eq)]
942pub struct OperationTitleError(&'static str);
943
944impl fmt::Display for OperationTitleError {
945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
946        write!(f, "invalid manifest operation_titles: {}", self.0)
947    }
948}
949
950impl std::error::Error for OperationTitleError {}
951
952fn validate_operation_title(
953    provides: &[ProviderRole],
954    name: &str,
955    title: &str,
956) -> Result<(), OperationTitleError> {
957    validate_display_name(title).map_err(|error| OperationTitleError(error.0))?;
958    if !declares_management_operation(provides, name) {
959        return Err(OperationTitleError(
960            "keys must name declared management operations",
961        ));
962    }
963    Ok(())
964}
965
966/// A group of management operations presented together to a person.
967#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968#[non_exhaustive]
969pub struct OperationGroup {
970    pub title: String,
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub description: Option<String>,
973    pub operations: Vec<String>,
974}
975
976impl OperationGroup {
977    /// Constructs a group. The manifest builder validates it against the other
978    /// groups and the manifest's declared management operations.
979    pub fn new(
980        title: impl Into<String>,
981        description: Option<String>,
982        operations: Vec<String>,
983    ) -> Self {
984        Self {
985            title: title.into(),
986            description,
987            operations,
988        }
989    }
990}
991
992/// A malformed operation metadata field, without untrusted values in the error.
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct OperationMetadataError {
995    field: &'static str,
996    reason: &'static str,
997}
998
999impl fmt::Display for OperationMetadataError {
1000    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001        write!(f, "invalid manifest {}: {}", self.field, self.reason)
1002    }
1003}
1004
1005impl std::error::Error for OperationMetadataError {}
1006
1007fn validate_operation_group(
1008    provides: &[ProviderRole],
1009    id: &str,
1010    group: &OperationGroup,
1011    assigned: &HashSet<&str>,
1012) -> Result<(), OperationMetadataError> {
1013    let invalid = |reason| OperationMetadataError {
1014        field: "operation_groups",
1015        reason,
1016    };
1017    if !(1..=40).contains(&id.len())
1018        || !id
1019            .bytes()
1020            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'))
1021    {
1022        return Err(invalid(
1023            "ids must contain 1 to 40 lowercase ASCII letters, digits or underscores",
1024        ));
1025    }
1026    validate_display_name(&group.title).map_err(|error| invalid(error.0))?;
1027    if group.operations.is_empty() {
1028        return Err(invalid("each group must contain at least one operation"));
1029    }
1030    for operation in &group.operations {
1031        if !declares_management_operation(provides, operation) {
1032            return Err(invalid(
1033                "groups may contain only declared management operations",
1034            ));
1035        }
1036        if assigned.contains(operation.as_str()) {
1037            return Err(invalid("an operation may belong to at most one group"));
1038        }
1039    }
1040    Ok(())
1041}
1042
1043fn validate_operation_requires(
1044    provides: &[ProviderRole],
1045    name: &str,
1046    requires: &[String],
1047) -> Result<(), OperationMetadataError> {
1048    let invalid = |reason| OperationMetadataError {
1049        field: "operation_requires",
1050        reason,
1051    };
1052    if !declares_management_operation(provides, name) {
1053        return Err(invalid("keys must name declared management operations"));
1054    }
1055    for dependency in requires {
1056        if let Some((module_id, operation)) = dependency.split_once('/') {
1057            if module_id.is_empty() || operation.is_empty() {
1058                return Err(invalid(
1059                    "foreign references must have a module id and operation name",
1060                ));
1061            }
1062        } else if dependency == name {
1063            return Err(invalid("an operation cannot require itself"));
1064        } else if !declares_management_operation(provides, dependency) {
1065            return Err(invalid(
1066                "local references must name declared management operations",
1067            ));
1068        }
1069    }
1070    Ok(())
1071}
1072
1073fn validate_operation_metadata(
1074    provides: &[ProviderRole],
1075    titles: &BTreeMap<String, String>,
1076    groups: &BTreeMap<String, OperationGroup>,
1077    requires: &BTreeMap<String, Vec<String>>,
1078) -> Result<(), OperationMetadataError> {
1079    for (name, title) in titles {
1080        validate_operation_title(provides, name, title).map_err(|error| {
1081            OperationMetadataError {
1082                field: "operation_titles",
1083                reason: error.0,
1084            }
1085        })?;
1086    }
1087    let mut assigned = HashSet::new();
1088    for (id, group) in groups {
1089        validate_operation_group(provides, id, group, &assigned)?;
1090        assigned.extend(group.operations.iter().map(String::as_str));
1091    }
1092    for (name, dependencies) in requires {
1093        validate_operation_requires(provides, name, dependencies)?;
1094    }
1095    Ok(())
1096}
1097
1098fn decode_hello_operation_map<T: serde::de::DeserializeOwned>(
1099    manifest: &Value,
1100    field: &'static str,
1101    reason: &'static str,
1102) -> Result<BTreeMap<String, T>, OperationMetadataError> {
1103    match manifest.get(field) {
1104        Some(value) => {
1105            BTreeMap::deserialize(value).map_err(|_| OperationMetadataError { field, reason })
1106        }
1107        None => Ok(BTreeMap::new()),
1108    }
1109}
1110
1111/// Checks operation metadata before HELLO decoding so refusals name the field.
1112pub fn validate_hello_operation_metadata(hello: &Value) -> Result<(), OperationMetadataError> {
1113    let Some(manifest) = hello.get("manifest") else {
1114        return Ok(());
1115    };
1116    let titles = decode_hello_operation_map(
1117        manifest,
1118        "operation_titles",
1119        "must be an object with string titles",
1120    )?;
1121    let groups = decode_hello_operation_map(
1122        manifest,
1123        "operation_groups",
1124        "must be an object with group values",
1125    )?;
1126    let requires = decode_hello_operation_map(
1127        manifest,
1128        "operation_requires",
1129        "must be an object with lists of operation names",
1130    )?;
1131    if titles.is_empty() && groups.is_empty() && requires.is_empty() {
1132        return Ok(());
1133    }
1134    // Let normal HELLO decoding report malformed role declarations.
1135    let Some(provides) = manifest
1136        .get("provides")
1137        .and_then(|value| Vec::<ProviderRole>::deserialize(value).ok())
1138    else {
1139        return Ok(());
1140    };
1141    validate_operation_metadata(&provides, &titles, &groups, &requires)
1142}
1143
1144/// A safe-to-report rich-UI descriptor failure, without echoing untrusted values.
1145#[derive(Debug, Clone, PartialEq, Eq)]
1146#[non_exhaustive]
1147pub struct RichUiDescriptorError {
1148    field: String,
1149    reason: &'static str,
1150}
1151
1152impl RichUiDescriptorError {
1153    fn new(field: impl Into<String>, reason: &'static str) -> Self {
1154        Self {
1155            field: field.into(),
1156            reason,
1157        }
1158    }
1159
1160    /// The precise malformed field path, relative to the manifest.
1161    pub fn field(&self) -> &str {
1162        &self.field
1163    }
1164}
1165
1166impl fmt::Display for RichUiDescriptorError {
1167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168        write!(
1169            f,
1170            "invalid rich_ui descriptor: field {} {}",
1171            self.field, self.reason
1172        )
1173    }
1174}
1175
1176impl std::error::Error for RichUiDescriptorError {}
1177
1178/// Validates the descriptor in a raw HELLO before serde loses field context.
1179pub fn validate_hello_rich_ui_descriptor(hello: &Value) -> Result<(), RichUiDescriptorError> {
1180    let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1181        return Ok(());
1182    };
1183    let Some(value) = manifest.get("rich_ui") else {
1184        return Ok(());
1185    };
1186    validate_rich_ui_descriptor_value(value)
1187}
1188
1189fn validate_rich_ui_descriptor_value(value: &Value) -> Result<(), RichUiDescriptorError> {
1190    let descriptor = value
1191        .as_object()
1192        .ok_or_else(|| RichUiDescriptorError::new("rich_ui", "must be an object"))?;
1193    let schema = descriptor
1194        .get("schema")
1195        .and_then(Value::as_str)
1196        .ok_or_else(|| RichUiDescriptorError::new("rich_ui.schema", "must be a string"))?;
1197    let digest = descriptor
1198        .get("manifest_digest")
1199        .and_then(Value::as_str)
1200        .ok_or_else(|| RichUiDescriptorError::new("rich_ui.manifest_digest", "must be a string"))?;
1201    let bytes = descriptor
1202        .get("bytes")
1203        .and_then(Value::as_u64)
1204        .ok_or_else(|| {
1205            RichUiDescriptorError::new("rich_ui.bytes", "must be an integer from 1 to 16777216")
1206        })?;
1207    let chunks = descriptor
1208        .get("chunks")
1209        .and_then(Value::as_u64)
1210        .ok_or_else(|| {
1211            RichUiDescriptorError::new("rich_ui.chunks", "must be an integer from 1 to 1024")
1212        })?;
1213    validate_rich_ui_fields(schema, digest, bytes, chunks)
1214}
1215
1216fn validate_rich_ui_fields(
1217    schema: &str,
1218    digest: &str,
1219    bytes: u64,
1220    chunks: u64,
1221) -> Result<(), RichUiDescriptorError> {
1222    if !(1..=64).contains(&schema.len())
1223        || !schema.bytes().all(|byte| {
1224            byte.is_ascii_lowercase()
1225                || byte.is_ascii_digit()
1226                || matches!(byte, b'.' | b'_' | b'/' | b'-')
1227        })
1228    {
1229        return Err(RichUiDescriptorError::new(
1230            "rich_ui.schema",
1231            "must be 1 to 64 bytes of [a-z0-9._/-]",
1232        ));
1233    }
1234    if !digest.strip_prefix("sha256:").is_some_and(|hex| {
1235        hex.len() == 64
1236            && hex
1237                .bytes()
1238                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1239    }) {
1240        return Err(RichUiDescriptorError::new(
1241            "rich_ui.manifest_digest",
1242            "must be sha256: followed by 64 lowercase hexadecimal characters",
1243        ));
1244    }
1245    if !(1..=16_777_216).contains(&bytes) {
1246        return Err(RichUiDescriptorError::new(
1247            "rich_ui.bytes",
1248            "must be an integer from 1 to 16777216",
1249        ));
1250    }
1251    if !(1..=1_024).contains(&chunks) {
1252        return Err(RichUiDescriptorError::new(
1253            "rich_ui.chunks",
1254            "must be an integer from 1 to 1024",
1255        ));
1256    }
1257    Ok(())
1258}
1259
1260/// The `server.describe` capability a daemon advertises when `catalog.list`
1261/// carries each module's declared `events`. Without it, an entry with no
1262/// `events` cannot tell "this module declares none" from "this daemon never
1263/// reports them", so a consumer that acts on declared events checks for this
1264/// first.
1265pub const CAP_CATALOG_EVENTS_V1: &str = "catalog-events/v1";
1266
1267/// A daemon advertising this capability stores scope `bind_proof_sha256` hashes
1268/// and enforces `bind_proof` on scoped route opens. A scope owner should set the
1269/// hash only when the daemon it is connected to advertises this capability.
1270pub const CAP_SCOPE_BIND_PROOF_V1: &str = "scope-bind-proof/v1";
1271
1272/// Bind proofs are required only from non-attested openers; reserved modules
1273/// are exempt. Owners relying on this exemption should set `bind_proof_sha256`
1274/// only when the connected daemon advertises this capability.
1275pub const CAP_SCOPE_BIND_PROOF_V2: &str = "scope-bind-proof/v2";
1276
1277/// Atomic idle-only scope rotation and connection-held scope presence.
1278pub const CAP_SCOPE_REPLACE_IF_IDLE_V1: &str = "scope-replace-if-idle/v1";
1279
1280/// A versioned bus event notice whose body is served by the publisher.
1281#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1282#[non_exhaustive]
1283pub struct EventDeclaration {
1284    /// One to four dot-separated NATS subject tokens, each
1285    /// `[a-z0-9][a-z0-9_]{0,62}`. Levels shaped like `v` followed by digits
1286    /// are reserved for the event subject's version.
1287    ///
1288    /// This matches `cortexkit-bus-naming` 0.2.6,
1289    /// [`token.rs`, lines 91–121](https://docs.rs/cortexkit-bus-naming/0.2.6/src/cortexkit_bus_naming/token.rs.html#91-121).
1290    pub name: String,
1291    /// Event schema version, at least 1.
1292    pub version: u32,
1293    /// Header names a notice of this event may carry, for filtering only, never
1294    /// authority. A notice omits a header it has no value for, and never sends
1295    /// one empty or invented, so a filter on a missing header does not match.
1296    /// Names match `[a-z][a-z0-9_]{0,31}` and are unique within the declaration.
1297    pub headers: Vec<String>,
1298    /// Short human line for consent cards, at most 200 characters without controls.
1299    #[serde(default, skip_serializing_if = "Option::is_none")]
1300    pub summary: Option<String>,
1301}
1302
1303impl EventDeclaration {
1304    /// Starts an event declaration with no filter headers or summary.
1305    /// Validation happens when decoding a manifest or admitting its HELLO.
1306    pub fn new(name: impl Into<String>, version: u32) -> Self {
1307        Self {
1308            name: name.into(),
1309            version,
1310            headers: Vec::new(),
1311            summary: None,
1312        }
1313    }
1314
1315    /// Sets the header names a notice of this event may carry.
1316    pub fn with_headers(mut self, headers: Vec<String>) -> Self {
1317        self.headers = headers;
1318        self
1319    }
1320
1321    /// Sets or removes the short human summary.
1322    pub fn with_summary(mut self, summary: Option<String>) -> Self {
1323        self.summary = summary;
1324        self
1325    }
1326}
1327
1328/// A safe-to-report event declaration failure, without echoing untrusted values.
1329#[derive(Debug, Clone, PartialEq, Eq)]
1330#[non_exhaustive]
1331pub struct EventDeclarationError {
1332    field: String,
1333    reason: &'static str,
1334}
1335
1336impl EventDeclarationError {
1337    fn new(field: impl Into<String>, reason: &'static str) -> Self {
1338        Self {
1339            field: field.into(),
1340            reason,
1341        }
1342    }
1343
1344    /// The precise malformed field path, relative to the manifest.
1345    pub fn field(&self) -> &str {
1346        &self.field
1347    }
1348}
1349
1350impl fmt::Display for EventDeclarationError {
1351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1352        write!(
1353            f,
1354            "invalid event declaration: field {} {}",
1355            self.field, self.reason
1356        )
1357    }
1358}
1359
1360impl std::error::Error for EventDeclarationError {}
1361
1362/// Validates event declarations before HELLO decoding can lose field context.
1363pub fn validate_hello_event_declarations(hello: &Value) -> Result<(), EventDeclarationError> {
1364    validate_events_value(
1365        hello
1366            .get("manifest")
1367            .and_then(|manifest| manifest.get("events")),
1368    )
1369}
1370
1371/// Matches `cortexkit-bus-naming` 0.2.6's event-name grammar. Keep manifest
1372/// declarations aligned with the names accepted in bus subjects.
1373fn is_valid_event_name(name: &str) -> bool {
1374    let level_count = name.split('.').count();
1375    (1..=4).contains(&level_count)
1376        && name.split('.').all(|level| {
1377            if level.is_empty() {
1378                return false;
1379            }
1380            let first = level.as_bytes()[0];
1381            (1..=63).contains(&level.len())
1382                && (first.is_ascii_lowercase() || first.is_ascii_digit())
1383                && level
1384                    .bytes()
1385                    .skip(1)
1386                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1387                && !level.strip_prefix('v').is_some_and(|digits| {
1388                    !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
1389                })
1390        })
1391}
1392
1393fn validate_events_value(value: Option<&Value>) -> Result<(), EventDeclarationError> {
1394    let Some(value) = value.filter(|value| !value.is_null()) else {
1395        return Ok(());
1396    };
1397    let entries = value
1398        .as_array()
1399        .ok_or_else(|| EventDeclarationError::new("events", "must be a list"))?;
1400    if entries.len() > 64 {
1401        return Err(EventDeclarationError::new(
1402            "events",
1403            "must contain at most 64 declarations",
1404        ));
1405    }
1406    let mut pairs = HashSet::new();
1407    for (index, entry) in entries.iter().enumerate() {
1408        let field = format!("events[{index}]");
1409        let entry = entry
1410            .as_object()
1411            .ok_or_else(|| EventDeclarationError::new(&field, "must be an object"))?;
1412        let name_field = format!("{field}.name");
1413        let name = entry
1414            .get("name")
1415            .and_then(Value::as_str)
1416            .ok_or_else(|| EventDeclarationError::new(&name_field, "must be a string"))?;
1417        if !is_valid_event_name(name) {
1418            return Err(EventDeclarationError::new(
1419                name_field,
1420                "must contain one to four valid dot-separated event-name levels",
1421            ));
1422        }
1423        let version = entry
1424            .get("version")
1425            .and_then(Value::as_u64)
1426            .filter(|version| (1..=u32::MAX as u64).contains(version))
1427            .ok_or_else(|| {
1428                EventDeclarationError::new(
1429                    format!("{field}.version"),
1430                    "must be an integer between 1 and u32::MAX",
1431                )
1432            })?;
1433        if !pairs.insert((name, version)) {
1434            return Err(EventDeclarationError::new(
1435                &field,
1436                "duplicates an event (name, version) pair",
1437            ));
1438        }
1439        let headers_field = format!("{field}.headers");
1440        let headers = entry
1441            .get("headers")
1442            .and_then(Value::as_array)
1443            .ok_or_else(|| EventDeclarationError::new(&headers_field, "must be a list"))?;
1444        if headers.len() > 16 {
1445            return Err(EventDeclarationError::new(
1446                headers_field,
1447                "must contain at most 16 headers",
1448            ));
1449        }
1450        let mut names = HashSet::new();
1451        for (header_index, header) in headers.iter().enumerate() {
1452            let header_field = format!("{headers_field}[{header_index}]");
1453            let header = header
1454                .as_str()
1455                .ok_or_else(|| EventDeclarationError::new(&header_field, "must be a string"))?;
1456            if !(1..=32).contains(&header.len())
1457                || !header.as_bytes()[0].is_ascii_lowercase()
1458                || !header
1459                    .bytes()
1460                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1461            {
1462                return Err(EventDeclarationError::new(
1463                    header_field,
1464                    "must match [a-z][a-z0-9_]{0,31}",
1465                ));
1466            }
1467            if !names.insert(header) {
1468                return Err(EventDeclarationError::new(
1469                    header_field,
1470                    "duplicates a header name",
1471                ));
1472            }
1473        }
1474        if let Some(summary) = entry.get("summary").filter(|value| !value.is_null()) {
1475            let summary_field = format!("{field}.summary");
1476            let summary = summary
1477                .as_str()
1478                .ok_or_else(|| EventDeclarationError::new(&summary_field, "must be a string"))?;
1479            if summary.chars().count() > 200 || summary.chars().any(char::is_control) {
1480                return Err(EventDeclarationError::new(
1481                    summary_field,
1482                    "must contain at most 200 characters and no control characters",
1483                ));
1484            }
1485        }
1486    }
1487    Ok(())
1488}
1489
1490/// A raw HELLO declaration error that can be reported before serde drops context.
1491#[derive(Debug, Clone, PartialEq, Eq)]
1492pub struct SelfSignalDeclarationError {
1493    module_id: String,
1494    entry_index: usize,
1495    field: &'static str,
1496}
1497
1498impl fmt::Display for SelfSignalDeclarationError {
1499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1500        write!(
1501            f,
1502            "module_id '{}' self_signals[{}] is missing required field '{}'",
1503            self.module_id.escape_debug(),
1504            self.entry_index,
1505            self.field
1506        )
1507    }
1508}
1509
1510/// Reject raw HELLO self-signal declarations that omit `effect` or `anchored_to`.
1511///
1512/// Serde correctly rejects these omissions while decoding [`ModuleManifest`], but
1513/// that decode does not retain the module id or list index needed for a useful
1514/// daemon refusal. This preflight adds only that reporting context; it does not
1515/// interpret a declaration's behavior.
1516pub fn validate_hello_self_signal_declarations(
1517    hello: &Value,
1518) -> Result<(), SelfSignalDeclarationError> {
1519    let Some(manifest) = hello.get("manifest").and_then(Value::as_object) else {
1520        return Ok(());
1521    };
1522    let module_id = manifest
1523        .get("module_id")
1524        .and_then(Value::as_str)
1525        .unwrap_or("<unknown>");
1526    let Some(entries) = manifest.get("self_signals").and_then(Value::as_array) else {
1527        return Ok(());
1528    };
1529
1530    for (entry_index, entry) in entries.iter().enumerate() {
1531        let Some(entry) = entry.as_object() else {
1532            continue;
1533        };
1534        for field in ["effect", "anchored_to"] {
1535            if !entry.contains_key(field) {
1536                return Err(SelfSignalDeclarationError {
1537                    module_id: module_id.to_string(),
1538                    entry_index,
1539                    field,
1540                });
1541            }
1542        }
1543    }
1544    Ok(())
1545}
1546
1547/// Static, versioned capabilities declared by a module.
1548#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1549#[serde(deny_unknown_fields)]
1550pub struct CapabilityDeclarations {
1551    #[serde(default)]
1552    pub provides: Vec<String>,
1553    #[serde(default)]
1554    pub requires: Vec<CapabilityRequirement>,
1555    #[serde(default)]
1556    pub must_never_reach: Vec<String>,
1557}
1558
1559/// A declared periodic or event-driven behavior that shapes an external surface.
1560#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1561pub struct SelfSignalDeclaration {
1562    /// Stable identifier for this declared behavior, such as `codex_keepalive`.
1563    pub name: String,
1564    /// Signal classification. `Busy` participates in drain quiescence; the
1565    /// remaining kinds are descriptive for operators and analysts.
1566    ///
1567    /// # A `Busy` GAUGE COUNTS WORK THE DRAIN CAN AFFECT, AND NOTHING ELSE
1568    ///
1569    /// The daemon waits for every declared `Busy` gauge to reach zero before
1570    /// tearing a module down, up to the drain ceiling. That wait is only worth
1571    /// anything for work whose RESULT WOULD BE DELIVERED if it finished during
1572    /// the drain.
1573    ///
1574    /// The test: **if this request completed one millisecond before the
1575    /// teardown, would anyone receive its answer?** If no, it does not belong
1576    /// in a `Busy` gauge, and counting it makes the daemon wait out its whole
1577    /// ceiling for something that cannot usefully complete.
1578    ///
1579    /// The case that names the rule (CEREB, 2026-09-19): cerebellum's
1580    /// management requests can park for up to 300 s awaiting a HUMAN's consent
1581    /// decision. Those were counted as in-flight, so a drain begun while a
1582    /// prompt was open waited on a person until the 30 s ceiling expired --
1583    /// and the pending answer dies with the process either way, so the wait
1584    /// bought nothing. The fix splits the accounting: `executing` counts toward
1585    /// `Busy`, `awaiting_consent` is reported as its own informational gauge.
1586    ///
1587    /// The same shape exists anywhere a request blocks on an external party the
1588    /// restart invalidates -- a human, a peer seat, a vendor call whose reply
1589    /// has nowhere to land. Those are legitimately IN FLIGHT and are not
1590    /// legitimately `Busy`.
1591    pub kind: SelfSignalKind,
1592    /// Whether the signal only observes the surface or changes it.
1593    pub effect: SelfSignalEffect,
1594    /// The cadence, event, or health gauges that anchor this signal.
1595    pub anchored_to: SignalAnchor,
1596    /// The effective cadence in force at HELLO time.
1597    ///
1598    /// Use [`SignalCadence::Literal`] when a compile-time constant is the
1599    /// effective value. Use [`SignalCadence::Derived`] when configuration or
1600    /// another runtime input resolves the effective value, naming the source so
1601    /// the declaration cannot silently drift from that resolution.
1602    #[serde(default, skip_serializing_if = "Option::is_none")]
1603    pub cadence: Option<SignalCadence>,
1604    /// The external surface this behavior shapes, such as `provider-usage`.
1605    #[serde(default, skip_serializing_if = "Option::is_none")]
1606    pub domain: Option<String>,
1607    #[serde(default, skip_serializing_if = "Option::is_none")]
1608    pub note: Option<String>,
1609}
1610
1611/// Class of a self-signal, tolerant of newer wire values.
1612#[derive(Debug, Clone, PartialEq, Eq)]
1613pub enum SelfSignalKind {
1614    Keepalive,
1615    /// Work that must settle before the daemon considers a module quiescent.
1616    Busy,
1617    Poller,
1618    Cron,
1619    Sweep,
1620    Watchdog,
1621    Heartbeat,
1622    Other(String),
1623}
1624
1625impl SelfSignalKind {
1626    fn wire_name(&self) -> &str {
1627        match self {
1628            Self::Keepalive => "keepalive",
1629            Self::Busy => "busy",
1630            Self::Poller => "poller",
1631            Self::Cron => "cron",
1632            Self::Sweep => "sweep",
1633            Self::Watchdog => "watchdog",
1634            Self::Heartbeat => "heartbeat",
1635            Self::Other(value) => value,
1636        }
1637    }
1638}
1639
1640impl Serialize for SelfSignalKind {
1641    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1642    where
1643        S: serde::Serializer,
1644    {
1645        serializer.serialize_str(self.wire_name())
1646    }
1647}
1648
1649impl<'de> Deserialize<'de> for SelfSignalKind {
1650    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1651    where
1652        D: Deserializer<'de>,
1653    {
1654        let value = String::deserialize(deserializer)?;
1655        Ok(match value.as_str() {
1656            "keepalive" => Self::Keepalive,
1657            "busy" => Self::Busy,
1658            "poller" => Self::Poller,
1659            "cron" => Self::Cron,
1660            "sweep" => Self::Sweep,
1661            "watchdog" => Self::Watchdog,
1662            "heartbeat" => Self::Heartbeat,
1663            _ => Self::Other(value),
1664        })
1665    }
1666}
1667
1668/// The effect a self-signal has on the external surface it targets.
1669#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1670#[serde(rename_all = "lowercase")]
1671pub enum SelfSignalEffect {
1672    Observe,
1673    Mutate,
1674}
1675
1676/// What anchors a self-signal to an interval, event, or health state.
1677#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1678#[serde(rename_all = "snake_case")]
1679pub enum SignalAnchor {
1680    /// The behavior follows its own periodic signature, so analysts can find it
1681    /// without an external event grid.
1682    FixedInterval,
1683    /// The behavior follows an external event boundary, which can make its shape
1684    /// indistinguishable from the surface mechanism without this declaration.
1685    Event { event: String },
1686    /// Health metrics whose non-negative integer values are summed during drain.
1687    HealthGauges { gauges: Vec<String> },
1688}
1689
1690/// How a self-signal's effective cadence is declared.
1691#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1692#[serde(rename_all = "snake_case")]
1693pub enum SignalCadence {
1694    Literal { interval_ms: u64 },
1695    Derived { source: String },
1696}
1697
1698/// Build facts a module DECLARES about its own binary at HELLO. The daemon
1699/// overlays process-identity evidence it alone can attest; the two halves are
1700/// served together via `supervisor.provenance` and never merged.
1701///
1702/// The canonical constructor form is a full 40-character lowercase hexadecimal
1703/// `build_git_sha` and a full 64-character lowercase hexadecimal
1704/// `build_lock_digest`; abbreviations are not conforming. The daemon's HELLO
1705/// decoder intentionally remains lenient enough to relay older declarations,
1706/// so this construction contract is enforced by [`build_provenance`] rather
1707/// than by wire deserialization.
1708///
1709/// Honesty contract for constructors (ruled with the first adopters):
1710/// - Every field is a VERIFIED-AT-BUILD claim. No field is required: a module
1711///   may declare any subset, and omitting an inapplicable field is the honest
1712///   choice rather than inventing a value to fill it. Populate `build_git_sha`
1713///   only from a value injected by the build/release pipeline (`CK_BUILD_REV`
1714///   via `option_env!` guarded by the packaging path, or build.rs equivalent)
1715///   — never from ambient env at an arbitrary consumer compile, which mints a
1716///   provenance claim from an accident of whoever ran cargo. A builder that
1717///   can determine whether the tree was clean may declare the sha regardless
1718///   of whether a release pipeline exists.
1719/// - Dirty or unstamped builds declare `None` for the affected fields. A
1720///   populated field stops the reader asking; absent-and-honest beats
1721///   present-and-best-effort. Absence is reported at two levels with two
1722///   distinct words: a module that declared no provenance block at all reads
1723///   `unverifiable`, while an omitted field inside a declared block is
1724///   dropped from the wire and reads `unavailable`. So omitting a field never
1725///   costs a module its `Reported` status -- declaration is decided by
1726///   whether the manifest carried a block, not by which fields it filled.
1727/// - Dirty-tree stamps are not canonical `build_git_sha` values. A pipeline
1728///   that emits `-dirty` must omit the affected field rather than pass that
1729///   stamp to the canonical constructor. Stricter is better: cerebellum's
1730///   build.rs reports the commit ONLY when the tree was clean, on the argument
1731///   that dirty bytes match no commit and a precise-looking wrong answer beats
1732///   absence at being believed.
1733/// - Two silent-when-wrong checks for any build-rev embedder (CEREB): does
1734///   the builder know whether the tree was clean, and can its no-git sentinel
1735///   (source-tarball builds) escape into a field parsed as a sha? Sentinels
1736///   render as absence, never as a value.
1737/// - Fill fields FROM THE BUILD only: reading Cargo.lock or the wire crate
1738///   version inside the manifest constructor describes the source tree
1739///   sitting beside the running binary, not the binary — the exact claim
1740///   this struct exists to avoid.
1741/// - Declare what you KNOW, not blanket-None (WERNI): `store_schema_version`
1742///   needs no pipeline — any module with a migration list can state its
1743///   newest migration as fact, and a daemon comparing it against the store's
1744///   actual version sees a stale-binary mismatch directly. Blanket `None`
1745///   where a field is knowable wastes the field; blanket-fill where it is
1746///   not mints a lie. Absence also beats sentinel values (CKCRED): omit the
1747///   FIELD when BUILD_REV reads a builder sentinel ("unknown", "unavailable",
1748///   "none", any casing) — publishing the sentinel string as a fact is a
1749///   well-formed lie shape validation cannot catch. Field omission, not block
1750///   omission, is the target shape for SDK modules: `wire_crate_version` is a
1751///   compile-time constant of the linked crate, so a module using the SDK
1752///   always has at least one honest fact and `build_provenance` reflects that
1753///   by never returning an absent block. (Block absence remains meaningful on
1754///   the wire — it reads `unverifiable`, the module made no claim — but it is
1755///   the shape for non-adopters and proxied manifests, not a target for
1756///   declarers; see #78.) The hazard in one sentence, for every referent and
1757///   sentinel case alike: A PRESENT, WELL-FORMED FIELD STOPS THE READER
1758///   ASKING — a value from the wrong domain and a sentinel from the wrong
1759///   vocabulary are indistinguishable from a correct value to every check
1760///   that inspects shape rather than meaning.
1761/// - PROXIED MANIFESTS STAY None PERMANENTLY (CALLO): a process that
1762///   forwards another machine's manifest cannot observe that build, and a
1763///   forwarded provenance claim is indistinguishable on the wire from a
1764///   verified one — filling it launders an unverifiable assertion. Same
1765///   reasoning as pinning a re-exported module's trust_tier to Untrusted.
1766///   Record that at the construction site: injection-wiring sweeps grep for
1767///   `provenance:` and the obvious action at a re-export site is the wrong
1768///   one.
1769///
1770/// `#[non_exhaustive]`: a new provenance fact must not break the modules that
1771/// build this block, so construct it with [`ManifestProvenance::new`] and the
1772/// `with_*` setters (or the `build_provenance*` helpers), never a struct
1773/// literal.
1774#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)]
1775#[non_exhaustive]
1776pub struct ManifestProvenance {
1777    #[serde(default, skip_serializing_if = "Option::is_none")]
1778    pub build_git_sha: Option<String>,
1779    /// Why `build_git_sha` is unavailable. This is absent when the commit is
1780    /// declared, and remains open so future causes do not make readers reject
1781    /// the enclosing provenance declaration.
1782    #[serde(default, skip_serializing_if = "Option::is_none")]
1783    pub build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1784    #[serde(default, skip_serializing_if = "Option::is_none")]
1785    pub build_lock_digest: Option<String>,
1786    /// REFERENT: the `subc-protocol` crate version linked into this binary
1787    /// (`subc_protocol::SUBC_PROTOCOL_CRATE_VERSION`) — the fleet's shared
1788    /// wire vocabulary, one numbering space for every module. Never a
1789    /// module's own envelope/payload crate version: that is real information
1790    /// in a different numbering space, and here it scores as a confident
1791    /// wrong answer at any census gate. (QTA's rule, learned live: a field
1792    /// whose entire content is a referent cannot be documented by its
1793    /// constraints — so the referent is stated here, where readers look.)
1794    #[serde(default, skip_serializing_if = "Option::is_none")]
1795    pub wire_crate_version: Option<String>,
1796    #[serde(default, skip_serializing_if = "Option::is_none")]
1797    pub store_schema_version: Option<String>,
1798    /// Where the running module read its launch nonce from: `fd` (the pipe
1799    /// the daemon hands over as descriptor 3), `pipe` (the Windows named pipe),
1800    /// or `env` (the environment
1801    /// variable kept while modules move to the pipe). Absent means the module
1802    /// did not say. This is a fact about the running process, not the build.
1803    #[serde(default, skip_serializing_if = "Option::is_none")]
1804    pub launch_nonce_source: Option<LaunchNonceSource>,
1805}
1806
1807/// Where a module read its launch nonce from, as reported in
1808/// [`ManifestProvenance::launch_nonce_source`].
1809///
1810/// An open string enum, like [`BuildGitShaAbsenceReason`]: a value this crate
1811/// does not know decodes as `ForwardCompatibleUnknown` instead of making the
1812/// whole provenance block, and with it the module's HELLO, fail to decode.
1813#[derive(Debug, Clone, PartialEq, Eq)]
1814#[non_exhaustive]
1815pub enum LaunchNonceSource {
1816    /// Read from the inherited descriptor the daemon passes.
1817    Fd,
1818    /// Read from the PID-authenticated Windows named pipe.
1819    Pipe,
1820    /// Read from the `SUBC_LAUNCH_NONCE` environment variable.
1821    Env,
1822    ForwardCompatibleUnknown(String),
1823}
1824
1825impl LaunchNonceSource {
1826    /// The value as it appears on the wire.
1827    pub fn wire_name(&self) -> &str {
1828        match self {
1829            Self::Fd => "fd",
1830            Self::Pipe => "pipe",
1831            Self::Env => "env",
1832            Self::ForwardCompatibleUnknown(value) => value,
1833        }
1834    }
1835
1836    /// The source a wire value names; unknown values are kept as they are.
1837    pub fn from_wire_name(value: &str) -> Self {
1838        match value {
1839            "fd" => Self::Fd,
1840            "pipe" => Self::Pipe,
1841            "env" => Self::Env,
1842            _ => Self::ForwardCompatibleUnknown(value.to_string()),
1843        }
1844    }
1845}
1846
1847impl Serialize for LaunchNonceSource {
1848    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1849    where
1850        S: serde::Serializer,
1851    {
1852        serializer.serialize_str(self.wire_name())
1853    }
1854}
1855
1856impl<'de> Deserialize<'de> for LaunchNonceSource {
1857    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1858    where
1859        D: serde::Deserializer<'de>,
1860    {
1861        let value = String::deserialize(deserializer)?;
1862        Ok(Self::from_wire_name(&value))
1863    }
1864}
1865
1866/// A build pipeline's reason for omitting `build_git_sha`.
1867///
1868/// This is an open string enum: consumers preserve a future reason instead of
1869/// rejecting the enclosing provenance declaration.
1870#[derive(Debug, Clone, PartialEq, Eq)]
1871pub enum BuildGitShaAbsenceReason {
1872    DeclinedDirty,
1873    NeverDerived,
1874    NoGitDir,
1875    ForwardCompatibleUnknown(String),
1876}
1877
1878impl BuildGitShaAbsenceReason {
1879    fn wire_name(&self) -> &str {
1880        match self {
1881            Self::DeclinedDirty => "declined_dirty",
1882            Self::NeverDerived => "never_derived",
1883            Self::NoGitDir => "no_git_dir",
1884            Self::ForwardCompatibleUnknown(value) => value,
1885        }
1886    }
1887}
1888
1889impl Serialize for BuildGitShaAbsenceReason {
1890    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1891    where
1892        S: serde::Serializer,
1893    {
1894        serializer.serialize_str(self.wire_name())
1895    }
1896}
1897
1898impl<'de> Deserialize<'de> for BuildGitShaAbsenceReason {
1899    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1900    where
1901        D: serde::Deserializer<'de>,
1902    {
1903        let value = String::deserialize(deserializer)?;
1904        Ok(match value.as_str() {
1905            "declined_dirty" => Self::DeclinedDirty,
1906            "never_derived" => Self::NeverDerived,
1907            "no_git_dir" => Self::NoGitDir,
1908            _ => Self::ForwardCompatibleUnknown(value),
1909        })
1910    }
1911}
1912
1913/// The observable state of a git worktree when a build pipeline found a revision.
1914#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1915pub enum GitTreeState {
1916    Clean,
1917    Dirty,
1918}
1919
1920/// How the build pipeline obtained (or did not obtain) git revision data.
1921///
1922/// `NoGitDir` and `NeverDerived` carry no revision, so callers cannot attach
1923/// those absence causes to an otherwise attested commit through this API.
1924#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1925pub enum BuildGitShaSource<'a> {
1926    Git {
1927        revision: &'a str,
1928        tree_state: GitTreeState,
1929    },
1930    NeverDerived,
1931    NoGitDir,
1932}
1933
1934/// Return a commit only when its source tree was clean at build time.
1935///
1936/// The rule is pure so stampers can exercise both branches without rebuilding.
1937pub fn attestable_commit(revision: &str, tree_state: GitTreeState) -> Option<&str> {
1938    match tree_state {
1939        GitTreeState::Clean => Some(revision),
1940        GitTreeState::Dirty => None,
1941    }
1942}
1943
1944const MAX_PROVENANCE_VALUE_BYTES: usize = 128;
1945const BUILD_GIT_SHA_CANONICAL_FORM: &str = "exactly 40 lowercase hexadecimal characters";
1946const BUILD_LOCK_DIGEST_CANONICAL_FORM: &str = "exactly 64 lowercase hexadecimal characters";
1947
1948#[derive(Deserialize)]
1949struct ManifestProvenanceWire {
1950    #[serde(default)]
1951    build_git_sha: Option<String>,
1952    #[serde(default)]
1953    build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
1954    #[serde(default)]
1955    build_lock_digest: Option<String>,
1956    #[serde(default)]
1957    wire_crate_version: Option<String>,
1958    #[serde(default)]
1959    store_schema_version: Option<String>,
1960    #[serde(default)]
1961    launch_nonce_source: Option<LaunchNonceSource>,
1962}
1963
1964impl<'de> Deserialize<'de> for ManifestProvenance {
1965    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1966    where
1967        D: Deserializer<'de>,
1968    {
1969        let wire = ManifestProvenanceWire::deserialize(deserializer)?;
1970        let provenance = Self {
1971            build_git_sha: wire.build_git_sha,
1972            build_git_sha_absence_reason: wire.build_git_sha_absence_reason,
1973            build_lock_digest: wire.build_lock_digest,
1974            wire_crate_version: wire.wire_crate_version,
1975            store_schema_version: wire.store_schema_version,
1976            launch_nonce_source: wire.launch_nonce_source,
1977        };
1978        provenance.validate().map_err(D::Error::custom)?;
1979        Ok(provenance)
1980    }
1981}
1982
1983/// A declared build fact did not use its canonical form.
1984#[derive(Debug, Clone, PartialEq, Eq)]
1985pub struct ProvenanceFormError {
1986    field: &'static str,
1987    length: usize,
1988    canonical_form: &'static str,
1989}
1990
1991impl ProvenanceFormError {
1992    fn new(field: &'static str, length: usize, canonical_form: &'static str) -> Self {
1993        Self {
1994            field,
1995            length,
1996            canonical_form,
1997        }
1998    }
1999
2000    /// The provenance field whose value was not canonical.
2001    pub fn field(&self) -> &str {
2002        self.field
2003    }
2004
2005    /// The offending value's length in bytes.
2006    pub fn length(&self) -> usize {
2007        self.length
2008    }
2009
2010    /// The canonical form required for this field.
2011    pub fn canonical_form(&self) -> &str {
2012        self.canonical_form
2013    }
2014}
2015
2016impl fmt::Display for ProvenanceFormError {
2017    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018        write!(
2019            f,
2020            "invalid manifest provenance form: field {} has length {}; canonical form is {}",
2021            self.field, self.length, self.canonical_form
2022        )
2023    }
2024}
2025
2026impl std::error::Error for ProvenanceFormError {}
2027
2028#[derive(Debug, Clone, PartialEq, Eq)]
2029pub struct ManifestProvenanceError {
2030    field: String,
2031    value: String,
2032    reason: &'static str,
2033}
2034
2035impl ManifestProvenanceError {
2036    fn new(field: &str, value: &str, reason: &'static str) -> Self {
2037        Self {
2038            field: field.to_string(),
2039            value: safe_error_value(value),
2040            reason,
2041        }
2042    }
2043
2044    pub fn field(&self) -> &str {
2045        &self.field
2046    }
2047}
2048
2049impl fmt::Display for ManifestProvenanceError {
2050    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2051        write!(
2052            f,
2053            "invalid manifest provenance: field {} has {} (value {:?})",
2054            self.field, self.reason, self.value
2055        )
2056    }
2057}
2058
2059impl std::error::Error for ManifestProvenanceError {}
2060
2061impl ManifestProvenance {
2062    /// A block declaring nothing; add facts with the `with_*` setters.
2063    pub fn new() -> Self {
2064        Self::default()
2065    }
2066
2067    pub fn with_build_git_sha(mut self, value: Option<String>) -> Self {
2068        self.build_git_sha = value;
2069        self
2070    }
2071
2072    pub fn with_build_git_sha_absence_reason(
2073        mut self,
2074        value: Option<BuildGitShaAbsenceReason>,
2075    ) -> Self {
2076        self.build_git_sha_absence_reason = value;
2077        self
2078    }
2079
2080    pub fn with_build_lock_digest(mut self, value: Option<String>) -> Self {
2081        self.build_lock_digest = value;
2082        self
2083    }
2084
2085    pub fn with_wire_crate_version(mut self, value: Option<String>) -> Self {
2086        self.wire_crate_version = value;
2087        self
2088    }
2089
2090    pub fn with_store_schema_version(mut self, value: Option<String>) -> Self {
2091        self.store_schema_version = value;
2092        self
2093    }
2094
2095    /// Report where this process read its launch nonce from. A module takes
2096    /// it from its nonce accessor's cached source, so whoever reads the fleet's
2097    /// provenance (`ck provenance`) can tell a module reading the pipe from
2098    /// one still reading the environment variable.
2099    pub fn with_launch_nonce_source(mut self, value: Option<LaunchNonceSource>) -> Self {
2100        self.launch_nonce_source = value;
2101        self
2102    }
2103
2104    pub fn validate(&self) -> Result<(), ManifestProvenanceError> {
2105        if let (Some(_), Some(reason)) = (
2106            self.build_git_sha.as_ref(),
2107            self.build_git_sha_absence_reason.as_ref(),
2108        ) {
2109            return Err(ManifestProvenanceError::new(
2110                "build_git_sha_absence_reason",
2111                reason.wire_name(),
2112                "must be omitted when build_git_sha is present",
2113            ));
2114        }
2115        for (field, value) in [
2116            ("build_git_sha", self.build_git_sha.as_deref()),
2117            (
2118                "build_git_sha_absence_reason",
2119                self.build_git_sha_absence_reason
2120                    .as_ref()
2121                    .map(|reason| reason.wire_name()),
2122            ),
2123            ("build_lock_digest", self.build_lock_digest.as_deref()),
2124            ("wire_crate_version", self.wire_crate_version.as_deref()),
2125            ("store_schema_version", self.store_schema_version.as_deref()),
2126            (
2127                "launch_nonce_source",
2128                self.launch_nonce_source
2129                    .as_ref()
2130                    .map(|source| source.wire_name()),
2131            ),
2132        ] {
2133            let Some(value) = value else { continue };
2134            if value.is_empty() {
2135                return Err(ManifestProvenanceError::new(
2136                    field,
2137                    value,
2138                    "must not be empty",
2139                ));
2140            }
2141            // HELLO decoding checks only wire safety here. Canonical build forms
2142            // belong to build_provenance; the daemon is a non-adjudicating relayer
2143            // and must continue accepting legacy declarations such as 12-hex
2144            // module revisions rather than breaking a fleet on daemon upgrade.
2145            if value.len() > MAX_PROVENANCE_VALUE_BYTES {
2146                return Err(ManifestProvenanceError::new(
2147                    field,
2148                    value,
2149                    "exceeds the 128-byte maximum",
2150                ));
2151            }
2152            if value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) {
2153                return Err(ManifestProvenanceError::new(
2154                    field,
2155                    value,
2156                    "contains non-printable ASCII",
2157                ));
2158            }
2159        }
2160        Ok(())
2161    }
2162}
2163
2164/// Build [`ManifestProvenance`] from legacy raw build facts.
2165///
2166/// Callers of this compatibility path did not supply the tree state that
2167/// explains an omitted SHA. It emits no absence reason not because the absence
2168/// has no cause, but because guessing one without that state would fabricate
2169/// the fact this API exists to report honestly.
2170///
2171/// ```
2172/// use subc_protocol::manifest::build_provenance;
2173///
2174/// let provenance = build_provenance(option_env!("CK_BUILD_REV"), None, None)
2175///     .expect("legacy build facts remain supported");
2176/// assert!(provenance.build_git_sha_absence_reason.is_none());
2177/// ```
2178///
2179/// Sentinel and empty values become field omission before canonical form
2180/// validation, preserving the established three-argument wire behavior.
2181pub fn build_provenance(
2182    build_git_sha: Option<&str>,
2183    build_lock_digest: Option<&str>,
2184    store_schema_version: Option<&str>,
2185) -> Result<ManifestProvenance, ProvenanceFormError> {
2186    let build_git_sha = normalize_and_validate_build_git_sha(build_git_sha)?;
2187    build_provenance_with_build_git_sha(
2188        build_git_sha,
2189        None,
2190        build_lock_digest,
2191        store_schema_version,
2192    )
2193}
2194
2195/// Build a [`ManifestProvenance`] from source-state-aware build facts.
2196///
2197/// The source state makes the SHA absence cause attestable: `Dirty` declines
2198/// the commit, while `NeverDerived` and `NoGitDir` name distinct source paths.
2199/// A `build_git_sha` must be exactly 40 lowercase hexadecimal characters and a
2200/// `build_lock_digest` exactly 64 lowercase hexadecimal characters. Abbreviations
2201/// are not conforming; a real value in the wrong form returns a
2202/// [`ProvenanceFormError`] instead of being discarded as if it were absent.
2203/// Sentinel values are filtered before form validation, so they remain honest
2204/// omission rather than becoming form errors.
2205///
2206/// OWNERSHIP RULE: a helper that constructs a wire type lives in the crate
2207/// that owns the type. This helper constructs `ManifestProvenance`, so it
2208/// lives here in subc-protocol (not in subc-client-rs) — transport-direct
2209/// modules that never link the client SDK can still build honest provenance.
2210pub fn build_provenance_from_source(
2211    build_git_sha_source: BuildGitShaSource<'_>,
2212    build_lock_digest: Option<&str>,
2213    store_schema_version: Option<&str>,
2214) -> Result<ManifestProvenance, ProvenanceFormError> {
2215    let (raw_build_git_sha, mut build_git_sha_absence_reason) = match build_git_sha_source {
2216        BuildGitShaSource::Git {
2217            revision,
2218            tree_state,
2219        } => match attestable_commit(revision, tree_state) {
2220            Some(revision) => (Some(revision), None),
2221            None => (None, Some(BuildGitShaAbsenceReason::DeclinedDirty)),
2222        },
2223        BuildGitShaSource::NeverDerived => (None, Some(BuildGitShaAbsenceReason::NeverDerived)),
2224        BuildGitShaSource::NoGitDir => (None, Some(BuildGitShaAbsenceReason::NoGitDir)),
2225    };
2226    let build_git_sha = normalize_and_validate_build_git_sha(raw_build_git_sha)?;
2227    if build_git_sha.is_none() {
2228        build_git_sha_absence_reason.get_or_insert(BuildGitShaAbsenceReason::NeverDerived);
2229    }
2230    build_provenance_with_build_git_sha(
2231        build_git_sha,
2232        build_git_sha_absence_reason,
2233        build_lock_digest,
2234        store_schema_version,
2235    )
2236}
2237
2238fn normalize_and_validate_build_git_sha(
2239    build_git_sha: Option<&str>,
2240) -> Result<Option<String>, ProvenanceFormError> {
2241    let build_git_sha = normalize_provenance_fact(build_git_sha);
2242    validate_provenance_form(
2243        "build_git_sha",
2244        build_git_sha.as_deref(),
2245        BUILD_GIT_SHA_CANONICAL_FORM,
2246        40,
2247    )?;
2248    Ok(build_git_sha)
2249}
2250
2251fn build_provenance_with_build_git_sha(
2252    build_git_sha: Option<String>,
2253    build_git_sha_absence_reason: Option<BuildGitShaAbsenceReason>,
2254    build_lock_digest: Option<&str>,
2255    store_schema_version: Option<&str>,
2256) -> Result<ManifestProvenance, ProvenanceFormError> {
2257    let build_lock_digest = normalize_provenance_fact(build_lock_digest);
2258    validate_provenance_form(
2259        "build_lock_digest",
2260        build_lock_digest.as_deref(),
2261        BUILD_LOCK_DIGEST_CANONICAL_FORM,
2262        64,
2263    )?;
2264
2265    Ok(ManifestProvenance {
2266        build_git_sha,
2267        build_git_sha_absence_reason,
2268        build_lock_digest,
2269        wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
2270        store_schema_version: normalize_provenance_fact(store_schema_version),
2271        launch_nonce_source: None,
2272    })
2273}
2274
2275fn validate_provenance_form(
2276    field: &'static str,
2277    value: Option<&str>,
2278    canonical_form: &'static str,
2279    expected_length: usize,
2280) -> Result<(), ProvenanceFormError> {
2281    let Some(value) = value else { return Ok(()) };
2282    if value.len() != expected_length
2283        || !value
2284            .bytes()
2285            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
2286    {
2287        return Err(ProvenanceFormError::new(field, value.len(), canonical_form));
2288    }
2289    Ok(())
2290}
2291
2292/// Sentinel strings that build tooling emits where it means "no value": shell
2293/// fallbacks and Makefile defaults produce `unknown`, wire vocabulary uses
2294/// `unavailable`, and `git describe` failures surface as `none`. Publishing
2295/// any of them as a fact is the well-formed-lie shape the provenance contract
2296/// warns against — a present, well-formed field stops the reader asking — so
2297/// the helper maps them all to field omission. Matched case-insensitively
2298/// because `UNKNOWN`/`Unknown` are equally common from shell fallbacks.
2299pub const PROVENANCE_SENTINELS: [&str; 3] = ["unknown", "unavailable", "none"];
2300
2301fn normalize_provenance_fact(value: Option<&str>) -> Option<String> {
2302    let value = value?.trim();
2303    if value.is_empty() {
2304        return None;
2305    }
2306    let lowered = value.to_ascii_lowercase();
2307    if PROVENANCE_SENTINELS.contains(&lowered.as_str()) {
2308        return None;
2309    }
2310    Some(value.to_string())
2311}
2312
2313/// One capability a module consumes and whether its absence is tolerated.
2314#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2315#[serde(deny_unknown_fields)]
2316pub struct CapabilityRequirement {
2317    pub capability: String,
2318    pub need: CapabilityNeed,
2319}
2320
2321/// Closed capability requirement strength vocabulary.
2322#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2323#[serde(rename_all = "snake_case")]
2324pub enum CapabilityNeed {
2325    Required,
2326    Optional,
2327}
2328
2329/// A safe-to-report capability-schema validation failure.
2330#[derive(Debug, Clone, PartialEq, Eq)]
2331pub struct CapabilityGrammarError {
2332    field: String,
2333    value: String,
2334}
2335
2336impl CapabilityGrammarError {
2337    fn new(field: impl Into<String>, value: impl AsRef<str>) -> Self {
2338        Self {
2339            field: field.into(),
2340            value: safe_error_value(value.as_ref()),
2341        }
2342    }
2343
2344    /// The precise malformed field path.
2345    pub fn field(&self) -> &str {
2346        &self.field
2347    }
2348
2349    /// The offending value, redacted when it resembles a credential.
2350    pub fn value(&self) -> &str {
2351        &self.value
2352    }
2353}
2354
2355impl fmt::Display for CapabilityGrammarError {
2356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2357        write!(
2358            f,
2359            "invalid capability grammar: field {} has offending value {:?}",
2360            self.field, self.value
2361        )
2362    }
2363}
2364
2365impl std::error::Error for CapabilityGrammarError {}
2366
2367impl ModuleManifest {
2368    /// Validate the typed capability block after serde has decoded it.
2369    pub fn validate_capability_grammar(&self) -> Result<(), CapabilityGrammarError> {
2370        let Some(capabilities) = &self.capabilities else {
2371            return Ok(());
2372        };
2373
2374        validate_capability_list("capabilities.provides", &capabilities.provides)?;
2375        validate_requires(&capabilities.requires)?;
2376        validate_capability_list(
2377            "capabilities.must_never_reach",
2378            &capabilities.must_never_reach,
2379        )
2380    }
2381}
2382
2383/// Validate capability grammar in a standalone manifest JSON value.
2384///
2385/// The raw-value form lets HELLO distinguish schema failures from malformed JSON,
2386/// including an unknown `need` that cannot be represented by [`CapabilityNeed`].
2387pub fn validate_manifest_capability_grammar(
2388    manifest: &Value,
2389) -> Result<(), CapabilityGrammarError> {
2390    let Some(object) = manifest.as_object() else {
2391        return Ok(());
2392    };
2393
2394    validate_capabilities_value(object.get("capabilities"))?;
2395    validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2396}
2397
2398/// Validate capability grammar in a raw HELLO body.
2399///
2400/// `runtime_computed` is a top-level sibling in --manifest output. HELLO keeps
2401/// accepting that sibling only so an attempted dynamic capability declaration is
2402/// refused explicitly instead of being silently ignored by serde.
2403pub fn validate_hello_capability_grammar(hello: &Value) -> Result<(), CapabilityGrammarError> {
2404    let Some(object) = hello.as_object() else {
2405        return Ok(());
2406    };
2407    if let Some(manifest) = object.get("manifest") {
2408        validate_manifest_capability_grammar(manifest)?;
2409    }
2410    validate_runtime_computed(object.get("runtime_computed"), "runtime_computed")
2411}
2412
2413/// Return whether `identifier` has the exact `<name>/v<N>` capability spelling.
2414pub fn is_valid_capability_identifier(identifier: &str) -> bool {
2415    if identifier.chars().any(char::is_whitespace) {
2416        return false;
2417    }
2418    let Some((name, version)) = identifier.split_once("/v") else {
2419        return false;
2420    };
2421    if name.is_empty() || name.len() > 64 || version.is_empty() {
2422        return false;
2423    }
2424
2425    let name_bytes = name.as_bytes();
2426    if !name_bytes[0].is_ascii_lowercase()
2427        || (name.len() > 1
2428            && !name_bytes[name.len() - 1].is_ascii_lowercase()
2429            && !name_bytes[name.len() - 1].is_ascii_digit())
2430        || name_bytes.windows(2).any(|pair| pair == b"--")
2431    {
2432        return false;
2433    }
2434    if !name_bytes
2435        .iter()
2436        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
2437    {
2438        return false;
2439    }
2440
2441    if version.len() > 1 && version.starts_with('0')
2442        || !version.bytes().all(|byte| byte.is_ascii_digit())
2443    {
2444        return false;
2445    }
2446    matches!(
2447        version.parse::<u64>(),
2448        Ok(value) if (1..=u64::from(u32::MAX)).contains(&value)
2449    )
2450}
2451
2452fn validate_capabilities_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2453    let Some(value) = value else {
2454        return Ok(());
2455    };
2456    let Some(object) = value.as_object() else {
2457        return Err(CapabilityGrammarError::new(
2458            "capabilities",
2459            value_description(value),
2460        ));
2461    };
2462
2463    for (key, value) in object {
2464        if !matches!(key.as_str(), "provides" | "requires" | "must_never_reach") {
2465            return Err(CapabilityGrammarError::new(
2466                field_child("capabilities", key),
2467                value_description(value),
2468            ));
2469        }
2470    }
2471
2472    validate_capability_list_value("capabilities.provides", object.get("provides"))?;
2473    validate_requires_value(object.get("requires"))?;
2474    validate_capability_list_value(
2475        "capabilities.must_never_reach",
2476        object.get("must_never_reach"),
2477    )
2478}
2479
2480fn validate_capability_list_value(
2481    field: &str,
2482    value: Option<&Value>,
2483) -> Result<(), CapabilityGrammarError> {
2484    let Some(value) = value else {
2485        return Ok(());
2486    };
2487    let Some(values) = value.as_array() else {
2488        return Err(CapabilityGrammarError::new(field, value_description(value)));
2489    };
2490
2491    let mut seen = HashSet::new();
2492    for (index, value) in values.iter().enumerate() {
2493        let field = format!("{field}[{index}]");
2494        let Some(identifier) = value.as_str() else {
2495            return Err(CapabilityGrammarError::new(field, value_description(value)));
2496        };
2497        validate_capability_identifier(&field, identifier)?;
2498        if !seen.insert(identifier) {
2499            return Err(CapabilityGrammarError::new(field, identifier));
2500        }
2501    }
2502    Ok(())
2503}
2504
2505fn validate_requires_value(value: Option<&Value>) -> Result<(), CapabilityGrammarError> {
2506    let Some(value) = value else {
2507        return Ok(());
2508    };
2509    let Some(values) = value.as_array() else {
2510        return Err(CapabilityGrammarError::new(
2511            "capabilities.requires",
2512            value_description(value),
2513        ));
2514    };
2515
2516    let mut seen = HashSet::new();
2517    for (index, value) in values.iter().enumerate() {
2518        let entry_field = format!("capabilities.requires[{index}]");
2519        let Some(object) = value.as_object() else {
2520            return Err(CapabilityGrammarError::new(
2521                entry_field,
2522                value_description(value),
2523            ));
2524        };
2525        for (key, value) in object {
2526            if !matches!(key.as_str(), "capability" | "need") {
2527                return Err(CapabilityGrammarError::new(
2528                    field_child(&entry_field, key),
2529                    value_description(value),
2530                ));
2531            }
2532        }
2533        let capability_field = format!("{entry_field}.capability");
2534        let Some(capability) = object.get("capability").and_then(Value::as_str) else {
2535            return Err(CapabilityGrammarError::new(
2536                capability_field,
2537                object
2538                    .get("capability")
2539                    .map_or("<missing>".to_string(), value_description),
2540            ));
2541        };
2542        validate_capability_identifier(&capability_field, capability)?;
2543
2544        let need_field = format!("{entry_field}.need");
2545        let Some(need) = object.get("need").and_then(Value::as_str) else {
2546            return Err(CapabilityGrammarError::new(
2547                need_field,
2548                object
2549                    .get("need")
2550                    .map_or("<missing>".to_string(), value_description),
2551            ));
2552        };
2553        if !matches!(need, "required" | "optional") {
2554            return Err(CapabilityGrammarError::new(need_field, need));
2555        }
2556        if !seen.insert(capability) {
2557            return Err(CapabilityGrammarError::new(entry_field, capability));
2558        }
2559    }
2560    Ok(())
2561}
2562
2563fn validate_capability_list(field: &str, values: &[String]) -> Result<(), CapabilityGrammarError> {
2564    let mut seen = HashSet::new();
2565    for (index, identifier) in values.iter().enumerate() {
2566        let field = format!("{field}[{index}]");
2567        validate_capability_identifier(&field, identifier)?;
2568        if !seen.insert(identifier) {
2569            return Err(CapabilityGrammarError::new(field, identifier));
2570        }
2571    }
2572    Ok(())
2573}
2574
2575fn validate_requires(values: &[CapabilityRequirement]) -> Result<(), CapabilityGrammarError> {
2576    let mut seen = HashSet::new();
2577    for (index, requirement) in values.iter().enumerate() {
2578        let field = format!("capabilities.requires[{index}].capability");
2579        validate_capability_identifier(&field, &requirement.capability)?;
2580        if !seen.insert(&requirement.capability) {
2581            return Err(CapabilityGrammarError::new(
2582                format!("capabilities.requires[{index}]"),
2583                &requirement.capability,
2584            ));
2585        }
2586    }
2587    Ok(())
2588}
2589
2590fn validate_capability_identifier(
2591    field: &str,
2592    identifier: &str,
2593) -> Result<(), CapabilityGrammarError> {
2594    if is_valid_capability_identifier(identifier) {
2595        Ok(())
2596    } else {
2597        Err(CapabilityGrammarError::new(field, identifier))
2598    }
2599}
2600
2601fn validate_runtime_computed(
2602    value: Option<&Value>,
2603    field: &str,
2604) -> Result<(), CapabilityGrammarError> {
2605    let Some(value) = value else {
2606        return Ok(());
2607    };
2608    let Some(pointers) = value.as_array() else {
2609        return Err(CapabilityGrammarError::new(field, value_description(value)));
2610    };
2611
2612    for (index, pointer) in pointers.iter().enumerate() {
2613        let field = format!("{field}[{index}]");
2614        let Some(pointer) = pointer.as_str() else {
2615            return Err(CapabilityGrammarError::new(
2616                field,
2617                value_description(pointer),
2618            ));
2619        };
2620        let Some(tokens) = parse_json_pointer(pointer) else {
2621            return Err(CapabilityGrammarError::new(field, pointer));
2622        };
2623        if tokens.first().is_some_and(|token| token == "capabilities") {
2624            return Err(CapabilityGrammarError::new(field, pointer));
2625        }
2626    }
2627    Ok(())
2628}
2629
2630fn parse_json_pointer(pointer: &str) -> Option<Vec<String>> {
2631    if pointer.is_empty() {
2632        return Some(Vec::new());
2633    }
2634    let raw_tokens = pointer.strip_prefix('/')?;
2635    raw_tokens
2636        .split('/')
2637        .map(unescape_json_pointer_token)
2638        .collect()
2639}
2640
2641fn unescape_json_pointer_token(token: &str) -> Option<String> {
2642    let mut output = String::with_capacity(token.len());
2643    let mut characters = token.chars();
2644    while let Some(character) = characters.next() {
2645        if character != '~' {
2646            output.push(character);
2647            continue;
2648        }
2649        match characters.next()? {
2650            '0' => output.push('~'),
2651            '1' => output.push('/'),
2652            _ => return None,
2653        }
2654    }
2655    Some(output)
2656}
2657
2658fn field_child(parent: &str, child: &str) -> String {
2659    let child = safe_error_value(child);
2660    format!("{parent}.{child}")
2661}
2662
2663fn value_description(value: &Value) -> String {
2664    match value {
2665        Value::String(value) => safe_error_value(value),
2666        Value::Null => "null".to_string(),
2667        Value::Bool(value) => value.to_string(),
2668        Value::Number(value) => value.to_string(),
2669        Value::Array(_) => "<array>".to_string(),
2670        Value::Object(_) => "<object>".to_string(),
2671    }
2672}
2673
2674fn safe_error_value(value: &str) -> String {
2675    let lower = value.to_ascii_lowercase();
2676    if ["secret", "password", "api_key"]
2677        .iter()
2678        .any(|marker| lower.contains(marker))
2679        || lower.starts_with("sk-")
2680        || lower.starts_with("akia")
2681        || lower.starts_with("bearer ")
2682        || lower.starts_with("token=")
2683        || lower.starts_with("credential=")
2684    {
2685        "<redacted>".to_string()
2686    } else {
2687        value.to_string()
2688    }
2689}
2690
2691/// How this module was sourced, as declared by the module itself.
2692///
2693/// Not read on any daemon routing or admission path; relayed verbatim. A
2694/// module declares it because it describes the module, not because the
2695/// daemon consumes it, and leaves it absent rather than inventing a value.
2696#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2697#[serde(rename_all = "snake_case")]
2698pub enum TrustTier {
2699    FirstParty,
2700    Reviewed,
2701    Untrusted,
2702}
2703
2704/// Provider capabilities exposed by a module.
2705///
2706/// The role set is closed for protocol v1; unknown role tags fail serde decode.
2707#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2708#[serde(tag = "role", rename_all = "snake_case")]
2709pub enum ProviderRole {
2710    ToolProvider {
2711        tools: Vec<Tool>,
2712        /// Which `BindIdentity` keys PARTITION this provider's state or
2713        /// answers: a module whose reply to a call depends on the caller's
2714        /// project declares `Project`; one that threads per session declares
2715        /// `Session`; one that answers identically to every caller declares
2716        /// `[]`. It states what the module does with the keys it is handed,
2717        /// not which keys it will accept — every bind carries all of them.
2718        /// Not read on any daemon path; relayed verbatim for consumers.
2719        identity_scope: Vec<IdentityScope>,
2720        concurrency: Concurrency,
2721        emits_push: bool,
2722        sub_supervises: bool,
2723    },
2724    PipelineStage {
2725        stage: PipelineStageKind,
2726        applies_to: PipelineAppliesTo,
2727        interface: String,
2728        declares_frozen_floor: bool,
2729        needs_signals: Vec<String>,
2730        conformance_class: String,
2731    },
2732    ManagementSurface {
2733        operations: Vec<ManagementOperation>,
2734        config_schema: Value,
2735        observability: Vec<ObservabilitySurface>,
2736        /// Same meaning as on `ToolProvider`: the keys that partition this
2737        /// surface's state or answers; `[]` for a surface that serves the
2738        /// same answer to every caller.
2739        identity_scope: Vec<IdentityScope>,
2740        #[serde(default)]
2741        concurrency: Concurrency,
2742    },
2743    InternalService {
2744        service_id: String,
2745        transport: InternalTransport,
2746        agent_facing: bool,
2747        operations: Vec<String>,
2748    },
2749}
2750
2751/// How a tool's side effects are fenced for durable at-most-once handling.
2752///
2753/// Classified on a tool's externally-observable effects, never inferred from
2754/// the module's concurrency lane:
2755/// - `Pure`: no observable side effect (reads, searches, cache warming) — safe
2756///   to re-run after an indeterminate outcome.
2757/// - `Mutating`: a fenceable external side effect such as a file write — a
2758///   re-run risks a duplicate effect, so an indeterminate outcome must not
2759///   auto-retry.
2760/// - `Unfenceable`: a side effect that cannot be fenced or safely replayed,
2761///   such as running a shell command — never auto-re-run on an indeterminate
2762///   outcome.
2763#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2764#[serde(rename_all = "snake_case")]
2765pub enum ExecutionMode {
2766    Pure,
2767    Mutating,
2768    Unfenceable,
2769}
2770
2771/// Tool-plane capability exposed by a `tool_provider`.
2772#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2773pub struct Tool {
2774    pub name: String,
2775    #[serde(default, skip_serializing_if = "Option::is_none")]
2776    pub description: Option<String>,
2777    /// How the tool's side effects are fenced for durable at-most-once handling.
2778    /// Observability + durability metadata only; subc's thin core never acts on
2779    /// this for routing, scheduling, or concurrency — the module's declared
2780    /// [`Concurrency`] contract governs delivery.
2781    pub execution_mode: ExecutionMode,
2782    pub schema: Value,
2783}
2784
2785/// How subc may deliver concurrent in-flight calls to the provider.
2786///
2787/// subc records and forwards these semantics unchanged; the dispatcher that
2788/// enforces them lives in subc-core, kept separate from this frozen manifest
2789/// contract.
2790#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2791#[serde(rename_all = "snake_case")]
2792pub enum Concurrency {
2793    /// One in-flight call at a time with strict submission and response order.
2794    Serial,
2795    /// Concurrent in-flight calls may span channels, while subc preserves FIFO
2796    /// submission within each channel; the module schedules internally.
2797    ModuleManaged,
2798    /// Fully parallel delivery with no ordering guarantee across or within
2799    /// channels.
2800    StatelessParallel,
2801}
2802
2803#[allow(clippy::derivable_impls)]
2804// The default is PINNED BY HISTORY, not chosen as the best value. Before this
2805// field existed, every ManagementSurface received ModuleManaged delivery (32
2806// concurrent credits) unconditionally, so an absent-field manifest must resolve
2807// to exactly that behavior -- any other default (including the fail-closed
2808// Serial) would convert a daemon upgrade into a silent delivery-semantics
2809// change for every deployed module. A genuinely-Serial module was ALREADY
2810// receiving concurrent delivery under pre-field daemons; the field's addition
2811// is what makes declaring Serial possible at all, so the fix for such a module
2812// is an explicit declaration, and the daemon logs defaulted registrations so
2813// the fleet's exposure is readable rather than assumed.
2814impl Default for Concurrency {
2815    fn default() -> Self {
2816        Self::ModuleManaged
2817    }
2818}
2819
2820/// A `BindIdentity` key a provider partitions its state or answers by.
2821///
2822/// Declared in a role's `identity_scope` to say which caller keys change
2823/// what the module does; the daemon hands every bind all of the keys
2824/// regardless, so an empty declaration means "answers do not depend on the
2825/// caller", never "keys are refused".
2826#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2827#[serde(rename_all = "snake_case")]
2828pub enum IdentityScope {
2829    Session,
2830    Project,
2831}
2832
2833/// Proxy-plane stage kind.
2834#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2835#[serde(rename_all = "snake_case")]
2836pub enum PipelineStageKind {
2837    Transform,
2838    Codec,
2839    Auth,
2840}
2841
2842/// Provider/model selector for a pipeline stage. `"*"` denotes wildcard.
2843#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
2844pub struct PipelineAppliesTo {
2845    pub provider: String,
2846    pub model: String,
2847}
2848
2849/// A management operation's declared raw request payload limit.
2850/// Validated with its operation name by [`ModuleManifest::validate_operation_payload`].
2851#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2852#[non_exhaustive]
2853pub struct OperationPayload {
2854    max_bytes: usize,
2855}
2856
2857impl OperationPayload {
2858    pub fn new(max_bytes: usize) -> Self {
2859        Self { max_bytes }
2860    }
2861
2862    pub fn max_bytes(&self) -> usize {
2863        self.max_bytes
2864    }
2865}
2866
2867/// Why a payload declaration cannot be accepted.
2868#[derive(Debug, Clone, PartialEq, Eq)]
2869#[non_exhaustive]
2870pub enum OperationPayloadError {
2871    UnknownOperation { operation: String },
2872    WatchOperation { operation: String },
2873    InvalidMaxBytes { operation: String },
2874}
2875
2876impl fmt::Display for OperationPayloadError {
2877    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2878        write!(f, "{self:?}")
2879    }
2880}
2881
2882impl std::error::Error for OperationPayloadError {}
2883
2884impl ModuleManifest {
2885    /// Checks that payload declarations name unary management operations and
2886    /// have limits in `1..=MAX_DECLARED_PAYLOAD_BYTES`.
2887    pub fn validate_operation_payload(&self) -> Result<(), OperationPayloadError> {
2888        for (name, payload) in &self.operation_payload {
2889            if !self.provides.iter().any(|role| match role {
2890                ProviderRole::ManagementSurface { operations, .. } => {
2891                    operations.iter().any(|op| op.name == *name)
2892                }
2893                _ => false,
2894            }) {
2895                return Err(OperationPayloadError::UnknownOperation {
2896                    operation: name.clone(),
2897                });
2898            }
2899            if self
2900                .operation_delivery
2901                .get(name)
2902                .is_some_and(OperationDelivery::is_watch)
2903            {
2904                return Err(OperationPayloadError::WatchOperation {
2905                    operation: name.clone(),
2906                });
2907            }
2908            if !(1..=crate::framed_body::MAX_DECLARED_PAYLOAD_BYTES).contains(&payload.max_bytes) {
2909                return Err(OperationPayloadError::InvalidMaxBytes {
2910                    operation: name.clone(),
2911                });
2912            }
2913        }
2914        Ok(())
2915    }
2916}
2917
2918/// Why a [`ModuleManifest::flow_operations`] list is dropped.
2919///
2920/// A dropped list leaves the manifest as if the module had not declared one;
2921/// it never refuses HELLO.
2922#[derive(Debug, Clone, PartialEq, Eq)]
2923#[non_exhaustive]
2924pub enum FlowOperationsError {
2925    /// The manifest provides neither `flow-scopes/v1` nor `call-modes/v1`, so it
2926    /// admits no flow-scoped call for the list to narrow.
2927    FlowScopesNotDeclared,
2928    /// The wire value is not an array of strings.
2929    NotAList,
2930    /// The list holds more than [`MAX_FLOW_OPERATIONS`] names.
2931    TooMany { count: usize },
2932    /// The same name appears more than once.
2933    DuplicateOperation { operation: String },
2934    /// The name is not a management operation declared by the same manifest.
2935    UnknownOperation { operation: String },
2936}
2937
2938impl fmt::Display for FlowOperationsError {
2939    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2940        match self {
2941            Self::FlowScopesNotDeclared => write!(
2942                f,
2943                "flow_operations requires '{}' or '{}' in capabilities.provides",
2944                crate::scope::FLOW_SCOPES_CAPABILITY,
2945                crate::call_mode::CALL_MODES_CAPABILITY
2946            ),
2947            Self::NotAList => f.write_str("flow_operations must be an array of operation names"),
2948            Self::TooMany { count } => write!(
2949                f,
2950                "flow_operations lists {count} names, more than {MAX_FLOW_OPERATIONS}"
2951            ),
2952            Self::DuplicateOperation { operation } => {
2953                write!(f, "flow_operations names '{operation}' more than once")
2954            }
2955            Self::UnknownOperation { operation } => write!(
2956                f,
2957                "flow_operations names '{operation}', which is not a declared management operation"
2958            ),
2959        }
2960    }
2961}
2962
2963impl std::error::Error for FlowOperationsError {}
2964
2965impl ModuleManifest {
2966    /// Checks a present [`Self::flow_operations`] list: the manifest provides
2967    /// `flow-scopes/v1` or `call-modes/v1`, the list holds at most
2968    /// [`MAX_FLOW_OPERATIONS`] distinct names, and each name is a management
2969    /// operation of this manifest. An absent list is always valid.
2970    pub fn validate_flow_operations(&self) -> Result<(), FlowOperationsError> {
2971        match &self.flow_operations {
2972            Some(operations) => check_flow_operations(self, operations),
2973            None => Ok(()),
2974        }
2975    }
2976}
2977
2978fn check_flow_operations(
2979    manifest: &ModuleManifest,
2980    operations: &[String],
2981) -> Result<(), FlowOperationsError> {
2982    let admits_flows = manifest.capabilities.as_ref().is_some_and(|capabilities| {
2983        capabilities.provides.iter().any(|capability| {
2984            capability == crate::scope::FLOW_SCOPES_CAPABILITY
2985                || capability == crate::call_mode::CALL_MODES_CAPABILITY
2986        })
2987    });
2988    if !admits_flows {
2989        return Err(FlowOperationsError::FlowScopesNotDeclared);
2990    }
2991    if operations.len() > MAX_FLOW_OPERATIONS {
2992        return Err(FlowOperationsError::TooMany {
2993            count: operations.len(),
2994        });
2995    }
2996    let mut seen = HashSet::new();
2997    for operation in operations {
2998        if !seen.insert(operation.as_str()) {
2999            return Err(FlowOperationsError::DuplicateOperation {
3000                operation: operation.clone(),
3001            });
3002        }
3003        let declared = manifest.provides.iter().any(|role| match role {
3004            ProviderRole::ManagementSurface { operations, .. } => {
3005                operations.iter().any(|op| op.name == *operation)
3006            }
3007            _ => false,
3008        });
3009        if !declared {
3010            return Err(FlowOperationsError::UnknownOperation {
3011                operation: operation.clone(),
3012            });
3013        }
3014    }
3015    Ok(())
3016}
3017
3018/// Decodes and checks a raw `flow_operations` value against the rest of its
3019/// manifest. JSON `null` is treated by callers as absent, never as a list.
3020fn decode_flow_operations(
3021    manifest: &ModuleManifest,
3022    value: &Value,
3023) -> Result<Vec<String>, FlowOperationsError> {
3024    let operations: Vec<String> =
3025        serde_json::from_value(value.clone()).map_err(|_| FlowOperationsError::NotAList)?;
3026    check_flow_operations(manifest, &operations)?;
3027    Ok(operations)
3028}
3029
3030/// Checks the `flow_operations` list of a raw HELLO, so the daemon can warn
3031/// about a list that decoding will drop.
3032///
3033/// Returns `Ok` when the list is absent or `null`, and also when the manifest
3034/// itself does not decode: that HELLO is refused for its own reason.
3035pub fn validate_hello_flow_operations(hello: &Value) -> Result<(), FlowOperationsError> {
3036    let Some(manifest_value) = hello.get("manifest") else {
3037        return Ok(());
3038    };
3039    let Some(value) = manifest_value
3040        .get("flow_operations")
3041        .filter(|value| !value.is_null())
3042    else {
3043        return Ok(());
3044    };
3045    let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3046        return Ok(());
3047    };
3048    decode_flow_operations(&manifest, value).map(|_| ())
3049}
3050
3051/// Maximum number of deferred-operation declarations in one manifest.
3052pub const MAX_OPERATION_DEFERRAL: usize = 256;
3053
3054fn decode_operation_deferral(
3055    manifest: &ModuleManifest,
3056    value: &Value,
3057) -> Result<BTreeMap<String, bool>, String> {
3058    if !manifest.capabilities.as_ref().is_some_and(|caps| {
3059        caps.provides
3060            .iter()
3061            .any(|cap| cap == crate::scope::SCOPE_FEDERATED_CAPABILITY)
3062    }) {
3063        return Err("operation_deferral requires scope-federated/v1".into());
3064    }
3065    let operations = value
3066        .as_object()
3067        .ok_or("operation_deferral must be an object")?;
3068    if operations.len() > MAX_OPERATION_DEFERRAL {
3069        return Err(format!(
3070            "operation_deferral exceeds {MAX_OPERATION_DEFERRAL} entries"
3071        ));
3072    }
3073    for (key, value) in operations {
3074        let (surface, name) = key
3075            .split_once(':')
3076            .ok_or("operation_deferral keys require a surface prefix")?;
3077        // Operation names share the federated catalog's printable-ASCII grammar;
3078        // colon is reserved for the surface separator and dots are allowed.
3079        if !matches!(surface, "tool" | "management")
3080            || name.is_empty()
3081            || name.len() > 128
3082            || !name
3083                .bytes()
3084                .all(|b| (0x21..=0x7e).contains(&b) && b != b':')
3085        {
3086            return Err(format!("invalid operation_deferral key '{key}'"));
3087        }
3088        if value != &Value::Bool(true) {
3089            return Err(format!("operation_deferral value for '{key}' must be true"));
3090        }
3091        if surface == "management" && !manifest.provides.iter().any(|role| matches!(role,
3092            ProviderRole::ManagementSurface { operations, .. } if operations.iter().any(|op| op.name == name))) {
3093            return Err(format!("operation_deferral names undeclared management operation '{name}'"));
3094        }
3095    }
3096    Ok(operations.keys().map(|key| (key.clone(), true)).collect())
3097}
3098
3099impl ModuleManifest {
3100    /// Check producer-constructed deferred-operation declarations against this manifest.
3101    pub fn validate_operation_deferral(&self) -> Result<(), String> {
3102        match &self.operation_deferral {
3103            Some(operations) => decode_operation_deferral(
3104                self,
3105                &serde_json::to_value(operations).expect("serializable map"),
3106            )
3107            .map(|_| ()),
3108            None => Ok(()),
3109        }
3110    }
3111}
3112
3113/// Warn about advisory metadata that the lenient manifest decoder drops whole.
3114pub fn validate_hello_operation_deferral(hello: &Value) -> Result<(), String> {
3115    let Some(manifest_value) = hello.get("manifest") else {
3116        return Ok(());
3117    };
3118    let Some(value) = manifest_value
3119        .get("operation_deferral")
3120        .filter(|v| !v.is_null())
3121    else {
3122        return Ok(());
3123    };
3124    let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3125        return Ok(());
3126    };
3127    decode_operation_deferral(&manifest, value).map(|_| ())
3128}
3129
3130/// Why a [`ModuleManifest::confirm_operations`] list is dropped.
3131///
3132/// A dropped list leaves the manifest as if the module had not declared one;
3133/// it never refuses HELLO.
3134#[derive(Debug, Clone, PartialEq, Eq)]
3135#[non_exhaustive]
3136pub enum ConfirmOperationsError {
3137    /// The wire value is not an array of strings.
3138    NotAList,
3139    /// The list holds more than [`MAX_CONFIRM_OPERATIONS`] names.
3140    TooMany { count: usize },
3141    /// The same name appears more than once.
3142    DuplicateOperation { operation: String },
3143    /// The name is not a management operation declared by the same manifest.
3144    UnknownOperation { operation: String },
3145}
3146
3147impl fmt::Display for ConfirmOperationsError {
3148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3149        match self {
3150            Self::NotAList => {
3151                f.write_str("confirm_operations must be an array of operation names")
3152            }
3153            Self::TooMany { count } => write!(
3154                f,
3155                "confirm_operations lists {count} names, more than {MAX_CONFIRM_OPERATIONS}"
3156            ),
3157            Self::DuplicateOperation { operation } => {
3158                write!(f, "confirm_operations names '{operation}' more than once")
3159            }
3160            Self::UnknownOperation { operation } => write!(
3161                f,
3162                "confirm_operations names '{operation}', which is not a declared management operation"
3163            ),
3164        }
3165    }
3166}
3167
3168impl std::error::Error for ConfirmOperationsError {}
3169
3170impl ModuleManifest {
3171    /// Checks a present [`Self::confirm_operations`] list: it holds at most
3172    /// [`MAX_CONFIRM_OPERATIONS`] distinct names, and each name is a management
3173    /// operation of this manifest. An absent list is always valid.
3174    pub fn validate_confirm_operations(&self) -> Result<(), ConfirmOperationsError> {
3175        match &self.confirm_operations {
3176            Some(operations) => check_confirm_operations(self, operations),
3177            None => Ok(()),
3178        }
3179    }
3180}
3181
3182fn check_confirm_operations(
3183    manifest: &ModuleManifest,
3184    operations: &[String],
3185) -> Result<(), ConfirmOperationsError> {
3186    if operations.len() > MAX_CONFIRM_OPERATIONS {
3187        return Err(ConfirmOperationsError::TooMany {
3188            count: operations.len(),
3189        });
3190    }
3191    let mut seen = HashSet::new();
3192    for operation in operations {
3193        if !seen.insert(operation.as_str()) {
3194            return Err(ConfirmOperationsError::DuplicateOperation {
3195                operation: operation.clone(),
3196            });
3197        }
3198        if !declares_management_operation(&manifest.provides, operation) {
3199            return Err(ConfirmOperationsError::UnknownOperation {
3200                operation: operation.clone(),
3201            });
3202        }
3203    }
3204    Ok(())
3205}
3206
3207fn declares_management_operation(provides: &[ProviderRole], operation: &str) -> bool {
3208    provides.iter().any(|role| match role {
3209        ProviderRole::ManagementSurface { operations, .. } => {
3210            operations.iter().any(|op| op.name == operation)
3211        }
3212        _ => false,
3213    })
3214}
3215
3216/// Decodes and checks a raw `confirm_operations` value against the rest of its
3217/// manifest. JSON `null` is treated by callers as absent, never as a list.
3218fn decode_confirm_operations(
3219    manifest: &ModuleManifest,
3220    value: &Value,
3221) -> Result<Vec<String>, ConfirmOperationsError> {
3222    let operations: Vec<String> =
3223        serde_json::from_value(value.clone()).map_err(|_| ConfirmOperationsError::NotAList)?;
3224    check_confirm_operations(manifest, &operations)?;
3225    Ok(operations)
3226}
3227
3228/// Checks the `confirm_operations` list of a raw HELLO, so the daemon can warn
3229/// about a list that decoding will drop.
3230///
3231/// Returns `Ok` when the list is absent or `null`, and also when the manifest
3232/// itself does not decode: that HELLO is refused for its own reason.
3233pub fn validate_hello_confirm_operations(hello: &Value) -> Result<(), ConfirmOperationsError> {
3234    let Some(manifest_value) = hello.get("manifest") else {
3235        return Ok(());
3236    };
3237    let Some(value) = manifest_value
3238        .get("confirm_operations")
3239        .filter(|value| !value.is_null())
3240    else {
3241        return Ok(());
3242    };
3243    let Ok(manifest) = ModuleManifest::deserialize(manifest_value) else {
3244        return Ok(());
3245    };
3246    decode_confirm_operations(&manifest, value).map(|_| ())
3247}
3248
3249/// Operation exposed on the management plane.
3250///
3251/// Delivery hints live in [`ModuleManifest::operation_delivery`] so adding a
3252/// delivery mode does not change this exhaustive operation descriptor.
3253#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3254pub struct ManagementOperation {
3255    pub name: String,
3256    pub kind: ManagementOperationKind,
3257    #[serde(default, skip_serializing_if = "Option::is_none")]
3258    pub description: Option<String>,
3259}
3260
3261#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3262#[serde(rename_all = "snake_case")]
3263pub enum ManagementOperationKind {
3264    Query,
3265    Mutate,
3266}
3267
3268/// An open delivery string, like [`SelfSignalKind`]: unknown values survive
3269/// decoding and re-encoding but do not grant watch semantics.
3270#[derive(Debug, Clone, PartialEq, Eq)]
3271#[non_exhaustive]
3272pub enum OperationDelivery {
3273    Watch,
3274    Other(String),
3275}
3276
3277impl OperationDelivery {
3278    /// The subscribable delivery mode for management queries.
3279    pub const WATCH: Self = Self::Watch;
3280
3281    /// The exact delivery string on the wire.
3282    pub fn wire_name(&self) -> &str {
3283        match self {
3284            Self::Watch => "watch",
3285            Self::Other(value) => value,
3286        }
3287    }
3288
3289    /// Recognizes only the exact `"watch"` string.
3290    pub fn is_watch(&self) -> bool {
3291        self.wire_name() == "watch"
3292    }
3293}
3294
3295impl Serialize for OperationDelivery {
3296    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3297    where
3298        S: serde::Serializer,
3299    {
3300        serializer.serialize_str(self.wire_name())
3301    }
3302}
3303
3304impl<'de> Deserialize<'de> for OperationDelivery {
3305    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3306    where
3307        D: Deserializer<'de>,
3308    {
3309        let value = String::deserialize(deserializer)?;
3310        Ok(if value == "watch" {
3311            Self::WATCH
3312        } else {
3313            Self::Other(value)
3314        })
3315    }
3316}
3317
3318/// Observable state exposed on the management plane.
3319#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3320pub struct ObservabilitySurface {
3321    pub name: String,
3322    pub kind: ObservabilityKind,
3323}
3324
3325#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3326#[serde(rename_all = "snake_case")]
3327pub enum ObservabilityKind {
3328    Snapshot,
3329    Stream,
3330}
3331
3332#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3333#[serde(rename_all = "snake_case")]
3334pub enum InternalTransport {
3335    Bulk,
3336}
3337
3338/// Consumer capabilities requested by a module.
3339#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3340#[serde(tag = "role", rename_all = "snake_case")]
3341pub enum ConsumerRole {
3342    ToolClient { of: Vec<String> },
3343    LlmClient { via: String, auth: String },
3344    ServiceClient { of: Vec<String> },
3345}
3346
3347/// External storage, vault, and identity bindings supplied through subc.
3348#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3349pub struct Bindings {
3350    pub storage: StorageBinding,
3351    pub vault_grants: Vec<VaultGrant>,
3352    pub identity: IdentityBinding,
3353}
3354
3355/// Storage backend supplied by subc; the module owns its schema.
3356#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3357pub struct StorageBinding {
3358    pub kind: StorageKind,
3359    pub scope: StorageScope,
3360    pub owns_schema: bool,
3361}
3362
3363#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3364#[serde(rename_all = "snake_case")]
3365pub enum StorageKind {
3366    Sqlite,
3367}
3368
3369#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3370#[serde(rename_all = "snake_case")]
3371pub enum StorageScope {
3372    Project,
3373}
3374
3375#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3376pub struct VaultGrant {
3377    pub secret: String,
3378    pub reason: String,
3379}
3380
3381#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
3382pub struct IdentityBinding {
3383    pub requires: Vec<IdentityScope>,
3384    pub optional: Vec<IdentityScope>,
3385}
3386
3387#[cfg(test)]
3388mod tests {
3389    use super::*;
3390    use serde_json::json;
3391
3392    fn aft_manifest_fixture() -> ModuleManifest {
3393        ModuleManifest::builder("aft", "0.39.2")
3394            .trust_tier(Some(TrustTier::FirstParty))
3395            .bindings(Some(Bindings {
3396                storage: StorageBinding {
3397                    kind: StorageKind::Sqlite,
3398                    scope: StorageScope::Project,
3399                    owns_schema: true,
3400                },
3401                vault_grants: vec![VaultGrant {
3402                    secret: "provider_api_key".to_string(),
3403                    reason: "cortexkit_native auth".to_string(),
3404                }],
3405                identity: IdentityBinding {
3406                    requires: vec![IdentityScope::Project],
3407                    optional: vec![IdentityScope::Session],
3408                },
3409            }))
3410            .protocol_ver(1)
3411            .provides(vec![ProviderRole::ToolProvider {
3412                tools: vec![
3413                    Tool {
3414                        name: "read".to_string(),
3415                        description: None,
3416                        execution_mode: ExecutionMode::Pure,
3417                        schema: json!({"type": "object"}),
3418                    },
3419                    Tool {
3420                        name: "grep".to_string(),
3421                        description: None,
3422                        execution_mode: ExecutionMode::Pure,
3423                        schema: json!({"type": "object"}),
3424                    },
3425                    Tool {
3426                        name: "outline".to_string(),
3427                        description: None,
3428                        execution_mode: ExecutionMode::Pure,
3429                        schema: json!({"type": "object"}),
3430                    },
3431                    Tool {
3432                        name: "semantic_search".to_string(),
3433                        description: None,
3434                        execution_mode: ExecutionMode::Pure,
3435                        schema: json!({"type": "object"}),
3436                    },
3437                    Tool {
3438                        name: "edit".to_string(),
3439                        description: None,
3440                        execution_mode: ExecutionMode::Mutating,
3441                        schema: json!({"type": "object"}),
3442                    },
3443                    Tool {
3444                        name: "write".to_string(),
3445                        description: None,
3446                        execution_mode: ExecutionMode::Mutating,
3447                        schema: json!({"type": "object"}),
3448                    },
3449                    Tool {
3450                        name: "bash".to_string(),
3451                        description: None,
3452                        execution_mode: ExecutionMode::Unfenceable,
3453                        schema: json!({"type": "object"}),
3454                    },
3455                ],
3456                identity_scope: vec![IdentityScope::Session, IdentityScope::Project],
3457                concurrency: Concurrency::ModuleManaged,
3458                emits_push: true,
3459                sub_supervises: true,
3460            }])
3461            .consumes(vec![ConsumerRole::ServiceClient {
3462                of: vec!["embedding.v2".to_string()],
3463            }])
3464            .build()
3465    }
3466
3467    #[test]
3468    fn serde_round_trips_representative_manifest() {
3469        let manifest = aft_manifest_fixture();
3470        let serialized = serde_json::to_string_pretty(&manifest).unwrap();
3471        let decoded: ModuleManifest = serde_json::from_str(&serialized).unwrap();
3472
3473        assert_eq!(manifest, decoded);
3474    }
3475
3476    #[test]
3477    fn builder_defaults_additions_to_honest_absence_and_round_trips() {
3478        let manifest = ModuleManifest::builder("builder-defaults", "2.0.0").build();
3479
3480        assert_eq!(manifest.module_id, "builder-defaults");
3481        assert_eq!(manifest.module_version, "2.0.0");
3482        assert_eq!(manifest.display_name, None);
3483        assert_eq!(manifest.protocol_ver, PROTOCOL_VERSION);
3484        assert_eq!(manifest.trust_tier, None);
3485        assert!(manifest.provides.is_empty());
3486        assert!(manifest.consumes.is_empty());
3487        assert_eq!(manifest.bindings, None);
3488        assert_eq!(manifest.capabilities, None);
3489        assert_eq!(manifest.self_signals, None);
3490        assert_eq!(manifest.provenance, None);
3491
3492        let encoded = serde_json::to_value(&manifest).expect("builder manifest serializes");
3493        for optional in [
3494            "display_name",
3495            "trust_tier",
3496            "consumes",
3497            "bindings",
3498            "capabilities",
3499            "self_signals",
3500            "provenance",
3501        ] {
3502            assert!(
3503                encoded.get(optional).is_none(),
3504                "an absent {optional} declaration must stay absent on the wire"
3505            );
3506        }
3507        let decoded: ModuleManifest =
3508            serde_json::from_value(encoded).expect("builder manifest round-trips");
3509        assert_eq!(decoded, manifest);
3510    }
3511
3512    #[test]
3513    fn fully_populated_builder_manifest_matches_the_literal_wire_golden() {
3514        let manifest = ModuleManifest::builder("full-builder", "2.0.0")
3515            .display_name(Some("Example".to_string()))
3516            .unwrap()
3517            .hosts_third_party_code(false)
3518            .trust_tier(Some(TrustTier::Reviewed))
3519            .bindings(Some(Bindings {
3520                storage: StorageBinding {
3521                    kind: StorageKind::Sqlite,
3522                    scope: StorageScope::Project,
3523                    owns_schema: false,
3524                },
3525                vault_grants: Vec::new(),
3526                identity: IdentityBinding {
3527                    requires: vec![IdentityScope::Project],
3528                    optional: Vec::new(),
3529                },
3530            }))
3531            .provides(vec![ProviderRole::ToolProvider {
3532                tools: vec![Tool {
3533                    name: "read".to_string(),
3534                    description: None,
3535                    execution_mode: ExecutionMode::Pure,
3536                    schema: json!({"type": "object"}),
3537                }],
3538                identity_scope: vec![IdentityScope::Project],
3539                concurrency: Concurrency::Serial,
3540                emits_push: false,
3541                sub_supervises: false,
3542            }])
3543            .consumes(vec![ConsumerRole::ServiceClient {
3544                of: vec!["embedding.v2".to_string()],
3545            }])
3546            .capabilities(Some(CapabilityDeclarations {
3547                provides: vec!["embedding/v2".to_string()],
3548                requires: Vec::new(),
3549                must_never_reach: Vec::new(),
3550            }))
3551            .self_signals(Some(vec![SelfSignalDeclaration {
3552                name: "usage_poller".to_string(),
3553                kind: SelfSignalKind::Poller,
3554                effect: SelfSignalEffect::Observe,
3555                anchored_to: SignalAnchor::FixedInterval,
3556                cadence: Some(SignalCadence::Literal {
3557                    interval_ms: 60_000,
3558                }),
3559                domain: Some("provider-usage".to_string()),
3560                note: None,
3561            }]))
3562            .provenance(Some(ManifestProvenance {
3563                build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3564                build_git_sha_absence_reason: None,
3565                build_lock_digest: Some(
3566                    "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3567                ),
3568                wire_crate_version: Some("0.16.0".to_string()),
3569                store_schema_version: Some("42".to_string()),
3570                launch_nonce_source: None,
3571            }))
3572            .build();
3573
3574        assert_eq!(
3575            serde_json::to_vec(&manifest).expect("builder manifest serializes"),
3576            include_bytes!("../tests/golden/module_manifest_builder_full.json"),
3577            "the builder must match the fully populated manifest wire bytes"
3578        );
3579    }
3580
3581    #[test]
3582    fn hosts_third_party_code_preserves_booleans_and_ignores_invalid_values() {
3583        let legacy =
3584            serde_json::to_value(ModuleManifest::builder("provider", "1.0.0").build()).unwrap();
3585        assert!(legacy.get("hosts_third_party_code").is_none());
3586        for (wire, expected) in [
3587            (json!(false), Some(false)),
3588            (json!(true), Some(true)),
3589            (json!(null), None),
3590            (json!("false"), None),
3591            (json!(0), None),
3592        ] {
3593            let mut manifest = legacy.clone();
3594            manifest["hosts_third_party_code"] = wire;
3595            let decoded: ModuleManifest = serde_json::from_value(manifest).unwrap();
3596            assert_eq!(decoded.hosts_third_party_code, expected);
3597            assert_eq!(
3598                serde_json::to_value(decoded)
3599                    .unwrap()
3600                    .get("hosts_third_party_code"),
3601                expected.map(|value| json!(value)).as_ref()
3602            );
3603        }
3604    }
3605
3606    #[test]
3607    fn display_name_validator_enforces_scalar_bounds_and_safe_text() {
3608        for valid in [
3609            "Routing".to_string(),
3610            "名".repeat(40),
3611            "a".repeat(40),
3612            "e\u{301}".repeat(20),
3613        ] {
3614            assert!(validate_display_name(&valid).is_ok(), "{valid:?}");
3615        }
3616        let mut invalid = vec![
3617            "".to_string(),
3618            "a".repeat(41),
3619            "名".repeat(41),
3620            " Routing".to_string(),
3621            "Routing ".to_string(),
3622            "\u{2003}Routing".to_string(),
3623            "a\nb".to_string(),
3624            "a\u{0085}b".to_string(),
3625            "a\u{007f}b".to_string(),
3626        ];
3627        for code in [0x061c, 0x200e, 0x200f]
3628            .into_iter()
3629            .chain(0x202a..=0x202e)
3630            .chain(0x2066..=0x2069)
3631        {
3632            invalid.push(format!("a{}b", char::from_u32(code).unwrap()));
3633        }
3634        let accepted: Vec<_> = invalid
3635            .iter()
3636            .filter(|value| validate_display_name(value).is_ok())
3637            .collect();
3638        assert!(
3639            accepted.is_empty(),
3640            "invalid display names accepted: {accepted:?}"
3641        );
3642    }
3643
3644    #[test]
3645    fn display_name_builder_refuses_invalid_value() {
3646        let error = ModuleManifest::builder("provider", "1.0.0")
3647            .display_name(Some(" Routing".to_string()))
3648            .unwrap_err();
3649        assert!(error.to_string().contains("display_name"));
3650    }
3651
3652    #[test]
3653    fn display_name_manifest_round_trips_and_keeps_unknown_fields_lenient() {
3654        let manifest = ModuleManifest::builder("provider", "1.0.0")
3655            .display_name(Some("Routing".to_string()))
3656            .unwrap()
3657            .build();
3658        let mut wire = serde_json::to_value(&manifest).unwrap();
3659        assert_eq!(wire["display_name"], "Routing");
3660        wire["future_manifest_field"] = json!(true);
3661        assert_eq!(
3662            serde_json::from_value::<ModuleManifest>(wire.clone()).unwrap(),
3663            manifest
3664        );
3665        wire["display_name"] = json!("bad\nname");
3666        assert!(serde_json::from_value::<ModuleManifest>(wire)
3667            .unwrap_err()
3668            .to_string()
3669            .contains("display_name"));
3670    }
3671
3672    #[test]
3673    fn icon_name_grammar_and_bounds() {
3674        for valid in ["1", "brain", "message-square", "shield-check", "a-0-b"] {
3675            assert!(validate_icon(valid).is_ok(), "{valid}");
3676        }
3677        assert!(validate_icon(&"a".repeat(64)).is_ok());
3678
3679        for invalid in [
3680            "",
3681            "Brain",
3682            "text icon",
3683            "text_icon",
3684            "-brain",
3685            "brain-",
3686            "message--square",
3687            "brain\n",
3688            "bräin",
3689            &"a".repeat(65),
3690        ] {
3691            let error = ModuleManifest::builder("provider", "1.0.0")
3692                .icon(invalid)
3693                .unwrap_err();
3694            assert!(error.to_string().contains("icon"), "{invalid:?}: {error}");
3695        }
3696    }
3697
3698    #[test]
3699    fn old_manifest_with_unread_fields_decodes_and_round_trips_verbatim() {
3700        let raw = include_bytes!("../tests/golden/module_manifest_builder_full.json");
3701        let decoded: ModuleManifest =
3702            serde_json::from_slice(raw).expect("old manifest with all unread fields decodes");
3703
3704        assert_eq!(decoded.trust_tier, Some(TrustTier::Reviewed));
3705        assert!(!decoded.consumes.is_empty());
3706        assert!(decoded.bindings.is_some());
3707
3708        let reencoded = serde_json::to_vec(&decoded).expect("re-encode succeeds");
3709        assert_eq!(
3710            reencoded, raw,
3711            "old manifest relay stays byte-for-byte verbatim"
3712        );
3713    }
3714
3715    #[test]
3716    fn new_manifest_omits_unread_fields_on_wire_and_decodes_cleanly() {
3717        let raw = include_bytes!("../tests/golden/module_manifest_diet.json");
3718        let decoded: ModuleManifest =
3719            serde_json::from_slice(raw).expect("new manifest omitting unread fields decodes");
3720
3721        assert_eq!(decoded.trust_tier, None);
3722        assert!(decoded.consumes.is_empty());
3723        assert_eq!(decoded.bindings, None);
3724
3725        let pretty = format!("{}\n", serde_json::to_string_pretty(&decoded).unwrap());
3726        assert_eq!(
3727            pretty.as_bytes(),
3728            raw,
3729            "new manifest matches golden byte-for-byte without unread keys"
3730        );
3731
3732        let as_val: serde_json::Value = serde_json::to_value(&decoded).unwrap();
3733        assert!(
3734            as_val.get("trust_tier").is_none(),
3735            "no trust_tier on wire for new manifest"
3736        );
3737        assert!(
3738            as_val.get("consumes").is_none(),
3739            "no consumes on wire for empty consumes"
3740        );
3741        assert!(
3742            as_val.get("bindings").is_none(),
3743            "no bindings on wire for new manifest"
3744        );
3745    }
3746
3747    #[test]
3748    fn aft_manifest_fixture_matches_v1_contract() {
3749        let manifest = aft_manifest_fixture();
3750
3751        assert_eq!(manifest.module_id, "aft");
3752        let ProviderRole::ToolProvider {
3753            tools,
3754            identity_scope,
3755            concurrency,
3756            emits_push,
3757            sub_supervises,
3758        } = &manifest.provides[0]
3759        else {
3760            panic!("AFT fixture must expose one tool_provider role");
3761        };
3762
3763        assert_eq!(*concurrency, Concurrency::ModuleManaged);
3764        assert!(*emits_push);
3765        assert!(*sub_supervises);
3766        assert_eq!(
3767            identity_scope,
3768            &vec![IdentityScope::Session, IdentityScope::Project]
3769        );
3770        assert_eq!(
3771            tools
3772                .iter()
3773                .map(|tool| (tool.name.as_str(), tool.execution_mode))
3774                .collect::<Vec<_>>(),
3775            vec![
3776                ("read", ExecutionMode::Pure),
3777                ("grep", ExecutionMode::Pure),
3778                ("outline", ExecutionMode::Pure),
3779                ("semantic_search", ExecutionMode::Pure),
3780                ("edit", ExecutionMode::Mutating),
3781                ("write", ExecutionMode::Mutating),
3782                ("bash", ExecutionMode::Unfenceable),
3783            ]
3784        );
3785    }
3786
3787    #[test]
3788    fn tool_provider_role_tag_serializes_as_snake_case() {
3789        let manifest = aft_manifest_fixture();
3790        let value = serde_json::to_value(&manifest).unwrap();
3791
3792        assert_eq!(value["provides"][0]["role"], "tool_provider");
3793    }
3794
3795    #[test]
3796    fn manifest_without_capabilities_preserves_the_existing_wire_shape() {
3797        let manifest = aft_manifest_fixture();
3798        let encoded = serde_json::to_value(&manifest).expect("manifest serializes");
3799        assert!(encoded.get("capabilities").is_none());
3800
3801        let decoded: ModuleManifest =
3802            serde_json::from_value(encoded).expect("legacy manifest parses");
3803        assert_eq!(decoded.capabilities, None);
3804    }
3805
3806    #[test]
3807    fn capability_identifier_lexical_grammar_accepts_only_pinned_forms() {
3808        for identifier in [
3809            "a/v1",
3810            "credentials-provider/v1",
3811            "a1-b2/v4294967295",
3812            "a123456789012345678901234567890123456789012345678901234567890123/v1",
3813        ] {
3814            assert!(
3815                is_valid_capability_identifier(identifier),
3816                "identifier must be accepted: {identifier}"
3817            );
3818        }
3819
3820        for identifier in [
3821            "credentials-Provider/v1",
3822            "credentials-provider/v01",
3823            "credentials-provider-/v1",
3824            "credentials--provider/v1",
3825            "Credentials-provider/v1",
3826            "credentials-provider/1",
3827            "credentials provider/v1",
3828            "credentials-provider/v0",
3829            "credentials-provider/v4294967296",
3830            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
3831        ] {
3832            assert!(
3833                !is_valid_capability_identifier(identifier),
3834                "identifier must be rejected: {identifier}"
3835            );
3836        }
3837    }
3838
3839    #[test]
3840    fn capability_grammar_errors_redact_secret_shaped_values() {
3841        let error = validate_manifest_capability_grammar(&json!({
3842            "capabilities": { "provides": ["sk-secret-value/v0"] }
3843        }))
3844        .expect_err("secret-shaped capability identifier is malformed");
3845        assert_eq!(error.field(), "capabilities.provides[0]");
3846        assert_eq!(error.value(), "<redacted>");
3847        assert!(!error.to_string().contains("sk-secret-value"));
3848    }
3849
3850    /// Builder sentinels are the strings tooling emits where it means "no
3851    /// value" (shell fallbacks say `unknown`, not `unavailable`); publishing
3852    /// one as a build fact is the well-formed lie the provenance contract
3853    /// names. The helper must map every sentinel, any casing, to field
3854    /// omission — and must keep a canonical real value intact (the control arm,
3855    /// so the filter cannot pass by refusing everything).
3856    #[test]
3857    fn provenance_builder_sentinels_become_field_omission() {
3858        for sentinel in [
3859            "unknown",
3860            "UNKNOWN",
3861            "Unknown",
3862            "unavailable",
3863            "none",
3864            "None",
3865            "  unknown  ",
3866            "",
3867        ] {
3868            let p = build_provenance_from_source(
3869                BuildGitShaSource::Git {
3870                    revision: sentinel,
3871                    tree_state: GitTreeState::Clean,
3872                },
3873                Some(sentinel),
3874                Some(sentinel),
3875            )
3876            .expect("sentinels are omitted before form validation");
3877            assert_eq!(
3878                (
3879                    p.build_git_sha,
3880                    p.build_git_sha_absence_reason,
3881                    p.build_lock_digest,
3882                    p.store_schema_version,
3883                ),
3884                (
3885                    None,
3886                    Some(BuildGitShaAbsenceReason::NeverDerived),
3887                    None,
3888                    None,
3889                ),
3890                "sentinel {sentinel:?} must be omitted, not published"
3891            );
3892        }
3893        let real = build_provenance_from_source(
3894            BuildGitShaSource::Git {
3895                revision: "0123456789abcdef0123456789abcdef01234567",
3896                tree_state: GitTreeState::Clean,
3897            },
3898            None,
3899            Some("9"),
3900        )
3901        .expect("canonical build revision is accepted");
3902        assert_eq!(
3903            real.build_git_sha.as_deref(),
3904            Some("0123456789abcdef0123456789abcdef01234567")
3905        );
3906        assert_eq!(real.store_schema_version.as_deref(), Some("9"));
3907        // The always-knowable fact: an SDK-built block always carries a crate
3908        // version, so it is never empty; that is why the contract omits a
3909        // field when it is absent rather than publishing a sentinel.
3910        assert_eq!(
3911            real.wire_crate_version.as_deref(),
3912            Some(crate::SUBC_PROTOCOL_CRATE_VERSION)
3913        );
3914    }
3915
3916    #[test]
3917    fn build_provenance_accepts_canonical_sha_and_lock_digest() {
3918        let provenance = build_provenance_from_source(
3919            BuildGitShaSource::Git {
3920                revision: " 0123456789abcdef0123456789abcdef01234567 ",
3921                tree_state: GitTreeState::Clean,
3922            },
3923            Some(" abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789 "),
3924            Some(" schema-v3 "),
3925        )
3926        .expect("canonical build facts are accepted");
3927
3928        assert_eq!(
3929            provenance,
3930            ManifestProvenance {
3931                build_git_sha: Some("0123456789abcdef0123456789abcdef01234567".to_string()),
3932                build_git_sha_absence_reason: None,
3933                build_lock_digest: Some(
3934                    "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3935                ),
3936                wire_crate_version: Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string()),
3937                store_schema_version: Some("schema-v3".to_string()),
3938                launch_nonce_source: None,
3939            }
3940        );
3941    }
3942
3943    #[test]
3944    fn build_provenance_refuses_an_abbreviated_git_sha() {
3945        let error = build_provenance_from_source(
3946            BuildGitShaSource::Git {
3947                revision: "0123456789ab",
3948                tree_state: GitTreeState::Clean,
3949            },
3950            None,
3951            None,
3952        )
3953        .expect_err("a 12-character abbreviation is not canonical");
3954
3955        assert_eq!(error.field(), "build_git_sha");
3956        assert_eq!(error.length(), 12);
3957        assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3958        assert_eq!(
3959            error.to_string(),
3960            "invalid manifest provenance form: field build_git_sha has length 12; canonical form is exactly 40 lowercase hexadecimal characters"
3961        );
3962    }
3963
3964    #[test]
3965    fn build_provenance_refuses_an_abbreviated_lock_digest() {
3966        let error = build_provenance_from_source(
3967            BuildGitShaSource::NeverDerived,
3968            Some("0123456789abcdef"),
3969            None,
3970        )
3971        .expect_err("a 16-character digest is not canonical");
3972
3973        assert_eq!(error.field(), "build_lock_digest");
3974        assert_eq!(error.length(), 16);
3975        assert_eq!(error.canonical_form(), BUILD_LOCK_DIGEST_CANONICAL_FORM);
3976    }
3977
3978    #[test]
3979    fn build_provenance_refuses_uppercase_hex() {
3980        let uppercase_sha = "A".repeat(40);
3981        let error = build_provenance_from_source(
3982            BuildGitShaSource::Git {
3983                revision: &uppercase_sha,
3984                tree_state: GitTreeState::Clean,
3985            },
3986            None,
3987            None,
3988        )
3989        .expect_err("uppercase hexadecimal is not canonical");
3990
3991        assert_eq!(error.field(), "build_git_sha");
3992        assert_eq!(error.length(), 40);
3993        assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
3994    }
3995
3996    #[test]
3997    fn build_provenance_refuses_dirty_revision_stamp_claimed_clean() {
3998        let error = build_provenance_from_source(
3999            BuildGitShaSource::Git {
4000                revision: "0123456789abcdef0123456789abcdef01234567-dirty",
4001                tree_state: GitTreeState::Clean,
4002            },
4003            None,
4004            None,
4005        )
4006        .expect_err("a dirty stamp is not a canonical build revision");
4007
4008        assert_eq!(error.field(), "build_git_sha");
4009        assert_eq!(error.length(), 46);
4010        assert_eq!(error.canonical_form(), BUILD_GIT_SHA_CANONICAL_FORM);
4011    }
4012
4013    #[test]
4014    fn build_provenance_keeps_a_lock_digest_when_identity_is_unavailable() {
4015        let provenance = build_provenance_from_source(
4016            BuildGitShaSource::Git {
4017                revision: "unavailable",
4018                tree_state: GitTreeState::Clean,
4019            },
4020            Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"),
4021            None,
4022        )
4023        .expect("sentinel SHA is omitted before the valid lock digest is checked");
4024
4025        assert_eq!(provenance.build_git_sha, None);
4026        assert_eq!(
4027            provenance.build_lock_digest,
4028            Some("abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string())
4029        );
4030        assert_eq!(
4031            provenance.wire_crate_version,
4032            Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
4033        );
4034    }
4035
4036    #[test]
4037    fn build_provenance_omits_fully_unavailable_inputs() {
4038        let provenance = build_provenance_from_source(
4039            BuildGitShaSource::NeverDerived,
4040            Some(" unavailable "),
4041            Some("   "),
4042        )
4043        .expect("omitted and sentinel inputs are not form errors");
4044
4045        assert_eq!(provenance.build_git_sha, None);
4046        assert_eq!(provenance.build_lock_digest, None);
4047        assert_eq!(provenance.store_schema_version, None);
4048        assert_eq!(
4049            provenance.wire_crate_version,
4050            Some(crate::SUBC_PROTOCOL_CRATE_VERSION.to_string())
4051        );
4052    }
4053
4054    #[test]
4055    fn legacy_build_provenance_keeps_master_wire_bytes_without_an_absence_reason() {
4056        let revision = "0123456789abcdef0123456789abcdef01234567";
4057        for (input, expected) in [
4058            (
4059                Some(revision),
4060                format!(
4061                    r#"{{"build_git_sha":"{revision}","wire_crate_version":"{}"}}"#,
4062                    crate::SUBC_PROTOCOL_CRATE_VERSION
4063                ),
4064            ),
4065            (
4066                None,
4067                format!(
4068                    r#"{{"wire_crate_version":"{}"}}"#,
4069                    crate::SUBC_PROTOCOL_CRATE_VERSION
4070                ),
4071            ),
4072            (
4073                Some("unknown"),
4074                format!(
4075                    r#"{{"wire_crate_version":"{}"}}"#,
4076                    crate::SUBC_PROTOCOL_CRATE_VERSION
4077                ),
4078            ),
4079        ] {
4080            let provenance = build_provenance(input, None, None)
4081                .expect("the legacy build facts remain constructible");
4082            assert_eq!(provenance.build_git_sha_absence_reason, None);
4083            assert_eq!(
4084                serde_json::to_string(&provenance).expect("legacy provenance serializes"),
4085                expected
4086            );
4087        }
4088    }
4089
4090    #[test]
4091    fn build_provenance_derives_git_sha_absence_from_the_stamping_inputs() {
4092        let revision = "0123456789abcdef0123456789abcdef01234567";
4093        let cases = [
4094            (
4095                BuildGitShaSource::Git {
4096                    revision,
4097                    tree_state: GitTreeState::Clean,
4098                },
4099                Some(revision),
4100                None,
4101            ),
4102            (
4103                BuildGitShaSource::Git {
4104                    revision,
4105                    tree_state: GitTreeState::Dirty,
4106                },
4107                None,
4108                Some(BuildGitShaAbsenceReason::DeclinedDirty),
4109            ),
4110            (
4111                BuildGitShaSource::NeverDerived,
4112                None,
4113                Some(BuildGitShaAbsenceReason::NeverDerived),
4114            ),
4115            (
4116                BuildGitShaSource::NoGitDir,
4117                None,
4118                Some(BuildGitShaAbsenceReason::NoGitDir),
4119            ),
4120        ];
4121
4122        for (source, expected_sha, expected_reason) in cases {
4123            let provenance = build_provenance_from_source(source, None, None)
4124                .expect("every stamping state constructs honest provenance");
4125            assert_eq!(provenance.build_git_sha.as_deref(), expected_sha);
4126            assert_eq!(provenance.build_git_sha_absence_reason, expected_reason);
4127        }
4128    }
4129
4130    #[test]
4131    fn unknown_git_sha_absence_reason_round_trips_byte_faithfully() {
4132        let wire = format!(
4133            r#"{{"build_git_sha_absence_reason":"future_stamper_state","wire_crate_version":"{}"}}"#,
4134            crate::SUBC_PROTOCOL_CRATE_VERSION
4135        );
4136        let provenance: ManifestProvenance =
4137            serde_json::from_str(&wire).expect("future absence reasons remain readable");
4138
4139        assert_eq!(
4140            provenance.build_git_sha_absence_reason,
4141            Some(BuildGitShaAbsenceReason::ForwardCompatibleUnknown(
4142                "future_stamper_state".to_string()
4143            ))
4144        );
4145        assert_eq!(
4146            serde_json::to_string(&provenance).expect("future absence reason reserializes"),
4147            wire
4148        );
4149    }
4150
4151    #[test]
4152    fn provenance_rejects_an_absence_reason_beside_a_declared_commit() {
4153        let error = serde_json::from_value::<ManifestProvenance>(json!({
4154            "build_git_sha": "0123456789abcdef0123456789abcdef01234567",
4155            "build_git_sha_absence_reason": "declined_dirty"
4156        }))
4157        .expect_err("a declared commit cannot also claim an absence reason");
4158
4159        assert!(error.to_string().contains(
4160            "build_git_sha_absence_reason has must be omitted when build_git_sha is present"
4161        ));
4162    }
4163
4164    #[test]
4165    fn rich_ui_descriptor_is_optional_and_round_trips_when_present() {
4166        let manifest = ModuleManifest::builder("provider", "1.0.0").build();
4167        assert_eq!(
4168            serde_json::to_string(&manifest).unwrap(),
4169            r#"{"module_id":"provider","module_version":"1.0.0","protocol_ver":2,"provides":[]}"#
4170        );
4171
4172        let descriptor = RichUiDescriptor::new(
4173            "ckios.richui.manifest/1",
4174            format!("sha256:{}", "a".repeat(64)),
4175            128,
4176            2,
4177        );
4178        let manifest = ModuleManifest::builder("provider", "1.0.0")
4179            .rich_ui(Some(descriptor.clone()))
4180            .build();
4181        let wire = serde_json::to_string(&manifest).unwrap();
4182        assert!(wire.contains("\"rich_ui\":{\"schema\":\"ckios.richui.manifest/1\""));
4183        assert_eq!(
4184            serde_json::from_str::<ModuleManifest>(&wire)
4185                .unwrap()
4186                .rich_ui,
4187            Some(descriptor)
4188        );
4189    }
4190
4191    #[test]
4192    fn rich_ui_descriptor_validation_names_each_invalid_field() {
4193        let good = json!({
4194            "schema": "ckios.richui.manifest/1",
4195            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
4196            "bytes": 1,
4197            "chunks": 1
4198        });
4199        let hello = json!({"manifest": {"rich_ui": good.clone()}});
4200        assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4201
4202        for (field, value) in [
4203            ("schema", json!("bad schema")),
4204            (
4205                "manifest_digest",
4206                json!(format!("sha256:{}", "A".repeat(64))),
4207            ),
4208            ("bytes", json!(0)),
4209            ("chunks", json!(1025)),
4210        ] {
4211            let mut invalid = hello.clone();
4212            invalid["manifest"]["rich_ui"][field] = value;
4213            let error = validate_hello_rich_ui_descriptor(&invalid)
4214                .expect_err("an invalid descriptor field must be refused");
4215            assert_eq!(error.field(), format!("rich_ui.{field}"));
4216        }
4217
4218        let mut hello = hello;
4219        hello["manifest"]["rich_ui"] = Value::Null;
4220        let error = validate_hello_rich_ui_descriptor(&hello)
4221            .expect_err("null is not an absent descriptor");
4222        assert_eq!(error.field(), "rich_ui");
4223    }
4224
4225    #[test]
4226    fn rich_ui_descriptor_validation_accepts_inclusive_bounds() {
4227        let hello = json!({"manifest": {"rich_ui": {
4228            "schema": "a".repeat(64),
4229            "manifest_digest": format!("sha256:{}", "f".repeat(64)),
4230            "bytes": 16_777_216,
4231            "chunks": 1024
4232        }}});
4233        assert!(validate_hello_rich_ui_descriptor(&hello).is_ok());
4234    }
4235}