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    /// Management operations the module guards with `operator.confirm`,
2125    /// mirrored unchanged from its manifest. Absent means the module did not
2126    /// say (or declared an invalid list, which the daemon dropped), so a reader
2127    /// treats the answer as unknown. Absence preserves catalog bytes from before
2128    /// the field. The daemon relays it and refuses nothing on its basis.
2129    #[serde(default, skip_serializing_if = "Option::is_none")]
2130    pub confirm_operations: Option<Vec<String>>,
2131    /// Rich-UI descriptor mirrored verbatim from the registering manifest.
2132    /// The daemon does not fetch or interpret the manifest described here.
2133    #[serde(default, skip_serializing_if = "Option::is_none")]
2134    pub rich_ui: Option<RichUiDescriptor>,
2135    /// Opaque per-role objects mirrored unchanged from the registered manifest.
2136    /// Each role owns its schema; the daemon validates only keys, shape and size.
2137    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2138    pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2139    /// True only when HELLO passes the launch-nonce check required for a reserved
2140    /// module or swap candidate.
2141    #[serde(default, skip_serializing_if = "is_false")]
2142    pub nonce_verified: bool,
2143}
2144
2145impl CatalogEntry {
2146    /// Sets the optional module-declared display name.
2147    #[must_use]
2148    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2149        self.display_name = display_name;
2150        self
2151    }
2152
2153    /// Construct an entry with its required fields and wire-compatible defaults.
2154    #[must_use]
2155    pub fn new(
2156        module_id: impl Into<String>,
2157        roles: Vec<ProviderRole>,
2158        control_ops: Vec<String>,
2159    ) -> Self {
2160        Self {
2161            module_id: module_id.into(),
2162            ready: default_true(),
2163            display_name: None,
2164            not_ready: None,
2165            module_version: None,
2166            provenance: None,
2167            roles,
2168            control_ops,
2169            capabilities: None,
2170            self_signals: None,
2171            events: None,
2172            operation_delivery: BTreeMap::new(),
2173            operation_payload: BTreeMap::new(),
2174            flow_operations: None,
2175            confirm_operations: None,
2176            rich_ui: None,
2177            role_declarations: BTreeMap::new(),
2178            nonce_verified: false,
2179        }
2180    }
2181
2182    /// Set raw request payload limits mirrored from the registered manifest.
2183    #[must_use]
2184    pub fn with_operation_payload(
2185        mut self,
2186        operation_payload: BTreeMap<String, OperationPayload>,
2187    ) -> Self {
2188        self.operation_payload = operation_payload;
2189        self
2190    }
2191
2192    /// Set or clear the flow-scoped operation list mirrored from the registered
2193    /// manifest. `None` is omitted from the wire.
2194    #[must_use]
2195    pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2196        self.flow_operations = flow_operations;
2197        self
2198    }
2199
2200    /// Set or clear the confirm-guarded operation list mirrored from the
2201    /// registered manifest. `None` is omitted from the wire.
2202    #[must_use]
2203    pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2204        self.confirm_operations = confirm_operations;
2205        self
2206    }
2207
2208    /// Set the module's effective readiness.
2209    #[must_use]
2210    pub fn with_ready(mut self, ready: bool) -> Self {
2211        self.ready = ready;
2212        self
2213    }
2214
2215    /// Set or clear the reason the module is not ready.
2216    #[must_use]
2217    pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2218        self.not_ready = not_ready;
2219        self
2220    }
2221
2222    /// Set or clear the module's self-declared version.
2223    #[must_use]
2224    pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2225        self.module_version = module_version;
2226        self
2227    }
2228
2229    /// Set or clear the build provenance mirrored from the registered manifest.
2230    #[must_use]
2231    pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2232        self.provenance = provenance;
2233        self
2234    }
2235
2236    /// Set or clear the module's static capability declarations.
2237    #[must_use]
2238    pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2239        self.capabilities = capabilities;
2240        self
2241    }
2242
2243    /// Set or clear the module's self-signal declarations.
2244    #[must_use]
2245    pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2246        self.self_signals = self_signals;
2247        self
2248    }
2249
2250    /// Set or clear the event declarations mirrored from the module manifest.
2251    #[must_use]
2252    pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2253        self.events = events;
2254        self
2255    }
2256
2257    /// Set delivery hints mirrored from the module manifest.
2258    /// Serialization omits this field when the stored map is empty.
2259    #[must_use]
2260    pub fn with_operation_delivery(
2261        mut self,
2262        operation_delivery: BTreeMap<String, OperationDelivery>,
2263    ) -> Self {
2264        self.operation_delivery = operation_delivery;
2265        self
2266    }
2267
2268    /// Set the descriptor mirrored from the module's HELLO manifest.
2269    #[must_use]
2270    pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2271        self.rich_ui = rich_ui;
2272        self
2273    }
2274
2275    /// Set opaque per-role declarations mirrored from the registered manifest.
2276    #[must_use]
2277    pub fn with_role_declarations(
2278        mut self,
2279        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2280    ) -> Self {
2281        self.role_declarations = role_declarations;
2282        self
2283    }
2284
2285    /// Mark a registration as nonce-verified when HELLO passes the launch-nonce
2286    /// check required for a reserved module or swap candidate.
2287    #[must_use]
2288    pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2289        self.nonce_verified = nonce_verified;
2290        self
2291    }
2292}
2293
2294fn is_false(value: &bool) -> bool {
2295    !value
2296}
2297
2298/// Why a registered module is not accepting new route binds.
2299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2300pub struct NotReadyReason {
2301    /// `declared_not_ready` when the module itself said it is not ready, or
2302    /// `required_capability_unprovided` when a capability it declares
2303    /// `need: required` has no registered provider. Open vocabulary: a newer
2304    /// daemon may add reasons.
2305    pub reason: String,
2306    /// For `required_capability_unprovided`, the lexicographically first
2307    /// required capability that has no registered provider.
2308    #[serde(default, skip_serializing_if = "Option::is_none")]
2309    pub capability: Option<String>,
2310}
2311
2312impl NotReadyReason {
2313    pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2314    pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2315}
2316
2317#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2318pub struct CapabilityRequirementStatus {
2319    pub consumer: String,
2320    pub capability: String,
2321    pub need: String,
2322    pub verdict: String,
2323    pub episode_seq: u64,
2324    pub config_satisfiable: bool,
2325    pub runtime_available: bool,
2326    pub detail: String,
2327}
2328
2329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2330pub struct SupervisorRescanResult {
2331    pub added: Vec<String>,
2332    pub removed: Vec<String>,
2333    pub changed_pending_reload: Vec<String>,
2334    /// Modules whose enabled flag differs between config and running state.
2335    ///
2336    /// Rescan calls `set_enabled` for these, so omitting them made the preview
2337    /// describe two of the three mutation classes it performs. A module changing
2338    /// only its enabled flag landed in no bucket at all -- not added, removed or
2339    /// changed, and deliberately not counted as unchanged either -- so the sole
2340    /// evidence was that the buckets no longer summed to the configured module
2341    /// count. A preview is consulted precisely when someone is being careful,
2342    /// which is the worst place to under-report.
2343    ///
2344    /// Empty is skipped so consumers written against the older shape keep
2345    /// parsing.
2346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2347    pub enabled_changes: Vec<String>,
2348    pub unchanged: u32,
2349    /// True when this reconciliation was computed but NOT applied.
2350    ///
2351    /// Carried on the result rather than left to the caller's memory of what it
2352    /// asked for. A preview and an execution are otherwise byte-identical, so a
2353    /// reader who meets this output later -- in a log, a transcript, a pasted
2354    /// snippet -- cannot tell which one happened. Absent when false, so existing
2355    /// consumers see the shape they already parse.
2356    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2357    pub preview: bool,
2358    /// Config sections that changed but which rescan CANNOT apply, so the
2359    /// operator learns a daemon restart is required from the command they just
2360    /// ran rather than from the journal.
2361    ///
2362    /// The daemon has always detected this and logged a warning. A warning in a
2363    /// log is addressed to whoever is reading the log, and the person who just
2364    /// edited the config is by construction looking at the CLI instead: reported
2365    /// by an outside contributor after a module crash-looped through four
2366    /// respawns because a new top-level `storage` section was silently not
2367    /// applied, diagnosable only by journal archaeology.
2368    ///
2369    /// Names the SECTIONS rather than a boolean, because "something else
2370    /// changed" sends the operator back to diffing their own file -- which is
2371    /// the work the message exists to save.
2372    ///
2373    /// Empty is skipped, so consumers written against the older shape keep
2374    /// parsing.
2375    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2376    pub restart_required: Vec<String>,
2377    /// Required capabilities that a dry-run's resulting module set would leave
2378    /// unprovided. Rows are human-readable because the preview is an operator
2379    /// explanation, not a second manifest schema.
2380    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2381    pub capability_warnings: Vec<String>,
2382    /// What applying the previewed candidate would do to each module, in
2383    /// module id order. Filled only by a `supervisor.rescan_checked` preview;
2384    /// a module whose launch spec, health policy and enabled flag all stay as
2385    /// staged has no entry, and neither has a disabled module that is added
2386    /// or removed. Empty is skipped, so `supervisor.rescan` replies keep their
2387    /// shape.
2388    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2389    pub module_actions: Vec<RescanModuleAction>,
2390    /// Modules whose running process still uses launch inputs from an earlier
2391    /// rescan: their staged spec waits for a restart that this candidate
2392    /// does not cause. Filled only by a `supervisor.rescan_checked` preview.
2393    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2394    pub earlier_pending: Vec<String>,
2395    /// The value an apply of this preview must send. Present only on a
2396    /// `supervisor.rescan_checked` preview.
2397    #[serde(default, skip_serializing_if = "Option::is_none")]
2398    pub expect: Option<RescanExpect>,
2399}
2400
2401/// Which wire protocol a supervised module speaks to subc, as DECLARED in
2402/// daemon config. Never inferred from observed behaviour.
2403///
2404/// The distinction this exists to keep is between a module that should have
2405/// registered and has not yet, and one that never will. A `Subc` module that has
2406/// not registered is a subc module that is LATE -- it may be booting, it may be
2407/// wedged, and the supervisor's health probing and restart escalation are the
2408/// right response. A `None` module is a third-party process (the NATS server is
2409/// the first) that subc launches, supervises, and stops, and that is all: it
2410/// speaks no subc wire at all, so treating its silence as a fault would restart
2411/// a perfectly healthy process forever.
2412///
2413/// Inferring the difference from "has not registered within N seconds" would
2414/// collapse exactly the two cases that must stay apart, which is why this is a
2415/// declaration.
2416#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2417#[serde(rename_all = "snake_case")]
2418pub enum ModuleProtocol {
2419    /// The module registers over channel 0, answers `health.check`, and can
2420    /// serve routes. Every module predating this field is one of these, which is
2421    /// why it is the default.
2422    #[default]
2423    Subc,
2424    /// The module speaks no subc wire. It is supervised as a process only.
2425    ///
2426    /// A clean exit (status 0) that the daemon did not request is restarted as
2427    /// a crash, counting against the restart budget, instead of being recorded
2428    /// as a stop. Such a module is usually a stock program that exits 0 on
2429    /// SIGTERM, so a stray outside signal would otherwise leave it down for
2430    /// good; a subc-wire module re-raises SIGTERM instead, so this rule is not
2431    /// needed for it.
2432    None,
2433}
2434
2435/// A supervised module's current state and process observations.
2436///
2437/// Use [`SupervisorEntry::new`] and its `with_*` methods to construct entries so
2438/// future fields do not require changes to callers.
2439/// Struct literals and functional record updates are not supported outside this crate:
2440///
2441/// ```compile_fail,E0639
2442/// use subc_control::{SupervisorEntry, SupervisorHealthStatus};
2443/// let entry = SupervisorEntry::new("provider", "running", true, true, SupervisorHealthStatus::Unknown);
2444/// let entry = SupervisorEntry { resources: None, ..entry };
2445/// ```
2446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2447#[non_exhaustive]
2448pub struct SupervisorEntry {
2449    /// A hidden previous instance blocks only this module's next spawn. This
2450    /// PID is not the supervised child and must not be presented as its identity.
2451    #[serde(default, skip_serializing_if = "Option::is_none")]
2452    pub waiting_for_previous_pid: Option<u32>,
2453    pub module_id: String,
2454    pub state: String,
2455    /// Estimated Unix milliseconds of the next retry after restart-budget
2456    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
2457    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
2458    #[serde(default, skip_serializing_if = "Option::is_none")]
2459    pub next_retry_at_ms: Option<u64>,
2460    pub enabled: bool,
2461    /// The enabled value in the daemon's loaded configuration, not a stored
2462    /// drift flag. Absent when there is no configured entry or on older daemons.
2463    #[serde(default, skip_serializing_if = "Option::is_none")]
2464    pub configured_enabled: Option<bool>,
2465    /// Whether this module is serving.
2466    ///
2467    /// For a `Subc` module: enabled, running, process alive, AND registered.
2468    /// For a `None` module the registration term is dropped, because a module
2469    /// that speaks no subc wire never registers and the daemon cannot assert
2470    /// more than "the process it launched is alive". READ IT WITH `protocol`:
2471    /// `live: true` means something weaker for a `None` module, and a renderer
2472    /// that prints it as a bare boolean for one is claiming more than the daemon
2473    /// knows.
2474    pub live: bool,
2475    /// The module's declared wire protocol. Absent on daemons predating the
2476    /// field, where every module was a subc module, so the default is exactly
2477    /// what those daemons meant.
2478    #[serde(default)]
2479    pub protocol: ModuleProtocol,
2480    /// Retained for one release for older status consumers: false on Unix, true
2481    /// on Windows. Non-wire modules receive no nonce on either platform.
2482    #[serde(default, skip_serializing_if = "Option::is_none")]
2483    pub launch_nonce_env: Option<bool>,
2484    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
2485    /// process read all bytes, otherwise `env` for the offered environment copy.
2486    /// Returned in `supervisor.list`, independently of the source the module
2487    /// declares in `manifest.provenance.launch_nonce_source` when registering.
2488    /// Processes that do not speak the wire protocol and stopped modules omit it.
2489    #[serde(default, skip_serializing_if = "Option::is_none")]
2490    pub launch_nonce_source: Option<String>,
2491    pub health: SupervisorHealthStatus,
2492    /// Computed from the stored launch spec and observed process at list time;
2493    /// None means an older daemon did not report this comparison.
2494    #[serde(default, skip_serializing_if = "Option::is_none")]
2495    pub pending_reload: Option<PendingReloadVerdict>,
2496    /// When the daemon last collected this module's health, as unix
2497    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
2498    /// window, whose `health` is therefore `Unknown` rather than good), not
2499    /// probed-long-ago. An old value and an absent one call for opposite
2500    /// readings, so do not render them alike.
2501    #[serde(default)]
2502    pub last_probe_ms: Option<u64>,
2503    /// Exit code of the module's most recent process exit, if the process has
2504    /// exited at least once. Survives respawn so a now-`running` module still
2505    /// reports what killed its previous incarnation.
2506    #[serde(default, skip_serializing_if = "Option::is_none")]
2507    pub last_exit_code: Option<i32>,
2508    /// Terminating signal of the module's most recent process exit (Unix), if
2509    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
2510    /// (often a panic-abort). Survives respawn.
2511    #[serde(default, skip_serializing_if = "Option::is_none")]
2512    pub last_exit_signal: Option<i32>,
2513    /// Unix milliseconds when the most recent child exit was observed. Present
2514    /// even when the terminal ring is not queried, so existing list readers can
2515    /// order their latest observed exit against events they already received.
2516    #[serde(default, skip_serializing_if = "Option::is_none")]
2517    pub last_exit_ms: Option<u64>,
2518    /// Classification of the most recent child exit. Absent on daemons that
2519    /// predate exit-kind reporting.
2520    #[serde(default, skip_serializing_if = "Option::is_none")]
2521    pub last_exit_kind: Option<TerminalExitKind>,
2522    /// Replacement processes spawned for this module so far, against the budget
2523    /// that disables it.
2524    ///
2525    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
2526    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
2527    /// successful probe, so a module can miss probes all day and read zero; this
2528    /// one only decreases when an operator restarts, reloads, or re-enables the
2529    /// module. Reaching the budget moves it to `Failed` and it stays there until
2530    /// somebody intervenes.
2531    ///
2532    /// So a module one restart from being disabled is indistinguishable from a
2533    /// freshly booted one unless this pair is read. Both are reported together
2534    /// because the count alone does not say how close it is.
2535    ///
2536    /// Absent from daemons predating the field, which is why it is optional
2537    /// rather than defaulted to zero: zero would assert a full budget.
2538    #[serde(default, skip_serializing_if = "Option::is_none")]
2539    pub restart_count: Option<u32>,
2540    /// Replacement processes this module is allowed before it is disabled. See
2541    /// `restart_count`; absent on daemons predating the field.
2542    #[serde(default, skip_serializing_if = "Option::is_none")]
2543    pub max_restarts: Option<u32>,
2544    /// Replacement processes spawned over this module's entire supervisor lifetime.
2545    /// Unlike `restart_count`, this value is never reset by an operator action.
2546    #[serde(default, skip_serializing_if = "Option::is_none")]
2547    pub lifetime_restarts: Option<u32>,
2548    /// Successful child spawns in this daemon incarnation. Zero means the
2549    /// module has not successfully spawned; every successful spawn increments
2550    /// the value exactly once.
2551    #[serde(default, skip_serializing_if = "Option::is_none")]
2552    pub spawn_generation: Option<u64>,
2553    /// The span `restart_count` is counted over, in seconds. The crash budget is
2554    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
2555    /// inside the last `restart_window_secs`, and older ones no longer hold a
2556    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
2557    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
2558    /// reactions.
2559    ///
2560    /// Absent on daemons predating the windowed budget, where the count really
2561    /// was a lifetime total.
2562    #[serde(default, skip_serializing_if = "Option::is_none")]
2563    pub restart_window_secs: Option<u64>,
2564    /// Effective drain budget for this module, in milliseconds. This is the
2565    /// resolved policy the running supervisor uses, not a config-file reread.
2566    /// Absent on older daemons.
2567    #[serde(default, skip_serializing_if = "Option::is_none")]
2568    pub drain_timeout_ms: Option<u64>,
2569    /// Effective base delay before a crash restart, in milliseconds. Absent on
2570    /// older daemons.
2571    #[serde(default, skip_serializing_if = "Option::is_none")]
2572    pub restart_backoff_ms: Option<u64>,
2573    /// Effective maximum delay before a crash restart, in milliseconds. Absent
2574    /// on older daemons.
2575    #[serde(default, skip_serializing_if = "Option::is_none")]
2576    pub restart_max_backoff_ms: Option<u64>,
2577    /// Memory and cumulative CPU time of the module's process, read when this
2578    /// list was answered. Report only: the daemon keeps no history and acts on
2579    /// none of it.
2580    ///
2581    /// It describes the one process the supervisor spawned (its `pid`), not
2582    /// processes that one has started in turn, so a module that forks workers
2583    /// reports only its own share.
2584    ///
2585    /// Absent means the daemon predates the field. A daemon that has the field
2586    /// but could not read the process (not running, unsupported platform, read
2587    /// failed) says so with `Unavailable` and a reason, so neither case can be
2588    /// mistaken for a process using nothing.
2589    #[serde(default, skip_serializing_if = "Option::is_none")]
2590    pub resources: Option<ChildResourceUsage>,
2591    /// Cumulative CPU and current memory including child processes, when known.
2592    #[serde(default, skip_serializing_if = "Option::is_none")]
2593    pub tree: Option<TreeReading>,
2594    /// Why this reporting daemon has no tree reading for this response.
2595    /// `not_yet_measured` means no measurement is available; other snake_case
2596    /// reasons may be added. Absence alone does not establish tree support.
2597    #[serde(default, skip_serializing_if = "Option::is_none")]
2598    pub tree_unavailable: Option<String>,
2599    /// CPU used across the wall-clock interval covered by retained samples.
2600    #[serde(default, skip_serializing_if = "Option::is_none")]
2601    pub cpu_last_hour: Option<CpuLastHour>,
2602}
2603
2604impl SupervisorEntry {
2605    /// Set the estimated time of a failed module's next automatic retry.
2606    #[must_use]
2607    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2608        self.next_retry_at_ms = next_retry_at_ms;
2609        self
2610    }
2611
2612    /// Construct an entry with its required fields and wire-compatible defaults.
2613    #[must_use]
2614    pub fn new(
2615        module_id: impl Into<String>,
2616        state: impl Into<String>,
2617        enabled: bool,
2618        live: bool,
2619        health: SupervisorHealthStatus,
2620    ) -> Self {
2621        Self {
2622            module_id: module_id.into(),
2623            state: state.into(),
2624            next_retry_at_ms: None,
2625            waiting_for_previous_pid: None,
2626            enabled,
2627            configured_enabled: None,
2628            live,
2629            protocol: ModuleProtocol::default(),
2630            launch_nonce_env: None,
2631            launch_nonce_source: None,
2632            health,
2633            pending_reload: None,
2634            last_probe_ms: None,
2635            last_exit_code: None,
2636            last_exit_signal: None,
2637            last_exit_ms: None,
2638            last_exit_kind: None,
2639            restart_count: None,
2640            max_restarts: None,
2641            lifetime_restarts: None,
2642            spawn_generation: None,
2643            restart_window_secs: None,
2644            drain_timeout_ms: None,
2645            restart_backoff_ms: None,
2646            restart_max_backoff_ms: None,
2647            resources: None,
2648            tree: None,
2649            tree_unavailable: None,
2650            cpu_last_hour: None,
2651        }
2652    }
2653
2654    /// Set the module's declared wire protocol.
2655    #[must_use]
2656    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2657        self.protocol = protocol;
2658        self
2659    }
2660
2661    /// Attach the enabled value from the daemon's loaded configuration.
2662    #[must_use]
2663    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2664        self.configured_enabled = configured_enabled;
2665        self
2666    }
2667
2668    /// Set or clear the launch nonce environment indicator.
2669    #[must_use]
2670    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2671        self.launch_nonce_env = launch_nonce_env;
2672        self
2673    }
2674
2675    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2676        self.launch_nonce_source = source;
2677        self
2678    }
2679
2680    #[must_use]
2681    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2682        self.waiting_for_previous_pid = pid;
2683        self
2684    }
2685
2686    /// Set or clear the comparison between the launch spec and observed process.
2687    #[must_use]
2688    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2689        self.pending_reload = pending_reload;
2690        self
2691    }
2692
2693    /// Set or clear the last health collection timestamp.
2694    #[must_use]
2695    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2696        self.last_probe_ms = last_probe_ms;
2697        self
2698    }
2699
2700    /// Set or clear the most recent process exit code.
2701    #[must_use]
2702    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2703        self.last_exit_code = last_exit_code;
2704        self
2705    }
2706
2707    /// Set or clear the most recent process exit signal.
2708    #[must_use]
2709    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2710        self.last_exit_signal = last_exit_signal;
2711        self
2712    }
2713
2714    /// Set or clear the most recent process exit timestamp.
2715    #[must_use]
2716    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2717        self.last_exit_ms = last_exit_ms;
2718        self
2719    }
2720
2721    /// Set or clear the most recent process exit classification.
2722    #[must_use]
2723    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2724        self.last_exit_kind = last_exit_kind;
2725        self
2726    }
2727
2728    /// Set or clear the restart count for the current crash budget.
2729    #[must_use]
2730    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2731        self.restart_count = restart_count;
2732        self
2733    }
2734
2735    /// Set or clear the maximum restarts allowed by the crash budget.
2736    #[must_use]
2737    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2738        self.max_restarts = max_restarts;
2739        self
2740    }
2741
2742    /// Set or clear the lifetime restart count.
2743    #[must_use]
2744    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2745        self.lifetime_restarts = lifetime_restarts;
2746        self
2747    }
2748
2749    /// Set or clear the successful spawn count for this daemon incarnation.
2750    #[must_use]
2751    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2752        self.spawn_generation = spawn_generation;
2753        self
2754    }
2755
2756    /// Set or clear the time window of the crash budget.
2757    #[must_use]
2758    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2759        self.restart_window_secs = restart_window_secs;
2760        self
2761    }
2762
2763    /// Set or clear the effective drain budget in milliseconds.
2764    #[must_use]
2765    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2766        self.drain_timeout_ms = drain_timeout_ms;
2767        self
2768    }
2769
2770    /// Set or clear the effective base restart delay in milliseconds.
2771    #[must_use]
2772    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2773        self.restart_backoff_ms = restart_backoff_ms;
2774        self
2775    }
2776
2777    /// Set or clear the effective maximum restart delay in milliseconds.
2778    #[must_use]
2779    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2780        self.restart_max_backoff_ms = restart_max_backoff_ms;
2781        self
2782    }
2783
2784    /// Set or clear the observed resource usage of the supervised process.
2785    #[must_use]
2786    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2787        self.resources = resources;
2788        self
2789    }
2790
2791    /// Attach a report-only reading covering the module's process container.
2792    #[must_use]
2793    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
2794        self.tree = tree;
2795        self
2796    }
2797
2798    /// Explain an absent tree reading without manufacturing numeric counters.
2799    #[must_use]
2800    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
2801        self.tree_unavailable = reason;
2802        self
2803    }
2804}
2805
2806/// A module process's memory and CPU time as read at list time, or why none
2807/// could be read.
2808#[derive(Debug, Clone, PartialEq)]
2809pub enum ChildResourceUsage {
2810    Measured(ChildResourceReading),
2811    Unavailable {
2812        reason: ChildResourceUnavailableReason,
2813    },
2814    /// Future discriminator. `body` retains the complete ordered object; `tag`
2815    /// is its decoded discriminator projection.
2816    Unknown {
2817        tag: String,
2818        body: OrderedJsonObject,
2819    },
2820}
2821
2822/// One reading of a module process's memory and CPU time.
2823/// Use [`ChildResourceReading::new`] and its builders so future fields stay additive.
2824#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2825#[non_exhaustive]
2826pub struct ChildResourceReading {
2827    /// Memory in bytes, measured as `memory_kind` says. The figures differ
2828    /// by platform and are not comparable across kinds.
2829    pub memory_bytes: u64,
2830    pub memory_kind: ChildMemoryKind,
2831    /// Bytes swapped out, where the platform reports it per process (Linux).
2832    /// Absent means not reported, not zero.
2833    #[serde(default, skip_serializing_if = "Option::is_none")]
2834    pub swap_bytes: Option<u64>,
2835    /// CPU time spent in user mode since the process started, in
2836    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
2837    /// and the elapsed time between them.
2838    pub cpu_user_ms: u64,
2839    /// CPU time spent in the kernel on the process's behalf since it started,
2840    /// in milliseconds.
2841    pub cpu_system_ms: u64,
2842}
2843
2844impl ChildResourceReading {
2845    /// Create a process reading without optional swap accounting.
2846    #[must_use]
2847    pub fn new(
2848        memory_bytes: u64,
2849        memory_kind: ChildMemoryKind,
2850        cpu_user_ms: u64,
2851        cpu_system_ms: u64,
2852    ) -> Self {
2853        Self {
2854            memory_bytes,
2855            memory_kind,
2856            cpu_user_ms,
2857            cpu_system_ms,
2858            swap_bytes: None,
2859        }
2860    }
2861
2862    /// Set or clear swap bytes where the platform can measure them.
2863    #[must_use]
2864    pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
2865        self.swap_bytes = swap_bytes;
2866        self
2867    }
2868}
2869
2870open_string_enum! {
2871    /// What `ChildResourceReading::memory_bytes` measures.
2872    ChildMemoryKind {
2873        /// macOS `phys_footprint`: memory the kernel charges to the process,
2874        /// the figure jetsam acts on. Unlike resident size it does not count
2875        /// pages an allocator has already released with `MADV_FREE`.
2876        PhysFootprint => "phys_footprint",
2877        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
2878        /// included and swapped-out pages excluded.
2879        ResidentSet => "resident_set",
2880        /// Windows `WorkingSetSize`: resident pageable memory, including shared
2881        /// pages, not Unix RSS or private committed bytes.
2882        WindowsWorkingSet => "windows_working_set",
2883    }
2884}
2885
2886open_string_enum! {
2887    /// Why a module process's resources could not be read.
2888    ChildResourceUnavailableReason {
2889        /// The module has no running process.
2890        NotRunning => "not_running",
2891        /// The daemon's platform has no per-process source.
2892        UnsupportedPlatform => "unsupported_platform",
2893        /// The process could not be read, typically because it exited while
2894        /// the list was being answered.
2895        Unreadable => "unreadable",
2896        /// The pid no longer names the process the supervisor spawned, so a
2897        /// reading would describe some other process.
2898        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2899    }
2900}
2901
2902#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2903#[serde(rename_all = "snake_case")]
2904pub enum SupervisorHealthStatus {
2905    Ok,
2906    Degraded,
2907    Failing,
2908    Unresponsive,
2909    Unknown,
2910}
2911
2912#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2913pub struct SupervisorHealthEntry {
2914    pub module_id: String,
2915    pub status: SupervisorHealthStatus,
2916    /// The module's own human-readable note on its state. Absent means the
2917    /// module said nothing, which is the ordinary shape for a healthy module and
2918    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
2919    /// module may reword freely, and `status` plus `metrics` are the machine
2920    /// surface.
2921    #[serde(default, skip_serializing_if = "Option::is_none")]
2922    pub detail: Option<String>,
2923    /// The module's own metrics object, relayed opaquely. Absent means the module
2924    /// published none on this probe — either it reports no metrics at all, or the
2925    /// probe did not reach it — so absence cannot distinguish "nothing to report"
2926    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
2927    #[serde(default, skip_serializing_if = "Option::is_none")]
2928    pub metrics: Option<serde_json::Value>,
2929    pub consecutive_failures: u32,
2930    /// Number of recurring health replies received after their daemon deadline.
2931    /// Each increment is evidence that the module remained alive despite a miss.
2932    #[serde(default)]
2933    pub late_answer_count: u64,
2934    /// End-to-end latency of the newest late reply, measured from probe start.
2935    #[serde(default, skip_serializing_if = "Option::is_none")]
2936    pub last_late_answer_latency_ms: Option<u64>,
2937    /// The escalation the supervisor last took for this module (report, restart,
2938    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
2939    /// succeeded — a module that has never misbehaved and one whose action record
2940    /// predates a daemon restart both present as absent.
2941    #[serde(default)]
2942    pub last_action: Option<String>,
2943    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
2944    /// `last_action` is absent; the pair moves together.
2945    #[serde(default)]
2946    pub last_action_ms: Option<u64>,
2947    /// When the daemon last collected this entry, as unix milliseconds.
2948    ///
2949    /// `supervisor.health` answers from the supervisor's STORED record rather
2950    /// than probing, so every field above describes some moment in the past and
2951    /// nothing here said which. That matters most right after a restart, where
2952    /// the surface is used to confirm a deploy: a record collected before the
2953    /// restart reports the OLD process, reads as a failed deploy, and invites a
2954    /// redeploy of something that was already correct.
2955    ///
2956    /// `None` means never probed — distinct from probed-long-ago, and the reader
2957    /// must not collapse them. Absent on modules that advertise no health
2958    /// capability, which is why it is optional rather than defaulted to zero.
2959    #[serde(default, skip_serializing_if = "Option::is_none")]
2960    pub last_probe_ms: Option<u64>,
2961}
2962
2963#[cfg(test)]
2964mod tests {
2965    #[test]
2966    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2967        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2968        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2969        assert_eq!(decoded.configured_enabled, None);
2970        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2971    }
2972
2973    #[test]
2974    fn configured_enabled_values_round_trip_in_list() {
2975        for enabled in [false, true] {
2976            let entry = SupervisorEntry::new(
2977                "provider",
2978                "running",
2979                true,
2980                true,
2981                SupervisorHealthStatus::Unknown,
2982            )
2983            .with_configured_enabled(Some(enabled));
2984            let entry_json = serde_json::to_value(&entry).unwrap();
2985            assert_eq!(entry_json["configured_enabled"], enabled);
2986            assert_eq!(
2987                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2988                entry
2989            );
2990        }
2991    }
2992
2993    #[test]
2994    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2995        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2996            volume_serial_number: u64::MAX,
2997            file_id: [
2998                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2999            ],
3000        };
3001        let agreement = super::RunningImageAgreement::Match { evidence };
3002        let encoded = serde_json::to_string(&agreement).unwrap();
3003        assert!(encoded.contains("windows_spawn_file_id"));
3004        assert_eq!(
3005            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3006            agreement
3007        );
3008    }
3009
3010    #[test]
3011    fn unix_running_image_evidence_keeps_original_wire_bytes() {
3012        assert_eq!(
3013            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3014                device: 7,
3015                inode: 11
3016            })
3017            .unwrap(),
3018            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3019        );
3020        assert_eq!(
3021            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3022                digest: "abc".to_owned()
3023            })
3024            .unwrap(),
3025            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3026        );
3027    }
3028    use super::*;
3029    use subc_protocol::{BindIdentity, RouteTarget};
3030
3031    #[test]
3032    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3033        let entry = TerminalEntry {
3034            daemon_incarnation: Some("daemon-before-restart".into()),
3035            exit_code: Some(1),
3036            exit_signal: None,
3037            at_ms: 1_700_000_000_123,
3038            disposition: TerminalDisposition::Restarting,
3039            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3040            disposition_detail: None,
3041        };
3042        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3043        assert_eq!(
3044            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3045                ["exit_kind"],
3046            "deliberate_severance"
3047        );
3048
3049        #[derive(serde::Deserialize)]
3050        struct LegacyTerminalEntry {
3051            exit_code: Option<i32>,
3052            exit_signal: Option<i32>,
3053            at_ms: u64,
3054            disposition: TerminalDisposition,
3055        }
3056
3057        let decoded: LegacyTerminalEntry =
3058            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3059        assert_eq!(decoded.exit_code, Some(1));
3060        assert_eq!(decoded.exit_signal, None);
3061        assert_eq!(decoded.at_ms, 1_700_000_000_123);
3062        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3063
3064        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3065        let future: TerminalEntry =
3066            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3067        assert_eq!(
3068            future.exit_kind,
3069            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3070        );
3071    }
3072
3073    #[test]
3074    fn terminal_incarnation_is_optional_for_older_daemons() {
3075        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3076            "at_ms": 123,
3077            "disposition": "stopped"
3078        }))
3079        .unwrap();
3080        let encoded = serde_json::to_value(&entry).unwrap();
3081        assert_eq!(
3082            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3083            (None, None)
3084        );
3085    }
3086
3087    #[test]
3088    fn route_poll_uses_kind_field() {
3089        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3090            route_channel: 7,
3091            route_epoch: 11,
3092            kind: PollKind::Status,
3093        })
3094        .unwrap();
3095
3096        assert_eq!(body["op"], "route.poll");
3097        assert_eq!(body["route_epoch"], 11);
3098        assert_eq!(body["kind"], "status");
3099        assert!(body.get("op").is_some());
3100    }
3101
3102    #[test]
3103    fn route_open_is_internally_tagged() {
3104        let request = ClientControlRequest::RouteOpen {
3105            busy_refusals: None,
3106            target: RouteTarget::ToolProvider {
3107                module_id: "aft".to_string(),
3108            },
3109            identity: BindIdentity::new("opencode", "session-1"),
3110            consumer_identity: None,
3111            consumer_capabilities: None,
3112            role_versions: None,
3113            admission_facts: None,
3114            scope: None,
3115        };
3116
3117        let body = serde_json::to_value(request).unwrap();
3118        assert_eq!(body["op"], "route.open");
3119        assert_eq!(body["target"]["kind"], "tool_provider");
3120        assert!(body.get("consumer_identity").is_none());
3121        assert!(body.get("consumer_capabilities").is_none());
3122        assert!(body.get("role_versions").is_none());
3123    }
3124
3125    #[test]
3126    fn route_open_without_optional_fields_still_decodes() {
3127        let body = serde_json::json!({
3128            "op": "route.open",
3129            "target": { "kind": "tool_provider", "module_id": "aft" },
3130            "identity": {
3131                "project_root": "/tmp/project",
3132                "harness": "opencode",
3133                "session": "session-1"
3134            }
3135        });
3136
3137        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3138        let ClientControlRequest::RouteOpen {
3139            consumer_identity,
3140            consumer_capabilities,
3141            role_versions,
3142            admission_facts,
3143            ..
3144        } = decoded
3145        else {
3146            panic!("decoded wrong request variant");
3147        };
3148        assert_eq!(consumer_identity, None);
3149        assert_eq!(consumer_capabilities, None);
3150        assert_eq!(role_versions, None);
3151        assert_eq!(admission_facts, None);
3152    }
3153
3154    #[test]
3155    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3156        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3157        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3158        match decoded {
3159            ClientControlPush::RouteClosed {
3160                excluded_subscriptions,
3161                terminal,
3162                ..
3163            } => {
3164                assert_eq!(excluded_subscriptions, 0);
3165                assert_eq!(terminal, None);
3166            }
3167            other => panic!("unexpected push: {other:?}"),
3168        }
3169        assert!(!serde_json::to_string(&decoded)
3170            .unwrap()
3171            .contains("terminal"));
3172    }
3173
3174    #[test]
3175    fn old_route_closed_decoder_ignores_new_terminal_field() {
3176        #[derive(serde::Deserialize)]
3177        #[serde(tag = "op")]
3178        enum LegacyClientControlPush {
3179            #[serde(rename = "route.closed")]
3180            RouteClosed {
3181                module_id: String,
3182                reason: RouteCloseReason,
3183                drained: bool,
3184                abandoned: u32,
3185            },
3186        }
3187
3188        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3189        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3190        match decoded {
3191            LegacyClientControlPush::RouteClosed {
3192                module_id,
3193                reason,
3194                drained,
3195                abandoned,
3196            } => {
3197                assert_eq!(module_id, "aft-tools");
3198                assert_eq!(reason, RouteCloseReason::Crash);
3199                assert!(!drained);
3200                assert_eq!(abandoned, 0);
3201            }
3202        }
3203    }
3204
3205    #[test]
3206    fn supervisor_routes_is_a_control_plane_request() {
3207        let body = serde_json::json!({
3208            "op": "supervisor.routes",
3209            "module_id": "aft"
3210        });
3211
3212        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3213        assert_eq!(serde_json::to_value(request).unwrap(), body);
3214    }
3215
3216    #[test]
3217    fn diagnostic_string_enums_retain_unknown_wire_values() {
3218        let reason: RunningImageUnavailableReason =
3219            serde_json::from_str("\"future_reason\"").unwrap();
3220        let disposition: TerminalDisposition =
3221            serde_json::from_str("\"future_disposition\"").unwrap();
3222
3223        assert_eq!(
3224            reason,
3225            RunningImageUnavailableReason::Unknown("future_reason".to_string())
3226        );
3227        assert_eq!(
3228            disposition,
3229            TerminalDisposition::Unknown("future_disposition".to_string())
3230        );
3231    }
3232
3233    #[test]
3234    fn diagnostic_string_enums_preserve_existing_wire_names() {
3235        let names = [
3236            (RunningImageUnavailableReason::NotRunning, "not_running"),
3237            (
3238                RunningImageUnavailableReason::UnsupportedPlatform,
3239                "unsupported_platform",
3240            ),
3241            (
3242                RunningImageUnavailableReason::RunningExecutableUnreadable,
3243                "running_executable_unreadable",
3244            ),
3245            (
3246                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3247                "running_executable_permission_denied",
3248            ),
3249            (
3250                RunningImageUnavailableReason::ProcessHidden,
3251                "process_hidden",
3252            ),
3253            (
3254                RunningImageUnavailableReason::SpawnedPathUnreadable,
3255                "spawned_path_unreadable",
3256            ),
3257            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3258            (
3259                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3260                "process_identity_unconfirmed",
3261            ),
3262        ];
3263        for (value, expected) in names {
3264            let wire = serde_json::to_string(&value).unwrap();
3265            assert_eq!(wire, format!("\"{expected}\""));
3266            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3267            assert_eq!(decoded, value);
3268        }
3269
3270        for (value, expected) in [
3271            (TerminalDisposition::Stopped, "stopped"),
3272            (TerminalDisposition::Disabled, "disabled"),
3273            (TerminalDisposition::Failed, "failed"),
3274            (TerminalDisposition::Restarting, "restarting"),
3275            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3276        ] {
3277            let wire = serde_json::to_string(&value).unwrap();
3278            assert_eq!(wire, format!("\"{expected}\""));
3279            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3280            assert_eq!(decoded, value);
3281        }
3282    }
3283
3284    #[test]
3285    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3286        let entry = SupervisorEntry::new(
3287            "waiting-module",
3288            "starting",
3289            true,
3290            false,
3291            SupervisorHealthStatus::Unknown,
3292        );
3293        let old_wire = serde_json::to_value(&entry).unwrap();
3294        assert!(old_wire.get("waiting_for_previous_pid").is_none());
3295        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3296        assert_eq!(decoded.waiting_for_previous_pid, None);
3297        let entry = entry.with_waiting_for_previous_pid(Some(42));
3298        let wire = serde_json::to_value(&entry).unwrap();
3299        assert_eq!(wire["waiting_for_previous_pid"], 42);
3300        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3301        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3302    }
3303
3304    #[test]
3305    fn diagnostic_string_enums_reject_non_string_bodies() {
3306        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3307        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3308    }
3309
3310    #[test]
3311    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3312        let body = serde_json::json!({
3313            "op": "supervisor.provenance",
3314            "daemon": {
3315                "daemon_build": {},
3316                "daemon_observed": {
3317                    "running_image": {
3318                        "status": "unavailable",
3319                        "reason": "not_running"
3320                    }
3321                }
3322            },
3323            "modules": [
3324                {
3325                    "module_id": "future",
3326                    "module_declared": { "status": "unverifiable" },
3327                    "daemon_observed": {
3328                        "running_image": {
3329                            "status": "unavailable",
3330                            "reason": "future_reason"
3331                        }
3332                    }
3333                },
3334                {
3335                    "module_id": "healthy-a",
3336                    "module_declared": { "status": "unverifiable" },
3337                    "daemon_observed": {
3338                        "running_image": {
3339                            "status": "match",
3340                            "evidence": {
3341                                "method": "linux_proc_sha256",
3342                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3343                            }
3344                        }
3345                    }
3346                },
3347                {
3348                    "module_id": "healthy-b",
3349                    "module_declared": { "status": "unverifiable" },
3350                    "daemon_observed": {
3351                        "running_image": {
3352                            "status": "unavailable",
3353                            "reason": "unsupported_platform"
3354                        }
3355                    }
3356                }
3357            ]
3358        });
3359
3360        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3361        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3362            panic!("decoded wrong response variant");
3363        };
3364        assert_eq!(modules.len(), 3);
3365        assert_eq!(modules[0].module_id, "future");
3366        assert_eq!(
3367            modules[0].daemon_observed.running_image,
3368            RunningImageAgreement::Unavailable {
3369                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3370            }
3371        );
3372        assert_eq!(modules[1].module_id, "healthy-a");
3373        assert_eq!(modules[2].module_id, "healthy-b");
3374    }
3375
3376    #[test]
3377    fn tagged_unknown_values_retain_tag_and_body() {
3378        macro_rules! assert_unknown_round_trip {
3379            ($ty:ident, $field:literal, $value:expr) => {
3380                let value = $value;
3381                let wire = serde_json::to_string(&value).unwrap();
3382                let decoded: $ty = serde_json::from_str(&wire).unwrap();
3383                match decoded {
3384                    $ty::Unknown { tag, body } => {
3385                        assert_eq!(tag, value[$field].as_str().unwrap());
3386                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
3387                    }
3388                    _ => panic!("decoded known variant"),
3389                }
3390            };
3391        }
3392
3393        assert_unknown_round_trip!(
3394            ModuleDeclaredProvenance,
3395            "status",
3396            serde_json::json!({"status": "future", "build": {"version": 7}})
3397        );
3398        assert_unknown_round_trip!(
3399            RunningImageAgreement,
3400            "status",
3401            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3402        );
3403        assert_unknown_round_trip!(
3404            RunningImageEvidence,
3405            "method",
3406            serde_json::json!({"method": "future", "digest": "abc"})
3407        );
3408        assert_unknown_round_trip!(
3409            SupervisorRouteConsumer,
3410            "kind",
3411            serde_json::json!({"kind": "future", "module_id": "m"})
3412        );
3413        assert_unknown_round_trip!(
3414            StderrCaptureState,
3415            "state",
3416            serde_json::json!({"state": "future", "reason": "because"})
3417        );
3418        assert_unknown_round_trip!(
3419            StderrTailEntry,
3420            "kind",
3421            serde_json::json!({"kind": "future", "text": "line"})
3422        );
3423        assert_unknown_round_trip!(
3424            ChildResourceUsage,
3425            "status",
3426            serde_json::json!({"status": "future", "memory_bytes": 1})
3427        );
3428    }
3429
3430    #[test]
3431    fn child_resource_usage_round_trips_both_known_states() {
3432        let measured = ChildResourceUsage::Measured(ChildResourceReading {
3433            memory_bytes: 0,
3434            memory_kind: ChildMemoryKind::ResidentSet,
3435            swap_bytes: Some(0),
3436            cpu_user_ms: 0,
3437            cpu_system_ms: 0,
3438        });
3439        let wire = serde_json::to_value(&measured).unwrap();
3440        assert_eq!(
3441            wire,
3442            serde_json::json!({
3443                "status": "measured",
3444                "memory_bytes": 0,
3445                "memory_kind": "resident_set",
3446                "swap_bytes": 0,
3447                "cpu_user_ms": 0,
3448                "cpu_system_ms": 0
3449            })
3450        );
3451        assert_eq!(
3452            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3453            measured
3454        );
3455
3456        let unavailable = ChildResourceUsage::Unavailable {
3457            reason: ChildResourceUnavailableReason::NotRunning,
3458        };
3459        let wire = serde_json::to_value(&unavailable).unwrap();
3460        assert_eq!(
3461            wire,
3462            serde_json::json!({"status": "unavailable", "reason": "not_running"})
3463        );
3464        assert_eq!(
3465            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3466            unavailable
3467        );
3468    }
3469
3470    #[test]
3471    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3472        // A current daemon stamps each line; an older one sends no `at_ms`.
3473        // Both must decode, and the absent case must stay absent rather than
3474        // turn into a time nobody recorded.
3475        let stamped: StderrTailEntry = serde_json::from_str(
3476            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3477        )
3478        .unwrap();
3479        assert_eq!(
3480            stamped,
3481            StderrTailEntry::Line {
3482                text: "boom".to_string(),
3483                truncated: true,
3484                at_ms: Some(1_789_801_440_685),
3485            }
3486        );
3487        let unstamped: StderrTailEntry =
3488            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3489        assert_eq!(
3490            unstamped,
3491            StderrTailEntry::Line {
3492                text: "boom".to_string(),
3493                truncated: false,
3494                at_ms: None,
3495            }
3496        );
3497        // Absent stays absent on the way out, so a reply without stamps is
3498        // exactly what an older daemon would have sent.
3499        assert_eq!(
3500            serde_json::to_string(&unstamped).unwrap(),
3501            r#"{"kind":"line","text":"boom"}"#
3502        );
3503        assert_eq!(
3504            serde_json::to_value(&stamped).unwrap()["at_ms"],
3505            serde_json::json!(1_789_801_440_685u64)
3506        );
3507    }
3508
3509    #[test]
3510    fn tagged_unknown_values_round_trip_the_original_json() {
3511        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3512        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3513        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3514    }
3515
3516    #[test]
3517    fn tagged_unknown_values_round_trip_trailing_tag() {
3518        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3519        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3520        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3521
3522        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3523        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3524        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3525    }
3526
3527    #[test]
3528    fn tagged_unknown_values_round_trip_middle_tag() {
3529        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3530        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3531        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3532
3533        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3534        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3535        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3536    }
3537
3538    #[test]
3539    fn tagged_unknown_values_round_trip_deep_payload() {
3540        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3541        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3542        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3543
3544        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3545        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3546        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3547    }
3548
3549    #[test]
3550    fn tagged_unknown_values_reject_non_object_bodies() {
3551        for wire in ["42", r#""future""#, "[]"] {
3552            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3553            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3554        }
3555    }
3556
3557    #[test]
3558    fn duplicate_discriminators_reject_without_panicking() {
3559        assert_eq!(
3560            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3561                .unwrap(),
3562            ModuleDeclaredProvenance::Unverifiable
3563        );
3564        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3565            .unwrap()
3566        {
3567            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3568            _ => panic!("future discriminator decoded as a known variant"),
3569        }
3570
3571        let wires = [
3572            r#"{"status":"reported","status":"unverifiable"}"#,
3573            r#"{"status":"unverifiable","status":"reported"}"#,
3574            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3575            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3576        ];
3577
3578        for wire in wires {
3579            let result =
3580                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3581            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3582            assert!(
3583                result.unwrap().is_err(),
3584                "duplicate discriminator decoded: {wire}"
3585            );
3586        }
3587
3588        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3589        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3590        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3591        assert!(
3592            result.unwrap().is_err(),
3593            "duplicate discriminator decoded: {wire}"
3594        );
3595    }
3596
3597    #[test]
3598    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3599        let known_wire =
3600            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3601        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3602        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3603
3604        for wire in [
3605            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3606            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3607        ] {
3608            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3609            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3610        }
3611
3612        for wire in [
3613            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3614            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3615        ] {
3616            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3617            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3618        }
3619
3620        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3621        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3622        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3623
3624        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3625        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3626        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3627    }
3628
3629    #[test]
3630    fn tagged_unknown_member_does_not_discard_known_siblings() {
3631        let body = serde_json::json!({
3632            "modules": [{
3633                "module_id": "target",
3634                "routes": [
3635                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3636                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3637                ]
3638            }]
3639        });
3640        let decoded: ClientControlResponse = serde_json::from_value(
3641            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3642        )
3643        .unwrap();
3644        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3645            panic!("decoded wrong response variant");
3646        };
3647        assert_eq!(modules[0].routes.len(), 2);
3648        assert_eq!(
3649            modules[0].routes[1].consumer,
3650            SupervisorRouteConsumer::Direct { connection_id: 7 }
3651        );
3652    }
3653}
3654
3655#[cfg(test)]
3656mod launch_nonce_redaction_tests {
3657    use super::*;
3658
3659    const NONCE: &str = "nonce-f00dfeed1234abcd";
3660
3661    fn identity() -> ConsumerIdentity {
3662        ConsumerIdentity {
3663            module_id: "wernicke".to_string(),
3664            launch_nonce: NONCE.to_string(),
3665        }
3666    }
3667
3668    #[test]
3669    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3670        let printed = format!("{:?}", identity());
3671        assert!(printed.contains("wernicke"), "{printed}");
3672        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3673    }
3674
3675    #[test]
3676    fn route_open_request_debug_never_prints_the_nonce() {
3677        let request = ClientControlRequest::RouteOpen {
3678            busy_refusals: None,
3679            target: subc_protocol::RouteTarget::ToolProvider {
3680                module_id: "broca".to_string(),
3681            },
3682            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
3683            consumer_identity: Some(identity()),
3684            consumer_capabilities: None,
3685            role_versions: None,
3686            admission_facts: None,
3687            scope: None,
3688        };
3689        let printed = format!("{request:?}");
3690        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3691    }
3692}