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