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