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