Skip to main content

subc_control/
lib.rs

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