Skip to main content

subc_control/
lib.rs

1//! Client-facing subc channel-0 control wire shapes.
2//!
3//! This crate is the client ↔ subc control-plane boundary. It depends only on
4//! [`subc-protocol`] for shared primitives such as `RouteTarget` and
5//! `BindIdentity`; clients can use it without depending on the
6//! daemon implementation.
7
8#![forbid(unsafe_code)]
9
10use std::{collections::BTreeMap, path::PathBuf};
11
12use serde::{
13    de::{Error as _, MapAccess, SeqAccess, Visitor},
14    ser::SerializeMap,
15    Deserialize, Deserializer, Serialize, Serializer,
16};
17use subc_protocol::{
18    manifest::{
19        CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
20        OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
21    },
22    scope::ScopeSelector,
23    session::HealthStatus,
24    BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::RouteCloseReason;
28
29mod activity;
30pub use activity::*;
31
32mod scope_served_by;
33pub use scope_served_by::*;
34
35macro_rules! open_string_enum {
36    (
37        $(#[$meta:meta])*
38        $name:ident {
39            $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
40        }
41    ) => {
42        $(#[$meta])*
43        #[derive(Debug, Clone, PartialEq, Eq)]
44        pub enum $name {
45            $( $(#[$variant_meta])* $variant, )+
46            Unknown(String),
47        }
48
49        impl $name {
50            fn wire_name(&self) -> &str {
51                match self {
52                    $( Self::$variant => $wire_name, )+
53                    Self::Unknown(value) => value,
54                }
55            }
56        }
57
58        impl Serialize for $name {
59            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60            where
61                S: serde::Serializer,
62            {
63                serializer.serialize_str(self.wire_name())
64            }
65        }
66
67        impl<'de> Deserialize<'de> for $name {
68            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69            where
70                D: serde::Deserializer<'de>,
71            {
72                let value = String::deserialize(deserializer)?;
73                Ok(match value.as_str() {
74                    $( $wire_name => Self::$variant, )+
75                    _ => Self::Unknown(value),
76                })
77            }
78        }
79    };
80}
81
82mod rescan_checked;
83pub use rescan_checked::*;
84
85mod app_open;
86pub use app_open::*;
87
88mod connection_describe;
89pub use connection_describe::*;
90
91mod subtree;
92pub use subtree::*;
93mod tree;
94pub use tree::*;
95
96/// Daemon-spawned consumer identity presented on route.open.
97#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
98pub struct ConsumerIdentity {
99    pub module_id: String,
100    pub launch_nonce: String,
101}
102
103// Hand-written so the launch nonce is never printed. The nonce is the credential
104// that attributes a connection to a supervised module, and a derived Debug would
105// write it into any log line or panic message that formats this value. Same
106// reasoning as ConnectionInfo's Debug in subc-transport.
107impl std::fmt::Debug for ConsumerIdentity {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("ConsumerIdentity")
110            .field("module_id", &self.module_id)
111            .field(
112                "launch_nonce",
113                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
114            )
115            .finish()
116    }
117}
118
119/// Reserved dotted operation prefixes for the v0.4 control vocabulary.
120///
121/// `scheduler.` and `watch.` were reserved here from v0.4 until 2026-08-10 and
122/// were removed deliberately rather than left as placeholders: neither was ever
123/// implemented, and both capabilities are now owned elsewhere by ruling --
124/// scheduled tasks belong to the session runtime (prefrontal) because the
125/// daemon is state-free routing, and external-event watching belongs to the
126/// connectors module (plexus). A reserved name for something that will never be
127/// built here reads as a roadmap commitment to anyone surveying the protocol,
128/// and it recruited exactly that misunderstanding from an outside contributor.
129pub mod ops {
130    pub const SERVER: &str = "server.";
131    pub const CATALOG: &str = "catalog.";
132    pub const ROUTE: &str = "route.";
133    pub const SUPERVISOR: &str = "supervisor.";
134    pub const CONFIG: &str = "config.";
135
136    pub const SERVER_DESCRIBE: &str = "server.describe";
137    pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
138    pub const CATALOG_LIST: &str = "catalog.list";
139    pub const ROUTE_OPEN: &str = "route.open";
140    pub const ROUTE_POLL: &str = "route.poll";
141    pub const ROUTE_CLOSING: &str = "route.closing";
142    pub const ROUTE_CLOSED: &str = "route.closed";
143    pub const SUPERVISOR_LIST: &str = "supervisor.list";
144    pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
145    pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
146    pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
147    pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
148    pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
149    pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
150    pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
151    pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
152    pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
153    pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
154    pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
155    pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
156    pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
157    pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
158    pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
159    pub const ACTIVITY_RECORD: &str = "activity.record";
160    pub const ACTIVITY_QUERY: &str = "activity.query";
161    pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
162    pub const APP_OPEN: &str = "app.open";
163    pub const CONNECTION_DESCRIBE: &str = "connection.describe";
164}
165
166/// Client-originated channel-0 control RPC body.
167#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
168#[serde(tag = "op")]
169// RouteOpen carries the complete route metadata, while several control operations
170// are markers; retain the direct public wire shape instead of boxing its fields.
171#[allow(clippy::large_enum_variant)]
172pub enum ClientControlRequest {
173    /// Announce a planned daemon restart. Other values, including an absent
174    /// intent, are refused by the daemon with `invalid_params`.
175    #[serde(rename = "daemon.shutdown_intent")]
176    DaemonShutdownIntent {
177        #[serde(default)]
178        intent: serde_json::Value,
179    },
180    #[serde(rename = "server.describe")]
181    ServerDescribe {},
182    #[serde(rename = "catalog.list")]
183    CatalogList {
184        /// Absent lists every registered module; present narrows to one. A
185        /// narrowed list for an unregistered id is an empty list rather than an
186        /// error, so absent and unregistered are distinguishable only by which
187        /// question you asked.
188        #[serde(default)]
189        module_id: Option<String>,
190    },
191    #[serde(rename = "route.open")]
192    RouteOpen {
193        target: RouteTarget,
194        identity: BindIdentity,
195        /// The consumer's claim to a supervised launch, which the daemon verifies
196        /// against its live spawn nonces before stamping a principal.
197        ///
198        /// Absent is a legitimate shape, not an omission: a direct key-holder has
199        /// no launch nonce to present, and the daemon stamps `Direct`. So absence
200        /// means NO CLAIM WAS MADE, never that a claim was refused — a refused
201        /// claim is an error frame and the route never opens. A provider deciding
202        /// what to trust reads the stamped principal on the bind, not this.
203        #[serde(default, skip_serializing_if = "Option::is_none")]
204        consumer_identity: Option<ConsumerIdentity>,
205        /// Consumer-declared reverse-request capabilities for the route. This is
206        /// an unverified declaration, not a privilege grant; if a consumer
207        /// over-declares, providers may still send reverse requests that later
208        /// time out or deny. Providers must treat an absent field as no
209        /// reverse-request capability. The vocabulary is open strings; known MCP
210        /// method-family values today are "elicitation", "sampling", and
211        /// "roots".
212        #[serde(default, skip_serializing_if = "Option::is_none")]
213        consumer_capabilities: Option<Vec<String>>,
214        /// The versions of provider roles this consumer speaks on the route,
215        /// role name to version (`{"tool-provider": "v1"}`). Like
216        /// `consumer_capabilities` it is an unverified declaration that grants
217        /// nothing: the daemon checks its shape
218        /// (`subc_protocol::session::validate_role_versions`), refuses a
219        /// malformed one as `invalid_request` naming `role_versions`, and
220        /// copies it unchanged onto the module's bind. An empty map means the
221        /// same as an absent one. Send it only to a daemon advertising
222        /// `route-role-versions/v1`: an older daemon drops unknown fields, so
223        /// the provider would never see it.
224        #[serde(default, skip_serializing_if = "Option::is_none")]
225        role_versions: Option<BTreeMap<String, String>>,
226        /// Opt into immediate, never-forwarded `route_busy` refusals instead of
227        /// waiting for request credits. This field is daemon-only and is never
228        /// copied into the module's bind.
229        #[serde(default, skip_serializing_if = "Option::is_none")]
230        busy_refusals: Option<bool>,
231        /// Opaque admission facts supplied by the configured carrier module.
232        #[serde(default, skip_serializing_if = "Option::is_none")]
233        admission_facts: Option<serde_json::Value>,
234        /// The scope to open the route under. The daemon admits the open only
235        /// when the opener (its attested principal, never anything in this
236        /// body) is the scope's owner or a listed carrier, and stamps the
237        /// scope on the module's bind. Send it only to a daemon advertising
238        /// `scopes/v1`: an older daemon drops unknown fields and would open an
239        /// unscoped route.
240        #[serde(default, skip_serializing_if = "Option::is_none")]
241        scope: Option<ScopeSelector>,
242    },
243    #[serde(rename = "route.poll")]
244    RoutePoll {
245        route_channel: u16,
246        route_epoch: u32,
247        kind: PollKind,
248    },
249    #[serde(rename = "supervisor.list")]
250    SupervisorList {},
251    /// Read the live supervised processes and the event cursor atomically.
252    #[serde(rename = "supervisor.spawn_snapshot")]
253    SupervisorSpawnSnapshot {},
254    /// Replay spawn events after `since`, then remain open for live events.
255    ///
256    /// The cursor is one value copied from a snapshot or event. It includes the
257    /// daemon incarnation so a restarted daemon rejects an earlier instance's
258    /// sequence instead of treating it as a position in the current stream.
259    ///
260    /// Refusals and terminal errors, as `Error` frames on the request's corr:
261    /// - `spawn_cursor_incarnation_mismatch` (detail `current_daemon_incarnation`):
262    ///   `since` names another daemon incarnation.
263    /// - `spawn_cursor_too_old` (detail `oldest_retained_cursor`): `since`
264    ///   predates the retained event ring.
265    /// - `spawn_subscriber_lagged` (detail `first_undelivered_cursor`): the open
266    ///   stream fell too far behind and the daemon dropped it. It arrives after
267    ///   every event that was already queued and ends the stream; resubscribe
268    ///   with `since` set to the last cursor received.
269    #[serde(rename = "supervisor.spawn_subscribe")]
270    SupervisorSpawnSubscribe {
271        #[serde(default, skip_serializing_if = "Option::is_none")]
272        since: Option<SpawnCursor>,
273    },
274    #[serde(rename = "supervisor.restart")]
275    SupervisorRestart {
276        module_id: String,
277        /// Optional per-restart override of the module's drain budget, in ms.
278        /// Absent: the module's configured `drain_timeout_ms` (or the daemon
279        /// default) applies. `0` tears down without waiting: use it to restart a
280        /// wedged module whose stuck in-flight request would never settle, so
281        /// waiting for a drain would be pointless.
282        /// Additive; older daemons silently ignore this field and use their
283        /// configured/default drain budget, even when the sender requests `0`.
284        /// Senders that require the override must use a daemon version that
285        /// supports it (the CLI only sends it when a flag is passed).
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        drain_timeout_ms: Option<u64>,
288    },
289    /// Blue/green restart: start a replacement beside the running process, keep
290    /// routing to the running one until the replacement declares itself ready,
291    /// then move new routes over and drain the old process.
292    ///
293    /// Refused before anything is spawned unless the module's daemon config
294    /// declares `overlap: "safe"`: two processes on one single-writer store is
295    /// a data hazard, so the default is exclusive. Answered once the swap has
296    /// either cut over (the old process is still draining) or failed; a failure
297    /// leaves the old process serving and undrained, and names the arm in
298    /// `ErrorBody.detail`.
299    ///
300    /// A new op rather than a flag on `supervisor.restart`: a daemon that
301    /// predates swap rejects an unknown op, whereas an unknown field could be
302    /// dropped and turned into a plain restart.
303    #[serde(rename = "supervisor.swap")]
304    SupervisorSwap {
305        module_id: String,
306        /// How long the replacement may take to register and declare itself
307        /// ready before the swap is abandoned. Absent: the daemon default.
308        #[serde(default, skip_serializing_if = "Option::is_none")]
309        ready_timeout_ms: Option<u64>,
310    },
311    #[serde(rename = "supervisor.reload")]
312    SupervisorReload { module_id: String },
313    #[serde(rename = "supervisor.rescan")]
314    SupervisorRescan {
315        /// Compute the reconciliation and return it WITHOUT applying it.
316        ///
317        /// Rescan retires any supervised module absent from the config, which
318        /// stops live processes. Both halves of that decision are inspectable in
319        /// advance -- the config is a file, the running set is `supervisor.list`
320        /// -- but nothing reconstructs the diff for the operator, so it is read
321        /// from the result table AFTER the retires have happened.
322        ///
323        /// A preview must be computed daemon-side rather than by a client, because
324        /// a client would have to locate the daemon's config itself: two rules
325        /// selecting one subject, agreeing until someone runs a daemon with a
326        /// non-default config. A preview that can describe a different file than
327        /// the operation reads is worse than none, because it is believed.
328        ///
329        /// Defaults to false so an existing client sending `{}` still executes,
330        /// and is OMITTED when false so the bytes an existing client sends are
331        /// unchanged. Serialising `preview:false` would have altered the request's
332        /// wire form for every caller that never asked for a preview -- caught by
333        /// the golden fixture, which is the whole reason that pin exists.
334        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335        preview: bool,
336    },
337    /// A rescan whose preview is computed on configuration text the caller
338    /// supplies, and whose apply runs only if the daemon still matches that
339    /// preview. Served by daemons advertising
340    /// [`RESCAN_CANDIDATE_PREVIEW_CAPABILITY`].
341    ///
342    /// Exactly two forms are accepted; any other combination is refused
343    /// `invalid_control_body`:
344    /// - `preview: true` with `candidate`: parse and validate the candidate
345    ///   (at most [`RESCAN_CANDIDATE_MAX_BYTES`]) with the loader the daemon
346    ///   uses for its file, compare it with the staged module specs, and
347    ///   report what applying it would do. Nothing is written or applied.
348    ///   The reply carries the `expect` an apply must send.
349    /// - `preview: false` with `expect`: refuse
350    ///   [`CONFIG_CHANGED_SINCE_PREVIEW`] when the daemon's config file no
351    ///   longer hashes to `expect.config_sha256` or the staged generation has
352    ///   moved; otherwise apply the file exactly as `supervisor.rescan` does.
353    ///
354    /// Both reply with `supervisor.rescan`'s result shape.
355    ///
356    /// A new op rather than fields on `supervisor.rescan`: a daemon that
357    /// predates it refuses the unknown op, whereas unknown fields would be
358    /// dropped and the preview would describe the file on disk instead of the
359    /// candidate.
360    #[serde(rename = "supervisor.rescan_checked")]
361    SupervisorRescanChecked {
362        preview: bool,
363        #[serde(default, skip_serializing_if = "Option::is_none")]
364        candidate: Option<String>,
365        #[serde(default, skip_serializing_if = "Option::is_none")]
366        expect: Option<RescanExpect>,
367    },
368    /// Retire the retained exact-id reservation after its configuration entry has
369    /// been removed. This is intentionally separate from rescan so deleting
370    /// configuration never silently opens a protected module id to registration.
371    #[serde(rename = "supervisor.release_reserved")]
372    SupervisorReleaseReserved { module_id: String },
373    #[serde(rename = "supervisor.set_enabled")]
374    SupervisorSetEnabled { module_id: String, enabled: bool },
375    #[serde(rename = "supervisor.health_probe")]
376    SupervisorHealthProbe { module_id: String },
377    #[serde(rename = "supervisor.health")]
378    SupervisorHealth {},
379    /// Enumerate the routes currently served by one supervised module, or every
380    /// module when omitted.
381    ///
382    /// This privileged census is control-plane-only. It is deliberately not an
383    /// MCP facade or agent-tool operation: callers holding the daemon control
384    /// connection may inspect live route ownership, while agent-facing modules
385    /// must not be able to address that surface at all.
386    ///
387    /// The daemon answers from its forwarding table under a read lock and never
388    /// consults a module. That makes the read safe during a drain, when a module
389    /// cannot be queried without recreating the hang/restart hazard that route
390    /// status reads avoid.
391    #[serde(rename = "supervisor.routes")]
392    SupervisorRoutes {
393        #[serde(default, skip_serializing_if = "Option::is_none")]
394        module_id: Option<String>,
395    },
396    /// Report source-tagged provenance for supervised modules, optionally narrowed
397    /// to one module.
398    #[serde(rename = "supervisor.provenance")]
399    SupervisorProvenance {
400        #[serde(default, skip_serializing_if = "Option::is_none")]
401        module_id: Option<String>,
402    },
403    /// Retained stderr for one module.
404    ///
405    /// A separate op rather than a field on `supervisor.list`: the tail is
406    /// kilobytes per module and `list` renders every module, so carrying it in
407    /// the snapshot would charge every status read for a payload almost no
408    /// caller wants. Caps ride on the REQUEST so a caller wanting twenty lines
409    /// and one wanting the whole ring need no separate fields anywhere.
410    #[serde(rename = "supervisor.stderr_tail")]
411    SupervisorStderrTail {
412        module_id: String,
413        #[serde(default, skip_serializing_if = "Option::is_none")]
414        max_lines: Option<u32>,
415        #[serde(default, skip_serializing_if = "Option::is_none")]
416        max_bytes: Option<u32>,
417    },
418    /// Retained terminal exits for one module.
419    ///
420    /// This stays separate from `supervisor.list`: a history grows with every
421    /// incident, while the list is a current-state read most callers issue often.
422    ///
423    /// The read MUST stay off the supervisor command channel — it reads the
424    /// module's shared ring directly. This is a requirement, not an
425    /// optimisation: when the supervision task itself dies, every
426    /// command-channel op returns `CommandClosed`, and that is precisely the
427    /// moment an operator needs the exit history most. A history reachable only
428    /// through the machinery whose death you are diagnosing is unreachable when
429    /// it matters. Proven failure mode, not a hypothetical.
430    #[serde(rename = "supervisor.terminals")]
431    SupervisorTerminals { module_id: String },
432}
433
434/// subc's channel-0 response body for client control RPCs.
435#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
436#[serde(tag = "op")]
437pub enum ClientControlResponse {
438    #[serde(rename = "daemon.shutdown_intent")]
439    DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
440    #[serde(rename = "server.describe")]
441    ServerDescribe {
442        protocol_ver: u8,
443        subc_ops: Vec<String>,
444        capabilities: Vec<String>,
445        connected_clients: u64,
446        #[serde(default, skip_serializing_if = "Option::is_none")]
447        counters: Option<serde_json::Value>,
448        /// Git commit the daemon was built from, or "unavailable" when the
449        /// build could not read it. The crate version cannot discriminate a
450        /// skewed daemon/CLI pair (it moves per release, not per commit), so
451        /// this is the identity a consumer compares against its own embedded
452        /// commit to detect that it is talking to an older build than it was
453        /// compiled with. Absent from daemons predating the field.
454        #[serde(default, skip_serializing_if = "Option::is_none")]
455        build_git_sha: Option<String>,
456        /// sha256 of the workspace Cargo.lock at build time, or "unavailable".
457        /// Answers "which dependency set" where the commit answers "which
458        /// source"; a commit match with a digest mismatch means a rebuild
459        /// against edited dependencies. Absent from daemons predating the
460        /// field.
461        #[serde(default, skip_serializing_if = "Option::is_none")]
462        build_lock_digest: Option<String>,
463        /// Daemon-evaluated capability requirements. Present when the configured
464        /// fleet has declarations to evaluate, so operators can inspect an absent
465        /// required capability without parsing daemon logs.
466        #[serde(default, skip_serializing_if = "Vec::is_empty")]
467        capability_requirements: Vec<CapabilityRequirementStatus>,
468        /// The daemon's machine id (`subc_protocol::MachineId`), the same value
469        /// every module receives on `HELLO_ACK`. A name for this machine, never
470        /// an authority: nothing may grant trust because two parties report the
471        /// same value. Absent from daemons predating the field.
472        #[serde(default, skip_serializing_if = "Option::is_none")]
473        machine_id: Option<String>,
474        /// The configuration file the daemon reads and `supervisor.rescan`
475        /// rescans, exactly as the daemon names it: never canonicalized, so a
476        /// symlinked file is reported as the link. Sent only when that path is
477        /// absolute; a relative one (no home variable set, or a relative
478        /// `XDG_CONFIG_HOME`) depends on the daemon's working directory and
479        /// would name a different file for the reader. Absent from daemons
480        /// predating the field and from daemons started without a reloadable
481        /// config file.
482        #[serde(default, skip_serializing_if = "Option::is_none")]
483        config_path: Option<PathBuf>,
484    },
485    #[serde(rename = "catalog.list")]
486    CatalogList {
487        generation: u64,
488        modules: Vec<CatalogEntry>,
489        subc_ops: Vec<String>,
490    },
491    #[serde(rename = "route.open")]
492    RouteOpen {
493        route_channel: u16,
494        route_epoch: u32,
495        /// Total request credits, present only when busy refusals were enabled.
496        #[serde(default, skip_serializing_if = "Option::is_none")]
497        request_window: Option<usize>,
498        /// Watch credits on an opted-in module-managed route.
499        #[serde(default, skip_serializing_if = "Option::is_none")]
500        watch_window: Option<usize>,
501    },
502    #[serde(rename = "route.poll")]
503    RoutePoll {
504        route_channel: u16,
505        route_epoch: u32,
506        status: Option<String>,
507        live: Option<bool>,
508    },
509    #[serde(rename = "supervisor.list")]
510    SupervisorList {
511        generation: u64,
512        modules: Vec<SupervisorEntry>,
513        #[serde(default, skip_serializing_if = "Option::is_none")]
514        daemon: Option<DaemonResources>,
515        #[serde(default, skip_serializing_if = "Option::is_none")]
516        agent_commands: Option<Vec<AgentCommandResources>>,
517    },
518    #[serde(rename = "supervisor.spawn_snapshot")]
519    SupervisorSpawnSnapshot {
520        #[serde(flatten)]
521        snapshot: SpawnSnapshot,
522    },
523    #[serde(rename = "supervisor.ack")]
524    SupervisorAck { module_id: String, applied: bool },
525    #[serde(rename = "supervisor.rescan")]
526    SupervisorRescan {
527        #[serde(flatten)]
528        result: SupervisorRescanResult,
529    },
530    #[serde(rename = "supervisor.health_probe")]
531    SupervisorHealthProbe {
532        module_id: String,
533        status: HealthStatus,
534        #[serde(default, skip_serializing_if = "Option::is_none")]
535        detail: Option<String>,
536        #[serde(default, skip_serializing_if = "Option::is_none")]
537        metrics: Option<serde_json::Value>,
538    },
539    #[serde(rename = "supervisor.health")]
540    SupervisorHealth {
541        generation: u64,
542        modules: Vec<SupervisorHealthEntry>,
543    },
544    #[serde(rename = "supervisor.routes")]
545    SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
546    #[serde(rename = "supervisor.provenance")]
547    SupervisorProvenance {
548        daemon: SupervisorDaemonProvenance,
549        modules: Vec<SupervisorModuleProvenance>,
550    },
551    #[serde(rename = "supervisor.stderr_tail")]
552    SupervisorStderrTail {
553        module_id: String,
554        #[serde(flatten)]
555        tail: StderrTail,
556    },
557    #[serde(rename = "supervisor.terminals")]
558    SupervisorTerminals {
559        module_id: String,
560        #[serde(flatten)]
561        terminals: TerminalHistory,
562    },
563}
564
565/// Daemon-originated channel-0 control push body.
566///
567/// A module cannot originate these pushes: subc creates them from its own
568/// forwarding state and enqueues them directly to client connection sinks.
569#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
570#[serde(tag = "op")]
571pub enum ClientControlPush {
572    #[serde(rename = "route.closing")]
573    RouteClosing {
574        module_id: String,
575        /// Channel numbers identifying affected routes on this client's connection.
576        /// Channels used by other clients or by the provider are not included.
577        #[serde(default)]
578        channels: Vec<u16>,
579        reason: RouteCloseReason,
580    },
581    #[serde(rename = "route.closed")]
582    RouteClosed {
583        module_id: String,
584        /// Channel numbers identifying affected routes on this client's connection.
585        /// Channels used by other clients or by the provider are not included.
586        #[serde(default)]
587        channels: Vec<u16>,
588        reason: RouteCloseReason,
589        /// The exact result of the forwarding-quiescence wait for live routes.
590        drained: bool,
591        /// Pending route.bind relays forced down before that wait. They are not
592        /// covered by `drained`, even when live routes quiesced.
593        abandoned: u32,
594        /// Subscription credits captured and excluded from this drain's wire predicate.
595        #[serde(default)]
596        excluded_subscriptions: u32,
597        /// Whether subc will leave this module down until operator action.
598        ///
599        /// The claim covers daemon-owned recovery only. `None` is accepted only
600        /// from daemons that predate this field; every current daemon emission is
601        /// `Some`.
602        #[serde(default, skip_serializing_if = "Option::is_none")]
603        terminal: Option<bool>,
604    },
605}
606
607/// A daemon-incarnation-scoped position in the supervised spawn event stream.
608#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
609pub struct SpawnCursor {
610    pub daemon_incarnation: String,
611    pub seq: u64,
612}
613
614/// One process present in an atomic supervisor spawn snapshot.
615#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
616pub struct LiveSpawn {
617    pub module_id: String,
618    pub spawn_generation: u64,
619    pub pid: u32,
620    pub spawned_at_ms: u64,
621}
622
623/// Atomic live-process census and the cursor at which it was observed.
624#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
625pub struct SpawnSnapshot {
626    pub cursor: SpawnCursor,
627    /// Maximum retained event count for this daemon.
628    pub ring_bound: u64,
629    pub live: Vec<LiveSpawn>,
630}
631
632/// Fact observed by the supervisor when a child process starts or exits.
633#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
634#[serde(rename_all = "snake_case")]
635pub enum SpawnEventKind {
636    Spawned,
637    Exited,
638}
639
640/// One retained or live spawn event.
641///
642/// Exit events intentionally carry no disposition or reason because exit
643/// classification is recorded separately; credential consumers revoke on every
644/// exit regardless of the cause.
645#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
646pub struct SpawnEvent {
647    pub cursor: SpawnCursor,
648    pub kind: SpawnEventKind,
649    pub module_id: String,
650    pub spawn_generation: u64,
651    pub pid: u32,
652    #[serde(default, skip_serializing_if = "Option::is_none")]
653    pub exit_code: Option<i32>,
654    #[serde(default, skip_serializing_if = "Option::is_none")]
655    pub exit_signal: Option<i32>,
656}
657
658/// A module's retained stderr, oldest entry first.
659#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
660pub struct StderrTail {
661    pub capture: StderrCaptureState,
662    pub entries: Vec<StderrTailEntry>,
663    /// Lines not present above: evicted by the ring, or held back by this
664    /// request's own caps.
665    ///
666    /// Non-zero means the first entry is not the first line the module wrote. A
667    /// reader hunting a cause needs that, or an absent explanation reads as a
668    /// module that never gave one.
669    ///
670    /// Zero is skipped so the common complete-tail case stays compact.
671    #[serde(default, skip_serializing_if = "is_zero_u64")]
672    pub dropped_lines: u64,
673}
674
675/// Live routes served by one module.
676#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
677pub struct SupervisorRouteModule {
678    pub module_id: String,
679    pub routes: Vec<SupervisorRoute>,
680}
681
682/// One live consumer route in a [`SupervisorRouteModule`].
683#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
684pub struct SupervisorRoute {
685    pub consumer: SupervisorRouteConsumer,
686    /// Milliseconds since the daemon bound this route.
687    pub age_ms: u64,
688    /// True once the endpoint began draining. Draining routes remain visible so
689    /// a census does not misreport an already-closing route as live.
690    pub draining: bool,
691    /// WHY the endpoint is draining — the same reason vocabulary the
692    /// route.closing push carries — present exactly when `draining` is true.
693    /// Additive: older daemons omit it, and a census consumer must treat a
694    /// draining route without a reason as draining-for-an-unstated-reason,
695    /// never as not-draining.
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub drain_reason: Option<RouteCloseReason>,
698}
699
700/// Source-tagged provenance for one supervised module.
701#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
702pub struct SupervisorModuleProvenance {
703    pub module_id: String,
704    pub module_declared: ModuleDeclaredProvenance,
705    pub daemon_observed: SupervisorObservedProcess,
706}
707
708/// A module's declared build metadata, if its HELLO manifest carried it.
709#[derive(Debug, Clone, PartialEq)]
710pub enum ModuleDeclaredProvenance {
711    Reported {
712        build: ManifestProvenance,
713    },
714    Unverifiable,
715    /// Future discriminator. `body` retains the complete ordered object; `tag`
716    /// is its decoded discriminator projection.
717    Unknown {
718        tag: String,
719        body: OrderedJsonObject,
720    },
721}
722
723/// Process facts observed by the daemon for a supervised module.
724///
725/// Build claims remain under `module_declared`; mixing them here would imply the
726/// daemon independently observed module-provided metadata.
727#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
728pub struct SupervisorObservedProcess {
729    /// The daemon's Windows delivery record for this process: `pipe` after the
730    /// process whose PID was returned by spawn has read all nonce bytes; `env`
731    /// when that delivery was not completed and SUBC_LAUNCH_NONCE was offered.
732    /// This is returned under `daemon_observed.launch_nonce_source` by
733    /// `supervisor.provenance`, and is absent when the daemon cannot report it.
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub launch_nonce_source: Option<String>,
736    #[serde(default, skip_serializing_if = "Option::is_none")]
737    pub pid: Option<u32>,
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub spawned_at_ms: Option<u64>,
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub spawned_from: Option<PathBuf>,
742    pub running_image: RunningImageAgreement,
743}
744
745/// Independent comparisons of configured path, launch spec and running image at list time.
746/// An absent verdict means the daemon predates this field, not agreement.
747#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
748pub struct PendingReloadVerdict {
749    pub path: ReloadPathAgreement,
750    pub image: RunningImageAgreement,
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub spec: Option<LaunchSpecAgreement>,
753}
754
755#[cfg(test)]
756mod launch_spec_wire_tests {
757    use super::*;
758
759    #[test]
760    fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
761        let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
762        let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
763        assert_eq!(parsed.spec, None);
764        assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
765        let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
766        let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
767        assert!(
768            matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
769        );
770        assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
771        let unavailable = LaunchSpecAgreement::Unavailable {
772            reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
773        };
774        let encoded = serde_json::to_string(&unavailable).unwrap();
775        assert_eq!(
776            encoded,
777            r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
778        );
779        assert_eq!(
780            serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
781            unavailable
782        );
783    }
784}
785
786/// Comparison of the configured launch inputs with the inputs recorded at spawn.
787/// No digest or configured env values are sent to clients.
788#[derive(Debug, Clone, PartialEq)]
789pub enum LaunchSpecAgreement {
790    Match,
791    Mismatch,
792    Unavailable {
793        reason: LaunchSpecUnavailableReason,
794    },
795    Unknown {
796        tag: String,
797        body: OrderedJsonObject,
798    },
799}
800
801open_string_enum! {
802    LaunchSpecUnavailableReason {
803        NotRunning => "not_running",
804        SpawnedSpecUnavailable => "spawned_spec_unavailable",
805    }
806}
807
808/// Whether the running process was spawned from the currently configured program.
809#[derive(Debug, Clone, PartialEq)]
810pub enum ReloadPathAgreement {
811    Match,
812    Mismatch {
813        configured: PathBuf,
814        spawned_from: PathBuf,
815    },
816    Unavailable {
817        reason: ReloadPathUnavailableReason,
818    },
819    Unknown {
820        tag: String,
821        body: OrderedJsonObject,
822    },
823}
824
825open_string_enum! {
826    /// Why configured and spawned paths cannot be compared.
827    ReloadPathUnavailableReason {
828        NotRunning => "not_running",
829        SpawnedPathUnavailable => "spawned_path_unavailable",
830    }
831}
832
833/// Daemon provenance paired with its runtime process observation.
834#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
835pub struct SupervisorDaemonProvenance {
836    pub daemon_build: DaemonBuildProvenance,
837    pub daemon_observed: DaemonObservedProcess,
838}
839
840/// Build metadata embedded in the daemon binary.
841#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
842pub struct DaemonBuildProvenance {
843    #[serde(default, skip_serializing_if = "Option::is_none")]
844    pub build_git_sha: Option<String>,
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub build_lock_digest: Option<String>,
847}
848
849/// Runtime process facts observed for the daemon itself.
850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
851pub struct DaemonObservedProcess {
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub pid: Option<u32>,
854    /// Wall time derived from suspend-inclusive elapsed time at each read. Clock
855    /// correction can move it by the size of a clock step, and even without a
856    /// step it may vary by about a second between reads. Do not equality-compare
857    /// it. Use raw process start ticks for stable identity.
858    #[serde(default, skip_serializing_if = "Option::is_none")]
859    pub started_at_ms: Option<u64>,
860    pub running_image: RunningImageAgreement,
861}
862
863/// Whether the executable currently running agrees with the spawned image.
864#[derive(Debug, Clone, PartialEq)]
865pub enum RunningImageAgreement {
866    Match {
867        evidence: RunningImageEvidence,
868    },
869    Mismatch {
870        running: RunningImageEvidence,
871        disk: RunningImageEvidence,
872    },
873    Unavailable {
874        reason: RunningImageUnavailableReason,
875    },
876    /// Future discriminator. `body` retains the complete ordered object; `tag`
877    /// is its decoded discriminator projection.
878    Unknown {
879        tag: String,
880        body: OrderedJsonObject,
881    },
882}
883
884/// Platform-specific evidence used to compare a running image with its spawn path.
885#[derive(Debug, Clone, PartialEq)]
886pub enum RunningImageEvidence {
887    LinuxProcSha256 {
888        digest: String,
889    },
890    MacosSpawnInode {
891        device: u64,
892        inode: u64,
893    },
894    /// The spawn-time Windows file object, not verified executable content.
895    WindowsSpawnFileId {
896        volume_serial_number: u64,
897        file_id: [u8; 16],
898    },
899    /// Future discriminator. `body` retains the complete ordered object; `tag`
900    /// is its decoded discriminator projection.
901    Unknown {
902        tag: String,
903        body: OrderedJsonObject,
904    },
905}
906
907open_string_enum! {
908    /// Reasons why an executable identity could not be observed.
909    RunningImageUnavailableReason {
910        NotRunning => "not_running",
911        NotYetMeasured => "not_yet_measured",
912        UnsupportedPlatform => "unsupported_platform",
913        RunningExecutableUnreadable => "running_executable_unreadable",
914        RunningExecutablePermissionDenied => "running_executable_permission_denied",
915        ProcessHidden => "process_hidden",
916        SpawnedPathUnreadable => "spawned_path_unreadable",
917        HashFailed => "hash_failed",
918        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
919    }
920}
921
922/// The identity tier the daemon can honestly report for a route consumer.
923///
924/// A caller that proved a live daemon-issued launch nonce is named `reserved`.
925/// A direct key-holder has no such attestation, so it is reported as `direct`
926/// with its connection counter instead of an invented module name.
927#[derive(Debug, Clone, PartialEq)]
928pub enum SupervisorRouteConsumer {
929    Reserved {
930        module_id: String,
931    },
932    Direct {
933        connection_id: u64,
934    },
935    /// Future discriminator. `body` retains the complete ordered object; `tag`
936    /// is its decoded discriminator projection.
937    Unknown {
938        tag: String,
939        body: OrderedJsonObject,
940    },
941}
942
943/// Whether stderr is being captured for a module, and if not, why not.
944///
945/// A typed state rather than an empty-tail convention. "The module printed
946/// nothing before dying" and "nobody was capturing" send an operator in opposite
947/// directions, and rendering them alike is the defect this op exists to fix --
948/// the same shape as a `detail -` that means both no-detail and never-probed.
949#[derive(Debug, Clone, PartialEq)]
950pub enum StderrCaptureState {
951    /// A reader is attached, or was attached and saw clean EOF. An empty
952    /// `entries` under this state means the module genuinely wrote nothing.
953    Captured,
954    /// Retained entries are valid, but the stderr reader ended before clean EOF.
955    Incomplete { reason: String },
956    /// No reader was attached. `entries` says nothing about what the module wrote.
957    NotCaptured { reason: String },
958    /// Future discriminator. `body` retains the complete ordered object; `tag`
959    /// is its decoded discriminator projection.
960    Unknown {
961        tag: String,
962        body: OrderedJsonObject,
963    },
964}
965
966#[derive(Debug, Clone, PartialEq)]
967pub enum StderrTailEntry {
968    Line {
969        text: String,
970        /// The line was cut at the per-line cap and `text` is a prefix.
971        ///
972        /// Carried as a field rather than left to a marker in `text` so a
973        /// consumer can branch on it without string matching.
974        truncated: bool,
975        /// Wall-clock Unix milliseconds at which the daemon read this line off
976        /// the module's pipe. `None` from a daemon that predates the field; a
977        /// reader must then show no time rather than make one up.
978        at_ms: Option<u64>,
979    },
980    /// The supervisor spawned a new process. Entries after this came from it.
981    ///
982    /// In-band because position is the information: which side of the restart a
983    /// line falls on is unanswerable from a count.
984    ProcessStart,
985    /// Future discriminator. `body` retains the complete ordered object; `tag`
986    /// is its decoded discriminator projection.
987    Unknown {
988        tag: String,
989        body: OrderedJsonObject,
990    },
991}
992
993#[derive(Debug, Serialize, Deserialize)]
994#[serde(tag = "status", rename_all = "snake_case")]
995enum ModuleDeclaredProvenanceWire {
996    Reported { build: ManifestProvenance },
997    Unverifiable,
998}
999
1000#[derive(Debug, Serialize, Deserialize)]
1001#[serde(tag = "status", rename_all = "snake_case")]
1002enum RunningImageAgreementWire {
1003    Match {
1004        evidence: RunningImageEvidence,
1005    },
1006    Mismatch {
1007        running: RunningImageEvidence,
1008        disk: RunningImageEvidence,
1009    },
1010    Unavailable {
1011        reason: RunningImageUnavailableReason,
1012    },
1013}
1014
1015#[derive(Debug, Serialize, Deserialize)]
1016#[serde(tag = "status", rename_all = "snake_case")]
1017enum ReloadPathAgreementWire {
1018    Match,
1019    Mismatch {
1020        configured: PathBuf,
1021        spawned_from: PathBuf,
1022    },
1023    Unavailable {
1024        reason: ReloadPathUnavailableReason,
1025    },
1026}
1027
1028#[derive(Debug, Serialize, Deserialize)]
1029#[serde(tag = "status", rename_all = "snake_case")]
1030enum LaunchSpecAgreementWire {
1031    Match,
1032    Mismatch,
1033    Unavailable { reason: LaunchSpecUnavailableReason },
1034}
1035
1036#[derive(Debug, Serialize, Deserialize)]
1037#[serde(tag = "method", rename_all = "snake_case")]
1038enum RunningImageEvidenceWire {
1039    LinuxProcSha256 {
1040        digest: String,
1041    },
1042    MacosSpawnInode {
1043        device: u64,
1044        inode: u64,
1045    },
1046    WindowsSpawnFileId {
1047        volume_serial_number: u64,
1048        file_id: [u8; 16],
1049    },
1050}
1051
1052#[derive(Debug, Serialize, Deserialize)]
1053#[serde(tag = "kind", rename_all = "snake_case")]
1054enum SupervisorRouteConsumerWire {
1055    Reserved { module_id: String },
1056    Direct { connection_id: u64 },
1057}
1058
1059#[derive(Debug, Serialize, Deserialize)]
1060#[serde(tag = "state", rename_all = "snake_case")]
1061enum StderrCaptureStateWire {
1062    Captured,
1063    Incomplete { reason: String },
1064    NotCaptured { reason: String },
1065}
1066
1067#[derive(Debug, Serialize, Deserialize)]
1068#[serde(tag = "status", rename_all = "snake_case")]
1069enum ChildResourceUsageWire {
1070    Measured(ChildResourceReading),
1071    Unavailable {
1072        reason: ChildResourceUnavailableReason,
1073    },
1074}
1075
1076#[derive(Debug, Serialize, Deserialize)]
1077#[serde(tag = "kind", rename_all = "snake_case")]
1078enum StderrTailEntryWire {
1079    Line {
1080        text: String,
1081        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1082        truncated: bool,
1083        // Omitted when absent so a reply without it is byte-identical to what
1084        // an older daemon sends. Older decoders ignore the member when present.
1085        #[serde(default, skip_serializing_if = "Option::is_none")]
1086        at_ms: Option<u64>,
1087    },
1088    ProcessStart,
1089}
1090
1091/// JSON values whose object members retain wire order at every depth.
1092#[derive(Debug, Clone, PartialEq)]
1093pub enum OrderedJsonValue {
1094    Null,
1095    Bool(bool),
1096    Number(serde_json::Number),
1097    String(String),
1098    Array(Vec<Self>),
1099    Object(OrderedJsonObject),
1100}
1101
1102/// Ordered JSON members retained for an unknown tagged value.
1103#[derive(Debug, Clone, PartialEq)]
1104pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1105
1106impl OrderedJsonObject {
1107    /// Returns the members in the order they appeared on the wire.
1108    pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1109        &self.0
1110    }
1111
1112    fn into_value(self) -> serde_json::Value {
1113        serde_json::Value::Object(
1114            self.0
1115                .into_iter()
1116                .map(|(key, value)| (key, value.into_value()))
1117                .collect(),
1118        )
1119    }
1120}
1121
1122impl OrderedJsonValue {
1123    fn into_value(self) -> serde_json::Value {
1124        match self {
1125            Self::Null => serde_json::Value::Null,
1126            Self::Bool(value) => serde_json::Value::Bool(value),
1127            Self::Number(value) => serde_json::Value::Number(value),
1128            Self::String(value) => serde_json::Value::String(value),
1129            Self::Array(values) => {
1130                serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1131            }
1132            Self::Object(value) => value.into_value(),
1133        }
1134    }
1135}
1136
1137impl Serialize for OrderedJsonValue {
1138    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1139    where
1140        S: Serializer,
1141    {
1142        match self {
1143            Self::Null => serializer.serialize_unit(),
1144            Self::Bool(value) => serializer.serialize_bool(*value),
1145            Self::Number(value) => value.serialize(serializer),
1146            Self::String(value) => serializer.serialize_str(value),
1147            Self::Array(values) => values.serialize(serializer),
1148            Self::Object(value) => value.serialize(serializer),
1149        }
1150    }
1151}
1152
1153impl<'de> Deserialize<'de> for OrderedJsonValue {
1154    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1155    where
1156        D: Deserializer<'de>,
1157    {
1158        struct OrderedValueVisitor;
1159
1160        impl<'de> Visitor<'de> for OrderedValueVisitor {
1161            type Value = OrderedJsonValue;
1162
1163            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1164                formatter.write_str("a JSON value with ordered object members")
1165            }
1166
1167            fn visit_unit<E>(self) -> Result<Self::Value, E>
1168            where
1169                E: serde::de::Error,
1170            {
1171                Ok(OrderedJsonValue::Null)
1172            }
1173
1174            fn visit_none<E>(self) -> Result<Self::Value, E>
1175            where
1176                E: serde::de::Error,
1177            {
1178                Ok(OrderedJsonValue::Null)
1179            }
1180
1181            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1182            where
1183                D: Deserializer<'de>,
1184            {
1185                OrderedJsonValue::deserialize(deserializer)
1186            }
1187
1188            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1189            where
1190                E: serde::de::Error,
1191            {
1192                Ok(OrderedJsonValue::Bool(value))
1193            }
1194
1195            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1196            where
1197                E: serde::de::Error,
1198            {
1199                Ok(OrderedJsonValue::Number(value.into()))
1200            }
1201
1202            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1203            where
1204                E: serde::de::Error,
1205            {
1206                Ok(OrderedJsonValue::Number(value.into()))
1207            }
1208
1209            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1210            where
1211                E: serde::de::Error,
1212            {
1213                serde_json::Number::from_f64(value)
1214                    .map(OrderedJsonValue::Number)
1215                    .ok_or_else(|| E::custom("non-finite JSON number"))
1216            }
1217
1218            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1219            where
1220                E: serde::de::Error,
1221            {
1222                Ok(OrderedJsonValue::String(value.to_owned()))
1223            }
1224
1225            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1226            where
1227                E: serde::de::Error,
1228            {
1229                Ok(OrderedJsonValue::String(value))
1230            }
1231
1232            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1233            where
1234                A: SeqAccess<'de>,
1235            {
1236                let mut values = Vec::new();
1237                while let Some(value) = sequence.next_element()? {
1238                    values.push(value);
1239                }
1240                Ok(OrderedJsonValue::Array(values))
1241            }
1242
1243            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1244            where
1245                A: MapAccess<'de>,
1246            {
1247                let mut entries = Vec::new();
1248                while let Some((key, value)) = map.next_entry()? {
1249                    entries.push((key, value));
1250                }
1251                Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1252            }
1253        }
1254
1255        deserializer.deserialize_any(OrderedValueVisitor)
1256    }
1257}
1258
1259impl Serialize for OrderedJsonObject {
1260    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1261    where
1262        S: Serializer,
1263    {
1264        let mut map = serializer.serialize_map(Some(self.0.len()))?;
1265        for (key, value) in &self.0 {
1266            map.serialize_entry(key, value)?;
1267        }
1268        map.end()
1269    }
1270}
1271
1272impl<'de> Deserialize<'de> for OrderedJsonObject {
1273    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1274    where
1275        D: Deserializer<'de>,
1276    {
1277        struct OrderedObjectVisitor;
1278
1279        impl<'de> Visitor<'de> for OrderedObjectVisitor {
1280            type Value = OrderedJsonObject;
1281
1282            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1283                formatter.write_str("an object with ordered JSON members")
1284            }
1285
1286            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1287            where
1288                A: MapAccess<'de>,
1289            {
1290                let mut entries = Vec::new();
1291                while let Some((key, value)) = map.next_entry()? {
1292                    entries.push((key, value));
1293                }
1294                Ok(OrderedJsonObject(entries))
1295            }
1296        }
1297
1298        deserializer.deserialize_map(OrderedObjectVisitor)
1299    }
1300}
1301
1302fn read_tagged<'de, D>(
1303    deserializer: D,
1304    field: &'static str,
1305) -> Result<(String, OrderedJsonObject), D::Error>
1306where
1307    D: Deserializer<'de>,
1308{
1309    let body = OrderedJsonObject::deserialize(deserializer)?;
1310    let mut tag = None;
1311    for (key, value) in body.as_entries() {
1312        if key != field {
1313            continue;
1314        }
1315        if tag.is_some() {
1316            return Err(D::Error::custom(format!(
1317                "tagged object has duplicate `{field}` field"
1318            )));
1319        }
1320        let OrderedJsonValue::String(value) = value else {
1321            return Err(D::Error::custom(format!(
1322                "tagged object has no string `{field}` field"
1323            )));
1324        };
1325        tag = Some(value);
1326    }
1327    let Some(tag) = tag else {
1328        return Err(D::Error::custom(format!(
1329            "tagged object has no string `{field}` field"
1330        )));
1331    };
1332    Ok((tag.to_string(), body))
1333}
1334
1335fn read_ordered_tagged(
1336    value: OrderedJsonValue,
1337    field: &'static str,
1338) -> Result<(String, OrderedJsonObject), String> {
1339    let OrderedJsonValue::Object(body) = value else {
1340        return Err(format!("expected tagged object with `{field}` field"));
1341    };
1342    let mut tag = None;
1343    for (key, value) in body.as_entries() {
1344        if key != field {
1345            continue;
1346        }
1347        if tag.is_some() {
1348            return Err(format!("tagged object has duplicate `{field}` field"));
1349        }
1350        let OrderedJsonValue::String(value) = value else {
1351            return Err(format!("tagged object has no string `{field}` field"));
1352        };
1353        tag = Some(value);
1354    }
1355    let Some(tag) = tag else {
1356        return Err(format!("tagged object has no string `{field}` field"));
1357    };
1358    Ok((tag.to_string(), body))
1359}
1360
1361fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1362    body.as_entries()
1363        .iter()
1364        .find_map(|(key, value)| (key == field).then_some(value))
1365}
1366
1367fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1368    match ordered_field(body, field) {
1369        Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1370        Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1371        None => Err(format!("tagged object has no `{field}` field")),
1372    }
1373}
1374
1375fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1376    let (tag, body) = read_ordered_tagged(value, "method")?;
1377    match tag.as_str() {
1378        "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1379            digest: ordered_string(&body, "digest")?,
1380        }),
1381        "macos_spawn_inode" => {
1382            let device = ordered_field(&body, "device")
1383                .and_then(|value| match value {
1384                    OrderedJsonValue::Number(number) => number.as_u64(),
1385                    _ => None,
1386                })
1387                .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1388            let inode = ordered_field(&body, "inode")
1389                .and_then(|value| match value {
1390                    OrderedJsonValue::Number(number) => number.as_u64(),
1391                    _ => None,
1392                })
1393                .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1394            Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1395        }
1396        "windows_spawn_file_id" => {
1397            let wire: RunningImageEvidenceWire = serde_json::from_value(
1398                serde_json::to_value(&body).map_err(|error| error.to_string())?,
1399            )
1400            .map_err(|error| error.to_string())?;
1401            match wire {
1402                RunningImageEvidenceWire::WindowsSpawnFileId {
1403                    volume_serial_number,
1404                    file_id,
1405                } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1406                    volume_serial_number,
1407                    file_id,
1408                }),
1409                _ => unreachable!(),
1410            }
1411        }
1412        _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1413    }
1414}
1415
1416impl Serialize for ModuleDeclaredProvenance {
1417    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1418    where
1419        S: Serializer,
1420    {
1421        match self {
1422            Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1423                build: build.clone(),
1424            }
1425            .serialize(serializer),
1426            Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1427            Self::Unknown { body, .. } => body.serialize(serializer),
1428        }
1429    }
1430}
1431
1432impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1433    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1434    where
1435        D: serde::Deserializer<'de>,
1436    {
1437        let (tag, value) = read_tagged(deserializer, "status")?;
1438        match tag.as_str() {
1439            "reported" => match serde_json::from_value(value.into_value())
1440                .map_err(D::Error::custom)?
1441            {
1442                ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1443                ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1444            },
1445            "unverifiable" => {
1446                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1447                    ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1448                    ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1449                }
1450            }
1451            _ => Ok(Self::Unknown { tag, body: value }),
1452        }
1453    }
1454}
1455
1456impl Serialize for RunningImageAgreement {
1457    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1458    where
1459        S: Serializer,
1460    {
1461        match self {
1462            Self::Match { evidence } => RunningImageAgreementWire::Match {
1463                evidence: evidence.clone(),
1464            }
1465            .serialize(serializer),
1466            Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1467                running: running.clone(),
1468                disk: disk.clone(),
1469            }
1470            .serialize(serializer),
1471            Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1472                reason: reason.clone(),
1473            }
1474            .serialize(serializer),
1475            Self::Unknown { body, .. } => body.serialize(serializer),
1476        }
1477    }
1478}
1479
1480impl Serialize for ReloadPathAgreement {
1481    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1482    where
1483        S: Serializer,
1484    {
1485        match self {
1486            Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1487            Self::Mismatch {
1488                configured,
1489                spawned_from,
1490            } => ReloadPathAgreementWire::Mismatch {
1491                configured: configured.clone(),
1492                spawned_from: spawned_from.clone(),
1493            }
1494            .serialize(serializer),
1495            Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1496                reason: reason.clone(),
1497            }
1498            .serialize(serializer),
1499            Self::Unknown { body, .. } => body.serialize(serializer),
1500        }
1501    }
1502}
1503
1504impl Serialize for LaunchSpecAgreement {
1505    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1506    where
1507        S: Serializer,
1508    {
1509        match self {
1510            Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1511            Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1512            Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1513                reason: reason.clone(),
1514            }
1515            .serialize(serializer),
1516            Self::Unknown { body, .. } => body.serialize(serializer),
1517        }
1518    }
1519}
1520
1521impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1522    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1523    where
1524        D: Deserializer<'de>,
1525    {
1526        let (tag, body) = read_tagged(deserializer, "status")?;
1527        match tag.as_str() {
1528            "match" => Ok(Self::Match),
1529            "mismatch" => Ok(Self::Mismatch),
1530            "unavailable" => match serde_json::from_value(body.into_value())
1531                .map_err(D::Error::custom)?
1532            {
1533                LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1534                _ => unreachable!(),
1535            },
1536            _ => Ok(Self::Unknown { tag, body }),
1537        }
1538    }
1539}
1540
1541impl<'de> Deserialize<'de> for ReloadPathAgreement {
1542    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1543    where
1544        D: Deserializer<'de>,
1545    {
1546        let (tag, body) = read_tagged(deserializer, "status")?;
1547        match tag.as_str() {
1548            "match" => Ok(Self::Match),
1549            "mismatch" => {
1550                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1551                    ReloadPathAgreementWire::Mismatch {
1552                        configured,
1553                        spawned_from,
1554                    } => Ok(Self::Mismatch {
1555                        configured,
1556                        spawned_from,
1557                    }),
1558                    _ => unreachable!(),
1559                }
1560            }
1561            "unavailable" => match serde_json::from_value(body.into_value())
1562                .map_err(D::Error::custom)?
1563            {
1564                ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1565                _ => unreachable!(),
1566            },
1567            _ => Ok(Self::Unknown { tag, body }),
1568        }
1569    }
1570}
1571
1572impl<'de> Deserialize<'de> for RunningImageAgreement {
1573    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1574    where
1575        D: serde::Deserializer<'de>,
1576    {
1577        let (tag, value) = read_tagged(deserializer, "status")?;
1578        match tag.as_str() {
1579            "match" => Ok(Self::Match {
1580                evidence: decode_running_image_evidence(
1581                    ordered_field(&value, "evidence")
1582                        .cloned()
1583                        .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1584                )
1585                .map_err(D::Error::custom)?,
1586            }),
1587            "mismatch" => Ok(Self::Mismatch {
1588                running: decode_running_image_evidence(
1589                    ordered_field(&value, "running")
1590                        .cloned()
1591                        .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1592                )
1593                .map_err(D::Error::custom)?,
1594                disk: decode_running_image_evidence(
1595                    ordered_field(&value, "disk")
1596                        .cloned()
1597                        .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1598                )
1599                .map_err(D::Error::custom)?,
1600            }),
1601            "unavailable" => Ok(Self::Unavailable {
1602                reason: serde_json::from_value(
1603                    ordered_field(&value, "reason")
1604                        .cloned()
1605                        .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1606                        .into_value(),
1607                )
1608                .map_err(D::Error::custom)?,
1609            }),
1610            _ => Ok(Self::Unknown { tag, body: value }),
1611        }
1612    }
1613}
1614
1615impl Serialize for ChildResourceUsage {
1616    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1617    where
1618        S: Serializer,
1619    {
1620        match self {
1621            Self::Measured(reading) => {
1622                ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1623            }
1624            Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1625                reason: reason.clone(),
1626            }
1627            .serialize(serializer),
1628            Self::Unknown { body, .. } => body.serialize(serializer),
1629        }
1630    }
1631}
1632
1633impl<'de> Deserialize<'de> for ChildResourceUsage {
1634    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1635    where
1636        D: Deserializer<'de>,
1637    {
1638        let (tag, body) = read_tagged(deserializer, "status")?;
1639        match tag.as_str() {
1640            "measured" | "unavailable" => {
1641                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1642                    ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1643                    ChildResourceUsageWire::Unavailable { reason } => {
1644                        Ok(Self::Unavailable { reason })
1645                    }
1646                }
1647            }
1648            _ => Ok(Self::Unknown { tag, body }),
1649        }
1650    }
1651}
1652
1653impl Serialize for RunningImageEvidence {
1654    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1655    where
1656        S: Serializer,
1657    {
1658        match self {
1659            Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1660                digest: digest.clone(),
1661            }
1662            .serialize(serializer),
1663            Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1664                device: *device,
1665                inode: *inode,
1666            }
1667            .serialize(serializer),
1668            Self::WindowsSpawnFileId {
1669                volume_serial_number,
1670                file_id,
1671            } => RunningImageEvidenceWire::WindowsSpawnFileId {
1672                volume_serial_number: *volume_serial_number,
1673                file_id: *file_id,
1674            }
1675            .serialize(serializer),
1676            Self::Unknown { body, .. } => body.serialize(serializer),
1677        }
1678    }
1679}
1680
1681impl<'de> Deserialize<'de> for RunningImageEvidence {
1682    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1683    where
1684        D: serde::Deserializer<'de>,
1685    {
1686        let (tag, value) = read_tagged(deserializer, "method")?;
1687        match tag.as_str() {
1688            "linux_proc_sha256" => {
1689                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1690                    RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1691                        Ok(Self::LinuxProcSha256 { digest })
1692                    }
1693                    _ => unreachable!(),
1694                }
1695            }
1696            "macos_spawn_inode" => {
1697                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1698                    RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1699                        Ok(Self::MacosSpawnInode { device, inode })
1700                    }
1701                    _ => unreachable!(),
1702                }
1703            }
1704            "windows_spawn_file_id" => {
1705                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1706                    RunningImageEvidenceWire::WindowsSpawnFileId {
1707                        volume_serial_number,
1708                        file_id,
1709                    } => Ok(Self::WindowsSpawnFileId {
1710                        volume_serial_number,
1711                        file_id,
1712                    }),
1713                    _ => unreachable!(),
1714                }
1715            }
1716            _ => Ok(Self::Unknown { tag, body: value }),
1717        }
1718    }
1719}
1720
1721impl Serialize for SupervisorRouteConsumer {
1722    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1723    where
1724        S: Serializer,
1725    {
1726        match self {
1727            Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1728                module_id: module_id.clone(),
1729            }
1730            .serialize(serializer),
1731            Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1732                connection_id: *connection_id,
1733            }
1734            .serialize(serializer),
1735            Self::Unknown { body, .. } => body.serialize(serializer),
1736        }
1737    }
1738}
1739
1740impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1741    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1742    where
1743        D: serde::Deserializer<'de>,
1744    {
1745        let (tag, value) = read_tagged(deserializer, "kind")?;
1746        match tag.as_str() {
1747            "reserved" => {
1748                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1749                    SupervisorRouteConsumerWire::Reserved { module_id } => {
1750                        Ok(Self::Reserved { module_id })
1751                    }
1752                    _ => unreachable!(),
1753                }
1754            }
1755            "direct" => {
1756                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1757                    SupervisorRouteConsumerWire::Direct { connection_id } => {
1758                        Ok(Self::Direct { connection_id })
1759                    }
1760                    _ => unreachable!(),
1761                }
1762            }
1763            _ => Ok(Self::Unknown { tag, body: value }),
1764        }
1765    }
1766}
1767
1768impl Serialize for StderrCaptureState {
1769    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1770    where
1771        S: Serializer,
1772    {
1773        match self {
1774            Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1775            Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1776                reason: reason.clone(),
1777            }
1778            .serialize(serializer),
1779            Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1780                reason: reason.clone(),
1781            }
1782            .serialize(serializer),
1783            Self::Unknown { body, .. } => body.serialize(serializer),
1784        }
1785    }
1786}
1787
1788impl<'de> Deserialize<'de> for StderrCaptureState {
1789    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1790    where
1791        D: serde::Deserializer<'de>,
1792    {
1793        let (tag, value) = read_tagged(deserializer, "state")?;
1794        match tag.as_str() {
1795            "captured" => {
1796                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1797                    StderrCaptureStateWire::Captured => Ok(Self::Captured),
1798                    _ => unreachable!(),
1799                }
1800            }
1801            "incomplete" => match serde_json::from_value(value.into_value())
1802                .map_err(D::Error::custom)?
1803            {
1804                StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1805                _ => unreachable!(),
1806            },
1807            "not_captured" => match serde_json::from_value(value.into_value())
1808                .map_err(D::Error::custom)?
1809            {
1810                StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1811                _ => unreachable!(),
1812            },
1813            _ => Ok(Self::Unknown { tag, body: value }),
1814        }
1815    }
1816}
1817
1818impl Serialize for StderrTailEntry {
1819    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1820    where
1821        S: Serializer,
1822    {
1823        match self {
1824            Self::Line {
1825                text,
1826                truncated,
1827                at_ms,
1828            } => StderrTailEntryWire::Line {
1829                text: text.clone(),
1830                truncated: *truncated,
1831                at_ms: *at_ms,
1832            }
1833            .serialize(serializer),
1834            Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1835            Self::Unknown { body, .. } => body.serialize(serializer),
1836        }
1837    }
1838}
1839
1840impl<'de> Deserialize<'de> for StderrTailEntry {
1841    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1842    where
1843        D: serde::Deserializer<'de>,
1844    {
1845        let (tag, value) = read_tagged(deserializer, "kind")?;
1846        match tag.as_str() {
1847            "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1848                StderrTailEntryWire::Line {
1849                    text,
1850                    truncated,
1851                    at_ms,
1852                } => Ok(Self::Line {
1853                    text,
1854                    truncated,
1855                    at_ms,
1856                }),
1857                _ => unreachable!(),
1858            },
1859            "process_start" => {
1860                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1861                    StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1862                    _ => unreachable!(),
1863                }
1864            }
1865            _ => Ok(Self::Unknown { tag, body: value }),
1866        }
1867    }
1868}
1869
1870fn is_zero_u64(value: &u64) -> bool {
1871    *value == 0
1872}
1873
1874fn default_true() -> bool {
1875    true
1876}
1877
1878/// Bounded terminal history for one module, oldest retained record first.
1879#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1880pub struct TerminalHistory {
1881    /// Unix milliseconds at the current daemon's start; entries may predate it.
1882    pub daemon_started_at_ms: u64,
1883    pub entries: Vec<TerminalEntry>,
1884    /// Exits evicted by the current daemon's ring, possibly recovered from its
1885    /// journal. Not a count of missing exits: expired journal totals are unknown.
1886    #[serde(default, skip_serializing_if = "is_zero_u64")]
1887    pub dropped: u64,
1888    /// Unparseable or incomplete lines across the shared journal, including
1889    /// lines whose module cannot be determined. Zero on older daemons.
1890    #[serde(default, skip_serializing_if = "is_zero_u64")]
1891    pub journal_skipped_lines: u64,
1892    /// Files that could not be read completely, excluding absent generations.
1893    #[serde(default, skip_serializing_if = "is_zero_u64")]
1894    pub journal_read_errors: u64,
1895    /// Failed journal appends across all modules in the current daemon.
1896    #[serde(default, skip_serializing_if = "is_zero_u64")]
1897    pub journal_write_failures: u64,
1898}
1899
1900/// One terminal child exit and the supervisor action it selected.
1901#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1902pub struct TerminalEntry {
1903    /// Opaque identity of the daemon that observed this exit; absent on older
1904    /// daemons. Different tokens mean different lifetimes, not chronological order.
1905    #[serde(default, skip_serializing_if = "Option::is_none")]
1906    pub daemon_incarnation: Option<String>,
1907    #[serde(default, skip_serializing_if = "Option::is_none")]
1908    pub exit_code: Option<i32>,
1909    #[serde(default, skip_serializing_if = "Option::is_none")]
1910    pub exit_signal: Option<i32>,
1911    pub at_ms: u64,
1912    pub disposition: TerminalDisposition,
1913    /// Supervisor classification of this exit. Absent on daemons that predate
1914    /// the field; unknown future kinds remain readable instead of failing the
1915    /// enclosing terminal record.
1916    #[serde(default, skip_serializing_if = "Option::is_none")]
1917    pub exit_kind: Option<TerminalExitKind>,
1918    /// Why the supervisor chose this disposition, when the disposition alone
1919    /// does not say. A `failed` record carries the exhausted crash budget here
1920    /// (`crash budget exhausted: max_restarts=3 within window_secs=600`), which
1921    /// is the difference between an operator seeing "it failed" and seeing which
1922    /// limit stopped it. Prose for humans: render it, never parse it. Absent for
1923    /// ordinary dispositions and on daemons predating the field.
1924    #[serde(default, skip_serializing_if = "Option::is_none")]
1925    pub disposition_detail: Option<String>,
1926}
1927
1928/// Exit classification carried by supervisor history and census records.
1929///
1930/// This is an open string enum so future daemon variants degrade to a readable
1931/// unknown kind rather than making a consumer discard the enclosing record.
1932#[derive(Debug, Clone, PartialEq, Eq)]
1933pub enum TerminalExitKind {
1934    Clean,
1935    Crash,
1936    DeliberateSeverance,
1937    Unknown(String),
1938}
1939
1940impl TerminalExitKind {
1941    fn wire_name(&self) -> &str {
1942        match self {
1943            Self::Clean => "clean",
1944            Self::Crash => "crash",
1945            Self::DeliberateSeverance => "deliberate_severance",
1946            Self::Unknown(value) => value,
1947        }
1948    }
1949}
1950
1951impl Serialize for TerminalExitKind {
1952    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1953    where
1954        S: serde::Serializer,
1955    {
1956        serializer.serialize_str(self.wire_name())
1957    }
1958}
1959
1960impl<'de> Deserialize<'de> for TerminalExitKind {
1961    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1962    where
1963        D: serde::Deserializer<'de>,
1964    {
1965        let value = String::deserialize(deserializer)?;
1966        Ok(match value.as_str() {
1967            "clean" => Self::Clean,
1968            "crash" => Self::Crash,
1969            "deliberate_severance" => Self::DeliberateSeverance,
1970            _ => Self::Unknown(value),
1971        })
1972    }
1973}
1974
1975open_string_enum! {
1976    /// The supervisor disposition selected after observing a terminal exit.
1977    TerminalDisposition {
1978        Stopped => "stopped",
1979        Disabled => "disabled",
1980        Failed => "failed",
1981        Restarting => "restarting",
1982        /// The child exited after the daemon had begun its own announced
1983        /// shutdown, whatever its exit code or signal. Such an exit is not
1984        /// a crash and is never followed by a respawn. Readers that predate
1985        /// this value decode it as `Unknown("daemon_shutdown")`.
1986        DaemonShutdown => "daemon_shutdown",
1987    }
1988}
1989
1990#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1991#[serde(rename_all = "snake_case")]
1992pub enum PollKind {
1993    Status,
1994    Liveness,
1995}
1996
1997/// A registered module's catalog projection.
1998///
1999/// Use [`CatalogEntry::new`] and its `with_*` methods to construct entries so
2000/// future fields do not require changes to callers.
2001/// Struct literals and functional record updates are not supported outside this crate:
2002///
2003/// ```compile_fail,E0639
2004/// use subc_control::CatalogEntry;
2005/// let entry = CatalogEntry::new("provider", vec![], vec![]);
2006/// let entry = CatalogEntry { ready: false, ..entry };
2007/// ```
2008#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2009#[non_exhaustive]
2010pub struct CatalogEntry {
2011    pub module_id: String,
2012    /// Module-declared human-readable name. Apps fall back to `module_id`.
2013    #[serde(default, skip_serializing_if = "Option::is_none")]
2014    pub display_name: Option<String>,
2015    /// Whether the registered module currently accepts new route binds.
2016    ///
2017    /// This is the module's EFFECTIVE readiness: its own declared readiness
2018    /// AND every one of its `need: required` capabilities having a registered
2019    /// provider. It is exactly the condition `route.open` checks, so a caller
2020    /// reading `false` here will be refused with `module_warming`; `not_ready`
2021    /// says why.
2022    ///
2023    /// Older daemons omit this field and are interpreted as ready. Daemons that
2024    /// predate `not_ready` report declared readiness only.
2025    #[serde(default = "default_true")]
2026    pub ready: bool,
2027    /// Why `ready` is false, in the same shape `route.open` puts in the
2028    /// `detail` of its `module_warming` refusal. Absent when the module is
2029    /// ready, and absent from daemons that predate the field.
2030    #[serde(default, skip_serializing_if = "Option::is_none")]
2031    pub not_ready: Option<NotReadyReason>,
2032    /// The registered module's self-declared build version, projected from its
2033    /// manifest so a consumer can tell WHICH BUILD of a module it is talking
2034    /// to at connect time.
2035    ///
2036    /// Without this, a client compiled against a module's current source reads
2037    /// a contract that is true of the repository and false of the running
2038    /// process -- the types match, the JSON decodes, and the meaning has
2039    /// changed. That failure carries no error to notice; the version in the
2040    /// catalog turns a semantic skew into a log line at connect instead of a
2041    /// wrong sentence on a user's screen.
2042    ///
2043    /// Optional on the wire only because entries serialized by older daemons
2044    /// lack it: absent means "daemon predates the field", never "module has
2045    /// no version" (the manifest field is required at registration).
2046    ///
2047    /// The reading is ARMED BY OBSERVATION, not by this documentation: until
2048    /// a consumer has seen at least one populated entry from the daemon it is
2049    /// connected to, an all-None catalog is indistinguishable from an old
2050    /// daemon, and a client shipping the documented reading against it would
2051    /// hold a guarantee it does not have.
2052    #[serde(default, skip_serializing_if = "Option::is_none")]
2053    pub module_version: Option<String>,
2054    /// Build provenance mirrored from the registered module's manifest.
2055    /// Absent when the module did not declare it or the daemon predates the field.
2056    #[serde(default, skip_serializing_if = "Option::is_none")]
2057    pub provenance: Option<ManifestProvenance>,
2058    pub roles: Vec<ProviderRole>,
2059    pub control_ops: Vec<String>,
2060    /// Static capability declarations from the registering module's manifest.
2061    ///
2062    /// Optional on the wire so consumers connected to a daemon that predates the
2063    /// capability grammar retain their existing catalog decoding behavior.
2064    #[serde(default, skip_serializing_if = "Option::is_none")]
2065    pub capabilities: Option<CapabilityDeclarations>,
2066    /// Self-signal declarations mirrored verbatim from the registering module's
2067    /// manifest. The daemon relays these declarations without interpreting them.
2068    #[serde(default, skip_serializing_if = "Option::is_none")]
2069    pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2070    /// Event declarations mirrored verbatim from the registering module's manifest.
2071    /// Absent when the manifest omits `events`; an empty array records an affirmative
2072    /// declaration that the module publishes no events.
2073    #[serde(default, skip_serializing_if = "Option::is_none")]
2074    pub events: Option<Vec<EventDeclaration>>,
2075    /// Open delivery hints mirrored from the module manifest. Empty means unary;
2076    /// only `"watch"` on a declared management query is subscribable.
2077    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2078    pub operation_delivery: BTreeMap<String, OperationDelivery>,
2079    /// Raw request payload limits mirrored from the module manifest by operation
2080    /// name. Empty maps preserve catalog bytes from before payload declarations.
2081    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2082    pub operation_payload: BTreeMap<String, OperationPayload>,
2083    /// Management operations the module serves to a flow-scoped call, mirrored
2084    /// unchanged from its manifest. Absent means the module did not say, so a
2085    /// reader treats the answer as unknown rather than as "none"; an empty list
2086    /// admits no operation under a flow scope. Absence preserves catalog bytes
2087    /// from before the field. The daemon relays it and never enforces it.
2088    #[serde(default, skip_serializing_if = "Option::is_none")]
2089    pub flow_operations: Option<Vec<String>>,
2090    /// Management operations the module guards with `operator.confirm`,
2091    /// mirrored unchanged from its manifest. Absent means the module did not
2092    /// say (or declared an invalid list, which the daemon dropped), so a reader
2093    /// treats the answer as unknown. Absence preserves catalog bytes from before
2094    /// the field. The daemon relays it and refuses nothing on its basis.
2095    #[serde(default, skip_serializing_if = "Option::is_none")]
2096    pub confirm_operations: Option<Vec<String>>,
2097    /// Rich-UI descriptor mirrored verbatim from the registering manifest.
2098    /// The daemon does not fetch or interpret the manifest described here.
2099    #[serde(default, skip_serializing_if = "Option::is_none")]
2100    pub rich_ui: Option<RichUiDescriptor>,
2101    /// Opaque per-role objects mirrored unchanged from the registered manifest.
2102    /// Each role owns its schema; the daemon validates only keys, shape and size.
2103    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2104    pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2105    /// True only when HELLO passes the launch-nonce check required for a reserved
2106    /// module or swap candidate.
2107    #[serde(default, skip_serializing_if = "is_false")]
2108    pub nonce_verified: bool,
2109}
2110
2111impl CatalogEntry {
2112    /// Sets the optional module-declared display name.
2113    #[must_use]
2114    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2115        self.display_name = display_name;
2116        self
2117    }
2118
2119    /// Construct an entry with its required fields and wire-compatible defaults.
2120    #[must_use]
2121    pub fn new(
2122        module_id: impl Into<String>,
2123        roles: Vec<ProviderRole>,
2124        control_ops: Vec<String>,
2125    ) -> Self {
2126        Self {
2127            module_id: module_id.into(),
2128            ready: default_true(),
2129            display_name: None,
2130            not_ready: None,
2131            module_version: None,
2132            provenance: None,
2133            roles,
2134            control_ops,
2135            capabilities: None,
2136            self_signals: None,
2137            events: None,
2138            operation_delivery: BTreeMap::new(),
2139            operation_payload: BTreeMap::new(),
2140            flow_operations: None,
2141            confirm_operations: None,
2142            rich_ui: None,
2143            role_declarations: BTreeMap::new(),
2144            nonce_verified: false,
2145        }
2146    }
2147
2148    /// Set raw request payload limits mirrored from the registered manifest.
2149    #[must_use]
2150    pub fn with_operation_payload(
2151        mut self,
2152        operation_payload: BTreeMap<String, OperationPayload>,
2153    ) -> Self {
2154        self.operation_payload = operation_payload;
2155        self
2156    }
2157
2158    /// Set or clear the flow-scoped operation list mirrored from the registered
2159    /// manifest. `None` is omitted from the wire.
2160    #[must_use]
2161    pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2162        self.flow_operations = flow_operations;
2163        self
2164    }
2165
2166    /// Set or clear the confirm-guarded operation list mirrored from the
2167    /// registered manifest. `None` is omitted from the wire.
2168    #[must_use]
2169    pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2170        self.confirm_operations = confirm_operations;
2171        self
2172    }
2173
2174    /// Set the module's effective readiness.
2175    #[must_use]
2176    pub fn with_ready(mut self, ready: bool) -> Self {
2177        self.ready = ready;
2178        self
2179    }
2180
2181    /// Set or clear the reason the module is not ready.
2182    #[must_use]
2183    pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2184        self.not_ready = not_ready;
2185        self
2186    }
2187
2188    /// Set or clear the module's self-declared version.
2189    #[must_use]
2190    pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2191        self.module_version = module_version;
2192        self
2193    }
2194
2195    /// Set or clear the build provenance mirrored from the registered manifest.
2196    #[must_use]
2197    pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2198        self.provenance = provenance;
2199        self
2200    }
2201
2202    /// Set or clear the module's static capability declarations.
2203    #[must_use]
2204    pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2205        self.capabilities = capabilities;
2206        self
2207    }
2208
2209    /// Set or clear the module's self-signal declarations.
2210    #[must_use]
2211    pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2212        self.self_signals = self_signals;
2213        self
2214    }
2215
2216    /// Set or clear the event declarations mirrored from the module manifest.
2217    #[must_use]
2218    pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2219        self.events = events;
2220        self
2221    }
2222
2223    /// Set delivery hints mirrored from the module manifest.
2224    /// Serialization omits this field when the stored map is empty.
2225    #[must_use]
2226    pub fn with_operation_delivery(
2227        mut self,
2228        operation_delivery: BTreeMap<String, OperationDelivery>,
2229    ) -> Self {
2230        self.operation_delivery = operation_delivery;
2231        self
2232    }
2233
2234    /// Set the descriptor mirrored from the module's HELLO manifest.
2235    #[must_use]
2236    pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2237        self.rich_ui = rich_ui;
2238        self
2239    }
2240
2241    /// Set opaque per-role declarations mirrored from the registered manifest.
2242    #[must_use]
2243    pub fn with_role_declarations(
2244        mut self,
2245        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2246    ) -> Self {
2247        self.role_declarations = role_declarations;
2248        self
2249    }
2250
2251    /// Mark a registration as nonce-verified when HELLO passes the launch-nonce
2252    /// check required for a reserved module or swap candidate.
2253    #[must_use]
2254    pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2255        self.nonce_verified = nonce_verified;
2256        self
2257    }
2258}
2259
2260fn is_false(value: &bool) -> bool {
2261    !value
2262}
2263
2264/// Why a registered module is not accepting new route binds.
2265#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2266pub struct NotReadyReason {
2267    /// `declared_not_ready` when the module itself said it is not ready, or
2268    /// `required_capability_unprovided` when a capability it declares
2269    /// `need: required` has no registered provider. Open vocabulary: a newer
2270    /// daemon may add reasons.
2271    pub reason: String,
2272    /// For `required_capability_unprovided`, the lexicographically first
2273    /// required capability that has no registered provider.
2274    #[serde(default, skip_serializing_if = "Option::is_none")]
2275    pub capability: Option<String>,
2276}
2277
2278impl NotReadyReason {
2279    pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2280    pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2281}
2282
2283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2284pub struct CapabilityRequirementStatus {
2285    pub consumer: String,
2286    pub capability: String,
2287    pub need: String,
2288    pub verdict: String,
2289    pub episode_seq: u64,
2290    pub config_satisfiable: bool,
2291    pub runtime_available: bool,
2292    pub detail: String,
2293}
2294
2295#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2296pub struct SupervisorRescanResult {
2297    pub added: Vec<String>,
2298    pub removed: Vec<String>,
2299    pub changed_pending_reload: Vec<String>,
2300    /// Modules whose enabled flag differs between config and running state.
2301    ///
2302    /// Rescan calls `set_enabled` for these, so omitting them made the preview
2303    /// describe two of the three mutation classes it performs. A module changing
2304    /// only its enabled flag landed in no bucket at all -- not added, removed or
2305    /// changed, and deliberately not counted as unchanged either -- so the sole
2306    /// evidence was that the buckets no longer summed to the configured module
2307    /// count. A preview is consulted precisely when someone is being careful,
2308    /// which is the worst place to under-report.
2309    ///
2310    /// Empty is skipped so consumers written against the older shape keep
2311    /// parsing.
2312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2313    pub enabled_changes: Vec<String>,
2314    pub unchanged: u32,
2315    /// True when this reconciliation was computed but NOT applied.
2316    ///
2317    /// Carried on the result rather than left to the caller's memory of what it
2318    /// asked for. A preview and an execution are otherwise byte-identical, so a
2319    /// reader who meets this output later -- in a log, a transcript, a pasted
2320    /// snippet -- cannot tell which one happened. Absent when false, so existing
2321    /// consumers see the shape they already parse.
2322    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2323    pub preview: bool,
2324    /// Config sections that changed but which rescan CANNOT apply, so the
2325    /// operator learns a daemon restart is required from the command they just
2326    /// ran rather than from the journal.
2327    ///
2328    /// The daemon has always detected this and logged a warning. A warning in a
2329    /// log is addressed to whoever is reading the log, and the person who just
2330    /// edited the config is by construction looking at the CLI instead: reported
2331    /// by an outside contributor after a module crash-looped through four
2332    /// respawns because a new top-level `storage` section was silently not
2333    /// applied, diagnosable only by journal archaeology.
2334    ///
2335    /// Names the SECTIONS rather than a boolean, because "something else
2336    /// changed" sends the operator back to diffing their own file -- which is
2337    /// the work the message exists to save.
2338    ///
2339    /// Empty is skipped, so consumers written against the older shape keep
2340    /// parsing.
2341    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2342    pub restart_required: Vec<String>,
2343    /// Required capabilities that a dry-run's resulting module set would leave
2344    /// unprovided. Rows are human-readable because the preview is an operator
2345    /// explanation, not a second manifest schema.
2346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2347    pub capability_warnings: Vec<String>,
2348    /// What applying the previewed candidate would do to each module, in
2349    /// module id order. Filled only by a `supervisor.rescan_checked` preview;
2350    /// a module whose launch spec, health policy and enabled flag all stay as
2351    /// staged has no entry, and neither has a disabled module that is added
2352    /// or removed. Empty is skipped, so `supervisor.rescan` replies keep their
2353    /// shape.
2354    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2355    pub module_actions: Vec<RescanModuleAction>,
2356    /// Modules whose running process still uses launch inputs from an earlier
2357    /// rescan: their staged spec waits for a restart that this candidate
2358    /// does not cause. Filled only by a `supervisor.rescan_checked` preview.
2359    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2360    pub earlier_pending: Vec<String>,
2361    /// The value an apply of this preview must send. Present only on a
2362    /// `supervisor.rescan_checked` preview.
2363    #[serde(default, skip_serializing_if = "Option::is_none")]
2364    pub expect: Option<RescanExpect>,
2365}
2366
2367/// Which wire protocol a supervised module speaks to subc, as DECLARED in
2368/// daemon config. Never inferred from observed behaviour.
2369///
2370/// The distinction this exists to keep is between a module that should have
2371/// registered and has not yet, and one that never will. A `Subc` module that has
2372/// not registered is a subc module that is LATE -- it may be booting, it may be
2373/// wedged, and the supervisor's health probing and restart escalation are the
2374/// right response. A `None` module is a third-party process (the NATS server is
2375/// the first) that subc launches, supervises, and stops, and that is all: it
2376/// speaks no subc wire at all, so treating its silence as a fault would restart
2377/// a perfectly healthy process forever.
2378///
2379/// Inferring the difference from "has not registered within N seconds" would
2380/// collapse exactly the two cases that must stay apart, which is why this is a
2381/// declaration.
2382#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2383#[serde(rename_all = "snake_case")]
2384pub enum ModuleProtocol {
2385    /// The module registers over channel 0, answers `health.check`, and can
2386    /// serve routes. Every module predating this field is one of these, which is
2387    /// why it is the default.
2388    #[default]
2389    Subc,
2390    /// The module speaks no subc wire. It is supervised as a process only.
2391    ///
2392    /// A clean exit (status 0) that the daemon did not request is restarted as
2393    /// a crash, counting against the restart budget, instead of being recorded
2394    /// as a stop. Such a module is usually a stock program that exits 0 on
2395    /// SIGTERM, so a stray outside signal would otherwise leave it down for
2396    /// good; a subc-wire module re-raises SIGTERM instead, so this rule is not
2397    /// needed for it.
2398    None,
2399}
2400
2401/// A supervised module's current state and process observations.
2402///
2403/// Use [`SupervisorEntry::new`] and its `with_*` methods to construct entries so
2404/// future fields do not require changes to callers.
2405/// Struct literals and functional record updates are not supported outside this crate:
2406///
2407/// ```compile_fail,E0639
2408/// use subc_control::{SupervisorEntry, SupervisorHealthStatus};
2409/// let entry = SupervisorEntry::new("provider", "running", true, true, SupervisorHealthStatus::Unknown);
2410/// let entry = SupervisorEntry { resources: None, ..entry };
2411/// ```
2412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2413#[non_exhaustive]
2414pub struct SupervisorEntry {
2415    /// A hidden previous instance blocks only this module's next spawn. This
2416    /// PID is not the supervised child and must not be presented as its identity.
2417    #[serde(default, skip_serializing_if = "Option::is_none")]
2418    pub waiting_for_previous_pid: Option<u32>,
2419    pub module_id: String,
2420    pub state: String,
2421    /// Estimated Unix milliseconds of the next retry after restart-budget
2422    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
2423    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
2424    #[serde(default, skip_serializing_if = "Option::is_none")]
2425    pub next_retry_at_ms: Option<u64>,
2426    pub enabled: bool,
2427    /// The enabled value in the daemon's loaded configuration, not a stored
2428    /// drift flag. Absent when there is no configured entry or on older daemons.
2429    #[serde(default, skip_serializing_if = "Option::is_none")]
2430    pub configured_enabled: Option<bool>,
2431    /// Whether this module is serving.
2432    ///
2433    /// For a `Subc` module: enabled, running, process alive, AND registered.
2434    /// For a `None` module the registration term is dropped, because a module
2435    /// that speaks no subc wire never registers and the daemon cannot assert
2436    /// more than "the process it launched is alive". READ IT WITH `protocol`:
2437    /// `live: true` means something weaker for a `None` module, and a renderer
2438    /// that prints it as a bare boolean for one is claiming more than the daemon
2439    /// knows.
2440    pub live: bool,
2441    /// The module's declared wire protocol. Absent on daemons predating the
2442    /// field, where every module was a subc module, so the default is exactly
2443    /// what those daemons meant.
2444    #[serde(default)]
2445    pub protocol: ModuleProtocol,
2446    /// Retained for one release for older status consumers: false on Unix, true
2447    /// on Windows. Non-wire modules receive no nonce on either platform.
2448    #[serde(default, skip_serializing_if = "Option::is_none")]
2449    pub launch_nonce_env: Option<bool>,
2450    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
2451    /// process read all bytes, otherwise `env` for the offered environment copy.
2452    /// Returned in `supervisor.list`, independently of the source the module
2453    /// declares in `manifest.provenance.launch_nonce_source` when registering.
2454    /// Processes that do not speak the wire protocol and stopped modules omit it.
2455    #[serde(default, skip_serializing_if = "Option::is_none")]
2456    pub launch_nonce_source: Option<String>,
2457    pub health: SupervisorHealthStatus,
2458    /// Computed from the stored launch spec and observed process at list time;
2459    /// None means an older daemon did not report this comparison.
2460    #[serde(default, skip_serializing_if = "Option::is_none")]
2461    pub pending_reload: Option<PendingReloadVerdict>,
2462    /// When the daemon last collected this module's health, as unix
2463    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
2464    /// window, whose `health` is therefore `Unknown` rather than good), not
2465    /// probed-long-ago. An old value and an absent one call for opposite
2466    /// readings, so do not render them alike.
2467    #[serde(default)]
2468    pub last_probe_ms: Option<u64>,
2469    /// Exit code of the module's most recent process exit, if the process has
2470    /// exited at least once. Survives respawn so a now-`running` module still
2471    /// reports what killed its previous incarnation.
2472    #[serde(default, skip_serializing_if = "Option::is_none")]
2473    pub last_exit_code: Option<i32>,
2474    /// Terminating signal of the module's most recent process exit (Unix), if
2475    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
2476    /// (often a panic-abort). Survives respawn.
2477    #[serde(default, skip_serializing_if = "Option::is_none")]
2478    pub last_exit_signal: Option<i32>,
2479    /// Unix milliseconds when the most recent child exit was observed. Present
2480    /// even when the terminal ring is not queried, so existing list readers can
2481    /// order their latest observed exit against events they already received.
2482    #[serde(default, skip_serializing_if = "Option::is_none")]
2483    pub last_exit_ms: Option<u64>,
2484    /// Classification of the most recent child exit. Absent on daemons that
2485    /// predate exit-kind reporting.
2486    #[serde(default, skip_serializing_if = "Option::is_none")]
2487    pub last_exit_kind: Option<TerminalExitKind>,
2488    /// Replacement processes spawned for this module so far, against the budget
2489    /// that disables it.
2490    ///
2491    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
2492    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
2493    /// successful probe, so a module can miss probes all day and read zero; this
2494    /// one only decreases when an operator restarts, reloads, or re-enables the
2495    /// module. Reaching the budget moves it to `Failed` and it stays there until
2496    /// somebody intervenes.
2497    ///
2498    /// So a module one restart from being disabled is indistinguishable from a
2499    /// freshly booted one unless this pair is read. Both are reported together
2500    /// because the count alone does not say how close it is.
2501    ///
2502    /// Absent from daemons predating the field, which is why it is optional
2503    /// rather than defaulted to zero: zero would assert a full budget.
2504    #[serde(default, skip_serializing_if = "Option::is_none")]
2505    pub restart_count: Option<u32>,
2506    /// Replacement processes this module is allowed before it is disabled. See
2507    /// `restart_count`; absent on daemons predating the field.
2508    #[serde(default, skip_serializing_if = "Option::is_none")]
2509    pub max_restarts: Option<u32>,
2510    /// Replacement processes spawned over this module's entire supervisor lifetime.
2511    /// Unlike `restart_count`, this value is never reset by an operator action.
2512    #[serde(default, skip_serializing_if = "Option::is_none")]
2513    pub lifetime_restarts: Option<u32>,
2514    /// Successful child spawns in this daemon incarnation. Zero means the
2515    /// module has not successfully spawned; every successful spawn increments
2516    /// the value exactly once.
2517    #[serde(default, skip_serializing_if = "Option::is_none")]
2518    pub spawn_generation: Option<u64>,
2519    /// The span `restart_count` is counted over, in seconds. The crash budget is
2520    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
2521    /// inside the last `restart_window_secs`, and older ones no longer hold a
2522    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
2523    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
2524    /// reactions.
2525    ///
2526    /// Absent on daemons predating the windowed budget, where the count really
2527    /// was a lifetime total.
2528    #[serde(default, skip_serializing_if = "Option::is_none")]
2529    pub restart_window_secs: Option<u64>,
2530    /// Effective drain budget for this module, in milliseconds. This is the
2531    /// resolved policy the running supervisor uses, not a config-file reread.
2532    /// Absent on older daemons.
2533    #[serde(default, skip_serializing_if = "Option::is_none")]
2534    pub drain_timeout_ms: Option<u64>,
2535    /// Effective base delay before a crash restart, in milliseconds. Absent on
2536    /// older daemons.
2537    #[serde(default, skip_serializing_if = "Option::is_none")]
2538    pub restart_backoff_ms: Option<u64>,
2539    /// Effective maximum delay before a crash restart, in milliseconds. Absent
2540    /// on older daemons.
2541    #[serde(default, skip_serializing_if = "Option::is_none")]
2542    pub restart_max_backoff_ms: Option<u64>,
2543    /// Memory and cumulative CPU time of the module's process, read when this
2544    /// list was answered. Report only: the daemon keeps no history and acts on
2545    /// none of it.
2546    ///
2547    /// It describes the one process the supervisor spawned (its `pid`), not
2548    /// processes that one has started in turn, so a module that forks workers
2549    /// reports only its own share.
2550    ///
2551    /// Absent means the daemon predates the field. A daemon that has the field
2552    /// but could not read the process (not running, unsupported platform, read
2553    /// failed) says so with `Unavailable` and a reason, so neither case can be
2554    /// mistaken for a process using nothing.
2555    #[serde(default, skip_serializing_if = "Option::is_none")]
2556    pub resources: Option<ChildResourceUsage>,
2557    /// Cumulative CPU and current memory including child processes, when known.
2558    #[serde(default, skip_serializing_if = "Option::is_none")]
2559    pub tree: Option<TreeReading>,
2560    /// Why this reporting daemon has no tree reading for this response.
2561    /// `not_yet_measured` means no measurement is available; other snake_case
2562    /// reasons may be added. Absence alone does not establish tree support.
2563    #[serde(default, skip_serializing_if = "Option::is_none")]
2564    pub tree_unavailable: Option<String>,
2565    /// CPU used across the wall-clock interval covered by retained samples.
2566    #[serde(default, skip_serializing_if = "Option::is_none")]
2567    pub cpu_last_hour: Option<CpuLastHour>,
2568}
2569
2570impl SupervisorEntry {
2571    /// Set the estimated time of a failed module's next automatic retry.
2572    #[must_use]
2573    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2574        self.next_retry_at_ms = next_retry_at_ms;
2575        self
2576    }
2577
2578    /// Construct an entry with its required fields and wire-compatible defaults.
2579    #[must_use]
2580    pub fn new(
2581        module_id: impl Into<String>,
2582        state: impl Into<String>,
2583        enabled: bool,
2584        live: bool,
2585        health: SupervisorHealthStatus,
2586    ) -> Self {
2587        Self {
2588            module_id: module_id.into(),
2589            state: state.into(),
2590            next_retry_at_ms: None,
2591            waiting_for_previous_pid: None,
2592            enabled,
2593            configured_enabled: None,
2594            live,
2595            protocol: ModuleProtocol::default(),
2596            launch_nonce_env: None,
2597            launch_nonce_source: None,
2598            health,
2599            pending_reload: None,
2600            last_probe_ms: None,
2601            last_exit_code: None,
2602            last_exit_signal: None,
2603            last_exit_ms: None,
2604            last_exit_kind: None,
2605            restart_count: None,
2606            max_restarts: None,
2607            lifetime_restarts: None,
2608            spawn_generation: None,
2609            restart_window_secs: None,
2610            drain_timeout_ms: None,
2611            restart_backoff_ms: None,
2612            restart_max_backoff_ms: None,
2613            resources: None,
2614            tree: None,
2615            tree_unavailable: None,
2616            cpu_last_hour: None,
2617        }
2618    }
2619
2620    /// Set the module's declared wire protocol.
2621    #[must_use]
2622    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2623        self.protocol = protocol;
2624        self
2625    }
2626
2627    /// Attach the enabled value from the daemon's loaded configuration.
2628    #[must_use]
2629    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2630        self.configured_enabled = configured_enabled;
2631        self
2632    }
2633
2634    /// Set or clear the launch nonce environment indicator.
2635    #[must_use]
2636    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2637        self.launch_nonce_env = launch_nonce_env;
2638        self
2639    }
2640
2641    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2642        self.launch_nonce_source = source;
2643        self
2644    }
2645
2646    #[must_use]
2647    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2648        self.waiting_for_previous_pid = pid;
2649        self
2650    }
2651
2652    /// Set or clear the comparison between the launch spec and observed process.
2653    #[must_use]
2654    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2655        self.pending_reload = pending_reload;
2656        self
2657    }
2658
2659    /// Set or clear the last health collection timestamp.
2660    #[must_use]
2661    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2662        self.last_probe_ms = last_probe_ms;
2663        self
2664    }
2665
2666    /// Set or clear the most recent process exit code.
2667    #[must_use]
2668    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2669        self.last_exit_code = last_exit_code;
2670        self
2671    }
2672
2673    /// Set or clear the most recent process exit signal.
2674    #[must_use]
2675    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2676        self.last_exit_signal = last_exit_signal;
2677        self
2678    }
2679
2680    /// Set or clear the most recent process exit timestamp.
2681    #[must_use]
2682    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2683        self.last_exit_ms = last_exit_ms;
2684        self
2685    }
2686
2687    /// Set or clear the most recent process exit classification.
2688    #[must_use]
2689    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2690        self.last_exit_kind = last_exit_kind;
2691        self
2692    }
2693
2694    /// Set or clear the restart count for the current crash budget.
2695    #[must_use]
2696    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2697        self.restart_count = restart_count;
2698        self
2699    }
2700
2701    /// Set or clear the maximum restarts allowed by the crash budget.
2702    #[must_use]
2703    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2704        self.max_restarts = max_restarts;
2705        self
2706    }
2707
2708    /// Set or clear the lifetime restart count.
2709    #[must_use]
2710    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2711        self.lifetime_restarts = lifetime_restarts;
2712        self
2713    }
2714
2715    /// Set or clear the successful spawn count for this daemon incarnation.
2716    #[must_use]
2717    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2718        self.spawn_generation = spawn_generation;
2719        self
2720    }
2721
2722    /// Set or clear the time window of the crash budget.
2723    #[must_use]
2724    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2725        self.restart_window_secs = restart_window_secs;
2726        self
2727    }
2728
2729    /// Set or clear the effective drain budget in milliseconds.
2730    #[must_use]
2731    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2732        self.drain_timeout_ms = drain_timeout_ms;
2733        self
2734    }
2735
2736    /// Set or clear the effective base restart delay in milliseconds.
2737    #[must_use]
2738    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2739        self.restart_backoff_ms = restart_backoff_ms;
2740        self
2741    }
2742
2743    /// Set or clear the effective maximum restart delay in milliseconds.
2744    #[must_use]
2745    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2746        self.restart_max_backoff_ms = restart_max_backoff_ms;
2747        self
2748    }
2749
2750    /// Set or clear the observed resource usage of the supervised process.
2751    #[must_use]
2752    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2753        self.resources = resources;
2754        self
2755    }
2756
2757    /// Attach a report-only reading covering the module's process container.
2758    #[must_use]
2759    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2760        self.tree = tree;
2761        self
2762    }
2763
2764    /// Explain an absent tree reading without manufacturing numeric counters.
2765    #[must_use]
2766    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2767        self.tree_unavailable = reason;
2768        self
2769    }
2770}
2771
2772/// A module process's memory and CPU time as read at list time, or why none
2773/// could be read.
2774#[derive(Debug, Clone, PartialEq)]
2775pub enum ChildResourceUsage {
2776    Measured(ChildResourceReading),
2777    Unavailable {
2778        reason: ChildResourceUnavailableReason,
2779    },
2780    /// Future discriminator. `body` retains the complete ordered object; `tag`
2781    /// is its decoded discriminator projection.
2782    Unknown {
2783        tag: String,
2784        body: OrderedJsonObject,
2785    },
2786}
2787
2788/// One reading of a module process's memory and CPU time.
2789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2790pub struct ChildResourceReading {
2791    /// Memory in bytes, measured as `memory_kind` says. The figures differ
2792    /// by platform and are not comparable across kinds.
2793    pub memory_bytes: u64,
2794    pub memory_kind: ChildMemoryKind,
2795    /// Bytes swapped out, where the platform reports it per process (Linux).
2796    /// Absent means not reported, not zero.
2797    #[serde(default, skip_serializing_if = "Option::is_none")]
2798    pub swap_bytes: Option<u64>,
2799    /// CPU time spent in user mode since the process started, in
2800    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
2801    /// and the elapsed time between them.
2802    pub cpu_user_ms: u64,
2803    /// CPU time spent in the kernel on the process's behalf since it started,
2804    /// in milliseconds.
2805    pub cpu_system_ms: u64,
2806}
2807
2808open_string_enum! {
2809    /// What `ChildResourceReading::memory_bytes` measures.
2810    ChildMemoryKind {
2811        /// macOS `phys_footprint`: memory the kernel charges to the process,
2812        /// the figure jetsam acts on. Unlike resident size it does not count
2813        /// pages an allocator has already released with `MADV_FREE`.
2814        PhysFootprint => "phys_footprint",
2815        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
2816        /// included and swapped-out pages excluded.
2817        ResidentSet => "resident_set",
2818        /// Windows `WorkingSetSize`: resident pageable memory, including shared
2819        /// pages, not Unix RSS or private committed bytes.
2820        WindowsWorkingSet => "windows_working_set",
2821    }
2822}
2823
2824open_string_enum! {
2825    /// Why a module process's resources could not be read.
2826    ChildResourceUnavailableReason {
2827        /// The module has no running process.
2828        NotRunning => "not_running",
2829        /// The daemon's platform has no per-process source.
2830        UnsupportedPlatform => "unsupported_platform",
2831        /// The process could not be read, typically because it exited while
2832        /// the list was being answered.
2833        Unreadable => "unreadable",
2834        /// The pid no longer names the process the supervisor spawned, so a
2835        /// reading would describe some other process.
2836        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2837    }
2838}
2839
2840#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2841#[serde(rename_all = "snake_case")]
2842pub enum SupervisorHealthStatus {
2843    Ok,
2844    Degraded,
2845    Failing,
2846    Unresponsive,
2847    Unknown,
2848}
2849
2850#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2851pub struct SupervisorHealthEntry {
2852    pub module_id: String,
2853    pub status: SupervisorHealthStatus,
2854    /// The module's own human-readable note on its state. Absent means the
2855    /// module said nothing, which is the ordinary shape for a healthy module and
2856    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
2857    /// module may reword freely, and `status` plus `metrics` are the machine
2858    /// surface.
2859    #[serde(default, skip_serializing_if = "Option::is_none")]
2860    pub detail: Option<String>,
2861    /// The module's own metrics object, relayed opaquely. Absent means the module
2862    /// published none on this probe — either it reports no metrics at all, or the
2863    /// probe did not reach it — so absence cannot distinguish "nothing to report"
2864    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
2865    #[serde(default, skip_serializing_if = "Option::is_none")]
2866    pub metrics: Option<serde_json::Value>,
2867    pub consecutive_failures: u32,
2868    /// Number of recurring health replies received after their daemon deadline.
2869    /// Each increment is evidence that the module remained alive despite a miss.
2870    #[serde(default)]
2871    pub late_answer_count: u64,
2872    /// End-to-end latency of the newest late reply, measured from probe start.
2873    #[serde(default, skip_serializing_if = "Option::is_none")]
2874    pub last_late_answer_latency_ms: Option<u64>,
2875    /// The escalation the supervisor last took for this module (report, restart,
2876    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
2877    /// succeeded — a module that has never misbehaved and one whose action record
2878    /// predates a daemon restart both present as absent.
2879    #[serde(default)]
2880    pub last_action: Option<String>,
2881    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
2882    /// `last_action` is absent; the pair moves together.
2883    #[serde(default)]
2884    pub last_action_ms: Option<u64>,
2885    /// When the daemon last collected this entry, as unix milliseconds.
2886    ///
2887    /// `supervisor.health` answers from the supervisor's STORED record rather
2888    /// than probing, so every field above describes some moment in the past and
2889    /// nothing here said which. That matters most right after a restart, where
2890    /// the surface is used to confirm a deploy: a record collected before the
2891    /// restart reports the OLD process, reads as a failed deploy, and invites a
2892    /// redeploy of something that was already correct.
2893    ///
2894    /// `None` means never probed — distinct from probed-long-ago, and the reader
2895    /// must not collapse them. Absent on modules that advertise no health
2896    /// capability, which is why it is optional rather than defaulted to zero.
2897    #[serde(default, skip_serializing_if = "Option::is_none")]
2898    pub last_probe_ms: Option<u64>,
2899}
2900
2901#[cfg(test)]
2902mod tests {
2903    #[test]
2904    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2905        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2906        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2907        assert_eq!(decoded.configured_enabled, None);
2908        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2909    }
2910
2911    #[test]
2912    fn configured_enabled_values_round_trip_in_list() {
2913        for enabled in [false, true] {
2914            let entry = SupervisorEntry::new(
2915                "provider",
2916                "running",
2917                true,
2918                true,
2919                SupervisorHealthStatus::Unknown,
2920            )
2921            .with_configured_enabled(Some(enabled));
2922            let entry_json = serde_json::to_value(&entry).unwrap();
2923            assert_eq!(entry_json["configured_enabled"], enabled);
2924            assert_eq!(
2925                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2926                entry
2927            );
2928        }
2929    }
2930
2931    #[test]
2932    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2933        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2934            volume_serial_number: u64::MAX,
2935            file_id: [
2936                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2937            ],
2938        };
2939        let agreement = super::RunningImageAgreement::Match { evidence };
2940        let encoded = serde_json::to_string(&agreement).unwrap();
2941        assert!(encoded.contains("windows_spawn_file_id"));
2942        assert_eq!(
2943            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2944            agreement
2945        );
2946    }
2947
2948    #[test]
2949    fn unix_running_image_evidence_keeps_original_wire_bytes() {
2950        assert_eq!(
2951            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2952                device: 7,
2953                inode: 11
2954            })
2955            .unwrap(),
2956            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2957        );
2958        assert_eq!(
2959            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2960                digest: "abc".to_owned()
2961            })
2962            .unwrap(),
2963            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2964        );
2965    }
2966    use super::*;
2967    use subc_protocol::{BindIdentity, RouteTarget};
2968
2969    #[test]
2970    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2971        let entry = TerminalEntry {
2972            daemon_incarnation: Some("daemon-before-restart".into()),
2973            exit_code: Some(1),
2974            exit_signal: None,
2975            at_ms: 1_700_000_000_123,
2976            disposition: TerminalDisposition::Restarting,
2977            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2978            disposition_detail: None,
2979        };
2980        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2981        assert_eq!(
2982            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2983                ["exit_kind"],
2984            "deliberate_severance"
2985        );
2986
2987        #[derive(serde::Deserialize)]
2988        struct LegacyTerminalEntry {
2989            exit_code: Option<i32>,
2990            exit_signal: Option<i32>,
2991            at_ms: u64,
2992            disposition: TerminalDisposition,
2993        }
2994
2995        let decoded: LegacyTerminalEntry =
2996            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2997        assert_eq!(decoded.exit_code, Some(1));
2998        assert_eq!(decoded.exit_signal, None);
2999        assert_eq!(decoded.at_ms, 1_700_000_000_123);
3000        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3001
3002        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3003        let future: TerminalEntry =
3004            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3005        assert_eq!(
3006            future.exit_kind,
3007            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3008        );
3009    }
3010
3011    #[test]
3012    fn terminal_incarnation_is_optional_for_older_daemons() {
3013        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3014            "at_ms": 123,
3015            "disposition": "stopped"
3016        }))
3017        .unwrap();
3018        let encoded = serde_json::to_value(&entry).unwrap();
3019        assert_eq!(
3020            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3021            (None, None)
3022        );
3023    }
3024
3025    #[test]
3026    fn route_poll_uses_kind_field() {
3027        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3028            route_channel: 7,
3029            route_epoch: 11,
3030            kind: PollKind::Status,
3031        })
3032        .unwrap();
3033
3034        assert_eq!(body["op"], "route.poll");
3035        assert_eq!(body["route_epoch"], 11);
3036        assert_eq!(body["kind"], "status");
3037        assert!(body.get("op").is_some());
3038    }
3039
3040    #[test]
3041    fn route_open_is_internally_tagged() {
3042        let request = ClientControlRequest::RouteOpen {
3043            busy_refusals: None,
3044            target: RouteTarget::ToolProvider {
3045                module_id: "aft".to_string(),
3046            },
3047            identity: BindIdentity::new("opencode", "session-1"),
3048            consumer_identity: None,
3049            consumer_capabilities: None,
3050            role_versions: None,
3051            admission_facts: None,
3052            scope: None,
3053        };
3054
3055        let body = serde_json::to_value(request).unwrap();
3056        assert_eq!(body["op"], "route.open");
3057        assert_eq!(body["target"]["kind"], "tool_provider");
3058        assert!(body.get("consumer_identity").is_none());
3059        assert!(body.get("consumer_capabilities").is_none());
3060        assert!(body.get("role_versions").is_none());
3061    }
3062
3063    #[test]
3064    fn route_open_without_optional_fields_still_decodes() {
3065        let body = serde_json::json!({
3066            "op": "route.open",
3067            "target": { "kind": "tool_provider", "module_id": "aft" },
3068            "identity": {
3069                "project_root": "/tmp/project",
3070                "harness": "opencode",
3071                "session": "session-1"
3072            }
3073        });
3074
3075        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3076        let ClientControlRequest::RouteOpen {
3077            consumer_identity,
3078            consumer_capabilities,
3079            role_versions,
3080            admission_facts,
3081            ..
3082        } = decoded
3083        else {
3084            panic!("decoded wrong request variant");
3085        };
3086        assert_eq!(consumer_identity, None);
3087        assert_eq!(consumer_capabilities, None);
3088        assert_eq!(role_versions, None);
3089        assert_eq!(admission_facts, None);
3090    }
3091
3092    #[test]
3093    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3094        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3095        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3096        match decoded {
3097            ClientControlPush::RouteClosed {
3098                excluded_subscriptions,
3099                terminal,
3100                ..
3101            } => {
3102                assert_eq!(excluded_subscriptions, 0);
3103                assert_eq!(terminal, None);
3104            }
3105            other => panic!("unexpected push: {other:?}"),
3106        }
3107        assert!(!serde_json::to_string(&decoded)
3108            .unwrap()
3109            .contains("terminal"));
3110    }
3111
3112    #[test]
3113    fn old_route_closed_decoder_ignores_new_terminal_field() {
3114        #[derive(serde::Deserialize)]
3115        #[serde(tag = "op")]
3116        enum LegacyClientControlPush {
3117            #[serde(rename = "route.closed")]
3118            RouteClosed {
3119                module_id: String,
3120                reason: RouteCloseReason,
3121                drained: bool,
3122                abandoned: u32,
3123            },
3124        }
3125
3126        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3127        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3128        match decoded {
3129            LegacyClientControlPush::RouteClosed {
3130                module_id,
3131                reason,
3132                drained,
3133                abandoned,
3134            } => {
3135                assert_eq!(module_id, "aft-tools");
3136                assert_eq!(reason, RouteCloseReason::Crash);
3137                assert!(!drained);
3138                assert_eq!(abandoned, 0);
3139            }
3140        }
3141    }
3142
3143    #[test]
3144    fn supervisor_routes_is_a_control_plane_request() {
3145        let body = serde_json::json!({
3146            "op": "supervisor.routes",
3147            "module_id": "aft"
3148        });
3149
3150        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3151        assert_eq!(serde_json::to_value(request).unwrap(), body);
3152    }
3153
3154    #[test]
3155    fn diagnostic_string_enums_retain_unknown_wire_values() {
3156        let reason: RunningImageUnavailableReason =
3157            serde_json::from_str("\"future_reason\"").unwrap();
3158        let disposition: TerminalDisposition =
3159            serde_json::from_str("\"future_disposition\"").unwrap();
3160
3161        assert_eq!(
3162            reason,
3163            RunningImageUnavailableReason::Unknown("future_reason".to_string())
3164        );
3165        assert_eq!(
3166            disposition,
3167            TerminalDisposition::Unknown("future_disposition".to_string())
3168        );
3169    }
3170
3171    #[test]
3172    fn diagnostic_string_enums_preserve_existing_wire_names() {
3173        let names = [
3174            (RunningImageUnavailableReason::NotRunning, "not_running"),
3175            (
3176                RunningImageUnavailableReason::UnsupportedPlatform,
3177                "unsupported_platform",
3178            ),
3179            (
3180                RunningImageUnavailableReason::RunningExecutableUnreadable,
3181                "running_executable_unreadable",
3182            ),
3183            (
3184                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3185                "running_executable_permission_denied",
3186            ),
3187            (
3188                RunningImageUnavailableReason::ProcessHidden,
3189                "process_hidden",
3190            ),
3191            (
3192                RunningImageUnavailableReason::SpawnedPathUnreadable,
3193                "spawned_path_unreadable",
3194            ),
3195            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3196            (
3197                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3198                "process_identity_unconfirmed",
3199            ),
3200        ];
3201        for (value, expected) in names {
3202            let wire = serde_json::to_string(&value).unwrap();
3203            assert_eq!(wire, format!("\"{expected}\""));
3204            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3205            assert_eq!(decoded, value);
3206        }
3207
3208        for (value, expected) in [
3209            (TerminalDisposition::Stopped, "stopped"),
3210            (TerminalDisposition::Disabled, "disabled"),
3211            (TerminalDisposition::Failed, "failed"),
3212            (TerminalDisposition::Restarting, "restarting"),
3213            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3214        ] {
3215            let wire = serde_json::to_string(&value).unwrap();
3216            assert_eq!(wire, format!("\"{expected}\""));
3217            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3218            assert_eq!(decoded, value);
3219        }
3220    }
3221
3222    #[test]
3223    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3224        let entry = SupervisorEntry::new(
3225            "waiting-module",
3226            "starting",
3227            true,
3228            false,
3229            SupervisorHealthStatus::Unknown,
3230        );
3231        let old_wire = serde_json::to_value(&entry).unwrap();
3232        assert!(old_wire.get("waiting_for_previous_pid").is_none());
3233        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3234        assert_eq!(decoded.waiting_for_previous_pid, None);
3235        let entry = entry.with_waiting_for_previous_pid(Some(42));
3236        let wire = serde_json::to_value(&entry).unwrap();
3237        assert_eq!(wire["waiting_for_previous_pid"], 42);
3238        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3239        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3240    }
3241
3242    #[test]
3243    fn diagnostic_string_enums_reject_non_string_bodies() {
3244        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3245        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3246    }
3247
3248    #[test]
3249    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3250        let body = serde_json::json!({
3251            "op": "supervisor.provenance",
3252            "daemon": {
3253                "daemon_build": {},
3254                "daemon_observed": {
3255                    "running_image": {
3256                        "status": "unavailable",
3257                        "reason": "not_running"
3258                    }
3259                }
3260            },
3261            "modules": [
3262                {
3263                    "module_id": "future",
3264                    "module_declared": { "status": "unverifiable" },
3265                    "daemon_observed": {
3266                        "running_image": {
3267                            "status": "unavailable",
3268                            "reason": "future_reason"
3269                        }
3270                    }
3271                },
3272                {
3273                    "module_id": "healthy-a",
3274                    "module_declared": { "status": "unverifiable" },
3275                    "daemon_observed": {
3276                        "running_image": {
3277                            "status": "match",
3278                            "evidence": {
3279                                "method": "linux_proc_sha256",
3280                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3281                            }
3282                        }
3283                    }
3284                },
3285                {
3286                    "module_id": "healthy-b",
3287                    "module_declared": { "status": "unverifiable" },
3288                    "daemon_observed": {
3289                        "running_image": {
3290                            "status": "unavailable",
3291                            "reason": "unsupported_platform"
3292                        }
3293                    }
3294                }
3295            ]
3296        });
3297
3298        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3299        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3300            panic!("decoded wrong response variant");
3301        };
3302        assert_eq!(modules.len(), 3);
3303        assert_eq!(modules[0].module_id, "future");
3304        assert_eq!(
3305            modules[0].daemon_observed.running_image,
3306            RunningImageAgreement::Unavailable {
3307                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3308            }
3309        );
3310        assert_eq!(modules[1].module_id, "healthy-a");
3311        assert_eq!(modules[2].module_id, "healthy-b");
3312    }
3313
3314    #[test]
3315    fn tagged_unknown_values_retain_tag_and_body() {
3316        macro_rules! assert_unknown_round_trip {
3317            ($ty:ident, $field:literal, $value:expr) => {
3318                let value = $value;
3319                let wire = serde_json::to_string(&value).unwrap();
3320                let decoded: $ty = serde_json::from_str(&wire).unwrap();
3321                match decoded {
3322                    $ty::Unknown { tag, body } => {
3323                        assert_eq!(tag, value[$field].as_str().unwrap());
3324                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
3325                    }
3326                    _ => panic!("decoded known variant"),
3327                }
3328            };
3329        }
3330
3331        assert_unknown_round_trip!(
3332            ModuleDeclaredProvenance,
3333            "status",
3334            serde_json::json!({"status": "future", "build": {"version": 7}})
3335        );
3336        assert_unknown_round_trip!(
3337            RunningImageAgreement,
3338            "status",
3339            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3340        );
3341        assert_unknown_round_trip!(
3342            RunningImageEvidence,
3343            "method",
3344            serde_json::json!({"method": "future", "digest": "abc"})
3345        );
3346        assert_unknown_round_trip!(
3347            SupervisorRouteConsumer,
3348            "kind",
3349            serde_json::json!({"kind": "future", "module_id": "m"})
3350        );
3351        assert_unknown_round_trip!(
3352            StderrCaptureState,
3353            "state",
3354            serde_json::json!({"state": "future", "reason": "because"})
3355        );
3356        assert_unknown_round_trip!(
3357            StderrTailEntry,
3358            "kind",
3359            serde_json::json!({"kind": "future", "text": "line"})
3360        );
3361        assert_unknown_round_trip!(
3362            ChildResourceUsage,
3363            "status",
3364            serde_json::json!({"status": "future", "memory_bytes": 1})
3365        );
3366    }
3367
3368    #[test]
3369    fn child_resource_usage_round_trips_both_known_states() {
3370        let measured = ChildResourceUsage::Measured(ChildResourceReading {
3371            memory_bytes: 0,
3372            memory_kind: ChildMemoryKind::ResidentSet,
3373            swap_bytes: Some(0),
3374            cpu_user_ms: 0,
3375            cpu_system_ms: 0,
3376        });
3377        let wire = serde_json::to_value(&measured).unwrap();
3378        assert_eq!(
3379            wire,
3380            serde_json::json!({
3381                "status": "measured",
3382                "memory_bytes": 0,
3383                "memory_kind": "resident_set",
3384                "swap_bytes": 0,
3385                "cpu_user_ms": 0,
3386                "cpu_system_ms": 0
3387            })
3388        );
3389        assert_eq!(
3390            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3391            measured
3392        );
3393
3394        let unavailable = ChildResourceUsage::Unavailable {
3395            reason: ChildResourceUnavailableReason::NotRunning,
3396        };
3397        let wire = serde_json::to_value(&unavailable).unwrap();
3398        assert_eq!(
3399            wire,
3400            serde_json::json!({"status": "unavailable", "reason": "not_running"})
3401        );
3402        assert_eq!(
3403            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3404            unavailable
3405        );
3406    }
3407
3408    #[test]
3409    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3410        // A current daemon stamps each line; an older one sends no `at_ms`.
3411        // Both must decode, and the absent case must stay absent rather than
3412        // turn into a time nobody recorded.
3413        let stamped: StderrTailEntry = serde_json::from_str(
3414            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3415        )
3416        .unwrap();
3417        assert_eq!(
3418            stamped,
3419            StderrTailEntry::Line {
3420                text: "boom".to_string(),
3421                truncated: true,
3422                at_ms: Some(1_789_801_440_685),
3423            }
3424        );
3425        let unstamped: StderrTailEntry =
3426            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3427        assert_eq!(
3428            unstamped,
3429            StderrTailEntry::Line {
3430                text: "boom".to_string(),
3431                truncated: false,
3432                at_ms: None,
3433            }
3434        );
3435        // Absent stays absent on the way out, so a reply without stamps is
3436        // exactly what an older daemon would have sent.
3437        assert_eq!(
3438            serde_json::to_string(&unstamped).unwrap(),
3439            r#"{"kind":"line","text":"boom"}"#
3440        );
3441        assert_eq!(
3442            serde_json::to_value(&stamped).unwrap()["at_ms"],
3443            serde_json::json!(1_789_801_440_685u64)
3444        );
3445    }
3446
3447    #[test]
3448    fn tagged_unknown_values_round_trip_the_original_json() {
3449        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3450        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3451        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3452    }
3453
3454    #[test]
3455    fn tagged_unknown_values_round_trip_trailing_tag() {
3456        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3457        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3458        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3459
3460        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3461        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3462        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3463    }
3464
3465    #[test]
3466    fn tagged_unknown_values_round_trip_middle_tag() {
3467        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3468        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3469        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3470
3471        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3472        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3473        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3474    }
3475
3476    #[test]
3477    fn tagged_unknown_values_round_trip_deep_payload() {
3478        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3479        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3480        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3481
3482        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3483        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3484        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3485    }
3486
3487    #[test]
3488    fn tagged_unknown_values_reject_non_object_bodies() {
3489        for wire in ["42", r#""future""#, "[]"] {
3490            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3491            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3492        }
3493    }
3494
3495    #[test]
3496    fn duplicate_discriminators_reject_without_panicking() {
3497        assert_eq!(
3498            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3499                .unwrap(),
3500            ModuleDeclaredProvenance::Unverifiable
3501        );
3502        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3503            .unwrap()
3504        {
3505            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3506            _ => panic!("future discriminator decoded as a known variant"),
3507        }
3508
3509        let wires = [
3510            r#"{"status":"reported","status":"unverifiable"}"#,
3511            r#"{"status":"unverifiable","status":"reported"}"#,
3512            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3513            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3514        ];
3515
3516        for wire in wires {
3517            let result =
3518                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3519            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3520            assert!(
3521                result.unwrap().is_err(),
3522                "duplicate discriminator decoded: {wire}"
3523            );
3524        }
3525
3526        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3527        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3528        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3529        assert!(
3530            result.unwrap().is_err(),
3531            "duplicate discriminator decoded: {wire}"
3532        );
3533    }
3534
3535    #[test]
3536    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3537        let known_wire =
3538            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3539        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3540        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3541
3542        for wire in [
3543            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3544            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3545        ] {
3546            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3547            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3548        }
3549
3550        for wire in [
3551            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3552            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3553        ] {
3554            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3555            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3556        }
3557
3558        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3559        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3560        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3561
3562        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3563        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3564        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3565    }
3566
3567    #[test]
3568    fn tagged_unknown_member_does_not_discard_known_siblings() {
3569        let body = serde_json::json!({
3570            "modules": [{
3571                "module_id": "target",
3572                "routes": [
3573                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3574                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3575                ]
3576            }]
3577        });
3578        let decoded: ClientControlResponse = serde_json::from_value(
3579            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3580        )
3581        .unwrap();
3582        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3583            panic!("decoded wrong response variant");
3584        };
3585        assert_eq!(modules[0].routes.len(), 2);
3586        assert_eq!(
3587            modules[0].routes[1].consumer,
3588            SupervisorRouteConsumer::Direct { connection_id: 7 }
3589        );
3590    }
3591}
3592
3593#[cfg(test)]
3594mod launch_nonce_redaction_tests {
3595    use super::*;
3596
3597    const NONCE: &str = "nonce-f00dfeed1234abcd";
3598
3599    fn identity() -> ConsumerIdentity {
3600        ConsumerIdentity {
3601            module_id: "wernicke".to_string(),
3602            launch_nonce: NONCE.to_string(),
3603        }
3604    }
3605
3606    #[test]
3607    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3608        let printed = format!("{:?}", identity());
3609        assert!(printed.contains("wernicke"), "{printed}");
3610        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3611    }
3612
3613    #[test]
3614    fn route_open_request_debug_never_prints_the_nonce() {
3615        let request = ClientControlRequest::RouteOpen {
3616            busy_refusals: None,
3617            target: subc_protocol::RouteTarget::ToolProvider {
3618                module_id: "broca".to_string(),
3619            },
3620            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3621            consumer_identity: Some(identity()),
3622            consumer_capabilities: None,
3623            role_versions: None,
3624            admission_facts: None,
3625            scope: None,
3626        };
3627        let printed = format!("{request:?}");
3628        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3629    }
3630}