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