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