Skip to main content

subc_control/
lib.rs

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