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