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