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