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