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