Skip to main content

subc_daemon/config_gate/
mod.rs

1//! Immutable config planning and approval, independent of transport dispatch.
2//!
3//! The daemon owner captures files, validates schemas/bounds and runs module
4//! review before handing snapshots here. It serializes this engine with the
5//! store and supervisor commit locks, recaptures files at completion, and uses
6//! only the committed snapshot for delivery. No client text is approval input.
7
8mod 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
28/// The settings edit base advances only when a retained generation names the module.
29pub(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    // Observational retries must not also retry stale review or plan decisions
74    // just because those refusals use the same wire code and message.
75    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
115/// The supervisor's program-admission adapter supplies this authority. A module
116/// registration and a schema declaration alone never admit its running code.
117pub 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
134/// Which build each module's approved configuration was reviewed by, as a
135/// plan writes it into its generation.
136pub(crate) enum ReviewRecord<'a> {
137    /// Write no record. Later plans then treat every module this plan approves
138    /// as owing a re-review.
139    Absent,
140    /// These modules' admitted reviewers answered `config.review` for this
141    /// plan. Their builds are recorded; other modules keep their entries from
142    /// the newest approved generation.
143    Reviewed(&'a BTreeSet<String>),
144    /// Copy a record verbatim, for a rollback to a generation whose reviewers
145    /// are known. `None` (that generation had no record) writes none.
146    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        // Approving more provider declarations for a development build does
187        // not start config delivery. The module read set still detects changes
188        // while the operator reviews those declarations.
189        Ok(if self.development_approval.is_some() {
190            BTreeSet::new()
191        } else {
192            targets
193        })
194    }
195}
196
197/// Memory-only plans cannot be replayed across a daemon restart. A successful
198/// generation commit changes the base revision and consumes its approval once.
199pub 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| plan.edits.is_none() && plan.modules.contains(module))
212            .max_by_key(|plan| plan.creation_sequence)
213            .map(|plan| plan.view.digest.clone())
214    }
215
216    pub(crate) fn plan_modules(&self, digest: &Digest) -> Result<BTreeSet<String>> {
217        self.plans
218            .get(digest)
219            .map(|plan| plan.modules.clone())
220            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))
221    }
222
223    pub(crate) fn cancel_attempt(&mut self, attempt: u64) {
224        self.attempts.remove(&attempt);
225    }
226
227    pub(crate) fn expire_plan(&mut self, digest: &Digest) -> bool {
228        self.plans.remove(digest).is_some()
229    }
230    pub fn new(incarnation: String) -> Self {
231        Self {
232            incarnation,
233            plans: BTreeMap::new(),
234            attempts: BTreeMap::new(),
235            next_attempt: 0,
236            next_plan_sequence: 0,
237        }
238    }
239
240    /// `review` enforces the approved schema and every affected project's bounds
241    /// before asking admitted module reviewers. Refusals produce no plan.
242    pub fn plan(
243        &mut self,
244        store: &mut ConfigStore,
245        kind: PlanKind,
246        candidate: GateSnapshot,
247        observed: &GateSnapshot,
248        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
249    ) -> Result<ConfigPlanView> {
250        self.plan_reviewed(
251            store,
252            kind,
253            candidate,
254            observed,
255            ReviewRecord::Absent,
256            review,
257        )
258    }
259
260    /// As [`Self::plan`], also writing the record of which build each module's
261    /// approved configuration was reviewed by. A generation planned without that
262    /// record vouches for no review, so later plans treat each module it
263    /// approved as needing re-review.
264    pub(crate) fn plan_reviewed(
265        &mut self,
266        store: &mut ConfigStore,
267        kind: PlanKind,
268        candidate: GateSnapshot,
269        observed: &GateSnapshot,
270        record: ReviewRecord<'_>,
271        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
272    ) -> Result<ConfigPlanView> {
273        self.plan_reviewed_inner(store, kind, candidate, observed, record, None, None, review)
274    }
275
276    #[allow(clippy::too_many_arguments)]
277    fn plan_reviewed_inner(
278        &mut self,
279        store: &mut ConfigStore,
280        kind: PlanKind,
281        mut candidate: GateSnapshot,
282        observed: &GateSnapshot,
283        record: ReviewRecord<'_>,
284        edits: Option<runtime::edits::EditPlan>,
285        projects: Option<targets::ProjectReviews>,
286        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
287    ) -> Result<ConfigPlanView> {
288        let status = store.status();
289        let recovery = matches!(
290            status.state,
291            StoreState::StoreUnverified | StoreState::StoreMissing
292        );
293        if (recovery && !matches!(kind, PlanKind::Stamp | PlanKind::Unstamp))
294            || (status.state == StoreState::Unstamped && kind != PlanKind::Stamp && edits.is_none())
295        {
296            return Err(GateError::new(
297                "config_gated",
298                "stamp is required before planning changes",
299            ));
300        }
301        if self.plans.len() >= 64 {
302            return Err(GateError::new("config_busy", "too many pending plans"));
303        }
304        let mut rollback_programs = Vec::new();
305        if let PlanKind::Rollback(id) = kind {
306            let mut target = GateSnapshot::from_store(&store.rollback_configuration(id)?)?;
307            runtime::policy_root::preserve_root_on_rollback(store.body()?, id, &mut target)?;
308            if target
309                .inputs
310                .iter()
311                .filter(|(key, _)| !key.is_program() && !key.is_project())
312                .ne(candidate
313                    .inputs
314                    .iter()
315                    .filter(|(key, _)| !key.is_program() && !key.is_project()))
316            {
317                return Err(GateError::invalid(
318                    "rollback must reverse the target configuration",
319                ));
320            }
321            for (key, now) in candidate.inputs.iter().filter(|(key, _)| key.is_program()) {
322                if target.inputs.get(key) != Some(now) {
323                    rollback_programs.push(serde_json::json!({
324                        "module_id":key.module(),
325                        "input":key,
326                        "reason":"program changed since that version",
327                        "approved_then":target.inputs.get(key),
328                        "on_disk_now":now,
329                    }));
330                }
331            }
332        }
333        let (base_revision, base_generation, approved, active) =
334            if let Some(edit) = edits.as_ref().filter(|edit| edit.unstamped) {
335                (
336                    status.base_revision,
337                    0,
338                    edit.baseline.clone(),
339                    BTreeMap::new(),
340                )
341            } else if recovery {
342                (0, 0, GateSnapshot::default(), BTreeMap::new())
343            } else {
344                store.delivery_ready()?;
345                let body = store.body()?;
346                let active = body
347                    .versions
348                    .iter()
349                    .filter_map(|(tuple, versions)| {
350                        versions
351                            .active
352                            .map(|id| (serde_json::to_string(tuple).expect("tuple"), id))
353                    })
354                    .collect();
355                (
356                    body.base_revision,
357                    body.last_generation,
358                    GateSnapshot::from_store(&body.approved)?,
359                    active,
360                )
361            };
362        if !recovery {
363            candidate.carry_project_inputs(&approved);
364        }
365        if status.state == StoreState::Stamped
366            && kind == PlanKind::Change
367            && edits.as_ref().is_none_or(|edit| edit.policy_root.is_none())
368            && runtime::policy_root::section_value(&candidate)
369                != runtime::policy_root::section_value(&approved)
370        {
371            return Err(GateError::new(
372                "value_invalid",
373                "use a policy_root operation to change the stamped agent policy trust root",
374            ));
375        }
376        let changed: BTreeSet<InputKey> = approved
377            .changed_keys(&candidate)
378            .into_iter()
379            .cloned()
380            .collect();
381        let callosum_entry_changed = if changed.contains(&InputKey::Daemon) {
382            match (
383                approved.inputs.get(&InputKey::Daemon),
384                candidate.inputs.get(&InputKey::Daemon),
385            ) {
386                (
387                    Some(CapturedInput {
388                        value: subc_config::RecordedValue::Value { value: old },
389                        ..
390                    }),
391                    Some(CapturedInput {
392                        value: subc_config::RecordedValue::Value { value: new },
393                        ..
394                    }),
395                ) => old.pointer("/modules/callosum") != new.pointer("/modules/callosum"),
396                _ => true,
397            }
398        } else {
399            false
400        };
401        let mut user_modules: BTreeSet<String> = changed
402            .iter()
403            .filter(|key| !key.is_project())
404            .filter_map(|key| key.module().map(str::to_owned))
405            .collect();
406        let mut changeset = review(&approved, &candidate)?;
407        for difference in &rollback_programs {
408            if let Some(module) = difference["module_id"].as_str() {
409                user_modules.insert(module.to_owned());
410                changeset
411                    .launch_manifests
412                    .entry(module.to_owned())
413                    .or_insert_with(|| serde_json::json!({}))
414                    .as_object_mut()
415                    .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
416                    .insert(
417                        "program_changed_since_target".into(),
418                        serde_json::Value::Bool(true),
419                    );
420            }
421        }
422        user_modules.extend(
423            changeset
424                .fields
425                .iter()
426                .filter(|field| field.project_id.is_none())
427                .map(|field| field.module_id.clone()),
428        );
429        user_modules.extend(changeset.launch_manifests.keys().cloned());
430        if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
431            user_modules.extend(
432                observed
433                    .inputs
434                    .keys()
435                    .chain(approved.inputs.keys())
436                    .filter(|key| !key.is_project())
437                    .filter_map(|key| key.module().map(str::to_owned)),
438            );
439        }
440        // Bind the full retained view and operation, including identity-only and
441        // declaration-only changes a module's scalar diff would not describe.
442        // Keep activation policy out of reviewer metadata. `small_prompt` in
443        // approval.rs offers the compact one-change prompt only when `review`
444        // is null, so leaving the transition table in it would deny that
445        // prompt to every one-field change.
446        let transitions = changeset
447            .apply_plan
448            .as_object_mut()
449            .and_then(|review| review.remove("module_transitions"));
450        if transitions.is_some()
451            && changeset
452                .apply_plan
453                .as_object()
454                .is_some_and(|review| review.is_empty())
455        {
456            changeset.apply_plan = serde_json::Value::Null;
457        }
458        changeset.apply_plan = serde_json::json!({
459            "operation": match kind { PlanKind::Change => "change", PlanKind::Stamp => "stamp", PlanKind::Unstamp => "unstamp", PlanKind::Rollback(_) => "rollback" },
460            "rollback_to": if let PlanKind::Rollback(id) = kind { Some(id) } else { None },
461            "review": changeset.apply_plan,
462            "previous": approved.to_store()?,
463            "snapshot": candidate.to_store()?,
464        });
465        if let Some(mut transitions) = transitions {
466            if let Some(table) = transitions.as_object_mut() {
467                if projects.is_some() {
468                    table.retain(|module, _| user_modules.contains(module));
469                } else {
470                    user_modules.extend(table.keys().cloned());
471                }
472            }
473            changeset.apply_plan["module_transitions"] = transitions;
474        }
475        if matches!(kind, PlanKind::Rollback(_)) {
476            changeset.apply_plan["rollback_programs"] = serde_json::Value::Array(rollback_programs);
477        }
478        let replaces_programs =
479            !recovery && matches!(kind, PlanKind::Change | PlanKind::Rollback(_));
480        if replaces_programs {
481            // A module whose active generation ran an older program than this
482            // plan's (an earlier program change not yet active, say) still has
483            // that older process running. It must not acknowledge this
484            // generation either, even though the program matches the last
485            // approval.
486            let body = store.body()?;
487            for module in &user_modules {
488                if reviewed_build::active(body, module)?
489                    .is_some_and(|active| active != reviewed_build::identity(&candidate, module))
490                {
491                    changeset
492                        .launch_manifests
493                        .entry(module.clone())
494                        .or_insert_with(|| serde_json::json!({}))
495                        .as_object_mut()
496                        .ok_or_else(|| GateError::invalid("launch manifest must be an object"))?
497                        .insert(
498                            "program_changed_since_active".into(),
499                            serde_json::Value::Bool(true),
500                        );
501                }
502            }
503        }
504        let reviewed = match record {
505            ReviewRecord::Absent | ReviewRecord::Copied(None) => None,
506            ReviewRecord::Copied(Some(copied)) => {
507                changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = copied;
508                None
509            }
510            ReviewRecord::Reviewed(reviewed) => Some(reviewed),
511        };
512        if let Some(reviewed) = reviewed {
513            let mut record = if replaces_programs {
514                reviewed_build::recorded(store.body()?)?
515            } else {
516                BTreeMap::new()
517            };
518            let present = candidate.modules();
519            record.retain(|module, _| present.contains(module));
520            for module in reviewed {
521                // A stamp records the programs already running. Otherwise the
522                // reviewer is the process that acknowledged the active
523                // generation, or one admitted from the last approval when the
524                // module has never acknowledged one.
525                let program = if replaces_programs {
526                    match reviewed_build::active(store.body()?, module)? {
527                        Some(active) => active,
528                        None => reviewed_build::identity(&approved, module),
529                    }
530                } else {
531                    reviewed_build::identity(&candidate, module)
532                };
533                if let Some(previous) = record.get(module).filter(|previous| **previous != program)
534                {
535                    if projects.is_some() {
536                        user_modules.insert(module.clone());
537                    }
538                    changeset.policy_changes.push(serde_json::json!({
539                        "module_id": module,
540                        "path": "reviewed_program",
541                        "old": previous,
542                        "new": program,
543                        "reason": "approved configuration re-reviewed by the module's newly approved program",
544                    }));
545                }
546                record.insert(module.clone(), program);
547            }
548            changeset.apply_plan[reviewed_build::REVIEWED_PROGRAMS] = serde_json::json!(record);
549        }
550        apply::bind_plan(&mut changeset)?;
551        if let Some(edit) = &edits {
552            changeset.apply_plan["edit_plan"] = serde_json::json!({
553                "unstamped": edit.unstamped,
554                "write_back": edit.files.iter().map(runtime::edits::WriteBack::intent).collect::<Vec<_>>(),
555            });
556            if !edit.refusals.is_empty() {
557                // Keep refusals bound to the plan digest so apply can reject it;
558                // settings clients read the keyed rows from view.refusals.
559                changeset.apply_plan["edit_refusals"] = serde_json::json!(edit.refusals);
560            }
561        }
562        let mut modules = user_modules.clone();
563        modules.extend(changed.iter().filter_map(|key| match key {
564            InputKey::ProjectTuple { module, .. } => Some(module.clone()),
565            _ => None,
566        }));
567        if let Some(projects) = &projects {
568            modules.extend(projects.tuples.keys().map(|tuple| tuple.module.clone()));
569        }
570        let inputs = observed.read_set(&modules)?;
571        let (delivery, project_files) = if let Some(projects) = projects {
572            let body = if recovery { None } else { Some(store.body()?) };
573            let (delivery, files) = projects.bind(body, &inputs, &mut changeset, &user_modules)?;
574            if recovery && !files.is_empty() {
575                return Err(GateError::new(
576                    "apply_plan_invalid",
577                    "recovery cannot approve project file write-back",
578                ));
579            }
580            (Some(delivery), files)
581        } else {
582            (None, Vec::new())
583        };
584        let mut plan = Plan::new(
585            base_revision,
586            base_generation,
587            &self.incarnation,
588            inputs,
589            changeset,
590        );
591        plan.active_generations = active;
592        targets::checked(&plan)?;
593        let mut view = ConfigPlanView::new(plan).map_err(GateError::invalid)?;
594        if let Some(edit) = &edits {
595            view.refusals = edit.refusals.clone();
596        }
597        self.next_plan_sequence = self
598            .next_plan_sequence
599            .checked_add(1)
600            .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
601        self.plans.insert(
602            view.digest.clone(),
603            PendingPlan {
604                creation_sequence: self.next_plan_sequence,
605                edits,
606                development_approval: None,
607                view: view.clone(),
608                kind,
609                snapshot: candidate,
610                modules,
611                changed,
612                callosum_entry_changed,
613                recovery,
614                delivery,
615                project_files,
616                project_capture: None,
617            },
618        );
619        Ok(view)
620    }
621
622    fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
623        let plan = self
624            .plans
625            .get(digest)
626            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
627        Ok(plan
628            .snapshot
629            .inputs
630            .keys()
631            .filter(|key| {
632                key.is_program()
633                    && key
634                        .module()
635                        .is_some_and(|module| plan.modules.contains(module))
636            })
637            .cloned()
638            .collect())
639    }
640
641    /// Attach daemon-reviewed raw inputs without exposing them in diagnostic
642    /// plans. The saved file identities and byte digests still bind the bytes
643    /// captured for review.
644    pub(crate) fn bind_delivery(
645        &mut self,
646        digest: &Digest,
647        mut delivery: crate::config_store::DeliverySnapshot,
648    ) -> Result<()> {
649        let plan = self
650            .plans
651            .get_mut(digest)
652            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
653        if let Some(projects) = &plan.delivery {
654            for (module, declaration) in &projects.declarations {
655                if delivery
656                    .declarations
657                    .get(module)
658                    .is_some_and(|user| user != declaration)
659                {
660                    return Err(GateError::new(
661                        "apply_plan_invalid",
662                        "user and project views name different declarations of the same module",
663                    ));
664                }
665                delivery
666                    .declarations
667                    .insert(module.clone(), declaration.clone());
668            }
669            delivery.project_views.clone_from(&projects.project_views);
670            delivery
671                .project_cutoffs
672                .clone_from(&projects.project_cutoffs);
673            delivery
674                .project_approval_digests
675                .clone_from(&projects.project_approval_digests);
676        }
677        plan.delivery = Some(delivery);
678        Ok(())
679    }
680
681    /// Capture program identities for the reverse configuration's launch specs
682    /// at the restored paths at plan time. No executable bytes or historical
683    /// identities are restored. The restored generation's reviewed-program
684    /// record is copied: its reviewers are known. If that generation has no
685    /// record, the rollback has none either, so its modules owe re-review.
686    pub fn rollback(
687        &mut self,
688        store: &mut ConfigStore,
689        generation: u64,
690        observed: &GateSnapshot,
691        current_programs: &GateSnapshot,
692        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
693    ) -> Result<ConfigPlanView> {
694        let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
695        runtime::policy_root::preserve_root_on_rollback(store.body()?, generation, &mut target)?;
696        target.inputs.retain(|key, _| !key.is_project());
697        target.restore_programs_from(current_programs)?;
698        let copied = store
699            .body()?
700            .generations
701            .get(&generation)
702            .and_then(|entry| {
703                entry
704                    .generation
705                    .changeset
706                    .apply_plan
707                    .get(reviewed_build::REVIEWED_PROGRAMS)
708            })
709            .cloned();
710        self.plan_reviewed(
711            store,
712            PlanKind::Rollback(generation),
713            target,
714            observed,
715            ReviewRecord::Copied(copied),
716            review,
717        )
718    }
719
720    fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
721        plan.targets()?;
722        let status = store.status();
723        let recovery = matches!(
724            status.state,
725            StoreState::StoreUnverified | StoreState::StoreMissing
726        );
727        if recovery != plan.recovery {
728            return Err(GateError::stale());
729        }
730        let base = if recovery {
731            0
732        } else {
733            store.delivery_ready()?;
734            store.body()?.base_revision
735        };
736        plan.view
737            .plan
738            .check_fresh(base, &current.read_set(&plan.modules)?)
739            .map_err(|_| {
740                if plan.project_capture.is_some() {
741                    capture_plan::changed()
742                } else {
743                    GateError::stale()
744                }
745            })
746    }
747
748    #[allow(clippy::too_many_arguments)]
749    fn commit(
750        &mut self,
751        digest: &Digest,
752        approval_channel: subc_config::ApprovalChannel,
753        store: &mut ConfigStore,
754        current: &GateSnapshot,
755        now_ms: u64,
756        before_publication: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
757    ) -> Result<u64> {
758        let plan = self
759            .plans
760            .get(digest)
761            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
762        Self::fresh(plan, store, current)?;
763        let mut generation = Generation::new(
764            0,
765            approval_channel,
766            digest.clone(),
767            plan.view.plan.input_vector.clone(),
768            plan.view.plan.changeset.clone(),
769        );
770        let declarations_only = plan.development_approval.is_some();
771        generation.active_generations = plan.view.plan.active_generations.clone();
772        let tuples = plan.targets()?;
773        for tuple in &tuples {
774            let module = &tuple.module;
775            if tuple.project.is_none() {
776                generation
777                    .module_states
778                    .insert(module.clone(), subc_config::GenerationState::Pending);
779            }
780            if let Some(CapturedInput {
781                state: subc_config::InputState::Present { digest },
782                ..
783            }) = plan
784                .snapshot
785                .inputs
786                .get(&InputKey::Declaration(module.clone()))
787            {
788                generation
789                    .declaration_digests
790                    .insert(module.clone(), digest.clone());
791            }
792        }
793        let snapshot = plan.snapshot.to_store()?;
794        let mut entry = HistoryEntry {
795            generation,
796            kind: if declarations_only {
797                CommitKind::DeclarationApproval
798            } else {
799                plan.kind.commit_kind()
800            },
801            approval_id: digest.to_string(),
802            outcome: "approved".into(),
803            tuples,
804            project_outcomes: BTreeMap::new(),
805            configuration: snapshot.clone(),
806            delivery: plan.delivery.clone(),
807        };
808        let base_before = store.status().base_revision;
809        let mut observed = current.clone();
810        if !plan.recovery {
811            let body = store.body()?;
812            let previous = body.observed.as_ref().unwrap_or(&body.approved);
813            let previous = GateSnapshot::from_store(previous)?;
814            // Project file observations are maintained by the project capture,
815            // not by the user-only file capturer. Keep deferred observations.
816            observed.inputs.retain(|key, _| !key.is_project());
817            observed.carry_project_inputs(&previous);
818            observed.carry_project_inputs(&plan.snapshot);
819            if let Some(capture) = &plan.project_capture {
820                observed
821                    .inputs
822                    .extend(capture.edit_observations.inputs.clone());
823                for (key, input) in &plan.snapshot.inputs {
824                    if matches!(key, InputKey::ProjectTuple { .. }) {
825                        observed.inputs.insert(key.clone(), input.clone());
826                    }
827                }
828                for key in observed.inputs.keys().cloned().collect::<Vec<_>>() {
829                    if matches!(&key, InputKey::Layer { module, .. } if capture.held_user.contains(module))
830                    {
831                        if let Some(input) = previous.inputs.get(&key) {
832                            observed.inputs.insert(key, input.clone());
833                        } else {
834                            observed.inputs.remove(&key);
835                        }
836                    }
837                }
838            }
839        }
840        let observed = observed.to_store()?;
841        if let Some(checkpoint) = before_publication()? {
842            // This is a publication receipt, not a change to the reviewed
843            // inputs: it describes the ledger after the durable append.
844            entry.generation.changeset.apply_plan[crate::policy_root::ledger::CHECKPOINT_FIELD] =
845                serde_json::to_value(checkpoint).map_err(GateError::invalid)?;
846        }
847        let result = if plan.recovery {
848            store.recovery_exit(entry, snapshot, now_ms)
849        } else {
850            store.commit_generation_with_project_files(
851                entry,
852                snapshot,
853                observed,
854                plan.project_files.clone(),
855                now_ms,
856            )
857        };
858        // The sealed store's external revision/digest anchor may fail to update
859        // after a durable commit. The committed base makes the old plan stale;
860        // never repeat that generation while retrying the anchor update.
861        if result.is_ok() || store.status().base_revision != base_before {
862            self.plans.remove(digest);
863        }
864        let id = result?;
865        store.delivery_ready()?;
866        Ok(id)
867    }
868}
869
870mod registration;
871#[cfg(test)]
872mod tests;