1use 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
18pub const KERNEL_DEF_METADATA_KEY: &str = "adk.kernel";
31
32pub const DEFAULT_WAKE_USER: &str = "kernel";
34
35pub const CROSS_PARTITION_VALUES: [&str; 2] = ["deny", "coordinator_with_approval"];
38
39#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase", deny_unknown_fields)]
82#[non_exhaustive]
83pub struct KernelDef {
84 #[serde(default, skip_serializing_if = "Vec::is_empty")]
86 pub partitions: Vec<PartitionDef>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub coordinator: Option<PartitionId>,
92 #[serde(default, skip_serializing_if = "Vec::is_empty")]
94 pub drivers: Vec<DriverManifest>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub proactivity: Option<ProactivityPolicy>,
99 #[serde(default, skip_serializing_if = "Vec::is_empty")]
101 pub wake_sets: Vec<WakeSetDef>,
102}
103
104impl KernelDef {
105 pub fn new() -> Self {
107 Self::default()
108 }
109
110 #[must_use]
112 pub fn with_partition(mut self, partition: PartitionDef) -> Self {
113 self.partitions.push(partition);
114 self
115 }
116
117 #[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 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 #[must_use]
134 pub fn with_driver(mut self, driver: DriverManifest) -> Self {
135 self.drivers.push(driver);
136 self
137 }
138
139 #[must_use]
141 pub fn with_proactivity(mut self, proactivity: ProactivityPolicy) -> Self {
142 self.proactivity = Some(proactivity);
143 self
144 }
145
146 #[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 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 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 pub fn consolidation(&self) -> Option<&ConsolidationTick> {
201 self.proactivity.as_ref().and_then(|proactivity| proactivity.consolidation.as_ref())
202 }
203
204 pub(crate) fn partition_of(wake_set: &WakeSetDef) -> PartitionId {
206 wake_set.partition.clone().unwrap_or_default()
207 }
208
209 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
263fn 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
291fn 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase", deny_unknown_fields)]
341#[non_exhaustive]
342pub struct PartitionDef {
343 pub id: PartitionId,
345 pub class: String,
347 #[serde(default = "ask")]
349 pub default_mode: PartitionMode,
350 #[serde(default, skip_serializing_if = "Option::is_none")]
353 pub memory_scope: Option<String>,
354 #[serde(default, skip_serializing_if = "Vec::is_empty")]
356 pub drivers: Vec<String>,
357 #[serde(default = "deny")]
359 pub cross_partition: String,
360 #[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 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 #[must_use]
389 pub fn with_mode(mut self, mode: PartitionMode) -> Self {
390 self.default_mode = mode;
391 self
392 }
393
394 #[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 pub fn memory_scope(&self) -> &str {
403 self.memory_scope.as_deref().unwrap_or(self.id.as_str())
404 }
405
406 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
512#[serde(rename_all = "camelCase", deny_unknown_fields)]
513#[non_exhaustive]
514pub struct WakeSetDef {
515 pub name: String,
517 pub any_of: Vec<Wake>,
519 pub input: String,
521 #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub partition: Option<PartitionId>,
524 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub queue: Option<String>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
531 pub user: Option<String>,
532 #[serde(default)]
534 pub overlap: WakeOverlap,
535}
536
537impl WakeSetDef {
538 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 pub fn cron(expr: impl Into<String>) -> Wake {
558 Wake::Cron { expr: expr.into(), missed: MissedFirePolicy::Skip }
559 }
560
561 #[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 #[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 #[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 #[must_use]
584 pub fn with_overlap(mut self, overlap: WakeOverlap) -> Self {
585 self.overlap = overlap;
586 self
587 }
588
589 pub fn queue_class(&self) -> QueueClass {
591 self.queue.as_deref().map(QueueClass::from_name).unwrap_or(QueueClass::Background)
592 }
593
594 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
639fn 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
701pub use crate::wake::WakeOverlap;
704
705fn invalid(reason: impl Into<String>) -> KernelError {
706 KernelError::Config { reason: reason.into() }
707}
708
709fn 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}