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