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