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