Skip to main content

subc_daemon/config_gate/
runtime.rs

1//! Serialized production owner for the approval engine and durable authority.
2
3use std::{
4    collections::{BTreeMap, BTreeSet, HashMap, VecDeque},
5    sync::Mutex,
6    time::{Duration, Instant},
7};
8
9use subc_config::{Changeset, Digest};
10use subc_control::config::ConfigPlanView;
11use subc_protocol::config::{
12    ConfigDeclareRequest, ConfigLayer, ConfigLayerSnapshot, ConfigStatus, ConfigView,
13};
14
15use super::{
16    capture::{CapturedConfiguration, ConfigCapturer},
17    capture_plan::{self, CapturePlan, ModuleRoots, ProjectCapture},
18    ApprovalChallenge, ApprovalFacts, ApprovalReply, ConfigGate, GateError, PlanKind, Result,
19};
20use crate::{
21    config_store::{ConfigStore, DeliverySnapshot, StoreActivity, StoreState},
22    ConnectionId,
23};
24
25#[path = "edits.rs"]
26pub(super) mod edits;
27#[path = "pending_settings.rs"]
28mod pending_settings;
29#[path = "policy_root.rs"]
30pub(super) mod policy_root;
31#[path = "runtime_project_edits.rs"]
32pub(super) mod project_edits;
33
34#[cfg(test)]
35pub(super) type ProjectWriteHook = std::sync::Arc<dyn Fn(bool) -> Result<()> + Send + Sync>;
36
37#[cfg(test)]
38type UserRestoreHook = std::sync::Arc<dyn Fn(&std::path::Path) -> Result<()> + Send + Sync>;
39
40#[cfg(test)]
41type RecoveryProbeHook = Box<dyn FnOnce() -> std::io::Result<()> + Send>;
42
43#[cfg(test)]
44type UserFileTestIdle =
45    tokio::sync::mpsc::UnboundedSender<(ConnectionId, tokio::sync::oneshot::Sender<()>)>;
46
47#[cfg(test)]
48pub(crate) type SettingsProjectionHook = Box<dyn FnMut() -> Result<()> + Send>;
49
50pub struct RuntimeOwner {
51    #[cfg(test)]
52    pub(crate) user_file_test_idle: Mutex<Option<UserFileTestIdle>>,
53    #[cfg(test)]
54    config_park_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
55    #[cfg(test)]
56    pub(crate) content_kill_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
57    #[cfg(test)]
58    polled_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
59    #[cfg(test)]
60    pub(crate) settings_projection_hook: Mutex<Option<SettingsProjectionHook>>,
61    #[cfg(test)]
62    pub(crate) settings_status_hook: Mutex<Option<SettingsProjectionHook>>,
63    #[cfg(test)]
64    pub(crate) settings_observation_hook: Mutex<Option<Box<dyn FnMut() + Send>>>,
65    #[cfg(test)]
66    polled_capture_count: std::sync::atomic::AtomicUsize,
67    #[cfg(test)]
68    census_probe: Mutex<Option<std::sync::Arc<dyn Fn() + Send + Sync>>>,
69    #[cfg(test)]
70    agent_validation_window: Mutex<Option<Duration>>,
71    #[cfg(test)]
72    pub(crate) warm_restart_pause: Mutex<Option<WarmRestartPause>>,
73    #[cfg(test)]
74    pub(crate) warm_restart_busy: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
75    #[cfg(test)]
76    pub(crate) swap_preflight_attempts: std::sync::atomic::AtomicUsize,
77    #[cfg(feature = "test-support")]
78    test_hooks: Option<crate::config_store::testing::TestSupport>,
79    #[cfg(test)]
80    spawn_exec_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
81    published: std::sync::RwLock<std::sync::Arc<Published>>,
82    /// Set after state that `published` derives from changed without an
83    /// `OwnerGuard` (a disconnect or cancellation taken with `try_lock`, or a
84    /// phone withdrawal ending). The next guard release republishes.
85    projection_stale: std::sync::atomic::AtomicBool,
86    #[cfg(test)]
87    projection_builds: std::sync::atomic::AtomicUsize,
88    #[cfg(test)]
89    owner_guards: std::sync::atomic::AtomicUsize,
90    /// Connections with a running `config.review` delivery worker. Closing
91    /// one must wake the delivery coordinator so it retires that worker.
92    config_workers: Mutex<std::collections::HashSet<ConnectionId>>,
93    configured_modules: std::sync::RwLock<Option<admission::ConfiguredModuleSnapshot>>,
94    inner: Mutex<OwnerState>,
95    capturer: ConfigCapturer,
96    settings_recovery_data: std::path::PathBuf,
97    settings_recovery_updates: std::sync::Arc<super::recovery_inventory::RecoveryLocks>,
98    #[cfg(test)]
99    recovery_probe_hook: Mutex<Option<RecoveryProbeHook>>,
100    #[cfg(test)]
101    after_settings_decline_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
102    user_file_refusals: Mutex<BTreeMap<String, subc_config::Digest>>,
103    policy_root_ledger: Option<std::path::PathBuf>,
104    policy_root_unstamped: Mutex<crate::policy_root::Section>,
105    #[cfg(test)]
106    policy_root_fail_after_append: std::sync::atomic::AtomicBool,
107    // Enable with the public project-settings capability. Until then an
108    // unscoped config.plan must not return project targets or diagnostics.
109    project_capture_enabled: bool,
110    settings_projects: settings::projects::ProjectObservations,
111    #[cfg(test)]
112    project_write_hook: std::sync::Mutex<Option<ProjectWriteHook>>,
113    #[cfg(test)]
114    user_restore_hook: Mutex<Option<UserRestoreHook>>,
115    #[cfg(test)]
116    after_restore_read_hook: Mutex<Option<UserRestoreHook>>,
117    pub(crate) settings_phone_delivery: tokio::sync::Mutex<()>,
118    settings_attempts_changed: tokio::sync::Notify,
119    settings_request_order: std::sync::atomic::AtomicU64,
120    phone_withdrawal_changed: tokio::sync::Notify,
121    #[cfg(test)]
122    project_write_waiter_done: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
123    #[cfg(test)]
124    trusted_review_connection_for_test: std::sync::Mutex<Option<crate::ConnectionId>>,
125    startup_overrides: Vec<String>,
126    module_gates: Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
127    delivery_changed: std::sync::Arc<tokio::sync::Notify>,
128    settings_changed: tokio::sync::watch::Sender<u64>,
129    route_policy_authority: std::sync::OnceLock<std::sync::Arc<dyn RoutePolicyAuthority>>,
130    mark_publisher: std::sync::OnceLock<std::sync::Arc<dyn mark::MarkPublisher>>,
131    binding_retirements: Mutex<BTreeMap<usize, Box<dyn Fn() + Send + Sync>>>,
132    canceled_approvals: Mutex<Vec<u64>>,
133    // Reader and Drop callbacks must not wait behind a keychain or disk check.
134    // These short queues/indexes never perform store I/O while locked.
135    approval_request_index: Mutex<HashMap<(ConnectionId, u64), std::sync::Arc<ApprovalRequest>>>,
136    disconnected_pending: Mutex<Vec<ConnectionId>>,
137    abandoned_spawns: Mutex<Vec<(DeliverySpawn, bool)>>,
138    phone_withdrawals: Mutex<phone::PhoneWithdrawals>,
139    #[cfg(any(test, feature = "test-support"))]
140    os_prompt_policy: std::sync::atomic::AtomicBool,
141    #[cfg(test)]
142    spawn_preflight_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
143    #[cfg(test)]
144    exit_record_attempts: std::sync::atomic::AtomicUsize,
145    #[cfg(test)]
146    phone_bind_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
147    #[cfg(test)]
148    begin_approval_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
149    #[cfg(test)]
150    begin_approval_completions: std::sync::atomic::AtomicUsize,
151    #[cfg(test)]
152    desktop_receipt_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
153    #[cfg(test)]
154    prepare_capture_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
155    #[cfg(all(test, unix))]
156    approval_claim_pause: Mutex<Option<ApprovalClaimPause>>,
157}
158
159#[cfg(any(target_os = "linux", target_os = "macos"))]
160impl RuntimeOwner {
161    pub(crate) fn upgrade_blocker(&self) -> Option<&'static str> {
162        let Ok(state) = self.inner.try_lock() else {
163            return Some("settings");
164        };
165        if state
166            .store
167            .loaded_admission_state()
168            .1
169            .daemon
170            .restart
171            .is_some()
172        {
173            return Some("shutdown");
174        }
175        (!state.gate.attempts.is_empty()).then_some("settings")
176    }
177}
178
179/// An in-memory cutover transaction. It is borrowed only for synchronous
180/// forwarding, registry and delivery-target publication under one module gate.
181pub(crate) struct SwapConfiguration<'a> {
182    owner: &'a RuntimeOwner,
183    state: OwnerGuard<'a>,
184}
185
186#[cfg(test)]
187pub(crate) struct WarmRestartPause {
188    pub(crate) reached: tokio::sync::oneshot::Sender<()>,
189    pub(crate) resume: tokio::sync::oneshot::Receiver<()>,
190}
191
192impl SwapConfiguration<'_> {
193    pub(crate) fn before_cutover(
194        &mut self,
195        module: &str,
196        connection: ConnectionId,
197        spawn: Option<&DeliverySpawn>,
198    ) -> Result<Option<u64>> {
199        match self.state.store.loaded_admission_state().0 {
200            StoreState::Unstamped => return Ok(None),
201            StoreState::Stamped => {}
202            _ => {
203                return Err(GateError::new(
204                    "config_gated",
205                    "configuration store is in recovery",
206                ))
207            }
208        }
209        let newer = RuntimeOwner::requires_fresher_spawn_loaded(&self.state, module, spawn)?;
210        if newer.is_none() {
211            self.owner.module_get_locked(
212                &mut self.state,
213                connection,
214                module,
215                subc_protocol::config::ConfigGetRequest::new(),
216                false,
217            )?;
218        }
219        Ok(newer)
220    }
221    pub(crate) fn promoted(
222        &mut self,
223        module: &str,
224        connection: ConnectionId,
225        at: tokio::time::Instant,
226    ) -> Result<()> {
227        RuntimeOwner::promote_loaded(&mut self.state, connection, module, at).map(|_| ())
228    }
229}
230
231#[cfg(all(test, unix))]
232struct ApprovalClaimPause {
233    reached: tokio::sync::oneshot::Sender<()>,
234    release: tokio::sync::oneshot::Receiver<()>,
235}
236
237/// The post-answer deadline can withdraw queued work, but never a publication
238/// that has crossed the final commit point while holding its owned gates.
239pub(crate) struct ApprovalCommitWindow {
240    pub deadline: tokio::time::Instant,
241    phase: std::sync::atomic::AtomicU8,
242}
243
244impl ApprovalCommitWindow {
245    pub(crate) fn new(deadline: tokio::time::Instant) -> Self {
246        Self {
247            deadline,
248            phase: std::sync::atomic::AtomicU8::new(0),
249        }
250    }
251
252    pub(crate) fn expire(&self) -> bool {
253        self.phase
254            .compare_exchange(
255                0,
256                2,
257                std::sync::atomic::Ordering::AcqRel,
258                std::sync::atomic::Ordering::Acquire,
259            )
260            .is_ok()
261    }
262
263    fn begin_publication(&self) -> Result<()> {
264        if tokio::time::Instant::now() >= self.deadline {
265            self.expire();
266            return Err(GateError::commit_timeout());
267        }
268        self.phase
269            .compare_exchange(
270                0,
271                1,
272                std::sync::atomic::Ordering::AcqRel,
273                std::sync::atomic::Ordering::Acquire,
274            )
275            .map(|_| ())
276            .map_err(|_| GateError::commit_timeout())
277    }
278}
279
280pub use route_policy::{
281    ApprovedRoutePolicy, RoutePolicyAuthority, RoutePolicyInstall, RoutePolicyInstallation,
282    RoutePolicyReceipt,
283};
284
285pub use delivery::{AppliedDisposition, DeliveryProbe, DeliverySpawn};
286
287/// Supervisor callbacks for the configuration delivery lifecycle. The caller
288/// supplies observed process events, never a module's claimed readiness.
289/// Target checks and promotion callbacks run under [`RuntimeOwner::module_gate`]
290/// across forwarding and registry changes. The spawn token binds a later
291/// registration to the approved generation and its original warm-up deadline.
292pub trait DeliveryObserver: Send + Sync {
293    fn spawned(
294        &self,
295        module: &str,
296        spawned_at: tokio::time::Instant,
297        register_timeout: std::time::Duration,
298        first_health_budget: std::time::Duration,
299    ) -> Result<Option<DeliverySpawn>>;
300    fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()>;
301    fn health_probe(&self, connection: ConnectionId, module: &str)
302        -> Result<Option<DeliveryProbe>>;
303    fn health_result(
304        &self,
305        probe: DeliveryProbe,
306        healthy: bool,
307    ) -> Result<Option<AppliedDisposition>>;
308    fn promoted(
309        &self,
310        connection: ConnectionId,
311        module: &str,
312        cutover_at: tokio::time::Instant,
313    ) -> Result<Option<(u64, u64)>>;
314    /// Retry only the retained, non-interactive backend when its backoff is due.
315    /// `None` means there is no pending anchor and no timer should be armed.
316    fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>>;
317}
318
319impl DeliveryObserver for RuntimeOwner {
320    fn spawned(
321        &self,
322        module: &str,
323        spawned_at: tokio::time::Instant,
324        register_timeout: std::time::Duration,
325        first_health_budget: std::time::Duration,
326    ) -> Result<Option<DeliverySpawn>> {
327        self.delivery_spawned(module, spawned_at, register_timeout, first_health_budget)
328    }
329
330    fn registered(&self, connection: ConnectionId, spawn: &DeliverySpawn) -> Result<()> {
331        self.delivery_child_registered(connection, spawn)
332    }
333
334    /// Capture before dispatching the ordinary health RPC. A later result must
335    /// use this witness, not look up whichever target is current on completion.
336    fn health_probe(
337        &self,
338        connection: ConnectionId,
339        module: &str,
340    ) -> Result<Option<DeliveryProbe>> {
341        self.delivery_health_probe(connection, module)
342    }
343
344    /// Complete under the module gate. A new target, attempt or policy install
345    /// invalidates an older witness rather than lending its health to new bytes.
346    fn health_result(
347        &self,
348        probe: DeliveryProbe,
349        healthy: bool,
350    ) -> Result<Option<AppliedDisposition>> {
351        self.delivery_health_result(probe, healthy)
352    }
353
354    fn promoted(
355        &self,
356        connection: ConnectionId,
357        module: &str,
358        cutover_at: tokio::time::Instant,
359    ) -> Result<Option<(u64, u64)>> {
360        self.delivery_promoted(connection, module, cutover_at)
361    }
362
363    fn retry_anchor(&self) -> Result<Option<tokio::time::Instant>> {
364        self.poll_anchor_retry()
365    }
366}
367
368/// Keep a reviewed plan for one idle hour so the operator can read the full diff.
369const PLAN_IDLE_TIMEOUT: Duration = Duration::from_secs(60 * 60);
370/// One shared sweep reclaims idle plans without allocating a timer per plan.
371pub(crate) const PLAN_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
372/// Remember recent expirations by digest without retaining unbounded plan bodies.
373const EXPIRED_PLAN_IDS: usize = 64;
374
375fn layer_file_rows(
376    changeset: &mut Changeset,
377    old: &super::GateSnapshot,
378    new: &super::GateSnapshot,
379    previous: Option<&DeliverySnapshot>,
380    candidate: &DeliverySnapshot,
381) -> Result<()> {
382    for key in old.changed_keys(new) {
383        let super::InputKey::Layer { module, path } = key else {
384            continue;
385        };
386        // A value or source row already explains the changed layer. Otherwise
387        // expose the exact raw input without disclosing its contents.
388        if changeset.fields.iter().any(|field| {
389            field.module_id == *module
390                && field.project_id.is_none()
391                && (field.old_source == subc_config::Layer::User
392                    || field.new_source == subc_config::Layer::User)
393        }) {
394            continue;
395        }
396        let describe = |snapshot: Option<&DeliverySnapshot>,
397                        input: Option<&super::CapturedInput>|
398         -> Result<serde_json::Value> {
399            if input.is_none()
400                || input.is_some_and(|input| input.state == subc_config::InputState::Absent)
401            {
402                return Ok(serde_json::json!({"absent":true}));
403            }
404            let bytes = snapshot
405                .and_then(|snapshot| snapshot.modules.get(module))
406                .and_then(|view| {
407                    view.layers
408                        .iter()
409                        .find(|layer| layer.path.as_deref() == Some(path.as_str()))
410                })
411                .and_then(|layer| layer.bytes.as_deref())
412                .ok_or_else(|| GateError::new("config_gated", "retained layer bytes are absent"))?;
413            Ok(
414                serde_json::json!({"sha256":subc_config::raw_digest(bytes).as_str().trim_start_matches("sha256:"), "bytes":bytes.len()}),
415            )
416        };
417        changeset.policy_changes.push(serde_json::json!({
418            "kind":"layer_file", "module_id":module, "layer":"user",
419            "old":describe(previous, old.inputs.get(key))?,
420            "new":describe(Some(candidate), new.inputs.get(key))?,
421        }));
422    }
423    Ok(())
424}
425
426pub(crate) fn daemon_review(
427    old: &super::GateSnapshot,
428    new: &super::GateSnapshot,
429) -> Result<Changeset> {
430    let mut changeset = Changeset::new();
431    for key in old.changed_keys(new) {
432        match key {
433            super::InputKey::Entry(module) | super::InputKey::Program { module, .. } => {
434                let field = match key {
435                    super::InputKey::Entry(_) => "entry".into(),
436                    super::InputKey::Program { path, .. } => format!("program:{path}"),
437                    _ => unreachable!(),
438                };
439                let manifest = changeset
440                    .launch_manifests
441                    .entry(module.clone())
442                    .or_insert_with(|| serde_json::json!({"origin": "other"}));
443                manifest.as_object_mut().expect("launch manifest is an object").insert(field,serde_json::json!({"old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
444            }
445            super::InputKey::Declaration(module) => {
446                changeset.policy_changes.push(serde_json::json!({"module_id":module,"path":"declaration","old":old.inputs.get(key).map(|v| &v.value),"new":new.inputs.get(key).map(|v| &v.value)}));
447            }
448            super::InputKey::Daemon => {
449                changeset.policy_changes.push(serde_json::json!({
450                    "path":"subc.jsonc",
451                    "old":old.inputs.get(key).map(|v| &v.value),
452                    "new":new.inputs.get(key).map(|v| &v.value),
453                }));
454                changeset.apply_plan = serde_json::json!({"supervisor_reconcile":true});
455            }
456            _ => {}
457        }
458    }
459    Ok(changeset)
460}
461
462struct OwnerState {
463    authority_incarnation: std::sync::Arc<()>,
464    observed_snapshot: Option<super::GateSnapshot>,
465    stamp_channel_cutover: bool,
466    gate: ConfigGate,
467    store: ConfigStore,
468    _writer_lock: Option<crate::config_store::StoreWriterLock>,
469    plan_deadlines: BTreeMap<Digest, Instant>,
470    // Only a successfully flushed complete plan on this connection can bind
471    // its desktop approval. A later view replaces the connection's old view.
472    desktop_views: BTreeMap<u64, (Digest, u64)>,
473    phone_waiters: BTreeMap<u64, tokio::sync::oneshot::Sender<()>>,
474    approval_requests: HashMap<(ConnectionId, u64), u64>,
475    delivery: delivery::DeliveryState,
476    anchor_retry: super::anchor_retry::AnchorRetry,
477    // Keep the original objects alive through approval so an unlinked file's
478    // inode/file id cannot be recycled to impersonate the reviewed input.
479    retained_plan_files: BTreeMap<Digest, Vec<std::fs::File>>,
480    pending_settings_card: Option<(Digest, u64)>,
481    open_settings_approval: Option<(Digest, u64, bool)>,
482    latest_explicit_settings_request: u64,
483    pending_settings_card_reason: Option<String>,
484    settings_review_errors: Vec<subc_control::config::ConfigStatusFileError>,
485    settings_review_errors_base: Option<u64>,
486    last_settings_decline: Option<(Digest, u64)>,
487    expired_plans: VecDeque<Digest>,
488    declarations: HashMap<ConnectionId, (String, ConfigDeclareRequest)>,
489    live_project_schemas:
490        HashMap<ConnectionId, std::sync::Arc<super::project_layers::ProjectLayerSchema>>,
491    active_declarations: BTreeMap<String, ConnectionId>,
492    activity: Option<crate::activity::ActivityLedger>,
493    refused_generations: BTreeMap<String, Digest>,
494    admission_holds: Vec<String>,
495    admission_releases: Vec<String>,
496    authority_exit: Option<u64>,
497    // Last reconciled daemon entries, independent of module-layer activation.
498    reconciled_entries: BTreeMap<String, crate::daemon_config::ConfiguredModule>,
499    recovery_exit_hold: bool,
500    unstamp_hints: std::collections::HashSet<ConnectionId>,
501    anchor_waiters: std::collections::HashSet<ConnectionId>,
502    anchor_hints: std::collections::HashSet<ConnectionId>,
503    anchor_notify: std::sync::Arc<tokio::sync::Notify>,
504    installed_route_policies: BTreeMap<String, u64>,
505    route_policy_receipts: BTreeMap<(String, u64), route_policy::PendingRoutePolicy>,
506    #[cfg(test)]
507    publication_hook: Option<Box<dyn FnOnce() + Send>>,
508    #[cfg(test)]
509    prepublication_hook: Option<Box<dyn FnOnce() + Send>>,
510    #[cfg(test)]
511    after_approval_drain_hook: Option<Box<dyn FnOnce() + Send>>,
512}
513
514impl OwnerState {
515    fn retry_anchor(&mut self, operator_command: bool) -> Option<tokio::time::Instant> {
516        self.retry_anchor_inner(operator_command, false)
517    }
518
519    fn retry_anchor_inner(
520        &mut self,
521        operator_command: bool,
522        verified: bool,
523    ) -> Option<tokio::time::Instant> {
524        if !verified {
525            let _ = self.store.check();
526        }
527        let pending = self.store.loaded_anchor_pending();
528        let events = self.anchor_retry.poll(
529            pending,
530            tokio::time::Instant::now(),
531            operator_command,
532            || {
533                let result = if verified {
534                    self.store.retry_verified_anchor()
535                } else {
536                    let result = self.store.retry_anchor();
537                    let _ = self.store.check();
538                    result
539                };
540                (
541                    self.store.loaded_anchor_pending(),
542                    result.err().map(|error| error.to_string()),
543                )
544            },
545        );
546        for event in events {
547            match event {
548                super::anchor_retry::Event::Pending => {
549                    tracing::info!("configuration anchor became pending")
550                }
551                super::anchor_retry::Event::Failed(reason) => {
552                    tracing::warn!(%reason, "configuration anchor retry failed")
553                }
554                super::anchor_retry::Event::Recovered => {
555                    tracing::info!("configuration anchor recovered");
556                    self.queue_anchor_hints();
557                }
558            }
559        }
560        if verified {
561            self.commit_verified_route_policies();
562        } else {
563            self.commit_anchored_route_policies();
564        }
565        self.anchor_retry.next()
566    }
567    fn with_desktop_view(&self, digest: &Digest, facts: &ApprovalFacts) -> ApprovalFacts {
568        let mut checked = facts.clone();
569        let bound = self
570            .desktop_views
571            .get(&facts.connection)
572            .is_some_and(|(shown, revision)| {
573                shown == digest
574                    && self
575                        .gate
576                        .plans
577                        .get(digest)
578                        .is_some_and(|plan| plan.view.base_revision == *revision)
579            });
580        if !bound {
581            checked.desktop_app = false;
582            checked.attested_operator_app = false;
583        }
584        checked
585    }
586    /// Reclaim idle plans. Returns whether any plan expired.
587    fn expire_idle(&mut self, now: Instant) -> bool {
588        let base = self.store.loaded_admission_state().1.base_revision;
589        let expired: Vec<_> = self
590            .plan_deadlines
591            .iter()
592            .filter(|(digest, deadline)| {
593                **deadline <= now
594                    && !self.gate.has_open_approval(digest)
595                    && !self.gate.plans.get(*digest).is_some_and(|plan| {
596                        (plan.kept_after_refused_decline || plan.decline_accepted || plan.restoring)
597                            && plan.view.base_revision == base
598                    })
599            })
600            .map(|(digest, _)| digest.clone())
601            .collect();
602        let any = !expired.is_empty();
603        for digest in expired {
604            self.plan_deadlines.remove(&digest);
605            self.retained_plan_files.remove(&digest);
606            self.desktop_views.retain(|_, (shown, _)| shown != &digest);
607            if self.gate.expire_plan(&digest) {
608                self.expired_plans.push_back(digest);
609                if self.expired_plans.len() > EXPIRED_PLAN_IDS {
610                    self.expired_plans.pop_front();
611                }
612            }
613        }
614        any
615    }
616    fn reviewed(&mut self, digest: &Digest, now: Instant) {
617        self.plan_deadlines
618            .insert(digest.clone(), now + PLAN_IDLE_TIMEOUT);
619        self.expired_plans.retain(|expired| expired != digest);
620    }
621}
622
623/// The owner's state, held exclusively. Releasing it republishes the polled
624/// projection, admission and approved-daemon views when anything they derive
625/// from could have changed: any mutable access through this guard, a store
626/// check that moved the store, or a change made outside a guard that set
627/// `RuntimeOwner::projection_stale`. A guard used only to read publishes
628/// nothing, so read-like authority checks do not rebuild the projection.
629struct OwnerGuard<'a> {
630    state: std::sync::MutexGuard<'a, OwnerState>,
631    owner: &'a RuntimeOwner,
632    changed: bool,
633}
634impl std::ops::Deref for OwnerGuard<'_> {
635    type Target = OwnerState;
636    fn deref(&self) -> &Self::Target {
637        &self.state
638    }
639}
640impl std::ops::DerefMut for OwnerGuard<'_> {
641    fn deref_mut(&mut self) -> &mut Self::Target {
642        // Any mutable access may change a published input. Read-only store
643        // checks use `OwnerGuard::store_read` so they republish only when the
644        // check itself changed the store.
645        self.changed = true;
646        &mut self.state
647    }
648}
649
650/// The parts of a store that a read-only integrity check can change and that
651/// feed the published views: its state (a failed check moves it into
652/// recovery), its atomic publications, its pending anchor and its key status.
653fn store_witness(store: &ConfigStore) -> (StoreState, u64, bool, u64) {
654    (
655        store.loaded_admission_state().0,
656        store.publication_sequence(),
657        store.loaded_anchor_pending(),
658        store.key_status_revision(),
659    )
660}
661
662impl<'a> OwnerGuard<'a> {
663    fn new(state: std::sync::MutexGuard<'a, OwnerState>, owner: &'a RuntimeOwner) -> Self {
664        #[cfg(test)]
665        owner
666            .owner_guards
667            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
668        Self {
669            state,
670            owner,
671            changed: false,
672        }
673    }
674
675    /// Run a store integrity read (`check`, `status`, `delivery_ready`) and
676    /// mark the guard changed only if the read changed what the store
677    /// publishes. Every caller still checks authority on every call.
678    fn store_read<T>(&mut self, read: impl FnOnce(&mut ConfigStore) -> T) -> T {
679        let before = store_witness(&self.state.store);
680        let result = read(&mut self.state.store);
681        if store_witness(&self.state.store) != before {
682            self.changed = true;
683        }
684        result
685    }
686
687    /// `ConfigStore::body` without marking the guard changed when the check
688    /// it performs leaves the store as it was.
689    fn checked_body(
690        &mut self,
691    ) -> std::result::Result<&crate::config_store::StoreBody, crate::config_store::StoreError> {
692        self.store_read(ConfigStore::check)?;
693        Ok(self.state.store.loaded_admission_state().1)
694    }
695
696    fn check_authority_for_read(&mut self) -> Result<()> {
697        let retry = self.state.anchor_retry.next();
698        let pending = self.state.store.loaded_anchor_pending();
699        self.store_read(ConfigStore::check)?;
700        let before = store_witness(&self.state.store);
701        self.state.retry_anchor_inner(true, true);
702        self.changed |= store_witness(&self.state.store) != before;
703        // Verification can finish writing the committed store's integrity
704        // anchor or schedule its first retry. Delivery waits for that write.
705        if pending != self.state.store.loaded_anchor_pending()
706            || retry != self.state.anchor_retry.next()
707        {
708            self.owner.notify_delivery_changed();
709        }
710        Ok(self.state.store.usable()?)
711    }
712
713    fn publish(&mut self) {
714        #[cfg(test)]
715        self.owner
716            .projection_builds
717            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
718        // Project committed or invalidated authority before releasing its owner.
719        // Parse changed generations outside the cheap reader lock, then publish
720        // only the Arc; list polling never waits for store or keychain work.
721        let (previous_daemon, previous_credentials) = self
722            .owner
723            .published
724            .read()
725            .map(|view| {
726                (
727                    view.approved_daemon.clone(),
728                    view.settings_credentials.clone(),
729                )
730            })
731            .unwrap_or((ApprovedDaemonView::Unavailable, None));
732        let approved_daemon = ApprovedDaemonView::from_store(
733            &self.state.store,
734            self.state.recovery_exit_hold,
735            &previous_daemon,
736        );
737        let settings_credentials = published::ApprovedSettingsCredentials::from_store(
738            &self.state.store,
739            self.state.recovery_exit_hold,
740            previous_credentials.as_ref(),
741        );
742        // Volatile holds follow the same lifetime as their durable records.
743        // Approving another program identity retires the previous identity's
744        // volatile hold, even if that previous identity is later approved again.
745        let (_, body) = self.state.store.loaded_admission_state();
746        let valid: std::collections::BTreeSet<_> = body
747            .program_refusals
748            .iter()
749            .map(|refusal| (refusal.module.clone(), refusal.approved_base.clone()))
750            .collect();
751        self.state
752            .refused_generations
753            .retain(|module, base| valid.contains(&(module.clone(), base.clone())));
754        let next = admission::AdmissionCache::from_state(&self.state);
755        // Lower the marks this state rules out (an unstamp, an ungated
756        // module, an active generation the spawn never acknowledged) before
757        // the owner is released: delivery, then record, then forwarding.
758        mark::sweep(self.owner, &mut self.state, &next);
759        let observed = self.state.observed_snapshot.clone();
760        let projection = self
761            .owner
762            .status_projection(&mut self.state, observed, &next);
763        let settings = settings::SettingsVersion::from_state(&self.state);
764        if let Ok(mut cache) = self.owner.published.write() {
765            let (holds, releases) = next.transitions_from(&cache);
766            let changed = next.is_recovering() != cache.is_recovering()
767                || !holds.is_empty()
768                || !releases.is_empty();
769            let settings_changed = cache.settings.as_ref() != Some(&settings)
770                || projection.status.ungated_modules != cache.projection.status.ungated_modules;
771            self.state.admission_holds.extend(holds);
772            self.state.admission_releases.extend(releases);
773            *cache = std::sync::Arc::new(Published {
774                admission: next,
775                approved_daemon,
776                refuses_control_in_recovery: Published::control_recovery(
777                    &self.state.store,
778                    self.state.recovery_exit_hold,
779                ),
780                projection,
781                settings: Some(settings),
782                settings_credentials,
783            });
784            if settings_changed {
785                self.owner
786                    .settings_changed
787                    .send_modify(|revision| *revision = revision.wrapping_add(1));
788            }
789            if changed {
790                self.owner.delivery_changed.notify_one();
791            }
792        }
793    }
794}
795impl Drop for OwnerGuard<'_> {
796    fn drop(&mut self) {
797        // Clear the outside-change flag even when this guard publishes anyway.
798        let stale = self
799            .owner
800            .projection_stale
801            .swap(false, std::sync::atomic::Ordering::AcqRel);
802        let published = (!(self.changed || stale))
803            .then(|| {
804                self.owner
805                    .published
806                    .read()
807                    .ok()
808                    .map(|view| std::sync::Arc::clone(&view))
809            })
810            .flatten();
811        match published {
812            // Nothing published here changed, so the published admission is
813            // what a rebuild would produce. Spawn records still carry their
814            // own mark facts, so sweep them against it on every release.
815            Some(published) => mark::sweep(self.owner, &mut self.state, &published.admission),
816            None => self.publish(),
817        }
818        let Some(ledger) = self.state.activity.clone() else {
819            return;
820        };
821        let Ok(gates) = self.owner.module_gates.try_lock() else {
822            return;
823        };
824        let held: Vec<_> = gates
825            .values()
826            .filter(|gate| gate.try_lock().is_err())
827            .cloned()
828            .collect();
829        drop(gates);
830        if held.is_empty() {
831            for activity in self.state.store.take_activities() {
832                ledger.config_store_activity(activity);
833            }
834        } else if let Ok(runtime) = tokio::runtime::Handle::try_current() {
835            let activities = self.state.store.take_activities();
836            if !activities.is_empty() {
837                runtime.spawn(async move {
838                    // No store mutex follows the activity into this task. Drop
839                    // each gate before waiting for another, then publish the log.
840                    for gate in held {
841                        drop(gate.lock_owned().await);
842                    }
843                    for activity in activities {
844                        ledger.config_store_activity(activity);
845                    }
846                });
847            }
848        }
849    }
850}
851
852pub struct PreparedPlan {
853    edits: Option<edits::EditPlan>,
854    /// Filled by project capture only after checking the module's reply. A
855    /// user-only plan leaves this absent to preserve its digest and view.
856    pub(crate) projects: Option<super::targets::ProjectReviews>,
857    project_capture: Option<CapturePlan>,
858    settings_users: Option<BTreeSet<String>>,
859    pub candidate: CapturedConfiguration,
860    pub bases: BTreeMap<String, ConfigView>,
861    pub base_schemas: BTreeMap<String, subc_config::Schema>,
862    pub kind: PlanKind,
863    pub review_modules: std::collections::BTreeSet<String>,
864    /// Modules in `review_modules` only because their newly approved program
865    /// is active and has not yet reviewed their approved layers. A missing
866    /// reviewer drops such a module from this plan instead of failing it.
867    pub rereview_modules: std::collections::BTreeSet<String>,
868    base_revision: u64,
869    active_generations: BTreeMap<crate::config_store::Tuple, Option<u64>>,
870    touched_modules: BTreeSet<String>,
871    read_set: subc_config::InputVector,
872    program_keys: Vec<super::InputKey>,
873    observed_handles: Vec<std::fs::File>,
874}
875
876/// Immutable command inputs for the supervisor's approved rollback admission.
877pub struct ApprovedRollbackCommands {
878    pub generation: u64,
879    pub daemon: ConfigLayerSnapshot,
880    pub programs: BTreeMap<String, ApprovedRollbackProgram>,
881}
882
883/// A supervisor reconciliation witness minted only from a verified committed
884/// generation. Keeping the raw layer prevents a caller from substituting a
885/// freshly parsed live file for the approved command inputs.
886#[derive(Clone, Debug)]
887pub(crate) struct ApprovedDaemonConfiguration {
888    generation: u64,
889    approval_digest: Digest,
890    authority_incarnation: std::sync::Arc<()>,
891    daemon: std::sync::Arc<ConfigLayerSnapshot>,
892    changed_entries: BTreeSet<String>,
893}
894
895#[derive(Clone, Debug)]
896pub(crate) struct ApprovalIdentity {
897    generation: u64,
898    approval_digest: Digest,
899    // Rebuilding rejected store authority from unchanged files can repeat both
900    // generation and digest. Retain this token in ApprovedDaemonConfiguration and
901    // each actor's approved_start_failure so old failures cannot alias new authority.
902    authority_incarnation: std::sync::Arc<()>,
903}
904
905impl PartialEq for ApprovalIdentity {
906    fn eq(&self, other: &Self) -> bool {
907        self.generation == other.generation
908            && self.approval_digest == other.approval_digest
909            && std::sync::Arc::ptr_eq(&self.authority_incarnation, &other.authority_incarnation)
910    }
911}
912
913impl Eq for ApprovalIdentity {}
914
915pub struct ApprovedRollbackProgram {
916    pub path: String,
917    pub identity: super::CapturedInput,
918}
919
920#[cfg(test)]
921#[path = "runtime_tests.rs"]
922mod tests;
923#[cfg(all(test, unix, feature = "test-support"))]
924pub(crate) use tests::capture_plan::RouteSettingsRig;
925
926#[cfg(test)]
927#[path = "commit_pause.rs"]
928pub(crate) mod commit_pause;
929
930#[path = "delivery.rs"]
931pub(crate) mod delivery;
932
933#[path = "admission.rs"]
934mod admission;
935#[path = "mark.rs"]
936pub(crate) mod mark;
937#[path = "recovery.rs"]
938mod recovery;
939#[path = "rollback.rs"]
940mod rollback;
941#[path = "route_policy.rs"]
942mod route_policy;
943pub(crate) use admission::SpawnAdmission;
944
945#[path = "approval_request.rs"]
946mod approval_request;
947#[path = "daemon_readers.rs"]
948mod daemon_readers;
949pub(crate) use daemon_readers::ApprovedDaemonView;
950#[path = "phone.rs"]
951mod phone;
952#[path = "placement.rs"]
953mod placement;
954#[path = "polled.rs"]
955mod polled;
956#[path = "published.rs"]
957mod published;
958#[path = "unstamped.rs"]
959pub(crate) mod unstamped;
960#[path = "unstamped_projects.rs"]
961pub(crate) mod unstamped_projects;
962#[path = "widening.rs"]
963mod widening;
964pub(crate) use published::Published;
965#[path = "settings.rs"]
966pub(crate) mod settings;
967#[path = "settings_observation.rs"]
968pub(crate) mod settings_observation;
969#[path = "status_inputs.rs"]
970mod status_inputs;
971
972#[path = "runtime_capture.rs"]
973mod runtime_capture;
974pub(crate) use approval_request::{ApprovalRequest, ApprovalRequestGuard, CancelApprovalRequest};
975pub(crate) use runtime_capture::CaptureApply;
976pub(crate) use settings_observation::{
977    SettingsCardResult, SettingsEvent, SettingsHistory, SettingsReviewResult,
978};
979
980impl RuntimeOwner {
981    /// Keep store I/O and waits for its synchronous owner lock off runtime threads.
982    pub(crate) async fn on_blocking<T: Send + 'static>(
983        self: &std::sync::Arc<Self>,
984        work: impl FnOnce(std::sync::Arc<Self>) -> Result<T> + Send + 'static,
985    ) -> Result<T> {
986        let owner = self.clone();
987        tokio::task::spawn_blocking(move || work(owner))
988            .await
989            .map_err(|_| GateError::new("config_unavailable", "configuration worker stopped"))?
990    }
991
992    #[cfg(feature = "test-support")]
993    pub(crate) fn pause_spawn_before_exec(&self) -> Result<()> {
994        if let Some(hooks) = &self.test_hooks {
995            hooks
996                .pause_spawn_before_exec()
997                .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
998        }
999        Ok(())
1000    }
1001
1002    #[cfg(feature = "test-support")]
1003    pub(crate) fn pause_swap_before_promotion(&self) -> Result<()> {
1004        if let Some(hooks) = &self.test_hooks {
1005            hooks
1006                .pause_swap_before_promotion()
1007                .map_err(|error| GateError::new("config_test_pause", error.to_string()))?;
1008        }
1009        Ok(())
1010    }
1011    /// Record the exact full response only after its writer flush succeeds and
1012    /// the adapter revalidates the same live desktop connection.
1013    #[cfg(test)]
1014    pub(crate) fn desktop_view_delivered(
1015        &self,
1016        connection: ConnectionId,
1017        view: &subc_control::config::ConfigPlanView,
1018    ) -> Result<()> {
1019        self.desktop_view_delivered_when(connection, view, || true)
1020    }
1021
1022    pub(crate) fn desktop_view_delivered_when(
1023        &self,
1024        connection: ConnectionId,
1025        view: &subc_control::config::ConfigPlanView,
1026        is_live: impl FnOnce() -> bool,
1027    ) -> Result<()> {
1028        #[cfg(test)]
1029        if let Some(hook) = self.desktop_receipt_hook.lock().unwrap().take() {
1030            hook();
1031        }
1032        let mut state = self.lock()?;
1033        // Check the live peer after acquiring the owner, without retaining the
1034        // peer mutex during an owner wait or any configuration/store work.
1035        if !is_live() {
1036            return Ok(());
1037        }
1038        let plan = state
1039            .gate
1040            .plans
1041            .get(&view.digest)
1042            .ok_or_else(|| GateError::new("plan_unknown", "plan is absent or expired"))?;
1043        if plan.view != *view {
1044            return Err(GateError::new(
1045                "plan_stale",
1046                "delivered view differs from the immutable plan",
1047            ));
1048        }
1049        state
1050            .desktop_views
1051            .insert(connection.get(), (view.digest.clone(), view.base_revision));
1052        Ok(())
1053    }
1054    pub fn new(incarnation: String, store: ConfigStore, capturer: ConfigCapturer) -> Self {
1055        Self::new_with_startup_env(incarnation, store, capturer, |name| {
1056            std::env::var_os(name).is_some()
1057        })
1058    }
1059
1060    pub(crate) fn new_with_startup_env(
1061        incarnation: String,
1062        mut store: ConfigStore,
1063        capturer: ConfigCapturer,
1064        env_present: impl FnMut(&str) -> bool,
1065    ) -> Self {
1066        // Daemon-restart generations newer than the booted one stay deferred.
1067        let initial_generation = match store.booted_generation() {
1068            Some(booted) => booted,
1069            None => store.body().map(|body| body.last_generation).unwrap_or(0),
1070        };
1071        let admission = admission::AdmissionCache::from_store(&store);
1072        let approved_daemon =
1073            ApprovedDaemonView::from_store(&store, false, &ApprovedDaemonView::Unavailable);
1074        let settings_credentials =
1075            published::ApprovedSettingsCredentials::from_store(&store, false, None);
1076        let reconciled_entries = match &approved_daemon {
1077            ApprovedDaemonView::Approved { config, .. } => config
1078                .modules
1079                .iter()
1080                .map(|module| (module.module_id.clone(), module.clone()))
1081                .collect(),
1082            _ => BTreeMap::new(),
1083        };
1084        let published = std::sync::RwLock::new(std::sync::Arc::new(Published {
1085            admission,
1086            approved_daemon,
1087            refuses_control_in_recovery: Published::control_recovery(&store, false),
1088            projection: polled::Projection::default(),
1089            settings: None,
1090            settings_credentials,
1091        }));
1092        let delivery_changed = std::sync::Arc::new(tokio::sync::Notify::new());
1093        let owner = Self {
1094            user_file_refusals: Mutex::new(BTreeMap::new()),
1095            #[cfg(test)]
1096            user_file_test_idle: Mutex::new(None),
1097            #[cfg(test)]
1098            polled_capture_hook: Mutex::new(None),
1099            #[cfg(test)]
1100            settings_projection_hook: Mutex::new(None),
1101            #[cfg(test)]
1102            settings_status_hook: Mutex::new(None),
1103            #[cfg(test)]
1104            settings_observation_hook: Mutex::new(None),
1105            #[cfg(test)]
1106            config_park_hook: Mutex::new(None),
1107            #[cfg(test)]
1108            content_kill_hook: Mutex::new(None),
1109            #[cfg(test)]
1110            polled_capture_count: std::sync::atomic::AtomicUsize::new(0),
1111            #[cfg(test)]
1112            census_probe: Mutex::new(None),
1113            #[cfg(test)]
1114            agent_validation_window: Mutex::new(None),
1115            #[cfg(test)]
1116            warm_restart_pause: Mutex::new(None),
1117            #[cfg(test)]
1118            warm_restart_busy: Mutex::new(None),
1119            #[cfg(test)]
1120            swap_preflight_attempts: std::sync::atomic::AtomicUsize::new(0),
1121            #[cfg(feature = "test-support")]
1122            test_hooks: store.test_support().cloned(),
1123            #[cfg(test)]
1124            spawn_exec_hook: Mutex::new(None),
1125            published,
1126            // The first guard release below builds the initial projection.
1127            projection_stale: std::sync::atomic::AtomicBool::new(true),
1128            #[cfg(test)]
1129            projection_builds: std::sync::atomic::AtomicUsize::new(0),
1130            #[cfg(test)]
1131            owner_guards: std::sync::atomic::AtomicUsize::new(0),
1132            config_workers: Mutex::new(std::collections::HashSet::new()),
1133            configured_modules: std::sync::RwLock::new(None),
1134            inner: Mutex::new(OwnerState {
1135                authority_incarnation: std::sync::Arc::new(()),
1136                observed_snapshot: None,
1137                stamp_channel_cutover: false,
1138                gate: ConfigGate::new(incarnation),
1139                store,
1140                _writer_lock: None,
1141                plan_deadlines: BTreeMap::new(),
1142                desktop_views: BTreeMap::new(),
1143                phone_waiters: BTreeMap::new(),
1144                approval_requests: HashMap::new(),
1145                delivery: delivery::DeliveryState::new(initial_generation),
1146                anchor_retry: super::anchor_retry::AnchorRetry::default(),
1147                retained_plan_files: BTreeMap::new(),
1148                pending_settings_card: None,
1149                open_settings_approval: None,
1150                latest_explicit_settings_request: 0,
1151                pending_settings_card_reason: None,
1152                settings_review_errors: Vec::new(),
1153                settings_review_errors_base: None,
1154                last_settings_decline: None,
1155                expired_plans: VecDeque::new(),
1156                declarations: HashMap::new(),
1157                live_project_schemas: HashMap::new(),
1158                active_declarations: BTreeMap::new(),
1159                activity: None,
1160                refused_generations: BTreeMap::new(),
1161                admission_holds: Vec::new(),
1162                admission_releases: Vec::new(),
1163                authority_exit: None,
1164                reconciled_entries,
1165                recovery_exit_hold: false,
1166                unstamp_hints: std::collections::HashSet::new(),
1167                anchor_waiters: std::collections::HashSet::new(),
1168                anchor_hints: std::collections::HashSet::new(),
1169                anchor_notify: delivery_changed.clone(),
1170                installed_route_policies: BTreeMap::new(),
1171                route_policy_receipts: BTreeMap::new(),
1172                #[cfg(test)]
1173                publication_hook: None,
1174                #[cfg(test)]
1175                prepublication_hook: None,
1176                #[cfg(test)]
1177                after_approval_drain_hook: None,
1178            }),
1179            settings_recovery_data: capturer.config_home.clone(),
1180            settings_recovery_updates: Default::default(),
1181            #[cfg(test)]
1182            recovery_probe_hook: Mutex::new(None),
1183            #[cfg(test)]
1184            after_settings_decline_hook: Mutex::new(None),
1185            capturer,
1186            policy_root_ledger: None,
1187            policy_root_unstamped: Mutex::new(Ok(None)),
1188            #[cfg(test)]
1189            policy_root_fail_after_append: std::sync::atomic::AtomicBool::new(false),
1190            project_capture_enabled: false,
1191            settings_projects: Default::default(),
1192            #[cfg(test)]
1193            project_write_hook: std::sync::Mutex::new(None),
1194            #[cfg(test)]
1195            user_restore_hook: Mutex::new(None),
1196            #[cfg(test)]
1197            after_restore_read_hook: Mutex::new(None),
1198            settings_phone_delivery: tokio::sync::Mutex::new(()),
1199            settings_attempts_changed: tokio::sync::Notify::new(),
1200            settings_request_order: std::sync::atomic::AtomicU64::new(1),
1201            phone_withdrawal_changed: tokio::sync::Notify::new(),
1202            #[cfg(test)]
1203            project_write_waiter_done: std::sync::Mutex::new(None),
1204            #[cfg(test)]
1205            trusted_review_connection_for_test: std::sync::Mutex::new(None),
1206            startup_overrides: status_inputs::present_overrides(env_present),
1207            module_gates: Mutex::new(HashMap::new()),
1208            delivery_changed,
1209            settings_changed: tokio::sync::watch::channel(0).0,
1210            route_policy_authority: std::sync::OnceLock::new(),
1211            mark_publisher: std::sync::OnceLock::new(),
1212            binding_retirements: Mutex::new(BTreeMap::new()),
1213            canceled_approvals: Mutex::new(Vec::new()),
1214            approval_request_index: Mutex::new(HashMap::new()),
1215            disconnected_pending: Mutex::new(Vec::new()),
1216            abandoned_spawns: Mutex::new(Vec::new()),
1217            phone_withdrawals: Mutex::new(phone::PhoneWithdrawals::default()),
1218            #[cfg(any(test, feature = "test-support"))]
1219            os_prompt_policy: std::sync::atomic::AtomicBool::new(false),
1220            #[cfg(test)]
1221            spawn_preflight_hook: Mutex::new(None),
1222            #[cfg(test)]
1223            exit_record_attempts: std::sync::atomic::AtomicUsize::new(0),
1224            #[cfg(test)]
1225            phone_bind_hook: Mutex::new(None),
1226            #[cfg(test)]
1227            begin_approval_hook: Mutex::new(None),
1228            #[cfg(test)]
1229            begin_approval_completions: std::sync::atomic::AtomicUsize::new(0),
1230            #[cfg(test)]
1231            desktop_receipt_hook: Mutex::new(None),
1232            #[cfg(test)]
1233            prepare_capture_hook: Mutex::new(None),
1234            #[cfg(all(test, unix))]
1235            approval_claim_pause: Mutex::new(None),
1236        };
1237        if let Ok(state) = owner.lock() {
1238            drop(state);
1239        }
1240        owner
1241    }
1242
1243    pub fn module_gate(&self, module: &str) -> Result<std::sync::Arc<tokio::sync::Mutex<()>>> {
1244        let mut gates = self
1245            .module_gates
1246            .lock()
1247            .map_err(|_| GateError::new("config_unavailable", "module gate lock is poisoned"))?;
1248        Ok(gates.entry(module.into()).or_default().clone())
1249    }
1250
1251    #[cfg(all(test, unix))]
1252    pub(crate) fn set_agent_validation_window_for_test(&self, window: Duration) {
1253        *self.agent_validation_window.lock().unwrap() = Some(window);
1254    }
1255
1256    #[cfg(test)]
1257    pub(crate) fn agent_validation_window_for_test(&self) -> Option<Duration> {
1258        *self.agent_validation_window.lock().unwrap()
1259    }
1260
1261    pub(crate) fn install_binding_retirement(
1262        &self,
1263        key: usize,
1264        retire: impl Fn() + Send + Sync + 'static,
1265    ) {
1266        self.binding_retirements
1267            .lock()
1268            .unwrap_or_else(|poisoned| poisoned.into_inner())
1269            .insert(key, Box::new(retire));
1270    }
1271
1272    pub(crate) fn delivery_notifications(&self) -> std::sync::Arc<tokio::sync::Notify> {
1273        self.delivery_changed.clone()
1274    }
1275
1276    pub(crate) fn notify_delivery_changed(&self) {
1277        self.delivery_changed.notify_one();
1278    }
1279
1280    pub(crate) fn retain_writer_lock(
1281        self,
1282        lock: crate::config_store::StoreWriterLock,
1283    ) -> Result<Self> {
1284        self.lock()?._writer_lock = Some(lock);
1285        Ok(self)
1286    }
1287
1288    fn lock(&self) -> Result<OwnerGuard<'_>> {
1289        // The owner's state comes before the forwarding lock: lowering a
1290        // first-party mark takes the forwarding lock under it.
1291        crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
1292        let mut guard = self
1293            .inner
1294            .lock()
1295            .map(|state| OwnerGuard::new(state, self))
1296            .map_err(|_| {
1297                GateError::new("config_unavailable", "configuration owner lock is poisoned")
1298            })?;
1299        // The test seam only arms a backend failure; nothing published reads it.
1300        #[cfg(feature = "test-support")]
1301        guard.state.store.refresh_test_anchor_failure();
1302        // Deferred cancellations, disconnects and abandoned spawns, and idle
1303        // plan expiry, change the owner only when they had work. Each runs on
1304        // every acquisition, and work done here publishes on release.
1305        let drained = self.drain_canceled_approvals(&mut guard.state)
1306            | self.drain_disconnections(&mut guard.state)
1307            | self.drain_abandoned_spawns(&mut guard.state)
1308            | guard.state.expire_idle(Instant::now());
1309        guard.changed |= drained;
1310        Ok(guard)
1311    }
1312
1313    pub(crate) fn try_swap_configuration(&self) -> Result<SwapConfiguration<'_>> {
1314        let state = self.inner.try_lock().map_err(|_| {
1315            GateError::new(
1316                "config_delivery_deferred",
1317                "configuration publication is busy or unavailable",
1318            )
1319        })?;
1320        Ok(SwapConfiguration {
1321            owner: self,
1322            state: OwnerGuard::new(state, self),
1323        })
1324    }
1325
1326    pub(crate) fn try_requires_fresher_spawn(
1327        &self,
1328        module: &str,
1329        spawn: Option<&DeliverySpawn>,
1330    ) -> Result<Option<u64>> {
1331        let state = self.inner.try_lock().map_err(|_| {
1332            GateError::new(
1333                "config_delivery_deferred",
1334                "configuration publication is busy or unavailable",
1335            )
1336        })?;
1337        Self::requires_fresher_spawn_loaded(&state, module, spawn)
1338    }
1339
1340    pub(crate) fn sweep_expired(&self) -> Result<()> {
1341        drop(self.lock()?);
1342        Ok(())
1343    }
1344
1345    pub(crate) fn poll_anchor_retry(&self) -> Result<Option<tokio::time::Instant>> {
1346        Ok(self.lock()?.retry_anchor(false))
1347    }
1348
1349    pub(crate) fn set_activity(
1350        &self,
1351        ledger: Option<crate::activity::ActivityLedger>,
1352    ) -> Result<()> {
1353        self.lock()?.activity = ledger;
1354        Ok(())
1355    }
1356
1357    pub fn take_activities(&self) -> Vec<StoreActivity> {
1358        self.inner
1359            .lock()
1360            .map(|mut state| state.store.take_activities())
1361            .unwrap_or_default()
1362    }
1363
1364    /// Declaration ownership comes from the registered transport connection.
1365    /// A candidate's proposal is retained without replacing the incumbent's.
1366    pub fn declare(
1367        &self,
1368        connection: ConnectionId,
1369        module: &str,
1370        declaration: ConfigDeclareRequest,
1371        active: bool,
1372    ) -> Result<()> {
1373        super::strict_json::check_canonical(&declaration.schema, "/schema")
1374            .map_err(|error| GateError::new(&error.code, format!("{module}: {}", error.detail)))?;
1375        let schema = subc_config::Schema::new(declaration.schema.clone())
1376            .map_err(|r| GateError::new("schema_invalid", format!("{module}: {}", r.path)))?;
1377        let live_schema = self
1378            .project_settings_enabled()
1379            .then(|| std::sync::Arc::new(super::project_layers::ProjectLayerSchema::new(schema)));
1380        let mut state = self.lock()?;
1381        if state.store.status().state == StoreState::StoreMissing
1382            || state.store.status().state == StoreState::StoreUnverified
1383        {
1384            return Err(GateError::new(
1385                "config_gated",
1386                "configuration store is in recovery",
1387            ));
1388        }
1389        if state.declarations.contains_key(&connection) {
1390            return Err(GateError::new(
1391                "declaration_order",
1392                "configuration is declared once per connection",
1393            ));
1394        }
1395        state
1396            .declarations
1397            .insert(connection, (module.into(), declaration));
1398        if let Some(schema) = live_schema {
1399            state.live_project_schemas.insert(connection, schema);
1400        }
1401        state.delivery.declared(connection, module, active);
1402        if active {
1403            state.active_declarations.insert(module.into(), connection);
1404        }
1405        self.notify_delivery_changed();
1406        Ok(())
1407    }
1408
1409    /// Clear everything `connection` held in the configuration owner. If another
1410    /// task holds the owner lock, the close is queued and the coordinator is
1411    /// always woken to drain it, because the connection can't be checked. When
1412    /// the lock is free, wake only if the connection had configuration state or
1413    /// ran a `config.review` worker.
1414    pub fn disconnected(&self, connection: ConnectionId) {
1415        let mut held = false;
1416        if let Ok(mut index) = self.approval_request_index.lock() {
1417            index.retain(|(caller, _), request| {
1418                if *caller == connection {
1419                    request.cancel();
1420                    held = true;
1421                    false
1422                } else {
1423                    true
1424                }
1425            });
1426        }
1427        match self.inner.try_lock() {
1428            Ok(mut state) => {
1429                if state.disconnected(connection) {
1430                    held = true;
1431                    // This change bypassed an OwnerGuard. Flag it before the
1432                    // owner is released so the next guard republishes it.
1433                    self.projection_stale
1434                        .store(true, std::sync::atomic::Ordering::Release);
1435                }
1436            }
1437            Err(_) => {
1438                if let Ok(mut pending) = self.disconnected_pending.lock() {
1439                    pending.push(connection);
1440                }
1441                // Without the owner lock we cannot rule out config state.
1442                // The coordinator's next acquisition applies the queued close.
1443                held = true;
1444            }
1445        }
1446        if held || self.runs_config_worker(connection) {
1447            self.notify_delivery_changed();
1448        }
1449    }
1450
1451    /// The delivery coordinator started a `config.review` worker for
1452    /// `connection`.
1453    pub(crate) fn config_worker_started(&self, connection: ConnectionId) {
1454        self.config_workers
1455            .lock()
1456            .unwrap_or_else(|poisoned| poisoned.into_inner())
1457            .insert(connection);
1458    }
1459
1460    /// The delivery coordinator retired `connection`'s worker.
1461    pub(crate) fn config_worker_stopped(&self, connection: ConnectionId) {
1462        self.config_workers
1463            .lock()
1464            .unwrap_or_else(|poisoned| poisoned.into_inner())
1465            .remove(&connection);
1466    }
1467
1468    fn runs_config_worker(&self, connection: ConnectionId) -> bool {
1469        self.config_workers
1470            .lock()
1471            .map_or(true, |workers| workers.contains(&connection))
1472    }
1473
1474    pub fn module_get(
1475        &self,
1476        connection: ConnectionId,
1477        module: &str,
1478        request: subc_protocol::config::ConfigGetRequest,
1479    ) -> Result<subc_protocol::config::ConfigGetReply> {
1480        let mut state = self.lock()?;
1481        self.module_get_locked(&mut state, connection, module, request, true)
1482    }
1483
1484    fn module_get_locked(
1485        &self,
1486        state: &mut OwnerState,
1487        connection: ConnectionId,
1488        module: &str,
1489        request: subc_protocol::config::ConfigGetRequest,
1490        check_store: bool,
1491    ) -> Result<subc_protocol::config::ConfigGetReply> {
1492        let declaration = state
1493            .declarations
1494            .get(&connection)
1495            .filter(|(id, _)| id == module)
1496            .map(|(_, declaration)| declaration.clone())
1497            .ok_or_else(|| {
1498                GateError::new(
1499                    "declaration_order",
1500                    "config.declare must precede get or applied on this connection",
1501                )
1502            })?;
1503        if request.project_id.is_some() {
1504            if state.store.loaded_admission_state().0 == StoreState::Stamped {
1505                return self.stamped_project_get(
1506                    state,
1507                    connection,
1508                    module,
1509                    &declaration,
1510                    &request,
1511                    check_store,
1512                );
1513            }
1514            return Err(GateError::new(
1515                "config_gated",
1516                format!("{module}: project-tuple delivery is not supported yet"),
1517            ));
1518        }
1519        if check_store {
1520            let checked = state.store.check();
1521            if matches!(
1522                state.store.loaded_admission_state().0,
1523                StoreState::StoreMissing | StoreState::StoreUnverified
1524            ) {
1525                return recovery::active_view(state, module, &declaration, &request);
1526            }
1527            checked?;
1528        }
1529        if state.store.loaded_admission_state().0 == StoreState::Unstamped {
1530            if request.generation.is_some() || request.attempt.is_some() {
1531                return Err(GateError::new(
1532                    "config_gated",
1533                    "unstamped reads have no assigned generation or delivery attempt",
1534                ));
1535            }
1536            let mut declarations = Self::declarations(state)?;
1537            declarations.insert(module.into(), declaration);
1538            let mut captured = self
1539                .capturer
1540                .capture_modules(&declarations, &BTreeSet::from([module.to_owned()]))?;
1541            let view = captured
1542                .modules
1543                .remove(module)
1544                .ok_or_else(|| GateError::new("config_gated", "module declaration is unavailable"))?
1545                .view;
1546            return Ok(subc_protocol::config::ConfigGetReply::new(Some(view), None));
1547        }
1548        if check_store {
1549            state.store.delivery_ready()?;
1550        }
1551        let body = if check_store {
1552            state.store.body()?
1553        } else {
1554            state.store.loaded_admission_state().1
1555        };
1556        let tuple = crate::config_store::Tuple {
1557            module: module.into(),
1558            project: None,
1559        };
1560        let versions = body
1561            .versions
1562            .iter()
1563            .find(|(entry, _)| entry == &tuple)
1564            .map(|(_, versions)| versions)
1565            .ok_or_else(|| {
1566                GateError::new("config_gated", "module is not in an approved generation")
1567            })?;
1568        let approved_declaration = versions
1569            .pending
1570            .or(versions.active)
1571            .and_then(|generation| body.generations.get(&generation))
1572            .and_then(|entry| entry.delivery.as_ref())
1573            .and_then(|snapshot| snapshot.declarations.get(module))
1574            == Some(&declaration);
1575        if !approved_declaration && versions.active.is_none() {
1576            return Err(GateError::new(
1577                "config_gated",
1578                "module has no approved active configuration",
1579            ));
1580        }
1581        let view = |generation: Option<u64>, status: ConfigStatus| -> Result<Option<ConfigView>> {
1582            let Some(generation) = generation else {
1583                return Ok(None);
1584            };
1585            let delivery = body
1586                .generations
1587                .get(&generation)
1588                .and_then(|entry| entry.delivery.as_ref())
1589                .ok_or_else(|| {
1590                    GateError::new("config_gated", "approved delivery bytes are absent")
1591                })?;
1592            let mut view =
1593                delivery.modules.get(module).cloned().ok_or_else(|| {
1594                    GateError::new("config_gated", "approved module view is absent")
1595                })?;
1596            view.generation = generation;
1597            view.status = status;
1598            Ok(Some(view))
1599        };
1600        let active = view(versions.active, ConfigStatus::Active)?;
1601        if !approved_declaration {
1602            let mut reply = subc_protocol::config::ConfigGetReply::new(active, None);
1603            reply.declaration_pending = Self::declaration_pending(state, module, &declaration);
1604            return if check_store {
1605                delivery::bind_declaration_fallback(state, connection, module, &request, reply)
1606            } else {
1607                Ok(reply)
1608            };
1609        }
1610        let pending = view(versions.pending, ConfigStatus::Pending)?;
1611        let transition = versions
1612            .pending
1613            .and_then(|id| body.generations.get(&id))
1614            .map(|entry| super::apply::Transition::for_module(&entry.generation.changeset, module))
1615            .transpose()?
1616            .unwrap_or(super::apply::Transition::Live);
1617        if active.is_none() && pending.is_none() {
1618            return Err(GateError::new(
1619                "config_gated",
1620                "module has no active or deliverable generation",
1621            ));
1622        }
1623        if !check_store {
1624            return delivery::visible_reply(
1625                state,
1626                connection,
1627                subc_protocol::config::ConfigGetReply::new(active, pending),
1628                transition,
1629            );
1630        }
1631        delivery::bind_get(
1632            state,
1633            connection,
1634            module,
1635            &request,
1636            subc_protocol::config::ConfigGetReply::new(active, pending),
1637            transition,
1638        )
1639    }
1640
1641    fn declaration_pending(
1642        state: &OwnerState,
1643        module: &str,
1644        declaration: &ConfigDeclareRequest,
1645    ) -> Option<subc_protocol::config::ConfigDeclarationPending> {
1646        let body = state.store.loaded_admission_state().1;
1647        if !body.stamped {
1648            return None;
1649        }
1650        let versions = body
1651            .versions
1652            .iter()
1653            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())?
1654            .1
1655            .clone();
1656        if versions.active.is_none()
1657            || versions
1658                .pending
1659                .or(versions.active)
1660                .and_then(|id| body.generations.get(&id))
1661                .and_then(|entry| entry.delivery.as_ref())
1662                .and_then(|delivery| delivery.declarations.get(module))
1663                == Some(declaration)
1664        {
1665            return None;
1666        }
1667        let mut marker = subc_protocol::config::ConfigDeclarationPending::default();
1668        marker.plan_digest = state
1669            .gate
1670            .plans
1671            .values()
1672            .filter(|plan| {
1673                plan.modules.contains(module)
1674                    && plan
1675                        .delivery
1676                        .as_ref()
1677                        .and_then(|delivery| delivery.declarations.get(module))
1678                        == Some(declaration)
1679            })
1680            .max_by_key(|plan| plan.creation_sequence)
1681            .map(|plan| plan.view.digest.clone());
1682        Some(marker)
1683    }
1684
1685    fn declarations(state: &mut OwnerState) -> Result<BTreeMap<String, ConfigDeclareRequest>> {
1686        if state.store.status().state == StoreState::Stamped {
1687            state.store.body()?;
1688        }
1689        Ok(Self::loaded_declarations(state))
1690    }
1691
1692    fn loaded_declarations(state: &OwnerState) -> BTreeMap<String, ConfigDeclareRequest> {
1693        let (store, body) = state.store.loaded_admission_state();
1694        let mut declarations = if store == StoreState::Stamped {
1695            body.generations
1696                .values()
1697                .next_back()
1698                .and_then(|entry| entry.delivery.as_ref())
1699                .map(|snapshot| snapshot.declarations.clone())
1700                .unwrap_or_default()
1701        } else {
1702            BTreeMap::new()
1703        };
1704        for (module, connection) in &state.active_declarations {
1705            if let Some((_, declaration)) = state.declarations.get(connection) {
1706                declarations.insert(module.clone(), declaration.clone());
1707            }
1708        }
1709        declarations
1710    }
1711
1712    fn capture(&self, state: &mut OwnerState) -> Result<CapturedConfiguration> {
1713        let declarations = Self::declarations(state)?;
1714        let captured = self.capturer.capture(&declarations)?;
1715        state.observed_snapshot = Some(captured.diagnostic.clone());
1716        Ok(captured)
1717    }
1718
1719    fn capture_modules(
1720        &self,
1721        state: &mut OwnerState,
1722        modules: &BTreeSet<String>,
1723    ) -> Result<CapturedConfiguration> {
1724        self.capturer
1725            .capture_modules(&Self::declarations(state)?, modules)
1726    }
1727
1728    fn check_authority(state: &mut OwnerState, recovery: bool) -> Result<()> {
1729        if let Err(error) = state.store.check() {
1730            return if recovery
1731                && matches!(
1732                    state.store.loaded_admission_state().0,
1733                    StoreState::StoreUnverified | StoreState::StoreMissing
1734                ) {
1735                Ok(())
1736            } else {
1737                Err(error.into())
1738            };
1739        }
1740        state.retry_anchor(true);
1741        match state.store.check() {
1742            Ok(()) => Ok(()),
1743            Err(_)
1744                if recovery
1745                    && matches!(
1746                        state.store.status().state,
1747                        StoreState::StoreUnverified | StoreState::StoreMissing
1748                    ) =>
1749            {
1750                Ok(())
1751            }
1752            Err(error) => Err(error.into()),
1753        }
1754    }
1755
1756    /// Run from a blocking worker: capture and store publication may touch disk
1757    /// and the platform keychain. No transport wait takes place under this lock.
1758    /// Preflight may record the proposal observed on disk. Refusals for missing
1759    /// authoritative project membership, active-scope usage or approved-program
1760    /// launch selection happen before any plan, approval or generation is
1761    /// written. A proposal neither approves nor records the refused plan.
1762    pub fn prepare(&self, kind: PlanKind) -> Result<PreparedPlan> {
1763        self.prepare_inner(kind, None)
1764    }
1765
1766    fn prepare_inner(
1767        &self,
1768        kind: PlanKind,
1769        registry: Option<(u64, Result<super::project_registry::RegistryBatch>)>,
1770    ) -> Result<PreparedPlan> {
1771        let mut state = self.lock()?;
1772        Self::check_authority(
1773            &mut state,
1774            matches!(kind, PlanKind::Stamp | PlanKind::Unstamp),
1775        )?;
1776        let registry = if let Some((base, reply)) = registry {
1777            if state.store.status().state != StoreState::Stamped
1778                || state.store.status().base_revision != base
1779            {
1780                return Err(capture_plan::changed());
1781            }
1782            let body = state.store.body()?;
1783            match reply {
1784                Ok(batch) => Some(batch),
1785                Err(error)
1786                    if error.code == "project_registry_unavailable"
1787                        && !capture_plan::known_projects(body) =>
1788                {
1789                    None
1790                }
1791                Err(error) => return Err(capture_plan::registry_retry(error)),
1792            }
1793        } else {
1794            None
1795        };
1796        #[cfg(test)]
1797        if let Some(hook) = self.prepare_capture_hook.lock().unwrap().take() {
1798            hook();
1799        }
1800        let (mut project_capture, observed) = if let Some((enumeration, revisions)) = registry {
1801            let declarations = Self::declarations(&mut state)?;
1802            if !declarations.keys().eq(revisions.keys()) {
1803                return Err(capture_plan::changed());
1804            }
1805            if let Some(enumeration) = &enumeration {
1806                state.store.replace_registry_membership(Ok(enumeration))?;
1807            }
1808            let mut project_plan = CapturePlan::default();
1809            let body = state.store.body()?;
1810            let approved = super::GateSnapshot::from_store(&body.approved)?;
1811            let roots = revisions
1812                .into_iter()
1813                .map(|(module, revision)| {
1814                    ModuleRoots::new(revision, &approved, &mut project_plan.skipped)
1815                        .map(|roots| (module, roots))
1816                })
1817                .collect::<Result<BTreeMap<_, _>>>()?;
1818            project_plan.context.held_user.extend(
1819                roots
1820                    .iter()
1821                    .filter(|(_, roots)| roots.holds_user())
1822                    .map(|(module, _)| module.clone()),
1823            );
1824            let held = capture_plan::retained_user_files(
1825                body,
1826                &approved,
1827                &declarations,
1828                &project_plan.context.held_user,
1829            );
1830            let captured = self
1831                .capturer
1832                .capture_with_retained_user(&declarations, None, held)?;
1833            let (project_plan, observed) = capture_plan::capture_projects(
1834                &self.capturer,
1835                body,
1836                &approved,
1837                &captured,
1838                &roots,
1839                project_plan,
1840            )?;
1841            state.store.observe(observed.to_store()?)?;
1842            state.observed_snapshot = Some(observed);
1843            (Some(project_plan), captured)
1844        } else {
1845            (None, self.capture(&mut state)?)
1846        };
1847        if observed.daemon.bytes.is_none() {
1848            return Err(GateError::new(
1849                "invalid_daemon_config",
1850                "subc.jsonc is absent; refusing to rescan",
1851            ));
1852        }
1853        if project_capture.is_none()
1854            && !state.recovery_exit_hold
1855            && state.store.status().state == StoreState::Stamped
1856        {
1857            let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
1858            state
1859                .store
1860                .observe(observed.proposal_snapshot(&approved).to_store()?)?;
1861        }
1862        let rollback = if let PlanKind::Rollback(id) = kind {
1863            Some(rollback::prepare(self, &mut state, id)?)
1864        } else {
1865            None
1866        };
1867        let (candidate, mut observed, target) = if let Some((candidate, target)) = rollback {
1868            (candidate, Some(observed), Some(target))
1869        } else {
1870            (observed, None, None)
1871        };
1872        if kind == PlanKind::Stamp {
1873            super::registration::check_stamp(&candidate.diagnostic)?;
1874        }
1875        let base_revision = state.store.status().base_revision;
1876        let old = if state.store.status().state == StoreState::Stamped {
1877            super::GateSnapshot::from_store(&state.store.body()?.approved)?
1878        } else {
1879            super::GateSnapshot::default()
1880        };
1881        let mut touched_modules: BTreeSet<_> = candidate
1882            .diagnostic
1883            .changed_keys(&old)
1884            .iter()
1885            .filter(|key| !key.is_project())
1886            .filter_map(|key| key.module().map(str::to_owned))
1887            .collect();
1888        if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
1889            touched_modules.extend(candidate.diagnostic.modules());
1890            touched_modules.extend(old.modules());
1891        }
1892        if let Some(target) = target {
1893            touched_modules.extend(
1894                candidate
1895                    .diagnostic
1896                    .inputs
1897                    .iter()
1898                    .filter(|(key, value)| {
1899                        key.is_program() && target.inputs.get(*key) != Some(*value)
1900                    })
1901                    .filter_map(|(key, _)| key.module().map(str::to_owned)),
1902            );
1903        }
1904        let mut review_modules: BTreeSet<String> = touched_modules
1905            .iter()
1906            .filter(|module| candidate.modules.contains_key(*module))
1907            .filter(|module|matches!(kind,PlanKind::Stamp|PlanKind::Unstamp) || candidate.diagnostic.changed_keys(&old).iter().any(|key|matches!(key,super::InputKey::Layer {module:owner,..}|super::InputKey::Declaration(owner) if owner==*module)))
1908            .cloned()
1909            .collect();
1910        if let Some(projects) = &project_capture {
1911            touched_modules.extend(projects.reviews.keys().map(|tuple| tuple.module.clone()));
1912        }
1913        // A program change is approved launch-only: neither the build being
1914        // approved nor the one still running can review for it. Once the new
1915        // program is active, the next plan re-reviews the approved layers with
1916        // it. While it is not yet active the module waits, and the plan
1917        // carries its earlier reviewer forward.
1918        let mut rereview_modules = BTreeSet::new();
1919        if matches!(kind, PlanKind::Change | PlanKind::Rollback(_))
1920            && state.store.status().state == StoreState::Stamped
1921        {
1922            for (module, rereview) in
1923                super::reviewed_build::pending(state.store.body()?, candidate.modules.keys())?
1924            {
1925                if rereview == super::reviewed_build::Rereview::Ready
1926                    && !review_modules.contains(&module)
1927                {
1928                    touched_modules.insert(module.clone());
1929                    review_modules.insert(module.clone());
1930                    rereview_modules.insert(module);
1931                }
1932            }
1933        }
1934        let program_keys: Vec<_> = candidate
1935            .diagnostic
1936            .inputs
1937            .keys()
1938            .filter(|key| {
1939                key.is_program()
1940                    && key
1941                        .module()
1942                        .is_some_and(|module| touched_modules.contains(module))
1943            })
1944            .cloned()
1945            .collect();
1946        let read_set = if let Some(observed) = &mut observed {
1947            observed.capture_programs(&program_keys)?;
1948            if program_keys.iter().any(|key| {
1949                observed.diagnostic.inputs.get(key) != candidate.diagnostic.inputs.get(key)
1950            }) {
1951                return Err(GateError::stale());
1952            }
1953            observed.diagnostic.read_set(&touched_modules)?
1954        } else {
1955            candidate.diagnostic.read_set(&touched_modules)?
1956        };
1957        let observed_handles = observed
1958            .as_mut()
1959            .map(CapturedConfiguration::take_handles)
1960            .unwrap_or_default();
1961        let mut bases = BTreeMap::new();
1962        let mut base_schemas = BTreeMap::new();
1963        let mut active_generations = BTreeMap::new();
1964        if state.store.status().state == StoreState::Stamped {
1965            let body = state.store.body()?;
1966            let approved_id = placement::last_approved_generation(body);
1967            for (tuple, versions) in &body.versions {
1968                if touched_modules.contains(&tuple.module) {
1969                    active_generations.insert(tuple.clone(), versions.active);
1970                }
1971                if tuple.project.is_some() || !review_modules.contains(&tuple.module) {
1972                    continue;
1973                }
1974                // A plan replaces the last approval, even when that generation
1975                // has not activated. The reviewer and the card use that base.
1976                // A launch entry alone is not an approved configuration base;
1977                // only a retained declaration establishes one for review.
1978                if old
1979                    .inputs
1980                    .contains_key(&super::InputKey::Declaration(tuple.module.clone()))
1981                {
1982                    let id = approved_id;
1983                    let snapshot = body
1984                        .generations
1985                        .get(&id)
1986                        .and_then(|entry| entry.delivery.as_ref())
1987                        .ok_or_else(|| {
1988                            GateError::new(
1989                                "approved_schema_unavailable",
1990                                format!(
1991                                    "{}: approved old schema is missing or damaged",
1992                                    tuple.module
1993                                ),
1994                            )
1995                        })?;
1996                    let schema = snapshot
1997                        .declarations
1998                        .get(&tuple.module)
1999                        .and_then(|declaration| {
2000                            subc_config::Schema::new(declaration.schema.clone()).ok()
2001                        })
2002                        .ok_or_else(|| {
2003                            GateError::new(
2004                                "approved_schema_unavailable",
2005                                format!(
2006                                    "{}: approved old schema is missing or damaged",
2007                                    tuple.module
2008                                ),
2009                            )
2010                        })?;
2011                    base_schemas.insert(tuple.module.clone(), schema);
2012                    let view = snapshot.modules.get(&tuple.module).ok_or_else(|| {
2013                        GateError::new(
2014                            "config_gated",
2015                            format!("{}: approved view is absent", tuple.module),
2016                        )
2017                    })?;
2018                    let mut view = view.clone();
2019                    view.generation = id;
2020                    view.status = if versions.active == Some(id) {
2021                        ConfigStatus::Active
2022                    } else {
2023                        ConfigStatus::Pending
2024                    };
2025                    bases.insert(tuple.module.clone(), view);
2026                }
2027            }
2028        }
2029        Ok(PreparedPlan {
2030            edits: None,
2031            projects: None,
2032            project_capture: project_capture.take(),
2033            settings_users: None,
2034            candidate,
2035            bases,
2036            base_schemas,
2037            kind,
2038            review_modules,
2039            rereview_modules,
2040            base_revision,
2041            active_generations,
2042            touched_modules,
2043            read_set,
2044            program_keys,
2045            observed_handles,
2046        })
2047    }
2048
2049    pub fn finish_plan(
2050        &self,
2051        mut prepared: PreparedPlan,
2052        review: impl FnOnce(&super::GateSnapshot, &super::GateSnapshot) -> Result<Changeset>,
2053    ) -> Result<ConfigPlanView> {
2054        let workspaces = if let Some(projects) = &prepared.project_capture {
2055            runtime_capture::reviewed_workspace_reads(Some(&projects.context), &projects.files)?
2056        } else {
2057            Vec::new()
2058        };
2059        let settings_file_witness = if prepared.settings_users.is_some() || !workspaces.is_empty() {
2060            let current = self.read_settings_file_witness(
2061                &prepared.settings_users.clone().unwrap_or_default(),
2062                workspaces,
2063            )?;
2064            prepared.settings_users.is_some().then_some(current)
2065        } else {
2066            None
2067        };
2068        let mut state = self.lock()?;
2069        Self::check_authority(
2070            &mut state,
2071            matches!(prepared.kind, PlanKind::Stamp | PlanKind::Unstamp),
2072        )?;
2073        let project_plan = prepared.project_capture.take();
2074        if let Some(projects) = &project_plan {
2075            if !projects.reviews.is_empty() || !projects.refusals.is_empty() {
2076                return Err(GateError::new(
2077                    "module_review_invalid",
2078                    "project reviews were not accepted",
2079                ));
2080            }
2081        }
2082        let active_generations = if state.store.status().state == StoreState::Stamped {
2083            state
2084                .store
2085                .body()?
2086                .versions
2087                .iter()
2088                .filter(|(tuple, _)| prepared.touched_modules.contains(&tuple.module))
2089                .map(|(tuple, versions)| (tuple.clone(), versions.active))
2090                .collect()
2091        } else {
2092            BTreeMap::new()
2093        };
2094        let mut current = if let Some(users) = &prepared.settings_users {
2095            self.capture_settings_users(&state, Some(users), None)
2096                .map(|(capture, ..)| capture)
2097        } else if let Some(edit) = &prepared.edits {
2098            self.edit_baseline(
2099                &mut state,
2100                Some(if edit.unstamped {
2101                    &prepared.touched_modules
2102                } else {
2103                    &edit.user_modules
2104                }),
2105            )
2106        } else if let Some(projects) = &project_plan {
2107            self.capture_with_project_context(
2108                &mut state,
2109                &prepared.touched_modules,
2110                &projects.context,
2111            )
2112        } else {
2113            self.capture_modules(&mut state, &prepared.touched_modules)
2114        }
2115        .map_err(|_| GateError::stale())?;
2116        if prepared.settings_users.is_none() {
2117            current
2118                .capture_programs(&prepared.program_keys)
2119                .map_err(|_| GateError::stale())?;
2120        }
2121        if ((prepared.edits.is_none() || project_plan.is_some())
2122            && state.store.status().base_revision != prepared.base_revision)
2123            || active_generations != prepared.active_generations
2124            || !prepared
2125                .read_set
2126                .matches(&current.diagnostic.read_set(&prepared.touched_modules)?)
2127        {
2128            return Err(if prepared.edits.is_some() {
2129                GateError::new(
2130                    "config_changed_since_review",
2131                    "a touched module changed while the edits were reviewed",
2132                )
2133            } else {
2134                GateError::stale()
2135            });
2136        }
2137        if prepared.edits.is_some() {
2138            // Carry forward approvals for modules outside the edit set. Changes
2139            // to those approvals must neither refuse these edits nor be reverted by them.
2140            let daemon_edit = prepared
2141                .edits
2142                .as_ref()
2143                .is_some_and(|edit| edit.policy_root.is_some());
2144            if daemon_edit {
2145                Self::no_pending_policy_root(&state)?;
2146            }
2147            let touched = &prepared.touched_modules;
2148            for (key, input) in &current.diagnostic.inputs {
2149                if daemon_edit && *key == super::InputKey::Daemon {
2150                    continue;
2151                }
2152                if key.module().is_none_or(|module| !touched.contains(module)) {
2153                    prepared
2154                        .candidate
2155                        .diagnostic
2156                        .inputs
2157                        .insert(key.clone(), input.clone());
2158                }
2159            }
2160            prepared.candidate.diagnostic.inputs.retain(|key, _| {
2161                key.module().is_some_and(|module| touched.contains(module))
2162                    || current.diagnostic.inputs.contains_key(key)
2163            });
2164            prepared
2165                .candidate
2166                .modules
2167                .retain(|module, _| touched.contains(module));
2168            for (module, captured) in std::mem::take(&mut current.modules) {
2169                if !touched.contains(&module) {
2170                    prepared.candidate.modules.insert(module, captured);
2171                }
2172            }
2173        }
2174        let mut project_context = None;
2175        let mut project_skips = Vec::new();
2176        let mut edit_registry = BTreeMap::new();
2177        let mut file_summary = Vec::new();
2178        if let Some(users) = &prepared.settings_users {
2179            for module in users {
2180                file_summary.push(subc_control::config::ConfigSettingsFile {
2181                    layer: subc_config::Layer::User,
2182                    module_id: module.clone(),
2183                    path: prepared.candidate.modules[module].file.path.clone(),
2184                    workspace_id: None,
2185                    affected_projects: Vec::new(),
2186                });
2187            }
2188        }
2189        if let Some(projects) = project_plan {
2190            let CapturePlan {
2191                mut context,
2192                witnesses,
2193                skipped,
2194                files,
2195                ..
2196            } = projects;
2197            if prepared.edits.is_some() {
2198                for (module, authority) in &context.authority {
2199                    edit_registry.insert(module.clone(), authority.revision_digest()?);
2200                }
2201            }
2202            for (key, input) in &witnesses.inputs {
2203                if matches!(key, super::InputKey::ProjectTuple { .. }) {
2204                    context.witnesses.inputs.insert(key.clone(), input.clone());
2205                }
2206            }
2207            current
2208                .diagnostic
2209                .inputs
2210                .extend(context.witnesses.inputs.clone());
2211            prepared
2212                .candidate
2213                .diagnostic
2214                .inputs
2215                .extend(witnesses.inputs);
2216            if !files.is_empty() {
2217                if prepared.settings_users.is_some() {
2218                    for file in &files {
2219                        let target = file.target();
2220                        let crate::config_store::ProjectFileLayer::Workspace { workspace_id } =
2221                            &target.layer
2222                        else {
2223                            unreachable!("automatic settings plans have no project-layer files")
2224                        };
2225                        let path = target.path().expect("captured workspace path");
2226                        let readers = context.authority[&target.module].readers_of(&path);
2227                        file_summary.push(subc_control::config::ConfigSettingsFile {
2228                            layer: subc_config::Layer::Workspace,
2229                            module_id: target.module.clone(),
2230                            path,
2231                            workspace_id: Some(workspace_id.clone()),
2232                            affected_projects: readers.into_iter().collect(),
2233                        });
2234                    }
2235                }
2236                prepared.projects.get_or_insert_with(Default::default).files = files;
2237            }
2238            project_skips = skipped;
2239            project_context = Some(context);
2240        }
2241        let delivery = DeliverySnapshot {
2242            daemon: Some(ConfigLayerSnapshot::file(
2243                "subc",
2244                ConfigLayer::User,
2245                prepared.candidate.daemon.path.to_string_lossy(),
2246                prepared.candidate.daemon.bytes.clone(),
2247            )),
2248            modules: prepared
2249                .candidate
2250                .modules
2251                .iter()
2252                .map(|(module, captured)| (module.clone(), captured.view.clone()))
2253                .collect(),
2254            declarations: prepared
2255                .candidate
2256                .modules
2257                .iter()
2258                .map(|(module, captured)| (module.clone(), captured.declaration.clone()))
2259                .collect(),
2260            ..DeliverySnapshot::default()
2261        };
2262        let mut handles = prepared.candidate.take_handles();
2263        let user_restore = if prepared.kind == PlanKind::Change && prepared.edits.is_none() {
2264            prepared
2265                .candidate
2266                .modules
2267                .iter()
2268                .filter(|(module, _)| prepared.touched_modules.contains(*module))
2269                .filter_map(|(_, captured)| {
2270                    super::restore::UserRestoreMetadata::capture(&captured.file)
2271                        .map(|metadata| (captured.file.path.clone(), metadata))
2272                })
2273                .collect()
2274        } else {
2275            BTreeMap::new()
2276        };
2277        handles.append(&mut prepared.observed_handles);
2278        let previous_delivery = if state.store.status().state == StoreState::Stamped {
2279            let body = state.store.body()?;
2280            body.generations
2281                .get(&placement::last_approved_generation(body))
2282                .and_then(|entry| entry.delivery.clone())
2283        } else if prepared.edits.as_ref().is_some_and(|edit| edit.unstamped) {
2284            Some(DeliverySnapshot {
2285                daemon: delivery.daemon.clone(),
2286                modules: prepared.bases.clone(),
2287                declarations: delivery.declarations.clone(),
2288                ..DeliverySnapshot::default()
2289            })
2290        } else {
2291            None
2292        };
2293        // Activation policy compares the candidate with what is running, not
2294        // with the last approval used by the visible field rows.
2295        let mut active_fields = Vec::new();
2296        for (module, captured) in prepared.candidate.modules.iter().filter(|(module, _)| {
2297            // Stamping records the inputs already running; unstamping returns
2298            // authority to files. Neither operation changes runtime values.
2299            matches!(prepared.kind, PlanKind::Change | PlanKind::Rollback(_))
2300                && prepared.touched_modules.contains(*module)
2301        }) {
2302            let active = if state.store.status().state == StoreState::Stamped {
2303                let body = state.store.body()?;
2304                body.versions
2305                    .iter()
2306                    .find(|(tuple, _)| tuple.module == *module && tuple.project.is_none())
2307                    .and_then(|(_, versions)| versions.active)
2308                    .and_then(|id| body.generations.get(&id))
2309                    .and_then(|entry| entry.delivery.as_ref())
2310            } else {
2311                None
2312            };
2313            let base = active.and_then(|snapshot| snapshot.modules.get(module));
2314            let schema = active
2315                .and_then(|snapshot| snapshot.declarations.get(module))
2316                .map(|declaration| subc_config::Schema::new(declaration.schema.clone()))
2317                .transpose()
2318                .map_err(GateError::invalid)?;
2319            active_fields.extend(
2320                super::review::expected_fields(
2321                    module,
2322                    &captured.schema,
2323                    base,
2324                    schema.as_ref(),
2325                    &captured.view,
2326                )?
2327                .into_values(),
2328            );
2329        }
2330        let OwnerState { gate, store, .. } = &mut *state;
2331        let mut view = gate.plan_reviewed_inner(
2332            store,
2333            prepared.kind,
2334            prepared.candidate.diagnostic,
2335            &current.diagnostic,
2336            super::ReviewRecord::Reviewed(&prepared.review_modules),
2337            prepared.edits,
2338            prepared.projects,
2339            settings_file_witness,
2340            |old, new| {
2341                let mut changeset = review(old, new)?;
2342                layer_file_rows(
2343                    &mut changeset,
2344                    old,
2345                    new,
2346                    previous_delivery.as_ref(),
2347                    &delivery,
2348                )?;
2349                let mut activation = changeset.clone();
2350                activation.fields = active_fields;
2351                super::apply::bind_plan(&mut activation)?;
2352                if !changeset.apply_plan.is_object() {
2353                    changeset.apply_plan = if changeset.apply_plan.is_null() {
2354                        serde_json::json!({})
2355                    } else {
2356                        serde_json::json!({"review": changeset.apply_plan})
2357                    };
2358                }
2359                if !edit_registry.is_empty() {
2360                    changeset.apply_plan["edit_registry"] = serde_json::json!(edit_registry);
2361                }
2362                changeset.apply_plan["module_transitions"] =
2363                    activation.apply_plan["module_transitions"].clone();
2364                Ok(changeset)
2365            },
2366        )?;
2367        view.skipped = project_skips;
2368        if !file_summary.is_empty() {
2369            let fields = &view.plan.changeset.fields;
2370            for file in &mut file_summary {
2371                if file.layer == subc_config::Layer::User {
2372                    file.affected_projects = fields
2373                        .iter()
2374                        .filter(|field| {
2375                            field.module_id == file.module_id
2376                                && (field.old_source == file.layer
2377                                    || field.new_source == file.layer)
2378                        })
2379                        .filter_map(|field| field.project_id.clone())
2380                        .collect::<BTreeSet<_>>()
2381                        .into_iter()
2382                        .collect();
2383                } else {
2384                    file.affected_projects
2385                        .retain(|project| view.plan.changeset.affected_projects.contains(project));
2386                }
2387            }
2388            view.settings_file_change = Some(subc_control::config::ConfigSettingsFileChange {
2389                label: "A settings file changed".into(),
2390                files: file_summary,
2391            });
2392        }
2393        if let Some(plan) = gate.plans.get_mut(&view.digest) {
2394            plan.user_restore = user_restore;
2395            plan.project_capture = project_context;
2396            plan.settings_users = prepared.settings_users;
2397            plan.view.skipped.clone_from(&view.skipped);
2398            plan.view
2399                .settings_file_change
2400                .clone_from(&view.settings_file_change);
2401        }
2402        if let Err(error) = self.check_route_policy_authority(&view.plan.changeset) {
2403            gate.expire_plan(&view.digest);
2404            return Err(error);
2405        }
2406        gate.bind_delivery(&view.digest, delivery)?;
2407        state.reviewed(&view.digest, Instant::now());
2408        state
2409            .retained_plan_files
2410            .insert(view.digest.clone(), handles);
2411        Ok(view)
2412    }
2413
2414    pub fn begin_approval(
2415        &self,
2416        digest: &Digest,
2417        facts: &ApprovalFacts,
2418    ) -> Result<ApprovalChallenge> {
2419        self.begin_approval_for_request(digest, facts, None)
2420    }
2421
2422    pub(crate) fn begin_approval_for_request(
2423        &self,
2424        digest: &Digest,
2425        facts: &ApprovalFacts,
2426        request: Option<&ApprovalRequest>,
2427    ) -> Result<ApprovalChallenge> {
2428        self.begin_approval_inner(digest, facts, request, None)
2429    }
2430
2431    pub(crate) fn next_settings_request_order(&self) -> u64 {
2432        self.settings_request_order
2433            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2434    }
2435
2436    pub(crate) fn begin_settings_apply_for_request(
2437        &self,
2438        digest: &Digest,
2439        facts: &ApprovalFacts,
2440        request: &ApprovalRequest,
2441        order: u64,
2442    ) -> Result<ApprovalChallenge> {
2443        self.begin_approval_inner(digest, facts, Some(request), Some(order))
2444    }
2445
2446    fn begin_approval_inner(
2447        &self,
2448        digest: &Digest,
2449        facts: &ApprovalFacts,
2450        request: Option<&ApprovalRequest>,
2451        settings_apply: Option<u64>,
2452    ) -> Result<ApprovalChallenge> {
2453        #[cfg(test)]
2454        struct Completion<'a>(&'a std::sync::atomic::AtomicUsize);
2455        #[cfg(test)]
2456        impl Drop for Completion<'_> {
2457            fn drop(&mut self) {
2458                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2459            }
2460        }
2461        #[cfg(test)]
2462        let _completed = Completion(&self.begin_approval_completions);
2463        #[cfg(test)]
2464        {
2465            let hook = self.begin_approval_hook.lock().unwrap().take();
2466            if let Some(hook) = hook {
2467                hook();
2468            }
2469        }
2470        let settings_file_witness = self.recheck_settings_file_witness(digest)?;
2471        let mut state = self.lock()?;
2472        if let Some(request) = request {
2473            request.ensure_live()?;
2474        }
2475        let daemon = facts.caller.is_daemon_settings();
2476        if let Some(order) = settings_apply {
2477            if daemon {
2478                state.claim_automatic_settings_plan(digest, order)?;
2479            }
2480            if !daemon && order < state.latest_explicit_settings_request {
2481                return Err(GateError::new(
2482                    "approval_surface_unavailable",
2483                    "a newer settings approval took precedence",
2484                ));
2485            }
2486            state.check_settings_approval(digest, daemon)?;
2487        }
2488        if state.expired_plans.contains(digest) {
2489            return Err(GateError::new(
2490                "plan_expired",
2491                "configuration plan exceeded its one-hour idle lifetime",
2492            ));
2493        }
2494        Self::check_authority(&mut state, true)?;
2495        let modules = state.gate.plan_modules(digest)?;
2496        if state.gate.plans[digest].settings_file_witness != settings_file_witness {
2497            return Err(capture_plan::changed());
2498        }
2499        let program_keys = state.gate.plan_program_keys(digest)?;
2500        let projects = state.gate.plans[digest].project_capture.clone();
2501        let user_edits = state.gate.plans[digest]
2502            .edits
2503            .as_ref()
2504            .map(|edit| edit.user_modules.clone());
2505        let settings_users = state.gate.plans[digest].settings_users.clone();
2506        let mut current = if let Some(users) = &settings_users {
2507            self.capture_settings_users(&state, Some(users), None)
2508                .map(|(capture, ..)| capture)
2509        } else if let Some(user_edits) = &user_edits {
2510            self.edit_baseline(&mut state, Some(user_edits))
2511        } else if let Some(capture) = &projects {
2512            self.capture_with_project_context(&mut state, &modules, capture)
2513        } else {
2514            self.capture_modules(&mut state, &modules)
2515        }
2516        .map_err(|_| GateError::stale())?;
2517        if let Some(capture) = projects {
2518            current.diagnostic.inputs.extend(capture.witnesses.inputs);
2519        }
2520        if settings_users.is_none() {
2521            current
2522                .capture_programs(&program_keys)
2523                .map_err(|_| GateError::stale())?;
2524        }
2525        let facts = state.with_desktop_view(digest, facts);
2526        let OwnerState { gate, store, .. } = &mut *state;
2527        if let Some(request) = request {
2528            request.ensure_live()?;
2529        }
2530        let challenge = gate.begin_approval(digest, store, &current.diagnostic, &facts)?;
2531        if let Some(order) = settings_apply {
2532            self.reserve_settings_approval(&mut state, digest, &challenge, daemon);
2533            if let Some(plan) = state.gate.plans.get_mut(digest) {
2534                plan.settings_attempt_owner = Some(order);
2535            }
2536            if !daemon {
2537                state.latest_explicit_settings_request = order;
2538            }
2539        }
2540        state.reviewed(digest, Instant::now());
2541        Ok(challenge)
2542    }
2543
2544    /// Acquire only after interactive approval. Sorted module locks serialize
2545    /// the final freshness check and publication with target changes at cutover.
2546    pub(crate) async fn approval_commit_gates(
2547        self: &std::sync::Arc<Self>,
2548        attempt: u64,
2549    ) -> Result<Vec<tokio::sync::OwnedMutexGuard<()>>> {
2550        let modules = self
2551            .on_blocking(move |owner| owner.lock()?.gate.approval_gate_modules(attempt))
2552            .await?;
2553        let mut guards = Vec::with_capacity(modules.len());
2554        for module in modules {
2555            guards.push(self.module_gate(&module)?.lock_owned().await);
2556        }
2557        Ok(guards)
2558    }
2559
2560    pub fn finish_approval(
2561        &self,
2562        attempt: u64,
2563        facts: &ApprovalFacts,
2564        reply: ApprovalReply,
2565        now_ms: u64,
2566    ) -> Result<u64> {
2567        // In-process approvals have no reader reservation. Wire approvals pass
2568        // their exact request token into the publication job instead.
2569        self.finish_approval_with_commit_window(
2570            attempt,
2571            facts,
2572            reply,
2573            now_ms,
2574            None,
2575            ApprovalRequest::for_attempt(attempt),
2576            None,
2577        )
2578    }
2579
2580    #[allow(clippy::too_many_arguments)]
2581    pub(crate) fn finish_approval_with_commit_window(
2582        &self,
2583        attempt: u64,
2584        facts: &ApprovalFacts,
2585        reply: ApprovalReply,
2586        now_ms: u64,
2587        window: Option<std::sync::Arc<ApprovalCommitWindow>>,
2588        cancellation: std::sync::Arc<ApprovalRequest>,
2589        project_apply: Option<CaptureApply>,
2590    ) -> Result<u64> {
2591        if cancellation.attempt() != attempt {
2592            return Err(GateError::new(
2593                "config_unavailable",
2594                "approval request witness does not match its attempt",
2595            ));
2596        }
2597        // The controller now holds the locks that serialize rescan and module
2598        // replacement. Reopen the workspace files before publishing the store.
2599        let reviewed_digest = self.lock()?.gate.approval_digest(attempt)?;
2600        let settings_file_witness = self.recheck_settings_file_witness(&reviewed_digest)?;
2601        let mut state = self.lock()?;
2602        let digest = state.gate.approval_digest(attempt)?;
2603        if digest != reviewed_digest
2604            || state.gate.plans[&digest].settings_file_witness != settings_file_witness
2605        {
2606            return Err(capture_plan::changed());
2607        }
2608        let project_capture = state.gate.plans[&digest].project_capture.clone();
2609        let settings_users = state.gate.plans[&digest].settings_users.clone();
2610        if let Some(capture) = &project_capture {
2611            if !capture.authority.is_empty()
2612                && project_apply
2613                    .as_ref()
2614                    .is_none_or(|apply| apply.digest != digest)
2615            {
2616                return Err(capture_plan::changed());
2617            }
2618            if state.store.status().base_revision
2619                != state.gate.plans[&digest].view.plan.base_revision
2620            {
2621                return Err(capture_plan::changed());
2622            }
2623        }
2624        if let Some(enumeration) = project_apply.and_then(|apply| apply.enumeration) {
2625            state.store.replace_registry_membership(Ok(&enumeration))?;
2626        }
2627        let declarations_only = state
2628            .gate
2629            .plans
2630            .get(&digest)
2631            .is_some_and(|plan| plan.development_approval.is_some());
2632        state.reviewed(&digest, Instant::now());
2633        let modules = state.gate.approval_modules(attempt)?;
2634        let user_modules = state.gate.plans[&digest]
2635            .targets()?
2636            .into_iter()
2637            .filter(|tuple| tuple.project.is_none())
2638            .map(|tuple| tuple.module)
2639            .collect();
2640        let program_keys = state.gate.plan_program_keys(&digest)?;
2641        // Reopen inputs after the operator's interactive confirmation, immediately
2642        // before freshness checking and atomic publication of the saved plan.
2643        let edit_plan = state
2644            .gate
2645            .plans
2646            .get(&digest)
2647            .and_then(|plan| plan.edits.clone());
2648        let current = match Self::check_authority(&mut state, true).and_then(|_| {
2649            let mut current = if let Some(users) = &settings_users {
2650                self.capture_settings_users(&state, Some(users), None)
2651                    .map(|(capture, ..)| capture)
2652            } else if let Some(edit) = &edit_plan {
2653                self.edit_baseline(&mut state, Some(&edit.user_modules))
2654            } else if let Some(capture) = &project_capture {
2655                self.capture_with_project_context(&mut state, &modules, capture)
2656            } else {
2657                self.capture_modules(&mut state, &modules)
2658            }
2659            .map_err(|_| {
2660                if project_capture.is_some() {
2661                    capture_plan::changed()
2662                } else {
2663                    GateError::stale()
2664                }
2665            })?;
2666            if let Some(capture) = &project_capture {
2667                current
2668                    .diagnostic
2669                    .inputs
2670                    .extend(capture.witnesses.inputs.clone());
2671            }
2672            if settings_users.is_none() {
2673                current
2674                    .capture_programs(&program_keys)
2675                    .map_err(|_| GateError::stale())?;
2676            }
2677            Ok(current)
2678        }) {
2679            Ok(current) => current,
2680            Err(error) => {
2681                state.gate.cancel_attempt(attempt);
2682                return Err(error);
2683            }
2684        };
2685        let facts = state.with_desktop_view(&digest, facts);
2686        self.drain_canceled_approvals(&mut state);
2687        self.drain_disconnections(&mut state);
2688        #[cfg(test)]
2689        if let Some(hook) = state.after_approval_drain_hook.take() {
2690            hook();
2691        }
2692        let was_unstamped = state.store.status().state == StoreState::Unstamped;
2693        let was_recovery = state.recovery_exit_hold
2694            || matches!(
2695                state.store.status().state,
2696                StoreState::StoreMissing | StoreState::StoreUnverified
2697            );
2698        let unstamp_hints = recovery::changed_file_views(self, &mut state, &current);
2699        #[cfg(test)]
2700        let publication_hook = state.publication_hook.take();
2701        #[cfg(test)]
2702        let prepublication_hook = state.prepublication_hook.take();
2703        let publication_before = state.store.publication_sequence();
2704        let (_, loaded) = state.store.loaded_admission_state();
2705        let ledger_checkpoint = crate::policy_root::ledger::last_checkpoint(loaded)
2706            .map(|(_, checkpoint)| checkpoint.clone());
2707        let pin_history = edit_plan
2708            .as_ref()
2709            .is_some_and(|edit| edit.policy_root.is_some())
2710            && policy_root::has_pin_history(loaded);
2711        let stamp_ledger = state
2712            .gate
2713            .plans
2714            .get(&digest)
2715            .and_then(|plan| self.stamp_ledger_intent(loaded, plan));
2716        let OwnerState {
2717            gate,
2718            store,
2719            route_policy_receipts,
2720            installed_route_policies,
2721            delivery,
2722            ..
2723        } = &mut *state;
2724        let result = gate.finish_approval_with_precommit(
2725            attempt,
2726            reply,
2727            store,
2728            &current.diagnostic,
2729            &facts,
2730            now_ms,
2731            || {
2732                #[cfg(test)]
2733                if let Some(hook) = prepublication_hook {
2734                    hook();
2735                }
2736                if let Some(window) = window {
2737                    window.begin_publication()?;
2738                }
2739                {
2740                    // Serialize the publication claim with cancellation-index
2741                    // health, then release the index before any store work.
2742                    let _index = self.approval_request_index.lock().map_err(|_| {
2743                        GateError::new(
2744                            "config_unavailable",
2745                            "approval cancellation index is poisoned",
2746                        )
2747                    })?;
2748                    cancellation.claim_publication()?;
2749                }
2750                if !declarations_only {
2751                    route_policy::restore_superseded(
2752                        route_policy_receipts,
2753                        installed_route_policies,
2754                        &user_modules,
2755                        delivery,
2756                    );
2757                }
2758                let checkpoint = if let Some(change) = edit_plan
2759                    .as_ref()
2760                    .and_then(|edit| edit.policy_root.as_ref())
2761                {
2762                    Some(self.publish_policy_root_ledger(
2763                        change,
2764                        now_ms,
2765                        ledger_checkpoint.as_ref(),
2766                        pin_history,
2767                    )?)
2768                } else if let Some(intent) = stamp_ledger {
2769                    self.publish_stamp_ledger(intent, now_ms, ledger_checkpoint.as_ref())?
2770                } else {
2771                    None
2772                };
2773                #[cfg(test)]
2774                if let Some(hook) = publication_hook {
2775                    hook();
2776                }
2777                Ok(checkpoint)
2778            },
2779        );
2780        let committed_this_call = state.store.publication_sequence() != publication_before;
2781        if committed_this_call {
2782            if let Some((card, card_attempt)) = state.pending_settings_card.take() {
2783                state.cancel_approval(card_attempt);
2784                Self::discard_settings_plan(&mut state, &card);
2785            }
2786            if state.store.status().state == StoreState::Unstamped {
2787                self.replace_unstamped_root(
2788                    policy_root::captured_section(&current)
2789                        .unwrap_or(Err("policy_root_not_canonical")),
2790                );
2791            }
2792            if let Some(edit_plan) = edit_plan {
2793                for file in &edit_plan.files {
2794                    let _ = file.write_back();
2795                }
2796                // Publication already succeeded. Refresh drift after reconciliation
2797                // without turning a failed diagnostic capture into a failed approval.
2798                let _ = self.observe_proposal(&mut state);
2799            }
2800        }
2801        let stamped_files = committed_this_call
2802            && (was_unstamped || was_recovery)
2803            && state.store.body().is_ok_and(|body| {
2804                body.generations
2805                    .get(&body.last_generation)
2806                    .is_some_and(|entry| {
2807                        entry.generation.plan_digest == digest
2808                            && entry.kind == crate::config_store::CommitKind::Stamp
2809                    })
2810            });
2811        if result.is_ok() {
2812            state.plan_deadlines.remove(&digest);
2813            state.retained_plan_files.remove(&digest);
2814            state.desktop_views.retain(|_, (shown, _)| shown != &digest);
2815        }
2816        let unstamped = result.is_ok() && state.store.status().state == StoreState::Unstamped;
2817        let committed_exit = state
2818            .store
2819            .loaded_admission_state()
2820            .1
2821            .generations
2822            .iter()
2823            .next_back()
2824            .filter(|(_, entry)| {
2825                committed_this_call
2826                    && entry.generation.plan_digest == digest
2827                    && entry.kind != crate::config_store::CommitKind::DeclarationApproval
2828                    && (was_recovery
2829                        || state.store.loaded_admission_state().1.stamped
2830                        || entry.kind == crate::config_store::CommitKind::Unstamp)
2831            })
2832            .map(|(generation, entry)| {
2833                (
2834                    *generation,
2835                    entry.kind == crate::config_store::CommitKind::Unstamp,
2836                )
2837            });
2838        if committed_this_call && was_recovery {
2839            state.authority_incarnation = std::sync::Arc::new(());
2840        }
2841        if let Some((generation, unstamp)) = committed_exit {
2842            state.authority_exit = Some(generation);
2843            state.recovery_exit_hold = was_recovery;
2844            if was_recovery || unstamp {
2845                state
2846                    .delivery
2847                    .reset_for_authority_exit(if unstamp { generation } else { 0 });
2848            }
2849            if unstamp {
2850                state.pending_settings_card_reason = None;
2851                state.settings_review_errors.clear();
2852                state.settings_review_errors_base = None;
2853                state.last_settings_decline = None;
2854                state.stamp_channel_cutover = false;
2855                state.reconciled_entries.clear();
2856                state.unstamp_hints.extend(unstamp_hints);
2857            }
2858        } else if committed_this_call {
2859            state.authority_exit = None;
2860        }
2861        if stamped_files {
2862            state.stamp_channel_cutover = true;
2863            let connections: Vec<_> = state.active_declarations.values().copied().collect();
2864            state.delivery.remember_stamp_connections(connections);
2865        }
2866        drop(state);
2867        if unstamped {
2868            self.retire_unstamped_bindings();
2869        }
2870        result
2871    }
2872
2873    #[cfg(all(test, unix))]
2874    pub(crate) fn set_publication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2875        self.inner.lock().unwrap().publication_hook = Some(Box::new(hook));
2876    }
2877
2878    #[cfg(all(test, unix))]
2879    pub(crate) fn set_prepublication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2880        self.inner.lock().unwrap().prepublication_hook = Some(Box::new(hook));
2881    }
2882
2883    #[cfg(all(test, unix))]
2884    pub(crate) fn set_after_approval_drain_hook(&self, hook: impl FnOnce() + Send + 'static) {
2885        self.inner.lock().unwrap().after_approval_drain_hook = Some(Box::new(hook));
2886    }
2887
2888    #[cfg(all(test, unix))]
2889    pub(crate) fn approval_request_count_for_test(&self) -> usize {
2890        self.approval_request_index.lock().unwrap().len()
2891    }
2892
2893    #[cfg(all(test, unix))]
2894    pub(crate) fn poison_approval_request_index_for_test(&self) {
2895        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2896            let _guard = self.approval_request_index.lock().unwrap();
2897            panic!("injected approval index poison");
2898        }));
2899        assert!(poisoned.is_err());
2900    }
2901
2902    #[cfg(all(test, unix))]
2903    pub(crate) fn pause_next_approval_claim_for_test(
2904        &self,
2905    ) -> (
2906        tokio::sync::oneshot::Receiver<()>,
2907        tokio::sync::oneshot::Sender<()>,
2908    ) {
2909        let (reached, observed) = tokio::sync::oneshot::channel();
2910        let (release, wait) = tokio::sync::oneshot::channel();
2911        *self.approval_claim_pause.lock().unwrap() = Some(ApprovalClaimPause {
2912            reached,
2913            release: wait,
2914        });
2915        (observed, release)
2916    }
2917
2918    #[cfg(all(test, unix))]
2919    pub(crate) async fn pause_approval_claim_for_test(&self) {
2920        let pause = self.approval_claim_pause.lock().unwrap().take();
2921        if let Some(pause) = pause {
2922            let _ = pause.reached.send(());
2923            pause.release.await.unwrap();
2924        }
2925    }
2926
2927    // Flipping a flag is platform-neutral. Its callers are the unix-only phone
2928    // tests and, under test-support, the ckdev config test seam and its tests.
2929    #[cfg(any(all(test, unix), feature = "test-support"))]
2930    pub(crate) fn set_os_prompt_policy_for_tests(&self) {
2931        self.os_prompt_policy
2932            .store(true, std::sync::atomic::Ordering::Relaxed);
2933    }
2934
2935    #[cfg(test)]
2936    pub(crate) fn has_trusted_review_connection_for_test(&self, id: crate::ConnectionId) -> bool {
2937        *self.trusted_review_connection_for_test.lock().unwrap() == Some(id)
2938    }
2939
2940    #[cfg(any(test, feature = "test-support"))]
2941    pub(crate) fn os_prompt_policy_for_tests(&self) -> bool {
2942        self.os_prompt_policy
2943            .load(std::sync::atomic::Ordering::Relaxed)
2944    }
2945
2946    pub fn status(&self) -> Result<subc_control::config::ConfigStatus> {
2947        let mut state = self.lock()?;
2948        let mut current_snapshot = None;
2949        let mut observation = None;
2950        state.retry_anchor(true);
2951        let verified = state.store.check().is_ok();
2952        if verified
2953            && !state.recovery_exit_hold
2954            && !state.store.status().anchor_pending
2955            && matches!(
2956                state.store.status().state,
2957                StoreState::Stamped | StoreState::Unstamped
2958            )
2959        {
2960            observation = Some(self.observe_proposal(&mut state)?);
2961            current_snapshot = state.observed_snapshot.clone();
2962        }
2963        let store_status = state.store.status();
2964        let mut status = subc_control::config::ConfigStatus::default();
2965        status.state = match store_status.state {
2966            StoreState::Stamped => "stamped",
2967            StoreState::Unstamped => "unstamped",
2968            StoreState::StoreMissing => "store_missing",
2969            StoreState::StoreUnverified => "store_unverified",
2970        }
2971        .into();
2972        if state.recovery_exit_hold {
2973            if store_status.state != StoreState::Stamped {
2974                status.state = "store_unverified".into();
2975            }
2976            status
2977                .warnings
2978                .push("approved recovery exit is waiting for reconciliation".into());
2979        }
2980        status.integrity = match store_status.integrity {
2981            crate::config_store::IntegrityMode::DigestOnly => "digest_only",
2982            crate::config_store::IntegrityMode::Sealed => "sealed",
2983        }
2984        .into();
2985        status.revision = store_status.revision;
2986        status.base_revision = store_status.base_revision;
2987        status.anchor_pending = store_status.anchor_pending;
2988        status.root_io = self.capturer.projects.root_io_health();
2989        status.ungated_inputs = self.startup_overrides.clone();
2990        #[cfg(feature = "test-support")]
2991        if state.store.uses_config_gate_test_seam() {
2992            status
2993                .development_switches
2994                .push("SUBC_TEST_CONFIG_GATE".into());
2995        }
2996        status.warnings.extend(store_status.warnings);
2997        if cfg!(feature = "dev-desktop-approval") {
2998            status
2999                .development_switches
3000                .push("dev-desktop-approval".into());
3001        }
3002        #[cfg(feature = "dev-desktop-approval")]
3003        if let Some(floor) = crate::operator_apps::development_floor_diagnostic() {
3004            status.development_switches.push(floor);
3005        }
3006        if cfg!(feature = "dev-placement") {
3007            status.development_switches.push("dev-placement".into());
3008        }
3009        let declared: Vec<String> = Self::declarations(&mut state)
3010            .map(|declarations| declarations.into_keys().collect())
3011            .unwrap_or_default();
3012        if let Ok(body) = state.store.body() {
3013            if body.stamped {
3014                for (module, rereview) in
3015                    super::reviewed_build::pending(body, &declared).unwrap_or_default()
3016                {
3017                    status.warnings.push(match rereview {
3018                        super::reviewed_build::Rereview::WaitingForProgram => format!(
3019                            "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the re-review waits until that program is running and active"
3020                        ),
3021                        super::reviewed_build::Rereview::Ready => format!(
3022                            "module {module}: needs configuration re-review: its approved program has not reviewed its approved layers; the next configuration plan re-reviews them with the running program"
3023                        ),
3024                    });
3025                }
3026            }
3027            if body.stamped {
3028                current_snapshot = super::GateSnapshot::from_store(&body.approved).ok();
3029            }
3030            for entry in body.generations.values().rev().take_while(|entry| {
3031                matches!(
3032                    entry.kind,
3033                    crate::config_store::CommitKind::Development
3034                        | crate::config_store::CommitKind::DeclarationApproval
3035                )
3036            }) {
3037                if entry.kind != crate::config_store::CommitKind::Development {
3038                    continue;
3039                }
3040                status.warnings.push(format!(
3041                    "development generation {}: development placement (no approval)",
3042                    entry.generation.id
3043                ));
3044            }
3045            status.approval_channels = body
3046                .generations
3047                .iter()
3048                .map(|(id, entry)| {
3049                    subc_control::config::ConfigApprovalRecord::new(
3050                        *id,
3051                        entry.generation.approval_channel,
3052                    )
3053                })
3054                .chain(body.pruned.iter().map(|(id, entry)| {
3055                    subc_control::config::ConfigApprovalRecord::new(*id, entry.approval_channel)
3056                }))
3057                .collect();
3058            status
3059                .approval_channels
3060                .sort_by_key(|record| record.generation);
3061            status.pending_proposals = u64::from(body.proposal.is_some());
3062            for (tuple, versions) in &body.versions {
3063                if let Some(generation) = versions.pending {
3064                    let entry = body.generations.get(&generation);
3065                    let transition = entry.and_then(|entry| {
3066                        super::apply::Transition::for_module(
3067                            &entry.generation.changeset,
3068                            &tuple.module,
3069                        )
3070                        .ok()
3071                    });
3072                    status.approved_but_inactive.push(serde_json::json!({
3073                        "module_id":tuple.module,"project_id":tuple.project,"generation":generation,
3074                        "digest":entry.map(|entry| &entry.generation.plan_digest),
3075                        "waiting_for":match transition {
3076                            Some(super::apply::Transition::DaemonRestart) => "daemon_restart",
3077                            Some(super::apply::Transition::NextSupervision) => "next_supervision",
3078                            _ => "delivery",
3079                        },
3080                    }));
3081                }
3082            }
3083        }
3084        if let Some(snapshot) = current_snapshot {
3085            status_inputs::report_snapshot(&snapshot, &mut status);
3086        }
3087        if let Some(captured) = observation {
3088            if status.state == "stamped" {
3089                self.log_user_file_observations(&captured);
3090            }
3091            captured.report_errors(&mut status);
3092        }
3093        status.gated_modules = admission::AdmissionCache::from_state(&state).held_modules();
3094        if state.store.loaded_admission_state().0 == StoreState::Stamped {
3095            let declarations: Vec<_> = state
3096                .declarations
3097                .iter()
3098                .map(|(connection, (module, _))| (*connection, module.clone()))
3099                .collect();
3100            for (connection, module) in declarations {
3101                // Use get's approved-declaration/view checks without opening the
3102                // store or binding a delivery attempt merely to display status.
3103                let reply = self.module_get_locked(
3104                    &mut state,
3105                    connection,
3106                    &module,
3107                    subc_protocol::config::ConfigGetRequest::new(),
3108                    false,
3109                );
3110                if let Ok(reply) = &reply {
3111                    Self::report_declaration_pending(
3112                        &state,
3113                        connection,
3114                        &module,
3115                        reply,
3116                        &mut status,
3117                    );
3118                }
3119                if reply.is_err_and(|error| error.code == "config_gated") {
3120                    status.gated_modules.push(module);
3121                }
3122            }
3123            status.gated_modules.sort();
3124            status.gated_modules.dedup();
3125        }
3126        Ok(status)
3127    }
3128
3129    fn report_declaration_pending(
3130        state: &OwnerState,
3131        connection: ConnectionId,
3132        module: &str,
3133        reply: &subc_protocol::config::ConfigGetReply,
3134        status: &mut subc_control::config::ConfigStatus,
3135    ) {
3136        if state.active_declarations.get(module) != Some(&connection) {
3137            return;
3138        }
3139        if let Some(marker) = &reply.declaration_pending {
3140            status
3141                .declaration_pending
3142                .insert(module.into(), marker.clone());
3143            if let Some(generation) = state.delivery.fallback_applied.get(&connection) {
3144                if reply
3145                    .active
3146                    .as_ref()
3147                    .is_some_and(|view| view.generation == *generation)
3148                {
3149                    status.warnings.push(format!("module {module}: running last approved settings (generation {generation}); declaration awaits approval"));
3150                }
3151            }
3152        }
3153    }
3154
3155    pub fn history(&self) -> Result<(Vec<subc_config::Generation>, Vec<serde_json::Value>)> {
3156        let mut state = self.lock()?;
3157        state.retry_anchor(true);
3158        state.store.check()?;
3159        let body = state.store.body()?;
3160        Ok((
3161            body.generations
3162                .values()
3163                .map(|entry| entry.generation.clone())
3164                .collect(),
3165            body.pruned
3166                .values()
3167                .map(serde_json::to_value)
3168                .collect::<std::result::Result<_, _>>()
3169                .map_err(GateError::invalid)?,
3170        ))
3171    }
3172
3173    /// Admission is owned by the supervisor adapter; until it is installed it
3174    /// must not infer executable authority from diagnostic snapshots.
3175    pub fn approved_snapshot(&self) -> Result<DeliverySnapshot> {
3176        let mut state = self.lock()?;
3177        state.store.delivery_ready()?;
3178        state
3179            .store
3180            .body()?
3181            .generations
3182            .values()
3183            .next_back()
3184            .and_then(|entry| entry.delivery.clone())
3185            .ok_or_else(|| GateError::new("config_gated", "approved delivery snapshot is absent"))
3186    }
3187
3188    /// Read the saved rollback, never today's edited files. This is not spawn
3189    /// authorization: admission must select an eligible module generation and
3190    /// launch exactly the returned identity under that module's gate lock.
3191    /// Re-check the file identity at spawn and refuse `plan_stale` if it changed
3192    /// since approval. Path-changing rollback plans remain refused until the
3193    /// supervisor uses these approved inputs to select and launch programs at
3194    /// the restored paths.
3195    pub fn approved_rollback_commands(&self, generation: u64) -> Result<ApprovedRollbackCommands> {
3196        let mut state = self.lock()?;
3197        state.store.delivery_ready()?;
3198        let configuration = state.store.rollback_configuration(generation)?;
3199        let entry = &state.store.body()?.generations[&generation];
3200        if entry.kind != crate::config_store::CommitKind::Rollback {
3201            return Err(GateError::new(
3202                "rollback_generation_required",
3203                "generation is not an approved rollback",
3204            ));
3205        }
3206        let daemon = entry
3207            .delivery
3208            .as_ref()
3209            .and_then(|snapshot| snapshot.daemon.clone())
3210            .ok_or_else(|| {
3211                GateError::new(
3212                    "rollback_snapshot_unavailable",
3213                    "approved rollback command input is absent",
3214                )
3215            })?;
3216        let snapshot = super::GateSnapshot::from_store(&configuration)?;
3217        let mut programs = BTreeMap::new();
3218        for (key, identity) in snapshot.inputs {
3219            if let super::InputKey::Program { module, path } = key {
3220                if programs
3221                    .insert(module, ApprovedRollbackProgram { path, identity })
3222                    .is_some()
3223                {
3224                    return Err(GateError::new(
3225                        "rollback_snapshot_unavailable",
3226                        "rollback contains conflicting program identities",
3227                    ));
3228                }
3229            }
3230        }
3231        Ok(ApprovedRollbackCommands {
3232            generation,
3233            daemon,
3234            programs,
3235        })
3236    }
3237}