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    /// Why admission was refused. This is an open string: readers must not
2955    /// match exhaustively. `registration_channel_unsupported` means the gated
2956    /// module lacks its support declaration, not a crash to restart.
2957    #[serde(default, skip_serializing_if = "Option::is_none")]
2958    pub admission_refused: Option<String>,
2959    /// Estimated Unix milliseconds of the next retry after restart-budget
2960    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
2961    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
2962    #[serde(default, skip_serializing_if = "Option::is_none")]
2963    pub next_retry_at_ms: Option<u64>,
2964    pub enabled: bool,
2965    /// The enabled value in the daemon's loaded configuration, not a stored
2966    /// drift flag. Absent when there is no configured entry or on older daemons.
2967    #[serde(default, skip_serializing_if = "Option::is_none")]
2968    pub configured_enabled: Option<bool>,
2969    /// Whether this module is serving.
2970    ///
2971    /// For a `Subc` module: enabled, running, process alive, AND registered.
2972    /// For a `None` module the registration term is dropped, because a module
2973    /// that speaks no subc wire never registers and the daemon cannot assert
2974    /// more than "the process it launched is alive". READ IT WITH `protocol`:
2975    /// `live: true` means something weaker for a `None` module, and a renderer
2976    /// that prints it as a bare boolean for one is claiming more than the daemon
2977    /// knows.
2978    pub live: bool,
2979    /// The module's declared wire protocol. Absent on daemons predating the
2980    /// field, where every module was a subc module, so the default is exactly
2981    /// what those daemons meant.
2982    #[serde(default)]
2983    pub protocol: ModuleProtocol,
2984    /// Retained for one release for older status consumers: false on Unix, true
2985    /// on Windows. Non-wire modules receive no nonce on either platform.
2986    #[serde(default, skip_serializing_if = "Option::is_none")]
2987    pub launch_nonce_env: Option<bool>,
2988    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
2989    /// process read all bytes, otherwise `env` for the offered environment copy.
2990    /// Returned in `supervisor.list`, independently of the source the module
2991    /// declares in `manifest.provenance.launch_nonce_source` when registering.
2992    /// Processes that do not speak the wire protocol and stopped modules omit it.
2993    #[serde(default, skip_serializing_if = "Option::is_none")]
2994    pub launch_nonce_source: Option<String>,
2995    pub health: SupervisorHealthStatus,
2996    /// Computed from the stored launch spec and observed process at list time;
2997    /// None means an older daemon did not report this comparison.
2998    #[serde(default, skip_serializing_if = "Option::is_none")]
2999    pub pending_reload: Option<PendingReloadVerdict>,
3000    /// When the daemon last collected this module's health, as unix
3001    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
3002    /// window, whose `health` is therefore `Unknown` rather than good), not
3003    /// probed-long-ago. An old value and an absent one call for opposite
3004    /// readings, so do not render them alike.
3005    #[serde(default)]
3006    pub last_probe_ms: Option<u64>,
3007    /// Exit code of the module's most recent process exit, if the process has
3008    /// exited at least once. Survives respawn so a now-`running` module still
3009    /// reports what killed its previous incarnation.
3010    #[serde(default, skip_serializing_if = "Option::is_none")]
3011    pub last_exit_code: Option<i32>,
3012    /// Terminating signal of the module's most recent process exit (Unix), if
3013    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
3014    /// (often a panic-abort). Survives respawn.
3015    #[serde(default, skip_serializing_if = "Option::is_none")]
3016    pub last_exit_signal: Option<i32>,
3017    /// Unix milliseconds when the most recent child exit was observed. Present
3018    /// even when the terminal ring is not queried, so existing list readers can
3019    /// order their latest observed exit against events they already received.
3020    #[serde(default, skip_serializing_if = "Option::is_none")]
3021    pub last_exit_ms: Option<u64>,
3022    /// Classification of the most recent child exit. Absent on daemons that
3023    /// predate exit-kind reporting.
3024    #[serde(default, skip_serializing_if = "Option::is_none")]
3025    pub last_exit_kind: Option<TerminalExitKind>,
3026    /// Replacement processes spawned for this module so far, against the budget
3027    /// that disables it.
3028    ///
3029    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
3030    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
3031    /// successful probe, so a module can miss probes all day and read zero; this
3032    /// one only decreases when an operator restarts, reloads, or re-enables the
3033    /// module. Reaching the budget moves it to `Failed` and it stays there until
3034    /// somebody intervenes.
3035    ///
3036    /// So a module one restart from being disabled is indistinguishable from a
3037    /// freshly booted one unless this pair is read. Both are reported together
3038    /// because the count alone does not say how close it is.
3039    ///
3040    /// Absent from daemons predating the field, which is why it is optional
3041    /// rather than defaulted to zero: zero would assert a full budget.
3042    #[serde(default, skip_serializing_if = "Option::is_none")]
3043    pub restart_count: Option<u32>,
3044    /// Replacement processes this module is allowed before it is disabled. See
3045    /// `restart_count`; absent on daemons predating the field.
3046    #[serde(default, skip_serializing_if = "Option::is_none")]
3047    pub max_restarts: Option<u32>,
3048    /// Replacement processes spawned over this module's entire supervisor lifetime.
3049    /// Unlike `restart_count`, this value is never reset by an operator action.
3050    #[serde(default, skip_serializing_if = "Option::is_none")]
3051    pub lifetime_restarts: Option<u32>,
3052    /// Successful child spawns in this daemon incarnation. Zero means the
3053    /// module has not successfully spawned; every successful spawn increments
3054    /// the value exactly once.
3055    #[serde(default, skip_serializing_if = "Option::is_none")]
3056    pub spawn_generation: Option<u64>,
3057    /// The span `restart_count` is counted over, in seconds. The crash budget is
3058    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
3059    /// inside the last `restart_window_secs`, and older ones no longer hold a
3060    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
3061    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
3062    /// reactions.
3063    ///
3064    /// Absent on daemons predating the windowed budget, where the count really
3065    /// was a lifetime total.
3066    #[serde(default, skip_serializing_if = "Option::is_none")]
3067    pub restart_window_secs: Option<u64>,
3068    /// Effective drain budget for this module, in milliseconds. This is the
3069    /// resolved policy the running supervisor uses, not a config-file reread.
3070    /// Absent on older daemons.
3071    #[serde(default, skip_serializing_if = "Option::is_none")]
3072    pub drain_timeout_ms: Option<u64>,
3073    /// Effective base delay before a crash restart, in milliseconds. Absent on
3074    /// older daemons.
3075    #[serde(default, skip_serializing_if = "Option::is_none")]
3076    pub restart_backoff_ms: Option<u64>,
3077    /// Effective maximum delay before a crash restart, in milliseconds. Absent
3078    /// on older daemons.
3079    #[serde(default, skip_serializing_if = "Option::is_none")]
3080    pub restart_max_backoff_ms: Option<u64>,
3081    /// Memory and cumulative CPU time of the module's process, read when this
3082    /// list was answered. Report only: the daemon keeps no history and acts on
3083    /// none of it.
3084    ///
3085    /// It describes the one process the supervisor spawned (its `pid`), not
3086    /// processes that one has started in turn, so a module that forks workers
3087    /// reports only its own share.
3088    ///
3089    /// Absent means the daemon predates the field. A daemon that has the field
3090    /// but could not read the process (not running, unsupported platform, read
3091    /// failed) says so with `Unavailable` and a reason, so neither case can be
3092    /// mistaken for a process using nothing.
3093    #[serde(default, skip_serializing_if = "Option::is_none")]
3094    pub resources: Option<ChildResourceUsage>,
3095    /// Cumulative CPU and current memory including child processes, when known.
3096    #[serde(default, skip_serializing_if = "Option::is_none")]
3097    pub tree: Option<TreeReading>,
3098    /// Why this reporting daemon has no tree reading for this response.
3099    /// `not_yet_measured` means this launch has no measurement; `unreadable`
3100    /// and `launch_changed` can accompany a retained, older tree. `not_running`
3101    /// marks a stopped module. Future reasons remain valid open-set strings.
3102    /// Absence alone does not establish tree support.
3103    #[serde(default, skip_serializing_if = "Option::is_none")]
3104    pub tree_unavailable: Option<String>,
3105    /// CPU used across the wall-clock interval covered by retained samples.
3106    #[serde(default, skip_serializing_if = "Option::is_none")]
3107    pub cpu_last_hour: Option<CpuLastHour>,
3108    /// Values read by an executed rescan that are not yet in force.
3109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3110    pub pending: Vec<SupervisorPendingField>,
3111}
3112
3113impl SupervisorEntry {
3114    #[must_use]
3115    pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
3116        self.script = script;
3117        self
3118    }
3119    /// Set the estimated time of a failed module's next automatic retry.
3120    #[must_use]
3121    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
3122        self.next_retry_at_ms = next_retry_at_ms;
3123        self
3124    }
3125
3126    /// Construct an entry with its required fields and wire-compatible defaults.
3127    #[must_use]
3128    pub fn new(
3129        module_id: impl Into<String>,
3130        state: impl Into<String>,
3131        enabled: bool,
3132        live: bool,
3133        health: SupervisorHealthStatus,
3134    ) -> Self {
3135        Self {
3136            module_id: module_id.into(),
3137            script: None,
3138            state: state.into(),
3139            admission_refused: None,
3140            next_retry_at_ms: None,
3141            waiting_for_previous_pid: None,
3142            enabled,
3143            configured_enabled: None,
3144            live,
3145            protocol: ModuleProtocol::default(),
3146            launch_nonce_env: None,
3147            launch_nonce_source: None,
3148            health,
3149            pending_reload: None,
3150            last_probe_ms: None,
3151            last_exit_code: None,
3152            last_exit_signal: None,
3153            last_exit_ms: None,
3154            last_exit_kind: None,
3155            restart_count: None,
3156            max_restarts: None,
3157            lifetime_restarts: None,
3158            spawn_generation: None,
3159            restart_window_secs: None,
3160            drain_timeout_ms: None,
3161            restart_backoff_ms: None,
3162            restart_max_backoff_ms: None,
3163            resources: None,
3164            tree: None,
3165            tree_unavailable: None,
3166            cpu_last_hour: None,
3167            pending: Vec::new(),
3168        }
3169    }
3170
3171    /// Set or clear the daemon's admission refusal reason.
3172    #[must_use]
3173    pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
3174        self.admission_refused = reason;
3175        self
3176    }
3177
3178    /// Set the module's declared wire protocol.
3179    #[must_use]
3180    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
3181        self.protocol = protocol;
3182        self
3183    }
3184
3185    /// Attach the enabled value from the daemon's loaded configuration.
3186    #[must_use]
3187    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
3188        self.configured_enabled = configured_enabled;
3189        self
3190    }
3191
3192    /// Set or clear the launch nonce environment indicator.
3193    #[must_use]
3194    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
3195        self.launch_nonce_env = launch_nonce_env;
3196        self
3197    }
3198
3199    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
3200        self.launch_nonce_source = source;
3201        self
3202    }
3203
3204    #[must_use]
3205    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
3206        self.waiting_for_previous_pid = pid;
3207        self
3208    }
3209
3210    /// Set or clear the comparison between the launch spec and observed process.
3211    #[must_use]
3212    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
3213        self.pending_reload = pending_reload;
3214        self
3215    }
3216
3217    /// Set or clear the last health collection timestamp.
3218    #[must_use]
3219    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
3220        self.last_probe_ms = last_probe_ms;
3221        self
3222    }
3223
3224    /// Set or clear the most recent process exit code.
3225    #[must_use]
3226    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
3227        self.last_exit_code = last_exit_code;
3228        self
3229    }
3230
3231    /// Set or clear the most recent process exit signal.
3232    #[must_use]
3233    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
3234        self.last_exit_signal = last_exit_signal;
3235        self
3236    }
3237
3238    /// Set or clear the most recent process exit timestamp.
3239    #[must_use]
3240    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
3241        self.last_exit_ms = last_exit_ms;
3242        self
3243    }
3244
3245    /// Set or clear the most recent process exit classification.
3246    #[must_use]
3247    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
3248        self.last_exit_kind = last_exit_kind;
3249        self
3250    }
3251
3252    /// Set or clear the restart count for the current crash budget.
3253    #[must_use]
3254    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
3255        self.restart_count = restart_count;
3256        self
3257    }
3258
3259    /// Set or clear the maximum restarts allowed by the crash budget.
3260    #[must_use]
3261    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
3262        self.max_restarts = max_restarts;
3263        self
3264    }
3265
3266    /// Set or clear the lifetime restart count.
3267    #[must_use]
3268    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
3269        self.lifetime_restarts = lifetime_restarts;
3270        self
3271    }
3272
3273    /// Set or clear the successful spawn count for this daemon incarnation.
3274    #[must_use]
3275    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
3276        self.spawn_generation = spawn_generation;
3277        self
3278    }
3279
3280    /// Set or clear the time window of the crash budget.
3281    #[must_use]
3282    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
3283        self.restart_window_secs = restart_window_secs;
3284        self
3285    }
3286
3287    /// Set or clear the effective drain budget in milliseconds.
3288    #[must_use]
3289    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
3290        self.drain_timeout_ms = drain_timeout_ms;
3291        self
3292    }
3293
3294    /// Set or clear the effective base restart delay in milliseconds.
3295    #[must_use]
3296    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
3297        self.restart_backoff_ms = restart_backoff_ms;
3298        self
3299    }
3300
3301    /// Set or clear the effective maximum restart delay in milliseconds.
3302    #[must_use]
3303    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
3304        self.restart_max_backoff_ms = restart_max_backoff_ms;
3305        self
3306    }
3307
3308    /// Set or clear the observed resource usage of the supervised process.
3309    #[must_use]
3310    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
3311        self.resources = resources;
3312        self
3313    }
3314
3315    /// Attach a report-only reading covering the module's process container.
3316    #[must_use]
3317    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
3318        self.tree = tree;
3319        self
3320    }
3321
3322    /// Explain an absent tree reading without manufacturing numeric counters.
3323    #[must_use]
3324    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
3325        self.tree_unavailable = reason;
3326        self
3327    }
3328}
3329
3330/// Content identity is separate from the runner executable's identity.
3331#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3332pub struct ScriptModuleStatus {
3333    pub runtime: String,
3334    pub bun_version: Option<String>,
3335    pub path: PathBuf,
3336    pub sha256: Option<String>,
3337    pub size: Option<u64>,
3338    pub needs_review: bool,
3339}
3340
3341#[cfg(test)]
3342mod script_status_tests {
3343    use super::*;
3344
3345    #[test]
3346    fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
3347        let old = SupervisorEntry::new(
3348            "example",
3349            "running",
3350            true,
3351            true,
3352            SupervisorHealthStatus::Unknown,
3353        );
3354        let value = serde_json::to_value(&old).unwrap();
3355        assert!(value.get("script").is_none());
3356        assert!(serde_json::from_value::<SupervisorEntry>(value)
3357            .unwrap()
3358            .script
3359            .is_none());
3360        let current = old.with_script(Some(ScriptModuleStatus {
3361            runtime: "bun".into(),
3362            bun_version: None,
3363            path: "bundle.js".into(),
3364            sha256: Some("ab".repeat(32)),
3365            size: Some(3),
3366            needs_review: true,
3367        }));
3368        let decoded: SupervisorEntry =
3369            serde_json::from_slice(&serde_json::to_vec(&current).unwrap()).unwrap();
3370        assert_eq!(decoded, current);
3371    }
3372}
3373
3374/// A module process's memory and CPU time as read at list time, or why none
3375/// could be read.
3376#[derive(Debug, Clone, PartialEq)]
3377pub enum ChildResourceUsage {
3378    Measured(ChildResourceReading),
3379    Unavailable {
3380        reason: ChildResourceUnavailableReason,
3381    },
3382    /// Future discriminator. `body` retains the complete ordered object; `tag`
3383    /// is its decoded discriminator projection.
3384    Unknown {
3385        tag: String,
3386        body: OrderedJsonObject,
3387    },
3388}
3389
3390/// One reading of a module process's memory and CPU time.
3391/// Use [`ChildResourceReading::new`] and its builders so future fields stay additive.
3392#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3393#[non_exhaustive]
3394pub struct ChildResourceReading {
3395    /// Memory in bytes, measured as `memory_kind` says. The figures differ
3396    /// by platform and are not comparable across kinds.
3397    pub memory_bytes: u64,
3398    pub memory_kind: ChildMemoryKind,
3399    /// Bytes swapped out, where the platform reports it per process (Linux).
3400    /// Absent means not reported, not zero.
3401    #[serde(default, skip_serializing_if = "Option::is_none")]
3402    pub swap_bytes: Option<u64>,
3403    /// CPU time spent in user mode since the process started, in
3404    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
3405    /// and the elapsed time between them.
3406    pub cpu_user_ms: u64,
3407    /// CPU time spent in the kernel on the process's behalf since it started,
3408    /// in milliseconds.
3409    pub cpu_system_ms: u64,
3410}
3411
3412impl ChildResourceReading {
3413    /// Create a process reading without optional swap accounting.
3414    #[must_use]
3415    pub fn new(
3416        memory_bytes: u64,
3417        memory_kind: ChildMemoryKind,
3418        cpu_user_ms: u64,
3419        cpu_system_ms: u64,
3420    ) -> Self {
3421        Self {
3422            memory_bytes,
3423            memory_kind,
3424            cpu_user_ms,
3425            cpu_system_ms,
3426            swap_bytes: None,
3427        }
3428    }
3429
3430    /// Set or clear swap bytes where the platform can measure them.
3431    #[must_use]
3432    pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
3433        self.swap_bytes = swap_bytes;
3434        self
3435    }
3436}
3437
3438open_string_enum! {
3439    /// What `ChildResourceReading::memory_bytes` measures.
3440    ChildMemoryKind {
3441        /// macOS `phys_footprint`: memory the kernel charges to the process,
3442        /// the figure jetsam acts on. Unlike resident size it does not count
3443        /// pages an allocator has already released with `MADV_FREE`.
3444        PhysFootprint => "phys_footprint",
3445        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
3446        /// included and swapped-out pages excluded.
3447        ResidentSet => "resident_set",
3448        /// Windows `WorkingSetSize`: resident pageable memory, including shared
3449        /// pages, not Unix RSS or private committed bytes.
3450        WindowsWorkingSet => "windows_working_set",
3451    }
3452}
3453
3454open_string_enum! {
3455    /// Why a module process's resources could not be read.
3456    ChildResourceUnavailableReason {
3457        /// The module has no running process.
3458        NotRunning => "not_running",
3459        /// The daemon's platform has no per-process source.
3460        UnsupportedPlatform => "unsupported_platform",
3461        /// The process could not be read, typically because it exited while
3462        /// the list was being answered.
3463        Unreadable => "unreadable",
3464        /// The pid no longer names the process the supervisor spawned, so a
3465        /// reading would describe some other process.
3466        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
3467    }
3468}
3469
3470#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
3471#[serde(rename_all = "snake_case")]
3472pub enum SupervisorHealthStatus {
3473    Ok,
3474    Degraded,
3475    Failing,
3476    Unresponsive,
3477    Unknown,
3478}
3479
3480#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3481pub struct SupervisorHealthEntry {
3482    pub module_id: String,
3483    pub status: SupervisorHealthStatus,
3484    /// The module's own human-readable note on its state. Absent means the
3485    /// module said nothing, which is the ordinary shape for a healthy module and
3486    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
3487    /// module may reword freely, and `status` plus `metrics` are the machine
3488    /// surface.
3489    #[serde(default, skip_serializing_if = "Option::is_none")]
3490    pub detail: Option<String>,
3491    /// The module's own metrics object, relayed opaquely. Absent means the module
3492    /// published none on this probe — either it reports no metrics at all, or the
3493    /// probe did not reach it — so absence cannot distinguish "nothing to report"
3494    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
3495    #[serde(default, skip_serializing_if = "Option::is_none")]
3496    pub metrics: Option<serde_json::Value>,
3497    pub consecutive_failures: u32,
3498    /// Number of recurring health replies received after their daemon deadline.
3499    /// Each increment is evidence that the module remained alive despite a miss.
3500    #[serde(default)]
3501    pub late_answer_count: u64,
3502    /// End-to-end latency of the newest late reply, measured from probe start.
3503    #[serde(default, skip_serializing_if = "Option::is_none")]
3504    pub last_late_answer_latency_ms: Option<u64>,
3505    /// The escalation the supervisor last took for this module (report, restart,
3506    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
3507    /// succeeded — a module that has never misbehaved and one whose action record
3508    /// predates a daemon restart both present as absent.
3509    #[serde(default)]
3510    pub last_action: Option<String>,
3511    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
3512    /// `last_action` is absent; the pair moves together.
3513    #[serde(default)]
3514    pub last_action_ms: Option<u64>,
3515    /// When the daemon last collected this entry, as unix milliseconds.
3516    ///
3517    /// `supervisor.health` answers from the supervisor's STORED record rather
3518    /// than probing, so every field above describes some moment in the past and
3519    /// nothing here said which. That matters most right after a restart, where
3520    /// the surface is used to confirm a deploy: a record collected before the
3521    /// restart reports the OLD process, reads as a failed deploy, and invites a
3522    /// redeploy of something that was already correct.
3523    ///
3524    /// `None` means never probed — distinct from probed-long-ago, and the reader
3525    /// must not collapse them. Absent on modules that advertise no health
3526    /// capability, which is why it is optional rather than defaulted to zero.
3527    #[serde(default, skip_serializing_if = "Option::is_none")]
3528    pub last_probe_ms: Option<u64>,
3529}
3530
3531#[cfg(test)]
3532mod tests {
3533    #[test]
3534    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
3535        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
3536        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
3537        assert_eq!(decoded.configured_enabled, None);
3538        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
3539    }
3540
3541    #[test]
3542    fn configured_enabled_values_round_trip_in_list() {
3543        for enabled in [false, true] {
3544            let entry = SupervisorEntry::new(
3545                "provider",
3546                "running",
3547                true,
3548                true,
3549                SupervisorHealthStatus::Unknown,
3550            )
3551            .with_configured_enabled(Some(enabled));
3552            let entry_json = serde_json::to_value(&entry).unwrap();
3553            assert_eq!(entry_json["configured_enabled"], enabled);
3554            assert_eq!(
3555                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
3556                entry
3557            );
3558        }
3559    }
3560
3561    #[test]
3562    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
3563        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
3564            volume_serial_number: u64::MAX,
3565            file_id: [
3566                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
3567            ],
3568        };
3569        let agreement = super::RunningImageAgreement::Match { evidence };
3570        let encoded = serde_json::to_string(&agreement).unwrap();
3571        assert!(encoded.contains("windows_spawn_file_id"));
3572        assert_eq!(
3573            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
3574            agreement
3575        );
3576    }
3577
3578    #[test]
3579    fn unix_running_image_evidence_keeps_original_wire_bytes() {
3580        assert_eq!(
3581            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
3582                device: 7,
3583                inode: 11
3584            })
3585            .unwrap(),
3586            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
3587        );
3588        assert_eq!(
3589            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
3590                digest: "abc".to_owned()
3591            })
3592            .unwrap(),
3593            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
3594        );
3595    }
3596    use super::*;
3597    use subc_protocol::{BindIdentity, RouteTarget};
3598
3599    #[test]
3600    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
3601        let entry = TerminalEntry {
3602            daemon_incarnation: Some("daemon-before-restart".into()),
3603            exit_code: Some(1),
3604            exit_signal: None,
3605            at_ms: 1_700_000_000_123,
3606            disposition: TerminalDisposition::Restarting,
3607            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
3608            disposition_detail: None,
3609        };
3610        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
3611        assert_eq!(
3612            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
3613                ["exit_kind"],
3614            "deliberate_severance"
3615        );
3616
3617        #[derive(serde::Deserialize)]
3618        struct LegacyTerminalEntry {
3619            exit_code: Option<i32>,
3620            exit_signal: Option<i32>,
3621            at_ms: u64,
3622            disposition: TerminalDisposition,
3623        }
3624
3625        let decoded: LegacyTerminalEntry =
3626            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
3627        assert_eq!(decoded.exit_code, Some(1));
3628        assert_eq!(decoded.exit_signal, None);
3629        assert_eq!(decoded.at_ms, 1_700_000_000_123);
3630        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
3631
3632        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
3633        let future: TerminalEntry =
3634            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
3635        assert_eq!(
3636            future.exit_kind,
3637            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
3638        );
3639    }
3640
3641    #[test]
3642    fn terminal_incarnation_is_optional_for_older_daemons() {
3643        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
3644            "at_ms": 123,
3645            "disposition": "stopped"
3646        }))
3647        .unwrap();
3648        let encoded = serde_json::to_value(&entry).unwrap();
3649        assert_eq!(
3650            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
3651            (None, None)
3652        );
3653    }
3654
3655    #[test]
3656    fn route_poll_uses_kind_field() {
3657        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
3658            route_channel: 7,
3659            route_epoch: 11,
3660            kind: PollKind::Status,
3661        })
3662        .unwrap();
3663
3664        assert_eq!(body["op"], "route.poll");
3665        assert_eq!(body["route_epoch"], 11);
3666        assert_eq!(body["kind"], "status");
3667        assert!(body.get("op").is_some());
3668    }
3669
3670    #[test]
3671    fn route_open_is_internally_tagged() {
3672        let request = ClientControlRequest::RouteOpen {
3673            busy_refusals: None,
3674            target: RouteTarget::ToolProvider {
3675                module_id: "aft".to_string(),
3676            },
3677            identity: BindIdentity::new("opencode", "session-1"),
3678            consumer_identity: None,
3679            consumer_capabilities: None,
3680            role_versions: None,
3681            admission_facts: None,
3682            scope: None,
3683        };
3684
3685        let body = serde_json::to_value(request).unwrap();
3686        assert_eq!(body["op"], "route.open");
3687        assert_eq!(body["target"]["kind"], "tool_provider");
3688        assert!(body.get("consumer_identity").is_none());
3689        assert!(body.get("consumer_capabilities").is_none());
3690        assert!(body.get("role_versions").is_none());
3691    }
3692
3693    #[test]
3694    fn route_open_without_optional_fields_still_decodes() {
3695        let body = serde_json::json!({
3696            "op": "route.open",
3697            "target": { "kind": "tool_provider", "module_id": "aft" },
3698            "identity": {
3699                "project_root": "/tmp/project",
3700                "harness": "opencode",
3701                "session": "session-1"
3702            }
3703        });
3704
3705        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3706        let ClientControlRequest::RouteOpen {
3707            consumer_identity,
3708            consumer_capabilities,
3709            role_versions,
3710            admission_facts,
3711            ..
3712        } = decoded
3713        else {
3714            panic!("decoded wrong request variant");
3715        };
3716        assert_eq!(consumer_identity, None);
3717        assert_eq!(consumer_capabilities, None);
3718        assert_eq!(role_versions, None);
3719        assert_eq!(admission_facts, None);
3720    }
3721
3722    #[test]
3723    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3724        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3725        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3726        match decoded {
3727            ClientControlPush::RouteClosed {
3728                excluded_subscriptions,
3729                terminal,
3730                ..
3731            } => {
3732                assert_eq!(excluded_subscriptions, 0);
3733                assert_eq!(terminal, None);
3734            }
3735            other => panic!("unexpected push: {other:?}"),
3736        }
3737        assert!(!serde_json::to_string(&decoded)
3738            .unwrap()
3739            .contains("terminal"));
3740    }
3741
3742    #[test]
3743    fn old_route_closed_decoder_ignores_new_terminal_field() {
3744        #[derive(serde::Deserialize)]
3745        #[serde(tag = "op")]
3746        enum LegacyClientControlPush {
3747            #[serde(rename = "route.closed")]
3748            RouteClosed {
3749                module_id: String,
3750                reason: RouteCloseReason,
3751                drained: bool,
3752                abandoned: u32,
3753            },
3754        }
3755
3756        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3757        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3758        match decoded {
3759            LegacyClientControlPush::RouteClosed {
3760                module_id,
3761                reason,
3762                drained,
3763                abandoned,
3764            } => {
3765                assert_eq!(module_id, "aft-tools");
3766                assert_eq!(reason, RouteCloseReason::Crash);
3767                assert!(!drained);
3768                assert_eq!(abandoned, 0);
3769            }
3770        }
3771    }
3772
3773    #[test]
3774    fn supervisor_routes_is_a_control_plane_request() {
3775        let body = serde_json::json!({
3776            "op": "supervisor.routes",
3777            "module_id": "aft"
3778        });
3779
3780        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3781        assert_eq!(serde_json::to_value(request).unwrap(), body);
3782    }
3783
3784    #[test]
3785    fn diagnostic_string_enums_retain_unknown_wire_values() {
3786        let reason: RunningImageUnavailableReason =
3787            serde_json::from_str("\"future_reason\"").unwrap();
3788        let disposition: TerminalDisposition =
3789            serde_json::from_str("\"future_disposition\"").unwrap();
3790
3791        assert_eq!(
3792            reason,
3793            RunningImageUnavailableReason::Unknown("future_reason".to_string())
3794        );
3795        assert_eq!(
3796            disposition,
3797            TerminalDisposition::Unknown("future_disposition".to_string())
3798        );
3799    }
3800
3801    #[test]
3802    fn diagnostic_string_enums_preserve_existing_wire_names() {
3803        let names = [
3804            (RunningImageUnavailableReason::NotRunning, "not_running"),
3805            (
3806                RunningImageUnavailableReason::UnsupportedPlatform,
3807                "unsupported_platform",
3808            ),
3809            (
3810                RunningImageUnavailableReason::RunningExecutableUnreadable,
3811                "running_executable_unreadable",
3812            ),
3813            (
3814                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3815                "running_executable_permission_denied",
3816            ),
3817            (
3818                RunningImageUnavailableReason::ProcessHidden,
3819                "process_hidden",
3820            ),
3821            (
3822                RunningImageUnavailableReason::SpawnedPathUnreadable,
3823                "spawned_path_unreadable",
3824            ),
3825            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3826            (
3827                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3828                "process_identity_unconfirmed",
3829            ),
3830        ];
3831        for (value, expected) in names {
3832            let wire = serde_json::to_string(&value).unwrap();
3833            assert_eq!(wire, format!("\"{expected}\""));
3834            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3835            assert_eq!(decoded, value);
3836        }
3837
3838        for (value, expected) in [
3839            (TerminalDisposition::Stopped, "stopped"),
3840            (TerminalDisposition::Disabled, "disabled"),
3841            (TerminalDisposition::Failed, "failed"),
3842            (TerminalDisposition::Restarting, "restarting"),
3843            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3844        ] {
3845            let wire = serde_json::to_string(&value).unwrap();
3846            assert_eq!(wire, format!("\"{expected}\""));
3847            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3848            assert_eq!(decoded, value);
3849        }
3850    }
3851
3852    #[test]
3853    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3854        let entry = SupervisorEntry::new(
3855            "waiting-module",
3856            "starting",
3857            true,
3858            false,
3859            SupervisorHealthStatus::Unknown,
3860        );
3861        let old_wire = serde_json::to_value(&entry).unwrap();
3862        assert!(old_wire.get("waiting_for_previous_pid").is_none());
3863        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3864        assert_eq!(decoded.waiting_for_previous_pid, None);
3865        let entry = entry.with_waiting_for_previous_pid(Some(42));
3866        let wire = serde_json::to_value(&entry).unwrap();
3867        assert_eq!(wire["waiting_for_previous_pid"], 42);
3868        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3869        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3870    }
3871
3872    #[test]
3873    fn diagnostic_string_enums_reject_non_string_bodies() {
3874        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3875        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3876    }
3877
3878    #[test]
3879    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3880        let body = serde_json::json!({
3881            "op": "supervisor.provenance",
3882            "daemon": {
3883                "daemon_build": {},
3884                "daemon_observed": {
3885                    "running_image": {
3886                        "status": "unavailable",
3887                        "reason": "not_running"
3888                    }
3889                }
3890            },
3891            "modules": [
3892                {
3893                    "module_id": "future",
3894                    "module_declared": { "status": "unverifiable" },
3895                    "daemon_observed": {
3896                        "running_image": {
3897                            "status": "unavailable",
3898                            "reason": "future_reason"
3899                        }
3900                    }
3901                },
3902                {
3903                    "module_id": "healthy-a",
3904                    "module_declared": { "status": "unverifiable" },
3905                    "daemon_observed": {
3906                        "running_image": {
3907                            "status": "match",
3908                            "evidence": {
3909                                "method": "linux_proc_sha256",
3910                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3911                            }
3912                        }
3913                    }
3914                },
3915                {
3916                    "module_id": "healthy-b",
3917                    "module_declared": { "status": "unverifiable" },
3918                    "daemon_observed": {
3919                        "running_image": {
3920                            "status": "unavailable",
3921                            "reason": "unsupported_platform"
3922                        }
3923                    }
3924                }
3925            ]
3926        });
3927
3928        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3929        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3930            panic!("decoded wrong response variant");
3931        };
3932        assert_eq!(modules.len(), 3);
3933        assert_eq!(modules[0].module_id, "future");
3934        assert_eq!(
3935            modules[0].daemon_observed.running_image,
3936            RunningImageAgreement::Unavailable {
3937                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3938            }
3939        );
3940        assert_eq!(modules[1].module_id, "healthy-a");
3941        assert_eq!(modules[2].module_id, "healthy-b");
3942    }
3943
3944    #[test]
3945    fn tagged_unknown_values_retain_tag_and_body() {
3946        macro_rules! assert_unknown_round_trip {
3947            ($ty:ident, $field:literal, $value:expr) => {
3948                let value = $value;
3949                let wire = serde_json::to_string(&value).unwrap();
3950                let decoded: $ty = serde_json::from_str(&wire).unwrap();
3951                match decoded {
3952                    $ty::Unknown { tag, body } => {
3953                        assert_eq!(tag, value[$field].as_str().unwrap());
3954                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
3955                    }
3956                    _ => panic!("decoded known variant"),
3957                }
3958            };
3959        }
3960
3961        assert_unknown_round_trip!(
3962            ModuleDeclaredProvenance,
3963            "status",
3964            serde_json::json!({"status": "future", "build": {"version": 7}})
3965        );
3966        assert_unknown_round_trip!(
3967            RunningImageAgreement,
3968            "status",
3969            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3970        );
3971        assert_unknown_round_trip!(
3972            RunningImageEvidence,
3973            "method",
3974            serde_json::json!({"method": "future", "digest": "abc"})
3975        );
3976        assert_unknown_round_trip!(
3977            SupervisorRouteConsumer,
3978            "kind",
3979            serde_json::json!({"kind": "future", "module_id": "m"})
3980        );
3981        assert_unknown_round_trip!(
3982            StderrCaptureState,
3983            "state",
3984            serde_json::json!({"state": "future", "reason": "because"})
3985        );
3986        assert_unknown_round_trip!(
3987            StderrTailEntry,
3988            "kind",
3989            serde_json::json!({"kind": "future", "text": "line"})
3990        );
3991        assert_unknown_round_trip!(
3992            ChildResourceUsage,
3993            "status",
3994            serde_json::json!({"status": "future", "memory_bytes": 1})
3995        );
3996    }
3997
3998    #[test]
3999    fn child_resource_usage_round_trips_both_known_states() {
4000        let measured = ChildResourceUsage::Measured(ChildResourceReading {
4001            memory_bytes: 0,
4002            memory_kind: ChildMemoryKind::ResidentSet,
4003            swap_bytes: Some(0),
4004            cpu_user_ms: 0,
4005            cpu_system_ms: 0,
4006        });
4007        let wire = serde_json::to_value(&measured).unwrap();
4008        assert_eq!(
4009            wire,
4010            serde_json::json!({
4011                "status": "measured",
4012                "memory_bytes": 0,
4013                "memory_kind": "resident_set",
4014                "swap_bytes": 0,
4015                "cpu_user_ms": 0,
4016                "cpu_system_ms": 0
4017            })
4018        );
4019        assert_eq!(
4020            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4021            measured
4022        );
4023
4024        let unavailable = ChildResourceUsage::Unavailable {
4025            reason: ChildResourceUnavailableReason::NotRunning,
4026        };
4027        let wire = serde_json::to_value(&unavailable).unwrap();
4028        assert_eq!(
4029            wire,
4030            serde_json::json!({"status": "unavailable", "reason": "not_running"})
4031        );
4032        assert_eq!(
4033            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
4034            unavailable
4035        );
4036    }
4037
4038    #[test]
4039    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
4040        // A current daemon stamps each line; an older one sends no `at_ms`.
4041        // Both must decode, and the absent case must stay absent rather than
4042        // turn into a time nobody recorded.
4043        let stamped: StderrTailEntry = serde_json::from_str(
4044            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
4045        )
4046        .unwrap();
4047        assert_eq!(
4048            stamped,
4049            StderrTailEntry::Line {
4050                text: "boom".to_string(),
4051                truncated: true,
4052                at_ms: Some(1_789_801_440_685),
4053            }
4054        );
4055        let unstamped: StderrTailEntry =
4056            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
4057        assert_eq!(
4058            unstamped,
4059            StderrTailEntry::Line {
4060                text: "boom".to_string(),
4061                truncated: false,
4062                at_ms: None,
4063            }
4064        );
4065        // Absent stays absent on the way out, so a reply without stamps is
4066        // exactly what an older daemon would have sent.
4067        assert_eq!(
4068            serde_json::to_string(&unstamped).unwrap(),
4069            r#"{"kind":"line","text":"boom"}"#
4070        );
4071        assert_eq!(
4072            serde_json::to_value(&stamped).unwrap()["at_ms"],
4073            serde_json::json!(1_789_801_440_685u64)
4074        );
4075    }
4076
4077    #[test]
4078    fn tagged_unknown_values_round_trip_the_original_json() {
4079        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
4080        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4081        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4082    }
4083
4084    #[test]
4085    fn tagged_unknown_values_round_trip_trailing_tag() {
4086        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
4087        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4088        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4089
4090        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
4091        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4092        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4093    }
4094
4095    #[test]
4096    fn tagged_unknown_values_round_trip_middle_tag() {
4097        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
4098        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4099        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4100
4101        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
4102        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4103        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4104    }
4105
4106    #[test]
4107    fn tagged_unknown_values_round_trip_deep_payload() {
4108        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
4109        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
4110        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
4111
4112        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
4113        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
4114        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
4115    }
4116
4117    #[test]
4118    fn tagged_unknown_values_reject_non_object_bodies() {
4119        for wire in ["42", r#""future""#, "[]"] {
4120            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
4121            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
4122        }
4123    }
4124
4125    #[test]
4126    fn duplicate_discriminators_reject_without_panicking() {
4127        assert_eq!(
4128            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
4129                .unwrap(),
4130            ModuleDeclaredProvenance::Unverifiable
4131        );
4132        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
4133            .unwrap()
4134        {
4135            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
4136            _ => panic!("future discriminator decoded as a known variant"),
4137        }
4138
4139        let wires = [
4140            r#"{"status":"reported","status":"unverifiable"}"#,
4141            r#"{"status":"unverifiable","status":"reported"}"#,
4142            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
4143            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
4144        ];
4145
4146        for wire in wires {
4147            let result =
4148                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
4149            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4150            assert!(
4151                result.unwrap().is_err(),
4152                "duplicate discriminator decoded: {wire}"
4153            );
4154        }
4155
4156        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
4157        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
4158        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
4159        assert!(
4160            result.unwrap().is_err(),
4161            "duplicate discriminator decoded: {wire}"
4162        );
4163    }
4164
4165    #[test]
4166    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
4167        let known_wire =
4168            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
4169        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
4170        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
4171
4172        for wire in [
4173            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
4174            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
4175        ] {
4176            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
4177            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4178        }
4179
4180        for wire in [
4181            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
4182            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
4183        ] {
4184            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4185            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4186        }
4187
4188        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
4189        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
4190        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4191
4192        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
4193        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
4194        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
4195    }
4196
4197    #[test]
4198    fn tagged_unknown_member_does_not_discard_known_siblings() {
4199        let body = serde_json::json!({
4200            "modules": [{
4201                "module_id": "target",
4202                "routes": [
4203                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
4204                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
4205                ]
4206            }]
4207        });
4208        let decoded: ClientControlResponse = serde_json::from_value(
4209            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
4210        )
4211        .unwrap();
4212        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
4213            panic!("decoded wrong response variant");
4214        };
4215        assert_eq!(modules[0].routes.len(), 2);
4216        assert_eq!(
4217            modules[0].routes[1].consumer,
4218            SupervisorRouteConsumer::Direct { connection_id: 7 }
4219        );
4220    }
4221}
4222
4223#[cfg(test)]
4224mod launch_nonce_redaction_tests {
4225    use super::*;
4226
4227    const NONCE: &str = "nonce-f00dfeed1234abcd";
4228
4229    fn identity() -> ConsumerIdentity {
4230        ConsumerIdentity {
4231            module_id: "wernicke".to_string(),
4232            launch_nonce: NONCE.to_string(),
4233        }
4234    }
4235
4236    #[test]
4237    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
4238        let printed = format!("{:?}", identity());
4239        assert!(printed.contains("wernicke"), "{printed}");
4240        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4241    }
4242
4243    #[test]
4244    fn route_open_request_debug_never_prints_the_nonce() {
4245        let request = ClientControlRequest::RouteOpen {
4246            busy_refusals: None,
4247            target: subc_protocol::RouteTarget::ToolProvider {
4248                module_id: "broca".to_string(),
4249            },
4250            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
4251            consumer_identity: Some(identity()),
4252            consumer_capabilities: None,
4253            role_versions: None,
4254            admission_facts: None,
4255            scope: None,
4256        };
4257        let printed = format!("{request:?}");
4258        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
4259    }
4260}
4261
4262#[cfg(test)]
4263mod reader_skew_tests {
4264    use super::*;
4265    use serde_json::{json, Value};
4266
4267    fn catalog() -> Value {
4268        json!({"module_id": "provider", "roles": [], "control_ops": []})
4269    }
4270
4271    fn reply() -> Value {
4272        json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
4273    }
4274
4275    fn target() -> Value {
4276        json!({
4277            "incarnation": "daemon", "kind": "spawn", "spawn": 17,
4278            "authority_epoch": 23, "first_party": true,
4279            "approved_declarations_digest": "approved"
4280        })
4281    }
4282
4283    fn request() -> Value {
4284        json!({
4285            "op": "route.open",
4286            "target": {"kind": "tool_provider", "module_id": "provider"},
4287            "identity": {"harness": "test", "session": "session-1"}
4288        })
4289    }
4290
4291    #[test]
4292    fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
4293        let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4294        let built = CatalogEntry::new("provider", vec![], vec![]);
4295        assert_eq!(old, built);
4296        assert_eq!(old.first_party, None);
4297        let old_bytes = serde_json::to_value(&old).unwrap();
4298        let additions = json!({
4299            "incarnation": "daemon", "spawn": 17, "first_party": false,
4300            "origin": "development", "requested_declarations_digest": "requested",
4301            "approved_declarations_digest": "approved"
4302        });
4303        let mut body = catalog();
4304        for (key, value) in additions.as_object().unwrap() {
4305            assert!(old_bytes.get(key).is_none(), "{key}");
4306            body[key] = value.clone();
4307        }
4308        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4309        let encoded = serde_json::to_value(&decoded).unwrap();
4310        for (key, value) in additions.as_object().unwrap() {
4311            assert_eq!(&encoded[key], value, "{key}");
4312        }
4313        assert_eq!(decoded.first_party, Some(false));
4314        assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
4315    }
4316
4317    #[test]
4318    fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
4319        let mut body = catalog();
4320        body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
4321        body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
4322        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4323        let encoded = serde_json::to_value(decoded).unwrap();
4324        for key in ["requested_declarations", "approved_declarations"] {
4325            assert_eq!(encoded[key], body[key]);
4326        }
4327        let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
4328        assert_eq!(unfiltered.approved_declarations, None);
4329        assert_eq!(unfiltered.requested_declarations, None);
4330    }
4331
4332    #[test]
4333    fn reader_skew_catalog_unknown_origin_is_other() {
4334        let mut body = catalog();
4335        body["origin"] = json!("future-origin");
4336        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
4337        assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
4338    }
4339
4340    #[test]
4341    fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
4342        let mut body = catalog();
4343        body["spawn"] = json!(9_007_199_254_740_991_u64);
4344        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
4345        assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
4346        for invalid in [
4347            json!(9_007_199_254_740_992_u64),
4348            json!(-1),
4349            json!(1.5),
4350            json!("17"),
4351        ] {
4352            body["spawn"] = invalid;
4353            assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
4354        }
4355    }
4356
4357    #[test]
4358    fn reader_skew_catalog_watch_request_uses_subscription_op() {
4359        let body = json!({"op": "catalog.watch"});
4360        let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
4361        assert_eq!(request, CatalogWatchRequest::new());
4362        assert_eq!(serde_json::to_value(request).unwrap(), body);
4363        assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
4364        for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
4365            assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
4366        }
4367    }
4368
4369    #[test]
4370    fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
4371        for generation in [0, 19, 42] {
4372            let body = json!({"op": "catalog.watch", "generation": generation});
4373            let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
4374            assert_eq!(push, CatalogWatchResponse::new(generation));
4375            assert_eq!(serde_json::to_value(push).unwrap(), body);
4376        }
4377        assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
4378        for invalid in [
4379            json!({"op": "catalog.watch"}),
4380            json!({"op": "activity.subscribe", "generation": 1}),
4381        ] {
4382            assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
4383        }
4384    }
4385
4386    #[test]
4387    fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
4388        let mut body = reply();
4389        let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
4390        let empty = RouteOpenReplyExt::read_from(&body).unwrap();
4391        assert_eq!(empty, RouteOpenReplyExt::new());
4392        empty.write_to(&mut body).unwrap();
4393        assert_eq!(body, reply());
4394        body["target"] = target();
4395        let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
4396        assert_eq!(
4397            decoded.target.as_ref().unwrap().kind,
4398            RouteOpenTargetKind::Spawn
4399        );
4400        let mut encoded = reply();
4401        RouteOpenReplyExt::new()
4402            .with_target(decoded.target)
4403            .write_to(&mut encoded)
4404            .unwrap();
4405        assert_eq!(encoded, body);
4406        assert_eq!(
4407            serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
4408            legacy
4409        );
4410        RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
4411        assert_eq!(encoded, reply());
4412    }
4413
4414    #[test]
4415    fn reader_skew_route_open_incomplete_target_is_unmarked() {
4416        let mut body = reply();
4417        body["target"] = target();
4418        assert!(RouteOpenReplyExt::read_from(&body)
4419            .unwrap()
4420            .target
4421            .is_some());
4422        for key in [
4423            "incarnation",
4424            "kind",
4425            "spawn",
4426            "authority_epoch",
4427            "first_party",
4428            "approved_declarations_digest",
4429        ] {
4430            let mut incomplete = body.clone();
4431            incomplete["target"].as_object_mut().unwrap().remove(key);
4432            assert_eq!(
4433                RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
4434                None,
4435                "{key}"
4436            );
4437        }
4438        body["target"] = Value::Null;
4439        assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
4440    }
4441
4442    #[test]
4443    fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
4444        for (kind, expected) in [
4445            ("prefix", RouteOpenTargetKind::Prefix),
4446            ("unsupervised", RouteOpenTargetKind::Unsupervised),
4447        ] {
4448            let mut body = reply();
4449            body["target"] = target();
4450            body["target"]["kind"] = json!(kind);
4451            // Spawn-only keys are not parsed, even when a future kind reuses them.
4452            body["target"]["spawn"] = json!("not-a-spawn");
4453            body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
4454            body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
4455            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4456            let target = ext.target.as_ref().unwrap();
4457            assert_eq!(target.kind, expected);
4458            assert_eq!(target.spawn, None);
4459            assert_eq!(target.authority_epoch, None);
4460            assert_eq!(target.approved_declarations_digest, None);
4461            assert!(!target.first_party);
4462            let mut encoded = reply();
4463            ext.write_to(&mut encoded).unwrap();
4464            for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
4465                assert!(encoded["target"].get(key).is_none());
4466            }
4467        }
4468    }
4469
4470    #[test]
4471    fn reader_skew_route_open_unknown_kind_is_not_spawn() {
4472        let mut body = reply();
4473        body["target"] = target();
4474        body["target"]["kind"] = json!("future-kind");
4475        let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4476        let target = ext.target.unwrap();
4477        assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
4478        assert_eq!(target.spawn, None);
4479        assert_eq!(target.authority_epoch, None);
4480        assert_eq!(target.approved_declarations_digest, None);
4481        assert!(!target.first_party);
4482    }
4483
4484    #[test]
4485    fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
4486        for field in ["spawn", "authority_epoch"] {
4487            let mut body = reply();
4488            body["target"] = target();
4489            body["target"][field] = json!(9_007_199_254_740_991_u64);
4490            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
4491            assert_eq!(
4492                serde_json::to_value(ext).unwrap()["target"][field],
4493                9_007_199_254_740_991_u64
4494            );
4495            for invalid in [
4496                json!(9_007_199_254_740_992_u64),
4497                json!(-1),
4498                json!(1.5),
4499                json!("17"),
4500            ] {
4501                body["target"][field] = invalid;
4502                assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
4503                let mut incomplete = body.clone();
4504                incomplete["target"]
4505                    .as_object_mut()
4506                    .unwrap()
4507                    .remove("incarnation");
4508                assert!(
4509                    RouteOpenReplyExt::read_from(&incomplete).is_err(),
4510                    "{field}"
4511                );
4512            }
4513        }
4514    }
4515
4516    #[test]
4517    fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
4518        let mut body = request();
4519        let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
4520        assert_eq!(
4521            RouteOpenRequestExt::read_from(&body).unwrap(),
4522            RouteOpenRequestExt::new()
4523        );
4524        RouteOpenRequestExt::new().write_to(&mut body).unwrap();
4525        assert_eq!(body, request());
4526        body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
4527        let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
4528        assert_eq!(
4529            decoded.accepts_close_reasons,
4530            Some(vec!["authority_changed".into(), "future-reason".into()])
4531        );
4532        let mut encoded = request();
4533        RouteOpenRequestExt::new()
4534            .with_accepts_close_reasons(decoded.accepts_close_reasons)
4535            .write_to(&mut encoded)
4536            .unwrap();
4537        assert_eq!(encoded, body);
4538        assert_eq!(
4539            serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
4540            legacy
4541        );
4542        RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
4543        assert_eq!(encoded, request());
4544        assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
4545    }
4546
4547    #[test]
4548    fn reader_skew_route_open_helpers_refuse_other_bodies() {
4549        for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
4550            assert!(RouteOpenRequestExt::read_from(&body).is_err());
4551            assert!(RouteOpenReplyExt::read_from(&body).is_err());
4552            assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
4553            assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
4554        }
4555    }
4556
4557    #[test]
4558    fn reader_skew_route_open_target_constructor_validates_like_reader() {
4559        let spawn = RouteOpenTarget::new(
4560            "daemon",
4561            RouteOpenTargetKind::Spawn,
4562            Some(17),
4563            Some(23),
4564            true,
4565            Some("approved".into()),
4566        )
4567        .unwrap();
4568        assert_eq!(serde_json::to_value(spawn).unwrap(), target());
4569        for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
4570            assert!(RouteOpenTarget::new(
4571                "daemon",
4572                RouteOpenTargetKind::Spawn,
4573                Some(spawn),
4574                Some(epoch),
4575                true,
4576                Some("approved".into())
4577            )
4578            .is_err());
4579        }
4580    }
4581}
4582
4583#[cfg(test)]
4584mod claim_wire_tests {
4585    use super::*;
4586    use serde_json::{json, Value};
4587
4588    fn legacy_provenance() -> SupervisorModuleProvenance {
4589        SupervisorModuleProvenance {
4590            module_id: "worker".into(),
4591            module_declared: ModuleDeclaredProvenance::Unverifiable,
4592            daemon_observed: SupervisorObservedProcess {
4593                launch_nonce_source: None,
4594                pid: None,
4595                spawned_at_ms: None,
4596                spawned_from: None,
4597                running_image: RunningImageAgreement::Unavailable {
4598                    reason: RunningImageUnavailableReason::NotRunning,
4599                },
4600            },
4601        }
4602    }
4603
4604    #[test]
4605    fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
4606        let legacy = legacy_provenance();
4607        let original = serde_json::to_value(&legacy).unwrap();
4608        let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
4609        assert_eq!(absent.registration, None);
4610        let mut wire = original.clone();
4611        absent.write_to(&mut wire).unwrap();
4612        assert_eq!(wire, original);
4613        for (method, spelling) in [
4614            (RegistrationMethod::Channel, "channel"),
4615            (RegistrationMethod::Nonce, "nonce"),
4616        ] {
4617            let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
4618            ext.write_to(&mut wire).unwrap();
4619            assert_eq!(wire["registration"], spelling);
4620            assert_eq!(
4621                SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
4622                ext
4623            );
4624            let old_reader: SupervisorModuleProvenance =
4625                serde_json::from_value(wire.clone()).unwrap();
4626            assert_eq!(old_reader, legacy);
4627            assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
4628        }
4629        absent.write_to(&mut wire).unwrap();
4630        assert_eq!(wire, original);
4631        for mut invalid in [Value::Null, json!([]), json!("entry")] {
4632            assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
4633            assert!(absent.write_to(&mut invalid).is_err());
4634        }
4635    }
4636
4637    #[test]
4638    fn provenance_unknown_registration_is_not_channel_or_nonce() {
4639        let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
4640        wire["registration"] = json!("future_method");
4641        let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
4642        assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
4643        assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
4644        assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
4645        wire["registration"] = json!(false);
4646        assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
4647    }
4648
4649    #[test]
4650    fn registration_declaration_golden_is_optional_open_and_source_compatible() {
4651        let original = serde_json::to_value(legacy_provenance()).unwrap();
4652        for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
4653            let mut golden = original.clone();
4654            golden["registration_declaration"] = json!(declaration);
4655            let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
4656            assert_eq!(
4657                serde_json::to_value(&extension).unwrap(),
4658                json!({
4659                    "registration_declaration": declaration
4660                })
4661            );
4662            let mut written = original.clone();
4663            extension.write_to(&mut written).unwrap();
4664            assert_eq!(written, golden);
4665            assert_eq!(
4666                serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
4667                legacy_provenance()
4668            );
4669            SupervisorModuleProvenanceExt::new()
4670                .write_to(&mut written)
4671                .unwrap();
4672            assert_eq!(written, original);
4673        }
4674    }
4675
4676    #[test]
4677    fn admission_refusal_is_optional_and_open() {
4678        let entry = SupervisorEntry::new(
4679            "worker",
4680            "stopped",
4681            true,
4682            false,
4683            SupervisorHealthStatus::Unknown,
4684        );
4685        let original = serde_json::to_value(&entry).unwrap();
4686        assert!(original.get("admission_refused").is_none());
4687        let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
4688        assert_eq!(read.admission_refused, None);
4689        assert_eq!(serde_json::to_value(read).unwrap(), original);
4690        assert_eq!(
4691            REGISTRATION_CHANNEL_UNSUPPORTED,
4692            "registration_channel_unsupported"
4693        );
4694        for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
4695            let mut wire = original.clone();
4696            wire["admission_refused"] = json!(reason);
4697            let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
4698            assert_eq!(read.admission_refused.as_deref(), Some(reason));
4699            assert_eq!(serde_json::to_value(read).unwrap(), wire);
4700            let built = entry.clone().with_admission_refused(Some(reason.into()));
4701            assert_eq!(serde_json::to_value(built).unwrap(), wire);
4702        }
4703    }
4704}