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