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