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