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