adk_kernel/partition.rs
1//! Partitions (spec 3.2 §7.8): areas of a user's life or an organisation's teams kept
2//! apart, with work across them only through the coordinator and under approval.
3//!
4//! A [`Partition`] is a policy class plus a memory scope plus a driver set, run by its own
5//! `HarnessAgent` built with the partition's mode (the `kernel` feature of `adk-harness`):
6//!
7//! | Part | Mechanism |
8//! |---|---|
9//! | Policy class | [`Partition::class`] and [`Partition::tenant`] on the `AgentPrincipal` of every agent in it, through the runner's identity source ([`Partition::identity_source`]), so `PolicyRule::for_class` rules apply |
10//! | Memory | The partition's [`memory_scope`](Partition::memory_scope) is the project of its long-term facts (`FactScope.project`) and of project-scoped memory ([`Partition::scope_memory`]) |
11//! | Drivers | [`Partition::drivers`]: the driver ids mounted for the partition |
12//! | Crossings | [`PartitionPolicy`]: a request that reaches another partition is denied unless the coordinator makes it, then `RequireApproval`, non-waivable, audited as `kernel.partition.crossing` (K-I15) |
13//!
14//! The approval's unit is the crossing fingerprint within one run (§13 Q3): an approved
15//! read lets the coordinator's identical reads through for the rest of that run and nothing
16//! beyond it; writes stay one-shot. [`Partitions`] keeps the partition table and the
17//! crossing ledger in a [`PartitionStore`].
18
19use std::collections::{BTreeSet, HashMap, HashSet};
20use std::fmt;
21use std::str::FromStr;
22use std::sync::{Arc, Mutex, OnceLock};
23
24use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
25use adk_core::{
26 AdkError, AgentPrincipal, Clock, ErrorCategory, ErrorComponent, IdentitySource, Memory,
27 MemoryEntry, SystemClock,
28};
29use async_trait::async_trait;
30use serde::{Deserialize, Serialize};
31use serde_json::{Value, json};
32
33use crate::audit;
34use crate::error::{KernelError, MEMORY_CROSSING_CODE, MEMORY_DELETE_CODE, NOT_FOUND_CODE, Result};
35use crate::sched::{QuietHours, Quotas};
36
37mod crossing;
38
39pub use crossing::{
40 CROSSING_PARTITION_ARG, Crossing, CrossingAccess, CrossingFilter, CrossingOutcome,
41 CrossingRecord, CrossingResource, CrossingRoute, CrossingRun, CrossingTool, PartitionPolicy,
42 RecurringCrossing,
43};
44
45/// Names a partition: `work`, `home`, a team (spec 3.2 §7.8).
46///
47/// # Example
48///
49/// ```rust
50/// use adk_kernel::PartitionId;
51///
52/// let work = PartitionId::new("work");
53/// assert_eq!(work.as_str(), "work");
54/// assert_eq!(PartitionId::default().as_str(), PartitionId::DEFAULT);
55/// assert_eq!(serde_json::to_value(&work).unwrap(), "work");
56/// ```
57#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(transparent)]
59pub struct PartitionId(String);
60
61impl PartitionId {
62 /// The partition a process runs in when none is named.
63 pub const DEFAULT: &'static str = "default";
64
65 /// A partition id.
66 pub fn new(id: impl Into<String>) -> Self {
67 Self(id.into())
68 }
69
70 /// The id as text.
71 pub fn as_str(&self) -> &str {
72 &self.0
73 }
74}
75
76impl Default for PartitionId {
77 fn default() -> Self {
78 Self::new(Self::DEFAULT)
79 }
80}
81
82impl fmt::Display for PartitionId {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(&self.0)
85 }
86}
87
88impl AsRef<str> for PartitionId {
89 fn as_ref(&self) -> &str {
90 &self.0
91 }
92}
93
94impl From<&str> for PartitionId {
95 fn from(id: &str) -> Self {
96 Self::new(id)
97 }
98}
99
100impl From<String> for PartitionId {
101 fn from(id: String) -> Self {
102 Self(id)
103 }
104}
105
106/// A partition's default mode (spec 3.2 §7.8): what its agents may do without asking.
107///
108/// The `kernel` feature of `adk-harness` maps it one to one onto `HarnessMode` (§10 HK1),
109/// and the values serialize as `HarnessMode`'s do (`read_only`, `plan`, `ask`, `auto`).
110/// Agentrix's Observe / Suggest / Automate is ReadOnly / Ask / Auto (§4).
111///
112/// # Example
113///
114/// ```rust
115/// use adk_kernel::PartitionMode;
116///
117/// let mode: PartitionMode = "read_only".parse().unwrap();
118/// assert_eq!(mode, PartitionMode::ReadOnly);
119/// assert_eq!(mode.to_string(), "read_only");
120/// assert_eq!(serde_json::to_value(PartitionMode::Auto).unwrap(), "auto");
121/// ```
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum PartitionMode {
126 /// Reads and todos only.
127 ReadOnly,
128 /// Reads and planning; nothing that changes the workspace.
129 Plan,
130 /// Changes need approval unless a standing rule allows them.
131 Ask,
132 /// Changes run without approval, within the harness's own limits.
133 Auto,
134}
135
136impl PartitionMode {
137 /// The mode's name: `read_only`, `plan`, `ask` or `auto`.
138 pub fn as_str(self) -> &'static str {
139 match self {
140 Self::ReadOnly => "read_only",
141 Self::Plan => "plan",
142 Self::Ask => "ask",
143 Self::Auto => "auto",
144 }
145 }
146}
147
148impl fmt::Display for PartitionMode {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 // `pad`, so a width or alignment in the format string applies.
151 f.pad(self.as_str())
152 }
153}
154
155impl FromStr for PartitionMode {
156 type Err = KernelError;
157
158 fn from_str(text: &str) -> Result<Self, Self::Err> {
159 match text.trim().to_ascii_lowercase().replace('-', "_").as_str() {
160 "read_only" | "readonly" => Ok(Self::ReadOnly),
161 "plan" => Ok(Self::Plan),
162 "ask" => Ok(Self::Ask),
163 "auto" => Ok(Self::Auto),
164 other => Err(KernelError::Config {
165 reason: format!(
166 "unknown partition mode `{other}`; use read_only, plan, ask or auto"
167 ),
168 }),
169 }
170 }
171}
172
173/// Whether a partition takes part in crossings (spec 3.2 §7.8).
174///
175/// A crossing needs both partitions to allow it: a partition set to [`Deny`](Self::Deny)
176/// is isolated both ways, even from the coordinator. Agentrix's Work and Home worlds are two
177/// partitions with [`CoordinatorWithApproval`](Self::CoordinatorWithApproval) (§4).
178///
179/// # Example
180///
181/// ```rust
182/// use adk_kernel::CrossPartition;
183///
184/// assert_eq!(CrossPartition::default(), CrossPartition::Deny);
185/// assert_eq!(
186/// serde_json::to_value(CrossPartition::CoordinatorWithApproval).unwrap(),
187/// "coordinator_with_approval"
188/// );
189/// ```
190#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192#[non_exhaustive]
193pub enum CrossPartition {
194 /// No request crosses into or out of the partition.
195 #[default]
196 Deny,
197 /// The coordinator may cross, each crossing under a non-waivable approval (K-I15).
198 CoordinatorWithApproval,
199}
200
201impl CrossPartition {
202 /// The value's name: `deny` or `coordinator_with_approval`.
203 pub fn as_str(self) -> &'static str {
204 match self {
205 Self::Deny => "deny",
206 Self::CoordinatorWithApproval => "coordinator_with_approval",
207 }
208 }
209}
210
211impl fmt::Display for CrossPartition {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 f.pad(self.as_str())
214 }
215}
216
217impl FromStr for CrossPartition {
218 type Err = KernelError;
219
220 fn from_str(text: &str) -> Result<Self> {
221 match text.trim().to_ascii_lowercase().replace('-', "_").as_str() {
222 "deny" => Ok(Self::Deny),
223 "coordinator_with_approval" | "coordinator" => Ok(Self::CoordinatorWithApproval),
224 other => Err(KernelError::Config {
225 reason: format!(
226 "unknown crossing setting `{other}`; use deny or coordinator_with_approval"
227 ),
228 }),
229 }
230 }
231}
232
233fn ask() -> PartitionMode {
234 PartitionMode::Ask
235}
236
237fn unlimited(quotas: &Quotas) -> bool {
238 *quotas == Quotas::default()
239}
240
241/// A partition (spec 3.2 §7.8): a policy class plus a memory scope plus a driver set, run by
242/// its own `HarnessAgent` built with [`default_mode`](Self::default_mode).
243///
244/// Its [`quotas`](Self::quotas) and [`quiet_hours`](Self::quiet_hours) apply beside the
245/// kernel's (spec 3.2 §7.9): each quota is the lower of the two, and every quiet-hours window
246/// holds.
247///
248/// # Example
249///
250/// ```rust
251/// use adk_kernel::{CrossPartition, Partition, PartitionMode, QuietHours, Quotas};
252///
253/// let work = Partition::new("work", "work")
254/// .with_mode(PartitionMode::Auto)
255/// .with_driver("calendar")
256/// .with_quotas(Quotas::new().with_max_running(2))
257/// .with_quiet_hours("19:00-08:00".parse::<QuietHours>().unwrap())
258/// .with_cross_partition(CrossPartition::CoordinatorWithApproval);
259/// assert_eq!(work.memory_scope, "work");
260/// assert_eq!(work.drivers, ["calendar"]);
261/// let wire = serde_json::to_value(&work).unwrap();
262/// assert_eq!(wire["defaultMode"], "auto");
263/// assert_eq!(wire["quotas"]["maxRunning"], 2);
264/// assert_eq!(wire["quietHours"]["start"], "19:00");
265/// assert_eq!(wire["crossPartition"], "coordinator_with_approval");
266/// assert_eq!(serde_json::from_value::<Partition>(wire).unwrap(), work);
267/// ```
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase")]
270#[non_exhaustive]
271pub struct Partition {
272 /// The partition's id: `work`, `home`, a team.
273 pub id: PartitionId,
274 /// `AgentPrincipal.class` of every agent in the partition.
275 pub class: String,
276 /// `AgentPrincipal.tenant` of every agent in the partition, on multi-tenant hosts.
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub tenant: Option<String>,
279 /// The mode of the partition's `HarnessAgent`; the harness maps it onto `HarnessMode`.
280 /// Defaults to `ask`.
281 #[serde(default = "ask")]
282 pub default_mode: PartitionMode,
283 /// The project of the partition's long-term facts (spec 3.1 §7.15.2) and of its
284 /// project-scoped memory. Defaults to the id.
285 pub memory_scope: String,
286 /// The ids of the drivers mounted for the partition (spec 3.2 §7.7). A driver reaches
287 /// the partition's agents only when it is mounted, its manifest lists the partition
288 /// and its id is here.
289 #[serde(default, skip_serializing_if = "Vec::is_empty")]
290 pub drivers: Vec<String>,
291 /// The partition's own quotas (spec 3.2 §7.9): each applies beside the kernel's, the
292 /// lower of the two. Defaults to none.
293 #[serde(default, skip_serializing_if = "unlimited")]
294 pub quotas: Quotas,
295 /// The partition's own quiet hours, which hold beside the kernel's: no proactive or
296 /// maintenance process of the partition starts inside them.
297 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub quiet_hours: Option<QuietHours>,
299 /// Whether the partition takes part in crossings. Defaults to [`CrossPartition::Deny`].
300 #[serde(default)]
301 pub cross_partition: CrossPartition,
302 /// Partitions the coordinator in this partition may no longer cross into: the prompt's
303 /// "deny and block crossings to *X* from this partition".
304 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
305 pub blocked_crossings: BTreeSet<PartitionId>,
306}
307
308impl Partition {
309 /// The principal attribute naming the partition of an agent
310 /// ([`principal`](Self::principal)).
311 pub const PRINCIPAL_ATTRIBUTE: &'static str = "adk.partition";
312
313 /// A partition `id` of class `class` in `ask` mode, its memory scope its id, with no
314 /// drivers and no crossings.
315 pub fn new(id: impl Into<PartitionId>, class: impl Into<String>) -> Self {
316 let id = id.into();
317 Self {
318 memory_scope: id.as_str().to_string(),
319 id,
320 class: class.into(),
321 tenant: None,
322 default_mode: PartitionMode::Ask,
323 drivers: Vec::new(),
324 quotas: Quotas::default(),
325 quiet_hours: None,
326 cross_partition: CrossPartition::Deny,
327 blocked_crossings: BTreeSet::new(),
328 }
329 }
330
331 /// Sets the tenant.
332 #[must_use]
333 pub fn with_tenant(mut self, tenant: impl Into<String>) -> Self {
334 self.tenant = Some(tenant.into());
335 self
336 }
337
338 /// Sets the mode.
339 #[must_use]
340 pub fn with_mode(mut self, mode: PartitionMode) -> Self {
341 self.default_mode = mode;
342 self
343 }
344
345 /// Sets the memory scope.
346 #[must_use]
347 pub fn with_memory_scope(mut self, scope: impl Into<String>) -> Self {
348 self.memory_scope = scope.into();
349 self
350 }
351
352 /// Adds a driver id.
353 #[must_use]
354 pub fn with_driver(mut self, driver: impl Into<String>) -> Self {
355 self.drivers.push(driver.into());
356 self
357 }
358
359 /// Sets the partition's own quotas.
360 #[must_use]
361 pub fn with_quotas(mut self, quotas: Quotas) -> Self {
362 self.quotas = quotas;
363 self
364 }
365
366 /// Sets the partition's own quiet hours.
367 #[must_use]
368 pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
369 self.quiet_hours = Some(quiet_hours);
370 self
371 }
372
373 /// Sets whether the partition takes part in crossings.
374 #[must_use]
375 pub fn with_cross_partition(mut self, cross_partition: CrossPartition) -> Self {
376 self.cross_partition = cross_partition;
377 self
378 }
379
380 /// Blocks crossings from this partition into `to`.
381 #[must_use]
382 pub fn with_blocked_crossing(mut self, to: impl Into<PartitionId>) -> Self {
383 self.blocked_crossings.insert(to.into());
384 self
385 }
386
387 /// Checks the record: a non-empty id, class and memory scope, none with control
388 /// characters.
389 ///
390 /// # Errors
391 ///
392 /// Returns [`KernelError::Config`] naming the field.
393 pub fn validate(&self) -> Result<()> {
394 let fields = [
395 ("id", self.id.as_str()),
396 ("class", self.class.as_str()),
397 ("memoryScope", self.memory_scope.as_str()),
398 ];
399 for (field, value) in fields {
400 if value.trim().is_empty() || value.chars().any(char::is_control) {
401 return Err(KernelError::Config {
402 reason: format!(
403 "partition `{}`: `{field}` must be non-empty text without control \
404 characters",
405 self.id
406 ),
407 });
408 }
409 }
410 Ok(())
411 }
412
413 /// The principal the agent `agent_name` of `app_name` acts as in this partition:
414 /// `urn:adk:agent:{app}/{agent}` with the partition's class and tenant, and the
415 /// partition's id as the [`PRINCIPAL_ATTRIBUTE`](Self::PRINCIPAL_ATTRIBUTE) attribute.
416 ///
417 /// # Example
418 ///
419 /// ```rust
420 /// use adk_kernel::Partition;
421 ///
422 /// let principal = Partition::new("work", "work-agents").with_tenant("acme").principal("ops", "harness");
423 /// assert_eq!(principal.id.as_str(), "urn:adk:agent:ops/harness");
424 /// assert_eq!(principal.class.as_deref(), Some("work-agents"));
425 /// assert_eq!(principal.tenant.as_deref(), Some("acme"));
426 /// assert_eq!(principal.attributes[Partition::PRINCIPAL_ATTRIBUTE], "work");
427 /// ```
428 pub fn principal(&self, app_name: &str, agent_name: &str) -> AgentPrincipal {
429 let mut principal = AgentPrincipal::derived(app_name, agent_name)
430 .with_class(self.class.clone())
431 .with_attribute(Self::PRINCIPAL_ATTRIBUTE, self.id.as_str());
432 if let Some(tenant) = &self.tenant {
433 principal = principal.with_tenant(tenant.clone());
434 }
435 principal
436 }
437
438 /// The runner's identity source for the partition's harness (spec 3.1 §7.14): every
439 /// agent of the runner whose root is `root_agent` acts as its
440 /// [`principal`](Self::principal) in this partition, so its class and tenant reach every
441 /// `ToolPolicyRequest`, `ToolConfirmationRequest`, `SpendKey` and audit record.
442 ///
443 /// # Example
444 ///
445 /// ```rust
446 /// use adk_core::IdentitySource;
447 /// use adk_kernel::Partition;
448 ///
449 /// # futures::executor::block_on(async {
450 /// let source = Partition::new("home", "home").identity_source("adk-rust", "harness");
451 /// assert_eq!(source.current().await.unwrap().class.as_deref(), Some("home"));
452 /// let member = source.principal_for("reviewer").await.unwrap().unwrap();
453 /// assert_eq!(member.id.as_str(), "urn:adk:agent:adk-rust/reviewer");
454 /// assert_eq!(member.class.as_deref(), Some("home"));
455 /// # });
456 /// ```
457 pub fn identity_source(&self, app_name: &str, root_agent: &str) -> Arc<dyn IdentitySource> {
458 Arc::new(PartitionIdentity {
459 partition: self.clone(),
460 app_name: app_name.to_string(),
461 root_agent: root_agent.to_string(),
462 })
463 }
464
465 /// `memory` confined to the partition's [`memory_scope`](Self::memory_scope): searches
466 /// and writes go through the memory's project scoping, and a search or write naming
467 /// another project is refused (K-I15).
468 ///
469 /// # Errors
470 ///
471 /// Returns [`KernelError::Config`] when `memory` does not keep projects apart
472 /// (`Memory::supports_project_scoping` is `false`): a memory without project scoping
473 /// would show every partition's entries to every other.
474 ///
475 /// # Example
476 ///
477 /// ```rust,ignore
478 /// let memory = work.scope_memory(Arc::new(adk_memory::SqliteMemoryService::new(url).await?))?;
479 /// let runner = Runner::builder().memory_service(memory) /* … */;
480 /// ```
481 pub fn scope_memory(&self, memory: Arc<dyn Memory>) -> Result<Arc<dyn Memory>> {
482 if !memory.supports_project_scoping() {
483 return Err(KernelError::Config {
484 reason: format!(
485 "partition `{}` needs a memory that keeps projects apart: this memory \
486 does not implement project scoping, so it would show every partition's \
487 entries to every other; use a MemoryService with project support",
488 self.id
489 ),
490 });
491 }
492 Ok(Arc::new(PartitionMemory {
493 inner: memory,
494 partition: self.id.clone(),
495 project: self.memory_scope.clone(),
496 }))
497 }
498}
499
500/// The identity of a partition's agents ([`Partition::identity_source`]).
501#[derive(Debug)]
502struct PartitionIdentity {
503 partition: Partition,
504 app_name: String,
505 root_agent: String,
506}
507
508#[async_trait]
509impl IdentitySource for PartitionIdentity {
510 async fn current(&self) -> adk_core::Result<AgentPrincipal> {
511 Ok(self.partition.principal(&self.app_name, &self.root_agent))
512 }
513
514 async fn principal_for(&self, agent_name: &str) -> adk_core::Result<Option<AgentPrincipal>> {
515 Ok(Some(self.partition.principal(&self.app_name, agent_name)))
516 }
517}
518
519/// A memory confined to one partition's project ([`Partition::scope_memory`]).
520struct PartitionMemory {
521 inner: Arc<dyn Memory>,
522 partition: PartitionId,
523 project: String,
524}
525
526impl PartitionMemory {
527 fn refuse(&self, project: &str) -> AdkError {
528 AdkError::new(
529 ErrorComponent::Memory,
530 ErrorCategory::Forbidden,
531 MEMORY_CROSSING_CODE,
532 format!(
533 "partition `{}` reads and writes only its own memory scope `{}`, not `{project}`; \
534 the coordinator reaches another partition through a crossing (spec 3.2 K-I15)",
535 self.partition, self.project
536 ),
537 )
538 }
539}
540
541#[async_trait]
542impl Memory for PartitionMemory {
543 async fn search(&self, query: &str) -> adk_core::Result<Vec<MemoryEntry>> {
544 self.inner.search_in_project(query, &self.project).await
545 }
546
547 async fn health_check(&self) -> adk_core::Result<()> {
548 self.inner.health_check().await
549 }
550
551 async fn add(&self, entry: MemoryEntry) -> adk_core::Result<()> {
552 self.inner.add_to_project(entry, &self.project).await
553 }
554
555 async fn delete(&self, _query: &str) -> adk_core::Result<u64> {
556 // The inner `delete` matches entries in every project.
557 Err(AdkError::new(
558 ErrorComponent::Memory,
559 ErrorCategory::Unsupported,
560 MEMORY_DELETE_CODE,
561 format!(
562 "partition `{}` cannot delete by query: the memory's delete reaches every \
563 project; delete the partition's project through its MemoryService",
564 self.partition
565 ),
566 ))
567 }
568
569 fn supports_project_scoping(&self) -> bool {
570 true
571 }
572
573 async fn search_in_project(
574 &self,
575 query: &str,
576 project_id: &str,
577 ) -> adk_core::Result<Vec<MemoryEntry>> {
578 if project_id != self.project {
579 return Err(self.refuse(project_id));
580 }
581 self.inner.search_in_project(query, project_id).await
582 }
583
584 async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> adk_core::Result<()> {
585 if project_id != self.project {
586 return Err(self.refuse(project_id));
587 }
588 self.inner.add_to_project(entry, project_id).await
589 }
590}
591
592/// The partition table and the crossing ledger (spec 3.2 §7.8, §13 Q8), on every backend
593/// [`ProcessStore`](crate::ProcessStore) has: [`InMemoryPartitionStore`](crate::InMemoryPartitionStore),
594/// `SqlitePartitionStore`, `PostgresPartitionStore` and `RedisPartitionStore`, with one
595/// conformance suite (`partition_store_conformance_tests!`, feature `conformance`).
596///
597/// # Example
598///
599/// ```rust
600/// use adk_kernel::{InMemoryPartitionStore, Partition, PartitionId, PartitionStore};
601///
602/// # #[tokio::main(flavor = "current_thread")]
603/// # async fn main() -> adk_kernel::Result<()> {
604/// let store = InMemoryPartitionStore::new();
605/// store.put(Partition::new("work", "work")).await?;
606/// assert_eq!(store.get(&PartitionId::new("work")).await?.unwrap().class, "work");
607/// assert_eq!(store.list().await?.len(), 1);
608/// # Ok(())
609/// # }
610/// ```
611#[async_trait]
612pub trait PartitionStore: Send + Sync {
613 /// Inserts `partition`, or replaces the record with the same id.
614 ///
615 /// # Errors
616 ///
617 /// Returns [`KernelError::Store`] when the backend fails.
618 async fn put(&self, partition: Partition) -> Result<()>;
619
620 /// The partition `id`, or `None`.
621 ///
622 /// # Errors
623 ///
624 /// Returns [`KernelError::Store`] when the backend fails.
625 async fn get(&self, id: &PartitionId) -> Result<Option<Partition>>;
626
627 /// Every partition, ordered by id in byte order.
628 ///
629 /// # Errors
630 ///
631 /// Returns [`KernelError::Store`] when the backend fails.
632 async fn list(&self) -> Result<Vec<Partition>>;
633
634 /// Deletes the partition `id`; `false` when there was none. Its crossing records stay.
635 ///
636 /// # Errors
637 ///
638 /// Returns [`KernelError::Store`] when the backend fails.
639 async fn delete(&self, id: &PartitionId) -> Result<bool>;
640
641 /// Appends one crossing record. Records are never changed or deleted.
642 ///
643 /// # Errors
644 ///
645 /// Returns [`KernelError::Store`] when the backend fails.
646 async fn record_crossing(&self, record: CrossingRecord) -> Result<()>;
647
648 /// The crossing records `filter` selects, ordered by time, then id, at most
649 /// `filter.limit`.
650 ///
651 /// # Errors
652 ///
653 /// Returns [`KernelError::Store`] when the backend fails.
654 async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>>;
655
656 /// Records that the read with crossing-fingerprint digest `fingerprint` was approved in
657 /// the durable run `run`, for the rest of that run (spec 3.2 §13 Q3). Granting twice
658 /// keeps one grant.
659 ///
660 /// # Errors
661 ///
662 /// Returns [`KernelError::Store`] when the backend fails.
663 async fn grant(&self, run: &str, fingerprint: &str) -> Result<()>;
664
665 /// The fingerprint digests the durable run `run` holds grants for.
666 ///
667 /// # Errors
668 ///
669 /// Returns [`KernelError::Store`] when the backend fails.
670 async fn grants(&self, run: &str) -> Result<Vec<String>>;
671
672 /// Drops every grant of the durable run `run`, which finished; answers how many.
673 ///
674 /// # Errors
675 ///
676 /// Returns [`KernelError::Store`] when the backend fails.
677 async fn release_run(&self, run: &str) -> Result<u64>;
678}
679
680/// An unknown partition, as the control plane answers it (`404`).
681pub(crate) fn unknown_partition(id: &PartitionId) -> KernelError {
682 KernelError::Core(AdkError::new(
683 ErrorComponent::Server,
684 ErrorCategory::NotFound,
685 NOT_FOUND_CODE,
686 format!("no partition named `{id}`; list them with `adk-rust partitions`"),
687 ))
688}
689
690/// How many (fingerprint, call, outcome) triples the policy remembers having recorded, so
691/// the re-evaluations of one call (an edit, a prompt's re-check) record once.
692const RECORDED_CAP: usize = 4096;
693
694/// How many invocations' grants are kept in memory before they are all dropped.
695const INVOCATION_GRANTS_CAP: usize = 4096;
696
697/// One call's crossing as the ledger records it: the crossing, its fingerprint, and the
698/// run, agent and tool that made it.
699pub(crate) struct CrossingCall<'a> {
700 pub(crate) crossing: &'a Crossing,
701 pub(crate) fingerprint: &'a str,
702 pub(crate) run: &'a str,
703 pub(crate) agent: &'a str,
704 pub(crate) tool: &'a str,
705}
706
707/// The partition table and its crossings (spec 3.2 §7.8): reads and changes partitions
708/// with `kernel.partition.created` and `kernel.partition.changed` records, builds each
709/// partition's [`PartitionPolicy`], and keeps the crossing ledger the policy and the crossing
710/// tools write and the run's approvals are read from. Cloning shares it.
711///
712/// # Example
713///
714/// ```rust
715/// use adk_core::audit_log::AuditActor;
716/// use adk_kernel::{CrossPartition, Partition, Partitions};
717///
718/// # #[tokio::main(flavor = "current_thread")]
719/// # async fn main() -> adk_kernel::Result<()> {
720/// let partitions = Partitions::in_memory();
721/// let by = AuditActor::default();
722/// partitions.put(Partition::new("home", "home").with_cross_partition(CrossPartition::CoordinatorWithApproval), by.clone()).await?;
723/// partitions.put(Partition::new("work", "work").with_cross_partition(CrossPartition::CoordinatorWithApproval), by.clone()).await?;
724/// let home = partitions.block("home", "work", by).await?;
725/// assert!(home.blocked_crossings.contains(&"work".into()));
726/// # Ok(())
727/// # }
728/// ```
729#[derive(Clone)]
730pub struct Partitions {
731 inner: Arc<PartitionsInner>,
732}
733
734struct PartitionsInner {
735 store: Arc<dyn PartitionStore>,
736 audit: OnceLock<AuditTrail>,
737 clock: Arc<dyn Clock>,
738 recorded: Mutex<HashSet<(String, String, CrossingOutcome)>>,
739 /// The approved reads of invocations outside a durable run, by invocation id; process
740 /// memory, so they end with the process if the invocation never does.
741 invocation_grants: Mutex<HashMap<String, HashSet<String>>>,
742}
743
744impl fmt::Debug for Partitions {
745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746 f.debug_struct("Partitions")
747 .field("audit", &self.inner.audit.get().is_some())
748 .finish_non_exhaustive()
749 }
750}
751
752impl Partitions {
753 /// The partitions in `store`.
754 pub fn new(store: Arc<dyn PartitionStore>) -> Self {
755 Self::with_parts(store, Arc::new(SystemClock))
756 }
757
758 /// The partitions in a new [`InMemoryPartitionStore`](crate::InMemoryPartitionStore).
759 pub fn in_memory() -> Self {
760 Self::new(Arc::new(crate::stores::InMemoryPartitionStore::new()))
761 }
762
763 fn with_parts(store: Arc<dyn PartitionStore>, clock: Arc<dyn Clock>) -> Self {
764 Self {
765 inner: Arc::new(PartitionsInner {
766 store,
767 audit: OnceLock::new(),
768 clock,
769 recorded: Mutex::new(HashSet::new()),
770 invocation_grants: Mutex::new(HashMap::new()),
771 }),
772 }
773 }
774
775 /// Writes the partition and crossing records to `trail` (spec 3.2 §9.3).
776 #[must_use]
777 pub fn with_audit(self, trail: AuditTrail) -> Self {
778 let _ = self.inner.audit.set(trail);
779 self
780 }
781
782 /// Reads crossing times from `clock` instead of the system clock.
783 #[must_use]
784 pub fn with_clock(self, clock: Arc<dyn Clock>) -> Self {
785 let partitions = Self::with_parts(Arc::clone(&self.inner.store), clock);
786 if let Some(trail) = self.inner.audit.get() {
787 let _ = partitions.inner.audit.set(trail.clone());
788 }
789 partitions
790 }
791
792 /// Sets the audit trail when none is set yet; the kernel attaches its own at build.
793 pub fn attach_audit(&self, trail: AuditTrail) {
794 let _ = self.inner.audit.set(trail);
795 }
796
797 /// The store.
798 pub fn store(&self) -> &Arc<dyn PartitionStore> {
799 &self.inner.store
800 }
801
802 /// The partition `id`, or `None`.
803 ///
804 /// # Errors
805 ///
806 /// Returns the store's error.
807 pub async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
808 self.inner.store.get(id).await
809 }
810
811 /// Every partition, ordered by id.
812 ///
813 /// # Errors
814 ///
815 /// Returns the store's error.
816 pub async fn list(&self) -> Result<Vec<Partition>> {
817 self.inner.store.list().await
818 }
819
820 /// Creates or changes `partition`, recording `kernel.partition.created` or
821 /// `kernel.partition.changed` with the fields that changed.
822 ///
823 /// # Errors
824 ///
825 /// Returns [`KernelError::Config`] when the record is invalid, or the store's error.
826 pub async fn put(&self, partition: Partition, by: AuditActor) -> Result<()> {
827 partition.validate()?;
828 let before = self.inner.store.get(&partition.id).await?;
829 let to = serde_json::to_value(&partition)?;
830 let (action, fields, from) = match &before {
831 None => (audit::PARTITION_CREATED, Vec::new(), Value::Null),
832 Some(before) => {
833 let from = serde_json::to_value(before)?;
834 let changed: Vec<String> = match (&from, &to) {
835 (Value::Object(old), Value::Object(new)) => old
836 .keys()
837 .chain(new.keys())
838 .filter(|key| old.get(*key) != new.get(*key))
839 .cloned()
840 .collect::<BTreeSet<_>>()
841 .into_iter()
842 .collect(),
843 _ => Vec::new(),
844 };
845 if changed.is_empty() {
846 return Ok(());
847 }
848 (audit::PARTITION_CHANGED, changed, from)
849 }
850 };
851 self.inner.store.put(partition.clone()).await?;
852 let fields = json!({
853 "partition": partition.id,
854 "fields": fields,
855 "from": from,
856 "to": to,
857 });
858 self.record_audit(action, by, fields).await;
859 Ok(())
860 }
861
862 /// Sets the mode of partition `id`.
863 ///
864 /// # Errors
865 ///
866 /// Returns a `404` error when there is no such partition, or the store's error.
867 pub async fn set_mode(
868 &self,
869 id: impl Into<PartitionId>,
870 mode: PartitionMode,
871 by: AuditActor,
872 ) -> Result<Partition> {
873 let id = id.into();
874 let partition = self.inner.store.get(&id).await?.ok_or_else(|| unknown_partition(&id))?;
875 let partition = partition.with_mode(mode);
876 self.put(partition.clone(), by).await?;
877 Ok(partition)
878 }
879
880 /// Blocks crossings from `from` into `to`: the prompt's "deny and block crossings to
881 /// *to* from this partition". The block stays until the partition record is changed.
882 ///
883 /// # Errors
884 ///
885 /// Returns a `404` error when `from` is not a partition, or the store's error.
886 pub async fn block(
887 &self,
888 from: impl Into<PartitionId>,
889 to: impl Into<PartitionId>,
890 by: AuditActor,
891 ) -> Result<Partition> {
892 let from = from.into();
893 let partition =
894 self.inner.store.get(&from).await?.ok_or_else(|| unknown_partition(&from))?;
895 let partition = partition.with_blocked_crossing(to);
896 self.put(partition.clone(), by).await?;
897 Ok(partition)
898 }
899
900 /// The crossing records `filter` selects.
901 ///
902 /// # Errors
903 ///
904 /// Returns the store's error.
905 pub async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
906 self.inner.store.crossings(filter).await
907 }
908
909 /// The policy of partition `home`'s harness ([`PartitionPolicy`]).
910 pub fn policy(&self, home: impl Into<PartitionId>) -> PartitionPolicy {
911 PartitionPolicy::new(self.clone(), home.into())
912 }
913
914 /// Why `crossing` may not happen, or `Ok` when it may ask for approval: both
915 /// partitions exist and take part in crossings, the caller is the coordinator, and the
916 /// source has not blocked the target (spec 3.2 §7.8, K-I15).
917 ///
918 /// # Errors
919 ///
920 /// The refusal's reason, also when the partition table cannot be read: a crossing
921 /// fails closed.
922 pub async fn admit(
923 &self,
924 crossing: &Crossing,
925 coordinator: bool,
926 ) -> std::result::Result<(), String> {
927 let read = |id: &PartitionId| {
928 let id = id.clone();
929 async move {
930 match self.inner.store.get(&id).await {
931 Ok(Some(partition)) => Ok(partition),
932 Ok(None) => Err(format!("there is no partition named `{id}`")),
933 Err(error) => Err(format!(
934 "the partition table could not be read ({error}), so the crossing is \
935 refused"
936 )),
937 }
938 }
939 };
940 let from = read(&crossing.from).await?;
941 let to = read(&crossing.to).await?;
942 if !coordinator {
943 return Err(format!(
944 "{} belongs to partition `{}`; only the coordinator may cross into another \
945 partition, and only under approval",
946 crossing.label(),
947 crossing.to
948 ));
949 }
950 for partition in [&from, &to] {
951 if partition.cross_partition == CrossPartition::Deny {
952 return Err(format!(
953 "partition `{}` takes part in no crossings (cross_partition: deny)",
954 partition.id
955 ));
956 }
957 }
958 if from.blocked_crossings.contains(&crossing.to) {
959 return Err(format!(
960 "crossings to `{}` from partition `{}` are blocked",
961 crossing.to, crossing.from
962 ));
963 }
964 Ok(())
965 }
966
967 /// Whether the read `fingerprint` (a [`Crossing::fingerprint`]) was approved earlier in
968 /// `run` and the run still holds the grant, so the coordinator's identical read needs no
969 /// approval for the rest of the run (spec 3.2 §13 Q3). A failed read of the store answers
970 /// `false`: the crossing asks again.
971 pub async fn granted(&self, run: &CrossingRun, fingerprint: &str) -> bool {
972 let digest = crossing::digest(fingerprint);
973 match run {
974 CrossingRun::Invocation(id) => self
975 .inner
976 .invocation_grants
977 .lock()
978 .unwrap_or_else(|e| e.into_inner())
979 .get(id)
980 .is_some_and(|grants| grants.contains(&digest)),
981 CrossingRun::Durable(id) => match self.inner.store.grants(id).await {
982 Ok(grants) => grants.contains(&digest),
983 Err(error) => {
984 tracing::warn!(error = %error, "could not read the run's crossing grants; the crossing asks again");
985 false
986 }
987 },
988 }
989 }
990
991 /// The fingerprint digests `run` holds grants for.
992 ///
993 /// # Errors
994 ///
995 /// Returns the store's error for a durable run.
996 pub async fn grants(&self, run: &CrossingRun) -> Result<Vec<String>> {
997 match run {
998 CrossingRun::Invocation(id) => {
999 let grants = self.inner.invocation_grants.lock().unwrap_or_else(|e| e.into_inner());
1000 let mut digests: Vec<String> =
1001 grants.get(id).map(|set| set.iter().cloned().collect()).unwrap_or_default();
1002 digests.sort();
1003 Ok(digests)
1004 }
1005 CrossingRun::Durable(id) => self.inner.store.grants(id).await,
1006 }
1007 }
1008
1009 /// Drops every grant of `run`, which finished, so no later run can reuse one (spec 3.2
1010 /// §13 Q3): the kernel's worker calls it when a durable run ends, the partition's
1011 /// harness when an invocation outside a durable run ends. Answers how many it dropped.
1012 ///
1013 /// # Errors
1014 ///
1015 /// Returns the store's error for a durable run.
1016 pub async fn release_run(&self, run: &CrossingRun) -> Result<u64> {
1017 match run {
1018 CrossingRun::Invocation(id) => Ok(self
1019 .inner
1020 .invocation_grants
1021 .lock()
1022 .unwrap_or_else(|e| e.into_inner())
1023 .remove(id)
1024 .map_or(0, |grants| grants.len() as u64)),
1025 CrossingRun::Durable(id) => self.inner.store.release_run(id).await,
1026 }
1027 }
1028
1029 /// Records that `crossing` ran in `run` after its approval, and, for a read, keeps the
1030 /// approval the coordinator's identical reads reuse for the rest of the run. A write is
1031 /// never kept: it is approved one call at a time. A crossing tool calls it after the
1032 /// governed path authorized the call.
1033 ///
1034 /// # Errors
1035 ///
1036 /// Returns the store's error; the tool then reports the crossing unrecorded.
1037 pub async fn executed(
1038 &self,
1039 crossing: &Crossing,
1040 fingerprint: &str,
1041 run: &CrossingRun,
1042 agent: &str,
1043 tool: &str,
1044 ) -> Result<()> {
1045 let read = crossing.access == CrossingAccess::Read;
1046 if read && self.granted(run, fingerprint).await {
1047 return Ok(());
1048 }
1049 let call = CrossingCall { crossing, fingerprint, run: run.as_str(), agent, tool };
1050 let record = self.crossing_record(&call, CrossingOutcome::Approved, None);
1051 self.inner.store.record_crossing(record.clone()).await?;
1052 self.audit_crossing(&record).await;
1053 if read {
1054 match run {
1055 CrossingRun::Invocation(id) => {
1056 let mut grants =
1057 self.inner.invocation_grants.lock().unwrap_or_else(|e| e.into_inner());
1058 // Dropping everything only makes later reads ask again.
1059 if grants.len() > INVOCATION_GRANTS_CAP {
1060 grants.clear();
1061 }
1062 grants.entry(id.clone()).or_default().insert(record.fingerprint);
1063 }
1064 CrossingRun::Durable(id) => self.inner.store.grant(id, &record.fingerprint).await?,
1065 }
1066 }
1067 Ok(())
1068 }
1069
1070 /// The crossings since `since` that recur at least `at_least` times, by source, target,
1071 /// resource and name, most frequent first (spec 3.2 §7.8): what the maintenance process
1072 /// reports, with partition membership as the remedy. A request counts once: held, denied,
1073 /// or let through by its run's approval; the approval of a held request is not counted
1074 /// again.
1075 ///
1076 /// # Errors
1077 ///
1078 /// Returns the store's error.
1079 pub async fn recurring_crossings(
1080 &self,
1081 since: chrono::DateTime<chrono::Utc>,
1082 at_least: usize,
1083 ) -> Result<Vec<RecurringCrossing>> {
1084 let filter = CrossingFilter::default().since(since).outcomes([
1085 CrossingOutcome::Held,
1086 CrossingOutcome::Denied,
1087 CrossingOutcome::RunGrant,
1088 ]);
1089 let mut counts: std::collections::BTreeMap<
1090 (PartitionId, PartitionId, CrossingResource, String),
1091 usize,
1092 > = std::collections::BTreeMap::new();
1093 for record in self.inner.store.crossings(&filter).await? {
1094 *counts.entry((record.from, record.to, record.resource, record.name)).or_default() += 1;
1095 }
1096 let mut recurring: Vec<RecurringCrossing> = counts
1097 .into_iter()
1098 .filter(|(_, count)| *count >= at_least)
1099 .map(|((from, to, resource, name), count)| {
1100 RecurringCrossing::new(from, to, resource, name, count)
1101 })
1102 .collect();
1103 recurring.sort_by_key(|crossing| std::cmp::Reverse(crossing.count));
1104 Ok(recurring)
1105 }
1106
1107 /// Records a decision the policy made about `call`, once per call id and outcome.
1108 pub(crate) async fn decided(
1109 &self,
1110 call: &CrossingCall<'_>,
1111 call_id: Option<&str>,
1112 outcome: CrossingOutcome,
1113 reason: Option<String>,
1114 ) {
1115 if let Some(call_id) = call_id {
1116 let mut recorded = self.inner.recorded.lock().unwrap_or_else(|e| e.into_inner());
1117 if recorded.len() > RECORDED_CAP {
1118 recorded.clear();
1119 }
1120 // Keyed by the call, not the run: a prompt's re-check sees no durable run id.
1121 if !recorded.insert((crossing::digest(call.fingerprint), call_id.to_string(), outcome))
1122 {
1123 return;
1124 }
1125 }
1126 let record = self.crossing_record(call, outcome, reason);
1127 if let Err(error) = self.inner.store.record_crossing(record.clone()).await {
1128 tracing::warn!(error = %error, "could not write a crossing record");
1129 }
1130 self.audit_crossing(&record).await;
1131 }
1132
1133 fn crossing_record(
1134 &self,
1135 call: &CrossingCall<'_>,
1136 outcome: CrossingOutcome,
1137 reason: Option<String>,
1138 ) -> CrossingRecord {
1139 let crossing = call.crossing;
1140 CrossingRecord {
1141 id: uuid::Uuid::new_v4().to_string(),
1142 at: self.inner.clock.now(),
1143 run: call.run.to_string(),
1144 agent: call.agent.to_string(),
1145 from: crossing.from.clone(),
1146 to: crossing.to.clone(),
1147 resource: crossing.resource,
1148 name: crossing.name.clone(),
1149 access: crossing.access,
1150 tool: call.tool.to_string(),
1151 fingerprint: crossing::digest(call.fingerprint),
1152 outcome,
1153 reason,
1154 }
1155 }
1156
1157 /// Writes `kernel.partition.crossing` (spec 3.2 §9.3): ids, names and a digest, never
1158 /// the call's arguments.
1159 async fn audit_crossing(&self, record: &CrossingRecord) {
1160 let actor = match adk_core::AgentId::new(record.agent.clone()) {
1161 Ok(agent) => AuditActor { agent: Some(agent), ..AuditActor::default() },
1162 Err(_) => AuditActor::default(),
1163 };
1164 let fields = json!({
1165 "partition": record.from,
1166 "to": record.to,
1167 "resource": record.resource,
1168 "name": record.name,
1169 "access": record.access,
1170 "outcome": record.outcome,
1171 "run": record.run,
1172 "tool": record.tool,
1173 "fingerprintDigest": record.fingerprint,
1174 "reason": record.reason,
1175 "by": record.agent,
1176 });
1177 self.record_audit(audit::PARTITION_CROSSING, actor, fields).await;
1178 }
1179
1180 async fn record_audit(&self, action: &str, actor: AuditActor, fields: Value) {
1181 let Some(trail) = self.inner.audit.get() else { return };
1182 let mut draft =
1183 AuditRecordDraft::new(AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.into()), action)
1184 .actor(actor);
1185 if let Value::Object(fields) = fields {
1186 for (key, value) in fields {
1187 draft = draft.ext(key, value);
1188 }
1189 }
1190 if let Err(error) = trail.record(draft).await {
1191 tracing::warn!(audit.action = action, error = %error, "could not write a partition audit record");
1192 }
1193 }
1194}