Skip to main content

subc_control/
lib.rs

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