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