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