Skip to main content

subc_protocol/
manifest.rs

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