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