Skip to main content

adk_kernel/
kernel.rs

1//! The supervisor (spec 3.2 §7.2).
2//!
3//! A [`Kernel`] composes the background machinery `adk-rust serve` already builds (§6 D-9)
4//! and adds a worker per queue class, the scheduler, the wake sources, the process table,
5//! the event bus and the control plane:
6//!
7//! | Kernel part | Built from |
8//! |---|---|
9//! | Workers | One `DurableWorker` per [`QueueClass`], each with [`KernelConfig::worker_config`]: `on_governance_refusal: Park` (§10 S3), the class's poll interval, the S1 `WorkerHooks` turned into [`KernelEvent`]s, and the targets registered with [`KernelBuilder::agent`] (the harness runner as `adk-rust` and `harness.goal`), on [`KernelConfig::clock`] |
10//! | Scheduler | `DurableScheduler::new(schedules, runs).with_governance(..).with_clock(..)`, ticking every [`KernelConfig::scheduler_tick`] on [`KernelConfig::clock`] |
11//! | Wake sources | [`KernelBuilder::wake_source`], [`KernelBuilder::trigger`] and [`KernelBuilder::queue_ingress`], routed by the [`WakeRouter`] (§7.4) |
12//! | Approvals | `StoreApprovalService::with_run_store`, so a decision wakes the parked run; the service's `tick` on the kernel's clock for expiries |
13//! | Kill switch | [`KernelConfig::governance`]: `GovernanceControl::mirrored` with a 250 ms poll on multi-replica ([`KernelConfig::mirrored_governance`], K-I8) |
14//! | Control plane | [`ControlPlane`] over [`KernelConfig::control`] (§7.11) |
15//! | `/proc` (feature `proc`) | `KernelBuilder::ledger`: a sink on the bus writes every event's ledger row; the hosted runtime's `ProgressSource` gets the ledger at start; with `proc-baselines` the maintenance tick enqueues the daily `kernel.proc` pass, and [`KernelBuilder::observation_audience`] puts a partition's observations to a person as agenda questions (§7.10) |
16//!
17//! Lifecycle: [`pause`](Kernel::pause) shuts each worker's claim loop down and lets running
18//! processes finish their attempt; [`drain`](Kernel::drain) suspends running processes at
19//! their next checkpoint through S1's suspend path, then shuts the loops down, and on
20//! timeout aborts them so their leases lapse; [`stop`](Kernel::stop) also stops drivers and
21//! closes the control plane. A `SIGTERM` is `drain(30 s)` then `stop`
22//! ([`shutdown_on_signal`](Kernel::shutdown_on_signal)). Nothing is lost on a hard kill:
23//! leases expire and another claim resumes from the checkpoint.
24//!
25//! [`freeze`](Kernel::freeze) calls `GovernanceControl::freeze_recorded`; parking is the
26//! worker's (§10 S3), so every replica's worker parks its own running processes
27//! `Waiting` with `ParkReason::Frozen` as its mirrored control observes the freeze.
28//! [`unfreeze`](Kernel::unfreeze) calls `unfreeze_recorded` and wakes exactly the
29//! freeze-parked processes (K-I21). The kernel registers itself as the
30//! `GovernanceController`'s `FreezeDelegate` (§10 S4), so `POST /api/admin/freeze` parks.
31
32use std::collections::{BTreeMap, HashMap};
33use std::fmt;
34use std::path::PathBuf;
35use std::sync::atomic::Ordering;
36use std::sync::{Arc, RwLock};
37use std::time::Duration;
38
39use adk_core::audit_log::{AuditActor, AuditTrail};
40use adk_core::queue_source::QueueIngress;
41use adk_core::schedule::Jitter;
42use adk_core::{
43    ApprovalPolicy, ApprovalService, ApproverSelector, Clock, DurableRunStore, Enqueued,
44    GovernanceControl, GovernanceMirrorConfig, GovernanceStateStore, ScheduleStore, SpendLedger,
45    SystemClock,
46};
47use adk_runner::Runner;
48use adk_server::background::{
49    DurableScheduler, DurableSubagents, DurableWorker, DurableWorkerConfig, SubagentBackend,
50    SubagentConfig, WorkflowExecutor, WorkflowRunContext, WorkflowState,
51};
52use adk_server::rest::{FreezeDelegate, FreezeReport};
53use adk_session::SessionService;
54use async_trait::async_trait;
55use futures::StreamExt;
56use serde::{Deserialize, Serialize};
57use serde_json::json;
58use tokio::task::JoinHandle;
59use tokio_util::sync::CancellationToken;
60
61use crate::agenda::{Agenda, AgendaHandle, AgendaStore, ObservationAudience, ProactivityPolicy};
62use crate::audit;
63use crate::bus::{EventBus, EventSink, EventSubscriber, KernelEvent};
64use crate::consolidation::{ConsolidationExecutor, ConsolidationTicker, Consolidator};
65use crate::control::{ControlPlane, ControlPlaneConfig};
66use crate::error::{KernelError, Result};
67use crate::inventory::{InventoryTrigger, InventoryWarning, KernelInventory};
68use crate::partition::{PartitionId, Partitions};
69#[cfg(feature = "proc")]
70use crate::proc::{Ledger, LedgerEventSink};
71use crate::process::{ProcessHandle, ProcessTable, ProgressSource, Suspension};
72use crate::sched::{QueueClass, QuietHours, Quotas};
73use crate::stores::{
74    InMemoryAgendaStore, InMemoryCronWatermarkStore, InMemoryProcessStore, ProcessStore,
75};
76use crate::stores::{KernelStores, ProcessFilter, StoreOrigin, StoreUse};
77use crate::supervise::{KernelHooks, Supervision};
78use crate::wake::{
79    CronWakeSource, FileWakeSource, KernelWakeExecutor, RunFinishedWakeSource, Trigger, Wake,
80    WakeEvent, WakeRouter, WakeSource, keys,
81};
82use crate::watermark::{CronWatermarkStore, SourceWatermark};
83
84/// How the kernel runs (spec 3.2 §7.2).
85///
86/// `proactivity`, `quiet_hours` and `quotas` apply to every partition (§7.5, §7.9); the
87/// partition records of phase 3 carry their own.
88///
89/// # Example
90///
91/// ```rust
92/// use std::time::Duration;
93/// use adk_kernel::{KernelConfig, QueueClass};
94///
95/// let config = KernelConfig::default().with_scheduler_tick(Duration::from_millis(500));
96/// assert_eq!(config.app_name, "adk-rust");
97/// assert_eq!(config.queues, QueueClass::defaults());
98/// let background = config.worker_config(&QueueClass::Background);
99/// assert_eq!(background.queue, "background");
100/// assert_eq!(background.poll_interval, Duration::from_secs(2));
101/// // No control plane unless one is configured.
102/// assert_eq!((config.control.socket, config.control.http), (None, None));
103/// ```
104#[derive(Debug, Clone)]
105#[non_exhaustive]
106pub struct KernelConfig {
107    /// The application runs belong to. Defaults to `adk-rust`.
108    pub app_name: String,
109    /// The kernel home: stores, socket and logs. Defaults to `dirs::config_dir()/adk-rust`.
110    pub home: PathBuf,
111    /// The queue classes, one worker each (spec 3.2 §7.9). Defaults to interactive,
112    /// background and maintenance. Under a kernel, runs submitted without a queue — through
113    /// `/api/runs` or `adk-rust serve`'s background state — land on `interactive`; there is
114    /// no worker for the `default` queue.
115    pub queues: Vec<QueueClass>,
116    /// The worker configuration every queue's worker starts from
117    /// (`adk-server/src/background/worker.rs`); [`worker_config`](Self::worker_config) sets
118    /// the queue and poll interval per class. Its `on_governance_refusal` is `Park` (§10 S3).
119    pub worker: DurableWorkerConfig,
120    /// How often the scheduler looks for due schedules. Defaults to 1 second.
121    pub scheduler_tick: Duration,
122    /// The kill switch: `GovernanceControl::mirrored(..)` on multi-replica, with a poll of at
123    /// most 250 ms (K-I8). Defaults to a local control.
124    pub governance: GovernanceControl,
125    /// The control plane: socket path, HTTP bind and the caller's
126    /// `RequestContextExtractor` (spec 3.2 §7.11). Defaults to none, neither a socket nor
127    /// an HTTP bind, so a kernel built from the defaults never takes the socket of a kernel
128    /// already serving the same home; `with_control(ControlPlaneConfig::default())` serves
129    /// the socket at [`home`](Self::home), as `adk-rust up` does.
130    pub control: ControlPlaneConfig,
131    /// Refuse to start a driver where no sandbox enforcer exists (spec 3.2 §7.7). Defaults
132    /// to `false`.
133    pub fail_if_sandbox_unavailable: bool,
134    /// The time the kernel reads: [`Wake::At`] times and wake-set expiry, the scheduler's
135    /// due schedules, process ages, spend days, and the age at which the workers prune
136    /// finished runs. Defaults to `SystemClock`. Give the run store the same clock
137    /// (`SqliteRunStore::with_clock`), since it decides leases and `not_before` and stamps
138    /// the times the workers compare with it.
139    pub clock: Arc<dyn Clock>,
140    /// The proactivity limits of every partition: open proposals, the daily proactive
141    /// budget, quiet hours, how proposals are approved, the consolidation tick (spec 3.2
142    /// §7.5). Defaults to [`ProactivityPolicy::default`].
143    pub proactivity: ProactivityPolicy,
144    /// A local-time window in which no proactive or maintenance process starts, beside the
145    /// proactivity policy's (spec 3.2 §7.2, §7.9). Defaults to none.
146    pub quiet_hours: Option<QuietHours>,
147    /// Every partition's quotas: max running, max queued, the daily spend cap (spec 3.2
148    /// §7.9). Defaults to none.
149    pub quotas: Quotas,
150    /// Spreads the kernel's cron ticks and schedule fires: each is delayed by a share of the
151    /// gap to the next one, under half of it, the share derived from the source or schedule
152    /// and the [`app_name`](Self::app_name). The tick keeps its scheduled time as its key and
153    /// watermark. Defaults to none.
154    pub cron_jitter: Option<Jitter>,
155}
156
157impl Default for KernelConfig {
158    fn default() -> Self {
159        Self {
160            app_name: "adk-rust".to_string(),
161            home: dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")).join("adk-rust"),
162            queues: QueueClass::defaults(),
163            worker: DurableWorkerConfig::default(),
164            scheduler_tick: Duration::from_secs(1),
165            governance: GovernanceControl::new(),
166            control: ControlPlaneConfig::default().without_socket(),
167            fail_if_sandbox_unavailable: false,
168            clock: Arc::new(SystemClock),
169            proactivity: ProactivityPolicy::default(),
170            quiet_hours: None,
171            quotas: Quotas::default(),
172            cron_jitter: None,
173        }
174    }
175}
176
177impl KernelConfig {
178    /// Sets the proactivity limits (spec 3.2 §7.5).
179    #[must_use]
180    pub fn with_proactivity(mut self, proactivity: ProactivityPolicy) -> Self {
181        self.proactivity = proactivity;
182        self
183    }
184
185    /// Sets the kernel's quiet hours (spec 3.2 §7.2, §7.9).
186    #[must_use]
187    pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
188        self.quiet_hours = Some(quiet_hours);
189        self
190    }
191
192    /// Sets every partition's quotas (spec 3.2 §7.9).
193    #[must_use]
194    pub fn with_quotas(mut self, quotas: Quotas) -> Self {
195        self.quotas = quotas;
196        self
197    }
198
199    /// Delays each cron tick and schedule fire by `jitter` (see
200    /// [`cron_jitter`](Self::cron_jitter)): the kernel's own cron sources, the cron wakes of
201    /// sleepers, a managed tenant's cron sources and the schedule store's `DurableScheduler`.
202    ///
203    /// # Example
204    ///
205    /// ```rust
206    /// use std::time::Duration;
207    /// use adk_core::schedule::Jitter;
208    /// use adk_kernel::KernelConfig;
209    ///
210    /// let config = KernelConfig::default().with_cron_jitter(Jitter::new(15, Duration::from_secs(540)));
211    /// assert_eq!(config.cron_jitter, Some(Jitter::default()));
212    /// ```
213    #[must_use]
214    pub fn with_cron_jitter(mut self, jitter: Jitter) -> Self {
215        self.cron_jitter = Some(jitter);
216        self
217    }
218
219    /// [`cron_jitter`](Self::cron_jitter) salted with the application name, so two kernels
220    /// or tenants whose sources share names spread apart.
221    pub(crate) fn salted_cron_jitter(&self) -> Option<Jitter> {
222        self.cron_jitter.map(|jitter| jitter.salted(&self.app_name))
223    }
224
225    /// The mirrored kill switch's poll interval on multi-replica (K-I8): no backend
226    /// implements `GovernanceWatch`, so the default 2 s poll would miss the one-second bound.
227    pub const GOVERNANCE_POLL: Duration = Duration::from_millis(250);
228
229    /// How long [`Kernel::start`] waits for the first read of a mirrored kill switch before
230    /// it takes work anyway, refusing it until the mirror reads the store.
231    pub const GOVERNANCE_FIRST_READ: Duration = Duration::from_secs(5);
232
233    /// Sets the application runs belong to.
234    #[must_use]
235    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
236        self.app_name = app_name.into();
237        self
238    }
239
240    /// Sets the kernel home.
241    #[must_use]
242    pub fn with_home(mut self, home: impl Into<PathBuf>) -> Self {
243        self.home = home.into();
244        self
245    }
246
247    /// Sets the queue classes.
248    #[must_use]
249    pub fn with_queues(mut self, queues: impl IntoIterator<Item = QueueClass>) -> Self {
250        self.queues = queues.into_iter().collect();
251        self
252    }
253
254    /// Sets the worker configuration every queue's worker starts from.
255    #[must_use]
256    pub fn with_worker(mut self, worker: DurableWorkerConfig) -> Self {
257        self.worker = worker;
258        self
259    }
260
261    /// Sets how often the scheduler looks for due schedules.
262    #[must_use]
263    pub fn with_scheduler_tick(mut self, tick: Duration) -> Self {
264        self.scheduler_tick = tick;
265        self
266    }
267
268    /// Sets the kill switch.
269    #[must_use]
270    pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
271        self.governance = governance;
272        self
273    }
274
275    /// Sets the control plane.
276    #[must_use]
277    pub fn with_control(mut self, control: ControlPlaneConfig) -> Self {
278        self.control = control;
279        self
280    }
281
282    /// Refuses to start a driver where no sandbox enforcer exists.
283    #[must_use]
284    pub fn with_fail_if_sandbox_unavailable(mut self, fail: bool) -> Self {
285        self.fail_if_sandbox_unavailable = fail;
286        self
287    }
288
289    /// Sets the clock the kernel reads, such as a `ManualClock` a test advances.
290    #[must_use]
291    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
292        self.clock = clock;
293        self
294    }
295
296    /// The configuration of the worker for `queue`: [`worker`](Self::worker) with the
297    /// class's queue name, its poll interval (spec 3.2 §7.9, §13 Q2) and a worker id
298    /// suffixed with the queue.
299    pub fn worker_config(&self, queue: &QueueClass) -> DurableWorkerConfig {
300        let worker_id = format!("{}:{}", self.worker.worker_id, queue.as_str());
301        self.worker
302            .clone()
303            .with_worker_id(worker_id)
304            .with_queue(queue.as_str())
305            .with_poll_interval(queue.poll_interval())
306    }
307
308    /// A kill switch mirrored from `store` with the 250 ms poll K-I8 needs, for replicas
309    /// that share one governance store.
310    ///
311    /// # Example
312    ///
313    /// ```rust
314    /// use std::sync::Arc;
315    /// use adk_core::InMemoryGovernanceStateStore;
316    /// use adk_kernel::KernelConfig;
317    ///
318    /// let control = KernelConfig::mirrored_governance(Arc::new(InMemoryGovernanceStateStore::new()));
319    /// assert!(control.is_mirrored());
320    /// ```
321    pub fn mirrored_governance(store: Arc<dyn GovernanceStateStore>) -> GovernanceControl {
322        GovernanceControl::mirrored(
323            store,
324            GovernanceMirrorConfig::default().with_poll_interval(Self::GOVERNANCE_POLL),
325        )
326    }
327}
328
329/// Where the kernel is in its lifecycle (spec 3.2 §7.2).
330///
331/// # Example
332///
333/// ```rust
334/// use adk_kernel::KernelState;
335///
336/// assert_eq!(KernelState::Paused.to_string(), "paused");
337/// ```
338#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
339#[serde(rename_all = "camelCase")]
340#[non_exhaustive]
341pub enum KernelState {
342    /// Built, not started.
343    #[default]
344    Built,
345    /// Workers claim, the scheduler ticks, wake sources deliver.
346    Running,
347    /// Workers do not claim; running processes finish their attempt.
348    Paused,
349    /// Running processes are being suspended at their next checkpoint.
350    Draining,
351    /// Stopped; the control plane is closed.
352    Stopped,
353}
354
355impl fmt::Display for KernelState {
356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357        f.write_str(match self {
358            Self::Built => "built",
359            Self::Running => "running",
360            Self::Paused => "paused",
361            Self::Draining => "draining",
362            Self::Stopped => "stopped",
363        })
364    }
365}
366
367/// The kernel's health (spec 3.2 §7.2): per worker, scheduler lag and store latency.
368///
369/// Driver states join in phase 3.
370///
371/// # Example
372///
373/// ```rust
374/// use adk_kernel::{KernelHealth, KernelState};
375///
376/// let health = KernelHealth::default();
377/// assert_eq!(health.state, KernelState::Built);
378/// assert_eq!(serde_json::to_value(&health).unwrap()["state"], "built");
379/// ```
380#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
381#[serde(rename_all = "camelCase")]
382#[non_exhaustive]
383pub struct KernelHealth {
384    /// The lifecycle state.
385    pub state: KernelState,
386    /// Whether the kill switch is engaged.
387    pub frozen: bool,
388    /// One entry per queue's worker.
389    #[serde(default)]
390    pub workers: Vec<WorkerHealth>,
391    /// How far the scheduler's last tick ran behind its due time.
392    #[serde(
393        default,
394        rename = "schedulerLagMs",
395        skip_serializing_if = "Option::is_none",
396        with = "crate::serde_util::option_millis"
397    )]
398    pub scheduler_lag: Option<Duration>,
399    /// The run store's latest round-trip time.
400    #[serde(
401        default,
402        rename = "storeLatencyMs",
403        skip_serializing_if = "Option::is_none",
404        with = "crate::serde_util::option_millis"
405    )]
406    pub store_latency: Option<Duration>,
407}
408
409/// The runner's code for a run that has not built its context yet, whose plugins cannot
410/// screen a steering message.
411const STEER_RUN_NOT_READY_CODE: &str = "agent.steer.run_not_ready";
412
413/// A message a running process holds for its agent's next safe point (spec 3.3 §6 "steer"):
414/// what [`Kernel::steer`] answers.
415///
416/// The message is delivered when the session holds an event whose steering marker carries
417/// the receipt's steer id; it is handed back when the claim ends without one.
418#[derive(Debug)]
419#[non_exhaustive]
420pub struct Steering {
421    /// The process that holds the message.
422    pub pid: String,
423    /// The lease epoch of the claim that holds it; a later claim of the process never
424    /// delivers it.
425    pub lease_epoch: u64,
426    /// Resolves once the turn takes the message, or ends first and hands it back.
427    pub receipt: adk_core::SteerReceipt,
428}
429
430/// What [`Kernel::run_now`] runs now.
431///
432/// # Example
433///
434/// ```rust
435/// use adk_kernel::RunNowTarget;
436///
437/// let target = RunNowTarget::Trigger { name: "nightly".into() };
438/// assert_eq!(serde_json::to_value(&target).unwrap(), serde_json::json!({"trigger": {"name": "nightly"}}));
439/// ```
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
442#[non_exhaustive]
443pub enum RunNowTarget {
444    /// A process asleep on a cron wake, such as one `adk-rust wake --cron` started.
445    Process {
446        /// The process id.
447        pid: String,
448    },
449    /// A standing trigger on a cron wake.
450    Trigger {
451        /// The trigger's name.
452        name: String,
453    },
454}
455
456/// What [`Kernel::run_now`] queued.
457#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "camelCase")]
459#[non_exhaustive]
460pub struct RunNow {
461    /// The wake's key, [`keys::run_now`].
462    pub key: String,
463    /// The `kernel.wake` run that routes it.
464    pub wake_run_id: String,
465    /// `true` when an earlier request with the same id queued it.
466    pub existing: bool,
467}
468
469/// One worker's health (spec 3.2 §7.2).
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(rename_all = "camelCase")]
472#[non_exhaustive]
473pub struct WorkerHealth {
474    /// The queue class it claims.
475    pub queue: QueueClass,
476    /// The lease owner name it writes.
477    pub worker_id: String,
478    /// Whether its claim loop is running.
479    pub claiming: bool,
480    /// Runs it executes now.
481    pub active_runs: usize,
482}
483
484impl WorkerHealth {
485    /// A worker of `queue` named `worker_id`, not claiming, with no active runs.
486    pub fn new(queue: QueueClass, worker_id: impl Into<String>) -> Self {
487        Self { queue, worker_id: worker_id.into(), claiming: false, active_runs: 0 }
488    }
489}
490
491/// The resident supervisor (spec 3.2 §7.2). Cloning shares the kernel.
492///
493/// # Example
494///
495/// ```rust,no_run
496/// use std::sync::Arc;
497/// use adk_core::InMemoryRunStore;
498/// use adk_kernel::{Kernel, KernelConfig};
499///
500/// # async fn example(runner: Arc<adk_runner::Runner>) -> adk_kernel::Result<()> {
501/// let kernel = Kernel::builder()
502///     .config(KernelConfig::default())
503///     .run_store(Arc::new(InMemoryRunStore::new()))
504///     .agent("adk-rust", runner)
505///     .build()?;
506/// kernel.start().await?;
507/// kernel.shutdown_on_signal().await?;
508/// # Ok(())
509/// # }
510/// ```
511#[derive(Clone)]
512pub struct Kernel {
513    inner: Arc<KernelInner>,
514}
515
516pub(crate) struct KernelInner {
517    config: KernelConfig,
518    sup: Arc<Supervision>,
519    processes: ProcessTable,
520    agenda: Agenda,
521    partitions: Partitions,
522    router: WakeRouter,
523    schedules: Option<Arc<dyn ScheduleStore>>,
524    /// Where each stateful store came from (spec 3.2 §7.1).
525    store_uses: Vec<StoreUse>,
526    approvals: Option<Arc<dyn ApprovalService>>,
527    sessions: Option<Arc<dyn SessionService>>,
528    agents: BTreeMap<String, Arc<Runner>>,
529    /// The agents a person adds (spec 3.3 §5.7, §10 K7).
530    agent_table: crate::agents::Agents,
531    workflows: Option<Arc<dyn WorkflowExecutor>>,
532    wake_sources: Vec<Arc<dyn WakeSource>>,
533    queue_ingresses: Vec<QueueIngress>,
534    /// Whether the agent table can add agents: the builder was given a factory.
535    adds_agents: bool,
536    /// The signal store of each partition the kernel files signals in (spec 3.5 §7.10).
537    #[cfg(feature = "charter")]
538    signal_stores: BTreeMap<PartitionId, Arc<dyn crate::charter::SignalStore>>,
539    /// Warnings the host or a kit added to the inventory.
540    inventory_warnings: Vec<InventoryWarning>,
541    consolidation: Option<ConsolidationTicker>,
542    #[cfg(feature = "drivers")]
543    drivers: Option<crate::drivers::DriverSupervisor>,
544    runtime: tokio::sync::Mutex<Runtime>,
545    status: Arc<RwLock<Status>>,
546    #[cfg(feature = "proc")]
547    ledger: Option<Ledger>,
548    /// The background sub-agent host ([`KernelBuilder::subagents`]).
549    subagents: Option<DurableSubagents>,
550    /// [`control::router`](crate::control::router) built the control plane's routes for a
551    /// server ([`Kernel::serves_routes`]).
552    serves_routes: std::sync::atomic::AtomicBool,
553}
554
555/// What a started kernel runs besides its claim loops.
556#[derive(Default)]
557struct Runtime {
558    stop: Option<CancellationToken>,
559    tasks: Vec<JoinHandle<()>>,
560    control: Option<ControlPlane>,
561    /// Claim loops a pause shut down, finishing their attempts.
562    stopping: Vec<JoinHandle<()>>,
563    /// The kernel is paused by a drain, whose attempts are parked or abandoned, so `stop`
564    /// has nothing left to drain.
565    drained: bool,
566}
567
568/// The health the loops measure, read by [`Kernel::health`].
569#[derive(Debug, Clone, Default)]
570struct Status {
571    state: KernelState,
572    scheduler_lag: Option<Duration>,
573    store_latency: Option<Duration>,
574    active: HashMap<String, usize>,
575}
576
577impl fmt::Debug for Kernel {
578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579        f.debug_struct("Kernel")
580            .field("app_name", &self.inner.config.app_name)
581            .field("home", &self.inner.config.home)
582            .field("queues", &self.inner.config.queues)
583            .field("state", &self.state())
584            .finish_non_exhaustive()
585    }
586}
587
588impl Kernel {
589    /// How long [`shutdown_on_signal`](Self::shutdown_on_signal) drains before it stops.
590    pub const SIGTERM_DRAIN: Duration = Duration::from_secs(30);
591
592    /// A builder.
593    pub fn builder() -> KernelBuilder {
594        KernelBuilder::new()
595    }
596
597    /// The configuration the kernel was built with.
598    pub fn config(&self) -> &KernelConfig {
599        &self.inner.config
600    }
601
602    /// Each stateful store of the kernel: where it came from and whether it is known to be
603    /// held in memory (spec 3.2 §7.1, [`KernelBuilder::require_durable`]).
604    pub fn store_uses(&self) -> &[StoreUse] {
605        &self.inner.store_uses
606    }
607
608    /// What the kernel runs, and a warning for each thing it would silently not do
609    /// ([`KernelInventory`]): logged when the kernel starts and served at
610    /// `GET /api/kernel/inventory`.
611    pub fn inventory(&self) -> KernelInventory {
612        let inner = &self.inner;
613        let mut warnings = Vec::new();
614        #[cfg(feature = "charter")]
615        let signal_partitions: Vec<PartitionId> = inner.signal_stores.keys().cloned().collect();
616        #[cfg(not(feature = "charter"))]
617        let signal_partitions: Vec<PartitionId> = Vec::new();
618        let triggers: Vec<InventoryTrigger> = inner
619            .router
620            .triggers()
621            .iter()
622            .map(|trigger| {
623                let served = self.has_target(&trigger.run.target);
624                if !served {
625                    warnings.push(
626                        InventoryWarning::new(
627                            InventoryWarning::TRIGGER_UNSERVED,
628                            format!(
629                                "trigger `{}` starts `{}`, which no agent or workflow of the \
630                                 kernel serves, so each of its runs fails; register the target \
631                                 or remove the trigger",
632                                trigger.name, trigger.run.target
633                            ),
634                        )
635                        .with_subject(trigger.name.clone()),
636                    );
637                }
638                if let Wake::Signal { kind, partition } = &trigger.wake {
639                    let filed = match partition {
640                        Some(partition) => signal_partitions.contains(partition),
641                        None => !signal_partitions.is_empty(),
642                    };
643                    if !filed {
644                        let place = partition
645                            .as_ref()
646                            .map_or_else(|| "any partition".to_string(), |p| format!("`{p}`"));
647                        warnings.push(
648                            InventoryWarning::new(
649                                InventoryWarning::SIGNAL_UNFILED,
650                                format!(
651                                    "trigger `{}` wakes on `{kind}` signals in {place}, and the \
652                                     kernel files no signals there, so it never fires; register \
653                                     a signal store with KernelBuilder::signals",
654                                    trigger.name
655                                ),
656                            )
657                            .with_subject(trigger.name.clone()),
658                        );
659                    }
660                }
661                InventoryTrigger {
662                    name: trigger.name.clone(),
663                    wake: trigger.wake.clone(),
664                    target: trigger.run.target.clone(),
665                    queue: trigger.run.queue.clone(),
666                    partition: trigger.partition.clone(),
667                    overlap: trigger.overlap,
668                    served,
669                }
670            })
671            .collect();
672        let served = inner.config.control.socket.is_some() || inner.config.control.http.is_some();
673        let mut bundled: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
674        for used in inner.store_uses.iter().filter(|used| used.in_memory) {
675            match (used.origin, &used.bundle) {
676                (StoreOrigin::Bundle, Some(label)) => {
677                    bundled.entry(label.as_str()).or_default().push(used.store.as_str());
678                }
679                // The settings store is read only by a control plane.
680                (StoreOrigin::Defaulted, _) if used.store == "control_store" && !served => {}
681                _ => warnings.push(
682                    InventoryWarning::new(
683                        InventoryWarning::STORE_IN_MEMORY,
684                        format!(
685                            "the kernel keeps its `{}` in memory, so its state ends with the \
686                             process; give the builder durable stores (KernelBuilder::stores) or \
687                             set it with {}",
688                            used.store,
689                            store_remedy(&used.store)
690                        ),
691                    )
692                    .with_subject(used.store.clone()),
693                ),
694            }
695        }
696        for (label, stores) in bundled {
697            warnings.push(
698                InventoryWarning::new(
699                    InventoryWarning::STORE_IN_MEMORY,
700                    format!(
701                        "the stores `{label}` keep {} in memory, so their state ends with the \
702                         process",
703                        stores.join(", ")
704                    ),
705                )
706                .with_subject(label),
707            );
708        }
709        let targets = self.targets();
710        if targets.is_empty()
711            && triggers.is_empty()
712            && inner.schedules.is_none()
713            && inner.workflows.is_none()
714            && !inner.adds_agents
715        {
716            warnings.push(InventoryWarning::new(
717                InventoryWarning::KERNEL_IDLE,
718                "the kernel has nothing to run: no agent, trigger, workflow, schedule store or \
719                 agent factory",
720            ));
721        }
722        warnings.extend(inner.inventory_warnings.iter().cloned());
723        KernelInventory {
724            app_name: inner.config.app_name.clone(),
725            targets,
726            triggers,
727            wake_sources: inner
728                .wake_sources
729                .iter()
730                .map(|source| source.name().to_string())
731                .collect(),
732            schedules: inner.schedules.is_some(),
733            signal_partitions,
734            stores: inner.store_uses.clone(),
735            warnings,
736        }
737    }
738
739    /// The sink that files signals in `partition` (spec 3.5 §7.10; feature `charter`): on
740    /// the kernel's agenda store, wake router, event bus, clock and audit trail, through the
741    /// store [`KernelBuilder::signals`] registered for the partition. Each filed or counted
742    /// signal wakes the [`Wake::Signal`] sleepers and triggers of the partition.
743    ///
744    /// # Errors
745    ///
746    /// Returns [`KernelError::Config`] when no signal store is registered for `partition`.
747    #[cfg(feature = "charter")]
748    pub fn signal_sink(
749        &self,
750        partition: impl Into<PartitionId>,
751    ) -> Result<crate::charter::SignalSink> {
752        let partition = partition.into();
753        let store =
754            self.inner.signal_stores.get(&partition).ok_or_else(|| KernelError::Config {
755                reason: format!(
756                    "the kernel files no signals in partition `{partition}`; register a signal \
757                 store for it with KernelBuilder::signals"
758                ),
759            })?;
760        let sink = crate::charter::SignalSink::for_kernel(self, Arc::clone(store), partition);
761        Ok(match &self.inner.sup.audit {
762            Some(trail) => sink.with_audit(trail.clone()),
763            None => sink,
764        })
765    }
766
767    fn state(&self) -> KernelState {
768        self.inner.status.read().unwrap_or_else(|e| e.into_inner()).state
769    }
770
771    fn set_state(&self, state: KernelState) {
772        self.inner.status.write().unwrap_or_else(|e| e.into_inner()).state = state;
773    }
774
775    fn lifecycle_fields(&self, reason: Option<&str>) -> serde_json::Value {
776        json!({
777            "kernelId": self.inner.sup.kernel_id,
778            "home": self.inner.config.home,
779            "replicas": serde_json::Value::Null,
780            "reason": reason,
781        })
782    }
783
784    async fn record_lifecycle(&self, action: &str, reason: Option<&str>) {
785        let sup = &self.inner.sup;
786        sup.record(action, sup.actor_for(None), self.lifecycle_fields(reason)).await;
787    }
788
789    /// Starts a claim loop for every queue class.
790    fn spawn_workers(&self) {
791        let sup = &self.inner.sup;
792        let mut handles = sup.handles.lock().unwrap_or_else(|e| e.into_inner());
793        for (queue, worker) in sup.workers() {
794            handles.push((queue.clone(), worker.clone().spawn()));
795        }
796    }
797
798    /// Starts the workers, scheduler, wake sources and control plane, after reconciling
799    /// the wakes missed while the kernel was down. Records `kernel.started`.
800    ///
801    /// A mirrored kill switch is read before anything else, for at most
802    /// [`KernelConfig::GOVERNANCE_FIRST_READ`], so work spawned once `start` returns is
803    /// decided by the store's state rather than refused as never read. A store that cannot be
804    /// read in that time leaves the control stale: the kernel starts and refuses work until
805    /// its mirror reads the store.
806    ///
807    /// Processes a drain parked are woken first, and those a freeze parked when the control
808    /// allows work again.
809    ///
810    /// # Errors
811    ///
812    /// Returns [`KernelError::Lifecycle`] when the kernel already runs,
813    /// [`KernelError::ControlPlane`] when the socket or bind is taken, or a store error.
814    pub async fn start(&self) -> Result<()> {
815        let mut runtime = self.inner.runtime.lock().await;
816        let state = self.state();
817        if !matches!(state, KernelState::Built | KernelState::Stopped) {
818            return Err(KernelError::Lifecycle { state, action: "start" });
819        }
820        let sup = Arc::clone(&self.inner.sup);
821        let config = &self.inner.config;
822        let governance = &config.governance;
823        if let Some(trail) = &sup.audit
824            && governance.audit().is_none()
825        {
826            governance.attach_audit(trail.clone());
827        }
828        let stop = CancellationToken::new();
829        let mut tasks = Vec::new();
830        // Until a mirrored control's first read, `check` refuses all work and `is_frozen`
831        // reads a freeze in force as lifted.
832        match tokio::time::timeout(KernelConfig::GOVERNANCE_FIRST_READ, governance.refresh()).await
833        {
834            Ok(Ok(())) => {}
835            Ok(Err(error)) => tracing::warn!(
836                error = %error,
837                "could not read the governance store; work is refused until it is read"
838            ),
839            Err(_) => tracing::warn!(
840                timeout.ms = KernelConfig::GOVERNANCE_FIRST_READ.as_millis() as u64,
841                "the governance store did not answer; work is refused until it is read"
842            ),
843        }
844        if let Some(mirror) = governance.spawn_mirror() {
845            tasks.push(mirror);
846        }
847        sup.draining.store(false, Ordering::SeqCst);
848        // Sleepers' cron occurrences missed while stopped are planned from the stored cursors.
849        sup.crons.lock().unwrap_or_else(|e| e.into_inner()).clear();
850        *sup.cron_started.lock().unwrap_or_else(|e| e.into_inner()) = None;
851        for progress in sup.progress_sources() {
852            progress.attach(ProcessHandle::new(&sup));
853            #[cfg(feature = "proc")]
854            if let Some(ledger) = &self.inner.ledger {
855                progress.attach_ledger(Arc::new(ledger.clone()));
856            }
857        }
858        for partition in sup.partition_progress.keys() {
859            if matches!(sup.partitions.get(partition).await, Ok(None)) {
860                tracing::warn!(
861                    partition = %partition,
862                    "a progress source is registered for a partition the partition table does not hold"
863                );
864            }
865        }
866        if governance.check().is_ok() {
867            sup.wake_suspended(&Suspension::Freeze).await;
868        }
869        sup.wake_suspended(&Suspension::Drain).await;
870        #[cfg(feature = "drivers")]
871        if let Some(drivers) = &self.inner.drivers {
872            drivers.attach(
873                &sup.bus,
874                sup.audit.as_ref(),
875                &sup.kernel_id,
876                &config.app_name,
877                &config.home,
878                config.fail_if_sandbox_unavailable,
879            );
880            if let Err(error) = drivers.start().await {
881                tracing::warn!(error = %error, "could not load the mounted drivers");
882            }
883        }
884        match self.inner.router.reconcile().await {
885            Ok(outcomes) if !outcomes.is_empty() => {
886                tracing::info!(
887                    wakes = outcomes.len(),
888                    "woke processes for changes missed while the kernel was down"
889                );
890            }
891            Ok(_) => {}
892            Err(error) => tracing::warn!(error = %error, "could not reconcile missed wakes"),
893        }
894        // Every active added agent is built before the first claim (spec 3.3 §5.7).
895        if let Err(error) = self.inner.agent_table.reconcile().await {
896            tracing::warn!(error = %error, "could not host the added agents yet; the next tick retries");
897        }
898        self.spawn_workers();
899        if let Some(subagents) = self.inner.subagents.clone() {
900            // A parent is told about a sub-agent that finished while no kernel ran.
901            tasks.push(tokio::spawn(async move {
902                match subagents.reconcile().await {
903                    Ok(looked) => {
904                        tracing::debug!(subagents.looked = looked, "sub-agent notices reconciled")
905                    }
906                    Err(error) => {
907                        tracing::warn!(error = %error, "could not reconcile sub-agent notices")
908                    }
909                }
910            }));
911        }
912        if let Some(schedules) = &self.inner.schedules {
913            let mut scheduler = DurableScheduler::new(Arc::clone(schedules), Arc::clone(&sup.runs))
914                .with_governance(governance.clone())
915                .with_clock(Arc::clone(&config.clock));
916            if let Some(jitter) = config.salted_cron_jitter() {
917                scheduler = scheduler.with_jitter(jitter);
918            }
919            tasks.push(spawn_scheduler(
920                scheduler,
921                Arc::clone(&sup),
922                config.scheduler_tick,
923                Arc::clone(&self.inner.status),
924                stop.clone(),
925            ));
926        }
927        for source in &self.inner.wake_sources {
928            tasks.push(spawn_wake_source(
929                Arc::clone(source),
930                Arc::clone(&sup),
931                self.inner.router.clone(),
932                stop.clone(),
933            ));
934        }
935        for ingress in &self.inner.queue_ingresses {
936            tasks.push(spawn_queue_ingress(ingress.clone(), Arc::clone(&sup), stop.clone()));
937        }
938        if let Some(approvals) = &self.inner.approvals {
939            // Inbox requests expire by the kernel's clock, as its agenda items and wakes do:
940            // an item's request carries the item's expiry.
941            let approvals = Arc::clone(approvals);
942            let clock = Arc::clone(&config.clock);
943            let every = config.scheduler_tick;
944            tasks.push(tokio::spawn(async move {
945                let mut timer = tokio::time::interval(every);
946                timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
947                loop {
948                    timer.tick().await;
949                    match approvals.tick(clock.now()).await {
950                        Ok(report) if report.expired.is_empty() && report.escalated.is_empty() => {}
951                        Ok(report) => tracing::info!(
952                            approvals.expired = report.expired.len(),
953                            approvals.escalated = report.escalated.len(),
954                            "approval tick"
955                        ),
956                        Err(error) => tracing::warn!(error = %error, "approval tick failed"),
957                    }
958                }
959            }));
960        }
961        tasks.push(spawn_mirror(Arc::clone(&sup), stop.clone()));
962        tasks.push(spawn_file_watch(
963            Arc::clone(&sup),
964            self.inner.router.clone(),
965            config.scheduler_tick,
966            stop.clone(),
967        ));
968        tasks.push(spawn_maintenance(
969            Arc::clone(&sup),
970            self.inner.router.clone(),
971            Ticks {
972                agenda: self.inner.agenda.clone(),
973                agents: self.inner.agent_table.clone(),
974                consolidation: self.inner.consolidation.clone(),
975            },
976            Arc::clone(&self.inner.status),
977            config.scheduler_tick,
978            stop.clone(),
979        ));
980        if config.control.socket.is_some() || config.control.http.is_some() {
981            match ControlPlane::start(self).await {
982                Ok(plane) => runtime.control = Some(plane),
983                Err(error) => {
984                    stop.cancel();
985                    for task in tasks {
986                        task.abort();
987                    }
988                    let handles: Vec<_> =
989                        sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
990                    for (_, handle) in handles {
991                        handle.shutdown().await;
992                    }
993                    return Err(error);
994                }
995            }
996        }
997        runtime.stop = Some(stop);
998        runtime.tasks = tasks;
999        drop(runtime);
1000        self.set_state(KernelState::Running);
1001        self.record_lifecycle(audit::KERNEL_STARTED, None).await;
1002        sup.publish(KernelEvent::Health(self.health()));
1003        let inventory = self.inventory();
1004        tracing::info!(
1005            kernel.app = %inventory.app_name,
1006            kernel.targets = ?inventory.targets,
1007            kernel.triggers = inventory.triggers.len(),
1008            kernel.wake_sources = inventory.wake_sources.len(),
1009            kernel.schedules = inventory.schedules,
1010            kernel.warnings = inventory.warnings.len(),
1011            "kernel started"
1012        );
1013        for warning in &inventory.warnings {
1014            tracing::warn!(
1015                kernel.warning = %warning.code,
1016                kernel.subject = warning.subject.as_deref().unwrap_or_default(),
1017                "{}",
1018                warning.message
1019            );
1020        }
1021        Ok(())
1022    }
1023
1024    /// Stops claiming; running processes run their attempt to its end. Records
1025    /// `kernel.paused`.
1026    ///
1027    /// # Errors
1028    ///
1029    /// Returns [`KernelError::Lifecycle`] when the kernel is not running.
1030    pub async fn pause(&self) -> Result<()> {
1031        let mut runtime = self.inner.runtime.lock().await;
1032        let state = self.state();
1033        if state != KernelState::Running {
1034            return Err(KernelError::Lifecycle { state, action: "pause" });
1035        }
1036        let handles: Vec<_> =
1037            self.inner.sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
1038        for (_, handle) in handles {
1039            runtime.stopping.push(tokio::spawn(handle.shutdown()));
1040        }
1041        drop(runtime);
1042        self.set_state(KernelState::Paused);
1043        self.record_lifecycle(audit::KERNEL_PAUSED, None).await;
1044        Ok(())
1045    }
1046
1047    /// Claims again after [`pause`](Self::pause) or [`drain`](Self::drain), waking the
1048    /// processes a drain parked. Records `kernel.resumed`.
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns [`KernelError::Lifecycle`] when the kernel is not paused.
1053    pub async fn resume(&self) -> Result<()> {
1054        let mut runtime = self.inner.runtime.lock().await;
1055        let state = self.state();
1056        if state != KernelState::Paused {
1057            return Err(KernelError::Lifecycle { state, action: "resume" });
1058        }
1059        self.spawn_workers();
1060        self.inner.sup.wake_suspended(&Suspension::Drain).await;
1061        runtime.drained = false;
1062        self.set_state(KernelState::Running);
1063        self.record_lifecycle(audit::KERNEL_RESUMED, None).await;
1064        Ok(())
1065    }
1066
1067    /// Suspends running processes at their next checkpoint through S1's suspend path
1068    /// ([`Suspension::Drain`]), then stops claiming; on
1069    /// `timeout` aborts the claim loops so their leases lapse. Records `kernel.drained`.
1070    /// The kernel is paused afterwards: [`resume`](Self::resume) or a later
1071    /// [`start`](Self::start) wakes what the drain parked.
1072    ///
1073    /// # Errors
1074    ///
1075    /// Returns [`KernelError::Lifecycle`] when the kernel is not running or paused, or a
1076    /// store error.
1077    pub async fn drain(&self, timeout: Duration) -> Result<()> {
1078        let mut runtime = self.inner.runtime.lock().await;
1079        let state = self.state();
1080        if !matches!(state, KernelState::Running | KernelState::Paused) {
1081            return Err(KernelError::Lifecycle { state, action: "drain" });
1082        }
1083        self.set_state(KernelState::Draining);
1084        let sup = &self.inner.sup;
1085        sup.draining.store(true, Ordering::SeqCst);
1086        let ours = sup.local_worker_ids();
1087        let deadline = tokio::time::Instant::now() + timeout;
1088        let mut busy;
1089        loop {
1090            busy = 0;
1091            for run in sup.running().await {
1092                if run.lease_owner.as_ref().is_some_and(|owner| ours.contains(owner)) {
1093                    busy += 1;
1094                    sup.suspend_local(&run.run_id);
1095                }
1096            }
1097            if busy == 0 || tokio::time::Instant::now() >= deadline {
1098                break;
1099            }
1100            tokio::time::sleep(DRAIN_POLL).await;
1101        }
1102        let handles: Vec<_> =
1103            sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
1104        if busy == 0 {
1105            for (_, handle) in handles {
1106                handle.shutdown().await;
1107            }
1108        } else {
1109            tracing::warn!(
1110                runs = busy,
1111                "drain timed out; dropping the attempts still running so their leases lapse"
1112            );
1113            for (_, handle) in &handles {
1114                handle.abort();
1115            }
1116        }
1117        for stopping in runtime.stopping.drain(..) {
1118            if busy == 0 {
1119                let _ = stopping.await;
1120            } else {
1121                stopping.abort();
1122            }
1123        }
1124        runtime.drained = true;
1125        drop(runtime);
1126        sup.draining.store(false, Ordering::SeqCst);
1127        self.set_state(KernelState::Paused);
1128        let reason = (busy > 0).then_some("timeout");
1129        self.record_lifecycle(audit::KERNEL_DRAINED, reason).await;
1130        Ok(())
1131    }
1132
1133    /// Drains for [`SIGTERM_DRAIN`](Self::SIGTERM_DRAIN), unless a [`drain`](Self::drain)
1134    /// already paused the kernel, stops drivers and closes the control plane. Records
1135    /// `kernel.stopped`.
1136    ///
1137    /// # Errors
1138    ///
1139    /// Returns a store or control-plane error; the kernel is stopped regardless.
1140    pub async fn stop(&self) -> Result<()> {
1141        let mut first_error = None;
1142        let drained = self.inner.runtime.lock().await.drained;
1143        let drains = match self.state() {
1144            KernelState::Running => true,
1145            KernelState::Paused => !drained,
1146            KernelState::Built | KernelState::Draining | KernelState::Stopped => false,
1147        };
1148        if drains && let Err(error) = self.drain(Self::SIGTERM_DRAIN).await {
1149            first_error = Some(error);
1150        }
1151        let mut runtime = self.inner.runtime.lock().await;
1152        if let Some(stop) = runtime.stop.take() {
1153            stop.cancel();
1154        }
1155        for task in runtime.tasks.drain(..) {
1156            task.abort();
1157        }
1158        for task in runtime.stopping.drain(..) {
1159            task.abort();
1160        }
1161        let watched: Vec<_> =
1162            std::mem::take(&mut *self.inner.sup.watched.lock().unwrap_or_else(|e| e.into_inner()))
1163                .into_values()
1164                .collect();
1165        for task in watched {
1166            task.abort();
1167        }
1168        let handles: Vec<_> =
1169            self.inner.sup.handles.lock().unwrap_or_else(|e| e.into_inner()).drain(..).collect();
1170        for (_, handle) in &handles {
1171            handle.abort();
1172        }
1173        if let Some(plane) = runtime.control.take()
1174            && let Err(error) = plane.shutdown().await
1175        {
1176            first_error.get_or_insert(error);
1177        }
1178        #[cfg(feature = "drivers")]
1179        if let Some(drivers) = &self.inner.drivers {
1180            drivers.shutdown().await;
1181        }
1182        // The agents a person added close with the kernel (spec 3.3 §5.7).
1183        self.inner.agent_table.close_hosted().await;
1184        runtime.drained = false;
1185        drop(runtime);
1186        let was = self.state();
1187        self.set_state(KernelState::Stopped);
1188        if was != KernelState::Stopped && was != KernelState::Built {
1189            self.record_lifecycle(audit::KERNEL_STOPPED, None).await;
1190        }
1191        first_error.map_or(Ok(()), Err)
1192    }
1193
1194    /// Waits for `SIGTERM` or Ctrl-C — or, in a Windows service, the service manager's stop
1195    /// (spec 3.2 §10 W3) — then [`stop`](Self::stop)s, which drains once for
1196    /// [`SIGTERM_DRAIN`](Self::SIGTERM_DRAIN).
1197    ///
1198    /// # Errors
1199    ///
1200    /// Returns the error of `stop`, or [`KernelError::Io`] when the signal
1201    /// handler cannot be installed.
1202    pub async fn shutdown_on_signal(&self) -> Result<()> {
1203        #[cfg(unix)]
1204        {
1205            let mut terminate =
1206                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
1207            tokio::select! {
1208                result = tokio::signal::ctrl_c() => result?,
1209                _ = terminate.recv() => {}
1210            }
1211        }
1212        #[cfg(all(not(unix), feature = "service"))]
1213        tokio::select! {
1214            result = tokio::signal::ctrl_c() => result?,
1215            () = crate::service::stop_requested() => {}
1216        }
1217        #[cfg(all(not(unix), not(feature = "service")))]
1218        tokio::signal::ctrl_c().await?;
1219        tracing::info!("shutdown signal received; draining the kernel");
1220        self.stop().await
1221    }
1222
1223    /// Freezes execution as `by`: `GovernanceControl::freeze_recorded`, then the running
1224    /// processes park `Waiting` at their next checkpoint with
1225    /// [`Suspension::Freeze`], one `kernel.process.suspended`
1226    /// record each, on every replica within one second (K-I8). No process starts until
1227    /// [`unfreeze`](Self::unfreeze).
1228    ///
1229    /// # Errors
1230    ///
1231    /// Returns the control's error when the freeze cannot be recorded; this replica is
1232    /// frozen regardless.
1233    pub async fn freeze(&self, reason: &str, by: AuditActor) -> Result<()> {
1234        self.inner.config.governance.freeze_recorded(reason, by).await?;
1235        Ok(())
1236    }
1237
1238    /// Lifts the freeze as `by`: `GovernanceControl::unfreeze_recorded`, then wakes exactly
1239    /// the processes the freeze parked, never a manual or preempted suspension (K-I21).
1240    ///
1241    /// # Errors
1242    ///
1243    /// Returns the control's error when the unfreeze cannot be recorded; execution stays
1244    /// frozen.
1245    pub async fn unfreeze(&self, by: AuditActor) -> Result<()> {
1246        self.inner.config.governance.unfreeze_recorded(by).await?;
1247        let sup = &self.inner.sup;
1248        for (_, worker) in sup.workers() {
1249            worker.wake_frozen().await;
1250        }
1251        sup.wake_suspended(&Suspension::Freeze).await;
1252        sup.nudge();
1253        Ok(())
1254    }
1255
1256    /// Runs a cron sleeper or a standing cron trigger now, outside its schedule, for `by`.
1257    ///
1258    /// The run now is a wake like a tick's: an event keyed [`keys::run_now`] that becomes its
1259    /// `kernel.wake` run, so a retried request with the same `request_id` routes once, and the
1260    /// router wakes the sleeper, or fires the trigger, as a tick would. The woken run passes
1261    /// admission like any other: quiet hours defer it, a spent budget parks it, a quota holds
1262    /// it. The schedule is untouched: no watermark moves, the next tick fires as planned, and
1263    /// a recurring sleeper's successor sleeps on the same cron wake after the run. The turn
1264    /// is told it was run now: its wake reason's payload carries `run_now`, the expression
1265    /// and who asked. The call is recorded as `kernel.run_now`.
1266    ///
1267    /// A run now of a trigger follows the trigger's [`WakeOverlap`](crate::WakeOverlap) as a
1268    /// tick does: while a process the trigger started is unfinished, `skip` refuses it here,
1269    /// `queueOne` queues one behind it or joins the one already waiting, and `queue` queues
1270    /// behind it.
1271    ///
1272    /// | Target | Must be |
1273    /// |---|---|
1274    /// | [`RunNowTarget::Process`] | `Waiting`, not suspended, its wake set holding a cron wake |
1275    /// | [`RunNowTarget::Trigger`] | A standing trigger of this kernel on a cron wake |
1276    ///
1277    /// # Example
1278    ///
1279    /// ```rust,no_run
1280    /// use adk_core::audit_log::AuditActor;
1281    /// use adk_kernel::{Kernel, RunNowTarget};
1282    ///
1283    /// # async fn example(kernel: Kernel) -> adk_kernel::Result<()> {
1284    /// let run_now = kernel
1285    ///     .run_now(RunNowTarget::Trigger { name: "nightly-digest".into() }, None, AuditActor::default())
1286    ///     .await?;
1287    /// println!("queued {}", run_now.key);
1288    /// # Ok(())
1289    /// # }
1290    /// ```
1291    ///
1292    /// # Errors
1293    ///
1294    /// Returns [`KernelError::Frozen`] while the kill switch refuses work, so nothing is
1295    /// queued; [`KernelError::NotFound`] or [`KernelError::InvalidState`] for a process that
1296    /// is missing or not asleep on a cron wake; [`KernelError::Config`] for a name no cron
1297    /// trigger has; [`KernelError::InvalidState`], naming the unfinished process, for a
1298    /// trigger whose overlap is `skip`; or a store error.
1299    pub async fn run_now(
1300        &self,
1301        target: RunNowTarget,
1302        request_id: Option<&str>,
1303        by: AuditActor,
1304    ) -> Result<RunNow> {
1305        let governance = &self.inner.config.governance;
1306        if let Err(error) = governance.check() {
1307            return Err(KernelError::Frozen {
1308                reason: governance.reason().unwrap_or(error.message),
1309            });
1310        }
1311        let sup = &self.inner.sup;
1312        let (key_target, expression, mut payload) = match &target {
1313            RunNowTarget::Process { pid } => {
1314                let run = sup
1315                    .runs
1316                    .get(pid)
1317                    .await?
1318                    .ok_or_else(|| KernelError::NotFound { pid: pid.clone() })?;
1319                let meta = sup.processes.get(pid).await?;
1320                let cron =
1321                    meta.as_ref().filter(|meta| meta.suspended_by.is_none()).and_then(|meta| {
1322                        meta.wake.iter().flat_map(|wake| wake.any_of.iter()).find_map(|wake| {
1323                            match wake {
1324                                Wake::Cron { expr, .. } => Some(expr.clone()),
1325                                _ => None,
1326                            }
1327                        })
1328                    });
1329                let Some(expression) = cron.filter(|_| run.state == adk_core::RunState::Waiting)
1330                else {
1331                    return Err(KernelError::InvalidState {
1332                        pid: pid.clone(),
1333                        state: run.state,
1334                        action: "run now (it is not asleep on a cron wake; `adk-rust resume` \
1335                                 wakes any sleeper)",
1336                    });
1337                };
1338                (pid.clone(), expression, json!({ "pid": pid }))
1339            }
1340            RunNowTarget::Trigger { name } => {
1341                let expression = self.inner.router.triggers().iter().find_map(|trigger| {
1342                    match (&trigger.wake, trigger.name == *name) {
1343                        (Wake::Cron { expr, .. }, true) => Some(expr.clone()),
1344                        _ => None,
1345                    }
1346                });
1347                let Some(expression) = expression else {
1348                    return Err(KernelError::Config {
1349                        reason: format!(
1350                            "no standing trigger `{name}` on a cron wake; `adk-rust inventory` \
1351                             lists the kernel's triggers"
1352                        ),
1353                    });
1354                };
1355                // Under `skip`, a run now while the trigger's process is unfinished would start
1356                // nothing; say so now rather than queue a wake that does nothing.
1357                if let Some(blocking) = self.inner.router.skips_run_now(name).await? {
1358                    return Err(KernelError::InvalidState {
1359                        pid: blocking.run_id,
1360                        state: blocking.state,
1361                        action: "joined by a run now of its trigger, whose overlap is `skip` \
1362                                 (let it finish, or `adk-rust kill` it)",
1363                    });
1364                }
1365                (format!("trigger:{name}"), expression, json!({ "trigger": name }))
1366            }
1367        };
1368        let request_id =
1369            request_id.map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_string);
1370        let key = keys::run_now(&key_target, &request_id);
1371        if let serde_json::Value::Object(fields) = &mut payload {
1372            fields.insert("run_now".into(), json!(true));
1373            fields.insert("expression".into(), json!(expression));
1374            fields.insert("requested_by".into(), json!(by.on_behalf_of));
1375        }
1376        let event = WakeEvent::new(crate::wake::RUN_NOW_SOURCE, key.clone(), payload);
1377        let (wake_run_id, existing) =
1378            match self.inner.router.submit(&event, &self.inner.config.app_name).await? {
1379                Enqueued::Created(run) => (run.run_id, false),
1380                Enqueued::Existing(run) => (run.run_id, true),
1381                Enqueued::Rejected { blocking_run_id } => {
1382                    return Err(KernelError::Config {
1383                        reason: format!(
1384                            "the run now `{key}` was refused by run {blocking_run_id}'s \
1385                             concurrency key"
1386                        ),
1387                    });
1388                }
1389            };
1390        sup.nudge();
1391        sup.record(
1392            audit::RUN_NOW,
1393            by,
1394            json!({ "target": target, "key": key, "expression": expression, "wakeRun": wake_run_id, "existing": existing }),
1395        )
1396        .await;
1397        tracing::info!(run_now.key = %key, run_now.existing = existing, "run now queued");
1398        Ok(RunNow { key, wake_run_id, existing })
1399    }
1400
1401    /// Sends `text` to the turn of `user_id`'s session `session_id` that this replica runs
1402    /// (spec 3.3 §6 "steer"): `Runner::steer` on the runner of the process's target, so the
1403    /// message is screened as a turn's own message is and the agent takes it at its next safe
1404    /// point.
1405    ///
1406    /// Returns `None` when no turn of the session takes messages here: none runs, another
1407    /// replica runs it, its target is a workflow, or its run has not reached its agent yet.
1408    /// Send the message as the session's next message then. An added agent's turn that
1409    /// started before the agent was changed finishes on the build it started on, which is no
1410    /// longer hosted, so it answers `None` too.
1411    ///
1412    /// # Errors
1413    ///
1414    /// Returns [`KernelError::Frozen`] while everything is stopped, or the runner's error
1415    /// when `text` is blank or an input guardrail or plugin refuses the message.
1416    ///
1417    /// # Example
1418    ///
1419    /// ```rust,no_run
1420    /// use adk_core::SteerOutcome;
1421    ///
1422    /// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
1423    /// match kernel.steer("ana", "s-1", "use the staging database").await? {
1424    ///     Some(steering) => match steering.receipt.outcome().await? {
1425    ///         SteerOutcome::Delivered { event_id } => println!("delivered as {event_id}"),
1426    ///         SteerOutcome::Returned(_) => println!("send it as the next message"),
1427    ///     },
1428    ///     None => println!("no turn runs here: send it as the next message"),
1429    /// }
1430    /// # Ok(())
1431    /// # }
1432    /// ```
1433    pub async fn steer(
1434        &self,
1435        user_id: &str,
1436        session_id: &str,
1437        text: &str,
1438    ) -> Result<Option<Steering>> {
1439        let governance = &self.inner.config.governance;
1440        if governance.is_frozen() {
1441            return Err(KernelError::Frozen { reason: governance.reason().unwrap_or_default() });
1442        }
1443        let message = adk_core::Content::new("user").with_text(text);
1444        adk_core::validate_steering_message(&message)?;
1445        let sup = &self.inner.sup;
1446        // The newest claim of the session on this replica; the session is the one its worker
1447        // runs the claim in, `run-{pid}` for a process spawned without one.
1448        let claimed = {
1449            let local = sup.local.lock().unwrap_or_else(|e| e.into_inner());
1450            local
1451                .values()
1452                .filter(|claim| {
1453                    let run = &claim.run;
1454                    run.app_name == sup.app_name
1455                        && run.user_id == user_id
1456                        && crate::supervise::run_session(run) == session_id
1457                })
1458                .max_by_key(|claim| claim.claimed_at)
1459                .map(|claim| claim.run.clone())
1460        };
1461        let Some(run) = claimed else { return Ok(None) };
1462        let runner = match self.inner.agents.get(&run.target) {
1463            Some(runner) => Arc::clone(runner),
1464            None => match sup.targets.hosted(&run.target) {
1465                Some(added) => added.runner,
1466                None => return Ok(None),
1467            },
1468        };
1469        let identity = adk_core::AdkIdentity::new(
1470            adk_core::AppName::try_from(runner.app_name()).map_err(adk_core::AdkError::from)?,
1471            adk_core::UserId::try_from(user_id).map_err(adk_core::AdkError::from)?,
1472            adk_core::SessionId::try_from(session_id).map_err(adk_core::AdkError::from)?,
1473        );
1474        match runner.steer(&identity, message).await {
1475            Ok(receipt) => {
1476                Ok(Some(Steering { pid: run.run_id, lease_epoch: run.lease_epoch, receipt }))
1477            }
1478            // The claim has not started its run, or the run ended meanwhile.
1479            Err(error)
1480                if error.code == adk_core::STEER_NO_ACTIVE_RUN_CODE
1481                    || error.code == STEER_RUN_NOT_READY_CODE =>
1482            {
1483                Ok(None)
1484            }
1485            Err(error) => Err(error.into()),
1486        }
1487    }
1488
1489    /// The process table.
1490    pub fn processes(&self) -> &ProcessTable {
1491        &self.inner.processes
1492    }
1493
1494    /// The background sub-agent host, when the kernel was built with
1495    /// [`KernelBuilder::subagents`].
1496    pub fn subagents(&self) -> Option<&DurableSubagents> {
1497        self.inner.subagents.as_ref()
1498    }
1499
1500    pub(crate) fn from_inner(inner: Arc<KernelInner>) -> Self {
1501        Self { inner }
1502    }
1503
1504    /// The agenda (spec 3.2 §7.5).
1505    pub fn agenda(&self) -> &Agenda {
1506        &self.inner.agenda
1507    }
1508
1509    /// The partition table and its crossings (spec 3.2 §7.8).
1510    pub fn partitions(&self) -> &Partitions {
1511        &self.inner.partitions
1512    }
1513
1514    /// The partition the target `target` is bound to, when it is a partition agent's.
1515    pub fn partition_of_target(&self, target: &str) -> Option<&PartitionId> {
1516        self.inner.sup.targets.statics().get(target)
1517    }
1518
1519    /// The agents a person adds, by asking or by hand (spec 3.3 §5.7, §10 K7): every
1520    /// change to one goes through this table.
1521    pub fn agents(&self) -> &crate::agents::Agents {
1522        &self.inner.agent_table
1523    }
1524
1525    /// The event bus.
1526    pub fn bus(&self) -> &EventBus {
1527        &self.inner.sup.bus
1528    }
1529
1530    /// The wake matcher.
1531    pub fn wake_router(&self) -> &WakeRouter {
1532        &self.inner.router
1533    }
1534
1535    /// The address the control plane's HTTP listener is bound to while the kernel runs, so
1536    /// a bind on port 0 is discoverable (spec 3.2 §7.11, spec 3.5 §8.2); `None` when the
1537    /// control plane serves no HTTP or the kernel is not running.
1538    ///
1539    /// # Example
1540    ///
1541    /// ```rust,ignore
1542    /// let control = ControlPlaneConfig::default().without_socket().with_http("127.0.0.1:0".parse()?);
1543    /// kernel.start().await?;
1544    /// let addr = kernel.control_addr().await.expect("the control plane listens");
1545    /// ```
1546    pub async fn control_addr(&self) -> Option<std::net::SocketAddr> {
1547        self.inner.runtime.lock().await.control.as_ref().and_then(ControlPlane::http_addr)
1548    }
1549
1550    /// The content-free activity ledger the kernel writes, when it was built with one
1551    /// (spec 3.2 §7.10, feature `proc`).
1552    #[cfg(feature = "proc")]
1553    pub fn ledger(&self) -> Option<&Ledger> {
1554        self.inner.ledger.as_ref()
1555    }
1556
1557    /// Whether [`control::router`](crate::control::router) built this kernel's control-plane
1558    /// routes for a server, so a page served beside them may read them: the web home reads
1559    /// `/api/kernel` only then (spec 3.3 §10).
1560    ///
1561    /// # Example
1562    ///
1563    /// ```rust,no_run
1564    /// # fn example(kernel: adk_kernel::Kernel) {
1565    /// assert!(!kernel.serves_routes());
1566    /// let _routes = adk_kernel::control::router(kernel.clone());
1567    /// assert!(kernel.serves_routes());
1568    /// # }
1569    /// ```
1570    pub fn serves_routes(&self) -> bool {
1571        self.inner.serves_routes.load(std::sync::atomic::Ordering::Relaxed)
1572    }
1573
1574    /// Records that the control plane's routes were built for a server.
1575    pub(crate) fn mark_routes_served(&self) {
1576        self.inner.serves_routes.store(true, std::sync::atomic::Ordering::Relaxed);
1577    }
1578
1579    /// What every kernel part shares, for the routes the surfaces need (spec 3.3 §10 K3,
1580    /// K4).
1581    pub(crate) fn supervision(&self) -> &Arc<Supervision> {
1582        &self.inner.sup
1583    }
1584
1585    /// The end of the quiet time that holds `at` in `partition`, followed through windows
1586    /// that touch; `None` when `at` is not quiet (spec 3.3 §5.4, §10 K3). It reads the
1587    /// windows in force now: the kernel's, the proactivity policy's and the partition's own,
1588    /// with a quiet time the person changed while the kernel runs in place of the kernel's and
1589    /// the partition's. A phone's wake-up waits for it.
1590    ///
1591    /// # Example
1592    ///
1593    /// ```rust,no_run
1594    /// # async fn example(kernel: adk_kernel::Kernel) {
1595    /// use adk_kernel::PartitionId;
1596    ///
1597    /// if let Some(until) = kernel.quiet_until(&PartitionId::default(), chrono::Utc::now()).await {
1598    ///     println!("quiet until {until}");
1599    /// }
1600    /// # }
1601    /// ```
1602    pub async fn quiet_until(
1603        &self,
1604        partition: &PartitionId,
1605        at: chrono::DateTime<chrono::Utc>,
1606    ) -> Option<chrono::DateTime<chrono::Utc>> {
1607        let windows = self.inner.sup.quiet_windows(partition).await;
1608        let mut until = at;
1609        // Two windows release into each other at most once each.
1610        for _ in 0..=windows.len() {
1611            match windows
1612                .iter()
1613                .filter(|quiet| quiet.contains(until))
1614                .map(|quiet| quiet.release_at(until))
1615                .max()
1616            {
1617                Some(next) if next > until => until = next,
1618                _ => break,
1619            }
1620        }
1621        (until > at).then_some(until)
1622    }
1623
1624    /// Subscribes to the event bus from now on.
1625    pub fn events(&self) -> EventSubscriber {
1626        self.inner.sup.bus.subscribe()
1627    }
1628
1629    /// The kernel's health: per worker, scheduler lag, store latency.
1630    pub fn health(&self) -> KernelHealth {
1631        let status = self.inner.status.read().unwrap_or_else(|e| e.into_inner()).clone();
1632        let sup = &self.inner.sup;
1633        let claiming: Vec<QueueClass> = sup
1634            .handles
1635            .lock()
1636            .unwrap_or_else(|e| e.into_inner())
1637            .iter()
1638            .filter(|(_, handle)| !handle.is_finished())
1639            .map(|(queue, _)| queue.clone())
1640            .collect();
1641        let workers = sup
1642            .workers()
1643            .iter()
1644            .map(|(queue, worker)| {
1645                let worker_id = worker.config().worker_id.clone();
1646                let mut health = WorkerHealth::new(queue.clone(), worker_id.clone());
1647                health.claiming = claiming.contains(queue);
1648                health.active_runs = status.active.get(&worker_id).copied().unwrap_or(0);
1649                health
1650            })
1651            .collect();
1652        KernelHealth {
1653            state: status.state,
1654            frozen: self.inner.config.governance.is_frozen(),
1655            workers,
1656            scheduler_lag: status.scheduler_lag,
1657            store_latency: status.store_latency,
1658        }
1659    }
1660}
1661
1662impl Kernel {
1663    /// The session service `attach` reads transcripts and holds from (spec 3.2 §7.11).
1664    pub(crate) fn session_service(&self) -> Option<&Arc<dyn SessionService>> {
1665        self.inner.sessions.as_ref()
1666    }
1667
1668    /// The approval service the socket serves the `/api/approvals` inbox from (K5).
1669    pub(crate) fn approval_service(&self) -> Option<&Arc<dyn ApprovalService>> {
1670        self.inner.approvals.as_ref()
1671    }
1672
1673    /// The audit trail `kernel.control` records go to (K-I16, spec 3.2 §9.3).
1674    pub(crate) fn audit_trail(&self) -> Option<&AuditTrail> {
1675        self.inner.sup.audit.as_ref()
1676    }
1677
1678    /// The registered agent target names, sorted; workflow ids cannot be listed
1679    /// (spec 3.2 §7.11, `POST /api/kernel/processes`).
1680    pub(crate) fn targets(&self) -> Vec<String> {
1681        let mut targets: std::collections::BTreeSet<String> =
1682            self.inner.agents.keys().cloned().collect();
1683        targets.extend(self.inner.sup.targets.table.targets());
1684        targets.into_iter().collect()
1685    }
1686
1687    /// The driver supervisor, when the kernel was built with one (spec 3.2 §7.7).
1688    #[cfg(feature = "drivers")]
1689    pub fn drivers(&self) -> Option<&crate::drivers::DriverSupervisor> {
1690        self.inner.drivers.as_ref()
1691    }
1692
1693    /// Whether `target` is a registered agent target or a workflow the executor has.
1694    pub(crate) fn has_target(&self, target: &str) -> bool {
1695        let table = &self.inner.sup.targets.table;
1696        self.inner.agents.contains_key(target)
1697            || table.contains(target)
1698            || table.is_expected(target)
1699            || self.inner.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(target))
1700    }
1701}
1702
1703#[async_trait]
1704impl FreezeDelegate for Kernel {
1705    async fn freeze(&self, reason: &str, by: AuditActor) -> adk_core::Result<FreezeReport> {
1706        // The running processes park at their next model-call boundary.
1707        let parked_runs = self.inner.sup.running().await.len();
1708        Kernel::freeze(self, reason, by).await?;
1709        Ok(FreezeReport { parked_runs, cancelled_runs: 0 })
1710    }
1711
1712    async fn unfreeze(&self, by: AuditActor) -> adk_core::Result<()> {
1713        Kernel::unfreeze(self, by).await.map_err(Into::into)
1714    }
1715}
1716
1717/// How long a queue ingress waits for a message before it pulls again.
1718const INGRESS_IDLE: Duration = Duration::from_secs(1);
1719/// How often a drain checks whether the suspended processes have parked.
1720const DRAIN_POLL: Duration = Duration::from_millis(50);
1721
1722/// Ticks the scheduler every `tick`, recording how late each tick ran.
1723fn spawn_scheduler(
1724    scheduler: DurableScheduler,
1725    sup: Arc<Supervision>,
1726    tick: Duration,
1727    status: Arc<RwLock<Status>>,
1728    stop: CancellationToken,
1729) -> JoinHandle<()> {
1730    tokio::spawn(async move {
1731        let mut due = tokio::time::Instant::now();
1732        loop {
1733            tokio::select! {
1734                () = stop.cancelled() => return,
1735                () = tokio::time::sleep_until(due) => {}
1736            }
1737            let lag = tokio::time::Instant::now().saturating_duration_since(due);
1738            match scheduler.tick().await {
1739                // A fired schedule runs now, not at its queue's next poll.
1740                Ok(fired) if fired.enqueued > 0 => sup.nudge(),
1741                Ok(_) => {}
1742                Err(error) => tracing::warn!(error = %error, "scheduler tick failed"),
1743            }
1744            status.write().unwrap_or_else(|e| e.into_inner()).scheduler_lag = Some(lag);
1745            due = (due + tick).max(tokio::time::Instant::now());
1746        }
1747    })
1748}
1749
1750/// Runs `ingress` as `QueueIngress::run` does, waking the workers when a message became a
1751/// `kernel.wake` run, so a queue wake is claimed at once rather than at the maintenance
1752/// queue's next poll.
1753fn spawn_queue_ingress(
1754    ingress: QueueIngress,
1755    sup: Arc<Supervision>,
1756    stop: CancellationToken,
1757) -> JoinHandle<()> {
1758    tokio::spawn(async move {
1759        loop {
1760            let pause = match ingress.poll_once().await {
1761                Ok(report) => {
1762                    if !report.created.is_empty() {
1763                        sup.nudge();
1764                    }
1765                    if report.pulled > 0 { Duration::ZERO } else { INGRESS_IDLE }
1766                }
1767                Err(error) => {
1768                    tracing::warn!(error = %error, "queue ingress pull failed");
1769                    INGRESS_IDLE
1770                }
1771            };
1772            tokio::select! {
1773                () = stop.cancelled() => return,
1774                () = tokio::time::sleep(pause) => {}
1775            }
1776        }
1777    })
1778}
1779
1780/// Hands every event of `source` to [`WakeRouter::submit`], which enqueues a `kernel.wake`
1781/// run keyed by the event, until the kernel stops (spec 3.2 §7.4). The maintenance worker's
1782/// [`KernelWakeExecutor`] routes it, so a delivery is routed once however often it arrives
1783/// (K-I3) and survives a restart.
1784fn spawn_wake_source(
1785    source: Arc<dyn WakeSource>,
1786    sup: Arc<Supervision>,
1787    router: WakeRouter,
1788    stop: CancellationToken,
1789) -> JoinHandle<()> {
1790    tokio::spawn(async move {
1791        let mut events = match source.subscribe().await {
1792            Ok(events) => events,
1793            Err(error) => {
1794                tracing::warn!(wake.source = source.name(), error = %error, "could not subscribe to a wake source");
1795                return;
1796            }
1797        };
1798        loop {
1799            let event = tokio::select! {
1800                () = stop.cancelled() => return,
1801                event = events.next() => event,
1802            };
1803            let Some(event) = event else { return };
1804            let key = event.key.clone();
1805            match router.submit(&event, &sup.app_name).await {
1806                Ok(Enqueued::Created(_)) => sup.nudge(),
1807                Ok(_) => {
1808                    tracing::debug!(wake.source = source.name(), wake.key = %key, "duplicate wake delivery");
1809                }
1810                Err(error) => {
1811                    tracing::warn!(wake.source = source.name(), wake.key = %key, error = %error, "could not hand a wake to the maintenance queue");
1812                }
1813            }
1814        }
1815    })
1816}
1817
1818/// Keeps one file source per root a sleeper or trigger watches (spec 3.2 §7.4): a spawn
1819/// that names a new root signals at once, and every tick drops the roots no sleeper needs
1820/// any more. A source whose subscription failed is not retried until its root is dropped
1821/// and needed again.
1822fn spawn_file_watch(
1823    sup: Arc<Supervision>,
1824    router: WakeRouter,
1825    tick: Duration,
1826    stop: CancellationToken,
1827) -> JoinHandle<()> {
1828    tokio::spawn(async move {
1829        loop {
1830            let roots = file_roots(&sup, &router).await;
1831            let mut started = Vec::new();
1832            {
1833                let mut watched = sup.watched.lock().unwrap_or_else(|e| e.into_inner());
1834                watched.retain(|root, task| {
1835                    let needed = roots.contains_key(root);
1836                    if !needed {
1837                        task.abort();
1838                        tracing::debug!(root = %root.display(), "no sleeper watches this root any more");
1839                    }
1840                    needed
1841                });
1842                for (root, debounce) in &roots {
1843                    if !watched.contains_key(root) {
1844                        started.push((root.clone(), *debounce));
1845                    }
1846                }
1847            }
1848            for (root, debounce) in started {
1849                let name = format!("file:{}", root.display());
1850                match FileWakeSource::new(name, root.clone(), "*") {
1851                    Ok(source) => {
1852                        let source: Arc<dyn WakeSource> = Arc::new(source.with_debounce(debounce));
1853                        let task = spawn_wake_source(
1854                            source,
1855                            Arc::clone(&sup),
1856                            router.clone(),
1857                            stop.clone(),
1858                        );
1859                        sup.watched.lock().unwrap_or_else(|e| e.into_inner()).insert(root, task);
1860                    }
1861                    Err(error) => {
1862                        tracing::warn!(root = %root.display(), error = %error, "could not watch a file wake's root");
1863                    }
1864                }
1865            }
1866            tokio::select! {
1867                () = stop.cancelled() => return,
1868                () = sup.roots_changed.notified() => {}
1869                () = tokio::time::sleep(tick) => {}
1870            }
1871        }
1872    })
1873}
1874
1875/// The roots of the file wakes of every sleeper and trigger, each with the shortest
1876/// debounce asked for it.
1877async fn file_roots(sup: &Supervision, router: &WakeRouter) -> BTreeMap<PathBuf, Duration> {
1878    let mut roots: BTreeMap<PathBuf, Duration> = BTreeMap::new();
1879    let mut add = |wake: &Wake| {
1880        if let Wake::FileChange { root, debounce, .. } = wake {
1881            let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.clone());
1882            let entry = roots.entry(root).or_insert(*debounce);
1883            *entry = (*entry).min(*debounce);
1884        }
1885    };
1886    for trigger in router.triggers() {
1887        add(&trigger.wake);
1888    }
1889    match sup.processes.list(&ProcessFilter::default()).await {
1890        Ok(metas) => {
1891            for wake in metas.iter().filter_map(|meta| meta.wake.as_ref()) {
1892                wake.any_of.iter().for_each(&mut add);
1893            }
1894        }
1895        Err(error) => tracing::debug!(error = %error, "could not list the sleepers' file wakes"),
1896    }
1897    roots
1898}
1899
1900/// Every 250 ms (K-I8): suspends the running processes this replica leases that have a
1901/// pending request, and wakes the freeze-parked processes once the control allows work
1902/// again, publishing each change of the kill switch.
1903fn spawn_mirror(sup: Arc<Supervision>, stop: CancellationToken) -> JoinHandle<()> {
1904    tokio::spawn(async move {
1905        let mut frozen = sup.governance.is_frozen();
1906        let mut refused = sup.governance.check().is_err();
1907        loop {
1908            tokio::select! {
1909                () = stop.cancelled() => return,
1910                () = tokio::time::sleep(KernelConfig::GOVERNANCE_POLL) => {}
1911            }
1912            sup.mirror_suspend_requests().await;
1913            let now = sup.governance.is_frozen();
1914            if now != frozen {
1915                frozen = now;
1916                sup.publish(KernelEvent::Governance { frozen, reason: sup.governance.reason() });
1917            }
1918            // Work is allowed again after an unfreeze, and once a store that was stale, or not
1919            // read when the kernel started, is read unfrozen.
1920            let refuses = sup.governance.check().is_err();
1921            if refused && !refuses {
1922                for (_, worker) in sup.workers() {
1923                    worker.wake_frozen().await;
1924                }
1925                sup.wake_suspended(&Suspension::Freeze).await;
1926            }
1927            refused = refuses;
1928        }
1929    })
1930}
1931
1932/// What the maintenance tick moves forward besides the supervision state: the agenda, the
1933/// agent table (spec 3.3 §5.7) and the consolidation tick.
1934struct Ticks {
1935    agenda: Agenda,
1936    agents: crate::agents::Agents,
1937    consolidation: Option<ConsolidationTicker>,
1938}
1939
1940/// Every scheduler tick: expires wake sets and fires time wakes, claims wake runs enqueued
1941/// from outside the kernel, attributes spend, applies the agenda's decisions, makes the
1942/// daily review, runs the admission sweep (preempted processes whose preemptor finished,
1943/// processes waiting for a slot, budgets replenished), and measures the store.
1944fn spawn_maintenance(
1945    sup: Arc<Supervision>,
1946    router: WakeRouter,
1947    ticks: Ticks,
1948    status: Arc<RwLock<Status>>,
1949    tick: Duration,
1950    stop: CancellationToken,
1951) -> JoinHandle<()> {
1952    tokio::spawn(async move {
1953        loop {
1954            tokio::select! {
1955                () = stop.cancelled() => return,
1956                () = tokio::time::sleep(tick) => {}
1957            }
1958            sup.fire_crons(&router).await;
1959            match router.sweep_expired(sup.clock.now()).await {
1960                Ok(outcomes) if !outcomes.is_empty() => sup.nudge(),
1961                Ok(_) => {}
1962                Err(error) => tracing::debug!(error = %error, "could not sweep expired wake sets"),
1963            }
1964            // A webhook ingress served outside the kernel, or another replica, enqueues
1965            // `kernel.wake` runs this kernel never sees enqueued: claim them within a tick
1966            // rather than at the maintenance queue's 5 s poll (§7.4, under 2 s).
1967            if sup.external_wakes_due().await {
1968                sup.nudge();
1969            }
1970            // The day that ended gets its baseline pass, once (spec 3.2 §7.10).
1971            #[cfg(feature = "proc-baselines")]
1972            if let Some(proc) = &sup.proc
1973                && proc.tick(&sup.runs, &sup.queues, sup.clock.now()).await
1974            {
1975                sup.nudge();
1976            }
1977            sup.attribute_all().await;
1978            ticks.agenda.tick().await;
1979            ticks.agents.tick().await;
1980            sup.review().await;
1981            if let Some(consolidation) = &ticks.consolidation {
1982                consolidation.tick().await;
1983            }
1984            // A preemptor that finished on another replica, a slot freed there, a new day.
1985            sup.requeue_preempted(None).await;
1986            if sup.caps_running().await {
1987                sup.admit_waiters().await;
1988            }
1989            let today = sup.clock.now().date_naive();
1990            for (partition, asleep) in sup.replenished_partitions().await {
1991                let event = crate::wake::WakeEvent::new(
1992                    "budget",
1993                    crate::wake::keys::budget(partition.as_str(), today, &asleep),
1994                    json!({ "partition": partition, "day": today }),
1995                );
1996                if let Err(error) = router.submit(&event, &sup.app_name).await {
1997                    tracing::debug!(partition = %partition, error = %error, "could not submit a budget wake");
1998                }
1999            }
2000            let probe = tokio::time::Instant::now();
2001            let running = sup.running().await;
2002            let latency = probe.elapsed();
2003            let mut active: HashMap<String, usize> = HashMap::new();
2004            for run in running {
2005                if let Some(owner) = run.lease_owner {
2006                    *active.entry(owner).or_default() += 1;
2007                }
2008            }
2009            let mut status = status.write().unwrap_or_else(|e| e.into_inner());
2010            status.store_latency = Some(latency);
2011            status.active = active;
2012        }
2013    })
2014}
2015
2016/// The workflows every kernel worker runs: the kernel's `kernel.wake` and the caller's.
2017struct KernelWorkflows {
2018    user: Option<Arc<dyn WorkflowExecutor>>,
2019    wake: KernelWakeExecutor,
2020    /// The daily baseline pass, `kernel.proc` (spec 3.2 §7.10).
2021    #[cfg(feature = "proc-baselines")]
2022    proc: Option<Arc<crate::proc::baselines::ProcRuntime>>,
2023}
2024
2025impl KernelWorkflows {
2026    /// The baseline pass when `workflow_id` names it.
2027    #[cfg(feature = "proc-baselines")]
2028    fn proc_for(&self, workflow_id: &str) -> Option<&Arc<crate::proc::baselines::ProcRuntime>> {
2029        self.proc.as_ref().filter(|_| workflow_id == crate::proc::baselines::PROC_TARGET)
2030    }
2031}
2032
2033#[async_trait]
2034impl WorkflowExecutor for KernelWorkflows {
2035    fn has_workflow(&self, workflow_id: &str) -> bool {
2036        #[cfg(feature = "proc-baselines")]
2037        if self.proc_for(workflow_id).is_some() {
2038            return true;
2039        }
2040        self.wake.has_workflow(workflow_id)
2041            || self.user.as_ref().is_some_and(|user| user.has_workflow(workflow_id))
2042    }
2043
2044    async fn execute(
2045        &self,
2046        workflow_id: &str,
2047        input: WorkflowState,
2048        cancel_token: CancellationToken,
2049    ) -> std::result::Result<serde_json::Value, String> {
2050        #[cfg(feature = "proc-baselines")]
2051        if let Some(proc) = self.proc_for(workflow_id) {
2052            let input = serde_json::Value::Object(input.into_iter().collect());
2053            return tokio::select! {
2054                done = proc.execute(input) => done,
2055                () = cancel_token.cancelled() => Err("the baseline pass was cancelled".to_string()),
2056            };
2057        }
2058        match &self.user {
2059            Some(user) if !self.wake.has_workflow(workflow_id) => {
2060                user.execute(workflow_id, input, cancel_token).await
2061            }
2062            _ => self.wake.execute(workflow_id, input, cancel_token).await,
2063        }
2064    }
2065
2066    async fn execute_durable(
2067        &self,
2068        workflow_id: &str,
2069        input: WorkflowState,
2070        run: WorkflowRunContext,
2071    ) -> std::result::Result<serde_json::Value, String> {
2072        #[cfg(feature = "proc-baselines")]
2073        if self.proc_for(workflow_id).is_some() {
2074            return self.execute(workflow_id, input, run.cancel).await;
2075        }
2076        match &self.user {
2077            Some(user) if !self.wake.has_workflow(workflow_id) => {
2078                user.execute_durable(workflow_id, input, run).await
2079            }
2080            _ => self.wake.execute_durable(workflow_id, input, run).await,
2081        }
2082    }
2083}
2084
2085/// The workflow executors a builder was given, each run going to the first that has its id.
2086struct WorkflowChain(Vec<Arc<dyn WorkflowExecutor>>);
2087
2088impl WorkflowChain {
2089    fn find(&self, workflow_id: &str) -> std::result::Result<&Arc<dyn WorkflowExecutor>, String> {
2090        self.0
2091            .iter()
2092            .find(|executor| executor.has_workflow(workflow_id))
2093            .ok_or_else(|| format!("no workflow executor of the kernel has `{workflow_id}`"))
2094    }
2095}
2096
2097#[async_trait]
2098impl WorkflowExecutor for WorkflowChain {
2099    fn has_workflow(&self, workflow_id: &str) -> bool {
2100        self.find(workflow_id).is_ok()
2101    }
2102
2103    async fn execute(
2104        &self,
2105        workflow_id: &str,
2106        input: WorkflowState,
2107        cancel_token: CancellationToken,
2108    ) -> std::result::Result<serde_json::Value, String> {
2109        self.find(workflow_id)?.execute(workflow_id, input, cancel_token).await
2110    }
2111
2112    async fn execute_durable(
2113        &self,
2114        workflow_id: &str,
2115        input: WorkflowState,
2116        run: WorkflowRunContext,
2117    ) -> std::result::Result<serde_json::Value, String> {
2118        self.find(workflow_id)?.execute_durable(workflow_id, input, run).await
2119    }
2120}
2121
2122/// Emits a finished run's model calls, tool calls and tool durations as the OTel GenAI
2123/// histograms (spec 3.2 §7.10, §13 Q4).
2124#[cfg(feature = "proc")]
2125pub(crate) fn record_histograms(target: &str, counts: &crate::supervise::TranscriptCounts) {
2126    use opentelemetry::KeyValue;
2127    use std::sync::OnceLock;
2128
2129    struct Instruments {
2130        inference_calls: opentelemetry::metrics::Histogram<u64>,
2131        tool_calls: opentelemetry::metrics::Histogram<u64>,
2132        tool_duration: opentelemetry::metrics::Histogram<f64>,
2133    }
2134    static INSTRUMENTS: OnceLock<Instruments> = OnceLock::new();
2135    let instruments = INSTRUMENTS.get_or_init(|| {
2136        let meter = opentelemetry::global::meter("adk-kernel");
2137        Instruments {
2138            inference_calls: meter
2139                .u64_histogram("gen_ai.invoke_agent.inference_calls")
2140                .with_description("Model calls per agent run")
2141                .build(),
2142            tool_calls: meter
2143                .u64_histogram("gen_ai.invoke_agent.tool_calls")
2144                .with_description("Tool calls per agent run")
2145                .build(),
2146            tool_duration: meter
2147                .f64_histogram("gen_ai.execute_tool.duration")
2148                .with_unit("s")
2149                .with_description("Tool call duration")
2150                .build(),
2151        }
2152    });
2153    let invoke = [
2154        KeyValue::new(adk_telemetry::semconv::GEN_AI_OPERATION_NAME, "invoke_agent"),
2155        KeyValue::new("gen_ai.agent.name", target.to_string()),
2156    ];
2157    instruments.inference_calls.record(counts.model_calls, &invoke);
2158    instruments.tool_calls.record(counts.tool_calls, &invoke);
2159    let execute = [KeyValue::new(adk_telemetry::semconv::GEN_AI_OPERATION_NAME, "execute_tool")];
2160    for seconds in &counts.tool_durations {
2161        instruments.tool_duration.record(*seconds, &execute);
2162    }
2163}
2164
2165/// Builds a [`Kernel`] (spec 3.2 §7.2).
2166///
2167/// A run store is required; everything else is optional. The process store defaults to
2168/// [`InMemoryProcessStore`]. `Harness::kernel(..)` (feature `kernel` of `adk-harness`,
2169/// §10 HK1) returns one with the harness runner registered as the `adk-rust` and
2170/// `harness.goal` targets.
2171///
2172/// # Example
2173///
2174/// ```rust
2175/// use std::sync::Arc;
2176/// use adk_core::InMemoryRunStore;
2177/// use adk_kernel::{Kernel, KernelConfig};
2178///
2179/// let kernel = Kernel::builder()
2180///     .config(KernelConfig::default().with_app_name("ops"))
2181///     .run_store(Arc::new(InMemoryRunStore::new()))
2182///     .build()
2183///     .unwrap();
2184/// assert_eq!(kernel.config().app_name, "ops");
2185/// ```
2186#[derive(Default)]
2187pub struct KernelBuilder {
2188    config: KernelConfig,
2189    governance: Option<GovernanceControl>,
2190    runs: Option<Arc<dyn DurableRunStore>>,
2191    processes: Option<Arc<dyn ProcessStore>>,
2192    schedules: Option<Arc<dyn ScheduleStore>>,
2193    approvals: Option<Arc<dyn ApprovalService>>,
2194    sessions: Option<Arc<dyn SessionService>>,
2195    spend: Option<Arc<dyn SpendLedger>>,
2196    audit: Option<AuditTrail>,
2197    agents: BTreeMap<String, Arc<Runner>>,
2198    workflows: Vec<Arc<dyn WorkflowExecutor>>,
2199    #[cfg(feature = "charter")]
2200    kpi_trackers: Vec<crate::charter::KpiTracker>,
2201    wake_sources: Vec<Arc<dyn WakeSource>>,
2202    triggers: Vec<Trigger>,
2203    sinks: Vec<Arc<dyn EventSink>>,
2204    progress: Option<Arc<dyn ProgressSource>>,
2205    partition_progress: Vec<(PartitionId, Arc<dyn ProgressSource>)>,
2206    queue_ingresses: Vec<QueueIngress>,
2207    agenda: Option<Arc<dyn AgendaStore>>,
2208    agenda_handles: Vec<AgendaHandle>,
2209    agent_store: Option<Arc<dyn crate::agents::AgentStore>>,
2210    agent_factory: Option<Arc<dyn crate::agents::AgentFactory>>,
2211    agents_handles: Vec<crate::agents::AgentsHandle>,
2212    rule_source: Option<Arc<dyn crate::review::StandingRuleSource>>,
2213    consolidators: BTreeMap<PartitionId, Arc<dyn Consolidator>>,
2214    #[cfg(feature = "drivers")]
2215    drivers: Option<crate::drivers::DriverSupervisor>,
2216    audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
2217    #[cfg(feature = "proc")]
2218    ledger: Option<Ledger>,
2219    #[cfg(feature = "proc-baselines")]
2220    baselines: Option<crate::proc::baselines::BaselinePolicy>,
2221    #[cfg(feature = "proc-baselines")]
2222    phraser: Option<Arc<dyn crate::proc::baselines::ObservationPhraser>>,
2223    partitions: Option<Partitions>,
2224    partition_targets: BTreeMap<String, PartitionId>,
2225    watermarks: Option<Arc<dyn CronWatermarkStore>>,
2226    bundle: Option<KernelStores>,
2227    require_durable: bool,
2228    #[cfg(feature = "charter")]
2229    signal_stores: BTreeMap<PartitionId, Arc<dyn crate::charter::SignalStore>>,
2230    inventory_warnings: Vec<InventoryWarning>,
2231    subagents: Option<SubagentConfig>,
2232    subagent_handles: Vec<crate::subagents::SubagentHandle>,
2233}
2234
2235impl fmt::Debug for KernelBuilder {
2236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2237        f.debug_struct("KernelBuilder")
2238            .field("config", &self.config)
2239            .field("agents", &self.agents.keys().collect::<Vec<_>>())
2240            .field("triggers", &self.triggers.len())
2241            .field("wake_sources", &self.wake_sources.len())
2242            .finish_non_exhaustive()
2243    }
2244}
2245
2246impl KernelBuilder {
2247    /// A builder with the default configuration and no stores.
2248    pub fn new() -> Self {
2249        Self::default()
2250    }
2251
2252    /// Sets the configuration.
2253    #[must_use]
2254    pub fn config(mut self, config: KernelConfig) -> Self {
2255        self.config = config;
2256        self
2257    }
2258
2259    /// Sets the kill switch. It replaces [`KernelConfig::governance`] at
2260    /// [`build`](Self::build), whenever [`config`](Self::config) is called, so a builder
2261    /// from `Harness::kernel()` keeps the harness's control when the caller sets its own
2262    /// configuration.
2263    #[must_use]
2264    pub fn governance(mut self, control: GovernanceControl) -> Self {
2265        self.governance = Some(control);
2266        self
2267    }
2268
2269    /// Sets the durable run store every process lives in. Required.
2270    #[must_use]
2271    pub fn run_store(mut self, runs: Arc<dyn DurableRunStore>) -> Self {
2272        self.runs = Some(runs);
2273        self
2274    }
2275
2276    /// Sets the process side table. Defaults to [`InMemoryProcessStore`].
2277    #[must_use]
2278    pub fn process_store(mut self, processes: Arc<dyn ProcessStore>) -> Self {
2279        self.processes = Some(processes);
2280        self
2281    }
2282
2283    /// Sets the schedule store the kernel's `DurableScheduler` fires.
2284    #[must_use]
2285    pub fn schedule_store(mut self, schedules: Arc<dyn ScheduleStore>) -> Self {
2286        self.schedules = Some(schedules);
2287        self
2288    }
2289
2290    /// Sets the approval service, built with `StoreApprovalService::with_run_store` so a
2291    /// decision wakes the parked run; pass the same service to the agents' `RunConfig`.
2292    ///
2293    /// The kernel files every call the service would hold with no route into its inbox for
2294    /// the `operator` group, self-approval allowed, as `adk-rust up` routes them
2295    /// (`ApprovalService::route_unrouted`): a router the service was built with keeps
2296    /// deciding. It publishes `held` when a request is filed and `decided` when a decision
2297    /// resolves one (`ApprovalService::add_notifier`). A service that takes neither is named
2298    /// in [`Kernel::inventory`]. For [`Wake::Approval`] sleepers, build the service with
2299    /// `with_notifier(source)` over an [`ApprovalWakeSource`](crate::ApprovalWakeSource) and
2300    /// pass the same source to [`wake_source`](Self::wake_source).
2301    ///
2302    /// # Example
2303    ///
2304    /// ```rust
2305    /// use std::sync::Arc;
2306    /// use adk_core::{InMemoryApprovalStore, InMemoryRunStore, StoreApprovalService};
2307    /// use adk_kernel::Kernel;
2308    ///
2309    /// let runs = Arc::new(InMemoryRunStore::new());
2310    /// let approvals = Arc::new(
2311    ///     StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
2312    ///         .with_run_store(runs.clone()),
2313    /// );
2314    /// // The agents' runner takes the same service: `RunConfig::builder().approval_service(..)`.
2315    /// let kernel = Kernel::builder().run_store(runs).approval_service(approvals).build()?;
2316    /// assert!(!kernel.inventory().warnings.iter().any(|w| w.code.starts_with("kernel.approvals")));
2317    /// # Ok::<(), adk_kernel::KernelError>(())
2318    /// ```
2319    #[must_use]
2320    pub fn approval_service(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
2321        self.approvals = Some(approvals);
2322        self
2323    }
2324
2325    /// Sets the session service `attach` reads transcripts from.
2326    #[must_use]
2327    pub fn session_service(mut self, sessions: Arc<dyn SessionService>) -> Self {
2328        self.sessions = Some(sessions);
2329        self
2330    }
2331
2332    /// Sets the spend ledger the process views read.
2333    #[must_use]
2334    pub fn spend_ledger(mut self, spend: Arc<dyn SpendLedger>) -> Self {
2335        self.spend = Some(spend);
2336        self
2337    }
2338
2339    /// Sets the signed audit trail for the kernel's records (spec 3.2 §9.3).
2340    #[must_use]
2341    pub fn audit(mut self, trail: AuditTrail) -> Self {
2342        self.audit = Some(trail);
2343        self
2344    }
2345
2346    /// Hosts `runner` as the target `target` on every queue's worker, as
2347    /// `DurableWorker::with_agent` does.
2348    #[must_use]
2349    pub fn agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
2350        self.agents.insert(target.into(), runner);
2351        self
2352    }
2353
2354    /// Hosts workflow targets, as `DurableWorker::with_workflows` does, in place of every
2355    /// executor given before; [`workflow`](Self::workflow) adds one beside them.
2356    #[must_use]
2357    pub fn workflows(mut self, workflows: Arc<dyn WorkflowExecutor>) -> Self {
2358        self.workflows = vec![workflows];
2359        self
2360    }
2361
2362    /// Adds `executor` beside the workflow executors given before: a workflow run goes to the
2363    /// first executor, in the order given, that has its workflow id. Products and kits each
2364    /// add their own, such as a site's workflows beside its KPI tracker.
2365    ///
2366    /// # Example
2367    ///
2368    /// ```rust
2369    /// use std::sync::Arc;
2370    /// use adk_core::InMemoryRunStore;
2371    /// use adk_kernel::{Kernel, Trigger, Wake};
2372    /// use adk_server::background::{WorkflowExecutor, WorkflowState};
2373    /// use tokio_util::sync::CancellationToken;
2374    ///
2375    /// struct One(&'static str);
2376    ///
2377    /// #[async_trait::async_trait]
2378    /// impl WorkflowExecutor for One {
2379    ///     fn has_workflow(&self, id: &str) -> bool {
2380    ///         id == self.0
2381    ///     }
2382    ///
2383    ///     async fn execute(&self, _: &str, _: WorkflowState, _: CancellationToken) -> Result<serde_json::Value, String> {
2384    ///         Ok(serde_json::json!(self.0))
2385    ///     }
2386    /// }
2387    ///
2388    /// let run = |target: &str| adk_core::NewRun::new("background", "ops", "kernel", target, serde_json::json!({}));
2389    /// let kernel = Kernel::builder()
2390    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2391    ///     .workflow(Arc::new(One("digest")))
2392    ///     .workflow(Arc::new(One("probe")))
2393    ///     .trigger(Trigger::new("weekly", Wake::Webhook { hook: "weekly".into() }, run("digest")))
2394    ///     .trigger(Trigger::new("probe", Wake::Webhook { hook: "probe".into() }, run("probe")))
2395    ///     .build()?;
2396    /// assert!(kernel.inventory().triggers.iter().all(|trigger| trigger.served));
2397    /// # Ok::<(), adk_kernel::KernelError>(())
2398    /// ```
2399    #[must_use]
2400    pub fn workflow(mut self, executor: Arc<dyn WorkflowExecutor>) -> Self {
2401        self.workflows.push(executor);
2402        self
2403    }
2404
2405    /// Runs `tracker`, a site's KPI tracker, as the kernel's `kernel.kpi` process (spec 3.5
2406    /// §7.11; feature `charter`): its trigger ([`KpiTracker::trigger`](crate::charter::KpiTracker::trigger))
2407    /// on the six-field UTC cron `expr` for app `app_name`, and one
2408    /// [`KpiTrackerExecutor`](crate::charter::KpiTrackerExecutor) over every tracker registered,
2409    /// beside the other workflows. The tracker then shows in `ps`, keeps a cron watermark and
2410    /// waits out a freeze.
2411    ///
2412    /// # Example
2413    ///
2414    /// ```rust
2415    /// use std::sync::Arc;
2416    /// use adk_core::InMemoryRunStore;
2417    /// use adk_kernel::Kernel;
2418    /// use adk_kernel::charter::{InMemoryCharterStore, InMemoryKpiStore, KpiTracker};
2419    ///
2420    /// let tracker = KpiTracker::new(uuid::Uuid::new_v4(), Arc::new(InMemoryCharterStore::new()), Arc::new(InMemoryKpiStore::new()));
2421    /// let kernel = Kernel::builder()
2422    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2423    ///     .kpi_tracker(tracker, "bakery", "0 0 * * * *")
2424    ///     .build()?;
2425    /// let trigger = &kernel.inventory().triggers[0];
2426    /// assert_eq!((trigger.target.as_str(), trigger.served), ("kernel.kpi", true));
2427    /// # Ok::<(), adk_kernel::KernelError>(())
2428    /// ```
2429    #[cfg(feature = "charter")]
2430    #[must_use]
2431    pub fn kpi_tracker(
2432        mut self,
2433        tracker: crate::charter::KpiTracker,
2434        app_name: &str,
2435        expr: &str,
2436    ) -> Self {
2437        self.triggers.push(tracker.trigger(app_name, expr));
2438        self.kpi_trackers.push(tracker);
2439        self
2440    }
2441
2442    /// Adds a wake source.
2443    #[must_use]
2444    pub fn wake_source(mut self, source: Arc<dyn WakeSource>) -> Self {
2445        self.wake_sources.push(source);
2446        self
2447    }
2448
2449    /// Adds a standing trigger.
2450    #[must_use]
2451    pub fn trigger(mut self, trigger: Trigger) -> Self {
2452        self.triggers.push(trigger);
2453        self
2454    }
2455
2456    /// Adds an event sink, such as an outbound `WebhookSink` (feature `webhooks`), that
2457    /// receives every later event through its own bounded queue (spec 3.2 §7.6).
2458    #[must_use]
2459    pub fn event_sink(mut self, sink: Arc<dyn EventSink>) -> Self {
2460        self.sinks.push(sink);
2461        self
2462    }
2463
2464    /// Sets the source of goal progress and loop-guard verdicts for process views.
2465    #[must_use]
2466    pub fn progress_source(mut self, source: Arc<dyn ProgressSource>) -> Self {
2467        self.progress = Some(source);
2468        self
2469    }
2470
2471    /// Sets the progress source of partition `partition` (spec 3.2 §7.8, §7.10): the
2472    /// kernel asks it, not the [`progress_source`](Self::progress_source), for the goal
2473    /// progress, loop-guard verdict and usage of that partition's processes — routed by the
2474    /// process's own partition — and hands it the process table and the ledger at start, as
2475    /// it does the main source. A partition without a source of its own falls back to the
2476    /// main source; its processes keep their partition.
2477    ///
2478    /// [`build`](Self::build) refuses a second source for the same partition, and
2479    /// [`Kernel::start`] warns about a partition the partition table does not hold.
2480    ///
2481    /// # Example
2482    ///
2483    /// ```rust
2484    /// use std::sync::Arc;
2485    /// use adk_core::InMemoryRunStore;
2486    /// use adk_kernel::{Kernel, ProgressSource};
2487    ///
2488    /// struct Work;
2489    /// impl ProgressSource for Work {}
2490    ///
2491    /// let builder = || Kernel::builder().run_store(Arc::new(InMemoryRunStore::new()));
2492    /// assert!(builder().partition_progress_source("work", Arc::new(Work)).build().is_ok());
2493    /// let twice = builder()
2494    ///     .partition_progress_source("work", Arc::new(Work))
2495    ///     .partition_progress_source("work", Arc::new(Work))
2496    ///     .build();
2497    /// assert!(twice.is_err());
2498    /// ```
2499    #[must_use]
2500    pub fn partition_progress_source(
2501        mut self,
2502        partition: impl Into<PartitionId>,
2503        source: Arc<dyn ProgressSource>,
2504    ) -> Self {
2505        self.partition_progress.push((partition.into(), source));
2506        self
2507    }
2508
2509    /// Adds a queue ingress the kernel runs while started, such as
2510    /// [`queue_wake_ingress`](crate::queue_wake_ingress).
2511    #[must_use]
2512    pub fn queue_ingress(mut self, ingress: QueueIngress) -> Self {
2513        self.queue_ingresses.push(ingress);
2514        self
2515    }
2516
2517    /// Sets the agenda's store (spec 3.2 §7.5). Defaults to [`InMemoryAgendaStore`].
2518    #[must_use]
2519    pub fn agenda_store(mut self, store: Arc<dyn AgendaStore>) -> Self {
2520        self.agenda = Some(store);
2521        self
2522    }
2523
2524    /// Binds `handle` to the built kernel's agenda, so a tool created before the kernel —
2525    /// the harness's `propose_followup` — reaches it (spec 3.2 §7.5, §10 HK1).
2526    #[must_use]
2527    pub fn agenda_handle(mut self, handle: AgendaHandle) -> Self {
2528        self.agenda_handles.push(handle);
2529        self
2530    }
2531
2532    /// Hosts background sub-agents (`adk_core::subagent`): a parent agent's
2533    /// `start_subagent` runs another agent as a process of this kernel's `background`
2534    /// queue — or of the queue `config` names, when the kernel has it — with a budget slice
2535    /// carved from the parent's run, the parent's tools as its ceiling, and its status on
2536    /// the bus. Off by default, since a sub-agent works without a person watching it.
2537    ///
2538    /// Needs a [`session_service`](Self::session_service): a fork copies the parent's
2539    /// session, and a parent is told once by the notice its session holds.
2540    ///
2541    /// # Example
2542    ///
2543    /// ```rust,no_run
2544    /// use std::sync::Arc;
2545    /// use adk_core::{InMemoryRunStore, RunBudget};
2546    /// use adk_kernel::{Kernel, SubagentHandle};
2547    /// use adk_server::background::SubagentConfig;
2548    ///
2549    /// # fn example(runner: Arc<adk_runner::Runner>, sessions: Arc<dyn adk_session::SessionService>) -> adk_kernel::Result<()> {
2550    /// let handle = SubagentHandle::new(); // give the lead agent `SubagentTools::new(Arc::new(handle.clone()))`
2551    /// let kernel = Kernel::builder()
2552    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2553    ///     .session_service(sessions)
2554    ///     .agent("lead", runner)
2555    ///     .subagents(SubagentConfig::default().with_default_budget(RunBudget::new().max_model_calls(20)))
2556    ///     .subagent_handle(handle)
2557    ///     .build()?;
2558    /// assert!(kernel.subagents().is_some());
2559    /// # Ok(())
2560    /// # }
2561    /// ```
2562    #[must_use]
2563    pub fn subagents(mut self, config: SubagentConfig) -> Self {
2564        self.subagents = Some(config);
2565        self
2566    }
2567
2568    /// Binds `handle` to the built kernel's sub-agent host, so the sub-agent tools of an
2569    /// agent built before the kernel reach it.
2570    #[must_use]
2571    pub fn subagent_handle(mut self, handle: crate::subagents::SubagentHandle) -> Self {
2572        self.subagent_handles.push(handle);
2573        self
2574    }
2575
2576    /// Sets where the agents a person adds are kept (spec 3.3 §5.7, §10 K7). Defaults to
2577    /// [`InMemoryAgentStore`](crate::stores::InMemoryAgentStore), which keeps nothing across
2578    /// a restart.
2579    #[must_use]
2580    pub fn agent_store(mut self, store: Arc<dyn crate::agents::AgentStore>) -> Self {
2581        self.agent_store = Some(store);
2582        self
2583    }
2584
2585    /// Sets how the agents a person adds are built (spec 3.3 §5.7, §10 K7). Without one the
2586    /// kernel lists and removes agents but adds none.
2587    #[must_use]
2588    pub fn agent_factory(mut self, factory: Arc<dyn crate::agents::AgentFactory>) -> Self {
2589        self.agent_factory = Some(factory);
2590        self
2591    }
2592
2593    /// Binds `handle` to the built kernel's agent table, so a tool created before the kernel
2594    /// — the harness's `propose_agent` — reaches it (spec 3.3 §10 K7), as
2595    /// [`agenda_handle`](Self::agenda_handle) does for `propose_followup`.
2596    #[must_use]
2597    pub fn agents_handle(mut self, handle: crate::agents::AgentsHandle) -> Self {
2598        self.agents_handles.push(handle);
2599        self
2600    }
2601
2602    /// Sets where the daily review reads standing rules (spec 3.2 §9.1); `Harness::kernel`
2603    /// sets the harness's rule store.
2604    #[must_use]
2605    pub fn standing_rules(mut self, source: Arc<dyn crate::review::StandingRuleSource>) -> Self {
2606        self.rule_source = Some(source);
2607        self
2608    }
2609
2610    /// Registers `consolidator` for `partition`: the kernel runs its consolidation tick
2611    /// there when [`ProactivityPolicy::consolidation`] is set (spec 3.2 §7.5, §10 HK2).
2612    #[must_use]
2613    pub fn consolidator(
2614        mut self,
2615        partition: impl Into<PartitionId>,
2616        consolidator: Arc<dyn Consolidator>,
2617    ) -> Self {
2618        self.consolidators.insert(partition.into(), consolidator);
2619        self
2620    }
2621
2622    /// Supervises drivers (spec 3.2 §7.7): `Kernel::start` loads the mounted drivers and
2623    /// starts the eager ones, `Kernel::stop` stops them, and their state changes reach the
2624    /// kernel's bus and audit trail.
2625    #[cfg(feature = "drivers")]
2626    #[must_use]
2627    pub fn drivers(mut self, drivers: crate::drivers::DriverSupervisor) -> Self {
2628        self.drivers = Some(drivers);
2629        self
2630    }
2631
2632    /// Registers `audience` for `partition` (spec 3.2 §7.10): the daily baseline pass puts
2633    /// the partition's observations to the person it names as
2634    /// [`AgendaOrigin::Observation`](crate::AgendaOrigin::Observation) questions, and a
2635    /// confirmation is remembered through it. Without one, observations stay at
2636    /// `/api/kernel/proc/observations` and nobody is asked.
2637    #[must_use]
2638    pub fn observation_audience(
2639        mut self,
2640        partition: impl Into<PartitionId>,
2641        audience: Arc<dyn ObservationAudience>,
2642    ) -> Self {
2643        self.audiences.insert(partition.into(), audience);
2644        self
2645    }
2646
2647    /// Keeps the content-free activity ledger in `ledger` (spec 3.2 §7.10, feature `proc`):
2648    /// every event but `Health` writes its row, the [`ProgressSource`] gets the ledger at
2649    /// start so the hosted runtime writes its own activity, and rows are stamped on
2650    /// [`KernelConfig::clock`].
2651    #[cfg(feature = "proc")]
2652    #[must_use]
2653    pub fn ledger(mut self, ledger: Ledger) -> Self {
2654        self.ledger = Some(ledger);
2655        self
2656    }
2657
2658    /// Runs the daily baseline pass under `policy` (spec 3.2 §7.10, feature
2659    /// `proc-baselines`). With a ledger and no policy, the pass runs under
2660    /// `BaselinePolicy::default()`; `BaselinePolicy::disabled()` turns it off.
2661    #[cfg(feature = "proc-baselines")]
2662    #[must_use]
2663    pub fn baseline_policy(mut self, policy: crate::proc::baselines::BaselinePolicy) -> Self {
2664        self.baselines = Some(policy);
2665        self
2666    }
2667
2668    /// Words observations with `phraser`, a model used only after the deterministic
2669    /// detection (spec 3.2 §7.10, feature `proc-baselines`); without one the kernel's
2670    /// template words them.
2671    #[cfg(feature = "proc-baselines")]
2672    #[must_use]
2673    pub fn observation_phraser(
2674        mut self,
2675        phraser: Arc<dyn crate::proc::baselines::ObservationPhraser>,
2676    ) -> Self {
2677        self.phraser = Some(phraser);
2678        self
2679    }
2680
2681    /// Sets the partition table (spec 3.2 §7.8). Defaults to one in memory. Give the kernel
2682    /// the [`Partitions`] its partition harnesses were built with, so their policies, the
2683    /// control plane and the daily review read one table.
2684    #[must_use]
2685    pub fn partitions(mut self, partitions: Partitions) -> Self {
2686        self.partitions = Some(partitions);
2687        self
2688    }
2689
2690    /// Hosts `runner`, the harness of partition `partition`, as the target `target`, bound to
2691    /// the partition (spec 3.2 §7.8, K-I15): a process of another partition cannot run it,
2692    /// a spawn of it in the default partition runs in `partition`, and a run of it enqueued
2693    /// outside the kernel is listed in `partition`.
2694    #[must_use]
2695    pub fn partition_agent(
2696        mut self,
2697        partition: impl Into<PartitionId>,
2698        target: impl Into<String>,
2699        runner: Arc<Runner>,
2700    ) -> Self {
2701        let target = target.into();
2702        self.partition_targets.insert(target.clone(), partition.into());
2703        self.agents.insert(target, runner);
2704        self
2705    }
2706
2707    /// Sets where the cron wakes of sleepers keep their cursors (spec 3.2 §7.4). Defaults to
2708    /// [`InMemoryCronWatermarkStore`], which keeps nothing across a restart.
2709    ///
2710    /// The kernel fires a sleeper's cron wake itself and keeps the expression's cursor here
2711    /// under `kernel:<expression>`. With a durable store shared by every replica, a restart
2712    /// or another replica fires each occurrence missed while no kernel ran once, as the
2713    /// sleepers' `missed` policies pick them, and never one that already fired.
2714    ///
2715    /// # Example
2716    ///
2717    /// ```rust
2718    /// use std::sync::Arc;
2719    /// use adk_core::InMemoryRunStore;
2720    /// use adk_kernel::{InMemoryCronWatermarkStore, Kernel};
2721    ///
2722    /// let kernel = Kernel::builder()
2723    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2724    ///     .watermark_store(Arc::new(InMemoryCronWatermarkStore::new()))
2725    ///     .build()
2726    ///     .unwrap();
2727    /// # let _ = kernel;
2728    /// ```
2729    #[must_use]
2730    pub fn watermark_store(mut self, store: Arc<dyn CronWatermarkStore>) -> Self {
2731        self.watermarks = Some(store);
2732        self
2733    }
2734
2735    /// Takes every stateful store the builder has no other from `stores` (spec 3.2 §7.1): a
2736    /// store set on the builder, before or after, wins.
2737    ///
2738    /// | Builder store | From `stores` |
2739    /// |---|---|
2740    /// | [`run_store`](Self::run_store), [`process_store`](Self::process_store), [`schedule_store`](Self::schedule_store), [`spend_ledger`](Self::spend_ledger), [`agenda_store`](Self::agenda_store), [`watermark_store`](Self::watermark_store), [`agent_store`](Self::agent_store) | the store of the same name |
2741    /// | [`partitions`](Self::partitions) | a table over `partitions` |
2742    /// | the kill switch | [`KernelConfig::mirrored_governance`] over `governance`, unless [`governance`](Self::governance) is set, the configuration's is mirrored, or the bundle keeps `governance` in memory |
2743    /// | the control plane's settings store | `control`, unless the configuration names its own (`ControlPlaneConfig::with_control_store`) |
2744    ///
2745    /// The approval service, the drivers' supervisor and the activity ledger are built by the
2746    /// host over `approvals`, `drivers` and `ledger`, with its own routing, home and key.
2747    /// A runner built before the kernel shares the kernel's kill switch through
2748    /// `kernel.config().governance`.
2749    ///
2750    /// # Example
2751    ///
2752    /// ```rust
2753    /// use adk_kernel::Kernel;
2754    /// use adk_kernel::stores::{KernelStores, StoreOrigin};
2755    ///
2756    /// let kernel = Kernel::builder().stores(&KernelStores::in_memory()).build()?;
2757    /// assert!(kernel.store_uses().iter().all(|used| used.origin == StoreOrigin::Bundle));
2758    /// # Ok::<(), adk_kernel::KernelError>(())
2759    /// ```
2760    #[must_use]
2761    pub fn stores(mut self, stores: &KernelStores) -> Self {
2762        self.bundle = Some(stores.clone());
2763        self
2764    }
2765
2766    /// Refuses to build a kernel that would keep a stateful store in memory (spec 3.2
2767    /// §7.1): one the builder defaulted, one its [`KernelStores`] keeps in memory, or a kill
2768    /// switch that is not mirrored. Without it, the kernel's [`inventory`](Kernel::inventory)
2769    /// warns about each such store when the kernel starts. [`Kernel::store_uses`] reports each store either way.
2770    ///
2771    /// # Example
2772    ///
2773    /// ```rust
2774    /// use std::sync::Arc;
2775    /// use adk_core::InMemoryRunStore;
2776    /// use adk_kernel::Kernel;
2777    ///
2778    /// let refused = Kernel::builder()
2779    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2780    ///     .require_durable()
2781    ///     .build()
2782    ///     .unwrap_err();
2783    /// assert!(refused.to_string().contains("`process_store`"));
2784    /// ```
2785    #[must_use]
2786    pub fn require_durable(mut self) -> Self {
2787        self.require_durable = true;
2788        self
2789    }
2790
2791    /// Files signals in `partition` through `store` (spec 3.5 §7.10; feature `charter`):
2792    /// [`Kernel::signal_sink`] returns the partition's sink, and the kernel's
2793    /// [`inventory`](Kernel::inventory) knows the partition's signal triggers can fire.
2794    /// Registering a partition again replaces its store.
2795    ///
2796    /// # Example
2797    ///
2798    /// ```rust
2799    /// use std::sync::Arc;
2800    /// use adk_core::InMemoryRunStore;
2801    /// use adk_kernel::Kernel;
2802    /// use adk_kernel::charter::InMemorySignalStore;
2803    ///
2804    /// let kernel = Kernel::builder()
2805    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2806    ///     .signals(Arc::new(InMemorySignalStore::new()), "back-office")
2807    ///     .build()?;
2808    /// assert_eq!(kernel.signal_sink("back-office")?.partition().as_str(), "back-office");
2809    /// assert!(kernel.signal_sink("public").is_err());
2810    /// # Ok::<(), adk_kernel::KernelError>(())
2811    /// ```
2812    #[cfg(feature = "charter")]
2813    #[must_use]
2814    pub fn signals(
2815        mut self,
2816        store: Arc<dyn crate::charter::SignalStore>,
2817        partition: impl Into<PartitionId>,
2818    ) -> Self {
2819        self.signal_stores.insert(partition.into(), store);
2820        self
2821    }
2822
2823    /// Adds `warning` to the kernel's [`inventory`](Kernel::inventory), logged when the kernel
2824    /// starts: something the host or a kit would otherwise leave silent, such as a job it does
2825    /// not schedule and why.
2826    ///
2827    /// # Example
2828    ///
2829    /// ```rust
2830    /// use std::sync::Arc;
2831    /// use adk_core::InMemoryRunStore;
2832    /// use adk_kernel::Kernel;
2833    /// use adk_kernel::inventory::InventoryWarning;
2834    ///
2835    /// let kernel = Kernel::builder()
2836    ///     .run_store(Arc::new(InMemoryRunStore::new()))
2837    ///     .inventory_warning(InventoryWarning::new("site.job_unscheduled", "no channel for the digest"))
2838    ///     .build()?;
2839    /// assert!(kernel.inventory().warnings.iter().any(|warning| warning.code == "site.job_unscheduled"));
2840    /// # Ok::<(), adk_kernel::KernelError>(())
2841    /// ```
2842    #[must_use]
2843    pub fn inventory_warning(mut self, warning: InventoryWarning) -> Self {
2844        self.inventory_warnings.push(warning);
2845        self
2846    }
2847
2848    /// Builds the kernel. Nothing runs until [`Kernel::start`].
2849    ///
2850    /// # Errors
2851    ///
2852    /// Returns [`KernelError::Config`] when no run store is set, the control plane
2853    /// configuration is refused (K-I18), a partition has two progress sources, or
2854    /// [`require_durable`](Self::require_durable) is set and a stateful store would be kept
2855    /// in memory, naming each.
2856    pub fn build(self) -> Result<Kernel> {
2857        let mut slots = Slots { uses: Vec::new(), bundle: self.bundle.as_ref() };
2858        let runs = slots.take("run_store", self.runs, "runs", |b| Arc::clone(&b.runs)).ok_or_else(
2859            || KernelError::Config {
2860                reason: "a kernel needs a durable run store; call KernelBuilder::run_store or \
2861                         KernelBuilder::stores"
2862                    .into(),
2863            },
2864        )?;
2865        let processes: Arc<dyn ProcessStore> = slots
2866            .take("process_store", self.processes, "processes", |b| Arc::clone(&b.processes))
2867            .unwrap_or_else(|| {
2868                slots.defaulted("process_store", Arc::new(InMemoryProcessStore::new()))
2869            });
2870        let schedules =
2871            slots.take("schedule_store", self.schedules, "schedules", |b| Arc::clone(&b.schedules));
2872        let spend = slots.take("spend_ledger", self.spend, "spend", |b| Arc::clone(&b.spend));
2873        let agenda_store: Arc<dyn AgendaStore> = slots
2874            .take("agenda_store", self.agenda, "agenda", |b| Arc::clone(&b.agenda))
2875            .unwrap_or_else(|| {
2876                slots.defaulted("agenda_store", Arc::new(InMemoryAgendaStore::new()))
2877            });
2878        let partitions = slots
2879            .take("partitions", self.partitions, "partitions", |b| {
2880                Partitions::new(Arc::clone(&b.partitions))
2881            })
2882            .unwrap_or_else(|| slots.defaulted("partitions", Partitions::in_memory()));
2883        let watermarks: Arc<dyn CronWatermarkStore> = slots
2884            .take("watermark_store", self.watermarks, "watermarks", |b| Arc::clone(&b.watermarks))
2885            .unwrap_or_else(|| {
2886                slots.defaulted("watermark_store", Arc::new(InMemoryCronWatermarkStore::new()))
2887            });
2888        let agent_store: Arc<dyn crate::agents::AgentStore> = slots
2889            .take("agent_store", self.agent_store, "agents", |b| Arc::clone(&b.agents))
2890            .unwrap_or_else(|| {
2891                slots.defaulted("agent_store", Arc::new(crate::stores::InMemoryAgentStore::new()))
2892            });
2893        let mut config = self.config;
2894        slots.governance(&mut config, self.governance);
2895        slots.control_store(&mut config);
2896        let store_uses = slots.finish(self.require_durable)?;
2897        let mut partition_progress = BTreeMap::new();
2898        for (partition, source) in self.partition_progress {
2899            if partition_progress.contains_key(&partition) {
2900                return Err(KernelError::Config {
2901                    reason: format!(
2902                        "partition `{partition}` has two progress sources; register one per \
2903                         partition with KernelBuilder::partition_progress_source"
2904                    ),
2905                });
2906            }
2907            partition_progress.insert(partition, source);
2908        }
2909        config.control.validate()?;
2910        let mut names = std::collections::BTreeSet::new();
2911        if config.queues.is_empty()
2912            || !config.queues.iter().all(|queue| names.insert(queue.as_str().to_string()))
2913        {
2914            return Err(KernelError::Config {
2915                reason: format!(
2916                    "the kernel needs at least one queue class and each once; got {:?}",
2917                    config.queues
2918                ),
2919            });
2920        }
2921        if let Some(trail) = &self.audit {
2922            partitions.attach_audit(trail.clone());
2923        }
2924        let bus = EventBus::default();
2925        for sink in self.sinks {
2926            bus.add_sink(sink);
2927        }
2928        let mut inventory_warnings = self.inventory_warnings;
2929        if let Some(approvals) = &self.approvals {
2930            // Every held call reaches the inbox and the bus, however the host built the
2931            // service: a call no one can see is a process no one can resume.
2932            let operator =
2933                ApprovalPolicy::new([ApproverSelector::group(crate::agenda::OPERATOR_GROUP)])
2934                    .allow_self_approval();
2935            if !approvals.route_unrouted(Arc::new(operator)) {
2936                inventory_warnings.push(InventoryWarning::new(
2937                    InventoryWarning::APPROVALS_UNROUTED,
2938                    "the approval service takes no router from the kernel: a call it holds \
2939                     with no route of its own reaches no inbox. Build it with `with_router`",
2940                ));
2941            }
2942            if !approvals.add_notifier(Arc::new(crate::bus::ApprovalEvents::new(bus.clone()))) {
2943                inventory_warnings.push(InventoryWarning::new(
2944                    InventoryWarning::APPROVALS_UNHEARD,
2945                    "the approval service takes no notifier from the kernel: no `held` or \
2946                     `decided` event is published",
2947                ));
2948            }
2949        }
2950        let trigger_names = self.triggers.iter().map(|trigger| trigger.name.clone()).collect();
2951        let trigger_crons = trigger_cron_sources(
2952            &self.triggers,
2953            &self.wake_sources,
2954            &watermarks,
2955            config.salted_cron_jitter(),
2956        )?;
2957        #[cfg(feature = "proc")]
2958        let ledger = self.ledger.map(|ledger| ledger.with_clock(Arc::clone(&config.clock)));
2959        #[cfg(feature = "proc")]
2960        if let Some(ledger) = &ledger {
2961            bus.add_sink(Arc::new(LedgerEventSink::new(
2962                ledger.clone(),
2963                runs.clone(),
2964                processes.clone(),
2965            )));
2966        }
2967        let kernel_id = format!("kernel-{}", uuid::Uuid::new_v4());
2968        // The kernel's own proposers reach the agenda through this handle, bound below.
2969        let kernel_agenda = AgendaHandle::new();
2970        #[cfg(feature = "proc-baselines")]
2971        let proc = ledger.as_ref().map(|ledger| {
2972            let mut pass = crate::proc::baselines::BaselinePass::new(
2973                ledger.clone(),
2974                self.baselines.clone().unwrap_or_default(),
2975            );
2976            if let Some(phraser) = self.phraser.clone() {
2977                pass = pass.with_phraser(phraser);
2978            }
2979            Arc::new(crate::proc::baselines::ProcRuntime::new(
2980                pass,
2981                bus.clone(),
2982                self.audit.clone(),
2983                kernel_id.clone(),
2984                config.app_name.clone(),
2985                kernel_agenda.clone(),
2986            ))
2987        });
2988        let router = self
2989            .triggers
2990            .into_iter()
2991            .fold(WakeRouter::new(runs.clone(), processes.clone()), WakeRouter::with_trigger)
2992            .with_bus(bus.clone())
2993            .with_clock(Arc::clone(&config.clock));
2994        // The agents a person adds share one live target table with every worker (spec 3.3
2995        // §10 S4).
2996        let targets = Arc::new(crate::agents::Targets::new(
2997            self.partition_targets,
2998            Some(Arc::clone(&agent_store)),
2999        ));
3000        let sup = Arc::new(Supervision {
3001            app_name: config.app_name.clone(),
3002            kernel_id,
3003            queues: config.queues.clone(),
3004            runs: runs.clone(),
3005            processes,
3006            bus,
3007            governance: config.governance.clone(),
3008            audit: self.audit.clone(),
3009            sessions: self.sessions.clone(),
3010            progress: self.progress,
3011            partition_progress,
3012            workers: std::sync::OnceLock::new(),
3013            handles: std::sync::Mutex::new(Vec::new()),
3014            draining: std::sync::atomic::AtomicBool::new(false),
3015            local: std::sync::Mutex::new(HashMap::new()),
3016            roots_changed: tokio::sync::Notify::new(),
3017            watched: std::sync::Mutex::new(BTreeMap::new()),
3018            clock: Arc::clone(&config.clock),
3019            proactivity: config.proactivity.clone(),
3020            quiet_hours: config.quiet_hours,
3021            quotas: config.quotas.clone(),
3022            agenda: agenda_store,
3023            admission: tokio::sync::Mutex::new(()),
3024            rule_source: self.rule_source,
3025            reviewed: std::sync::Mutex::new(None),
3026            crons: std::sync::Mutex::new(BTreeMap::new()),
3027            watermarks,
3028            cron_started: std::sync::Mutex::new(None),
3029            cron_jitter: config.salted_cron_jitter(),
3030            triggers: trigger_names,
3031            #[cfg(feature = "proc-baselines")]
3032            proc: proc.clone(),
3033            targets: Arc::clone(&targets),
3034            partitions: partitions.clone(),
3035            control: Arc::new(crate::control::LastRead::new(config.control.control_store.clone())),
3036        });
3037        let run_finished = Arc::new(RunFinishedWakeSource::new());
3038        let subagent_backend = self.subagents.is_some().then(|| {
3039            Arc::new(crate::subagents::KernelSubagentBackend {
3040                processes: ProcessTable::supervised(Arc::clone(&sup), spend.clone()),
3041                sup: Arc::clone(&sup),
3042                kernel: std::sync::OnceLock::new(),
3043            })
3044        });
3045        let subagents = match (self.subagents, &subagent_backend) {
3046            (Some(mut sub_config), Some(backend)) => {
3047                let Some(sessions) = self.sessions.clone() else {
3048                    return Err(KernelError::Config {
3049                        reason: "background sub-agents need a session service; call \
3050                                 KernelBuilder::session_service"
3051                            .into(),
3052                    });
3053                };
3054                // A sub-agent runs on one of this kernel's queues.
3055                if !config.queues.iter().any(|queue| queue.as_str() == sub_config.queue) {
3056                    sub_config.queue = config
3057                        .queues
3058                        .iter()
3059                        .find(|queue| queue.as_str() == QueueClass::BACKGROUND)
3060                        .unwrap_or(&config.queues[0])
3061                        .as_str()
3062                        .to_string();
3063                }
3064                let backend: Arc<dyn SubagentBackend> = backend.clone();
3065                Some(DurableSubagents::new(runs.clone(), sessions, backend, sub_config))
3066            }
3067            _ => None,
3068        };
3069        for handle in &self.subagent_handles {
3070            if let Some(subagents) = &subagents {
3071                handle.bind(subagents);
3072            }
3073        }
3074        let hooks = Arc::new(KernelHooks {
3075            sup: Arc::clone(&sup),
3076            run_finished: run_finished.clone(),
3077            subagents: subagents.clone(),
3078        });
3079        let mut chain = self.workflows;
3080        #[cfg(feature = "charter")]
3081        if !self.kpi_trackers.is_empty() {
3082            chain.push(Arc::new(crate::charter::KpiTrackerExecutor::new(self.kpi_trackers)));
3083        }
3084        let caller_workflows: Option<Arc<dyn WorkflowExecutor>> = match chain.len() {
3085            0 | 1 => chain.pop(),
3086            _ => Some(Arc::new(WorkflowChain(chain))),
3087        };
3088        // The consolidation tick's workflow sits before the caller's (spec 3.2 §7.5).
3089        let consolidators = Arc::new(self.consolidators);
3090        let user_workflows = if consolidators.is_empty() {
3091            caller_workflows.clone()
3092        } else {
3093            Some(Arc::new(ConsolidationExecutor::new(
3094                Arc::clone(&sup),
3095                Arc::clone(&consolidators),
3096                kernel_agenda.clone(),
3097                caller_workflows.clone(),
3098            )) as Arc<dyn WorkflowExecutor>)
3099        };
3100        let workflows = Arc::new(KernelWorkflows {
3101            user: user_workflows,
3102            wake: KernelWakeExecutor::new(router.clone()),
3103            #[cfg(feature = "proc-baselines")]
3104            proc,
3105        });
3106        let workers = config
3107            .queues
3108            .iter()
3109            .map(|queue| {
3110                let mut worker = DurableWorker::new(runs.clone())
3111                    .with_config(config.worker_config(queue))
3112                    .with_clock(Arc::clone(&config.clock))
3113                    .with_governance(config.governance.clone())
3114                    .with_workflows(workflows.clone())
3115                    .with_hooks(hooks.clone());
3116                if let Some(trail) = &self.audit {
3117                    worker = worker.with_audit(trail.clone());
3118                }
3119                for (target, runner) in &self.agents {
3120                    worker = worker.with_agent(target.clone(), runner.clone());
3121                }
3122                // The agents a person adds, hosted while the kernel runs (spec 3.3 §10 S4).
3123                worker = worker.with_agent_table(targets.table.clone());
3124                (queue.clone(), worker)
3125            })
3126            .collect();
3127        let _ = sup.workers.set(workers);
3128        let mut wake_sources = self.wake_sources;
3129        wake_sources.extend(trigger_crons);
3130        wake_sources.push(run_finished);
3131        let processes = ProcessTable::supervised(Arc::clone(&sup), spend);
3132        let agenda = Agenda::new(
3133            Arc::clone(&sup),
3134            processes.clone(),
3135            self.approvals.clone(),
3136            self.audiences,
3137        );
3138        for handle in self.agenda_handles.iter().chain([&kernel_agenda]) {
3139            handle.bind(&agenda);
3140        }
3141        let consolidation = (!consolidators.is_empty())
3142            .then(|| ConsolidationTicker::new(Arc::clone(&sup), processes.clone(), consolidators));
3143        let adds_agents = self.agent_factory.is_some();
3144        let agent_table = crate::agents::Agents::new(crate::agents::AgentsParts {
3145            sup: Arc::clone(&sup),
3146            processes: processes.clone(),
3147            agenda: agenda.clone(),
3148            targets,
3149            store: agent_store,
3150            factory: self.agent_factory,
3151            approvals: self.approvals.clone(),
3152            statics: self.agents.keys().cloned().collect(),
3153            start_modes: config.control.start_modes.clone(),
3154            workflows: caller_workflows.clone(),
3155            #[cfg(feature = "drivers")]
3156            drivers: self.drivers.clone(),
3157            #[cfg(feature = "proc")]
3158            ledger: ledger.clone(),
3159        });
3160        for handle in &self.agents_handles {
3161            handle.bind(&agent_table);
3162        }
3163        let kernel = Kernel {
3164            inner: Arc::new(KernelInner {
3165                config,
3166                sup,
3167                processes,
3168                agenda,
3169                partitions,
3170                router,
3171                schedules,
3172                store_uses,
3173                approvals: self.approvals,
3174                sessions: self.sessions,
3175                agents: self.agents,
3176                agent_table,
3177                workflows: caller_workflows,
3178                wake_sources,
3179                queue_ingresses: self.queue_ingresses,
3180                adds_agents,
3181                #[cfg(feature = "charter")]
3182                signal_stores: self.signal_stores,
3183                inventory_warnings,
3184                consolidation,
3185                #[cfg(feature = "drivers")]
3186                drivers: self.drivers,
3187                runtime: tokio::sync::Mutex::new(Runtime::default()),
3188                status: Arc::new(RwLock::new(Status::default())),
3189                #[cfg(feature = "proc")]
3190                ledger,
3191                subagents,
3192                serves_routes: std::sync::atomic::AtomicBool::new(false),
3193            }),
3194        };
3195        if let Some(backend) = subagent_backend {
3196            let _ = backend.kernel.set(Arc::downgrade(&kernel.inner));
3197        }
3198        Ok(kernel)
3199    }
3200}
3201
3202/// The stateful stores a [`KernelBuilder`] resolves: each set one, else its bundle's, else
3203/// one in memory, with where each came from.
3204struct Slots<'a> {
3205    uses: Vec<StoreUse>,
3206    bundle: Option<&'a KernelStores>,
3207}
3208
3209impl Slots<'_> {
3210    /// `set`, else the bundle's store `field` picks, recording which; `None` with neither.
3211    fn take<T>(
3212        &mut self,
3213        store: &str,
3214        set: Option<T>,
3215        field: &str,
3216        pick: impl FnOnce(&KernelStores) -> T,
3217    ) -> Option<T> {
3218        if set.is_some() {
3219            self.uses.push(StoreUse::new(store, StoreOrigin::Set, false));
3220            return set;
3221        }
3222        let bundle = self.bundle?;
3223        self.uses.push(self.bundled(store, field));
3224        Some(pick(bundle))
3225    }
3226
3227    /// `memory`, recorded as the store the builder defaulted.
3228    fn defaulted<T>(&mut self, store: &str, memory: T) -> T {
3229        self.uses.push(StoreUse::new(store, StoreOrigin::Defaulted, true));
3230        memory
3231    }
3232
3233    fn bundled(&self, store: &str, field: &str) -> StoreUse {
3234        let bundle = self.bundle.expect("only called with a bundle");
3235        let mut used = StoreUse::new(store, StoreOrigin::Bundle, bundle.is_in_memory(field));
3236        used.bundle = Some(bundle.label().to_string());
3237        used
3238    }
3239
3240    /// The kill switch: the one set, a mirrored configuration's, else mirrored over the
3241    /// bundle's governance store when it is durable; one held in this process otherwise.
3242    fn governance(&mut self, config: &mut KernelConfig, set: Option<GovernanceControl>) {
3243        let used = match (set, self.bundle) {
3244            (Some(control), _) => {
3245                config.governance = control;
3246                StoreUse::new("governance", StoreOrigin::Set, !config.governance.is_mirrored())
3247            }
3248            (None, _) if config.governance.is_mirrored() => {
3249                StoreUse::new("governance", StoreOrigin::Set, false)
3250            }
3251            (None, Some(bundle)) => {
3252                if !bundle.is_in_memory("governance") {
3253                    config.governance =
3254                        KernelConfig::mirrored_governance(Arc::clone(&bundle.governance));
3255                }
3256                self.bundled("governance", "governance")
3257            }
3258            (None, None) => StoreUse::new("governance", StoreOrigin::Defaulted, true),
3259        };
3260        self.uses.push(used);
3261    }
3262
3263    /// The control plane's settings store: the configuration's own, else the bundle's.
3264    fn control_store(&mut self, config: &mut KernelConfig) {
3265        let used = if !config.control.has_default_control_store() {
3266            StoreUse::new("control_store", StoreOrigin::Set, false)
3267        } else if let Some(bundle) = self.bundle {
3268            config.control.control_store = Arc::clone(&bundle.control);
3269            self.bundled("control_store", "control")
3270        } else {
3271            StoreUse::new("control_store", StoreOrigin::Defaulted, true)
3272        };
3273        self.uses.push(used);
3274    }
3275
3276    /// The record of every store, refused when `require_durable` and one is held in memory;
3277    /// the inventory warns about each when the kernel starts.
3278    fn finish(self, require_durable: bool) -> Result<Vec<StoreUse>> {
3279        if require_durable {
3280            let held: Vec<String> = self
3281                .uses
3282                .iter()
3283                .filter(|used| used.in_memory)
3284                .map(|used| {
3285                    let why = match (used.origin, &used.bundle) {
3286                        (StoreOrigin::Bundle, Some(label)) => {
3287                            format!("the stores `{label}` keep it in memory")
3288                        }
3289                        (StoreOrigin::Set, _) => "the kill switch is not mirrored".to_string(),
3290                        _ => format!("defaulted; set it with {}", store_remedy(&used.store)),
3291                    };
3292                    format!("`{}` ({why})", used.store)
3293                })
3294                .collect();
3295            if !held.is_empty() {
3296                return Err(KernelError::Config {
3297                    reason: format!(
3298                        "the kernel requires durable stores, and these would lose their state \
3299                         on a restart: {}; give the builder durable stores with \
3300                         KernelBuilder::stores(&KernelStores::open(url)), or set each",
3301                        held.join(", ")
3302                    ),
3303                });
3304            }
3305        }
3306        Ok(self.uses)
3307    }
3308}
3309
3310/// The builder setter that gives a kernel its `store` durably.
3311fn store_remedy(store: &str) -> &'static str {
3312    match store {
3313        "governance" => "KernelBuilder::governance with KernelConfig::mirrored_governance",
3314        "control_store" => "ControlPlaneConfig::with_control_store",
3315        "partitions" => "KernelBuilder::partitions",
3316        "process_store" => "KernelBuilder::process_store",
3317        "agenda_store" => "KernelBuilder::agenda_store",
3318        "watermark_store" => "KernelBuilder::watermark_store",
3319        "agent_store" => "KernelBuilder::agent_store",
3320        "schedule_store" => "KernelBuilder::schedule_store",
3321        "spend_ledger" => "KernelBuilder::spend_ledger",
3322        _ => "KernelBuilder::run_store",
3323    }
3324}
3325
3326/// The kernel's own source for each cron expression of `triggers` no source in `sources`
3327/// ticks on (spec 3.2 §7.4, spec 3.5 §7.11): one per expression, so every trigger on it
3328/// matches each tick once, planned with the widest missed-tick policy of its triggers, its
3329/// cursor kept in `watermarks` across restarts, each tick delayed by `jitter`.
3330fn trigger_cron_sources(
3331    triggers: &[Trigger],
3332    sources: &[Arc<dyn WakeSource>],
3333    watermarks: &Arc<dyn CronWatermarkStore>,
3334    jitter: Option<Jitter>,
3335) -> Result<Vec<Arc<dyn WakeSource>>> {
3336    let covered: std::collections::BTreeSet<&str> =
3337        sources.iter().filter_map(|source| source.cron_expression()).collect();
3338    let mut crons: BTreeMap<&str, adk_core::schedule::MissedFirePolicy> = BTreeMap::new();
3339    for trigger in triggers {
3340        if let Wake::Cron { expr, missed } = &trigger.wake
3341            && !covered.contains(expr.as_str())
3342        {
3343            let widest = crons
3344                .get(expr.as_str())
3345                .map_or(*missed, |held| crate::wake::widest_policy(*held, *missed));
3346            crons.insert(expr, widest);
3347        }
3348    }
3349    crons
3350        .into_iter()
3351        .map(|(expr, missed)| {
3352            let name =
3353                format!("trigger-cron:{}", expr.split_whitespace().collect::<Vec<_>>().join("_"));
3354            let watermark = SourceWatermark::new(Arc::clone(watermarks), name.clone());
3355            let mut source = CronWakeSource::watermarked(name, expr, missed, Arc::new(watermark))?;
3356            if let Some(jitter) = jitter {
3357                source = source.with_jitter(jitter);
3358            }
3359            Ok(Arc::new(source) as Arc<dyn WakeSource>)
3360        })
3361        .collect()
3362}
3363
3364#[cfg(test)]
3365mod tests {
3366    use adk_core::{InMemoryRunStore, NewRun};
3367    use serde_json::json;
3368
3369    use super::*;
3370    use crate::process::{ProcessKind, ProcessSpec};
3371    use crate::wake::WakeSet;
3372
3373    async fn eventually(what: &str, mut probe: impl FnMut() -> bool) {
3374        let started = tokio::time::Instant::now();
3375        while started.elapsed() < Duration::from_secs(3) {
3376            if probe() {
3377                return;
3378            }
3379            tokio::time::sleep(Duration::from_millis(10)).await;
3380        }
3381        panic!("timed out waiting for {what}");
3382    }
3383
3384    /// Two kernels built from the defaults in one process and one home both start: the
3385    /// defaults serve no control plane, so neither takes the other's socket or pipe.
3386    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3387    async fn kernels_built_from_the_defaults_share_a_home() {
3388        let home = tempfile::tempdir().unwrap();
3389        let config = KernelConfig::default().with_home(home.path());
3390        assert_eq!((config.control.socket.as_deref(), config.control.http), (None, None));
3391        let build = || {
3392            Kernel::builder()
3393                .config(config.clone())
3394                .run_store(Arc::new(InMemoryRunStore::new()))
3395                .build()
3396                .unwrap()
3397        };
3398        let (first, second) = (build(), build());
3399        first.start().await.unwrap();
3400        second.start().await.unwrap();
3401        assert!(!home.path().join(ControlPlaneConfig::DEFAULT_SOCKET).exists());
3402        second.stop().await.unwrap();
3403        first.stop().await.unwrap();
3404
3405        // Asked for, the socket at the home is still one kernel's.
3406        #[cfg(unix)]
3407        {
3408            let served = config.with_control(ControlPlaneConfig::default());
3409            let build = || {
3410                Kernel::builder()
3411                    .config(served.clone())
3412                    .run_store(Arc::new(InMemoryRunStore::new()))
3413                    .build()
3414                    .unwrap()
3415            };
3416            let (first, second) = (build(), build());
3417            first.start().await.unwrap();
3418            let error = second.start().await.unwrap_err();
3419            assert!(error.to_string().contains("already listens"), "{error}");
3420            first.stop().await.unwrap();
3421        }
3422    }
3423
3424    /// A shared governance store whose reads answer after `delay`, and fail while unreachable.
3425    struct SlowGovernanceStore {
3426        inner: Arc<adk_core::InMemoryGovernanceStateStore>,
3427        delay: Duration,
3428        reachable: Arc<std::sync::atomic::AtomicBool>,
3429    }
3430
3431    impl SlowGovernanceStore {
3432        fn over(inner: &Arc<adk_core::InMemoryGovernanceStateStore>, delay: Duration) -> Self {
3433            Self {
3434                inner: Arc::clone(inner),
3435                delay,
3436                reachable: Arc::new(std::sync::atomic::AtomicBool::new(true)),
3437            }
3438        }
3439    }
3440
3441    #[async_trait]
3442    impl GovernanceStateStore for SlowGovernanceStore {
3443        async fn get(
3444            &self,
3445            scope: &adk_core::GovernanceScope,
3446        ) -> adk_core::Result<Option<adk_core::GovernanceState>> {
3447            tokio::time::sleep(self.delay).await;
3448            if !self.reachable.load(Ordering::SeqCst) {
3449                return Err(adk_core::AdkError::session("the governance store is unreachable"));
3450            }
3451            self.inner.get(scope).await
3452        }
3453
3454        async fn set(
3455            &self,
3456            scope: adk_core::GovernanceScope,
3457            expected_epoch: u64,
3458            frozen: bool,
3459            reason: Option<String>,
3460            issued_by: Option<adk_core::SubjectRef>,
3461        ) -> adk_core::Result<adk_core::GovernanceState> {
3462            self.inner.set(scope, expected_epoch, frozen, reason, issued_by).await
3463        }
3464
3465        async fn list(&self) -> adk_core::Result<Vec<adk_core::GovernanceState>> {
3466            self.inner.list().await
3467        }
3468    }
3469
3470    /// A run no worker claims for an hour, so its process stays a queued sleeper.
3471    fn sleeper() -> NewRun {
3472        NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }))
3473            .with_not_before(chrono::Utc::now() + chrono::Duration::hours(1))
3474    }
3475
3476    fn operator() -> AuditActor {
3477        AuditActor::subject(adk_core::SubjectRef::human("operator"))
3478    }
3479
3480    /// K9's race: work spawned as soon as `start` returns is decided by the mirrored store,
3481    /// even when the store answers slower than the rest of the start-up, rather than refused
3482    /// as never read.
3483    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3484    async fn work_spawned_once_start_returns_is_not_refused_as_never_read() {
3485        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
3486        let slow = SlowGovernanceStore::over(&store, Duration::from_millis(500));
3487        let kernel = Kernel::builder()
3488            .config(
3489                KernelConfig::default()
3490                    .with_governance(KernelConfig::mirrored_governance(Arc::new(slow))),
3491            )
3492            .run_store(Arc::new(InMemoryRunStore::new()))
3493            .build()
3494            .unwrap();
3495        kernel.start().await.unwrap();
3496        let spawned =
3497            kernel.processes().spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive)).await;
3498        assert!(spawned.is_ok(), "{:?}", spawned.err());
3499        kernel.stop().await.unwrap();
3500    }
3501
3502    /// The kill switch stays fail-closed: a kernel whose store cannot be read starts and
3503    /// refuses work until its mirror reads the store.
3504    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3505    async fn a_kernel_whose_governance_store_is_unreachable_refuses_work_until_it_is_read() {
3506        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
3507        let slow = SlowGovernanceStore::over(&store, Duration::ZERO);
3508        let reachable = Arc::clone(&slow.reachable);
3509        reachable.store(false, Ordering::SeqCst);
3510        let kernel = Kernel::builder()
3511            .config(
3512                KernelConfig::default()
3513                    .with_governance(KernelConfig::mirrored_governance(Arc::new(slow))),
3514            )
3515            .run_store(Arc::new(InMemoryRunStore::new()))
3516            .build()
3517            .unwrap();
3518        kernel.start().await.unwrap();
3519        let refused = kernel
3520            .processes()
3521            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
3522            .await
3523            .unwrap_err();
3524        assert!(
3525            matches!(&refused, KernelError::Frozen { reason } if reason.contains("last read never")),
3526            "{refused:?}"
3527        );
3528
3529        reachable.store(true, Ordering::SeqCst);
3530        let started = tokio::time::Instant::now();
3531        while kernel.config().governance.check().is_err() {
3532            assert!(started.elapsed() < Duration::from_secs(3), "the mirror never read the store");
3533            tokio::time::sleep(Duration::from_millis(10)).await;
3534        }
3535        kernel
3536            .processes()
3537            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
3538            .await
3539            .unwrap();
3540        kernel.stop().await.unwrap();
3541    }
3542
3543    /// A replica that starts while the replicated freeze is in force reads it before it wakes
3544    /// anything: the processes the freeze parked stay parked until the unfreeze.
3545    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3546    async fn a_replica_started_during_a_freeze_keeps_the_frozen_processes_parked() {
3547        let store = Arc::new(adk_core::InMemoryGovernanceStateStore::new());
3548        let runs: Arc<dyn DurableRunStore> = Arc::new(InMemoryRunStore::new());
3549        let processes: Arc<dyn ProcessStore> = Arc::new(InMemoryProcessStore::new());
3550        let replica = |delay: Duration| {
3551            let control = KernelConfig::mirrored_governance(Arc::new(SlowGovernanceStore::over(
3552                &store, delay,
3553            )));
3554            Kernel::builder()
3555                .config(KernelConfig::default().with_governance(control))
3556                .run_store(Arc::clone(&runs))
3557                .process_store(Arc::clone(&processes))
3558                .build()
3559                .unwrap()
3560        };
3561        let first = replica(Duration::ZERO);
3562        first.start().await.unwrap();
3563        let process = first
3564            .processes()
3565            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
3566            .await
3567            .unwrap();
3568        let pid = process.meta.pid.clone();
3569        processes.put(process.meta.with_suspension(Suspension::Freeze)).await.unwrap();
3570        first.freeze("incident 9", operator()).await.unwrap();
3571        first.stop().await.unwrap();
3572
3573        // The new replica's store answers slower than the rest of its start-up.
3574        let second = replica(Duration::from_millis(300));
3575        second.start().await.unwrap();
3576        let parked = processes.get(&pid).await.unwrap().unwrap();
3577        assert_eq!(parked.suspended_by, Some(Suspension::Freeze));
3578        let refused = second
3579            .processes()
3580            .spawn(sleeper(), ProcessSpec::new(ProcessKind::Interactive))
3581            .await
3582            .unwrap_err();
3583        assert!(
3584            matches!(&refused, KernelError::Frozen { reason } if reason == "incident 9"),
3585            "{refused:?}"
3586        );
3587
3588        second.unfreeze(operator()).await.unwrap();
3589        assert_eq!(processes.get(&pid).await.unwrap().unwrap().suspended_by, None);
3590        second.stop().await.unwrap();
3591    }
3592
3593    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3594    async fn a_file_wake_spawned_after_start_is_watched_until_no_sleeper_needs_it() {
3595        let dir = tempfile::tempdir().unwrap();
3596        let kernel = Kernel::builder()
3597            .config(
3598                KernelConfig::default()
3599                    // Long enough that only the spawn's signal can explain a prompt watch.
3600                    .with_scheduler_tick(Duration::from_secs(60))
3601                    .with_control(ControlPlaneConfig::default().without_socket()),
3602            )
3603            .run_store(Arc::new(InMemoryRunStore::new()))
3604            .build()
3605            .unwrap();
3606        kernel.start().await.unwrap();
3607        let root = std::fs::canonicalize(dir.path()).unwrap();
3608        assert!(kernel.inner.sup.watched_roots().is_empty());
3609
3610        let wake = WakeSet::any_of([Wake::FileChange {
3611            root: dir.path().to_path_buf(),
3612            glob: "notes.md".into(),
3613            debounce: Duration::from_millis(100),
3614        }]);
3615        // Not claimable for an hour: it stays a queued sleeper the whole test.
3616        let run =
3617            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }))
3618                .with_not_before(chrono::Utc::now() + chrono::Duration::hours(1));
3619        let process = kernel
3620            .processes()
3621            .spawn(run, ProcessSpec::new(ProcessKind::Interactive).with_wake(wake))
3622            .await
3623            .unwrap();
3624        eventually("the root to be watched", || kernel.inner.sup.watched_roots() == [root.clone()])
3625            .await;
3626
3627        kernel.processes().kill(&process.meta.pid, "not needed").await.unwrap();
3628        eventually("the root to be dropped", || kernel.inner.sup.watched_roots().is_empty()).await;
3629        kernel.stop().await.unwrap();
3630    }
3631
3632    /// A standing cron trigger fires with no source registered for it: the kernel adds one
3633    /// watermarked source per expression, so two triggers on one expression each fire once
3634    /// per tick, and a registered source on the expression takes its place (spec 3.5 §7.11).
3635    /// The control plane's address is readable once it listens.
3636    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3637    async fn a_standing_cron_trigger_fires_through_the_kernels_own_source() {
3638        let every_second = "* * * * * *";
3639        let wake =
3640            || Wake::Cron { expr: every_second.into(), missed: adk_core::MissedFirePolicy::Skip };
3641        let template = |target: &str| {
3642            NewRun::new("background", "adk-rust", "alice", target, json!({ "text": "tick" }))
3643        };
3644        let runs: Arc<dyn DurableRunStore> = Arc::new(InMemoryRunStore::new());
3645        let loopback: std::net::SocketAddr = "127.0.0.1:0".parse().unwrap();
3646        let kernel =
3647            Kernel::builder()
3648                .config(KernelConfig::default().with_control(
3649                    ControlPlaneConfig::default().without_socket().with_http(loopback),
3650                ))
3651                .run_store(Arc::clone(&runs))
3652                .trigger(Trigger::new("digest-a", wake(), template("digest-a")))
3653                .trigger(Trigger::new("digest-b", wake(), template("digest-b")))
3654                .build()
3655                .unwrap();
3656        let crons: Vec<&str> =
3657            kernel.inner.wake_sources.iter().filter_map(|s| s.cron_expression()).collect();
3658        assert_eq!(crons, [every_second], "one source for the expression");
3659        assert_eq!(kernel.control_addr().await, None, "nothing listens before the start");
3660        kernel.start().await.unwrap();
3661        let addr = kernel.control_addr().await.expect("the control plane listens");
3662        assert_ne!(addr.port(), 0, "the bound port, not the configured 0");
3663
3664        let started = tokio::time::Instant::now();
3665        let fired = loop {
3666            let targets: Vec<String> = runs
3667                .list(adk_core::RunFilter::default())
3668                .await
3669                .unwrap()
3670                .into_iter()
3671                .map(|run| run.target)
3672                .collect();
3673            if ["digest-a", "digest-b"].iter().all(|t| targets.iter().any(|run| run == t)) {
3674                break targets;
3675            }
3676            assert!(started.elapsed() < Duration::from_secs(5), "no trigger fired: {targets:?}");
3677            tokio::time::sleep(Duration::from_millis(50)).await;
3678        };
3679        kernel.stop().await.unwrap();
3680        let count = |t: &str| fired.iter().filter(|run| *run == t).count();
3681        assert!(count("digest-a").abs_diff(count("digest-b")) <= 1, "{fired:?}");
3682
3683        // A registered source on the expression takes the kernel's place.
3684        let watermarks: Arc<dyn CronWatermarkStore> = Arc::new(InMemoryCronWatermarkStore::new());
3685        let own = CronWakeSource::watermarked(
3686            "mine",
3687            every_second,
3688            adk_core::MissedFirePolicy::Skip,
3689            Arc::new(SourceWatermark::new(watermarks, "mine")),
3690        )
3691        .unwrap();
3692        let kernel = Kernel::builder()
3693            .run_store(Arc::new(InMemoryRunStore::new()))
3694            .wake_source(Arc::new(own))
3695            .trigger(Trigger::new("digest-a", wake(), template("digest-a")))
3696            .build()
3697            .unwrap();
3698        let names: Vec<&str> = kernel
3699            .inner
3700            .wake_sources
3701            .iter()
3702            .filter(|s| s.cron_expression().is_some())
3703            .map(|s| s.name())
3704            .collect();
3705        assert_eq!(names, ["mine"]);
3706    }
3707
3708    /// A sleeper on a cron wake no registered source covers (spec 3.2 §7.4, §8.1 `wake
3709    /// --cron`), on a manual clock: the kernel fires it at each occurrence — the first
3710    /// sleeper, then the successor it re-armed — and forgets the expression once the
3711    /// series is killed.
3712    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3713    async fn a_cron_sleeper_wakes_at_each_occurrence_until_it_is_killed() {
3714        use adk_core::{Llm, ManualClock, RunState};
3715        use adk_model::{ScriptedLlm, ScriptedResponse};
3716
3717        let clock = ManualClock::new(chrono::Utc::now());
3718        let runs: Arc<dyn DurableRunStore> =
3719            Arc::new(InMemoryRunStore::new().with_clock(Arc::new(clock.clone())));
3720        let model = Arc::new(ScriptedLlm::new(
3721            "scripted",
3722            ["first occurrence", "second occurrence"].map(ScriptedResponse::text),
3723        ));
3724        let agent = adk_agent::LlmAgentBuilder::new("agent")
3725            .model(Arc::clone(&model) as Arc<dyn Llm>)
3726            .build()
3727            .unwrap();
3728        let runner = Arc::new(
3729            Runner::builder()
3730                .app_name("adk-rust")
3731                .agent(Arc::new(agent))
3732                .session_service(Arc::new(adk_session::InMemorySessionService::new()))
3733                .build()
3734                .unwrap(),
3735        );
3736        let kernel = Kernel::builder()
3737            .config(
3738                KernelConfig::default()
3739                    .with_scheduler_tick(Duration::from_millis(50))
3740                    .with_clock(Arc::new(clock.clone()))
3741                    .with_control(ControlPlaneConfig::default().without_socket()),
3742            )
3743            .run_store(Arc::clone(&runs))
3744            .agent("adk-rust", runner)
3745            .build()
3746            .unwrap();
3747        kernel.start().await.unwrap();
3748        let hourly = "0 0 * * * *";
3749        let wake = WakeSet::any_of([Wake::Cron {
3750            expr: hourly.into(),
3751            missed: adk_core::MissedFirePolicy::Skip,
3752        }]);
3753        let run =
3754            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }));
3755        let first = kernel
3756            .processes()
3757            .spawn(run, ProcessSpec::new(ProcessKind::Scheduled).with_wake(wake.clone()))
3758            .await
3759            .unwrap()
3760            .meta
3761            .pid;
3762        let state = |pid: String| {
3763            let runs = Arc::clone(&runs);
3764            async move { runs.get(&pid).await.unwrap().map(|run| run.state) }
3765        };
3766        let wait_for = |what: &'static str, pid: String, wanted: RunState| async move {
3767            let started = tokio::time::Instant::now();
3768            while state(pid.clone()).await != Some(wanted) {
3769                assert!(started.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
3770                tokio::time::sleep(Duration::from_millis(20)).await;
3771            }
3772        };
3773        let successor = |parent: String| {
3774            let kernel = kernel.clone();
3775            async move {
3776                let started = tokio::time::Instant::now();
3777                loop {
3778                    let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
3779                    if let Some(next) =
3780                        processes.iter().find(|p| p.meta.parent.as_deref() == Some(parent.as_str()))
3781                    {
3782                        return next.meta.pid.clone();
3783                    }
3784                    assert!(
3785                        started.elapsed() < Duration::from_secs(5),
3786                        "timed out waiting for the successor of {parent}"
3787                    );
3788                    tokio::time::sleep(Duration::from_millis(20)).await;
3789                }
3790            }
3791        };
3792        wait_for("the sleeper asleep", first.clone(), RunState::Waiting).await;
3793        eventually("the expression to be fired by the kernel", || {
3794            kernel.inner.sup.watched_crons() == [hourly]
3795        })
3796        .await;
3797        assert_eq!(model.requests().len(), 0, "asleep until the hour");
3798
3799        // Each hour is routed a second after it is due: a `skip` wake fires on time only.
3800        let spec = adk_core::ScheduleSpec::Cron { expr: hourly.into(), timezone: "UTC".into() };
3801        let first_hour = spec.next_after(clock.now()).unwrap().unwrap();
3802        clock.set(first_hour + chrono::Duration::seconds(1));
3803        wait_for("the first occurrence's run", first.clone(), RunState::Completed).await;
3804        let second = successor(first.clone()).await;
3805        wait_for("the successor asleep", second.clone(), RunState::Waiting).await;
3806        let meta = kernel.processes().get(&second).await.unwrap().unwrap().meta;
3807        assert_eq!(meta.wake, Some(wake.clone()), "the successor sleeps on the same cron wake");
3808
3809        clock.set(spec.next_after(first_hour).unwrap().unwrap() + chrono::Duration::seconds(1));
3810        wait_for("the second occurrence's run", second.clone(), RunState::Completed).await;
3811        assert_eq!(model.requests().len(), 2, "one run per occurrence");
3812        let third = successor(second).await;
3813        wait_for("the next successor asleep", third.clone(), RunState::Waiting).await;
3814
3815        kernel.processes().kill(&third, "the series ends").await.unwrap();
3816        eventually("the expression to be dropped", || kernel.inner.sup.watched_crons().is_empty())
3817            .await;
3818        tokio::time::sleep(Duration::from_millis(300)).await;
3819        let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
3820        assert!(
3821            !processes.iter().any(|p| p.meta.parent.as_deref() == Some(third.as_str())),
3822            "a killed sleeper is not re-armed"
3823        );
3824        kernel.stop().await.unwrap();
3825    }
3826
3827    /// A cron sleeper run now (spec 3.2 §7.4 parity): refused while frozen, queued once per
3828    /// request id, woken with a wake reason that says so, re-armed on the same cron wake, and
3829    /// the expression's watermark untouched; the next tick is jittered: submitted at its
3830    /// scheduled time and keyed by it, routed only after the offset. A standing cron trigger
3831    /// runs now too, and a name no cron trigger has is refused.
3832    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3833    async fn a_cron_sleeper_runs_now_and_its_next_tick_waits_out_the_jitter() {
3834        use adk_core::schedule::{Jitter, ScheduleSpec};
3835        use adk_core::{Llm, ManualClock, RunFilter, RunState};
3836        use adk_model::{ScriptedLlm, ScriptedResponse};
3837
3838        let clock = ManualClock::new(
3839            chrono::DateTime::parse_from_rfc3339("2026-11-18T09:10:00Z").unwrap().into(),
3840        );
3841        let runs: Arc<dyn DurableRunStore> =
3842            Arc::new(InMemoryRunStore::new().with_clock(Arc::new(clock.clone())));
3843        let model = Arc::new(ScriptedLlm::new(
3844            "scripted",
3845            ["ran now", "the hourly tick", "the trigger now"].map(ScriptedResponse::text),
3846        ));
3847        let agent = adk_agent::LlmAgentBuilder::new("agent")
3848            .model(Arc::clone(&model) as Arc<dyn Llm>)
3849            .build()
3850            .unwrap();
3851        let runner = Arc::new(
3852            Runner::builder()
3853                .app_name("adk-rust")
3854                .agent(Arc::new(agent))
3855                .session_service(Arc::new(adk_session::InMemorySessionService::new()))
3856                .build()
3857                .unwrap(),
3858        );
3859        let jitter = Jitter::new(50, Duration::from_secs(3600));
3860        let yearly = "0 0 0 1 1 *";
3861        let kernel = Kernel::builder()
3862            .config(
3863                KernelConfig::default()
3864                    .with_scheduler_tick(Duration::from_millis(50))
3865                    .with_clock(Arc::new(clock.clone()))
3866                    .with_cron_jitter(jitter)
3867                    .with_control(ControlPlaneConfig::default().without_socket()),
3868            )
3869            .run_store(Arc::clone(&runs))
3870            .agent("adk-rust", runner)
3871            .trigger(Trigger::new(
3872                "digest",
3873                Wake::Cron { expr: yearly.into(), missed: adk_core::MissedFirePolicy::Skip },
3874                NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "d" })),
3875            ))
3876            .build()
3877            .unwrap();
3878        kernel.start().await.unwrap();
3879        let hourly = "0 0 * * * *";
3880        let wake = WakeSet::any_of([Wake::Cron {
3881            expr: hourly.into(),
3882            missed: adk_core::MissedFirePolicy::Skip,
3883        }]);
3884        let run =
3885            NewRun::new("background", "adk-rust", "alice", "adk-rust", json!({ "text": "x" }));
3886        let first = kernel
3887            .processes()
3888            .spawn(run, ProcessSpec::new(ProcessKind::Scheduled).with_wake(wake.clone()))
3889            .await
3890            .unwrap()
3891            .meta
3892            .pid;
3893        let state = |pid: String| {
3894            let runs = Arc::clone(&runs);
3895            async move { runs.get(&pid).await.unwrap().map(|run| run.state) }
3896        };
3897        let wait_for = |what: &'static str, pid: String, wanted: RunState| async move {
3898            let started = tokio::time::Instant::now();
3899            while state(pid.clone()).await != Some(wanted) {
3900                assert!(started.elapsed() < Duration::from_secs(5), "timed out waiting for {what}");
3901                tokio::time::sleep(Duration::from_millis(20)).await;
3902            }
3903        };
3904        wait_for("the sleeper asleep", first.clone(), RunState::Waiting).await;
3905        eventually("the expression to be fired by the kernel", || {
3906            kernel.inner.sup.watched_crons() == [hourly]
3907        })
3908        .await;
3909        let source = format!("kernel:{hourly}");
3910        let watermark = || async { kernel.inner.sup.watermarks.read(&source).await.unwrap() };
3911        let cursor = watermark().await;
3912
3913        let target = || RunNowTarget::Process { pid: first.clone() };
3914        kernel.freeze("incident", AuditActor::default()).await.unwrap();
3915        let refused = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await;
3916        assert!(matches!(refused, Err(KernelError::Frozen { .. })), "{refused:?}");
3917        kernel.unfreeze(AuditActor::default()).await.unwrap();
3918
3919        let queued = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await.unwrap();
3920        assert_eq!(
3921            (queued.key.as_str(), queued.existing),
3922            (format!("now:{first}:r-1").as_str(), false)
3923        );
3924        let again = kernel.run_now(target(), Some("r-1"), AuditActor::default()).await.unwrap();
3925        assert!(
3926            again.existing && again.wake_run_id == queued.wake_run_id,
3927            "one wake per request id"
3928        );
3929        wait_for("the run now", first.clone(), RunState::Completed).await;
3930        let reason = crate::WakeReason::recorded(
3931            &kernel.processes().get(&first).await.unwrap().unwrap().meta,
3932        )
3933        .expect("the run now records its wake reason");
3934        assert_eq!(reason.source, crate::wake::RUN_NOW_SOURCE);
3935        assert!(reason.payload.contains(r#""run_now":true"#), "{}", reason.payload);
3936        assert_eq!(watermark().await, cursor, "a run now moves no watermark");
3937        let second = loop {
3938            let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
3939            if let Some(next) =
3940                processes.iter().find(|p| p.meta.parent.as_deref() == Some(first.as_str()))
3941            {
3942                break next.meta.pid.clone();
3943            }
3944            tokio::time::sleep(Duration::from_millis(20)).await;
3945        };
3946        wait_for("the successor asleep", second.clone(), RunState::Waiting).await;
3947        assert_eq!(
3948            kernel.processes().get(&second).await.unwrap().unwrap().meta.wake,
3949            Some(wake.clone()),
3950            "the successor sleeps on the same cron wake"
3951        );
3952        let refused = kernel
3953            .run_now(RunNowTarget::Process { pid: "missing".into() }, None, AuditActor::default())
3954            .await;
3955        assert!(matches!(refused, Err(KernelError::NotFound { .. })), "{refused:?}");
3956
3957        // The 10:00 tick is submitted when it falls due, keyed by 10:00, and waits out its
3958        // offset before it is routed.
3959        let ten = chrono::DateTime::parse_from_rfc3339("2026-11-18T10:00:00Z").unwrap().into();
3960        let spec = ScheduleSpec::Cron { expr: hourly.into(), timezone: "UTC".into() };
3961        let offset = jitter.salted("adk-rust").offset_in(&spec, &source, ten);
3962        assert!(offset < Duration::from_secs(30 * 60), "under half the hour: {offset:?}");
3963        clock.set(ten + chrono::Duration::seconds(1));
3964        let key = crate::wake::keys::cron(&source, ten);
3965        let wake_run = loop {
3966            let found = runs
3967                .list(RunFilter::default())
3968                .await
3969                .unwrap()
3970                .into_iter()
3971                .find(|run| run.idempotency_key.as_deref() == Some(key.as_str()));
3972            if let Some(found) = found {
3973                break found;
3974            }
3975            tokio::time::sleep(Duration::from_millis(20)).await;
3976        };
3977        if offset >= Duration::from_secs(2) {
3978            assert_eq!(
3979                wake_run.not_before,
3980                Some(ten + chrono::Duration::from_std(offset).unwrap())
3981            );
3982            tokio::time::sleep(Duration::from_millis(300)).await;
3983            assert_eq!(
3984                state(second.clone()).await,
3985                Some(RunState::Waiting),
3986                "not before the offset"
3987            );
3988        }
3989        clock.set(ten + chrono::Duration::from_std(offset).unwrap() + chrono::Duration::seconds(1));
3990        wait_for("the jittered tick's run", second.clone(), RunState::Completed).await;
3991        assert_eq!(model.requests().len(), 2, "the run now and the tick");
3992
3993        let refused = kernel
3994            .run_now(RunNowTarget::Trigger { name: "nope".into() }, None, AuditActor::default())
3995            .await;
3996        assert!(matches!(refused, Err(KernelError::Config { .. })), "{refused:?}");
3997        kernel
3998            .run_now(
3999                RunNowTarget::Trigger { name: "digest".into() },
4000                Some("t-1"),
4001                AuditActor::default(),
4002            )
4003            .await
4004            .unwrap();
4005        let started = tokio::time::Instant::now();
4006        loop {
4007            let processes = kernel.processes().ps(ProcessFilter::default()).await.unwrap();
4008            let fired = processes.iter().find(|p| {
4009                p.meta.kind == ProcessKind::Triggered { source: "digest".into() }
4010                    && p.run.state == RunState::Completed
4011            });
4012            if fired.is_some() {
4013                break;
4014            }
4015            assert!(started.elapsed() < Duration::from_secs(5), "the trigger did not run now");
4016            tokio::time::sleep(Duration::from_millis(20)).await;
4017        }
4018        assert_eq!(model.requests().len(), 3, "and the trigger run now");
4019        kernel.stop().await.unwrap();
4020    }
4021}