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