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