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