Skip to main content

subc_control/
lib.rs

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