Skip to main content

adk_kernel/drivers/
supervisor.rs

1//! The driver supervisor over `adk-tool`'s MCP manager (spec 3.2 §7.7, K-I13, K-I14).
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, RwLock, Weak};
7use std::time::Duration;
8
9use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
10use adk_core::{
11    ActingContext, AdkError, CredentialBroker, ErrorCategory, ErrorComponent, ReadonlyContext,
12    SubjectKind, Tool, ToolOrigin, ToolPolicy, Toolset,
13};
14use adk_tool::mcp::{ElicitationHandler, McpServerManager, ServerStatus, ServerStatusTransition};
15use adk_tool::sampling::SamplingHandler;
16use async_trait::async_trait;
17use chrono::Utc;
18use serde::{Deserialize, Serialize};
19use serde_json::{Value, json};
20use tokio::task::JoinHandle;
21
22use super::launch::{EnforcerSource, LaunchPlan, clear_run_dir, platform_enforcer, prepare};
23use super::manifest::{DriverAccess, DriverLifecycle, DriverManifest, DriverSandbox};
24use super::policy::DriverPolicy;
25use super::store::{DriverRecord, DriverStore};
26use super::tool::{DriverElicitation, DriverToolset, LegacyWaiters};
27use super::{DriverState, EffectClass, driver_of, driver_source};
28use crate::audit;
29use crate::bus::{EventBus, KernelEvent};
30use crate::error::{KernelError, Result};
31use crate::partition::{PartitionId, PartitionPolicy};
32
33/// Builds the sampling handler of a driver whose manifest lets it sample.
34pub(crate) type SamplingFactory =
35    Arc<dyn Fn(&DriverManifest) -> Option<Arc<dyn SamplingHandler>> + Send + Sync>;
36
37/// Carries a person's standing rules forward when a driver's changed declarations are
38/// re-approved (spec 3.2 §7.7, K-I14).
39///
40/// The kernel depends on no harness type, so the harness implements this over its
41/// standing-rule store (`adk-harness`'s `kernel` feature).
42///
43/// # Example
44///
45/// ```rust
46/// use adk_kernel::drivers::StandingRulePins;
47///
48/// #[derive(Debug)]
49/// struct NoRules;
50///
51/// #[async_trait::async_trait]
52/// impl StandingRulePins for NoRules {
53///     async fn repin(&self, _: &str, _: &str, _: &str, _: &str, _: &str) -> adk_core::Result<usize> {
54///         Ok(0)
55///     }
56/// }
57/// ```
58#[async_trait]
59pub trait StandingRulePins: std::fmt::Debug + Send + Sync {
60    /// Moves `subject`'s standing rules for `tool` from `source` pinned to the declaration
61    /// digest `from` onto `to`, and returns how many moved.
62    ///
63    /// # Errors
64    ///
65    /// Returns the rule store's error.
66    async fn repin(
67        &self,
68        subject: &str,
69        source: &str,
70        tool: &str,
71        from: &str,
72        to: &str,
73    ) -> adk_core::Result<usize>;
74}
75
76/// What the person approving a mount sees (spec 3.2 §7.7): the command line, the
77/// partitions and the effect classes, with the sandbox, its access and the secrets the
78/// driver names.
79///
80/// # Example
81///
82/// ```rust
83/// use adk_kernel::drivers::{DriverManifest, DriverProposal, EffectClass};
84///
85/// let manifest = DriverManifest::from_toml(r#"
86///     id = "email"
87///     command = "mcp-email"
88///     env = { EMAIL_TOKEN = "secret://email/token" }
89///     [tools]
90///     send_draft = "send_external"
91/// "#).unwrap();
92/// let proposal = DriverProposal::of(&manifest);
93/// assert_eq!(proposal.command_line, "mcp-email");
94/// assert_eq!(proposal.secrets["EMAIL_TOKEN"], "secret://email/token");
95/// assert_eq!(proposal.unlisted_tools, EffectClass::Other);
96/// ```
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99#[non_exhaustive]
100pub struct DriverProposal {
101    /// The driver's id.
102    pub id: String,
103    /// The command and its arguments, quoted as the shell would need.
104    pub command_line: String,
105    /// The digest recorded with the approval.
106    pub command_digest: String,
107    /// The partitions whose agents may use it.
108    pub partitions: Vec<PartitionId>,
109    /// How its process is isolated.
110    pub sandbox: DriverSandbox,
111    /// What a sandboxed process may reach.
112    pub access: DriverAccess,
113    /// The effect class of each listed tool.
114    pub effect_classes: BTreeMap<String, EffectClass>,
115    /// The class of every tool the manifest does not list: always `other`.
116    pub unlisted_tools: EffectClass,
117    /// The `secret://` references of its environment, by variable; never a secret.
118    pub secrets: BTreeMap<String, String>,
119    /// The labels of the data it handles.
120    pub data_classes: Vec<String>,
121    /// Whether it may sample the harness model.
122    pub sampling: bool,
123    /// When it starts.
124    pub lifecycle: DriverLifecycle,
125}
126
127impl DriverProposal {
128    /// The proposal of mounting `manifest`.
129    pub fn of(manifest: &DriverManifest) -> Self {
130        Self {
131            id: manifest.id.clone(),
132            command_line: manifest.command_line(),
133            command_digest: manifest.command_digest(),
134            partitions: manifest.partitions.clone(),
135            sandbox: manifest.sandbox,
136            access: manifest.access.clone(),
137            effect_classes: manifest.tools.clone(),
138            unlisted_tools: EffectClass::Other,
139            secrets: manifest
140                .secret_references()
141                .into_iter()
142                .map(|(name, reference)| (name, reference.to_string()))
143                .collect(),
144            data_classes: manifest.data_classes.clone(),
145            sampling: manifest.sampling,
146            lifecycle: manifest.lifecycle,
147        }
148    }
149}
150
151/// A mounted driver and its current state, as `GET /api/kernel/drivers` lists it.
152///
153/// # Example
154///
155/// ```rust
156/// use adk_kernel::drivers::{DriverManifest, DriverRecord, DriverState, DriverView};
157///
158/// let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n").unwrap();
159/// let view = DriverView::new(DriverRecord::new(manifest, "alice", chrono::Utc::now()), DriverState::Stopped);
160/// assert_eq!(view.command_line, "mcp-fs");
161/// ```
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164#[non_exhaustive]
165pub struct DriverView {
166    /// The approved record.
167    pub record: DriverRecord,
168    /// The driver's state.
169    pub state: DriverState,
170    /// The command line that runs.
171    pub command_line: String,
172}
173
174impl DriverView {
175    /// The view of `record` in `state`.
176    pub fn new(record: DriverRecord, state: DriverState) -> Self {
177        Self { command_line: record.manifest.command_line(), record, state }
178    }
179}
180
181/// Builds a [`DriverSupervisor`].
182pub struct DriverSupervisorBuilder {
183    store: Arc<dyn DriverStore>,
184    app_name: Option<String>,
185    home: Option<PathBuf>,
186    broker: Option<Arc<dyn CredentialBroker>>,
187    fail_if_sandbox_unavailable: bool,
188    enforcer: EnforcerSource,
189    sampling: Option<SamplingFactory>,
190    fallback_elicitation: Option<Arc<dyn ElicitationHandler>>,
191    health_interval: Duration,
192    question_timeout: Duration,
193    rule_pins: Option<Arc<dyn StandingRulePins>>,
194    bus: Option<EventBus>,
195    audit: Option<AuditTrail>,
196}
197
198impl std::fmt::Debug for DriverSupervisorBuilder {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        f.debug_struct("DriverSupervisorBuilder")
201            .field("app_name", &self.app_name)
202            .field("home", &self.home)
203            .field("fail_if_sandbox_unavailable", &self.fail_if_sandbox_unavailable)
204            .finish_non_exhaustive()
205    }
206}
207
208impl DriverSupervisorBuilder {
209    /// How often a running driver's connection is checked by default: 2 seconds.
210    pub const DEFAULT_HEALTH_INTERVAL: Duration = Duration::from_secs(2);
211    /// How long a parked driver call's question waits by default: 24 hours.
212    pub const DEFAULT_QUESTION_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
213
214    /// Records the app's drivers in `store`; it runs under the kernel's app name and home
215    /// once the kernel is built with it, unless set here.
216    pub fn new(store: Arc<dyn DriverStore>) -> Self {
217        Self {
218            store,
219            app_name: None,
220            home: None,
221            broker: None,
222            fail_if_sandbox_unavailable: false,
223            enforcer: platform_enforcer(),
224            sampling: None,
225            fallback_elicitation: None,
226            health_interval: Self::DEFAULT_HEALTH_INTERVAL,
227            question_timeout: Self::DEFAULT_QUESTION_TIMEOUT,
228            rule_pins: None,
229            bus: None,
230            audit: None,
231        }
232    }
233
234    /// The app the drivers' acting agents belong to (`urn:adk:agent:<app>/driver.<id>`).
235    #[must_use]
236    pub fn app_name(mut self, app_name: impl Into<String>) -> Self {
237        self.app_name = Some(app_name.into());
238        self
239    }
240
241    /// The kernel home; drivers keep their scratch homes and secret files under
242    /// `<home>/drivers/run/<id>`.
243    #[must_use]
244    pub fn home(mut self, home: impl Into<PathBuf>) -> Self {
245        self.home = Some(home.into());
246        self
247    }
248
249    /// Resolves `secret://` references (spec 3.2 §7.7). The broker is asked for each one
250    /// as the driver's acting agent, `urn:adk:agent:<app>/driver.<id>`, at every start.
251    #[must_use]
252    pub fn credential_broker(mut self, broker: Arc<dyn CredentialBroker>) -> Self {
253        self.broker = Some(broker);
254        self
255    }
256
257    /// Refuses to start a driver whose sandbox is unavailable instead of recording it
258    /// unsandboxed. A kernel's [`KernelConfig::fail_if_sandbox_unavailable`] also sets it.
259    ///
260    /// [`KernelConfig::fail_if_sandbox_unavailable`]: crate::KernelConfig::fail_if_sandbox_unavailable
261    #[must_use]
262    pub fn fail_if_sandbox_unavailable(mut self, fail: bool) -> Self {
263        self.fail_if_sandbox_unavailable = fail;
264        self
265    }
266
267    /// Builds the sampling handler of each driver whose manifest sets `sampling = true`;
268    /// a driver without one cannot sample (spec 3.2 §7.7).
269    #[must_use]
270    pub fn sampling_handlers<F>(mut self, factory: F) -> Self
271    where
272        F: Fn(&DriverManifest) -> Option<Arc<dyn SamplingHandler>> + Send + Sync + 'static,
273    {
274        self.sampling = Some(Arc::new(factory));
275        self
276    }
277
278    /// Answers elicitations a driver sends outside any call; without one they are declined.
279    #[must_use]
280    pub fn idle_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
281        self.fallback_elicitation = Some(handler);
282        self
283    }
284
285    /// How often a running driver's connection is checked; a closed one is restarted under
286    /// its restart policy.
287    #[must_use]
288    pub fn health_check_interval(mut self, interval: Duration) -> Self {
289        self.health_interval = interval;
290        self
291    }
292
293    /// How long the question of a parked driver call waits for an answer.
294    #[must_use]
295    pub fn question_timeout(mut self, timeout: Duration) -> Self {
296        self.question_timeout = timeout;
297        self
298    }
299
300    /// Carries the re-approving person's standing rules forward at re-approval.
301    #[must_use]
302    pub fn rule_pins(mut self, pins: Arc<dyn StandingRulePins>) -> Self {
303        self.rule_pins = Some(pins);
304        self
305    }
306
307    /// Publishes `Driver` events on `bus`; the kernel sets its own.
308    #[must_use]
309    pub fn event_bus(mut self, bus: EventBus) -> Self {
310        self.bus = Some(bus);
311        self
312    }
313
314    /// Writes `kernel.driver.*` records to `trail`; the kernel sets its own.
315    #[must_use]
316    pub fn audit(mut self, trail: AuditTrail) -> Self {
317        self.audit = Some(trail);
318        self
319    }
320
321    /// Builds the supervisor. Nothing starts until [`DriverSupervisor::start`], which a
322    /// kernel calls from `Kernel::start`.
323    pub fn build(self) -> DriverSupervisor {
324        DriverSupervisor {
325            inner: Arc::new(Inner {
326                store: self.store,
327                app_name: RwLock::new(self.app_name),
328                home: RwLock::new(self.home),
329                broker: self.broker,
330                fail_if_sandbox_unavailable: AtomicBool::new(self.fail_if_sandbox_unavailable),
331                enforcer: self.enforcer,
332                sampling: self.sampling,
333                fallback_elicitation: self.fallback_elicitation,
334                health_interval: self.health_interval,
335                question_timeout: self.question_timeout,
336                rule_pins: RwLock::new(self.rule_pins),
337                hooks: RwLock::new(Hooks { bus: self.bus, audit: self.audit, kernel_id: None }),
338                live: tokio::sync::Mutex::new(BTreeMap::new()),
339                view: RwLock::new(BTreeMap::new()),
340                states: RwLock::new(BTreeMap::new()),
341                attempts: std::sync::Mutex::new(BTreeMap::new()),
342                loaded: tokio::sync::OnceCell::new(),
343                legacy: Arc::new(LegacyWaiters::default()),
344                crossings: RwLock::new(BTreeMap::new()),
345                approved: std::sync::Mutex::new(Vec::new()),
346            }),
347        }
348    }
349}
350
351/// Where events and records go.
352#[derive(Default)]
353struct Hooks {
354    bus: Option<EventBus>,
355    audit: Option<AuditTrail>,
356    kernel_id: Option<String>,
357}
358
359/// A mounted driver's manager while the supervisor runs.
360pub(crate) struct Live {
361    pub(crate) manager: Arc<McpServerManager>,
362    plan: Arc<RwLock<Option<LaunchPlan>>>,
363    watcher: std::sync::Mutex<Option<JoinHandle<()>>>,
364    /// Held while the driver starts; `true` once its health monitor runs.
365    started: tokio::sync::Mutex<bool>,
366}
367
368pub(crate) struct Inner {
369    pub(crate) store: Arc<dyn DriverStore>,
370    app_name: RwLock<Option<String>>,
371    home: RwLock<Option<PathBuf>>,
372    broker: Option<Arc<dyn CredentialBroker>>,
373    fail_if_sandbox_unavailable: AtomicBool,
374    enforcer: EnforcerSource,
375    sampling: Option<SamplingFactory>,
376    fallback_elicitation: Option<Arc<dyn ElicitationHandler>>,
377    health_interval: Duration,
378    pub(crate) question_timeout: Duration,
379    rule_pins: RwLock<Option<Arc<dyn StandingRulePins>>>,
380    hooks: RwLock<Hooks>,
381    live: tokio::sync::Mutex<BTreeMap<String, Arc<Live>>>,
382    /// The mounted records, read synchronously by the policy and the harness's classes.
383    view: RwLock<BTreeMap<String, DriverRecord>>,
384    states: RwLock<BTreeMap<String, DriverState>>,
385    /// Starts since a driver last ran, for `kernel.driver.restarted`.
386    attempts: std::sync::Mutex<BTreeMap<String, u32>>,
387    loaded: tokio::sync::OnceCell<()>,
388    pub(crate) legacy: Arc<LegacyWaiters>,
389    /// The driver tool each crossing tool wraps, by driver and crossing name, so a crossing
390    /// is classed and governed as the tool it reaches (spec 3.2 §7.8).
391    crossings: RwLock<BTreeMap<(String, String), String>>,
392    /// Manifests approved before the supervisor started, with who approved each; mounted
393    /// by [`DriverSupervisor::start`].
394    approved: std::sync::Mutex<Vec<(DriverManifest, String)>>,
395}
396
397/// The kernel's supervisor of drivers: MCP servers run as child processes under the
398/// manifests the user approved (spec 3.2 §7.7).
399///
400/// Each mounted driver runs on an `McpServerManager` of its own, so its stdio launcher,
401/// sandbox, secrets and sampling handler are its own; the manager's status channel
402/// (spec 3.2 §10 T1) becomes [`KernelEvent::Driver`] events and `kernel.driver.*` records.
403/// Clones share the supervisor.
404///
405/// # Example
406///
407/// ```rust,no_run
408/// use std::sync::Arc;
409/// use adk_kernel::drivers::{DriverManifest, DriverSupervisor};
410/// use adk_kernel::stores::InMemoryDriverStore;
411///
412/// # async fn example(runs: Arc<dyn adk_core::DurableRunStore>) -> adk_kernel::Result<()> {
413/// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
414/// let kernel = adk_kernel::Kernel::builder().run_store(runs).drivers(drivers.clone()).build()?;
415/// kernel.start().await?;
416///
417/// let manifest = DriverManifest::from_file("email.toml")?;
418/// println!("{:?}", adk_kernel::drivers::DriverProposal::of(&manifest)); // shown to the person
419/// drivers.mount(manifest, "alice").await?;
420/// let tools = drivers.toolset_for(&"work".into(), &["email".to_string()]);
421/// # Ok(())
422/// # }
423/// ```
424#[derive(Clone)]
425pub struct DriverSupervisor {
426    pub(crate) inner: Arc<Inner>,
427}
428
429impl std::fmt::Debug for DriverSupervisor {
430    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
431        let mounted: Vec<String> =
432            self.inner.view.read().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect();
433        f.debug_struct("DriverSupervisor").field("mounted", &mounted).finish_non_exhaustive()
434    }
435}
436
437pub(crate) fn not_mounted(id: &str) -> KernelError {
438    KernelError::Core(AdkError::new(
439        ErrorComponent::Server,
440        ErrorCategory::NotFound,
441        crate::error::NOT_FOUND_CODE,
442        format!("no driver `{id}` is mounted; mount its manifest first"),
443    ))
444}
445
446impl DriverSupervisor {
447    /// A builder over `store`.
448    pub fn builder(store: Arc<dyn DriverStore>) -> DriverSupervisorBuilder {
449        DriverSupervisorBuilder::new(store)
450    }
451
452    /// The store of mounted drivers and parked calls.
453    pub fn store(&self) -> &Arc<dyn DriverStore> {
454        &self.inner.store
455    }
456
457    /// Sets what the kernel provides: the bus, the audit trail, the kernel's id, app, home
458    /// and sandbox policy, where the builder did not.
459    pub(crate) fn attach(
460        &self,
461        bus: &EventBus,
462        audit: Option<&AuditTrail>,
463        kernel_id: &str,
464        app_name: &str,
465        home: &Path,
466        fail_if_sandbox_unavailable: bool,
467    ) {
468        let mut hooks = self.inner.hooks.write().unwrap_or_else(|e| e.into_inner());
469        hooks.bus.get_or_insert_with(|| bus.clone());
470        if hooks.audit.is_none() {
471            hooks.audit = audit.cloned();
472        }
473        hooks.kernel_id = Some(kernel_id.to_string());
474        drop(hooks);
475        self.inner
476            .app_name
477            .write()
478            .unwrap_or_else(|e| e.into_inner())
479            .get_or_insert_with(|| app_name.to_string());
480        self.inner
481            .home
482            .write()
483            .unwrap_or_else(|e| e.into_inner())
484            .get_or_insert_with(|| home.to_path_buf());
485        if fail_if_sandbox_unavailable {
486            self.inner.fail_if_sandbox_unavailable.store(true, Ordering::SeqCst);
487        }
488    }
489
490    /// Sets the app and the home the drivers run under where the builder set neither, before
491    /// a kernel attaches its own: a tenant kernel gives each tenant's drivers a home of the
492    /// tenant's own (spec 3.2 §7.13).
493    #[cfg(feature = "managed")]
494    pub(crate) fn host_defaults(&self, app_name: &str, home: &Path) {
495        self.inner
496            .app_name
497            .write()
498            .unwrap_or_else(|e| e.into_inner())
499            .get_or_insert_with(|| app_name.to_string());
500        self.inner
501            .home
502            .write()
503            .unwrap_or_else(|e| e.into_inner())
504            .get_or_insert_with(|| home.to_path_buf());
505    }
506
507    /// Whether `other` is this supervisor, rather than a clone of another.
508    #[cfg(feature = "managed")]
509    pub(crate) fn same(&self, other: &Self) -> bool {
510        Arc::ptr_eq(&self.inner, &other.inner)
511    }
512
513    /// Loads the mounted drivers, mounts those approved with
514    /// [`mount_at_start`](Self::mount_at_start), and starts the eager ones. A driver that
515    /// fails to start is logged and left `FailedToStart`; the others start.
516    ///
517    /// # Errors
518    ///
519    /// Returns the store's error.
520    pub async fn start(&self) -> Result<()> {
521        self.inner.load().await?;
522        let approved =
523            std::mem::take(&mut *self.inner.approved.lock().unwrap_or_else(|e| e.into_inner()));
524        let mut mounted = BTreeSet::new();
525        for (manifest, by) in approved {
526            // Mounting again would clear the pins of a driver already mounted as approved.
527            if self.is_mounted_as(&manifest).await? {
528                continue;
529            }
530            mounted.insert(manifest.id.clone());
531            self.mount(manifest, &by).await?;
532        }
533        let records: Vec<DriverRecord> =
534            self.inner.view.read().unwrap_or_else(|e| e.into_inner()).values().cloned().collect();
535        for record in records.into_iter().filter(|record| !mounted.contains(record.id())) {
536            self.inner.activate(&record).await;
537            if record.manifest.lifecycle == DriverLifecycle::Eager
538                && let Err(error) = self.inner.ensure_started(record.id()).await
539            {
540                tracing::warn!(driver.id = %record.id(), error = %error, "eager driver did not start");
541            }
542        }
543        Ok(())
544    }
545
546    /// Stops every driver's server and removes its secret files.
547    pub async fn shutdown(&self) {
548        let live: Vec<(String, Arc<Live>)> =
549            std::mem::take(&mut *self.inner.live.lock().await).into_iter().collect();
550        for (id, live) in live {
551            self.inner.stop_live(&id, &live).await;
552        }
553    }
554
555    /// What mounting `manifest` asks the person to approve.
556    pub fn propose(&self, manifest: &DriverManifest) -> DriverProposal {
557        DriverProposal::of(manifest)
558    }
559
560    /// Whether driver `manifest.id` is mounted under exactly `manifest`, so mounting it
561    /// needs no new approval (spec 3.2 §7.7, K-I13). The declaration digests pinned since
562    /// the approval are not compared: they are the kernel's, not the manifest's.
563    ///
564    /// # Example
565    ///
566    /// ```rust
567    /// use std::sync::Arc;
568    /// use adk_kernel::drivers::{DriverManifest, DriverSupervisor};
569    /// use adk_kernel::stores::InMemoryDriverStore;
570    ///
571    /// # #[tokio::main(flavor = "current_thread")]
572    /// # async fn main() -> adk_kernel::Result<()> {
573    /// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
574    /// let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n")?;
575    /// assert!(!drivers.is_mounted_as(&manifest).await?);
576    /// drivers.mount(manifest.clone(), "alice").await?;
577    /// assert!(drivers.is_mounted_as(&manifest).await?);
578    /// # Ok(())
579    /// # }
580    /// ```
581    ///
582    /// # Errors
583    ///
584    /// Returns the store's error.
585    pub async fn is_mounted_as(&self, manifest: &DriverManifest) -> Result<bool> {
586        self.inner.load().await?;
587        let Some(record) = self.record(&manifest.id) else { return Ok(false) };
588        let mut approved = record.manifest;
589        approved.declaration_digests.clone_from(&manifest.declaration_digests);
590        Ok(approved == *manifest)
591    }
592
593    /// Mounts `manifest`, approved by `by`, when [`start`](Self::start) runs — which a
594    /// kernel calls from `Kernel::start` — so the mount is recorded as
595    /// `kernel.driver.mounted` on the kernel's audit trail and published on its bus (spec
596    /// 3.2 §7.7, §8.2, K-I13). `adk-rust up` uses it for the drivers `[kernel] drivers`
597    /// lists, after the person approves each one at its terminal.
598    ///
599    /// A manifest already mounted as approved when the supervisor starts is left as it is,
600    /// with its pinned declarations. After `start`, call [`mount`](Self::mount) instead.
601    ///
602    /// # Example
603    ///
604    /// ```rust
605    /// use std::sync::Arc;
606    /// use adk_kernel::drivers::{DriverManifest, DriverSupervisor};
607    /// use adk_kernel::stores::InMemoryDriverStore;
608    ///
609    /// # #[tokio::main(flavor = "current_thread")]
610    /// # async fn main() -> adk_kernel::Result<()> {
611    /// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
612    /// let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n")?;
613    /// drivers.mount_at_start(manifest.clone(), "alice");
614    /// assert!(drivers.mounted().is_empty(), "nothing is mounted before start");
615    /// drivers.start().await?;
616    /// assert_eq!(drivers.record("fs").unwrap().approved_by, "alice");
617    /// # Ok(())
618    /// # }
619    /// ```
620    pub fn mount_at_start(&self, manifest: DriverManifest, by: impl Into<String>) {
621        self.inner.approved.lock().unwrap_or_else(|e| e.into_inner()).push((manifest, by.into()));
622    }
623
624    /// Mounts `manifest`, approved by `by` (spec 3.2 §7.7, K-I13): records the approval as
625    /// `kernel.driver.mounted` and starts an eager driver. Mounting an id again replaces
626    /// the driver, its approval and its pins.
627    ///
628    /// # Errors
629    ///
630    /// Returns [`KernelError::Config`] for an invalid manifest, or the store's error. An
631    /// eager driver that fails to start is mounted and reported in the log and the events.
632    pub async fn mount(&self, manifest: DriverManifest, by: &str) -> Result<DriverRecord> {
633        manifest.validate()?;
634        self.inner.load().await?;
635        let mut manifest = manifest;
636        manifest.declaration_digests.clear();
637        let id = manifest.id.clone();
638        if let Some(live) = self.inner.live.lock().await.remove(&id) {
639            self.inner.stop_live(&id, &live).await;
640        }
641        let record = DriverRecord::new(manifest, by, Utc::now());
642        self.inner.store.put(record.clone()).await?;
643        self.inner.cache(&record);
644        self.inner.set_state(&id, DriverState::Stopped);
645        self.inner
646            .record(
647                audit::DRIVER_MOUNTED,
648                Some(by),
649                json!({
650                    "driverId": id,
651                    "commandDigest": record.command_digest,
652                    "commandLine": record.manifest.command_line(),
653                    "partitions": record.manifest.partitions,
654                    "effectClasses": record.manifest.tools,
655                    "sandbox": record.manifest.sandbox,
656                    "digests": record.manifest.declaration_digests,
657                    "by": by,
658                }),
659            )
660            .await;
661        self.inner.publish(&id, DriverState::Stopped, Some(format!("mounted by {by}")));
662        self.inner.activate(&record).await;
663        if record.manifest.lifecycle == DriverLifecycle::Eager
664            && let Err(error) = self.inner.ensure_started(&id).await
665        {
666            tracing::warn!(driver.id = %id, error = %error, "eager driver did not start");
667        }
668        Ok(record)
669    }
670
671    /// Unmounts driver `id`: stops it, deletes its record and its parked calls, and records
672    /// `kernel.driver.unmounted`. `false` when it was not mounted.
673    ///
674    /// # Errors
675    ///
676    /// Returns the store's error.
677    pub async fn unmount(&self, id: &str, by: &str) -> Result<bool> {
678        self.inner.load().await?;
679        if let Some(live) = self.inner.live.lock().await.remove(id) {
680            self.inner.stop_live(id, &live).await;
681        }
682        let existed = self.inner.store.delete(id).await?;
683        for park in self.inner.store.list_parks(Some(id)).await? {
684            self.inner.store.delete_park(&park.scope, &park.call_id).await?;
685        }
686        self.inner.view.write().unwrap_or_else(|e| e.into_inner()).remove(id);
687        self.inner.states.write().unwrap_or_else(|e| e.into_inner()).remove(id);
688        if existed {
689            self.inner
690                .record(audit::DRIVER_UNMOUNTED, Some(by), json!({ "driverId": id, "by": by }))
691                .await;
692            self.inner.publish(id, DriverState::Stopped, Some(format!("unmounted by {by}")));
693        }
694        Ok(existed)
695    }
696
697    /// Restarts driver `id`, minting its secrets again.
698    ///
699    /// # Errors
700    ///
701    /// Returns a not-found error when `id` is not mounted, and the start's error.
702    pub async fn restart(&self, id: &str) -> Result<()> {
703        self.inner.load().await?;
704        let live = self.inner.live_for(id).await?;
705        let started = *live.started.lock().await;
706        if !started {
707            return self.inner.ensure_started(id).await;
708        }
709        self.inner.prepare_plan(id, &live).await?;
710        live.manager.restart_server(id).await?;
711        Ok(())
712    }
713
714    /// Re-approves driver `id` as `by` (spec 3.2 §7.7, K-I14): pins the declarations its
715    /// tools publish now, clears the stale tools, moves `by`'s standing rules from the old
716    /// declarations to the new, and records `kernel.driver.reapproved`.
717    ///
718    /// # Errors
719    ///
720    /// Returns a not-found error when `id` is not mounted, the start's error when it cannot
721    /// run to list its tools, or the store's error.
722    pub async fn reapprove(&self, id: &str, by: &str) -> Result<DriverRecord> {
723        self.inner.load().await?;
724        self.inner.ensure_started(id).await?;
725        let observed = self.inner.declarations(id).await?;
726        let mut record = self.inner.store.get(id).await?.ok_or_else(|| not_mounted(id))?;
727        let previous =
728            std::mem::replace(&mut record.manifest.declaration_digests, observed.clone());
729        record.stale.clear();
730        record.approved_by = by.to_string();
731        record.approved_at = Utc::now();
732        record.updated_at = record.approved_at;
733        self.inner.store.put(record.clone()).await?;
734        self.inner.cache(&record);
735        let mut repinned = 0;
736        let pins = self.inner.rule_pins.read().unwrap_or_else(|e| e.into_inner()).clone();
737        if let Some(pins) = &pins {
738            let source = driver_source(id);
739            for (tool, to) in &observed {
740                if let Some(from) = previous.get(tool).filter(|from| *from != to) {
741                    match pins.repin(by, &source, tool, from, to).await {
742                        Ok(moved) => repinned += moved,
743                        Err(error) => {
744                            tracing::warn!(driver.id = %id, tool = %tool, error = %error, "could not move standing rules to the re-approved declaration")
745                        }
746                    }
747                }
748            }
749        }
750        self.inner
751            .record(
752                audit::DRIVER_REAPPROVED,
753                Some(by),
754                json!({
755                    "driverId": id,
756                    "commandDigest": record.command_digest,
757                    "partitions": record.manifest.partitions,
758                    "effectClasses": record.manifest.tools,
759                    "digests": observed,
760                    "previousDigests": previous,
761                    "rulesRepinned": repinned,
762                    "by": by,
763                }),
764            )
765            .await;
766        self.inner.set_state(id, DriverState::Running);
767        self.inner.publish(id, DriverState::Running, Some(format!("re-approved by {by}")));
768        Ok(record)
769    }
770
771    /// Every mounted driver with its state, ordered by id.
772    ///
773    /// # Errors
774    ///
775    /// Returns the store's error.
776    pub async fn drivers(&self) -> Result<Vec<DriverView>> {
777        self.inner.load().await?;
778        let states = self.inner.states.read().unwrap_or_else(|e| e.into_inner()).clone();
779        Ok(self
780            .inner
781            .store
782            .list()
783            .await?
784            .into_iter()
785            .map(|record| {
786                let state = match states.get(record.id()) {
787                    Some(_) if record.needs_reapproval() => DriverState::NeedsReapproval,
788                    Some(state) => *state,
789                    None if record.needs_reapproval() => DriverState::NeedsReapproval,
790                    None => DriverState::Stopped,
791                };
792                DriverView::new(record, state)
793            })
794            .collect())
795    }
796
797    /// The state of driver `id`, or `None` when it is not mounted.
798    pub fn state(&self, id: &str) -> Option<DriverState> {
799        let stale =
800            self.inner.view.read().unwrap_or_else(|e| e.into_inner()).get(id)?.needs_reapproval();
801        let state = self
802            .inner
803            .states
804            .read()
805            .unwrap_or_else(|e| e.into_inner())
806            .get(id)
807            .copied()
808            .unwrap_or(DriverState::Stopped);
809        Some(if stale { DriverState::NeedsReapproval } else { state })
810    }
811
812    /// The tools of the drivers mounted for `partition` (spec 3.2 §7.7, §7.8): a driver is
813    /// served when its manifest lists `partition` and `drivers` — the partition's own list
814    /// of driver ids — names it, so neither side alone widens what a partition reaches
815    /// (K-I15). A lazy driver starts when the toolset is first listed.
816    pub fn toolset_for(&self, partition: &PartitionId, drivers: &[String]) -> Arc<dyn Toolset> {
817        Arc::new(DriverToolset::new(self.clone(), partition.clone(), Some(drivers.to_vec())))
818    }
819
820    /// The tools of every mounted driver whose manifest lists `partition`, for a kernel
821    /// that keeps no partition records of its own, such as `adk-rust up` serving the
822    /// default partition. Drivers mounted later are served from the next listing.
823    pub fn toolset_for_manifests(&self, partition: &PartitionId) -> Arc<dyn Toolset> {
824        Arc::new(DriverToolset::new(self.clone(), partition.clone(), None))
825    }
826
827    /// The drivers of `partitions` offered to the coordinator whose partition `policy`
828    /// governs, as crossings (spec 3.2 §7.8, K-I15): each tool a target partition's own
829    /// toolset serves — its manifest lists the partition and the partition lists the
830    /// driver — named `<to>__<tool>` and registered with `policy`, so every call is the
831    /// coordinator's crossing under a non-waivable approval. A read of a tool the manifest
832    /// classes `read` approved once holds for the rest of the run; any other class is
833    /// approved one call at a time. The partitions are read from the table at every
834    /// listing: one that takes no crossing, or that the coordinator's partition blocks,
835    /// offers nothing.
836    ///
837    /// # Example
838    ///
839    /// ```rust
840    /// use std::sync::Arc;
841    /// use adk_kernel::drivers::DriverSupervisor;
842    /// use adk_kernel::stores::InMemoryDriverStore;
843    /// use adk_kernel::Partitions;
844    ///
845    /// let drivers = DriverSupervisor::builder(Arc::new(InMemoryDriverStore::new())).build();
846    /// let policy = Partitions::in_memory().policy("home").with_coordinator("harness");
847    /// let crossings = drivers.crossing_toolset(&policy, ["work".into()]);
848    /// assert_eq!(crossings.name(), "kernel_driver_crossings");
849    /// ```
850    pub fn crossing_toolset(
851        &self,
852        policy: &PartitionPolicy,
853        partitions: impl IntoIterator<Item = PartitionId>,
854    ) -> Arc<dyn Toolset> {
855        Arc::new(super::tool::DriverCrossings::new(
856            self.clone(),
857            policy.clone(),
858            partitions.into_iter().collect(),
859        ))
860    }
861
862    /// Carries the re-approving person's standing rules forward at re-approval, set after
863    /// the supervisor is built — for a harness built with the supervisor's tools.
864    pub fn set_rule_pins(&self, pins: Arc<dyn StandingRulePins>) {
865        *self.inner.rule_pins.write().unwrap_or_else(|e| e.into_inner()) = Some(pins);
866    }
867
868    /// The ids of the mounted drivers, ordered.
869    pub fn mounted(&self) -> Vec<String> {
870        self.inner.view.read().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()
871    }
872
873    /// The kernel's policy layer for driver tools (spec 3.2 §7.7, K-I9, K-I14); compose it
874    /// with the harness's, which it never loosens.
875    pub fn policy(&self) -> Arc<dyn ToolPolicy> {
876        Arc::new(DriverPolicy::new(self.clone()))
877    }
878
879    /// The effect class of `tool` when `source` is a mounted driver's
880    /// ([`driver_source`]); `None` for any other source.
881    pub fn class_of(&self, source: &str, tool: &str) -> Option<EffectClass> {
882        let id = driver_of(source)?;
883        let tool = self.wrapped_tool(id, tool).unwrap_or_else(|| tool.to_string());
884        let view = self.inner.view.read().unwrap_or_else(|e| e.into_inner());
885        view.get(id).map(|record| record.manifest.class_of(&tool))
886    }
887
888    /// Records that the crossing tool `crossing` wraps tool `tool` of driver `id`.
889    pub(crate) fn register_crossing(&self, id: &str, crossing: &str, tool: &str) {
890        self.inner
891            .crossings
892            .write()
893            .unwrap_or_else(|e| e.into_inner())
894            .insert((id.to_string(), crossing.to_string()), tool.to_string());
895    }
896
897    /// The tool of driver `id` the crossing tool `crossing` wraps, if it is one.
898    pub(crate) fn wrapped_tool(&self, id: &str, crossing: &str) -> Option<String> {
899        self.inner
900            .crossings
901            .read()
902            .unwrap_or_else(|e| e.into_inner())
903            .get(&(id.to_string(), crossing.to_string()))
904            .cloned()
905    }
906
907    /// The mounted record of driver `id`, as last read or written.
908    pub fn record(&self, id: &str) -> Option<DriverRecord> {
909        self.inner.view.read().unwrap_or_else(|e| e.into_inner()).get(id).cloned()
910    }
911
912    /// The running manager of driver `id`, starting it if needed.
913    pub(crate) async fn manager(&self, id: &str) -> Result<Arc<McpServerManager>> {
914        self.inner.ensure_started(id).await?;
915        Ok(self.inner.live_for(id).await?.manager.clone())
916    }
917
918    /// Records the declarations driver `id`'s tools publish now; see [`Inner::observe`].
919    pub(crate) async fn observe(&self, id: &str, observed: BTreeMap<String, String>) {
920        self.inner.observe(id, observed).await;
921    }
922
923    pub(crate) async fn load(&self) -> Result<()> {
924        self.inner.load().await
925    }
926}
927
928/// The digest a driver tool's declaration is pinned under.
929pub(crate) fn declaration_digest(id: &str, tool: &dyn Tool) -> String {
930    ToolOrigin::new(driver_source(id), &tool.declaration(), tool.annotations()).declaration_digest
931}
932
933impl Inner {
934    async fn load(&self) -> Result<()> {
935        self.loaded
936            .get_or_try_init(|| async {
937                let records = self.store.list().await?;
938                let mut view = self.view.write().unwrap_or_else(|e| e.into_inner());
939                for record in records {
940                    view.insert(record.id().to_string(), record);
941                }
942                Ok::<_, KernelError>(())
943            })
944            .await
945            .map(|_| ())
946    }
947
948    fn cache(&self, record: &DriverRecord) {
949        self.view
950            .write()
951            .unwrap_or_else(|e| e.into_inner())
952            .insert(record.id().to_string(), record.clone());
953    }
954
955    fn set_state(&self, id: &str, state: DriverState) {
956        self.states.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), state);
957    }
958
959    fn publish(&self, id: &str, state: DriverState, reason: Option<String>) {
960        let bus = self.hooks.read().unwrap_or_else(|e| e.into_inner()).bus.clone();
961        if let Some(bus) = bus {
962            bus.publish(KernelEvent::Driver { id: id.to_string(), state, reason });
963        }
964    }
965
966    /// Writes a `kernel.driver.*` record (spec 3.2 §9.3), actor `by` or the kernel.
967    async fn record(&self, action: &str, by: Option<&str>, fields: Value) {
968        let (trail, kernel_id) = {
969            let hooks = self.hooks.read().unwrap_or_else(|e| e.into_inner());
970            (hooks.audit.clone(), hooks.kernel_id.clone())
971        };
972        let Some(trail) = trail else { return };
973        let mut actor = match by {
974            Some(by) => AuditActor::subject(adk_core::principal::SubjectRef::human(by)),
975            None => AuditActor::default(),
976        };
977        actor.instance = kernel_id;
978        let mut draft = AuditRecordDraft::new(
979            AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.to_string()),
980            action,
981        )
982        .actor(actor);
983        if let Value::Object(fields) = fields {
984            for (key, value) in fields {
985                draft = draft.ext(key, value);
986            }
987        }
988        if let Err(error) = trail.record(draft).await {
989            tracing::warn!(audit.action = action, error = %error, "could not write a driver audit record");
990        }
991    }
992
993    fn app_name(&self) -> String {
994        self.app_name
995            .read()
996            .unwrap_or_else(|e| e.into_inner())
997            .clone()
998            .unwrap_or_else(|| "adk-rust".to_string())
999    }
1000
1001    fn run_dir(&self, id: &str) -> PathBuf {
1002        let home =
1003            self.home.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_else(|| {
1004                dirs::config_dir().unwrap_or_else(std::env::temp_dir).join("adk-rust")
1005            });
1006        home.join("drivers").join("run").join(id)
1007    }
1008
1009    /// The acting context driver `id` asks the credential broker as.
1010    fn acting(&self, id: &str) -> ActingContext {
1011        ActingContext::derived(&self.app_name(), &format!("driver.{id}"), "", SubjectKind::Service)
1012    }
1013
1014    /// The live manager of a mounted driver, created on first use.
1015    async fn live_for(self: &Arc<Self>, id: &str) -> Result<Arc<Live>> {
1016        if let Some(live) = self.live.lock().await.get(id) {
1017            return Ok(live.clone());
1018        }
1019        let record = self.view.read().unwrap_or_else(|e| e.into_inner()).get(id).cloned();
1020        let record = record.ok_or_else(|| not_mounted(id))?;
1021        Ok(self.activate(&record).await)
1022    }
1023
1024    /// Creates the manager of `record`'s driver and watches its status channel.
1025    async fn activate(self: &Arc<Self>, record: &DriverRecord) -> Arc<Live> {
1026        let id = record.id().to_string();
1027        let mut live = self.live.lock().await;
1028        if let Some(existing) = live.get(&id) {
1029            return existing.clone();
1030        }
1031        let plan: Arc<RwLock<Option<LaunchPlan>>> = Arc::new(RwLock::new(None));
1032        let launch_plan = plan.clone();
1033        let launch_id = id.clone();
1034        let mut manager =
1035            McpServerManager::new([(id.clone(), record.manifest.server.clone())].into())
1036                .with_name(driver_source(&id))
1037                .with_health_check_interval(self.health_interval)
1038                .with_stdio_launcher(move |config| {
1039                    let plan = launch_plan.read().unwrap_or_else(|e| e.into_inner()).clone();
1040                    match plan {
1041                        Some(plan) => plan.command(config),
1042                        None => Err(AdkError::tool(format!(
1043                            "driver `{launch_id}` was started without its launch plan; start it \
1044                             through the driver supervisor"
1045                        ))),
1046                    }
1047                })
1048                .with_server_elicitation_handler(
1049                    id.clone(),
1050                    Arc::new(DriverElicitation::new(
1051                        id.clone(),
1052                        self.legacy.clone(),
1053                        self.fallback_elicitation.clone(),
1054                    )),
1055                );
1056        if record.manifest.sampling
1057            && let Some(handler) =
1058                self.sampling.as_ref().and_then(|factory| factory(&record.manifest))
1059        {
1060            manager = manager.with_server_sampling_handler(id.clone(), handler);
1061        }
1062        let manager = Arc::new(manager);
1063        let transitions = manager.subscribe_status_transitions();
1064        let watcher = tokio::spawn(watch(Arc::downgrade(self), transitions));
1065        let entry = Arc::new(Live {
1066            manager,
1067            plan,
1068            watcher: std::sync::Mutex::new(Some(watcher)),
1069            started: tokio::sync::Mutex::new(false),
1070        });
1071        live.insert(id, entry.clone());
1072        entry
1073    }
1074
1075    /// Prepares the launch plan of driver `id`, minting its secrets, and records how it is
1076    /// isolated.
1077    async fn prepare_plan(&self, id: &str, live: &Live) -> Result<()> {
1078        let record = self.store.get(id).await?.ok_or_else(|| not_mounted(id))?;
1079        let plan = prepare(
1080            &record.manifest,
1081            &self.run_dir(id),
1082            self.broker.as_deref(),
1083            &self.acting(id),
1084            self.fail_if_sandbox_unavailable.load(Ordering::SeqCst),
1085            &self.enforcer,
1086        )
1087        .await?;
1088        if record.isolation.as_ref() != Some(&plan.isolation)
1089            || record.process_tree != plan.process_tree
1090        {
1091            let mut record = record;
1092            record.isolation = Some(plan.isolation.clone());
1093            record.process_tree = plan.process_tree;
1094            record.updated_at = Utc::now();
1095            self.store.put(record.clone()).await?;
1096            self.cache(&record);
1097        }
1098        *live.plan.write().unwrap_or_else(|e| e.into_inner()) = Some(plan);
1099        Ok(())
1100    }
1101
1102    /// Starts driver `id` unless it runs, and its health monitor on the first start.
1103    async fn ensure_started(self: &Arc<Self>, id: &str) -> Result<()> {
1104        self.load().await?;
1105        let live = self.live_for(id).await?;
1106        let mut started = live.started.lock().await;
1107        if live.manager.server_status(id).await? == ServerStatus::Running {
1108            return Ok(());
1109        }
1110        self.prepare_plan(id, &live).await?;
1111        live.manager.start_server(id).await?;
1112        if !*started {
1113            live.manager.start_monitoring();
1114            *started = true;
1115        }
1116        Ok(())
1117    }
1118
1119    async fn stop_live(&self, id: &str, live: &Live) {
1120        live.manager.stop_monitoring();
1121        if let Err(error) = live.manager.shutdown().await {
1122            tracing::warn!(driver.id = %id, error = %error, "driver did not shut down cleanly");
1123        }
1124        if let Some(watcher) = live.watcher.lock().unwrap_or_else(|e| e.into_inner()).take() {
1125            watcher.abort();
1126        }
1127        clear_run_dir(&self.run_dir(id));
1128    }
1129
1130    /// Each tool's declaration digest as driver `id` publishes it now.
1131    async fn declarations(&self, id: &str) -> Result<BTreeMap<String, String>> {
1132        let live = self.live.lock().await.get(id).cloned().ok_or_else(|| not_mounted(id))?;
1133        let ctx: Arc<dyn ReadonlyContext> =
1134            Arc::new(adk_tool::SimpleToolContext::new(format!("driver:{id}")));
1135        let tools = live.manager.tools(ctx).await?;
1136        Ok(tools
1137            .iter()
1138            .map(|tool| (tool.name().to_string(), declaration_digest(id, tool.as_ref())))
1139            .collect())
1140    }
1141
1142    /// Compares the declarations driver `id` publishes with its pins (spec 3.2 §7.7, K-I14).
1143    ///
1144    /// The first listing after approval pins them. Afterwards a tool whose digest differs,
1145    /// or that was not there at approval, is stale: the record keeps the digest seen, the
1146    /// driver goes `NeedsReapproval`, and `kernel.driver.stale` is written. A tool that
1147    /// publishes its pinned declaration again stops being stale.
1148    pub(crate) async fn observe(&self, id: &str, observed: BTreeMap<String, String>) {
1149        let record = match self.store.get(id).await {
1150            Ok(Some(record)) => record,
1151            Ok(None) => return,
1152            Err(error) => {
1153                tracing::warn!(driver.id = %id, error = %error, "could not read a driver to check its declarations");
1154                return;
1155            }
1156        };
1157        let mut record = record;
1158        if record.manifest.declaration_digests.is_empty() {
1159            if observed.is_empty() {
1160                return;
1161            }
1162            record.manifest.declaration_digests = observed;
1163            record.updated_at = Utc::now();
1164            if let Err(error) = self.store.put(record.clone()).await {
1165                tracing::warn!(driver.id = %id, error = %error, "could not pin a driver's declarations");
1166                return;
1167            }
1168            self.cache(&record);
1169            tracing::info!(driver.id = %id, tools = record.manifest.declaration_digests.len(), "driver declarations pinned");
1170            return;
1171        }
1172        let pins = &record.manifest.declaration_digests;
1173        let stale: BTreeMap<String, String> = observed
1174            .iter()
1175            .filter(|(tool, digest)| pins.get(*tool) != Some(*digest))
1176            .map(|(tool, digest)| (tool.clone(), digest.clone()))
1177            .collect();
1178        if stale == record.stale {
1179            return;
1180        }
1181        let newly: BTreeSet<&String> =
1182            stale.keys().filter(|tool| !record.stale.contains_key(*tool)).collect();
1183        record.stale = stale.clone();
1184        record.updated_at = Utc::now();
1185        if let Err(error) = self.store.put(record.clone()).await {
1186            tracing::warn!(driver.id = %id, error = %error, "could not record a driver's stale tools");
1187            return;
1188        }
1189        self.cache(&record);
1190        if stale.is_empty() {
1191            self.publish(
1192                id,
1193                DriverState::Running,
1194                Some("its tools publish the approved declarations again".into()),
1195            );
1196            return;
1197        }
1198        if !newly.is_empty() {
1199            let tools: Vec<&String> = stale.keys().collect();
1200            tracing::warn!(driver.id = %id, tools = ?tools, "driver tools changed since approval; re-approval needed");
1201            self.record(
1202                audit::DRIVER_STALE,
1203                None,
1204                json!({
1205                    "driverId": id,
1206                    "commandDigest": record.command_digest,
1207                    "partitions": record.manifest.partitions,
1208                    "effectClasses": record.manifest.tools,
1209                    "digests": record.manifest.declaration_digests,
1210                    "observed": stale,
1211                    "tools": tools,
1212                }),
1213            )
1214            .await;
1215            self.publish(
1216                id,
1217                DriverState::NeedsReapproval,
1218                Some(format!(
1219                    "tools changed since approval: {}",
1220                    tools.iter().map(|tool| tool.as_str()).collect::<Vec<_>>().join(", ")
1221                )),
1222            );
1223        }
1224    }
1225
1226    /// Turns one status transition into an event, a record and, on `Running`, a check of
1227    /// the declarations.
1228    async fn on_transition(self: &Arc<Self>, transition: ServerStatusTransition) {
1229        let ServerStatusTransition { id, from, to } = transition;
1230        let record = self.view.read().unwrap_or_else(|e| e.into_inner()).get(&id).cloned();
1231        let attempt = {
1232            let mut attempts = self.attempts.lock().unwrap_or_else(|e| e.into_inner());
1233            let count = attempts.entry(id.clone()).or_default();
1234            if to == ServerStatus::Restarting {
1235                *count += 1;
1236            }
1237            *count
1238        };
1239        let reason = match to {
1240            ServerStatus::Crashed => {
1241                Some("the server's process exited or its connection closed".to_string())
1242            }
1243            ServerStatus::Restarting => Some(format!("restart attempt {attempt}")),
1244            ServerStatus::FailedToStart => Some("the server did not start".to_string()),
1245            _ => None,
1246        };
1247        self.set_state(&id, to.into());
1248        let stale = record.as_ref().is_some_and(DriverRecord::needs_reapproval);
1249        let state = if to == ServerStatus::Running && stale {
1250            DriverState::NeedsReapproval
1251        } else {
1252            to.into()
1253        };
1254        self.publish(&id, state, reason);
1255        let fields = |record: &DriverRecord| {
1256            json!({
1257                "driverId": id,
1258                "commandDigest": record.command_digest,
1259                "partitions": record.manifest.partitions,
1260                "effectClasses": record.manifest.tools,
1261                "digests": record.manifest.declaration_digests,
1262                "isolation": record.isolation,
1263                "processTree": record.process_tree,
1264                "attempt": attempt,
1265                "from": format!("{from:?}"),
1266            })
1267        };
1268        if let Some(record) = &record {
1269            match (from, to) {
1270                (ServerStatus::Starting, ServerStatus::Running) if attempt == 0 => {
1271                    self.record(audit::DRIVER_STARTED, None, fields(record)).await;
1272                }
1273                (_, ServerStatus::Running) => {
1274                    self.record(audit::DRIVER_RESTARTED, None, fields(record)).await;
1275                }
1276                (_, ServerStatus::Crashed) => {
1277                    self.record(audit::DRIVER_CRASHED, None, fields(record)).await;
1278                }
1279                _ => {}
1280            }
1281        }
1282        if to == ServerStatus::Running {
1283            self.attempts.lock().unwrap_or_else(|e| e.into_inner()).insert(id.clone(), 0);
1284            match self.declarations(&id).await {
1285                Ok(observed) => self.observe(&id, observed).await,
1286                Err(error) => {
1287                    tracing::warn!(driver.id = %id, error = %error, "could not list a driver's tools to check its declarations")
1288                }
1289            }
1290        }
1291    }
1292}
1293
1294/// Follows one driver manager's status channel until the supervisor is gone.
1295async fn watch(
1296    inner: Weak<Inner>,
1297    mut transitions: tokio::sync::broadcast::Receiver<ServerStatusTransition>,
1298) {
1299    loop {
1300        match transitions.recv().await {
1301            Ok(transition) => match inner.upgrade() {
1302                Some(inner) => inner.on_transition(transition).await,
1303                None => return,
1304            },
1305            Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
1306                tracing::warn!(transitions.skipped = skipped, "driver status channel fell behind");
1307            }
1308            Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
1309        }
1310    }
1311}