1mod anchor_retry;
9mod apply;
10mod approval;
11pub mod capture;
12mod capture_plan;
13pub(crate) mod program;
14pub mod project_layers;
15pub mod project_registry;
16mod recovery_inventory;
17mod refusal_rule;
18mod restore;
19pub(crate) mod review;
20mod reviewed_build;
21mod root_io;
22pub mod runtime;
23mod snapshot;
24mod strict_json;
25pub(crate) mod targets;
26
27pub(crate) use apply::Transition;
28pub use approval::*;
29pub use snapshot::{CapturedInput, GateSnapshot, InputKey};
30
31pub(crate) fn module_base_generation(body: &crate::config_store::StoreBody, module: &str) -> u64 {
33 if !body.stamped {
34 return 0;
35 }
36 body.generations
37 .values()
38 .rev()
39 .find(|entry| entry.tuples.iter().any(|tuple| tuple.module == module))
40 .map_or(0, |entry| entry.generation.id)
41}
42
43use std::collections::{BTreeMap, BTreeSet};
44
45use subc_config::{Changeset, Digest, Generation, Layer, Plan};
46use subc_control::config::{ConfigFileError, ConfigFileErrorLayer, ConfigPlanView};
47
48use crate::config_store::{CommitKind, ConfigStore, HistoryEntry, StoreError, StoreState, Tuple};
49
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct GateError {
52 pub code: String,
53 pub detail: String,
54 capture_race: bool,
55 restore_installed: bool,
56 settings_file: Option<Box<SettingsFile>>,
57 settings_pointer: Option<String>,
58 pub(crate) wire_detail: Option<Box<serde_json::Value>>,
59 pub(crate) settings_review_paths: Vec<std::path::PathBuf>,
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
63struct SettingsFile {
64 layer: Layer,
65 path: Option<String>,
66 content_digest: Option<Digest>,
67}
68type Result<T> = std::result::Result<T, GateError>;
69
70impl GateError {
71 pub fn new(code: &str, detail: impl ToString) -> Self {
72 Self {
73 code: code.into(),
74 detail: detail.to_string(),
75 capture_race: false,
76 restore_installed: false,
77 settings_file: None,
78 settings_pointer: None,
79 wire_detail: None,
80 settings_review_paths: Vec::new(),
81 }
82 }
83
84 pub(crate) fn with_wire_detail(mut self, detail: serde_json::Value) -> Self {
85 self.wire_detail = Some(Box::new(detail));
86 self
87 }
88
89 pub(crate) fn with_settings_review_paths(mut self, paths: Vec<std::path::PathBuf>) -> Self {
90 self.settings_review_paths = paths;
91 self
92 }
93
94 fn at_settings_layer(mut self, layer: Layer) -> Self {
95 if matches!(layer, Layer::Project | Layer::Workspace) {
96 self.settings_file = Some(Box::new(SettingsFile {
97 layer,
98 path: None,
99 content_digest: None,
100 }));
101 }
102 self
103 }
104
105 fn at_user_file(mut self, path: &std::path::Path, bytes: Option<&[u8]>) -> Self {
106 self.settings_file = Some(Box::new(SettingsFile {
107 layer: Layer::User,
108 path: Some(path.to_string_lossy().into_owned()),
109 content_digest: bytes.map(subc_config::raw_digest),
110 }));
111 self
112 }
113
114 fn with_settings_path(mut self, path_for: impl FnOnce(Layer) -> Option<String>) -> Self {
115 if let Some(file) = self.settings_file.as_mut() {
116 file.path =
117 path_for(file.layer).filter(|path| std::path::Path::new(path).is_absolute());
118 }
119 self
120 }
121
122 fn with_settings_pointer(mut self, pointer: String) -> Self {
123 self.settings_pointer = (!pointer.is_empty()).then_some(pointer);
125 self
126 }
127
128 fn into_settings_file_error(self) -> ConfigFileError {
129 let mut error = ConfigFileError::new(self.code, self.detail);
130 error.pointer = self.settings_pointer;
131 if let Some(file) = self.settings_file {
132 error.layer = match file.layer {
133 Layer::Project => Some(ConfigFileErrorLayer::Project),
134 Layer::Workspace => Some(ConfigFileErrorLayer::Workspace),
135 _ => None,
136 };
137 error.path = file.path;
138 }
139 error
140 }
141 fn invalid(detail: impl ToString) -> Self {
142 Self::new("value_invalid", detail)
143 }
144 fn stale() -> Self {
145 Self::new(
146 "plan_stale",
147 "reviewed inputs or generation changed; plan again",
148 )
149 }
150
151 pub(crate) fn capture_race() -> Self {
154 Self {
155 capture_race: true,
156 ..Self::stale()
157 }
158 }
159
160 pub(crate) fn is_capture_race(&self) -> bool {
161 self.capture_race
162 }
163
164 pub(crate) fn commit_timeout() -> Self {
165 Self::new("config_commit_timeout", "the post-answer commit window expired before durable publication; plan remains unapproved")
166 }
167}
168impl std::fmt::Display for GateError {
169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170 write!(f, "{}: {}", self.code, self.detail)
171 }
172}
173impl std::error::Error for GateError {}
174impl From<StoreError> for GateError {
175 fn from(error: StoreError) -> Self {
176 use crate::config_store::StoreErrorCode as Code;
177 let code = match error.code {
178 Code::StoreUnverified => "store_unverified",
179 Code::StoreMissing => "store_missing",
180 Code::StoreTampered => "store_tampered",
181 Code::StoreTooLarge => "store_too_large",
182 Code::AnchorPending => "anchor_pending",
183 Code::GenerationPruned => "generation_pruned",
184 Code::GenerationMissing => "generation_missing",
185 Code::RevisionExhausted => "revision_exhausted",
186 Code::InvalidState => "config_gated",
187 Code::Io => "config_store_io",
188 };
189 Self::new(code, error.detail)
190 }
191}
192
193pub trait ReviewAdmission: Send + Sync {
196 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()>;
197}
198
199pub(crate) struct MissingReviewAdmission;
200impl ReviewAdmission for MissingReviewAdmission {
201 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()> {
202 Err(GateError::new(
203 "program_admission_unavailable",
204 format!(
205 "{}: running program review admission is not connected",
206 registration.manifest.module_id
207 ),
208 ))
209 }
210}
211
212pub(crate) enum ReviewRecord<'a> {
215 Absent,
218 Reviewed(&'a BTreeSet<String>),
222 Copied(Option<serde_json::Value>),
225}
226
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub enum PlanKind {
229 Change,
230 Stamp,
231 Unstamp,
232 Rollback(u64),
233}
234impl PlanKind {
235 fn commit_kind(self) -> CommitKind {
236 match self {
237 Self::Change => CommitKind::Approved,
238 Self::Stamp => CommitKind::Stamp,
239 Self::Unstamp => CommitKind::Unstamp,
240 Self::Rollback(_) => CommitKind::Rollback,
241 }
242 }
243}
244
245struct PendingPlan {
246 settings_attempt_owner: Option<u64>,
247 kept_after_refused_decline: bool,
248 decline_accepted: bool,
249 restoring: bool,
250 restored_paths: BTreeSet<std::path::PathBuf>,
251 user_restore: BTreeMap<std::path::PathBuf, restore::UserRestoreMetadata>,
252 settings_users: Option<BTreeSet<String>>,
253 settings_file_witness: Option<Digest>,
254 creation_sequence: u64,
255 edits: Option<runtime::edits::EditPlan>,
256 development_approval: Option<crate::program_origin::DevelopmentApproval>,
257 view: ConfigPlanView,
258 kind: PlanKind,
259 snapshot: GateSnapshot,
260 modules: BTreeSet<String>,
261 changed: BTreeSet<InputKey>,
262 callosum_entry_changed: bool,
263 recovery: bool,
264 delivery: Option<crate::config_store::DeliverySnapshot>,
265 project_files: Vec<crate::config_store::ProjectFileApproval>,
266 project_capture: Option<capture_plan::ProjectCapture>,
267}
268
269impl PendingPlan {
270 fn targets(&self) -> Result<BTreeSet<Tuple>> {
271 let targets = targets::checked(&self.view.plan)?;
272 Ok(if self.development_approval.is_some() {
276 BTreeSet::new()
277 } else {
278 targets
279 })
280 }
281}
282
283pub struct ConfigGate {
286 incarnation: String,
287 plans: BTreeMap<Digest, PendingPlan>,
288 kept_paths: BTreeMap<std::path::PathBuf, Digest>,
289 attempts: BTreeMap<u64, approval::Attempt>,
290 next_attempt: u64,
291 next_plan_sequence: u64,
292}
293
294impl ConfigGate {
295 fn pending_file_plan(&self, module: &str) -> Option<Digest> {
296 self.plans
297 .values()
298 .filter(|plan| {
299 plan.edits.is_none()
300 && plan.modules.contains(module)
301 && plan.targets().is_ok_and(|targets| {
302 targets
303 .iter()
304 .any(|tuple| tuple.module == module && tuple.project.is_none())
305 || !targets.iter().any(|tuple| tuple.module == module)
306 })
307 })
308 .max_by_key(|plan| plan.creation_sequence)
309 .map(|plan| plan.view.digest.clone())
310 }
311
312 pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
313 self.plans
314 .get(digest)
315 .map(|plan| plan.modules.clone())
316 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
317 }
318
319 pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
320 self.attempts.remove(&attempt);
321 }
322
323 pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
324 self.kept_paths.retain(|_, owner| owner != digest);
325 self.plans.remove(digest).is_some()
326 }
327 pub fn new(incarnation: String) -> Self {
328 Self {
329 incarnation,
330 plans: BTreeMap::new(),
331 kept_paths: BTreeMap::new(),
332 attempts: BTreeMap::new(),
333 next_attempt: 0,
334 next_plan_sequence: 0,
335 }
336 }
337
338 pub fn plan(
341 &mut self,
342 store: &mut ConfigStore,
343 kind: PlanKind,
344 candidate: GateSnapshot,
345 observed: &GateSnapshot,
346 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
347 ) -> Result<ConfigPlanView> {
348 self.plan_reviewed(
349 store,
350 kind,
351 candidate,
352 observed,
353 ReviewRecord::Absent,
354 review,
355 )
356 }
357
358 pub(crate) fn plan_reviewed(
363 &mut self,
364 store: &mut ConfigStore,
365 kind: PlanKind,
366 candidate: GateSnapshot,
367 observed: &GateSnapshot,
368 record: ReviewRecord<'_>,
369 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
370 ) -> Result<ConfigPlanView> {
371 self.plan_reviewed_inner(
372 store, kind, candidate, observed, record, None, None, None, review,
373 )
374 }
375
376 #[allow(clippy::too_many_arguments)]
377 fn plan_reviewed_inner(
378 &mut self,
379 store: &mut ConfigStore,
380 kind: PlanKind,
381 mut candidate: GateSnapshot,
382 observed: &GateSnapshot,
383 record: ReviewRecord<'_>,
384 edits: Option<runtime::edits::EditPlan>,
385 projects: Option<targets::ProjectReviews>,
386 settings_file_witness: Option<Digest>,
387 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
388 ) -> Result<ConfigPlanView> {
389 let status = store.status();
390 let recovery = matches!(
391 status.state,
392 StoreState::StoreUnverified | StoreState::StoreMissing
393 );
394 if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
395 || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
396 {
397 return Err(GateError::new(
398 "config_gated",
399 "stamp is required before planning changes",
400 ));
401 }
402 if self
403 .plans
404 .values()
405 .filter(|plan| !plan.kept_after_refused_decline)
406 .count()
407 >= 64
408 {
409 return Err(GateError::new("config_busy", "too many pending plans"));
410 }
411 let mut rollback_programs = Vec::new();
412 if let PlanKind::Rollback(id) = kind {
413 let mut target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
414 runtime::policy_root::preserve_root_on_rollback(store.body()?, id, &mut target)?;
415 if target
416 .inputs
417 .iter()
418 .filter(|(key, _)| !key.is_program() && !key.is_project())
419 .ne(candidate
420 .inputs
421 .iter()
422 .filter(|(key, _)| !key.is_program() && !key.is_project()))
423 {
424 return Err(GateError::invalid(
425 "rollback must reverse the target configuration",
426 ));
427 }
428 for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
429 if target.inputs.get(key) != Some(now) {
430 rollback_programs.push(serde_json::json!({
431 "module_id":key.module(),
432 "input":key,
433 "reason":"program changed since that version",
434 "approved_then":target.inputs.get(key),
435 "on_disk_now":now,
436 }));
437 }
438 }
439 }
440 let (base_revision, base_generation, approved, active) =
441 if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
442 (
443 status.base_revision,
444 0,
445 edit.baseline.clone(),
446 BTreeMap::new(),
447 )
448 } else if recovery {
449 (0, 0, GateSnapshot::default(), BTreeMap::new())
450 } else {
451 store.delivery_ready()?;
452 let body = store.body()?;
453 let active = body
454 .versions
455 .iter()
456 .filter_map(|(tuple, versions)| {
457 versions
458 .active
459 .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
460 })
461 .collect();
462 (
463 body.base_revision,
464 body.last_generation,
465 GateSnapshot::from_store(&body.approved)?,
466 active,
467 )
468 };
469 if !recovery {
470 candidate.carry_project_inputs(&approved);
471 }
472 if status.state == StoreState::Stamped
473 && kind == PlanKind::Change
474 && edits.as_ref().is_none_or(|edit| edit.policy_root.is_none())
475 && runtime::policy_root::section_value(&candidate)
476 != runtime::policy_root::section_value(&approved)
477 {
478 return Err(GateError::new(
479 "value_invalid",
480 "use a policy_root operation to change the stamped agent policy trust root",
481 ));
482 }
483 let changed: BTreeSet<InputKey> = approved
484 .changed_keys(&candidate)
485 .into_iter()
486 .cloned()
487 .collect();
488 let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
489 match (
490 approved.inputs.get(&InputKey::Daemon),
491 candidate.inputs.get(&InputKey::Daemon),
492 ) {
493 (
494 Some(CapturedInput {
495 value: subc_config::RecordedValue::Value { value: old },
496 ..
497 }),
498 Some(CapturedInput {
499 value: subc_config::RecordedValue::Value { value: new },
500 ..
501 }),
502 ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
503 _ => true,
504 }
505 } else {
506 false
507 };
508 let mut user_modules: BTreeSet<String> = changed
509 .iter()
510 .filter(|key| !key.is_project())
511 .filter_map(|key| key.module().map(str::to_owned))
512 .collect();
513 let mut changeset = review(&approved, &candidate)?;
514 for difference in &rollback_programs {
515 if let Some(module) = difference["module_id"].as_str() {
516 user_modules.insert(module.to_owned());
517 changeset
518 .launch_manifests
519 .entry(module.to_owned())
520 .or_insert_with(|| serde_json::json!({}))
521 .as_object_mut()
522 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
523 .insert(
524 "program_changed_since_target".into(),
525 serde_json::Value::Bool(true),
526 );
527 }
528 }
529 user_modules.extend(
530 changeset
531 .fields
532 .iter()
533 .filter(|field| field.project_id.is_none())
534 .map(|field| field.module_id.clone()),
535 );
536 user_modules.extend(changeset.launch_manifests.keys().cloned());
537 if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
538 user_modules.extend(
539 observed
540 .inputs
541 .keys()
542 .chain(approved.inputs.keys())
543 .filter(|key| !key.is_project())
544 .filter_map(|key| key.module().map(str::to_owned)),
545 );
546 }
547 let transitions = changeset
554 .apply_plan
555 .as_object_mut()
556 .and_then(|review| review.remove("module_transitions"));
557 if transitions.is_some()
558 && changeset
559 .apply_plan
560 .as_object()
561 .is_some_and(|review| review.is_empty())
562 {
563 changeset.apply_plan = serde_json::Value::Null;
564 }
565 changeset.apply_plan = serde_json::json!({
566 "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
567 "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
568 "review": changeset.apply_plan,
569 "previous": approved.to_store()?,
570 "snapshot": candidate.to_store()?,
571 });
572 if let Some(mut transitions) = transitions {
573 if let Some(table) = transitions.as_object_mut() {
574 if projects.is_some() {
575 table.retain(|module, _| user_modules.contains(module));
576 } else {
577 user_modules.extend(table.keys().cloned());
578 }
579 }
580 changeset.apply_plan["module_transitions"] = transitions;
581 }
582 if matches!(kind, PlanKind::Rollback(_)) {
583 changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
584 }
585 let replaces_programs =
586 !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
587 if replaces_programs {
588 let body = store.body()?;
594 for module in &user_modules {
595 if reviewed_build::active(body, module)?
596 .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
597 {
598 changeset
599 .launch_manifests
600 .entry(module.clone())
601 .or_insert_with(|| serde_json::json!({}))
602 .as_object_mut()
603 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
604 .insert(
605 "program_changed_since_active".into(),
606 serde_json::Value::Bool(true),
607 );
608 }
609 }
610 }
611 let reviewed = match record {
612 ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
613 ReviewRecord::Copied(Some(copied)) => {
614 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
615 None
616 }
617 ReviewRecord::Reviewed(reviewed) => Some(reviewed),
618 };
619 if let Some(reviewed) = reviewed {
620 let mut record = if replaces_programs {
621 reviewed_build::recorded(store.body()?)?
622 } else {
623 BTreeMap::new()
624 };
625 let present = candidate.modules();
626 record.retain(|module, _| present.contains(module));
627 for module in reviewed {
628 let program = if replaces_programs {
633 match reviewed_build::active(store.body()?, module)? {
634 Some(active) => active,
635 None => reviewed_build::identity(&approved, module),
636 }
637 } else {
638 reviewed_build::identity(&candidate, module)
639 };
640 if let Some(previous) = record.get(module).filter(|previous| **previous != program)
641 {
642 if projects.is_some() {
643 user_modules.insert(module.clone());
644 }
645 changeset.policy_changes.push(serde_json::json!({
646 "module_id": module,
647 "path": "reviewed_program",
648 "old": previous,
649 "new": program,
650 "reason": "approved configuration re-reviewed by the module's newly approved program",
651 }));
652 }
653 record.insert(module.clone(), program);
654 }
655 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
656 }
657 apply::bind_plan(&mut changeset)?;
658 if let Some(edit) = &edits {
659 changeset.apply_plan["edit_plan"] = serde_json::json!({
660 "unstamped": edit.unstamped,
661 "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
662 });
663 if !edit.refusals.is_empty() {
664 changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
667 }
668 }
669 let mut modules = user_modules.clone();
670 modules.extend(changed.iter().filter_map(|key| match key {
671 InputKey::ProjectTuple { module, .. } => Some(module.clone()),
672 _ => None,
673 }));
674 if let Some(projects) = &projects {
675 modules.extend(projects.tuples.keys().map(|tuple| tuple.module.clone()));
676 }
677 let mut inputs = observed.read_set(&modules)?;
678 add_settings_file_witness(&mut inputs, settings_file_witness.as_ref());
679 let (delivery, project_files) = if let Some(projects) = projects {
680 let body = if recovery { None } else { Some(store.body()?) };
681 let (delivery, files) = projects.bind(body, &inputs, &mut changeset, &user_modules)?;
682 if recovery && !files.is_empty() {
683 return Err(GateError::new(
684 "apply_plan_invalid",
685 "recovery cannot approve project file write-back",
686 ));
687 }
688 (Some(delivery), files)
689 } else {
690 (None, Vec::new())
691 };
692 let mut plan = Plan::new(
693 base_revision,
694 base_generation,
695 &self.incarnation,
696 inputs,
697 changeset,
698 );
699 plan.active_generations = active;
700 targets::checked(&plan)?;
701 let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
702 view.unstamped = status.state == StoreState::Unstamped;
703 if let Some(edit) = &edits {
704 view.refusals = edit.refusals.clone();
705 }
706 if self.plans.get(&view.digest).is_some_and(|plan| {
707 plan.kept_after_refused_decline || plan.decline_accepted || plan.restoring
708 }) {
709 return Err(GateError::new(
710 "settings_decline_kept",
711 "the declined settings plan is waiting for a manual restore",
712 ));
713 }
714 if settings_file_witness.is_some()
715 && self
716 .plans
717 .get(&view.digest)
718 .is_some_and(|plan| plan.settings_attempt_owner.is_some())
719 && self.has_open_approval(&view.digest)
720 {
721 return Err(GateError::new(
722 "config_busy",
723 "a settings approval already owns this plan",
724 ));
725 }
726 self.next_plan_sequence = self
727 .next_plan_sequence
728 .checked_add(1)
729 .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
730 self.plans.insert(
731 view.digest.clone(),
732 PendingPlan {
733 settings_attempt_owner: None,
734 kept_after_refused_decline: false,
735 decline_accepted: false,
736 restoring: false,
737 restored_paths: BTreeSet::new(),
738 user_restore: BTreeMap::new(),
739 settings_users: None,
740 settings_file_witness,
741 creation_sequence: self.next_plan_sequence,
742 edits,
743 development_approval: None,
744 view: view.clone(),
745 kind,
746 snapshot: candidate,
747 modules,
748 changed,
749 callosum_entry_changed,
750 recovery,
751 delivery,
752 project_files,
753 project_capture: None,
754 },
755 );
756 Ok(view)
757 }
758
759 fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
760 let plan = self
761 .plans
762 .get(digest)
763 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
764 Ok(plan
765 .snapshot
766 .inputs
767 .keys()
768 .filter(|key| {
769 key.is_program()
770 && key
771 .module()
772 .is_some_and(|module| plan.modules.contains(module))
773 })
774 .cloned()
775 .collect())
776 }
777
778 pub(crate) fn bind_delivery(
782 &mut self,
783 digest: &Digest,
784 mut delivery: crate::config_store::DeliverySnapshot,
785 ) -> Result<()> {
786 let plan = self
787 .plans
788 .get_mut(digest)
789 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
790 if let Some(projects) = &plan.delivery {
791 for (module, declaration) in &projects.declarations {
792 if delivery
793 .declarations
794 .get(module)
795 .is_some_and(|user| user != declaration)
796 {
797 return Err(GateError::new(
798 "apply_plan_invalid",
799 "user and project views name different declarations of the same module",
800 ));
801 }
802 delivery
803 .declarations
804 .insert(module.clone(), declaration.clone());
805 }
806 delivery.project_views.clone_from(&projects.project_views);
807 delivery
808 .project_cutoffs
809 .clone_from(&projects.project_cutoffs);
810 delivery
811 .project_approval_digests
812 .clone_from(&projects.project_approval_digests);
813 }
814 plan.delivery = Some(delivery);
815 Ok(())
816 }
817
818 pub fn rollback(
824 &mut self,
825 store: &mut ConfigStore,
826 generation: u64,
827 observed: &GateSnapshot,
828 current_programs: &GateSnapshot,
829 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
830 ) -> Result<ConfigPlanView> {
831 let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
832 runtime::policy_root::preserve_root_on_rollback(store.body()?, generation, &mut target)?;
833 target.inputs.retain(|key, _| !key.is_project());
834 target.restore_programs_from(current_programs)?;
835 let copied = store
836 .body()?
837 .generations
838 .get(&generation)
839 .and_then(|entry| {
840 entry
841 .generation
842 .changeset
843 .apply_plan
844 .get(reviewed_build::REVIEWED_PROGRAMS)
845 })
846 .cloned();
847 self.plan_reviewed(
848 store,
849 PlanKind::Rollback(generation),
850 target,
851 observed,
852 ReviewRecord::Copied(copied),
853 review,
854 )
855 }
856
857 fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
858 plan.targets()?;
859 let status = store.status();
860 let recovery = matches!(
861 status.state,
862 StoreState::StoreUnverified | StoreState::StoreMissing
863 );
864 if recovery != plan.recovery {
865 return Err(GateError::stale());
866 }
867 let base = if recovery {
868 0
869 } else {
870 store.delivery_ready()?;
871 store.body()?.base_revision
872 };
873 let mut inputs = current.read_set(&plan.modules)?;
874 add_settings_file_witness(&mut inputs, plan.settings_file_witness.as_ref());
877 plan.view.plan.check_fresh(base, &inputs).map_err(|_| {
878 if plan.project_capture.is_some() {
879 capture_plan::changed()
880 } else {
881 GateError::stale()
882 }
883 })
884 }
885
886 #[allow(clippy::too_many_arguments)]
887 fn commit(
888 &mut self,
889 digest: &Digest,
890 approval_channel: subc_config::ApprovalChannel,
891 store: &mut ConfigStore,
892 current: &GateSnapshot,
893 now_ms: u64,
894 before_publication: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
895 ) -> Result<u64> {
896 let plan = self
897 .plans
898 .get(digest)
899 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
900 Self::fresh(plan, store, current)?;
901 let mut generation = Generation::new(
902 0,
903 approval_channel,
904 digest.clone(),
905 plan.view.plan.input_vector.clone(),
906 plan.view.plan.changeset.clone(),
907 );
908 let declarations_only = plan.development_approval.is_some();
909 generation.active_generations = plan.view.plan.active_generations.clone();
910 let tuples = plan.targets()?;
911 for tuple in &tuples {
912 let module = &tuple.module;
913 if tuple.project.is_none() {
914 generation
915 .module_states
916 .insert(module.clone(), subc_config::GenerationState::Pending);
917 }
918 if let Some(CapturedInput {
919 state: subc_config::InputState::Present { digest },
920 ..
921 }) = plan
922 .snapshot
923 .inputs
924 .get(&InputKey::Declaration(module.clone()))
925 {
926 generation
927 .declaration_digests
928 .insert(module.clone(), digest.clone());
929 }
930 }
931 let snapshot = plan.snapshot.to_store()?;
932 let mut entry = HistoryEntry {
933 generation,
934 kind: if declarations_only {
935 CommitKind::DeclarationApproval
936 } else {
937 plan.kind.commit_kind()
938 },
939 approval_id: digest.to_string(),
940 outcome: "approved".into(),
941 tuples,
942 project_outcomes: BTreeMap::new(),
943 configuration: snapshot.clone(),
944 delivery: plan.delivery.clone(),
945 };
946 let base_before = store.status().base_revision;
947 let mut observed = current.clone();
948 if !plan.recovery {
949 let body = store.body()?;
950 let previous = body.observed.as_ref().unwrap_or(&body.approved);
951 let previous = GateSnapshot::from_store(previous)?;
952 if plan.settings_users.is_some() {
953 observed = previous.clone();
957 for key in &plan.changed {
958 if let Some(input) = plan.snapshot.inputs.get(key) {
959 observed.inputs.insert(key.clone(), input.clone());
960 }
961 }
962 }
963 observed.inputs.retain(|key, _| !key.is_project());
966 observed.carry_project_inputs(&previous);
967 observed.carry_project_inputs(&plan.snapshot);
968 if let Some(capture) = &plan.project_capture {
969 observed
970 .inputs
971 .extend(capture.edit_observations.inputs.clone());
972 for (key, input) in &plan.snapshot.inputs {
973 if matches!(key, InputKey::ProjectTuple { .. }) {
974 observed.inputs.insert(key.clone(), input.clone());
975 }
976 }
977 for key in observed.inputs.keys().cloned().collect::<Vec<_>>() {
978 if matches!(&key, InputKey::Layer { module, .. } if capture.held_user.contains(module))
979 {
980 if let Some(input) = previous.inputs.get(&key) {
981 observed.inputs.insert(key, input.clone());
982 } else {
983 observed.inputs.remove(&key);
984 }
985 }
986 }
987 }
988 }
989 let observed = observed.to_store()?;
990 if let Some(checkpoint) = before_publication()? {
991 entry.generation.changeset.apply_plan[crate::policy_root::ledger::CHECKPOINT_FIELD] =
994 serde_json::to_value(checkpoint).map_err(GateError::invalid)?;
995 }
996 let result = if plan.recovery {
997 store.recovery_exit(entry, snapshot, now_ms)
998 } else {
999 store.commit_generation_with_project_files(
1000 entry,
1001 snapshot,
1002 observed,
1003 plan.project_files.clone(),
1004 now_ms,
1005 )
1006 };
1007 if result.is_ok() || store.status().base_revision != base_before {
1011 self.expire_plan(digest);
1012 }
1013 let id = result?;
1014 store.delivery_ready()?;
1015 Ok(id)
1016 }
1017}
1018
1019mod registration;
1020
1021fn add_settings_file_witness(inputs: &mut subc_config::InputVector, witness: Option<&Digest>) {
1022 if let Some(digest) = witness {
1023 inputs.inputs.insert(
1024 "settings-files".into(),
1025 subc_config::InputState::Present {
1026 digest: digest.clone(),
1027 },
1028 );
1029 }
1030}
1031#[cfg(test)]
1032mod tests;