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