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