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;
16pub(crate) mod review;
17mod reviewed_build;
18mod root_io;
19pub mod runtime;
20mod snapshot;
21mod strict_json;
22pub(crate) mod targets;
23
24pub(crate) use apply::Transition;
25pub use approval::*;
26pub use snapshot::{CapturedInput, GateSnapshot, InputKey};
27
28pub(crate) fn module_base_generation(body: &crate::config_store::StoreBody, module: &str) -> u64 {
30 if !body.stamped {
31 return 0;
32 }
33 body.generations
34 .values()
35 .rev()
36 .find(|entry| entry.tuples.iter().any(|tuple| tuple.module == module))
37 .map_or(0, |entry| entry.generation.id)
38}
39
40use std::collections::{BTreeMap, BTreeSet};
41
42use subc_config::{Changeset, Digest, Generation, Plan};
43use subc_control::config::ConfigPlanView;
44
45use crate::config_store::{CommitKind, ConfigStore, HistoryEntry, StoreError, StoreState, Tuple};
46
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct GateError {
49 pub code: String,
50 pub detail: String,
51 capture_race: bool,
52}
53type Result<T> = std::result::Result<T, GateError>;
54
55impl GateError {
56 pub fn new(code: &str, detail: impl ToString) -> Self {
57 Self {
58 code: code.into(),
59 detail: detail.to_string(),
60 capture_race: false,
61 }
62 }
63 fn invalid(detail: impl ToString) -> Self {
64 Self::new("value_invalid", detail)
65 }
66 fn stale() -> Self {
67 Self::new(
68 "plan_stale",
69 "reviewed inputs or generation changed; plan again",
70 )
71 }
72
73 pub(crate) fn capture_race() -> Self {
76 Self {
77 capture_race: true,
78 ..Self::stale()
79 }
80 }
81
82 pub(crate) fn is_capture_race(&self) -> bool {
83 self.capture_race
84 }
85
86 pub(crate) fn commit_timeout() -> Self {
87 Self::new("config_commit_timeout", "the post-answer commit window expired before durable publication; plan remains unapproved")
88 }
89}
90impl std::fmt::Display for GateError {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 write!(f, "{}: {}", self.code, self.detail)
93 }
94}
95impl std::error::Error for GateError {}
96impl From<StoreError> for GateError {
97 fn from(error: StoreError) -> Self {
98 use crate::config_store::StoreErrorCode as Code;
99 let code = match error.code {
100 Code::StoreUnverified => "store_unverified",
101 Code::StoreMissing => "store_missing",
102 Code::StoreTampered => "store_tampered",
103 Code::StoreTooLarge => "store_too_large",
104 Code::AnchorPending => "anchor_pending",
105 Code::GenerationPruned => "generation_pruned",
106 Code::GenerationMissing => "generation_missing",
107 Code::RevisionExhausted => "revision_exhausted",
108 Code::InvalidState => "config_gated",
109 Code::Io => "config_store_io",
110 };
111 Self::new(code, error.detail)
112 }
113}
114
115pub trait ReviewAdmission: Send + Sync {
118 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()>;
119}
120
121pub(crate) struct MissingReviewAdmission;
122impl ReviewAdmission for MissingReviewAdmission {
123 fn check(&self, registration: &crate::registry::ModuleRegistration) -> Result<()> {
124 Err(GateError::new(
125 "program_admission_unavailable",
126 format!(
127 "{}: running program review admission is not connected",
128 registration.manifest.module_id
129 ),
130 ))
131 }
132}
133
134pub(crate) enum ReviewRecord<'a> {
137 Absent,
140 Reviewed(&'a BTreeSet<String>),
144 Copied(Option<serde_json::Value>),
147}
148
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum PlanKind {
151 Change,
152 Stamp,
153 Unstamp,
154 Rollback(u64),
155}
156impl PlanKind {
157 fn commit_kind(self) -> CommitKind {
158 match self {
159 Self::Change => CommitKind::Approved,
160 Self::Stamp => CommitKind::Stamp,
161 Self::Unstamp => CommitKind::Unstamp,
162 Self::Rollback(_) => CommitKind::Rollback,
163 }
164 }
165}
166
167struct PendingPlan {
168 creation_sequence: u64,
169 edits: Option<runtime::edits::EditPlan>,
170 development_approval: Option<crate::program_origin::DevelopmentApproval>,
171 view: ConfigPlanView,
172 kind: PlanKind,
173 snapshot: GateSnapshot,
174 modules: BTreeSet<String>,
175 changed: BTreeSet<InputKey>,
176 callosum_entry_changed: bool,
177 recovery: bool,
178 delivery: Option<crate::config_store::DeliverySnapshot>,
179 project_files: Vec<crate::config_store::ProjectFileApproval>,
180 project_capture: Option<capture_plan::ProjectCapture>,
181}
182
183impl PendingPlan {
184 fn targets(&self) -> Result<BTreeSet<Tuple>> {
185 let targets = targets::checked(&self.view.plan)?;
186 Ok(if self.development_approval.is_some() {
190 BTreeSet::new()
191 } else {
192 targets
193 })
194 }
195}
196
197pub struct ConfigGate {
200 incarnation: String,
201 plans: BTreeMap<Digest, PendingPlan>,
202 attempts: BTreeMap<u64, approval::Attempt>,
203 next_attempt: u64,
204 next_plan_sequence: u64,
205}
206
207impl ConfigGate {
208 fn pending_file_plan(&self, module: &str) -> Option<Digest> {
209 self.plans
210 .values()
211 .filter(|plan| {
212 plan.edits.is_none()
213 && plan.modules.contains(module)
214 && plan.targets().is_ok_and(|targets| {
215 targets
216 .iter()
217 .any(|tuple| tuple.module == module && tuple.project.is_none())
218 || !targets.iter().any(|tuple| tuple.module == module)
219 })
220 })
221 .max_by_key(|plan| plan.creation_sequence)
222 .map(|plan| plan.view.digest.clone())
223 }
224
225 pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
226 self.plans
227 .get(digest)
228 .map(|plan| plan.modules.clone())
229 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
230 }
231
232 pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
233 self.attempts.remove(&attempt);
234 }
235
236 pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
237 self.plans.remove(digest).is_some()
238 }
239 pub fn new(incarnation: String) -> Self {
240 Self {
241 incarnation,
242 plans: BTreeMap::new(),
243 attempts: BTreeMap::new(),
244 next_attempt: 0,
245 next_plan_sequence: 0,
246 }
247 }
248
249 pub fn plan(
252 &mut self,
253 store: &mut ConfigStore,
254 kind: PlanKind,
255 candidate: GateSnapshot,
256 observed: &GateSnapshot,
257 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
258 ) -> Result<ConfigPlanView> {
259 self.plan_reviewed(
260 store,
261 kind,
262 candidate,
263 observed,
264 ReviewRecord::Absent,
265 review,
266 )
267 }
268
269 pub(crate) fn plan_reviewed(
274 &mut self,
275 store: &mut ConfigStore,
276 kind: PlanKind,
277 candidate: GateSnapshot,
278 observed: &GateSnapshot,
279 record: ReviewRecord<'_>,
280 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
281 ) -> Result<ConfigPlanView> {
282 self.plan_reviewed_inner(store, kind, candidate, observed, record, None, None, review)
283 }
284
285 #[allow(clippy::too_many_arguments)]
286 fn plan_reviewed_inner(
287 &mut self,
288 store: &mut ConfigStore,
289 kind: PlanKind,
290 mut candidate: GateSnapshot,
291 observed: &GateSnapshot,
292 record: ReviewRecord<'_>,
293 edits: Option<runtime::edits::EditPlan>,
294 projects: Option<targets::ProjectReviews>,
295 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
296 ) -> Result<ConfigPlanView> {
297 let status = store.status();
298 let recovery = matches!(
299 status.state,
300 StoreState::StoreUnverified | StoreState::StoreMissing
301 );
302 if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
303 || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
304 {
305 return Err(GateError::new(
306 "config_gated",
307 "stamp is required before planning changes",
308 ));
309 }
310 if self.plans.len() >= 64 {
311 return Err(GateError::new("config_busy", "too many pending plans"));
312 }
313 let mut rollback_programs = Vec::new();
314 if let PlanKind::Rollback(id) = kind {
315 let mut target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
316 runtime::policy_root::preserve_root_on_rollback(store.body()?, id, &mut target)?;
317 if target
318 .inputs
319 .iter()
320 .filter(|(key, _)| !key.is_program() && !key.is_project())
321 .ne(candidate
322 .inputs
323 .iter()
324 .filter(|(key, _)| !key.is_program() && !key.is_project()))
325 {
326 return Err(GateError::invalid(
327 "rollback must reverse the target configuration",
328 ));
329 }
330 for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
331 if target.inputs.get(key) != Some(now) {
332 rollback_programs.push(serde_json::json!({
333 "module_id":key.module(),
334 "input":key,
335 "reason":"program changed since that version",
336 "approved_then":target.inputs.get(key),
337 "on_disk_now":now,
338 }));
339 }
340 }
341 }
342 let (base_revision, base_generation, approved, active) =
343 if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
344 (
345 status.base_revision,
346 0,
347 edit.baseline.clone(),
348 BTreeMap::new(),
349 )
350 } else if recovery {
351 (0, 0, GateSnapshot::default(), BTreeMap::new())
352 } else {
353 store.delivery_ready()?;
354 let body = store.body()?;
355 let active = body
356 .versions
357 .iter()
358 .filter_map(|(tuple, versions)| {
359 versions
360 .active
361 .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
362 })
363 .collect();
364 (
365 body.base_revision,
366 body.last_generation,
367 GateSnapshot::from_store(&body.approved)?,
368 active,
369 )
370 };
371 if !recovery {
372 candidate.carry_project_inputs(&approved);
373 }
374 if status.state == StoreState::Stamped
375 && kind == PlanKind::Change
376 && edits.as_ref().is_none_or(|edit| edit.policy_root.is_none())
377 && runtime::policy_root::section_value(&candidate)
378 != runtime::policy_root::section_value(&approved)
379 {
380 return Err(GateError::new(
381 "value_invalid",
382 "use a policy_root operation to change the stamped agent policy trust root",
383 ));
384 }
385 let changed: BTreeSet<InputKey> = approved
386 .changed_keys(&candidate)
387 .into_iter()
388 .cloned()
389 .collect();
390 let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
391 match (
392 approved.inputs.get(&InputKey::Daemon),
393 candidate.inputs.get(&InputKey::Daemon),
394 ) {
395 (
396 Some(CapturedInput {
397 value: subc_config::RecordedValue::Value { value: old },
398 ..
399 }),
400 Some(CapturedInput {
401 value: subc_config::RecordedValue::Value { value: new },
402 ..
403 }),
404 ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
405 _ => true,
406 }
407 } else {
408 false
409 };
410 let mut user_modules: BTreeSet<String> = changed
411 .iter()
412 .filter(|key| !key.is_project())
413 .filter_map(|key| key.module().map(str::to_owned))
414 .collect();
415 let mut changeset = review(&approved, &candidate)?;
416 for difference in &rollback_programs {
417 if let Some(module) = difference["module_id"].as_str() {
418 user_modules.insert(module.to_owned());
419 changeset
420 .launch_manifests
421 .entry(module.to_owned())
422 .or_insert_with(|| serde_json::json!({}))
423 .as_object_mut()
424 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
425 .insert(
426 "program_changed_since_target".into(),
427 serde_json::Value::Bool(true),
428 );
429 }
430 }
431 user_modules.extend(
432 changeset
433 .fields
434 .iter()
435 .filter(|field| field.project_id.is_none())
436 .map(|field| field.module_id.clone()),
437 );
438 user_modules.extend(changeset.launch_manifests.keys().cloned());
439 if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
440 user_modules.extend(
441 observed
442 .inputs
443 .keys()
444 .chain(approved.inputs.keys())
445 .filter(|key| !key.is_project())
446 .filter_map(|key| key.module().map(str::to_owned)),
447 );
448 }
449 let transitions = changeset
456 .apply_plan
457 .as_object_mut()
458 .and_then(|review| review.remove("module_transitions"));
459 if transitions.is_some()
460 && changeset
461 .apply_plan
462 .as_object()
463 .is_some_and(|review| review.is_empty())
464 {
465 changeset.apply_plan = serde_json::Value::Null;
466 }
467 changeset.apply_plan = serde_json::json!({
468 "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
469 "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
470 "review": changeset.apply_plan,
471 "previous": approved.to_store()?,
472 "snapshot": candidate.to_store()?,
473 });
474 if let Some(mut transitions) = transitions {
475 if let Some(table) = transitions.as_object_mut() {
476 if projects.is_some() {
477 table.retain(|module, _| user_modules.contains(module));
478 } else {
479 user_modules.extend(table.keys().cloned());
480 }
481 }
482 changeset.apply_plan["module_transitions"] = transitions;
483 }
484 if matches!(kind, PlanKind::Rollback(_)) {
485 changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
486 }
487 let replaces_programs =
488 !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
489 if replaces_programs {
490 let body = store.body()?;
496 for module in &user_modules {
497 if reviewed_build::active(body, module)?
498 .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
499 {
500 changeset
501 .launch_manifests
502 .entry(module.clone())
503 .or_insert_with(|| serde_json::json!({}))
504 .as_object_mut()
505 .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
506 .insert(
507 "program_changed_since_active".into(),
508 serde_json::Value::Bool(true),
509 );
510 }
511 }
512 }
513 let reviewed = match record {
514 ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
515 ReviewRecord::Copied(Some(copied)) => {
516 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
517 None
518 }
519 ReviewRecord::Reviewed(reviewed) => Some(reviewed),
520 };
521 if let Some(reviewed) = reviewed {
522 let mut record = if replaces_programs {
523 reviewed_build::recorded(store.body()?)?
524 } else {
525 BTreeMap::new()
526 };
527 let present = candidate.modules();
528 record.retain(|module, _| present.contains(module));
529 for module in reviewed {
530 let program = if replaces_programs {
535 match reviewed_build::active(store.body()?, module)? {
536 Some(active) => active,
537 None => reviewed_build::identity(&approved, module),
538 }
539 } else {
540 reviewed_build::identity(&candidate, module)
541 };
542 if let Some(previous) = record.get(module).filter(|previous| **previous != program)
543 {
544 if projects.is_some() {
545 user_modules.insert(module.clone());
546 }
547 changeset.policy_changes.push(serde_json::json!({
548 "module_id": module,
549 "path": "reviewed_program",
550 "old": previous,
551 "new": program,
552 "reason": "approved configuration re-reviewed by the module's newly approved program",
553 }));
554 }
555 record.insert(module.clone(), program);
556 }
557 changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
558 }
559 apply::bind_plan(&mut changeset)?;
560 if let Some(edit) = &edits {
561 changeset.apply_plan["edit_plan"] = serde_json::json!({
562 "unstamped": edit.unstamped,
563 "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
564 });
565 if !edit.refusals.is_empty() {
566 changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
569 }
570 }
571 let mut modules = user_modules.clone();
572 modules.extend(changed.iter().filter_map(|key| match key {
573 InputKey::ProjectTuple { module, .. } => Some(module.clone()),
574 _ => None,
575 }));
576 if let Some(projects) = &projects {
577 modules.extend(projects.tuples.keys().map(|tuple| tuple.module.clone()));
578 }
579 let inputs = observed.read_set(&modules)?;
580 let (delivery, project_files) = if let Some(projects) = projects {
581 let body = if recovery { None } else { Some(store.body()?) };
582 let (delivery, files) = projects.bind(body, &inputs, &mut changeset, &user_modules)?;
583 if recovery && !files.is_empty() {
584 return Err(GateError::new(
585 "apply_plan_invalid",
586 "recovery cannot approve project file write-back",
587 ));
588 }
589 (Some(delivery), files)
590 } else {
591 (None, Vec::new())
592 };
593 let mut plan = Plan::new(
594 base_revision,
595 base_generation,
596 &self.incarnation,
597 inputs,
598 changeset,
599 );
600 plan.active_generations = active;
601 targets::checked(&plan)?;
602 let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
603 if let Some(edit) = &edits {
604 view.refusals = edit.refusals.clone();
605 }
606 self.next_plan_sequence = self
607 .next_plan_sequence
608 .checked_add(1)
609 .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
610 self.plans.insert(
611 view.digest.clone(),
612 PendingPlan {
613 creation_sequence: self.next_plan_sequence,
614 edits,
615 development_approval: None,
616 view: view.clone(),
617 kind,
618 snapshot: candidate,
619 modules,
620 changed,
621 callosum_entry_changed,
622 recovery,
623 delivery,
624 project_files,
625 project_capture: None,
626 },
627 );
628 Ok(view)
629 }
630
631 fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
632 let plan = self
633 .plans
634 .get(digest)
635 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
636 Ok(plan
637 .snapshot
638 .inputs
639 .keys()
640 .filter(|key| {
641 key.is_program()
642 && key
643 .module()
644 .is_some_and(|module| plan.modules.contains(module))
645 })
646 .cloned()
647 .collect())
648 }
649
650 pub(crate) fn bind_delivery(
654 &mut self,
655 digest: &Digest,
656 mut delivery: crate::config_store::DeliverySnapshot,
657 ) -> Result<()> {
658 let plan = self
659 .plans
660 .get_mut(digest)
661 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
662 if let Some(projects) = &plan.delivery {
663 for (module, declaration) in &projects.declarations {
664 if delivery
665 .declarations
666 .get(module)
667 .is_some_and(|user| user != declaration)
668 {
669 return Err(GateError::new(
670 "apply_plan_invalid",
671 "user and project views name different declarations of the same module",
672 ));
673 }
674 delivery
675 .declarations
676 .insert(module.clone(), declaration.clone());
677 }
678 delivery.project_views.clone_from(&projects.project_views);
679 delivery
680 .project_cutoffs
681 .clone_from(&projects.project_cutoffs);
682 delivery
683 .project_approval_digests
684 .clone_from(&projects.project_approval_digests);
685 }
686 plan.delivery = Some(delivery);
687 Ok(())
688 }
689
690 pub fn rollback(
696 &mut self,
697 store: &mut ConfigStore,
698 generation: u64,
699 observed: &GateSnapshot,
700 current_programs: &GateSnapshot,
701 review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
702 ) -> Result<ConfigPlanView> {
703 let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
704 runtime::policy_root::preserve_root_on_rollback(store.body()?, generation, &mut target)?;
705 target.inputs.retain(|key, _| !key.is_project());
706 target.restore_programs_from(current_programs)?;
707 let copied = store
708 .body()?
709 .generations
710 .get(&generation)
711 .and_then(|entry| {
712 entry
713 .generation
714 .changeset
715 .apply_plan
716 .get(reviewed_build::REVIEWED_PROGRAMS)
717 })
718 .cloned();
719 self.plan_reviewed(
720 store,
721 PlanKind::Rollback(generation),
722 target,
723 observed,
724 ReviewRecord::Copied(copied),
725 review,
726 )
727 }
728
729 fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
730 plan.targets()?;
731 let status = store.status();
732 let recovery = matches!(
733 status.state,
734 StoreState::StoreUnverified | StoreState::StoreMissing
735 );
736 if recovery != plan.recovery {
737 return Err(GateError::stale());
738 }
739 let base = if recovery {
740 0
741 } else {
742 store.delivery_ready()?;
743 store.body()?.base_revision
744 };
745 plan.view
746 .plan
747 .check_fresh(base, ¤t.read_set(&plan.modules)?)
748 .map_err(|_| {
749 if plan.project_capture.is_some() {
750 capture_plan::changed()
751 } else {
752 GateError::stale()
753 }
754 })
755 }
756
757 #[allow(clippy::too_many_arguments)]
758 fn commit(
759 &mut self,
760 digest: &Digest,
761 approval_channel: subc_config::ApprovalChannel,
762 store: &mut ConfigStore,
763 current: &GateSnapshot,
764 now_ms: u64,
765 before_publication: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
766 ) -> Result<u64> {
767 let plan = self
768 .plans
769 .get(digest)
770 .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
771 Self::fresh(plan, store, current)?;
772 let mut generation = Generation::new(
773 0,
774 approval_channel,
775 digest.clone(),
776 plan.view.plan.input_vector.clone(),
777 plan.view.plan.changeset.clone(),
778 );
779 let declarations_only = plan.development_approval.is_some();
780 generation.active_generations = plan.view.plan.active_generations.clone();
781 let tuples = plan.targets()?;
782 for tuple in &tuples {
783 let module = &tuple.module;
784 if tuple.project.is_none() {
785 generation
786 .module_states
787 .insert(module.clone(), subc_config::GenerationState::Pending);
788 }
789 if let Some(CapturedInput {
790 state: subc_config::InputState::Present { digest },
791 ..
792 }) = plan
793 .snapshot
794 .inputs
795 .get(&InputKey::Declaration(module.clone()))
796 {
797 generation
798 .declaration_digests
799 .insert(module.clone(), digest.clone());
800 }
801 }
802 let snapshot = plan.snapshot.to_store()?;
803 let mut entry = HistoryEntry {
804 generation,
805 kind: if declarations_only {
806 CommitKind::DeclarationApproval
807 } else {
808 plan.kind.commit_kind()
809 },
810 approval_id: digest.to_string(),
811 outcome: "approved".into(),
812 tuples,
813 project_outcomes: BTreeMap::new(),
814 configuration: snapshot.clone(),
815 delivery: plan.delivery.clone(),
816 };
817 let base_before = store.status().base_revision;
818 let mut observed = current.clone();
819 if !plan.recovery {
820 let body = store.body()?;
821 let previous = body.observed.as_ref().unwrap_or(&body.approved);
822 let previous = GateSnapshot::from_store(previous)?;
823 observed.inputs.retain(|key, _| !key.is_project());
826 observed.carry_project_inputs(&previous);
827 observed.carry_project_inputs(&plan.snapshot);
828 if let Some(capture) = &plan.project_capture {
829 observed
830 .inputs
831 .extend(capture.edit_observations.inputs.clone());
832 for (key, input) in &plan.snapshot.inputs {
833 if matches!(key, InputKey::ProjectTuple { .. }) {
834 observed.inputs.insert(key.clone(), input.clone());
835 }
836 }
837 for key in observed.inputs.keys().cloned().collect::<Vec<_>>() {
838 if matches!(&key, InputKey::Layer { module, .. } if capture.held_user.contains(module))
839 {
840 if let Some(input) = previous.inputs.get(&key) {
841 observed.inputs.insert(key, input.clone());
842 } else {
843 observed.inputs.remove(&key);
844 }
845 }
846 }
847 }
848 }
849 let observed = observed.to_store()?;
850 if let Some(checkpoint) = before_publication()? {
851 entry.generation.changeset.apply_plan[crate::policy_root::ledger::CHECKPOINT_FIELD] =
854 serde_json::to_value(checkpoint).map_err(GateError::invalid)?;
855 }
856 let result = if plan.recovery {
857 store.recovery_exit(entry, snapshot, now_ms)
858 } else {
859 store.commit_generation_with_project_files(
860 entry,
861 snapshot,
862 observed,
863 plan.project_files.clone(),
864 now_ms,
865 )
866 };
867 if result.is_ok() || store.status().base_revision != base_before {
871 self.plans.remove(digest);
872 }
873 let id = result?;
874 store.delivery_ready()?;
875 Ok(id)
876 }
877}
878
879mod registration;
880#[cfg(test)]
881mod tests;