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