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