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