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