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