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