1#![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, ProviderRole,
20 SelfSignalDeclaration,
21 },
22 scope::ScopeSelector,
23 session::HealthStatus,
24 BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::RouteCloseReason;
28
29mod activity;
30pub use activity::*;
31
32macro_rules! open_string_enum {
33 (
34 $(#[$meta:meta])*
35 $name:ident {
36 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
37 }
38 ) => {
39 $(#[$meta])*
40 #[derive(Debug, Clone, PartialEq, Eq)]
41 pub enum $name {
42 $( $(#[$variant_meta])* $variant, )+
43 Unknown(String),
44 }
45
46 impl $name {
47 fn wire_name(&self) -> &str {
48 match self {
49 $( Self::$variant => $wire_name, )+
50 Self::Unknown(value) => value,
51 }
52 }
53 }
54
55 impl Serialize for $name {
56 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
57 where
58 S: serde::Serializer,
59 {
60 serializer.serialize_str(self.wire_name())
61 }
62 }
63
64 impl<'de> Deserialize<'de> for $name {
65 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
66 where
67 D: serde::Deserializer<'de>,
68 {
69 let value = String::deserialize(deserializer)?;
70 Ok(match value.as_str() {
71 $( $wire_name => Self::$variant, )+
72 _ => Self::Unknown(value),
73 })
74 }
75 }
76 };
77}
78
79#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
81pub struct ConsumerIdentity {
82 pub module_id: String,
83 pub launch_nonce: String,
84}
85
86impl std::fmt::Debug for ConsumerIdentity {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.debug_struct("ConsumerIdentity")
93 .field("module_id", &self.module_id)
94 .field(
95 "launch_nonce",
96 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
97 )
98 .finish()
99 }
100}
101
102pub mod ops {
113 pub const SERVER: &str = "server.";
114 pub const CATALOG: &str = "catalog.";
115 pub const ROUTE: &str = "route.";
116 pub const SUPERVISOR: &str = "supervisor.";
117 pub const CONFIG: &str = "config.";
118
119 pub const SERVER_DESCRIBE: &str = "server.describe";
120 pub const CATALOG_LIST: &str = "catalog.list";
121 pub const ROUTE_OPEN: &str = "route.open";
122 pub const ROUTE_POLL: &str = "route.poll";
123 pub const ROUTE_CLOSING: &str = "route.closing";
124 pub const ROUTE_CLOSED: &str = "route.closed";
125 pub const SUPERVISOR_LIST: &str = "supervisor.list";
126 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
127 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
128 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
129 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
130 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
131 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
132 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
133 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
134 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
135 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
136 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
137 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
138 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
139 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
140 pub const ACTIVITY_RECORD: &str = "activity.record";
141 pub const ACTIVITY_QUERY: &str = "activity.query";
142 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
147#[serde(tag = "op")]
148#[allow(clippy::large_enum_variant)]
151pub enum ClientControlRequest {
152 #[serde(rename = "server.describe")]
153 ServerDescribe {},
154 #[serde(rename = "catalog.list")]
155 CatalogList {
156 #[serde(default)]
161 module_id: Option<String>,
162 },
163 #[serde(rename = "route.open")]
164 RouteOpen {
165 target: RouteTarget,
166 identity: BindIdentity,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
176 consumer_identity: Option<ConsumerIdentity>,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
185 consumer_capabilities: Option<Vec<String>>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
197 role_versions: Option<BTreeMap<String, String>>,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
200 admission_facts: Option<serde_json::Value>,
201 #[serde(default, skip_serializing_if = "Option::is_none")]
208 scope: Option<ScopeSelector>,
209 },
210 #[serde(rename = "route.poll")]
211 RoutePoll {
212 route_channel: u16,
213 route_epoch: u32,
214 kind: PollKind,
215 },
216 #[serde(rename = "supervisor.list")]
217 SupervisorList {},
218 #[serde(rename = "supervisor.spawn_snapshot")]
220 SupervisorSpawnSnapshot {},
221 #[serde(rename = "supervisor.spawn_subscribe")]
237 SupervisorSpawnSubscribe {
238 #[serde(default, skip_serializing_if = "Option::is_none")]
239 since: Option<SpawnCursor>,
240 },
241 #[serde(rename = "supervisor.restart")]
242 SupervisorRestart {
243 module_id: String,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
254 drain_timeout_ms: Option<u64>,
255 },
256 #[serde(rename = "supervisor.swap")]
271 SupervisorSwap {
272 module_id: String,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
276 ready_timeout_ms: Option<u64>,
277 },
278 #[serde(rename = "supervisor.reload")]
279 SupervisorReload { module_id: String },
280 #[serde(rename = "supervisor.rescan")]
281 SupervisorRescan {
282 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
302 preview: bool,
303 },
304 #[serde(rename = "supervisor.release_reserved")]
308 SupervisorReleaseReserved { module_id: String },
309 #[serde(rename = "supervisor.set_enabled")]
310 SupervisorSetEnabled { module_id: String, enabled: bool },
311 #[serde(rename = "supervisor.health_probe")]
312 SupervisorHealthProbe { module_id: String },
313 #[serde(rename = "supervisor.health")]
314 SupervisorHealth {},
315 #[serde(rename = "supervisor.routes")]
328 SupervisorRoutes {
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 module_id: Option<String>,
331 },
332 #[serde(rename = "supervisor.provenance")]
335 SupervisorProvenance {
336 #[serde(default, skip_serializing_if = "Option::is_none")]
337 module_id: Option<String>,
338 },
339 #[serde(rename = "supervisor.stderr_tail")]
347 SupervisorStderrTail {
348 module_id: String,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
350 max_lines: Option<u32>,
351 #[serde(default, skip_serializing_if = "Option::is_none")]
352 max_bytes: Option<u32>,
353 },
354 #[serde(rename = "supervisor.terminals")]
367 SupervisorTerminals { module_id: String },
368}
369
370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
372#[serde(tag = "op")]
373pub enum ClientControlResponse {
374 #[serde(rename = "server.describe")]
375 ServerDescribe {
376 protocol_ver: u8,
377 subc_ops: Vec<String>,
378 capabilities: Vec<String>,
379 connected_clients: u64,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 counters: Option<serde_json::Value>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
389 build_git_sha: Option<String>,
390 #[serde(default, skip_serializing_if = "Option::is_none")]
396 build_lock_digest: Option<String>,
397 #[serde(default, skip_serializing_if = "Vec::is_empty")]
401 capability_requirements: Vec<CapabilityRequirementStatus>,
402 #[serde(default, skip_serializing_if = "Option::is_none")]
407 machine_id: Option<String>,
408 },
409 #[serde(rename = "catalog.list")]
410 CatalogList {
411 generation: u64,
412 modules: Vec<CatalogEntry>,
413 subc_ops: Vec<String>,
414 },
415 #[serde(rename = "route.open")]
416 RouteOpen {
417 route_channel: u16,
418 route_epoch: u32,
419 },
420 #[serde(rename = "route.poll")]
421 RoutePoll {
422 route_channel: u16,
423 route_epoch: u32,
424 status: Option<String>,
425 live: Option<bool>,
426 },
427 #[serde(rename = "supervisor.list")]
428 SupervisorList {
429 generation: u64,
430 modules: Vec<SupervisorEntry>,
431 },
432 #[serde(rename = "supervisor.spawn_snapshot")]
433 SupervisorSpawnSnapshot {
434 #[serde(flatten)]
435 snapshot: SpawnSnapshot,
436 },
437 #[serde(rename = "supervisor.ack")]
438 SupervisorAck { module_id: String, applied: bool },
439 #[serde(rename = "supervisor.rescan")]
440 SupervisorRescan {
441 #[serde(flatten)]
442 result: SupervisorRescanResult,
443 },
444 #[serde(rename = "supervisor.health_probe")]
445 SupervisorHealthProbe {
446 module_id: String,
447 status: HealthStatus,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 detail: Option<String>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 metrics: Option<serde_json::Value>,
452 },
453 #[serde(rename = "supervisor.health")]
454 SupervisorHealth {
455 generation: u64,
456 modules: Vec<SupervisorHealthEntry>,
457 },
458 #[serde(rename = "supervisor.routes")]
459 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
460 #[serde(rename = "supervisor.provenance")]
461 SupervisorProvenance {
462 daemon: SupervisorDaemonProvenance,
463 modules: Vec<SupervisorModuleProvenance>,
464 },
465 #[serde(rename = "supervisor.stderr_tail")]
466 SupervisorStderrTail {
467 module_id: String,
468 #[serde(flatten)]
469 tail: StderrTail,
470 },
471 #[serde(rename = "supervisor.terminals")]
472 SupervisorTerminals {
473 module_id: String,
474 #[serde(flatten)]
475 terminals: TerminalHistory,
476 },
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
484#[serde(tag = "op")]
485pub enum ClientControlPush {
486 #[serde(rename = "route.closing")]
487 RouteClosing {
488 module_id: String,
489 #[serde(default)]
492 channels: Vec<u16>,
493 reason: RouteCloseReason,
494 },
495 #[serde(rename = "route.closed")]
496 RouteClosed {
497 module_id: String,
498 #[serde(default)]
501 channels: Vec<u16>,
502 reason: RouteCloseReason,
503 drained: bool,
505 abandoned: u32,
508 #[serde(default)]
510 excluded_subscriptions: u32,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
517 terminal: Option<bool>,
518 },
519}
520
521#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
523pub struct SpawnCursor {
524 pub daemon_incarnation: String,
525 pub seq: u64,
526}
527
528#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
530pub struct LiveSpawn {
531 pub module_id: String,
532 pub spawn_generation: u64,
533 pub pid: u32,
534 pub spawned_at_ms: u64,
535}
536
537#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
539pub struct SpawnSnapshot {
540 pub cursor: SpawnCursor,
541 pub ring_bound: u64,
543 pub live: Vec<LiveSpawn>,
544}
545
546#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
548#[serde(rename_all = "snake_case")]
549pub enum SpawnEventKind {
550 Spawned,
551 Exited,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
560pub struct SpawnEvent {
561 pub cursor: SpawnCursor,
562 pub kind: SpawnEventKind,
563 pub module_id: String,
564 pub spawn_generation: u64,
565 pub pid: u32,
566 #[serde(default, skip_serializing_if = "Option::is_none")]
567 pub exit_code: Option<i32>,
568 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub exit_signal: Option<i32>,
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
574pub struct StderrTail {
575 pub capture: StderrCaptureState,
576 pub entries: Vec<StderrTailEntry>,
577 #[serde(default, skip_serializing_if = "is_zero_u64")]
586 pub dropped_lines: u64,
587}
588
589#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
591pub struct SupervisorRouteModule {
592 pub module_id: String,
593 pub routes: Vec<SupervisorRoute>,
594}
595
596#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
598pub struct SupervisorRoute {
599 pub consumer: SupervisorRouteConsumer,
600 pub age_ms: u64,
602 pub draining: bool,
605 #[serde(default, skip_serializing_if = "Option::is_none")]
611 pub drain_reason: Option<RouteCloseReason>,
612}
613
614#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
616pub struct SupervisorModuleProvenance {
617 pub module_id: String,
618 pub module_declared: ModuleDeclaredProvenance,
619 pub daemon_observed: SupervisorObservedProcess,
620}
621
622#[derive(Debug, Clone, PartialEq)]
624pub enum ModuleDeclaredProvenance {
625 Reported {
626 build: ManifestProvenance,
627 },
628 Unverifiable,
629 Unknown {
632 tag: String,
633 body: OrderedJsonObject,
634 },
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
642pub struct SupervisorObservedProcess {
643 #[serde(default, skip_serializing_if = "Option::is_none")]
649 pub launch_nonce_source: Option<String>,
650 #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub pid: Option<u32>,
652 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub spawned_at_ms: Option<u64>,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
655 pub spawned_from: Option<PathBuf>,
656 pub running_image: RunningImageAgreement,
657}
658
659#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
662pub struct PendingReloadVerdict {
663 pub path: ReloadPathAgreement,
664 pub image: RunningImageAgreement,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub spec: Option<LaunchSpecAgreement>,
667}
668
669#[cfg(test)]
670mod launch_spec_wire_tests {
671 use super::*;
672
673 #[test]
674 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
675 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
676 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
677 assert_eq!(parsed.spec, None);
678 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
679 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
680 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
681 assert!(
682 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
683 );
684 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
685 let unavailable = LaunchSpecAgreement::Unavailable {
686 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
687 };
688 let encoded = serde_json::to_string(&unavailable).unwrap();
689 assert_eq!(
690 encoded,
691 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
692 );
693 assert_eq!(
694 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
695 unavailable
696 );
697 }
698}
699
700#[derive(Debug, Clone, PartialEq)]
703pub enum LaunchSpecAgreement {
704 Match,
705 Mismatch,
706 Unavailable {
707 reason: LaunchSpecUnavailableReason,
708 },
709 Unknown {
710 tag: String,
711 body: OrderedJsonObject,
712 },
713}
714
715open_string_enum! {
716 LaunchSpecUnavailableReason {
717 NotRunning => "not_running",
718 SpawnedSpecUnavailable => "spawned_spec_unavailable",
719 }
720}
721
722#[derive(Debug, Clone, PartialEq)]
724pub enum ReloadPathAgreement {
725 Match,
726 Mismatch {
727 configured: PathBuf,
728 spawned_from: PathBuf,
729 },
730 Unavailable {
731 reason: ReloadPathUnavailableReason,
732 },
733 Unknown {
734 tag: String,
735 body: OrderedJsonObject,
736 },
737}
738
739open_string_enum! {
740 ReloadPathUnavailableReason {
742 NotRunning => "not_running",
743 SpawnedPathUnavailable => "spawned_path_unavailable",
744 }
745}
746
747#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
749pub struct SupervisorDaemonProvenance {
750 pub daemon_build: DaemonBuildProvenance,
751 pub daemon_observed: DaemonObservedProcess,
752}
753
754#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
756pub struct DaemonBuildProvenance {
757 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub build_git_sha: Option<String>,
759 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub build_lock_digest: Option<String>,
761}
762
763#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
765pub struct DaemonObservedProcess {
766 #[serde(default, skip_serializing_if = "Option::is_none")]
767 pub pid: Option<u32>,
768 #[serde(default, skip_serializing_if = "Option::is_none")]
773 pub started_at_ms: Option<u64>,
774 pub running_image: RunningImageAgreement,
775}
776
777#[derive(Debug, Clone, PartialEq)]
779pub enum RunningImageAgreement {
780 Match {
781 evidence: RunningImageEvidence,
782 },
783 Mismatch {
784 running: RunningImageEvidence,
785 disk: RunningImageEvidence,
786 },
787 Unavailable {
788 reason: RunningImageUnavailableReason,
789 },
790 Unknown {
793 tag: String,
794 body: OrderedJsonObject,
795 },
796}
797
798#[derive(Debug, Clone, PartialEq)]
800pub enum RunningImageEvidence {
801 LinuxProcSha256 {
802 digest: String,
803 },
804 MacosSpawnInode {
805 device: u64,
806 inode: u64,
807 },
808 WindowsSpawnFileId {
810 volume_serial_number: u64,
811 file_id: [u8; 16],
812 },
813 Unknown {
816 tag: String,
817 body: OrderedJsonObject,
818 },
819}
820
821open_string_enum! {
822 RunningImageUnavailableReason {
824 NotRunning => "not_running",
825 UnsupportedPlatform => "unsupported_platform",
826 RunningExecutableUnreadable => "running_executable_unreadable",
827 RunningExecutablePermissionDenied => "running_executable_permission_denied",
828 ProcessHidden => "process_hidden",
829 SpawnedPathUnreadable => "spawned_path_unreadable",
830 HashFailed => "hash_failed",
831 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
832 }
833}
834
835#[derive(Debug, Clone, PartialEq)]
841pub enum SupervisorRouteConsumer {
842 Reserved {
843 module_id: String,
844 },
845 Direct {
846 connection_id: u64,
847 },
848 Unknown {
851 tag: String,
852 body: OrderedJsonObject,
853 },
854}
855
856#[derive(Debug, Clone, PartialEq)]
863pub enum StderrCaptureState {
864 Captured,
867 Incomplete { reason: String },
869 NotCaptured { reason: String },
871 Unknown {
874 tag: String,
875 body: OrderedJsonObject,
876 },
877}
878
879#[derive(Debug, Clone, PartialEq)]
880pub enum StderrTailEntry {
881 Line {
882 text: String,
883 truncated: bool,
888 at_ms: Option<u64>,
892 },
893 ProcessStart,
898 Unknown {
901 tag: String,
902 body: OrderedJsonObject,
903 },
904}
905
906#[derive(Debug, Serialize, Deserialize)]
907#[serde(tag = "status", rename_all = "snake_case")]
908enum ModuleDeclaredProvenanceWire {
909 Reported { build: ManifestProvenance },
910 Unverifiable,
911}
912
913#[derive(Debug, Serialize, Deserialize)]
914#[serde(tag = "status", rename_all = "snake_case")]
915enum RunningImageAgreementWire {
916 Match {
917 evidence: RunningImageEvidence,
918 },
919 Mismatch {
920 running: RunningImageEvidence,
921 disk: RunningImageEvidence,
922 },
923 Unavailable {
924 reason: RunningImageUnavailableReason,
925 },
926}
927
928#[derive(Debug, Serialize, Deserialize)]
929#[serde(tag = "status", rename_all = "snake_case")]
930enum ReloadPathAgreementWire {
931 Match,
932 Mismatch {
933 configured: PathBuf,
934 spawned_from: PathBuf,
935 },
936 Unavailable {
937 reason: ReloadPathUnavailableReason,
938 },
939}
940
941#[derive(Debug, Serialize, Deserialize)]
942#[serde(tag = "status", rename_all = "snake_case")]
943enum LaunchSpecAgreementWire {
944 Match,
945 Mismatch,
946 Unavailable { reason: LaunchSpecUnavailableReason },
947}
948
949#[derive(Debug, Serialize, Deserialize)]
950#[serde(tag = "method", rename_all = "snake_case")]
951enum RunningImageEvidenceWire {
952 LinuxProcSha256 {
953 digest: String,
954 },
955 MacosSpawnInode {
956 device: u64,
957 inode: u64,
958 },
959 WindowsSpawnFileId {
960 volume_serial_number: u64,
961 file_id: [u8; 16],
962 },
963}
964
965#[derive(Debug, Serialize, Deserialize)]
966#[serde(tag = "kind", rename_all = "snake_case")]
967enum SupervisorRouteConsumerWire {
968 Reserved { module_id: String },
969 Direct { connection_id: u64 },
970}
971
972#[derive(Debug, Serialize, Deserialize)]
973#[serde(tag = "state", rename_all = "snake_case")]
974enum StderrCaptureStateWire {
975 Captured,
976 Incomplete { reason: String },
977 NotCaptured { reason: String },
978}
979
980#[derive(Debug, Serialize, Deserialize)]
981#[serde(tag = "status", rename_all = "snake_case")]
982enum ChildResourceUsageWire {
983 Measured(ChildResourceReading),
984 Unavailable {
985 reason: ChildResourceUnavailableReason,
986 },
987}
988
989#[derive(Debug, Serialize, Deserialize)]
990#[serde(tag = "kind", rename_all = "snake_case")]
991enum StderrTailEntryWire {
992 Line {
993 text: String,
994 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
995 truncated: bool,
996 #[serde(default, skip_serializing_if = "Option::is_none")]
999 at_ms: Option<u64>,
1000 },
1001 ProcessStart,
1002}
1003
1004#[derive(Debug, Clone, PartialEq)]
1006pub enum OrderedJsonValue {
1007 Null,
1008 Bool(bool),
1009 Number(serde_json::Number),
1010 String(String),
1011 Array(Vec<Self>),
1012 Object(OrderedJsonObject),
1013}
1014
1015#[derive(Debug, Clone, PartialEq)]
1017pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1018
1019impl OrderedJsonObject {
1020 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1022 &self.0
1023 }
1024
1025 fn into_value(self) -> serde_json::Value {
1026 serde_json::Value::Object(
1027 self.0
1028 .into_iter()
1029 .map(|(key, value)| (key, value.into_value()))
1030 .collect(),
1031 )
1032 }
1033}
1034
1035impl OrderedJsonValue {
1036 fn into_value(self) -> serde_json::Value {
1037 match self {
1038 Self::Null => serde_json::Value::Null,
1039 Self::Bool(value) => serde_json::Value::Bool(value),
1040 Self::Number(value) => serde_json::Value::Number(value),
1041 Self::String(value) => serde_json::Value::String(value),
1042 Self::Array(values) => {
1043 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1044 }
1045 Self::Object(value) => value.into_value(),
1046 }
1047 }
1048}
1049
1050impl Serialize for OrderedJsonValue {
1051 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1052 where
1053 S: Serializer,
1054 {
1055 match self {
1056 Self::Null => serializer.serialize_unit(),
1057 Self::Bool(value) => serializer.serialize_bool(*value),
1058 Self::Number(value) => value.serialize(serializer),
1059 Self::String(value) => serializer.serialize_str(value),
1060 Self::Array(values) => values.serialize(serializer),
1061 Self::Object(value) => value.serialize(serializer),
1062 }
1063 }
1064}
1065
1066impl<'de> Deserialize<'de> for OrderedJsonValue {
1067 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1068 where
1069 D: Deserializer<'de>,
1070 {
1071 struct OrderedValueVisitor;
1072
1073 impl<'de> Visitor<'de> for OrderedValueVisitor {
1074 type Value = OrderedJsonValue;
1075
1076 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1077 formatter.write_str("a JSON value with ordered object members")
1078 }
1079
1080 fn visit_unit<E>(self) -> Result<Self::Value, E>
1081 where
1082 E: serde::de::Error,
1083 {
1084 Ok(OrderedJsonValue::Null)
1085 }
1086
1087 fn visit_none<E>(self) -> Result<Self::Value, E>
1088 where
1089 E: serde::de::Error,
1090 {
1091 Ok(OrderedJsonValue::Null)
1092 }
1093
1094 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1095 where
1096 D: Deserializer<'de>,
1097 {
1098 OrderedJsonValue::deserialize(deserializer)
1099 }
1100
1101 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1102 where
1103 E: serde::de::Error,
1104 {
1105 Ok(OrderedJsonValue::Bool(value))
1106 }
1107
1108 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1109 where
1110 E: serde::de::Error,
1111 {
1112 Ok(OrderedJsonValue::Number(value.into()))
1113 }
1114
1115 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1116 where
1117 E: serde::de::Error,
1118 {
1119 Ok(OrderedJsonValue::Number(value.into()))
1120 }
1121
1122 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1123 where
1124 E: serde::de::Error,
1125 {
1126 serde_json::Number::from_f64(value)
1127 .map(OrderedJsonValue::Number)
1128 .ok_or_else(|| E::custom("non-finite JSON number"))
1129 }
1130
1131 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1132 where
1133 E: serde::de::Error,
1134 {
1135 Ok(OrderedJsonValue::String(value.to_owned()))
1136 }
1137
1138 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1139 where
1140 E: serde::de::Error,
1141 {
1142 Ok(OrderedJsonValue::String(value))
1143 }
1144
1145 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1146 where
1147 A: SeqAccess<'de>,
1148 {
1149 let mut values = Vec::new();
1150 while let Some(value) = sequence.next_element()? {
1151 values.push(value);
1152 }
1153 Ok(OrderedJsonValue::Array(values))
1154 }
1155
1156 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1157 where
1158 A: MapAccess<'de>,
1159 {
1160 let mut entries = Vec::new();
1161 while let Some((key, value)) = map.next_entry()? {
1162 entries.push((key, value));
1163 }
1164 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1165 }
1166 }
1167
1168 deserializer.deserialize_any(OrderedValueVisitor)
1169 }
1170}
1171
1172impl Serialize for OrderedJsonObject {
1173 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1174 where
1175 S: Serializer,
1176 {
1177 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1178 for (key, value) in &self.0 {
1179 map.serialize_entry(key, value)?;
1180 }
1181 map.end()
1182 }
1183}
1184
1185impl<'de> Deserialize<'de> for OrderedJsonObject {
1186 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1187 where
1188 D: Deserializer<'de>,
1189 {
1190 struct OrderedObjectVisitor;
1191
1192 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1193 type Value = OrderedJsonObject;
1194
1195 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1196 formatter.write_str("an object with ordered JSON members")
1197 }
1198
1199 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1200 where
1201 A: MapAccess<'de>,
1202 {
1203 let mut entries = Vec::new();
1204 while let Some((key, value)) = map.next_entry()? {
1205 entries.push((key, value));
1206 }
1207 Ok(OrderedJsonObject(entries))
1208 }
1209 }
1210
1211 deserializer.deserialize_map(OrderedObjectVisitor)
1212 }
1213}
1214
1215fn read_tagged<'de, D>(
1216 deserializer: D,
1217 field: &'static str,
1218) -> Result<(String, OrderedJsonObject), D::Error>
1219where
1220 D: Deserializer<'de>,
1221{
1222 let body = OrderedJsonObject::deserialize(deserializer)?;
1223 let mut tag = None;
1224 for (key, value) in body.as_entries() {
1225 if key != field {
1226 continue;
1227 }
1228 if tag.is_some() {
1229 return Err(D::Error::custom(format!(
1230 "tagged object has duplicate `{field}` field"
1231 )));
1232 }
1233 let OrderedJsonValue::String(value) = value else {
1234 return Err(D::Error::custom(format!(
1235 "tagged object has no string `{field}` field"
1236 )));
1237 };
1238 tag = Some(value);
1239 }
1240 let Some(tag) = tag else {
1241 return Err(D::Error::custom(format!(
1242 "tagged object has no string `{field}` field"
1243 )));
1244 };
1245 Ok((tag.to_string(), body))
1246}
1247
1248fn read_ordered_tagged(
1249 value: OrderedJsonValue,
1250 field: &'static str,
1251) -> Result<(String, OrderedJsonObject), String> {
1252 let OrderedJsonValue::Object(body) = value else {
1253 return Err(format!("expected tagged object with `{field}` field"));
1254 };
1255 let mut tag = None;
1256 for (key, value) in body.as_entries() {
1257 if key != field {
1258 continue;
1259 }
1260 if tag.is_some() {
1261 return Err(format!("tagged object has duplicate `{field}` field"));
1262 }
1263 let OrderedJsonValue::String(value) = value else {
1264 return Err(format!("tagged object has no string `{field}` field"));
1265 };
1266 tag = Some(value);
1267 }
1268 let Some(tag) = tag else {
1269 return Err(format!("tagged object has no string `{field}` field"));
1270 };
1271 Ok((tag.to_string(), body))
1272}
1273
1274fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1275 body.as_entries()
1276 .iter()
1277 .find_map(|(key, value)| (key == field).then_some(value))
1278}
1279
1280fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1281 match ordered_field(body, field) {
1282 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1283 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1284 None => Err(format!("tagged object has no `{field}` field")),
1285 }
1286}
1287
1288fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1289 let (tag, body) = read_ordered_tagged(value, "method")?;
1290 match tag.as_str() {
1291 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1292 digest: ordered_string(&body, "digest")?,
1293 }),
1294 "macos_spawn_inode" => {
1295 let device = ordered_field(&body, "device")
1296 .and_then(|value| match value {
1297 OrderedJsonValue::Number(number) => number.as_u64(),
1298 _ => None,
1299 })
1300 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1301 let inode = ordered_field(&body, "inode")
1302 .and_then(|value| match value {
1303 OrderedJsonValue::Number(number) => number.as_u64(),
1304 _ => None,
1305 })
1306 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1307 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1308 }
1309 "windows_spawn_file_id" => {
1310 let wire: RunningImageEvidenceWire = serde_json::from_value(
1311 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1312 )
1313 .map_err(|error| error.to_string())?;
1314 match wire {
1315 RunningImageEvidenceWire::WindowsSpawnFileId {
1316 volume_serial_number,
1317 file_id,
1318 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1319 volume_serial_number,
1320 file_id,
1321 }),
1322 _ => unreachable!(),
1323 }
1324 }
1325 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1326 }
1327}
1328
1329impl Serialize for ModuleDeclaredProvenance {
1330 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1331 where
1332 S: Serializer,
1333 {
1334 match self {
1335 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1336 build: build.clone(),
1337 }
1338 .serialize(serializer),
1339 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1340 Self::Unknown { body, .. } => body.serialize(serializer),
1341 }
1342 }
1343}
1344
1345impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1346 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1347 where
1348 D: serde::Deserializer<'de>,
1349 {
1350 let (tag, value) = read_tagged(deserializer, "status")?;
1351 match tag.as_str() {
1352 "reported" => match serde_json::from_value(value.into_value())
1353 .map_err(D::Error::custom)?
1354 {
1355 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1356 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1357 },
1358 "unverifiable" => {
1359 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1360 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1361 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1362 }
1363 }
1364 _ => Ok(Self::Unknown { tag, body: value }),
1365 }
1366 }
1367}
1368
1369impl Serialize for RunningImageAgreement {
1370 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1371 where
1372 S: Serializer,
1373 {
1374 match self {
1375 Self::Match { evidence } => RunningImageAgreementWire::Match {
1376 evidence: evidence.clone(),
1377 }
1378 .serialize(serializer),
1379 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1380 running: running.clone(),
1381 disk: disk.clone(),
1382 }
1383 .serialize(serializer),
1384 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1385 reason: reason.clone(),
1386 }
1387 .serialize(serializer),
1388 Self::Unknown { body, .. } => body.serialize(serializer),
1389 }
1390 }
1391}
1392
1393impl Serialize for ReloadPathAgreement {
1394 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1395 where
1396 S: Serializer,
1397 {
1398 match self {
1399 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1400 Self::Mismatch {
1401 configured,
1402 spawned_from,
1403 } => ReloadPathAgreementWire::Mismatch {
1404 configured: configured.clone(),
1405 spawned_from: spawned_from.clone(),
1406 }
1407 .serialize(serializer),
1408 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1409 reason: reason.clone(),
1410 }
1411 .serialize(serializer),
1412 Self::Unknown { body, .. } => body.serialize(serializer),
1413 }
1414 }
1415}
1416
1417impl Serialize for LaunchSpecAgreement {
1418 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1419 where
1420 S: Serializer,
1421 {
1422 match self {
1423 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1424 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1425 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1426 reason: reason.clone(),
1427 }
1428 .serialize(serializer),
1429 Self::Unknown { body, .. } => body.serialize(serializer),
1430 }
1431 }
1432}
1433
1434impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1435 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1436 where
1437 D: Deserializer<'de>,
1438 {
1439 let (tag, body) = read_tagged(deserializer, "status")?;
1440 match tag.as_str() {
1441 "match" => Ok(Self::Match),
1442 "mismatch" => Ok(Self::Mismatch),
1443 "unavailable" => match serde_json::from_value(body.into_value())
1444 .map_err(D::Error::custom)?
1445 {
1446 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1447 _ => unreachable!(),
1448 },
1449 _ => Ok(Self::Unknown { tag, body }),
1450 }
1451 }
1452}
1453
1454impl<'de> Deserialize<'de> for ReloadPathAgreement {
1455 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1456 where
1457 D: Deserializer<'de>,
1458 {
1459 let (tag, body) = read_tagged(deserializer, "status")?;
1460 match tag.as_str() {
1461 "match" => Ok(Self::Match),
1462 "mismatch" => {
1463 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1464 ReloadPathAgreementWire::Mismatch {
1465 configured,
1466 spawned_from,
1467 } => Ok(Self::Mismatch {
1468 configured,
1469 spawned_from,
1470 }),
1471 _ => unreachable!(),
1472 }
1473 }
1474 "unavailable" => match serde_json::from_value(body.into_value())
1475 .map_err(D::Error::custom)?
1476 {
1477 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1478 _ => unreachable!(),
1479 },
1480 _ => Ok(Self::Unknown { tag, body }),
1481 }
1482 }
1483}
1484
1485impl<'de> Deserialize<'de> for RunningImageAgreement {
1486 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1487 where
1488 D: serde::Deserializer<'de>,
1489 {
1490 let (tag, value) = read_tagged(deserializer, "status")?;
1491 match tag.as_str() {
1492 "match" => Ok(Self::Match {
1493 evidence: decode_running_image_evidence(
1494 ordered_field(&value, "evidence")
1495 .cloned()
1496 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1497 )
1498 .map_err(D::Error::custom)?,
1499 }),
1500 "mismatch" => Ok(Self::Mismatch {
1501 running: decode_running_image_evidence(
1502 ordered_field(&value, "running")
1503 .cloned()
1504 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1505 )
1506 .map_err(D::Error::custom)?,
1507 disk: decode_running_image_evidence(
1508 ordered_field(&value, "disk")
1509 .cloned()
1510 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1511 )
1512 .map_err(D::Error::custom)?,
1513 }),
1514 "unavailable" => Ok(Self::Unavailable {
1515 reason: serde_json::from_value(
1516 ordered_field(&value, "reason")
1517 .cloned()
1518 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1519 .into_value(),
1520 )
1521 .map_err(D::Error::custom)?,
1522 }),
1523 _ => Ok(Self::Unknown { tag, body: value }),
1524 }
1525 }
1526}
1527
1528impl Serialize for ChildResourceUsage {
1529 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1530 where
1531 S: Serializer,
1532 {
1533 match self {
1534 Self::Measured(reading) => {
1535 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1536 }
1537 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1538 reason: reason.clone(),
1539 }
1540 .serialize(serializer),
1541 Self::Unknown { body, .. } => body.serialize(serializer),
1542 }
1543 }
1544}
1545
1546impl<'de> Deserialize<'de> for ChildResourceUsage {
1547 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1548 where
1549 D: Deserializer<'de>,
1550 {
1551 let (tag, body) = read_tagged(deserializer, "status")?;
1552 match tag.as_str() {
1553 "measured" | "unavailable" => {
1554 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1555 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1556 ChildResourceUsageWire::Unavailable { reason } => {
1557 Ok(Self::Unavailable { reason })
1558 }
1559 }
1560 }
1561 _ => Ok(Self::Unknown { tag, body }),
1562 }
1563 }
1564}
1565
1566impl Serialize for RunningImageEvidence {
1567 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1568 where
1569 S: Serializer,
1570 {
1571 match self {
1572 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1573 digest: digest.clone(),
1574 }
1575 .serialize(serializer),
1576 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1577 device: *device,
1578 inode: *inode,
1579 }
1580 .serialize(serializer),
1581 Self::WindowsSpawnFileId {
1582 volume_serial_number,
1583 file_id,
1584 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1585 volume_serial_number: *volume_serial_number,
1586 file_id: *file_id,
1587 }
1588 .serialize(serializer),
1589 Self::Unknown { body, .. } => body.serialize(serializer),
1590 }
1591 }
1592}
1593
1594impl<'de> Deserialize<'de> for RunningImageEvidence {
1595 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1596 where
1597 D: serde::Deserializer<'de>,
1598 {
1599 let (tag, value) = read_tagged(deserializer, "method")?;
1600 match tag.as_str() {
1601 "linux_proc_sha256" => {
1602 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1603 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1604 Ok(Self::LinuxProcSha256 { digest })
1605 }
1606 _ => unreachable!(),
1607 }
1608 }
1609 "macos_spawn_inode" => {
1610 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1611 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1612 Ok(Self::MacosSpawnInode { device, inode })
1613 }
1614 _ => unreachable!(),
1615 }
1616 }
1617 "windows_spawn_file_id" => {
1618 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1619 RunningImageEvidenceWire::WindowsSpawnFileId {
1620 volume_serial_number,
1621 file_id,
1622 } => Ok(Self::WindowsSpawnFileId {
1623 volume_serial_number,
1624 file_id,
1625 }),
1626 _ => unreachable!(),
1627 }
1628 }
1629 _ => Ok(Self::Unknown { tag, body: value }),
1630 }
1631 }
1632}
1633
1634impl Serialize for SupervisorRouteConsumer {
1635 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1636 where
1637 S: Serializer,
1638 {
1639 match self {
1640 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1641 module_id: module_id.clone(),
1642 }
1643 .serialize(serializer),
1644 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1645 connection_id: *connection_id,
1646 }
1647 .serialize(serializer),
1648 Self::Unknown { body, .. } => body.serialize(serializer),
1649 }
1650 }
1651}
1652
1653impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1654 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1655 where
1656 D: serde::Deserializer<'de>,
1657 {
1658 let (tag, value) = read_tagged(deserializer, "kind")?;
1659 match tag.as_str() {
1660 "reserved" => {
1661 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1662 SupervisorRouteConsumerWire::Reserved { module_id } => {
1663 Ok(Self::Reserved { module_id })
1664 }
1665 _ => unreachable!(),
1666 }
1667 }
1668 "direct" => {
1669 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1670 SupervisorRouteConsumerWire::Direct { connection_id } => {
1671 Ok(Self::Direct { connection_id })
1672 }
1673 _ => unreachable!(),
1674 }
1675 }
1676 _ => Ok(Self::Unknown { tag, body: value }),
1677 }
1678 }
1679}
1680
1681impl Serialize for StderrCaptureState {
1682 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1683 where
1684 S: Serializer,
1685 {
1686 match self {
1687 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1688 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1689 reason: reason.clone(),
1690 }
1691 .serialize(serializer),
1692 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1693 reason: reason.clone(),
1694 }
1695 .serialize(serializer),
1696 Self::Unknown { body, .. } => body.serialize(serializer),
1697 }
1698 }
1699}
1700
1701impl<'de> Deserialize<'de> for StderrCaptureState {
1702 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1703 where
1704 D: serde::Deserializer<'de>,
1705 {
1706 let (tag, value) = read_tagged(deserializer, "state")?;
1707 match tag.as_str() {
1708 "captured" => {
1709 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1710 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1711 _ => unreachable!(),
1712 }
1713 }
1714 "incomplete" => match serde_json::from_value(value.into_value())
1715 .map_err(D::Error::custom)?
1716 {
1717 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1718 _ => unreachable!(),
1719 },
1720 "not_captured" => match serde_json::from_value(value.into_value())
1721 .map_err(D::Error::custom)?
1722 {
1723 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1724 _ => unreachable!(),
1725 },
1726 _ => Ok(Self::Unknown { tag, body: value }),
1727 }
1728 }
1729}
1730
1731impl Serialize for StderrTailEntry {
1732 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1733 where
1734 S: Serializer,
1735 {
1736 match self {
1737 Self::Line {
1738 text,
1739 truncated,
1740 at_ms,
1741 } => StderrTailEntryWire::Line {
1742 text: text.clone(),
1743 truncated: *truncated,
1744 at_ms: *at_ms,
1745 }
1746 .serialize(serializer),
1747 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1748 Self::Unknown { body, .. } => body.serialize(serializer),
1749 }
1750 }
1751}
1752
1753impl<'de> Deserialize<'de> for StderrTailEntry {
1754 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1755 where
1756 D: serde::Deserializer<'de>,
1757 {
1758 let (tag, value) = read_tagged(deserializer, "kind")?;
1759 match tag.as_str() {
1760 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1761 StderrTailEntryWire::Line {
1762 text,
1763 truncated,
1764 at_ms,
1765 } => Ok(Self::Line {
1766 text,
1767 truncated,
1768 at_ms,
1769 }),
1770 _ => unreachable!(),
1771 },
1772 "process_start" => {
1773 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1774 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1775 _ => unreachable!(),
1776 }
1777 }
1778 _ => Ok(Self::Unknown { tag, body: value }),
1779 }
1780 }
1781}
1782
1783fn is_zero_u64(value: &u64) -> bool {
1784 *value == 0
1785}
1786
1787fn default_true() -> bool {
1788 true
1789}
1790
1791#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1793pub struct TerminalHistory {
1794 pub daemon_started_at_ms: u64,
1796 pub entries: Vec<TerminalEntry>,
1797 #[serde(default, skip_serializing_if = "is_zero_u64")]
1800 pub dropped: u64,
1801 #[serde(default, skip_serializing_if = "is_zero_u64")]
1804 pub journal_skipped_lines: u64,
1805 #[serde(default, skip_serializing_if = "is_zero_u64")]
1807 pub journal_read_errors: u64,
1808 #[serde(default, skip_serializing_if = "is_zero_u64")]
1810 pub journal_write_failures: u64,
1811}
1812
1813#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1815pub struct TerminalEntry {
1816 #[serde(default, skip_serializing_if = "Option::is_none")]
1819 pub daemon_incarnation: Option<String>,
1820 #[serde(default, skip_serializing_if = "Option::is_none")]
1821 pub exit_code: Option<i32>,
1822 #[serde(default, skip_serializing_if = "Option::is_none")]
1823 pub exit_signal: Option<i32>,
1824 pub at_ms: u64,
1825 pub disposition: TerminalDisposition,
1826 #[serde(default, skip_serializing_if = "Option::is_none")]
1830 pub exit_kind: Option<TerminalExitKind>,
1831 #[serde(default, skip_serializing_if = "Option::is_none")]
1838 pub disposition_detail: Option<String>,
1839}
1840
1841#[derive(Debug, Clone, PartialEq, Eq)]
1846pub enum TerminalExitKind {
1847 Clean,
1848 Crash,
1849 DeliberateSeverance,
1850 Unknown(String),
1851}
1852
1853impl TerminalExitKind {
1854 fn wire_name(&self) -> &str {
1855 match self {
1856 Self::Clean => "clean",
1857 Self::Crash => "crash",
1858 Self::DeliberateSeverance => "deliberate_severance",
1859 Self::Unknown(value) => value,
1860 }
1861 }
1862}
1863
1864impl Serialize for TerminalExitKind {
1865 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1866 where
1867 S: serde::Serializer,
1868 {
1869 serializer.serialize_str(self.wire_name())
1870 }
1871}
1872
1873impl<'de> Deserialize<'de> for TerminalExitKind {
1874 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1875 where
1876 D: serde::Deserializer<'de>,
1877 {
1878 let value = String::deserialize(deserializer)?;
1879 Ok(match value.as_str() {
1880 "clean" => Self::Clean,
1881 "crash" => Self::Crash,
1882 "deliberate_severance" => Self::DeliberateSeverance,
1883 _ => Self::Unknown(value),
1884 })
1885 }
1886}
1887
1888open_string_enum! {
1889 TerminalDisposition {
1891 Stopped => "stopped",
1892 Disabled => "disabled",
1893 Failed => "failed",
1894 Restarting => "restarting",
1895 DaemonShutdown => "daemon_shutdown",
1900 }
1901}
1902
1903#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1904#[serde(rename_all = "snake_case")]
1905pub enum PollKind {
1906 Status,
1907 Liveness,
1908}
1909
1910#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1922#[non_exhaustive]
1923pub struct CatalogEntry {
1924 pub module_id: String,
1925 #[serde(default = "default_true")]
1936 pub ready: bool,
1937 #[serde(default, skip_serializing_if = "Option::is_none")]
1941 pub not_ready: Option<NotReadyReason>,
1942 #[serde(default, skip_serializing_if = "Option::is_none")]
1963 pub module_version: Option<String>,
1964 pub roles: Vec<ProviderRole>,
1965 pub control_ops: Vec<String>,
1966 #[serde(default, skip_serializing_if = "Option::is_none")]
1971 pub capabilities: Option<CapabilityDeclarations>,
1972 #[serde(default, skip_serializing_if = "Option::is_none")]
1975 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
1976 #[serde(default, skip_serializing_if = "Option::is_none")]
1980 pub events: Option<Vec<EventDeclaration>>,
1981}
1982
1983impl CatalogEntry {
1984 #[must_use]
1986 pub fn new(
1987 module_id: impl Into<String>,
1988 roles: Vec<ProviderRole>,
1989 control_ops: Vec<String>,
1990 ) -> Self {
1991 Self {
1992 module_id: module_id.into(),
1993 ready: default_true(),
1994 not_ready: None,
1995 module_version: None,
1996 roles,
1997 control_ops,
1998 capabilities: None,
1999 self_signals: None,
2000 events: None,
2001 }
2002 }
2003
2004 #[must_use]
2006 pub fn with_ready(mut self, ready: bool) -> Self {
2007 self.ready = ready;
2008 self
2009 }
2010
2011 #[must_use]
2013 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2014 self.not_ready = not_ready;
2015 self
2016 }
2017
2018 #[must_use]
2020 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2021 self.module_version = module_version;
2022 self
2023 }
2024
2025 #[must_use]
2027 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2028 self.capabilities = capabilities;
2029 self
2030 }
2031
2032 #[must_use]
2034 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2035 self.self_signals = self_signals;
2036 self
2037 }
2038
2039 #[must_use]
2041 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2042 self.events = events;
2043 self
2044 }
2045}
2046
2047#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2049pub struct NotReadyReason {
2050 pub reason: String,
2055 #[serde(default, skip_serializing_if = "Option::is_none")]
2058 pub capability: Option<String>,
2059}
2060
2061impl NotReadyReason {
2062 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2063 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2064}
2065
2066#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2067pub struct CapabilityRequirementStatus {
2068 pub consumer: String,
2069 pub capability: String,
2070 pub need: String,
2071 pub verdict: String,
2072 pub episode_seq: u64,
2073 pub config_satisfiable: bool,
2074 pub runtime_available: bool,
2075 pub detail: String,
2076}
2077
2078#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2079pub struct SupervisorRescanResult {
2080 pub added: Vec<String>,
2081 pub removed: Vec<String>,
2082 pub changed_pending_reload: Vec<String>,
2083 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2096 pub enabled_changes: Vec<String>,
2097 pub unchanged: u32,
2098 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2106 pub preview: bool,
2107 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2125 pub restart_required: Vec<String>,
2126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2130 pub capability_warnings: Vec<String>,
2131}
2132
2133#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2149#[serde(rename_all = "snake_case")]
2150pub enum ModuleProtocol {
2151 #[default]
2155 Subc,
2156 None,
2165}
2166
2167#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2179#[non_exhaustive]
2180pub struct SupervisorEntry {
2181 #[serde(default, skip_serializing_if = "Option::is_none")]
2184 pub waiting_for_previous_pid: Option<u32>,
2185 pub module_id: String,
2186 pub state: String,
2187 pub enabled: bool,
2188 pub live: bool,
2198 #[serde(default)]
2202 pub protocol: ModuleProtocol,
2203 #[serde(default, skip_serializing_if = "Option::is_none")]
2206 pub launch_nonce_env: Option<bool>,
2207 #[serde(default, skip_serializing_if = "Option::is_none")]
2213 pub launch_nonce_source: Option<String>,
2214 pub health: SupervisorHealthStatus,
2215 #[serde(default, skip_serializing_if = "Option::is_none")]
2218 pub pending_reload: Option<PendingReloadVerdict>,
2219 #[serde(default)]
2225 pub last_probe_ms: Option<u64>,
2226 #[serde(default, skip_serializing_if = "Option::is_none")]
2230 pub last_exit_code: Option<i32>,
2231 #[serde(default, skip_serializing_if = "Option::is_none")]
2235 pub last_exit_signal: Option<i32>,
2236 #[serde(default, skip_serializing_if = "Option::is_none")]
2240 pub last_exit_ms: Option<u64>,
2241 #[serde(default, skip_serializing_if = "Option::is_none")]
2244 pub last_exit_kind: Option<TerminalExitKind>,
2245 #[serde(default, skip_serializing_if = "Option::is_none")]
2262 pub restart_count: Option<u32>,
2263 #[serde(default, skip_serializing_if = "Option::is_none")]
2266 pub max_restarts: Option<u32>,
2267 #[serde(default, skip_serializing_if = "Option::is_none")]
2270 pub lifetime_restarts: Option<u32>,
2271 #[serde(default, skip_serializing_if = "Option::is_none")]
2275 pub spawn_generation: Option<u64>,
2276 #[serde(default, skip_serializing_if = "Option::is_none")]
2286 pub restart_window_secs: Option<u64>,
2287 #[serde(default, skip_serializing_if = "Option::is_none")]
2291 pub drain_timeout_ms: Option<u64>,
2292 #[serde(default, skip_serializing_if = "Option::is_none")]
2295 pub restart_backoff_ms: Option<u64>,
2296 #[serde(default, skip_serializing_if = "Option::is_none")]
2299 pub restart_max_backoff_ms: Option<u64>,
2300 #[serde(default, skip_serializing_if = "Option::is_none")]
2313 pub resources: Option<ChildResourceUsage>,
2314}
2315
2316impl SupervisorEntry {
2317 #[must_use]
2319 pub fn new(
2320 module_id: impl Into<String>,
2321 state: impl Into<String>,
2322 enabled: bool,
2323 live: bool,
2324 health: SupervisorHealthStatus,
2325 ) -> Self {
2326 Self {
2327 module_id: module_id.into(),
2328 state: state.into(),
2329 waiting_for_previous_pid: None,
2330 enabled,
2331 live,
2332 protocol: ModuleProtocol::default(),
2333 launch_nonce_env: None,
2334 launch_nonce_source: None,
2335 health,
2336 pending_reload: None,
2337 last_probe_ms: None,
2338 last_exit_code: None,
2339 last_exit_signal: None,
2340 last_exit_ms: None,
2341 last_exit_kind: None,
2342 restart_count: None,
2343 max_restarts: None,
2344 lifetime_restarts: None,
2345 spawn_generation: None,
2346 restart_window_secs: None,
2347 drain_timeout_ms: None,
2348 restart_backoff_ms: None,
2349 restart_max_backoff_ms: None,
2350 resources: None,
2351 }
2352 }
2353
2354 #[must_use]
2356 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2357 self.protocol = protocol;
2358 self
2359 }
2360
2361 #[must_use]
2363 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2364 self.launch_nonce_env = launch_nonce_env;
2365 self
2366 }
2367
2368 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2369 self.launch_nonce_source = source;
2370 self
2371 }
2372
2373 #[must_use]
2374 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2375 self.waiting_for_previous_pid = pid;
2376 self
2377 }
2378
2379 #[must_use]
2381 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2382 self.pending_reload = pending_reload;
2383 self
2384 }
2385
2386 #[must_use]
2388 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2389 self.last_probe_ms = last_probe_ms;
2390 self
2391 }
2392
2393 #[must_use]
2395 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2396 self.last_exit_code = last_exit_code;
2397 self
2398 }
2399
2400 #[must_use]
2402 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2403 self.last_exit_signal = last_exit_signal;
2404 self
2405 }
2406
2407 #[must_use]
2409 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2410 self.last_exit_ms = last_exit_ms;
2411 self
2412 }
2413
2414 #[must_use]
2416 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2417 self.last_exit_kind = last_exit_kind;
2418 self
2419 }
2420
2421 #[must_use]
2423 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2424 self.restart_count = restart_count;
2425 self
2426 }
2427
2428 #[must_use]
2430 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2431 self.max_restarts = max_restarts;
2432 self
2433 }
2434
2435 #[must_use]
2437 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2438 self.lifetime_restarts = lifetime_restarts;
2439 self
2440 }
2441
2442 #[must_use]
2444 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2445 self.spawn_generation = spawn_generation;
2446 self
2447 }
2448
2449 #[must_use]
2451 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2452 self.restart_window_secs = restart_window_secs;
2453 self
2454 }
2455
2456 #[must_use]
2458 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2459 self.drain_timeout_ms = drain_timeout_ms;
2460 self
2461 }
2462
2463 #[must_use]
2465 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2466 self.restart_backoff_ms = restart_backoff_ms;
2467 self
2468 }
2469
2470 #[must_use]
2472 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2473 self.restart_max_backoff_ms = restart_max_backoff_ms;
2474 self
2475 }
2476
2477 #[must_use]
2479 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2480 self.resources = resources;
2481 self
2482 }
2483}
2484
2485#[derive(Debug, Clone, PartialEq)]
2488pub enum ChildResourceUsage {
2489 Measured(ChildResourceReading),
2490 Unavailable {
2491 reason: ChildResourceUnavailableReason,
2492 },
2493 Unknown {
2496 tag: String,
2497 body: OrderedJsonObject,
2498 },
2499}
2500
2501#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2503pub struct ChildResourceReading {
2504 pub memory_bytes: u64,
2507 pub memory_kind: ChildMemoryKind,
2508 #[serde(default, skip_serializing_if = "Option::is_none")]
2511 pub swap_bytes: Option<u64>,
2512 pub cpu_user_ms: u64,
2516 pub cpu_system_ms: u64,
2519}
2520
2521open_string_enum! {
2522 ChildMemoryKind {
2524 PhysFootprint => "phys_footprint",
2528 ResidentSet => "resident_set",
2531 WindowsWorkingSet => "windows_working_set",
2534 }
2535}
2536
2537open_string_enum! {
2538 ChildResourceUnavailableReason {
2540 NotRunning => "not_running",
2542 UnsupportedPlatform => "unsupported_platform",
2544 Unreadable => "unreadable",
2547 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2550 }
2551}
2552
2553#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2554#[serde(rename_all = "snake_case")]
2555pub enum SupervisorHealthStatus {
2556 Ok,
2557 Degraded,
2558 Failing,
2559 Unresponsive,
2560 Unknown,
2561}
2562
2563#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2564pub struct SupervisorHealthEntry {
2565 pub module_id: String,
2566 pub status: SupervisorHealthStatus,
2567 #[serde(default, skip_serializing_if = "Option::is_none")]
2573 pub detail: Option<String>,
2574 #[serde(default, skip_serializing_if = "Option::is_none")]
2579 pub metrics: Option<serde_json::Value>,
2580 pub consecutive_failures: u32,
2581 #[serde(default)]
2584 pub late_answer_count: u64,
2585 #[serde(default, skip_serializing_if = "Option::is_none")]
2587 pub last_late_answer_latency_ms: Option<u64>,
2588 #[serde(default)]
2593 pub last_action: Option<String>,
2594 #[serde(default)]
2597 pub last_action_ms: Option<u64>,
2598 #[serde(default, skip_serializing_if = "Option::is_none")]
2611 pub last_probe_ms: Option<u64>,
2612}
2613
2614#[cfg(test)]
2615mod tests {
2616 #[test]
2617 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2618 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2619 volume_serial_number: u64::MAX,
2620 file_id: [
2621 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2622 ],
2623 };
2624 let agreement = super::RunningImageAgreement::Match { evidence };
2625 let encoded = serde_json::to_string(&agreement).unwrap();
2626 assert!(encoded.contains("windows_spawn_file_id"));
2627 assert_eq!(
2628 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2629 agreement
2630 );
2631 }
2632
2633 #[test]
2634 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2635 assert_eq!(
2636 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2637 device: 7,
2638 inode: 11
2639 })
2640 .unwrap(),
2641 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2642 );
2643 assert_eq!(
2644 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2645 digest: "abc".to_owned()
2646 })
2647 .unwrap(),
2648 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2649 );
2650 }
2651 use super::*;
2652 use subc_protocol::{BindIdentity, RouteTarget};
2653
2654 #[test]
2655 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2656 let entry = TerminalEntry {
2657 daemon_incarnation: Some("daemon-before-restart".into()),
2658 exit_code: Some(1),
2659 exit_signal: None,
2660 at_ms: 1_700_000_000_123,
2661 disposition: TerminalDisposition::Restarting,
2662 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2663 disposition_detail: None,
2664 };
2665 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2666 assert_eq!(
2667 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2668 ["exit_kind"],
2669 "deliberate_severance"
2670 );
2671
2672 #[derive(serde::Deserialize)]
2673 struct LegacyTerminalEntry {
2674 exit_code: Option<i32>,
2675 exit_signal: Option<i32>,
2676 at_ms: u64,
2677 disposition: TerminalDisposition,
2678 }
2679
2680 let decoded: LegacyTerminalEntry =
2681 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2682 assert_eq!(decoded.exit_code, Some(1));
2683 assert_eq!(decoded.exit_signal, None);
2684 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2685 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2686
2687 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2688 let future: TerminalEntry =
2689 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2690 assert_eq!(
2691 future.exit_kind,
2692 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2693 );
2694 }
2695
2696 #[test]
2697 fn terminal_incarnation_is_optional_for_older_daemons() {
2698 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2699 "at_ms": 123,
2700 "disposition": "stopped"
2701 }))
2702 .unwrap();
2703 let encoded = serde_json::to_value(&entry).unwrap();
2704 assert_eq!(
2705 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2706 (None, None)
2707 );
2708 }
2709
2710 #[test]
2711 fn route_poll_uses_kind_field() {
2712 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2713 route_channel: 7,
2714 route_epoch: 11,
2715 kind: PollKind::Status,
2716 })
2717 .unwrap();
2718
2719 assert_eq!(body["op"], "route.poll");
2720 assert_eq!(body["route_epoch"], 11);
2721 assert_eq!(body["kind"], "status");
2722 assert!(body.get("op").is_some());
2723 }
2724
2725 #[test]
2726 fn route_open_is_internally_tagged() {
2727 let request = ClientControlRequest::RouteOpen {
2728 target: RouteTarget::ToolProvider {
2729 module_id: "aft".to_string(),
2730 },
2731 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2732 consumer_identity: None,
2733 consumer_capabilities: None,
2734 role_versions: None,
2735 admission_facts: None,
2736 scope: None,
2737 };
2738
2739 let body = serde_json::to_value(request).unwrap();
2740 assert_eq!(body["op"], "route.open");
2741 assert_eq!(body["target"]["kind"], "tool_provider");
2742 assert!(body.get("consumer_identity").is_none());
2743 assert!(body.get("consumer_capabilities").is_none());
2744 assert!(body.get("role_versions").is_none());
2745 }
2746
2747 #[test]
2748 fn route_open_without_optional_fields_still_decodes() {
2749 let body = serde_json::json!({
2750 "op": "route.open",
2751 "target": { "kind": "tool_provider", "module_id": "aft" },
2752 "identity": {
2753 "project_root": "/tmp/project",
2754 "harness": "opencode",
2755 "session": "session-1"
2756 }
2757 });
2758
2759 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
2760 let ClientControlRequest::RouteOpen {
2761 consumer_identity,
2762 consumer_capabilities,
2763 role_versions,
2764 admission_facts,
2765 ..
2766 } = decoded
2767 else {
2768 panic!("decoded wrong request variant");
2769 };
2770 assert_eq!(consumer_identity, None);
2771 assert_eq!(consumer_capabilities, None);
2772 assert_eq!(role_versions, None);
2773 assert_eq!(admission_facts, None);
2774 }
2775
2776 #[test]
2777 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
2778 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
2779 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
2780 match decoded {
2781 ClientControlPush::RouteClosed {
2782 excluded_subscriptions,
2783 terminal,
2784 ..
2785 } => {
2786 assert_eq!(excluded_subscriptions, 0);
2787 assert_eq!(terminal, None);
2788 }
2789 other => panic!("unexpected push: {other:?}"),
2790 }
2791 assert!(!serde_json::to_string(&decoded)
2792 .unwrap()
2793 .contains("terminal"));
2794 }
2795
2796 #[test]
2797 fn old_route_closed_decoder_ignores_new_terminal_field() {
2798 #[derive(serde::Deserialize)]
2799 #[serde(tag = "op")]
2800 enum LegacyClientControlPush {
2801 #[serde(rename = "route.closed")]
2802 RouteClosed {
2803 module_id: String,
2804 reason: RouteCloseReason,
2805 drained: bool,
2806 abandoned: u32,
2807 },
2808 }
2809
2810 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
2811 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
2812 match decoded {
2813 LegacyClientControlPush::RouteClosed {
2814 module_id,
2815 reason,
2816 drained,
2817 abandoned,
2818 } => {
2819 assert_eq!(module_id, "aft-tools");
2820 assert_eq!(reason, RouteCloseReason::Crash);
2821 assert!(!drained);
2822 assert_eq!(abandoned, 0);
2823 }
2824 }
2825 }
2826
2827 #[test]
2828 fn supervisor_routes_is_a_control_plane_request() {
2829 let body = serde_json::json!({
2830 "op": "supervisor.routes",
2831 "module_id": "aft"
2832 });
2833
2834 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
2835 assert_eq!(serde_json::to_value(request).unwrap(), body);
2836 }
2837
2838 #[test]
2839 fn diagnostic_string_enums_retain_unknown_wire_values() {
2840 let reason: RunningImageUnavailableReason =
2841 serde_json::from_str("\"future_reason\"").unwrap();
2842 let disposition: TerminalDisposition =
2843 serde_json::from_str("\"future_disposition\"").unwrap();
2844
2845 assert_eq!(
2846 reason,
2847 RunningImageUnavailableReason::Unknown("future_reason".to_string())
2848 );
2849 assert_eq!(
2850 disposition,
2851 TerminalDisposition::Unknown("future_disposition".to_string())
2852 );
2853 }
2854
2855 #[test]
2856 fn diagnostic_string_enums_preserve_existing_wire_names() {
2857 let names = [
2858 (RunningImageUnavailableReason::NotRunning, "not_running"),
2859 (
2860 RunningImageUnavailableReason::UnsupportedPlatform,
2861 "unsupported_platform",
2862 ),
2863 (
2864 RunningImageUnavailableReason::RunningExecutableUnreadable,
2865 "running_executable_unreadable",
2866 ),
2867 (
2868 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
2869 "running_executable_permission_denied",
2870 ),
2871 (
2872 RunningImageUnavailableReason::ProcessHidden,
2873 "process_hidden",
2874 ),
2875 (
2876 RunningImageUnavailableReason::SpawnedPathUnreadable,
2877 "spawned_path_unreadable",
2878 ),
2879 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
2880 (
2881 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
2882 "process_identity_unconfirmed",
2883 ),
2884 ];
2885 for (value, expected) in names {
2886 let wire = serde_json::to_string(&value).unwrap();
2887 assert_eq!(wire, format!("\"{expected}\""));
2888 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
2889 assert_eq!(decoded, value);
2890 }
2891
2892 for (value, expected) in [
2893 (TerminalDisposition::Stopped, "stopped"),
2894 (TerminalDisposition::Disabled, "disabled"),
2895 (TerminalDisposition::Failed, "failed"),
2896 (TerminalDisposition::Restarting, "restarting"),
2897 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
2898 ] {
2899 let wire = serde_json::to_string(&value).unwrap();
2900 assert_eq!(wire, format!("\"{expected}\""));
2901 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
2902 assert_eq!(decoded, value);
2903 }
2904 }
2905
2906 #[test]
2907 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
2908 let entry = SupervisorEntry::new(
2909 "waiting-module",
2910 "starting",
2911 true,
2912 false,
2913 SupervisorHealthStatus::Unknown,
2914 );
2915 let old_wire = serde_json::to_value(&entry).unwrap();
2916 assert!(old_wire.get("waiting_for_previous_pid").is_none());
2917 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
2918 assert_eq!(decoded.waiting_for_previous_pid, None);
2919 let entry = entry.with_waiting_for_previous_pid(Some(42));
2920 let wire = serde_json::to_value(&entry).unwrap();
2921 assert_eq!(wire["waiting_for_previous_pid"], 42);
2922 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
2923 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
2924 }
2925
2926 #[test]
2927 fn diagnostic_string_enums_reject_non_string_bodies() {
2928 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
2929 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
2930 }
2931
2932 #[test]
2933 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
2934 let body = serde_json::json!({
2935 "op": "supervisor.provenance",
2936 "daemon": {
2937 "daemon_build": {},
2938 "daemon_observed": {
2939 "running_image": {
2940 "status": "unavailable",
2941 "reason": "not_running"
2942 }
2943 }
2944 },
2945 "modules": [
2946 {
2947 "module_id": "future",
2948 "module_declared": { "status": "unverifiable" },
2949 "daemon_observed": {
2950 "running_image": {
2951 "status": "unavailable",
2952 "reason": "future_reason"
2953 }
2954 }
2955 },
2956 {
2957 "module_id": "healthy-a",
2958 "module_declared": { "status": "unverifiable" },
2959 "daemon_observed": {
2960 "running_image": {
2961 "status": "match",
2962 "evidence": {
2963 "method": "linux_proc_sha256",
2964 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
2965 }
2966 }
2967 }
2968 },
2969 {
2970 "module_id": "healthy-b",
2971 "module_declared": { "status": "unverifiable" },
2972 "daemon_observed": {
2973 "running_image": {
2974 "status": "unavailable",
2975 "reason": "unsupported_platform"
2976 }
2977 }
2978 }
2979 ]
2980 });
2981
2982 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
2983 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
2984 panic!("decoded wrong response variant");
2985 };
2986 assert_eq!(modules.len(), 3);
2987 assert_eq!(modules[0].module_id, "future");
2988 assert_eq!(
2989 modules[0].daemon_observed.running_image,
2990 RunningImageAgreement::Unavailable {
2991 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
2992 }
2993 );
2994 assert_eq!(modules[1].module_id, "healthy-a");
2995 assert_eq!(modules[2].module_id, "healthy-b");
2996 }
2997
2998 #[test]
2999 fn tagged_unknown_values_retain_tag_and_body() {
3000 macro_rules! assert_unknown_round_trip {
3001 ($ty:ident, $field:literal, $value:expr) => {
3002 let value = $value;
3003 let wire = serde_json::to_string(&value).unwrap();
3004 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3005 match decoded {
3006 $ty::Unknown { tag, body } => {
3007 assert_eq!(tag, value[$field].as_str().unwrap());
3008 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3009 }
3010 _ => panic!("decoded known variant"),
3011 }
3012 };
3013 }
3014
3015 assert_unknown_round_trip!(
3016 ModuleDeclaredProvenance,
3017 "status",
3018 serde_json::json!({"status": "future", "build": {"version": 7}})
3019 );
3020 assert_unknown_round_trip!(
3021 RunningImageAgreement,
3022 "status",
3023 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3024 );
3025 assert_unknown_round_trip!(
3026 RunningImageEvidence,
3027 "method",
3028 serde_json::json!({"method": "future", "digest": "abc"})
3029 );
3030 assert_unknown_round_trip!(
3031 SupervisorRouteConsumer,
3032 "kind",
3033 serde_json::json!({"kind": "future", "module_id": "m"})
3034 );
3035 assert_unknown_round_trip!(
3036 StderrCaptureState,
3037 "state",
3038 serde_json::json!({"state": "future", "reason": "because"})
3039 );
3040 assert_unknown_round_trip!(
3041 StderrTailEntry,
3042 "kind",
3043 serde_json::json!({"kind": "future", "text": "line"})
3044 );
3045 assert_unknown_round_trip!(
3046 ChildResourceUsage,
3047 "status",
3048 serde_json::json!({"status": "future", "memory_bytes": 1})
3049 );
3050 }
3051
3052 #[test]
3053 fn child_resource_usage_round_trips_both_known_states() {
3054 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3055 memory_bytes: 0,
3056 memory_kind: ChildMemoryKind::ResidentSet,
3057 swap_bytes: Some(0),
3058 cpu_user_ms: 0,
3059 cpu_system_ms: 0,
3060 });
3061 let wire = serde_json::to_value(&measured).unwrap();
3062 assert_eq!(
3063 wire,
3064 serde_json::json!({
3065 "status": "measured",
3066 "memory_bytes": 0,
3067 "memory_kind": "resident_set",
3068 "swap_bytes": 0,
3069 "cpu_user_ms": 0,
3070 "cpu_system_ms": 0
3071 })
3072 );
3073 assert_eq!(
3074 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3075 measured
3076 );
3077
3078 let unavailable = ChildResourceUsage::Unavailable {
3079 reason: ChildResourceUnavailableReason::NotRunning,
3080 };
3081 let wire = serde_json::to_value(&unavailable).unwrap();
3082 assert_eq!(
3083 wire,
3084 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3085 );
3086 assert_eq!(
3087 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3088 unavailable
3089 );
3090 }
3091
3092 #[test]
3093 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3094 let stamped: StderrTailEntry = serde_json::from_str(
3098 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3099 )
3100 .unwrap();
3101 assert_eq!(
3102 stamped,
3103 StderrTailEntry::Line {
3104 text: "boom".to_string(),
3105 truncated: true,
3106 at_ms: Some(1_789_801_440_685),
3107 }
3108 );
3109 let unstamped: StderrTailEntry =
3110 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3111 assert_eq!(
3112 unstamped,
3113 StderrTailEntry::Line {
3114 text: "boom".to_string(),
3115 truncated: false,
3116 at_ms: None,
3117 }
3118 );
3119 assert_eq!(
3122 serde_json::to_string(&unstamped).unwrap(),
3123 r#"{"kind":"line","text":"boom"}"#
3124 );
3125 assert_eq!(
3126 serde_json::to_value(&stamped).unwrap()["at_ms"],
3127 serde_json::json!(1_789_801_440_685u64)
3128 );
3129 }
3130
3131 #[test]
3132 fn tagged_unknown_values_round_trip_the_original_json() {
3133 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3134 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3135 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3136 }
3137
3138 #[test]
3139 fn tagged_unknown_values_round_trip_trailing_tag() {
3140 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3141 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3142 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3143
3144 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3145 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3146 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3147 }
3148
3149 #[test]
3150 fn tagged_unknown_values_round_trip_middle_tag() {
3151 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3152 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3153 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3154
3155 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3156 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3157 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3158 }
3159
3160 #[test]
3161 fn tagged_unknown_values_round_trip_deep_payload() {
3162 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3163 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3164 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3165
3166 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3167 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3168 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3169 }
3170
3171 #[test]
3172 fn tagged_unknown_values_reject_non_object_bodies() {
3173 for wire in ["42", r#""future""#, "[]"] {
3174 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3175 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3176 }
3177 }
3178
3179 #[test]
3180 fn duplicate_discriminators_reject_without_panicking() {
3181 assert_eq!(
3182 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3183 .unwrap(),
3184 ModuleDeclaredProvenance::Unverifiable
3185 );
3186 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3187 .unwrap()
3188 {
3189 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3190 _ => panic!("future discriminator decoded as a known variant"),
3191 }
3192
3193 let wires = [
3194 r#"{"status":"reported","status":"unverifiable"}"#,
3195 r#"{"status":"unverifiable","status":"reported"}"#,
3196 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3197 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3198 ];
3199
3200 for wire in wires {
3201 let result =
3202 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3203 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3204 assert!(
3205 result.unwrap().is_err(),
3206 "duplicate discriminator decoded: {wire}"
3207 );
3208 }
3209
3210 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3211 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3212 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3213 assert!(
3214 result.unwrap().is_err(),
3215 "duplicate discriminator decoded: {wire}"
3216 );
3217 }
3218
3219 #[test]
3220 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3221 let known_wire =
3222 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3223 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3224 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3225
3226 for wire in [
3227 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3228 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3229 ] {
3230 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3231 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3232 }
3233
3234 for wire in [
3235 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3236 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3237 ] {
3238 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3239 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3240 }
3241
3242 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3243 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3244 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3245
3246 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3247 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3248 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3249 }
3250
3251 #[test]
3252 fn tagged_unknown_member_does_not_discard_known_siblings() {
3253 let body = serde_json::json!({
3254 "modules": [{
3255 "module_id": "target",
3256 "routes": [
3257 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3258 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3259 ]
3260 }]
3261 });
3262 let decoded: ClientControlResponse = serde_json::from_value(
3263 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3264 )
3265 .unwrap();
3266 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3267 panic!("decoded wrong response variant");
3268 };
3269 assert_eq!(modules[0].routes.len(), 2);
3270 assert_eq!(
3271 modules[0].routes[1].consumer,
3272 SupervisorRouteConsumer::Direct { connection_id: 7 }
3273 );
3274 }
3275}
3276
3277#[cfg(test)]
3278mod launch_nonce_redaction_tests {
3279 use super::*;
3280
3281 const NONCE: &str = "nonce-f00dfeed1234abcd";
3282
3283 fn identity() -> ConsumerIdentity {
3284 ConsumerIdentity {
3285 module_id: "wernicke".to_string(),
3286 launch_nonce: NONCE.to_string(),
3287 }
3288 }
3289
3290 #[test]
3291 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3292 let printed = format!("{:?}", identity());
3293 assert!(printed.contains("wernicke"), "{printed}");
3294 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3295 }
3296
3297 #[test]
3298 fn route_open_request_debug_never_prints_the_nonce() {
3299 let request = ClientControlRequest::RouteOpen {
3300 target: subc_protocol::RouteTarget::ToolProvider {
3301 module_id: "broca".to_string(),
3302 },
3303 identity: subc_protocol::BindIdentity::new(
3304 PathBuf::from("/tmp/project"),
3305 "test".to_string(),
3306 "session".to_string(),
3307 ),
3308 consumer_identity: Some(identity()),
3309 consumer_capabilities: None,
3310 role_versions: None,
3311 admission_facts: None,
3312 scope: None,
3313 };
3314 let printed = format!("{request:?}");
3315 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3316 }
3317}