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