use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use adk_core::principal::{SubjectKind, SubjectRef};
use adk_core::{
ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApprovalService,
ApprovalState, ApproverSelector, NewRun, RunBudget, RunState, ToolConfirmationRequest,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::consolidation::ConsolidationTick;
use crate::error::{KernelError, Result};
use crate::partition::{PartitionId, PartitionMode};
use crate::process::{ProcessKind, ProcessSpec, ProcessTable};
use crate::sched::{QueueClass, QuietHours};
use crate::supervise::Supervision;
use crate::wake::{Wake, WakeSet};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AgendaItem {
pub id: String,
#[serde(default)]
pub partition: PartitionId,
pub subject: SubjectRef,
pub title: String,
pub rationale: String,
pub origin: AgendaOrigin,
pub state: AgendaState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plan: Option<PlanRef>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "crate::serde_util::option_run_budget"
)]
pub budget: Option<RunBudget>,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub when: Option<Wake>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub answer: Option<AgendaAnswer>,
}
impl AgendaItem {
pub fn new(
id: impl Into<String>,
subject: SubjectRef,
title: impl Into<String>,
rationale: impl Into<String>,
origin: AgendaOrigin,
created_at: DateTime<Utc>,
) -> Self {
Self {
id: id.into(),
partition: PartitionId::default(),
subject,
title: title.into(),
rationale: rationale.into(),
origin,
state: AgendaState::Proposed,
plan: None,
budget: None,
created_at,
expires_at: None,
when: None,
answer: None,
}
}
#[must_use]
pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = partition.into();
self
}
#[must_use]
pub fn with_state(mut self, state: AgendaState) -> Self {
self.state = state;
self
}
#[must_use]
pub fn with_plan(mut self, plan: PlanRef) -> Self {
self.plan = Some(plan);
self
}
#[must_use]
pub fn with_budget(mut self, budget: RunBudget) -> Self {
self.budget = Some(budget);
self
}
#[must_use]
pub fn with_expiry(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
#[must_use]
pub fn with_when(mut self, when: Wake) -> Self {
self.when = Some(when);
self
}
pub fn proposer(&self) -> Option<&str> {
match &self.origin {
AgendaOrigin::Agent { pid, .. } => Some(pid),
AgendaOrigin::User
| AgendaOrigin::Consolidation
| AgendaOrigin::Observation { .. }
| AgendaOrigin::Signal { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum AgendaOrigin {
User,
Agent {
pid: String,
confidence: f32,
},
Consolidation,
Observation {
id: String,
},
Signal {
kind: String,
count: u32,
},
}
impl AgendaOrigin {
pub fn needs_a_person(&self) -> bool {
matches!(self, Self::Consolidation | Self::Observation { .. } | Self::Signal { .. })
}
pub fn is_question(&self) -> bool {
matches!(self, Self::Observation { .. })
}
pub fn kind(&self) -> &'static str {
match self {
Self::User => "user",
Self::Agent { .. } => "agent",
Self::Consolidation => "consolidation",
Self::Observation { .. } => "observation",
Self::Signal { .. } => "signal",
}
}
}
impl fmt::Display for AgendaOrigin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Agent { pid, .. } => write!(f, "agent:{pid}"),
Self::Observation { id } => write!(f, "observation:{id}"),
Self::Signal { kind, .. } => write!(f, "signal:{kind}"),
Self::User | Self::Consolidation => f.write_str(self.kind()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AgendaAnswer {
pub confirmed: bool,
pub by: SubjectRef,
pub at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fact: Option<String>,
}
impl AgendaAnswer {
pub fn new(confirmed: bool, by: SubjectRef, at: DateTime<Utc>) -> Self {
Self { confirmed, by, at, fact: None }
}
#[must_use]
pub fn with_fact(mut self, fact: impl Into<String>) -> Self {
self.fact = Some(fact.into());
self
}
}
#[async_trait]
pub trait ObservationAudience: Send + Sync {
async fn audience(
&self,
partition: &PartitionId,
) -> Result<Option<(SubjectRef, PartitionMode)>>;
async fn confirm(&self, item: &AgendaItem, by: &SubjectRef) -> Result<String>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum AgendaState {
Proposed,
Approved,
Scheduled {
wake: WakeSet,
},
Running {
pid: String,
},
Done,
Rejected,
Expired,
}
impl AgendaState {
pub fn kind(&self) -> AgendaStateKind {
match self {
Self::Proposed => AgendaStateKind::Proposed,
Self::Approved => AgendaStateKind::Approved,
Self::Scheduled { .. } => AgendaStateKind::Scheduled,
Self::Running { .. } => AgendaStateKind::Running,
Self::Done => AgendaStateKind::Done,
Self::Rejected => AgendaStateKind::Rejected,
Self::Expired => AgendaStateKind::Expired,
}
}
}
impl fmt::Display for AgendaState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Running { pid } => write!(f, "running:{pid}"),
other => f.write_str(other.kind().as_str()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum AgendaStateKind {
Proposed,
Approved,
Scheduled,
Running,
Done,
Rejected,
Expired,
}
impl AgendaStateKind {
pub const ALL: [Self; 7] = [
Self::Proposed,
Self::Approved,
Self::Scheduled,
Self::Running,
Self::Done,
Self::Rejected,
Self::Expired,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Proposed => "proposed",
Self::Approved => "approved",
Self::Scheduled => "scheduled",
Self::Running => "running",
Self::Done => "done",
Self::Rejected => "rejected",
Self::Expired => "expired",
}
}
pub fn is_open(self) -> bool {
matches!(self, Self::Proposed | Self::Approved | Self::Scheduled | Self::Running)
}
}
impl fmt::Display for AgendaStateKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for AgendaStateKind {
type Err = crate::KernelError;
fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
let text = text.trim().to_ascii_lowercase();
Self::ALL.into_iter().find(|kind| kind.as_str() == text).ok_or_else(|| {
crate::KernelError::Config {
reason: format!(
"unknown agenda state `{text}`; use proposed, approved, scheduled, running, done, rejected or expired"
),
}
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PlanRef {
pub plan_hash: String,
pub steps: Vec<Value>,
}
impl PlanRef {
pub fn new(plan_hash: impl Into<String>, steps: Vec<Value>) -> Self {
Self { plan_hash: plan_hash.into(), steps }
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProactiveApproval {
#[default]
FollowMode,
AlwaysAsk,
Never,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct ProactivityPolicy {
pub max_proposed_open: usize,
#[serde(with = "crate::serde_util::run_budget")]
pub daily_budget: RunBudget,
#[serde(skip_serializing_if = "Option::is_none")]
pub quiet_hours: Option<QuietHours>,
pub approval: ProactiveApproval,
#[serde(skip_serializing_if = "Option::is_none")]
pub consolidation: Option<ConsolidationTick>,
#[serde(rename = "reviewPeriodMs", with = "crate::serde_util::millis")]
pub review_period: std::time::Duration,
}
impl ProactivityPolicy {
pub const DEFAULT_MAX_PROPOSED_OPEN: usize = 10;
pub const DEFAULT_REVIEW_PERIOD: std::time::Duration =
std::time::Duration::from_secs(90 * 24 * 60 * 60);
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_max_proposed_open(mut self, max: usize) -> Self {
self.max_proposed_open = max;
self
}
#[must_use]
pub fn with_daily_budget(mut self, budget: RunBudget) -> Self {
self.daily_budget = budget;
self
}
#[must_use]
pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
self.quiet_hours = Some(quiet_hours);
self
}
#[must_use]
pub fn with_approval(mut self, approval: ProactiveApproval) -> Self {
self.approval = approval;
self
}
#[must_use]
pub fn with_consolidation(mut self, tick: ConsolidationTick) -> Self {
self.consolidation = Some(tick);
self
}
#[must_use]
pub fn with_review_period(mut self, period: std::time::Duration) -> Self {
self.review_period = period;
self
}
}
impl Default for ProactivityPolicy {
fn default() -> Self {
Self {
max_proposed_open: Self::DEFAULT_MAX_PROPOSED_OPEN,
daily_budget: RunBudget::new(),
quiet_hours: None,
approval: ProactiveApproval::FollowMode,
consolidation: None,
review_period: Self::DEFAULT_REVIEW_PERIOD,
}
}
}
#[async_trait]
pub trait AgendaStore: Send + Sync {
async fn put(&self, item: AgendaItem) -> Result<()>;
async fn get(&self, id: &str) -> Result<Option<AgendaItem>>;
async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>>;
async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool>;
async fn delete(&self, id: &str) -> Result<bool>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AgendaFilter {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub partition: Option<PartitionId>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub states: Vec<AgendaStateKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
}
impl AgendaFilter {
#[must_use]
pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
self.partition = Some(partition.into());
self
}
#[must_use]
pub fn states(mut self, states: impl IntoIterator<Item = AgendaStateKind>) -> Self {
self.states = states.into_iter().collect();
self
}
#[must_use]
pub fn open(self) -> Self {
self.states(AgendaStateKind::ALL.into_iter().filter(|kind| kind.is_open()))
}
#[must_use]
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn matches(&self, item: &AgendaItem) -> bool {
self.partition.as_ref().is_none_or(|partition| *partition == item.partition)
&& (self.states.is_empty() || self.states.contains(&item.state.kind()))
}
}
pub const AGENDA_TOOL_NAME: &str = "kernel:agenda";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "camelCase", rename_all_fields = "camelCase")]
#[non_exhaustive]
pub enum ProposalOutcome {
Held {
item: AgendaItem,
},
AwaitingApproval {
item: AgendaItem,
request_id: String,
},
Scheduled {
item: AgendaItem,
pid: String,
},
Rejected {
reason: String,
},
}
impl ProposalOutcome {
pub fn item(&self) -> Option<&AgendaItem> {
match self {
Self::Held { item }
| Self::AwaitingApproval { item, .. }
| Self::Scheduled { item, .. } => Some(item),
Self::Rejected { .. } => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Route {
Hold,
Ask,
Schedule,
}
pub(crate) fn route(
approval: ProactiveApproval,
mode: PartitionMode,
origin: &AgendaOrigin,
) -> Route {
let follow = match mode {
PartitionMode::ReadOnly | PartitionMode::Plan => Route::Hold,
PartitionMode::Ask => Route::Ask,
PartitionMode::Auto if origin.needs_a_person() => Route::Ask,
PartitionMode::Auto => Route::Schedule,
};
match approval {
ProactiveApproval::FollowMode => follow,
ProactiveApproval::AlwaysAsk => Route::Ask,
ProactiveApproval::Never => Route::Hold,
}
}
#[derive(Clone)]
pub struct Agenda {
inner: Arc<AgendaInner>,
}
struct AgendaInner {
sup: Arc<Supervision>,
processes: ProcessTable,
approvals: Option<Arc<dyn ApprovalService>>,
audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
}
impl fmt::Debug for Agenda {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Agenda")
.field("policy", &self.inner.sup.proactivity)
.field("inbox", &self.inner.approvals.is_some())
.field("audiences", &self.inner.audiences.keys().collect::<Vec<_>>())
.finish_non_exhaustive()
}
}
#[derive(Clone, Default)]
pub struct AgendaHandle {
slot: Arc<std::sync::RwLock<std::sync::Weak<AgendaInner>>>,
}
impl fmt::Debug for AgendaHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AgendaHandle").field("bound", &self.get().is_some()).finish()
}
}
impl AgendaHandle {
pub fn new() -> Self {
Self::default()
}
pub fn get(&self) -> Option<Agenda> {
let slot = self.slot.read().unwrap_or_else(|e| e.into_inner());
slot.upgrade().map(|inner| Agenda { inner })
}
pub(crate) fn bind(&self, agenda: &Agenda) {
*self.slot.write().unwrap_or_else(|e| e.into_inner()) = Arc::downgrade(&agenda.inner);
}
}
pub fn item_session(item_id: &str) -> String {
format!("agenda-{item_id}")
}
pub(crate) const OPERATOR_GROUP: &str = "operator";
fn request_id(item_id: &str) -> String {
format!("agenda_{item_id}")
}
fn prompt(item: &AgendaItem) -> String {
let mut text = format!(
"Follow-up from the agenda (item {}): {}\n\nWhy: {}",
item.id, item.title, item.rationale
);
if let Some(plan) = &item.plan
&& !plan.steps.is_empty()
{
text.push_str("\n\nSteps:");
for (index, step) in plan.steps.iter().enumerate() {
let title = step.get("title").and_then(Value::as_str).unwrap_or_default();
let instruction = step.get("instruction").and_then(Value::as_str).unwrap_or_default();
text.push_str(&format!("\n{}. {title}: {instruction}", index + 1));
}
}
text
}
fn not_found(id: &str) -> KernelError {
KernelError::AgendaNotFound { item: id.to_string() }
}
const QUESTION_NOT_SCHEDULED: &str = "scheduled: an observation is a question, answered with \
`adk-rust agenda approve ID` (confirm) or `adk-rust agenda reject ID`, never scheduled";
const QUESTION_NOT_RUN: &str = "run: an observation is a question and never becomes a process";
const PARK_RECORDED_WITHIN: std::time::Duration = std::time::Duration::from_secs(5);
const PARK_RECORDED_POLL: std::time::Duration = std::time::Duration::from_millis(20);
fn needs_a_person(item: &AgendaItem, verb: &str) -> KernelError {
let why = match &item.origin {
AgendaOrigin::Observation { .. } => "is an observation's question".to_string(),
AgendaOrigin::Signal { kind, .. } => format!("is a {kind} signal (spec 3.5 §7.10)"),
other => format!("came from the {} tick", other.kind()),
};
KernelError::Unauthorized {
reason: format!(
"agenda item {} {why}, so only a person {verb} it (K-I23, spec 3.2 §7.10)",
item.id
),
}
}
fn wrong_state(item: &AgendaItem, action: &'static str) -> KernelError {
KernelError::AgendaState { item: item.id.clone(), state: item.state.kind(), action }
}
impl Agenda {
pub(crate) fn new(
sup: Arc<Supervision>,
processes: ProcessTable,
approvals: Option<Arc<dyn ApprovalService>>,
audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
) -> Self {
Self { inner: Arc::new(AgendaInner { sup, processes, approvals, audiences }) }
}
pub fn store(&self) -> &Arc<dyn AgendaStore> {
&self.inner.sup.agenda
}
pub fn policy(&self) -> &ProactivityPolicy {
&self.inner.sup.proactivity
}
pub async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
self.store().get(id).await
}
pub async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
self.store().list(filter).await
}
pub async fn propose(
&self,
mut item: AgendaItem,
mode: PartitionMode,
) -> Result<ProposalOutcome> {
if item.title.trim().is_empty() {
return Err(KernelError::Config { reason: "an agenda item needs a title".into() });
}
if item.state != AgendaState::Proposed {
return Err(KernelError::Config {
reason: format!("a new agenda item is proposed, not {}", item.state.kind()),
});
}
let sup = &self.inner.sup;
if let Some(reason) = self.refusal(&item).await? {
item.state = AgendaState::Rejected;
sup.agenda_changed(&item, &AgendaState::Proposed, Some(&reason), None).await;
tracing::info!(agenda.item = %item.id, reason = %reason, "proposal refused by the proactivity policy");
return Ok(ProposalOutcome::Rejected { reason });
}
sup.agenda.put(item.clone()).await?;
let by =
item.proposer().map(|pid| SubjectRef::new(SubjectKind::Agent, format!("run:{pid}")));
sup.agenda_changed(&item, &AgendaState::Proposed, Some("proposed"), by.as_ref()).await;
let mut route = route(sup.proactivity.approval, mode, &item.origin);
if route == Route::Ask && self.inner.approvals.is_none() {
route = Route::Hold;
}
match route {
Route::Hold => Ok(ProposalOutcome::Held { item }),
Route::Ask => {
let request_id = self.submit(&item).await?;
Ok(ProposalOutcome::AwaitingApproval { item, request_id })
}
Route::Schedule => {
let policy = SubjectRef::service("kernel:proactivity-policy");
let item = self
.approve_as(item, &policy, "admitted by the Auto partition's policy")
.await?;
let pid = match &item.state {
AgendaState::Scheduled { .. } => self.process_of(&item.id).await?,
_ => None,
};
match pid {
Some(pid) => Ok(ProposalOutcome::Scheduled { item, pid }),
None => Ok(ProposalOutcome::Held { item }),
}
}
}
}
#[cfg(feature = "proc-baselines")]
pub(crate) async fn offer(
&self,
observation: &crate::proc::Observation,
) -> Result<Option<ProposalOutcome>> {
let Some(audience) = self.inner.audiences.get(&observation.partition) else {
return Ok(None);
};
let Some((person, mode)) = audience.audience(&observation.partition).await? else {
return Ok(None);
};
let mode = self.inner.sup.area_mode(&observation.partition, mode).await;
if self.get(&observation.id).await?.is_some() {
return Ok(None);
}
let open_for = observation.windows.iter().copied().max().unwrap_or(14);
let item = AgendaItem::new(
observation.id.clone(),
person,
observation.question.clone(),
observation.statement(),
AgendaOrigin::Observation { id: observation.id.clone() },
observation.created_at,
)
.with_partition(observation.partition.clone())
.with_expiry(observation.created_at + chrono::Duration::days(i64::from(open_for)));
self.propose(item, mode).await.map(Some)
}
async fn refusal(&self, item: &AgendaItem) -> Result<Option<String>> {
let sup = &self.inner.sup;
let policy = &sup.proactivity;
let open = self
.store()
.list(&AgendaFilter::default().partition(item.partition.clone()).open())
.await?
.iter()
.filter(|open| !matches!(open.origin, AgendaOrigin::Signal { .. }))
.count();
if open >= policy.max_proposed_open {
return Ok(Some(format!(
"partition {} already has {open} open agenda items, the most max_proposed_open ({}) allows",
item.partition, policy.max_proposed_open
)));
}
if item.origin.is_question() {
return Ok(None);
}
let daily = &policy.daily_budget;
if let Some(cap) = daily.max_cost_micro_usd {
let need =
item.budget.as_ref().and_then(|budget| budget.max_cost_micro_usd).unwrap_or(0);
if need > cap {
return Ok(Some(format!(
"its budget of {need} micro-USD exceeds the daily proactive budget of {cap}"
)));
}
}
if daily.max_cost_micro_usd.is_none()
&& daily.max_model_calls.is_none()
&& daily.max_total_tokens.is_none()
{
return Ok(None);
}
let used = sup.proactive_usage(&item.partition).await;
let reached = [
(daily.max_cost_micro_usd, used.micro_usd, "micro-USD"),
(daily.max_model_calls, used.model_calls, "model calls"),
(daily.max_total_tokens, used.total_tokens, "tokens"),
]
.into_iter()
.find_map(|(cap, used, unit)| cap.filter(|cap| used >= *cap).map(|cap| (used, cap, unit)));
if let Some((used, cap, unit)) = reached {
return Ok(Some(format!(
"partition {} spent its daily proactive budget ({used} of {cap} {unit})",
item.partition
)));
}
Ok(None)
}
async fn submit(&self, item: &AgendaItem) -> Result<String> {
let Some(approvals) = &self.inner.approvals else {
return Err(KernelError::Config {
reason: "the kernel has no approval service".into(),
});
};
let sup = &self.inner.sup;
let session = match item.proposer() {
Some(pid) => match sup.runs.get(pid).await? {
Some(run) => crate::supervise::run_session(&run),
None => item_session(&item.id),
},
None => item_session(&item.id),
};
let scope = ApprovalScope::new(sup.app_name.clone(), item.subject.id.clone(), session);
let args = serde_json::to_value(item)?;
let call = ToolConfirmationRequest::new(AGENDA_TOOL_NAME, args.clone());
let policy = ApprovalPolicy::new([
ApproverSelector::human(item.subject.id.clone()),
ApproverSelector::group(OPERATOR_GROUP),
])
.allow_self_approval();
let id = request_id(&item.id);
let mut request = ApprovalRequest::new(id.clone(), scope, &call, policy)
.with_redacted_args(args)
.with_requester(item.subject.clone());
request = if item.origin.is_question() {
request
.with_summary(format!("Observation: {}", item.title))
.with_risk(ApprovalRisk::Low)
.with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject])
} else {
request
.with_summary(format!("Agenda follow-up: {}", item.title))
.with_risk(ApprovalRisk::Medium)
.with_allowed_actions([
ApprovalAction::Approve,
ApprovalAction::Edit,
ApprovalAction::Reject,
])
};
if let Some(at) = item.expires_at {
request = request.with_expires_at(at);
}
if let Some(pid) = item.proposer() {
request = request.with_run_id(pid.to_string());
}
approvals.submit(request).await?;
tracing::info!(agenda.item = %item.id, approval.id = %id, "agenda proposal put to the approval inbox");
Ok(id)
}
pub async fn approve(&self, id: &str, by: &SubjectRef) -> Result<AgendaItem> {
let item = self.get(id).await?.ok_or_else(|| not_found(id))?;
let approved = self.approve_as(item, by, "approved").await?;
self.withdraw(id, "approved through the agenda").await;
Ok(approved)
}
async fn approve_as(
&self,
item: AgendaItem,
by: &SubjectRef,
reason: &str,
) -> Result<AgendaItem> {
if item.state != AgendaState::Proposed {
return Err(wrong_state(&item, "approved"));
}
if item.origin.needs_a_person() && by.kind != SubjectKind::Human {
return Err(needs_a_person(&item, "approves"));
}
if item.origin.is_question() {
return self.answer(item, by, true, reason).await;
}
let from = item.state.clone();
let approved = item.with_state(AgendaState::Approved);
if !self.inner.sup.move_item(&approved, &from, Some(reason), Some(by)).await? {
let current = self.get(&approved.id).await?.ok_or_else(|| not_found(&approved.id))?;
return Err(wrong_state(¤t, "approved"));
}
Ok(self.start(approved, by).await)
}
async fn answer(
&self,
item: AgendaItem,
by: &SubjectRef,
confirmed: bool,
reason: &str,
) -> Result<AgendaItem> {
let sup = &self.inner.sup;
let mut answer = AgendaAnswer::new(confirmed, by.clone(), sup.clock.now());
let mut reason = if confirmed { "confirmed".to_string() } else { reason.to_string() };
if confirmed && let Some(audience) = self.inner.audiences.get(&item.partition) {
let fact = audience.confirm(&item, by).await?;
reason = format!("confirmed; remembered as known fact {fact}");
answer = answer.with_fact(fact);
}
let from = item.state.clone();
let mut closed =
item.with_state(if confirmed { AgendaState::Done } else { AgendaState::Rejected });
closed.answer = Some(answer);
if !sup.move_item(&closed, &from, Some(&reason), Some(by)).await? {
let current = self.get(&closed.id).await?.ok_or_else(|| not_found(&closed.id))?;
return Err(wrong_state(¤t, if confirmed { "confirmed" } else { "rejected" }));
}
Ok(closed)
}
async fn start(&self, item: AgendaItem, by: &SubjectRef) -> AgendaItem {
match self.spawn(&item, None).await {
Ok((pid, wake)) => {
let from = item.state.clone();
let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
match self
.inner
.sup
.move_item(&scheduled, &from, Some(&format!("process {pid}")), Some(by))
.await
{
Ok(true) => scheduled,
Ok(false) | Err(_) => self.get(&item.id).await.ok().flatten().unwrap_or(item),
}
}
Err(error) => {
tracing::warn!(agenda.item = %item.id, error = %error, "could not create the agenda item's process yet; the next tick retries");
item
}
}
}
async fn spawn(&self, item: &AgendaItem, wake: Option<WakeSet>) -> Result<(String, WakeSet)> {
if item.origin.is_question() {
return Err(wrong_state(item, QUESTION_NOT_RUN));
}
let sup = &self.inner.sup;
let now = sup.clock.now();
let asleep = wake.or_else(|| item.when.clone().map(|when| WakeSet::any_of([when])));
let asleep = match (asleep, item.expires_at) {
(Some(set), Some(at)) => Some(set.with_expiry(at, crate::wake::ExpiryAction::Cancel)),
(set, _) => set,
};
let release = sup.quiet_release(&item.partition, now).await;
let proposer = match item.proposer() {
Some(pid) => sup.runs.get(pid).await?,
None => None,
};
let target = match &proposer {
Some(run) => run.target.clone(),
None => {
let own: Vec<&String> = sup
.targets
.statics()
.iter()
.filter(|(_, bound)| **bound == item.partition)
.map(|(target, _)| target)
.collect();
match own.first() {
Some(first) if !own.contains(&&sup.app_name) => (*first).clone(),
_ => sup.app_name.clone(),
}
}
};
let mut run = NewRun::new(
QueueClass::BACKGROUND,
sup.app_name.clone(),
item.subject.id.clone(),
target,
Value::String(prompt(item)),
);
run.session_id = Some(item_session(&item.id));
run.idempotency_key = Some(format!("agenda:{}", item.id));
if asleep.is_none() && release > now {
run.not_before = Some(release);
}
if let Some(proposer) = &proposer {
run.principal = proposer.principal.clone();
run.authenticated = proposer.authenticated;
}
let mut spec = ProcessSpec::new(ProcessKind::Proposed)
.with_partition(item.partition.clone())
.with_agenda_item(item.id.clone());
if let Some(set) = &asleep {
spec = spec.with_wake(set.clone());
}
if let Some(pid) = item.proposer() {
spec = spec.with_parent(pid);
}
let process = self.inner.processes.spawn(run, spec).await?;
let scheduled = asleep.unwrap_or_else(|| WakeSet::any_of([Wake::At(release)]));
Ok((process.meta.pid, scheduled))
}
async fn process_of(&self, id: &str) -> Result<Option<String>> {
let item = self.get(id).await?;
let filter = crate::ProcessFilter::default();
let filter = match &item {
Some(item) => filter.partition(item.partition.clone()),
None => filter,
};
Ok(self
.inner
.sup
.processes
.list(&filter)
.await?
.into_iter()
.find(|meta| {
meta.agenda_item.as_deref() == Some(id) && meta.kind == ProcessKind::Proposed
})
.map(|meta| meta.pid))
}
pub async fn reject(
&self,
id: &str,
by: &SubjectRef,
reason: Option<&str>,
) -> Result<AgendaItem> {
let item = self.get(id).await?.ok_or_else(|| not_found(id))?;
let rejected = self.reject_as(item, by, reason.unwrap_or("rejected")).await?;
self.withdraw(id, "rejected through the agenda").await;
Ok(rejected)
}
async fn reject_as(
&self,
item: AgendaItem,
by: &SubjectRef,
reason: &str,
) -> Result<AgendaItem> {
if !matches!(item.state, AgendaState::Proposed | AgendaState::Approved) {
return Err(wrong_state(&item, "rejected"));
}
if item.origin.is_question() {
return self.answer(item, by, false, reason).await;
}
let from = item.state.clone();
let rejected = item.with_state(AgendaState::Rejected);
if !self.inner.sup.move_item(&rejected, &from, Some(reason), Some(by)).await? {
let current = self.get(&rejected.id).await?.ok_or_else(|| not_found(&rejected.id))?;
return Err(wrong_state(¤t, "rejected"));
}
Ok(rejected)
}
pub async fn schedule(&self, id: &str, wake: WakeSet, by: &SubjectRef) -> Result<AgendaItem> {
let mut item = self.get(id).await?.ok_or_else(|| not_found(id))?;
let sup = &self.inner.sup;
if item.origin.is_question() {
return Err(wrong_state(&item, QUESTION_NOT_SCHEDULED));
}
if item.state == AgendaState::Proposed {
if item.origin.needs_a_person() && by.kind != SubjectKind::Human {
return Err(needs_a_person(&item, "schedules"));
}
let approved = item.clone().with_state(AgendaState::Approved);
if !sup
.move_item(&approved, &item.state, Some("approved to schedule"), Some(by))
.await?
{
return Err(wrong_state(&item, "scheduled"));
}
self.withdraw(id, "scheduled through the agenda").await;
item = approved;
}
match &item.state {
AgendaState::Approved => {
let (pid, wake) = self.spawn(&item, Some(wake)).await?;
let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
if !sup
.move_item(&scheduled, &item.state, Some(&format!("process {pid}")), Some(by))
.await?
{
return Err(wrong_state(&item, "scheduled"));
}
Ok(scheduled)
}
AgendaState::Scheduled { .. } => {
let pid =
self.process_of(id).await?.ok_or_else(|| wrong_state(&item, "rescheduled"))?;
let state = sup.runs.get(&pid).await?.map(|run| run.state);
let parking = state == Some(RunState::Running)
&& sup.processes.get(&pid).await?.is_some_and(|meta| meta.wake.is_some());
if !parking && !matches!(state, Some(RunState::Waiting | RunState::Queued)) {
return Err(wrong_state(&item, "rescheduled (its process already started)"));
}
let wake = match item.expires_at {
Some(at) => wake.with_expiry(at, crate::wake::ExpiryAction::Cancel),
None => wake,
};
sup.processes.set_wake(&pid, Some(wake.clone())).await?;
if state == Some(RunState::Queued) {
sup.processes.set_suspend_requested(&pid, true).await?;
} else {
self.keep_wake_through_park(&pid, &wake).await?;
}
sup.roots_changed.notify_one();
let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
if !sup.move_item(&scheduled, &item.state, Some("rescheduled"), Some(by)).await? {
return Err(wrong_state(&item, "rescheduled"));
}
Ok(scheduled)
}
_ => Err(wrong_state(&item, "scheduled")),
}
}
async fn withdraw(&self, id: &str, note: &str) {
let Some(approvals) = &self.inner.approvals else { return };
if let Ok(Some(request)) = approvals.get(&request_id(id)).await
&& request.state == ApprovalState::Pending
&& let Err(error) = approvals.cancel(&request.id, Some(note.to_string())).await
{
tracing::debug!(approval.id = %request.id, error = %error, "could not withdraw an agenda request");
}
}
async fn keep_wake_through_park(&self, pid: &str, wake: &WakeSet) -> Result<()> {
let sup = &self.inner.sup;
if sup.runs.get(pid).await?.is_none_or(|run| run.state != RunState::Waiting) {
return Ok(());
}
let deadline = tokio::time::Instant::now() + PARK_RECORDED_WITHIN;
loop {
let Some(meta) = sup.processes.get(pid).await? else { return Ok(()) };
if !meta.suspend_requested || tokio::time::Instant::now() >= deadline {
if meta.wake.as_ref() != Some(wake) {
sup.processes.set_wake(pid, Some(wake.clone())).await?;
}
return Ok(());
}
tokio::time::sleep(PARK_RECORDED_POLL).await;
}
}
pub(crate) async fn tick(&self) {
if let Err(error) = self.tick_inner().await {
tracing::debug!(error = %error, "agenda tick failed");
}
}
async fn tick_inner(&self) -> Result<()> {
let sup = &self.inner.sup;
let now = sup.clock.now();
for item in self.store().list(&AgendaFilter::default().open()).await? {
match &item.state {
AgendaState::Proposed => {
if item.expires_at.is_some_and(|at| at <= now) {
self.expire(item).await?;
continue;
}
self.apply_decision(item).await?;
}
AgendaState::Approved => {
if item.expires_at.is_some_and(|at| at <= now) {
self.expire(item).await?;
} else if !item.origin.is_question() {
let by = SubjectRef::service("kernel");
self.start(item, &by).await;
}
}
AgendaState::Scheduled { .. } | AgendaState::Running { .. } => {
let Some(pid) = self.process_of(&item.id).await? else { continue };
let Some(run) = sup.runs.get(&pid).await? else { continue };
if !run.state.is_terminal() {
if run.state == RunState::Queued
&& matches!(item.state, AgendaState::Scheduled { .. })
&& item.expires_at.is_some_and(|at| at <= now)
{
self.inner.processes.kill(&pid, "its agenda item expired").await?;
}
continue;
}
let from = item.state.clone();
let never_ran = matches!(from, AgendaState::Scheduled { .. })
&& run.state == RunState::Cancelled
&& item.expires_at.is_some_and(|at| at <= now);
let next = item.with_state(if never_ran {
AgendaState::Expired
} else {
AgendaState::Done
});
let reason = format!("process {pid} ended");
sup.move_item(&next, &from, Some(&reason), None).await?;
}
_ => {}
}
}
Ok(())
}
async fn expire(&self, item: AgendaItem) -> Result<()> {
let from = item.state.clone();
let id = item.id.clone();
let expired = item.with_state(AgendaState::Expired);
if self.inner.sup.move_item(&expired, &from, Some("expired before it ran"), None).await? {
self.withdraw(&id, "the agenda item expired").await;
}
Ok(())
}
async fn apply_decision(&self, item: AgendaItem) -> Result<()> {
let Some(approvals) = &self.inner.approvals else { return Ok(()) };
let Some(request) = approvals.get(&request_id(&item.id)).await? else { return Ok(()) };
let last = request.decisions.last();
let by =
last.map_or_else(|| SubjectRef::service("kernel:approvals"), |d| d.approver.clone());
match request.state {
ApprovalState::Pending => Ok(()),
ApprovalState::Approved => {
let mut item = item;
if let Some(edited) = last
.filter(|d| d.kind == ApprovalAction::Edit)
.and_then(|d| d.edited_args.as_ref())
{
let from = item.state.clone();
let edited_item = edit(item.clone(), edited);
if edited_item != item
&& self
.inner
.sup
.move_item(&edited_item, &from, Some("edited in the inbox"), Some(&by))
.await?
{
item = edited_item;
}
}
match self.approve_as(item.clone(), &by, "approved in the inbox").await {
Ok(_) => Ok(()),
Err(KernelError::Unauthorized { reason }) => {
tracing::warn!(agenda.item = %item.id, reason = %reason, "an inbox approval by someone other than a person was ignored");
Ok(())
}
Err(KernelError::AgendaState { .. }) => Ok(()),
Err(error) if item.origin.is_question() => {
tracing::warn!(agenda.item = %item.id, error = %error, "could not record a confirmed observation yet; the next tick retries");
Ok(())
}
Err(error) => Err(error),
}
}
ApprovalState::Rejected | ApprovalState::Responded => {
let reason = last
.and_then(|d| d.reason.clone())
.unwrap_or_else(|| "rejected in the inbox".into());
match self.reject_as(item, &by, &reason).await {
Ok(_) | Err(KernelError::AgendaState { .. }) => Ok(()),
Err(error) => Err(error),
}
}
ApprovalState::Expired => self.expire(item).await,
ApprovalState::Cancelled => {
let note = request.note.unwrap_or_else(|| "the inbox request was withdrawn".into());
match self.reject_as(item, &by, ¬e).await {
Ok(_) | Err(KernelError::AgendaState { .. }) => Ok(()),
Err(error) => Err(error),
}
}
}
}
}
fn edit(mut item: AgendaItem, edited: &Value) -> AgendaItem {
if let Some(title) =
edited.get("title").and_then(Value::as_str).filter(|t| !t.trim().is_empty())
{
item.title = title.to_string();
}
if let Some(rationale) = edited.get("rationale").and_then(Value::as_str) {
item.rationale = rationale.to_string();
}
if let Some(when) = edited.get("when") {
item.when = serde_json::from_value(when.clone()).ok();
}
if let Some(expires) = edited.get("expiresAt") {
item.expires_at = serde_json::from_value(expires.clone()).ok();
}
item
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use serde_json::json;
use super::*;
const MODES: [PartitionMode; 4] =
[PartitionMode::ReadOnly, PartitionMode::Plan, PartitionMode::Ask, PartitionMode::Auto];
#[test]
fn follow_mode_holds_asks_or_schedules_by_the_partitions_mode() {
let agent = AgendaOrigin::Agent { pid: "run-1".into(), confidence: 1.0 };
let routes: Vec<Route> =
MODES.iter().map(|mode| route(ProactiveApproval::FollowMode, *mode, &agent)).collect();
assert_eq!(routes, [Route::Hold, Route::Hold, Route::Ask, Route::Schedule]);
for mode in MODES {
assert_eq!(route(ProactiveApproval::AlwaysAsk, mode, &agent), Route::Ask);
assert_eq!(route(ProactiveApproval::Never, mode, &agent), Route::Hold);
}
}
#[test]
fn consolidation_and_observation_items_never_schedule_without_a_person() {
for origin in
[AgendaOrigin::Consolidation, AgendaOrigin::Observation { id: "obs-1".into() }]
{
let routes: Vec<Route> = MODES
.iter()
.map(|mode| route(ProactiveApproval::FollowMode, *mode, &origin))
.collect();
assert_eq!(
routes,
[Route::Hold, Route::Hold, Route::Ask, Route::Ask],
"Auto asks too (K-I23, spec 3.2 §7.10): {origin}"
);
}
}
fn origin() -> impl Strategy<Value = AgendaOrigin> {
prop_oneof![
Just(AgendaOrigin::User),
Just(AgendaOrigin::Consolidation),
(0.0f32..=1.0)
.prop_map(|confidence| AgendaOrigin::Agent { pid: "run-1".into(), confidence }),
Just(AgendaOrigin::Observation { id: "obs-1".into() }),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn only_auto_follow_mode_schedules_and_never_consolidation_or_a_question(
mode in prop::sample::select(MODES.to_vec()),
approval in prop::sample::select(vec![ProactiveApproval::FollowMode, ProactiveApproval::AlwaysAsk, ProactiveApproval::Never]),
origin in origin(),
) {
let routed = route(approval, mode, &origin);
if routed == Route::Schedule {
prop_assert_eq!(mode, PartitionMode::Auto);
prop_assert_eq!(approval, ProactiveApproval::FollowMode);
prop_assert!(!origin.needs_a_person());
prop_assert!(!origin.is_question());
}
}
}
#[test]
fn an_inbox_edit_changes_only_title_rationale_when_and_expiry() {
let item = AgendaItem::new(
"item-1",
SubjectRef::human("alice"),
"Old",
"Because",
AgendaOrigin::Consolidation,
Utc::now(),
);
let edited = edit(
item.clone(),
&json!({
"title": "New",
"rationale": "Better reason",
"when": { "at": "2026-10-24T07:00:00Z" },
"origin": "user",
"partition": "home",
"subject": { "kind": "human", "id": "mallory" },
"budget": { "maxCostMicroUsd": 1 }
}),
);
assert_eq!((edited.title.as_str(), edited.rationale.as_str()), ("New", "Better reason"));
assert!(matches!(edited.when, Some(Wake::At(_))));
assert_eq!(edited.origin, item.origin, "an edit cannot launder the origin (K-I23)");
assert_eq!(
edit(item.clone(), &json!({ "title": " " })).title,
"Old",
"a blank title is kept"
);
assert_eq!(
(edited.partition, edited.subject, edited.budget),
(item.partition, item.subject, item.budget)
);
}
#[test]
fn the_prompt_names_the_item_and_its_steps() {
let item = AgendaItem::new(
"item-9",
SubjectRef::human("alice"),
"Re-run the tests",
"The bump landed",
AgendaOrigin::User,
Utc::now(),
)
.with_plan(PlanRef::new(
"sha256:1",
vec![json!({"id": "1", "title": "Test", "instruction": "cargo test"})],
));
let text = prompt(&item);
assert!(
text.contains("item item-9")
&& text.contains("Re-run the tests")
&& text.contains("1. Test: cargo test"),
"{text}"
);
assert_eq!(request_id("item-9"), "agenda_item-9");
}
}