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