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