Skip to main content

subc_control/
lib.rs

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