Skip to main content

subc_daemon/config_gate/
runtime.rs

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