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