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