Skip to main content

subc_daemon/config_gate/
runtime.rs

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