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