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, mut store: ConfigStore, capturer: ConfigCapturer) -> Self {
1055        // Daemon-restart generations newer than the booted one stay deferred.
1056        let initial_generation = match store.booted_generation() {
1057            Some(booted) => booted,
1058            None => store.body().map(|body| body.last_generation).unwrap_or(0),
1059        };
1060        let admission = admission::AdmissionCache::from_store(&store);
1061        let approved_daemon =
1062            ApprovedDaemonView::from_store(&store, false, &ApprovedDaemonView::Unavailable);
1063        let settings_credentials =
1064            published::ApprovedSettingsCredentials::from_store(&store, false, None);
1065        let reconciled_entries = match &approved_daemon {
1066            ApprovedDaemonView::Approved { config, .. } => config
1067                .modules
1068                .iter()
1069                .map(|module| (module.module_id.clone(), module.clone()))
1070                .collect(),
1071            _ => BTreeMap::new(),
1072        };
1073        let published = std::sync::RwLock::new(std::sync::Arc::new(Published {
1074            admission,
1075            approved_daemon,
1076            refuses_control_in_recovery: Published::control_recovery(&store, false),
1077            projection: polled::Projection::default(),
1078            settings: None,
1079            settings_credentials,
1080        }));
1081        let delivery_changed = std::sync::Arc::new(tokio::sync::Notify::new());
1082        let owner = Self {
1083            user_file_refusals: Mutex::new(BTreeMap::new()),
1084            #[cfg(test)]
1085            user_file_test_idle: Mutex::new(None),
1086            #[cfg(test)]
1087            polled_capture_hook: Mutex::new(None),
1088            #[cfg(test)]
1089            settings_projection_hook: Mutex::new(None),
1090            #[cfg(test)]
1091            settings_status_hook: Mutex::new(None),
1092            #[cfg(test)]
1093            settings_observation_hook: Mutex::new(None),
1094            #[cfg(test)]
1095            config_park_hook: Mutex::new(None),
1096            #[cfg(test)]
1097            content_kill_hook: Mutex::new(None),
1098            #[cfg(test)]
1099            polled_capture_count: std::sync::atomic::AtomicUsize::new(0),
1100            #[cfg(test)]
1101            census_probe: Mutex::new(None),
1102            #[cfg(test)]
1103            agent_validation_window: Mutex::new(None),
1104            #[cfg(test)]
1105            warm_restart_pause: Mutex::new(None),
1106            #[cfg(test)]
1107            warm_restart_busy: Mutex::new(None),
1108            #[cfg(test)]
1109            swap_preflight_attempts: std::sync::atomic::AtomicUsize::new(0),
1110            #[cfg(feature = "test-support")]
1111            test_hooks: store.test_support().cloned(),
1112            #[cfg(test)]
1113            spawn_exec_hook: Mutex::new(None),
1114            published,
1115            // The first guard release below builds the initial projection.
1116            projection_stale: std::sync::atomic::AtomicBool::new(true),
1117            #[cfg(test)]
1118            projection_builds: std::sync::atomic::AtomicUsize::new(0),
1119            #[cfg(test)]
1120            owner_guards: std::sync::atomic::AtomicUsize::new(0),
1121            config_workers: Mutex::new(std::collections::HashSet::new()),
1122            configured_modules: std::sync::RwLock::new(None),
1123            inner: Mutex::new(OwnerState {
1124                authority_incarnation: std::sync::Arc::new(()),
1125                observed_snapshot: None,
1126                stamp_channel_cutover: false,
1127                gate: ConfigGate::new(incarnation),
1128                store,
1129                _writer_lock: None,
1130                plan_deadlines: BTreeMap::new(),
1131                desktop_views: BTreeMap::new(),
1132                phone_waiters: BTreeMap::new(),
1133                approval_requests: HashMap::new(),
1134                delivery: delivery::DeliveryState::new(initial_generation),
1135                anchor_retry: super::anchor_retry::AnchorRetry::default(),
1136                retained_plan_files: BTreeMap::new(),
1137                pending_settings_card: None,
1138                open_settings_approval: None,
1139                latest_explicit_settings_request: 0,
1140                pending_settings_card_reason: None,
1141                settings_review_errors: Vec::new(),
1142                settings_review_errors_base: None,
1143                last_settings_decline: None,
1144                expired_plans: VecDeque::new(),
1145                declarations: HashMap::new(),
1146                live_project_schemas: HashMap::new(),
1147                active_declarations: BTreeMap::new(),
1148                activity: None,
1149                refused_generations: BTreeMap::new(),
1150                admission_holds: Vec::new(),
1151                admission_releases: Vec::new(),
1152                authority_exit: None,
1153                reconciled_entries,
1154                recovery_exit_hold: false,
1155                unstamp_hints: std::collections::HashSet::new(),
1156                anchor_waiters: std::collections::HashSet::new(),
1157                anchor_hints: std::collections::HashSet::new(),
1158                anchor_notify: delivery_changed.clone(),
1159                installed_route_policies: BTreeMap::new(),
1160                route_policy_receipts: BTreeMap::new(),
1161                #[cfg(test)]
1162                publication_hook: None,
1163                #[cfg(test)]
1164                prepublication_hook: None,
1165                #[cfg(test)]
1166                after_approval_drain_hook: None,
1167            }),
1168            settings_recovery_data: capturer.config_home.clone(),
1169            settings_recovery_updates: Default::default(),
1170            #[cfg(test)]
1171            recovery_probe_hook: Mutex::new(None),
1172            #[cfg(test)]
1173            after_settings_decline_hook: Mutex::new(None),
1174            capturer,
1175            policy_root_ledger: None,
1176            policy_root_unstamped: Mutex::new(Ok(None)),
1177            #[cfg(test)]
1178            policy_root_fail_after_append: std::sync::atomic::AtomicBool::new(false),
1179            project_capture_enabled: false,
1180            settings_projects: Default::default(),
1181            #[cfg(test)]
1182            project_write_hook: std::sync::Mutex::new(None),
1183            #[cfg(test)]
1184            user_restore_hook: Mutex::new(None),
1185            #[cfg(test)]
1186            after_restore_read_hook: Mutex::new(None),
1187            settings_phone_delivery: tokio::sync::Mutex::new(()),
1188            settings_attempts_changed: tokio::sync::Notify::new(),
1189            settings_request_order: std::sync::atomic::AtomicU64::new(1),
1190            phone_withdrawal_changed: tokio::sync::Notify::new(),
1191            #[cfg(test)]
1192            project_write_waiter_done: std::sync::Mutex::new(None),
1193            #[cfg(test)]
1194            trusted_review_connection_for_test: std::sync::Mutex::new(None),
1195            startup_overrides: status_inputs::present_overrides(|name| {
1196                std::env::var_os(name).is_some()
1197            }),
1198            module_gates: Mutex::new(HashMap::new()),
1199            delivery_changed,
1200            settings_changed: tokio::sync::watch::channel(0).0,
1201            route_policy_authority: std::sync::OnceLock::new(),
1202            mark_publisher: std::sync::OnceLock::new(),
1203            binding_retirements: Mutex::new(BTreeMap::new()),
1204            canceled_approvals: Mutex::new(Vec::new()),
1205            approval_request_index: Mutex::new(HashMap::new()),
1206            disconnected_pending: Mutex::new(Vec::new()),
1207            abandoned_spawns: Mutex::new(Vec::new()),
1208            phone_withdrawals: Mutex::new(phone::PhoneWithdrawals::default()),
1209            #[cfg(any(test, feature = "test-support"))]
1210            os_prompt_policy: std::sync::atomic::AtomicBool::new(false),
1211            #[cfg(test)]
1212            spawn_preflight_hook: Mutex::new(None),
1213            #[cfg(test)]
1214            exit_record_attempts: std::sync::atomic::AtomicUsize::new(0),
1215            #[cfg(test)]
1216            phone_bind_hook: Mutex::new(None),
1217            #[cfg(test)]
1218            begin_approval_hook: Mutex::new(None),
1219            #[cfg(test)]
1220            begin_approval_completions: std::sync::atomic::AtomicUsize::new(0),
1221            #[cfg(test)]
1222            desktop_receipt_hook: Mutex::new(None),
1223            #[cfg(test)]
1224            prepare_capture_hook: Mutex::new(None),
1225            #[cfg(all(test, unix))]
1226            approval_claim_pause: Mutex::new(None),
1227        };
1228        if let Ok(state) = owner.lock() {
1229            drop(state);
1230        }
1231        owner
1232    }
1233
1234    pub fn module_gate(&self, module: &str) -> Result<std::sync::Arc<tokio::sync::Mutex<()>>> {
1235        let mut gates = self
1236            .module_gates
1237            .lock()
1238            .map_err(|_| GateError::new("config_unavailable", "module gate lock is poisoned"))?;
1239        Ok(gates.entry(module.into()).or_default().clone())
1240    }
1241
1242    #[cfg(all(test, unix))]
1243    pub(crate) fn set_agent_validation_window_for_test(&self, window: Duration) {
1244        *self.agent_validation_window.lock().unwrap() = Some(window);
1245    }
1246
1247    #[cfg(test)]
1248    pub(crate) fn agent_validation_window_for_test(&self) -> Option<Duration> {
1249        *self.agent_validation_window.lock().unwrap()
1250    }
1251
1252    pub(crate) fn install_binding_retirement(
1253        &self,
1254        key: usize,
1255        retire: impl Fn() + Send + Sync + 'static,
1256    ) {
1257        self.binding_retirements
1258            .lock()
1259            .unwrap_or_else(|poisoned| poisoned.into_inner())
1260            .insert(key, Box::new(retire));
1261    }
1262
1263    pub(crate) fn delivery_notifications(&self) -> std::sync::Arc<tokio::sync::Notify> {
1264        self.delivery_changed.clone()
1265    }
1266
1267    pub(crate) fn notify_delivery_changed(&self) {
1268        self.delivery_changed.notify_one();
1269    }
1270
1271    pub(crate) fn retain_writer_lock(
1272        self,
1273        lock: crate::config_store::StoreWriterLock,
1274    ) -> Result<Self> {
1275        self.lock()?._writer_lock = Some(lock);
1276        Ok(self)
1277    }
1278
1279    fn lock(&self) -> Result<OwnerGuard<'_>> {
1280        // The owner's state comes before the forwarding lock: lowering a
1281        // first-party mark takes the forwarding lock under it.
1282        crate::forwarding::assert_forwarding_unlocked("the configuration owner's state");
1283        let mut guard = self
1284            .inner
1285            .lock()
1286            .map(|state| OwnerGuard::new(state, self))
1287            .map_err(|_| {
1288                GateError::new("config_unavailable", "configuration owner lock is poisoned")
1289            })?;
1290        // The test seam only arms a backend failure; nothing published reads it.
1291        #[cfg(feature = "test-support")]
1292        guard.state.store.refresh_test_anchor_failure();
1293        // Deferred cancellations, disconnects and abandoned spawns, and idle
1294        // plan expiry, change the owner only when they had work. Each runs on
1295        // every acquisition, and work done here publishes on release.
1296        let drained = self.drain_canceled_approvals(&mut guard.state)
1297            | self.drain_disconnections(&mut guard.state)
1298            | self.drain_abandoned_spawns(&mut guard.state)
1299            | guard.state.expire_idle(Instant::now());
1300        guard.changed |= drained;
1301        Ok(guard)
1302    }
1303
1304    pub(crate) fn try_swap_configuration(&self) -> Result<SwapConfiguration<'_>> {
1305        let state = self.inner.try_lock().map_err(|_| {
1306            GateError::new(
1307                "config_delivery_deferred",
1308                "configuration publication is busy or unavailable",
1309            )
1310        })?;
1311        Ok(SwapConfiguration {
1312            owner: self,
1313            state: OwnerGuard::new(state, self),
1314        })
1315    }
1316
1317    pub(crate) fn try_requires_fresher_spawn(
1318        &self,
1319        module: &str,
1320        spawn: Option<&DeliverySpawn>,
1321    ) -> Result<Option<u64>> {
1322        let state = self.inner.try_lock().map_err(|_| {
1323            GateError::new(
1324                "config_delivery_deferred",
1325                "configuration publication is busy or unavailable",
1326            )
1327        })?;
1328        Self::requires_fresher_spawn_loaded(&state, module, spawn)
1329    }
1330
1331    pub(crate) fn sweep_expired(&self) -> Result<()> {
1332        drop(self.lock()?);
1333        Ok(())
1334    }
1335
1336    pub(crate) fn poll_anchor_retry(&self) -> Result<Option<tokio::time::Instant>> {
1337        Ok(self.lock()?.retry_anchor(false))
1338    }
1339
1340    pub(crate) fn set_activity(
1341        &self,
1342        ledger: Option<crate::activity::ActivityLedger>,
1343    ) -> Result<()> {
1344        self.lock()?.activity = ledger;
1345        Ok(())
1346    }
1347
1348    pub fn take_activities(&self) -> Vec<StoreActivity> {
1349        self.inner
1350            .lock()
1351            .map(|mut state| state.store.take_activities())
1352            .unwrap_or_default()
1353    }
1354
1355    /// Declaration ownership comes from the registered transport connection.
1356    /// A candidate's proposal is retained without replacing the incumbent's.
1357    pub fn declare(
1358        &self,
1359        connection: ConnectionId,
1360        module: &str,
1361        declaration: ConfigDeclareRequest,
1362        active: bool,
1363    ) -> Result<()> {
1364        super::strict_json::check_canonical(&declaration.schema, "/schema")
1365            .map_err(|error| GateError::new(&error.code, format!("{module}: {}", error.detail)))?;
1366        let schema = subc_config::Schema::new(declaration.schema.clone())
1367            .map_err(|r| GateError::new("schema_invalid", format!("{module}: {}", r.path)))?;
1368        let live_schema = self
1369            .project_settings_enabled()
1370            .then(|| std::sync::Arc::new(super::project_layers::ProjectLayerSchema::new(schema)));
1371        let mut state = self.lock()?;
1372        if state.store.status().state == StoreState::StoreMissing
1373            || state.store.status().state == StoreState::StoreUnverified
1374        {
1375            return Err(GateError::new(
1376                "config_gated",
1377                "configuration store is in recovery",
1378            ));
1379        }
1380        if state.declarations.contains_key(&connection) {
1381            return Err(GateError::new(
1382                "declaration_order",
1383                "configuration is declared once per connection",
1384            ));
1385        }
1386        state
1387            .declarations
1388            .insert(connection, (module.into(), declaration));
1389        if let Some(schema) = live_schema {
1390            state.live_project_schemas.insert(connection, schema);
1391        }
1392        state.delivery.declared(connection, module, active);
1393        if active {
1394            state.active_declarations.insert(module.into(), connection);
1395        }
1396        self.notify_delivery_changed();
1397        Ok(())
1398    }
1399
1400    /// Clear everything `connection` held in the configuration owner. If another
1401    /// task holds the owner lock, the close is queued and the coordinator is
1402    /// always woken to drain it, because the connection can't be checked. When
1403    /// the lock is free, wake only if the connection had configuration state or
1404    /// ran a `config.review` worker.
1405    pub fn disconnected(&self, connection: ConnectionId) {
1406        let mut held = false;
1407        if let Ok(mut index) = self.approval_request_index.lock() {
1408            index.retain(|(caller, _), request| {
1409                if *caller == connection {
1410                    request.cancel();
1411                    held = true;
1412                    false
1413                } else {
1414                    true
1415                }
1416            });
1417        }
1418        match self.inner.try_lock() {
1419            Ok(mut state) => {
1420                if state.disconnected(connection) {
1421                    held = true;
1422                    // This change bypassed an OwnerGuard. Flag it before the
1423                    // owner is released so the next guard republishes it.
1424                    self.projection_stale
1425                        .store(true, std::sync::atomic::Ordering::Release);
1426                }
1427            }
1428            Err(_) => {
1429                if let Ok(mut pending) = self.disconnected_pending.lock() {
1430                    pending.push(connection);
1431                }
1432                // Without the owner lock we cannot rule out config state.
1433                // The coordinator's next acquisition applies the queued close.
1434                held = true;
1435            }
1436        }
1437        if held || self.runs_config_worker(connection) {
1438            self.notify_delivery_changed();
1439        }
1440    }
1441
1442    /// The delivery coordinator started a `config.review` worker for
1443    /// `connection`.
1444    pub(crate) fn config_worker_started(&self, connection: ConnectionId) {
1445        self.config_workers
1446            .lock()
1447            .unwrap_or_else(|poisoned| poisoned.into_inner())
1448            .insert(connection);
1449    }
1450
1451    /// The delivery coordinator retired `connection`'s worker.
1452    pub(crate) fn config_worker_stopped(&self, connection: ConnectionId) {
1453        self.config_workers
1454            .lock()
1455            .unwrap_or_else(|poisoned| poisoned.into_inner())
1456            .remove(&connection);
1457    }
1458
1459    fn runs_config_worker(&self, connection: ConnectionId) -> bool {
1460        self.config_workers
1461            .lock()
1462            .map_or(true, |workers| workers.contains(&connection))
1463    }
1464
1465    pub fn module_get(
1466        &self,
1467        connection: ConnectionId,
1468        module: &str,
1469        request: subc_protocol::config::ConfigGetRequest,
1470    ) -> Result<subc_protocol::config::ConfigGetReply> {
1471        let mut state = self.lock()?;
1472        self.module_get_locked(&mut state, connection, module, request, true)
1473    }
1474
1475    fn module_get_locked(
1476        &self,
1477        state: &mut OwnerState,
1478        connection: ConnectionId,
1479        module: &str,
1480        request: subc_protocol::config::ConfigGetRequest,
1481        check_store: bool,
1482    ) -> Result<subc_protocol::config::ConfigGetReply> {
1483        let declaration = state
1484            .declarations
1485            .get(&connection)
1486            .filter(|(id, _)| id == module)
1487            .map(|(_, declaration)| declaration.clone())
1488            .ok_or_else(|| {
1489                GateError::new(
1490                    "declaration_order",
1491                    "config.declare must precede get or applied on this connection",
1492                )
1493            })?;
1494        if request.project_id.is_some() {
1495            if state.store.loaded_admission_state().0 == StoreState::Stamped {
1496                return self.stamped_project_get(
1497                    state,
1498                    connection,
1499                    module,
1500                    &declaration,
1501                    &request,
1502                    check_store,
1503                );
1504            }
1505            return Err(GateError::new(
1506                "config_gated",
1507                format!("{module}: project-tuple delivery is not supported yet"),
1508            ));
1509        }
1510        if check_store {
1511            let checked = state.store.check();
1512            if matches!(
1513                state.store.loaded_admission_state().0,
1514                StoreState::StoreMissing | StoreState::StoreUnverified
1515            ) {
1516                return recovery::active_view(state, module, &declaration, &request);
1517            }
1518            checked?;
1519        }
1520        if state.store.loaded_admission_state().0 == StoreState::Unstamped {
1521            if request.generation.is_some() || request.attempt.is_some() {
1522                return Err(GateError::new(
1523                    "config_gated",
1524                    "unstamped reads have no assigned generation or delivery attempt",
1525                ));
1526            }
1527            let mut declarations = Self::declarations(state)?;
1528            declarations.insert(module.into(), declaration);
1529            let mut captured = self
1530                .capturer
1531                .capture_modules(&declarations, &BTreeSet::from([module.to_owned()]))?;
1532            let view = captured
1533                .modules
1534                .remove(module)
1535                .ok_or_else(|| GateError::new("config_gated", "module declaration is unavailable"))?
1536                .view;
1537            return Ok(subc_protocol::config::ConfigGetReply::new(Some(view), None));
1538        }
1539        if check_store {
1540            state.store.delivery_ready()?;
1541        }
1542        let body = if check_store {
1543            state.store.body()?
1544        } else {
1545            state.store.loaded_admission_state().1
1546        };
1547        let tuple = crate::config_store::Tuple {
1548            module: module.into(),
1549            project: None,
1550        };
1551        let versions = body
1552            .versions
1553            .iter()
1554            .find(|(entry, _)| entry == &tuple)
1555            .map(|(_, versions)| versions)
1556            .ok_or_else(|| {
1557                GateError::new("config_gated", "module is not in an approved generation")
1558            })?;
1559        let approved_declaration = versions
1560            .pending
1561            .or(versions.active)
1562            .and_then(|generation| body.generations.get(&generation))
1563            .and_then(|entry| entry.delivery.as_ref())
1564            .and_then(|snapshot| snapshot.declarations.get(module))
1565            == Some(&declaration);
1566        if !approved_declaration && versions.active.is_none() {
1567            return Err(GateError::new(
1568                "config_gated",
1569                "module has no approved active configuration",
1570            ));
1571        }
1572        let view = |generation: Option<u64>, status: ConfigStatus| -> Result<Option<ConfigView>> {
1573            let Some(generation) = generation else {
1574                return Ok(None);
1575            };
1576            let delivery = body
1577                .generations
1578                .get(&generation)
1579                .and_then(|entry| entry.delivery.as_ref())
1580                .ok_or_else(|| {
1581                    GateError::new("config_gated", "approved delivery bytes are absent")
1582                })?;
1583            let mut view =
1584                delivery.modules.get(module).cloned().ok_or_else(|| {
1585                    GateError::new("config_gated", "approved module view is absent")
1586                })?;
1587            view.generation = generation;
1588            view.status = status;
1589            Ok(Some(view))
1590        };
1591        let active = view(versions.active, ConfigStatus::Active)?;
1592        if !approved_declaration {
1593            let mut reply = subc_protocol::config::ConfigGetReply::new(active, None);
1594            reply.declaration_pending = Self::declaration_pending(state, module, &declaration);
1595            return if check_store {
1596                delivery::bind_declaration_fallback(state, connection, module, &request, reply)
1597            } else {
1598                Ok(reply)
1599            };
1600        }
1601        let pending = view(versions.pending, ConfigStatus::Pending)?;
1602        let transition = versions
1603            .pending
1604            .and_then(|id| body.generations.get(&id))
1605            .map(|entry| super::apply::Transition::for_module(&entry.generation.changeset, module))
1606            .transpose()?
1607            .unwrap_or(super::apply::Transition::Live);
1608        if active.is_none() && pending.is_none() {
1609            return Err(GateError::new(
1610                "config_gated",
1611                "module has no active or deliverable generation",
1612            ));
1613        }
1614        if !check_store {
1615            return delivery::visible_reply(
1616                state,
1617                connection,
1618                subc_protocol::config::ConfigGetReply::new(active, pending),
1619                transition,
1620            );
1621        }
1622        delivery::bind_get(
1623            state,
1624            connection,
1625            module,
1626            &request,
1627            subc_protocol::config::ConfigGetReply::new(active, pending),
1628            transition,
1629        )
1630    }
1631
1632    fn declaration_pending(
1633        state: &OwnerState,
1634        module: &str,
1635        declaration: &ConfigDeclareRequest,
1636    ) -> Option<subc_protocol::config::ConfigDeclarationPending> {
1637        let body = state.store.loaded_admission_state().1;
1638        if !body.stamped {
1639            return None;
1640        }
1641        let versions = body
1642            .versions
1643            .iter()
1644            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())?
1645            .1
1646            .clone();
1647        if versions.active.is_none()
1648            || versions
1649                .pending
1650                .or(versions.active)
1651                .and_then(|id| body.generations.get(&id))
1652                .and_then(|entry| entry.delivery.as_ref())
1653                .and_then(|delivery| delivery.declarations.get(module))
1654                == Some(declaration)
1655        {
1656            return None;
1657        }
1658        let mut marker = subc_protocol::config::ConfigDeclarationPending::default();
1659        marker.plan_digest = state
1660            .gate
1661            .plans
1662            .values()
1663            .filter(|plan| {
1664                plan.modules.contains(module)
1665                    && plan
1666                        .delivery
1667                        .as_ref()
1668                        .and_then(|delivery| delivery.declarations.get(module))
1669                        == Some(declaration)
1670            })
1671            .max_by_key(|plan| plan.creation_sequence)
1672            .map(|plan| plan.view.digest.clone());
1673        Some(marker)
1674    }
1675
1676    fn declarations(state: &mut OwnerState) -> Result<BTreeMap<String, ConfigDeclareRequest>> {
1677        if state.store.status().state == StoreState::Stamped {
1678            state.store.body()?;
1679        }
1680        Ok(Self::loaded_declarations(state))
1681    }
1682
1683    fn loaded_declarations(state: &OwnerState) -> BTreeMap<String, ConfigDeclareRequest> {
1684        let (store, body) = state.store.loaded_admission_state();
1685        let mut declarations = if store == StoreState::Stamped {
1686            body.generations
1687                .values()
1688                .next_back()
1689                .and_then(|entry| entry.delivery.as_ref())
1690                .map(|snapshot| snapshot.declarations.clone())
1691                .unwrap_or_default()
1692        } else {
1693            BTreeMap::new()
1694        };
1695        for (module, connection) in &state.active_declarations {
1696            if let Some((_, declaration)) = state.declarations.get(connection) {
1697                declarations.insert(module.clone(), declaration.clone());
1698            }
1699        }
1700        declarations
1701    }
1702
1703    fn capture(&self, state: &mut OwnerState) -> Result<CapturedConfiguration> {
1704        let declarations = Self::declarations(state)?;
1705        let captured = self.capturer.capture(&declarations)?;
1706        state.observed_snapshot = Some(captured.diagnostic.clone());
1707        Ok(captured)
1708    }
1709
1710    fn capture_modules(
1711        &self,
1712        state: &mut OwnerState,
1713        modules: &BTreeSet<String>,
1714    ) -> Result<CapturedConfiguration> {
1715        self.capturer
1716            .capture_modules(&Self::declarations(state)?, modules)
1717    }
1718
1719    fn check_authority(state: &mut OwnerState, recovery: bool) -> Result<()> {
1720        if let Err(error) = state.store.check() {
1721            return if recovery
1722                && matches!(
1723                    state.store.loaded_admission_state().0,
1724                    StoreState::StoreUnverified | StoreState::StoreMissing
1725                ) {
1726                Ok(())
1727            } else {
1728                Err(error.into())
1729            };
1730        }
1731        state.retry_anchor(true);
1732        match state.store.check() {
1733            Ok(()) => Ok(()),
1734            Err(_)
1735                if recovery
1736                    && matches!(
1737                        state.store.status().state,
1738                        StoreState::StoreUnverified | StoreState::StoreMissing
1739                    ) =>
1740            {
1741                Ok(())
1742            }
1743            Err(error) => Err(error.into()),
1744        }
1745    }
1746
1747    /// Run from a blocking worker: capture and store publication may touch disk
1748    /// and the platform keychain. No transport wait takes place under this lock.
1749    /// Preflight may record the proposal observed on disk. Refusals for missing
1750    /// authoritative project membership, active-scope usage or approved-program
1751    /// launch selection happen before any plan, approval or generation is
1752    /// written. A proposal neither approves nor records the refused plan.
1753    pub fn prepare(&self, kind: PlanKind) -> Result<PreparedPlan> {
1754        self.prepare_inner(kind, None)
1755    }
1756
1757    fn prepare_inner(
1758        &self,
1759        kind: PlanKind,
1760        registry: Option<(u64, Result<super::project_registry::RegistryBatch>)>,
1761    ) -> Result<PreparedPlan> {
1762        let mut state = self.lock()?;
1763        Self::check_authority(
1764            &mut state,
1765            matches!(kind, PlanKind::Stamp | PlanKind::Unstamp),
1766        )?;
1767        let registry = if let Some((base, reply)) = registry {
1768            if state.store.status().state != StoreState::Stamped
1769                || state.store.status().base_revision != base
1770            {
1771                return Err(capture_plan::changed());
1772            }
1773            let body = state.store.body()?;
1774            match reply {
1775                Ok(batch) => Some(batch),
1776                Err(error)
1777                    if error.code == "project_registry_unavailable"
1778                        && !capture_plan::known_projects(body) =>
1779                {
1780                    None
1781                }
1782                Err(error) => return Err(capture_plan::registry_retry(error)),
1783            }
1784        } else {
1785            None
1786        };
1787        #[cfg(test)]
1788        if let Some(hook) = self.prepare_capture_hook.lock().unwrap().take() {
1789            hook();
1790        }
1791        let (mut project_capture, observed) = if let Some((enumeration, revisions)) = registry {
1792            let declarations = Self::declarations(&mut state)?;
1793            if !declarations.keys().eq(revisions.keys()) {
1794                return Err(capture_plan::changed());
1795            }
1796            if let Some(enumeration) = &enumeration {
1797                state.store.replace_registry_membership(Ok(enumeration))?;
1798            }
1799            let mut project_plan = CapturePlan::default();
1800            let body = state.store.body()?;
1801            let approved = super::GateSnapshot::from_store(&body.approved)?;
1802            let roots = revisions
1803                .into_iter()
1804                .map(|(module, revision)| {
1805                    ModuleRoots::new(revision, &approved, &mut project_plan.skipped)
1806                        .map(|roots| (module, roots))
1807                })
1808                .collect::<Result<BTreeMap<_, _>>>()?;
1809            project_plan.context.held_user.extend(
1810                roots
1811                    .iter()
1812                    .filter(|(_, roots)| roots.holds_user())
1813                    .map(|(module, _)| module.clone()),
1814            );
1815            let held = capture_plan::retained_user_files(
1816                body,
1817                &approved,
1818                &declarations,
1819                &project_plan.context.held_user,
1820            );
1821            let captured = self
1822                .capturer
1823                .capture_with_retained_user(&declarations, None, held)?;
1824            let (project_plan, observed) = capture_plan::capture_projects(
1825                &self.capturer,
1826                body,
1827                &approved,
1828                &captured,
1829                &roots,
1830                project_plan,
1831            )?;
1832            state.store.observe(observed.to_store()?)?;
1833            state.observed_snapshot = Some(observed);
1834            (Some(project_plan), captured)
1835        } else {
1836            (None, self.capture(&mut state)?)
1837        };
1838        if observed.daemon.bytes.is_none() {
1839            return Err(GateError::new(
1840                "invalid_daemon_config",
1841                "subc.jsonc is absent; refusing to rescan",
1842            ));
1843        }
1844        if project_capture.is_none()
1845            && !state.recovery_exit_hold
1846            && state.store.status().state == StoreState::Stamped
1847        {
1848            let approved = super::GateSnapshot::from_store(&state.store.body()?.approved)?;
1849            state
1850                .store
1851                .observe(observed.proposal_snapshot(&approved).to_store()?)?;
1852        }
1853        let rollback = if let PlanKind::Rollback(id) = kind {
1854            Some(rollback::prepare(self, &mut state, id)?)
1855        } else {
1856            None
1857        };
1858        let (candidate, mut observed, target) = if let Some((candidate, target)) = rollback {
1859            (candidate, Some(observed), Some(target))
1860        } else {
1861            (observed, None, None)
1862        };
1863        if kind == PlanKind::Stamp {
1864            super::registration::check_stamp(&candidate.diagnostic)?;
1865        }
1866        let base_revision = state.store.status().base_revision;
1867        let old = if state.store.status().state == StoreState::Stamped {
1868            super::GateSnapshot::from_store(&state.store.body()?.approved)?
1869        } else {
1870            super::GateSnapshot::default()
1871        };
1872        let mut touched_modules: BTreeSet<_> = candidate
1873            .diagnostic
1874            .changed_keys(&old)
1875            .iter()
1876            .filter(|key| !key.is_project())
1877            .filter_map(|key| key.module().map(str::to_owned))
1878            .collect();
1879        if matches!(kind, PlanKind::Stamp | PlanKind::Unstamp) {
1880            touched_modules.extend(candidate.diagnostic.modules());
1881            touched_modules.extend(old.modules());
1882        }
1883        if let Some(target) = target {
1884            touched_modules.extend(
1885                candidate
1886                    .diagnostic
1887                    .inputs
1888                    .iter()
1889                    .filter(|(key, value)| {
1890                        key.is_program() && target.inputs.get(*key) != Some(*value)
1891                    })
1892                    .filter_map(|(key, _)| key.module().map(str::to_owned)),
1893            );
1894        }
1895        let mut review_modules: BTreeSet<String> = touched_modules
1896            .iter()
1897            .filter(|module| candidate.modules.contains_key(*module))
1898            .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)))
1899            .cloned()
1900            .collect();
1901        if let Some(projects) = &project_capture {
1902            touched_modules.extend(projects.reviews.keys().map(|tuple| tuple.module.clone()));
1903        }
1904        // A program change is approved launch-only: neither the build being
1905        // approved nor the one still running can review for it. Once the new
1906        // program is active, the next plan re-reviews the approved layers with
1907        // it. While it is not yet active the module waits, and the plan
1908        // carries its earlier reviewer forward.
1909        let mut rereview_modules = BTreeSet::new();
1910        if matches!(kind, PlanKind::Change | PlanKind::Rollback(_))
1911            && state.store.status().state == StoreState::Stamped
1912        {
1913            for (module, rereview) in
1914                super::reviewed_build::pending(state.store.body()?, candidate.modules.keys())?
1915            {
1916                if rereview == super::reviewed_build::Rereview::Ready
1917                    && !review_modules.contains(&module)
1918                {
1919                    touched_modules.insert(module.clone());
1920                    review_modules.insert(module.clone());
1921                    rereview_modules.insert(module);
1922                }
1923            }
1924        }
1925        let program_keys: Vec<_> = candidate
1926            .diagnostic
1927            .inputs
1928            .keys()
1929            .filter(|key| {
1930                key.is_program()
1931                    && key
1932                        .module()
1933                        .is_some_and(|module| touched_modules.contains(module))
1934            })
1935            .cloned()
1936            .collect();
1937        let read_set = if let Some(observed) = &mut observed {
1938            observed.capture_programs(&program_keys)?;
1939            if program_keys.iter().any(|key| {
1940                observed.diagnostic.inputs.get(key) != candidate.diagnostic.inputs.get(key)
1941            }) {
1942                return Err(GateError::stale());
1943            }
1944            observed.diagnostic.read_set(&touched_modules)?
1945        } else {
1946            candidate.diagnostic.read_set(&touched_modules)?
1947        };
1948        let observed_handles = observed
1949            .as_mut()
1950            .map(CapturedConfiguration::take_handles)
1951            .unwrap_or_default();
1952        let mut bases = BTreeMap::new();
1953        let mut base_schemas = BTreeMap::new();
1954        let mut active_generations = BTreeMap::new();
1955        if state.store.status().state == StoreState::Stamped {
1956            let body = state.store.body()?;
1957            let approved_id = placement::last_approved_generation(body);
1958            for (tuple, versions) in &body.versions {
1959                if touched_modules.contains(&tuple.module) {
1960                    active_generations.insert(tuple.clone(), versions.active);
1961                }
1962                if tuple.project.is_some() || !review_modules.contains(&tuple.module) {
1963                    continue;
1964                }
1965                // A plan replaces the last approval, even when that generation
1966                // has not activated. The reviewer and the card use that base.
1967                // A launch entry alone is not an approved configuration base;
1968                // only a retained declaration establishes one for review.
1969                if old
1970                    .inputs
1971                    .contains_key(&super::InputKey::Declaration(tuple.module.clone()))
1972                {
1973                    let id = approved_id;
1974                    let snapshot = body
1975                        .generations
1976                        .get(&id)
1977                        .and_then(|entry| entry.delivery.as_ref())
1978                        .ok_or_else(|| {
1979                            GateError::new(
1980                                "approved_schema_unavailable",
1981                                format!(
1982                                    "{}: approved old schema is missing or damaged",
1983                                    tuple.module
1984                                ),
1985                            )
1986                        })?;
1987                    let schema = snapshot
1988                        .declarations
1989                        .get(&tuple.module)
1990                        .and_then(|declaration| {
1991                            subc_config::Schema::new(declaration.schema.clone()).ok()
1992                        })
1993                        .ok_or_else(|| {
1994                            GateError::new(
1995                                "approved_schema_unavailable",
1996                                format!(
1997                                    "{}: approved old schema is missing or damaged",
1998                                    tuple.module
1999                                ),
2000                            )
2001                        })?;
2002                    base_schemas.insert(tuple.module.clone(), schema);
2003                    let view = snapshot.modules.get(&tuple.module).ok_or_else(|| {
2004                        GateError::new(
2005                            "config_gated",
2006                            format!("{}: approved view is absent", tuple.module),
2007                        )
2008                    })?;
2009                    let mut view = view.clone();
2010                    view.generation = id;
2011                    view.status = if versions.active == Some(id) {
2012                        ConfigStatus::Active
2013                    } else {
2014                        ConfigStatus::Pending
2015                    };
2016                    bases.insert(tuple.module.clone(), view);
2017                }
2018            }
2019        }
2020        Ok(PreparedPlan {
2021            edits: None,
2022            projects: None,
2023            project_capture: project_capture.take(),
2024            settings_users: None,
2025            candidate,
2026            bases,
2027            base_schemas,
2028            kind,
2029            review_modules,
2030            rereview_modules,
2031            base_revision,
2032            active_generations,
2033            touched_modules,
2034            read_set,
2035            program_keys,
2036            observed_handles,
2037        })
2038    }
2039
2040    pub fn finish_plan(
2041        &self,
2042        mut prepared: PreparedPlan,
2043        review: impl FnOnce(&super::GateSnapshot, &super::GateSnapshot) -> Result<Changeset>,
2044    ) -> Result<ConfigPlanView> {
2045        let workspaces = if let Some(projects) = &prepared.project_capture {
2046            runtime_capture::reviewed_workspace_reads(Some(&projects.context), &projects.files)?
2047        } else {
2048            Vec::new()
2049        };
2050        let settings_file_witness = if prepared.settings_users.is_some() || !workspaces.is_empty() {
2051            let current = self.read_settings_file_witness(
2052                &prepared.settings_users.clone().unwrap_or_default(),
2053                workspaces,
2054            )?;
2055            prepared.settings_users.is_some().then_some(current)
2056        } else {
2057            None
2058        };
2059        let mut state = self.lock()?;
2060        Self::check_authority(
2061            &mut state,
2062            matches!(prepared.kind, PlanKind::Stamp | PlanKind::Unstamp),
2063        )?;
2064        let project_plan = prepared.project_capture.take();
2065        if let Some(projects) = &project_plan {
2066            if !projects.reviews.is_empty() || !projects.refusals.is_empty() {
2067                return Err(GateError::new(
2068                    "module_review_invalid",
2069                    "project reviews were not accepted",
2070                ));
2071            }
2072        }
2073        let active_generations = if state.store.status().state == StoreState::Stamped {
2074            state
2075                .store
2076                .body()?
2077                .versions
2078                .iter()
2079                .filter(|(tuple, _)| prepared.touched_modules.contains(&tuple.module))
2080                .map(|(tuple, versions)| (tuple.clone(), versions.active))
2081                .collect()
2082        } else {
2083            BTreeMap::new()
2084        };
2085        let mut current = if let Some(users) = &prepared.settings_users {
2086            self.capture_settings_users(&state, Some(users), None)
2087                .map(|(capture, ..)| capture)
2088        } else if let Some(edit) = &prepared.edits {
2089            self.edit_baseline(
2090                &mut state,
2091                Some(if edit.unstamped {
2092                    &prepared.touched_modules
2093                } else {
2094                    &edit.user_modules
2095                }),
2096            )
2097        } else if let Some(projects) = &project_plan {
2098            self.capture_with_project_context(
2099                &mut state,
2100                &prepared.touched_modules,
2101                &projects.context,
2102            )
2103        } else {
2104            self.capture_modules(&mut state, &prepared.touched_modules)
2105        }
2106        .map_err(|_| GateError::stale())?;
2107        if prepared.settings_users.is_none() {
2108            current
2109                .capture_programs(&prepared.program_keys)
2110                .map_err(|_| GateError::stale())?;
2111        }
2112        if ((prepared.edits.is_none() || project_plan.is_some())
2113            && state.store.status().base_revision != prepared.base_revision)
2114            || active_generations != prepared.active_generations
2115            || !prepared
2116                .read_set
2117                .matches(&current.diagnostic.read_set(&prepared.touched_modules)?)
2118        {
2119            return Err(if prepared.edits.is_some() {
2120                GateError::new(
2121                    "config_changed_since_review",
2122                    "a touched module changed while the edits were reviewed",
2123                )
2124            } else {
2125                GateError::stale()
2126            });
2127        }
2128        if prepared.edits.is_some() {
2129            // Carry forward approvals for modules outside the edit set. Changes
2130            // to those approvals must neither refuse these edits nor be reverted by them.
2131            let daemon_edit = prepared
2132                .edits
2133                .as_ref()
2134                .is_some_and(|edit| edit.policy_root.is_some());
2135            if daemon_edit {
2136                Self::no_pending_policy_root(&state)?;
2137            }
2138            let touched = &prepared.touched_modules;
2139            for (key, input) in &current.diagnostic.inputs {
2140                if daemon_edit && *key == super::InputKey::Daemon {
2141                    continue;
2142                }
2143                if key.module().is_none_or(|module| !touched.contains(module)) {
2144                    prepared
2145                        .candidate
2146                        .diagnostic
2147                        .inputs
2148                        .insert(key.clone(), input.clone());
2149                }
2150            }
2151            prepared.candidate.diagnostic.inputs.retain(|key, _| {
2152                key.module().is_some_and(|module| touched.contains(module))
2153                    || current.diagnostic.inputs.contains_key(key)
2154            });
2155            prepared
2156                .candidate
2157                .modules
2158                .retain(|module, _| touched.contains(module));
2159            for (module, captured) in std::mem::take(&mut current.modules) {
2160                if !touched.contains(&module) {
2161                    prepared.candidate.modules.insert(module, captured);
2162                }
2163            }
2164        }
2165        let mut project_context = None;
2166        let mut project_skips = Vec::new();
2167        let mut edit_registry = BTreeMap::new();
2168        let mut file_summary = Vec::new();
2169        if let Some(users) = &prepared.settings_users {
2170            for module in users {
2171                file_summary.push(subc_control::config::ConfigSettingsFile {
2172                    layer: subc_config::Layer::User,
2173                    module_id: module.clone(),
2174                    path: prepared.candidate.modules[module].file.path.clone(),
2175                    workspace_id: None,
2176                    affected_projects: Vec::new(),
2177                });
2178            }
2179        }
2180        if let Some(projects) = project_plan {
2181            let CapturePlan {
2182                mut context,
2183                witnesses,
2184                skipped,
2185                files,
2186                ..
2187            } = projects;
2188            if prepared.edits.is_some() {
2189                for (module, authority) in &context.authority {
2190                    edit_registry.insert(module.clone(), authority.revision_digest()?);
2191                }
2192            }
2193            for (key, input) in &witnesses.inputs {
2194                if matches!(key, super::InputKey::ProjectTuple { .. }) {
2195                    context.witnesses.inputs.insert(key.clone(), input.clone());
2196                }
2197            }
2198            current
2199                .diagnostic
2200                .inputs
2201                .extend(context.witnesses.inputs.clone());
2202            prepared
2203                .candidate
2204                .diagnostic
2205                .inputs
2206                .extend(witnesses.inputs);
2207            if !files.is_empty() {
2208                if prepared.settings_users.is_some() {
2209                    for file in &files {
2210                        let target = file.target();
2211                        let crate::config_store::ProjectFileLayer::Workspace { workspace_id } =
2212                            &target.layer
2213                        else {
2214                            unreachable!("automatic settings plans have no project-layer files")
2215                        };
2216                        let path = target.path().expect("captured workspace path");
2217                        let readers = context.authority[&target.module].readers_of(&path);
2218                        file_summary.push(subc_control::config::ConfigSettingsFile {
2219                            layer: subc_config::Layer::Workspace,
2220                            module_id: target.module.clone(),
2221                            path,
2222                            workspace_id: Some(workspace_id.clone()),
2223                            affected_projects: readers.into_iter().collect(),
2224                        });
2225                    }
2226                }
2227                prepared.projects.get_or_insert_with(Default::default).files = files;
2228            }
2229            project_skips = skipped;
2230            project_context = Some(context);
2231        }
2232        let delivery = DeliverySnapshot {
2233            daemon: Some(ConfigLayerSnapshot::file(
2234                "subc",
2235                ConfigLayer::User,
2236                prepared.candidate.daemon.path.to_string_lossy(),
2237                prepared.candidate.daemon.bytes.clone(),
2238            )),
2239            modules: prepared
2240                .candidate
2241                .modules
2242                .iter()
2243                .map(|(module, captured)| (module.clone(), captured.view.clone()))
2244                .collect(),
2245            declarations: prepared
2246                .candidate
2247                .modules
2248                .iter()
2249                .map(|(module, captured)| (module.clone(), captured.declaration.clone()))
2250                .collect(),
2251            ..DeliverySnapshot::default()
2252        };
2253        let mut handles = prepared.candidate.take_handles();
2254        let user_restore = if prepared.kind == PlanKind::Change && prepared.edits.is_none() {
2255            prepared
2256                .candidate
2257                .modules
2258                .iter()
2259                .filter(|(module, _)| prepared.touched_modules.contains(*module))
2260                .filter_map(|(_, captured)| {
2261                    super::restore::UserRestoreMetadata::capture(&captured.file)
2262                        .map(|metadata| (captured.file.path.clone(), metadata))
2263                })
2264                .collect()
2265        } else {
2266            BTreeMap::new()
2267        };
2268        handles.append(&mut prepared.observed_handles);
2269        let previous_delivery = if state.store.status().state == StoreState::Stamped {
2270            let body = state.store.body()?;
2271            body.generations
2272                .get(&placement::last_approved_generation(body))
2273                .and_then(|entry| entry.delivery.clone())
2274        } else if prepared.edits.as_ref().is_some_and(|edit| edit.unstamped) {
2275            Some(DeliverySnapshot {
2276                daemon: delivery.daemon.clone(),
2277                modules: prepared.bases.clone(),
2278                declarations: delivery.declarations.clone(),
2279                ..DeliverySnapshot::default()
2280            })
2281        } else {
2282            None
2283        };
2284        // Activation policy compares the candidate with what is running, not
2285        // with the last approval used by the visible field rows.
2286        let mut active_fields = Vec::new();
2287        for (module, captured) in prepared.candidate.modules.iter().filter(|(module, _)| {
2288            // Stamping records the inputs already running; unstamping returns
2289            // authority to files. Neither operation changes runtime values.
2290            matches!(prepared.kind, PlanKind::Change | PlanKind::Rollback(_))
2291                && prepared.touched_modules.contains(*module)
2292        }) {
2293            let active = if state.store.status().state == StoreState::Stamped {
2294                let body = state.store.body()?;
2295                body.versions
2296                    .iter()
2297                    .find(|(tuple, _)| tuple.module == *module && tuple.project.is_none())
2298                    .and_then(|(_, versions)| versions.active)
2299                    .and_then(|id| body.generations.get(&id))
2300                    .and_then(|entry| entry.delivery.as_ref())
2301            } else {
2302                None
2303            };
2304            let base = active.and_then(|snapshot| snapshot.modules.get(module));
2305            let schema = active
2306                .and_then(|snapshot| snapshot.declarations.get(module))
2307                .map(|declaration| subc_config::Schema::new(declaration.schema.clone()))
2308                .transpose()
2309                .map_err(GateError::invalid)?;
2310            active_fields.extend(
2311                super::review::expected_fields(
2312                    module,
2313                    &captured.schema,
2314                    base,
2315                    schema.as_ref(),
2316                    &captured.view,
2317                )?
2318                .into_values(),
2319            );
2320        }
2321        let OwnerState { gate, store, .. } = &mut *state;
2322        let mut view = gate.plan_reviewed_inner(
2323            store,
2324            prepared.kind,
2325            prepared.candidate.diagnostic,
2326            &current.diagnostic,
2327            super::ReviewRecord::Reviewed(&prepared.review_modules),
2328            prepared.edits,
2329            prepared.projects,
2330            settings_file_witness,
2331            |old, new| {
2332                let mut changeset = review(old, new)?;
2333                layer_file_rows(
2334                    &mut changeset,
2335                    old,
2336                    new,
2337                    previous_delivery.as_ref(),
2338                    &delivery,
2339                )?;
2340                let mut activation = changeset.clone();
2341                activation.fields = active_fields;
2342                super::apply::bind_plan(&mut activation)?;
2343                if !changeset.apply_plan.is_object() {
2344                    changeset.apply_plan = if changeset.apply_plan.is_null() {
2345                        serde_json::json!({})
2346                    } else {
2347                        serde_json::json!({"review": changeset.apply_plan})
2348                    };
2349                }
2350                if !edit_registry.is_empty() {
2351                    changeset.apply_plan["edit_registry"] = serde_json::json!(edit_registry);
2352                }
2353                changeset.apply_plan["module_transitions"] =
2354                    activation.apply_plan["module_transitions"].clone();
2355                Ok(changeset)
2356            },
2357        )?;
2358        view.skipped = project_skips;
2359        if !file_summary.is_empty() {
2360            let fields = &view.plan.changeset.fields;
2361            for file in &mut file_summary {
2362                if file.layer == subc_config::Layer::User {
2363                    file.affected_projects = fields
2364                        .iter()
2365                        .filter(|field| {
2366                            field.module_id == file.module_id
2367                                && (field.old_source == file.layer
2368                                    || field.new_source == file.layer)
2369                        })
2370                        .filter_map(|field| field.project_id.clone())
2371                        .collect::<BTreeSet<_>>()
2372                        .into_iter()
2373                        .collect();
2374                } else {
2375                    file.affected_projects
2376                        .retain(|project| view.plan.changeset.affected_projects.contains(project));
2377                }
2378            }
2379            view.settings_file_change = Some(subc_control::config::ConfigSettingsFileChange {
2380                label: "A settings file changed".into(),
2381                files: file_summary,
2382            });
2383        }
2384        if let Some(plan) = gate.plans.get_mut(&view.digest) {
2385            plan.user_restore = user_restore;
2386            plan.project_capture = project_context;
2387            plan.settings_users = prepared.settings_users;
2388            plan.view.skipped.clone_from(&view.skipped);
2389            plan.view
2390                .settings_file_change
2391                .clone_from(&view.settings_file_change);
2392        }
2393        if let Err(error) = self.check_route_policy_authority(&view.plan.changeset) {
2394            gate.expire_plan(&view.digest);
2395            return Err(error);
2396        }
2397        gate.bind_delivery(&view.digest, delivery)?;
2398        state.reviewed(&view.digest, Instant::now());
2399        state
2400            .retained_plan_files
2401            .insert(view.digest.clone(), handles);
2402        Ok(view)
2403    }
2404
2405    pub fn begin_approval(
2406        &self,
2407        digest: &Digest,
2408        facts: &ApprovalFacts,
2409    ) -> Result<ApprovalChallenge> {
2410        self.begin_approval_for_request(digest, facts, None)
2411    }
2412
2413    pub(crate) fn begin_approval_for_request(
2414        &self,
2415        digest: &Digest,
2416        facts: &ApprovalFacts,
2417        request: Option<&ApprovalRequest>,
2418    ) -> Result<ApprovalChallenge> {
2419        self.begin_approval_inner(digest, facts, request, None)
2420    }
2421
2422    pub(crate) fn next_settings_request_order(&self) -> u64 {
2423        self.settings_request_order
2424            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2425    }
2426
2427    pub(crate) fn begin_settings_apply_for_request(
2428        &self,
2429        digest: &Digest,
2430        facts: &ApprovalFacts,
2431        request: &ApprovalRequest,
2432        order: u64,
2433    ) -> Result<ApprovalChallenge> {
2434        self.begin_approval_inner(digest, facts, Some(request), Some(order))
2435    }
2436
2437    fn begin_approval_inner(
2438        &self,
2439        digest: &Digest,
2440        facts: &ApprovalFacts,
2441        request: Option<&ApprovalRequest>,
2442        settings_apply: Option<u64>,
2443    ) -> Result<ApprovalChallenge> {
2444        #[cfg(test)]
2445        struct Completion<'a>(&'a std::sync::atomic::AtomicUsize);
2446        #[cfg(test)]
2447        impl Drop for Completion<'_> {
2448            fn drop(&mut self) {
2449                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2450            }
2451        }
2452        #[cfg(test)]
2453        let _completed = Completion(&self.begin_approval_completions);
2454        #[cfg(test)]
2455        {
2456            let hook = self.begin_approval_hook.lock().unwrap().take();
2457            if let Some(hook) = hook {
2458                hook();
2459            }
2460        }
2461        let settings_file_witness = self.recheck_settings_file_witness(digest)?;
2462        let mut state = self.lock()?;
2463        if let Some(request) = request {
2464            request.ensure_live()?;
2465        }
2466        let daemon = facts.caller.is_daemon_settings();
2467        if let Some(order) = settings_apply {
2468            if daemon {
2469                state.claim_automatic_settings_plan(digest, order)?;
2470            }
2471            if !daemon && order < state.latest_explicit_settings_request {
2472                return Err(GateError::new(
2473                    "approval_surface_unavailable",
2474                    "a newer settings approval took precedence",
2475                ));
2476            }
2477            state.check_settings_approval(digest, daemon)?;
2478        }
2479        if state.expired_plans.contains(digest) {
2480            return Err(GateError::new(
2481                "plan_expired",
2482                "configuration plan exceeded its one-hour idle lifetime",
2483            ));
2484        }
2485        Self::check_authority(&mut state, true)?;
2486        let modules = state.gate.plan_modules(digest)?;
2487        if state.gate.plans[digest].settings_file_witness != settings_file_witness {
2488            return Err(capture_plan::changed());
2489        }
2490        let program_keys = state.gate.plan_program_keys(digest)?;
2491        let projects = state.gate.plans[digest].project_capture.clone();
2492        let user_edits = state.gate.plans[digest]
2493            .edits
2494            .as_ref()
2495            .map(|edit| edit.user_modules.clone());
2496        let settings_users = state.gate.plans[digest].settings_users.clone();
2497        let mut current = if let Some(users) = &settings_users {
2498            self.capture_settings_users(&state, Some(users), None)
2499                .map(|(capture, ..)| capture)
2500        } else if let Some(user_edits) = &user_edits {
2501            self.edit_baseline(&mut state, Some(user_edits))
2502        } else if let Some(capture) = &projects {
2503            self.capture_with_project_context(&mut state, &modules, capture)
2504        } else {
2505            self.capture_modules(&mut state, &modules)
2506        }
2507        .map_err(|_| GateError::stale())?;
2508        if let Some(capture) = projects {
2509            current.diagnostic.inputs.extend(capture.witnesses.inputs);
2510        }
2511        if settings_users.is_none() {
2512            current
2513                .capture_programs(&program_keys)
2514                .map_err(|_| GateError::stale())?;
2515        }
2516        let facts = state.with_desktop_view(digest, facts);
2517        let OwnerState { gate, store, .. } = &mut *state;
2518        if let Some(request) = request {
2519            request.ensure_live()?;
2520        }
2521        let challenge = gate.begin_approval(digest, store, &current.diagnostic, &facts)?;
2522        if let Some(order) = settings_apply {
2523            self.reserve_settings_approval(&mut state, digest, &challenge, daemon);
2524            if let Some(plan) = state.gate.plans.get_mut(digest) {
2525                plan.settings_attempt_owner = Some(order);
2526            }
2527            if !daemon {
2528                state.latest_explicit_settings_request = order;
2529            }
2530        }
2531        state.reviewed(digest, Instant::now());
2532        Ok(challenge)
2533    }
2534
2535    /// Acquire only after interactive approval. Sorted module locks serialize
2536    /// the final freshness check and publication with target changes at cutover.
2537    pub(crate) async fn approval_commit_gates(
2538        self: &std::sync::Arc<Self>,
2539        attempt: u64,
2540    ) -> Result<Vec<tokio::sync::OwnedMutexGuard<()>>> {
2541        let modules = self
2542            .on_blocking(move |owner| owner.lock()?.gate.approval_gate_modules(attempt))
2543            .await?;
2544        let mut guards = Vec::with_capacity(modules.len());
2545        for module in modules {
2546            guards.push(self.module_gate(&module)?.lock_owned().await);
2547        }
2548        Ok(guards)
2549    }
2550
2551    pub fn finish_approval(
2552        &self,
2553        attempt: u64,
2554        facts: &ApprovalFacts,
2555        reply: ApprovalReply,
2556        now_ms: u64,
2557    ) -> Result<u64> {
2558        // In-process approvals have no reader reservation. Wire approvals pass
2559        // their exact request token into the publication job instead.
2560        self.finish_approval_with_commit_window(
2561            attempt,
2562            facts,
2563            reply,
2564            now_ms,
2565            None,
2566            ApprovalRequest::for_attempt(attempt),
2567            None,
2568        )
2569    }
2570
2571    #[allow(clippy::too_many_arguments)]
2572    pub(crate) fn finish_approval_with_commit_window(
2573        &self,
2574        attempt: u64,
2575        facts: &ApprovalFacts,
2576        reply: ApprovalReply,
2577        now_ms: u64,
2578        window: Option<std::sync::Arc<ApprovalCommitWindow>>,
2579        cancellation: std::sync::Arc<ApprovalRequest>,
2580        project_apply: Option<CaptureApply>,
2581    ) -> Result<u64> {
2582        if cancellation.attempt() != attempt {
2583            return Err(GateError::new(
2584                "config_unavailable",
2585                "approval request witness does not match its attempt",
2586            ));
2587        }
2588        // The controller now holds the locks that serialize rescan and module
2589        // replacement. Reopen the workspace files before publishing the store.
2590        let reviewed_digest = self.lock()?.gate.approval_digest(attempt)?;
2591        let settings_file_witness = self.recheck_settings_file_witness(&reviewed_digest)?;
2592        let mut state = self.lock()?;
2593        let digest = state.gate.approval_digest(attempt)?;
2594        if digest != reviewed_digest
2595            || state.gate.plans[&digest].settings_file_witness != settings_file_witness
2596        {
2597            return Err(capture_plan::changed());
2598        }
2599        let project_capture = state.gate.plans[&digest].project_capture.clone();
2600        let settings_users = state.gate.plans[&digest].settings_users.clone();
2601        if let Some(capture) = &project_capture {
2602            if !capture.authority.is_empty()
2603                && project_apply
2604                    .as_ref()
2605                    .is_none_or(|apply| apply.digest != digest)
2606            {
2607                return Err(capture_plan::changed());
2608            }
2609            if state.store.status().base_revision
2610                != state.gate.plans[&digest].view.plan.base_revision
2611            {
2612                return Err(capture_plan::changed());
2613            }
2614        }
2615        if let Some(enumeration) = project_apply.and_then(|apply| apply.enumeration) {
2616            state.store.replace_registry_membership(Ok(&enumeration))?;
2617        }
2618        let declarations_only = state
2619            .gate
2620            .plans
2621            .get(&digest)
2622            .is_some_and(|plan| plan.development_approval.is_some());
2623        state.reviewed(&digest, Instant::now());
2624        let modules = state.gate.approval_modules(attempt)?;
2625        let user_modules = state.gate.plans[&digest]
2626            .targets()?
2627            .into_iter()
2628            .filter(|tuple| tuple.project.is_none())
2629            .map(|tuple| tuple.module)
2630            .collect();
2631        let program_keys = state.gate.plan_program_keys(&digest)?;
2632        // Reopen inputs after the operator's interactive confirmation, immediately
2633        // before freshness checking and atomic publication of the saved plan.
2634        let edit_plan = state
2635            .gate
2636            .plans
2637            .get(&digest)
2638            .and_then(|plan| plan.edits.clone());
2639        let current = match Self::check_authority(&mut state, true).and_then(|_| {
2640            let mut current = if let Some(users) = &settings_users {
2641                self.capture_settings_users(&state, Some(users), None)
2642                    .map(|(capture, ..)| capture)
2643            } else if let Some(edit) = &edit_plan {
2644                self.edit_baseline(&mut state, Some(&edit.user_modules))
2645            } else if let Some(capture) = &project_capture {
2646                self.capture_with_project_context(&mut state, &modules, capture)
2647            } else {
2648                self.capture_modules(&mut state, &modules)
2649            }
2650            .map_err(|_| {
2651                if project_capture.is_some() {
2652                    capture_plan::changed()
2653                } else {
2654                    GateError::stale()
2655                }
2656            })?;
2657            if let Some(capture) = &project_capture {
2658                current
2659                    .diagnostic
2660                    .inputs
2661                    .extend(capture.witnesses.inputs.clone());
2662            }
2663            if settings_users.is_none() {
2664                current
2665                    .capture_programs(&program_keys)
2666                    .map_err(|_| GateError::stale())?;
2667            }
2668            Ok(current)
2669        }) {
2670            Ok(current) => current,
2671            Err(error) => {
2672                state.gate.cancel_attempt(attempt);
2673                return Err(error);
2674            }
2675        };
2676        let facts = state.with_desktop_view(&digest, facts);
2677        self.drain_canceled_approvals(&mut state);
2678        self.drain_disconnections(&mut state);
2679        #[cfg(test)]
2680        if let Some(hook) = state.after_approval_drain_hook.take() {
2681            hook();
2682        }
2683        let was_unstamped = state.store.status().state == StoreState::Unstamped;
2684        let was_recovery = state.recovery_exit_hold
2685            || matches!(
2686                state.store.status().state,
2687                StoreState::StoreMissing | StoreState::StoreUnverified
2688            );
2689        let unstamp_hints = recovery::changed_file_views(self, &mut state, &current);
2690        #[cfg(test)]
2691        let publication_hook = state.publication_hook.take();
2692        #[cfg(test)]
2693        let prepublication_hook = state.prepublication_hook.take();
2694        let publication_before = state.store.publication_sequence();
2695        let (_, loaded) = state.store.loaded_admission_state();
2696        let ledger_checkpoint = crate::policy_root::ledger::last_checkpoint(loaded)
2697            .map(|(_, checkpoint)| checkpoint.clone());
2698        let pin_history = edit_plan
2699            .as_ref()
2700            .is_some_and(|edit| edit.policy_root.is_some())
2701            && policy_root::has_pin_history(loaded);
2702        let stamp_ledger = state
2703            .gate
2704            .plans
2705            .get(&digest)
2706            .and_then(|plan| self.stamp_ledger_intent(loaded, plan));
2707        let OwnerState {
2708            gate,
2709            store,
2710            route_policy_receipts,
2711            installed_route_policies,
2712            delivery,
2713            ..
2714        } = &mut *state;
2715        let result = gate.finish_approval_with_precommit(
2716            attempt,
2717            reply,
2718            store,
2719            &current.diagnostic,
2720            &facts,
2721            now_ms,
2722            || {
2723                #[cfg(test)]
2724                if let Some(hook) = prepublication_hook {
2725                    hook();
2726                }
2727                if let Some(window) = window {
2728                    window.begin_publication()?;
2729                }
2730                {
2731                    // Serialize the publication claim with cancellation-index
2732                    // health, then release the index before any store work.
2733                    let _index = self.approval_request_index.lock().map_err(|_| {
2734                        GateError::new(
2735                            "config_unavailable",
2736                            "approval cancellation index is poisoned",
2737                        )
2738                    })?;
2739                    cancellation.claim_publication()?;
2740                }
2741                if !declarations_only {
2742                    route_policy::restore_superseded(
2743                        route_policy_receipts,
2744                        installed_route_policies,
2745                        &user_modules,
2746                        delivery,
2747                    );
2748                }
2749                let checkpoint = if let Some(change) = edit_plan
2750                    .as_ref()
2751                    .and_then(|edit| edit.policy_root.as_ref())
2752                {
2753                    Some(self.publish_policy_root_ledger(
2754                        change,
2755                        now_ms,
2756                        ledger_checkpoint.as_ref(),
2757                        pin_history,
2758                    )?)
2759                } else if let Some(intent) = stamp_ledger {
2760                    self.publish_stamp_ledger(intent, now_ms, ledger_checkpoint.as_ref())?
2761                } else {
2762                    None
2763                };
2764                #[cfg(test)]
2765                if let Some(hook) = publication_hook {
2766                    hook();
2767                }
2768                Ok(checkpoint)
2769            },
2770        );
2771        let committed_this_call = state.store.publication_sequence() != publication_before;
2772        if committed_this_call {
2773            if let Some((card, card_attempt)) = state.pending_settings_card.take() {
2774                state.cancel_approval(card_attempt);
2775                Self::discard_settings_plan(&mut state, &card);
2776            }
2777            if state.store.status().state == StoreState::Unstamped {
2778                self.replace_unstamped_root(
2779                    policy_root::captured_section(&current)
2780                        .unwrap_or(Err("policy_root_not_canonical")),
2781                );
2782            }
2783            if let Some(edit_plan) = edit_plan {
2784                for file in &edit_plan.files {
2785                    let _ = file.write_back();
2786                }
2787                // Publication already succeeded. Refresh drift after reconciliation
2788                // without turning a failed diagnostic capture into a failed approval.
2789                let _ = self.observe_proposal(&mut state);
2790            }
2791        }
2792        let stamped_files = committed_this_call
2793            && (was_unstamped || was_recovery)
2794            && state.store.body().is_ok_and(|body| {
2795                body.generations
2796                    .get(&body.last_generation)
2797                    .is_some_and(|entry| {
2798                        entry.generation.plan_digest == digest
2799                            && entry.kind == crate::config_store::CommitKind::Stamp
2800                    })
2801            });
2802        if result.is_ok() {
2803            state.plan_deadlines.remove(&digest);
2804            state.retained_plan_files.remove(&digest);
2805            state.desktop_views.retain(|_, (shown, _)| shown != &digest);
2806        }
2807        let unstamped = result.is_ok() && state.store.status().state == StoreState::Unstamped;
2808        let committed_exit = state
2809            .store
2810            .loaded_admission_state()
2811            .1
2812            .generations
2813            .iter()
2814            .next_back()
2815            .filter(|(_, entry)| {
2816                committed_this_call
2817                    && entry.generation.plan_digest == digest
2818                    && entry.kind != crate::config_store::CommitKind::DeclarationApproval
2819                    && (was_recovery
2820                        || state.store.loaded_admission_state().1.stamped
2821                        || entry.kind == crate::config_store::CommitKind::Unstamp)
2822            })
2823            .map(|(generation, entry)| {
2824                (
2825                    *generation,
2826                    entry.kind == crate::config_store::CommitKind::Unstamp,
2827                )
2828            });
2829        if committed_this_call && was_recovery {
2830            state.authority_incarnation = std::sync::Arc::new(());
2831        }
2832        if let Some((generation, unstamp)) = committed_exit {
2833            state.authority_exit = Some(generation);
2834            state.recovery_exit_hold = was_recovery;
2835            if was_recovery || unstamp {
2836                state
2837                    .delivery
2838                    .reset_for_authority_exit(if unstamp { generation } else { 0 });
2839            }
2840            if unstamp {
2841                state.pending_settings_card_reason = None;
2842                state.settings_review_errors.clear();
2843                state.settings_review_errors_base = None;
2844                state.last_settings_decline = None;
2845                state.stamp_channel_cutover = false;
2846                state.reconciled_entries.clear();
2847                state.unstamp_hints.extend(unstamp_hints);
2848            }
2849        } else if committed_this_call {
2850            state.authority_exit = None;
2851        }
2852        if stamped_files {
2853            state.stamp_channel_cutover = true;
2854            let connections: Vec<_> = state.active_declarations.values().copied().collect();
2855            state.delivery.remember_stamp_connections(connections);
2856        }
2857        drop(state);
2858        if unstamped {
2859            self.retire_unstamped_bindings();
2860        }
2861        result
2862    }
2863
2864    #[cfg(all(test, unix))]
2865    pub(crate) fn set_publication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2866        self.inner.lock().unwrap().publication_hook = Some(Box::new(hook));
2867    }
2868
2869    #[cfg(all(test, unix))]
2870    pub(crate) fn set_prepublication_hook(&self, hook: impl FnOnce() + Send + 'static) {
2871        self.inner.lock().unwrap().prepublication_hook = Some(Box::new(hook));
2872    }
2873
2874    #[cfg(all(test, unix))]
2875    pub(crate) fn set_after_approval_drain_hook(&self, hook: impl FnOnce() + Send + 'static) {
2876        self.inner.lock().unwrap().after_approval_drain_hook = Some(Box::new(hook));
2877    }
2878
2879    #[cfg(all(test, unix))]
2880    pub(crate) fn approval_request_count_for_test(&self) -> usize {
2881        self.approval_request_index.lock().unwrap().len()
2882    }
2883
2884    #[cfg(all(test, unix))]
2885    pub(crate) fn poison_approval_request_index_for_test(&self) {
2886        let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2887            let _guard = self.approval_request_index.lock().unwrap();
2888            panic!("injected approval index poison");
2889        }));
2890        assert!(poisoned.is_err());
2891    }
2892
2893    #[cfg(all(test, unix))]
2894    pub(crate) fn pause_next_approval_claim_for_test(
2895        &self,
2896    ) -> (
2897        tokio::sync::oneshot::Receiver<()>,
2898        tokio::sync::oneshot::Sender<()>,
2899    ) {
2900        let (reached, observed) = tokio::sync::oneshot::channel();
2901        let (release, wait) = tokio::sync::oneshot::channel();
2902        *self.approval_claim_pause.lock().unwrap() = Some(ApprovalClaimPause {
2903            reached,
2904            release: wait,
2905        });
2906        (observed, release)
2907    }
2908
2909    #[cfg(all(test, unix))]
2910    pub(crate) async fn pause_approval_claim_for_test(&self) {
2911        let pause = self.approval_claim_pause.lock().unwrap().take();
2912        if let Some(pause) = pause {
2913            let _ = pause.reached.send(());
2914            pause.release.await.unwrap();
2915        }
2916    }
2917
2918    // Flipping a flag is platform-neutral. Its callers are the unix-only phone
2919    // tests and, under test-support, the ckdev config test seam and its tests.
2920    #[cfg(any(all(test, unix), feature = "test-support"))]
2921    pub(crate) fn set_os_prompt_policy_for_tests(&self) {
2922        self.os_prompt_policy
2923            .store(true, std::sync::atomic::Ordering::Relaxed);
2924    }
2925
2926    #[cfg(test)]
2927    pub(crate) fn has_trusted_review_connection_for_test(&self, id: crate::ConnectionId) -> bool {
2928        *self.trusted_review_connection_for_test.lock().unwrap() == Some(id)
2929    }
2930
2931    #[cfg(any(test, feature = "test-support"))]
2932    pub(crate) fn os_prompt_policy_for_tests(&self) -> bool {
2933        self.os_prompt_policy
2934            .load(std::sync::atomic::Ordering::Relaxed)
2935    }
2936
2937    pub fn status(&self) -> Result<subc_control::config::ConfigStatus> {
2938        let mut state = self.lock()?;
2939        let mut current_snapshot = None;
2940        let mut observation = None;
2941        state.retry_anchor(true);
2942        let verified = state.store.check().is_ok();
2943        if verified
2944            && !state.recovery_exit_hold
2945            && !state.store.status().anchor_pending
2946            && matches!(
2947                state.store.status().state,
2948                StoreState::Stamped | StoreState::Unstamped
2949            )
2950        {
2951            observation = Some(self.observe_proposal(&mut state)?);
2952            current_snapshot = state.observed_snapshot.clone();
2953        }
2954        let store_status = state.store.status();
2955        let mut status = subc_control::config::ConfigStatus::default();
2956        status.state = match store_status.state {
2957            StoreState::Stamped => "stamped",
2958            StoreState::Unstamped => "unstamped",
2959            StoreState::StoreMissing => "store_missing",
2960            StoreState::StoreUnverified => "store_unverified",
2961        }
2962        .into();
2963        if state.recovery_exit_hold {
2964            if store_status.state != StoreState::Stamped {
2965                status.state = "store_unverified".into();
2966            }
2967            status
2968                .warnings
2969                .push("approved recovery exit is waiting for reconciliation".into());
2970        }
2971        status.integrity = match store_status.integrity {
2972            crate::config_store::IntegrityMode::DigestOnly => "digest_only",
2973            crate::config_store::IntegrityMode::Sealed => "sealed",
2974        }
2975        .into();
2976        status.revision = store_status.revision;
2977        status.base_revision = store_status.base_revision;
2978        status.anchor_pending = store_status.anchor_pending;
2979        status.root_io = self.capturer.projects.root_io_health();
2980        status.ungated_inputs = self.startup_overrides.clone();
2981        #[cfg(feature = "test-support")]
2982        if state.store.uses_config_gate_test_seam() {
2983            status
2984                .development_switches
2985                .push("SUBC_TEST_CONFIG_GATE".into());
2986        }
2987        status.warnings.extend(store_status.warnings);
2988        if cfg!(feature = "dev-desktop-approval") {
2989            status
2990                .development_switches
2991                .push("dev-desktop-approval".into());
2992        }
2993        #[cfg(feature = "dev-desktop-approval")]
2994        if let Some(floor) = crate::operator_apps::development_floor_diagnostic() {
2995            status.development_switches.push(floor);
2996        }
2997        if cfg!(feature = "dev-placement") {
2998            status.development_switches.push("dev-placement".into());
2999        }
3000        let declared: Vec<String> = Self::declarations(&mut state)
3001            .map(|declarations| declarations.into_keys().collect())
3002            .unwrap_or_default();
3003        if let Ok(body) = state.store.body() {
3004            if body.stamped {
3005                for (module, rereview) in
3006                    super::reviewed_build::pending(body, &declared).unwrap_or_default()
3007                {
3008                    status.warnings.push(match rereview {
3009                        super::reviewed_build::Rereview::WaitingForProgram => format!(
3010                            "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"
3011                        ),
3012                        super::reviewed_build::Rereview::Ready => format!(
3013                            "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"
3014                        ),
3015                    });
3016                }
3017            }
3018            if body.stamped {
3019                current_snapshot = super::GateSnapshot::from_store(&body.approved).ok();
3020            }
3021            for entry in body.generations.values().rev().take_while(|entry| {
3022                matches!(
3023                    entry.kind,
3024                    crate::config_store::CommitKind::Development
3025                        | crate::config_store::CommitKind::DeclarationApproval
3026                )
3027            }) {
3028                if entry.kind != crate::config_store::CommitKind::Development {
3029                    continue;
3030                }
3031                status.warnings.push(format!(
3032                    "development generation {}: development placement (no approval)",
3033                    entry.generation.id
3034                ));
3035            }
3036            status.approval_channels = body
3037                .generations
3038                .iter()
3039                .map(|(id, entry)| {
3040                    subc_control::config::ConfigApprovalRecord::new(
3041                        *id,
3042                        entry.generation.approval_channel,
3043                    )
3044                })
3045                .chain(body.pruned.iter().map(|(id, entry)| {
3046                    subc_control::config::ConfigApprovalRecord::new(*id, entry.approval_channel)
3047                }))
3048                .collect();
3049            status
3050                .approval_channels
3051                .sort_by_key(|record| record.generation);
3052            status.pending_proposals = u64::from(body.proposal.is_some());
3053            for (tuple, versions) in &body.versions {
3054                if let Some(generation) = versions.pending {
3055                    let entry = body.generations.get(&generation);
3056                    let transition = entry.and_then(|entry| {
3057                        super::apply::Transition::for_module(
3058                            &entry.generation.changeset,
3059                            &tuple.module,
3060                        )
3061                        .ok()
3062                    });
3063                    status.approved_but_inactive.push(serde_json::json!({
3064                        "module_id":tuple.module,"project_id":tuple.project,"generation":generation,
3065                        "digest":entry.map(|entry| &entry.generation.plan_digest),
3066                        "waiting_for":match transition {
3067                            Some(super::apply::Transition::DaemonRestart) => "daemon_restart",
3068                            Some(super::apply::Transition::NextSupervision) => "next_supervision",
3069                            _ => "delivery",
3070                        },
3071                    }));
3072                }
3073            }
3074        }
3075        if let Some(snapshot) = current_snapshot {
3076            status_inputs::report_snapshot(&snapshot, &mut status);
3077        }
3078        if let Some(captured) = observation {
3079            if status.state == "stamped" {
3080                self.log_user_file_observations(&captured);
3081            }
3082            captured.report_errors(&mut status);
3083        }
3084        status.gated_modules = admission::AdmissionCache::from_state(&state).held_modules();
3085        if state.store.loaded_admission_state().0 == StoreState::Stamped {
3086            let declarations: Vec<_> = state
3087                .declarations
3088                .iter()
3089                .map(|(connection, (module, _))| (*connection, module.clone()))
3090                .collect();
3091            for (connection, module) in declarations {
3092                // Use get's approved-declaration/view checks without opening the
3093                // store or binding a delivery attempt merely to display status.
3094                let reply = self.module_get_locked(
3095                    &mut state,
3096                    connection,
3097                    &module,
3098                    subc_protocol::config::ConfigGetRequest::new(),
3099                    false,
3100                );
3101                if let Ok(reply) = &reply {
3102                    Self::report_declaration_pending(
3103                        &state,
3104                        connection,
3105                        &module,
3106                        reply,
3107                        &mut status,
3108                    );
3109                }
3110                if reply.is_err_and(|error| error.code == "config_gated") {
3111                    status.gated_modules.push(module);
3112                }
3113            }
3114            status.gated_modules.sort();
3115            status.gated_modules.dedup();
3116        }
3117        Ok(status)
3118    }
3119
3120    fn report_declaration_pending(
3121        state: &OwnerState,
3122        connection: ConnectionId,
3123        module: &str,
3124        reply: &subc_protocol::config::ConfigGetReply,
3125        status: &mut subc_control::config::ConfigStatus,
3126    ) {
3127        if state.active_declarations.get(module) != Some(&connection) {
3128            return;
3129        }
3130        if let Some(marker) = &reply.declaration_pending {
3131            status
3132                .declaration_pending
3133                .insert(module.into(), marker.clone());
3134            if let Some(generation) = state.delivery.fallback_applied.get(&connection) {
3135                if reply
3136                    .active
3137                    .as_ref()
3138                    .is_some_and(|view| view.generation == *generation)
3139                {
3140                    status.warnings.push(format!("module {module}: running last approved settings (generation {generation}); declaration awaits approval"));
3141                }
3142            }
3143        }
3144    }
3145
3146    pub fn history(&self) -> Result<(Vec<subc_config::Generation>, Vec<serde_json::Value>)> {
3147        let mut state = self.lock()?;
3148        state.retry_anchor(true);
3149        state.store.check()?;
3150        let body = state.store.body()?;
3151        Ok((
3152            body.generations
3153                .values()
3154                .map(|entry| entry.generation.clone())
3155                .collect(),
3156            body.pruned
3157                .values()
3158                .map(serde_json::to_value)
3159                .collect::<std::result::Result<_, _>>()
3160                .map_err(GateError::invalid)?,
3161        ))
3162    }
3163
3164    /// Admission is owned by the supervisor adapter; until it is installed it
3165    /// must not infer executable authority from diagnostic snapshots.
3166    pub fn approved_snapshot(&self) -> Result<DeliverySnapshot> {
3167        let mut state = self.lock()?;
3168        state.store.delivery_ready()?;
3169        state
3170            .store
3171            .body()?
3172            .generations
3173            .values()
3174            .next_back()
3175            .and_then(|entry| entry.delivery.clone())
3176            .ok_or_else(|| GateError::new("config_gated", "approved delivery snapshot is absent"))
3177    }
3178
3179    /// Read the saved rollback, never today's edited files. This is not spawn
3180    /// authorization: admission must select an eligible module generation and
3181    /// launch exactly the returned identity under that module's gate lock.
3182    /// Re-check the file identity at spawn and refuse `plan_stale` if it changed
3183    /// since approval. Path-changing rollback plans remain refused until the
3184    /// supervisor uses these approved inputs to select and launch programs at
3185    /// the restored paths.
3186    pub fn approved_rollback_commands(&self, generation: u64) -> Result<ApprovedRollbackCommands> {
3187        let mut state = self.lock()?;
3188        state.store.delivery_ready()?;
3189        let configuration = state.store.rollback_configuration(generation)?;
3190        let entry = &state.store.body()?.generations[&generation];
3191        if entry.kind != crate::config_store::CommitKind::Rollback {
3192            return Err(GateError::new(
3193                "rollback_generation_required",
3194                "generation is not an approved rollback",
3195            ));
3196        }
3197        let daemon = entry
3198            .delivery
3199            .as_ref()
3200            .and_then(|snapshot| snapshot.daemon.clone())
3201            .ok_or_else(|| {
3202                GateError::new(
3203                    "rollback_snapshot_unavailable",
3204                    "approved rollback command input is absent",
3205                )
3206            })?;
3207        let snapshot = super::GateSnapshot::from_store(&configuration)?;
3208        let mut programs = BTreeMap::new();
3209        for (key, identity) in snapshot.inputs {
3210            if let super::InputKey::Program { module, path } = key {
3211                if programs
3212                    .insert(module, ApprovedRollbackProgram { path, identity })
3213                    .is_some()
3214                {
3215                    return Err(GateError::new(
3216                        "rollback_snapshot_unavailable",
3217                        "rollback contains conflicting program identities",
3218                    ));
3219                }
3220            }
3221        }
3222        Ok(ApprovedRollbackCommands {
3223            generation,
3224            daemon,
3225            programs,
3226        })
3227    }
3228}