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///
748/// Use [`PendingReloadVerdict::new`] rather than an external struct literal:
749///
750/// ```compile_fail,E0639
751/// use subc_control::{PendingReloadVerdict, ReloadPathAgreement, RunningImageAgreement,
752///     RunningImageUnavailableReason};
753/// let verdict = PendingReloadVerdict {
754///     path: ReloadPathAgreement::Match,
755///     image: RunningImageAgreement::Unavailable {
756///         reason: RunningImageUnavailableReason::NotRunning,
757///     },
758///     spec: None,
759/// };
760/// ```
761#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
762#[non_exhaustive]
763pub struct PendingReloadVerdict {
764    pub path: ReloadPathAgreement,
765    pub image: RunningImageAgreement,
766    #[serde(default, skip_serializing_if = "Option::is_none")]
767    pub spec: Option<LaunchSpecAgreement>,
768}
769
770impl PendingReloadVerdict {
771    /// Create the path and image comparisons without a launch-spec verdict.
772    #[must_use]
773    pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
774        Self {
775            path,
776            image,
777            spec: None,
778        }
779    }
780
781    /// Set or clear the comparison of launch specifications.
782    #[must_use]
783    pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
784        self.spec = spec;
785        self
786    }
787}
788
789#[cfg(test)]
790mod launch_spec_wire_tests {
791    use super::*;
792
793    #[test]
794    fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
795        let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
796        let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
797        assert_eq!(parsed.spec, None);
798        assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
799        let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
800        let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
801        assert!(
802            matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
803        );
804        assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
805        let unavailable = LaunchSpecAgreement::Unavailable {
806            reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
807        };
808        let encoded = serde_json::to_string(&unavailable).unwrap();
809        assert_eq!(
810            encoded,
811            r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
812        );
813        assert_eq!(
814            serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
815            unavailable
816        );
817    }
818}
819
820/// Comparison of the configured launch inputs with the inputs recorded at spawn.
821/// No digest or configured env values are sent to clients.
822#[derive(Debug, Clone, PartialEq)]
823pub enum LaunchSpecAgreement {
824    Match,
825    Mismatch,
826    Unavailable {
827        reason: LaunchSpecUnavailableReason,
828    },
829    Unknown {
830        tag: String,
831        body: OrderedJsonObject,
832    },
833}
834
835open_string_enum! {
836    LaunchSpecUnavailableReason {
837        NotRunning => "not_running",
838        SpawnedSpecUnavailable => "spawned_spec_unavailable",
839    }
840}
841
842/// Whether the running process was spawned from the currently configured program.
843#[derive(Debug, Clone, PartialEq)]
844pub enum ReloadPathAgreement {
845    Match,
846    Mismatch {
847        configured: PathBuf,
848        spawned_from: PathBuf,
849    },
850    Unavailable {
851        reason: ReloadPathUnavailableReason,
852    },
853    Unknown {
854        tag: String,
855        body: OrderedJsonObject,
856    },
857}
858
859open_string_enum! {
860    /// Why configured and spawned paths cannot be compared.
861    ReloadPathUnavailableReason {
862        NotRunning => "not_running",
863        SpawnedPathUnavailable => "spawned_path_unavailable",
864    }
865}
866
867/// Daemon provenance paired with its runtime process observation.
868#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
869pub struct SupervisorDaemonProvenance {
870    pub daemon_build: DaemonBuildProvenance,
871    pub daemon_observed: DaemonObservedProcess,
872}
873
874/// Build metadata embedded in the daemon binary.
875#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
876pub struct DaemonBuildProvenance {
877    #[serde(default, skip_serializing_if = "Option::is_none")]
878    pub build_git_sha: Option<String>,
879    #[serde(default, skip_serializing_if = "Option::is_none")]
880    pub build_lock_digest: Option<String>,
881}
882
883/// Runtime process facts observed for the daemon itself.
884#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
885pub struct DaemonObservedProcess {
886    #[serde(default, skip_serializing_if = "Option::is_none")]
887    pub pid: Option<u32>,
888    /// Wall time derived from suspend-inclusive elapsed time at each read. Clock
889    /// correction can move it by the size of a clock step, and even without a
890    /// step it may vary by about a second between reads. Do not equality-compare
891    /// it. Use raw process start ticks for stable identity.
892    #[serde(default, skip_serializing_if = "Option::is_none")]
893    pub started_at_ms: Option<u64>,
894    pub running_image: RunningImageAgreement,
895}
896
897/// Whether the executable currently running agrees with the spawned image.
898#[derive(Debug, Clone, PartialEq)]
899pub enum RunningImageAgreement {
900    Match {
901        evidence: RunningImageEvidence,
902    },
903    Mismatch {
904        running: RunningImageEvidence,
905        disk: RunningImageEvidence,
906    },
907    Unavailable {
908        reason: RunningImageUnavailableReason,
909    },
910    /// Future discriminator. `body` retains the complete ordered object; `tag`
911    /// is its decoded discriminator projection.
912    Unknown {
913        tag: String,
914        body: OrderedJsonObject,
915    },
916}
917
918/// Platform-specific evidence used to compare a running image with its spawn path.
919#[derive(Debug, Clone, PartialEq)]
920pub enum RunningImageEvidence {
921    LinuxProcSha256 {
922        digest: String,
923    },
924    MacosSpawnInode {
925        device: u64,
926        inode: u64,
927    },
928    /// The spawn-time Windows file object, not verified executable content.
929    WindowsSpawnFileId {
930        volume_serial_number: u64,
931        file_id: [u8; 16],
932    },
933    /// Future discriminator. `body` retains the complete ordered object; `tag`
934    /// is its decoded discriminator projection.
935    Unknown {
936        tag: String,
937        body: OrderedJsonObject,
938    },
939}
940
941open_string_enum! {
942    /// Reasons why an executable identity could not be observed.
943    RunningImageUnavailableReason {
944        NotRunning => "not_running",
945        NotYetMeasured => "not_yet_measured",
946        UnsupportedPlatform => "unsupported_platform",
947        RunningExecutableUnreadable => "running_executable_unreadable",
948        RunningExecutablePermissionDenied => "running_executable_permission_denied",
949        ProcessHidden => "process_hidden",
950        SpawnedPathUnreadable => "spawned_path_unreadable",
951        HashFailed => "hash_failed",
952        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
953    }
954}
955
956/// The identity tier the daemon can honestly report for a route consumer.
957///
958/// A caller that proved a live daemon-issued launch nonce is named `reserved`.
959/// A direct key-holder has no such attestation, so it is reported as `direct`
960/// with its connection counter instead of an invented module name.
961#[derive(Debug, Clone, PartialEq)]
962pub enum SupervisorRouteConsumer {
963    Reserved {
964        module_id: String,
965    },
966    Direct {
967        connection_id: u64,
968    },
969    /// Future discriminator. `body` retains the complete ordered object; `tag`
970    /// is its decoded discriminator projection.
971    Unknown {
972        tag: String,
973        body: OrderedJsonObject,
974    },
975}
976
977/// Whether stderr is being captured for a module, and if not, why not.
978///
979/// A typed state rather than an empty-tail convention. "The module printed
980/// nothing before dying" and "nobody was capturing" send an operator in opposite
981/// directions, and rendering them alike is the defect this op exists to fix --
982/// the same shape as a `detail -` that means both no-detail and never-probed.
983#[derive(Debug, Clone, PartialEq)]
984pub enum StderrCaptureState {
985    /// A reader is attached, or was attached and saw clean EOF. An empty
986    /// `entries` under this state means the module genuinely wrote nothing.
987    Captured,
988    /// Retained entries are valid, but the stderr reader ended before clean EOF.
989    Incomplete { reason: String },
990    /// No reader was attached. `entries` says nothing about what the module wrote.
991    NotCaptured { reason: String },
992    /// Future discriminator. `body` retains the complete ordered object; `tag`
993    /// is its decoded discriminator projection.
994    Unknown {
995        tag: String,
996        body: OrderedJsonObject,
997    },
998}
999
1000#[derive(Debug, Clone, PartialEq)]
1001pub enum StderrTailEntry {
1002    Line {
1003        text: String,
1004        /// The line was cut at the per-line cap and `text` is a prefix.
1005        ///
1006        /// Carried as a field rather than left to a marker in `text` so a
1007        /// consumer can branch on it without string matching.
1008        truncated: bool,
1009        /// Wall-clock Unix milliseconds at which the daemon read this line off
1010        /// the module's pipe. `None` from a daemon that predates the field; a
1011        /// reader must then show no time rather than make one up.
1012        at_ms: Option<u64>,
1013    },
1014    /// The supervisor spawned a new process. Entries after this came from it.
1015    ///
1016    /// In-band because position is the information: which side of the restart a
1017    /// line falls on is unanswerable from a count.
1018    ProcessStart,
1019    /// Future discriminator. `body` retains the complete ordered object; `tag`
1020    /// is its decoded discriminator projection.
1021    Unknown {
1022        tag: String,
1023        body: OrderedJsonObject,
1024    },
1025}
1026
1027#[derive(Debug, Serialize, Deserialize)]
1028#[serde(tag = "status", rename_all = "snake_case")]
1029enum ModuleDeclaredProvenanceWire {
1030    Reported { build: ManifestProvenance },
1031    Unverifiable,
1032}
1033
1034#[derive(Debug, Serialize, Deserialize)]
1035#[serde(tag = "status", rename_all = "snake_case")]
1036enum RunningImageAgreementWire {
1037    Match {
1038        evidence: RunningImageEvidence,
1039    },
1040    Mismatch {
1041        running: RunningImageEvidence,
1042        disk: RunningImageEvidence,
1043    },
1044    Unavailable {
1045        reason: RunningImageUnavailableReason,
1046    },
1047}
1048
1049#[derive(Debug, Serialize, Deserialize)]
1050#[serde(tag = "status", rename_all = "snake_case")]
1051enum ReloadPathAgreementWire {
1052    Match,
1053    Mismatch {
1054        configured: PathBuf,
1055        spawned_from: PathBuf,
1056    },
1057    Unavailable {
1058        reason: ReloadPathUnavailableReason,
1059    },
1060}
1061
1062#[derive(Debug, Serialize, Deserialize)]
1063#[serde(tag = "status", rename_all = "snake_case")]
1064enum LaunchSpecAgreementWire {
1065    Match,
1066    Mismatch,
1067    Unavailable { reason: LaunchSpecUnavailableReason },
1068}
1069
1070#[derive(Debug, Serialize, Deserialize)]
1071#[serde(tag = "method", rename_all = "snake_case")]
1072enum RunningImageEvidenceWire {
1073    LinuxProcSha256 {
1074        digest: String,
1075    },
1076    MacosSpawnInode {
1077        device: u64,
1078        inode: u64,
1079    },
1080    WindowsSpawnFileId {
1081        volume_serial_number: u64,
1082        file_id: [u8; 16],
1083    },
1084}
1085
1086#[derive(Debug, Serialize, Deserialize)]
1087#[serde(tag = "kind", rename_all = "snake_case")]
1088enum SupervisorRouteConsumerWire {
1089    Reserved { module_id: String },
1090    Direct { connection_id: u64 },
1091}
1092
1093#[derive(Debug, Serialize, Deserialize)]
1094#[serde(tag = "state", rename_all = "snake_case")]
1095enum StderrCaptureStateWire {
1096    Captured,
1097    Incomplete { reason: String },
1098    NotCaptured { reason: String },
1099}
1100
1101#[derive(Debug, Serialize, Deserialize)]
1102#[serde(tag = "status", rename_all = "snake_case")]
1103enum ChildResourceUsageWire {
1104    Measured(ChildResourceReading),
1105    Unavailable {
1106        reason: ChildResourceUnavailableReason,
1107    },
1108}
1109
1110#[derive(Debug, Serialize, Deserialize)]
1111#[serde(tag = "kind", rename_all = "snake_case")]
1112enum StderrTailEntryWire {
1113    Line {
1114        text: String,
1115        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1116        truncated: bool,
1117        // Omitted when absent so a reply without it is byte-identical to what
1118        // an older daemon sends. Older decoders ignore the member when present.
1119        #[serde(default, skip_serializing_if = "Option::is_none")]
1120        at_ms: Option<u64>,
1121    },
1122    ProcessStart,
1123}
1124
1125/// JSON values whose object members retain wire order at every depth.
1126#[derive(Debug, Clone, PartialEq)]
1127pub enum OrderedJsonValue {
1128    Null,
1129    Bool(bool),
1130    Number(serde_json::Number),
1131    String(String),
1132    Array(Vec<Self>),
1133    Object(OrderedJsonObject),
1134}
1135
1136/// Ordered JSON members retained for an unknown tagged value.
1137#[derive(Debug, Clone, PartialEq)]
1138pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1139
1140impl OrderedJsonObject {
1141    /// Returns the members in the order they appeared on the wire.
1142    pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1143        &self.0
1144    }
1145
1146    fn into_value(self) -> serde_json::Value {
1147        serde_json::Value::Object(
1148            self.0
1149                .into_iter()
1150                .map(|(key, value)| (key, value.into_value()))
1151                .collect(),
1152        )
1153    }
1154}
1155
1156impl OrderedJsonValue {
1157    fn into_value(self) -> serde_json::Value {
1158        match self {
1159            Self::Null => serde_json::Value::Null,
1160            Self::Bool(value) => serde_json::Value::Bool(value),
1161            Self::Number(value) => serde_json::Value::Number(value),
1162            Self::String(value) => serde_json::Value::String(value),
1163            Self::Array(values) => {
1164                serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1165            }
1166            Self::Object(value) => value.into_value(),
1167        }
1168    }
1169}
1170
1171impl Serialize for OrderedJsonValue {
1172    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1173    where
1174        S: Serializer,
1175    {
1176        match self {
1177            Self::Null => serializer.serialize_unit(),
1178            Self::Bool(value) => serializer.serialize_bool(*value),
1179            Self::Number(value) => value.serialize(serializer),
1180            Self::String(value) => serializer.serialize_str(value),
1181            Self::Array(values) => values.serialize(serializer),
1182            Self::Object(value) => value.serialize(serializer),
1183        }
1184    }
1185}
1186
1187impl<'de> Deserialize<'de> for OrderedJsonValue {
1188    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1189    where
1190        D: Deserializer<'de>,
1191    {
1192        struct OrderedValueVisitor;
1193
1194        impl<'de> Visitor<'de> for OrderedValueVisitor {
1195            type Value = OrderedJsonValue;
1196
1197            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1198                formatter.write_str("a JSON value with ordered object members")
1199            }
1200
1201            fn visit_unit<E>(self) -> Result<Self::Value, E>
1202            where
1203                E: serde::de::Error,
1204            {
1205                Ok(OrderedJsonValue::Null)
1206            }
1207
1208            fn visit_none<E>(self) -> Result<Self::Value, E>
1209            where
1210                E: serde::de::Error,
1211            {
1212                Ok(OrderedJsonValue::Null)
1213            }
1214
1215            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1216            where
1217                D: Deserializer<'de>,
1218            {
1219                OrderedJsonValue::deserialize(deserializer)
1220            }
1221
1222            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1223            where
1224                E: serde::de::Error,
1225            {
1226                Ok(OrderedJsonValue::Bool(value))
1227            }
1228
1229            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1230            where
1231                E: serde::de::Error,
1232            {
1233                Ok(OrderedJsonValue::Number(value.into()))
1234            }
1235
1236            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1237            where
1238                E: serde::de::Error,
1239            {
1240                Ok(OrderedJsonValue::Number(value.into()))
1241            }
1242
1243            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1244            where
1245                E: serde::de::Error,
1246            {
1247                serde_json::Number::from_f64(value)
1248                    .map(OrderedJsonValue::Number)
1249                    .ok_or_else(|| E::custom("non-finite JSON number"))
1250            }
1251
1252            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1253            where
1254                E: serde::de::Error,
1255            {
1256                Ok(OrderedJsonValue::String(value.to_owned()))
1257            }
1258
1259            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1260            where
1261                E: serde::de::Error,
1262            {
1263                Ok(OrderedJsonValue::String(value))
1264            }
1265
1266            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1267            where
1268                A: SeqAccess<'de>,
1269            {
1270                let mut values = Vec::new();
1271                while let Some(value) = sequence.next_element()? {
1272                    values.push(value);
1273                }
1274                Ok(OrderedJsonValue::Array(values))
1275            }
1276
1277            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1278            where
1279                A: MapAccess<'de>,
1280            {
1281                let mut entries = Vec::new();
1282                while let Some((key, value)) = map.next_entry()? {
1283                    entries.push((key, value));
1284                }
1285                Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1286            }
1287        }
1288
1289        deserializer.deserialize_any(OrderedValueVisitor)
1290    }
1291}
1292
1293impl Serialize for OrderedJsonObject {
1294    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1295    where
1296        S: Serializer,
1297    {
1298        let mut map = serializer.serialize_map(Some(self.0.len()))?;
1299        for (key, value) in &self.0 {
1300            map.serialize_entry(key, value)?;
1301        }
1302        map.end()
1303    }
1304}
1305
1306impl<'de> Deserialize<'de> for OrderedJsonObject {
1307    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1308    where
1309        D: Deserializer<'de>,
1310    {
1311        struct OrderedObjectVisitor;
1312
1313        impl<'de> Visitor<'de> for OrderedObjectVisitor {
1314            type Value = OrderedJsonObject;
1315
1316            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1317                formatter.write_str("an object with ordered JSON members")
1318            }
1319
1320            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1321            where
1322                A: MapAccess<'de>,
1323            {
1324                let mut entries = Vec::new();
1325                while let Some((key, value)) = map.next_entry()? {
1326                    entries.push((key, value));
1327                }
1328                Ok(OrderedJsonObject(entries))
1329            }
1330        }
1331
1332        deserializer.deserialize_map(OrderedObjectVisitor)
1333    }
1334}
1335
1336fn read_tagged<'de, D>(
1337    deserializer: D,
1338    field: &'static str,
1339) -> Result<(String, OrderedJsonObject), D::Error>
1340where
1341    D: Deserializer<'de>,
1342{
1343    let body = OrderedJsonObject::deserialize(deserializer)?;
1344    let mut tag = None;
1345    for (key, value) in body.as_entries() {
1346        if key != field {
1347            continue;
1348        }
1349        if tag.is_some() {
1350            return Err(D::Error::custom(format!(
1351                "tagged object has duplicate `{field}` field"
1352            )));
1353        }
1354        let OrderedJsonValue::String(value) = value else {
1355            return Err(D::Error::custom(format!(
1356                "tagged object has no string `{field}` field"
1357            )));
1358        };
1359        tag = Some(value);
1360    }
1361    let Some(tag) = tag else {
1362        return Err(D::Error::custom(format!(
1363            "tagged object has no string `{field}` field"
1364        )));
1365    };
1366    Ok((tag.to_string(), body))
1367}
1368
1369fn read_ordered_tagged(
1370    value: OrderedJsonValue,
1371    field: &'static str,
1372) -> Result<(String, OrderedJsonObject), String> {
1373    let OrderedJsonValue::Object(body) = value else {
1374        return Err(format!("expected tagged object with `{field}` field"));
1375    };
1376    let mut tag = None;
1377    for (key, value) in body.as_entries() {
1378        if key != field {
1379            continue;
1380        }
1381        if tag.is_some() {
1382            return Err(format!("tagged object has duplicate `{field}` field"));
1383        }
1384        let OrderedJsonValue::String(value) = value else {
1385            return Err(format!("tagged object has no string `{field}` field"));
1386        };
1387        tag = Some(value);
1388    }
1389    let Some(tag) = tag else {
1390        return Err(format!("tagged object has no string `{field}` field"));
1391    };
1392    Ok((tag.to_string(), body))
1393}
1394
1395fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1396    body.as_entries()
1397        .iter()
1398        .find_map(|(key, value)| (key == field).then_some(value))
1399}
1400
1401fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1402    match ordered_field(body, field) {
1403        Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1404        Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1405        None => Err(format!("tagged object has no `{field}` field")),
1406    }
1407}
1408
1409fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1410    let (tag, body) = read_ordered_tagged(value, "method")?;
1411    match tag.as_str() {
1412        "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1413            digest: ordered_string(&body, "digest")?,
1414        }),
1415        "macos_spawn_inode" => {
1416            let device = ordered_field(&body, "device")
1417                .and_then(|value| match value {
1418                    OrderedJsonValue::Number(number) => number.as_u64(),
1419                    _ => None,
1420                })
1421                .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1422            let inode = ordered_field(&body, "inode")
1423                .and_then(|value| match value {
1424                    OrderedJsonValue::Number(number) => number.as_u64(),
1425                    _ => None,
1426                })
1427                .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1428            Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1429        }
1430        "windows_spawn_file_id" => {
1431            let wire: RunningImageEvidenceWire = serde_json::from_value(
1432                serde_json::to_value(&body).map_err(|error| error.to_string())?,
1433            )
1434            .map_err(|error| error.to_string())?;
1435            match wire {
1436                RunningImageEvidenceWire::WindowsSpawnFileId {
1437                    volume_serial_number,
1438                    file_id,
1439                } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1440                    volume_serial_number,
1441                    file_id,
1442                }),
1443                _ => unreachable!(),
1444            }
1445        }
1446        _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1447    }
1448}
1449
1450impl Serialize for ModuleDeclaredProvenance {
1451    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1452    where
1453        S: Serializer,
1454    {
1455        match self {
1456            Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1457                build: build.clone(),
1458            }
1459            .serialize(serializer),
1460            Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1461            Self::Unknown { body, .. } => body.serialize(serializer),
1462        }
1463    }
1464}
1465
1466impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1467    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1468    where
1469        D: serde::Deserializer<'de>,
1470    {
1471        let (tag, value) = read_tagged(deserializer, "status")?;
1472        match tag.as_str() {
1473            "reported" => match serde_json::from_value(value.into_value())
1474                .map_err(D::Error::custom)?
1475            {
1476                ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1477                ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1478            },
1479            "unverifiable" => {
1480                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1481                    ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1482                    ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1483                }
1484            }
1485            _ => Ok(Self::Unknown { tag, body: value }),
1486        }
1487    }
1488}
1489
1490impl Serialize for RunningImageAgreement {
1491    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1492    where
1493        S: Serializer,
1494    {
1495        match self {
1496            Self::Match { evidence } => RunningImageAgreementWire::Match {
1497                evidence: evidence.clone(),
1498            }
1499            .serialize(serializer),
1500            Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1501                running: running.clone(),
1502                disk: disk.clone(),
1503            }
1504            .serialize(serializer),
1505            Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1506                reason: reason.clone(),
1507            }
1508            .serialize(serializer),
1509            Self::Unknown { body, .. } => body.serialize(serializer),
1510        }
1511    }
1512}
1513
1514impl Serialize for ReloadPathAgreement {
1515    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1516    where
1517        S: Serializer,
1518    {
1519        match self {
1520            Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1521            Self::Mismatch {
1522                configured,
1523                spawned_from,
1524            } => ReloadPathAgreementWire::Mismatch {
1525                configured: configured.clone(),
1526                spawned_from: spawned_from.clone(),
1527            }
1528            .serialize(serializer),
1529            Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1530                reason: reason.clone(),
1531            }
1532            .serialize(serializer),
1533            Self::Unknown { body, .. } => body.serialize(serializer),
1534        }
1535    }
1536}
1537
1538impl Serialize for LaunchSpecAgreement {
1539    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1540    where
1541        S: Serializer,
1542    {
1543        match self {
1544            Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1545            Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1546            Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1547                reason: reason.clone(),
1548            }
1549            .serialize(serializer),
1550            Self::Unknown { body, .. } => body.serialize(serializer),
1551        }
1552    }
1553}
1554
1555impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1556    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1557    where
1558        D: Deserializer<'de>,
1559    {
1560        let (tag, body) = read_tagged(deserializer, "status")?;
1561        match tag.as_str() {
1562            "match" => Ok(Self::Match),
1563            "mismatch" => Ok(Self::Mismatch),
1564            "unavailable" => match serde_json::from_value(body.into_value())
1565                .map_err(D::Error::custom)?
1566            {
1567                LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1568                _ => unreachable!(),
1569            },
1570            _ => Ok(Self::Unknown { tag, body }),
1571        }
1572    }
1573}
1574
1575impl<'de> Deserialize<'de> for ReloadPathAgreement {
1576    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1577    where
1578        D: Deserializer<'de>,
1579    {
1580        let (tag, body) = read_tagged(deserializer, "status")?;
1581        match tag.as_str() {
1582            "match" => Ok(Self::Match),
1583            "mismatch" => {
1584                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1585                    ReloadPathAgreementWire::Mismatch {
1586                        configured,
1587                        spawned_from,
1588                    } => Ok(Self::Mismatch {
1589                        configured,
1590                        spawned_from,
1591                    }),
1592                    _ => unreachable!(),
1593                }
1594            }
1595            "unavailable" => match serde_json::from_value(body.into_value())
1596                .map_err(D::Error::custom)?
1597            {
1598                ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1599                _ => unreachable!(),
1600            },
1601            _ => Ok(Self::Unknown { tag, body }),
1602        }
1603    }
1604}
1605
1606impl<'de> Deserialize<'de> for RunningImageAgreement {
1607    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1608    where
1609        D: serde::Deserializer<'de>,
1610    {
1611        let (tag, value) = read_tagged(deserializer, "status")?;
1612        match tag.as_str() {
1613            "match" => Ok(Self::Match {
1614                evidence: decode_running_image_evidence(
1615                    ordered_field(&value, "evidence")
1616                        .cloned()
1617                        .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1618                )
1619                .map_err(D::Error::custom)?,
1620            }),
1621            "mismatch" => Ok(Self::Mismatch {
1622                running: decode_running_image_evidence(
1623                    ordered_field(&value, "running")
1624                        .cloned()
1625                        .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1626                )
1627                .map_err(D::Error::custom)?,
1628                disk: decode_running_image_evidence(
1629                    ordered_field(&value, "disk")
1630                        .cloned()
1631                        .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1632                )
1633                .map_err(D::Error::custom)?,
1634            }),
1635            "unavailable" => Ok(Self::Unavailable {
1636                reason: serde_json::from_value(
1637                    ordered_field(&value, "reason")
1638                        .cloned()
1639                        .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1640                        .into_value(),
1641                )
1642                .map_err(D::Error::custom)?,
1643            }),
1644            _ => Ok(Self::Unknown { tag, body: value }),
1645        }
1646    }
1647}
1648
1649impl Serialize for ChildResourceUsage {
1650    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1651    where
1652        S: Serializer,
1653    {
1654        match self {
1655            Self::Measured(reading) => {
1656                ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1657            }
1658            Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1659                reason: reason.clone(),
1660            }
1661            .serialize(serializer),
1662            Self::Unknown { body, .. } => body.serialize(serializer),
1663        }
1664    }
1665}
1666
1667impl<'de> Deserialize<'de> for ChildResourceUsage {
1668    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1669    where
1670        D: Deserializer<'de>,
1671    {
1672        let (tag, body) = read_tagged(deserializer, "status")?;
1673        match tag.as_str() {
1674            "measured" | "unavailable" => {
1675                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1676                    ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1677                    ChildResourceUsageWire::Unavailable { reason } => {
1678                        Ok(Self::Unavailable { reason })
1679                    }
1680                }
1681            }
1682            _ => Ok(Self::Unknown { tag, body }),
1683        }
1684    }
1685}
1686
1687impl Serialize for RunningImageEvidence {
1688    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1689    where
1690        S: Serializer,
1691    {
1692        match self {
1693            Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1694                digest: digest.clone(),
1695            }
1696            .serialize(serializer),
1697            Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1698                device: *device,
1699                inode: *inode,
1700            }
1701            .serialize(serializer),
1702            Self::WindowsSpawnFileId {
1703                volume_serial_number,
1704                file_id,
1705            } => RunningImageEvidenceWire::WindowsSpawnFileId {
1706                volume_serial_number: *volume_serial_number,
1707                file_id: *file_id,
1708            }
1709            .serialize(serializer),
1710            Self::Unknown { body, .. } => body.serialize(serializer),
1711        }
1712    }
1713}
1714
1715impl<'de> Deserialize<'de> for RunningImageEvidence {
1716    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1717    where
1718        D: serde::Deserializer<'de>,
1719    {
1720        let (tag, value) = read_tagged(deserializer, "method")?;
1721        match tag.as_str() {
1722            "linux_proc_sha256" => {
1723                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1724                    RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1725                        Ok(Self::LinuxProcSha256 { digest })
1726                    }
1727                    _ => unreachable!(),
1728                }
1729            }
1730            "macos_spawn_inode" => {
1731                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1732                    RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1733                        Ok(Self::MacosSpawnInode { device, inode })
1734                    }
1735                    _ => unreachable!(),
1736                }
1737            }
1738            "windows_spawn_file_id" => {
1739                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1740                    RunningImageEvidenceWire::WindowsSpawnFileId {
1741                        volume_serial_number,
1742                        file_id,
1743                    } => Ok(Self::WindowsSpawnFileId {
1744                        volume_serial_number,
1745                        file_id,
1746                    }),
1747                    _ => unreachable!(),
1748                }
1749            }
1750            _ => Ok(Self::Unknown { tag, body: value }),
1751        }
1752    }
1753}
1754
1755impl Serialize for SupervisorRouteConsumer {
1756    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1757    where
1758        S: Serializer,
1759    {
1760        match self {
1761            Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1762                module_id: module_id.clone(),
1763            }
1764            .serialize(serializer),
1765            Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1766                connection_id: *connection_id,
1767            }
1768            .serialize(serializer),
1769            Self::Unknown { body, .. } => body.serialize(serializer),
1770        }
1771    }
1772}
1773
1774impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1775    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1776    where
1777        D: serde::Deserializer<'de>,
1778    {
1779        let (tag, value) = read_tagged(deserializer, "kind")?;
1780        match tag.as_str() {
1781            "reserved" => {
1782                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1783                    SupervisorRouteConsumerWire::Reserved { module_id } => {
1784                        Ok(Self::Reserved { module_id })
1785                    }
1786                    _ => unreachable!(),
1787                }
1788            }
1789            "direct" => {
1790                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1791                    SupervisorRouteConsumerWire::Direct { connection_id } => {
1792                        Ok(Self::Direct { connection_id })
1793                    }
1794                    _ => unreachable!(),
1795                }
1796            }
1797            _ => Ok(Self::Unknown { tag, body: value }),
1798        }
1799    }
1800}
1801
1802impl Serialize for StderrCaptureState {
1803    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1804    where
1805        S: Serializer,
1806    {
1807        match self {
1808            Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1809            Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1810                reason: reason.clone(),
1811            }
1812            .serialize(serializer),
1813            Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1814                reason: reason.clone(),
1815            }
1816            .serialize(serializer),
1817            Self::Unknown { body, .. } => body.serialize(serializer),
1818        }
1819    }
1820}
1821
1822impl<'de> Deserialize<'de> for StderrCaptureState {
1823    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1824    where
1825        D: serde::Deserializer<'de>,
1826    {
1827        let (tag, value) = read_tagged(deserializer, "state")?;
1828        match tag.as_str() {
1829            "captured" => {
1830                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1831                    StderrCaptureStateWire::Captured => Ok(Self::Captured),
1832                    _ => unreachable!(),
1833                }
1834            }
1835            "incomplete" => match serde_json::from_value(value.into_value())
1836                .map_err(D::Error::custom)?
1837            {
1838                StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1839                _ => unreachable!(),
1840            },
1841            "not_captured" => match serde_json::from_value(value.into_value())
1842                .map_err(D::Error::custom)?
1843            {
1844                StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1845                _ => unreachable!(),
1846            },
1847            _ => Ok(Self::Unknown { tag, body: value }),
1848        }
1849    }
1850}
1851
1852impl Serialize for StderrTailEntry {
1853    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1854    where
1855        S: Serializer,
1856    {
1857        match self {
1858            Self::Line {
1859                text,
1860                truncated,
1861                at_ms,
1862            } => StderrTailEntryWire::Line {
1863                text: text.clone(),
1864                truncated: *truncated,
1865                at_ms: *at_ms,
1866            }
1867            .serialize(serializer),
1868            Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1869            Self::Unknown { body, .. } => body.serialize(serializer),
1870        }
1871    }
1872}
1873
1874impl<'de> Deserialize<'de> for StderrTailEntry {
1875    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1876    where
1877        D: serde::Deserializer<'de>,
1878    {
1879        let (tag, value) = read_tagged(deserializer, "kind")?;
1880        match tag.as_str() {
1881            "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1882                StderrTailEntryWire::Line {
1883                    text,
1884                    truncated,
1885                    at_ms,
1886                } => Ok(Self::Line {
1887                    text,
1888                    truncated,
1889                    at_ms,
1890                }),
1891                _ => unreachable!(),
1892            },
1893            "process_start" => {
1894                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1895                    StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1896                    _ => unreachable!(),
1897                }
1898            }
1899            _ => Ok(Self::Unknown { tag, body: value }),
1900        }
1901    }
1902}
1903
1904fn is_zero_u64(value: &u64) -> bool {
1905    *value == 0
1906}
1907
1908fn default_true() -> bool {
1909    true
1910}
1911
1912/// Bounded terminal history for one module, oldest retained record first.
1913#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1914pub struct TerminalHistory {
1915    /// Unix milliseconds at the current daemon's start; entries may predate it.
1916    pub daemon_started_at_ms: u64,
1917    pub entries: Vec<TerminalEntry>,
1918    /// Exits evicted by the current daemon's ring, possibly recovered from its
1919    /// journal. Not a count of missing exits: expired journal totals are unknown.
1920    #[serde(default, skip_serializing_if = "is_zero_u64")]
1921    pub dropped: u64,
1922    /// Unparseable or incomplete lines across the shared journal, including
1923    /// lines whose module cannot be determined. Zero on older daemons.
1924    #[serde(default, skip_serializing_if = "is_zero_u64")]
1925    pub journal_skipped_lines: u64,
1926    /// Files that could not be read completely, excluding absent generations.
1927    #[serde(default, skip_serializing_if = "is_zero_u64")]
1928    pub journal_read_errors: u64,
1929    /// Failed journal appends across all modules in the current daemon.
1930    #[serde(default, skip_serializing_if = "is_zero_u64")]
1931    pub journal_write_failures: u64,
1932}
1933
1934/// One terminal child exit and the supervisor action it selected.
1935#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1936pub struct TerminalEntry {
1937    /// Opaque identity of the daemon that observed this exit; absent on older
1938    /// daemons. Different tokens mean different lifetimes, not chronological order.
1939    #[serde(default, skip_serializing_if = "Option::is_none")]
1940    pub daemon_incarnation: Option<String>,
1941    #[serde(default, skip_serializing_if = "Option::is_none")]
1942    pub exit_code: Option<i32>,
1943    #[serde(default, skip_serializing_if = "Option::is_none")]
1944    pub exit_signal: Option<i32>,
1945    pub at_ms: u64,
1946    pub disposition: TerminalDisposition,
1947    /// Supervisor classification of this exit. Absent on daemons that predate
1948    /// the field; unknown future kinds remain readable instead of failing the
1949    /// enclosing terminal record.
1950    #[serde(default, skip_serializing_if = "Option::is_none")]
1951    pub exit_kind: Option<TerminalExitKind>,
1952    /// Why the supervisor chose this disposition, when the disposition alone
1953    /// does not say. A `failed` record carries the exhausted crash budget here
1954    /// (`crash budget exhausted: max_restarts=3 within window_secs=600`), which
1955    /// is the difference between an operator seeing "it failed" and seeing which
1956    /// limit stopped it. Prose for humans: render it, never parse it. Absent for
1957    /// ordinary dispositions and on daemons predating the field.
1958    #[serde(default, skip_serializing_if = "Option::is_none")]
1959    pub disposition_detail: Option<String>,
1960}
1961
1962/// Exit classification carried by supervisor history and census records.
1963///
1964/// This is an open string enum so future daemon variants degrade to a readable
1965/// unknown kind rather than making a consumer discard the enclosing record.
1966#[derive(Debug, Clone, PartialEq, Eq)]
1967pub enum TerminalExitKind {
1968    Clean,
1969    Crash,
1970    DeliberateSeverance,
1971    Unknown(String),
1972}
1973
1974impl TerminalExitKind {
1975    fn wire_name(&self) -> &str {
1976        match self {
1977            Self::Clean => "clean",
1978            Self::Crash => "crash",
1979            Self::DeliberateSeverance => "deliberate_severance",
1980            Self::Unknown(value) => value,
1981        }
1982    }
1983}
1984
1985impl Serialize for TerminalExitKind {
1986    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1987    where
1988        S: serde::Serializer,
1989    {
1990        serializer.serialize_str(self.wire_name())
1991    }
1992}
1993
1994impl<'de> Deserialize<'de> for TerminalExitKind {
1995    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1996    where
1997        D: serde::Deserializer<'de>,
1998    {
1999        let value = String::deserialize(deserializer)?;
2000        Ok(match value.as_str() {
2001            "clean" => Self::Clean,
2002            "crash" => Self::Crash,
2003            "deliberate_severance" => Self::DeliberateSeverance,
2004            _ => Self::Unknown(value),
2005        })
2006    }
2007}
2008
2009open_string_enum! {
2010    /// The supervisor disposition selected after observing a terminal exit.
2011    TerminalDisposition {
2012        Stopped => "stopped",
2013        Disabled => "disabled",
2014        Failed => "failed",
2015        Restarting => "restarting",
2016        /// The child exited after the daemon had begun its own announced
2017        /// shutdown, whatever its exit code or signal. Such an exit is not
2018        /// a crash and is never followed by a respawn. Readers that predate
2019        /// this value decode it as `Unknown("daemon_shutdown")`.
2020        DaemonShutdown => "daemon_shutdown",
2021    }
2022}
2023
2024#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2025#[serde(rename_all = "snake_case")]
2026pub enum PollKind {
2027    Status,
2028    Liveness,
2029}
2030
2031/// A registered module's catalog projection.
2032///
2033/// Use [`CatalogEntry::new`] and its `with_*` methods to construct entries so
2034/// future fields do not require changes to callers.
2035/// Struct literals and functional record updates are not supported outside this crate:
2036///
2037/// ```compile_fail,E0639
2038/// use subc_control::CatalogEntry;
2039/// let entry = CatalogEntry::new("provider", vec![], vec![]);
2040/// let entry = CatalogEntry { ready: false, ..entry };
2041/// ```
2042#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2043#[non_exhaustive]
2044pub struct CatalogEntry {
2045    pub module_id: String,
2046    /// Module-declared human-readable name. Apps fall back to `module_id`.
2047    #[serde(default, skip_serializing_if = "Option::is_none")]
2048    pub display_name: Option<String>,
2049    /// Whether the registered module currently accepts new route binds.
2050    ///
2051    /// This is the module's EFFECTIVE readiness: its own declared readiness
2052    /// AND every one of its `need: required` capabilities having a registered
2053    /// provider. It is exactly the condition `route.open` checks, so a caller
2054    /// reading `false` here will be refused with `module_warming`; `not_ready`
2055    /// says why.
2056    ///
2057    /// Older daemons omit this field and are interpreted as ready. Daemons that
2058    /// predate `not_ready` report declared readiness only.
2059    #[serde(default = "default_true")]
2060    pub ready: bool,
2061    /// Why `ready` is false, in the same shape `route.open` puts in the
2062    /// `detail` of its `module_warming` refusal. Absent when the module is
2063    /// ready, and absent from daemons that predate the field.
2064    #[serde(default, skip_serializing_if = "Option::is_none")]
2065    pub not_ready: Option<NotReadyReason>,
2066    /// The registered module's self-declared build version, projected from its
2067    /// manifest so a consumer can tell WHICH BUILD of a module it is talking
2068    /// to at connect time.
2069    ///
2070    /// Without this, a client compiled against a module's current source reads
2071    /// a contract that is true of the repository and false of the running
2072    /// process -- the types match, the JSON decodes, and the meaning has
2073    /// changed. That failure carries no error to notice; the version in the
2074    /// catalog turns a semantic skew into a log line at connect instead of a
2075    /// wrong sentence on a user's screen.
2076    ///
2077    /// Optional on the wire only because entries serialized by older daemons
2078    /// lack it: absent means "daemon predates the field", never "module has
2079    /// no version" (the manifest field is required at registration).
2080    ///
2081    /// The reading is ARMED BY OBSERVATION, not by this documentation: until
2082    /// a consumer has seen at least one populated entry from the daemon it is
2083    /// connected to, an all-None catalog is indistinguishable from an old
2084    /// daemon, and a client shipping the documented reading against it would
2085    /// hold a guarantee it does not have.
2086    #[serde(default, skip_serializing_if = "Option::is_none")]
2087    pub module_version: Option<String>,
2088    /// Build provenance mirrored from the registered module's manifest.
2089    /// Absent when the module did not declare it or the daemon predates the field.
2090    #[serde(default, skip_serializing_if = "Option::is_none")]
2091    pub provenance: Option<ManifestProvenance>,
2092    pub roles: Vec<ProviderRole>,
2093    pub control_ops: Vec<String>,
2094    /// Static capability declarations from the registering module's manifest.
2095    ///
2096    /// Optional on the wire so consumers connected to a daemon that predates the
2097    /// capability grammar retain their existing catalog decoding behavior.
2098    #[serde(default, skip_serializing_if = "Option::is_none")]
2099    pub capabilities: Option<CapabilityDeclarations>,
2100    /// Self-signal declarations mirrored verbatim from the registering module's
2101    /// manifest. The daemon relays these declarations without interpreting them.
2102    #[serde(default, skip_serializing_if = "Option::is_none")]
2103    pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2104    /// Event declarations mirrored verbatim from the registering module's manifest.
2105    /// Absent when the manifest omits `events`; an empty array records an affirmative
2106    /// declaration that the module publishes no events.
2107    #[serde(default, skip_serializing_if = "Option::is_none")]
2108    pub events: Option<Vec<EventDeclaration>>,
2109    /// Open delivery hints mirrored from the module manifest. Empty means unary;
2110    /// only `"watch"` on a declared management query is subscribable.
2111    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2112    pub operation_delivery: BTreeMap<String, OperationDelivery>,
2113    /// Raw request payload limits mirrored from the module manifest by operation
2114    /// name. Empty maps preserve catalog bytes from before payload declarations.
2115    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2116    pub operation_payload: BTreeMap<String, OperationPayload>,
2117    /// Management operations the module serves to a flow-scoped call, mirrored
2118    /// unchanged from its manifest. Absent means the module did not say, so a
2119    /// reader treats the answer as unknown rather than as "none"; an empty list
2120    /// admits no operation under a flow scope. Absence preserves catalog bytes
2121    /// from before the field. The daemon relays it and never enforces it.
2122    #[serde(default, skip_serializing_if = "Option::is_none")]
2123    pub flow_operations: Option<Vec<String>>,
2124    /// Deferred-operation declarations mirrored from the registered manifest.
2125    #[serde(default, skip_serializing_if = "Option::is_none")]
2126    pub operation_deferral: Option<BTreeMap<String, bool>>,
2127    /// Management operations the module guards with `operator.confirm`,
2128    /// mirrored unchanged from its manifest. Absent means the module did not
2129    /// say (or declared an invalid list, which the daemon dropped), so a reader
2130    /// treats the answer as unknown. Absence preserves catalog bytes from before
2131    /// the field. The daemon relays it and refuses nothing on its basis.
2132    #[serde(default, skip_serializing_if = "Option::is_none")]
2133    pub confirm_operations: Option<Vec<String>>,
2134    /// Rich-UI descriptor mirrored verbatim from the registering manifest.
2135    /// The daemon does not fetch or interpret the manifest described here.
2136    #[serde(default, skip_serializing_if = "Option::is_none")]
2137    pub rich_ui: Option<RichUiDescriptor>,
2138    /// Opaque per-role objects mirrored unchanged from the registered manifest.
2139    /// Each role owns its schema; the daemon validates only keys, shape and size.
2140    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2141    pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2142    /// True only when HELLO passes the launch-nonce check required for a reserved
2143    /// module or swap candidate.
2144    #[serde(default, skip_serializing_if = "is_false")]
2145    pub nonce_verified: bool,
2146}
2147
2148impl CatalogEntry {
2149    /// Sets the optional module-declared display name.
2150    #[must_use]
2151    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2152        self.display_name = display_name;
2153        self
2154    }
2155
2156    /// Construct an entry with its required fields and wire-compatible defaults.
2157    #[must_use]
2158    pub fn new(
2159        module_id: impl Into<String>,
2160        roles: Vec<ProviderRole>,
2161        control_ops: Vec<String>,
2162    ) -> Self {
2163        Self {
2164            module_id: module_id.into(),
2165            ready: default_true(),
2166            display_name: None,
2167            not_ready: None,
2168            module_version: None,
2169            provenance: None,
2170            roles,
2171            control_ops,
2172            capabilities: None,
2173            self_signals: None,
2174            events: None,
2175            operation_delivery: BTreeMap::new(),
2176            operation_payload: BTreeMap::new(),
2177            flow_operations: None,
2178            operation_deferral: None,
2179            confirm_operations: None,
2180            rich_ui: None,
2181            role_declarations: BTreeMap::new(),
2182            nonce_verified: false,
2183        }
2184    }
2185
2186    /// Set raw request payload limits mirrored from the registered manifest.
2187    #[must_use]
2188    pub fn with_operation_payload(
2189        mut self,
2190        operation_payload: BTreeMap<String, OperationPayload>,
2191    ) -> Self {
2192        self.operation_payload = operation_payload;
2193        self
2194    }
2195
2196    /// Set or clear the flow-scoped operation list mirrored from the registered
2197    /// manifest. `None` is omitted from the wire.
2198    #[must_use]
2199    pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2200        self.flow_operations = flow_operations;
2201        self
2202    }
2203
2204    /// Set deferred-operation declarations mirrored from the manifest.
2205    #[must_use]
2206    pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2207        self.operation_deferral = operations;
2208        self
2209    }
2210
2211    /// Set or clear the confirm-guarded operation list mirrored from the
2212    /// registered manifest. `None` is omitted from the wire.
2213    #[must_use]
2214    pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2215        self.confirm_operations = confirm_operations;
2216        self
2217    }
2218
2219    /// Set the module's effective readiness.
2220    #[must_use]
2221    pub fn with_ready(mut self, ready: bool) -> Self {
2222        self.ready = ready;
2223        self
2224    }
2225
2226    /// Set or clear the reason the module is not ready.
2227    #[must_use]
2228    pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2229        self.not_ready = not_ready;
2230        self
2231    }
2232
2233    /// Set or clear the module's self-declared version.
2234    #[must_use]
2235    pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2236        self.module_version = module_version;
2237        self
2238    }
2239
2240    /// Set or clear the build provenance mirrored from the registered manifest.
2241    #[must_use]
2242    pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2243        self.provenance = provenance;
2244        self
2245    }
2246
2247    /// Set or clear the module's static capability declarations.
2248    #[must_use]
2249    pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2250        self.capabilities = capabilities;
2251        self
2252    }
2253
2254    /// Set or clear the module's self-signal declarations.
2255    #[must_use]
2256    pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2257        self.self_signals = self_signals;
2258        self
2259    }
2260
2261    /// Set or clear the event declarations mirrored from the module manifest.
2262    #[must_use]
2263    pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2264        self.events = events;
2265        self
2266    }
2267
2268    /// Set delivery hints mirrored from the module manifest.
2269    /// Serialization omits this field when the stored map is empty.
2270    #[must_use]
2271    pub fn with_operation_delivery(
2272        mut self,
2273        operation_delivery: BTreeMap<String, OperationDelivery>,
2274    ) -> Self {
2275        self.operation_delivery = operation_delivery;
2276        self
2277    }
2278
2279    /// Set the descriptor mirrored from the module's HELLO manifest.
2280    #[must_use]
2281    pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2282        self.rich_ui = rich_ui;
2283        self
2284    }
2285
2286    /// Set opaque per-role declarations mirrored from the registered manifest.
2287    #[must_use]
2288    pub fn with_role_declarations(
2289        mut self,
2290        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2291    ) -> Self {
2292        self.role_declarations = role_declarations;
2293        self
2294    }
2295
2296    /// Mark a registration as nonce-verified when HELLO passes the launch-nonce
2297    /// check required for a reserved module or swap candidate.
2298    #[must_use]
2299    pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2300        self.nonce_verified = nonce_verified;
2301        self
2302    }
2303}
2304
2305fn is_false(value: &bool) -> bool {
2306    !value
2307}
2308
2309/// Why a registered module is not accepting new route binds.
2310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2311pub struct NotReadyReason {
2312    /// `declared_not_ready` when the module itself said it is not ready, or
2313    /// `required_capability_unprovided` when a capability it declares
2314    /// `need: required` has no registered provider. Open vocabulary: a newer
2315    /// daemon may add reasons.
2316    pub reason: String,
2317    /// For `required_capability_unprovided`, the lexicographically first
2318    /// required capability that has no registered provider.
2319    #[serde(default, skip_serializing_if = "Option::is_none")]
2320    pub capability: Option<String>,
2321}
2322
2323impl NotReadyReason {
2324    pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2325    pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2326}
2327
2328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2329pub struct CapabilityRequirementStatus {
2330    pub consumer: String,
2331    pub capability: String,
2332    pub need: String,
2333    pub verdict: String,
2334    pub episode_seq: u64,
2335    pub config_satisfiable: bool,
2336    pub runtime_available: bool,
2337    pub detail: String,
2338}
2339
2340#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2341pub struct SupervisorRescanResult {
2342    pub added: Vec<String>,
2343    pub removed: Vec<String>,
2344    pub changed_pending_reload: Vec<String>,
2345    /// Modules whose enabled flag differs between config and running state.
2346    ///
2347    /// Rescan calls `set_enabled` for these, so omitting them made the preview
2348    /// describe two of the three mutation classes it performs. A module changing
2349    /// only its enabled flag landed in no bucket at all -- not added, removed or
2350    /// changed, and deliberately not counted as unchanged either -- so the sole
2351    /// evidence was that the buckets no longer summed to the configured module
2352    /// count. A preview is consulted precisely when someone is being careful,
2353    /// which is the worst place to under-report.
2354    ///
2355    /// Empty is skipped so consumers written against the older shape keep
2356    /// parsing.
2357    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2358    pub enabled_changes: Vec<String>,
2359    pub unchanged: u32,
2360    /// True when this reconciliation was computed but NOT applied.
2361    ///
2362    /// Carried on the result rather than left to the caller's memory of what it
2363    /// asked for. A preview and an execution are otherwise byte-identical, so a
2364    /// reader who meets this output later -- in a log, a transcript, a pasted
2365    /// snippet -- cannot tell which one happened. Absent when false, so existing
2366    /// consumers see the shape they already parse.
2367    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2368    pub preview: bool,
2369    /// Config sections that changed but which rescan CANNOT apply, so the
2370    /// operator learns a daemon restart is required from the command they just
2371    /// ran rather than from the journal.
2372    ///
2373    /// The daemon has always detected this and logged a warning. A warning in a
2374    /// log is addressed to whoever is reading the log, and the person who just
2375    /// edited the config is by construction looking at the CLI instead: reported
2376    /// by an outside contributor after a module crash-looped through four
2377    /// respawns because a new top-level `storage` section was silently not
2378    /// applied, diagnosable only by journal archaeology.
2379    ///
2380    /// Names the SECTIONS rather than a boolean, because "something else
2381    /// changed" sends the operator back to diffing their own file -- which is
2382    /// the work the message exists to save.
2383    ///
2384    /// Empty is skipped, so consumers written against the older shape keep
2385    /// parsing.
2386    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2387    pub restart_required: Vec<String>,
2388    /// Required capabilities that a dry-run's resulting module set would leave
2389    /// unprovided. Rows are human-readable because the preview is an operator
2390    /// explanation, not a second manifest schema.
2391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2392    pub capability_warnings: Vec<String>,
2393    /// What applying the previewed candidate would do to each module, in
2394    /// module id order. Filled only by a `supervisor.rescan_checked` preview;
2395    /// a module whose launch spec, health policy and enabled flag all stay as
2396    /// staged has no entry, and neither has a disabled module that is added
2397    /// or removed. Empty is skipped, so `supervisor.rescan` replies keep their
2398    /// shape.
2399    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2400    pub module_actions: Vec<RescanModuleAction>,
2401    /// Modules whose running process still uses launch inputs from an earlier
2402    /// rescan: their staged spec waits for a restart that this candidate
2403    /// does not cause. Filled only by a `supervisor.rescan_checked` preview.
2404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2405    pub earlier_pending: Vec<String>,
2406    /// The value an apply of this preview must send. Present only on a
2407    /// `supervisor.rescan_checked` preview.
2408    #[serde(default, skip_serializing_if = "Option::is_none")]
2409    pub expect: Option<RescanExpect>,
2410}
2411
2412/// Which wire protocol a supervised module speaks to subc, as DECLARED in
2413/// daemon config. Never inferred from observed behaviour.
2414///
2415/// The distinction this exists to keep is between a module that should have
2416/// registered and has not yet, and one that never will. A `Subc` module that has
2417/// not registered is a subc module that is LATE -- it may be booting, it may be
2418/// wedged, and the supervisor's health probing and restart escalation are the
2419/// right response. A `None` module is a third-party process (the NATS server is
2420/// the first) that subc launches, supervises, and stops, and that is all: it
2421/// speaks no subc wire at all, so treating its silence as a fault would restart
2422/// a perfectly healthy process forever.
2423///
2424/// Inferring the difference from "has not registered within N seconds" would
2425/// collapse exactly the two cases that must stay apart, which is why this is a
2426/// declaration.
2427#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2428#[serde(rename_all = "snake_case")]
2429pub enum ModuleProtocol {
2430    /// The module registers over channel 0, answers `health.check`, and can
2431    /// serve routes. Every module predating this field is one of these, which is
2432    /// why it is the default.
2433    #[default]
2434    Subc,
2435    /// The module speaks no subc wire. It is supervised as a process only.
2436    ///
2437    /// A clean exit (status 0) that the daemon did not request is restarted as
2438    /// a crash, counting against the restart budget, instead of being recorded
2439    /// as a stop. Such a module is usually a stock program that exits 0 on
2440    /// SIGTERM, so a stray outside signal would otherwise leave it down for
2441    /// good; a subc-wire module re-raises SIGTERM instead, so this rule is not
2442    /// needed for it.
2443    None,
2444}
2445
2446/// A supervised module's current state and process observations.
2447///
2448/// Use [`SupervisorEntry::new`] and its `with_*` methods to construct entries so
2449/// future fields do not require changes to callers.
2450/// Struct literals and functional record updates are not supported outside this crate:
2451///
2452/// ```compile_fail,E0639
2453/// use subc_control::{SupervisorEntry, SupervisorHealthStatus};
2454/// let entry = SupervisorEntry::new("provider", "running", true, true, SupervisorHealthStatus::Unknown);
2455/// let entry = SupervisorEntry { resources: None, ..entry };
2456/// ```
2457#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2458#[non_exhaustive]
2459pub struct SupervisorEntry {
2460    /// A hidden previous instance blocks only this module's next spawn. This
2461    /// PID is not the supervised child and must not be presented as its identity.
2462    #[serde(default, skip_serializing_if = "Option::is_none")]
2463    pub waiting_for_previous_pid: Option<u32>,
2464    pub module_id: String,
2465    pub state: String,
2466    /// Estimated Unix milliseconds of the next retry after restart-budget
2467    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
2468    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
2469    #[serde(default, skip_serializing_if = "Option::is_none")]
2470    pub next_retry_at_ms: Option<u64>,
2471    pub enabled: bool,
2472    /// The enabled value in the daemon's loaded configuration, not a stored
2473    /// drift flag. Absent when there is no configured entry or on older daemons.
2474    #[serde(default, skip_serializing_if = "Option::is_none")]
2475    pub configured_enabled: Option<bool>,
2476    /// Whether this module is serving.
2477    ///
2478    /// For a `Subc` module: enabled, running, process alive, AND registered.
2479    /// For a `None` module the registration term is dropped, because a module
2480    /// that speaks no subc wire never registers and the daemon cannot assert
2481    /// more than "the process it launched is alive". READ IT WITH `protocol`:
2482    /// `live: true` means something weaker for a `None` module, and a renderer
2483    /// that prints it as a bare boolean for one is claiming more than the daemon
2484    /// knows.
2485    pub live: bool,
2486    /// The module's declared wire protocol. Absent on daemons predating the
2487    /// field, where every module was a subc module, so the default is exactly
2488    /// what those daemons meant.
2489    #[serde(default)]
2490    pub protocol: ModuleProtocol,
2491    /// Retained for one release for older status consumers: false on Unix, true
2492    /// on Windows. Non-wire modules receive no nonce on either platform.
2493    #[serde(default, skip_serializing_if = "Option::is_none")]
2494    pub launch_nonce_env: Option<bool>,
2495    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
2496    /// process read all bytes, otherwise `env` for the offered environment copy.
2497    /// Returned in `supervisor.list`, independently of the source the module
2498    /// declares in `manifest.provenance.launch_nonce_source` when registering.
2499    /// Processes that do not speak the wire protocol and stopped modules omit it.
2500    #[serde(default, skip_serializing_if = "Option::is_none")]
2501    pub launch_nonce_source: Option<String>,
2502    pub health: SupervisorHealthStatus,
2503    /// Computed from the stored launch spec and observed process at list time;
2504    /// None means an older daemon did not report this comparison.
2505    #[serde(default, skip_serializing_if = "Option::is_none")]
2506    pub pending_reload: Option<PendingReloadVerdict>,
2507    /// When the daemon last collected this module's health, as unix
2508    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
2509    /// window, whose `health` is therefore `Unknown` rather than good), not
2510    /// probed-long-ago. An old value and an absent one call for opposite
2511    /// readings, so do not render them alike.
2512    #[serde(default)]
2513    pub last_probe_ms: Option<u64>,
2514    /// Exit code of the module's most recent process exit, if the process has
2515    /// exited at least once. Survives respawn so a now-`running` module still
2516    /// reports what killed its previous incarnation.
2517    #[serde(default, skip_serializing_if = "Option::is_none")]
2518    pub last_exit_code: Option<i32>,
2519    /// Terminating signal of the module's most recent process exit (Unix), if
2520    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
2521    /// (often a panic-abort). Survives respawn.
2522    #[serde(default, skip_serializing_if = "Option::is_none")]
2523    pub last_exit_signal: Option<i32>,
2524    /// Unix milliseconds when the most recent child exit was observed. Present
2525    /// even when the terminal ring is not queried, so existing list readers can
2526    /// order their latest observed exit against events they already received.
2527    #[serde(default, skip_serializing_if = "Option::is_none")]
2528    pub last_exit_ms: Option<u64>,
2529    /// Classification of the most recent child exit. Absent on daemons that
2530    /// predate exit-kind reporting.
2531    #[serde(default, skip_serializing_if = "Option::is_none")]
2532    pub last_exit_kind: Option<TerminalExitKind>,
2533    /// Replacement processes spawned for this module so far, against the budget
2534    /// that disables it.
2535    ///
2536    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
2537    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
2538    /// successful probe, so a module can miss probes all day and read zero; this
2539    /// one only decreases when an operator restarts, reloads, or re-enables the
2540    /// module. Reaching the budget moves it to `Failed` and it stays there until
2541    /// somebody intervenes.
2542    ///
2543    /// So a module one restart from being disabled is indistinguishable from a
2544    /// freshly booted one unless this pair is read. Both are reported together
2545    /// because the count alone does not say how close it is.
2546    ///
2547    /// Absent from daemons predating the field, which is why it is optional
2548    /// rather than defaulted to zero: zero would assert a full budget.
2549    #[serde(default, skip_serializing_if = "Option::is_none")]
2550    pub restart_count: Option<u32>,
2551    /// Replacement processes this module is allowed before it is disabled. See
2552    /// `restart_count`; absent on daemons predating the field.
2553    #[serde(default, skip_serializing_if = "Option::is_none")]
2554    pub max_restarts: Option<u32>,
2555    /// Replacement processes spawned over this module's entire supervisor lifetime.
2556    /// Unlike `restart_count`, this value is never reset by an operator action.
2557    #[serde(default, skip_serializing_if = "Option::is_none")]
2558    pub lifetime_restarts: Option<u32>,
2559    /// Successful child spawns in this daemon incarnation. Zero means the
2560    /// module has not successfully spawned; every successful spawn increments
2561    /// the value exactly once.
2562    #[serde(default, skip_serializing_if = "Option::is_none")]
2563    pub spawn_generation: Option<u64>,
2564    /// The span `restart_count` is counted over, in seconds. The crash budget is
2565    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
2566    /// inside the last `restart_window_secs`, and older ones no longer hold a
2567    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
2568    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
2569    /// reactions.
2570    ///
2571    /// Absent on daemons predating the windowed budget, where the count really
2572    /// was a lifetime total.
2573    #[serde(default, skip_serializing_if = "Option::is_none")]
2574    pub restart_window_secs: Option<u64>,
2575    /// Effective drain budget for this module, in milliseconds. This is the
2576    /// resolved policy the running supervisor uses, not a config-file reread.
2577    /// Absent on older daemons.
2578    #[serde(default, skip_serializing_if = "Option::is_none")]
2579    pub drain_timeout_ms: Option<u64>,
2580    /// Effective base delay before a crash restart, in milliseconds. Absent on
2581    /// older daemons.
2582    #[serde(default, skip_serializing_if = "Option::is_none")]
2583    pub restart_backoff_ms: Option<u64>,
2584    /// Effective maximum delay before a crash restart, in milliseconds. Absent
2585    /// on older daemons.
2586    #[serde(default, skip_serializing_if = "Option::is_none")]
2587    pub restart_max_backoff_ms: Option<u64>,
2588    /// Memory and cumulative CPU time of the module's process, read when this
2589    /// list was answered. Report only: the daemon keeps no history and acts on
2590    /// none of it.
2591    ///
2592    /// It describes the one process the supervisor spawned (its `pid`), not
2593    /// processes that one has started in turn, so a module that forks workers
2594    /// reports only its own share.
2595    ///
2596    /// Absent means the daemon predates the field. A daemon that has the field
2597    /// but could not read the process (not running, unsupported platform, read
2598    /// failed) says so with `Unavailable` and a reason, so neither case can be
2599    /// mistaken for a process using nothing.
2600    #[serde(default, skip_serializing_if = "Option::is_none")]
2601    pub resources: Option<ChildResourceUsage>,
2602    /// Cumulative CPU and current memory including child processes, when known.
2603    #[serde(default, skip_serializing_if = "Option::is_none")]
2604    pub tree: Option<TreeReading>,
2605    /// Why this reporting daemon has no tree reading for this response.
2606    /// `not_yet_measured` means this launch has no measurement; `unreadable`
2607    /// and `launch_changed` can accompany a retained, older tree. `not_running`
2608    /// marks a stopped module. Future reasons remain valid open-set strings.
2609    /// Absence alone does not establish tree support.
2610    #[serde(default, skip_serializing_if = "Option::is_none")]
2611    pub tree_unavailable: Option<String>,
2612    /// CPU used across the wall-clock interval covered by retained samples.
2613    #[serde(default, skip_serializing_if = "Option::is_none")]
2614    pub cpu_last_hour: Option<CpuLastHour>,
2615}
2616
2617impl SupervisorEntry {
2618    /// Set the estimated time of a failed module's next automatic retry.
2619    #[must_use]
2620    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2621        self.next_retry_at_ms = next_retry_at_ms;
2622        self
2623    }
2624
2625    /// Construct an entry with its required fields and wire-compatible defaults.
2626    #[must_use]
2627    pub fn new(
2628        module_id: impl Into<String>,
2629        state: impl Into<String>,
2630        enabled: bool,
2631        live: bool,
2632        health: SupervisorHealthStatus,
2633    ) -> Self {
2634        Self {
2635            module_id: module_id.into(),
2636            state: state.into(),
2637            next_retry_at_ms: None,
2638            waiting_for_previous_pid: None,
2639            enabled,
2640            configured_enabled: None,
2641            live,
2642            protocol: ModuleProtocol::default(),
2643            launch_nonce_env: None,
2644            launch_nonce_source: None,
2645            health,
2646            pending_reload: None,
2647            last_probe_ms: None,
2648            last_exit_code: None,
2649            last_exit_signal: None,
2650            last_exit_ms: None,
2651            last_exit_kind: None,
2652            restart_count: None,
2653            max_restarts: None,
2654            lifetime_restarts: None,
2655            spawn_generation: None,
2656            restart_window_secs: None,
2657            drain_timeout_ms: None,
2658            restart_backoff_ms: None,
2659            restart_max_backoff_ms: None,
2660            resources: None,
2661            tree: None,
2662            tree_unavailable: None,
2663            cpu_last_hour: None,
2664        }
2665    }
2666
2667    /// Set the module's declared wire protocol.
2668    #[must_use]
2669    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2670        self.protocol = protocol;
2671        self
2672    }
2673
2674    /// Attach the enabled value from the daemon's loaded configuration.
2675    #[must_use]
2676    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2677        self.configured_enabled = configured_enabled;
2678        self
2679    }
2680
2681    /// Set or clear the launch nonce environment indicator.
2682    #[must_use]
2683    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2684        self.launch_nonce_env = launch_nonce_env;
2685        self
2686    }
2687
2688    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2689        self.launch_nonce_source = source;
2690        self
2691    }
2692
2693    #[must_use]
2694    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2695        self.waiting_for_previous_pid = pid;
2696        self
2697    }
2698
2699    /// Set or clear the comparison between the launch spec and observed process.
2700    #[must_use]
2701    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2702        self.pending_reload = pending_reload;
2703        self
2704    }
2705
2706    /// Set or clear the last health collection timestamp.
2707    #[must_use]
2708    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2709        self.last_probe_ms = last_probe_ms;
2710        self
2711    }
2712
2713    /// Set or clear the most recent process exit code.
2714    #[must_use]
2715    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2716        self.last_exit_code = last_exit_code;
2717        self
2718    }
2719
2720    /// Set or clear the most recent process exit signal.
2721    #[must_use]
2722    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2723        self.last_exit_signal = last_exit_signal;
2724        self
2725    }
2726
2727    /// Set or clear the most recent process exit timestamp.
2728    #[must_use]
2729    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2730        self.last_exit_ms = last_exit_ms;
2731        self
2732    }
2733
2734    /// Set or clear the most recent process exit classification.
2735    #[must_use]
2736    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2737        self.last_exit_kind = last_exit_kind;
2738        self
2739    }
2740
2741    /// Set or clear the restart count for the current crash budget.
2742    #[must_use]
2743    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2744        self.restart_count = restart_count;
2745        self
2746    }
2747
2748    /// Set or clear the maximum restarts allowed by the crash budget.
2749    #[must_use]
2750    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2751        self.max_restarts = max_restarts;
2752        self
2753    }
2754
2755    /// Set or clear the lifetime restart count.
2756    #[must_use]
2757    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2758        self.lifetime_restarts = lifetime_restarts;
2759        self
2760    }
2761
2762    /// Set or clear the successful spawn count for this daemon incarnation.
2763    #[must_use]
2764    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2765        self.spawn_generation = spawn_generation;
2766        self
2767    }
2768
2769    /// Set or clear the time window of the crash budget.
2770    #[must_use]
2771    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2772        self.restart_window_secs = restart_window_secs;
2773        self
2774    }
2775
2776    /// Set or clear the effective drain budget in milliseconds.
2777    #[must_use]
2778    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2779        self.drain_timeout_ms = drain_timeout_ms;
2780        self
2781    }
2782
2783    /// Set or clear the effective base restart delay in milliseconds.
2784    #[must_use]
2785    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2786        self.restart_backoff_ms = restart_backoff_ms;
2787        self
2788    }
2789
2790    /// Set or clear the effective maximum restart delay in milliseconds.
2791    #[must_use]
2792    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2793        self.restart_max_backoff_ms = restart_max_backoff_ms;
2794        self
2795    }
2796
2797    /// Set or clear the observed resource usage of the supervised process.
2798    #[must_use]
2799    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2800        self.resources = resources;
2801        self
2802    }
2803
2804    /// Attach a report-only reading covering the module's process container.
2805    #[must_use]
2806    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2807        self.tree = tree;
2808        self
2809    }
2810
2811    /// Explain an absent tree reading without manufacturing numeric counters.
2812    #[must_use]
2813    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2814        self.tree_unavailable = reason;
2815        self
2816    }
2817}
2818
2819/// A module process's memory and CPU time as read at list time, or why none
2820/// could be read.
2821#[derive(Debug, Clone, PartialEq)]
2822pub enum ChildResourceUsage {
2823    Measured(ChildResourceReading),
2824    Unavailable {
2825        reason: ChildResourceUnavailableReason,
2826    },
2827    /// Future discriminator. `body` retains the complete ordered object; `tag`
2828    /// is its decoded discriminator projection.
2829    Unknown {
2830        tag: String,
2831        body: OrderedJsonObject,
2832    },
2833}
2834
2835/// One reading of a module process's memory and CPU time.
2836/// Use [`ChildResourceReading::new`] and its builders so future fields stay additive.
2837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2838#[non_exhaustive]
2839pub struct ChildResourceReading {
2840    /// Memory in bytes, measured as `memory_kind` says. The figures differ
2841    /// by platform and are not comparable across kinds.
2842    pub memory_bytes: u64,
2843    pub memory_kind: ChildMemoryKind,
2844    /// Bytes swapped out, where the platform reports it per process (Linux).
2845    /// Absent means not reported, not zero.
2846    #[serde(default, skip_serializing_if = "Option::is_none")]
2847    pub swap_bytes: Option<u64>,
2848    /// CPU time spent in user mode since the process started, in
2849    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
2850    /// and the elapsed time between them.
2851    pub cpu_user_ms: u64,
2852    /// CPU time spent in the kernel on the process's behalf since it started,
2853    /// in milliseconds.
2854    pub cpu_system_ms: u64,
2855}
2856
2857impl ChildResourceReading {
2858    /// Create a process reading without optional swap accounting.
2859    #[must_use]
2860    pub fn new(
2861        memory_bytes: u64,
2862        memory_kind: ChildMemoryKind,
2863        cpu_user_ms: u64,
2864        cpu_system_ms: u64,
2865    ) -> Self {
2866        Self {
2867            memory_bytes,
2868            memory_kind,
2869            cpu_user_ms,
2870            cpu_system_ms,
2871            swap_bytes: None,
2872        }
2873    }
2874
2875    /// Set or clear swap bytes where the platform can measure them.
2876    #[must_use]
2877    pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
2878        self.swap_bytes = swap_bytes;
2879        self
2880    }
2881}
2882
2883open_string_enum! {
2884    /// What `ChildResourceReading::memory_bytes` measures.
2885    ChildMemoryKind {
2886        /// macOS `phys_footprint`: memory the kernel charges to the process,
2887        /// the figure jetsam acts on. Unlike resident size it does not count
2888        /// pages an allocator has already released with `MADV_FREE`.
2889        PhysFootprint => "phys_footprint",
2890        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
2891        /// included and swapped-out pages excluded.
2892        ResidentSet => "resident_set",
2893        /// Windows `WorkingSetSize`: resident pageable memory, including shared
2894        /// pages, not Unix RSS or private committed bytes.
2895        WindowsWorkingSet => "windows_working_set",
2896    }
2897}
2898
2899open_string_enum! {
2900    /// Why a module process's resources could not be read.
2901    ChildResourceUnavailableReason {
2902        /// The module has no running process.
2903        NotRunning => "not_running",
2904        /// The daemon's platform has no per-process source.
2905        UnsupportedPlatform => "unsupported_platform",
2906        /// The process could not be read, typically because it exited while
2907        /// the list was being answered.
2908        Unreadable => "unreadable",
2909        /// The pid no longer names the process the supervisor spawned, so a
2910        /// reading would describe some other process.
2911        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2912    }
2913}
2914
2915#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2916#[serde(rename_all = "snake_case")]
2917pub enum SupervisorHealthStatus {
2918    Ok,
2919    Degraded,
2920    Failing,
2921    Unresponsive,
2922    Unknown,
2923}
2924
2925#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2926pub struct SupervisorHealthEntry {
2927    pub module_id: String,
2928    pub status: SupervisorHealthStatus,
2929    /// The module's own human-readable note on its state. Absent means the
2930    /// module said nothing, which is the ordinary shape for a healthy module and
2931    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
2932    /// module may reword freely, and `status` plus `metrics` are the machine
2933    /// surface.
2934    #[serde(default, skip_serializing_if = "Option::is_none")]
2935    pub detail: Option<String>,
2936    /// The module's own metrics object, relayed opaquely. Absent means the module
2937    /// published none on this probe — either it reports no metrics at all, or the
2938    /// probe did not reach it — so absence cannot distinguish "nothing to report"
2939    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
2940    #[serde(default, skip_serializing_if = "Option::is_none")]
2941    pub metrics: Option<serde_json::Value>,
2942    pub consecutive_failures: u32,
2943    /// Number of recurring health replies received after their daemon deadline.
2944    /// Each increment is evidence that the module remained alive despite a miss.
2945    #[serde(default)]
2946    pub late_answer_count: u64,
2947    /// End-to-end latency of the newest late reply, measured from probe start.
2948    #[serde(default, skip_serializing_if = "Option::is_none")]
2949    pub last_late_answer_latency_ms: Option<u64>,
2950    /// The escalation the supervisor last took for this module (report, restart,
2951    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
2952    /// succeeded — a module that has never misbehaved and one whose action record
2953    /// predates a daemon restart both present as absent.
2954    #[serde(default)]
2955    pub last_action: Option<String>,
2956    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
2957    /// `last_action` is absent; the pair moves together.
2958    #[serde(default)]
2959    pub last_action_ms: Option<u64>,
2960    /// When the daemon last collected this entry, as unix milliseconds.
2961    ///
2962    /// `supervisor.health` answers from the supervisor's STORED record rather
2963    /// than probing, so every field above describes some moment in the past and
2964    /// nothing here said which. That matters most right after a restart, where
2965    /// the surface is used to confirm a deploy: a record collected before the
2966    /// restart reports the OLD process, reads as a failed deploy, and invites a
2967    /// redeploy of something that was already correct.
2968    ///
2969    /// `None` means never probed — distinct from probed-long-ago, and the reader
2970    /// must not collapse them. Absent on modules that advertise no health
2971    /// capability, which is why it is optional rather than defaulted to zero.
2972    #[serde(default, skip_serializing_if = "Option::is_none")]
2973    pub last_probe_ms: Option<u64>,
2974}
2975
2976#[cfg(test)]
2977mod tests {
2978    #[test]
2979    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2980        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2981        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2982        assert_eq!(decoded.configured_enabled, None);
2983        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2984    }
2985
2986    #[test]
2987    fn configured_enabled_values_round_trip_in_list() {
2988        for enabled in [false, true] {
2989            let entry = SupervisorEntry::new(
2990                "provider",
2991                "running",
2992                true,
2993                true,
2994                SupervisorHealthStatus::Unknown,
2995            )
2996            .with_configured_enabled(Some(enabled));
2997            let entry_json = serde_json::to_value(&entry).unwrap();
2998            assert_eq!(entry_json["configured_enabled"], enabled);
2999            assert_eq!(
3000                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3001                entry
3002            );
3003        }
3004    }
3005
3006    #[test]
3007    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3008        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3009            volume_serial_number: u64::MAX,
3010            file_id: [
3011                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3012            ],
3013        };
3014        let agreement = super::RunningImageAgreement::Match { evidence };
3015        let encoded = serde_json::to_string(&agreement).unwrap();
3016        assert!(encoded.contains("windows_spawn_file_id"));
3017        assert_eq!(
3018            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3019            agreement
3020        );
3021    }
3022
3023    #[test]
3024    fn unix_running_image_evidence_keeps_original_wire_bytes() {
3025        assert_eq!(
3026            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3027                device: 7,
3028                inode: 11
3029            })
3030            .unwrap(),
3031            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3032        );
3033        assert_eq!(
3034            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3035                digest: "abc".to_owned()
3036            })
3037            .unwrap(),
3038            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3039        );
3040    }
3041    use super::*;
3042    use subc_protocol::{BindIdentity, RouteTarget};
3043
3044    #[test]
3045    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3046        let entry = TerminalEntry {
3047            daemon_incarnation: Some("daemon-before-restart".into()),
3048            exit_code: Some(1),
3049            exit_signal: None,
3050            at_ms: 1_700_000_000_123,
3051            disposition: TerminalDisposition::Restarting,
3052            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3053            disposition_detail: None,
3054        };
3055        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3056        assert_eq!(
3057            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3058                ["exit_kind"],
3059            "deliberate_severance"
3060        );
3061
3062        #[derive(serde::Deserialize)]
3063        struct LegacyTerminalEntry {
3064            exit_code: Option<i32>,
3065            exit_signal: Option<i32>,
3066            at_ms: u64,
3067            disposition: TerminalDisposition,
3068        }
3069
3070        let decoded: LegacyTerminalEntry =
3071            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3072        assert_eq!(decoded.exit_code, Some(1));
3073        assert_eq!(decoded.exit_signal, None);
3074        assert_eq!(decoded.at_ms, 1_700_000_000_123);
3075        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3076
3077        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3078        let future: TerminalEntry =
3079            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3080        assert_eq!(
3081            future.exit_kind,
3082            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3083        );
3084    }
3085
3086    #[test]
3087    fn terminal_incarnation_is_optional_for_older_daemons() {
3088        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3089            "at_ms": 123,
3090            "disposition": "stopped"
3091        }))
3092        .unwrap();
3093        let encoded = serde_json::to_value(&entry).unwrap();
3094        assert_eq!(
3095            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3096            (None, None)
3097        );
3098    }
3099
3100    #[test]
3101    fn route_poll_uses_kind_field() {
3102        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3103            route_channel: 7,
3104            route_epoch: 11,
3105            kind: PollKind::Status,
3106        })
3107        .unwrap();
3108
3109        assert_eq!(body["op"], "route.poll");
3110        assert_eq!(body["route_epoch"], 11);
3111        assert_eq!(body["kind"], "status");
3112        assert!(body.get("op").is_some());
3113    }
3114
3115    #[test]
3116    fn route_open_is_internally_tagged() {
3117        let request = ClientControlRequest::RouteOpen {
3118            busy_refusals: None,
3119            target: RouteTarget::ToolProvider {
3120                module_id: "aft".to_string(),
3121            },
3122            identity: BindIdentity::new("opencode", "session-1"),
3123            consumer_identity: None,
3124            consumer_capabilities: None,
3125            role_versions: None,
3126            admission_facts: None,
3127            scope: None,
3128        };
3129
3130        let body = serde_json::to_value(request).unwrap();
3131        assert_eq!(body["op"], "route.open");
3132        assert_eq!(body["target"]["kind"], "tool_provider");
3133        assert!(body.get("consumer_identity").is_none());
3134        assert!(body.get("consumer_capabilities").is_none());
3135        assert!(body.get("role_versions").is_none());
3136    }
3137
3138    #[test]
3139    fn route_open_without_optional_fields_still_decodes() {
3140        let body = serde_json::json!({
3141            "op": "route.open",
3142            "target": { "kind": "tool_provider", "module_id": "aft" },
3143            "identity": {
3144                "project_root": "/tmp/project",
3145                "harness": "opencode",
3146                "session": "session-1"
3147            }
3148        });
3149
3150        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3151        let ClientControlRequest::RouteOpen {
3152            consumer_identity,
3153            consumer_capabilities,
3154            role_versions,
3155            admission_facts,
3156            ..
3157        } = decoded
3158        else {
3159            panic!("decoded wrong request variant");
3160        };
3161        assert_eq!(consumer_identity, None);
3162        assert_eq!(consumer_capabilities, None);
3163        assert_eq!(role_versions, None);
3164        assert_eq!(admission_facts, None);
3165    }
3166
3167    #[test]
3168    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3169        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3170        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3171        match decoded {
3172            ClientControlPush::RouteClosed {
3173                excluded_subscriptions,
3174                terminal,
3175                ..
3176            } => {
3177                assert_eq!(excluded_subscriptions, 0);
3178                assert_eq!(terminal, None);
3179            }
3180            other => panic!("unexpected push: {other:?}"),
3181        }
3182        assert!(!serde_json::to_string(&decoded)
3183            .unwrap()
3184            .contains("terminal"));
3185    }
3186
3187    #[test]
3188    fn old_route_closed_decoder_ignores_new_terminal_field() {
3189        #[derive(serde::Deserialize)]
3190        #[serde(tag = "op")]
3191        enum LegacyClientControlPush {
3192            #[serde(rename = "route.closed")]
3193            RouteClosed {
3194                module_id: String,
3195                reason: RouteCloseReason,
3196                drained: bool,
3197                abandoned: u32,
3198            },
3199        }
3200
3201        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3202        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3203        match decoded {
3204            LegacyClientControlPush::RouteClosed {
3205                module_id,
3206                reason,
3207                drained,
3208                abandoned,
3209            } => {
3210                assert_eq!(module_id, "aft-tools");
3211                assert_eq!(reason, RouteCloseReason::Crash);
3212                assert!(!drained);
3213                assert_eq!(abandoned, 0);
3214            }
3215        }
3216    }
3217
3218    #[test]
3219    fn supervisor_routes_is_a_control_plane_request() {
3220        let body = serde_json::json!({
3221            "op": "supervisor.routes",
3222            "module_id": "aft"
3223        });
3224
3225        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3226        assert_eq!(serde_json::to_value(request).unwrap(), body);
3227    }
3228
3229    #[test]
3230    fn diagnostic_string_enums_retain_unknown_wire_values() {
3231        let reason: RunningImageUnavailableReason =
3232            serde_json::from_str("\"future_reason\"").unwrap();
3233        let disposition: TerminalDisposition =
3234            serde_json::from_str("\"future_disposition\"").unwrap();
3235
3236        assert_eq!(
3237            reason,
3238            RunningImageUnavailableReason::Unknown("future_reason".to_string())
3239        );
3240        assert_eq!(
3241            disposition,
3242            TerminalDisposition::Unknown("future_disposition".to_string())
3243        );
3244    }
3245
3246    #[test]
3247    fn diagnostic_string_enums_preserve_existing_wire_names() {
3248        let names = [
3249            (RunningImageUnavailableReason::NotRunning, "not_running"),
3250            (
3251                RunningImageUnavailableReason::UnsupportedPlatform,
3252                "unsupported_platform",
3253            ),
3254            (
3255                RunningImageUnavailableReason::RunningExecutableUnreadable,
3256                "running_executable_unreadable",
3257            ),
3258            (
3259                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3260                "running_executable_permission_denied",
3261            ),
3262            (
3263                RunningImageUnavailableReason::ProcessHidden,
3264                "process_hidden",
3265            ),
3266            (
3267                RunningImageUnavailableReason::SpawnedPathUnreadable,
3268                "spawned_path_unreadable",
3269            ),
3270            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3271            (
3272                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3273                "process_identity_unconfirmed",
3274            ),
3275        ];
3276        for (value, expected) in names {
3277            let wire = serde_json::to_string(&value).unwrap();
3278            assert_eq!(wire, format!("\"{expected}\""));
3279            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3280            assert_eq!(decoded, value);
3281        }
3282
3283        for (value, expected) in [
3284            (TerminalDisposition::Stopped, "stopped"),
3285            (TerminalDisposition::Disabled, "disabled"),
3286            (TerminalDisposition::Failed, "failed"),
3287            (TerminalDisposition::Restarting, "restarting"),
3288            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3289        ] {
3290            let wire = serde_json::to_string(&value).unwrap();
3291            assert_eq!(wire, format!("\"{expected}\""));
3292            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3293            assert_eq!(decoded, value);
3294        }
3295    }
3296
3297    #[test]
3298    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3299        let entry = SupervisorEntry::new(
3300            "waiting-module",
3301            "starting",
3302            true,
3303            false,
3304            SupervisorHealthStatus::Unknown,
3305        );
3306        let old_wire = serde_json::to_value(&entry).unwrap();
3307        assert!(old_wire.get("waiting_for_previous_pid").is_none());
3308        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3309        assert_eq!(decoded.waiting_for_previous_pid, None);
3310        let entry = entry.with_waiting_for_previous_pid(Some(42));
3311        let wire = serde_json::to_value(&entry).unwrap();
3312        assert_eq!(wire["waiting_for_previous_pid"], 42);
3313        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3314        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3315    }
3316
3317    #[test]
3318    fn diagnostic_string_enums_reject_non_string_bodies() {
3319        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3320        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3321    }
3322
3323    #[test]
3324    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3325        let body = serde_json::json!({
3326            "op": "supervisor.provenance",
3327            "daemon": {
3328                "daemon_build": {},
3329                "daemon_observed": {
3330                    "running_image": {
3331                        "status": "unavailable",
3332                        "reason": "not_running"
3333                    }
3334                }
3335            },
3336            "modules": [
3337                {
3338                    "module_id": "future",
3339                    "module_declared": { "status": "unverifiable" },
3340                    "daemon_observed": {
3341                        "running_image": {
3342                            "status": "unavailable",
3343                            "reason": "future_reason"
3344                        }
3345                    }
3346                },
3347                {
3348                    "module_id": "healthy-a",
3349                    "module_declared": { "status": "unverifiable" },
3350                    "daemon_observed": {
3351                        "running_image": {
3352                            "status": "match",
3353                            "evidence": {
3354                                "method": "linux_proc_sha256",
3355                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3356                            }
3357                        }
3358                    }
3359                },
3360                {
3361                    "module_id": "healthy-b",
3362                    "module_declared": { "status": "unverifiable" },
3363                    "daemon_observed": {
3364                        "running_image": {
3365                            "status": "unavailable",
3366                            "reason": "unsupported_platform"
3367                        }
3368                    }
3369                }
3370            ]
3371        });
3372
3373        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3374        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3375            panic!("decoded wrong response variant");
3376        };
3377        assert_eq!(modules.len(), 3);
3378        assert_eq!(modules[0].module_id, "future");
3379        assert_eq!(
3380            modules[0].daemon_observed.running_image,
3381            RunningImageAgreement::Unavailable {
3382                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3383            }
3384        );
3385        assert_eq!(modules[1].module_id, "healthy-a");
3386        assert_eq!(modules[2].module_id, "healthy-b");
3387    }
3388
3389    #[test]
3390    fn tagged_unknown_values_retain_tag_and_body() {
3391        macro_rules! assert_unknown_round_trip {
3392            ($ty:ident, $field:literal, $value:expr) => {
3393                let value = $value;
3394                let wire = serde_json::to_string(&value).unwrap();
3395                let decoded: $ty = serde_json::from_str(&wire).unwrap();
3396                match decoded {
3397                    $ty::Unknown { tag, body } => {
3398                        assert_eq!(tag, value[$field].as_str().unwrap());
3399                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
3400                    }
3401                    _ => panic!("decoded known variant"),
3402                }
3403            };
3404        }
3405
3406        assert_unknown_round_trip!(
3407            ModuleDeclaredProvenance,
3408            "status",
3409            serde_json::json!({"status": "future", "build": {"version": 7}})
3410        );
3411        assert_unknown_round_trip!(
3412            RunningImageAgreement,
3413            "status",
3414            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3415        );
3416        assert_unknown_round_trip!(
3417            RunningImageEvidence,
3418            "method",
3419            serde_json::json!({"method": "future", "digest": "abc"})
3420        );
3421        assert_unknown_round_trip!(
3422            SupervisorRouteConsumer,
3423            "kind",
3424            serde_json::json!({"kind": "future", "module_id": "m"})
3425        );
3426        assert_unknown_round_trip!(
3427            StderrCaptureState,
3428            "state",
3429            serde_json::json!({"state": "future", "reason": "because"})
3430        );
3431        assert_unknown_round_trip!(
3432            StderrTailEntry,
3433            "kind",
3434            serde_json::json!({"kind": "future", "text": "line"})
3435        );
3436        assert_unknown_round_trip!(
3437            ChildResourceUsage,
3438            "status",
3439            serde_json::json!({"status": "future", "memory_bytes": 1})
3440        );
3441    }
3442
3443    #[test]
3444    fn child_resource_usage_round_trips_both_known_states() {
3445        let measured = ChildResourceUsage::Measured(ChildResourceReading {
3446            memory_bytes: 0,
3447            memory_kind: ChildMemoryKind::ResidentSet,
3448            swap_bytes: Some(0),
3449            cpu_user_ms: 0,
3450            cpu_system_ms: 0,
3451        });
3452        let wire = serde_json::to_value(&measured).unwrap();
3453        assert_eq!(
3454            wire,
3455            serde_json::json!({
3456                "status": "measured",
3457                "memory_bytes": 0,
3458                "memory_kind": "resident_set",
3459                "swap_bytes": 0,
3460                "cpu_user_ms": 0,
3461                "cpu_system_ms": 0
3462            })
3463        );
3464        assert_eq!(
3465            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3466            measured
3467        );
3468
3469        let unavailable = ChildResourceUsage::Unavailable {
3470            reason: ChildResourceUnavailableReason::NotRunning,
3471        };
3472        let wire = serde_json::to_value(&unavailable).unwrap();
3473        assert_eq!(
3474            wire,
3475            serde_json::json!({"status": "unavailable", "reason": "not_running"})
3476        );
3477        assert_eq!(
3478            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3479            unavailable
3480        );
3481    }
3482
3483    #[test]
3484    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3485        // A current daemon stamps each line; an older one sends no `at_ms`.
3486        // Both must decode, and the absent case must stay absent rather than
3487        // turn into a time nobody recorded.
3488        let stamped: StderrTailEntry = serde_json::from_str(
3489            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3490        )
3491        .unwrap();
3492        assert_eq!(
3493            stamped,
3494            StderrTailEntry::Line {
3495                text: "boom".to_string(),
3496                truncated: true,
3497                at_ms: Some(1_789_801_440_685),
3498            }
3499        );
3500        let unstamped: StderrTailEntry =
3501            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3502        assert_eq!(
3503            unstamped,
3504            StderrTailEntry::Line {
3505                text: "boom".to_string(),
3506                truncated: false,
3507                at_ms: None,
3508            }
3509        );
3510        // Absent stays absent on the way out, so a reply without stamps is
3511        // exactly what an older daemon would have sent.
3512        assert_eq!(
3513            serde_json::to_string(&unstamped).unwrap(),
3514            r#"{"kind":"line","text":"boom"}"#
3515        );
3516        assert_eq!(
3517            serde_json::to_value(&stamped).unwrap()["at_ms"],
3518            serde_json::json!(1_789_801_440_685u64)
3519        );
3520    }
3521
3522    #[test]
3523    fn tagged_unknown_values_round_trip_the_original_json() {
3524        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3525        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3526        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3527    }
3528
3529    #[test]
3530    fn tagged_unknown_values_round_trip_trailing_tag() {
3531        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3532        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3533        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3534
3535        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3536        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3537        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3538    }
3539
3540    #[test]
3541    fn tagged_unknown_values_round_trip_middle_tag() {
3542        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3543        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3544        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3545
3546        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3547        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3548        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3549    }
3550
3551    #[test]
3552    fn tagged_unknown_values_round_trip_deep_payload() {
3553        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3554        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3555        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3556
3557        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3558        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3559        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3560    }
3561
3562    #[test]
3563    fn tagged_unknown_values_reject_non_object_bodies() {
3564        for wire in ["42", r#""future""#, "[]"] {
3565            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3566            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3567        }
3568    }
3569
3570    #[test]
3571    fn duplicate_discriminators_reject_without_panicking() {
3572        assert_eq!(
3573            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3574                .unwrap(),
3575            ModuleDeclaredProvenance::Unverifiable
3576        );
3577        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3578            .unwrap()
3579        {
3580            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3581            _ => panic!("future discriminator decoded as a known variant"),
3582        }
3583
3584        let wires = [
3585            r#"{"status":"reported","status":"unverifiable"}"#,
3586            r#"{"status":"unverifiable","status":"reported"}"#,
3587            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3588            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3589        ];
3590
3591        for wire in wires {
3592            let result =
3593                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3594            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3595            assert!(
3596                result.unwrap().is_err(),
3597                "duplicate discriminator decoded: {wire}"
3598            );
3599        }
3600
3601        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3602        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3603        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3604        assert!(
3605            result.unwrap().is_err(),
3606            "duplicate discriminator decoded: {wire}"
3607        );
3608    }
3609
3610    #[test]
3611    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3612        let known_wire =
3613            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3614        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3615        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3616
3617        for wire in [
3618            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3619            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3620        ] {
3621            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3622            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3623        }
3624
3625        for wire in [
3626            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3627            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3628        ] {
3629            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3630            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3631        }
3632
3633        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3634        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3635        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3636
3637        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3638        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3639        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3640    }
3641
3642    #[test]
3643    fn tagged_unknown_member_does_not_discard_known_siblings() {
3644        let body = serde_json::json!({
3645            "modules": [{
3646                "module_id": "target",
3647                "routes": [
3648                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3649                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3650                ]
3651            }]
3652        });
3653        let decoded: ClientControlResponse = serde_json::from_value(
3654            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3655        )
3656        .unwrap();
3657        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3658            panic!("decoded wrong response variant");
3659        };
3660        assert_eq!(modules[0].routes.len(), 2);
3661        assert_eq!(
3662            modules[0].routes[1].consumer,
3663            SupervisorRouteConsumer::Direct { connection_id: 7 }
3664        );
3665    }
3666}
3667
3668#[cfg(test)]
3669mod launch_nonce_redaction_tests {
3670    use super::*;
3671
3672    const NONCE: &str = "nonce-f00dfeed1234abcd";
3673
3674    fn identity() -> ConsumerIdentity {
3675        ConsumerIdentity {
3676            module_id: "wernicke".to_string(),
3677            launch_nonce: NONCE.to_string(),
3678        }
3679    }
3680
3681    #[test]
3682    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3683        let printed = format!("{:?}", identity());
3684        assert!(printed.contains("wernicke"), "{printed}");
3685        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3686    }
3687
3688    #[test]
3689    fn route_open_request_debug_never_prints_the_nonce() {
3690        let request = ClientControlRequest::RouteOpen {
3691            busy_refusals: None,
3692            target: subc_protocol::RouteTarget::ToolProvider {
3693                module_id: "broca".to_string(),
3694            },
3695            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3696            consumer_identity: Some(identity()),
3697            consumer_capabilities: None,
3698            role_versions: None,
3699            admission_facts: None,
3700            scope: None,
3701        };
3702        let printed = format!("{request:?}");
3703        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3704    }
3705}