1use 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#[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#[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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
110 projects: Option<bool>,
111 },
112 #[serde(rename = "config.plan")]
113 Plan {
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 base_generations: Option<BTreeMap<String, u64>>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 edits: Option<Vec<ConfigEdit>>,
118 },
119 #[serde(rename = "config.plan_get")]
120 PlanGet { digest: Digest },
121 #[serde(rename = "config.plan_discard")]
122 PlanDiscard { digest: Digest },
123 #[serde(rename = "config.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 #[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#[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#[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#[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 #[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#[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#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
266#[serde(tag = "event", rename_all = "snake_case")]
267#[non_exhaustive]
268#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub struct ConfigPlanView {
345 pub digest: Digest,
346 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub settings_file_change: Option<ConfigSettingsFileChange>,
350 pub base_revision: u64,
351 pub plan: Plan,
352 #[serde(default, skip_serializing_if = "Vec::is_empty")]
354 pub refusals: Vec<ConfigPlanRefusal>,
355 #[serde(default, skip_serializing_if = "Vec::is_empty")]
357 pub skipped: Vec<ConfigPlanRefusal>,
358}
359
360#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
361pub struct ConfigSettingsFileChange {
362 pub label: String,
363 pub files: Vec<ConfigSettingsFile>,
364}
365
366#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
367pub struct ConfigSettingsFile {
368 pub module_id: String,
369 pub layer: subc_config::Layer,
370 pub path: std::path::PathBuf,
371 pub workspace_id: Option<String>,
372 pub affected_projects: Vec<String>,
373}
374
375impl ConfigPlanView {
376 pub fn new(plan: Plan) -> Result<Self, subc_config::CanonicalError> {
377 Ok(Self {
378 digest: plan.digest()?,
379 base_revision: plan.base_revision,
380 plan,
381 refusals: Vec::new(),
382 skipped: Vec::new(),
383 settings_file_change: None,
384 })
385 }
386}
387
388#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
390#[non_exhaustive]
391pub struct ConfigApprovalRecord {
392 pub generation: u64,
393 pub channel: ApprovalChannel,
394}
395
396impl ConfigApprovalRecord {
397 pub fn new(generation: u64, channel: ApprovalChannel) -> Self {
398 Self {
399 generation,
400 channel,
401 }
402 }
403}
404
405#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
407#[non_exhaustive]
408pub struct ConfigStatus {
409 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
410 pub declaration_pending: BTreeMap<String, ConfigDeclarationPending>,
411 pub approval_channels: Vec<ConfigApprovalRecord>,
412 pub state: String,
413 pub integrity: String,
414 pub revision: u64,
415 pub base_revision: u64,
416 pub pending_proposals: u64,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub pending_settings_card: Option<Digest>,
420 #[serde(default, skip_serializing_if = "Option::is_none")]
422 pub pending_settings_card_reason: Option<String>,
423 #[serde(default, skip_serializing_if = "Vec::is_empty")]
425 pub settings_recovery_copies: Vec<ConfigSettingsRecoveryCopy>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
428 pub settings_recovery_copy_count: Option<u64>,
429 pub anchor_pending: bool,
430 pub ungated_modules: Vec<String>,
431 pub ungated_inputs: Vec<String>,
432 pub gated_modules: Vec<String>,
433 pub interpreter_only_covered: Vec<String>,
434 pub approved_but_inactive: Vec<serde_json::Value>,
435 pub development_switches: Vec<String>,
436 pub missing_approval_surfaces: Vec<String>,
437 pub warnings: Vec<String>,
438 #[serde(default, skip_serializing_if = "Vec::is_empty")]
439 pub file_errors: Vec<ConfigStatusFileError>,
440 #[serde(default, skip_serializing_if = "Option::is_none")]
441 pub file_errors_incomplete: Option<ConfigFileErrorsIncomplete>,
442 #[serde(default, skip_serializing_if = "ConfigRootIo::absent_or_idle")]
443 pub root_io: Option<ConfigRootIo>,
444}
445
446#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
447pub struct ConfigSettingsRecoveryCopy {
448 pub path: String,
449 pub recovery_path: String,
450}
451
452#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
454#[non_exhaustive]
455pub struct ConfigStatusFileError {
456 pub module_id: String,
457 #[serde(default, skip_serializing_if = "Option::is_none")]
458 pub project_id: Option<String>,
459 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub workspace_id: Option<String>,
461 #[serde(flatten)]
462 pub error: ConfigFileError,
463}
464
465impl ConfigStatusFileError {
466 pub fn new(module_id: String, error: ConfigFileError) -> Self {
467 Self {
468 module_id,
469 project_id: None,
470 workspace_id: None,
471 error,
472 }
473 }
474}
475
476#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
478#[non_exhaustive]
479pub struct ConfigFileErrorsIncomplete {
480 pub reason: String,
481}
482
483impl ConfigFileErrorsIncomplete {
484 pub fn new(reason: impl Into<String>) -> Self {
485 Self {
486 reason: reason.into(),
487 }
488 }
489}
490
491#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
493#[non_exhaustive]
494pub struct ConfigRootIo {
495 pub stuck_roots: Vec<String>,
497 pub charged_workers: u64,
499}
500
501impl ConfigRootIo {
502 fn absent_or_idle(root_io: &Option<Self>) -> bool {
503 root_io
504 .as_ref()
505 .is_none_or(|io| io.stuck_roots.is_empty() && io.charged_workers == 0)
506 }
507}
508
509#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
510#[non_exhaustive]
511pub struct ConfigRevertFile {
512 pub path: String,
513 pub status: ConfigRevertFileStatus,
514 #[serde(default, skip_serializing_if = "Option::is_none")]
515 pub code: Option<String>,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub message: Option<String>,
518 #[serde(default, skip_serializing_if = "Option::is_none")]
519 pub detail: Option<serde_json::Value>,
520}
521
522#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
523#[serde(rename_all = "snake_case")]
524pub enum ConfigRevertFileStatus {
525 Restored,
526 Refused,
527}
528
529impl ConfigRevertFile {
530 pub fn restored(path: String) -> Self {
531 Self {
532 path,
533 status: ConfigRevertFileStatus::Restored,
534 code: None,
535 message: None,
536 detail: None,
537 }
538 }
539
540 pub fn refused(
541 path: String,
542 code: String,
543 message: String,
544 detail: Option<serde_json::Value>,
545 ) -> Self {
546 Self {
547 path,
548 status: ConfigRevertFileStatus::Refused,
549 code: Some(code),
550 message: Some(message),
551 detail,
552 }
553 }
554}
555
556#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
557#[serde(tag = "op")]
558#[non_exhaustive]
559pub enum ConfigControlResponse {
560 #[serde(rename = "config.status")]
561 Status { status: ConfigStatus },
562 #[serde(rename = "config.modules")]
563 Modules {
564 modules: Vec<ConfigModule>,
565 stamped: bool,
566 },
567 #[serde(rename = "config.schema")]
568 Schema {
569 module_id: String,
570 schema_digest: Digest,
571 schema: serde_json::Value,
572 },
573 #[serde(rename = "config.show")]
574 Show {
575 module_id: String,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
577 project_id: Option<String>,
578 #[serde(default, skip_serializing_if = "Option::is_none")]
579 through: Option<ConfigThrough>,
580 stamped: bool,
581 base_generation: u64,
582 effective: serde_json::Value,
583 sources: std::collections::BTreeMap<String, subc_config::Layer>,
584 layers: Vec<ConfigSettingsLayer>,
585 #[serde(default, skip_serializing_if = "Option::is_none")]
586 file_error: Option<ConfigFileError>,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pending_plan: Option<Digest>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
590 declaration_pending: Option<ConfigDeclarationPending>,
591 },
592 #[serde(rename = "config.plan")]
593 Plan { view: ConfigPlanView },
594 #[serde(rename = "config.plan_get")]
595 PlanGet { view: ConfigPlanView },
596 #[serde(rename = "config.plan_discard")]
597 PlanDiscard {},
598 #[serde(rename = "config.revert")]
599 Revert {
600 #[serde(default)]
601 files: Vec<ConfigRevertFile>,
602 },
603 #[serde(rename = "config.stamp")]
604 Stamp { view: ConfigPlanView },
605 #[serde(rename = "config.unstamp")]
606 Unstamp { view: ConfigPlanView },
607 #[serde(rename = "config.rollback")]
608 Rollback { view: ConfigPlanView },
609 #[serde(rename = "config.apply")]
610 Applied {
611 generation: u64,
612 #[serde(default)]
613 restart_required: bool,
614 },
615 #[serde(rename = "config.history")]
616 History {
617 generations: Vec<Generation>,
618 pruned: Vec<serde_json::Value>,
619 },
620 #[serde(rename = "config.place_program")]
621 ProgramPlaced {
622 #[serde(default, skip_serializing_if = "Option::is_none")]
623 generation: Option<u64>,
624 },
625}
626
627#[cfg(test)]
628mod tests {
629 #[test]
630 fn config_wire_declaration_pending_reaches_settings_watch() {
631 use super::*;
632 let row = ConfigModule {
633 module_id: "sample".into(),
634 declaration_pending: Some(ConfigDeclarationPending::default()),
635 ..ConfigModule::default()
636 };
637 let event = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
638 let mut wire = serde_json::to_value(&event).unwrap();
639 assert_eq!(wire["declaration_pending"], serde_json::json!({}));
640 wire["declaration_pending"]["future_member"] = serde_json::json!(true);
641 assert_eq!(
642 serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
643 event
644 );
645 }
646 #[test]
647 fn config_wire_existing_bodies_remain_byte_identical() {
648 const DIGEST: &str =
649 "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
650 for wire in [
651 r#"{"op":"config.status"}"#,
652 r#"{"op":"config.modules"}"#,
653 r#"{"op":"config.schema","module_id":"demo"}"#,
654 r#"{"op":"config.show","module_id":"demo"}"#,
655 r#"{"op":"config.show","module_id":"demo","through":"workspace"}"#,
656 r#"{"op":"config.watch"}"#,
657 r#"{"op":"config.watch","modules":["demo"]}"#,
658 r#"{"op":"config.plan"}"#,
659 r#"{"op":"config.plan","base_generations":{"demo":3},"edits":[{"module_id":"demo","layer":"user","path":"/limit","set":3}]}"#,
660 r#"{"op":"config.stamp"}"#,
661 r#"{"op":"config.unstamp"}"#,
662 r#"{"op":"config.history"}"#,
663 r#"{"op":"config.rollback","generation":3}"#,
664 ] {
665 assert_wire_bytes::<ConfigControlRequest>(wire);
666 }
667 for op in [
668 "config.plan_get",
669 "config.plan_discard",
670 "config.apply",
671 "config.revert",
672 ] {
673 assert_wire_bytes::<ConfigControlRequest>(&format!(
674 r#"{{"op":"{op}","digest":"{DIGEST}"}}"#
675 ));
676 }
677 assert_wire_bytes::<ConfigControlRequest>(&format!(
678 r#"{{"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":"{DIGEST}"}}"#
679 ));
680
681 let row = r#"{"module_id":"demo","gated":true,"status":"adopted"}"#;
682 for wire in [
683 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(),
684 format!(r#"{{"op":"config.modules","modules":[{row}],"stamped":true}}"#),
685 format!(r#"{{"op":"config.schema","module_id":"demo","schema_digest":"{DIGEST}","schema":{{"type":"object"}}}}"#),
686 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(),
687 r#"{"op":"config.plan_discard"}"#.to_owned(),
688 r#"{"op":"config.apply","generation":3,"restart_required":false}"#.to_owned(),
689 r#"{"op":"config.history","generations":[],"pruned":[]}"#.to_owned(),
690 r#"{"op":"config.place_program","generation":3}"#.to_owned(),
691 ] {
692 assert_wire_bytes::<ConfigControlResponse>(&wire);
693 }
694 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}}"#;
695 for op in [
696 "config.plan",
697 "config.plan_get",
698 "config.stamp",
699 "config.unstamp",
700 "config.rollback",
701 ] {
702 assert_wire_bytes::<ConfigControlResponse>(&format!(
703 r#"{{"op":"{op}","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan}}}}}"#
704 ));
705 }
706 let refusal = r#"{"module_id":"demo","path":"/limit","code":"value_invalid","message":"invalid limit"}"#;
707 assert_wire_bytes::<ConfigControlResponse>(&format!(
708 r#"{{"op":"config.plan","view":{{"digest":"{DIGEST}","base_revision":7,"plan":{plan},"refusals":[{refusal}]}}}}"#
709 ));
710 assert_wire_bytes::<ConfigWatchResponse>(&format!(
711 r#"{{"op":"config.watch","event":"resync","modules":[{row}],"stamped":true}}"#
712 ));
713 assert_wire_bytes::<ConfigWatchResponse>(
714 r#"{"op":"config.watch","event":"change","module_id":"demo","status":"adopted"}"#,
715 );
716 }
717
718 fn assert_wire_bytes<T: serde::de::DeserializeOwned + Serialize>(wire: &str) {
719 let decoded: T =
720 serde_json::from_str(wire).unwrap_or_else(|error| panic!("{wire}: {error}"));
721 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
722 }
723
724 #[test]
725 fn config_wire_revert_decodes_legacy_success_and_writes_a_file_list() {
726 let old: ConfigControlResponse = serde_json::from_str(r#"{"op":"config.revert"}"#).unwrap();
727 assert!(matches!(old, ConfigControlResponse::Revert { files } if files.is_empty()));
728 assert_wire_bytes::<ConfigControlResponse>(
729 r#"{"op":"config.revert","files":[{"path":"/settings/demo.jsonc","status":"restored"}]}"#,
730 );
731 assert_wire_bytes::<ConfigControlResponse>(r#"{"op":"config.revert","files":[]}"#);
732 }
733
734 #[test]
735 fn config_wire_project_watch_round_trips_ids_and_opt_in() {
736 assert_eq!(
737 CONFIG_SETTINGS_PROJECTS_CAPABILITY,
738 "config.settings.projects/v1"
739 );
740 assert_wire_bytes::<ConfigControlRequest>(
741 r#"{"op":"config.watch","modules":["demo"],"projects":true}"#,
742 );
743 assert_wire_bytes::<ConfigControlRequest>(r#"{"op":"config.watch","projects":false}"#);
744 assert!(serde_json::from_str::<ConfigControlRequest>(
745 r#"{"op":"config.watch","projects":"true"}"#
746 )
747 .is_err());
748
749 let row = ConfigModule {
750 module_id: "demo".into(),
751 project_id: Some("p".into()),
752 workspace_id: Some("w".into()),
753 gated: true,
754 status: "adopted".into(),
755 ..ConfigModule::default()
756 };
757 let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
758 let wire = r#"{"op":"config.watch","event":"change","module_id":"demo","project_id":"p","workspace_id":"w","status":"adopted"}"#;
759 assert_eq!(serde_json::to_string(&change).unwrap(), wire);
760 assert_eq!(
761 serde_json::from_str::<ConfigWatchResponse>(wire).unwrap(),
762 change
763 );
764 assert_wire_bytes::<ConfigWatchResponse>(
765 r#"{"op":"config.watch","event":"resync","modules":[{"module_id":"demo","project_id":"p","workspace_id":"w","gated":true,"status":"adopted"}],"stamped":true}"#,
766 );
767 }
768
769 #[test]
770 fn config_wire_project_plan_keeps_skips_separate_from_refusals() {
771 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
772 let mut view = ConfigPlanView::new(plan).unwrap();
773 view.refusals.push(ConfigPlanRefusal {
774 module_id: "demo".into(),
775 path: "/limit".into(),
776 code: "credential_layer_unsupported".into(),
777 message: "section is user-only".into(),
778 project_id: Some("p".into()),
779 workspace_id: None,
780 });
781 view.skipped.push(ConfigPlanRefusal {
782 module_id: "demo".into(),
783 path: ".cortexkit/demo.jsonc".into(),
784 code: "layer_symlink".into(),
785 message: "layer is a symlink".into(),
786 project_id: Some("q".into()),
787 workspace_id: Some("w".into()),
788 });
789 let response = ConfigControlResponse::Plan { view };
790 let wire = serde_json::to_value(&response).unwrap();
791 assert_eq!(
792 wire["view"]["refusals"],
793 json!([{
794 "module_id":"demo","path":"/limit","code":"credential_layer_unsupported",
795 "message":"section is user-only","project_id":"p"
796 }])
797 );
798 assert_eq!(
799 wire["view"]["skipped"],
800 json!([{
801 "module_id":"demo","path":".cortexkit/demo.jsonc","code":"layer_symlink",
802 "message":"layer is a symlink","project_id":"q","workspace_id":"w"
803 }])
804 );
805 assert_eq!(
806 serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
807 response
808 );
809 }
810
811 #[test]
812 fn config_wire_status_emits_only_non_idle_root_io_health() {
813 let mut status = ConfigStatus::default();
814 let legacy = serde_json::to_vec(&status).unwrap();
815 status.root_io = Some(ConfigRootIo::default());
816 assert_eq!(serde_json::to_vec(&status).unwrap(), legacy);
817
818 status.root_io = Some(ConfigRootIo {
819 stuck_roots: vec!["/roots/a".into(), "/roots/b".into()],
820 charged_workers: 2,
821 });
822 let response = ConfigControlResponse::Status { status };
823 let wire = serde_json::to_value(&response).unwrap();
824 assert_eq!(
825 wire["status"]["root_io"],
826 json!({
827 "stuck_roots":["/roots/a","/roots/b"],"charged_workers":2
828 })
829 );
830 assert_eq!(
831 serde_json::from_value::<ConfigControlResponse>(wire).unwrap(),
832 response
833 );
834 }
835
836 #[test]
837 fn config_wire_settings_status_is_open_and_selectors_are_strict() {
838 use super::*;
839 let module: ConfigModule = serde_json::from_value(
840 serde_json::json!({"module_id":"sample","gated":true,"status":"future_status"}),
841 )
842 .unwrap();
843 assert_eq!(module.status, "future_status");
844 assert!(serde_json::from_value::<ConfigControlRequest>(
845 serde_json::json!({"op":"config.show","module_id":"sample","through":"project"})
846 )
847 .is_err());
848 let event = ConfigWatchResponse::new(ConfigWatchEvent::Resync {
849 modules: vec![module],
850 stamped: false,
851 });
852 assert_eq!(
853 serde_json::from_slice::<ConfigWatchResponse>(&serde_json::to_vec(&event).unwrap())
854 .unwrap(),
855 event
856 );
857 }
858
859 #[test]
860 fn config_wire_file_errors_are_optional_and_tolerate_extensions() {
861 let legacy = json!({"module_id":"sample","gated":true,"status":"adopted"});
862 let mut row: ConfigModule = serde_json::from_value(legacy).unwrap();
863 assert!(row.file_error.is_none());
864 let error = ConfigFileError::new("value_invalid", "invalid settings");
865 row.file_error = Some(error.clone());
866 let change = ConfigWatchResponse::new(ConfigWatchEvent::change(&row));
867 let mut wire = serde_json::to_value(&change).unwrap();
868 assert_eq!(
869 wire["file_error"],
870 json!({"code":"value_invalid","message":"invalid settings"})
871 );
872 wire["file_error"]["future"] = json!(true);
873 assert_eq!(
874 serde_json::from_value::<ConfigWatchResponse>(wire).unwrap(),
875 change
876 );
877 let mut shown = json!({"op":"config.show","module_id":"sample","stamped":true,"base_generation":1,"effective":{},"sources":{},"layers":[]});
878 assert!(matches!(
879 serde_json::from_value::<ConfigControlResponse>(shown.clone()).unwrap(),
880 ConfigControlResponse::Show {
881 file_error: None,
882 ..
883 }
884 ));
885 shown["file_error"] = serde_json::to_value(&error).unwrap();
886 assert!(
887 matches!(serde_json::from_value::<ConfigControlResponse>(shown).unwrap(), ConfigControlResponse::Show {file_error:Some(found), ..} if found == error)
888 );
889 }
890
891 #[test]
892 fn config_wire_project_file_errors_keep_layer_and_path() {
893 let mut status = serde_json::to_value(ConfigStatus::default()).unwrap();
894 let path = "/home/example/workspace/.cortexkit/demo.jsonc";
895 status["file_errors"] = json!([
896 {"module_id":"demo","code":"value_invalid","message":"legacy"},
897 {"module_id":"demo","project_id":"p","workspace_id":"w","code":"value_invalid",
898 "message":"new","layer":"workspace","path":path,"future":true}
899 ]);
900 let response: ConfigControlResponse =
901 serde_json::from_value(json!({"op":"config.status","status":status})).unwrap();
902 let ConfigControlResponse::Status { status } = &response else {
903 panic!("expected config.status");
904 };
905 assert_eq!(status.file_errors[0].error.layer, None);
906 assert_eq!(status.file_errors[0].error.path, None);
907 assert_eq!(
908 status.file_errors[1].error.layer,
909 Some(ConfigFileErrorLayer::Workspace)
910 );
911 assert_eq!(status.file_errors[1].error.path.as_deref(), Some(path));
912 let wire = serde_json::to_value(response).unwrap();
913 assert!(wire["status"]["file_errors"][0].get("layer").is_none());
914 assert!(wire["status"]["file_errors"][0].get("path").is_none());
915 assert_eq!(wire["status"]["file_errors"][1]["layer"], "workspace");
916 assert_eq!(wire["status"]["file_errors"][1]["path"], path);
917 }
918
919 #[test]
920 fn config_wire_program_placement_names_and_optional_generation() {
921 use super::*;
922 let body = serde_json::json!({"op":"config.place_program","module_id":"demo","path":"/bin/demo","sha256":format!("sha256:{}", "a".repeat(64))});
923 let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
924 assert_eq!(request.op(), "config.place_program");
925 assert_eq!(serde_json::to_value(request).unwrap(), body);
926 assert!(matches!(
927 serde_json::from_value::<ConfigControlResponse>(
928 serde_json::json!({"op":"config.place_program"})
929 )
930 .unwrap(),
931 ConfigControlResponse::ProgramPlaced { generation: None }
932 ));
933 let response = ConfigControlResponse::ProgramPlaced {
934 generation: Some(3),
935 };
936 assert_eq!(
937 serde_json::to_value(response).unwrap(),
938 serde_json::json!({"op":"config.place_program","generation":3})
939 );
940 }
941 #[test]
942 fn config_wire_applied_reports_restart_required_and_defaults_absent_to_false() {
943 use super::*;
944 let response = ConfigControlResponse::Applied {
945 generation: 7,
946 restart_required: true,
947 };
948 assert_eq!(
949 serde_json::to_value(response).unwrap(),
950 serde_json::json!({"op":"config.apply", "generation":7, "restart_required":true})
951 );
952 assert_eq!(
953 serde_json::from_value::<ConfigControlResponse>(
954 serde_json::json!({"op":"config.apply", "generation":7})
955 )
956 .unwrap(),
957 ConfigControlResponse::Applied {
958 generation: 7,
959 restart_required: false,
960 }
961 );
962 assert_eq!(
963 serde_json::to_value(ConfigControlResponse::Applied {
964 generation: 7,
965 restart_required: false,
966 })
967 .unwrap()["restart_required"],
968 false
969 );
970 }
971
972 #[test]
973 fn config_wire_status_and_history_preserve_unverified_approval_channel() {
974 use super::*;
975 let channel = ApprovalChannel::UnverifiedDevelopmentDesktop;
976 let mut status = ConfigStatus::default();
977 status
978 .approval_channels
979 .push(ConfigApprovalRecord::new(1, channel));
980 let generation = Generation::new(
981 1,
982 channel,
983 subc_config::raw_digest(b"plan"),
984 subc_config::InputVector::default(),
985 subc_config::Changeset::new(),
986 );
987 for response in [
988 ConfigControlResponse::Status { status },
989 ConfigControlResponse::History {
990 generations: vec![generation],
991 pruned: vec![],
992 },
993 ] {
994 let encoded = serde_json::to_string(&response).unwrap();
995 assert!(encoded.contains("unverified_development_desktop"));
996 assert_eq!(
997 serde_json::from_str::<ConfigControlResponse>(&encoded).unwrap(),
998 response
999 );
1000 }
1001 }
1002 use super::*;
1003 use serde_json::json;
1004
1005 #[test]
1006 fn config_wire_requests_are_strict_and_round_trip() {
1007 for body in [
1008 json!({"op":"config.status"}),
1009 json!({"op":"config.modules"}),
1010 json!({"op":"config.schema","module_id":"sample-reader"}),
1011 json!({"op":"config.show","module_id":"sample-reader"}),
1012 json!({"op":"config.show","module_id":"sample-reader","project_id":"sample-project","through":"workspace"}),
1013 json!({"op":"config.watch"}),
1014 json!({"op":"config.watch","modules":["sample-reader"]}),
1015 json!({"op":"config.plan"}),
1016 json!({"op":"config.plan_get", "digest":subc_config::raw_digest(b"plan")}),
1017 json!({"op":"config.plan_discard", "digest":subc_config::raw_digest(b"plan")}),
1018 json!({"op":"config.apply", "digest":subc_config::raw_digest(b"plan")}),
1019 json!({"op":"config.stamp"}),
1020 json!({"op":"config.unstamp"}),
1021 json!({"op":"config.history"}),
1022 json!({"op":"config.rollback", "generation":4}),
1023 ] {
1024 let request: ConfigControlRequest = serde_json::from_value(body.clone()).unwrap();
1025 assert_eq!(body["op"], request.op());
1026 assert_eq!(serde_json::to_value(&request).unwrap(), body);
1027 let mut claimed = body;
1028 claimed["reviewed"] = json!(true);
1029 assert!(serde_json::from_value::<ConfigControlRequest>(claimed).is_err());
1030 }
1031 assert!(
1032 serde_json::from_value::<ConfigControlRequest>(json!({"op":"config.apply"})).is_err()
1033 );
1034 }
1035
1036 #[test]
1037 fn config_wire_plan_view_and_status_tolerate_reply_extensions() {
1038 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
1039 let view = ConfigPlanView::new(plan.clone()).unwrap();
1040 assert_eq!(view.digest, plan.digest().unwrap());
1041 let response = ConfigControlResponse::Stamp { view };
1042 let mut body = serde_json::to_value(&response).unwrap();
1043 body["future"] = json!(true);
1044 assert_eq!(
1045 serde_json::from_value::<ConfigControlResponse>(body).unwrap(),
1046 response
1047 );
1048 let status = ConfigControlResponse::Status {
1049 status: ConfigStatus::default(),
1050 };
1051 assert_eq!(
1052 serde_json::from_value::<ConfigControlResponse>(serde_json::to_value(&status).unwrap())
1053 .unwrap(),
1054 status
1055 );
1056 }
1057
1058 #[test]
1059 fn config_wire_edit_actions_are_exclusive_and_null_is_not_absence() {
1060 let base = json!({"module_id":"demo","layer":"user","path":"/limit"});
1061 for action in [
1062 json!({"set":0}),
1063 json!({"set":false}),
1064 json!({"set":null}),
1065 json!({"remove":true}),
1066 ] {
1067 let mut value = base.clone();
1068 value
1069 .as_object_mut()
1070 .unwrap()
1071 .extend(action.as_object().unwrap().clone());
1072 let edit: ConfigEdit = serde_json::from_value(value.clone()).unwrap();
1073 assert_eq!(serde_json::to_value(edit).unwrap(), value);
1074 }
1075 for action in [
1076 json!({}),
1077 json!({"set":1,"remove":true}),
1078 json!({"remove":false}),
1079 json!({"remove":true,"extra":1}),
1080 ] {
1081 let mut value = base.clone();
1082 value
1083 .as_object_mut()
1084 .unwrap()
1085 .extend(action.as_object().unwrap().clone());
1086 assert!(serde_json::from_value::<ConfigEdit>(value).is_err());
1087 }
1088 let request: ConfigControlRequest =
1089 serde_json::from_value(json!({"op":"config.plan"})).unwrap();
1090 assert_eq!(
1091 serde_json::to_vec(&request).unwrap(),
1092 br#"{"op":"config.plan"}"#
1093 );
1094 }
1095
1096 #[test]
1097 fn config_wire_empty_refusals_preserve_legacy_view_bytes() {
1098 let plan = Plan::new(7, 3, "daemon", Default::default(), Default::default());
1099 let view = ConfigPlanView::new(plan.clone()).unwrap();
1100 let legacy = json!({"digest":plan.digest().unwrap(),"base_revision":7,"plan":plan});
1101 assert_eq!(serde_json::to_value(&view).unwrap(), legacy);
1102 assert_eq!(
1103 serde_json::from_value::<ConfigPlanView>(legacy).unwrap(),
1104 view
1105 );
1106 assert_eq!(
1107 serde_json::to_string(&ConfigControlResponse::PlanDiscard {}).unwrap(),
1108 r#"{"op":"config.plan_discard"}"#
1109 );
1110 }
1111}