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