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