Skip to main content

subc_daemon/config_gate/
runtime.rs

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