Skip to main content

subc_control/
lib.rs

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