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