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