Skip to main content

adk_kernel/managed/
def.rs

1//! The kernel block of a managed agent definition (spec 3.2 §7.13, §10 M1).
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use adk_agent::ambient::CronTrigger;
6use adk_core::schedule::MissedFirePolicy;
7use adk_managed::types::ManagedAgentDef;
8use serde::{Deserialize, Serialize};
9
10use crate::agenda::ProactivityPolicy;
11use crate::consolidation::ConsolidationTick;
12use crate::drivers::{DriverManifest, DriverSandbox};
13use crate::error::{KernelError, Result};
14use crate::partition::{CrossPartition, Partition, PartitionId, PartitionMode};
15use crate::sched::QueueClass;
16use crate::wake::Wake;
17
18/// The [`ManagedAgentDef::metadata`] key a [`KernelDef`] travels under, beside the
19/// harness's `adk.harness` (spec 3.2 §7.13, §10 M1).
20///
21/// The block is JSON in a string value, as the harness block is, so a store or service that
22/// keeps a `ManagedAgentDef` — the managed state store's session records included — keeps
23/// it unchanged.
24///
25/// # Example
26///
27/// ```rust
28/// assert_eq!(adk_kernel::managed::KERNEL_DEF_METADATA_KEY, "adk.kernel");
29/// ```
30pub const KERNEL_DEF_METADATA_KEY: &str = "adk.kernel";
31
32/// The user a wake set's processes run for when it names none (spec 3.2 §7.13).
33pub const DEFAULT_WAKE_USER: &str = "kernel";
34
35/// The values of [`PartitionDef::cross_partition`], as the partition record names them
36/// (spec 3.2 §7.8).
37pub const CROSS_PARTITION_VALUES: [&str; 2] = ["deny", "coordinator_with_approval"];
38
39/// The kernel part of a hosted definition: partitions and their coordinator, drivers, the
40/// proactivity policy and wake sets (spec 3.2 §7.8, §7.13, §10 M1).
41///
42/// A `KernelDef` travels as JSON under [`KERNEL_DEF_METADATA_KEY`] in a
43/// [`ManagedAgentDef`]'s metadata, beside the harness block, so the managed runtime stores
44/// and rebuilds it like any other definition, and a [`KernelResolver`](super::KernelResolver)
45/// hosts the definition on its tenant's kernel. The block is written in the kernel's own
46/// camelCase wire shape — its wakes, driver manifests and proactivity policy are the
47/// kernel's types — and an unknown key of the block, a partition or a wake set refuses it.
48///
49/// | Field | In the tenant's kernel |
50/// |---|---|
51/// | `wakeSets` | standing triggers: each wake starts a governed run of the definition's agent |
52/// | `proactivity` | the tenant kernel's [`ProactivityPolicy`]: open proposals, the daily proactive budget, quiet hours, how proposals are approved; the consolidation tick runs only when the block sets `consolidation` (§13 Q1) |
53/// | `drivers` | real [`DriverManifest`]s, validated; with the tenant's driver supervisor (`TenantKernelBuilder::drivers`), each one a declared partition mounts is proposed in the tenant's approval inbox and mounted when a person approves it, then served to that partition's harness (spec 3.2 §7.7) |
54/// | `partitions`, `coordinator` | as `[[kernel.partitions]]` and `kernel.coordinator` in `harness.toml`: each partition in the tenant's partition table, its tenant the hosting tenant, with an agent of its own built by the tenant's [`PartitionAgentResolver`](super::PartitionAgentResolver) — one harness per partition — as the target `<definition>@<partition>`; the coordinator's agent, else the first partition's by id, also serves the definition's own target. Without a partition resolver the partitions are recorded and the definition's agent runs in the default partition |
55///
56/// A definition comes from a tenant, so the block cannot widen what the operator allows: a
57/// driver is never `unsandboxed` and pins no declaration digest of its own, a credential
58/// reaches a driver only as a `secret://` reference, a wake set never runs on the
59/// `interactive` queue a person's turn holds nor watches the host's files, and no field lets
60/// an agenda item of origin `Consolidation` start without a person's approval (K-I23).
61///
62/// # Example
63///
64/// ```rust
65/// use adk_kernel::Wake;
66/// use adk_kernel::managed::{KernelDef, WakeSetDef};
67/// use adk_managed::types::{ManagedAgentDef, ModelRef};
68///
69/// let kernel = KernelDef::new().with_wake_set(WakeSetDef::new(
70///     "morning",
71///     [WakeSetDef::cron("0 0 9 * * *")],
72///     "Summarize what changed overnight.",
73/// ));
74/// let def = kernel.apply_to(ManagedAgentDef::new("digest", ModelRef::Shorthand("gemini-3.5-flash-lite".into())));
75/// // The definition crosses a store as JSON, as a session record does.
76/// let def: ManagedAgentDef = serde_json::from_value(serde_json::to_value(&def)?)?;
77/// assert_eq!(KernelDef::from_agent_def(&def)?, Some(kernel));
78/// # Ok::<(), Box<dyn std::error::Error>>(())
79/// ```
80#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82#[non_exhaustive]
83pub struct KernelDef {
84    /// The partitions the definition's agents run in (spec 3.2 §7.8).
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub partitions: Vec<PartitionDef>,
87    /// The partition whose agent is the coordinator, the one that may cross into another
88    /// partition under a non-waivable approval (spec 3.2 §7.8, K-I15); one of
89    /// [`partitions`](Self::partitions).
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub coordinator: Option<PartitionId>,
92    /// The drivers the definition asks to mount (spec 3.2 §7.7).
93    #[serde(default, skip_serializing_if = "Vec::is_empty")]
94    pub drivers: Vec<DriverManifest>,
95    /// The proactivity policy (spec 3.2 §7.5); `None` leaves the operator's, with the
96    /// consolidation tick off.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub proactivity: Option<ProactivityPolicy>,
99    /// The wake sets that start the definition's agent (spec 3.2 §7.4).
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub wake_sets: Vec<WakeSetDef>,
102}
103
104impl KernelDef {
105    /// An empty block: no partitions, drivers or wake sets, no proactivity policy.
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    /// Adds a partition.
111    #[must_use]
112    pub fn with_partition(mut self, partition: PartitionDef) -> Self {
113        self.partitions.push(partition);
114        self
115    }
116
117    /// Makes `partition`'s agent the coordinator (spec 3.2 §7.8).
118    #[must_use]
119    pub fn with_coordinator(mut self, partition: impl Into<PartitionId>) -> Self {
120        self.coordinator = Some(partition.into());
121        self
122    }
123
124    /// The partition whose agent serves the definition's own target: the coordinator's,
125    /// else the first partition's by id; `None` without partitions (spec 3.2 §7.8).
126    pub fn primary_partition(&self) -> Option<PartitionId> {
127        self.coordinator
128            .clone()
129            .or_else(|| self.partitions.iter().map(|partition| partition.id.clone()).min())
130    }
131
132    /// Adds a driver manifest.
133    #[must_use]
134    pub fn with_driver(mut self, driver: DriverManifest) -> Self {
135        self.drivers.push(driver);
136        self
137    }
138
139    /// Sets the proactivity policy.
140    #[must_use]
141    pub fn with_proactivity(mut self, proactivity: ProactivityPolicy) -> Self {
142        self.proactivity = Some(proactivity);
143        self
144    }
145
146    /// Adds a wake set.
147    #[must_use]
148    pub fn with_wake_set(mut self, wake_set: WakeSetDef) -> Self {
149        self.wake_sets.push(wake_set);
150        self
151    }
152
153    /// The kernel block `def` carries, validated, or `None` when its metadata holds no
154    /// [`KERNEL_DEF_METADATA_KEY`] (spec 3.2 §7.13, §10 M1).
155    ///
156    /// # Errors
157    ///
158    /// Returns [`KernelError::Config`] when the block is not valid JSON, has an unknown key,
159    /// or fails [`validate`](Self::validate); the message names the definition and the key.
160    pub fn from_agent_def(def: &ManagedAgentDef) -> Result<Option<Self>> {
161        let Some(text) =
162            def.metadata.as_ref().and_then(|metadata| metadata.get(KERNEL_DEF_METADATA_KEY))
163        else {
164            return Ok(None);
165        };
166        let block: Self = serde_json::from_str(text).map_err(|error| KernelError::Config {
167            reason: format!(
168                "metadata `{KERNEL_DEF_METADATA_KEY}` of definition '{}' is not a kernel \
169                 block: {error}",
170                def.name
171            ),
172        })?;
173        block.validate().map_err(|error| match error {
174            KernelError::Config { reason } => KernelError::Config {
175                reason: format!(
176                    "metadata `{KERNEL_DEF_METADATA_KEY}` of definition '{}': {reason}",
177                    def.name
178                ),
179            },
180            other => other,
181        })?;
182        Ok(Some(block))
183    }
184
185    /// `def` with this block in its metadata under [`KERNEL_DEF_METADATA_KEY`], replacing
186    /// any block it carried; the caller's other keys, `adk.harness` included, stay.
187    ///
188    /// The block is not validated here; [`from_agent_def`](Self::from_agent_def) validates
189    /// it where it is read.
190    pub fn apply_to(&self, mut def: ManagedAgentDef) -> ManagedAgentDef {
191        let text = serde_json::to_string(self).expect("a kernel block always serializes");
192        def.metadata
193            .get_or_insert_with(BTreeMap::new)
194            .insert(KERNEL_DEF_METADATA_KEY.to_string(), text);
195        def
196    }
197
198    /// The consolidation tick the block turns on, or `None`: the tick is off in the managed
199    /// form unless the definition's policy sets it (spec 3.2 §7.5, §13 Q1).
200    pub fn consolidation(&self) -> Option<&ConsolidationTick> {
201        self.proactivity.as_ref().and_then(|proactivity| proactivity.consolidation.as_ref())
202    }
203
204    /// The partition a wake set's processes run in: its own, or the default partition.
205    pub(crate) fn partition_of(wake_set: &WakeSetDef) -> PartitionId {
206        wake_set.partition.clone().unwrap_or_default()
207    }
208
209    /// Checks every rule of the block (spec 3.2 §7.4, §7.5, §7.7, §7.8).
210    ///
211    /// | Part | Refused when |
212    /// |---|---|
213    /// | partitions | an id or class is blank or repeated, an id has a character other than letters, digits, `-` and `_`, a mounted driver is not one of the block's, `crossPartition` is unknown, a blocked crossing names the partition itself |
214    /// | coordinator | it names a partition the block does not declare |
215    /// | drivers | a manifest fails `DriverManifest::validate`, an id is repeated, a partition is not declared, the sandbox is `unsandboxed`, a declaration digest is pinned |
216    /// | proactivity | a share, score or fraction of the consolidation tick is outside its range, or its schedule is blank |
217    /// | wake sets | a name is blank, repeated or not an identifier, `anyOf` or `input` is empty, a wake is not a cron, webhook, queue or signal wake, a cron expression does not parse, a hook or source is blank, a signal kind is not an identifier, the partition — the set's or a signal wake's — is not declared, the queue is `interactive`, the user is blank |
218    ///
219    /// # Errors
220    ///
221    /// Returns [`KernelError::Config`] naming the first rule broken and how to fix it.
222    pub fn validate(&self) -> Result<()> {
223        let mut declared = BTreeSet::new();
224        let drivers: BTreeSet<&str> =
225            self.drivers.iter().map(|driver| driver.id.as_str()).collect();
226        for partition in &self.partitions {
227            partition.validate(&drivers)?;
228            if !declared.insert(partition.id.clone()) {
229                return Err(invalid(format!("partition `{}` is declared twice", partition.id)));
230            }
231        }
232        if let Some(coordinator) = &self.coordinator
233            && !declared.contains(coordinator)
234        {
235            return Err(invalid(format!(
236                "coordinator `{coordinator}` is not a partition the block declares; name one \
237                 of `partitions`"
238            )));
239        }
240        let mut partitions = declared;
241        partitions.insert(PartitionId::default());
242        let mut seen = BTreeSet::new();
243        for driver in &self.drivers {
244            validate_driver(driver, &partitions)?;
245            if !seen.insert(driver.id.as_str()) {
246                return Err(invalid(format!("driver `{}` is declared twice", driver.id)));
247            }
248        }
249        if let Some(tick) = self.consolidation() {
250            validate_tick(tick)?;
251        }
252        let mut names = BTreeSet::new();
253        for wake_set in &self.wake_sets {
254            wake_set.validate(&partitions)?;
255            if !names.insert(wake_set.name.as_str()) {
256                return Err(invalid(format!("wake set `{}` is declared twice", wake_set.name)));
257            }
258        }
259        Ok(())
260    }
261}
262
263/// A driver manifest a tenant may ask for: the manifest's own rules, then the managed form's.
264fn validate_driver(driver: &DriverManifest, partitions: &BTreeSet<PartitionId>) -> Result<()> {
265    driver.validate()?;
266    if driver.sandbox == DriverSandbox::Unsandboxed {
267        return Err(invalid(format!(
268            "driver `{}`: a definition's driver runs sandboxed; `unsandboxed` drivers are the \
269             operator's to configure, so use `os` or `container`",
270            driver.id
271        )));
272    }
273    if !driver.declaration_digests.is_empty() {
274        return Err(invalid(format!(
275            "driver `{}`: declaration digests are pinned when a person approves the mount, \
276             never by a definition; leave `declarationDigests` out",
277            driver.id
278        )));
279    }
280    for partition in &driver.partitions {
281        if !partitions.contains(partition) {
282            return Err(invalid(format!(
283                "driver `{}` serves partition `{partition}`, which the block does not declare",
284                driver.id
285            )));
286        }
287    }
288    Ok(())
289}
290
291/// The ranges of a consolidation tick's shares, scores and fractions.
292fn validate_tick(tick: &ConsolidationTick) -> Result<()> {
293    let within = |field: &str, value: f32, zero_allowed: bool| {
294        let low_ok = if zero_allowed { value >= 0.0 } else { value > 0.0 };
295        if low_ok && value <= 1.0 {
296            Ok(())
297        } else {
298            let range = if zero_allowed { "[0, 1]" } else { "(0, 1]" };
299            Err(invalid(format!(
300                "proactivity.consolidation.{field} is {value}; it must be in {range}"
301            )))
302        }
303    };
304    within("budgetShare", tick.budget_share, false)?;
305    within("dedupScore", tick.dedup_score, true)?;
306    within("expireConfidence", tick.expire_confidence, true)?;
307    within("maxLossFraction", tick.max_loss_fraction, false)?;
308    if tick.schedule.as_deref().is_some_and(|schedule| schedule.trim().is_empty()) {
309        return Err(invalid(
310            "proactivity.consolidation.schedule is blank; leave it out to admit ticks on new \
311             material",
312        ));
313    }
314    Ok(())
315}
316
317/// A partition of a hosted definition, as plain data in the partition record's shape (spec
318/// 3.2 §7.8).
319///
320/// The tenant is the hosting kernel's, never the definition's, so the block has no
321/// `tenant` key.
322///
323/// # Example
324///
325/// ```rust
326/// use adk_kernel::PartitionMode;
327/// use adk_kernel::managed::PartitionDef;
328///
329/// let work: PartitionDef = serde_json::from_value(serde_json::json!({
330///     "id": "work",
331///     "class": "work",
332///     "defaultMode": "auto",
333///     "crossPartition": "coordinator_with_approval",
334/// }))?;
335/// assert_eq!(work.default_mode, PartitionMode::Auto);
336/// assert_eq!(work.memory_scope(), "work");
337/// # Ok::<(), serde_json::Error>(())
338/// ```
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase", deny_unknown_fields)]
341#[non_exhaustive]
342pub struct PartitionDef {
343    /// The partition's id: `work`, `home`, a team.
344    pub id: PartitionId,
345    /// `AgentPrincipal.class` of every agent in the partition.
346    pub class: String,
347    /// The mode of the partition's agents (default `ask`).
348    #[serde(default = "ask")]
349    pub default_mode: PartitionMode,
350    /// The project of the partition's long-term facts and project-scoped memory; defaults to
351    /// the id.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub memory_scope: Option<String>,
354    /// The ids of the block's drivers mounted for the partition.
355    #[serde(default, skip_serializing_if = "Vec::is_empty")]
356    pub drivers: Vec<String>,
357    /// [`CROSS_PARTITION_VALUES`]: `deny` (default) or `coordinator_with_approval`.
358    #[serde(default = "deny")]
359    pub cross_partition: String,
360    /// Partitions the coordinator in this partition may not cross into.
361    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
362    pub blocked_crossings: BTreeSet<PartitionId>,
363}
364
365fn ask() -> PartitionMode {
366    PartitionMode::Ask
367}
368
369fn deny() -> String {
370    CROSS_PARTITION_VALUES[0].to_string()
371}
372
373impl PartitionDef {
374    /// A partition `id` of class `class`, in `ask` mode, denying crossings.
375    pub fn new(id: impl Into<PartitionId>, class: impl Into<String>) -> Self {
376        Self {
377            id: id.into(),
378            class: class.into(),
379            default_mode: PartitionMode::Ask,
380            memory_scope: None,
381            drivers: Vec::new(),
382            cross_partition: deny(),
383            blocked_crossings: BTreeSet::new(),
384        }
385    }
386
387    /// Sets the mode.
388    #[must_use]
389    pub fn with_mode(mut self, mode: PartitionMode) -> Self {
390        self.default_mode = mode;
391        self
392    }
393
394    /// Mounts the block's driver `id` for the partition.
395    #[must_use]
396    pub fn with_driver(mut self, id: impl Into<String>) -> Self {
397        self.drivers.push(id.into());
398        self
399    }
400
401    /// The memory scope: the one set, or the id.
402    pub fn memory_scope(&self) -> &str {
403        self.memory_scope.as_deref().unwrap_or(self.id.as_str())
404    }
405
406    /// The partition record of this partition on `tenant`'s kernel (spec 3.2 §7.8): the
407    /// tenant is the hosting tenant, never the definition's.
408    ///
409    /// # Example
410    ///
411    /// ```rust
412    /// use adk_kernel::managed::PartitionDef;
413    ///
414    /// let work = PartitionDef::new("work", "work-agents").with_driver("calendar").to_partition("tenant-a")?;
415    /// assert_eq!(work.tenant.as_deref(), Some("tenant-a"));
416    /// assert_eq!((work.memory_scope.as_str(), work.drivers.as_slice()), ("work", ["calendar".to_string()].as_slice()));
417    /// # Ok::<(), adk_kernel::KernelError>(())
418    /// ```
419    ///
420    /// # Errors
421    ///
422    /// Returns [`KernelError::Config`] when `crossPartition` is unknown.
423    pub fn to_partition(&self, tenant: &str) -> Result<Partition> {
424        let mut partition = Partition::new(self.id.clone(), self.class.clone())
425            .with_tenant(tenant)
426            .with_mode(self.default_mode)
427            .with_memory_scope(self.memory_scope())
428            .with_cross_partition(self.cross_partition.parse::<CrossPartition>()?);
429        for driver in &self.drivers {
430            partition = partition.with_driver(driver.clone());
431        }
432        for blocked in &self.blocked_crossings {
433            partition = partition.with_blocked_crossing(blocked.clone());
434        }
435        Ok(partition)
436    }
437
438    fn validate(&self, drivers: &BTreeSet<&str>) -> Result<()> {
439        name("partition id", self.id.as_str())?;
440        if self.class.trim().is_empty() {
441            return Err(invalid(format!("partition `{}` needs a `class`", self.id)));
442        }
443        if self.memory_scope.as_deref().is_some_and(|scope| scope.trim().is_empty()) {
444            return Err(invalid(format!(
445                "partition `{}` has a blank `memoryScope`; leave it out to use the id",
446                self.id
447            )));
448        }
449        for driver in &self.drivers {
450            if !drivers.contains(driver.as_str()) {
451                return Err(invalid(format!(
452                    "partition `{}` mounts driver `{driver}`, which the block does not declare",
453                    self.id
454                )));
455            }
456        }
457        if !CROSS_PARTITION_VALUES.contains(&self.cross_partition.as_str()) {
458            return Err(invalid(format!(
459                "partition `{}`: crossPartition `{}` is unknown; use {}",
460                self.id,
461                self.cross_partition,
462                CROSS_PARTITION_VALUES.join(" or ")
463            )));
464        }
465        if self.blocked_crossings.contains(&self.id) {
466            return Err(invalid(format!(
467                "partition `{}` blocks crossings to itself; list other partitions",
468                self.id
469            )));
470        }
471        Ok(())
472    }
473}
474
475/// A wake set of a hosted definition: wakes that each start a governed run of the
476/// definition's agent with `input` (spec 3.2 §7.4, §7.13).
477///
478/// A wake set is standing: every firing starts a process, keyed by the wake's own key, so
479/// a repeated delivery starts nothing (K-I3). `overlap` says what a firing does while the
480/// set's previous process is unfinished. The hosting application serves a webhook through
481/// `webhook_wake_hook` and a queue through `queue_wake_ingress` on the tenant's run store,
482/// and files a signal through `TenantKernel::signal_sink` (feature `charter`).
483///
484/// | Wake | In a wake set |
485/// |---|---|
486/// | `cron`, `webhook`, `queue` | Accepted |
487/// | `signal` | Accepted: its `kind` an identifier, its `partition` one the block declares; unset, the set's own partition, so a definition hears only signals filed in its partitions. The tenant needs a signal store (`TenantKernelBuilder::signal_store`) |
488/// | `fileChange` | Refused: it would watch the host's files |
489/// | `at` | Refused: it matches no event, only a sleeper's time; a cron wake recurs, and one-shot work is a schedule (`ScheduleSpec::At`) on the tenant's schedule store |
490/// | `budgetReplenished` | Refused: admission already parks a budget-deferred process on it and wakes it when the budget returns, so as a standing wake it never fires |
491/// | `approval`, `runFinished`, `manual` | Refused: each names one sleeping process |
492///
493/// A run a signal starts stays unauthenticated, and its input is the set's `input`, never
494/// the signal's text (spec 3.5 A-I3).
495///
496/// # Example
497///
498/// ```rust
499/// use adk_kernel::Wake;
500/// use adk_kernel::managed::{WakeOverlap, WakeSetDef};
501///
502/// let set: WakeSetDef = serde_json::from_value(serde_json::json!({
503///     "name": "orders",
504///     "anyOf": [{ "webhook": { "hook": "orders" } }, { "cron": { "expr": "0 0 * * * *", "missed": "skip" } }],
505///     "input": "Triage the new orders.",
506/// }))?;
507/// assert_eq!(set.any_of[0], Wake::Webhook { hook: "orders".into() });
508/// assert_eq!(set.overlap, WakeOverlap::Skip);
509/// # Ok::<(), serde_json::Error>(())
510/// ```
511#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
512#[serde(rename_all = "camelCase", deny_unknown_fields)]
513#[non_exhaustive]
514pub struct WakeSetDef {
515    /// The set's name, unique in the definition.
516    pub name: String,
517    /// The wakes; any one starts a process.
518    pub any_of: Vec<Wake>,
519    /// The text each process starts with.
520    pub input: String,
521    /// The partition its processes run in; the default partition when unset.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub partition: Option<PartitionId>,
524    /// The queue its processes run on: `background` (default), `maintenance` or a named
525    /// queue; never `interactive`, which a person's turn holds.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub queue: Option<String>,
528    /// The user its processes run for, as a `Service` subject; [`DEFAULT_WAKE_USER`] when
529    /// unset.
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    pub user: Option<String>,
532    /// What a firing does while the set's previous process is unfinished.
533    #[serde(default)]
534    pub overlap: WakeOverlap,
535}
536
537impl WakeSetDef {
538    /// A set `name` that starts a process with `input` when any of `wakes` fires.
539    pub fn new(
540        name: impl Into<String>,
541        wakes: impl IntoIterator<Item = Wake>,
542        input: impl Into<String>,
543    ) -> Self {
544        Self {
545            name: name.into(),
546            any_of: wakes.into_iter().collect(),
547            input: input.into(),
548            partition: None,
549            queue: None,
550            user: None,
551            overlap: WakeOverlap::default(),
552        }
553    }
554
555    /// A cron wake on the six-field expression `expr` (seconds first) that skips missed
556    /// occurrences.
557    pub fn cron(expr: impl Into<String>) -> Wake {
558        Wake::Cron { expr: expr.into(), missed: MissedFirePolicy::Skip }
559    }
560
561    /// Runs the set's processes in `partition`.
562    #[must_use]
563    pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
564        self.partition = Some(partition.into());
565        self
566    }
567
568    /// Runs the set's processes on `queue`.
569    #[must_use]
570    pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
571        self.queue = Some(queue.into());
572        self
573    }
574
575    /// Runs the set's processes for `user`.
576    #[must_use]
577    pub fn with_user(mut self, user: impl Into<String>) -> Self {
578        self.user = Some(user.into());
579        self
580    }
581
582    /// Sets what a firing does while the previous process is unfinished.
583    #[must_use]
584    pub fn with_overlap(mut self, overlap: WakeOverlap) -> Self {
585        self.overlap = overlap;
586        self
587    }
588
589    /// The queue class the set's processes run on.
590    pub fn queue_class(&self) -> QueueClass {
591        self.queue.as_deref().map(QueueClass::from_name).unwrap_or(QueueClass::Background)
592    }
593
594    /// The user the set's processes run for.
595    pub fn user(&self) -> &str {
596        self.user.as_deref().unwrap_or(DEFAULT_WAKE_USER)
597    }
598
599    fn validate(&self, partitions: &BTreeSet<PartitionId>) -> Result<()> {
600        name("wake set name", &self.name)?;
601        if self.any_of.is_empty() {
602            return Err(invalid(format!("wake set `{}` needs at least one wake", self.name)));
603        }
604        if self.input.trim().is_empty() {
605            return Err(invalid(format!(
606                "wake set `{}` needs an `input`: the text its processes start with",
607                self.name
608            )));
609        }
610        let partition = KernelDef::partition_of(self);
611        if !partitions.contains(&partition) {
612            return Err(invalid(format!(
613                "wake set `{}` runs in partition `{partition}`, which the block does not declare",
614                self.name
615            )));
616        }
617        if self.queue_class() == QueueClass::Interactive {
618            return Err(invalid(format!(
619                "wake set `{}`: the `interactive` queue is reserved for a person's turn; use \
620                 `background` or `maintenance`",
621                self.name
622            )));
623        }
624        if self.queue.as_deref().is_some_and(|queue| queue.trim().is_empty())
625            || self.user.as_deref().is_some_and(|user| user.trim().is_empty())
626        {
627            return Err(invalid(format!(
628                "wake set `{}` has a blank `queue` or `user`; leave it out for the default",
629                self.name
630            )));
631        }
632        for wake in &self.any_of {
633            validate_wake(&self.name, wake, partitions)?;
634        }
635        Ok(())
636    }
637}
638
639/// One wake of a definition's wake set: a cron, webhook, queue or signal wake.
640fn validate_wake(set: &str, wake: &Wake, partitions: &BTreeSet<PartitionId>) -> Result<()> {
641    let one_process = |kind: &str| {
642        Err(invalid(format!(
643            "wake set `{set}`: `{kind}` names one sleeping process, not a standing wake; use a \
644             cron, webhook, queue or signal wake"
645        )))
646    };
647    match wake {
648        Wake::Cron { expr, missed } => {
649            CronTrigger::new(expr).map_err(|error| {
650                invalid(format!(
651                    "wake set `{set}`: `{expr}` is not a six-field cron expression (seconds \
652                     first): {error}"
653                ))
654            })?;
655            if *missed == MissedFirePolicy::CatchUp(0) {
656                return Err(invalid(format!(
657                    "wake set `{set}`: `missed.catchUp` must be at least 1"
658                )));
659            }
660            Ok(())
661        }
662        Wake::Webhook { hook } => name("webhook hook", hook),
663        Wake::Queue { source } if source.trim().is_empty() => {
664            Err(invalid(format!("wake set `{set}` names a blank queue source")))
665        }
666        Wake::Queue { .. } => Ok(()),
667        Wake::Signal { kind, partition } => {
668            name("signal kind", kind).map_err(|error| match error {
669                KernelError::Config { reason } => invalid(format!("wake set `{set}`: {reason}")),
670                other => other,
671            })?;
672            match partition {
673                Some(partition) if !partitions.contains(partition) => Err(invalid(format!(
674                    "wake set `{set}` hears `{kind}` signals in partition `{partition}`, which \
675                     the block does not declare; declare it, or leave `partition` out to hear \
676                     the set's own"
677                ))),
678                _ => Ok(()),
679            }
680        }
681        Wake::FileChange { .. } => Err(invalid(format!(
682            "wake set `{set}`: a definition does not watch the host's files; use a cron, \
683             webhook, queue or signal wake"
684        ))),
685        Wake::At(_) => Err(invalid(format!(
686            "wake set `{set}`: an `at` wake matches no event, only a sleeping process's time, so \
687             it starts nothing; use a cron wake for recurring work, or a schedule \
688             (`ScheduleSpec::At`) on the tenant's schedule store for one-shot work"
689        ))),
690        Wake::BudgetReplenished { .. } => Err(invalid(format!(
691            "wake set `{set}`: a `budgetReplenished` wake never fires as a standing wake: \
692             admission already parks a budget-deferred process on it and wakes it when the \
693             budget returns; use a cron, webhook, queue or signal wake"
694        ))),
695        Wake::Approval { .. } => one_process("approval"),
696        Wake::RunFinished { .. } => one_process("runFinished"),
697        Wake::Manual => one_process("manual"),
698    }
699}
700
701/// What a wake set's firing does while its previous process is unfinished (spec 3.2 §7.9):
702/// the kernel's [`WakeOverlap`](crate::WakeOverlap), which a standing trigger takes too.
703pub use crate::wake::WakeOverlap;
704
705fn invalid(reason: impl Into<String>) -> KernelError {
706    KernelError::Config { reason: reason.into() }
707}
708
709/// An identifier a target, trigger or process names: ASCII letters, digits, `-` and `_`.
710fn name(what: &str, value: &str) -> Result<()> {
711    let valid = !value.is_empty()
712        && value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
713    if valid {
714        Ok(())
715    } else {
716        Err(invalid(format!(
717            "{what} `{value}` must be ASCII letters, digits, `-` and `_`, and not empty"
718        )))
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use std::time::Duration;
725
726    use adk_managed::types::ModelRef;
727    use adk_tool::mcp::manager::McpServerConfig;
728    use serde_json::json;
729
730    use super::*;
731    use crate::agenda::ProactiveApproval;
732
733    fn def() -> ManagedAgentDef {
734        ManagedAgentDef::new("digest", ModelRef::Shorthand("gemini-3.5-flash-lite".into()))
735    }
736
737    fn morning() -> WakeSetDef {
738        WakeSetDef::new("morning", [WakeSetDef::cron("0 0 9 * * *")], "Summarize the night.")
739    }
740
741    fn webhook(hook: &str) -> Wake {
742        Wake::Webhook { hook: hook.into() }
743    }
744
745    fn manifest(id: &str) -> DriverManifest {
746        let server: McpServerConfig =
747            serde_json::from_value(json!({ "command": format!("mcp-{id}") })).unwrap();
748        DriverManifest::new(id, server).unwrap()
749    }
750
751    fn reason(error: KernelError) -> String {
752        match error {
753            KernelError::Config { reason } => reason,
754            other => panic!("expected a configuration error, got {other}"),
755        }
756    }
757
758    #[test]
759    fn the_block_travels_beside_the_harness_block_and_other_keys() {
760        let mut wire = def();
761        wire.metadata = Some(BTreeMap::from([
762            ("adk.harness".to_string(), r#"{"mode":"plan"}"#.to_string()),
763            ("team".to_string(), "a".to_string()),
764        ]));
765        let kernel = KernelDef::new().with_wake_set(morning()).with_driver(manifest("email"));
766        let wire = kernel.apply_to(wire);
767        let metadata = wire.metadata.clone().unwrap();
768        assert_eq!(metadata["adk.harness"], r#"{"mode":"plan"}"#);
769        assert_eq!(metadata["team"], "a");
770        let wire: ManagedAgentDef =
771            serde_json::from_value(serde_json::to_value(&wire).unwrap()).unwrap();
772        assert_eq!(KernelDef::from_agent_def(&wire).unwrap(), Some(kernel));
773    }
774
775    #[test]
776    fn a_definition_without_a_block_has_no_kernel_part() {
777        assert_eq!(KernelDef::from_agent_def(&def()).unwrap(), None);
778    }
779
780    #[test]
781    fn applying_a_block_again_replaces_it() {
782        let first = KernelDef::new().with_wake_set(morning());
783        let second = KernelDef::new();
784        let wire = second.apply_to(first.apply_to(def()));
785        assert_eq!(KernelDef::from_agent_def(&wire).unwrap(), Some(second));
786    }
787
788    #[test]
789    fn a_malformed_block_names_the_definition_and_the_key() {
790        let mut wire = def();
791        wire.metadata =
792            Some(BTreeMap::from([(KERNEL_DEF_METADATA_KEY.to_string(), "{".to_string())]));
793        let reason = reason(KernelDef::from_agent_def(&wire).unwrap_err());
794        assert!(reason.contains("adk.kernel") && reason.contains("'digest'"), "{reason}");
795    }
796
797    #[test]
798    fn the_block_carries_the_kernels_own_types() {
799        let policy = ProactivityPolicy::default()
800            .with_quiet_hours("22:00-07:00".parse().unwrap())
801            .with_approval(ProactiveApproval::AlwaysAsk);
802        let kernel = KernelDef::new()
803            .with_partition(PartitionDef::new("work", "work").with_driver("email"))
804            .with_driver(DriverManifest { partitions: vec!["work".into()], ..manifest("email") })
805            .with_proactivity(policy.clone())
806            .with_wake_set(morning().with_partition("work"));
807        kernel.validate().unwrap();
808        let wire = serde_json::to_value(&kernel).unwrap();
809        assert_eq!(wire["partitions"][0]["defaultMode"], "ask");
810        assert_eq!(wire["partitions"][0]["crossPartition"], "deny");
811        assert_eq!(wire["drivers"][0]["server"]["command"], "mcp-email");
812        assert_eq!(wire["proactivity"]["approval"], "always_ask");
813        assert_eq!(wire["wakeSets"][0]["anyOf"][0]["cron"]["missed"], "skip");
814        let back: KernelDef = serde_json::from_value(wire).unwrap();
815        assert_eq!(back, kernel);
816        assert_eq!(back.proactivity, Some(policy));
817    }
818
819    #[test]
820    fn the_consolidation_tick_is_off_unless_the_block_sets_it() {
821        assert!(KernelDef::new().consolidation().is_none());
822        let quiet = KernelDef::new().with_proactivity(ProactivityPolicy::default());
823        assert!(quiet.consolidation().is_none(), "§13 Q1: off in the managed form by default");
824        let on = KernelDef::new().with_proactivity(
825            ProactivityPolicy::default().with_consolidation(ConsolidationTick::default()),
826        );
827        assert!(on.consolidation().is_some());
828    }
829
830    #[test]
831    fn a_tenant_block_cannot_widen_what_the_operator_allows() {
832        let mut pinned = manifest("email");
833        pinned.declaration_digests.insert("send".into(), "sha256:abc".into());
834        let mut credential = manifest("github");
835        credential.server.env.insert("GITHUB_TOKEN".into(), "ghp_plaintext".into());
836        let cases = [
837            (
838                KernelDef::new().with_driver(DriverManifest {
839                    sandbox: DriverSandbox::Unsandboxed,
840                    ..manifest("shell")
841                }),
842                "unsandboxed",
843            ),
844            (KernelDef::new().with_driver(pinned), "declarationDigests"),
845            (KernelDef::new().with_driver(credential), "secret://"),
846            (KernelDef::new().with_wake_set(morning().with_queue("interactive")), "interactive"),
847            (
848                KernelDef::new().with_wake_set(WakeSetDef::new(
849                    "files",
850                    [Wake::FileChange {
851                        root: "/".into(),
852                        glob: "*".into(),
853                        debounce: Duration::from_millis(500),
854                    }],
855                    "x",
856                )),
857                "host's files",
858            ),
859        ];
860        for (kernel, needle) in cases {
861            let reason = reason(kernel.validate().unwrap_err());
862            assert!(reason.contains(needle), "expected `{needle}` in: {reason}");
863        }
864    }
865
866    #[test]
867    fn every_rule_names_what_to_fix() {
868        let cases: Vec<(KernelDef, &str)> = vec![
869            (KernelDef::new().with_wake_set(morning()).with_wake_set(morning()), "twice"),
870            (
871                KernelDef::new().with_wake_set(WakeSetDef::new(
872                    "bad",
873                    [WakeSetDef::cron("nope")],
874                    "x",
875                )),
876                "six-field",
877            ),
878            (KernelDef::new().with_wake_set(WakeSetDef::new("none", [], "x")), "at least one wake"),
879            (
880                KernelDef::new().with_wake_set(WakeSetDef::new("blank", [webhook("h")], " ")),
881                "input",
882            ),
883            (KernelDef::new().with_wake_set(morning().with_partition("home")), "home"),
884            (
885                KernelDef::new().with_wake_set(WakeSetDef::new("manual", [Wake::Manual], "x")),
886                "`manual` names one sleeping process",
887            ),
888            (
889                KernelDef::new().with_wake_set(WakeSetDef::new(
890                    "approval",
891                    [Wake::Approval { fingerprint: "f".into() }],
892                    "x",
893                )),
894                "`approval` names one sleeping process",
895            ),
896            (
897                KernelDef::new()
898                    .with_partition(PartitionDef::new("work", "work").with_driver("email")),
899                "email",
900            ),
901            (
902                KernelDef::new().with_partition(PartitionDef {
903                    cross_partition: "always".into(),
904                    ..PartitionDef::new("work", "work")
905                }),
906                "coordinator_with_approval",
907            ),
908            (
909                KernelDef::new().with_driver(DriverManifest {
910                    partitions: vec!["home".into()],
911                    ..manifest("email")
912                }),
913                "partition `home`",
914            ),
915            (
916                KernelDef::new().with_driver(manifest("email")).with_driver(manifest("email")),
917                "twice",
918            ),
919            (
920                KernelDef::new().with_proactivity(
921                    ProactivityPolicy::default()
922                        .with_consolidation(ConsolidationTick::default().with_budget_share(1.5)),
923                ),
924                "budgetShare",
925            ),
926            (
927                KernelDef::new().with_wake_set(WakeSetDef::new(
928                    "catch",
929                    [Wake::Cron {
930                        expr: "0 0 9 * * *".into(),
931                        missed: MissedFirePolicy::CatchUp(0),
932                    }],
933                    "x",
934                )),
935                "catchUp",
936            ),
937            (
938                KernelDef::new().with_wake_set(WakeSetDef::new("sp ace", [webhook("h")], "x")),
939                "ASCII",
940            ),
941        ];
942        for (kernel, needle) in cases {
943            let reason = reason(kernel.validate().unwrap_err());
944            assert!(reason.contains(needle), "expected `{needle}` in: {reason}");
945        }
946    }
947
948    fn signal(kind: &str, partition: Option<&str>) -> Wake {
949        Wake::Signal { kind: kind.into(), partition: partition.map(PartitionId::new) }
950    }
951
952    #[test]
953    fn a_signal_wake_is_a_standing_wake_of_the_sets_own_or_a_declared_partition() {
954        let gap = |partition: Option<&str>| {
955            WakeSetDef::new("gaps", [signal("content_gap", partition)], "Fill the gap.")
956        };
957        KernelDef::new().with_wake_set(gap(None)).validate().unwrap();
958        KernelDef::new().with_wake_set(gap(Some(PartitionId::DEFAULT))).validate().unwrap();
959        let work = KernelDef::new().with_partition(PartitionDef::new("work", "work"));
960        work.clone().with_wake_set(gap(Some("work"))).validate().unwrap();
961        work.with_wake_set(gap(Some("work")).with_partition("work")).validate().unwrap();
962        let wire: WakeSetDef = serde_json::from_value(json!({
963            "name": "gaps",
964            "anyOf": [{ "signal": { "kind": "content_gap" } }],
965            "input": "Fill the gap.",
966        }))
967        .unwrap();
968        assert_eq!(wire, gap(None));
969    }
970
971    #[test]
972    fn a_signal_wake_names_an_identifier_kind_in_a_declared_partition() {
973        let cases = [
974            (signal("content_gap", Some("home")), "partition `home`"),
975            (signal("", None), "signal kind"),
976            (signal("content gap", None), "signal kind `content gap`"),
977        ];
978        for (wake, needle) in cases {
979            let kernel = KernelDef::new().with_wake_set(WakeSetDef::new("gaps", [wake], "x"));
980            let reason = reason(kernel.validate().unwrap_err());
981            assert!(reason.contains(needle) && reason.contains("gaps"), "{needle}: {reason}");
982        }
983    }
984
985    #[test]
986    fn time_and_budget_wakes_are_refused_naming_what_to_use_instead() {
987        let cases = [
988            (Wake::At(chrono::Utc::now()), ["`at` wake", "ScheduleSpec::At"]),
989            (
990                Wake::BudgetReplenished { partition: PartitionId::default() },
991                ["`budgetReplenished`", "admission already parks"],
992            ),
993            (Wake::RunFinished { pid: "run-1".into() }, ["`runFinished`", "signal wake"]),
994        ];
995        for (wake, needles) in cases {
996            let kernel = KernelDef::new().with_wake_set(WakeSetDef::new("later", [wake], "x"));
997            let reason = reason(kernel.validate().unwrap_err());
998            for needle in needles {
999                assert!(reason.contains(needle), "expected `{needle}` in: {reason}");
1000            }
1001        }
1002    }
1003
1004    #[test]
1005    fn wake_sets_default_to_the_background_queue_and_the_kernel_user() {
1006        assert_eq!(morning().queue_class(), QueueClass::Background);
1007        assert_eq!(morning().with_queue("maintenance").queue_class(), QueueClass::Maintenance);
1008        assert_eq!(morning().user(), DEFAULT_WAKE_USER);
1009        assert_eq!(morning().with_user("ana").user(), "ana");
1010    }
1011}