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    /// Attribute agent-requested command roots to the declaring module.
214    /// Only the module's supervised connection may send this operation.
215    /// `known`, when present, replaces its complete live root set. The reply
216    /// is an empty object; invalid roots are ignored independently.
217    #[serde(rename = "supervisor.agent_commands")]
218    AgentCommands {
219        started: Vec<AgentCommandRoot>,
220        finished: Vec<AgentCommandFinished>,
221        #[serde(default, skip_serializing_if = "Option::is_none")]
222        known: Option<Vec<AgentCommandRoot>>,
223    },
224    /// Register this module's full scope set. The owner is the module whose
225    /// registered connection sends it; nothing in the body names the owner.
226    /// Per-record refusals come back in the reply; a refusal of the whole sync
227    /// (not the owner's sync authority, a stale generation, a bound exceeded)
228    /// is an `Error` frame and changes nothing.
229    #[serde(rename = "scope.sync")]
230    ScopeSync {
231        generation: u64,
232        scopes: Vec<ScopeRecord>,
233    },
234    /// Change selected scopes after the daemon accepts a full `scope.sync` from
235    /// this connection. Shares the full sync's generation sequence. Unlike a
236    /// full sync, omitting a scope does not end it; expiry processing still runs.
237    /// A whole-call refusal is an `Error` frame and changes nothing.
238    #[serde(rename = "scope.apply")]
239    ScopeApply {
240        generation: u64,
241        upsert: Vec<ScopeRecord>,
242        end: Vec<ScopeEnd>,
243    },
244    /// Read one scope's current state.
245    #[serde(rename = "scope.describe")]
246    ScopeDescribe {
247        owner: Principal,
248        #[serde(rename = "ref")]
249        scope_ref: String,
250    },
251}
252
253/// A command's PID and kernel start time in milliseconds since the Unix epoch.
254/// Obtain the time through `subc_os::process_start_time_ms`, not a wall clock.
255#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
256pub struct AgentCommandRoot {
257    pub pid: u32,
258    pub start_time_ms: u64,
259}
260
261/// A completed declared root. CPU includes reaped descendants where available.
262#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
263pub struct AgentCommandFinished {
264    pub pid: u32,
265    pub start_time_ms: u64,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub cpu_ms: Option<u64>,
268}
269
270/// Counts of routes for one canonical project root.
271#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
272pub struct LiveRoot {
273    pub project_root: std::path::PathBuf,
274    pub bound: u64,
275    pub pending: u64,
276}
277
278/// subc's channel-0 response body for module-originated control RPCs.
279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
280#[serde(tag = "op")]
281// ScopeDescribe carries a complete stamp. Keep its public fields inline to
282// preserve the response construction API instead of boxing a single variant.
283#[allow(clippy::large_enum_variant)]
284pub enum ModuleControlResponseToModule {
285    #[serde(rename = "catalog.update")]
286    CatalogUpdate {},
287    #[serde(rename = "catalog.update_role_declarations")]
288    CatalogUpdateRoleDeclarations {},
289    #[serde(rename = "supervisor.live_roots")]
290    LiveRoots {
291        roots: Vec<LiveRoot>,
292        unknown_root_bindings: u64,
293        total_bindings: u64,
294    },
295    #[serde(rename = "scope.sync")]
296    ScopeSync {
297        generation: u64,
298        results: Vec<ScopeRecordResult>,
299        #[serde(default, skip_serializing_if = "Vec::is_empty")]
300        ended: Vec<ScopeEnded>,
301    },
302    #[serde(rename = "scope.apply")]
303    ScopeApply {
304        generation: u64,
305        results: Vec<ScopeRecordResult>,
306        end_results: Vec<ScopeEndResult>,
307        #[serde(default, skip_serializing_if = "Vec::is_empty")]
308        ended: Vec<ScopeEnded>,
309    },
310    #[serde(rename = "scope.describe")]
311    ScopeDescribe {
312        status: ScopeStatus,
313        /// The live epoch, or for `ended` the most recent epoch that ended.
314        #[serde(default, skip_serializing_if = "Option::is_none")]
315        scope_epoch: Option<u64>,
316        daemon_incarnation: String,
317        /// Whether the owner has synced since this daemon incarnation started.
318        owner_synced: bool,
319        /// Whether the owner is a module in the daemon's supervised roster.
320        owner_configured: bool,
321        /// The stamp fields, present only when `status` is `live`.
322        #[serde(default, skip_serializing_if = "Option::is_none")]
323        scope: Option<ScopeStamp>,
324    },
325}
326
327/// A module's channel-0 request to confirm one in-flight write with the person.
328///
329/// This standalone body keeps the existing exhaustive module-control enums
330/// unchanged. The daemon validates the summary and the asking connection's
331/// permission before showing a prompt; constructing a request grants nothing.
332#[non_exhaustive]
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334pub struct OperatorConfirmRequest {
335    op: OperatorConfirmOp,
336    pub summary: String,
337    /// The caller's route channel as seen on the asking module's connection.
338    pub route_channel: u16,
339    /// The epoch of that route on the asking module's connection.
340    pub route_epoch: u32,
341    /// What the asking module says it is confirming. Absent (an older module)
342    /// means the same as an unrecognised kind: the person is prompted. Only
343    /// [`OperatorConfirmKind::Operation`] can ever be answered without a
344    /// prompt; [`OperatorConfirmKind::Enrollment`] always prompts.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub kind: Option<OperatorConfirmKind>,
347    /// The management operation being confirmed, as the asking module's
348    /// manifest names it in `confirm_operations`. Meaningful only with
349    /// [`OperatorConfirmKind::Operation`]; absent means the person is prompted.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub operation: Option<String>,
352}
353
354impl OperatorConfirmRequest {
355    /// A request with neither `kind` nor `operation`, whose bytes match what
356    /// modules sent before those fields existed.
357    pub fn new(summary: impl Into<String>, route_channel: u16, route_epoch: u32) -> Self {
358        Self {
359            op: OperatorConfirmOp::Confirm,
360            summary: summary.into(),
361            route_channel,
362            route_epoch,
363            kind: None,
364            operation: None,
365        }
366    }
367
368    /// Set or clear `kind`.
369    #[must_use]
370    pub fn with_kind(mut self, kind: Option<OperatorConfirmKind>) -> Self {
371        self.kind = kind;
372        self
373    }
374
375    /// Set or clear `operation`.
376    #[must_use]
377    pub fn with_operation(mut self, operation: Option<String>) -> Self {
378        self.operation = operation;
379        self
380    }
381}
382
383/// The `kind` of an [`OperatorConfirmRequest`].
384///
385/// A value from a newer module decodes as [`OperatorConfirmKind::Unknown`],
386/// keeping its spelling, rather than refusing the request. The daemon prompts
387/// for every kind except an explicit `operation`.
388#[derive(Debug, Clone, PartialEq, Eq)]
389pub enum OperatorConfirmKind {
390    /// A management operation the module declares in `confirm_operations`.
391    Operation,
392    /// Pairing or enrolling a device or credential. Always prompts.
393    Enrollment,
394    Unknown(String),
395}
396
397impl Serialize for OperatorConfirmKind {
398    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
399        serializer.serialize_str(match self {
400            Self::Operation => "operation",
401            Self::Enrollment => "enrollment",
402            Self::Unknown(value) => value,
403        })
404    }
405}
406
407impl<'de> Deserialize<'de> for OperatorConfirmKind {
408    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
409        Ok(match String::deserialize(deserializer)?.as_str() {
410            "operation" => Self::Operation,
411            "enrollment" => Self::Enrollment,
412            value => Self::Unknown(value.to_owned()),
413        })
414    }
415}
416
417/// A successful channel-0 reply to an [`OperatorConfirmRequest`].
418///
419/// Only `outcome: "confirmed"` confirms the write. Refusals use [`crate::ErrorBody`]
420/// instead. Readers must not treat an unknown outcome as confirmation.
421#[non_exhaustive]
422#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
423pub struct OperatorConfirmReply {
424    op: OperatorConfirmOp,
425    pub outcome: String,
426}
427
428impl OperatorConfirmReply {
429    pub fn confirmed() -> Self {
430        Self {
431            op: OperatorConfirmOp::Confirm,
432            outcome: "confirmed".to_string(),
433        }
434    }
435}
436
437// A required, single-valued field both emits the op and refuses a missing or
438// different op when decoding, without exposing a caller-editable tag.
439#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
440enum OperatorConfirmOp {
441    #[serde(rename = "operator.confirm")]
442    Confirm,
443}
444
445impl From<HealthReport> for ModuleControlResponse {
446    fn from(report: HealthReport) -> Self {
447        Self::HealthCheck {
448            status: report.status,
449            detail: report.detail,
450            metrics: report.metrics,
451        }
452    }
453}
454
455impl ModuleControlResponse {
456    pub fn health_report(&self) -> Option<HealthReport> {
457        match self {
458            Self::HealthCheck {
459                status,
460                detail,
461                metrics,
462            } => Some(HealthReport {
463                status: *status,
464                detail: detail.clone(),
465                metrics: metrics.clone(),
466            }),
467            Self::RouteBindAck {} => None,
468        }
469    }
470}
471
472/// Module-to-subc channel-0 push body.
473#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
474#[serde(tag = "op")]
475pub enum ModuleControlPush {
476    #[serde(rename = "route.status")]
477    RouteStatus {
478        route_channel: u16,
479        route_epoch: u32,
480        status: String,
481    },
482}
483
484/// The wire name of the `role_versions` field on `route.open` and
485/// `route.bind`, for the `detail.field` of the `invalid_request` error that
486/// refuses a malformed one.
487pub const ROLE_VERSIONS_FIELD: &str = "role_versions";
488
489/// Most entries a `role_versions` map may hold.
490pub const MAX_ROLE_VERSIONS: usize = 8;
491
492/// The longest role name accepted in `role_versions`, in bytes.
493pub const MAX_ROLE_NAME_LEN: usize = 64;
494
495/// Why a `role_versions` map was refused.
496#[derive(Clone, Debug, PartialEq, Eq)]
497#[non_exhaustive]
498pub enum RoleVersionsError {
499    /// The map has more than [`MAX_ROLE_VERSIONS`] entries.
500    TooMany { count: usize },
501    /// A role name is not lowercase ASCII letters and digits in words joined
502    /// by single hyphens (`tool-provider`), or is longer than
503    /// [`MAX_ROLE_NAME_LEN`] bytes.
504    InvalidRole { role: String },
505    /// A version is not `v` followed by a positive integer without leading
506    /// zeros (`v1`, `v12`).
507    InvalidVersion { role: String, version: String },
508}
509
510impl RoleVersionsError {
511    /// The request field the error is about: always [`ROLE_VERSIONS_FIELD`].
512    pub fn field(&self) -> &'static str {
513        ROLE_VERSIONS_FIELD
514    }
515}
516
517impl std::fmt::Display for RoleVersionsError {
518    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
519        match self {
520            Self::TooMany { count } => write!(
521                f,
522                "{ROLE_VERSIONS_FIELD} has {count} entries; at most {MAX_ROLE_VERSIONS} are allowed"
523            ),
524            Self::InvalidRole { role } => write!(
525                f,
526                "{ROLE_VERSIONS_FIELD} names role {role:?}, which is not lowercase letters and \
527                 digits in words joined by '-', at most {MAX_ROLE_NAME_LEN} bytes"
528            ),
529            Self::InvalidVersion { role, version } => write!(
530                f,
531                "{ROLE_VERSIONS_FIELD} gives role {role:?} version {version:?}, which is not 'v' \
532                 followed by a positive integer without leading zeros"
533            ),
534        }
535    }
536}
537
538impl std::error::Error for RoleVersionsError {}
539
540/// Check a `role_versions` map: at most [`MAX_ROLE_VERSIONS`] entries, each
541/// role name matching `^[a-z0-9]+(-[a-z0-9]+)*$` in at most
542/// [`MAX_ROLE_NAME_LEN`] bytes, and each version matching `^v[1-9][0-9]*$`.
543///
544/// The daemon refuses a `route.open` that fails this, so a consumer can run
545/// the same check before sending. An empty map passes; the daemon treats it
546/// as no declaration at all.
547pub fn validate_role_versions(
548    role_versions: &BTreeMap<String, String>,
549) -> Result<(), RoleVersionsError> {
550    if role_versions.len() > MAX_ROLE_VERSIONS {
551        return Err(RoleVersionsError::TooMany {
552            count: role_versions.len(),
553        });
554    }
555    for (role, version) in role_versions {
556        if !is_role_name(role) {
557            return Err(RoleVersionsError::InvalidRole { role: role.clone() });
558        }
559        if !is_role_version(version) {
560            return Err(RoleVersionsError::InvalidVersion {
561                role: role.clone(),
562                version: version.clone(),
563            });
564        }
565    }
566    Ok(())
567}
568
569fn is_role_name(role: &str) -> bool {
570    !role.is_empty()
571        && role.len() <= MAX_ROLE_NAME_LEN
572        && role.split('-').all(|word| {
573            !word.is_empty()
574                && word
575                    .bytes()
576                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
577        })
578}
579
580fn is_role_version(version: &str) -> bool {
581    let bytes = version.as_bytes();
582    bytes.len() >= 2
583        && bytes[0] == b'v'
584        && (b'1'..=b'9').contains(&bytes[1])
585        && bytes[2..].iter().all(u8::is_ascii_digit)
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591
592    #[test]
593    fn catalog_update_role_declarations_wire_round_trip() {
594        for declarations in [
595            serde_json::json!({"media-provider/v1": {"engines": ["image"]}}),
596            serde_json::json!({}),
597        ] {
598            let body = serde_json::json!({
599                "op": "catalog.update_role_declarations",
600                "role_declarations": declarations,
601            });
602            let request: ModuleControlRequestFromModule =
603                serde_json::from_value(body.clone()).unwrap();
604            assert_eq!(serde_json::to_value(request).unwrap(), body);
605        }
606        let body = serde_json::json!({"op": "catalog.update_role_declarations"});
607        let response: ModuleControlResponseToModule = serde_json::from_value(body.clone()).unwrap();
608        assert_eq!(serde_json::to_value(response).unwrap(), body);
609        assert!(serde_json::from_value::<ModuleControlRequestFromModule>(body).is_err());
610    }
611
612    fn map(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
613        entries
614            .iter()
615            .map(|(role, version)| (role.to_string(), version.to_string()))
616            .collect()
617    }
618
619    #[test]
620    fn role_versions_accept_role_names_and_positive_versions() {
621        for entries in [
622            vec![],
623            vec![("tool-provider", "v1")],
624            vec![("a", "v9"), ("b2", "v10"), ("x-1-y", "v1203")],
625        ] {
626            assert_eq!(
627                validate_role_versions(&map(&entries)),
628                Ok(()),
629                "{entries:?}"
630            );
631        }
632        let longest = "a".repeat(MAX_ROLE_NAME_LEN);
633        assert_eq!(validate_role_versions(&map(&[(&longest, "v1")])), Ok(()));
634        let full: BTreeMap<String, String> = (0..MAX_ROLE_VERSIONS)
635            .map(|index| (format!("role-{index}"), "v1".to_string()))
636            .collect();
637        assert_eq!(validate_role_versions(&full), Ok(()));
638    }
639
640    #[test]
641    fn role_versions_refuse_malformed_role_names() {
642        let too_long = "a".repeat(MAX_ROLE_NAME_LEN + 1);
643        for role in [
644            "",
645            "Tool-provider",
646            "tool_provider",
647            "tool provider",
648            "-tool",
649            "tool-",
650            "tool--provider",
651            "tool.provider",
652            "outil-é",
653            too_long.as_str(),
654        ] {
655            let error = validate_role_versions(&map(&[(role, "v1")])).unwrap_err();
656            assert_eq!(
657                error,
658                RoleVersionsError::InvalidRole {
659                    role: role.to_string()
660                },
661                "{role:?}"
662            );
663            assert_eq!(error.field(), "role_versions");
664        }
665    }
666
667    #[test]
668    fn role_versions_refuse_malformed_versions() {
669        for version in [
670            "", "v", "v0", "v01", "1", "V1", "v1.0", "v-1", "v1 ", " v1", "vx",
671        ] {
672            let error = validate_role_versions(&map(&[("tool-provider", version)])).unwrap_err();
673            assert_eq!(
674                error,
675                RoleVersionsError::InvalidVersion {
676                    role: "tool-provider".to_string(),
677                    version: version.to_string(),
678                },
679                "{version:?}"
680            );
681            assert_eq!(error.field(), "role_versions");
682        }
683    }
684
685    #[test]
686    fn role_versions_refuse_more_than_eight_entries() {
687        let nine: BTreeMap<String, String> = (0..=MAX_ROLE_VERSIONS)
688            .map(|index| (format!("role-{index}"), "v1".to_string()))
689            .collect();
690        let error = validate_role_versions(&nine).unwrap_err();
691        assert_eq!(error, RoleVersionsError::TooMany { count: 9 });
692        assert_eq!(error.field(), "role_versions");
693        assert!(error.to_string().starts_with("role_versions"), "{error}");
694    }
695
696    #[test]
697    fn route_bind_omits_absent_role_versions_and_carries_present_ones_verbatim() {
698        let bind = |role_versions| ModuleControlRequest::RouteBind {
699            route_channel: 1,
700            epoch: 1,
701            target: crate::RouteTarget::ToolProvider {
702                module_id: "aft".to_string(),
703            },
704            identity: crate::BindIdentity::new("h", "s"),
705            principal: None,
706            consumer_capabilities: None,
707            role_versions,
708            admission_facts: None,
709            scope: None,
710            call_mode: None,
711        };
712        let absent = serde_json::to_value(bind(None)).unwrap();
713        assert!(absent.get("role_versions").is_none(), "{absent}");
714        let present = bind(Some(map(&[("tool-provider", "v1")])));
715        let encoded = serde_json::to_value(&present).unwrap();
716        assert_eq!(
717            encoded["role_versions"],
718            serde_json::json!({ "tool-provider": "v1" })
719        );
720        let decoded: ModuleControlRequest = serde_json::from_value(encoded).unwrap();
721        assert_eq!(decoded, present);
722    }
723}
724
725#[cfg(test)]
726mod agent_command_tests {
727    use super::*;
728
729    #[test]
730    fn agent_commands_round_trip_start_finish_and_known_snapshot() {
731        let root = AgentCommandRoot {
732            pid: 42,
733            start_time_ms: 1_700_000_000_123,
734        };
735        let request = ModuleControlRequestFromModule::AgentCommands {
736            started: vec![root],
737            finished: vec![AgentCommandFinished {
738                pid: 43,
739                start_time_ms: root.start_time_ms,
740                cpu_ms: Some(100),
741            }],
742            known: Some(vec![root]),
743        };
744        let value = serde_json::to_value(&request).unwrap();
745        assert_eq!(
746            value,
747            serde_json::json!({"op":"supervisor.agent_commands",
748            "started":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}],
749            "finished":[{"pid":43,"start_time_ms":1_700_000_000_123_u64,"cpu_ms":100}],
750            "known":[{"pid":42,"start_time_ms":1_700_000_000_123_u64}]})
751        );
752        assert_eq!(
753            serde_json::from_value::<ModuleControlRequestFromModule>(value).unwrap(),
754            request
755        );
756        let absent = ModuleControlRequestFromModule::AgentCommands {
757            started: Vec::new(),
758            finished: vec![AgentCommandFinished {
759                pid: 1,
760                start_time_ms: 2,
761                cpu_ms: None,
762            }],
763            known: None,
764        };
765        assert_eq!(
766            serde_json::to_value(absent).unwrap(),
767            serde_json::json!({"op":"supervisor.agent_commands",
768            "started":[],"finished":[{"pid":1,"start_time_ms":2}]})
769        );
770    }
771}