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