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