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