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";
11pub const CONFIG_SETTINGS_PROJECTS_CAPABILITY: &str = "config.settings.projects/v1";
12
13/// One approved-layer patch. Workspace and project edits currently produce
14/// `layer_not_served`; daemon settings cannot be edited through this operation.
15#[derive(Clone, Debug, PartialEq, Serialize)]
16pub struct ConfigEdit {
17    pub module_id: String,
18    pub layer: String,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub workspace_id: Option<String>,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub project_id: Option<String>,
23    pub path: String,
24    #[serde(flatten)]
25    pub action: ConfigEditAction,
26}
27
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29#[serde(untagged)]
30pub enum ConfigEditAction {
31    Set { set: serde_json::Value },
32    Remove { remove: bool },
33}
34
35impl<'de> Deserialize<'de> for ConfigEdit {
36    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
37        #[derive(Deserialize)]
38        #[serde(deny_unknown_fields)]
39        struct Wire {
40            module_id: String,
41            layer: String,
42            workspace_id: Option<String>,
43            project_id: Option<String>,
44            path: String,
45            #[serde(default, deserialize_with = "present_value")]
46            set: Option<serde_json::Value>,
47            remove: Option<bool>,
48        }
49        fn present_value<'de, D: serde::Deserializer<'de>>(
50            deserializer: D,
51        ) -> Result<Option<serde_json::Value>, D::Error> {
52            serde_json::Value::deserialize(deserializer).map(Some)
53        }
54        let wire = Wire::deserialize(deserializer)?;
55        let action = match (wire.set, wire.remove) {
56            (Some(set), None) => ConfigEditAction::Set { set },
57            (None, Some(true)) => ConfigEditAction::Remove { remove: true },
58            _ => return Err(serde::de::Error::custom("expected set or remove: true")),
59        };
60        Ok(Self {
61            module_id: wire.module_id,
62            layer: wire.layer,
63            workspace_id: wire.workspace_id,
64            project_id: wire.project_id,
65            path: wire.path,
66            action,
67        })
68    }
69}
70
71/// A diagnostic displayed verbatim for a blocking refusal or a skipped input.
72#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
73pub struct ConfigPlanRefusal {
74    pub module_id: String,
75    pub path: String,
76    pub code: String,
77    pub message: String,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub project_id: Option<String>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub workspace_id: Option<String>,
82}
83
84/// Standalone bodies keep additions out of the legacy exhaustive control enum.
85/// Unknown request fields are refused, including caller-authored review claims.
86#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
87#[serde(tag = "op", deny_unknown_fields)]
88#[non_exhaustive]
89pub enum ConfigControlRequest {
90    #[serde(rename = "config.status")]
91    Status {},
92    #[serde(rename = "config.modules")]
93    Modules {},
94    #[serde(rename = "config.schema")]
95    Schema { module_id: String },
96    #[serde(rename = "config.show")]
97    Show {
98        module_id: String,
99        #[serde(default, skip_serializing_if = "Option::is_none")]
100        project_id: Option<String>,
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        through: Option<ConfigThrough>,
103    },
104    #[serde(rename = "config.watch")]
105    Watch {
106        #[serde(default, skip_serializing_if = "Option::is_none")]
107        modules: Option<Vec<String>>,
108        /// Only `true` opts in to project rows.
109        #[serde(default, skip_serializing_if = "Option::is_none")]
110        projects: Option<bool>,
111    },
112    #[serde(rename = "config.plan")]
113    Plan {
114        #[serde(default, skip_serializing_if = "Option::is_none")]
115        base_generations: Option<BTreeMap<String, u64>>,
116        #[serde(default, skip_serializing_if = "Option::is_none")]
117        edits: Option<Vec<ConfigEdit>>,
118    },
119    #[serde(rename = "config.plan_get")]
120    PlanGet { digest: Digest },
121    #[serde(rename = "config.plan_discard")]
122    PlanDiscard { digest: Digest },
123    #[serde(rename = "config.apply")]
124    Apply { digest: Digest },
125    #[serde(rename = "config.stamp")]
126    Stamp {},
127    #[serde(rename = "config.unstamp")]
128    Unstamp {},
129    #[serde(rename = "config.history")]
130    History {},
131    #[serde(rename = "config.rollback")]
132    Rollback { generation: u64 },
133    #[serde(rename = "config.place_program")]
134    PlaceProgram {
135        module_id: String,
136        path: String,
137        sha256: Digest,
138        /// Offline manifest reported by the placement tool, not executed by the daemon.
139        #[serde(default, skip_serializing_if = "Option::is_none")]
140        manifest: Option<serde_json::Value>,
141    },
142}
143
144impl ConfigControlRequest {
145    pub fn op(&self) -> &'static str {
146        match self {
147            Self::Status {} => "config.status",
148            Self::Modules {} => "config.modules",
149            Self::Schema { .. } => "config.schema",
150            Self::Show { .. } => "config.show",
151            Self::Watch { .. } => "config.watch",
152            Self::Plan { .. } => "config.plan",
153            Self::PlanGet { .. } => "config.plan_get",
154            Self::PlanDiscard { .. } => "config.plan_discard",
155            Self::Apply { .. } => "config.apply",
156            Self::Stamp {} => "config.stamp",
157            Self::Unstamp {} => "config.unstamp",
158            Self::History {} => "config.history",
159            Self::Rollback { .. } => "config.rollback",
160            Self::PlaceProgram { .. } => "config.place_program",
161        }
162    }
163}
164
165/// An inclusive upper bound on the layers merged by `config.show`.
166#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
167#[serde(rename_all = "snake_case")]
168pub enum ConfigThrough {
169    Default,
170    User,
171    Workspace,
172}
173
174/// A settings-file observation failure, separate from the approved settings status.
175#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
176#[non_exhaustive]
177pub struct ConfigFileError {
178    pub code: String,
179    pub message: String,
180}
181
182impl ConfigFileError {
183    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
184        Self {
185            code: code.into(),
186            message: message.into(),
187        }
188    }
189}
190
191/// Status strings are open: clients display an unfamiliar status as raw text.
192#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
193#[non_exhaustive]
194pub struct ConfigModule {
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub declaration_pending: Option<ConfigDeclarationPending>,
197    pub module_id: String,
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub project_id: Option<String>,
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub workspace_id: Option<String>,
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub display_name: Option<String>,
204    pub gated: bool,
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub schema_digest: Option<Digest>,
207    pub status: String,
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub status_reason: Option<String>,
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub file_error: Option<ConfigFileError>,
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub approved_generation: Option<u64>,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub active_generation: Option<u64>,
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub pending_plan: Option<Digest>,
218}
219
220/// Parsed layer documents, never file paths, raw bytes, or proposal values.
221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct ConfigSettingsLayer {
224    pub layer: subc_config::Layer,
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub workspace_id: Option<String>,
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub project_id: Option<String>,
229    pub document: serde_json::Value,
230}
231
232impl ConfigSettingsLayer {
233    pub fn new(layer: subc_config::Layer, document: serde_json::Value) -> Self {
234        Self {
235            layer,
236            workspace_id: None,
237            project_id: None,
238            document,
239        }
240    }
241}
242
243/// A watch always begins with a full resync, including after reconnecting.
244/// A resync may arrive at any time and replaces the reader's entire state.
245#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
246#[serde(tag = "event", rename_all = "snake_case")]
247#[non_exhaustive]
248// Resync holds a vector, while Change exposes its fields directly so Rust
249// callers can keep matching the existing optional fields without indirection.
250#[allow(clippy::large_enum_variant)]
251pub enum ConfigWatchEvent {
252    Resync {
253        modules: Vec<ConfigModule>,
254        stamped: bool,
255    },
256    Change {
257        module_id: String,
258        #[serde(default, skip_serializing_if = "Option::is_none")]
259        project_id: Option<String>,
260        #[serde(default, skip_serializing_if = "Option::is_none")]
261        workspace_id: Option<String>,
262        #[serde(default, skip_serializing_if = "Option::is_none")]
263        declaration_pending: Option<ConfigDeclarationPending>,
264        #[serde(default, skip_serializing_if = "Option::is_none")]
265        approved_generation: Option<u64>,
266        #[serde(default, skip_serializing_if = "Option::is_none")]
267        active_generation: Option<u64>,
268        status: String,
269        #[serde(default, skip_serializing_if = "Option::is_none")]
270        status_reason: Option<String>,
271        #[serde(default, skip_serializing_if = "Option::is_none")]
272        file_error: Option<ConfigFileError>,
273        #[serde(default, skip_serializing_if = "Option::is_none")]
274        schema_digest: Option<Digest>,
275        #[serde(default, skip_serializing_if = "Option::is_none")]
276        pending_plan: Option<Digest>,
277    },
278}
279
280impl ConfigWatchEvent {
281    pub fn change(row: &ConfigModule) -> Self {
282        Self::Change {
283            module_id: row.module_id.clone(),
284            project_id: row.project_id.clone(),
285            workspace_id: row.workspace_id.clone(),
286            declaration_pending: row.declaration_pending.clone(),
287            approved_generation: row.approved_generation,
288            active_generation: row.active_generation,
289            status: row.status.clone(),
290            status_reason: row.status_reason.clone(),
291            file_error: row.file_error.clone(),
292            schema_digest: row.schema_digest.clone(),
293            pending_plan: row.pending_plan.clone(),
294        }
295    }
296}
297
298#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
299#[non_exhaustive]
300pub struct ConfigWatchResponse {
301    op: ConfigWatchOp,
302    #[serde(flatten)]
303    pub event: ConfigWatchEvent,
304}
305
306impl ConfigWatchResponse {
307    pub fn new(event: ConfigWatchEvent) -> Self {
308        Self {
309            op: ConfigWatchOp::Watch,
310            event,
311        }
312    }
313}
314
315#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
316enum ConfigWatchOp {
317    #[serde(rename = "config.watch")]
318    Watch,
319}
320
321/// The trusted surface renders the entire plan, not just the digest.
322#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
323#[non_exhaustive]
324pub struct ConfigPlanView {
325    pub digest: Digest,
326    pub base_revision: u64,
327    pub plan: Plan,
328    /// Every entry prevents applying the plan.
329    #[serde(default, skip_serializing_if = "Vec::is_empty")]
330    pub refusals: Vec<ConfigPlanRefusal>,
331    /// Inputs skipped while reading layer files do not block the plan or enter its digest.
332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
333    pub skipped: Vec<ConfigPlanRefusal>,
334}
335
336impl ConfigPlanView {
337    pub fn new(plan: Plan) -> Result<Self, subc_config::CanonicalError> {
338        Ok(Self {
339            digest: plan.digest()?,
340            base_revision: plan.base_revision,
341            plan,
342            refusals: Vec::new(),
343            skipped: Vec::new(),
344        })
345    }
346}
347
348/// The durable review channel for a retained or pruned generation.
349#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
350#[non_exhaustive]
351pub struct ConfigApprovalRecord {
352    pub generation: u64,
353    pub channel: ApprovalChannel,
354}
355
356impl ConfigApprovalRecord {
357    pub fn new(generation: u64, channel: ApprovalChannel) -> Self {
358        Self {
359            generation,
360            channel,
361        }
362    }
363}
364
365/// Diagnostic strings are extensible; they never grant approval authority.
366#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
367#[non_exhaustive]
368pub struct ConfigStatus {
369    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
370    pub declaration_pending: BTreeMap<String, ConfigDeclarationPending>,
371    pub approval_channels: Vec<ConfigApprovalRecord>,
372    pub state: String,
373    pub integrity: String,
374    pub revision: u64,
375    pub base_revision: u64,
376    pub pending_proposals: u64,
377    pub anchor_pending: bool,
378    pub ungated_modules: Vec<String>,
379    pub ungated_inputs: Vec<String>,
380    pub gated_modules: Vec<String>,
381    pub interpreter_only_covered: Vec<String>,
382    pub approved_but_inactive: Vec<serde_json::Value>,
383    pub development_switches: Vec<String>,
384    pub missing_approval_surfaces: Vec<String>,
385    pub warnings: Vec<String>,
386    #[serde(default, skip_serializing_if = "Vec::is_empty")]
387    pub file_errors: Vec<ConfigStatusFileError>,
388    #[serde(default, skip_serializing_if = "Option::is_none")]
389    pub file_errors_incomplete: Option<ConfigFileErrorsIncomplete>,
390    #[serde(default, skip_serializing_if = "ConfigRootIo::absent_or_idle")]
391    pub root_io: Option<ConfigRootIo>,
392}
393
394/// The file error for one user or project settings row.
395#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
396#[non_exhaustive]
397pub struct ConfigStatusFileError {
398    pub module_id: String,
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub project_id: Option<String>,
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub workspace_id: Option<String>,
403    #[serde(flatten)]
404    pub error: ConfigFileError,
405}
406
407impl ConfigStatusFileError {
408    pub fn new(module_id: String, error: ConfigFileError) -> Self {
409        Self {
410            module_id,
411            project_id: None,
412            workspace_id: None,
413            error,
414        }
415    }
416}
417
418/// An open diagnostic reason for missing project file observations.
419#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
420#[non_exhaustive]
421pub struct ConfigFileErrorsIncomplete {
422    pub reason: String,
423}
424
425impl ConfigFileErrorsIncomplete {
426    pub fn new(reason: impl Into<String>) -> Self {
427        Self {
428            reason: reason.into(),
429        }
430    }
431}
432
433/// Root I/O still outstanding after its deadline.
434#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
435#[non_exhaustive]
436pub struct ConfigRootIo {
437    /// Canonical paths in sorted order.
438    pub stuck_roots: Vec<String>,
439    /// Workers still occupied by past-deadline jobs.
440    pub charged_workers: u64,
441}
442
443impl ConfigRootIo {
444    fn absent_or_idle(root_io: &Option<Self>) -> bool {
445        root_io
446            .as_ref()
447            .is_none_or(|io| io.stuck_roots.is_empty() && io.charged_workers == 0)
448    }
449}
450
451#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
452#[serde(tag = "op")]
453#[non_exhaustive]
454pub enum ConfigControlResponse {
455    #[serde(rename = "config.status")]
456    Status { status: ConfigStatus },
457    #[serde(rename = "config.modules")]
458    Modules {
459        modules: Vec<ConfigModule>,
460        stamped: bool,
461    },
462    #[serde(rename = "config.schema")]
463    Schema {
464        module_id: String,
465        schema_digest: Digest,
466        schema: serde_json::Value,
467    },
468    #[serde(rename = "config.show")]
469    Show {
470        module_id: String,
471        #[serde(default, skip_serializing_if = "Option::is_none")]
472        project_id: Option<String>,
473        #[serde(default, skip_serializing_if = "Option::is_none")]
474        through: Option<ConfigThrough>,
475        stamped: bool,
476        base_generation: u64,
477        effective: serde_json::Value,
478        sources: std::collections::BTreeMap<String, subc_config::Layer>,
479        layers: Vec<ConfigSettingsLayer>,
480        #[serde(default, skip_serializing_if = "Option::is_none")]
481        file_error: Option<ConfigFileError>,
482        #[serde(default, skip_serializing_if = "Option::is_none")]
483        pending_plan: Option<Digest>,
484        #[serde(default, skip_serializing_if = "Option::is_none")]
485        declaration_pending: Option<ConfigDeclarationPending>,
486    },
487    #[serde(rename = "config.plan")]
488    Plan { view: ConfigPlanView },
489    #[serde(rename = "config.plan_get")]
490    PlanGet { view: ConfigPlanView },
491    #[serde(rename = "config.plan_discard")]
492    PlanDiscard {},
493    #[serde(rename = "config.stamp")]
494    Stamp { view: ConfigPlanView },
495    #[serde(rename = "config.unstamp")]
496    Unstamp { view: ConfigPlanView },
497    #[serde(rename = "config.rollback")]
498    Rollback { view: ConfigPlanView },
499    #[serde(rename = "config.apply")]
500    Applied {
501        generation: u64,
502        #[serde(default)]
503        restart_required: bool,
504    },
505    #[serde(rename = "config.history")]
506    History {
507        generations: Vec<Generation>,
508        pruned: Vec<serde_json::Value>,
509    },
510    #[serde(rename = "config.place_program")]
511    ProgramPlaced {
512        #[serde(default, skip_serializing_if = "Option::is_none")]
513        generation: Option<u64>,
514    },
515}
516
517#[cfg(test)]
518mod tests {
519    #[test]
520    fn config_wire_declaration_pending_reaches_settings_watch() {
521        use super::*;
522        let row = ConfigModule {
523            module_id: "sample".into(),
524            declaration_pending: Some(ConfigDeclarationPending::default()),
525            ..ConfigModule::default()
526        };
527        let event = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
528        let mut wire = serde_json::to_value(&event).unwrap();
529        assert_eq!(wire["declaration_pending"], serde_json::json!({}));
530        wire["declaration_pending"]["future_member"] = serde_json::json!(true);
531        assert_eq!(
532            serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
533            event
534        );
535    }
536    #[test]
537    fn config_wire_existing_bodies_remain_byte_identical() {
538        const DIGEST: &str =
539            "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
540        for wire in [
541            r#"{"op":"config.status"}"#,
542            r#"{"op":"config.modules"}"#,
543            r#"{"op":"config.schema","module_id":"demo"}"#,
544            r#"{"op":"config.show","module_id":"demo"}"#,
545            r#"{"op":"config.show","module_id":"demo","through":"workspace"}"#,
546            r#"{"op":"config.watch"}"#,
547            r#"{"op":"config.watch","modules":["demo"]}"#,
548            r#"{"op":"config.plan"}"#,
549            r#"{"op":"config.plan","base_generations":{"demo":3},"edits":[{"module_id":"demo","layer":"user","path":"/limit","set":3}]}"#,
550            r#"{"op":"config.stamp"}"#,
551            r#"{"op":"config.unstamp"}"#,
552            r#"{"op":"config.history"}"#,
553            r#"{"op":"config.rollback","generation":3}"#,
554        ] {
555            assert_wire_bytes::<ConfigControlRequest>(wire);
556        }
557        for op in ["config.plan_get", "config.plan_discard", "config.apply"] {
558            assert_wire_bytes::<ConfigControlRequest>(&format!(
559                r#"{{"op":"{op}","digest":"{DIGEST}"}}"#
560            ));
561        }
562        assert_wire_bytes::<ConfigControlRequest>(&format!(
563            r#"{{"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":"{DIGEST}"}}"#
564        ));
565
566        let row = r#"{"module_id":"demo","gated":true,"status":"adopted"}"#;
567        for wire in [
568            r#"{"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":[]}}"#.to_owned(),
569            format!(r#"{{"op":"config.modules","modules":[{row}],"stamped":true}}"#),
570            format!(r#"{{"op":"config.schema","module_id":"demo","schema_digest":"{DIGEST}","schema":{{"type":"object"}}}}"#),
571            r#"{"op":"config.show","module_id":"demo","through":"workspace","stamped":true,"base_generation":3,"effective":{"limit":3},"sources":{"/limit":"user"},"layers":[{"layer":"user","document":{"limit":3}}]}"#.to_owned(),
572            r#"{"op":"config.plan_discard"}"#.to_owned(),
573            r#"{"op":"config.apply","generation":3,"restart_required":false}"#.to_owned(),
574            r#"{"op":"config.history","generations":[],"pruned":[]}"#.to_owned(),
575            r#"{"op":"config.place_program","generation":3}"#.to_owned(),
576        ] {
577            assert_wire_bytes::<ConfigControlResponse>(&wire);
578        }
579        let plan = r#"{"base_revision":7,"base_generation":3,"active_generations":{},"daemon_incarnation":"daemon","input_vector":{"inputs":{}},"changeset":{"fields":[],"affected_projects":[],"policy_changes":[],"launch_manifests":{},"apply_plan":null}}"#;
580        for op in [
581            "config.plan",
582            "config.plan_get",
583            "config.stamp",
584            "config.unstamp",
585            "config.rollback",
586        ] {
587            assert_wire_bytes::<ConfigControlResponse>(&format!(
588                r#"{{"op":"{op}","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan}}}}}"#
589            ));
590        }
591        let refusal = r#"{"module_id":"demo","path":"/limit","code":"value_invalid","message":"invalid limit"}"#;
592        assert_wire_bytes::<ConfigControlResponse>(&format!(
593            r#"{{"op":"config.plan","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan},"refusals":[{refusal}]}}}}"#
594        ));
595        assert_wire_bytes::<ConfigWatchResponse>(&format!(
596            r#"{{"op":"config.watch","event":"resync","modules":[{row}],"stamped":true}}"#
597        ));
598        assert_wire_bytes::<ConfigWatchResponse>(
599            r#"{"op":"config.watch","event":"change","module_id":"demo","status":"adopted"}"#,
600        );
601    }
602
603    fn assert_wire_bytes<T: serde::de::DeserializeOwned + Serialize>(wire: &str) {
604        let decoded: T =
605            serde_json::from_str(wire).unwrap_or_else(|error| panic!("{wire}: {error}"));
606        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
607    }
608
609    #[test]
610    fn config_wire_project_watch_round_trips_ids_and_opt_in() {
611        assert_eq!(
612            CONFIG_SETTINGS_PROJECTS_CAPABILITY,
613            "config.settings.projects/v1"
614        );
615        assert_wire_bytes::<ConfigControlRequest>(
616            r#"{"op":"config.watch","modules":["demo"],"projects":true}"#,
617        );
618        assert_wire_bytes::<ConfigControlRequest>(r#"{"op":"config.watch","projects":false}"#);
619        assert!(serde_json::from_str::<ConfigControlRequest>(
620            r#"{"op":"config.watch","projects":"true"}"#
621        )
622        .is_err());
623
624        let row = ConfigModule {
625            module_id: "demo".into(),
626            project_id: Some("p".into()),
627            workspace_id: Some("w".into()),
628            gated: true,
629            status: "adopted".into(),
630            ..ConfigModule::default()
631        };
632        let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
633        let wire = r#"{"op":"config.watch","event":"change","module_id":"demo","project_id":"p","workspace_id":"w","status":"adopted"}"#;
634        assert_eq!(serde_json::to_string(&change).unwrap(), wire);
635        assert_eq!(
636            serde_json::from_str::<ConfigWatchResponse>(wire).unwrap(),
637            change
638        );
639        assert_wire_bytes::<ConfigWatchResponse>(
640            r#"{"op":"config.watch","event":"resync","modules":[{"module_id":"demo","project_id":"p","workspace_id":"w","gated":true,"status":"adopted"}],"stamped":true}"#,
641        );
642    }
643
644    #[test]
645    fn config_wire_project_plan_keeps_skips_separate_from_refusals() {
646        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
647        let mut view = ConfigPlanView::new(plan).unwrap();
648        view.refusals.push(ConfigPlanRefusal {
649            module_id: "demo".into(),
650            path: "/limit".into(),
651            code: "credential_layer_unsupported".into(),
652            message: "section is user-only".into(),
653            project_id: Some("p".into()),
654            workspace_id: None,
655        });
656        view.skipped.push(ConfigPlanRefusal {
657            module_id: "demo".into(),
658            path: ".cortexkit/demo.jsonc".into(),
659            code: "layer_symlink".into(),
660            message: "layer is a symlink".into(),
661            project_id: Some("q".into()),
662            workspace_id: Some("w".into()),
663        });
664        let response = ConfigControlResponse::Plan { view };
665        let wire = serde_json::to_value(&response).unwrap();
666        assert_eq!(
667            wire["view"]["refusals"],
668            json!([{
669                "module_id":"demo","path":"/limit","code":"credential_layer_unsupported",
670                "message":"section is user-only","project_id":"p"
671            }])
672        );
673        assert_eq!(
674            wire["view"]["skipped"],
675            json!([{
676                "module_id":"demo","path":".cortexkit/demo.jsonc","code":"layer_symlink",
677                "message":"layer is a symlink","project_id":"q","workspace_id":"w"
678            }])
679        );
680        assert_eq!(
681            serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
682            response
683        );
684    }
685
686    #[test]
687    fn config_wire_status_emits_only_non_idle_root_io_health() {
688        let mut status = ConfigStatus::default();
689        let legacy = serde_json::to_vec(&status).unwrap();
690        status.root_io = Some(ConfigRootIo::default());
691        assert_eq!(serde_json::to_vec(&status).unwrap(), legacy);
692
693        status.root_io = Some(ConfigRootIo {
694            stuck_roots: vec!["/roots/a".into(), "/roots/b".into()],
695            charged_workers: 2,
696        });
697        let response = ConfigControlResponse::Status { status };
698        let wire = serde_json::to_value(&response).unwrap();
699        assert_eq!(
700            wire["status"]["root_io"],
701            json!({
702                "stuck_roots":["/roots/a","/roots/b"],"charged_workers":2
703            })
704        );
705        assert_eq!(
706            serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
707            response
708        );
709    }
710
711    #[test]
712    fn config_wire_settings_status_is_open_and_selectors_are_strict() {
713        use super::*;
714        let module: ConfigModule = serde_json::from_value(
715            serde_json::json!({"module_id":"sample","gated":true,"status":"future_status"}),
716        )
717        .unwrap();
718        assert_eq!(module.status, "future_status");
719        assert!(serde_json::from_value::<ConfigControlRequest>(
720            serde_json::json!({"op":"config.show","module_id":"sample","through":"project"})
721        )
722        .is_err());
723        let event = ConfigWatchResponse::new(ConfigWatchEvent::Resync {
724            modules: vec![module],
725            stamped: false,
726        });
727        assert_eq!(
728            serde_json::from_slice::<ConfigWatchResponse>(&serde_json::to_vec(&event).unwrap())
729                .unwrap(),
730            event
731        );
732    }
733
734    #[test]
735    fn config_wire_file_errors_are_optional_and_tolerate_extensions() {
736        let legacy = json!({"module_id":"sample","gated":true,"status":"adopted"});
737        let mut row: ConfigModule = serde_json::from_value(legacy).unwrap();
738        assert!(row.file_error.is_none());
739        let error = ConfigFileError::new("value_invalid", "invalid settings");
740        row.file_error = Some(error.clone());
741        let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
742        let mut wire = serde_json::to_value(&change).unwrap();
743        assert_eq!(
744            wire["file_error"],
745            json!({"code":"value_invalid","message":"invalid settings"})
746        );
747        wire["file_error"]["future"] = json!(true);
748        assert_eq!(
749            serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
750            change
751        );
752        let mut shown = json!({"op":"config.show","module_id":"sample","stamped":true,"base_generation":1,"effective":{},"sources":{},"layers":[]});
753        assert!(matches!(
754            serde_json::from_value::<ConfigControlResponse>(shown.clone()).unwrap(),
755            ConfigControlResponse::Show {
756                file_error: None,
757                ..
758            }
759        ));
760        shown["file_error"] = serde_json::to_value(&error).unwrap();
761        assert!(
762            matches!(serde_json::from_value::<ConfigControlResponse>(shown).unwrap(), ConfigControlResponse::Show {file_error:Some(found), ..} if found == error)
763        );
764    }
765
766    #[test]
767    fn config_wire_program_placement_names_and_optional_generation() {
768        use super::*;
769        let body = serde_json::json!({"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":format!("sha256:{}", "a".repeat(64))});
770        let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
771        assert_eq!(request.op(), "config.place_program");
772        assert_eq!(serde_json::to_value(request).unwrap(), body);
773        assert!(matches!(
774            serde_json::from_value::<ConfigControlResponse>(
775                serde_json::json!({"op":"config.place_program"})
776            )
777            .unwrap(),
778            ConfigControlResponse::ProgramPlaced { generation: None }
779        ));
780        let response = ConfigControlResponse::ProgramPlaced {
781            generation: Some(3),
782        };
783        assert_eq!(
784            serde_json::to_value(response).unwrap(),
785            serde_json::json!({"op":"config.place_program","generation":3})
786        );
787    }
788    #[test]
789    fn config_wire_applied_reports_restart_required_and_defaults_absent_to_false() {
790        use super::*;
791        let response = ConfigControlResponse::Applied {
792            generation: 7,
793            restart_required: true,
794        };
795        assert_eq!(
796            serde_json::to_value(response).unwrap(),
797            serde_json::json!({"op":"config.apply", "generation":7, "restart_required":true})
798        );
799        assert_eq!(
800            serde_json::from_value::<ConfigControlResponse>(
801                serde_json::json!({"op":"config.apply", "generation":7})
802            )
803            .unwrap(),
804            ConfigControlResponse::Applied {
805                generation: 7,
806                restart_required: false,
807            }
808        );
809        assert_eq!(
810            serde_json::to_value(ConfigControlResponse::Applied {
811                generation: 7,
812                restart_required: false,
813            })
814            .unwrap()["restart_required"],
815            false
816        );
817    }
818
819    #[test]
820    fn config_wire_status_and_history_preserve_unverified_approval_channel() {
821        use super::*;
822        let channel = ApprovalChannel::UnverifiedDevelopmentDesktop;
823        let mut status = ConfigStatus::default();
824        status
825            .approval_channels
826            .push(ConfigApprovalRecord::new(1, channel));
827        let generation = Generation::new(
828            1,
829            channel,
830            subc_config::raw_digest(b"plan"),
831            subc_config::InputVector::default(),
832            subc_config::Changeset::new(),
833        );
834        for response in [
835            ConfigControlResponse::Status { status },
836            ConfigControlResponse::History {
837                generations: vec![generation],
838                pruned: vec![],
839            },
840        ] {
841            let encoded = serde_json::to_string(&response).unwrap();
842            assert!(encoded.contains("unverified_development_desktop"));
843            assert_eq!(
844                serde_json::from_str::<ConfigControlResponse>(&encoded).unwrap(),
845                response
846            );
847        }
848    }
849    use super::*;
850    use serde_json::json;
851
852    #[test]
853    fn config_wire_requests_are_strict_and_round_trip() {
854        for body in [
855            json!({"op":"config.status"}),
856            json!({"op":"config.modules"}),
857            json!({"op":"config.schema","module_id":"sample-reader"}),
858            json!({"op":"config.show","module_id":"sample-reader"}),
859            json!({"op":"config.show","module_id":"sample-reader","project_id":"sample-project","through":"workspace"}),
860            json!({"op":"config.watch"}),
861            json!({"op":"config.watch","modules":["sample-reader"]}),
862            json!({"op":"config.plan"}),
863            json!({"op":"config.plan_get", "digest":subc_config::raw_digest(b"plan")}),
864            json!({"op":"config.plan_discard", "digest":subc_config::raw_digest(b"plan")}),
865            json!({"op":"config.apply", "digest":subc_config::raw_digest(b"plan")}),
866            json!({"op":"config.stamp"}),
867            json!({"op":"config.unstamp"}),
868            json!({"op":"config.history"}),
869            json!({"op":"config.rollback", "generation":4}),
870        ] {
871            let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
872            assert_eq!(body["op"], request.op());
873            assert_eq!(serde_json::to_value(&request).unwrap(), body);
874            let mut claimed = body;
875            claimed["reviewed"] = json!(true);
876            assert!(serde_json::from_value::<ConfigControlRequest>(claimed).is_err());
877        }
878        assert!(
879            serde_json::from_value::<ConfigControlRequest>(json!({"op":"config.apply"})).is_err()
880        );
881    }
882
883    #[test]
884    fn config_wire_plan_view_and_status_tolerate_reply_extensions() {
885        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
886        let view = ConfigPlanView::new(plan.clone()).unwrap();
887        assert_eq!(view.digest, plan.digest().unwrap());
888        let response = ConfigControlResponse::Stamp { view };
889        let mut body = serde_json::to_value(&response).unwrap();
890        body["future"] = json!(true);
891        assert_eq!(
892            serde_json::from_value::<ConfigControlResponse>(body).unwrap(),
893            response
894        );
895        let status = ConfigControlResponse::Status {
896            status: ConfigStatus::default(),
897        };
898        assert_eq!(
899            serde_json::from_value::<ConfigControlResponse>(serde_json::to_value(&status).unwrap())
900                .unwrap(),
901            status
902        );
903    }
904
905    #[test]
906    fn config_wire_edit_actions_are_exclusive_and_null_is_not_absence() {
907        let base = json!({"module_id":"demo","layer":"user","path":"/limit"});
908        for action in [
909            json!({"set":0}),
910            json!({"set":false}),
911            json!({"set":null}),
912            json!({"remove":true}),
913        ] {
914            let mut value = base.clone();
915            value
916                .as_object_mut()
917                .unwrap()
918                .extend(action.as_object().unwrap().clone());
919            let edit: ConfigEdit = serde_json::from_value(value.clone()).unwrap();
920            assert_eq!(serde_json::to_value(edit).unwrap(), value);
921        }
922        for action in [
923            json!({}),
924            json!({"set":1,"remove":true}),
925            json!({"remove":false}),
926            json!({"remove":true,"extra":1}),
927        ] {
928            let mut value = base.clone();
929            value
930                .as_object_mut()
931                .unwrap()
932                .extend(action.as_object().unwrap().clone());
933            assert!(serde_json::from_value::<ConfigEdit>(value).is_err());
934        }
935        let request: ConfigControlRequest =
936            serde_json::from_value(json!({"op":"config.plan"})).unwrap();
937        assert_eq!(
938            serde_json::to_vec(&request).unwrap(),
939            br#"{"op":"config.plan"}"#
940        );
941    }
942
943    #[test]
944    fn config_wire_empty_refusals_preserve_legacy_view_bytes() {
945        let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
946        let view = ConfigPlanView::new(plan.clone()).unwrap();
947        let legacy = json!({"digest":plan.digest().unwrap(),"base_revision":7,"plan":plan});
948        assert_eq!(serde_json::to_value(&view).unwrap(), legacy);
949        assert_eq!(
950            serde_json::from_value::<ConfigPlanView>(legacy).unwrap(),
951            view
952        );
953        assert_eq!(
954            serde_json::to_string(&ConfigControlResponse::PlanDiscard {}).unwrap(),
955            r#"{"op":"config.plan_discard"}"#
956        );
957    }
958}