Skip to main content

subc_daemon/config_gate/
runtime.rs

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