Skip to main content

subc_control/
config.rs

1//! Opt-in config-gate client wire. Plans never commit until `config.apply` is
2//! approved; a terminal's claim to have displayed a diff grants no authority.
3
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6pub use subc_config::{ApprovalChannel, Digest, Generation, Plan};
7pub use subc_protocol::config::ConfigDeclarationPending;
8
9pub const CONFIG_GATE_CAPABILITY: &str = "config.gate";
10pub const CONFIG_SETTINGS_CAPABILITY: &str = "config.settings/v1";
11
12/// One approved-layer patch. Workspace and project edits currently produce
13/// `layer_not_served`; daemon settings cannot be edited through this operation.
14#[derive(Clone, Debug, PartialEq, Serialize)]
15pub struct ConfigEdit {
16    pub module_id: String,
17    pub layer: String,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub workspace_id: Option<String>,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub project_id: Option<String>,
22    pub path: String,
23    #[serde(flatten)]
24    pub action: ConfigEditAction,
25}
26
27#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
28#[serde(untagged)]
29pub enum ConfigEditAction {
30    Set { set: serde_json::Value },
31    Remove { remove: bool },
32}
33
34impl<'de> Deserialize<'de> for ConfigEdit {
35    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
36        #[derive(Deserialize)]
37        #[serde(deny_unknown_fields)]
38        struct Wire {
39            module_id: String,
40            layer: String,
41            workspace_id: Option<String>,
42            project_id: Option<String>,
43            path: String,
44            #[serde(default, deserialize_with = "present_value")]
45            set: Option<serde_json::Value>,
46            remove: Option<bool>,
47        }
48        fn present_value<'de, D: serde::Deserializer<'de>>(
49            deserializer: D,
50        ) -> Result<Option<serde_json::Value>, D::Error> {
51            serde_json::Value::deserialize(deserializer).map(Some)
52        }
53        let wire = Wire::deserialize(deserializer)?;
54        let action = match (wire.set, wire.remove) {
55            (Some(set), None) => ConfigEditAction::Set { set },
56            (None, Some(true)) => ConfigEditAction::Remove { remove: true },
57            _ => return Err(serde::de::Error::custom("expected set or remove: true")),
58        };
59        Ok(Self {
60            module_id: wire.module_id,
61            layer: wire.layer,
62            workspace_id: wire.workspace_id,
63            project_id: wire.project_id,
64            path: wire.path,
65            action,
66        })
67    }
68}
69
70/// A field refusal is displayed verbatim and prevents applying the whole plan.
71#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
72pub struct ConfigPlanRefusal {
73    pub module_id: String,
74    pub path: String,
75    pub code: String,
76    pub message: String,
77}
78
79/// Standalone bodies keep additions out of the legacy exhaustive control enum.
80/// Unknown request fields are refused, including caller-authored review claims.
81#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
82#[serde(tag = "op", deny_unknown_fields)]
83#[non_exhaustive]
84pub enum ConfigControlRequest {
85    #[serde(rename = "config.status")]
86    Status {},
87    #[serde(rename = "config.modules")]
88    Modules {},
89    #[serde(rename = "config.schema")]
90    Schema { module_id: String },
91    #[serde(rename = "config.show")]
92    Show {
93        module_id: String,
94        #[serde(default, skip_serializing_if = "Option::is_none")]
95        project_id: Option<String>,
96        #[serde(default, skip_serializing_if = "Option::is_none")]
97        through: Option<ConfigThrough>,
98    },
99    #[serde(rename = "config.watch")]
100    Watch {
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        modules: Option<Vec<String>>,
103    },
104    #[serde(rename = "config.plan")]
105    Plan {
106        #[serde(default, skip_serializing_if = "Option::is_none")]
107        base_generations: Option<BTreeMap<String, u64>>,
108        #[serde(default, skip_serializing_if = "Option::is_none")]
109        edits: Option<Vec<ConfigEdit>>,
110    },
111    #[serde(rename = "config.plan_get")]
112    PlanGet { digest: Digest },
113    #[serde(rename = "config.plan_discard")]
114    PlanDiscard { digest: Digest },
115    #[serde(rename = "config.apply")]
116    Apply { digest: Digest },
117    #[serde(rename = "config.stamp")]
118    Stamp {},
119    #[serde(rename = "config.unstamp")]
120    Unstamp {},
121    #[serde(rename = "config.history")]
122    History {},
123    #[serde(rename = "config.rollback")]
124    Rollback { generation: u64 },
125    #[serde(rename = "config.place_program")]
126    PlaceProgram {
127        module_id: String,
128        path: String,
129        sha256: Digest,
130        /// Offline manifest reported by the placement tool, not executed by the daemon.
131        #[serde(default, skip_serializing_if = "Option::is_none")]
132        manifest: Option<serde_json::Value>,
133    },
134}
135
136impl ConfigControlRequest {
137    pub fn op(&self) -> &'static str {
138        match self {
139            Self::Status {} => "config.status",
140            Self::Modules {} => "config.modules",
141            Self::Schema { .. } => "config.schema",
142            Self::Show { .. } => "config.show",
143            Self::Watch { .. } => "config.watch",
144            Self::Plan { .. } => "config.plan",
145            Self::PlanGet { .. } => "config.plan_get",
146            Self::PlanDiscard { .. } => "config.plan_discard",
147            Self::Apply { .. } => "config.apply",
148            Self::Stamp {} => "config.stamp",
149            Self::Unstamp {} => "config.unstamp",
150            Self::History {} => "config.history",
151            Self::Rollback { .. } => "config.rollback",
152            Self::PlaceProgram { .. } => "config.place_program",
153        }
154    }
155}
156
157/// An inclusive upper bound on the layers merged by `config.show`.
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(rename_all = "snake_case")]
160pub enum ConfigThrough {
161    Default,
162    User,
163    Workspace,
164}
165
166/// A user-file observation failure, separate from the approved settings status.
167#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
168#[non_exhaustive]
169pub struct ConfigFileError {
170    pub code: String,
171    pub message: String,
172}
173
174impl ConfigFileError {
175    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
176        Self {
177            code: code.into(),
178            message: message.into(),
179        }
180    }
181}
182
183/// Status strings are open: clients display an unfamiliar status as raw text.
184#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
185#[non_exhaustive]
186pub struct ConfigModule {
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub declaration_pending: Option<ConfigDeclarationPending>,
189    pub module_id: String,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub display_name: Option<String>,
192    pub gated: bool,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub schema_digest: Option<Digest>,
195    pub status: String,
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub status_reason: Option<String>,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub file_error: Option<ConfigFileError>,
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub approved_generation: Option<u64>,
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub active_generation: Option<u64>,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub pending_plan: Option<Digest>,
206}
207
208/// Parsed layer documents, never file paths, raw bytes, or proposal values.
209#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
210#[non_exhaustive]
211pub struct ConfigSettingsLayer {
212    pub layer: subc_config::Layer,
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub workspace_id: Option<String>,
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub project_id: Option<String>,
217    pub document: serde_json::Value,
218}
219
220impl ConfigSettingsLayer {
221    pub fn new(layer: subc_config::Layer, document: serde_json::Value) -> Self {
222        Self {
223            layer,
224            workspace_id: None,
225            project_id: None,
226            document,
227        }
228    }
229}
230
231/// A watch always begins with a full resync, including after reconnecting.
232/// A resync may arrive at any time and replaces the reader's entire state.
233#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
234#[serde(tag = "event", rename_all = "snake_case")]
235#[non_exhaustive]
236pub enum ConfigWatchEvent {
237    Resync {
238        modules: Vec<ConfigModule>,
239        stamped: bool,
240    },
241    Change {
242        module_id: String,
243        #[serde(default, skip_serializing_if = "Option::is_none")]
244        declaration_pending: Option<ConfigDeclarationPending>,
245        #[serde(default, skip_serializing_if = "Option::is_none")]
246        approved_generation: Option<u64>,
247        #[serde(default, skip_serializing_if = "Option::is_none")]
248        active_generation: Option<u64>,
249        status: String,
250        #[serde(default, skip_serializing_if = "Option::is_none")]
251        status_reason: Option<String>,
252        #[serde(default, skip_serializing_if = "Option::is_none")]
253        file_error: Option<ConfigFileError>,
254        #[serde(default, skip_serializing_if = "Option::is_none")]
255        schema_digest: Option<Digest>,
256        #[serde(default, skip_serializing_if = "Option::is_none")]
257        pending_plan: Option<Digest>,
258    },
259}
260
261impl ConfigWatchEvent {
262    pub fn change(row: &ConfigModule) -> Self {
263        Self::Change {
264            module_id: row.module_id.clone(),
265            declaration_pending: row.declaration_pending.clone(),
266            approved_generation: row.approved_generation,
267            active_generation: row.active_generation,
268            status: row.status.clone(),
269            status_reason: row.status_reason.clone(),
270            file_error: row.file_error.clone(),
271            schema_digest: row.schema_digest.clone(),
272            pending_plan: row.pending_plan.clone(),
273        }
274    }
275}
276
277#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
278#[non_exhaustive]
279pub struct ConfigWatchResponse {
280    op: ConfigWatchOp,
281    #[serde(flatten)]
282    pub event: ConfigWatchEvent,
283}
284
285impl ConfigWatchResponse {
286    pub fn new(event: ConfigWatchEvent) -> Self {
287        Self {
288            op: ConfigWatchOp::Watch,
289            event,
290        }
291    }
292}
293
294#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
295enum ConfigWatchOp {
296    #[serde(rename = "config.watch")]
297    Watch,
298}
299
300/// The trusted surface renders the entire plan, not just the digest.
301#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
302#[non_exhaustive]
303pub struct ConfigPlanView {
304    pub digest: Digest,
305    pub base_revision: u64,
306    pub plan: Plan,
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub refusals: Vec<ConfigPlanRefusal>,
309}
310
311impl ConfigPlanView {
312    pub fn new(plan: Plan) -> Result<Self, subc_config::CanonicalError> {
313        Ok(Self {
314            digest: plan.digest()?,
315            base_revision: plan.base_revision,
316            plan,
317            refusals: Vec::new(),
318        })
319    }
320}
321
322/// The durable review channel for a retained or pruned generation.
323#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
324#[non_exhaustive]
325pub struct ConfigApprovalRecord {
326    pub generation: u64,
327    pub channel: ApprovalChannel,
328}
329
330impl ConfigApprovalRecord {
331    pub fn new(generation: u64, channel: ApprovalChannel) -> Self {
332        Self {
333            generation,
334            channel,
335        }
336    }
337}
338
339/// Diagnostic strings are extensible; they never grant approval authority.
340#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
341#[non_exhaustive]
342pub struct ConfigStatus {
343    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
344    pub declaration_pending: BTreeMap<String, ConfigDeclarationPending>,
345    pub approval_channels: Vec<ConfigApprovalRecord>,
346    pub state: String,
347    pub integrity: String,
348    pub revision: u64,
349    pub base_revision: u64,
350    pub pending_proposals: u64,
351    pub anchor_pending: bool,
352    pub ungated_modules: Vec<String>,
353    pub ungated_inputs: Vec<String>,
354    pub gated_modules: Vec<String>,
355    pub interpreter_only_covered: Vec<String>,
356    pub approved_but_inactive: Vec<serde_json::Value>,
357    pub development_switches: Vec<String>,
358    pub missing_approval_surfaces: Vec<String>,
359    pub warnings: Vec<String>,
360}
361
362#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
363#[serde(tag = "op")]
364#[non_exhaustive]
365pub enum ConfigControlResponse {
366    #[serde(rename = "config.status")]
367    Status { status: ConfigStatus },
368    #[serde(rename = "config.modules")]
369    Modules {
370        modules: Vec<ConfigModule>,
371        stamped: bool,
372    },
373    #[serde(rename = "config.schema")]
374    Schema {
375        module_id: String,
376        schema_digest: Digest,
377        schema: serde_json::Value,
378    },
379    #[serde(rename = "config.show")]
380    Show {
381        module_id: String,
382        #[serde(default, skip_serializing_if = "Option::is_none")]
383        project_id: Option<String>,
384        #[serde(default, skip_serializing_if = "Option::is_none")]
385        through: Option<ConfigThrough>,
386        stamped: bool,
387        base_generation: u64,
388        effective: serde_json::Value,
389        sources: std::collections::BTreeMap<String, subc_config::Layer>,
390        layers: Vec<ConfigSettingsLayer>,
391        #[serde(default, skip_serializing_if = "Option::is_none")]
392        file_error: Option<ConfigFileError>,
393        #[serde(default, skip_serializing_if = "Option::is_none")]
394        pending_plan: Option<Digest>,
395        #[serde(default, skip_serializing_if = "Option::is_none")]
396        declaration_pending: Option<ConfigDeclarationPending>,
397    },
398    #[serde(rename = "config.plan")]
399    Plan { view: ConfigPlanView },
400    #[serde(rename = "config.plan_get")]
401    PlanGet { view: ConfigPlanView },
402    #[serde(rename = "config.plan_discard")]
403    PlanDiscard {},
404    #[serde(rename = "config.stamp")]
405    Stamp { view: ConfigPlanView },
406    #[serde(rename = "config.unstamp")]
407    Unstamp { view: ConfigPlanView },
408    #[serde(rename = "config.rollback")]
409    Rollback { view: ConfigPlanView },
410    #[serde(rename = "config.apply")]
411    Applied {
412        generation: u64,
413        #[serde(default)]
414        restart_required: bool,
415    },
416    #[serde(rename = "config.history")]
417    History {
418        generations: Vec<Generation>,
419        pruned: Vec<serde_json::Value>,
420    },
421    #[serde(rename = "config.place_program")]
422    ProgramPlaced {
423        #[serde(default, skip_serializing_if = "Option::is_none")]
424        generation: Option<u64>,
425    },
426}
427
428#[cfg(test)]
429mod tests {
430    #[test]
431    fn config_wire_declaration_pending_reaches_settings_watch() {
432        use super::*;
433        let row = ConfigModule {
434            module_id: "sample".into(),
435            declaration_pending: Some(ConfigDeclarationPending::default()),
436            ..ConfigModule::default()
437        };
438        let event = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
439        let mut wire = serde_json::to_value(&event).unwrap();
440        assert_eq!(wire["declaration_pending"], serde_json::json!({}));
441        wire["declaration_pending"]["future_member"] = serde_json::json!(true);
442        assert_eq!(
443            serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
444            event
445        );
446    }
447    #[test]
448    fn config_wire_existing_bodies_remain_byte_identical() {
449        use super::*;
450        assert_eq!(
451            serde_json::to_vec(&ConfigControlRequest::Plan {
452                base_generations: None,
453                edits: None,
454            })
455            .unwrap(),
456            br#"{"op":"config.plan"}"#
457        );
458        assert_eq!(
459            serde_json::to_vec(&ConfigControlRequest::Status {}).unwrap(),
460            br#"{"op":"config.status"}"#
461        );
462        assert_eq!(
463            serde_json::to_vec(&ConfigControlRequest::History {}).unwrap(),
464            br#"{"op":"config.history"}"#
465        );
466        assert_eq!(
467            serde_json::to_vec(&ConfigControlResponse::History {
468                generations: vec![],
469                pruned: vec![]
470            })
471            .unwrap(),
472            br#"{"op":"config.history","generations":[],"pruned":[]}"#
473        );
474        assert_eq!(serde_json::to_vec(&ConfigControlResponse::Status { status: ConfigStatus::default() }).unwrap(), br#"{"op":"config.status","status":{"approval_channels":[],"state":"","integrity":"","revision":0,"base_revision":0,"pending_proposals":0,"anchor_pending":false,"ungated_modules":[],"ungated_inputs":[],"gated_modules":[],"interpreter_only_covered":[],"approved_but_inactive":[],"development_switches":[],"missing_approval_surfaces":[],"warnings":[]}}"#);
475    }
476
477    #[test]
478    fn config_wire_settings_status_is_open_and_selectors_are_strict() {
479        use super::*;
480        let module: ConfigModule = serde_json::from_value(
481            serde_json::json!({"module_id":"sample","gated":true,"status":"future_status"}),
482        )
483        .unwrap();
484        assert_eq!(module.status, "future_status");
485        assert!(serde_json::from_value::<ConfigControlRequest>(
486            serde_json::json!({"op":"config.show","module_id":"sample","through":"project"})
487        )
488        .is_err());
489        let event = ConfigWatchResponse::new(ConfigWatchEvent::Resync {
490            modules: vec![module],
491            stamped: false,
492        });
493        assert_eq!(
494            serde_json::from_slice::<ConfigWatchResponse>(&serde_json::to_vec(&event).unwrap())
495                .unwrap(),
496            event
497        );
498    }
499
500    #[test]
501    fn config_wire_file_errors_are_optional_and_tolerate_extensions() {
502        let legacy = json!({"module_id":"sample","gated":true,"status":"adopted"});
503        let mut row: ConfigModule = serde_json::from_value(legacy).unwrap();
504        assert!(row.file_error.is_none());
505        let error = ConfigFileError::new("value_invalid", "invalid settings");
506        row.file_error = Some(error.clone());
507        let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
508        let mut wire = serde_json::to_value(&change).unwrap();
509        assert_eq!(
510            wire["file_error"],
511            json!({"code":"value_invalid","message":"invalid settings"})
512        );
513        wire["file_error"]["future"] = json!(true);
514        assert_eq!(
515            serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
516            change
517        );
518        let mut shown = json!({"op":"config.show","module_id":"sample","stamped":true,"base_generation":1,"effective":{},"sources":{},"layers":[]});
519        assert!(matches!(
520            serde_json::from_value::<ConfigControlResponse>(shown.clone()).unwrap(),
521            ConfigControlResponse::Show {
522                file_error: None,
523                ..
524            }
525        ));
526        shown["file_error"] = serde_json::to_value(&error).unwrap();
527        assert!(
528            matches!(serde_json::from_value::<ConfigControlResponse>(shown).unwrap(), ConfigControlResponse::Show {file_error:Some(found), ..} if found == error)
529        );
530    }
531
532    #[test]
533    fn config_wire_program_placement_names_and_optional_generation() {
534        use super::*;
535        let body = serde_json::json!({"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":format!("sha256:{}", "a".repeat(64))});
536        let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
537        assert_eq!(request.op(), "config.place_program");
538        assert_eq!(serde_json::to_value(request).unwrap(), body);
539        assert!(matches!(
540            serde_json::from_value::<ConfigControlResponse>(
541                serde_json::json!({"op":"config.place_program"})
542            )
543            .unwrap(),
544            ConfigControlResponse::ProgramPlaced { generation: None }
545        ));
546        let response = ConfigControlResponse::ProgramPlaced {
547            generation: Some(3),
548        };
549        assert_eq!(
550            serde_json::to_value(response).unwrap(),
551            serde_json::json!({"op":"config.place_program","generation":3})
552        );
553    }
554    #[test]
555    fn config_wire_applied_reports_restart_required_and_defaults_absent_to_false() {
556        use super::*;
557        let response = ConfigControlResponse::Applied {
558            generation: 7,
559            restart_required: true,
560        };
561        assert_eq!(
562            serde_json::to_value(response).unwrap(),
563            serde_json::json!({"op":"config.apply", "generation":7, "restart_required":true})
564        );
565        assert_eq!(
566            serde_json::from_value::<ConfigControlResponse>(
567                serde_json::json!({"op":"config.apply", "generation":7})
568            )
569            .unwrap(),
570            ConfigControlResponse::Applied {
571                generation: 7,
572                restart_required: false,
573            }
574        );
575        assert_eq!(
576            serde_json::to_value(ConfigControlResponse::Applied {
577                generation: 7,
578                restart_required: false,
579            })
580            .unwrap()["restart_required"],
581            false
582        );
583    }
584
585    #[test]
586    fn config_wire_status_and_history_preserve_unverified_approval_channel() {
587        use super::*;
588        let channel = ApprovalChannel::UnverifiedDevelopmentDesktop;
589        let mut status = ConfigStatus::default();
590        status
591            .approval_channels
592            .push(ConfigApprovalRecord::new(1, channel));
593        let generation = Generation::new(
594            1,
595            channel,
596            subc_config::raw_digest(b"plan"),
597            subc_config::InputVector::default(),
598            subc_config::Changeset::new(),
599        );
600        for response in [
601            ConfigControlResponse::Status { status },
602            ConfigControlResponse::History {
603                generations: vec![generation],
604                pruned: vec![],
605            },
606        ] {
607            let encoded = serde_json::to_string(&response).unwrap();
608            assert!(encoded.contains("unverified_development_desktop"));
609            assert_eq!(
610                serde_json::from_str::<ConfigControlResponse>(&encoded).unwrap(),
611                response
612            );
613        }
614    }
615    use super::*;
616    use serde_json::json;
617
618    #[test]
619    fn config_wire_requests_are_strict_and_round_trip() {
620        for body in [
621            json!({"op":"config.status"}),
622            json!({"op":"config.modules"}),
623            json!({"op":"config.schema","module_id":"sample-reader"}),
624            json!({"op":"config.show","module_id":"sample-reader"}),
625            json!({"op":"config.show","module_id":"sample-reader","project_id":"sample-project","through":"workspace"}),
626            json!({"op":"config.watch"}),
627            json!({"op":"config.watch","modules":["sample-reader"]}),
628            json!({"op":"config.plan"}),
629            json!({"op":"config.plan_get", "digest":subc_config::raw_digest(b"plan")}),
630            json!({"op":"config.plan_discard", "digest":subc_config::raw_digest(b"plan")}),
631            json!({"op":"config.apply", "digest":subc_config::raw_digest(b"plan")}),
632            json!({"op":"config.stamp"}),
633            json!({"op":"config.unstamp"}),
634            json!({"op":"config.history"}),
635            json!({"op":"config.rollback", "generation":4}),
636        ] {
637            let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
638            assert_eq!(body["op"], request.op());
639            assert_eq!(serde_json::to_value(&request).unwrap(), body);
640            let mut claimed = body;
641            claimed["reviewed"] = json!(true);
642            assert!(serde_json::from_value::<ConfigControlRequest>(claimed).is_err());
643        }
644        assert!(
645            serde_json::from_value::<ConfigControlRequest>(json!({"op":"config.apply"})).is_err()
646        );
647    }
648
649    #[test]
650    fn config_wire_plan_view_and_status_tolerate_reply_extensions() {
651        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
652        let view = ConfigPlanView::new(plan.clone()).unwrap();
653        assert_eq!(view.digest, plan.digest().unwrap());
654        let response = ConfigControlResponse::Stamp { view };
655        let mut body = serde_json::to_value(&response).unwrap();
656        body["future"] = json!(true);
657        assert_eq!(
658            serde_json::from_value::<ConfigControlResponse>(body).unwrap(),
659            response
660        );
661        let status = ConfigControlResponse::Status {
662            status: ConfigStatus::default(),
663        };
664        assert_eq!(
665            serde_json::from_value::<ConfigControlResponse>(serde_json::to_value(&status).unwrap())
666                .unwrap(),
667            status
668        );
669    }
670
671    #[test]
672    fn config_wire_edit_actions_are_exclusive_and_null_is_not_absence() {
673        let base = json!({"module_id":"demo","layer":"user","path":"/limit"});
674        for action in [
675            json!({"set":0}),
676            json!({"set":false}),
677            json!({"set":null}),
678            json!({"remove":true}),
679        ] {
680            let mut value = base.clone();
681            value
682                .as_object_mut()
683                .unwrap()
684                .extend(action.as_object().unwrap().clone());
685            let edit: ConfigEdit = serde_json::from_value(value.clone()).unwrap();
686            assert_eq!(serde_json::to_value(edit).unwrap(), value);
687        }
688        for action in [
689            json!({}),
690            json!({"set":1,"remove":true}),
691            json!({"remove":false}),
692            json!({"remove":true,"extra":1}),
693        ] {
694            let mut value = base.clone();
695            value
696                .as_object_mut()
697                .unwrap()
698                .extend(action.as_object().unwrap().clone());
699            assert!(serde_json::from_value::<ConfigEdit>(value).is_err());
700        }
701        let request: ConfigControlRequest =
702            serde_json::from_value(json!({"op":"config.plan"})).unwrap();
703        assert_eq!(
704            serde_json::to_vec(&request).unwrap(),
705            br#"{"op":"config.plan"}"#
706        );
707    }
708
709    #[test]
710    fn config_wire_empty_refusals_preserve_legacy_view_bytes() {
711        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
712        let view = ConfigPlanView::new(plan.clone()).unwrap();
713        let legacy = json!({"digest":plan.digest().unwrap(),"base_revision":7,"plan":plan});
714        assert_eq!(serde_json::to_value(&view).unwrap(), legacy);
715        assert_eq!(
716            serde_json::from_value::<ConfigPlanView>(legacy).unwrap(),
717            view
718        );
719        assert_eq!(
720            serde_json::to_string(&ConfigControlResponse::PlanDiscard {}).unwrap(),
721            r#"{"op":"config.plan_discard"}"#
722        );
723    }
724}