Skip to main content

subc_protocol/
manifest.rs

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