Skip to main content

adk_kernel/managed/
tenant.rs

1//! One kernel per tenant over that tenant's `ManagedStores` (spec 3.2 §7.13, §10 M1).
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fmt;
5use std::sync::Arc;
6
7use adk_core::audit_log::{AuditActor, AuditTrail};
8use adk_core::schedule::MissedFirePolicy;
9use adk_core::{
10    ActionLedger, Agent, ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalRisk,
11    ApprovalScope, ApprovalState, ApproverSelector, GovernanceControl, NewRun, OnConflict,
12    RunConfig, ScheduleStore, SpendLedger, SubjectKind, SubjectRef, ToolConfirmationRequest,
13};
14use adk_managed::state_store::SessionRecord;
15use adk_managed::types::{ManagedAgentDef, RuntimeError};
16use adk_managed::{AgentResolver, DefaultManagedAgentRuntime, ManagedStores, ModelResolver};
17use adk_runner::Runner;
18use adk_session::SessionService;
19use async_trait::async_trait;
20use serde_json::json;
21use sha2::Digest as _;
22
23use super::def::{KernelDef, WakeOverlap, WakeSetDef};
24use crate::agenda::{AgendaHandle, AgendaStore, ProactivityPolicy};
25use crate::consolidation::Consolidator;
26use crate::control::ControlPlaneConfig;
27use crate::drivers::{DriverManifest, DriverProposal, DriverRecord, DriverSupervisor};
28use crate::error::{KernelError, Result};
29use crate::kernel::{Kernel, KernelConfig, KernelState};
30use crate::partition::{Partition, PartitionId, PartitionStore, Partitions};
31use crate::stores::{
32    InMemoryAgendaStore, InMemoryAgentStore, InMemoryCronWatermarkStore, InMemoryPartitionStore,
33    InMemoryProcessStore, KernelStores, ProcessStore,
34};
35use crate::wake::{CronWakeSource, Trigger, Wake};
36use crate::watermark::{CronWatermarkStore, SourceWatermark};
37#[cfg(feature = "charter")]
38use crate::{
39    charter::{SignalSink, SignalStore},
40    wake::WakeRouter,
41};
42
43/// One kernel over one tenant's [`ManagedStores`]: the managed form of the kernel (spec 3.2
44/// §7.13, §10 M1).
45///
46/// The kernel hosts a user's or a team's agents on their own infrastructure; the managed
47/// runtime hosts tenants. A `TenantKernel` joins the two: the tenant's
48/// [`DefaultManagedAgentRuntime`] ([`runtime`](Self::runtime)) runs its sessions, and the
49/// tenant's kernel runs the processes its definitions' wake sets start, over the same
50/// stores, session service and approvals.
51///
52/// | Kernel part | From the tenant |
53/// |---|---|
54/// | Run store | [`ManagedStores::runs`]: the kernel's queues (`interactive`, `background`, `maintenance`) beside the sessions' per-session queues |
55/// | Approvals | [`ManagedStores::approval_service`], whose run store wakes the parked process, and [`ManagedStores::decisions`] as each run's approval store |
56/// | Targets | one per hosted definition, named like it: the agent the tenant's resolver builds |
57/// | Triggers | the definitions' wake sets ([`KernelDef::wake_sets`]); a cron source per expression, its watermark in the tenant's [`CronWatermarkStore`], so ticks missed while no replica of the tenant ran fire once each as the wake sets' `missed` policies pick them (spec 3.2 §7.4) |
58/// | Proactivity | the hosted definitions' [`KernelDef::proactivity`], one policy per tenant; else the operator's with the consolidation tick off (§13 Q1); the tick runs where the builder registered a consolidator |
59/// | Agenda | the tenant's agenda store, and [`agenda_handle`](Self::agenda_handle) rebound to each kernel built |
60/// | Partitions | the tenant's partition table ([`partitions`](Self::partitions)) holding the definitions' [`KernelDef::partitions`], each with the tenant as its tenant; with a [`PartitionAgentResolver`], one agent per partition — one harness per partition — as `<definition>@<partition>`, bound to its partition and acting with its class and tenant (spec 3.2 §7.8) |
61/// | Drivers | the tenant's own [`DriverSupervisor`] ([`TenantKernelBuilder::drivers`]), its drivers under a home of the tenant's own: each driver a definition's partition mounts is proposed in the tenant's approval inbox, mounted when a person approves it ([`apply_driver_decisions`](Self::apply_driver_decisions)), its tools' declarations pinned at the first listing, and served to that partition's harness only (spec 3.2 §7.7, §7.8, K-I13) |
62/// | Signals | with the `charter` feature, the tenant's signal store (`TenantKernelBuilder::signal_store`): `TenantKernel::signal_sink` files a signal in a partition's agenda and wakes the wake sets that hear its kind there (spec 3.5 §7.10); a definition with a signal wake is refused on a tenant without one |
63/// | App name | the tenant: the `ManagedOwner::app_name` its sessions are created under |
64/// | Kill switch | its own `GovernanceControl`, unless the builder is given one |
65/// | Control plane | none of its own; mount `control::router(kernel)` on the host's server to serve one |
66///
67/// A definition is hosted when the runtime resolves it through the [`KernelResolver`]
68/// ([`resolver`](Self::resolver)): on `create`, and when a session is rebuilt from the state
69/// store. A definition hosted after [`start`](Self::start), or hosted again changed,
70/// restarts the kernel over the same stores: its running processes park at their next
71/// model-call boundary and the new kernel resumes them. Every runtime instance that hosts
72/// the tenant's sessions needs a `TenantKernel` over the same stores.
73///
74/// Each tenant's stores are its own: a run store two tenants share would let one tenant's
75/// workers claim the other's runs. [`ManagedKernels`] refuses a tenant whose stores
76/// another tenant holds.
77///
78/// # Example
79///
80/// ```rust,no_run
81/// use std::sync::Arc;
82/// use adk_kernel::managed::{KernelDef, TenantKernel, WakeSetDef};
83/// use adk_managed::resolver::DefaultModelResolver;
84/// use adk_managed::types::{ManagedAgentDef, ModelRef};
85/// use adk_managed::{AgentResolver, ManagedAgentRuntime, ManagedStores};
86/// use adk_session::InMemorySessionService;
87///
88/// # async fn example(harnesses: Arc<dyn AgentResolver>) -> Result<(), Box<dyn std::error::Error>> {
89/// let tenant = TenantKernel::builder(
90///     "tenant-a",
91///     ManagedStores::in_memory(),
92///     Arc::new(InMemorySessionService::new()),
93/// )
94/// .resolver(harnesses)
95/// .build()?;
96/// let runtime = tenant.runtime(Arc::new(DefaultModelResolver::new()));
97/// let def = KernelDef::new()
98///     .with_wake_set(WakeSetDef::new("morning", [WakeSetDef::cron("0 0 9 * * *")], "Summarize the night."))
99///     .apply_to(ManagedAgentDef::new("digest", ModelRef::Shorthand("gemini-3.5-flash-lite".into())));
100/// runtime.create(def).await?;
101/// tenant.start().await?;
102/// # Ok(())
103/// # }
104/// ```
105#[derive(Clone)]
106pub struct TenantKernel {
107    inner: Arc<TenantInner>,
108}
109
110struct TenantInner {
111    tenant: String,
112    stores: ManagedStores,
113    sessions: Arc<dyn SessionService>,
114    config: KernelConfig,
115    processes: Arc<dyn ProcessStore>,
116    schedules: Option<Arc<dyn ScheduleStore>>,
117    resolver: Option<Arc<dyn AgentResolver>>,
118    action_ledger: Option<Arc<dyn ActionLedger>>,
119    spend: Option<Arc<dyn SpendLedger>>,
120    audit: Option<AuditTrail>,
121    agenda: Arc<dyn AgendaStore>,
122    agenda_handle: AgendaHandle,
123    /// The agent table's store; a tenant kernel adds no agents, so it stays empty unless
124    /// the host's bundle holds some.
125    agents: Arc<dyn crate::agents::AgentStore>,
126    consolidators: BTreeMap<PartitionId, Arc<dyn Consolidator>>,
127    partitions: Partitions,
128    partition_resolver: Option<Arc<dyn PartitionAgentResolver>>,
129    watermarks: Arc<dyn CronWatermarkStore>,
130    drivers: Option<DriverSupervisor>,
131    driver_approvers: ApprovalPolicy,
132    #[cfg(feature = "charter")]
133    signals: Option<Arc<dyn SignalStore>>,
134    /// Applies inbox decisions on driver mounts while the tenant's kernel runs.
135    driver_decisions: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
136    hosting: tokio::sync::Mutex<Hosting>,
137}
138
139/// The hosted definitions, and the kernel while the tenant runs.
140#[derive(Default)]
141struct Hosting {
142    hosted: BTreeMap<String, Hosted>,
143    kernel: Option<Kernel>,
144}
145
146/// One hosted definition.
147#[derive(Clone)]
148struct Hosted {
149    kernel: KernelDef,
150    /// The definition as a session record keeps it, to tell a changed definition from the
151    /// same one rebuilt.
152    digest: String,
153    agent: Arc<dyn Agent>,
154    /// Each partition's agent, when the definition declares partitions and the tenant has a
155    /// partition resolver (spec 3.2 §7.8).
156    partitions: BTreeMap<PartitionId, (Partition, Arc<dyn Agent>)>,
157}
158
159impl fmt::Debug for TenantKernel {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.debug_struct("TenantKernel")
162            .field("tenant", &self.inner.tenant)
163            .field("stores", &self.inner.stores)
164            .finish_non_exhaustive()
165    }
166}
167
168impl TenantKernel {
169    /// A builder for `tenant`'s kernel over its `stores` and the session service its
170    /// sessions live in.
171    pub fn builder(
172        tenant: impl Into<String>,
173        stores: ManagedStores,
174        sessions: Arc<dyn SessionService>,
175    ) -> TenantKernelBuilder {
176        TenantKernelBuilder {
177            tenant: tenant.into(),
178            stores,
179            sessions,
180            config: None,
181            processes: None,
182            schedules: None,
183            resolver: None,
184            action_ledger: None,
185            spend: None,
186            audit: None,
187            governance: None,
188            agenda: None,
189            agenda_handle: None,
190            consolidators: BTreeMap::new(),
191            partition_store: None,
192            partition_resolver: None,
193            watermark_store: None,
194            drivers: None,
195            driver_approvers: None,
196            #[cfg(feature = "charter")]
197            signals: None,
198            bundle: None,
199        }
200    }
201
202    /// The tenant: the app name its runs and sessions belong to.
203    pub fn tenant(&self) -> &str {
204        &self.inner.tenant
205    }
206
207    /// The tenant's stores.
208    pub fn stores(&self) -> &ManagedStores {
209        &self.inner.stores
210    }
211
212    /// The process side table.
213    pub fn process_store(&self) -> &Arc<dyn ProcessStore> {
214        &self.inner.processes
215    }
216
217    /// The tenant's kill switch.
218    pub fn governance(&self) -> &GovernanceControl {
219        &self.inner.config.governance
220    }
221
222    /// The tenant's partition table: its definitions' partitions, each with the tenant as
223    /// its tenant, and the crossing ledger (spec 3.2 §7.8).
224    pub fn partitions(&self) -> &Partitions {
225        &self.inner.partitions
226    }
227
228    /// The tenant's cron watermarks: where each cron expression of its wake sets left off
229    /// (spec 3.2 §7.4).
230    pub fn watermark_store(&self) -> &Arc<dyn CronWatermarkStore> {
231        &self.inner.watermarks
232    }
233
234    /// The tenant's driver supervisor, when the builder was given one (spec 3.2 §7.7).
235    pub fn drivers(&self) -> Option<&DriverSupervisor> {
236        self.inner.drivers.as_ref()
237    }
238
239    /// The tenant's signal store, when the builder was given one (spec 3.5 §7.10).
240    #[cfg(feature = "charter")]
241    pub fn signal_store(&self) -> Option<&Arc<dyn SignalStore>> {
242        self.inner.signals.as_ref()
243    }
244
245    /// A sink that files signals in `partition`'s agenda items on the tenant's agenda and
246    /// signal stores, and wakes the hosted wake sets that hear their kind there (spec 3.2
247    /// §7.13, spec 3.5 §7.10; feature `charter`).
248    ///
249    /// Each signal filed or counted becomes a keyed `kernel.wake` run on the tenant's run
250    /// store (`signal:<partition>:<item>:<count>`), which whichever kernel the tenant runs
251    /// routes, so a sink taken before a definition is hosted — and the kernel restarts —
252    /// keeps waking the new kernel, and a repeated key starts nothing (K-I3). A run a signal
253    /// starts carries no principal, so it stays unauthenticated (spec 3.1 I6), and its input
254    /// is the wake set's `input`, never the signal's text (spec 3.5 A-I3). The sink audits
255    /// `kernel.signal` on the tenant's audit trail and reads the kernel configuration's
256    /// clock; it publishes on no event bus, since each kernel the tenant builds has its own.
257    ///
258    /// # Example
259    ///
260    /// ```rust
261    /// use std::sync::Arc;
262    /// use adk_core::RunFilter;
263    /// use adk_kernel::charter::{InMemorySignalStore, SignalOutcome};
264    /// use adk_kernel::managed::TenantKernel;
265    /// use adk_managed::ManagedStores;
266    /// use adk_session::InMemorySessionService;
267    /// use awp_types::{Bounded, Signal, SignalKind};
268    ///
269    /// # #[tokio::main(flavor = "current_thread")]
270    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
271    /// let stores = ManagedStores::in_memory();
272    /// let tenant = TenantKernel::builder("tenant-a", stores.clone(), Arc::new(InMemorySessionService::new()))
273    ///     .signal_store(Arc::new(InMemorySignalStore::new()))
274    ///     .build()?;
275    /// let sink = tenant.signal_sink("default").await?;
276    /// let gap = Signal {
277    ///     id: uuid::Uuid::new_v4(),
278    ///     kind: SignalKind::ContentGap { topic: Bounded::new("parking", 80).unwrap(), question_count: 1, samples: vec![] },
279    ///     emitted_by: "concierge".into(),
280    ///     emitted_at: chrono::Utc::now(),
281    /// };
282    /// assert!(matches!(sink.emit(gap).await?, SignalOutcome::Filed { count: 1, .. }));
283    /// // The wake waits on the tenant's run store for whichever kernel the tenant runs.
284    /// let wakes = stores.runs.list(RunFilter::default()).await?;
285    /// assert!(wakes[0].idempotency_key.as_deref().is_some_and(|key| key.starts_with("signal:default:")));
286    /// assert!(tenant.signal_sink("back-office").await.is_err(), "not in the tenant's partition table");
287    /// # Ok(())
288    /// # }
289    /// ```
290    ///
291    /// # Errors
292    ///
293    /// Returns [`KernelError::Config`] when the tenant has no signal store, or `partition` is
294    /// neither the default partition nor one in the tenant's partition table; and the
295    /// partition table's error.
296    #[cfg(feature = "charter")]
297    pub async fn signal_sink(&self, partition: impl Into<PartitionId>) -> Result<SignalSink> {
298        let inner = &self.inner;
299        let partition = partition.into();
300        let Some(store) = &inner.signals else {
301            return Err(KernelError::Config {
302                reason: format!(
303                    "tenant `{}` has no signal store to file signals in; build it with \
304                     TenantKernelBuilder::signal_store",
305                    inner.tenant
306                ),
307            });
308        };
309        if partition != PartitionId::default() && inner.partitions.get(&partition).await?.is_none()
310        {
311            return Err(KernelError::Config {
312                reason: format!(
313                    "partition `{partition}` is not in tenant `{}`'s partition table; file \
314                     signals in the default partition or one a hosted definition declares",
315                    inner.tenant
316                ),
317            });
318        }
319        let router = WakeRouter::new(Arc::clone(&inner.stores.runs), Arc::clone(&inner.processes));
320        let mut sink = SignalSink::new(Arc::clone(store), Arc::clone(&inner.agenda), partition)
321            .with_wakes(router, inner.tenant.clone())
322            .with_clock(Arc::clone(&inner.config.clock));
323        if let Some(trail) = &inner.audit {
324            sink = sink.with_audit(trail.clone());
325        }
326        Ok(sink)
327    }
328
329    /// Mounts every driver a hosted definition's partition mounts whose proposal a person
330    /// approved in the tenant's approval inbox, and returns the ids mounted (spec 3.2 §7.7,
331    /// K-I13). While the tenant's kernel runs it does this every scheduler tick; a host may
332    /// call it to apply a decision at once.
333    ///
334    /// The person whose approval completed the request is recorded as the mount's approver
335    /// (`kernel.driver.mounted`). A decision by anyone but a person is ignored, and a
336    /// rejected proposal mounts nothing. A driver already mounted as proposed is left as it
337    /// is, its pins included.
338    ///
339    /// # Errors
340    ///
341    /// Returns the approval service's or the driver store's error.
342    pub async fn apply_driver_decisions(&self) -> Result<Vec<String>> {
343        let (Some(drivers), Some(service)) =
344            (&self.inner.drivers, &self.inner.stores.approval_service)
345        else {
346            return Ok(Vec::new());
347        };
348        let manifests = {
349            let hosting = self.inner.hosting.lock().await;
350            served_drivers(&hosting.hosted)
351        };
352        let mut mounted = Vec::new();
353        for (definition, manifest) in manifests {
354            if mounted_as_proposed(drivers, &manifest) {
355                continue;
356            }
357            let Some(request) = service.get(&driver_request_id(&manifest)).await? else {
358                continue;
359            };
360            if request.state != ApprovalState::Approved {
361                continue;
362            }
363            let Some(decision) = request.decisions.last() else { continue };
364            if decision.approver.kind != SubjectKind::Human {
365                tracing::warn!(
366                    tenant = %self.inner.tenant,
367                    driver.id = %manifest.id,
368                    approver = %decision.approver.id,
369                    "a driver mount approved by someone other than a person was ignored"
370                );
371                continue;
372            }
373            let id = manifest.id.clone();
374            drivers.mount(manifest, &decision.approver.id).await?;
375            tracing::info!(
376                tenant = %self.inner.tenant,
377                definition = %definition,
378                driver.id = %id,
379                by = %decision.approver.id,
380                "driver mounted on a person's approval"
381            );
382            mounted.push(id);
383        }
384        Ok(mounted)
385    }
386
387    /// The handle of the tenant kernel's agenda, rebound to every kernel the tenant builds:
388    /// give it to the harnesses the tenant's resolver builds, so their `propose_followup`
389    /// reaches the tenant's agenda (spec 3.2 §7.5).
390    pub fn agenda_handle(&self) -> &AgendaHandle {
391        &self.inner.agenda_handle
392    }
393
394    /// The tenant kernel's proactivity policy: the one its hosted definitions set, or the
395    /// operator's with the consolidation tick off (spec 3.2 §7.5, §13 Q1).
396    pub async fn proactivity(&self) -> ProactivityPolicy {
397        let hosting = self.inner.hosting.lock().await;
398        self.policy(&hosting.hosted)
399    }
400
401    /// The resolver to install with `DefaultManagedAgentRuntime::with_agent_resolver`: it
402    /// builds each definition through the tenant's resolver and hosts a definition carrying
403    /// a kernel block on this kernel.
404    pub fn resolver(&self) -> Arc<dyn AgentResolver> {
405        Arc::new(KernelResolver { tenant: self.clone() })
406    }
407
408    /// The tenant's managed runtime: its session service and stores, with
409    /// [`resolver`](Self::resolver) installed. Further `with_*` settings chain on the value.
410    pub fn runtime(&self, models: Arc<dyn ModelResolver>) -> DefaultManagedAgentRuntime {
411        DefaultManagedAgentRuntime::new(models, Arc::clone(&self.inner.sessions))
412            .with_stores(self.inner.stores.clone())
413            .with_agent_resolver(self.resolver())
414    }
415
416    /// The kernel while the tenant runs. A definition hosted later restarts the kernel, so
417    /// the value returned here stops then; read it again.
418    pub async fn kernel(&self) -> Option<Kernel> {
419        self.inner.hosting.lock().await.kernel.clone()
420    }
421
422    /// The hosted definitions' kernel blocks, by definition name.
423    pub async fn definitions(&self) -> BTreeMap<String, KernelDef> {
424        let hosting = self.inner.hosting.lock().await;
425        hosting.hosted.iter().map(|(name, hosted)| (name.clone(), hosted.kernel.clone())).collect()
426    }
427
428    /// Hosts `def` with `agent` as its target when `def` carries a kernel block, and
429    /// returns whether it does (spec 3.2 §7.13). The [`KernelResolver`] calls this for
430    /// every definition it resolves.
431    ///
432    /// The same definition hosted again changes nothing; a changed one replaces it, and a
433    /// running kernel restarts with it.
434    ///
435    /// # Errors
436    ///
437    /// Returns [`KernelError::Config`] for an invalid kernel block, and the error of the
438    /// restart when the kernel runs; a refused restart leaves the running kernel as it was.
439    pub async fn host(&self, def: &ManagedAgentDef, agent: Arc<dyn Agent>) -> Result<bool> {
440        self.host_with(def, agent, BTreeMap::new()).await
441    }
442
443    /// Hosts `def` with one agent per partition its kernel block declares (spec 3.2 §7.8),
444    /// `agents` keyed by partition id: each runs as `<definition>@<partition>`, bound to its
445    /// partition and acting with its class and the tenant, and the coordinator's agent —
446    /// else the first partition's by id — also as the definition's own target. A wake set
447    /// in a partition starts that partition's agent. Every partition is written to the
448    /// tenant's partition table with the tenant as its tenant. [`KernelResolver`] calls this
449    /// with the agents the tenant's [`PartitionAgentResolver`] builds.
450    ///
451    /// # Errors
452    ///
453    /// Returns [`KernelError::Config`] for an invalid kernel block, a block without
454    /// partitions, `agents` not naming exactly the declared partitions, or a partition
455    /// another hosted definition declares; and the table's or the restart's error.
456    pub async fn host_partitions(
457        &self,
458        def: &ManagedAgentDef,
459        agents: BTreeMap<PartitionId, Arc<dyn Agent>>,
460    ) -> Result<bool> {
461        let Some(kernel) = KernelDef::from_agent_def(def)? else {
462            return Ok(false);
463        };
464        let declared: BTreeSet<PartitionId> =
465            kernel.partitions.iter().map(|partition| partition.id.clone()).collect();
466        let given: BTreeSet<PartitionId> = agents.keys().cloned().collect();
467        if declared.is_empty() || declared != given {
468            return Err(KernelError::Config {
469                reason: format!(
470                    "definition '{}' declares partitions {declared:?}, and agents were given for \
471                     {given:?}: host one agent per declared partition",
472                    def.name
473                ),
474            });
475        }
476        let primary = kernel.primary_partition().expect("a block with partitions has a primary");
477        let agent = Arc::clone(&agents[&primary]);
478        self.host_with(def, agent, agents).await
479    }
480
481    async fn host_with(
482        &self,
483        def: &ManagedAgentDef,
484        agent: Arc<dyn Agent>,
485        agents: BTreeMap<PartitionId, Arc<dyn Agent>>,
486    ) -> Result<bool> {
487        let Some(kernel) = KernelDef::from_agent_def(def)? else {
488            return Ok(false);
489        };
490        if def.name.trim().is_empty() {
491            return Err(KernelError::Config {
492                reason: "a definition with a kernel block needs a name: it names the kernel's \
493                         target"
494                    .into(),
495            });
496        }
497        // A signal wake on a tenant that files no signals would never fire.
498        if let Some(set) = kernel
499            .wake_sets
500            .iter()
501            .find(|set| set.any_of.iter().any(|wake| matches!(wake, Wake::Signal { .. })))
502        {
503            #[cfg(feature = "charter")]
504            let missing = self
505                .inner
506                .signals
507                .is_none()
508                .then_some("build the tenant with TenantKernelBuilder::signal_store");
509            #[cfg(not(feature = "charter"))]
510            let missing = Some(
511                "build adk-kernel with the `charter` feature and the tenant with \
512                 TenantKernelBuilder::signal_store",
513            );
514            if let Some(fix) = missing {
515                return Err(KernelError::Config {
516                    reason: format!(
517                        "definition '{}': wake set `{}` wakes on a signal, and tenant `{}` has \
518                         no signal store to file signals in; {fix}",
519                        def.name, set.name, self.inner.tenant
520                    ),
521                });
522            }
523        }
524        let digest = serde_json::to_string(&SessionRecord::new("", "", def.clone()).agent)?;
525        let mut hosting = self.inner.hosting.lock().await;
526        if hosting.hosted.get(&def.name).is_some_and(|hosted| hosted.digest == digest) {
527            return Ok(true);
528        }
529        if let Some(policy) = &kernel.proactivity {
530            let other = hosting.hosted.iter().find(|(name, hosted)| {
531                **name != def.name
532                    && hosted.kernel.proactivity.as_ref().is_some_and(|theirs| theirs != policy)
533            });
534            if let Some((other, _)) = other {
535                return Err(KernelError::Config {
536                    reason: format!(
537                        "definition '{}' sets a proactivity policy other than definition \
538                         '{other}''s, and tenant `{}` has one kernel with one policy: set the \
539                         same policy in both, or leave it out of one",
540                        def.name, self.inner.tenant
541                    ),
542                });
543            }
544        }
545        for partition in &kernel.partitions {
546            let other = hosting.hosted.iter().find(|(name, hosted)| {
547                **name != def.name
548                    && hosted.kernel.partitions.iter().any(|theirs| theirs.id == partition.id)
549            });
550            if let Some((other, _)) = other {
551                return Err(KernelError::Config {
552                    reason: format!(
553                        "definition '{}' declares partition `{}`, which definition '{other}' \
554                         declares too, and tenant `{}` has one partition table: declare it in \
555                         one definition",
556                        def.name, partition.id, self.inner.tenant
557                    ),
558                });
559            }
560        }
561        if agents.is_empty() && !kernel.partitions.is_empty() {
562            tracing::warn!(
563                tenant = %self.inner.tenant,
564                definition = %def.name,
565                partitions = kernel.partitions.len(),
566                "the definition's partitions are recorded, and without a partition resolver its \
567                 agent runs in the default partition (TenantKernelBuilder::partition_resolver)"
568            );
569        }
570        self.propose_drivers(&def.name, &kernel).await?;
571        // The tenant's partition table holds the definition's partitions, the tenant theirs.
572        let mut partitions = BTreeMap::new();
573        for declared in &kernel.partitions {
574            let record = declared.to_partition(&self.inner.tenant)?;
575            if self.inner.partitions.get(&record.id).await?.as_ref() != Some(&record) {
576                self.inner.partitions.put(record.clone(), AuditActor::default()).await?;
577            }
578            if let Some(agent) = agents.get(&record.id) {
579                partitions.insert(record.id.clone(), (record, Arc::clone(agent)));
580            }
581        }
582        let mut hosted = hosting.hosted.clone();
583        hosted.insert(def.name.clone(), Hosted { kernel, digest, agent, partitions });
584        if let Some(running) = hosting.kernel.take() {
585            match self.restart(running, &hosted).await {
586                Ok(kernel) => hosting.kernel = Some(kernel),
587                Err((kernel, error)) => {
588                    hosting.kernel = kernel;
589                    return Err(error);
590                }
591            }
592        }
593        let dropped: Vec<String> = cron_expressions(&hosting.hosted)
594            .difference(&cron_expressions(&hosted))
595            .cloned()
596            .collect();
597        hosting.hosted = hosted;
598        // An expression no hosted wake set uses any more was idle from here on, not missed:
599        // its cursor goes with its source, so a wake set that uses it later starts at its
600        // first watch (spec 3.2 §7.4).
601        for expr in dropped {
602            let source = cron_source_name(&expr);
603            match self.inner.watermarks.delete(&source).await {
604                Ok(_) => {
605                    tracing::info!(tenant = %self.inner.tenant, cron = %expr, "cron watermark dropped with the last wake set on it")
606                }
607                Err(error) => {
608                    tracing::warn!(tenant = %self.inner.tenant, cron = %expr, error = %error, "could not drop the cron watermark of an expression no wake set uses")
609                }
610            }
611        }
612        tracing::info!(tenant = %self.inner.tenant, definition = %def.name, "definition hosted");
613        Ok(true)
614    }
615
616    /// Starts the tenant's kernel with the definitions hosted so far.
617    ///
618    /// # Errors
619    ///
620    /// Returns [`KernelError::Lifecycle`] when it already runs, or the kernel's build or
621    /// start error.
622    pub async fn start(&self) -> Result<()> {
623        let mut hosting = self.inner.hosting.lock().await;
624        if hosting.kernel.is_some() {
625            return Err(KernelError::Lifecycle { state: KernelState::Running, action: "start" });
626        }
627        let kernel = self.build(&hosting.hosted)?;
628        kernel.start().await?;
629        hosting.kernel = Some(kernel);
630        drop(hosting);
631        self.watch_driver_decisions();
632        Ok(())
633    }
634
635    /// Stops the tenant's kernel: running processes park at their next checkpoint, and the
636    /// next [`start`](Self::start) resumes them.
637    ///
638    /// # Errors
639    ///
640    /// Returns the kernel's stop error; it is stopped regardless.
641    pub async fn stop(&self) -> Result<()> {
642        if let Some(task) =
643            self.inner.driver_decisions.lock().unwrap_or_else(|e| e.into_inner()).take()
644        {
645            task.abort();
646        }
647        let kernel = self.inner.hosting.lock().await.kernel.take();
648        match kernel {
649            Some(kernel) => kernel.stop().await,
650            None => Ok(()),
651        }
652    }
653
654    /// Proposes each driver of `kernel` that a declared partition mounts, unless it is
655    /// mounted as proposed: an approval request in the tenant's inbox showing what a person
656    /// approves — the command line, the partitions, the effect classes, the sandbox and the
657    /// secrets it names (spec 3.2 §7.7, K-I13). Nothing runs before a person approves it.
658    async fn propose_drivers(&self, definition: &str, kernel: &KernelDef) -> Result<()> {
659        if kernel.drivers.is_empty() {
660            return Ok(());
661        }
662        let served = served_by_partitions(kernel);
663        for manifest in &kernel.drivers {
664            if !served.contains(&manifest.id) {
665                tracing::warn!(
666                    tenant = %self.inner.tenant,
667                    definition = %definition,
668                    driver.id = %manifest.id,
669                    "the driver is recorded and not proposed: no partition of the definition \
670                     mounts it (list it in a partition's `drivers`, and the partition in its \
671                     manifest's `partitions`)"
672                );
673            }
674        }
675        let Some(drivers) = &self.inner.drivers else {
676            tracing::warn!(
677                tenant = %self.inner.tenant,
678                definition = %definition,
679                drivers = served.len(),
680                "the definition's driver manifests are recorded; the tenant has no driver \
681                 supervisor to mount them on (TenantKernelBuilder::drivers)"
682            );
683            return Ok(());
684        };
685        let Some(service) = &self.inner.stores.approval_service else {
686            tracing::warn!(
687                tenant = %self.inner.tenant,
688                definition = %definition,
689                "the definition's drivers are recorded; the tenant has no approval service to \
690                 ask a person to mount them"
691            );
692            return Ok(());
693        };
694        for manifest in kernel.drivers.iter().filter(|manifest| served.contains(&manifest.id)) {
695            if mounted_as_proposed(drivers, manifest) {
696                continue;
697            }
698            let proposal = DriverProposal::of(manifest);
699            let args = serde_json::to_value(&proposal)?;
700            let scope = ApprovalScope::new(
701                self.inner.tenant.clone(),
702                super::DEFAULT_WAKE_USER,
703                format!("kernel-driver-{}", manifest.id),
704            );
705            let call = ToolConfirmationRequest::new(DRIVER_MOUNT_TOOL_NAME, args.clone());
706            let request = ApprovalRequest::new(
707                driver_request_id(manifest),
708                scope,
709                &call,
710                self.inner.driver_approvers.clone(),
711            )
712            .with_redacted_args(args)
713            .with_requester(SubjectRef::service(format!("definition:{definition}")))
714            .with_summary(format!(
715                "Mount driver `{}` for definition `{definition}`: {} (partitions {}; sandbox {})",
716                manifest.id,
717                proposal.command_line,
718                proposal
719                    .partitions
720                    .iter()
721                    .map(|partition| partition.as_str())
722                    .collect::<Vec<_>>()
723                    .join(", "),
724                proposal.sandbox.as_str(),
725            ))
726            .with_risk(ApprovalRisk::High)
727            .with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject]);
728            service.submit(request).await?;
729            tracing::info!(
730                tenant = %self.inner.tenant,
731                definition = %definition,
732                driver.id = %manifest.id,
733                "driver mount proposed in the tenant's approval inbox"
734            );
735        }
736        Ok(())
737    }
738
739    /// Applies driver decisions every scheduler tick while the tenant's kernel runs.
740    fn watch_driver_decisions(&self) {
741        if self.inner.drivers.is_none() || self.inner.stores.approval_service.is_none() {
742            return;
743        }
744        let tenant = self.clone();
745        let tick = self.inner.config.scheduler_tick.max(std::time::Duration::from_millis(10));
746        let task = tokio::spawn(async move {
747            let mut interval = tokio::time::interval(tick);
748            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
749            loop {
750                interval.tick().await;
751                if let Err(error) = tenant.apply_driver_decisions().await {
752                    tracing::debug!(tenant = %tenant.inner.tenant, error = %error, "could not apply driver decisions this tick");
753                }
754            }
755        });
756        if let Some(previous) =
757            self.inner.driver_decisions.lock().unwrap_or_else(|e| e.into_inner()).replace(task)
758        {
759            previous.abort();
760        }
761    }
762
763    /// Replaces `running` with a kernel over `hosted`. Built before `running` stops, so a
764    /// refused build changes nothing; a new kernel that cannot start gives way to the old
765    /// one again.
766    async fn restart(
767        &self,
768        running: Kernel,
769        hosted: &BTreeMap<String, Hosted>,
770    ) -> std::result::Result<Kernel, (Option<Kernel>, KernelError)> {
771        let next = match self.build(hosted) {
772            Ok(next) => next,
773            Err(error) => return Err((Some(running), error)),
774        };
775        if let Err(error) = running.stop().await {
776            tracing::warn!(tenant = %self.inner.tenant, error = %error, "the replaced kernel stopped with an error");
777        }
778        match next.start().await {
779            Ok(()) => Ok(next),
780            Err(error) => {
781                let restored = running.start().await.is_ok().then_some(running);
782                Err((restored, error))
783            }
784        }
785    }
786
787    /// A kernel over the tenant's stores hosting `hosted`.
788    fn build(&self, hosted: &BTreeMap<String, Hosted>) -> Result<Kernel> {
789        let inner = &self.inner;
790        let config = inner.config.clone().with_proactivity(self.policy(hosted));
791        let mut builder = Kernel::builder()
792            .config(config)
793            .run_store(Arc::clone(&inner.stores.runs))
794            .process_store(Arc::clone(&inner.processes))
795            .session_service(Arc::clone(&inner.sessions))
796            .agenda_store(Arc::clone(&inner.agenda))
797            .agenda_handle(inner.agenda_handle.clone())
798            .agent_store(Arc::clone(&inner.agents))
799            .governance(inner.config.governance.clone())
800            .partitions(inner.partitions.clone())
801            .watermark_store(Arc::clone(&inner.watermarks));
802        for (partition, consolidator) in &inner.consolidators {
803            builder = builder.consolidator(partition.clone(), Arc::clone(consolidator));
804        }
805        if let Some(service) = &inner.stores.approval_service {
806            builder = builder.approval_service(Arc::clone(service));
807        }
808        if let Some(schedules) = &inner.schedules {
809            builder = builder.schedule_store(Arc::clone(schedules));
810        }
811        if let Some(spend) = &inner.spend {
812            builder = builder.spend_ledger(Arc::clone(spend));
813        }
814        if let Some(trail) = &inner.audit {
815            builder = builder.audit(trail.clone());
816        }
817        if let Some(drivers) = &inner.drivers {
818            builder = builder.drivers(drivers.clone());
819        }
820        let mut crons: BTreeMap<String, MissedFirePolicy> = BTreeMap::new();
821        for (target, hosted) in hosted {
822            match hosted.kernel.primary_partition().filter(|_| !hosted.partitions.is_empty()) {
823                // One agent per partition, each bound to its partition; the primary's also
824                // serves the definition's own target (spec 3.2 §7.8).
825                Some(primary) => {
826                    for (id, (partition, agent)) in &hosted.partitions {
827                        let runner = self.partition_runner(Arc::clone(agent), partition)?;
828                        if *id == primary {
829                            builder =
830                                builder.partition_agent(id.clone(), target.clone(), runner.clone());
831                        }
832                        builder = builder.partition_agent(
833                            id.clone(),
834                            partition_target(target, id),
835                            runner,
836                        );
837                    }
838                }
839                None => {
840                    builder =
841                        builder.agent(target.clone(), self.runner(Arc::clone(&hosted.agent))?);
842                }
843            }
844            for set in &hosted.kernel.wake_sets {
845                let run_target = match &set.partition {
846                    Some(partition) if hosted.partitions.contains_key(partition) => {
847                        partition_target(target, partition)
848                    }
849                    _ => target.clone(),
850                };
851                for trigger in triggers(&inner.tenant, target, &run_target, set) {
852                    builder = builder.trigger(trigger);
853                }
854                for wake in &set.any_of {
855                    if let Wake::Cron { expr, missed } = wake {
856                        let widest = crons
857                            .get(expr)
858                            .map_or(*missed, |held| crate::wake::widest_policy(*held, *missed));
859                        crons.insert(expr.clone(), widest);
860                    }
861                }
862            }
863        }
864        // One source per expression: every trigger on it matches each tick once. Its
865        // watermark is the tenant's, so the ticks missed while no replica ran fire once each,
866        // as the widest policy on the expression plans them and each wake's own policy picks.
867        for (expr, missed) in crons {
868            let name = cron_source_name(&expr);
869            let watermark = SourceWatermark::new(Arc::clone(&inner.watermarks), name.clone());
870            let mut source = CronWakeSource::watermarked(name, &expr, missed, Arc::new(watermark))?;
871            if let Some(jitter) = inner.config.salted_cron_jitter() {
872                source = source.with_jitter(jitter);
873            }
874            builder = builder.wake_source(Arc::new(source));
875        }
876        builder.build()
877    }
878
879    /// The policy of a kernel hosting `hosted`: the first definition's that sets one, or the
880    /// operator's with the consolidation tick off, since only a definition turns it on in the
881    /// managed form (spec 3.2 §13 Q1).
882    fn policy(&self, hosted: &BTreeMap<String, Hosted>) -> ProactivityPolicy {
883        if let Some(policy) = hosted.values().find_map(|hosted| hosted.kernel.proactivity.clone()) {
884            return policy;
885        }
886        let mut policy = self.inner.config.proactivity.clone();
887        policy.consolidation = None;
888        policy
889    }
890
891    /// The runner of partition `partition`'s agent: the tenant's, acting with the
892    /// partition's class and tenant (spec 3.2 §7.8).
893    fn partition_runner(
894        &self,
895        agent: Arc<dyn Agent>,
896        partition: &Partition,
897    ) -> Result<Arc<Runner>> {
898        let identity = partition.identity_source(&self.inner.tenant, agent.name());
899        self.runner_with(agent, Some(identity))
900    }
901
902    /// The runner of a hosted definition's agent: the tenant's app, sessions, kill switch
903    /// and approvals.
904    fn runner(&self, agent: Arc<dyn Agent>) -> Result<Arc<Runner>> {
905        self.runner_with(agent, None)
906    }
907
908    fn runner_with(
909        &self,
910        agent: Arc<dyn Agent>,
911        identity: Option<Arc<dyn adk_core::IdentitySource>>,
912    ) -> Result<Arc<Runner>> {
913        let inner = &self.inner;
914        let mut config = RunConfig::builder();
915        if let Some(service) = &inner.stores.approval_service {
916            config = config.approval_service(Arc::clone(service));
917        }
918        let mut builder = Runner::builder()
919            .app_name(inner.tenant.as_str())
920            .agent(agent)
921            .session_service(Arc::clone(&inner.sessions))
922            .run_config(config.build())
923            .approval_store(Arc::clone(&inner.stores.decisions))
924            .governance(inner.config.governance.clone());
925        if let Some(ledger) = &inner.action_ledger {
926            builder = builder.action_ledger(Arc::clone(ledger));
927        }
928        if let Some(spend) = &inner.spend {
929            builder = builder.spend_ledger(Arc::clone(spend));
930        }
931        if let Some(identity) = identity {
932            builder = builder.identity_source(identity);
933        }
934        Ok(Arc::new(builder.build()?))
935    }
936}
937
938/// The target of partition `partition`'s agent of definition `target`:
939/// `<definition>@<partition>` (spec 3.2 §7.8).
940fn partition_target(target: &str, partition: &PartitionId) -> String {
941    format!("{target}@{partition}")
942}
943
944/// The kernel triggers of `set` on definition `target`: one per wake, named
945/// `<target>/<set>`, each enqueueing a run of `run_target` — the definition's target, or its
946/// partition's agent — for the tenant. A signal wake that names no partition hears the set's
947/// own, so a definition never hears the signals of another's partitions.
948fn triggers(tenant: &str, target: &str, run_target: &str, set: &WakeSetDef) -> Vec<Trigger> {
949    let name = format!("{target}/{}", set.name);
950    // `skip` is held by the store too, so two replicas that route two firings at once start
951    // one process; `queueOne` coalesces in the router.
952    let on_conflict = match set.overlap {
953        WakeOverlap::Skip => OnConflict::Reject,
954        _ => OnConflict::Enqueue,
955    };
956    let run = NewRun::new(
957        set.queue_class().as_str(),
958        tenant,
959        set.user(),
960        run_target,
961        json!({ "text": set.input }),
962    )
963    .with_concurrency_key(format!("wake-set:{name}"), on_conflict);
964    let partition = KernelDef::partition_of(set);
965    set.any_of
966        .iter()
967        .map(|wake| {
968            let wake = match wake {
969                Wake::Signal { kind, partition: None } => {
970                    Wake::Signal { kind: kind.clone(), partition: Some(partition.clone()) }
971                }
972                other => other.clone(),
973            };
974            Trigger::new(name.clone(), wake, run.clone())
975                .with_partition(partition.clone())
976                .with_overlap(set.overlap)
977        })
978        .collect()
979}
980
981/// The cron expressions the wake sets of `hosted` use.
982fn cron_expressions(hosted: &BTreeMap<String, Hosted>) -> BTreeSet<String> {
983    hosted
984        .values()
985        .flat_map(|hosted| hosted.kernel.wake_sets.iter())
986        .flat_map(|set| set.any_of.iter())
987        .filter_map(|wake| match wake {
988            Wake::Cron { expr, .. } => Some(expr.clone()),
989            _ => None,
990        })
991        .collect()
992}
993
994/// The cron source of `expr`, named by the expression with `_` for spaces.
995fn cron_source_name(expr: &str) -> String {
996    expr.split_whitespace().collect::<Vec<_>>().join("_")
997}
998
999/// The approval-inbox tool name of a driver mount a hosted definition asks for (spec 3.2
1000/// §7.7): the proposal waits in the tenant's inbox as an `ApprovalRequest` with this
1001/// `tool_name`, the `DriverProposal` as `args_redacted` and `allowed_actions = [Approve,
1002/// Reject]`.
1003pub const DRIVER_MOUNT_TOOL_NAME: &str = "kernel:driver.mount";
1004
1005/// The approver group of a driver mount unless [`TenantKernelBuilder::driver_approvers`]
1006/// names others: the control plane's operators.
1007const DRIVER_APPROVER_GROUP: &str = "operator";
1008
1009/// The ids of `kernel`'s drivers that a declared partition mounts: listed in the partition's
1010/// `drivers`, with the partition in the manifest's `partitions`.
1011fn served_by_partitions(kernel: &KernelDef) -> Vec<String> {
1012    kernel
1013        .drivers
1014        .iter()
1015        .filter(|manifest| {
1016            kernel.partitions.iter().any(|partition| {
1017                partition.drivers.contains(&manifest.id)
1018                    && manifest.partitions.contains(&partition.id)
1019            })
1020        })
1021        .map(|manifest| manifest.id.clone())
1022        .collect()
1023}
1024
1025/// Every driver the hosted definitions' partitions mount, with its definition.
1026fn served_drivers(hosted: &BTreeMap<String, Hosted>) -> Vec<(String, DriverManifest)> {
1027    hosted
1028        .iter()
1029        .flat_map(|(definition, hosted)| {
1030            let served = served_by_partitions(&hosted.kernel);
1031            hosted
1032                .kernel
1033                .drivers
1034                .iter()
1035                .filter(move |manifest| served.contains(&manifest.id))
1036                .map(|manifest| (definition.clone(), manifest.clone()))
1037                .collect::<Vec<_>>()
1038        })
1039        .collect()
1040}
1041
1042/// Whether `manifest` is mounted with what its proposal shows: the same command, partitions,
1043/// effect classes, sandbox, secrets and lifecycle.
1044fn mounted_as_proposed(drivers: &DriverSupervisor, manifest: &DriverManifest) -> bool {
1045    drivers.record(&manifest.id).is_some_and(|record: DriverRecord| {
1046        DriverProposal::of(&record.manifest) == DriverProposal::of(manifest)
1047    })
1048}
1049
1050/// The inbox request id of mounting `manifest`: `kernel-driver-<id>-<digest>`, the digest of
1051/// what the proposal shows, so a changed manifest is asked again.
1052fn driver_request_id(manifest: &DriverManifest) -> String {
1053    let proposal =
1054        serde_json::to_vec(&DriverProposal::of(manifest)).expect("a proposal always serializes");
1055    let digest = sha2::Sha256::digest(&proposal);
1056    let hex: String = digest[..8].iter().map(|byte| format!("{byte:02x}")).collect();
1057    let id: String = manifest
1058        .id
1059        .chars()
1060        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
1061        .collect();
1062    format!("kernel-driver-{id}-{hex}")
1063}
1064
1065/// The directory name of `tenant` under the kernel home: its letters, digits, `-` and `_`,
1066/// and a digest of the whole name, so two tenants never share one.
1067fn tenant_dir(tenant: &str) -> String {
1068    let readable: String = tenant
1069        .chars()
1070        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
1071        .collect();
1072    let digest = sha2::Sha256::digest(tenant.as_bytes());
1073    let hex: String = digest[..4].iter().map(|byte| format!("{byte:02x}")).collect();
1074    format!("{readable}-{hex}")
1075}
1076
1077/// Builds `TenantKernel` (spec 3.2 §7.13, §10 M1).
1078pub struct TenantKernelBuilder {
1079    tenant: String,
1080    stores: ManagedStores,
1081    sessions: Arc<dyn SessionService>,
1082    config: Option<KernelConfig>,
1083    processes: Option<Arc<dyn ProcessStore>>,
1084    schedules: Option<Arc<dyn ScheduleStore>>,
1085    resolver: Option<Arc<dyn AgentResolver>>,
1086    action_ledger: Option<Arc<dyn ActionLedger>>,
1087    spend: Option<Arc<dyn SpendLedger>>,
1088    audit: Option<AuditTrail>,
1089    governance: Option<GovernanceControl>,
1090    agenda: Option<Arc<dyn AgendaStore>>,
1091    agenda_handle: Option<AgendaHandle>,
1092    consolidators: BTreeMap<PartitionId, Arc<dyn Consolidator>>,
1093    partition_store: Option<Arc<dyn PartitionStore>>,
1094    partition_resolver: Option<Arc<dyn PartitionAgentResolver>>,
1095    watermark_store: Option<Arc<dyn CronWatermarkStore>>,
1096    drivers: Option<DriverSupervisor>,
1097    driver_approvers: Option<ApprovalPolicy>,
1098    #[cfg(feature = "charter")]
1099    signals: Option<Arc<dyn SignalStore>>,
1100    bundle: Option<KernelStores>,
1101}
1102
1103impl fmt::Debug for TenantKernelBuilder {
1104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1105        f.debug_struct("TenantKernelBuilder").field("tenant", &self.tenant).finish_non_exhaustive()
1106    }
1107}
1108
1109impl TenantKernelBuilder {
1110    /// Sets the kernel configuration. Its `app_name` is replaced by the tenant and its control
1111    /// plane cleared — every tenant's kernel would otherwise open the socket of one shared
1112    /// home — and its proactivity policy gives the limits of a tenant whose definitions set
1113    /// none, with the consolidation tick off (spec 3.2 §13 Q1). Serve a tenant's control
1114    /// plane by mounting `control::router(kernel)` on the host's server.
1115    #[must_use]
1116    pub fn config(mut self, config: KernelConfig) -> Self {
1117        self.config = Some(config);
1118        self
1119    }
1120
1121    /// Sets the process side table, the tenant's own. Defaults to in memory.
1122    #[must_use]
1123    pub fn process_store(mut self, processes: Arc<dyn ProcessStore>) -> Self {
1124        self.processes = Some(processes);
1125        self
1126    }
1127
1128    /// Sets the schedule store the kernel's scheduler fires, the tenant's own.
1129    #[must_use]
1130    pub fn schedule_store(mut self, schedules: Arc<dyn ScheduleStore>) -> Self {
1131        self.schedules = Some(schedules);
1132        self
1133    }
1134
1135    /// Builds the definitions' agents with `resolver`, such as `adk-harness`'s
1136    /// `HarnessResolver`. A definition with a kernel block needs an agent it builds.
1137    #[must_use]
1138    pub fn resolver(mut self, resolver: Arc<dyn AgentResolver>) -> Self {
1139        self.resolver = Some(resolver);
1140        self
1141    }
1142
1143    /// Sets the action ledger the kernel's runs record non-idempotent calls in, so a resumed
1144    /// process never runs a completed call again (K-I4).
1145    #[must_use]
1146    pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
1147        self.action_ledger = Some(ledger);
1148        self
1149    }
1150
1151    /// Sets the spend ledger.
1152    #[must_use]
1153    pub fn spend_ledger(mut self, spend: Arc<dyn SpendLedger>) -> Self {
1154        self.spend = Some(spend);
1155        self
1156    }
1157
1158    /// Sets the signed audit trail of the kernel's records.
1159    #[must_use]
1160    pub fn audit(mut self, trail: AuditTrail) -> Self {
1161        self.audit = Some(trail);
1162        self
1163    }
1164
1165    /// Sets the kill switch, such as one mirrored across the tenant's replicas; it replaces
1166    /// the configuration's.
1167    #[must_use]
1168    pub fn governance(mut self, control: GovernanceControl) -> Self {
1169        self.governance = Some(control);
1170        self
1171    }
1172
1173    /// Sets the agenda's store, the tenant's own. Defaults to in memory.
1174    #[must_use]
1175    pub fn agenda_store(mut self, store: Arc<dyn AgendaStore>) -> Self {
1176        self.agenda = Some(store);
1177        self
1178    }
1179
1180    /// Binds `handle` to every kernel the tenant builds, such as the handle the tenant's
1181    /// harnesses were given (`HarnessAgentBuilder::agenda_handle`), so their follow-ups reach
1182    /// the tenant's agenda (spec 3.2 §7.5). Defaults to a new handle.
1183    #[must_use]
1184    pub fn agenda_handle(mut self, handle: AgendaHandle) -> Self {
1185        self.agenda_handle = Some(handle);
1186        self
1187    }
1188
1189    /// Registers `consolidator` for `partition`: the tenant's kernel runs its consolidation
1190    /// tick there when a hosted definition's policy turns the tick on (spec 3.2 §7.5,
1191    /// §13 Q1).
1192    #[must_use]
1193    pub fn consolidator(
1194        mut self,
1195        partition: impl Into<PartitionId>,
1196        consolidator: Arc<dyn Consolidator>,
1197    ) -> Self {
1198        self.consolidators.insert(partition.into(), consolidator);
1199        self
1200    }
1201
1202    /// Sets the tenant's partition table and crossing ledger, the tenant's own (spec 3.2
1203    /// §7.8). Defaults to in memory.
1204    #[must_use]
1205    pub fn partition_store(mut self, store: Arc<dyn PartitionStore>) -> Self {
1206        self.partition_store = Some(store);
1207        self
1208    }
1209
1210    /// Builds one agent per partition a definition declares with `resolver`, such as
1211    /// `adk-harness`'s `HarnessResolver`: one harness per partition (spec 3.2 §7.8). Without
1212    /// one, a definition's partitions are recorded and its agent runs in the default
1213    /// partition.
1214    #[must_use]
1215    pub fn partition_resolver(mut self, resolver: Arc<dyn PartitionAgentResolver>) -> Self {
1216        self.partition_resolver = Some(resolver);
1217        self
1218    }
1219
1220    /// Sets where the tenant's cron sources keep their watermarks, the tenant's own (spec 3.2
1221    /// §7.4, §7.13): on a durable store, a tick missed while no replica of the tenant ran
1222    /// fires once each as the wake set's `missed` policy picks it, when the next replica
1223    /// starts. Defaults to in memory, which keeps nothing across a restart.
1224    #[must_use]
1225    pub fn watermark_store(mut self, store: Arc<dyn CronWatermarkStore>) -> Self {
1226        self.watermark_store = Some(store);
1227        self
1228    }
1229
1230    /// Mounts the drivers the tenant's definitions ask for on `drivers`, the tenant's own
1231    /// supervisor over the tenant's own driver store (spec 3.2 §7.7, §7.13). Each driver a
1232    /// definition's partition mounts is proposed in the tenant's approval inbox and mounted
1233    /// when a person approves it; its tools reach that partition's harness only. Its drivers
1234    /// run as the tenant's app under `<kernel home>/tenants/<tenant>` unless the
1235    /// supervisor's builder set an app name or a home. Without one, a definition's driver
1236    /// manifests are recorded and none is mounted.
1237    #[must_use]
1238    pub fn drivers(mut self, drivers: DriverSupervisor) -> Self {
1239        self.drivers = Some(drivers);
1240        self
1241    }
1242
1243    /// Who approves a driver mount: by default anyone in the `operator` group, as the
1244    /// control plane's operators are. Only a person's approval mounts a driver.
1245    #[must_use]
1246    pub fn driver_approvers(mut self, approvers: ApprovalPolicy) -> Self {
1247        self.driver_approvers = Some(approvers);
1248        self
1249    }
1250
1251    /// Sets where the tenant's signals are counted, the tenant's own (spec 3.5 §7.10;
1252    /// feature `charter`): [`TenantKernel::signal_sink`] files them, and a definition whose
1253    /// wake set hears a signal is hosted only on a tenant with one. Defaults to none.
1254    ///
1255    /// `SignalStore` runs on in-memory, SQLite, PostgreSQL and Redis; a tenant whose other
1256    /// stores are on MongoDB, Firestore or Neo4j keeps its signals on one of those.
1257    #[cfg(feature = "charter")]
1258    #[must_use]
1259    pub fn signal_store(mut self, store: Arc<dyn SignalStore>) -> Self {
1260        self.signals = Some(store);
1261        self
1262    }
1263
1264    /// Takes the tenant's stateful stores the builder has no other from `stores`, the
1265    /// tenant's own (spec 3.2 §7.1, §7.13): the process side table, schedules, spend and
1266    /// action ledgers, agenda, partition table, cron watermarks, agent table and, with the
1267    /// `charter` feature, the signal store; the kill
1268    /// switch mirrored over `governance` unless [`governance`](Self::governance) is set or
1269    /// the bundle keeps it in memory. A store set on the builder wins. The run store and the
1270    /// approvals are the tenant's [`ManagedStores`]'.
1271    ///
1272    /// # Example
1273    ///
1274    /// ```rust
1275    /// use std::sync::Arc;
1276    /// use adk_kernel::managed::TenantKernel;
1277    /// use adk_kernel::stores::KernelStores;
1278    /// use adk_managed::ManagedStores;
1279    /// use adk_session::InMemorySessionService;
1280    ///
1281    /// let stores = KernelStores::in_memory();
1282    /// let tenant = TenantKernel::builder("tenant-a", ManagedStores::in_memory(), Arc::new(InMemorySessionService::new()))
1283    ///     .stores(&stores)
1284    ///     .build()?;
1285    /// assert!(Arc::ptr_eq(tenant.process_store(), &stores.processes));
1286    /// # Ok::<(), adk_kernel::KernelError>(())
1287    /// ```
1288    #[must_use]
1289    pub fn stores(mut self, stores: &KernelStores) -> Self {
1290        self.bundle = Some(stores.clone());
1291        self
1292    }
1293
1294    /// Builds the tenant's kernel. Nothing runs until [`TenantKernel::start`]. Each store
1295    /// neither set nor in the builder's [`stores`](Self::stores) is kept in memory, with a
1296    /// warning naming it.
1297    ///
1298    /// # Errors
1299    ///
1300    /// Returns [`KernelError::Config`] when the tenant is blank.
1301    pub fn build(self) -> Result<TenantKernel> {
1302        if self.tenant.trim().is_empty() {
1303            return Err(KernelError::Config {
1304                reason: "a tenant kernel needs the tenant's name: the app name its sessions \
1305                         are created under"
1306                    .into(),
1307            });
1308        }
1309        let mut config = self.config.unwrap_or_default();
1310        config.app_name = self.tenant.clone();
1311        config.control = ControlPlaneConfig::default().without_socket();
1312        let bundle = self.bundle.as_ref();
1313        match (self.governance, bundle) {
1314            (Some(governance), _) => config.governance = governance,
1315            (None, Some(bundle))
1316                if !config.governance.is_mirrored() && !bundle.is_in_memory("governance") =>
1317            {
1318                config.governance =
1319                    KernelConfig::mirrored_governance(Arc::clone(&bundle.governance));
1320            }
1321            (None, _) => {}
1322        }
1323        // A store neither set nor bundled is kept in memory, named once here; the kernels
1324        // the tenant builds are given every store, so they warn about none.
1325        let tenant = self.tenant.clone();
1326        let memory = |store: &str| {
1327            tracing::warn!(
1328                tenant = %tenant,
1329                kernel.store = store,
1330                "the tenant's kernel keeps this store in memory, so its state ends with the \
1331                 process; give the builder durable stores (TenantKernelBuilder::stores)"
1332            );
1333        };
1334        let processes: Arc<dyn ProcessStore> = self
1335            .processes
1336            .or_else(|| bundle.map(|b| Arc::clone(&b.processes)))
1337            .unwrap_or_else(|| {
1338                memory("process_store");
1339                Arc::new(InMemoryProcessStore::new())
1340            });
1341        let agenda: Arc<dyn AgendaStore> =
1342            self.agenda.or_else(|| bundle.map(|b| Arc::clone(&b.agenda))).unwrap_or_else(|| {
1343                memory("agenda_store");
1344                Arc::new(InMemoryAgendaStore::new())
1345            });
1346        let partition_store: Arc<dyn PartitionStore> = self
1347            .partition_store
1348            .or_else(|| bundle.map(|b| Arc::clone(&b.partitions)))
1349            .unwrap_or_else(|| {
1350                memory("partition_store");
1351                Arc::new(InMemoryPartitionStore::new())
1352            });
1353        let watermarks: Arc<dyn CronWatermarkStore> = self
1354            .watermark_store
1355            .or_else(|| bundle.map(|b| Arc::clone(&b.watermarks)))
1356            .unwrap_or_else(|| {
1357                memory("watermark_store");
1358                Arc::new(InMemoryCronWatermarkStore::new())
1359            });
1360        let agents: Arc<dyn crate::agents::AgentStore> = match bundle {
1361            Some(bundle) => Arc::clone(&bundle.agents),
1362            None => Arc::new(InMemoryAgentStore::new()),
1363        };
1364        let schedules = self.schedules.or_else(|| bundle.map(|b| Arc::clone(&b.schedules)));
1365        let spend = self.spend.or_else(|| bundle.map(|b| Arc::clone(&b.spend)));
1366        let action_ledger = self.action_ledger.or_else(|| bundle.map(|b| Arc::clone(&b.actions)));
1367        if let Some(drivers) = &self.drivers {
1368            drivers.host_defaults(
1369                &self.tenant,
1370                &config.home.join("tenants").join(tenant_dir(&self.tenant)),
1371            );
1372        }
1373        let mut partitions = Partitions::new(partition_store);
1374        if let Some(trail) = &self.audit {
1375            partitions = partitions.with_audit(trail.clone());
1376        }
1377        Ok(TenantKernel {
1378            inner: Arc::new(TenantInner {
1379                tenant: self.tenant,
1380                stores: self.stores,
1381                sessions: self.sessions,
1382                config,
1383                processes,
1384                schedules,
1385                resolver: self.resolver,
1386                action_ledger,
1387                spend,
1388                audit: self.audit,
1389                agenda,
1390                agenda_handle: self.agenda_handle.unwrap_or_default(),
1391                agents,
1392                consolidators: self.consolidators,
1393                partitions,
1394                partition_resolver: self.partition_resolver,
1395                watermarks,
1396                drivers: self.drivers,
1397                driver_approvers: self.driver_approvers.unwrap_or_else(|| {
1398                    ApprovalPolicy::new([ApproverSelector::group(DRIVER_APPROVER_GROUP)])
1399                }),
1400                #[cfg(feature = "charter")]
1401                signals: self.signals.or_else(|| bundle.map(|b| Arc::clone(&b.charter.signals))),
1402                driver_decisions: std::sync::Mutex::new(None),
1403                hosting: tokio::sync::Mutex::new(Hosting::default()),
1404            }),
1405        })
1406    }
1407}
1408
1409/// Resolves managed definitions for a [`TenantKernel`] (spec 3.2 §7.13, §10 M1): an
1410/// `AgentResolver` for `DefaultManagedAgentRuntime::with_agent_resolver`.
1411///
1412/// | Definition | Resolved as |
1413/// |---|---|
1414/// | no kernel block | whatever the tenant's resolver answers, `None` leaving it to `build_agent` |
1415/// | a kernel block, an agent the tenant's resolver builds | that agent, hosted on the tenant's kernel |
1416/// | a kernel block with partitions, and a [`PartitionAgentResolver`] | one agent per partition, hosted with [`TenantKernel::host_partitions`]; the runtime's sessions run the coordinator's, else the first partition's by id (spec 3.2 §7.8) |
1417/// | a kernel block, no agent the resolver builds | refused: a kernel hosts an agent the operator's resolver builds, such as a harness definition |
1418/// | an invalid kernel block | refused as an invalid request, naming the key |
1419///
1420/// Built by [`TenantKernel::resolver`].
1421pub struct KernelResolver {
1422    tenant: TenantKernel,
1423}
1424
1425impl fmt::Debug for KernelResolver {
1426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427        f.debug_struct("KernelResolver").field("tenant", &self.tenant.tenant()).finish()
1428    }
1429}
1430
1431#[async_trait]
1432impl AgentResolver for KernelResolver {
1433    async fn resolve(
1434        &self,
1435        def: &ManagedAgentDef,
1436        models: &dyn ModelResolver,
1437    ) -> std::result::Result<Option<Arc<dyn Agent>>, RuntimeError> {
1438        let block = KernelDef::from_agent_def(def).map_err(runtime_error)?;
1439        let agent = match &self.tenant.inner.resolver {
1440            Some(resolver) => resolver.resolve(def, models).await?,
1441            None => None,
1442        };
1443        if block.is_none() {
1444            return Ok(agent);
1445        }
1446        let Some(agent) = agent else {
1447            return Err(RuntimeError::invalid_request(format!(
1448                "definition '{}' carries a kernel block (`{}`), and the tenant's resolver builds \
1449                 no agent for it: a kernel hosts an agent the operator's resolver builds, such \
1450                 as a harness definition (`adk.harness`) under HarnessResolver",
1451                def.name,
1452                super::KERNEL_DEF_METADATA_KEY
1453            )));
1454        };
1455        let partitions = match &block {
1456            Some(block) if !block.partitions.is_empty() => {
1457                self.tenant.inner.partition_resolver.as_ref().map(|resolver| (block, resolver))
1458            }
1459            _ => None,
1460        };
1461        let Some((block, resolver)) = partitions else {
1462            self.tenant.host(def, Arc::clone(&agent)).await.map_err(runtime_error)?;
1463            return Ok(Some(agent));
1464        };
1465        // One agent per partition, each in the tenant's partition table (spec 3.2 §7.8).
1466        let mut agents = BTreeMap::new();
1467        for declared in &block.partitions {
1468            let host = PartitionHost {
1469                partition: declared.to_partition(self.tenant.tenant()).map_err(runtime_error)?,
1470                partitions: self.tenant.partitions().clone(),
1471                coordinator: block.coordinator.as_ref() == Some(&declared.id),
1472                drivers: self.tenant.drivers().cloned(),
1473            };
1474            let Some(agent) = resolver.resolve_partition(def, &host, models).await? else {
1475                return Err(RuntimeError::invalid_request(format!(
1476                    "definition '{}' declares partition `{}`, and the tenant's partition \
1477                     resolver builds no agent for it",
1478                    def.name, declared.id
1479                )));
1480            };
1481            agents.insert(declared.id.clone(), agent);
1482        }
1483        let primary = block.primary_partition().expect("a block with partitions has a primary");
1484        let agent = Arc::clone(&agents[&primary]);
1485        self.tenant.host_partitions(def, agents).await.map_err(runtime_error)?;
1486        Ok(Some(agent))
1487    }
1488}
1489
1490/// Builds the agent of one partition of a hosted definition (spec 3.2 §7.8, §7.13): one
1491/// harness per partition, built with the partition's mode, class and tenant, memory scope,
1492/// drivers and crossing policy over the tenant's partition table. `adk-harness`'s
1493/// `HarnessResolver` implements it.
1494///
1495/// # Example
1496///
1497/// ```rust
1498/// use std::sync::Arc;
1499/// use adk_core::Agent;
1500/// use adk_kernel::managed::{PartitionAgentResolver, PartitionHost};
1501/// use adk_managed::resolver::ModelResolver;
1502/// use adk_managed::types::{ManagedAgentDef, RuntimeError};
1503///
1504/// struct Builds;
1505///
1506/// #[async_trait::async_trait]
1507/// impl PartitionAgentResolver for Builds {
1508///     async fn resolve_partition(
1509///         &self,
1510///         _def: &ManagedAgentDef,
1511///         host: &PartitionHost,
1512///         _models: &dyn ModelResolver,
1513///     ) -> Result<Option<Arc<dyn Agent>>, RuntimeError> {
1514///         // Build the partition's harness with `host.partition` and `host.partitions`.
1515///         let _ = (&host.partition, &host.partitions, host.coordinator);
1516///         Ok(None)
1517///     }
1518/// }
1519/// ```
1520#[async_trait]
1521pub trait PartitionAgentResolver: Send + Sync {
1522    /// The agent of `host.partition` for `def`, or `None` when this resolver builds none.
1523    ///
1524    /// # Errors
1525    ///
1526    /// Returns the error that kept the agent from being built; the definition is refused.
1527    async fn resolve_partition(
1528        &self,
1529        def: &ManagedAgentDef,
1530        host: &PartitionHost,
1531        models: &dyn ModelResolver,
1532    ) -> std::result::Result<Option<Arc<dyn Agent>>, RuntimeError>;
1533}
1534
1535/// The partition a [`PartitionAgentResolver`] builds an agent for (spec 3.2 §7.8).
1536#[derive(Debug, Clone)]
1537#[non_exhaustive]
1538pub struct PartitionHost {
1539    /// The partition's record, its tenant the hosting tenant.
1540    pub partition: Partition,
1541    /// The tenant's partition table, which the partition's crossing policy reads.
1542    pub partitions: Partitions,
1543    /// Whether the partition's agent is the coordinator ([`KernelDef::coordinator`]).
1544    pub coordinator: bool,
1545    /// The tenant's driver supervisor, when it has one: the partition's harness mounts the
1546    /// drivers its `drivers` names from it (`HarnessAgentBuilder::partition_drivers`), and
1547    /// the coordinator's offers the other partitions' drivers as crossings (spec 3.2 §7.7,
1548    /// §7.8).
1549    pub drivers: Option<DriverSupervisor>,
1550}
1551
1552fn runtime_error(error: KernelError) -> RuntimeError {
1553    match error {
1554        KernelError::Config { reason } => RuntimeError::invalid_request(reason),
1555        other => RuntimeError::internal(other.to_string()),
1556    }
1557}
1558
1559/// The tenants a host runs, one kernel each (spec 3.2 §7.13).
1560///
1561/// A tenant's stores are its own: [`insert`](Self::insert) refuses a tenant whose run
1562/// store, decision store, state store, approval service, process store, partition store, cron
1563/// watermark store, signal store, driver supervisor or driver store another tenant already
1564/// holds, since a shared run store lets one tenant's workers claim the other's runs, and a
1565/// shared signal store counts one tenant's signals into the other's items. Stores that are distinct values over one database are not detected; give each
1566/// tenant its own database, schema or key namespace.
1567///
1568/// # Example
1569///
1570/// ```rust
1571/// use std::sync::Arc;
1572/// use adk_kernel::managed::{ManagedKernels, TenantKernel};
1573/// use adk_managed::ManagedStores;
1574/// use adk_session::InMemorySessionService;
1575///
1576/// let sessions = Arc::new(InMemorySessionService::new());
1577/// let kernels = ManagedKernels::new();
1578/// let a = TenantKernel::builder("tenant-a", ManagedStores::in_memory(), sessions.clone()).build()?;
1579/// kernels.insert(a.clone())?;
1580/// let shared = TenantKernel::builder("tenant-b", a.stores().clone(), sessions).build()?;
1581/// assert!(kernels.insert(shared).is_err(), "tenant-b may not run on tenant-a's stores");
1582/// assert_eq!(kernels.tenants(), ["tenant-a"]);
1583/// # Ok::<(), adk_kernel::KernelError>(())
1584/// ```
1585#[derive(Clone, Default)]
1586pub struct ManagedKernels {
1587    tenants: Arc<std::sync::RwLock<BTreeMap<String, TenantKernel>>>,
1588}
1589
1590impl fmt::Debug for ManagedKernels {
1591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592        f.debug_struct("ManagedKernels").field("tenants", &self.tenants()).finish()
1593    }
1594}
1595
1596impl ManagedKernels {
1597    /// No tenants.
1598    pub fn new() -> Self {
1599        Self::default()
1600    }
1601
1602    /// Adds `tenant`.
1603    ///
1604    /// # Errors
1605    ///
1606    /// Returns [`KernelError::Config`] when a tenant of the same name exists or another
1607    /// tenant holds one of its stores.
1608    pub fn insert(&self, tenant: TenantKernel) -> Result<()> {
1609        let mut tenants = self.tenants.write().unwrap_or_else(|e| e.into_inner());
1610        if tenants.contains_key(tenant.tenant()) {
1611            return Err(KernelError::Config {
1612                reason: format!("tenant `{}` already has a kernel", tenant.tenant()),
1613            });
1614        }
1615        for other in tenants.values() {
1616            if let Some(store) = shared_store(&tenant, other) {
1617                return Err(KernelError::Config {
1618                    reason: format!(
1619                        "tenant `{}` would share its {store} with tenant `{}`; give each \
1620                         tenant its own stores",
1621                        tenant.tenant(),
1622                        other.tenant()
1623                    ),
1624                });
1625            }
1626        }
1627        tenants.insert(tenant.tenant().to_string(), tenant);
1628        Ok(())
1629    }
1630
1631    /// The kernel of `tenant`.
1632    pub fn get(&self, tenant: &str) -> Option<TenantKernel> {
1633        self.tenants.read().unwrap_or_else(|e| e.into_inner()).get(tenant).cloned()
1634    }
1635
1636    /// The tenants' names, sorted.
1637    pub fn tenants(&self) -> Vec<String> {
1638        self.tenants.read().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()
1639    }
1640
1641    /// Starts every tenant's kernel that does not run yet.
1642    ///
1643    /// # Errors
1644    ///
1645    /// Returns the first start error; the tenants before it keep running.
1646    pub async fn start(&self) -> Result<()> {
1647        let tenants: Vec<TenantKernel> =
1648            self.tenants.read().unwrap_or_else(|e| e.into_inner()).values().cloned().collect();
1649        for tenant in tenants {
1650            if tenant.kernel().await.is_none() {
1651                tenant.start().await?;
1652            }
1653        }
1654        Ok(())
1655    }
1656
1657    /// Stops every tenant's kernel.
1658    ///
1659    /// # Errors
1660    ///
1661    /// Returns the first stop error; every kernel is stopped regardless.
1662    pub async fn stop(&self) -> Result<()> {
1663        let tenants: Vec<TenantKernel> =
1664            self.tenants.read().unwrap_or_else(|e| e.into_inner()).values().cloned().collect();
1665        let mut first = None;
1666        for tenant in tenants {
1667            if let Err(error) = tenant.stop().await {
1668                first.get_or_insert(error);
1669            }
1670        }
1671        first.map_or(Ok(()), Err)
1672    }
1673}
1674
1675/// The store `a` and `b` share, by name, if any.
1676fn shared_store(a: &TenantKernel, b: &TenantKernel) -> Option<&'static str> {
1677    fn same<T: ?Sized>(a: &Arc<T>, b: &Arc<T>) -> bool {
1678        std::ptr::eq(Arc::as_ptr(a) as *const (), Arc::as_ptr(b) as *const ())
1679    }
1680    let (x, y) = (a.stores(), b.stores());
1681    if same(&x.runs, &y.runs) {
1682        return Some("run store");
1683    }
1684    if same(&x.decisions, &y.decisions) {
1685        return Some("decision store");
1686    }
1687    if same(&x.state, &y.state) {
1688        return Some("state store");
1689    }
1690    if let (Some(p), Some(q)) = (&x.approval_service, &y.approval_service)
1691        && same(p, q)
1692    {
1693        return Some("approval service");
1694    }
1695    if same(a.process_store(), b.process_store()) {
1696        return Some("process store");
1697    }
1698    if same(a.partitions().store(), b.partitions().store()) {
1699        return Some("partition store");
1700    }
1701    if same(a.watermark_store(), b.watermark_store()) {
1702        return Some("cron watermark store");
1703    }
1704    #[cfg(feature = "charter")]
1705    if let (Some(p), Some(q)) = (a.signal_store(), b.signal_store())
1706        && same(p, q)
1707    {
1708        return Some("signal store");
1709    }
1710    if let (Some(p), Some(q)) = (a.drivers(), b.drivers()) {
1711        if p.same(q) {
1712            return Some("driver supervisor");
1713        }
1714        if same(p.store(), q.store()) {
1715            return Some("driver store");
1716        }
1717    }
1718    None
1719}