Skip to main content

subc_control/
lib.rs

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