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