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