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        if let Some(edit) = &edits {
694            view.refusals = edit.refusals.clone();
695        }
696        if self.plans.get(&view.digest).is_some_and(|plan| {
697            plan.kept_after_refused_decline || plan.decline_accepted || plan.restoring
698        }) {
699            return Err(GateError::new(
700                "settings_decline_kept",
701                "the declined settings plan is waiting for a manual restore",
702            ));
703        }
704        if settings_file_witness.is_some()
705            && self
706                .plans
707                .get(&view.digest)
708                .is_some_and(|plan| plan.settings_attempt_owner.is_some())
709            && self.has_open_approval(&view.digest)
710        {
711            return Err(GateError::new(
712                "config_busy",
713                "a settings approval already owns this plan",
714            ));
715        }
716        self.next_plan_sequence = self
717            .next_plan_sequence
718            .checked_add(1)
719            .ok_or_else(|| GateError::new("config_busy", "plan creation sequence exhausted"))?;
720        self.plans.insert(
721            view.digest.clone(),
722            PendingPlan {
723                settings_attempt_owner: None,
724                kept_after_refused_decline: false,
725                decline_accepted: false,
726                restoring: false,
727                restored_paths: BTreeSet::new(),
728                user_restore: BTreeMap::new(),
729                settings_users: None,
730                settings_file_witness,
731                creation_sequence: self.next_plan_sequence,
732                edits,
733                development_approval: None,
734                view: view.clone(),
735                kind,
736                snapshot: candidate,
737                modules,
738                changed,
739                callosum_entry_changed,
740                recovery,
741                delivery,
742                project_files,
743                project_capture: None,
744            },
745        );
746        Ok(view)
747    }
748
749    fn plan_program_keys(&self, digest: &Digest) -> Result<Vec<InputKey>> {
750        let plan = self
751            .plans
752            .get(digest)
753            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
754        Ok(plan
755            .snapshot
756            .inputs
757            .keys()
758            .filter(|key| {
759                key.is_program()
760                    && key
761                        .module()
762                        .is_some_and(|module| plan.modules.contains(module))
763            })
764            .cloned()
765            .collect())
766    }
767
768    /// Attach daemon-reviewed raw inputs without exposing them in diagnostic
769    /// plans. The saved file identities and byte digests still bind the bytes
770    /// captured for review.
771    pub(crate) fn bind_delivery(
772        &mut self,
773        digest: &Digest,
774        mut delivery: crate::config_store::DeliverySnapshot,
775    ) -> Result<()> {
776        let plan = self
777            .plans
778            .get_mut(digest)
779            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
780        if let Some(projects) = &plan.delivery {
781            for (module, declaration) in &projects.declarations {
782                if delivery
783                    .declarations
784                    .get(module)
785                    .is_some_and(|user| user != declaration)
786                {
787                    return Err(GateError::new(
788                        "apply_plan_invalid",
789                        "user and project views name different declarations of the same module",
790                    ));
791                }
792                delivery
793                    .declarations
794                    .insert(module.clone(), declaration.clone());
795            }
796            delivery.project_views.clone_from(&projects.project_views);
797            delivery
798                .project_cutoffs
799                .clone_from(&projects.project_cutoffs);
800            delivery
801                .project_approval_digests
802                .clone_from(&projects.project_approval_digests);
803        }
804        plan.delivery = Some(delivery);
805        Ok(())
806    }
807
808    /// Capture program identities for the reverse configuration's launch specs
809    /// at the restored paths at plan time. No executable bytes or historical
810    /// identities are restored. The restored generation's reviewed-program
811    /// record is copied: its reviewers are known. If that generation has no
812    /// record, the rollback has none either, so its modules owe re-review.
813    pub fn rollback(
814        &mut self,
815        store: &mut ConfigStore,
816        generation: u64,
817        observed: &GateSnapshot,
818        current_programs: &GateSnapshot,
819        review: impl FnOnce(&GateSnapshot, &GateSnapshot) -> Result<Changeset>,
820    ) -> Result<ConfigPlanView> {
821        let mut target = GateSnapshot::from_store(&store.rollback_configuration(generation)?)?;
822        runtime::policy_root::preserve_root_on_rollback(store.body()?, generation, &mut target)?;
823        target.inputs.retain(|key, _| !key.is_project());
824        target.restore_programs_from(current_programs)?;
825        let copied = store
826            .body()?
827            .generations
828            .get(&generation)
829            .and_then(|entry| {
830                entry
831                    .generation
832                    .changeset
833                    .apply_plan
834                    .get(reviewed_build::REVIEWED_PROGRAMS)
835            })
836            .cloned();
837        self.plan_reviewed(
838            store,
839            PlanKind::Rollback(generation),
840            target,
841            observed,
842            ReviewRecord::Copied(copied),
843            review,
844        )
845    }
846
847    fn fresh(plan: &PendingPlan, store: &mut ConfigStore, current: &GateSnapshot) -> Result<()> {
848        plan.targets()?;
849        let status = store.status();
850        let recovery = matches!(
851            status.state,
852            StoreState::StoreUnverified | StoreState::StoreMissing
853        );
854        if recovery != plan.recovery {
855            return Err(GateError::stale());
856        }
857        let base = if recovery {
858            0
859        } else {
860            store.delivery_ready()?;
861            store.body()?.base_revision
862        };
863        let mut inputs = current.read_set(&plan.modules)?;
864        // Before publication, the registry reopens each reviewed workspace
865        // file. That filesystem work must not hold the owner mutex.
866        add_settings_file_witness(&mut inputs, plan.settings_file_witness.as_ref());
867        plan.view.plan.check_fresh(base, &inputs).map_err(|_| {
868            if plan.project_capture.is_some() {
869                capture_plan::changed()
870            } else {
871                GateError::stale()
872            }
873        })
874    }
875
876    #[allow(clippy::too_many_arguments)]
877    fn commit(
878        &mut self,
879        digest: &Digest,
880        approval_channel: subc_config::ApprovalChannel,
881        store: &mut ConfigStore,
882        current: &GateSnapshot,
883        now_ms: u64,
884        before_publication: impl FnOnce() -> Result<Option<crate::policy_root::ledger::Checkpoint>>,
885    ) -> Result<u64> {
886        let plan = self
887            .plans
888            .get(digest)
889            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or already applied"))?;
890        Self::fresh(plan, store, current)?;
891        let mut generation = Generation::new(
892            0,
893            approval_channel,
894            digest.clone(),
895            plan.view.plan.input_vector.clone(),
896            plan.view.plan.changeset.clone(),
897        );
898        let declarations_only = plan.development_approval.is_some();
899        generation.active_generations = plan.view.plan.active_generations.clone();
900        let tuples = plan.targets()?;
901        for tuple in &tuples {
902            let module = &tuple.module;
903            if tuple.project.is_none() {
904                generation
905                    .module_states
906                    .insert(module.clone(), subc_config::GenerationState::Pending);
907            }
908            if let Some(CapturedInput {
909                state: subc_config::InputState::Present { digest },
910                ..
911            }) = plan
912                .snapshot
913                .inputs
914                .get(&InputKey::Declaration(module.clone()))
915            {
916                generation
917                    .declaration_digests
918                    .insert(module.clone(), digest.clone());
919            }
920        }
921        let snapshot = plan.snapshot.to_store()?;
922        let mut entry = HistoryEntry {
923            generation,
924            kind: if declarations_only {
925                CommitKind::DeclarationApproval
926            } else {
927                plan.kind.commit_kind()
928            },
929            approval_id: digest.to_string(),
930            outcome: "approved".into(),
931            tuples,
932            project_outcomes: BTreeMap::new(),
933            configuration: snapshot.clone(),
934            delivery: plan.delivery.clone(),
935        };
936        let base_before = store.status().base_revision;
937        let mut observed = current.clone();
938        if !plan.recovery {
939            let body = store.body()?;
940            let previous = body.observed.as_ref().unwrap_or(&body.approved);
941            let previous = GateSnapshot::from_store(previous)?;
942            if plan.settings_users.is_some() {
943                // The scoped read set intentionally never opens unrelated
944                // inputs. Keep their last observed proposals, not the approved
945                // values that the staged generation carries forward.
946                observed = previous.clone();
947                for key in &plan.changed {
948                    if let Some(input) = plan.snapshot.inputs.get(key) {
949                        observed.inputs.insert(key.clone(), input.clone());
950                    }
951                }
952            }
953            // Project file observations are maintained by the project capture,
954            // not by the user-only file capturer. Keep deferred observations.
955            observed.inputs.retain(|key, _| !key.is_project());
956            observed.carry_project_inputs(&previous);
957            observed.carry_project_inputs(&plan.snapshot);
958            if let Some(capture) = &plan.project_capture {
959                observed
960                    .inputs
961                    .extend(capture.edit_observations.inputs.clone());
962                for (key, input) in &plan.snapshot.inputs {
963                    if matches!(key, InputKey::ProjectTuple { .. }) {
964                        observed.inputs.insert(key.clone(), input.clone());
965                    }
966                }
967                for key in observed.inputs.keys().cloned().collect::<Vec<_>>() {
968                    if matches!(&key, InputKey::Layer { module, .. } if capture.held_user.contains(module))
969                    {
970                        if let Some(input) = previous.inputs.get(&key) {
971                            observed.inputs.insert(key, input.clone());
972                        } else {
973                            observed.inputs.remove(&key);
974                        }
975                    }
976                }
977            }
978        }
979        let observed = observed.to_store()?;
980        if let Some(checkpoint) = before_publication()? {
981            // This is a publication receipt, not a change to the reviewed
982            // inputs: it describes the ledger after the durable append.
983            entry.generation.changeset.apply_plan[crate::policy_root::ledger::CHECKPOINT_FIELD] =
984                serde_json::to_value(checkpoint).map_err(GateError::invalid)?;
985        }
986        let result = if plan.recovery {
987            store.recovery_exit(entry, snapshot, now_ms)
988        } else {
989            store.commit_generation_with_project_files(
990                entry,
991                snapshot,
992                observed,
993                plan.project_files.clone(),
994                now_ms,
995            )
996        };
997        // The sealed store's external revision/digest anchor may fail to update
998        // after a durable commit. The committed base makes the old plan stale;
999        // never repeat that generation while retrying the anchor update.
1000        if result.is_ok() || store.status().base_revision != base_before {
1001            self.expire_plan(digest);
1002        }
1003        let id = result?;
1004        store.delivery_ready()?;
1005        Ok(id)
1006    }
1007}
1008
1009mod registration;
1010
1011fn add_settings_file_witness(inputs: &mut subc_config::InputVector, witness: Option<&Digest>) {
1012    if let Some(digest) = witness {
1013        inputs.inputs.insert(
1014            "settings-files".into(),
1015            subc_config::InputState::Present {
1016                digest: digest.clone(),
1017            },
1018        );
1019    }
1020}
1021#[cfg(test)]
1022mod tests;