Skip to main content

subc_daemon/config_gate/
runtime.rs

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