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