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