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