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