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