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