Skip to main content

subc_protocol/
session.rs

1//! Session route control wire contract.
2//!
3//! subc has two distinct channel-0 handshakes. Module registration is the
4//! module-to-subc `HELLO`/`HELLO_ACK` handshake that registers the manifest and
5//! liveness. Route bind is the client-to-subc-to-module request/response
6//! handshake that binds one client route to a module route channel.
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::{
14    call_mode::CallMode,
15    manifest::{CapabilityDeclarations, ProviderRole},
16    scope::{
17        ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
18        ScopeStatus,
19    },
20    BindIdentity, Principal, RouteCloseReason, RouteTarget,
21};
22
23pub const MODULE_CONTROL_OP_HEALTH_CHECK: &str = "health.check";
24pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE: &str = "catalog.update";
25pub const MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS: &str =
26    "catalog.update_role_declarations";
27
28#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(rename_all = "snake_case")]
30pub enum HealthStatus {
31    Ok,
32    Degraded,
33    Failing,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub struct HealthReport {
38    pub status: HealthStatus,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub detail: Option<String>,
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub metrics: Option<Value>,
43}
44
45impl HealthReport {
46    pub fn ok() -> Self {
47        Self {
48            status: HealthStatus::Ok,
49            detail: None,
50            metrics: None,
51        }
52    }
53}
54
55/// subc-to-module channel-0 control RPC body.
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[serde(tag = "op")]
58// RouteBind carries the complete bind metadata, while HealthCheck is a marker;
59// preserving the direct wire shape is more useful than boxing every bind field.
60#[allow(clippy::large_enum_variant)]
61pub enum ModuleControlRequest {
62    #[serde(rename = "route.bind")]
63    RouteBind {
64        route_channel: u16,
65        epoch: u32,
66        target: RouteTarget,
67        identity: BindIdentity,
68        /// The daemon's attestation of the consumer, and the only field here a
69        /// provider may grant privilege on.
70        ///
71        /// `Reserved` is minted at exactly one place in the daemon, on the branch
72        /// where the consumer's launch nonce matched a supervised spawn — the
73        /// function that checks is the function that mints, so the value cannot
74        /// exist without the check having run. That property is what a provider is
75        /// relying on, and it is the reason to key authority on this rather than on
76        /// `identity`, which is client-supplied and unattested (see BindIdentity).
77        ///
78        /// Absent means the daemon made no attestation, which is not the same as a
79        /// denial: it is the shape a pre-attestation peer sends. Treat it as
80        /// unattested rather than as trusted-by-default.
81        #[serde(default, skip_serializing_if = "Option::is_none")]
82        principal: Option<Principal>,
83        /// Consumer-declared reverse-request families and provider-contract
84        /// capabilities for the route. For example, `content/v1` declares that
85        /// the consumer understands the tool-provider content result format.
86        /// This remains an unverified declaration that grants nothing; a provider
87        /// that over-trusts it may still send reverse requests that later time
88        /// out or deny. Providers must treat an absent field as no declared
89        /// capability. The vocabulary is open strings; known MCP method-family
90        /// values today are "elicitation", "sampling", and "roots".
91        #[serde(default, skip_serializing_if = "Option::is_none")]
92        consumer_capabilities: Option<Vec<String>>,
93        /// The versions of provider roles the consumer speaks on this route,
94        /// role name to version (`{"tool-provider": "v1"}`), copied from the
95        /// consumer's `route.open` unchanged. Like `consumer_capabilities` it
96        /// is the consumer's unverified declaration and grants nothing; a
97        /// provider uses it to choose which version of a role's wire shape to
98        /// speak. The daemon has checked it with [`validate_role_versions`] and
99        /// never sends an empty map. Absent means the consumer declared none:
100        /// a legacy consumer, or a daemon that predates the field.
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        role_versions: Option<BTreeMap<String, String>>,
103        /// Opaque admission facts supplied by the configured carrier module.
104        #[serde(default, skip_serializing_if = "Option::is_none")]
105        admission_facts: Option<Value>,
106        /// The daemon's stamp of the scope the route was admitted under, taken
107        /// from the owner's synced record at admission. Like `principal`, it is
108        /// the daemon's, never the opener's: a provider may act on it (on
109        /// `owner_authorized`, `delegates` and `agent_id` together), and must
110        /// treat it as fixed for the route's life, because a change that
111        /// revokes authority closes the route.
112        ///
113        /// Absent means the route was opened without a scope, or by a daemon
114        /// that predates scopes. A provider that needs a scope refuses the bind.
115        #[serde(default, skip_serializing_if = "Option::is_none")]
116        scope: Option<ScopeStamp>,
117        /// The daemon-derived mode, sent only to targets declaring
118        /// [`crate::call_mode::CALL_MODES_CAPABILITY`]. If absent, readers derive
119        /// the mode from `scope` with [`crate::call_mode::derive_call_mode`].
120        /// Providers must refuse an unknown mode.
121        #[serde(default, skip_serializing_if = "Option::is_none")]
122        call_mode: Option<CallMode>,
123    },
124    #[serde(rename = "health.check")]
125    HealthCheck {},
126}
127
128/// One-way subc-to-module channel-0 control command.
129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
130#[serde(tag = "op")]
131pub enum ModuleControlCommand {
132    #[serde(rename = "module.draining")]
133    Draining {
134        reason: RouteCloseReason,
135        /// Absolute Unix-millisecond deadline for this drain.
136        ///
137        /// WALL CLOCK, WHILE THE DAEMON ENFORCES THE CEILING ON A
138        /// SUSPEND-EXCLUDING MONOTONIC CLOCK (`Instant`, supervise.rs). Both
139        /// processes share one host so `CLOCK_REALTIME` agrees exactly, and the
140        /// two clocks diverge only across host sleep: `Instant` stops, wall does
141        /// not. So a module that sleeps mid-drain wakes to a deadline further in
142        /// the past than the daemon's own ceiling, computes LESS remaining time
143        /// than it has, and seals early.
144        ///
145        /// That direction is deliberate and is the safe one — a module stopping
146        /// early loses nothing, since the daemon kills at its own ceiling
147        /// regardless. The reverse (a module believing it has time the daemon
148        /// has already spent) is the failure this ordering avoids. A module must
149        /// therefore treat this as "no later than", never as a grant.
150        deadline_ms: u64,
151    },
152}
153
154/// Module-to-subc channel-0 response body.
155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
156#[serde(tag = "op")]
157pub enum ModuleControlResponse {
158    /// ACK-only success. Rejections use the `FrameType::Error` lane.
159    #[serde(rename = "route.bind")]
160    RouteBindAck {},
161    #[serde(rename = "health.check")]
162    HealthCheck {
163        status: HealthStatus,
164        #[serde(default, skip_serializing_if = "Option::is_none")]
165        detail: Option<String>,
166        #[serde(default, skip_serializing_if = "Option::is_none")]
167        metrics: Option<Value>,
168    },
169}
170
171/// Module-originated channel-0 control RPC body.
172///
173/// This is intentionally separate from [`ModuleControlRequest`]: that enum is the
174/// daemon-to-module direction (`route.bind`, `health.check`), while these bodies
175/// are sent by an already-registered module to subc on a `REQUEST` frame.
176#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
177#[serde(tag = "op")]
178#[non_exhaustive]
179pub enum ModuleControlRequestFromModule {
180    /// Ask the daemon whether a stored source may still open its route.
181    #[serde(rename = "route.authorize")]
182    RouteAuthorize {
183        principal: Principal,
184        scope: crate::scope::RouteAuthorizeScope,
185        target: String,
186        expected: crate::scope::RouteAuthorizeExpected,
187    },
188    #[serde(rename = "catalog.update")]
189    CatalogUpdate {
190        provides: Vec<ProviderRole>,
191        /// An attested replacement for the static capability declaration emitted
192        /// by the module's current manifest. `None` preserves the prior
193        /// declaration so existing role-only catalog updates remain byte-identical.
194        #[serde(default, skip_serializing_if = "Option::is_none")]
195        capabilities: Option<CapabilityDeclarations>,
196        /// Updates readiness without re-registering. `None` leaves it unchanged.
197        ///
198        /// Both directions are allowed, but repeatedly flapping readiness looks
199        /// like a restart storm to callers and is a defect in the module.
200        #[serde(default, skip_serializing_if = "Option::is_none")]
201        ready: Option<bool>,
202    },
203    /// Replace the complete role-declaration map; an empty object clears it.
204    #[serde(rename = "catalog.update_role_declarations")]
205    CatalogUpdateRoleDeclarations {
206        /// Kept raw so malformed maps receive a reasoned daemon refusal rather
207        /// than being dropped by the manifest's lenient HELLO decoding.
208        #[serde(deserialize_with = "Value::deserialize")]
209        role_declarations: Value,
210    },
211    #[serde(rename = "supervisor.live_roots")]
212    LiveRoots {},
213    #[serde(rename = "policy_root.get")]
214    PolicyRoot(crate::policy_root::GetPolicyRoot),
215    #[serde(rename = "policy_root.rotate")]
216    PolicyRootRotate(crate::policy_root::RotatePolicyRoot),
217    /// Attribute agent-requested command roots to the declaring module.
218    /// Only the module's supervised connection may send this operation.
219    /// `known`, when present, replaces its complete live root set. The reply
220    /// is an empty object; invalid roots are ignored independently.
221    #[serde(rename = "supervisor.agent_commands")]
222    AgentCommands {
223        started: Vec<AgentCommandRoot>,
224        finished: Vec<AgentCommandFinished>,
225        #[serde(default, skip_serializing_if = "Option::is_none")]
226        known: Option<Vec<AgentCommandRoot>>,
227    },
228    /// Register this module's full scope set. The owner is the module whose
229    /// registered connection sends it; nothing in the body names the owner.
230    /// Per-record refusals come back in the reply; a refusal of the whole sync
231    /// (not the owner's sync authority, a stale generation, a bound exceeded)
232    /// is an `Error` frame and changes nothing.
233    #[serde(rename = "scope.sync")]
234    ScopeSync {
235        generation: u64,
236        scopes: Vec<ScopeRecord>,
237    },
238    /// Change selected scopes after the daemon accepts a full `scope.sync` from
239    /// this connection. Shares the full sync's generation sequence. Unlike a
240    /// full sync, omitting a scope does not end it; expiry processing still runs.
241    /// A whole-call refusal is an `Error` frame and changes nothing.
242    #[serde(rename = "scope.apply")]
243    ScopeApply {
244        generation: u64,
245        upsert: Vec<ScopeRecord>,
246        end: Vec<ScopeEnd>,
247    },
248    /// Read one scope's current state.
249    #[serde(rename = "scope.describe")]
250    ScopeDescribe {
251        owner: Principal,
252        #[serde(rename = "ref")]
253        scope_ref: String,
254    },
255}
256
257/// A command's PID and kernel start time in milliseconds since the Unix epoch.
258/// Obtain the time through `subc_os::process_start_time_ms`, not a wall clock.
259#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
260pub struct AgentCommandRoot {
261    pub pid: u32,
262    pub start_time_ms: u64,
263}
264
265/// A completed declared root. CPU includes reaped descendants where available.
266#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
267pub struct AgentCommandFinished {
268    pub pid: u32,
269    pub start_time_ms: u64,
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub cpu_ms: Option<u64>,
272}
273
274/// Counts of routes for one canonical project root.
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276pub struct LiveRoot {
277    pub project_root: std::path::PathBuf,
278    pub bound: u64,
279    pub pending: u64,
280}
281
282/// subc's channel-0 response body for module-originated control RPCs.
283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
284#[serde(tag = "op")]
285// ScopeDescribe carries a complete stamp. Keep its public fields inline to
286// preserve the response construction API instead of boxing a single variant.
287#[allow(clippy::large_enum_variant)]
288pub enum ModuleControlResponseToModule {
289    #[serde(rename = "catalog.update")]
290    CatalogUpdate {},
291    #[serde(rename = "catalog.update_role_declarations")]
292    CatalogUpdateRoleDeclarations {},
293    #[serde(rename = "supervisor.live_roots")]
294    LiveRoots {
295        roots: Vec<LiveRoot>,
296        unknown_root_bindings: u64,
297        total_bindings: u64,
298    },
299    #[serde(rename = "policy_root.get")]
300    PolicyRoot(crate::policy_root::PolicyRoot),
301    #[serde(rename = "policy_root.rotate")]
302    PolicyRootRotate(crate::policy_root::PolicyRootChange),
303    #[serde(rename = "scope.sync")]
304    ScopeSync {
305        generation: u64,
306        results: Vec<ScopeRecordResult>,
307        #[serde(default, skip_serializing_if = "Vec::is_empty")]
308        ended: Vec<ScopeEnded>,
309    },
310    #[serde(rename = "scope.apply")]
311    ScopeApply {
312        generation: u64,
313        results: Vec<ScopeRecordResult>,
314        end_results: Vec<ScopeEndResult>,
315        #[serde(default, skip_serializing_if = "Vec::is_empty")]
316        ended: Vec<ScopeEnded>,
317    },
318    #[serde(rename = "scope.describe")]
319    ScopeDescribe {
320        status: ScopeStatus,
321        /// The live epoch, or for `ended` the most recent epoch that ended.
322        #[serde(default, skip_serializing_if = "Option::is_none")]
323        scope_epoch: Option<u64>,
324        daemon_incarnation: String,
325        /// Whether the owner has synced since this daemon incarnation started.
326        owner_synced: bool,
327        /// Whether the owner is a module in the daemon's supervised roster.
328        owner_configured: bool,
329        /// The stamp fields, present only when `status` is `live`.
330        #[serde(default, skip_serializing_if = "Option::is_none")]
331        scope: Option<ScopeStamp>,
332    },
333}
334
335/// A module's channel-0 request to confirm one in-flight write with the person.
336///
337/// This standalone body keeps the existing exhaustive module-control enums
338/// unchanged. The daemon validates the summary and the asking connection's
339/// permission before showing a prompt; constructing a request grants nothing.
340#[non_exhaustive]
341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
342pub struct OperatorConfirmRequest {
343    op: OperatorConfirmOp,
344    pub summary: String,
345    /// The caller's route channel as seen on the asking module's connection.
346    pub route_channel: u16,
347    /// The epoch of that route on the asking module's connection.
348    pub route_epoch: u32,
349    /// What the asking module says it is confirming. Absent (an older module)
350    /// means the same as an unrecognised kind: the person is prompted. Only
351    /// [`OperatorConfirmKind::Operation`] can ever be answered without a
352    /// prompt; [`OperatorConfirmKind::Enrollment`] always prompts.
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub kind: Option<OperatorConfirmKind>,
355    /// The management operation being confirmed, as the asking module's
356    /// manifest names it in `confirm_operations`. Meaningful only with
357    /// [`OperatorConfirmKind::Operation`]; absent means the person is prompted.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub operation: Option<String>,
360}
361
362impl OperatorConfirmRequest {
363    /// A request with neither `kind` nor `operation`, whose bytes match what
364    /// modules sent before those fields existed.
365    pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
366        Self {
367            op: OperatorConfirmOp::Confirm,
368            summary: summary.into(),
369            route_channel,
370            route_epoch,
371            kind: None,
372            operation: None,
373        }
374    }
375
376    /// Set or clear `kind`.
377    #[must_use]
378    pub fn with_kind(mut self, kind: Option<OperatorConfirmKind>) -> Self {
379        self.kind = kind;
380        self
381    }
382
383    /// Set or clear `operation`.
384    #[must_use]
385    pub fn with_operation(mut self, operation: Option<String>) -> Self {
386        self.operation = operation;
387        self
388    }
389}
390
391/// The `kind` of an [`OperatorConfirmRequest`].
392///
393/// A value from a newer module decodes as [`OperatorConfirmKind::Unknown`],
394/// keeping its spelling, rather than refusing the request. The daemon prompts
395/// for every kind except an explicit `operation`.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub enum OperatorConfirmKind {
398    /// A management operation the module declares in `confirm_operations`.
399    Operation,
400    /// Pairing or enrolling a device or credential. Always prompts.
401    Enrollment,
402    Unknown(String),
403}
404
405impl Serialize for OperatorConfirmKind {
406    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
407        serializer.serialize_str(match self {
408            Self::Operation => "operation",
409            Self::Enrollment => "enrollment",
410            Self::Unknown(value) => value,
411        })
412    }
413}
414
415impl<'de> Deserialize<'de> for OperatorConfirmKind {
416    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
417        Ok(match String::deserialize(deserializer)?.as_str() {
418            "operation" => Self::Operation,
419            "enrollment" => Self::Enrollment,
420            value => Self::Unknown(value.to_owned()),
421        })
422    }
423}
424
425/// A successful channel-0 reply to an [`OperatorConfirmRequest`].
426///
427/// Only `outcome: "confirmed"` confirms the write. Refusals use [`crate::ErrorBody`]
428/// instead. Readers must not treat an unknown outcome as confirmation.
429#[non_exhaustive]
430#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
431pub struct OperatorConfirmReply {
432    op: OperatorConfirmOp,
433    pub outcome: String,
434}
435
436impl OperatorConfirmReply {
437    pub fn confirmed() -> Self {
438        Self {
439            op: OperatorConfirmOp::Confirm,
440            outcome: "confirmed".to_string(),
441        }
442    }
443}
444
445// A required, single-valued field both emits the op and refuses a missing or
446// different op when decoding, without exposing a caller-editable tag.
447#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
448enum OperatorConfirmOp {
449    #[serde(rename = "operator.confirm")]
450    Confirm,
451}
452
453impl From<HealthReport> for ModuleControlResponse {
454    fn from(report: HealthReport) -> Self {
455        Self::HealthCheck {
456            status: report.status,
457            detail: report.detail,
458            metrics: report.metrics,
459        }
460    }
461}
462
463impl ModuleControlResponse {
464    pub fn health_report(&self) -> Option<HealthReport> {
465        match self {
466            Self::HealthCheck {
467                status,
468                detail,
469                metrics,
470            } => Some(HealthReport {
471                status: *status,
472                detail: detail.clone(),
473                metrics: metrics.clone(),
474            }),
475            Self::RouteBindAck {} => None,
476        }
477    }
478}
479
480/// Module-to-subc channel-0 push body.
481#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
482#[serde(tag = "op")]
483pub enum ModuleControlPush {
484    #[serde(rename = "route.status")]
485    RouteStatus {
486        route_channel: u16,
487        route_epoch: u32,
488        status: String,
489    },
490}
491
492/// The wire name of the `role_versions` field on `route.open` and
493/// `route.bind`, for the `detail.field` of the `invalid_request` error that
494/// refuses a malformed one.
495pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
496
497/// Most entries a `role_versions` map may hold.
498pub const MAX_ROLE_VERSIONS: usize = 8;
499
500/// The longest role name accepted in `role_versions`, in bytes.
501pub const MAX_ROLE_NAME_LEN: usize = 64;
502
503/// Why a `role_versions` map was refused.
504#[derive(Clone, Debug, PartialEq, Eq)]
505#[non_exhaustive]
506pub enum RoleVersionsError {
507    /// The map has more than [`MAX_ROLE_VERSIONS`] entries.
508    TooMany { count: usize },
509    /// A role name is not lowercase ASCII letters and digits in words joined
510    /// by single hyphens (`tool-provider`), or is longer than
511    /// [`MAX_ROLE_NAME_LEN`] bytes.
512    InvalidRole { role: String },
513    /// A version is not `v` followed by a positive integer without leading
514    /// zeros (`v1`, `v12`).
515    InvalidVersion { role: String, version: String },
516}
517
518impl RoleVersionsError {
519    /// The request field the error is about: always [`ROLE_VERSIONS_FIELD`].
520    pub fn field(&self) -> &'static str {
521        ROLE_VERSIONS_FIELD
522    }
523}
524
525impl std::fmt::Display for RoleVersionsError {
526    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527        match self {
528            Self::TooMany { count } => write!(
529                f,
530                "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
531            ),
532            Self::InvalidRole { role } => write!(
533                f,
534                "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
535                 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
536            ),
537            Self::InvalidVersion { role, version } => write!(
538                f,
539                "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
540                 followed by a positive integer without leading zeros"
541            ),
542        }
543    }
544}
545
546impl std::error::Error for RoleVersionsError {}
547
548/// Check a `role_versions` map: at most [`MAX_ROLE_VERSIONS`] entries, each
549/// role name matching `^[a-z0-9]+(-[a-z0-9]+)*$` in at most
550/// [`MAX_ROLE_NAME_LEN`] bytes, and each version matching `^v[1-9][0-9]*$`.
551///
552/// The daemon refuses a `route.open` that fails this, so a consumer can run
553/// the same check before sending. An empty map passes; the daemon treats it
554/// as no declaration at all.
555pub fn validate_role_versions(
556    role_versions: &BTreeMap<String, String>,
557) -> Result<(), RoleVersionsError> {
558    if role_versions.len() > MAX_ROLE_VERSIONS {
559        return Err(RoleVersionsError::TooMany {
560            count: role_versions.len(),
561        });
562    }
563    for (role, version) in role_versions {
564        if !is_role_name(role) {
565            return Err(RoleVersionsError::InvalidRole { role: role.clone() });
566        }
567        if !is_role_version(version) {
568            return Err(RoleVersionsError::InvalidVersion {
569                role: role.clone(),
570                version: version.clone(),
571            });
572        }
573    }
574    Ok(())
575}
576
577fn is_role_name(role: &str) -> bool {
578    !role.is_empty()
579        && role.len() <= MAX_ROLE_NAME_LEN
580        && role.split('-').all(|word| {
581            !word.is_empty()
582                && word
583                    .bytes()
584                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
585        })
586}
587
588fn is_role_version(version: &str) -> bool {
589    let bytes = version.as_bytes();
590    bytes.len() >= 2
591        && bytes[0] == b'v'
592        && (b'1'..=b'9').contains(&bytes[1])
593        && bytes[2..].iter().all(u8::is_ascii_digit)
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    #[test]
601    fn catalog_update_role_declarations_wire_round_trip() {
602        for declarations in [
603            serde_json::json!({"media-provider/v1": {"engines": ["image"]}}),
604            serde_json::json!({}),
605        ] {
606            let body = serde_json::json!({
607                "op": "catalog.update_role_declarations",
608                "role_declarations": declarations,
609            });
610            let request: ModuleControlRequestFromModule =
611                serde_json::from_value(body.clone()).unwrap();
612            assert_eq!(serde_json::to_value(request).unwrap(), body);
613        }
614        let body = serde_json::json!({"op": "catalog.update_role_declarations"});
615        let response: ModuleControlResponseToModule = serde_json::from_value(body.clone()).unwrap();
616        assert_eq!(serde_json::to_value(response).unwrap(), body);
617        assert!(serde_json::from_value::<ModuleControlRequestFromModule>(body).is_err());
618    }
619
620    fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
621        entries
622            .iter()
623            .map(|(role, version)| (role.to_string(), version.to_string()))
624            .collect()
625    }
626
627    #[test]
628    fn role_versions_accept_role_names_and_positive_versions() {
629        for entries in [
630            vec![],
631            vec![("tool-provider", "v1")],
632            vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
633        ] {
634            assert_eq!(
635                validate_role_versions(&map(&entries)),
636                Ok(()),
637                "{entries:?}"
638            );
639        }
640        let longest = "a".repeat(MAX_ROLE_NAME_LEN);
641        assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
642        let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
643            .map(|index| (format!("role-{index}"), "v1".to_string()))
644            .collect();
645        assert_eq!(validate_role_versions(&full), Ok(()));
646    }
647
648    #[test]
649    fn role_versions_refuse_malformed_role_names() {
650        let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
651        for role in [
652            "",
653            "Tool-provider",
654            "tool_provider",
655            "tool provider",
656            "-tool",
657            "tool-",
658            "tool--provider",
659            "tool.provider",
660            "outil-é",
661            too_long.as_str(),
662        ] {
663            let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
664            assert_eq!(
665                error,
666                RoleVersionsError::InvalidRole {
667                    role: role.to_string()
668                },
669                "{role:?}"
670            );
671            assert_eq!(error.field(), "role_versions");
672        }
673    }
674
675    #[test]
676    fn role_versions_refuse_malformed_versions() {
677        for version in [
678            "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
679        ] {
680            let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
681            assert_eq!(
682                error,
683                RoleVersionsError::InvalidVersion {
684                    role: "tool-provider".to_string(),
685                    version: version.to_string(),
686                },
687                "{version:?}"
688            );
689            assert_eq!(error.field(), "role_versions");
690        }
691    }
692
693    #[test]
694    fn role_versions_refuse_more_than_eight_entries() {
695        let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
696            .map(|index| (format!("role-{index}"), "v1".to_string()))
697            .collect();
698        let error = validate_role_versions(&nine).unwrap_err();
699        assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
700        assert_eq!(error.field(), "role_versions");
701        assert!(error.to_string().starts_with("role_versions"), "{error}");
702    }
703
704    #[test]
705    fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
706        let bind = |role_versions| ModuleControlRequest::RouteBind {
707            route_channel: 1,
708            epoch: 1,
709            target: crate::RouteTarget::ToolProvider {
710                module_id: "aft".to_string(),
711            },
712            identity: crate::BindIdentity::new("h", "s"),
713            principal: None,
714            consumer_capabilities: None,
715            role_versions,
716            admission_facts: None,
717            scope: None,
718            call_mode: None,
719        };
720        let absent = serde_json::to_value(bind(None)).unwrap();
721        assert!(absent.get("role_versions").is_none(), "{absent}");
722        let present = bind(Some(map(&[("tool-provider", "v1")])));
723        let encoded = serde_json::to_value(&present).unwrap();
724        assert_eq!(
725            encoded["role_versions"],
726            serde_json::json!({ "tool-provider": "v1" })
727        );
728        let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
729        assert_eq!(decoded, present);
730    }
731}
732
733#[cfg(test)]
734mod agent_command_tests {
735    use super::*;
736
737    #[test]
738    fn agent_commands_round_trip_start_finish_and_known_snapshot() {
739        let root = AgentCommandRoot {
740            pid: 42,
741            start_time_ms: 1_700_000_000_123,
742        };
743        let request = ModuleControlRequestFromModule::AgentCommands {
744            started: vec![root],
745            finished: vec![AgentCommandFinished {
746                pid: 43,
747                start_time_ms: root.start_time_ms,
748                cpu_ms: Some(100),
749            }],
750            known: Some(vec![root]),
751        };
752        let value = serde_json::to_value(&request).unwrap();
753        assert_eq!(
754            value,
755            serde_json::json!({"op":"supervisor.agent_commands",
756            "started":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}],
757            "finished":[{"pid":43,"start_time_ms":1_700_000_000_123_u64,"cpu_ms":100}],
758            "known":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}]})
759        );
760        assert_eq!(
761            serde_json::from_value::<ModuleControlRequestFromModule>(value).unwrap(),
762            request
763        );
764        let absent = ModuleControlRequestFromModule::AgentCommands {
765            started: Vec::new(),
766            finished: vec![AgentCommandFinished {
767                pid: 1,
768                start_time_ms: 2,
769                cpu_ms: None,
770            }],
771            known: None,
772        };
773        assert_eq!(
774            serde_json::to_value(absent).unwrap(),
775            serde_json::json!({"op":"supervisor.agent_commands",
776            "started":[],"finished":[{"pid":1,"start_time_ms":2}]})
777        );
778    }
779}