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