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