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