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