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::claim::{
28    Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
29    ClaimRateLimitedDetail,
30};
31pub use subc_protocol::peer::CallerOrigin as CatalogOrigin;
32pub use subc_protocol::RouteCloseReason;
33use subc_protocol::{peer::MAX_ATTESTATION_INTEGER, provider_declarations::ProviderDeclarations};
34
35mod activity;
36pub use activity::*;
37
38mod scope_served_by;
39pub use scope_served_by::*;
40
41macro_rules! open_string_enum {
42    (
43        $(#[$meta:meta])*
44        $name:ident {
45            $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
46        }
47    ) => {
48        $(#[$meta])*
49        #[derive(Debug, Clone, PartialEq, Eq)]
50        pub enum $name {
51            $( $(#[$variant_meta])* $variant, )+
52            Unknown(String),
53        }
54
55        impl $name {
56            fn wire_name(&self) -> &str {
57                match self {
58                    $( Self::$variant => $wire_name, )+
59                    Self::Unknown(value) => value,
60                }
61            }
62        }
63
64        impl Serialize for $name {
65            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
66            where
67                S: serde::Serializer,
68            {
69                serializer.serialize_str(self.wire_name())
70            }
71        }
72
73        impl<'de> Deserialize<'de> for $name {
74            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75            where
76                D: serde::Deserializer<'de>,
77            {
78                let value = String::deserialize(deserializer)?;
79                Ok(match value.as_str() {
80                    $( $wire_name => Self::$variant, )+
81                    _ => Self::Unknown(value),
82                })
83            }
84        }
85    };
86}
87
88pub mod policy_root;
89mod rescan_checked;
90pub mod upgrade_in_place;
91pub use rescan_checked::*;
92
93mod app_open;
94pub use app_open::*;
95
96mod connection_describe;
97pub use connection_describe::*;
98
99mod scope_watch;
100pub use scope_watch::*;
101
102mod subtree;
103pub use subtree::*;
104mod tree;
105pub use tree::*;
106
107/// Daemon-spawned consumer identity presented on route.open.
108#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
109pub struct ConsumerIdentity {
110    pub module_id: String,
111    pub launch_nonce: String,
112}
113
114// Hand-written so the launch nonce is never printed. The nonce is the credential
115// that attributes a connection to a supervised module, and a derived Debug would
116// write it into any log line or panic message that formats this value. Same
117// reasoning as ConnectionInfo's Debug in subc-transport.
118impl std::fmt::Debug for ConsumerIdentity {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("ConsumerIdentity")
121            .field("module_id", &self.module_id)
122            .field(
123                "launch_nonce",
124                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
125            )
126            .finish()
127    }
128}
129
130/// Reserved dotted operation prefixes for the v0.4 control vocabulary.
131///
132/// `scheduler.` and `watch.` were reserved here from v0.4 until 2026-08-10 and
133/// were removed deliberately rather than left as placeholders: neither was ever
134/// implemented, and both capabilities are now owned elsewhere by ruling --
135/// scheduled tasks belong to the session runtime (prefrontal) because the
136/// daemon is state-free routing, and external-event watching belongs to the
137/// connectors module (plexus). A reserved name for something that will never be
138/// built here reads as a roadmap commitment to anyone surveying the protocol,
139/// and it recruited exactly that misunderstanding from an outside contributor.
140pub mod config;
141
142pub mod ops {
143    pub const SERVER: &str = "server.";
144    pub const CATALOG: &str = "catalog.";
145    pub const ROUTE: &str = "route.";
146    pub const SUPERVISOR: &str = "supervisor.";
147    pub const CONFIG: &str = "config.";
148
149    pub const SERVER_DESCRIBE: &str = "server.describe";
150    pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
151    pub const DAEMON_UPGRADE_IN_PLACE: &str = "daemon.upgrade_in_place";
152    pub const CATALOG_LIST: &str = "catalog.list";
153    pub const CATALOG_WATCH: &str = "catalog.watch";
154    pub const SCOPE_WATCH: &str = "scope.watch";
155    pub const ROUTE_OPEN: &str = "route.open";
156    pub const ROUTE_POLL: &str = "route.poll";
157    pub const ROUTE_CLOSING: &str = "route.closing";
158    pub const ROUTE_CLOSED: &str = "route.closed";
159    pub const SUPERVISOR_LIST: &str = "supervisor.list";
160    pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
161    pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
162    pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
163    pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
164    pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
165    pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
166    pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
167    pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
168    pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
169    pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
170    pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
171    pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
172    pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
173    pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
174    pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
175    pub const ACTIVITY_RECORD: &str = "activity.record";
176    pub const ACTIVITY_QUERY: &str = "activity.query";
177    pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
178    pub const APP_OPEN: &str = "app.open";
179    pub const CONNECTION_DESCRIBE: &str = "connection.describe";
180}
181
182/// Client-originated channel-0 control RPC body.
183#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
184#[serde(tag = "op")]
185// RouteOpen carries the complete route metadata, while several control operations
186// are markers; retain the direct public wire shape instead of boxing its fields.
187#[allow(clippy::large_enum_variant)]
188pub enum ClientControlRequest {
189    #[serde(rename = "policy_root.get")]
190    PolicyRoot(subc_protocol::policy_root::GetPolicyRoot),
191    #[serde(rename = "policy_root.set")]
192    PolicyRootSet(policy_root::SetPolicyRoot),
193    #[serde(rename = "policy_root.recover")]
194    PolicyRootRecover(policy_root::RecoverPolicyRoot),
195    /// Announce a planned daemon restart. Other values, including an absent
196    /// intent, are refused by the daemon with `invalid_params`.
197    #[serde(rename = "daemon.shutdown_intent")]
198    DaemonShutdownIntent {
199        #[serde(default)]
200        intent: serde_json::Value,
201    },
202    #[serde(rename = "daemon.upgrade_in_place")]
203    DaemonUpgradeInPlace { executable_sha256: String },
204    #[serde(rename = "server.describe")]
205    ServerDescribe {},
206    #[serde(rename = "catalog.list")]
207    CatalogList {
208        /// Absent lists every registered module; present narrows to one. A
209        /// narrowed list for an unregistered id is an empty list rather than an
210        /// error, so absent and unregistered are distinguishable only by which
211        /// question you asked.
212        #[serde(default)]
213        module_id: Option<String>,
214    },
215    #[serde(rename = "route.open")]
216    RouteOpen {
217        target: RouteTarget,
218        identity: BindIdentity,
219        /// The consumer's claim to a supervised launch, which the daemon verifies
220        /// against its live spawn nonces before stamping a principal.
221        ///
222        /// Absent is a legitimate shape, not an omission: a direct key-holder has
223        /// no launch nonce to present, and the daemon stamps `Direct`. So absence
224        /// means NO CLAIM WAS MADE, never that a claim was refused — a refused
225        /// claim is an error frame and the route never opens. A provider deciding
226        /// what to trust reads the stamped principal on the bind, not this.
227        #[serde(default, skip_serializing_if = "Option::is_none")]
228        consumer_identity: Option<ConsumerIdentity>,
229        /// Consumer-declared reverse-request capabilities for the route. This is
230        /// an unverified declaration, not a privilege grant; if a consumer
231        /// over-declares, providers may still send reverse requests that later
232        /// time out or deny. Providers must treat an absent field as no
233        /// reverse-request capability. The vocabulary is open strings; known MCP
234        /// method-family values today are "elicitation", "sampling", and
235        /// "roots".
236        #[serde(default, skip_serializing_if = "Option::is_none")]
237        consumer_capabilities: Option<Vec<String>>,
238        /// The versions of provider roles this consumer speaks on the route,
239        /// role name to version (`{"tool-provider": "v1"}`). Like
240        /// `consumer_capabilities` it is an unverified declaration that grants
241        /// nothing: the daemon checks its shape
242        /// (`subc_protocol::session::validate_role_versions`), refuses a
243        /// malformed one as `invalid_request` naming `role_versions`, and
244        /// copies it unchanged onto the module's bind. An empty map means the
245        /// same as an absent one. Send it only to a daemon advertising
246        /// `route-role-versions/v1`: an older daemon drops unknown fields, so
247        /// the provider would never see it.
248        #[serde(default, skip_serializing_if = "Option::is_none")]
249        role_versions: Option<BTreeMap<String, String>>,
250        /// Opt into immediate, never-forwarded `route_busy` refusals instead of
251        /// waiting for request credits. This field is daemon-only and is never
252        /// copied into the module's bind.
253        #[serde(default, skip_serializing_if = "Option::is_none")]
254        busy_refusals: Option<bool>,
255        /// Opaque admission facts supplied by the configured carrier module.
256        #[serde(default, skip_serializing_if = "Option::is_none")]
257        admission_facts: Option<serde_json::Value>,
258        /// The scope to open the route under. The daemon admits the open only
259        /// when the opener (its attested principal, never anything in this
260        /// body) is the scope's owner or a listed carrier, and stamps the
261        /// scope on the module's bind. Send it only to a daemon advertising
262        /// `scopes/v1`: an older daemon drops unknown fields and would open an
263        /// unscoped route.
264        #[serde(default, skip_serializing_if = "Option::is_none")]
265        scope: Option<ScopeSelector>,
266    },
267    #[serde(rename = "route.poll")]
268    RoutePoll {
269        route_channel: u16,
270        route_epoch: u32,
271        kind: PollKind,
272    },
273    #[serde(rename = "supervisor.list")]
274    SupervisorList {},
275    /// Read the live supervised processes and the event cursor atomically.
276    #[serde(rename = "supervisor.spawn_snapshot")]
277    SupervisorSpawnSnapshot {},
278    /// Replay spawn events after `since`, then remain open for live events.
279    ///
280    /// The cursor is one value copied from a snapshot or event. It includes the
281    /// daemon incarnation so a restarted daemon rejects an earlier instance's
282    /// sequence instead of treating it as a position in the current stream.
283    ///
284    /// Refusals and terminal errors, as `Error` frames on the request's corr:
285    /// - `spawn_cursor_incarnation_mismatch` (detail `current_daemon_incarnation`):
286    ///   `since` names another daemon incarnation.
287    /// - `spawn_cursor_too_old` (detail `oldest_retained_cursor`): `since`
288    ///   predates the retained event ring.
289    /// - `spawn_subscriber_lagged` (detail `first_undelivered_cursor`): the open
290    ///   stream fell too far behind and the daemon dropped it. It arrives after
291    ///   every event that was already queued and ends the stream; resubscribe
292    ///   with `since` set to the last cursor received.
293    #[serde(rename = "supervisor.spawn_subscribe")]
294    SupervisorSpawnSubscribe {
295        #[serde(default, skip_serializing_if = "Option::is_none")]
296        since: Option<SpawnCursor>,
297    },
298    #[serde(rename = "supervisor.restart")]
299    SupervisorRestart {
300        module_id: String,
301        /// Optional per-restart override of the module's drain budget, in ms.
302        /// Absent: the module's configured `drain_timeout_ms` (or the daemon
303        /// default) applies. `0` tears down without waiting: use it to restart a
304        /// wedged module whose stuck in-flight request would never settle, so
305        /// waiting for a drain would be pointless.
306        /// Additive; older daemons silently ignore this field and use their
307        /// configured/default drain budget, even when the sender requests `0`.
308        /// Senders that require the override must use a daemon version that
309        /// supports it (the CLI only sends it when a flag is passed).
310        #[serde(default, skip_serializing_if = "Option::is_none")]
311        drain_timeout_ms: Option<u64>,
312    },
313    /// Blue/green restart: start a replacement beside the running process, keep
314    /// routing to the running one until the replacement declares itself ready,
315    /// then move new routes over and drain the old process.
316    ///
317    /// Refused before anything is spawned unless the module's daemon config
318    /// declares `overlap: "safe"`: two processes on one single-writer store is
319    /// a data hazard, so the default is exclusive. Answered once the swap has
320    /// either cut over (the old process is still draining) or failed; a failure
321    /// leaves the old process serving and undrained, and names the arm in
322    /// `ErrorBody.detail`.
323    ///
324    /// A new op rather than a flag on `supervisor.restart`: a daemon that
325    /// predates swap rejects an unknown op, whereas an unknown field could be
326    /// dropped and turned into a plain restart.
327    #[serde(rename = "supervisor.swap")]
328    SupervisorSwap {
329        module_id: String,
330        /// How long the replacement may take to register and declare itself
331        /// ready before the swap is abandoned. Absent: the daemon default.
332        #[serde(default, skip_serializing_if = "Option::is_none")]
333        ready_timeout_ms: Option<u64>,
334    },
335    #[serde(rename = "supervisor.reload")]
336    SupervisorReload { module_id: String },
337    #[serde(rename = "supervisor.rescan")]
338    SupervisorRescan {
339        /// Compute the reconciliation and return it WITHOUT applying it.
340        ///
341        /// Rescan retires any supervised module absent from the config, which
342        /// stops live processes. Both halves of that decision are inspectable in
343        /// advance -- the config is a file, the running set is `supervisor.list`
344        /// -- but nothing reconstructs the diff for the operator, so it is read
345        /// from the result table AFTER the retires have happened.
346        ///
347        /// A preview must be computed daemon-side rather than by a client, because
348        /// a client would have to locate the daemon's config itself: two rules
349        /// selecting one subject, agreeing until someone runs a daemon with a
350        /// non-default config. A preview that can describe a different file than
351        /// the operation reads is worse than none, because it is believed.
352        ///
353        /// Defaults to false so an existing client sending `{}` still executes,
354        /// and is OMITTED when false so the bytes an existing client sends are
355        /// unchanged. Serialising `preview:false` would have altered the request's
356        /// wire form for every caller that never asked for a preview -- caught by
357        /// the golden fixture, which is the whole reason that pin exists.
358        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
359        preview: bool,
360    },
361    /// A rescan whose preview is computed on configuration text the caller
362    /// supplies, and whose apply runs only if the daemon still matches that
363    /// preview. Served by daemons advertising
364    /// [`RESCAN_CANDIDATE_PREVIEW_CAPABILITY`].
365    ///
366    /// Exactly two forms are accepted; any other combination is refused
367    /// `invalid_control_body`:
368    /// - `preview: true` with `candidate`: parse and validate the candidate
369    ///   (at most [`RESCAN_CANDIDATE_MAX_BYTES`]) with the loader the daemon
370    ///   uses for its file, compare it with the staged module specs, and
371    ///   report what applying it would do. Nothing is written or applied.
372    ///   The reply carries the `expect` an apply must send.
373    /// - `preview: false` with `expect`: refuse
374    ///   [`CONFIG_CHANGED_SINCE_PREVIEW`] when the daemon's config file no
375    ///   longer hashes to `expect.config_sha256` or the staged generation has
376    ///   moved; otherwise apply the file exactly as `supervisor.rescan` does.
377    ///
378    /// Both reply with `supervisor.rescan`'s result shape.
379    ///
380    /// A new op rather than fields on `supervisor.rescan`: a daemon that
381    /// predates it refuses the unknown op, whereas unknown fields would be
382    /// dropped and the preview would describe the file on disk instead of the
383    /// candidate.
384    #[serde(rename = "supervisor.rescan_checked")]
385    SupervisorRescanChecked {
386        preview: bool,
387        #[serde(default, skip_serializing_if = "Option::is_none")]
388        candidate: Option<String>,
389        #[serde(default, skip_serializing_if = "Option::is_none")]
390        expect: Option<RescanExpect>,
391    },
392    /// Retire the retained exact-id reservation after its configuration entry has
393    /// been removed. This is intentionally separate from rescan so deleting
394    /// configuration never silently opens a protected module id to registration.
395    #[serde(rename = "supervisor.release_reserved")]
396    SupervisorReleaseReserved { module_id: String },
397    #[serde(rename = "supervisor.set_enabled")]
398    SupervisorSetEnabled { module_id: String, enabled: bool },
399    #[serde(rename = "supervisor.health_probe")]
400    SupervisorHealthProbe { module_id: String },
401    #[serde(rename = "supervisor.health")]
402    SupervisorHealth {},
403    /// Enumerate the routes currently served by one supervised module, or every
404    /// module when omitted.
405    ///
406    /// This privileged census is control-plane-only. It is deliberately not an
407    /// MCP facade or agent-tool operation: callers holding the daemon control
408    /// connection may inspect live route ownership, while agent-facing modules
409    /// must not be able to address that surface at all.
410    ///
411    /// The daemon answers from its forwarding table under a read lock and never
412    /// consults a module. That makes the read safe during a drain, when a module
413    /// cannot be queried without recreating the hang/restart hazard that route
414    /// status reads avoid.
415    #[serde(rename = "supervisor.routes")]
416    SupervisorRoutes {
417        #[serde(default, skip_serializing_if = "Option::is_none")]
418        module_id: Option<String>,
419    },
420    /// Report source-tagged provenance for supervised modules, optionally narrowed
421    /// to one module.
422    #[serde(rename = "supervisor.provenance")]
423    SupervisorProvenance {
424        #[serde(default, skip_serializing_if = "Option::is_none")]
425        module_id: Option<String>,
426    },
427    /// Retained stderr for one module.
428    ///
429    /// A separate op rather than a field on `supervisor.list`: the tail is
430    /// kilobytes per module and `list` renders every module, so carrying it in
431    /// the snapshot would charge every status read for a payload almost no
432    /// caller wants. Caps ride on the REQUEST so a caller wanting twenty lines
433    /// and one wanting the whole ring need no separate fields anywhere.
434    #[serde(rename = "supervisor.stderr_tail")]
435    SupervisorStderrTail {
436        module_id: String,
437        #[serde(default, skip_serializing_if = "Option::is_none")]
438        max_lines: Option<u32>,
439        #[serde(default, skip_serializing_if = "Option::is_none")]
440        max_bytes: Option<u32>,
441    },
442    /// Retained terminal exits for one module.
443    ///
444    /// This stays separate from `supervisor.list`: a history grows with every
445    /// incident, while the list is a current-state read most callers issue often.
446    ///
447    /// The read MUST stay off the supervisor command channel — it reads the
448    /// module's shared ring directly. This is a requirement, not an
449    /// optimisation: when the supervision task itself dies, every
450    /// command-channel op returns `CommandClosed`, and that is precisely the
451    /// moment an operator needs the exit history most. A history reachable only
452    /// through the machinery whose death you are diagnosing is unreachable when
453    /// it matters. Proven failure mode, not a hypothetical.
454    #[serde(rename = "supervisor.terminals")]
455    SupervisorTerminals { module_id: String },
456}
457
458/// subc's channel-0 response body for client control RPCs.
459#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
460#[serde(tag = "op")]
461pub enum ClientControlResponse {
462    #[serde(rename = "policy_root.get")]
463    PolicyRoot(subc_protocol::policy_root::PolicyRoot),
464    #[serde(rename = "policy_root.set")]
465    PolicyRootSet(subc_protocol::policy_root::PolicyRootChange),
466    #[serde(rename = "policy_root.recover")]
467    PolicyRootRecover(subc_protocol::policy_root::PolicyRootChange),
468    #[serde(rename = "daemon.shutdown_intent")]
469    DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
470    #[serde(rename = "server.describe")]
471    ServerDescribe {
472        protocol_ver: u8,
473        subc_ops: Vec<String>,
474        capabilities: Vec<String>,
475        connected_clients: u64,
476        #[serde(default, skip_serializing_if = "Option::is_none")]
477        counters: Option<serde_json::Value>,
478        /// Git commit the daemon was built from, or "unavailable" when the
479        /// build could not read it. The crate version cannot discriminate a
480        /// skewed daemon/CLI pair (it moves per release, not per commit), so
481        /// this is the identity a consumer compares against its own embedded
482        /// commit to detect that it is talking to an older build than it was
483        /// compiled with. Absent from daemons predating the field.
484        #[serde(default, skip_serializing_if = "Option::is_none")]
485        build_git_sha: Option<String>,
486        /// sha256 of the workspace Cargo.lock at build time, or "unavailable".
487        /// Answers "which dependency set" where the commit answers "which
488        /// source"; a commit match with a digest mismatch means a rebuild
489        /// against edited dependencies. Absent from daemons predating the
490        /// field.
491        #[serde(default, skip_serializing_if = "Option::is_none")]
492        build_lock_digest: Option<String>,
493        /// Daemon-evaluated capability requirements. Present when the configured
494        /// fleet has declarations to evaluate, so operators can inspect an absent
495        /// required capability without parsing daemon logs.
496        #[serde(default, skip_serializing_if = "Vec::is_empty")]
497        capability_requirements: Vec<CapabilityRequirementStatus>,
498        /// The daemon's machine id (`subc_protocol::MachineId`), the same value
499        /// every module receives on `HELLO_ACK`. A name for this machine, never
500        /// an authority: nothing may grant trust because two parties report the
501        /// same value. Absent from daemons predating the field.
502        #[serde(default, skip_serializing_if = "Option::is_none")]
503        machine_id: Option<String>,
504        /// The configuration file the daemon reads and `supervisor.rescan`
505        /// rescans, exactly as the daemon names it: never canonicalized, so a
506        /// symlinked file is reported as the link. Sent only when that path is
507        /// absolute; a relative one (no home variable set, or a relative
508        /// `XDG_CONFIG_HOME`) depends on the daemon's working directory and
509        /// would name a different file for the reader. Absent from daemons
510        /// predating the field and from daemons started without a reloadable
511        /// config file.
512        #[serde(default, skip_serializing_if = "Option::is_none")]
513        config_path: Option<PathBuf>,
514    },
515    #[serde(rename = "catalog.list")]
516    CatalogList {
517        generation: u64,
518        modules: Vec<CatalogEntry>,
519        subc_ops: Vec<String>,
520    },
521    #[serde(rename = "route.open")]
522    RouteOpen {
523        route_channel: u16,
524        route_epoch: u32,
525        /// Total request credits, present only when busy refusals were enabled.
526        #[serde(default, skip_serializing_if = "Option::is_none")]
527        request_window: Option<usize>,
528        /// Watch credits on an opted-in module-managed route.
529        #[serde(default, skip_serializing_if = "Option::is_none")]
530        watch_window: Option<usize>,
531    },
532    #[serde(rename = "route.poll")]
533    RoutePoll {
534        route_channel: u16,
535        route_epoch: u32,
536        status: Option<String>,
537        live: Option<bool>,
538    },
539    #[serde(rename = "supervisor.list")]
540    SupervisorList {
541        generation: u64,
542        modules: Vec<SupervisorEntry>,
543        #[serde(default, skip_serializing_if = "Option::is_none")]
544        daemon: Option<DaemonResources>,
545        #[serde(default, skip_serializing_if = "Option::is_none")]
546        agent_commands: Option<Vec<AgentCommandResources>>,
547    },
548    #[serde(rename = "supervisor.spawn_snapshot")]
549    SupervisorSpawnSnapshot {
550        #[serde(flatten)]
551        snapshot: SpawnSnapshot,
552    },
553    #[serde(rename = "supervisor.ack")]
554    SupervisorAck { module_id: String, applied: bool },
555    #[serde(rename = "supervisor.rescan")]
556    SupervisorRescan {
557        #[serde(flatten)]
558        result: SupervisorRescanResult,
559    },
560    #[serde(rename = "supervisor.health_probe")]
561    SupervisorHealthProbe {
562        module_id: String,
563        status: HealthStatus,
564        #[serde(default, skip_serializing_if = "Option::is_none")]
565        detail: Option<String>,
566        #[serde(default, skip_serializing_if = "Option::is_none")]
567        metrics: Option<serde_json::Value>,
568    },
569    #[serde(rename = "supervisor.health")]
570    SupervisorHealth {
571        generation: u64,
572        modules: Vec<SupervisorHealthEntry>,
573    },
574    #[serde(rename = "supervisor.routes")]
575    SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
576    #[serde(rename = "supervisor.provenance")]
577    SupervisorProvenance {
578        daemon: SupervisorDaemonProvenance,
579        modules: Vec<SupervisorModuleProvenance>,
580    },
581    #[serde(rename = "supervisor.stderr_tail")]
582    SupervisorStderrTail {
583        module_id: String,
584        #[serde(flatten)]
585        tail: StderrTail,
586    },
587    #[serde(rename = "supervisor.terminals")]
588    SupervisorTerminals {
589        module_id: String,
590        #[serde(flatten)]
591        terminals: TerminalHistory,
592    },
593}
594
595/// Capability required before sending `accepts_close_reasons` on `route.open`.
596pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";
597
598/// Optional request keys kept outside the exhaustive `RouteOpen` variant so
599/// existing construction sites and destructures remain source-compatible.
600/// SDKs send these keys only after observing [`ROUTE_CLOSE_REASONS_CAPABILITY`].
601#[non_exhaustive]
602#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
603pub struct RouteOpenRequestExt {
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub accepts_close_reasons: Option<Vec<String>>,
606}
607
608impl RouteOpenRequestExt {
609    pub fn new() -> Self {
610        Self::default()
611    }
612
613    #[must_use]
614    pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
615        self.accepts_close_reasons = reasons;
616        self
617    }
618
619    /// Read the companion keys from the same JSON body as the existing request.
620    pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
621        require_route_open_object(body)?;
622        serde_json::from_value(body.clone())
623    }
624
625    /// Write companion keys into an existing request body, replacing stale keys.
626    /// Empty companions omit their keys rather than writing `null`.
627    pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
628        write_route_open_ext(body, self, &["accepts_close_reasons"])
629    }
630}
631
632/// Optional reply keys kept beside, rather than inside, the exhaustive
633/// `RouteOpen` variant so existing emitters and readers need no source changes.
634#[non_exhaustive]
635#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
636pub struct RouteOpenReplyExt {
637    /// An absent or incomplete target establishes no marked spawn.
638    #[serde(
639        default,
640        skip_serializing_if = "Option::is_none",
641        deserialize_with = "deserialize_route_open_target"
642    )]
643    pub target: Option<RouteOpenTarget>,
644}
645
646impl RouteOpenReplyExt {
647    pub fn new() -> Self {
648        Self::default()
649    }
650
651    #[must_use]
652    pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
653        self.target = target;
654        self
655    }
656
657    /// Read target facts from the same JSON body as the existing reply.
658    pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
659        require_route_open_object(body)?;
660        serde_json::from_value(body.clone())
661    }
662
663    /// Write target facts into an existing reply body, replacing a stale target.
664    /// An empty companion removes the key rather than writing `null`.
665    pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
666        write_route_open_ext(body, self, &["target"])
667    }
668}
669
670fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
671    if body.is_object()
672        && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
673    {
674        Ok(())
675    } else {
676        Err(serde_json::Error::custom(
677            "expected a route.open body object",
678        ))
679    }
680}
681
682fn write_route_open_ext(
683    body: &mut serde_json::Value,
684    ext: &impl Serialize,
685    keys: &[&str],
686) -> serde_json::Result<()> {
687    require_route_open_object(body)?;
688    let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
689        unreachable!("route.open companions serialize as objects");
690    };
691    let object = body.as_object_mut().expect("validated route.open object");
692    for key in keys {
693        object.remove(*key);
694    }
695    object.extend(fields);
696    Ok(())
697}
698
699/// A target kind unknown to this reader never establishes a supervised spawn.
700#[non_exhaustive]
701#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
702#[serde(rename_all = "snake_case")]
703pub enum RouteOpenTargetKind {
704    Spawn,
705    Prefix,
706    Unsupervised,
707    #[serde(other)]
708    Unknown,
709}
710
711/// Daemon-attested target facts. Spawn-only keys are ignored for all other kinds,
712/// which are always unmarked. Incomplete targets decode as absent in the reply.
713#[non_exhaustive]
714#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
715pub struct RouteOpenTarget {
716    pub incarnation: String,
717    pub kind: RouteOpenTargetKind,
718    #[serde(skip_serializing_if = "Option::is_none")]
719    pub spawn: Option<u64>,
720    #[serde(skip_serializing_if = "Option::is_none")]
721    pub authority_epoch: Option<u64>,
722    pub first_party: bool,
723    #[serde(skip_serializing_if = "Option::is_none")]
724    pub approved_declarations_digest: Option<String>,
725}
726
727impl RouteOpenTarget {
728    /// Construct target facts using the same validation and per-kind rules as
729    /// the wire reader, including the cross-language integer bound.
730    pub fn new(
731        incarnation: impl Into<String>,
732        kind: RouteOpenTargetKind,
733        spawn: Option<u64>,
734        authority_epoch: Option<u64>,
735        first_party: bool,
736        approved_declarations_digest: Option<String>,
737    ) -> serde_json::Result<Self> {
738        serde_json::from_value(serde_json::json!({
739            "incarnation": incarnation.into(), "kind": kind,
740            "spawn": spawn, "authority_epoch": authority_epoch,
741            "first_party": first_party,
742            "approved_declarations_digest": approved_declarations_digest,
743        }))
744    }
745}
746
747impl<'de> Deserialize<'de> for RouteOpenTarget {
748    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
749        decode_route_open_target(serde_json::Value::deserialize(decoder)?)
750            .map_err(D::Error::custom)?
751            .ok_or_else(|| D::Error::custom("incomplete route.open target"))
752    }
753}
754
755fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
756    decoder: D,
757) -> Result<Option<RouteOpenTarget>, D::Error> {
758    decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
759}
760
761fn decode_route_open_target(
762    mut value: serde_json::Value,
763) -> serde_json::Result<Option<RouteOpenTarget>> {
764    if value.is_null() {
765        return Ok(None);
766    }
767    let object = value
768        .as_object_mut()
769        .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
770    let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
771    if is_spawn {
772        // Validate even an incomplete spawn: rounding must not alias identities.
773        for field in ["spawn", "authority_epoch"] {
774            if let Some(integer) = object.get(field) {
775                deserialize_optional_attestation_integer(integer)?;
776            }
777        }
778    } else {
779        for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
780            object.remove(field);
781        }
782    }
783    if ["incarnation", "kind", "first_party"]
784        .iter()
785        .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
786        || (is_spawn
787            && ["spawn", "authority_epoch", "approved_declarations_digest"]
788                .iter()
789                .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
790    {
791        return Ok(None);
792    }
793    #[derive(Deserialize)]
794    struct Wire {
795        incarnation: String,
796        kind: RouteOpenTargetKind,
797        spawn: Option<u64>,
798        authority_epoch: Option<u64>,
799        first_party: bool,
800        approved_declarations_digest: Option<String>,
801    }
802    let wire: Wire = serde_json::from_value(value)?;
803    Ok(Some(RouteOpenTarget {
804        incarnation: wire.incarnation,
805        kind: wire.kind,
806        spawn: wire.spawn,
807        authority_epoch: wire.authority_epoch,
808        first_party: is_spawn && wire.first_party,
809        approved_declarations_digest: wire.approved_declarations_digest,
810    }))
811}
812
813fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
814    decoder: D,
815) -> Result<Option<u64>, D::Error> {
816    let value = Option::<u64>::deserialize(decoder)?;
817    if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
818        return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
819    }
820    Ok(value)
821}
822
823/// Channel-0 subscription request, framed like `activity.subscribe`. It stays
824/// outside the exhaustive control enums; defining it does not advertise the op.
825#[non_exhaustive]
826#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
827#[serde(tag = "op", rename = "catalog.watch")]
828pub struct CatalogWatchRequest {}
829
830impl CatalogWatchRequest {
831    pub const OP: &'static str = ops::CATALOG_WATCH;
832
833    pub fn new() -> Self {
834        Self {}
835    }
836}
837
838/// One channel-0 subscription response on the request's correlation id, with
839/// RESPONSE and MORE set, like `activity.subscribe`. There is no separate ACK:
840/// the first push carries the current generation, then advances may coalesce.
841#[non_exhaustive]
842#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
843#[serde(tag = "op", rename = "catalog.watch")]
844pub struct CatalogWatchResponse {
845    pub generation: u64,
846}
847
848impl CatalogWatchResponse {
849    pub const OP: &'static str = ops::CATALOG_WATCH;
850
851    pub fn new(generation: u64) -> Self {
852        Self { generation }
853    }
854}
855
856impl<'de> Deserialize<'de> for CatalogWatchRequest {
857    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
858        #[derive(Deserialize)]
859        #[serde(tag = "op")]
860        enum Wire {
861            #[serde(rename = "catalog.watch")]
862            Body {},
863        }
864        let Wire::Body {} = Wire::deserialize(decoder)?;
865        Ok(Self::new())
866    }
867}
868
869impl<'de> Deserialize<'de> for CatalogWatchResponse {
870    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
871        #[derive(Deserialize)]
872        #[serde(tag = "op")]
873        enum Wire {
874            #[serde(rename = "catalog.watch")]
875            Body { generation: u64 },
876        }
877        let Wire::Body { generation } = Wire::deserialize(decoder)?;
878        Ok(Self::new(generation))
879    }
880}
881
882/// Daemon-originated channel-0 control push body.
883///
884/// A module cannot originate these pushes: subc creates them from its own
885/// forwarding state and enqueues them directly to client connection sinks.
886#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
887#[serde(tag = "op")]
888pub enum ClientControlPush {
889    #[serde(rename = "route.closing")]
890    RouteClosing {
891        module_id: String,
892        /// Channel numbers identifying affected routes on this client's connection.
893        /// Channels used by other clients or by the provider are not included.
894        #[serde(default)]
895        channels: Vec<u16>,
896        reason: RouteCloseReason,
897    },
898    #[serde(rename = "route.closed")]
899    RouteClosed {
900        module_id: String,
901        /// Channel numbers identifying affected routes on this client's connection.
902        /// Channels used by other clients or by the provider are not included.
903        #[serde(default)]
904        channels: Vec<u16>,
905        reason: RouteCloseReason,
906        /// The exact result of the forwarding-quiescence wait for live routes.
907        drained: bool,
908        /// Pending route.bind relays forced down before that wait. They are not
909        /// covered by `drained`, even when live routes quiesced.
910        abandoned: u32,
911        /// Subscription credits captured and excluded from this drain's wire predicate.
912        #[serde(default)]
913        excluded_subscriptions: u32,
914        /// Whether subc will leave this module down until operator action.
915        ///
916        /// The claim covers daemon-owned recovery only. `None` is accepted only
917        /// from daemons that predate this field; every current daemon emission is
918        /// `Some`.
919        #[serde(default, skip_serializing_if = "Option::is_none")]
920        terminal: Option<bool>,
921    },
922}
923
924/// A daemon-incarnation-scoped position in the supervised spawn event stream.
925#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
926pub struct SpawnCursor {
927    pub daemon_incarnation: String,
928    pub seq: u64,
929}
930
931/// One process present in an atomic supervisor spawn snapshot.
932#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
933pub struct LiveSpawn {
934    pub module_id: String,
935    /// Names one launch of this module: unique and increasing per module
936    /// within one daemon run (one `daemon_incarnation`). The daemon assigns it when the launch
937    /// starts, before the process is running, and it is the `spawn` a caller
938    /// or target attestation names. A launch that never runs keeps its number,
939    /// so successive generations may skip.
940    pub spawn_generation: u64,
941    pub pid: u32,
942    pub spawned_at_ms: u64,
943}
944
945/// Atomic live-process census and the cursor at which it was observed.
946#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
947pub struct SpawnSnapshot {
948    pub cursor: SpawnCursor,
949    /// Maximum retained event count for this daemon.
950    pub ring_bound: u64,
951    pub live: Vec<LiveSpawn>,
952}
953
954/// Fact observed by the supervisor when a child process starts or exits.
955#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
956#[serde(rename_all = "snake_case")]
957pub enum SpawnEventKind {
958    Spawned,
959    Exited,
960}
961
962/// One retained or live spawn event.
963///
964/// Exit events intentionally carry no disposition or reason because exit
965/// classification is recorded separately; credential consumers revoke on every
966/// exit regardless of the cause.
967#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
968pub struct SpawnEvent {
969    pub cursor: SpawnCursor,
970    pub kind: SpawnEventKind,
971    pub module_id: String,
972    /// The launch's generation; see [`LiveSpawn::spawn_generation`].
973    pub spawn_generation: u64,
974    pub pid: u32,
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub exit_code: Option<i32>,
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub exit_signal: Option<i32>,
979}
980
981/// A module's retained stderr, oldest entry first.
982#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
983pub struct StderrTail {
984    pub capture: StderrCaptureState,
985    pub entries: Vec<StderrTailEntry>,
986    /// Lines not present above: evicted by the ring, or held back by this
987    /// request's own caps.
988    ///
989    /// Non-zero means the first entry is not the first line the module wrote. A
990    /// reader hunting a cause needs that, or an absent explanation reads as a
991    /// module that never gave one.
992    ///
993    /// Zero is skipped so the common complete-tail case stays compact.
994    #[serde(default, skip_serializing_if = "is_zero_u64")]
995    pub dropped_lines: u64,
996}
997
998/// Live routes served by one module.
999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1000pub struct SupervisorRouteModule {
1001    pub module_id: String,
1002    pub routes: Vec<SupervisorRoute>,
1003}
1004
1005/// One live consumer route in a [`SupervisorRouteModule`].
1006#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1007pub struct SupervisorRoute {
1008    pub consumer: SupervisorRouteConsumer,
1009    /// Milliseconds since the daemon bound this route.
1010    pub age_ms: u64,
1011    /// True once the endpoint began draining. Draining routes remain visible so
1012    /// a census does not misreport an already-closing route as live.
1013    pub draining: bool,
1014    /// WHY the endpoint is draining — the same reason vocabulary the
1015    /// route.closing push carries — present exactly when `draining` is true.
1016    /// Additive: older daemons omit it, and a census consumer must treat a
1017    /// draining route without a reason as draining-for-an-unstated-reason,
1018    /// never as not-draining.
1019    #[serde(default, skip_serializing_if = "Option::is_none")]
1020    pub drain_reason: Option<RouteCloseReason>,
1021    /// The connection that opened the route, when the daemon recorded it.
1022    #[serde(default, skip_serializing_if = "Option::is_none")]
1023    pub opener: Option<SupervisorRouteOpener>,
1024}
1025
1026/// Diagnostic information about a route's opening connection.
1027#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1028pub struct SupervisorRouteOpener {
1029    pub connection_id: u64,
1030    pub transport: SupervisorRouteTransport,
1031    #[serde(default, skip_serializing_if = "Option::is_none")]
1032    pub pid: Option<u32>,
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub command: Option<String>,
1035}
1036
1037/// Transport used by the opening connection.
1038#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1039#[serde(rename_all = "snake_case")]
1040pub enum SupervisorRouteTransport {
1041    Local,
1042    Tcp,
1043}
1044
1045/// Source-tagged provenance for one supervised module.
1046#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1047pub struct SupervisorModuleProvenance {
1048    pub module_id: String,
1049    pub module_declared: ModuleDeclaredProvenance,
1050    pub daemon_observed: SupervisorObservedProcess,
1051}
1052
1053/// Optional entry keys kept outside the exhaustive provenance struct so older
1054/// construction sites and destructures remain source-compatible.
1055#[non_exhaustive]
1056#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
1057pub struct SupervisorModuleProvenanceExt {
1058    /// The running spawn's registration path. Absence makes no claim about it.
1059    #[serde(default, skip_serializing_if = "Option::is_none")]
1060    pub registration: Option<RegistrationMethod>,
1061    /// Durable configured channel support, including stopped and disabled modules:
1062    /// `declared`, `undeclared`, or `not_applicable` for protocol-none children.
1063    /// Absence means unknown; future strings are retained unchanged.
1064    #[serde(default, skip_serializing_if = "Option::is_none")]
1065    pub registration_declaration: Option<String>,
1066    /// Why a previous instance or its remaining container blocks a new start.
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub waiting_for_previous_detail: Option<String>,
1069}
1070
1071impl SupervisorModuleProvenanceExt {
1072    pub fn new() -> Self {
1073        Self::default()
1074    }
1075
1076    #[must_use]
1077    pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
1078        self.registration = registration;
1079        self
1080    }
1081
1082    #[must_use]
1083    pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
1084        self.waiting_for_previous_detail = detail;
1085        self
1086    }
1087
1088    /// Read from a single module entry, not the enclosing provenance reply.
1089    pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
1090        if !entry.is_object() {
1091            return Err(serde_json::Error::custom(
1092                "expected a module provenance entry object",
1093            ));
1094        }
1095        serde_json::from_value(entry.clone())
1096    }
1097
1098    /// Replace companion keys in a single module entry. Absent observations
1099    /// remove stale keys rather than writing `null`.
1100    pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
1101        let object = entry.as_object_mut().ok_or_else(|| {
1102            serde_json::Error::custom("expected a module provenance entry object")
1103        })?;
1104        object.remove("registration");
1105        if let Some(method) = &self.registration {
1106            object.insert("registration".into(), serde_json::to_value(method)?);
1107        }
1108        object.remove("registration_declaration");
1109        if let Some(declaration) = &self.registration_declaration {
1110            object.insert(
1111                "registration_declaration".into(),
1112                declaration.clone().into(),
1113            );
1114        }
1115        object.remove("waiting_for_previous_detail");
1116        if let Some(detail) = &self.waiting_for_previous_detail {
1117            object.insert("waiting_for_previous_detail".into(), detail.clone().into());
1118        }
1119        Ok(())
1120    }
1121}
1122
1123/// How a running supervised spawn registered. Unknown future methods confer
1124/// neither channel registration nor nonce registration.
1125#[non_exhaustive]
1126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1127#[serde(rename_all = "snake_case")]
1128pub enum RegistrationMethod {
1129    Channel,
1130    Nonce,
1131    #[serde(other)]
1132    Unknown,
1133}
1134
1135/// Admission refused because a gated module lacks channel support. This reason
1136/// spends no restart budget; restarting cannot repair a missing declaration.
1137pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";
1138
1139/// A module's declared build metadata, if its HELLO manifest carried it.
1140#[derive(Debug, Clone, PartialEq)]
1141pub enum ModuleDeclaredProvenance {
1142    Reported {
1143        build: ManifestProvenance,
1144    },
1145    Unverifiable,
1146    /// Future discriminator. `body` retains the complete ordered object; `tag`
1147    /// is its decoded discriminator projection.
1148    Unknown {
1149        tag: String,
1150        body: OrderedJsonObject,
1151    },
1152}
1153
1154/// Process facts observed by the daemon for a supervised module.
1155///
1156/// Build claims remain under `module_declared`; mixing them here would imply the
1157/// daemon independently observed module-provided metadata.
1158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1159pub struct SupervisorObservedProcess {
1160    /// The daemon's Windows delivery record for this process: `pipe` after the
1161    /// process whose PID was returned by spawn has read all nonce bytes; `env`
1162    /// when that delivery was not completed and SUBC_LAUNCH_NONCE was offered.
1163    /// This is returned under `daemon_observed.launch_nonce_source` by
1164    /// `supervisor.provenance`, and is absent when the daemon cannot report it.
1165    #[serde(default, skip_serializing_if = "Option::is_none")]
1166    pub launch_nonce_source: Option<String>,
1167    #[serde(default, skip_serializing_if = "Option::is_none")]
1168    pub pid: Option<u32>,
1169    #[serde(default, skip_serializing_if = "Option::is_none")]
1170    pub spawned_at_ms: Option<u64>,
1171    #[serde(default, skip_serializing_if = "Option::is_none")]
1172    pub spawned_from: Option<PathBuf>,
1173    pub running_image: RunningImageAgreement,
1174}
1175
1176/// Independent comparisons of configured path, launch spec and running image at list time.
1177/// An absent verdict means the daemon predates this field, not agreement.
1178///
1179/// Use [`PendingReloadVerdict::new`] rather than an external struct literal:
1180///
1181/// ```compile_fail,E0639
1182/// use subc_control::{PendingReloadVerdict, ReloadPathAgreement, RunningImageAgreement,
1183///     RunningImageUnavailableReason};
1184/// let verdict = PendingReloadVerdict {
1185///     path: ReloadPathAgreement::Match,
1186///     image: RunningImageAgreement::Unavailable {
1187///         reason: RunningImageUnavailableReason::NotRunning,
1188///     },
1189///     spec: None,
1190/// };
1191/// ```
1192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1193#[non_exhaustive]
1194pub struct PendingReloadVerdict {
1195    pub path: ReloadPathAgreement,
1196    pub image: RunningImageAgreement,
1197    #[serde(default, skip_serializing_if = "Option::is_none")]
1198    pub spec: Option<LaunchSpecAgreement>,
1199}
1200
1201impl PendingReloadVerdict {
1202    /// Create the path and image comparisons without a launch-spec verdict.
1203    #[must_use]
1204    pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
1205        Self {
1206            path,
1207            image,
1208            spec: None,
1209        }
1210    }
1211
1212    /// Set or clear the comparison of launch specifications.
1213    #[must_use]
1214    pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
1215        self.spec = spec;
1216        self
1217    }
1218}
1219
1220#[cfg(test)]
1221mod launch_spec_wire_tests {
1222    use super::*;
1223
1224    #[test]
1225    fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
1226        let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
1227        let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
1228        assert_eq!(parsed.spec, None);
1229        assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
1230        let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
1231        let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
1232        assert!(
1233            matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
1234        );
1235        assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
1236        let unavailable = LaunchSpecAgreement::Unavailable {
1237            reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
1238        };
1239        let encoded = serde_json::to_string(&unavailable).unwrap();
1240        assert_eq!(
1241            encoded,
1242            r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
1243        );
1244        assert_eq!(
1245            serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
1246            unavailable
1247        );
1248    }
1249}
1250
1251/// Comparison of the configured launch inputs with the inputs recorded at spawn.
1252/// No digest or configured env values are sent to clients.
1253#[derive(Debug, Clone, PartialEq)]
1254pub enum LaunchSpecAgreement {
1255    Match,
1256    Mismatch,
1257    Unavailable {
1258        reason: LaunchSpecUnavailableReason,
1259    },
1260    Unknown {
1261        tag: String,
1262        body: OrderedJsonObject,
1263    },
1264}
1265
1266open_string_enum! {
1267    LaunchSpecUnavailableReason {
1268        NotRunning => "not_running",
1269        SpawnedSpecUnavailable => "spawned_spec_unavailable",
1270    }
1271}
1272
1273/// Whether the running process was spawned from the currently configured program.
1274#[derive(Debug, Clone, PartialEq)]
1275pub enum ReloadPathAgreement {
1276    Match,
1277    Mismatch {
1278        configured: PathBuf,
1279        spawned_from: PathBuf,
1280    },
1281    Unavailable {
1282        reason: ReloadPathUnavailableReason,
1283    },
1284    Unknown {
1285        tag: String,
1286        body: OrderedJsonObject,
1287    },
1288}
1289
1290open_string_enum! {
1291    /// Why configured and spawned paths cannot be compared.
1292    ReloadPathUnavailableReason {
1293        NotRunning => "not_running",
1294        SpawnedPathUnavailable => "spawned_path_unavailable",
1295    }
1296}
1297
1298/// Daemon provenance paired with its runtime process observation.
1299#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1300pub struct SupervisorDaemonProvenance {
1301    pub daemon_build: DaemonBuildProvenance,
1302    pub daemon_observed: DaemonObservedProcess,
1303}
1304
1305/// Build metadata embedded in the daemon binary.
1306#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1307pub struct DaemonBuildProvenance {
1308    #[serde(default, skip_serializing_if = "Option::is_none")]
1309    pub build_git_sha: Option<String>,
1310    #[serde(default, skip_serializing_if = "Option::is_none")]
1311    pub build_lock_digest: Option<String>,
1312}
1313
1314/// Runtime process facts observed for the daemon itself.
1315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1316pub struct DaemonObservedProcess {
1317    #[serde(default, skip_serializing_if = "Option::is_none")]
1318    pub pid: Option<u32>,
1319    /// Wall time derived from suspend-inclusive elapsed time at each read. Clock
1320    /// correction can move it by the size of a clock step, and even without a
1321    /// step it may vary by about a second between reads. Do not equality-compare
1322    /// it. Use raw process start ticks for stable identity.
1323    #[serde(default, skip_serializing_if = "Option::is_none")]
1324    pub started_at_ms: Option<u64>,
1325    pub running_image: RunningImageAgreement,
1326}
1327
1328/// Whether the executable currently running agrees with the spawned image.
1329#[derive(Debug, Clone, PartialEq)]
1330pub enum RunningImageAgreement {
1331    Match {
1332        evidence: RunningImageEvidence,
1333    },
1334    Mismatch {
1335        running: RunningImageEvidence,
1336        disk: RunningImageEvidence,
1337    },
1338    Unavailable {
1339        reason: RunningImageUnavailableReason,
1340    },
1341    /// Future discriminator. `body` retains the complete ordered object; `tag`
1342    /// is its decoded discriminator projection.
1343    Unknown {
1344        tag: String,
1345        body: OrderedJsonObject,
1346    },
1347}
1348
1349/// Platform-specific evidence used to compare a running image with its spawn path.
1350#[derive(Debug, Clone, PartialEq)]
1351pub enum RunningImageEvidence {
1352    LinuxProcSha256 {
1353        digest: String,
1354    },
1355    MacosSpawnInode {
1356        device: u64,
1357        inode: u64,
1358    },
1359    /// The spawn-time Windows file object, not verified executable content.
1360    WindowsSpawnFileId {
1361        volume_serial_number: u64,
1362        file_id: [u8; 16],
1363    },
1364    /// Future discriminator. `body` retains the complete ordered object; `tag`
1365    /// is its decoded discriminator projection.
1366    Unknown {
1367        tag: String,
1368        body: OrderedJsonObject,
1369    },
1370}
1371
1372open_string_enum! {
1373    /// Reasons why an executable identity could not be observed.
1374    RunningImageUnavailableReason {
1375        NotRunning => "not_running",
1376        NotYetMeasured => "not_yet_measured",
1377        UnsupportedPlatform => "unsupported_platform",
1378        RunningExecutableUnreadable => "running_executable_unreadable",
1379        RunningExecutablePermissionDenied => "running_executable_permission_denied",
1380        ProcessHidden => "process_hidden",
1381        SpawnedPathUnreadable => "spawned_path_unreadable",
1382        HashFailed => "hash_failed",
1383        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
1384    }
1385}
1386
1387/// The identity tier the daemon can honestly report for a route consumer.
1388///
1389/// A caller that proved a live daemon-issued launch nonce is named `reserved`.
1390/// A direct key-holder has no such attestation, so it is reported as `direct`
1391/// with its connection counter instead of an invented module name.
1392#[derive(Debug, Clone, PartialEq)]
1393pub enum SupervisorRouteConsumer {
1394    Reserved {
1395        module_id: String,
1396    },
1397    Direct {
1398        connection_id: u64,
1399    },
1400    /// Future discriminator. `body` retains the complete ordered object; `tag`
1401    /// is its decoded discriminator projection.
1402    Unknown {
1403        tag: String,
1404        body: OrderedJsonObject,
1405    },
1406}
1407
1408/// Whether stderr is being captured for a module, and if not, why not.
1409///
1410/// A typed state rather than an empty-tail convention. "The module printed
1411/// nothing before dying" and "nobody was capturing" send an operator in opposite
1412/// directions, and rendering them alike is the defect this op exists to fix --
1413/// the same shape as a `detail -` that means both no-detail and never-probed.
1414#[derive(Debug, Clone, PartialEq)]
1415pub enum StderrCaptureState {
1416    /// A reader is attached, or was attached and saw clean EOF. An empty
1417    /// `entries` under this state means the module genuinely wrote nothing.
1418    Captured,
1419    /// Retained entries are valid, but the stderr reader ended before clean EOF.
1420    Incomplete { reason: String },
1421    /// No reader was attached. `entries` says nothing about what the module wrote.
1422    NotCaptured { reason: String },
1423    /// Future discriminator. `body` retains the complete ordered object; `tag`
1424    /// is its decoded discriminator projection.
1425    Unknown {
1426        tag: String,
1427        body: OrderedJsonObject,
1428    },
1429}
1430
1431#[derive(Debug, Clone, PartialEq)]
1432pub enum StderrTailEntry {
1433    Line {
1434        text: String,
1435        /// The line was cut at the per-line cap and `text` is a prefix.
1436        ///
1437        /// Carried as a field rather than left to a marker in `text` so a
1438        /// consumer can branch on it without string matching.
1439        truncated: bool,
1440        /// Wall-clock Unix milliseconds at which the daemon read this line off
1441        /// the module's pipe. `None` from a daemon that predates the field; a
1442        /// reader must then show no time rather than make one up.
1443        at_ms: Option<u64>,
1444    },
1445    /// The supervisor spawned a new process. Entries after this came from it.
1446    ///
1447    /// In-band because position is the information: which side of the restart a
1448    /// line falls on is unanswerable from a count.
1449    ProcessStart,
1450    /// Future discriminator. `body` retains the complete ordered object; `tag`
1451    /// is its decoded discriminator projection.
1452    Unknown {
1453        tag: String,
1454        body: OrderedJsonObject,
1455    },
1456}
1457
1458#[derive(Debug, Serialize, Deserialize)]
1459#[serde(tag = "status", rename_all = "snake_case")]
1460enum ModuleDeclaredProvenanceWire {
1461    Reported { build: ManifestProvenance },
1462    Unverifiable,
1463}
1464
1465#[derive(Debug, Serialize, Deserialize)]
1466#[serde(tag = "status", rename_all = "snake_case")]
1467enum RunningImageAgreementWire {
1468    Match {
1469        evidence: RunningImageEvidence,
1470    },
1471    Mismatch {
1472        running: RunningImageEvidence,
1473        disk: RunningImageEvidence,
1474    },
1475    Unavailable {
1476        reason: RunningImageUnavailableReason,
1477    },
1478}
1479
1480#[derive(Debug, Serialize, Deserialize)]
1481#[serde(tag = "status", rename_all = "snake_case")]
1482enum ReloadPathAgreementWire {
1483    Match,
1484    Mismatch {
1485        configured: PathBuf,
1486        spawned_from: PathBuf,
1487    },
1488    Unavailable {
1489        reason: ReloadPathUnavailableReason,
1490    },
1491}
1492
1493#[derive(Debug, Serialize, Deserialize)]
1494#[serde(tag = "status", rename_all = "snake_case")]
1495enum LaunchSpecAgreementWire {
1496    Match,
1497    Mismatch,
1498    Unavailable { reason: LaunchSpecUnavailableReason },
1499}
1500
1501#[derive(Debug, Serialize, Deserialize)]
1502#[serde(tag = "method", rename_all = "snake_case")]
1503enum RunningImageEvidenceWire {
1504    LinuxProcSha256 {
1505        digest: String,
1506    },
1507    MacosSpawnInode {
1508        device: u64,
1509        inode: u64,
1510    },
1511    WindowsSpawnFileId {
1512        volume_serial_number: u64,
1513        file_id: [u8; 16],
1514    },
1515}
1516
1517#[derive(Debug, Serialize, Deserialize)]
1518#[serde(tag = "kind", rename_all = "snake_case")]
1519enum SupervisorRouteConsumerWire {
1520    Reserved { module_id: String },
1521    Direct { connection_id: u64 },
1522}
1523
1524#[derive(Debug, Serialize, Deserialize)]
1525#[serde(tag = "state", rename_all = "snake_case")]
1526enum StderrCaptureStateWire {
1527    Captured,
1528    Incomplete { reason: String },
1529    NotCaptured { reason: String },
1530}
1531
1532#[derive(Debug, Serialize, Deserialize)]
1533#[serde(tag = "status", rename_all = "snake_case")]
1534enum ChildResourceUsageWire {
1535    Measured(ChildResourceReading),
1536    Unavailable {
1537        reason: ChildResourceUnavailableReason,
1538    },
1539}
1540
1541#[derive(Debug, Serialize, Deserialize)]
1542#[serde(tag = "kind", rename_all = "snake_case")]
1543enum StderrTailEntryWire {
1544    Line {
1545        text: String,
1546        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1547        truncated: bool,
1548        // Omitted when absent so a reply without it is byte-identical to what
1549        // an older daemon sends. Older decoders ignore the member when present.
1550        #[serde(default, skip_serializing_if = "Option::is_none")]
1551        at_ms: Option<u64>,
1552    },
1553    ProcessStart,
1554}
1555
1556/// JSON values whose object members retain wire order at every depth.
1557#[derive(Debug, Clone, PartialEq)]
1558pub enum OrderedJsonValue {
1559    Null,
1560    Bool(bool),
1561    Number(serde_json::Number),
1562    String(String),
1563    Array(Vec<Self>),
1564    Object(OrderedJsonObject),
1565}
1566
1567/// Ordered JSON members retained for an unknown tagged value.
1568#[derive(Debug, Clone, PartialEq)]
1569pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1570
1571impl OrderedJsonObject {
1572    /// Returns the members in the order they appeared on the wire.
1573    pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1574        &self.0
1575    }
1576
1577    fn into_value(self) -> serde_json::Value {
1578        serde_json::Value::Object(
1579            self.0
1580                .into_iter()
1581                .map(|(key, value)| (key, value.into_value()))
1582                .collect(),
1583        )
1584    }
1585}
1586
1587impl OrderedJsonValue {
1588    fn into_value(self) -> serde_json::Value {
1589        match self {
1590            Self::Null => serde_json::Value::Null,
1591            Self::Bool(value) => serde_json::Value::Bool(value),
1592            Self::Number(value) => serde_json::Value::Number(value),
1593            Self::String(value) => serde_json::Value::String(value),
1594            Self::Array(values) => {
1595                serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1596            }
1597            Self::Object(value) => value.into_value(),
1598        }
1599    }
1600}
1601
1602impl Serialize for OrderedJsonValue {
1603    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1604    where
1605        S: Serializer,
1606    {
1607        match self {
1608            Self::Null => serializer.serialize_unit(),
1609            Self::Bool(value) => serializer.serialize_bool(*value),
1610            Self::Number(value) => value.serialize(serializer),
1611            Self::String(value) => serializer.serialize_str(value),
1612            Self::Array(values) => values.serialize(serializer),
1613            Self::Object(value) => value.serialize(serializer),
1614        }
1615    }
1616}
1617
1618impl<'de> Deserialize<'de> for OrderedJsonValue {
1619    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1620    where
1621        D: Deserializer<'de>,
1622    {
1623        struct OrderedValueVisitor;
1624
1625        impl<'de> Visitor<'de> for OrderedValueVisitor {
1626            type Value = OrderedJsonValue;
1627
1628            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1629                formatter.write_str("a JSON value with ordered object members")
1630            }
1631
1632            fn visit_unit<E>(self) -> Result<Self::Value, E>
1633            where
1634                E: serde::de::Error,
1635            {
1636                Ok(OrderedJsonValue::Null)
1637            }
1638
1639            fn visit_none<E>(self) -> Result<Self::Value, E>
1640            where
1641                E: serde::de::Error,
1642            {
1643                Ok(OrderedJsonValue::Null)
1644            }
1645
1646            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1647            where
1648                D: Deserializer<'de>,
1649            {
1650                OrderedJsonValue::deserialize(deserializer)
1651            }
1652
1653            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1654            where
1655                E: serde::de::Error,
1656            {
1657                Ok(OrderedJsonValue::Bool(value))
1658            }
1659
1660            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1661            where
1662                E: serde::de::Error,
1663            {
1664                Ok(OrderedJsonValue::Number(value.into()))
1665            }
1666
1667            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1668            where
1669                E: serde::de::Error,
1670            {
1671                Ok(OrderedJsonValue::Number(value.into()))
1672            }
1673
1674            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1675            where
1676                E: serde::de::Error,
1677            {
1678                serde_json::Number::from_f64(value)
1679                    .map(OrderedJsonValue::Number)
1680                    .ok_or_else(|| E::custom("non-finite JSON number"))
1681            }
1682
1683            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1684            where
1685                E: serde::de::Error,
1686            {
1687                Ok(OrderedJsonValue::String(value.to_owned()))
1688            }
1689
1690            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1691            where
1692                E: serde::de::Error,
1693            {
1694                Ok(OrderedJsonValue::String(value))
1695            }
1696
1697            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1698            where
1699                A: SeqAccess<'de>,
1700            {
1701                let mut values = Vec::new();
1702                while let Some(value) = sequence.next_element()? {
1703                    values.push(value);
1704                }
1705                Ok(OrderedJsonValue::Array(values))
1706            }
1707
1708            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1709            where
1710                A: MapAccess<'de>,
1711            {
1712                let mut entries = Vec::new();
1713                while let Some((key, value)) = map.next_entry()? {
1714                    entries.push((key, value));
1715                }
1716                Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1717            }
1718        }
1719
1720        deserializer.deserialize_any(OrderedValueVisitor)
1721    }
1722}
1723
1724impl Serialize for OrderedJsonObject {
1725    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1726    where
1727        S: Serializer,
1728    {
1729        let mut map = serializer.serialize_map(Some(self.0.len()))?;
1730        for (key, value) in &self.0 {
1731            map.serialize_entry(key, value)?;
1732        }
1733        map.end()
1734    }
1735}
1736
1737impl<'de> Deserialize<'de> for OrderedJsonObject {
1738    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1739    where
1740        D: Deserializer<'de>,
1741    {
1742        struct OrderedObjectVisitor;
1743
1744        impl<'de> Visitor<'de> for OrderedObjectVisitor {
1745            type Value = OrderedJsonObject;
1746
1747            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1748                formatter.write_str("an object with ordered JSON members")
1749            }
1750
1751            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1752            where
1753                A: MapAccess<'de>,
1754            {
1755                let mut entries = Vec::new();
1756                while let Some((key, value)) = map.next_entry()? {
1757                    entries.push((key, value));
1758                }
1759                Ok(OrderedJsonObject(entries))
1760            }
1761        }
1762
1763        deserializer.deserialize_map(OrderedObjectVisitor)
1764    }
1765}
1766
1767fn read_tagged<'de, D>(
1768    deserializer: D,
1769    field: &'static str,
1770) -> Result<(String, OrderedJsonObject), D::Error>
1771where
1772    D: Deserializer<'de>,
1773{
1774    let body = OrderedJsonObject::deserialize(deserializer)?;
1775    let mut tag = None;
1776    for (key, value) in body.as_entries() {
1777        if key != field {
1778            continue;
1779        }
1780        if tag.is_some() {
1781            return Err(D::Error::custom(format!(
1782                "tagged object has duplicate `{field}` field"
1783            )));
1784        }
1785        let OrderedJsonValue::String(value) = value else {
1786            return Err(D::Error::custom(format!(
1787                "tagged object has no string `{field}` field"
1788            )));
1789        };
1790        tag = Some(value);
1791    }
1792    let Some(tag) = tag else {
1793        return Err(D::Error::custom(format!(
1794            "tagged object has no string `{field}` field"
1795        )));
1796    };
1797    Ok((tag.to_string(), body))
1798}
1799
1800fn read_ordered_tagged(
1801    value: OrderedJsonValue,
1802    field: &'static str,
1803) -> Result<(String, OrderedJsonObject), String> {
1804    let OrderedJsonValue::Object(body) = value else {
1805        return Err(format!("expected tagged object with `{field}` field"));
1806    };
1807    let mut tag = None;
1808    for (key, value) in body.as_entries() {
1809        if key != field {
1810            continue;
1811        }
1812        if tag.is_some() {
1813            return Err(format!("tagged object has duplicate `{field}` field"));
1814        }
1815        let OrderedJsonValue::String(value) = value else {
1816            return Err(format!("tagged object has no string `{field}` field"));
1817        };
1818        tag = Some(value);
1819    }
1820    let Some(tag) = tag else {
1821        return Err(format!("tagged object has no string `{field}` field"));
1822    };
1823    Ok((tag.to_string(), body))
1824}
1825
1826fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1827    body.as_entries()
1828        .iter()
1829        .find_map(|(key, value)| (key == field).then_some(value))
1830}
1831
1832fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1833    match ordered_field(body, field) {
1834        Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1835        Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1836        None => Err(format!("tagged object has no `{field}` field")),
1837    }
1838}
1839
1840fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1841    let (tag, body) = read_ordered_tagged(value, "method")?;
1842    match tag.as_str() {
1843        "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1844            digest: ordered_string(&body, "digest")?,
1845        }),
1846        "macos_spawn_inode" => {
1847            let device = ordered_field(&body, "device")
1848                .and_then(|value| match value {
1849                    OrderedJsonValue::Number(number) => number.as_u64(),
1850                    _ => None,
1851                })
1852                .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1853            let inode = ordered_field(&body, "inode")
1854                .and_then(|value| match value {
1855                    OrderedJsonValue::Number(number) => number.as_u64(),
1856                    _ => None,
1857                })
1858                .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1859            Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1860        }
1861        "windows_spawn_file_id" => {
1862            let wire: RunningImageEvidenceWire = serde_json::from_value(
1863                serde_json::to_value(&body).map_err(|error| error.to_string())?,
1864            )
1865            .map_err(|error| error.to_string())?;
1866            match wire {
1867                RunningImageEvidenceWire::WindowsSpawnFileId {
1868                    volume_serial_number,
1869                    file_id,
1870                } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1871                    volume_serial_number,
1872                    file_id,
1873                }),
1874                _ => unreachable!(),
1875            }
1876        }
1877        _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1878    }
1879}
1880
1881impl Serialize for ModuleDeclaredProvenance {
1882    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1883    where
1884        S: Serializer,
1885    {
1886        match self {
1887            Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1888                build: build.clone(),
1889            }
1890            .serialize(serializer),
1891            Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1892            Self::Unknown { body, .. } => body.serialize(serializer),
1893        }
1894    }
1895}
1896
1897impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1898    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1899    where
1900        D: serde::Deserializer<'de>,
1901    {
1902        let (tag, value) = read_tagged(deserializer, "status")?;
1903        match tag.as_str() {
1904            "reported" => match serde_json::from_value(value.into_value())
1905                .map_err(D::Error::custom)?
1906            {
1907                ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1908                ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1909            },
1910            "unverifiable" => {
1911                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1912                    ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1913                    ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1914                }
1915            }
1916            _ => Ok(Self::Unknown { tag, body: value }),
1917        }
1918    }
1919}
1920
1921impl Serialize for RunningImageAgreement {
1922    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1923    where
1924        S: Serializer,
1925    {
1926        match self {
1927            Self::Match { evidence } => RunningImageAgreementWire::Match {
1928                evidence: evidence.clone(),
1929            }
1930            .serialize(serializer),
1931            Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1932                running: running.clone(),
1933                disk: disk.clone(),
1934            }
1935            .serialize(serializer),
1936            Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1937                reason: reason.clone(),
1938            }
1939            .serialize(serializer),
1940            Self::Unknown { body, .. } => body.serialize(serializer),
1941        }
1942    }
1943}
1944
1945impl Serialize for ReloadPathAgreement {
1946    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1947    where
1948        S: Serializer,
1949    {
1950        match self {
1951            Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1952            Self::Mismatch {
1953                configured,
1954                spawned_from,
1955            } => ReloadPathAgreementWire::Mismatch {
1956                configured: configured.clone(),
1957                spawned_from: spawned_from.clone(),
1958            }
1959            .serialize(serializer),
1960            Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1961                reason: reason.clone(),
1962            }
1963            .serialize(serializer),
1964            Self::Unknown { body, .. } => body.serialize(serializer),
1965        }
1966    }
1967}
1968
1969impl Serialize for LaunchSpecAgreement {
1970    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1971    where
1972        S: Serializer,
1973    {
1974        match self {
1975            Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1976            Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1977            Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1978                reason: reason.clone(),
1979            }
1980            .serialize(serializer),
1981            Self::Unknown { body, .. } => body.serialize(serializer),
1982        }
1983    }
1984}
1985
1986impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1987    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1988    where
1989        D: Deserializer<'de>,
1990    {
1991        let (tag, body) = read_tagged(deserializer, "status")?;
1992        match tag.as_str() {
1993            "match" => Ok(Self::Match),
1994            "mismatch" => Ok(Self::Mismatch),
1995            "unavailable" => match serde_json::from_value(body.into_value())
1996                .map_err(D::Error::custom)?
1997            {
1998                LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1999                _ => unreachable!(),
2000            },
2001            _ => Ok(Self::Unknown { tag, body }),
2002        }
2003    }
2004}
2005
2006impl<'de> Deserialize<'de> for ReloadPathAgreement {
2007    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2008    where
2009        D: Deserializer<'de>,
2010    {
2011        let (tag, body) = read_tagged(deserializer, "status")?;
2012        match tag.as_str() {
2013            "match" => Ok(Self::Match),
2014            "mismatch" => {
2015                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2016                    ReloadPathAgreementWire::Mismatch {
2017                        configured,
2018                        spawned_from,
2019                    } => Ok(Self::Mismatch {
2020                        configured,
2021                        spawned_from,
2022                    }),
2023                    _ => unreachable!(),
2024                }
2025            }
2026            "unavailable" => match serde_json::from_value(body.into_value())
2027                .map_err(D::Error::custom)?
2028            {
2029                ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
2030                _ => unreachable!(),
2031            },
2032            _ => Ok(Self::Unknown { tag, body }),
2033        }
2034    }
2035}
2036
2037impl<'de> Deserialize<'de> for RunningImageAgreement {
2038    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2039    where
2040        D: serde::Deserializer<'de>,
2041    {
2042        let (tag, value) = read_tagged(deserializer, "status")?;
2043        match tag.as_str() {
2044            "match" => Ok(Self::Match {
2045                evidence: decode_running_image_evidence(
2046                    ordered_field(&value, "evidence")
2047                        .cloned()
2048                        .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
2049                )
2050                .map_err(D::Error::custom)?,
2051            }),
2052            "mismatch" => Ok(Self::Mismatch {
2053                running: decode_running_image_evidence(
2054                    ordered_field(&value, "running")
2055                        .cloned()
2056                        .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
2057                )
2058                .map_err(D::Error::custom)?,
2059                disk: decode_running_image_evidence(
2060                    ordered_field(&value, "disk")
2061                        .cloned()
2062                        .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
2063                )
2064                .map_err(D::Error::custom)?,
2065            }),
2066            "unavailable" => Ok(Self::Unavailable {
2067                reason: serde_json::from_value(
2068                    ordered_field(&value, "reason")
2069                        .cloned()
2070                        .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
2071                        .into_value(),
2072                )
2073                .map_err(D::Error::custom)?,
2074            }),
2075            _ => Ok(Self::Unknown { tag, body: value }),
2076        }
2077    }
2078}
2079
2080impl Serialize for ChildResourceUsage {
2081    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2082    where
2083        S: Serializer,
2084    {
2085        match self {
2086            Self::Measured(reading) => {
2087                ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
2088            }
2089            Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
2090                reason: reason.clone(),
2091            }
2092            .serialize(serializer),
2093            Self::Unknown { body, .. } => body.serialize(serializer),
2094        }
2095    }
2096}
2097
2098impl<'de> Deserialize<'de> for ChildResourceUsage {
2099    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2100    where
2101        D: Deserializer<'de>,
2102    {
2103        let (tag, body) = read_tagged(deserializer, "status")?;
2104        match tag.as_str() {
2105            "measured" | "unavailable" => {
2106                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
2107                    ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
2108                    ChildResourceUsageWire::Unavailable { reason } => {
2109                        Ok(Self::Unavailable { reason })
2110                    }
2111                }
2112            }
2113            _ => Ok(Self::Unknown { tag, body }),
2114        }
2115    }
2116}
2117
2118impl Serialize for RunningImageEvidence {
2119    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2120    where
2121        S: Serializer,
2122    {
2123        match self {
2124            Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
2125                digest: digest.clone(),
2126            }
2127            .serialize(serializer),
2128            Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
2129                device: *device,
2130                inode: *inode,
2131            }
2132            .serialize(serializer),
2133            Self::WindowsSpawnFileId {
2134                volume_serial_number,
2135                file_id,
2136            } => RunningImageEvidenceWire::WindowsSpawnFileId {
2137                volume_serial_number: *volume_serial_number,
2138                file_id: *file_id,
2139            }
2140            .serialize(serializer),
2141            Self::Unknown { body, .. } => body.serialize(serializer),
2142        }
2143    }
2144}
2145
2146impl<'de> Deserialize<'de> for RunningImageEvidence {
2147    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2148    where
2149        D: serde::Deserializer<'de>,
2150    {
2151        let (tag, value) = read_tagged(deserializer, "method")?;
2152        match tag.as_str() {
2153            "linux_proc_sha256" => {
2154                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2155                    RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
2156                        Ok(Self::LinuxProcSha256 { digest })
2157                    }
2158                    _ => unreachable!(),
2159                }
2160            }
2161            "macos_spawn_inode" => {
2162                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2163                    RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
2164                        Ok(Self::MacosSpawnInode { device, inode })
2165                    }
2166                    _ => unreachable!(),
2167                }
2168            }
2169            "windows_spawn_file_id" => {
2170                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2171                    RunningImageEvidenceWire::WindowsSpawnFileId {
2172                        volume_serial_number,
2173                        file_id,
2174                    } => Ok(Self::WindowsSpawnFileId {
2175                        volume_serial_number,
2176                        file_id,
2177                    }),
2178                    _ => unreachable!(),
2179                }
2180            }
2181            _ => Ok(Self::Unknown { tag, body: value }),
2182        }
2183    }
2184}
2185
2186impl Serialize for SupervisorRouteConsumer {
2187    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2188    where
2189        S: Serializer,
2190    {
2191        match self {
2192            Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
2193                module_id: module_id.clone(),
2194            }
2195            .serialize(serializer),
2196            Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
2197                connection_id: *connection_id,
2198            }
2199            .serialize(serializer),
2200            Self::Unknown { body, .. } => body.serialize(serializer),
2201        }
2202    }
2203}
2204
2205impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
2206    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2207    where
2208        D: serde::Deserializer<'de>,
2209    {
2210        let (tag, value) = read_tagged(deserializer, "kind")?;
2211        match tag.as_str() {
2212            "reserved" => {
2213                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2214                    SupervisorRouteConsumerWire::Reserved { module_id } => {
2215                        Ok(Self::Reserved { module_id })
2216                    }
2217                    _ => unreachable!(),
2218                }
2219            }
2220            "direct" => {
2221                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2222                    SupervisorRouteConsumerWire::Direct { connection_id } => {
2223                        Ok(Self::Direct { connection_id })
2224                    }
2225                    _ => unreachable!(),
2226                }
2227            }
2228            _ => Ok(Self::Unknown { tag, body: value }),
2229        }
2230    }
2231}
2232
2233impl Serialize for StderrCaptureState {
2234    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2235    where
2236        S: Serializer,
2237    {
2238        match self {
2239            Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
2240            Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
2241                reason: reason.clone(),
2242            }
2243            .serialize(serializer),
2244            Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
2245                reason: reason.clone(),
2246            }
2247            .serialize(serializer),
2248            Self::Unknown { body, .. } => body.serialize(serializer),
2249        }
2250    }
2251}
2252
2253impl<'de> Deserialize<'de> for StderrCaptureState {
2254    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2255    where
2256        D: serde::Deserializer<'de>,
2257    {
2258        let (tag, value) = read_tagged(deserializer, "state")?;
2259        match tag.as_str() {
2260            "captured" => {
2261                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2262                    StderrCaptureStateWire::Captured => Ok(Self::Captured),
2263                    _ => unreachable!(),
2264                }
2265            }
2266            "incomplete" => match serde_json::from_value(value.into_value())
2267                .map_err(D::Error::custom)?
2268            {
2269                StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
2270                _ => unreachable!(),
2271            },
2272            "not_captured" => match serde_json::from_value(value.into_value())
2273                .map_err(D::Error::custom)?
2274            {
2275                StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
2276                _ => unreachable!(),
2277            },
2278            _ => Ok(Self::Unknown { tag, body: value }),
2279        }
2280    }
2281}
2282
2283impl Serialize for StderrTailEntry {
2284    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2285    where
2286        S: Serializer,
2287    {
2288        match self {
2289            Self::Line {
2290                text,
2291                truncated,
2292                at_ms,
2293            } => StderrTailEntryWire::Line {
2294                text: text.clone(),
2295                truncated: *truncated,
2296                at_ms: *at_ms,
2297            }
2298            .serialize(serializer),
2299            Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
2300            Self::Unknown { body, .. } => body.serialize(serializer),
2301        }
2302    }
2303}
2304
2305impl<'de> Deserialize<'de> for StderrTailEntry {
2306    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2307    where
2308        D: serde::Deserializer<'de>,
2309    {
2310        let (tag, value) = read_tagged(deserializer, "kind")?;
2311        match tag.as_str() {
2312            "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2313                StderrTailEntryWire::Line {
2314                    text,
2315                    truncated,
2316                    at_ms,
2317                } => Ok(Self::Line {
2318                    text,
2319                    truncated,
2320                    at_ms,
2321                }),
2322                _ => unreachable!(),
2323            },
2324            "process_start" => {
2325                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
2326                    StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
2327                    _ => unreachable!(),
2328                }
2329            }
2330            _ => Ok(Self::Unknown { tag, body: value }),
2331        }
2332    }
2333}
2334
2335fn is_zero_u64(value: &u64) -> bool {
2336    *value == 0
2337}
2338
2339fn default_true() -> bool {
2340    true
2341}
2342
2343/// Bounded terminal history for one module, oldest retained record first.
2344#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2345pub struct TerminalHistory {
2346    /// Unix milliseconds at the current daemon's start; entries may predate it.
2347    pub daemon_started_at_ms: u64,
2348    pub entries: Vec<TerminalEntry>,
2349    /// Exits evicted by the current daemon's ring, possibly recovered from its
2350    /// journal. Not a count of missing exits: expired journal totals are unknown.
2351    #[serde(default, skip_serializing_if = "is_zero_u64")]
2352    pub dropped: u64,
2353    /// Unparseable or incomplete lines across the shared journal, including
2354    /// lines whose module cannot be determined. Zero on older daemons.
2355    #[serde(default, skip_serializing_if = "is_zero_u64")]
2356    pub journal_skipped_lines: u64,
2357    /// Files that could not be read completely, excluding absent generations.
2358    #[serde(default, skip_serializing_if = "is_zero_u64")]
2359    pub journal_read_errors: u64,
2360    /// Failed journal appends across all modules in the current daemon.
2361    #[serde(default, skip_serializing_if = "is_zero_u64")]
2362    pub journal_write_failures: u64,
2363}
2364
2365/// One terminal child exit and the supervisor action it selected.
2366#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2367pub struct TerminalEntry {
2368    /// Opaque identity of the daemon that observed this exit; absent on older
2369    /// daemons. Different tokens mean different lifetimes, not chronological order.
2370    #[serde(default, skip_serializing_if = "Option::is_none")]
2371    pub daemon_incarnation: Option<String>,
2372    #[serde(default, skip_serializing_if = "Option::is_none")]
2373    pub exit_code: Option<i32>,
2374    #[serde(default, skip_serializing_if = "Option::is_none")]
2375    pub exit_signal: Option<i32>,
2376    pub at_ms: u64,
2377    pub disposition: TerminalDisposition,
2378    /// Supervisor classification of this exit. Absent on daemons that predate
2379    /// the field; unknown future kinds remain readable instead of failing the
2380    /// enclosing terminal record.
2381    #[serde(default, skip_serializing_if = "Option::is_none")]
2382    pub exit_kind: Option<TerminalExitKind>,
2383    /// Why the supervisor chose this disposition, when the disposition alone
2384    /// does not say. A `failed` record carries the exhausted crash budget here
2385    /// (`crash budget exhausted: max_restarts=3 within window_secs=600`), which
2386    /// is the difference between an operator seeing "it failed" and seeing which
2387    /// limit stopped it. Prose for humans: render it, never parse it. Absent for
2388    /// ordinary dispositions and on daemons predating the field.
2389    #[serde(default, skip_serializing_if = "Option::is_none")]
2390    pub disposition_detail: Option<String>,
2391}
2392
2393/// Exit classification carried by supervisor history and census records.
2394///
2395/// This is an open string enum so future daemon variants degrade to a readable
2396/// unknown kind rather than making a consumer discard the enclosing record.
2397#[derive(Debug, Clone, PartialEq, Eq)]
2398pub enum TerminalExitKind {
2399    Clean,
2400    Crash,
2401    DeliberateSeverance,
2402    Unknown(String),
2403}
2404
2405impl TerminalExitKind {
2406    fn wire_name(&self) -> &str {
2407        match self {
2408            Self::Clean => "clean",
2409            Self::Crash => "crash",
2410            Self::DeliberateSeverance => "deliberate_severance",
2411            Self::Unknown(value) => value,
2412        }
2413    }
2414}
2415
2416impl Serialize for TerminalExitKind {
2417    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2418    where
2419        S: serde::Serializer,
2420    {
2421        serializer.serialize_str(self.wire_name())
2422    }
2423}
2424
2425impl<'de> Deserialize<'de> for TerminalExitKind {
2426    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2427    where
2428        D: serde::Deserializer<'de>,
2429    {
2430        let value = String::deserialize(deserializer)?;
2431        Ok(match value.as_str() {
2432            "clean" => Self::Clean,
2433            "crash" => Self::Crash,
2434            "deliberate_severance" => Self::DeliberateSeverance,
2435            _ => Self::Unknown(value),
2436        })
2437    }
2438}
2439
2440open_string_enum! {
2441    /// The supervisor disposition selected after observing a terminal exit.
2442    TerminalDisposition {
2443        Stopped => "stopped",
2444        Disabled => "disabled",
2445        Failed => "failed",
2446        Restarting => "restarting",
2447        /// The child exited after the daemon had begun its own announced
2448        /// shutdown, whatever its exit code or signal. Such an exit is not
2449        /// a crash and is never followed by a respawn. Readers that predate
2450        /// this value decode it as `Unknown("daemon_shutdown")`.
2451        DaemonShutdown => "daemon_shutdown",
2452    }
2453}
2454
2455#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2456#[serde(rename_all = "snake_case")]
2457pub enum PollKind {
2458    Status,
2459    Liveness,
2460}
2461
2462/// A registered module's catalog projection.
2463///
2464/// Use [`CatalogEntry::new`] and its `with_*` methods to construct entries so
2465/// future fields do not require changes to callers.
2466/// Struct literals and functional record updates are not supported outside this crate:
2467///
2468/// ```compile_fail,E0639
2469/// use subc_control::CatalogEntry;
2470/// let entry = CatalogEntry::new("provider", vec![], vec![]);
2471/// let entry = CatalogEntry { ready: false, ..entry };
2472/// ```
2473#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2474#[non_exhaustive]
2475pub struct CatalogEntry {
2476    pub module_id: String,
2477    /// Module-declared human-readable name. Apps fall back to `module_id`.
2478    #[serde(default, skip_serializing_if = "Option::is_none")]
2479    pub display_name: Option<String>,
2480    /// Whether the registered module currently accepts new route binds.
2481    ///
2482    /// This is the module's EFFECTIVE readiness: its own declared readiness
2483    /// AND every one of its `need: required` capabilities having a registered
2484    /// provider. It is exactly the condition `route.open` checks, so a caller
2485    /// reading `false` here will be refused with `module_warming`; `not_ready`
2486    /// says why.
2487    ///
2488    /// Older daemons omit this field and are interpreted as ready. Daemons that
2489    /// predate `not_ready` report declared readiness only.
2490    #[serde(default = "default_true")]
2491    pub ready: bool,
2492    /// Why `ready` is false, in the same shape `route.open` puts in the
2493    /// `detail` of its `module_warming` refusal. Absent when the module is
2494    /// ready, and absent from daemons that predate the field.
2495    #[serde(default, skip_serializing_if = "Option::is_none")]
2496    pub not_ready: Option<NotReadyReason>,
2497    /// The registered module's self-declared build version, projected from its
2498    /// manifest so a consumer can tell WHICH BUILD of a module it is talking
2499    /// to at connect time.
2500    ///
2501    /// Without this, a client compiled against a module's current source reads
2502    /// a contract that is true of the repository and false of the running
2503    /// process -- the types match, the JSON decodes, and the meaning has
2504    /// changed. That failure carries no error to notice; the version in the
2505    /// catalog turns a semantic skew into a log line at connect instead of a
2506    /// wrong sentence on a user's screen.
2507    ///
2508    /// Optional on the wire only because entries serialized by older daemons
2509    /// lack it: absent means "daemon predates the field", never "module has
2510    /// no version" (the manifest field is required at registration).
2511    ///
2512    /// The reading is ARMED BY OBSERVATION, not by this documentation: until
2513    /// a consumer has seen at least one populated entry from the daemon it is
2514    /// connected to, an all-None catalog is indistinguishable from an old
2515    /// daemon, and a client shipping the documented reading against it would
2516    /// hold a guarantee it does not have.
2517    #[serde(default, skip_serializing_if = "Option::is_none")]
2518    pub module_version: Option<String>,
2519    /// Build provenance mirrored from the registered module's manifest.
2520    /// Absent when the module did not declare it or the daemon predates the field.
2521    #[serde(default, skip_serializing_if = "Option::is_none")]
2522    pub provenance: Option<ManifestProvenance>,
2523    pub roles: Vec<ProviderRole>,
2524    pub control_ops: Vec<String>,
2525    /// Static capability declarations from the registering module's manifest.
2526    ///
2527    /// Optional on the wire so consumers connected to a daemon that predates the
2528    /// capability grammar retain their existing catalog decoding behavior.
2529    #[serde(default, skip_serializing_if = "Option::is_none")]
2530    pub capabilities: Option<CapabilityDeclarations>,
2531    /// Self-signal declarations mirrored verbatim from the registering module's
2532    /// manifest. The daemon relays these declarations without interpreting them.
2533    #[serde(default, skip_serializing_if = "Option::is_none")]
2534    pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2535    /// Event declarations mirrored verbatim from the registering module's manifest.
2536    /// Absent when the manifest omits `events`; an empty array records an affirmative
2537    /// declaration that the module publishes no events.
2538    #[serde(default, skip_serializing_if = "Option::is_none")]
2539    pub events: Option<Vec<EventDeclaration>>,
2540    /// Open delivery hints mirrored from the module manifest. Empty means unary;
2541    /// only `"watch"` on a declared management query is subscribable.
2542    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2543    pub operation_delivery: BTreeMap<String, OperationDelivery>,
2544    /// Raw request payload limits mirrored from the module manifest by operation
2545    /// name. Empty maps preserve catalog bytes from before payload declarations.
2546    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2547    pub operation_payload: BTreeMap<String, OperationPayload>,
2548    /// Management operations the module serves to a flow-scoped call, mirrored
2549    /// unchanged from its manifest. Absent means the module did not say, so a
2550    /// reader treats the answer as unknown rather than as "none"; an empty list
2551    /// admits no operation under a flow scope. Absence preserves catalog bytes
2552    /// from before the field. The daemon relays it and never enforces it.
2553    #[serde(default, skip_serializing_if = "Option::is_none")]
2554    pub flow_operations: Option<Vec<String>>,
2555    /// Deferred-operation declarations mirrored from the registered manifest.
2556    #[serde(default, skip_serializing_if = "Option::is_none")]
2557    pub operation_deferral: Option<BTreeMap<String, bool>>,
2558    /// Management operations the module guards with `operator.confirm`,
2559    /// mirrored unchanged from its manifest. Absent means the module did not
2560    /// say (or declared an invalid list, which the daemon dropped), so a reader
2561    /// treats the answer as unknown. Absence preserves catalog bytes from before
2562    /// the field. The daemon relays it and refuses nothing on its basis.
2563    #[serde(default, skip_serializing_if = "Option::is_none")]
2564    pub confirm_operations: Option<Vec<String>>,
2565    /// Rich-UI descriptor mirrored verbatim from the registering manifest.
2566    /// The daemon does not fetch or interpret the manifest described here.
2567    #[serde(default, skip_serializing_if = "Option::is_none")]
2568    pub rich_ui: Option<RichUiDescriptor>,
2569    /// Opaque per-role objects mirrored unchanged from the registered manifest.
2570    /// Each role owns its schema; the daemon validates only keys, shape and size.
2571    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2572    pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2573    /// True when HELLO is bound to its configured spawn through a registration
2574    /// channel (gated or ungated), a prefix claim, or the legacy launch-nonce
2575    /// check for an ungated reserved module or swap candidate. The historical
2576    /// field name does not imply that a channel registration presented a nonce.
2577    #[serde(default, skip_serializing_if = "is_false")]
2578    pub nonce_verified: bool,
2579    /// Active-spawn discovery facts, never an authorization source. Older
2580    /// daemons omit these fields; absence confers no first-party mark.
2581    #[serde(default, skip_serializing_if = "Option::is_none")]
2582    pub incarnation: Option<String>,
2583    #[serde(
2584        default,
2585        skip_serializing_if = "Option::is_none",
2586        deserialize_with = "deserialize_optional_attestation_integer"
2587    )]
2588    pub spawn: Option<u64>,
2589    #[serde(default, skip_serializing_if = "Option::is_none")]
2590    pub first_party: Option<bool>,
2591    #[serde(default, skip_serializing_if = "Option::is_none")]
2592    pub origin: Option<CatalogOrigin>,
2593    #[serde(default, skip_serializing_if = "Option::is_none")]
2594    pub requested_declarations_digest: Option<String>,
2595    #[serde(default, skip_serializing_if = "Option::is_none")]
2596    pub approved_declarations_digest: Option<String>,
2597    /// Whole declaration sets appear only on a filtered catalog read. Provider
2598    /// objects retain unknown keys; requested entries are not approval evidence.
2599    #[serde(default, skip_serializing_if = "Option::is_none")]
2600    pub approved_declarations: Option<ProviderDeclarations>,
2601    #[serde(default, skip_serializing_if = "Option::is_none")]
2602    pub requested_declarations: Option<ProviderDeclarations>,
2603}
2604
2605impl CatalogEntry {
2606    /// Sets the optional module-declared display name.
2607    #[must_use]
2608    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
2609        self.display_name = display_name;
2610        self
2611    }
2612
2613    /// Construct an entry with its required fields and wire-compatible defaults.
2614    #[must_use]
2615    pub fn new(
2616        module_id: impl Into<String>,
2617        roles: Vec<ProviderRole>,
2618        control_ops: Vec<String>,
2619    ) -> Self {
2620        Self {
2621            module_id: module_id.into(),
2622            ready: default_true(),
2623            display_name: None,
2624            not_ready: None,
2625            module_version: None,
2626            provenance: None,
2627            roles,
2628            control_ops,
2629            capabilities: None,
2630            self_signals: None,
2631            events: None,
2632            operation_delivery: BTreeMap::new(),
2633            operation_payload: BTreeMap::new(),
2634            flow_operations: None,
2635            operation_deferral: None,
2636            confirm_operations: None,
2637            rich_ui: None,
2638            role_declarations: BTreeMap::new(),
2639            nonce_verified: false,
2640            incarnation: None,
2641            spawn: None,
2642            first_party: None,
2643            origin: None,
2644            requested_declarations_digest: None,
2645            approved_declarations_digest: None,
2646            approved_declarations: None,
2647            requested_declarations: None,
2648        }
2649    }
2650
2651    /// Set raw request payload limits mirrored from the registered manifest.
2652    #[must_use]
2653    pub fn with_operation_payload(
2654        mut self,
2655        operation_payload: BTreeMap<String, OperationPayload>,
2656    ) -> Self {
2657        self.operation_payload = operation_payload;
2658        self
2659    }
2660
2661    /// Set or clear the flow-scoped operation list mirrored from the registered
2662    /// manifest. `None` is omitted from the wire.
2663    #[must_use]
2664    pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2665        self.flow_operations = flow_operations;
2666        self
2667    }
2668
2669    /// Set deferred-operation declarations mirrored from the manifest.
2670    #[must_use]
2671    pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
2672        self.operation_deferral = operations;
2673        self
2674    }
2675
2676    /// Set or clear the confirm-guarded operation list mirrored from the
2677    /// registered manifest. `None` is omitted from the wire.
2678    #[must_use]
2679    pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2680        self.confirm_operations = confirm_operations;
2681        self
2682    }
2683
2684    /// Set the module's effective readiness.
2685    #[must_use]
2686    pub fn with_ready(mut self, ready: bool) -> Self {
2687        self.ready = ready;
2688        self
2689    }
2690
2691    /// Set or clear the reason the module is not ready.
2692    #[must_use]
2693    pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2694        self.not_ready = not_ready;
2695        self
2696    }
2697
2698    /// Set or clear the module's self-declared version.
2699    #[must_use]
2700    pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2701        self.module_version = module_version;
2702        self
2703    }
2704
2705    /// Set or clear the build provenance mirrored from the registered manifest.
2706    #[must_use]
2707    pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
2708        self.provenance = provenance;
2709        self
2710    }
2711
2712    /// Set or clear the module's static capability declarations.
2713    #[must_use]
2714    pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2715        self.capabilities = capabilities;
2716        self
2717    }
2718
2719    /// Set or clear the module's self-signal declarations.
2720    #[must_use]
2721    pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2722        self.self_signals = self_signals;
2723        self
2724    }
2725
2726    /// Set or clear the event declarations mirrored from the module manifest.
2727    #[must_use]
2728    pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2729        self.events = events;
2730        self
2731    }
2732
2733    /// Set delivery hints mirrored from the module manifest.
2734    /// Serialization omits this field when the stored map is empty.
2735    #[must_use]
2736    pub fn with_operation_delivery(
2737        mut self,
2738        operation_delivery: BTreeMap<String, OperationDelivery>,
2739    ) -> Self {
2740        self.operation_delivery = operation_delivery;
2741        self
2742    }
2743
2744    /// Set the descriptor mirrored from the module's HELLO manifest.
2745    #[must_use]
2746    pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2747        self.rich_ui = rich_ui;
2748        self
2749    }
2750
2751    /// Set opaque per-role declarations mirrored from the registered manifest.
2752    #[must_use]
2753    pub fn with_role_declarations(
2754        mut self,
2755        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2756    ) -> Self {
2757        self.role_declarations = role_declarations;
2758        self
2759    }
2760
2761    /// Record HELLO's verified spawn or prefix binding; see `nonce_verified`.
2762    #[must_use]
2763    pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2764        self.nonce_verified = nonce_verified;
2765        self
2766    }
2767}
2768
2769fn is_false(value: &bool) -> bool {
2770    !value
2771}
2772
2773/// Why a registered module is not accepting new route binds.
2774#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2775pub struct NotReadyReason {
2776    /// `declared_not_ready` when the module itself said it is not ready, or
2777    /// `required_capability_unprovided` when a capability it declares
2778    /// `need: required` has no registered provider. Open vocabulary: a newer
2779    /// daemon may add reasons.
2780    pub reason: String,
2781    /// For `required_capability_unprovided`, the lexicographically first
2782    /// required capability that has no registered provider.
2783    #[serde(default, skip_serializing_if = "Option::is_none")]
2784    pub capability: Option<String>,
2785}
2786
2787impl NotReadyReason {
2788    pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2789    pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2790}
2791
2792#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2793pub struct CapabilityRequirementStatus {
2794    pub consumer: String,
2795    pub capability: String,
2796    pub need: String,
2797    pub verdict: String,
2798    pub episode_seq: u64,
2799    pub config_satisfiable: bool,
2800    pub runtime_available: bool,
2801    pub detail: String,
2802}
2803
2804/// When a module-entry edit can take effect without changing rescan semantics.
2805///
2806/// The set is open: a newer daemon may name another boundary, which older
2807/// readers decode as `Other` instead of refusing the whole rescan reply.
2808#[non_exhaustive]
2809#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2810#[serde(rename_all = "snake_case")]
2811pub enum PendingModuleApply {
2812    NextSupervision,
2813    WithNextLaunchOrHealthChange,
2814    DaemonRestart,
2815    ConfigGate,
2816    #[serde(other)]
2817    Other,
2818}
2819
2820/// A configured value that rescan has read but has not applied.
2821#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2822pub struct SupervisorPendingField {
2823    pub field: String,
2824    pub applies: PendingModuleApply,
2825    #[serde(default, skip_serializing_if = "Option::is_none")]
2826    pub value: Option<serde_json::Value>,
2827}
2828
2829#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2830pub struct SupervisorPendingModule {
2831    pub module_id: String,
2832    pub fields: Vec<SupervisorPendingField>,
2833}
2834
2835#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2836pub struct SupervisorRescanResult {
2837    pub added: Vec<String>,
2838    pub removed: Vec<String>,
2839    pub changed_pending_reload: Vec<String>,
2840    /// Module-entry edits rescan cannot apply, with their activation boundaries.
2841    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2842    pub changed_pending: Vec<SupervisorPendingModule>,
2843    /// Modules whose enabled flag differs between config and running state.
2844    ///
2845    /// Rescan calls `set_enabled` for these, so omitting them made the preview
2846    /// describe two of the three mutation classes it performs. A module changing
2847    /// only its enabled flag landed in no bucket at all -- not added, removed or
2848    /// changed, and deliberately not counted as unchanged either -- so the sole
2849    /// evidence was that the buckets no longer summed to the configured module
2850    /// count. A preview is consulted precisely when someone is being careful,
2851    /// which is the worst place to under-report.
2852    ///
2853    /// Empty is skipped so consumers written against the older shape keep
2854    /// parsing.
2855    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2856    pub enabled_changes: Vec<String>,
2857    pub unchanged: u32,
2858    /// True when this reconciliation was computed but NOT applied.
2859    ///
2860    /// Carried on the result rather than left to the caller's memory of what it
2861    /// asked for. A preview and an execution are otherwise byte-identical, so a
2862    /// reader who meets this output later -- in a log, a transcript, a pasted
2863    /// snippet -- cannot tell which one happened. Absent when false, so existing
2864    /// consumers see the shape they already parse.
2865    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2866    pub preview: bool,
2867    /// Config sections that changed but which rescan CANNOT apply, so the
2868    /// operator learns a daemon restart is required from the command they just
2869    /// ran rather than from the journal.
2870    ///
2871    /// The daemon has always detected this and logged a warning. A warning in a
2872    /// log is addressed to whoever is reading the log, and the person who just
2873    /// edited the config is by construction looking at the CLI instead: reported
2874    /// by an outside contributor after a module crash-looped through four
2875    /// respawns because a new top-level `storage` section was silently not
2876    /// applied, diagnosable only by journal archaeology.
2877    ///
2878    /// Names the SECTIONS rather than a boolean, because "something else
2879    /// changed" sends the operator back to diffing their own file -- which is
2880    /// the work the message exists to save.
2881    ///
2882    /// Empty is skipped, so consumers written against the older shape keep
2883    /// parsing.
2884    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2885    pub restart_required: Vec<String>,
2886    /// Required capabilities that a dry-run's resulting module set would leave
2887    /// unprovided. Rows are human-readable because the preview is an operator
2888    /// explanation, not a second manifest schema.
2889    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2890    pub capability_warnings: Vec<String>,
2891    /// What applying the previewed candidate would do to each module, in
2892    /// module id order. Filled only by a `supervisor.rescan_checked` preview;
2893    /// a module whose launch spec, health policy and enabled flag all stay as
2894    /// staged has no entry, and neither has a disabled module that is added
2895    /// or removed. Empty is skipped, so `supervisor.rescan` replies keep their
2896    /// shape.
2897    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2898    pub module_actions: Vec<RescanModuleAction>,
2899    /// Modules whose running process still uses launch inputs from an earlier
2900    /// rescan: their staged spec waits for a restart that this candidate
2901    /// does not cause. Filled only by a `supervisor.rescan_checked` preview.
2902    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2903    pub earlier_pending: Vec<String>,
2904    /// The value an apply of this preview must send. Present only on a
2905    /// `supervisor.rescan_checked` preview.
2906    #[serde(default, skip_serializing_if = "Option::is_none")]
2907    pub expect: Option<RescanExpect>,
2908}
2909
2910/// Which wire protocol a supervised module speaks to subc, as DECLARED in
2911/// daemon config. Never inferred from observed behaviour.
2912///
2913/// The distinction this exists to keep is between a module that should have
2914/// registered and has not yet, and one that never will. A `Subc` module that has
2915/// not registered is a subc module that is LATE -- it may be booting, it may be
2916/// wedged, and the supervisor's health probing and restart escalation are the
2917/// right response. A `None` module is a third-party process (the NATS server is
2918/// the first) that subc launches, supervises, and stops, and that is all: it
2919/// speaks no subc wire at all, so treating its silence as a fault would restart
2920/// a perfectly healthy process forever.
2921///
2922/// Inferring the difference from "has not registered within N seconds" would
2923/// collapse exactly the two cases that must stay apart, which is why this is a
2924/// declaration.
2925#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2926#[serde(rename_all = "snake_case")]
2927pub enum ModuleProtocol {
2928    /// The module registers over channel 0, answers `health.check`, and can
2929    /// serve routes. Every module predating this field is one of these, which is
2930    /// why it is the default.
2931    #[default]
2932    Subc,
2933    /// The module speaks no subc wire. It is supervised as a process only.
2934    ///
2935    /// A clean exit (status 0) that the daemon did not request is restarted as
2936    /// a crash, counting against the restart budget, instead of being recorded
2937    /// as a stop. Such a module is usually a stock program that exits 0 on
2938    /// SIGTERM, so a stray outside signal would otherwise leave it down for
2939    /// good; a subc-wire module re-raises SIGTERM instead, so this rule is not
2940    /// needed for it.
2941    None,
2942}
2943
2944/// A supervised module's current state and process observations.
2945///
2946/// Use [`SupervisorEntry::new`] and its `with_*` methods to construct entries so
2947/// future fields do not require changes to callers.
2948/// Struct literals and functional record updates are not supported outside this crate:
2949///
2950/// ```compile_fail,E0639
2951/// use subc_control::{SupervisorEntry, SupervisorHealthStatus};
2952/// let entry = SupervisorEntry::new("provider", "running", true, true, SupervisorHealthStatus::Unknown);
2953/// let entry = SupervisorEntry { resources: None, ..entry };
2954/// ```
2955#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2956#[non_exhaustive]
2957pub struct SupervisorEntry {
2958    /// Script content approved for the installed runner, when configured.
2959    #[serde(default, skip_serializing_if = "Option::is_none")]
2960    pub script: Option<ScriptModuleStatus>,
2961    /// A hidden previous instance blocks only this module's next spawn. This
2962    /// PID is not the supervised child and must not be presented as its identity.
2963    #[serde(default, skip_serializing_if = "Option::is_none")]
2964    pub waiting_for_previous_pid: Option<u32>,
2965    /// Why the previous instance blocks a new start. Container details may
2966    /// name surviving processes other than the recorded PID.
2967    #[serde(default, skip_serializing_if = "Option::is_none")]
2968    pub waiting_for_previous_detail: Option<String>,
2969    pub module_id: String,
2970    pub state: String,
2971    /// Present and true while a draining module still admits routes and requests.
2972    #[serde(default, skip_serializing_if = "Option::is_none")]
2973    pub accepting_drain: Option<bool>,
2974    /// Why admission was refused. This is an open string: readers must not
2975    /// match exhaustively. `registration_channel_unsupported` means the gated
2976    /// module lacks its support declaration, not a crash to restart.
2977    #[serde(default, skip_serializing_if = "Option::is_none")]
2978    pub admission_refused: Option<String>,
2979    /// Estimated Unix milliseconds of the next retry after restart-budget
2980    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
2981    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
2982    #[serde(default, skip_serializing_if = "Option::is_none")]
2983    pub next_retry_at_ms: Option<u64>,
2984    pub enabled: bool,
2985    /// The enabled value in the daemon's loaded configuration, not a stored
2986    /// drift flag. Absent when there is no configured entry or on older daemons.
2987    #[serde(default, skip_serializing_if = "Option::is_none")]
2988    pub configured_enabled: Option<bool>,
2989    /// Whether this module is serving.
2990    ///
2991    /// For a `Subc` module: enabled, running, process alive, AND registered.
2992    /// For a `None` module the registration term is dropped, because a module
2993    /// that speaks no subc wire never registers and the daemon cannot assert
2994    /// more than "the process it launched is alive". READ IT WITH `protocol`:
2995    /// `live: true` means something weaker for a `None` module, and a renderer
2996    /// that prints it as a bare boolean for one is claiming more than the daemon
2997    /// knows.
2998    pub live: bool,
2999    /// The module's declared wire protocol. Absent on daemons predating the
3000    /// field, where every module was a subc module, so the default is exactly
3001    /// what those daemons meant.
3002    #[serde(default)]
3003    pub protocol: ModuleProtocol,
3004    /// Retained for one release for older status consumers: false on Unix, true
3005    /// on Windows. Non-wire modules receive no nonce on either platform.
3006    #[serde(default, skip_serializing_if = "Option::is_none")]
3007    pub launch_nonce_env: Option<bool>,
3008    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
3009    /// process read all bytes, otherwise `env` for the offered environment copy.
3010    /// Returned in `supervisor.list`, independently of the source the module
3011    /// declares in `manifest.provenance.launch_nonce_source` when registering.
3012    /// Processes that do not speak the wire protocol and stopped modules omit it.
3013    #[serde(default, skip_serializing_if = "Option::is_none")]
3014    pub launch_nonce_source: Option<String>,
3015    pub health: SupervisorHealthStatus,
3016    /// Computed from the stored launch spec and observed process at list time;
3017    /// None means an older daemon did not report this comparison.
3018    #[serde(default, skip_serializing_if = "Option::is_none")]
3019    pub pending_reload: Option<PendingReloadVerdict>,
3020    /// When the daemon last collected this module's health, as unix
3021    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
3022    /// window, whose `health` is therefore `Unknown` rather than good), not
3023    /// probed-long-ago. An old value and an absent one call for opposite
3024    /// readings, so do not render them alike.
3025    #[serde(default)]
3026    pub last_probe_ms: Option<u64>,
3027    /// Exit code of the module's most recent process exit, if the process has
3028    /// exited at least once. Survives respawn so a now-`running` module still
3029    /// reports what killed its previous incarnation.
3030    #[serde(default, skip_serializing_if = "Option::is_none")]
3031    pub last_exit_code: Option<i32>,
3032    /// Terminating signal of the module's most recent process exit (Unix), if
3033    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
3034    /// (often a panic-abort). Survives respawn.
3035    #[serde(default, skip_serializing_if = "Option::is_none")]
3036    pub last_exit_signal: Option<i32>,
3037    /// Unix milliseconds when the most recent child exit was observed. Present
3038    /// even when the terminal ring is not queried, so existing list readers can
3039    /// order their latest observed exit against events they already received.
3040    #[serde(default, skip_serializing_if = "Option::is_none")]
3041    pub last_exit_ms: Option<u64>,
3042    /// Classification of the most recent child exit. Absent on daemons that
3043    /// predate exit-kind reporting.
3044    #[serde(default, skip_serializing_if = "Option::is_none")]
3045    pub last_exit_kind: Option<TerminalExitKind>,
3046    /// Replacement processes spawned for this module so far, against the budget
3047    /// that disables it.
3048    ///
3049    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
3050    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
3051    /// successful probe, so a module can miss probes all day and read zero; this
3052    /// one only decreases when an operator restarts, reloads, or re-enables the
3053    /// module. Reaching the budget moves it to `Failed` and it stays there until
3054    /// somebody intervenes.
3055    ///
3056    /// So a module one restart from being disabled is indistinguishable from a
3057    /// freshly booted one unless this pair is read. Both are reported together
3058    /// because the count alone does not say how close it is.
3059    ///
3060    /// Absent from daemons predating the field, which is why it is optional
3061    /// rather than defaulted to zero: zero would assert a full budget.
3062    #[serde(default, skip_serializing_if = "Option::is_none")]
3063    pub restart_count: Option<u32>,
3064    /// Replacement processes this module is allowed before it is disabled. See
3065    /// `restart_count`; absent on daemons predating the field.
3066    #[serde(default, skip_serializing_if = "Option::is_none")]
3067    pub max_restarts: Option<u32>,
3068    /// Replacement processes spawned over this module's entire supervisor lifetime.
3069    /// Unlike `restart_count`, this value is never reset by an operator action.
3070    #[serde(default, skip_serializing_if = "Option::is_none")]
3071    pub lifetime_restarts: Option<u32>,
3072    /// Successful child spawns in this daemon incarnation. Zero means the
3073    /// module has not successfully spawned; every successful spawn increments
3074    /// the value exactly once.
3075    #[serde(default, skip_serializing_if = "Option::is_none")]
3076    pub spawn_generation: Option<u64>,
3077    /// The span `restart_count` is counted over, in seconds. The crash budget is
3078    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
3079    /// inside the last `restart_window_secs`, and older ones no longer hold a
3080    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
3081    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
3082    /// reactions.
3083    ///
3084    /// Absent on daemons predating the windowed budget, where the count really
3085    /// was a lifetime total.
3086    #[serde(default, skip_serializing_if = "Option::is_none")]
3087    pub restart_window_secs: Option<u64>,
3088    /// Effective drain budget for this module, in milliseconds. This is the
3089    /// resolved policy the running supervisor uses, not a config-file reread.
3090    /// Absent on older daemons.
3091    #[serde(default, skip_serializing_if = "Option::is_none")]
3092    pub drain_timeout_ms: Option<u64>,
3093    /// Effective base delay before a crash restart, in milliseconds. Absent on
3094    /// older daemons.
3095    #[serde(default, skip_serializing_if = "Option::is_none")]
3096    pub restart_backoff_ms: Option<u64>,
3097    /// Effective maximum delay before a crash restart, in milliseconds. Absent
3098    /// on older daemons.
3099    #[serde(default, skip_serializing_if = "Option::is_none")]
3100    pub restart_max_backoff_ms: Option<u64>,
3101    /// Memory and cumulative CPU time of the module's process, read when this
3102    /// list was answered. Report only: the daemon keeps no history and acts on
3103    /// none of it.
3104    ///
3105    /// It describes the one process the supervisor spawned (its `pid`), not
3106    /// processes that one has started in turn, so a module that forks workers
3107    /// reports only its own share.
3108    ///
3109    /// Absent means the daemon predates the field. A daemon that has the field
3110    /// but could not read the process (not running, unsupported platform, read
3111    /// failed) says so with `Unavailable` and a reason, so neither case can be
3112    /// mistaken for a process using nothing.
3113    #[serde(default, skip_serializing_if = "Option::is_none")]
3114    pub resources: Option<ChildResourceUsage>,
3115    /// Cumulative CPU and current memory including child processes, when known.
3116    #[serde(default, skip_serializing_if = "Option::is_none")]
3117    pub tree: Option<TreeReading>,
3118    /// Why this reporting daemon has no tree reading for this response.
3119    /// `not_yet_measured` means this launch has no measurement; `unreadable`
3120    /// and `launch_changed` can accompany a retained, older tree. `not_running`
3121    /// marks a stopped module. Future reasons remain valid open-set strings.
3122    /// Absence alone does not establish tree support.
3123    #[serde(default, skip_serializing_if = "Option::is_none")]
3124    pub tree_unavailable: Option<String>,
3125    /// CPU used across the wall-clock interval covered by retained samples.
3126    #[serde(default, skip_serializing_if = "Option::is_none")]
3127    pub cpu_last_hour: Option<CpuLastHour>,
3128    /// Values read by an executed rescan that are not yet in force.
3129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3130    pub pending: Vec<SupervisorPendingField>,
3131}
3132
3133impl SupervisorEntry {
3134    #[must_use]
3135    pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3136        self.script = script;
3137        self
3138    }
3139    /// Set the estimated time of a failed module's next automatic retry.
3140    #[must_use]
3141    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3142        self.next_retry_at_ms = next_retry_at_ms;
3143        self
3144    }
3145
3146    /// Construct an entry with its required fields and wire-compatible defaults.
3147    #[must_use]
3148    pub fn new(
3149        module_id: impl Into<String>,
3150        state: impl Into<String>,
3151        enabled: bool,
3152        live: bool,
3153        health: SupervisorHealthStatus,
3154    ) -> Self {
3155        Self {
3156            module_id: module_id.into(),
3157            script: None,
3158            state: state.into(),
3159            admission_refused: None,
3160            next_retry_at_ms: None,
3161            waiting_for_previous_pid: None,
3162            waiting_for_previous_detail: None,
3163            accepting_drain: None,
3164            enabled,
3165            configured_enabled: None,
3166            live,
3167            protocol: ModuleProtocol::default(),
3168            launch_nonce_env: None,
3169            launch_nonce_source: None,
3170            health,
3171            pending_reload: None,
3172            last_probe_ms: None,
3173            last_exit_code: None,
3174            last_exit_signal: None,
3175            last_exit_ms: None,
3176            last_exit_kind: None,
3177            restart_count: None,
3178            max_restarts: None,
3179            lifetime_restarts: None,
3180            spawn_generation: None,
3181            restart_window_secs: None,
3182            drain_timeout_ms: None,
3183            restart_backoff_ms: None,
3184            restart_max_backoff_ms: None,
3185            resources: None,
3186            tree: None,
3187            tree_unavailable: None,
3188            cpu_last_hour: None,
3189            pending: Vec::new(),
3190        }
3191    }
3192
3193    /// Set or clear the daemon's admission refusal reason.
3194    #[must_use]
3195    pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3196        self.admission_refused = reason;
3197        self
3198    }
3199
3200    /// Set the module's declared wire protocol.
3201    #[must_use]
3202    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3203        self.protocol = protocol;
3204        self
3205    }
3206
3207    /// Attach the enabled value from the daemon's loaded configuration.
3208    #[must_use]
3209    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3210        self.configured_enabled = configured_enabled;
3211        self
3212    }
3213
3214    /// Set or clear the launch nonce environment indicator.
3215    #[must_use]
3216    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3217        self.launch_nonce_env = launch_nonce_env;
3218        self
3219    }
3220
3221    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3222        self.launch_nonce_source = source;
3223        self
3224    }
3225
3226    #[must_use]
3227    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3228        self.waiting_for_previous_pid = pid;
3229        self
3230    }
3231
3232    #[must_use]
3233    pub fn with_waiting_for_previous_detail(mut self, detail: Option<String>) -> Self {
3234        self.waiting_for_previous_detail = detail;
3235        self
3236    }
3237
3238    /// Set or clear the comparison between the launch spec and observed process.
3239    #[must_use]
3240    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3241        self.pending_reload = pending_reload;
3242        self
3243    }
3244
3245    /// Set or clear the last health collection timestamp.
3246    #[must_use]
3247    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3248        self.last_probe_ms = last_probe_ms;
3249        self
3250    }
3251
3252    /// Set or clear the most recent process exit code.
3253    #[must_use]
3254    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3255        self.last_exit_code = last_exit_code;
3256        self
3257    }
3258
3259    /// Set or clear the most recent process exit signal.
3260    #[must_use]
3261    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3262        self.last_exit_signal = last_exit_signal;
3263        self
3264    }
3265
3266    /// Set or clear the most recent process exit timestamp.
3267    #[must_use]
3268    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3269        self.last_exit_ms = last_exit_ms;
3270        self
3271    }
3272
3273    /// Set or clear the most recent process exit classification.
3274    #[must_use]
3275    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3276        self.last_exit_kind = last_exit_kind;
3277        self
3278    }
3279
3280    /// Set or clear the restart count for the current crash budget.
3281    #[must_use]
3282    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3283        self.restart_count = restart_count;
3284        self
3285    }
3286
3287    /// Set or clear the maximum restarts allowed by the crash budget.
3288    #[must_use]
3289    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3290        self.max_restarts = max_restarts;
3291        self
3292    }
3293
3294    /// Set or clear the lifetime restart count.
3295    #[must_use]
3296    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3297        self.lifetime_restarts = lifetime_restarts;
3298        self
3299    }
3300
3301    /// Set or clear the successful spawn count for this daemon incarnation.
3302    #[must_use]
3303    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3304        self.spawn_generation = spawn_generation;
3305        self
3306    }
3307
3308    /// Set or clear the time window of the crash budget.
3309    #[must_use]
3310    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3311        self.restart_window_secs = restart_window_secs;
3312        self
3313    }
3314
3315    /// Set or clear the effective drain budget in milliseconds.
3316    #[must_use]
3317    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3318        self.drain_timeout_ms = drain_timeout_ms;
3319        self
3320    }
3321
3322    /// Set or clear the effective base restart delay in milliseconds.
3323    #[must_use]
3324    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3325        self.restart_backoff_ms = restart_backoff_ms;
3326        self
3327    }
3328
3329    /// Set or clear the effective maximum restart delay in milliseconds.
3330    #[must_use]
3331    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3332        self.restart_max_backoff_ms = restart_max_backoff_ms;
3333        self
3334    }
3335
3336    /// Set or clear the observed resource usage of the supervised process.
3337    #[must_use]
3338    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3339        self.resources = resources;
3340        self
3341    }
3342
3343    /// Attach a report-only reading covering the module's process container.
3344    #[must_use]
3345    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3346        self.tree = tree;
3347        self
3348    }
3349
3350    /// Explain an absent tree reading without manufacturing numeric counters.
3351    #[must_use]
3352    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3353        self.tree_unavailable = reason;
3354        self
3355    }
3356}
3357
3358/// Content identity is separate from the runner executable's identity.
3359#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3360pub struct ScriptModuleStatus {
3361    pub runtime: String,
3362    pub bun_version: Option<String>,
3363    pub path: PathBuf,
3364    pub sha256: Option<String>,
3365    pub size: Option<u64>,
3366    pub needs_review: bool,
3367}
3368
3369#[cfg(test)]
3370mod script_status_tests {
3371    use super::*;
3372
3373    #[test]
3374    fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3375        let old = SupervisorEntry::new(
3376            "example",
3377            "running",
3378            true,
3379            true,
3380            SupervisorHealthStatus::Unknown,
3381        );
3382        let value = serde_json::to_value(&old).unwrap();
3383        assert!(value.get("script").is_none());
3384        assert!(serde_json::from_value::<SupervisorEntry>(value)
3385            .unwrap()
3386            .script
3387            .is_none());
3388        let current = old.with_script(Some(ScriptModuleStatus {
3389            runtime: "bun".into(),
3390            bun_version: None,
3391            path: "bundle.js".into(),
3392            sha256: Some("ab".repeat(32)),
3393            size: Some(3),
3394            needs_review: true,
3395        }));
3396        let decoded: SupervisorEntry =
3397            serde_json::from_slice(&serde_json::to_vec(&current).unwrap()).unwrap();
3398        assert_eq!(decoded, current);
3399    }
3400}
3401
3402/// A module process's memory and CPU time as read at list time, or why none
3403/// could be read.
3404#[derive(Debug, Clone, PartialEq)]
3405pub enum ChildResourceUsage {
3406    Measured(ChildResourceReading),
3407    Unavailable {
3408        reason: ChildResourceUnavailableReason,
3409    },
3410    /// Future discriminator. `body` retains the complete ordered object; `tag`
3411    /// is its decoded discriminator projection.
3412    Unknown {
3413        tag: String,
3414        body: OrderedJsonObject,
3415    },
3416}
3417
3418/// One reading of a module process's memory and CPU time.
3419/// Use [`ChildResourceReading::new`] and its builders so future fields stay additive.
3420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3421#[non_exhaustive]
3422pub struct ChildResourceReading {
3423    /// Memory in bytes, measured as `memory_kind` says. The figures differ
3424    /// by platform and are not comparable across kinds.
3425    pub memory_bytes: u64,
3426    pub memory_kind: ChildMemoryKind,
3427    /// Bytes swapped out, where the platform reports it per process (Linux).
3428    /// Absent means not reported, not zero.
3429    #[serde(default, skip_serializing_if = "Option::is_none")]
3430    pub swap_bytes: Option<u64>,
3431    /// CPU time spent in user mode since the process started, in
3432    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
3433    /// and the elapsed time between them.
3434    pub cpu_user_ms: u64,
3435    /// CPU time spent in the kernel on the process's behalf since it started,
3436    /// in milliseconds.
3437    pub cpu_system_ms: u64,
3438}
3439
3440impl ChildResourceReading {
3441    /// Create a process reading without optional swap accounting.
3442    #[must_use]
3443    pub fn new(
3444        memory_bytes: u64,
3445        memory_kind: ChildMemoryKind,
3446        cpu_user_ms: u64,
3447        cpu_system_ms: u64,
3448    ) -> Self {
3449        Self {
3450            memory_bytes,
3451            memory_kind,
3452            cpu_user_ms,
3453            cpu_system_ms,
3454            swap_bytes: None,
3455        }
3456    }
3457
3458    /// Set or clear swap bytes where the platform can measure them.
3459    #[must_use]
3460    pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3461        self.swap_bytes = swap_bytes;
3462        self
3463    }
3464}
3465
3466open_string_enum! {
3467    /// What `ChildResourceReading::memory_bytes` measures.
3468    ChildMemoryKind {
3469        /// macOS `phys_footprint`: memory the kernel charges to the process,
3470        /// the figure jetsam acts on. Unlike resident size it does not count
3471        /// pages an allocator has already released with `MADV_FREE`.
3472        PhysFootprint => "phys_footprint",
3473        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
3474        /// included and swapped-out pages excluded.
3475        ResidentSet => "resident_set",
3476        /// Windows `WorkingSetSize`: resident pageable memory, including shared
3477        /// pages, not Unix RSS or private committed bytes.
3478        WindowsWorkingSet => "windows_working_set",
3479    }
3480}
3481
3482open_string_enum! {
3483    /// Why a module process's resources could not be read.
3484    ChildResourceUnavailableReason {
3485        /// The module has no running process.
3486        NotRunning => "not_running",
3487        /// The daemon's platform has no per-process source.
3488        UnsupportedPlatform => "unsupported_platform",
3489        /// The process could not be read, typically because it exited while
3490        /// the list was being answered.
3491        Unreadable => "unreadable",
3492        /// The pid no longer names the process the supervisor spawned, so a
3493        /// reading would describe some other process.
3494        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3495    }
3496}
3497
3498#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3499#[serde(rename_all = "snake_case")]
3500pub enum SupervisorHealthStatus {
3501    Ok,
3502    Degraded,
3503    Failing,
3504    Unresponsive,
3505    Unknown,
3506}
3507
3508#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3509pub struct SupervisorHealthEntry {
3510    pub module_id: String,
3511    pub status: SupervisorHealthStatus,
3512    /// The module's own human-readable note on its state. Absent means the
3513    /// module said nothing, which is the ordinary shape for a healthy module and
3514    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
3515    /// module may reword freely, and `status` plus `metrics` are the machine
3516    /// surface.
3517    #[serde(default, skip_serializing_if = "Option::is_none")]
3518    pub detail: Option<String>,
3519    /// The module's own metrics object, relayed opaquely. Absent means the module
3520    /// published none on this probe — either it reports no metrics at all, or the
3521    /// probe did not reach it — so absence cannot distinguish "nothing to report"
3522    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
3523    #[serde(default, skip_serializing_if = "Option::is_none")]
3524    pub metrics: Option<serde_json::Value>,
3525    pub consecutive_failures: u32,
3526    /// Number of recurring health replies received after their daemon deadline.
3527    /// Each increment is evidence that the module remained alive despite a miss.
3528    #[serde(default)]
3529    pub late_answer_count: u64,
3530    /// End-to-end latency of the newest late reply, measured from probe start.
3531    #[serde(default, skip_serializing_if = "Option::is_none")]
3532    pub last_late_answer_latency_ms: Option<u64>,
3533    /// The escalation the supervisor last took for this module (report, restart,
3534    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
3535    /// succeeded — a module that has never misbehaved and one whose action record
3536    /// predates a daemon restart both present as absent.
3537    #[serde(default)]
3538    pub last_action: Option<String>,
3539    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
3540    /// `last_action` is absent; the pair moves together.
3541    #[serde(default)]
3542    pub last_action_ms: Option<u64>,
3543    /// When the daemon last collected this entry, as unix milliseconds.
3544    ///
3545    /// `supervisor.health` answers from the supervisor's STORED record rather
3546    /// than probing, so every field above describes some moment in the past and
3547    /// nothing here said which. That matters most right after a restart, where
3548    /// the surface is used to confirm a deploy: a record collected before the
3549    /// restart reports the OLD process, reads as a failed deploy, and invites a
3550    /// redeploy of something that was already correct.
3551    ///
3552    /// `None` means never probed — distinct from probed-long-ago, and the reader
3553    /// must not collapse them. Absent on modules that advertise no health
3554    /// capability, which is why it is optional rather than defaulted to zero.
3555    #[serde(default, skip_serializing_if = "Option::is_none")]
3556    pub last_probe_ms: Option<u64>,
3557}
3558
3559#[cfg(test)]
3560mod tests {
3561    #[test]
3562    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3563        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3564        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3565        assert_eq!(decoded.configured_enabled, None);
3566        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3567    }
3568
3569    #[test]
3570    fn configured_enabled_values_round_trip_in_list() {
3571        for enabled in [false, true] {
3572            let entry = SupervisorEntry::new(
3573                "provider",
3574                "running",
3575                true,
3576                true,
3577                SupervisorHealthStatus::Unknown,
3578            )
3579            .with_configured_enabled(Some(enabled));
3580            let entry_json = serde_json::to_value(&entry).unwrap();
3581            assert_eq!(entry_json["configured_enabled"], enabled);
3582            assert_eq!(
3583                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3584                entry
3585            );
3586        }
3587    }
3588
3589    #[test]
3590    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3591        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3592            volume_serial_number: u64::MAX,
3593            file_id: [
3594                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3595            ],
3596        };
3597        let agreement = super::RunningImageAgreement::Match { evidence };
3598        let encoded = serde_json::to_string(&agreement).unwrap();
3599        assert!(encoded.contains("windows_spawn_file_id"));
3600        assert_eq!(
3601            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3602            agreement
3603        );
3604    }
3605
3606    #[test]
3607    fn unix_running_image_evidence_keeps_original_wire_bytes() {
3608        assert_eq!(
3609            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3610                device: 7,
3611                inode: 11
3612            })
3613            .unwrap(),
3614            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3615        );
3616        assert_eq!(
3617            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3618                digest: "abc".to_owned()
3619            })
3620            .unwrap(),
3621            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3622        );
3623    }
3624    use super::*;
3625    use subc_protocol::{BindIdentity, RouteTarget};
3626
3627    #[test]
3628    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3629        let entry = TerminalEntry {
3630            daemon_incarnation: Some("daemon-before-restart".into()),
3631            exit_code: Some(1),
3632            exit_signal: None,
3633            at_ms: 1_700_000_000_123,
3634            disposition: TerminalDisposition::Restarting,
3635            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3636            disposition_detail: None,
3637        };
3638        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3639        assert_eq!(
3640            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3641                ["exit_kind"],
3642            "deliberate_severance"
3643        );
3644
3645        #[derive(serde::Deserialize)]
3646        struct LegacyTerminalEntry {
3647            exit_code: Option<i32>,
3648            exit_signal: Option<i32>,
3649            at_ms: u64,
3650            disposition: TerminalDisposition,
3651        }
3652
3653        let decoded: LegacyTerminalEntry =
3654            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3655        assert_eq!(decoded.exit_code, Some(1));
3656        assert_eq!(decoded.exit_signal, None);
3657        assert_eq!(decoded.at_ms, 1_700_000_000_123);
3658        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3659
3660        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3661        let future: TerminalEntry =
3662            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3663        assert_eq!(
3664            future.exit_kind,
3665            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3666        );
3667    }
3668
3669    #[test]
3670    fn terminal_incarnation_is_optional_for_older_daemons() {
3671        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3672            "at_ms": 123,
3673            "disposition": "stopped"
3674        }))
3675        .unwrap();
3676        let encoded = serde_json::to_value(&entry).unwrap();
3677        assert_eq!(
3678            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3679            (None, None)
3680        );
3681    }
3682
3683    #[test]
3684    fn route_poll_uses_kind_field() {
3685        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3686            route_channel: 7,
3687            route_epoch: 11,
3688            kind: PollKind::Status,
3689        })
3690        .unwrap();
3691
3692        assert_eq!(body["op"], "route.poll");
3693        assert_eq!(body["route_epoch"], 11);
3694        assert_eq!(body["kind"], "status");
3695        assert!(body.get("op").is_some());
3696    }
3697
3698    #[test]
3699    fn route_open_is_internally_tagged() {
3700        let request = ClientControlRequest::RouteOpen {
3701            busy_refusals: None,
3702            target: RouteTarget::ToolProvider {
3703                module_id: "aft".to_string(),
3704            },
3705            identity: BindIdentity::new("opencode", "session-1"),
3706            consumer_identity: None,
3707            consumer_capabilities: None,
3708            role_versions: None,
3709            admission_facts: None,
3710            scope: None,
3711        };
3712
3713        let body = serde_json::to_value(request).unwrap();
3714        assert_eq!(body["op"], "route.open");
3715        assert_eq!(body["target"]["kind"], "tool_provider");
3716        assert!(body.get("consumer_identity").is_none());
3717        assert!(body.get("consumer_capabilities").is_none());
3718        assert!(body.get("role_versions").is_none());
3719    }
3720
3721    #[test]
3722    fn route_open_without_optional_fields_still_decodes() {
3723        let body = serde_json::json!({
3724            "op": "route.open",
3725            "target": { "kind": "tool_provider", "module_id": "aft" },
3726            "identity": {
3727                "project_root": "/tmp/project",
3728                "harness": "opencode",
3729                "session": "session-1"
3730            }
3731        });
3732
3733        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3734        let ClientControlRequest::RouteOpen {
3735            consumer_identity,
3736            consumer_capabilities,
3737            role_versions,
3738            admission_facts,
3739            ..
3740        } = decoded
3741        else {
3742            panic!("decoded wrong request variant");
3743        };
3744        assert_eq!(consumer_identity, None);
3745        assert_eq!(consumer_capabilities, None);
3746        assert_eq!(role_versions, None);
3747        assert_eq!(admission_facts, None);
3748    }
3749
3750    #[test]
3751    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3752        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3753        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3754        match decoded {
3755            ClientControlPush::RouteClosed {
3756                excluded_subscriptions,
3757                terminal,
3758                ..
3759            } => {
3760                assert_eq!(excluded_subscriptions, 0);
3761                assert_eq!(terminal, None);
3762            }
3763            other => panic!("unexpected push: {other:?}"),
3764        }
3765        assert!(!serde_json::to_string(&decoded)
3766            .unwrap()
3767            .contains("terminal"));
3768    }
3769
3770    #[test]
3771    fn old_route_closed_decoder_ignores_new_terminal_field() {
3772        #[derive(serde::Deserialize)]
3773        #[serde(tag = "op")]
3774        enum LegacyClientControlPush {
3775            #[serde(rename = "route.closed")]
3776            RouteClosed {
3777                module_id: String,
3778                reason: RouteCloseReason,
3779                drained: bool,
3780                abandoned: u32,
3781            },
3782        }
3783
3784        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3785        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3786        match decoded {
3787            LegacyClientControlPush::RouteClosed {
3788                module_id,
3789                reason,
3790                drained,
3791                abandoned,
3792            } => {
3793                assert_eq!(module_id, "aft-tools");
3794                assert_eq!(reason, RouteCloseReason::Crash);
3795                assert!(!drained);
3796                assert_eq!(abandoned, 0);
3797            }
3798        }
3799    }
3800
3801    #[test]
3802    fn supervisor_routes_is_a_control_plane_request() {
3803        let body = serde_json::json!({
3804            "op": "supervisor.routes",
3805            "module_id": "aft"
3806        });
3807
3808        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3809        assert_eq!(serde_json::to_value(request).unwrap(), body);
3810    }
3811
3812    #[test]
3813    fn diagnostic_string_enums_retain_unknown_wire_values() {
3814        let reason: RunningImageUnavailableReason =
3815            serde_json::from_str("\"future_reason\"").unwrap();
3816        let disposition: TerminalDisposition =
3817            serde_json::from_str("\"future_disposition\"").unwrap();
3818
3819        assert_eq!(
3820            reason,
3821            RunningImageUnavailableReason::Unknown("future_reason".to_string())
3822        );
3823        assert_eq!(
3824            disposition,
3825            TerminalDisposition::Unknown("future_disposition".to_string())
3826        );
3827    }
3828
3829    #[test]
3830    fn diagnostic_string_enums_preserve_existing_wire_names() {
3831        let names = [
3832            (RunningImageUnavailableReason::NotRunning, "not_running"),
3833            (
3834                RunningImageUnavailableReason::UnsupportedPlatform,
3835                "unsupported_platform",
3836            ),
3837            (
3838                RunningImageUnavailableReason::RunningExecutableUnreadable,
3839                "running_executable_unreadable",
3840            ),
3841            (
3842                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3843                "running_executable_permission_denied",
3844            ),
3845            (
3846                RunningImageUnavailableReason::ProcessHidden,
3847                "process_hidden",
3848            ),
3849            (
3850                RunningImageUnavailableReason::SpawnedPathUnreadable,
3851                "spawned_path_unreadable",
3852            ),
3853            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3854            (
3855                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3856                "process_identity_unconfirmed",
3857            ),
3858        ];
3859        for (value, expected) in names {
3860            let wire = serde_json::to_string(&value).unwrap();
3861            assert_eq!(wire, format!("\"{expected}\""));
3862            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3863            assert_eq!(decoded, value);
3864        }
3865
3866        for (value, expected) in [
3867            (TerminalDisposition::Stopped, "stopped"),
3868            (TerminalDisposition::Disabled, "disabled"),
3869            (TerminalDisposition::Failed, "failed"),
3870            (TerminalDisposition::Restarting, "restarting"),
3871            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3872        ] {
3873            let wire = serde_json::to_string(&value).unwrap();
3874            assert_eq!(wire, format!("\"{expected}\""));
3875            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3876            assert_eq!(decoded, value);
3877        }
3878    }
3879
3880    #[test]
3881    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3882        let entry = SupervisorEntry::new(
3883            "waiting-module",
3884            "starting",
3885            true,
3886            false,
3887            SupervisorHealthStatus::Unknown,
3888        );
3889        let old_wire = serde_json::to_value(&entry).unwrap();
3890        assert!(old_wire.get("waiting_for_previous_pid").is_none());
3891        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3892        assert_eq!(decoded.waiting_for_previous_pid, None);
3893        let entry = entry.with_waiting_for_previous_pid(Some(42));
3894        let wire = serde_json::to_value(&entry).unwrap();
3895        assert_eq!(wire["waiting_for_previous_pid"], 42);
3896        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3897        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3898    }
3899
3900    #[test]
3901    fn supervisor_waiting_previous_detail_is_optional_and_round_trips() {
3902        let entry = SupervisorEntry::new(
3903            "worker",
3904            "starting",
3905            true,
3906            false,
3907            SupervisorHealthStatus::Unknown,
3908        )
3909        .with_waiting_for_previous_pid(Some(41));
3910        let old_wire = serde_json::to_value(&entry).unwrap();
3911        assert!(old_wire.get("waiting_for_previous_detail").is_none());
3912        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3913        assert_eq!(decoded.waiting_for_previous_detail, None);
3914        let detail = "waiting: container survivors (pids [42])";
3915        let wire =
3916            serde_json::to_value(entry.with_waiting_for_previous_detail(Some(detail.into())))
3917                .unwrap();
3918        assert_eq!(wire["waiting_for_previous_pid"], 41);
3919        assert_eq!(wire["waiting_for_previous_detail"], detail);
3920        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3921        assert_eq!(decoded.waiting_for_previous_detail.as_deref(), Some(detail));
3922    }
3923
3924    #[test]
3925    fn diagnostic_string_enums_reject_non_string_bodies() {
3926        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3927        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3928    }
3929
3930    #[test]
3931    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3932        let body = serde_json::json!({
3933            "op": "supervisor.provenance",
3934            "daemon": {
3935                "daemon_build": {},
3936                "daemon_observed": {
3937                    "running_image": {
3938                        "status": "unavailable",
3939                        "reason": "not_running"
3940                    }
3941                }
3942            },
3943            "modules": [
3944                {
3945                    "module_id": "future",
3946                    "module_declared": { "status": "unverifiable" },
3947                    "daemon_observed": {
3948                        "running_image": {
3949                            "status": "unavailable",
3950                            "reason": "future_reason"
3951                        }
3952                    }
3953                },
3954                {
3955                    "module_id": "healthy-a",
3956                    "module_declared": { "status": "unverifiable" },
3957                    "daemon_observed": {
3958                        "running_image": {
3959                            "status": "match",
3960                            "evidence": {
3961                                "method": "linux_proc_sha256",
3962                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3963                            }
3964                        }
3965                    }
3966                },
3967                {
3968                    "module_id": "healthy-b",
3969                    "module_declared": { "status": "unverifiable" },
3970                    "daemon_observed": {
3971                        "running_image": {
3972                            "status": "unavailable",
3973                            "reason": "unsupported_platform"
3974                        }
3975                    }
3976                }
3977            ]
3978        });
3979
3980        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3981        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3982            panic!("decoded wrong response variant");
3983        };
3984        assert_eq!(modules.len(), 3);
3985        assert_eq!(modules[0].module_id, "future");
3986        assert_eq!(
3987            modules[0].daemon_observed.running_image,
3988            RunningImageAgreement::Unavailable {
3989                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3990            }
3991        );
3992        assert_eq!(modules[1].module_id, "healthy-a");
3993        assert_eq!(modules[2].module_id, "healthy-b");
3994    }
3995
3996    #[test]
3997    fn tagged_unknown_values_retain_tag_and_body() {
3998        macro_rules! assert_unknown_round_trip {
3999            ($ty:ident, $field:literal, $value:expr) => {
4000                let value = $value;
4001                let wire = serde_json::to_string(&value).unwrap();
4002                let decoded: $ty = serde_json::from_str(&wire).unwrap();
4003                match decoded {
4004                    $ty::Unknown { tag, body } => {
4005                        assert_eq!(tag, value[$field].as_str().unwrap());
4006                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
4007                    }
4008                    _ => panic!("decoded known variant"),
4009                }
4010            };
4011        }
4012
4013        assert_unknown_round_trip!(
4014            ModuleDeclaredProvenance,
4015            "status",
4016            serde_json::json!({"status": "future", "build": {"version": 7}})
4017        );
4018        assert_unknown_round_trip!(
4019            RunningImageAgreement,
4020            "status",
4021            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
4022        );
4023        assert_unknown_round_trip!(
4024            RunningImageEvidence,
4025            "method",
4026            serde_json::json!({"method": "future", "digest": "abc"})
4027        );
4028        assert_unknown_round_trip!(
4029            SupervisorRouteConsumer,
4030            "kind",
4031            serde_json::json!({"kind": "future", "module_id": "m"})
4032        );
4033        assert_unknown_round_trip!(
4034            StderrCaptureState,
4035            "state",
4036            serde_json::json!({"state": "future", "reason": "because"})
4037        );
4038        assert_unknown_round_trip!(
4039            StderrTailEntry,
4040            "kind",
4041            serde_json::json!({"kind": "future", "text": "line"})
4042        );
4043        assert_unknown_round_trip!(
4044            ChildResourceUsage,
4045            "status",
4046            serde_json::json!({"status": "future", "memory_bytes": 1})
4047        );
4048    }
4049
4050    #[test]
4051    fn child_resource_usage_round_trips_both_known_states() {
4052        let measured = ChildResourceUsage::Measured(ChildResourceReading {
4053            memory_bytes: 0,
4054            memory_kind: ChildMemoryKind::ResidentSet,
4055            swap_bytes: Some(0),
4056            cpu_user_ms: 0,
4057            cpu_system_ms: 0,
4058        });
4059        let wire = serde_json::to_value(&measured).unwrap();
4060        assert_eq!(
4061            wire,
4062            serde_json::json!({
4063                "status": "measured",
4064                "memory_bytes": 0,
4065                "memory_kind": "resident_set",
4066                "swap_bytes": 0,
4067                "cpu_user_ms": 0,
4068                "cpu_system_ms": 0
4069            })
4070        );
4071        assert_eq!(
4072            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4073            measured
4074        );
4075
4076        let unavailable = ChildResourceUsage::Unavailable {
4077            reason: ChildResourceUnavailableReason::NotRunning,
4078        };
4079        let wire = serde_json::to_value(&unavailable).unwrap();
4080        assert_eq!(
4081            wire,
4082            serde_json::json!({"status": "unavailable", "reason": "not_running"})
4083        );
4084        assert_eq!(
4085            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4086            unavailable
4087        );
4088    }
4089
4090    #[test]
4091    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4092        // A current daemon stamps each line; an older one sends no `at_ms`.
4093        // Both must decode, and the absent case must stay absent rather than
4094        // turn into a time nobody recorded.
4095        let stamped: StderrTailEntry = serde_json::from_str(
4096            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4097        )
4098        .unwrap();
4099        assert_eq!(
4100            stamped,
4101            StderrTailEntry::Line {
4102                text: "boom".to_string(),
4103                truncated: true,
4104                at_ms: Some(1_789_801_440_685),
4105            }
4106        );
4107        let unstamped: StderrTailEntry =
4108            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4109        assert_eq!(
4110            unstamped,
4111            StderrTailEntry::Line {
4112                text: "boom".to_string(),
4113                truncated: false,
4114                at_ms: None,
4115            }
4116        );
4117        // Absent stays absent on the way out, so a reply without stamps is
4118        // exactly what an older daemon would have sent.
4119        assert_eq!(
4120            serde_json::to_string(&unstamped).unwrap(),
4121            r#"{"kind":"line","text":"boom"}"#
4122        );
4123        assert_eq!(
4124            serde_json::to_value(&stamped).unwrap()["at_ms"],
4125            serde_json::json!(1_789_801_440_685u64)
4126        );
4127    }
4128
4129    #[test]
4130    fn tagged_unknown_values_round_trip_the_original_json() {
4131        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4132        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4133        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4134    }
4135
4136    #[test]
4137    fn tagged_unknown_values_round_trip_trailing_tag() {
4138        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4139        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4140        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4141
4142        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4143        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4144        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4145    }
4146
4147    #[test]
4148    fn tagged_unknown_values_round_trip_middle_tag() {
4149        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4150        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4151        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4152
4153        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4154        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4155        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4156    }
4157
4158    #[test]
4159    fn tagged_unknown_values_round_trip_deep_payload() {
4160        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4161        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4162        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4163
4164        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4165        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4166        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4167    }
4168
4169    #[test]
4170    fn tagged_unknown_values_reject_non_object_bodies() {
4171        for wire in ["42", r#""future""#, "[]"] {
4172            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4173            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4174        }
4175    }
4176
4177    #[test]
4178    fn duplicate_discriminators_reject_without_panicking() {
4179        assert_eq!(
4180            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4181                .unwrap(),
4182            ModuleDeclaredProvenance::Unverifiable
4183        );
4184        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4185            .unwrap()
4186        {
4187            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4188            _ => panic!("future discriminator decoded as a known variant"),
4189        }
4190
4191        let wires = [
4192            r#"{"status":"reported","status":"unverifiable"}"#,
4193            r#"{"status":"unverifiable","status":"reported"}"#,
4194            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4195            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4196        ];
4197
4198        for wire in wires {
4199            let result =
4200                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4201            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4202            assert!(
4203                result.unwrap().is_err(),
4204                "duplicate discriminator decoded: {wire}"
4205            );
4206        }
4207
4208        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4209        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4210        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4211        assert!(
4212            result.unwrap().is_err(),
4213            "duplicate discriminator decoded: {wire}"
4214        );
4215    }
4216
4217    #[test]
4218    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4219        let known_wire =
4220            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4221        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4222        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4223
4224        for wire in [
4225            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4226            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4227        ] {
4228            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4229            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4230        }
4231
4232        for wire in [
4233            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4234            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4235        ] {
4236            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4237            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4238        }
4239
4240        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4241        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4242        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4243
4244        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4245        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4246        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4247    }
4248
4249    #[test]
4250    fn tagged_unknown_member_does_not_discard_known_siblings() {
4251        let body = serde_json::json!({
4252            "modules": [{
4253                "module_id": "target",
4254                "routes": [
4255                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4256                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4257                ]
4258            }]
4259        });
4260        let decoded: ClientControlResponse = serde_json::from_value(
4261            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4262        )
4263        .unwrap();
4264        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4265            panic!("decoded wrong response variant");
4266        };
4267        assert_eq!(modules[0].routes.len(), 2);
4268        assert_eq!(
4269            modules[0].routes[1].consumer,
4270            SupervisorRouteConsumer::Direct { connection_id: 7 }
4271        );
4272    }
4273}
4274
4275#[cfg(test)]
4276mod launch_nonce_redaction_tests {
4277    use super::*;
4278
4279    const NONCE: &str = "nonce-f00dfeed1234abcd";
4280
4281    fn identity() -> ConsumerIdentity {
4282        ConsumerIdentity {
4283            module_id: "wernicke".to_string(),
4284            launch_nonce: NONCE.to_string(),
4285        }
4286    }
4287
4288    #[test]
4289    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4290        let printed = format!("{:?}", identity());
4291        assert!(printed.contains("wernicke"), "{printed}");
4292        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4293    }
4294
4295    #[test]
4296    fn route_open_request_debug_never_prints_the_nonce() {
4297        let request = ClientControlRequest::RouteOpen {
4298            busy_refusals: None,
4299            target: subc_protocol::RouteTarget::ToolProvider {
4300                module_id: "broca".to_string(),
4301            },
4302            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4303            consumer_identity: Some(identity()),
4304            consumer_capabilities: None,
4305            role_versions: None,
4306            admission_facts: None,
4307            scope: None,
4308        };
4309        let printed = format!("{request:?}");
4310        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4311    }
4312}
4313
4314#[cfg(test)]
4315mod reader_skew_tests {
4316    use super::*;
4317    use serde_json::{json, Value};
4318
4319    fn catalog() -> Value {
4320        json!({"module_id": "provider", "roles": [], "control_ops": []})
4321    }
4322
4323    fn reply() -> Value {
4324        json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4325    }
4326
4327    fn target() -> Value {
4328        json!({
4329            "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4330            "authority_epoch": 23, "first_party": true,
4331            "approved_declarations_digest": "approved"
4332        })
4333    }
4334
4335    fn request() -> Value {
4336        json!({
4337            "op": "route.open",
4338            "target": {"kind": "tool_provider", "module_id": "provider"},
4339            "identity": {"harness": "test", "session": "session-1"}
4340        })
4341    }
4342
4343    #[test]
4344    fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4345        let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4346        let built = CatalogEntry::new("provider", vec![], vec![]);
4347        assert_eq!(old, built);
4348        assert_eq!(old.first_party, None);
4349        let old_bytes = serde_json::to_value(&old).unwrap();
4350        let additions = json!({
4351            "incarnation": "daemon", "spawn": 17, "first_party": false,
4352            "origin": "development", "requested_declarations_digest": "requested",
4353            "approved_declarations_digest": "approved"
4354        });
4355        let mut body = catalog();
4356        for (key, value) in additions.as_object().unwrap() {
4357            assert!(old_bytes.get(key).is_none(), "{key}");
4358            body[key] = value.clone();
4359        }
4360        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4361        let encoded = serde_json::to_value(&decoded).unwrap();
4362        for (key, value) in additions.as_object().unwrap() {
4363            assert_eq!(&encoded[key], value, "{key}");
4364        }
4365        assert_eq!(decoded.first_party, Some(false));
4366        assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4367    }
4368
4369    #[test]
4370    fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4371        let mut body = catalog();
4372        body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4373        body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4374        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4375        let encoded = serde_json::to_value(decoded).unwrap();
4376        for key in ["requested_declarations", "approved_declarations"] {
4377            assert_eq!(encoded[key], body[key]);
4378        }
4379        let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4380        assert_eq!(unfiltered.approved_declarations, None);
4381        assert_eq!(unfiltered.requested_declarations, None);
4382    }
4383
4384    #[test]
4385    fn reader_skew_catalog_unknown_origin_is_other() {
4386        let mut body = catalog();
4387        body["origin"] = json!("future-origin");
4388        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4389        assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4390    }
4391
4392    #[test]
4393    fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4394        let mut body = catalog();
4395        body["spawn"] = json!(9_007_199_254_740_991_u64);
4396        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4397        assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4398        for invalid in [
4399            json!(9_007_199_254_740_992_u64),
4400            json!(-1),
4401            json!(1.5),
4402            json!("17"),
4403        ] {
4404            body["spawn"] = invalid;
4405            assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4406        }
4407    }
4408
4409    #[test]
4410    fn reader_skew_catalog_watch_request_uses_subscription_op() {
4411        let body = json!({"op": "catalog.watch"});
4412        let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4413        assert_eq!(request, CatalogWatchRequest::new());
4414        assert_eq!(serde_json::to_value(request).unwrap(), body);
4415        assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4416        for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4417            assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4418        }
4419    }
4420
4421    #[test]
4422    fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4423        for generation in [0, 19, 42] {
4424            let body = json!({"op": "catalog.watch", "generation": generation});
4425            let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4426            assert_eq!(push, CatalogWatchResponse::new(generation));
4427            assert_eq!(serde_json::to_value(push).unwrap(), body);
4428        }
4429        assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4430        for invalid in [
4431            json!({"op": "catalog.watch"}),
4432            json!({"op": "activity.subscribe", "generation": 1}),
4433        ] {
4434            assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4435        }
4436    }
4437
4438    #[test]
4439    fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4440        let mut body = reply();
4441        let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4442        let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4443        assert_eq!(empty, RouteOpenReplyExt::new());
4444        empty.write_to(&mut body).unwrap();
4445        assert_eq!(body, reply());
4446        body["target"] = target();
4447        let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4448        assert_eq!(
4449            decoded.target.as_ref().unwrap().kind,
4450            RouteOpenTargetKind::Spawn
4451        );
4452        let mut encoded = reply();
4453        RouteOpenReplyExt::new()
4454            .with_target(decoded.target)
4455            .write_to(&mut encoded)
4456            .unwrap();
4457        assert_eq!(encoded, body);
4458        assert_eq!(
4459            serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4460            legacy
4461        );
4462        RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4463        assert_eq!(encoded, reply());
4464    }
4465
4466    #[test]
4467    fn reader_skew_route_open_incomplete_target_is_unmarked() {
4468        let mut body = reply();
4469        body["target"] = target();
4470        assert!(RouteOpenReplyExt::read_from(&body)
4471            .unwrap()
4472            .target
4473            .is_some());
4474        for key in [
4475            "incarnation",
4476            "kind",
4477            "spawn",
4478            "authority_epoch",
4479            "first_party",
4480            "approved_declarations_digest",
4481        ] {
4482            let mut incomplete = body.clone();
4483            incomplete["target"].as_object_mut().unwrap().remove(key);
4484            assert_eq!(
4485                RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4486                None,
4487                "{key}"
4488            );
4489        }
4490        body["target"] = Value::Null;
4491        assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4492    }
4493
4494    #[test]
4495    fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4496        for (kind, expected) in [
4497            ("prefix", RouteOpenTargetKind::Prefix),
4498            ("unsupervised", RouteOpenTargetKind::Unsupervised),
4499        ] {
4500            let mut body = reply();
4501            body["target"] = target();
4502            body["target"]["kind"] = json!(kind);
4503            // Spawn-only keys are not parsed, even when a future kind reuses them.
4504            body["target"]["spawn"] = json!("not-a-spawn");
4505            body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4506            body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4507            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4508            let target = ext.target.as_ref().unwrap();
4509            assert_eq!(target.kind, expected);
4510            assert_eq!(target.spawn, None);
4511            assert_eq!(target.authority_epoch, None);
4512            assert_eq!(target.approved_declarations_digest, None);
4513            assert!(!target.first_party);
4514            let mut encoded = reply();
4515            ext.write_to(&mut encoded).unwrap();
4516            for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4517                assert!(encoded["target"].get(key).is_none());
4518            }
4519        }
4520    }
4521
4522    #[test]
4523    fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4524        let mut body = reply();
4525        body["target"] = target();
4526        body["target"]["kind"] = json!("future-kind");
4527        let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4528        let target = ext.target.unwrap();
4529        assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4530        assert_eq!(target.spawn, None);
4531        assert_eq!(target.authority_epoch, None);
4532        assert_eq!(target.approved_declarations_digest, None);
4533        assert!(!target.first_party);
4534    }
4535
4536    #[test]
4537    fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4538        for field in ["spawn", "authority_epoch"] {
4539            let mut body = reply();
4540            body["target"] = target();
4541            body["target"][field] = json!(9_007_199_254_740_991_u64);
4542            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4543            assert_eq!(
4544                serde_json::to_value(ext).unwrap()["target"][field],
4545                9_007_199_254_740_991_u64
4546            );
4547            for invalid in [
4548                json!(9_007_199_254_740_992_u64),
4549                json!(-1),
4550                json!(1.5),
4551                json!("17"),
4552            ] {
4553                body["target"][field] = invalid;
4554                assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4555                let mut incomplete = body.clone();
4556                incomplete["target"]
4557                    .as_object_mut()
4558                    .unwrap()
4559                    .remove("incarnation");
4560                assert!(
4561                    RouteOpenReplyExt::read_from(&incomplete).is_err(),
4562                    "{field}"
4563                );
4564            }
4565        }
4566    }
4567
4568    #[test]
4569    fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4570        let mut body = request();
4571        let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4572        assert_eq!(
4573            RouteOpenRequestExt::read_from(&body).unwrap(),
4574            RouteOpenRequestExt::new()
4575        );
4576        RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4577        assert_eq!(body, request());
4578        body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4579        let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4580        assert_eq!(
4581            decoded.accepts_close_reasons,
4582            Some(vec!["authority_changed".into(), "future-reason".into()])
4583        );
4584        let mut encoded = request();
4585        RouteOpenRequestExt::new()
4586            .with_accepts_close_reasons(decoded.accepts_close_reasons)
4587            .write_to(&mut encoded)
4588            .unwrap();
4589        assert_eq!(encoded, body);
4590        assert_eq!(
4591            serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4592            legacy
4593        );
4594        RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4595        assert_eq!(encoded, request());
4596        assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4597    }
4598
4599    #[test]
4600    fn reader_skew_route_open_helpers_refuse_other_bodies() {
4601        for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4602            assert!(RouteOpenRequestExt::read_from(&body).is_err());
4603            assert!(RouteOpenReplyExt::read_from(&body).is_err());
4604            assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4605            assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4606        }
4607    }
4608
4609    #[test]
4610    fn reader_skew_route_open_target_constructor_validates_like_reader() {
4611        let spawn = RouteOpenTarget::new(
4612            "daemon",
4613            RouteOpenTargetKind::Spawn,
4614            Some(17),
4615            Some(23),
4616            true,
4617            Some("approved".into()),
4618        )
4619        .unwrap();
4620        assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4621        for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4622            assert!(RouteOpenTarget::new(
4623                "daemon",
4624                RouteOpenTargetKind::Spawn,
4625                Some(spawn),
4626                Some(epoch),
4627                true,
4628                Some("approved".into())
4629            )
4630            .is_err());
4631        }
4632    }
4633}
4634
4635#[cfg(test)]
4636mod claim_wire_tests {
4637    use super::*;
4638    use serde_json::{json, Value};
4639
4640    fn legacy_provenance() -> SupervisorModuleProvenance {
4641        SupervisorModuleProvenance {
4642            module_id: "worker".into(),
4643            module_declared: ModuleDeclaredProvenance::Unverifiable,
4644            daemon_observed: SupervisorObservedProcess {
4645                launch_nonce_source: None,
4646                pid: None,
4647                spawned_at_ms: None,
4648                spawned_from: None,
4649                running_image: RunningImageAgreement::Unavailable {
4650                    reason: RunningImageUnavailableReason::NotRunning,
4651                },
4652            },
4653        }
4654    }
4655
4656    #[test]
4657    fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4658        let legacy = legacy_provenance();
4659        let original = serde_json::to_value(&legacy).unwrap();
4660        let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4661        assert_eq!(absent.registration, None);
4662        let mut wire = original.clone();
4663        absent.write_to(&mut wire).unwrap();
4664        assert_eq!(wire, original);
4665        for (method, spelling) in [
4666            (RegistrationMethod::Channel, "channel"),
4667            (RegistrationMethod::Nonce, "nonce"),
4668        ] {
4669            let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4670            ext.write_to(&mut wire).unwrap();
4671            assert_eq!(wire["registration"], spelling);
4672            assert_eq!(
4673                SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4674                ext
4675            );
4676            let old_reader: SupervisorModuleProvenance =
4677                serde_json::from_value(wire.clone()).unwrap();
4678            assert_eq!(old_reader, legacy);
4679            assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4680        }
4681        absent.write_to(&mut wire).unwrap();
4682        assert_eq!(wire, original);
4683        for mut invalid in [Value::Null, json!([]), json!("entry")] {
4684            assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4685            assert!(absent.write_to(&mut invalid).is_err());
4686        }
4687    }
4688
4689    #[test]
4690    fn provenance_waiting_previous_detail_preserves_legacy_entry() {
4691        let legacy = legacy_provenance();
4692        let mut wire = serde_json::to_value(&legacy).unwrap();
4693        let absent = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4694        assert_eq!(absent.waiting_for_previous_detail, None);
4695        let detail = "waiting: container survivors (pids [42])";
4696        let ext = absent
4697            .clone()
4698            .with_waiting_for_previous_detail(Some(detail.into()));
4699        ext.write_to(&mut wire).unwrap();
4700        assert_eq!(wire["waiting_for_previous_detail"], detail);
4701        assert_eq!(
4702            SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4703            ext
4704        );
4705        assert_eq!(
4706            serde_json::from_value::<SupervisorModuleProvenance>(wire.clone()).unwrap(),
4707            legacy
4708        );
4709        absent.write_to(&mut wire).unwrap();
4710        assert!(wire.get("waiting_for_previous_detail").is_none());
4711    }
4712
4713    #[test]
4714    fn provenance_unknown_registration_is_not_channel_or_nonce() {
4715        let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4716        wire["registration"] = json!("future_method");
4717        let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4718        assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4719        assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4720        assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4721        wire["registration"] = json!(false);
4722        assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4723    }
4724
4725    #[test]
4726    fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4727        let original = serde_json::to_value(legacy_provenance()).unwrap();
4728        for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4729            let mut golden = original.clone();
4730            golden["registration_declaration"] = json!(declaration);
4731            let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4732            assert_eq!(
4733                serde_json::to_value(&extension).unwrap(),
4734                json!({
4735                    "registration_declaration": declaration
4736                })
4737            );
4738            let mut written = original.clone();
4739            extension.write_to(&mut written).unwrap();
4740            assert_eq!(written, golden);
4741            assert_eq!(
4742                serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4743                legacy_provenance()
4744            );
4745            SupervisorModuleProvenanceExt::new()
4746                .write_to(&mut written)
4747                .unwrap();
4748            assert_eq!(written, original);
4749        }
4750    }
4751
4752    #[test]
4753    fn admission_refusal_is_optional_and_open() {
4754        let entry = SupervisorEntry::new(
4755            "worker",
4756            "stopped",
4757            true,
4758            false,
4759            SupervisorHealthStatus::Unknown,
4760        );
4761        let original = serde_json::to_value(&entry).unwrap();
4762        assert!(original.get("admission_refused").is_none());
4763        let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4764        assert_eq!(read.admission_refused, None);
4765        assert_eq!(serde_json::to_value(read).unwrap(), original);
4766        assert_eq!(
4767            REGISTRATION_CHANNEL_UNSUPPORTED,
4768            "registration_channel_unsupported"
4769        );
4770        for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4771            let mut wire = original.clone();
4772            wire["admission_refused"] = json!(reason);
4773            let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4774            assert_eq!(read.admission_refused.as_deref(), Some(reason));
4775            assert_eq!(serde_json::to_value(read).unwrap(), wire);
4776            let built = entry.clone().with_admission_refused(Some(reason.into()));
4777            assert_eq!(serde_json::to_value(built).unwrap(), wire);
4778        }
4779    }
4780}