Skip to main content

adk_kernel/
agenda.rs

1//! The agenda: proactivity under control (spec 3.2 §7.5).
2//!
3//! The agenda is the kernel-scope todo list: [`AgendaItem`]s that outlive a session and may
4//! become processes. Proposing is free; running is governed. An item starts `Proposed`
5//! and runs only once it is `Approved` — by a person, or by an Auto partition's policy
6//! (K-I10) — and then only outside quiet hours and within the partition's daily budget
7//! (K-I11). An item of [`AgendaOrigin::Consolidation`] needs a person's approval in every
8//! mode, Auto included (K-I23).
9//!
10//! An item of [`AgendaOrigin::Observation`] is a question, answered and never scheduled
11//! (spec 3.2 §7.10): it needs a person in every mode, becomes no process, and closes with
12//! the person's [`AgendaAnswer`]. Confirmed, it is `Done` and the partition's
13//! [`ObservationAudience`] records its statement as a `Known` fact; rejected or withdrawn,
14//! it is `Rejected` and nothing is recorded.
15//!
16//! | State | Meaning |
17//! |---|---|
18//! | [`Proposed`](AgendaState::Proposed) | Waiting for approval, or held by a ReadOnly or Plan partition |
19//! | [`Approved`](AgendaState::Approved) | Approved; the kernel schedules it next |
20//! | [`Scheduled`](AgendaState::Scheduled) | A sleeping process waits on its wake set |
21//! | [`Running`](AgendaState::Running) | Its process runs |
22//! | [`Done`](AgendaState::Done), [`Rejected`](AgendaState::Rejected), [`Expired`](AgendaState::Expired) | Finished |
23//!
24//! Items live in an [`AgendaStore`] on every backend the [`ProcessStore`](crate::ProcessStore)
25//! has: in-memory, SQLite, PostgreSQL and Redis.
26
27use std::collections::BTreeMap;
28use std::fmt;
29use std::sync::Arc;
30
31use adk_core::principal::{SubjectKind, SubjectRef};
32use adk_core::{
33    ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApprovalService,
34    ApprovalState, ApproverSelector, NewRun, RunBudget, RunState, ToolConfirmationRequest,
35};
36use async_trait::async_trait;
37use chrono::{DateTime, Utc};
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40
41use crate::consolidation::ConsolidationTick;
42use crate::error::{KernelError, Result};
43use crate::partition::{PartitionId, PartitionMode};
44use crate::process::{ProcessKind, ProcessSpec, ProcessTable};
45use crate::sched::{QueueClass, QuietHours};
46use crate::supervise::Supervision;
47use crate::wake::{Wake, WakeSet};
48
49/// One item of the agenda (spec 3.2 §7.5).
50///
51/// `when` holds the wake the proposer asked for until the item is scheduled; an item with
52/// none runs as soon as it is admitted.
53///
54/// # Example
55///
56/// ```rust
57/// use adk_core::principal::SubjectRef;
58/// use adk_kernel::{AgendaItem, AgendaOrigin, AgendaState};
59///
60/// let item = AgendaItem::new(
61///     "item-1",
62///     SubjectRef::human("alice"),
63///     "Re-run the tests",
64///     "The dependency bump lands tonight",
65///     AgendaOrigin::Agent { pid: "run-7".into(), confidence: 1.0 },
66///     chrono::Utc::now(),
67/// )
68/// .with_partition("work");
69/// assert_eq!(item.state, AgendaState::Proposed);
70/// let json = serde_json::to_value(&item).unwrap();
71/// assert_eq!(json["origin"]["agent"]["pid"], "run-7");
72/// assert_eq!(json["state"], "proposed");
73/// ```
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76#[non_exhaustive]
77pub struct AgendaItem {
78    /// The item id.
79    pub id: String,
80    /// The partition the item belongs to.
81    #[serde(default)]
82    pub partition: PartitionId,
83    /// Whom the item works for: the user its process runs as.
84    pub subject: SubjectRef,
85    /// A short title.
86    pub title: String,
87    /// Why the work is worth doing.
88    pub rationale: String,
89    /// Who proposed it.
90    pub origin: AgendaOrigin,
91    /// Where it stands.
92    pub state: AgendaState,
93    /// The plan steps, when the proposer produced some (spec 3.1 §7.11).
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub plan: Option<PlanRef>,
96    /// The budget of the item's process (`adk-core/src/budget.rs`); its cost cap is what
97    /// admission reserves against the daily budget.
98    #[serde(
99        default,
100        skip_serializing_if = "Option::is_none",
101        with = "crate::serde_util::option_run_budget"
102    )]
103    pub budget: Option<RunBudget>,
104    /// When the item was proposed.
105    pub created_at: DateTime<Utc>,
106    /// When an item not yet running expires; `None` never.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub expires_at: Option<DateTime<Utc>>,
109    /// The wake the proposer asked for (`propose_followup`'s `when`), kept until the item
110    /// is scheduled.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub when: Option<Wake>,
113    /// A person's answer to a question item ([`AgendaOrigin::is_question`]), once given.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub answer: Option<AgendaAnswer>,
116}
117
118impl AgendaItem {
119    /// A `Proposed` item in the default partition with no plan, budget, expiry or wake.
120    pub fn new(
121        id: impl Into<String>,
122        subject: SubjectRef,
123        title: impl Into<String>,
124        rationale: impl Into<String>,
125        origin: AgendaOrigin,
126        created_at: DateTime<Utc>,
127    ) -> Self {
128        Self {
129            id: id.into(),
130            partition: PartitionId::default(),
131            subject,
132            title: title.into(),
133            rationale: rationale.into(),
134            origin,
135            state: AgendaState::Proposed,
136            plan: None,
137            budget: None,
138            created_at,
139            expires_at: None,
140            when: None,
141            answer: None,
142        }
143    }
144
145    /// Sets the partition.
146    #[must_use]
147    pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
148        self.partition = partition.into();
149        self
150    }
151
152    /// Sets the state.
153    #[must_use]
154    pub fn with_state(mut self, state: AgendaState) -> Self {
155        self.state = state;
156        self
157    }
158
159    /// Sets the plan.
160    #[must_use]
161    pub fn with_plan(mut self, plan: PlanRef) -> Self {
162        self.plan = Some(plan);
163        self
164    }
165
166    /// Sets the budget.
167    #[must_use]
168    pub fn with_budget(mut self, budget: RunBudget) -> Self {
169        self.budget = Some(budget);
170        self
171    }
172
173    /// Sets the expiry.
174    #[must_use]
175    pub fn with_expiry(mut self, at: DateTime<Utc>) -> Self {
176        self.expires_at = Some(at);
177        self
178    }
179
180    /// Sets the wake the proposer asked for.
181    #[must_use]
182    pub fn with_when(mut self, when: Wake) -> Self {
183        self.when = Some(when);
184        self
185    }
186
187    /// The run that proposed the item, for an agent's proposal.
188    pub fn proposer(&self) -> Option<&str> {
189        match &self.origin {
190            AgendaOrigin::Agent { pid, .. } => Some(pid),
191            AgendaOrigin::User
192            | AgendaOrigin::Consolidation
193            | AgendaOrigin::Observation { .. }
194            | AgendaOrigin::Signal { .. } => None,
195        }
196    }
197}
198
199/// Who proposed an [`AgendaItem`] (spec 3.2 §7.5).
200///
201/// # Example
202///
203/// ```rust
204/// use adk_kernel::AgendaOrigin;
205///
206/// assert_eq!(serde_json::to_value(AgendaOrigin::Consolidation).unwrap(), "consolidation");
207/// assert_eq!(AgendaOrigin::Agent { pid: "run-1".into(), confidence: 0.8 }.to_string(), "agent:run-1");
208/// assert!(AgendaOrigin::Consolidation.needs_a_person());
209/// assert!(!AgendaOrigin::User.needs_a_person());
210/// let observation = AgendaOrigin::Observation { id: "obs-20261022-1a2b3c4d".into() };
211/// assert!(observation.needs_a_person() && observation.is_question());
212/// assert!(!AgendaOrigin::Consolidation.is_question());
213/// ```
214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
215#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
216#[non_exhaustive]
217pub enum AgendaOrigin {
218    /// A person added it.
219    User,
220    /// An agent proposed it with `propose_followup`.
221    Agent {
222        /// The proposing run; the item's process is its child.
223        pid: String,
224        /// How sure the proposer is the work is wanted, 0 to 1.
225        confidence: f32,
226    },
227    /// The consolidation tick proposed it; it runs only after a person approves it, in
228    /// every mode (K-I23).
229    Consolidation,
230    /// A `/proc` observation proposed it (spec 3.2 §7.10): a question a person answers in
231    /// every mode, never scheduled.
232    Observation {
233        /// The observation.
234        id: String,
235    },
236    /// A typed signal from the public partition (spec 3.5 §7.10, §10 X10): the kernel's
237    /// `SignalSink` (feature `charter`) files it in the back office's agenda, and a repeat of
238    /// its kind and topic raises `count` instead of adding an item. Only a person turns one
239    /// into work.
240    Signal {
241        /// The signal's kind, such as `content_gap`.
242        kind: String,
243        /// How many signals of this kind and topic the item stands for.
244        count: u32,
245    },
246}
247
248impl AgendaOrigin {
249    /// Whether only a person may approve items of this origin, whatever the partition's
250    /// mode and policy: true for [`Consolidation`](Self::Consolidation) (K-I23),
251    /// [`Observation`](Self::Observation) (spec 3.2 §7.10) and [`Signal`](Self::Signal)
252    /// (spec 3.5 §7.10).
253    pub fn needs_a_person(&self) -> bool {
254        matches!(self, Self::Consolidation | Self::Observation { .. } | Self::Signal { .. })
255    }
256
257    /// Whether items of this origin are questions a person answers rather than work the
258    /// kernel schedules: true for [`Observation`](Self::Observation) (spec 3.2 §7.10). Such
259    /// an item never becomes a process; approving it confirms it.
260    pub fn is_question(&self) -> bool {
261        matches!(self, Self::Observation { .. })
262    }
263
264    /// The origin's name: `user`, `agent`, `consolidation`, `observation` or `signal`.
265    pub fn kind(&self) -> &'static str {
266        match self {
267            Self::User => "user",
268            Self::Agent { .. } => "agent",
269            Self::Consolidation => "consolidation",
270            Self::Observation { .. } => "observation",
271            Self::Signal { .. } => "signal",
272        }
273    }
274}
275
276impl fmt::Display for AgendaOrigin {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        match self {
279            Self::Agent { pid, .. } => write!(f, "agent:{pid}"),
280            Self::Observation { id } => write!(f, "observation:{id}"),
281            Self::Signal { kind, .. } => write!(f, "signal:{kind}"),
282            Self::User | Self::Consolidation => f.write_str(self.kind()),
283        }
284    }
285}
286
287/// A person's answer to a question item ([`AgendaOrigin::is_question`]), recorded on the
288/// item when it closes (spec 3.2 §7.10).
289///
290/// # Example
291///
292/// ```rust
293/// use adk_core::principal::SubjectRef;
294/// use adk_kernel::AgendaAnswer;
295///
296/// let answer = AgendaAnswer::new(true, SubjectRef::human("alice"), chrono::Utc::now())
297///     .with_fact("fact-1");
298/// let json = serde_json::to_value(&answer).unwrap();
299/// assert_eq!((json["confirmed"].as_bool(), json["fact"].as_str()), (Some(true), Some("fact-1")));
300/// ```
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase")]
303#[non_exhaustive]
304pub struct AgendaAnswer {
305    /// Whether the person confirmed it; `false` for a rejection or a withdrawn request.
306    pub confirmed: bool,
307    /// Who answered.
308    pub by: SubjectRef,
309    /// When.
310    pub at: DateTime<Utc>,
311    /// The `Known` fact the confirmation recorded, when the partition has an
312    /// [`ObservationAudience`].
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub fact: Option<String>,
315}
316
317impl AgendaAnswer {
318    /// An answer by `by` at `at` that recorded no fact.
319    pub fn new(confirmed: bool, by: SubjectRef, at: DateTime<Utc>) -> Self {
320        Self { confirmed, by, at, fact: None }
321    }
322
323    /// Sets the fact the confirmation recorded.
324    #[must_use]
325    pub fn with_fact(mut self, fact: impl Into<String>) -> Self {
326        self.fact = Some(fact.into());
327        self
328    }
329}
330
331/// Whom a partition's observations are put to, and where a confirmed one is remembered
332/// (spec 3.2 §7.10, spec 3.1 §7.15): the kernel reads no harness type, so the harness
333/// implements this over its long-term memory (`adk_harness::Harness::observation_audience`)
334/// and registers it with
335/// [`KernelBuilder::observation_audience`](crate::KernelBuilder::observation_audience).
336///
337/// The daily baseline pass (feature `proc-baselines`) files each observation of a
338/// partition with an audience as an [`AgendaOrigin::Observation`] item: titled with the
339/// question, its rationale the factual statement the person confirms. A partition without
340/// one keeps its observations at `/api/kernel/proc/observations` and puts no question to
341/// anyone.
342///
343/// # Example
344///
345/// ```rust
346/// use adk_core::principal::SubjectRef;
347/// use adk_kernel::{AgendaItem, ObservationAudience, PartitionId, PartitionMode};
348///
349/// struct Alice;
350///
351/// #[async_trait::async_trait]
352/// impl ObservationAudience for Alice {
353///     async fn audience(&self, _: &PartitionId) -> adk_kernel::Result<Option<(SubjectRef, PartitionMode)>> {
354///         Ok(Some((SubjectRef::human("alice"), PartitionMode::Ask)))
355///     }
356///     async fn confirm(&self, item: &AgendaItem, _by: &SubjectRef) -> adk_kernel::Result<String> {
357///         Ok(format!("fact-for-{}", item.id))
358///     }
359/// }
360/// ```
361#[async_trait]
362pub trait ObservationAudience: Send + Sync {
363    /// The person `partition`'s observations are put to and the partition's mode now;
364    /// `None` puts them to nobody.
365    ///
366    /// # Errors
367    ///
368    /// Returns the error that kept the audience from answering; the observation stays
369    /// recorded and no item is filed.
370    async fn audience(
371        &self,
372        partition: &PartitionId,
373    ) -> Result<Option<(SubjectRef, PartitionMode)>>;
374
375    /// Records that the person `by` confirmed `item`: its rationale, the observation's
376    /// statement, becomes a `Known` fact of `item.subject` with the person as its source.
377    /// Returns the fact's id.
378    ///
379    /// # Errors
380    ///
381    /// Returns the error that kept the fact from being recorded; the item stays `Proposed`.
382    async fn confirm(&self, item: &AgendaItem, by: &SubjectRef) -> Result<String>;
383}
384
385/// Where an [`AgendaItem`] stands (spec 3.2 §7.5).
386///
387/// # Example
388///
389/// ```rust
390/// use adk_kernel::{AgendaState, AgendaStateKind, Wake, WakeSet};
391///
392/// let scheduled = AgendaState::Scheduled { wake: WakeSet::any_of([Wake::Manual]) };
393/// assert_eq!(scheduled.kind(), AgendaStateKind::Scheduled);
394/// assert!(scheduled.kind().is_open());
395/// assert!(!AgendaState::Done.kind().is_open());
396/// assert_eq!(serde_json::to_value(AgendaState::Running { pid: "run-2".into() }).unwrap()["running"]["pid"], "run-2");
397/// ```
398#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
399#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
400#[non_exhaustive]
401pub enum AgendaState {
402    /// Waiting for approval.
403    Proposed,
404    /// Approved and not scheduled yet.
405    Approved,
406    /// Its process sleeps on `wake`.
407    Scheduled {
408        /// The wake set of the item's process.
409        wake: WakeSet,
410    },
411    /// Its process runs.
412    Running {
413        /// The item's process.
414        pid: String,
415    },
416    /// Its process finished.
417    Done,
418    /// A person or the policy rejected it.
419    Rejected,
420    /// It expired before it ran.
421    Expired,
422}
423
424impl AgendaState {
425    /// The state's kind, without its payload.
426    pub fn kind(&self) -> AgendaStateKind {
427        match self {
428            Self::Proposed => AgendaStateKind::Proposed,
429            Self::Approved => AgendaStateKind::Approved,
430            Self::Scheduled { .. } => AgendaStateKind::Scheduled,
431            Self::Running { .. } => AgendaStateKind::Running,
432            Self::Done => AgendaStateKind::Done,
433            Self::Rejected => AgendaStateKind::Rejected,
434            Self::Expired => AgendaStateKind::Expired,
435        }
436    }
437}
438
439impl fmt::Display for AgendaState {
440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441        match self {
442            Self::Running { pid } => write!(f, "running:{pid}"),
443            other => f.write_str(other.kind().as_str()),
444        }
445    }
446}
447
448/// The kind of an [`AgendaState`], without its payload: what an [`AgendaFilter`] selects
449/// and an [`AgendaStore::transition`] compares (spec 3.2 §7.5).
450///
451/// # Example
452///
453/// ```rust
454/// use adk_kernel::AgendaStateKind;
455///
456/// assert_eq!("scheduled".parse::<AgendaStateKind>().unwrap(), AgendaStateKind::Scheduled);
457/// assert_eq!(serde_json::to_value(AgendaStateKind::Proposed).unwrap(), "proposed");
458/// ```
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461#[non_exhaustive]
462pub enum AgendaStateKind {
463    /// [`AgendaState::Proposed`].
464    Proposed,
465    /// [`AgendaState::Approved`].
466    Approved,
467    /// [`AgendaState::Scheduled`].
468    Scheduled,
469    /// [`AgendaState::Running`].
470    Running,
471    /// [`AgendaState::Done`].
472    Done,
473    /// [`AgendaState::Rejected`].
474    Rejected,
475    /// [`AgendaState::Expired`].
476    Expired,
477}
478
479impl AgendaStateKind {
480    /// Every kind, in lifecycle order.
481    pub const ALL: [Self; 7] = [
482        Self::Proposed,
483        Self::Approved,
484        Self::Scheduled,
485        Self::Running,
486        Self::Done,
487        Self::Rejected,
488        Self::Expired,
489    ];
490
491    /// The kind's name.
492    pub fn as_str(self) -> &'static str {
493        match self {
494            Self::Proposed => "proposed",
495            Self::Approved => "approved",
496            Self::Scheduled => "scheduled",
497            Self::Running => "running",
498            Self::Done => "done",
499            Self::Rejected => "rejected",
500            Self::Expired => "expired",
501        }
502    }
503
504    /// Whether an item of this kind is open: not done, rejected or expired. Open items
505    /// count against [`ProactivityPolicy::max_proposed_open`].
506    pub fn is_open(self) -> bool {
507        matches!(self, Self::Proposed | Self::Approved | Self::Scheduled | Self::Running)
508    }
509}
510
511impl fmt::Display for AgendaStateKind {
512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
513        f.write_str(self.as_str())
514    }
515}
516
517impl std::str::FromStr for AgendaStateKind {
518    type Err = crate::KernelError;
519
520    fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
521        let text = text.trim().to_ascii_lowercase();
522        Self::ALL.into_iter().find(|kind| kind.as_str() == text).ok_or_else(|| {
523            crate::KernelError::Config {
524                reason: format!(
525                    "unknown agenda state `{text}`; use proposed, approved, scheduled, running, done, rejected or expired"
526                ),
527            }
528        })
529    }
530}
531
532/// The plan an agent proposed with its follow-up (spec 3.2 §7.5, spec 3.1 §7.11): the
533/// steps as the harness writes them, each a spec 3.1 `PlanStep` in JSON, and their digest.
534/// The kernel stores them without reading them (§6 D-1).
535///
536/// # Example
537///
538/// ```rust
539/// use adk_kernel::PlanRef;
540///
541/// let plan = PlanRef::new("sha256:ab12", vec![serde_json::json!({"id": "1", "title": "Run the tests", "instruction": "cargo test"})]);
542/// assert_eq!(plan.steps.len(), 1);
543/// ```
544#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
545#[serde(rename_all = "camelCase")]
546#[non_exhaustive]
547pub struct PlanRef {
548    /// The digest of the steps, as the harness computes a plan's hash.
549    pub plan_hash: String,
550    /// The steps.
551    pub steps: Vec<Value>,
552}
553
554impl PlanRef {
555    /// A plan of `steps` with digest `plan_hash`.
556    pub fn new(plan_hash: impl Into<String>, steps: Vec<Value>) -> Self {
557        Self { plan_hash: plan_hash.into(), steps }
558    }
559}
560
561/// How agenda proposals are approved (spec 3.2 §7.5).
562///
563/// | Value | ReadOnly, Plan | Ask | Auto |
564/// |---|---|---|---|
565/// | [`FollowMode`](Self::FollowMode) (default) | Stays `Proposed` | An inbox approval | Scheduled |
566/// | [`AlwaysAsk`](Self::AlwaysAsk) | An inbox approval | An inbox approval | An inbox approval |
567/// | [`Never`](Self::Never) | Stays `Proposed` | Stays `Proposed` | Stays `Proposed` |
568///
569/// Under `Never` the kernel neither asks nor schedules; an item runs only when a person
570/// approves it through the agenda (`adk-rust agenda approve`). Whatever the value, an item
571/// of [`AgendaOrigin::Consolidation`] is never scheduled without a person (K-I23).
572///
573/// # Example
574///
575/// ```rust
576/// use adk_kernel::ProactiveApproval;
577///
578/// assert_eq!(ProactiveApproval::default(), ProactiveApproval::FollowMode);
579/// assert_eq!(serde_json::to_value(ProactiveApproval::AlwaysAsk).unwrap(), "always_ask");
580/// ```
581#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
582#[serde(rename_all = "snake_case")]
583#[non_exhaustive]
584pub enum ProactiveApproval {
585    /// The partition's mode decides: ReadOnly and Plan hold, Ask asks, Auto schedules.
586    #[default]
587    FollowMode,
588    /// Every proposal goes to the inbox, whatever the mode.
589    AlwaysAsk,
590    /// No proposal is put to the inbox or scheduled by the kernel.
591    Never,
592}
593
594/// The proactivity limits of a partition (spec 3.2 §7.5, §9.1 runaway proactivity).
595///
596/// A proposal past `max_proposed_open` open items, or made while the daily budget is
597/// spent, is rejected with a reason on the event bus. `daily_budget` bounds the proactive
598/// processes of a partition per UTC day: admission holds one whose budget's cost cap the
599/// day's remaining proactive spend does not cover. Proactive processes never start inside
600/// `quiet_hours`. `consolidation` turns the consolidation tick on; it is `None` in the
601/// library and on servers, and the CLI sets it in its Ask and Auto partitions.
602/// `review_period` bounds the daily review of standing rules, sleepers and freezes
603/// ([`ReviewReport`](crate::ReviewReport)).
604///
605/// # Example
606///
607/// ```rust
608/// use adk_core::RunBudget;
609/// use adk_kernel::{ConsolidationTick, ProactiveApproval, ProactivityPolicy};
610///
611/// let policy = ProactivityPolicy::default()
612///     .with_daily_budget(RunBudget::new().max_cost_micro_usd(2_000_000))
613///     .with_quiet_hours("22:00-07:00".parse().unwrap())
614///     .with_consolidation(ConsolidationTick::default());
615/// assert_eq!(policy.max_proposed_open, 10);
616/// assert_eq!(policy.approval, ProactiveApproval::FollowMode);
617/// let json = serde_json::to_value(&policy).unwrap();
618/// assert_eq!(json["dailyBudget"]["maxCostMicroUsd"], 2_000_000);
619/// assert!(ProactivityPolicy::default().consolidation.is_none());
620/// ```
621#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
622#[serde(rename_all = "camelCase", default)]
623#[non_exhaustive]
624pub struct ProactivityPolicy {
625    /// Most open items per partition (10).
626    pub max_proposed_open: usize,
627    /// Model calls, tokens and cost for the partition's proactive processes per UTC day;
628    /// unlimited by default.
629    #[serde(with = "crate::serde_util::run_budget")]
630    pub daily_budget: RunBudget,
631    /// Proactive processes never start inside these.
632    #[serde(skip_serializing_if = "Option::is_none")]
633    pub quiet_hours: Option<QuietHours>,
634    /// How proposals are approved.
635    pub approval: ProactiveApproval,
636    /// The consolidation tick; the model and effort come from the harness.
637    #[serde(skip_serializing_if = "Option::is_none")]
638    pub consolidation: Option<ConsolidationTick>,
639    /// How old a standing rule without an expiry, a sleeper or a freeze-parked process gets
640    /// before the maintenance tick's daily review reports it (spec 3.2 §7.4, §9.1); 90 days.
641    #[serde(rename = "reviewPeriodMs", with = "crate::serde_util::millis")]
642    pub review_period: std::time::Duration,
643}
644
645impl ProactivityPolicy {
646    /// The default `max_proposed_open`.
647    pub const DEFAULT_MAX_PROPOSED_OPEN: usize = 10;
648
649    /// The default `review_period`, 90 days; the spec names the period without a number.
650    pub const DEFAULT_REVIEW_PERIOD: std::time::Duration =
651        std::time::Duration::from_secs(90 * 24 * 60 * 60);
652
653    /// The default policy: ten open items, no daily limit, no quiet hours, approval
654    /// following the mode, no consolidation tick.
655    pub fn new() -> Self {
656        Self::default()
657    }
658
659    /// Sets the most open items per partition.
660    #[must_use]
661    pub fn with_max_proposed_open(mut self, max: usize) -> Self {
662        self.max_proposed_open = max;
663        self
664    }
665
666    /// Sets the daily proactive budget.
667    #[must_use]
668    pub fn with_daily_budget(mut self, budget: RunBudget) -> Self {
669        self.daily_budget = budget;
670        self
671    }
672
673    /// Sets the quiet hours.
674    #[must_use]
675    pub fn with_quiet_hours(mut self, quiet_hours: QuietHours) -> Self {
676        self.quiet_hours = Some(quiet_hours);
677        self
678    }
679
680    /// Sets how proposals are approved.
681    #[must_use]
682    pub fn with_approval(mut self, approval: ProactiveApproval) -> Self {
683        self.approval = approval;
684        self
685    }
686
687    /// Turns the consolidation tick on.
688    #[must_use]
689    pub fn with_consolidation(mut self, tick: ConsolidationTick) -> Self {
690        self.consolidation = Some(tick);
691        self
692    }
693
694    /// Sets the review period.
695    #[must_use]
696    pub fn with_review_period(mut self, period: std::time::Duration) -> Self {
697        self.review_period = period;
698        self
699    }
700}
701
702impl Default for ProactivityPolicy {
703    fn default() -> Self {
704        Self {
705            max_proposed_open: Self::DEFAULT_MAX_PROPOSED_OPEN,
706            daily_budget: RunBudget::new(),
707            quiet_hours: None,
708            approval: ProactiveApproval::FollowMode,
709            consolidation: None,
710            review_period: Self::DEFAULT_REVIEW_PERIOD,
711        }
712    }
713}
714
715/// The kernel's store of agenda items (spec 3.2 §7.5, §13 Q8), on every backend the
716/// [`ProcessStore`](crate::ProcessStore) has.
717///
718/// State changes go through [`transition`](Self::transition), a compare-and-set on the
719/// stored state's kind, so two replicas approving or admitting one item move it once.
720///
721/// # Example
722///
723/// ```rust
724/// use adk_core::principal::SubjectRef;
725/// use adk_kernel::{AgendaFilter, AgendaItem, AgendaOrigin, AgendaState, AgendaStateKind, AgendaStore, InMemoryAgendaStore};
726///
727/// # #[tokio::main(flavor = "current_thread")]
728/// # async fn main() -> adk_kernel::Result<()> {
729/// let store = InMemoryAgendaStore::new();
730/// let item = AgendaItem::new("item-1", SubjectRef::human("alice"), "Tidy", "Weekly", AgendaOrigin::User, chrono::Utc::now());
731/// store.put(item.clone()).await?;
732/// assert!(store.transition(item.clone().with_state(AgendaState::Approved), AgendaStateKind::Proposed).await?);
733/// assert!(!store.transition(item.with_state(AgendaState::Rejected), AgendaStateKind::Proposed).await?);
734/// let open = store.list(&AgendaFilter::default().states([AgendaStateKind::Approved])).await?;
735/// assert_eq!(open.len(), 1);
736/// # Ok(())
737/// # }
738/// ```
739#[async_trait]
740pub trait AgendaStore: Send + Sync {
741    /// Inserts `item`, or replaces the item with the same id.
742    ///
743    /// # Errors
744    ///
745    /// Returns [`KernelError::Store`] when the backend fails.
746    async fn put(&self, item: AgendaItem) -> Result<()>;
747
748    /// The item `id`, or `None`.
749    ///
750    /// # Errors
751    ///
752    /// Returns [`KernelError::Store`] when the backend fails.
753    async fn get(&self, id: &str) -> Result<Option<AgendaItem>>;
754
755    /// The items `filter` selects, oldest first (by `created_at`, then id), at most
756    /// `filter.limit`.
757    ///
758    /// # Errors
759    ///
760    /// Returns [`KernelError::Store`] when the backend fails.
761    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>>;
762
763    /// Writes `item` over the stored item with its id when the stored item's state is of
764    /// kind `from`; `false`, writing nothing, when there is no such item or its state is
765    /// of another kind.
766    ///
767    /// # Errors
768    ///
769    /// Returns [`KernelError::Store`] when the backend fails.
770    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool>;
771
772    /// Deletes the item `id`; `false` when there was none.
773    ///
774    /// # Errors
775    ///
776    /// Returns [`KernelError::Store`] when the backend fails.
777    async fn delete(&self, id: &str) -> Result<bool>;
778}
779
780/// Which agenda items [`AgendaStore::list`] returns (spec 3.2 §7.5, §8.1 `adk-rust agenda
781/// list`). An empty field matches everything.
782///
783/// # Example
784///
785/// ```rust
786/// use adk_core::principal::SubjectRef;
787/// use adk_kernel::{AgendaFilter, AgendaItem, AgendaOrigin, AgendaStateKind};
788///
789/// let filter = AgendaFilter::default().partition("work").open();
790/// let item = AgendaItem::new("item-1", SubjectRef::human("alice"), "t", "r", AgendaOrigin::User, chrono::Utc::now()).with_partition("work");
791/// assert!(filter.matches(&item));
792/// assert!(!AgendaFilter::default().states([AgendaStateKind::Done]).matches(&item));
793/// ```
794#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
795#[serde(rename_all = "camelCase")]
796#[non_exhaustive]
797pub struct AgendaFilter {
798    /// Only items of this partition.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub partition: Option<PartitionId>,
801    /// Only items in one of these states.
802    #[serde(default, skip_serializing_if = "Vec::is_empty")]
803    pub states: Vec<AgendaStateKind>,
804    /// At most this many items.
805    #[serde(default, skip_serializing_if = "Option::is_none")]
806    pub limit: Option<usize>,
807}
808
809impl AgendaFilter {
810    /// Only items of `partition`.
811    #[must_use]
812    pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
813        self.partition = Some(partition.into());
814        self
815    }
816
817    /// Only items in one of `states`.
818    #[must_use]
819    pub fn states(mut self, states: impl IntoIterator<Item = AgendaStateKind>) -> Self {
820        self.states = states.into_iter().collect();
821        self
822    }
823
824    /// Only open items ([`AgendaStateKind::is_open`]).
825    #[must_use]
826    pub fn open(self) -> Self {
827        self.states(AgendaStateKind::ALL.into_iter().filter(|kind| kind.is_open()))
828    }
829
830    /// At most `limit` items.
831    #[must_use]
832    pub fn limit(mut self, limit: usize) -> Self {
833        self.limit = Some(limit);
834        self
835    }
836
837    /// Whether `item` passes the partition and state fields; `limit` is not checked here.
838    pub fn matches(&self, item: &AgendaItem) -> bool {
839        self.partition.as_ref().is_none_or(|partition| *partition == item.partition)
840            && (self.states.is_empty() || self.states.contains(&item.state.kind()))
841    }
842}
843
844/// The approval-inbox tool name of agenda proposals (spec 3.2 §7.5): an Ask partition's
845/// proposal waits in the inbox as an `ApprovalRequest` with this `tool_name`, the item as
846/// `args_redacted` and `allowed_actions = [Approve, Edit, Reject]`.
847pub const AGENDA_TOOL_NAME: &str = "kernel:agenda";
848
849/// What [`Agenda::propose`] did with a proposal (spec 3.2 §7.5).
850///
851/// # Example
852///
853/// ```rust
854/// use adk_kernel::ProposalOutcome;
855///
856/// let outcome = ProposalOutcome::Rejected { reason: "ten open items".into() };
857/// assert!(outcome.item().is_none());
858/// assert_eq!(serde_json::to_value(&outcome).unwrap()["outcome"], "rejected");
859/// ```
860#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
861#[serde(tag = "outcome", rename_all = "camelCase", rename_all_fields = "camelCase")]
862#[non_exhaustive]
863pub enum ProposalOutcome {
864    /// Recorded `Proposed` and held for a person: a ReadOnly or Plan partition, or
865    /// [`ProactiveApproval::Never`].
866    Held {
867        /// The item.
868        item: AgendaItem,
869    },
870    /// Recorded `Proposed` and put to the approval inbox.
871    AwaitingApproval {
872        /// The item.
873        item: AgendaItem,
874        /// The inbox request.
875        request_id: String,
876    },
877    /// Approved by an Auto partition's policy and scheduled.
878    Scheduled {
879        /// The item.
880        item: AgendaItem,
881        /// Its process.
882        pid: String,
883    },
884    /// Refused by the proactivity policy; nothing was recorded.
885    Rejected {
886        /// Which limit the proposal would exceed.
887        reason: String,
888    },
889}
890
891impl ProposalOutcome {
892    /// The recorded item, `None` for a rejection.
893    pub fn item(&self) -> Option<&AgendaItem> {
894        match self {
895            Self::Held { item }
896            | Self::AwaitingApproval { item, .. }
897            | Self::Scheduled { item, .. } => Some(item),
898            Self::Rejected { .. } => None,
899        }
900    }
901}
902
903/// Where a new proposal goes (spec 3.2 §7.5, K-I10, K-I23).
904#[derive(Debug, Clone, Copy, PartialEq, Eq)]
905pub(crate) enum Route {
906    /// Stays `Proposed` for a person.
907    Hold,
908    /// To the approval inbox.
909    Ask,
910    /// Approved by the policy and scheduled.
911    Schedule,
912}
913
914/// Routes a proposal of `origin` from a partition in `mode` under `approval`: only an Auto
915/// partition following its mode schedules without a person, and never an item the
916/// consolidation tick proposed (K-I23).
917pub(crate) fn route(
918    approval: ProactiveApproval,
919    mode: PartitionMode,
920    origin: &AgendaOrigin,
921) -> Route {
922    let follow = match mode {
923        PartitionMode::ReadOnly | PartitionMode::Plan => Route::Hold,
924        PartitionMode::Ask => Route::Ask,
925        PartitionMode::Auto if origin.needs_a_person() => Route::Ask,
926        PartitionMode::Auto => Route::Schedule,
927    };
928    match approval {
929        ProactiveApproval::FollowMode => follow,
930        ProactiveApproval::AlwaysAsk => Route::Ask,
931        ProactiveApproval::Never => Route::Hold,
932    }
933}
934
935/// The agenda of a kernel (spec 3.2 §7.5): proposals, approvals and the processes items
936/// become. [`Kernel::agenda`](crate::Kernel::agenda) returns it; cloning shares it.
937///
938/// | Call | Effect |
939/// |---|---|
940/// | [`propose`](Self::propose) | Checks the [`ProactivityPolicy`], records the item `Proposed`, and routes it: held, to the inbox, or — in an Auto partition following its mode — approved and scheduled |
941/// | [`approve`](Self::approve) | `Proposed` → `Approved` → `Scheduled`: a [`ProcessKind::Proposed`] process whose parent is the proposing run; for a question, `Proposed` → `Done`, confirmed |
942/// | [`reject`](Self::reject) | `Proposed` or `Approved` → `Rejected` |
943/// | [`schedule`](Self::schedule) | Puts the item's process to sleep on a wake set, approving a proposed item first; refused for a question |
944///
945/// Every change is published as a [`KernelEvent::Agenda`](crate::KernelEvent::Agenda) and
946/// audited as `kernel.agenda.*`. Inbox decisions, expiry and finished processes are applied
947/// on every scheduler tick.
948///
949/// # Example
950///
951/// ```rust,no_run
952/// use adk_core::principal::SubjectRef;
953/// use adk_kernel::{AgendaItem, AgendaOrigin, Kernel, PartitionMode, ProposalOutcome};
954///
955/// # async fn example(kernel: Kernel) -> adk_kernel::Result<()> {
956/// let item = AgendaItem::new(
957///     "item-1",
958///     SubjectRef::human("alice"),
959///     "Re-run the tests",
960///     "The dependency bump lands tonight",
961///     AgendaOrigin::User,
962///     chrono::Utc::now(),
963/// );
964/// if let ProposalOutcome::AwaitingApproval { request_id, .. } = kernel.agenda().propose(item, PartitionMode::Ask).await? {
965///     println!("approve {request_id} in the inbox");
966/// }
967/// # Ok(())
968/// # }
969/// ```
970#[derive(Clone)]
971pub struct Agenda {
972    inner: Arc<AgendaInner>,
973}
974
975struct AgendaInner {
976    sup: Arc<Supervision>,
977    processes: ProcessTable,
978    approvals: Option<Arc<dyn ApprovalService>>,
979    audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
980}
981
982impl fmt::Debug for Agenda {
983    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
984        f.debug_struct("Agenda")
985            .field("policy", &self.inner.sup.proactivity)
986            .field("inbox", &self.inner.approvals.is_some())
987            .field("audiences", &self.inner.audiences.keys().collect::<Vec<_>>())
988            .finish_non_exhaustive()
989    }
990}
991
992/// A handle on a kernel's agenda that does not keep the kernel alive, bound when the kernel
993/// is built (spec 3.2 §7.5, §10 HK1): the harness's `propose_followup` tool exists before the
994/// kernel that hosts it.
995///
996/// # Example
997///
998/// ```rust
999/// use adk_kernel::AgendaHandle;
1000///
1001/// let handle = AgendaHandle::new();
1002/// assert!(handle.get().is_none(), "no kernel was built with it");
1003/// ```
1004#[derive(Clone, Default)]
1005pub struct AgendaHandle {
1006    slot: Arc<std::sync::RwLock<std::sync::Weak<AgendaInner>>>,
1007}
1008
1009impl fmt::Debug for AgendaHandle {
1010    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011        f.debug_struct("AgendaHandle").field("bound", &self.get().is_some()).finish()
1012    }
1013}
1014
1015impl AgendaHandle {
1016    /// An unbound handle.
1017    pub fn new() -> Self {
1018        Self::default()
1019    }
1020
1021    /// The agenda of the kernel last built with this handle, while that kernel lives.
1022    pub fn get(&self) -> Option<Agenda> {
1023        let slot = self.slot.read().unwrap_or_else(|e| e.into_inner());
1024        slot.upgrade().map(|inner| Agenda { inner })
1025    }
1026
1027    pub(crate) fn bind(&self, agenda: &Agenda) {
1028        *self.slot.write().unwrap_or_else(|e| e.into_inner()) = Arc::downgrade(&agenda.inner);
1029    }
1030}
1031
1032/// The session an item's process runs in: `agenda-<item id>`, a session of its own.
1033///
1034/// # Example
1035///
1036/// ```rust
1037/// assert_eq!(adk_kernel::agenda::item_session("item-1"), "agenda-item-1");
1038/// ```
1039pub fn item_session(item_id: &str) -> String {
1040    format!("agenda-{item_id}")
1041}
1042
1043/// The approver group of the approvals inbox `adk-rust up` serves: the control plane's
1044/// `operator` scope.
1045pub(crate) const OPERATOR_GROUP: &str = "operator";
1046
1047/// The id of the inbox request of item `item_id`.
1048fn request_id(item_id: &str) -> String {
1049    format!("agenda_{item_id}")
1050}
1051
1052/// The user turn an item's process starts from.
1053fn prompt(item: &AgendaItem) -> String {
1054    let mut text = format!(
1055        "Follow-up from the agenda (item {}): {}\n\nWhy: {}",
1056        item.id, item.title, item.rationale
1057    );
1058    if let Some(plan) = &item.plan
1059        && !plan.steps.is_empty()
1060    {
1061        text.push_str("\n\nSteps:");
1062        for (index, step) in plan.steps.iter().enumerate() {
1063            let title = step.get("title").and_then(Value::as_str).unwrap_or_default();
1064            let instruction = step.get("instruction").and_then(Value::as_str).unwrap_or_default();
1065            text.push_str(&format!("\n{}. {title}: {instruction}", index + 1));
1066        }
1067    }
1068    text
1069}
1070
1071fn not_found(id: &str) -> KernelError {
1072    KernelError::AgendaNotFound { item: id.to_string() }
1073}
1074
1075/// Why a question is never scheduled, as [`KernelError::AgendaState`] names the action.
1076const QUESTION_NOT_SCHEDULED: &str = "scheduled: an observation is a question, answered with \
1077     `adk-rust agenda approve ID` (confirm) or `adk-rust agenda reject ID`, never scheduled";
1078
1079/// Why a question never becomes a process.
1080const QUESTION_NOT_RUN: &str = "run: an observation is a question and never becomes a process";
1081
1082/// How long a reschedule waits for a park in progress to be recorded, and how often it looks:
1083/// the park writes its row moments after its run turns `Waiting`, and the 250 ms suspend
1084/// mirror clears a request it left.
1085const PARK_RECORDED_WITHIN: std::time::Duration = std::time::Duration::from_secs(5);
1086const PARK_RECORDED_POLL: std::time::Duration = std::time::Duration::from_millis(20);
1087
1088/// The refusal of `item`, which only a person `verb`, to anyone else (K-I23, spec 3.2 §7.10).
1089fn needs_a_person(item: &AgendaItem, verb: &str) -> KernelError {
1090    let why = match &item.origin {
1091        AgendaOrigin::Observation { .. } => "is an observation's question".to_string(),
1092        AgendaOrigin::Signal { kind, .. } => format!("is a {kind} signal (spec 3.5 §7.10)"),
1093        other => format!("came from the {} tick", other.kind()),
1094    };
1095    KernelError::Unauthorized {
1096        reason: format!(
1097            "agenda item {} {why}, so only a person {verb} it (K-I23, spec 3.2 §7.10)",
1098            item.id
1099        ),
1100    }
1101}
1102
1103fn wrong_state(item: &AgendaItem, action: &'static str) -> KernelError {
1104    KernelError::AgendaState { item: item.id.clone(), state: item.state.kind(), action }
1105}
1106
1107impl Agenda {
1108    pub(crate) fn new(
1109        sup: Arc<Supervision>,
1110        processes: ProcessTable,
1111        approvals: Option<Arc<dyn ApprovalService>>,
1112        audiences: BTreeMap<PartitionId, Arc<dyn ObservationAudience>>,
1113    ) -> Self {
1114        Self { inner: Arc::new(AgendaInner { sup, processes, approvals, audiences }) }
1115    }
1116
1117    /// The store the items live in.
1118    pub fn store(&self) -> &Arc<dyn AgendaStore> {
1119        &self.inner.sup.agenda
1120    }
1121
1122    /// Every partition's proactivity limits.
1123    pub fn policy(&self) -> &ProactivityPolicy {
1124        &self.inner.sup.proactivity
1125    }
1126
1127    /// The item `id`, or `None`.
1128    ///
1129    /// # Errors
1130    ///
1131    /// Returns a store error.
1132    pub async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
1133        self.store().get(id).await
1134    }
1135
1136    /// The items `filter` selects, oldest first.
1137    ///
1138    /// # Errors
1139    ///
1140    /// Returns a store error.
1141    pub async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
1142        self.store().list(filter).await
1143    }
1144
1145    /// Proposes `item` from a partition in `mode` (spec 3.2 §7.5, §9.1 runaway
1146    /// proactivity).
1147    ///
1148    /// The policy refuses a proposal — published `proposed` → `rejected` with the reason
1149    /// and audited, nothing stored — past `max_proposed_open` open items in the partition,
1150    /// once the day's proactive budget is spent, or whose own budget exceeds the daily one.
1151    /// Otherwise the item is stored `Proposed` and routed by [`ProactiveApproval`]: held in
1152    /// ReadOnly and Plan, put to the inbox in Ask, approved and scheduled in Auto. An item
1153    /// of [`AgendaOrigin::Consolidation`] or [`AgendaOrigin::Observation`] goes to the inbox
1154    /// in Auto too (K-I23, spec 3.2 §7.10); a question costs no budget, so only the open-item
1155    /// limit refuses one. Without an approval service an Ask proposal is held.
1156    ///
1157    /// # Errors
1158    ///
1159    /// Returns [`KernelError::Config`] for an empty title or an item not `Proposed`, or a
1160    /// store error.
1161    pub async fn propose(
1162        &self,
1163        mut item: AgendaItem,
1164        mode: PartitionMode,
1165    ) -> Result<ProposalOutcome> {
1166        if item.title.trim().is_empty() {
1167            return Err(KernelError::Config { reason: "an agenda item needs a title".into() });
1168        }
1169        if item.state != AgendaState::Proposed {
1170            return Err(KernelError::Config {
1171                reason: format!("a new agenda item is proposed, not {}", item.state.kind()),
1172            });
1173        }
1174        let sup = &self.inner.sup;
1175        if let Some(reason) = self.refusal(&item).await? {
1176            item.state = AgendaState::Rejected;
1177            sup.agenda_changed(&item, &AgendaState::Proposed, Some(&reason), None).await;
1178            tracing::info!(agenda.item = %item.id, reason = %reason, "proposal refused by the proactivity policy");
1179            return Ok(ProposalOutcome::Rejected { reason });
1180        }
1181        sup.agenda.put(item.clone()).await?;
1182        let by =
1183            item.proposer().map(|pid| SubjectRef::new(SubjectKind::Agent, format!("run:{pid}")));
1184        sup.agenda_changed(&item, &AgendaState::Proposed, Some("proposed"), by.as_ref()).await;
1185        let mut route = route(sup.proactivity.approval, mode, &item.origin);
1186        if route == Route::Ask && self.inner.approvals.is_none() {
1187            route = Route::Hold;
1188        }
1189        match route {
1190            Route::Hold => Ok(ProposalOutcome::Held { item }),
1191            Route::Ask => {
1192                let request_id = self.submit(&item).await?;
1193                Ok(ProposalOutcome::AwaitingApproval { item, request_id })
1194            }
1195            Route::Schedule => {
1196                let policy = SubjectRef::service("kernel:proactivity-policy");
1197                let item = self
1198                    .approve_as(item, &policy, "admitted by the Auto partition's policy")
1199                    .await?;
1200                let pid = match &item.state {
1201                    AgendaState::Scheduled { .. } => self.process_of(&item.id).await?,
1202                    _ => None,
1203                };
1204                match pid {
1205                    Some(pid) => Ok(ProposalOutcome::Scheduled { item, pid }),
1206                    None => Ok(ProposalOutcome::Held { item }),
1207                }
1208            }
1209        }
1210    }
1211
1212    /// Files `observation` as a question for its partition's audience (spec 3.2 §7.10): an
1213    /// [`AgendaOrigin::Observation`] item with the observation's id, titled with its
1214    /// question, its rationale the statement a confirmation remembers, expiring unanswered
1215    /// after the longest comparison window. `None` when the partition has no audience, the
1216    /// audience names nobody, or the item exists already (another replica filed it).
1217    #[cfg(feature = "proc-baselines")]
1218    pub(crate) async fn offer(
1219        &self,
1220        observation: &crate::proc::Observation,
1221    ) -> Result<Option<ProposalOutcome>> {
1222        let Some(audience) = self.inner.audiences.get(&observation.partition) else {
1223            return Ok(None);
1224        };
1225        let Some((person, mode)) = audience.audience(&observation.partition).await? else {
1226            return Ok(None);
1227        };
1228        // A mode tightened while the kernel runs routes the question (spec 3.3 §10 K3).
1229        let mode = self.inner.sup.area_mode(&observation.partition, mode).await;
1230        if self.get(&observation.id).await?.is_some() {
1231            return Ok(None);
1232        }
1233        let open_for = observation.windows.iter().copied().max().unwrap_or(14);
1234        let item = AgendaItem::new(
1235            observation.id.clone(),
1236            person,
1237            observation.question.clone(),
1238            observation.statement(),
1239            AgendaOrigin::Observation { id: observation.id.clone() },
1240            observation.created_at,
1241        )
1242        .with_partition(observation.partition.clone())
1243        .with_expiry(observation.created_at + chrono::Duration::days(i64::from(open_for)));
1244        self.propose(item, mode).await.map(Some)
1245    }
1246
1247    /// Why the policy refuses `item`, or `None`.
1248    async fn refusal(&self, item: &AgendaItem) -> Result<Option<String>> {
1249        let sup = &self.inner.sup;
1250        let policy = &sup.proactivity;
1251        let open = self
1252            .store()
1253            .list(&AgendaFilter::default().partition(item.partition.clone()).open())
1254            .await?
1255            .iter()
1256            // Signals are inputs with a rate limit of their own, not proposals (spec 3.5 §7.10).
1257            .filter(|open| !matches!(open.origin, AgendaOrigin::Signal { .. }))
1258            .count();
1259        if open >= policy.max_proposed_open {
1260            return Ok(Some(format!(
1261                "partition {} already has {open} open agenda items, the most max_proposed_open ({}) allows",
1262                item.partition, policy.max_proposed_open
1263            )));
1264        }
1265        // A question becomes no process, so it spends nothing.
1266        if item.origin.is_question() {
1267            return Ok(None);
1268        }
1269        let daily = &policy.daily_budget;
1270        if let Some(cap) = daily.max_cost_micro_usd {
1271            let need =
1272                item.budget.as_ref().and_then(|budget| budget.max_cost_micro_usd).unwrap_or(0);
1273            if need > cap {
1274                return Ok(Some(format!(
1275                    "its budget of {need} micro-USD exceeds the daily proactive budget of {cap}"
1276                )));
1277            }
1278        }
1279        if daily.max_cost_micro_usd.is_none()
1280            && daily.max_model_calls.is_none()
1281            && daily.max_total_tokens.is_none()
1282        {
1283            return Ok(None);
1284        }
1285        let used = sup.proactive_usage(&item.partition).await;
1286        let reached = [
1287            (daily.max_cost_micro_usd, used.micro_usd, "micro-USD"),
1288            (daily.max_model_calls, used.model_calls, "model calls"),
1289            (daily.max_total_tokens, used.total_tokens, "tokens"),
1290        ]
1291        .into_iter()
1292        .find_map(|(cap, used, unit)| cap.filter(|cap| used >= *cap).map(|cap| (used, cap, unit)));
1293        if let Some((used, cap, unit)) = reached {
1294            return Ok(Some(format!(
1295                "partition {} spent its daily proactive budget ({used} of {cap} {unit})",
1296                item.partition
1297            )));
1298        }
1299        Ok(None)
1300    }
1301
1302    /// Puts `item` to the approval inbox; returns the request id.
1303    async fn submit(&self, item: &AgendaItem) -> Result<String> {
1304        let Some(approvals) = &self.inner.approvals else {
1305            return Err(KernelError::Config {
1306                reason: "the kernel has no approval service".into(),
1307            });
1308        };
1309        let sup = &self.inner.sup;
1310        let session = match item.proposer() {
1311            Some(pid) => match sup.runs.get(pid).await? {
1312                Some(run) => crate::supervise::run_session(&run),
1313                None => item_session(&item.id),
1314            },
1315            None => item_session(&item.id),
1316        };
1317        let scope = ApprovalScope::new(sup.app_name.clone(), item.subject.id.clone(), session);
1318        let args = serde_json::to_value(item)?;
1319        let call = ToolConfirmationRequest::new(AGENDA_TOOL_NAME, args.clone());
1320        // The item's user, or the operators the control plane's socket and loopback serve,
1321        // decide it; either is a person.
1322        let policy = ApprovalPolicy::new([
1323            ApproverSelector::human(item.subject.id.clone()),
1324            ApproverSelector::group(OPERATOR_GROUP),
1325        ])
1326        .allow_self_approval();
1327        let id = request_id(&item.id);
1328        let mut request = ApprovalRequest::new(id.clone(), scope, &call, policy)
1329            .with_redacted_args(args)
1330            .with_requester(item.subject.clone());
1331        // A question is confirmed or rejected as worded; nothing in it runs.
1332        request = if item.origin.is_question() {
1333            request
1334                .with_summary(format!("Observation: {}", item.title))
1335                .with_risk(ApprovalRisk::Low)
1336                .with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject])
1337        } else {
1338            request
1339                .with_summary(format!("Agenda follow-up: {}", item.title))
1340                .with_risk(ApprovalRisk::Medium)
1341                .with_allowed_actions([
1342                    ApprovalAction::Approve,
1343                    ApprovalAction::Edit,
1344                    ApprovalAction::Reject,
1345                ])
1346        };
1347        if let Some(at) = item.expires_at {
1348            request = request.with_expires_at(at);
1349        }
1350        if let Some(pid) = item.proposer() {
1351            request = request.with_run_id(pid.to_string());
1352        }
1353        approvals.submit(request).await?;
1354        tracing::info!(agenda.item = %item.id, approval.id = %id, "agenda proposal put to the approval inbox");
1355        Ok(id)
1356    }
1357
1358    /// Approves the proposed item `id` as `by`, then schedules it: `Proposed` → `Approved` →
1359    /// `Scheduled` (spec 3.2 §7.5, K-I10). An item of [`AgendaOrigin::Consolidation`] needs
1360    /// a person (K-I23). A pending inbox request for the item is withdrawn.
1361    ///
1362    /// A question ([`AgendaOrigin::is_question`]) is confirmed instead, by a person only:
1363    /// the partition's [`ObservationAudience`] records its statement as a `Known` fact, and
1364    /// the item is `Done` with the [`AgendaAnswer`]; no process is created (spec 3.2 §7.10).
1365    ///
1366    /// Returns the item as it stands: `Scheduled`, or `Approved` when its process could not
1367    /// be created yet (a freeze, a full queue), which the next tick retries; `Done` for a
1368    /// confirmed question.
1369    ///
1370    /// # Errors
1371    ///
1372    /// Returns [`KernelError::AgendaNotFound`], [`KernelError::AgendaState`] when the item is
1373    /// not `Proposed`, [`KernelError::Unauthorized`] when `by` is not a person and the item
1374    /// needs one, the audience's error, or a store error.
1375    pub async fn approve(&self, id: &str, by: &SubjectRef) -> Result<AgendaItem> {
1376        let item = self.get(id).await?.ok_or_else(|| not_found(id))?;
1377        let approved = self.approve_as(item, by, "approved").await?;
1378        self.withdraw(id, "approved through the agenda").await;
1379        Ok(approved)
1380    }
1381
1382    async fn approve_as(
1383        &self,
1384        item: AgendaItem,
1385        by: &SubjectRef,
1386        reason: &str,
1387    ) -> Result<AgendaItem> {
1388        if item.state != AgendaState::Proposed {
1389            return Err(wrong_state(&item, "approved"));
1390        }
1391        if item.origin.needs_a_person() && by.kind != SubjectKind::Human {
1392            return Err(needs_a_person(&item, "approves"));
1393        }
1394        if item.origin.is_question() {
1395            return self.answer(item, by, true, reason).await;
1396        }
1397        let from = item.state.clone();
1398        let approved = item.with_state(AgendaState::Approved);
1399        if !self.inner.sup.move_item(&approved, &from, Some(reason), Some(by)).await? {
1400            let current = self.get(&approved.id).await?.ok_or_else(|| not_found(&approved.id))?;
1401            return Err(wrong_state(&current, "approved"));
1402        }
1403        Ok(self.start(approved, by).await)
1404    }
1405
1406    /// Closes the question `item` with `by`'s answer (spec 3.2 §7.10): confirmed, the
1407    /// partition's audience records it first and the item is `Done`; otherwise it is
1408    /// `Rejected` and nothing is recorded.
1409    async fn answer(
1410        &self,
1411        item: AgendaItem,
1412        by: &SubjectRef,
1413        confirmed: bool,
1414        reason: &str,
1415    ) -> Result<AgendaItem> {
1416        let sup = &self.inner.sup;
1417        let mut answer = AgendaAnswer::new(confirmed, by.clone(), sup.clock.now());
1418        let mut reason = if confirmed { "confirmed".to_string() } else { reason.to_string() };
1419        if confirmed && let Some(audience) = self.inner.audiences.get(&item.partition) {
1420            let fact = audience.confirm(&item, by).await?;
1421            reason = format!("confirmed; remembered as known fact {fact}");
1422            answer = answer.with_fact(fact);
1423        }
1424        let from = item.state.clone();
1425        let mut closed =
1426            item.with_state(if confirmed { AgendaState::Done } else { AgendaState::Rejected });
1427        closed.answer = Some(answer);
1428        if !sup.move_item(&closed, &from, Some(&reason), Some(by)).await? {
1429            let current = self.get(&closed.id).await?.ok_or_else(|| not_found(&closed.id))?;
1430            return Err(wrong_state(&current, if confirmed { "confirmed" } else { "rejected" }));
1431        }
1432        Ok(closed)
1433    }
1434
1435    /// Creates the process of the approved `item`, asleep on its wake (or on the end of
1436    /// quiet hours, or now), and marks it `Scheduled`; leaves it `Approved` when the
1437    /// process cannot be created yet.
1438    async fn start(&self, item: AgendaItem, by: &SubjectRef) -> AgendaItem {
1439        match self.spawn(&item, None).await {
1440            Ok((pid, wake)) => {
1441                let from = item.state.clone();
1442                let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
1443                match self
1444                    .inner
1445                    .sup
1446                    .move_item(&scheduled, &from, Some(&format!("process {pid}")), Some(by))
1447                    .await
1448                {
1449                    Ok(true) => scheduled,
1450                    Ok(false) | Err(_) => self.get(&item.id).await.ok().flatten().unwrap_or(item),
1451                }
1452            }
1453            Err(error) => {
1454                tracing::warn!(agenda.item = %item.id, error = %error, "could not create the agenda item's process yet; the next tick retries");
1455                item
1456            }
1457        }
1458    }
1459
1460    /// Creates or finds the process of `item` (spec 3.2 §7.5, §7.9): asleep on `wake`, or on
1461    /// the item's own `when`; otherwise awake, with `not_before` at the end of quiet hours
1462    /// when they hold now. Returns the pid and the wake set the item is scheduled on.
1463    async fn spawn(&self, item: &AgendaItem, wake: Option<WakeSet>) -> Result<(String, WakeSet)> {
1464        if item.origin.is_question() {
1465            return Err(wrong_state(item, QUESTION_NOT_RUN));
1466        }
1467        let sup = &self.inner.sup;
1468        let now = sup.clock.now();
1469        let asleep = wake.or_else(|| item.when.clone().map(|when| WakeSet::any_of([when])));
1470        let asleep = match (asleep, item.expires_at) {
1471            (Some(set), Some(at)) => Some(set.with_expiry(at, crate::wake::ExpiryAction::Cancel)),
1472            (set, _) => set,
1473        };
1474        let release = sup.quiet_release(&item.partition, now).await;
1475        let proposer = match item.proposer() {
1476            Some(pid) => sup.runs.get(pid).await?,
1477            None => None,
1478        };
1479        // Without the proposing run, the app's target runs the follow-up, unless the item's
1480        // partition has agents of its own and the app's is not one: then the first of them,
1481        // by name, does (spec 3.2 §7.8).
1482        let target = match &proposer {
1483            Some(run) => run.target.clone(),
1484            None => {
1485                let own: Vec<&String> = sup
1486                    .targets
1487                    .statics()
1488                    .iter()
1489                    .filter(|(_, bound)| **bound == item.partition)
1490                    .map(|(target, _)| target)
1491                    .collect();
1492                match own.first() {
1493                    Some(first) if !own.contains(&&sup.app_name) => (*first).clone(),
1494                    _ => sup.app_name.clone(),
1495                }
1496            }
1497        };
1498        let mut run = NewRun::new(
1499            QueueClass::BACKGROUND,
1500            sup.app_name.clone(),
1501            item.subject.id.clone(),
1502            target,
1503            Value::String(prompt(item)),
1504        );
1505        run.session_id = Some(item_session(&item.id));
1506        run.idempotency_key = Some(format!("agenda:{}", item.id));
1507        if asleep.is_none() && release > now {
1508            run.not_before = Some(release);
1509        }
1510        if let Some(proposer) = &proposer {
1511            run.principal = proposer.principal.clone();
1512            // Auto and standing rules apply only when the proposing run's did (K-I7).
1513            run.authenticated = proposer.authenticated;
1514        }
1515        let mut spec = ProcessSpec::new(ProcessKind::Proposed)
1516            .with_partition(item.partition.clone())
1517            .with_agenda_item(item.id.clone());
1518        if let Some(set) = &asleep {
1519            spec = spec.with_wake(set.clone());
1520        }
1521        if let Some(pid) = item.proposer() {
1522            spec = spec.with_parent(pid);
1523        }
1524        let process = self.inner.processes.spawn(run, spec).await?;
1525        let scheduled = asleep.unwrap_or_else(|| WakeSet::any_of([Wake::At(release)]));
1526        Ok((process.meta.pid, scheduled))
1527    }
1528
1529    /// The process of item `id`, the run keyed `agenda:<id>`.
1530    async fn process_of(&self, id: &str) -> Result<Option<String>> {
1531        let item = self.get(id).await?;
1532        let filter = crate::ProcessFilter::default();
1533        let filter = match &item {
1534            Some(item) => filter.partition(item.partition.clone()),
1535            None => filter,
1536        };
1537        Ok(self
1538            .inner
1539            .sup
1540            .processes
1541            .list(&filter)
1542            .await?
1543            .into_iter()
1544            .find(|meta| {
1545                meta.agenda_item.as_deref() == Some(id) && meta.kind == ProcessKind::Proposed
1546            })
1547            .map(|meta| meta.pid))
1548    }
1549
1550    /// Rejects item `id` as `by`: a `Proposed` or `Approved` item becomes `Rejected`, and a
1551    /// pending inbox request for it is withdrawn. A question is closed with `by`'s
1552    /// [`AgendaAnswer`], and nothing is remembered (spec 3.2 §7.10).
1553    ///
1554    /// # Errors
1555    ///
1556    /// Returns [`KernelError::AgendaNotFound`], [`KernelError::AgendaState`] when the item is
1557    /// past approval, or a store error.
1558    pub async fn reject(
1559        &self,
1560        id: &str,
1561        by: &SubjectRef,
1562        reason: Option<&str>,
1563    ) -> Result<AgendaItem> {
1564        let item = self.get(id).await?.ok_or_else(|| not_found(id))?;
1565        let rejected = self.reject_as(item, by, reason.unwrap_or("rejected")).await?;
1566        self.withdraw(id, "rejected through the agenda").await;
1567        Ok(rejected)
1568    }
1569
1570    async fn reject_as(
1571        &self,
1572        item: AgendaItem,
1573        by: &SubjectRef,
1574        reason: &str,
1575    ) -> Result<AgendaItem> {
1576        if !matches!(item.state, AgendaState::Proposed | AgendaState::Approved) {
1577            return Err(wrong_state(&item, "rejected"));
1578        }
1579        if item.origin.is_question() {
1580            return self.answer(item, by, false, reason).await;
1581        }
1582        let from = item.state.clone();
1583        let rejected = item.with_state(AgendaState::Rejected);
1584        if !self.inner.sup.move_item(&rejected, &from, Some(reason), Some(by)).await? {
1585            let current = self.get(&rejected.id).await?.ok_or_else(|| not_found(&rejected.id))?;
1586            return Err(wrong_state(&current, "rejected"));
1587        }
1588        Ok(rejected)
1589    }
1590
1591    /// Schedules item `id` on `wake` as `by` (spec 3.2 §7.5, §8.1 `adk-rust agenda schedule
1592    /// ID --at|--cron`): a `Proposed` item is approved as by [`approve`](Self::approve) and
1593    /// its process created asleep on `wake`; an `Approved` one gets its process asleep on
1594    /// `wake`; a `Scheduled` one whose process has not started sleeps on `wake` instead —
1595    /// a queued process parks on it when it is claimed, and one a worker claimed only to
1596    /// park it on its wake set parks on `wake` (K-I2).
1597    ///
1598    /// # Errors
1599    ///
1600    /// Returns [`KernelError::AgendaNotFound`], [`KernelError::AgendaState`] for an item that
1601    /// is past scheduling or whose process already started, and for a question, which is
1602    /// answered and never scheduled (spec 3.2 §7.10), [`KernelError::Unauthorized`] when `by`
1603    /// is not a person and the item needs one, or a store error.
1604    pub async fn schedule(&self, id: &str, wake: WakeSet, by: &SubjectRef) -> Result<AgendaItem> {
1605        let mut item = self.get(id).await?.ok_or_else(|| not_found(id))?;
1606        let sup = &self.inner.sup;
1607        if item.origin.is_question() {
1608            return Err(wrong_state(&item, QUESTION_NOT_SCHEDULED));
1609        }
1610        if item.state == AgendaState::Proposed {
1611            if item.origin.needs_a_person() && by.kind != SubjectKind::Human {
1612                return Err(needs_a_person(&item, "schedules"));
1613            }
1614            let approved = item.clone().with_state(AgendaState::Approved);
1615            if !sup
1616                .move_item(&approved, &item.state, Some("approved to schedule"), Some(by))
1617                .await?
1618            {
1619                return Err(wrong_state(&item, "scheduled"));
1620            }
1621            self.withdraw(id, "scheduled through the agenda").await;
1622            item = approved;
1623        }
1624        match &item.state {
1625            AgendaState::Approved => {
1626                let (pid, wake) = self.spawn(&item, Some(wake)).await?;
1627                let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
1628                if !sup
1629                    .move_item(&scheduled, &item.state, Some(&format!("process {pid}")), Some(by))
1630                    .await?
1631                {
1632                    return Err(wrong_state(&item, "scheduled"));
1633                }
1634                Ok(scheduled)
1635            }
1636            AgendaState::Scheduled { .. } => {
1637                let pid =
1638                    self.process_of(id).await?.ok_or_else(|| wrong_state(&item, "rescheduled"))?;
1639                let state = sup.runs.get(&pid).await?.map(|run| run.state);
1640                // A claim of a process whose row still holds its wake set only parks it on
1641                // that set, before its first model call (K-I2): it has not started.
1642                let parking = state == Some(RunState::Running)
1643                    && sup.processes.get(&pid).await?.is_some_and(|meta| meta.wake.is_some());
1644                if !parking && !matches!(state, Some(RunState::Waiting | RunState::Queued)) {
1645                    return Err(wrong_state(&item, "rescheduled (its process already started)"));
1646                }
1647                let wake = match item.expires_at {
1648                    Some(at) => wake.with_expiry(at, crate::wake::ExpiryAction::Cancel),
1649                    None => wake,
1650                };
1651                sup.processes.set_wake(&pid, Some(wake.clone())).await?;
1652                if state == Some(RunState::Queued) {
1653                    // Parks at its claim, before its first model call, on the new wake set.
1654                    sup.processes.set_suspend_requested(&pid, true).await?;
1655                } else {
1656                    self.keep_wake_through_park(&pid, &wake).await?;
1657                }
1658                sup.roots_changed.notify_one();
1659                let scheduled = item.clone().with_state(AgendaState::Scheduled { wake });
1660                if !sup.move_item(&scheduled, &item.state, Some("rescheduled"), Some(by)).await? {
1661                    return Err(wrong_state(&item, "rescheduled"));
1662                }
1663                Ok(scheduled)
1664            }
1665            _ => Err(wrong_state(&item, "scheduled")),
1666        }
1667    }
1668
1669    /// Withdraws the pending inbox request of item `id`, if any.
1670    async fn withdraw(&self, id: &str, note: &str) {
1671        let Some(approvals) = &self.inner.approvals else { return };
1672        if let Ok(Some(request)) = approvals.get(&request_id(id)).await
1673            && request.state == ApprovalState::Pending
1674            && let Err(error) = approvals.cancel(&request.id, Some(note.to_string())).await
1675        {
1676            tracing::debug!(approval.id = %request.id, error = %error, "could not withdraw an agenda request");
1677        }
1678    }
1679
1680    /// Keeps `wake`, just written to the row of `pid`, through a park in progress. A park
1681    /// writes back the row it read after its run turned `Waiting`: a run still `Running` once
1682    /// `wake` is written reads `wake` there; one already `Waiting` may have read the row
1683    /// before, so once its park is recorded — its sleep request cleared — a replaced `wake` is
1684    /// written again.
1685    async fn keep_wake_through_park(&self, pid: &str, wake: &WakeSet) -> Result<()> {
1686        let sup = &self.inner.sup;
1687        if sup.runs.get(pid).await?.is_none_or(|run| run.state != RunState::Waiting) {
1688            return Ok(());
1689        }
1690        let deadline = tokio::time::Instant::now() + PARK_RECORDED_WITHIN;
1691        loop {
1692            let Some(meta) = sup.processes.get(pid).await? else { return Ok(()) };
1693            if !meta.suspend_requested || tokio::time::Instant::now() >= deadline {
1694                if meta.wake.as_ref() != Some(wake) {
1695                    sup.processes.set_wake(pid, Some(wake.clone())).await?;
1696                }
1697                return Ok(());
1698            }
1699            tokio::time::sleep(PARK_RECORDED_POLL).await;
1700        }
1701    }
1702
1703    /// One scheduler tick of the agenda (spec 3.2 §7.5): applies inbox decisions, expires
1704    /// items, retries approved items without a process, and finishes items whose process
1705    /// ended while not running.
1706    pub(crate) async fn tick(&self) {
1707        if let Err(error) = self.tick_inner().await {
1708            tracing::debug!(error = %error, "agenda tick failed");
1709        }
1710    }
1711
1712    async fn tick_inner(&self) -> Result<()> {
1713        let sup = &self.inner.sup;
1714        let now = sup.clock.now();
1715        for item in self.store().list(&AgendaFilter::default().open()).await? {
1716            match &item.state {
1717                AgendaState::Proposed => {
1718                    if item.expires_at.is_some_and(|at| at <= now) {
1719                        self.expire(item).await?;
1720                        continue;
1721                    }
1722                    self.apply_decision(item).await?;
1723                }
1724                AgendaState::Approved => {
1725                    if item.expires_at.is_some_and(|at| at <= now) {
1726                        self.expire(item).await?;
1727                    } else if !item.origin.is_question() {
1728                        let by = SubjectRef::service("kernel");
1729                        self.start(item, &by).await;
1730                    }
1731                }
1732                AgendaState::Scheduled { .. } | AgendaState::Running { .. } => {
1733                    let Some(pid) = self.process_of(&item.id).await? else { continue };
1734                    let Some(run) = sup.runs.get(&pid).await? else { continue };
1735                    if !run.state.is_terminal() {
1736                        // A process still queued past the item's expiry never starts; the
1737                        // next tick finds it cancelled and expires the item.
1738                        if run.state == RunState::Queued
1739                            && matches!(item.state, AgendaState::Scheduled { .. })
1740                            && item.expires_at.is_some_and(|at| at <= now)
1741                        {
1742                            self.inner.processes.kill(&pid, "its agenda item expired").await?;
1743                        }
1744                        continue;
1745                    }
1746                    let from = item.state.clone();
1747                    let never_ran = matches!(from, AgendaState::Scheduled { .. })
1748                        && run.state == RunState::Cancelled
1749                        && item.expires_at.is_some_and(|at| at <= now);
1750                    let next = item.with_state(if never_ran {
1751                        AgendaState::Expired
1752                    } else {
1753                        AgendaState::Done
1754                    });
1755                    let reason = format!("process {pid} ended");
1756                    sup.move_item(&next, &from, Some(&reason), None).await?;
1757                }
1758                _ => {}
1759            }
1760        }
1761        Ok(())
1762    }
1763
1764    async fn expire(&self, item: AgendaItem) -> Result<()> {
1765        let from = item.state.clone();
1766        let id = item.id.clone();
1767        let expired = item.with_state(AgendaState::Expired);
1768        if self.inner.sup.move_item(&expired, &from, Some("expired before it ran"), None).await? {
1769            self.withdraw(&id, "the agenda item expired").await;
1770        }
1771        Ok(())
1772    }
1773
1774    /// Applies the inbox decision on the proposed `item`, if one was made.
1775    async fn apply_decision(&self, item: AgendaItem) -> Result<()> {
1776        let Some(approvals) = &self.inner.approvals else { return Ok(()) };
1777        let Some(request) = approvals.get(&request_id(&item.id)).await? else { return Ok(()) };
1778        let last = request.decisions.last();
1779        let by =
1780            last.map_or_else(|| SubjectRef::service("kernel:approvals"), |d| d.approver.clone());
1781        match request.state {
1782            ApprovalState::Pending => Ok(()),
1783            ApprovalState::Approved => {
1784                let mut item = item;
1785                if let Some(edited) = last
1786                    .filter(|d| d.kind == ApprovalAction::Edit)
1787                    .and_then(|d| d.edited_args.as_ref())
1788                {
1789                    let from = item.state.clone();
1790                    let edited_item = edit(item.clone(), edited);
1791                    if edited_item != item
1792                        && self
1793                            .inner
1794                            .sup
1795                            .move_item(&edited_item, &from, Some("edited in the inbox"), Some(&by))
1796                            .await?
1797                    {
1798                        item = edited_item;
1799                    }
1800                }
1801                match self.approve_as(item.clone(), &by, "approved in the inbox").await {
1802                    Ok(_) => Ok(()),
1803                    Err(KernelError::Unauthorized { reason }) => {
1804                        tracing::warn!(agenda.item = %item.id, reason = %reason, "an inbox approval by someone other than a person was ignored");
1805                        Ok(())
1806                    }
1807                    Err(KernelError::AgendaState { .. }) => Ok(()),
1808                    // The confirmation stays pending in the inbox; the next tick records it.
1809                    Err(error) if item.origin.is_question() => {
1810                        tracing::warn!(agenda.item = %item.id, error = %error, "could not record a confirmed observation yet; the next tick retries");
1811                        Ok(())
1812                    }
1813                    Err(error) => Err(error),
1814                }
1815            }
1816            ApprovalState::Rejected | ApprovalState::Responded => {
1817                let reason = last
1818                    .and_then(|d| d.reason.clone())
1819                    .unwrap_or_else(|| "rejected in the inbox".into());
1820                match self.reject_as(item, &by, &reason).await {
1821                    Ok(_) | Err(KernelError::AgendaState { .. }) => Ok(()),
1822                    Err(error) => Err(error),
1823                }
1824            }
1825            ApprovalState::Expired => self.expire(item).await,
1826            ApprovalState::Cancelled => {
1827                let note = request.note.unwrap_or_else(|| "the inbox request was withdrawn".into());
1828                match self.reject_as(item, &by, &note).await {
1829                    Ok(_) | Err(KernelError::AgendaState { .. }) => Ok(()),
1830                    Err(error) => Err(error),
1831                }
1832            }
1833        }
1834    }
1835}
1836
1837/// `item` with the fields an inbox `Edit` may change: `title`, `rationale`, `when` and
1838/// `expiresAt`; anything else in `edited` is ignored, so an edit cannot change the origin,
1839/// partition, subject or budget.
1840fn edit(mut item: AgendaItem, edited: &Value) -> AgendaItem {
1841    if let Some(title) =
1842        edited.get("title").and_then(Value::as_str).filter(|t| !t.trim().is_empty())
1843    {
1844        item.title = title.to_string();
1845    }
1846    if let Some(rationale) = edited.get("rationale").and_then(Value::as_str) {
1847        item.rationale = rationale.to_string();
1848    }
1849    if let Some(when) = edited.get("when") {
1850        item.when = serde_json::from_value(when.clone()).ok();
1851    }
1852    if let Some(expires) = edited.get("expiresAt") {
1853        item.expires_at = serde_json::from_value(expires.clone()).ok();
1854    }
1855    item
1856}
1857
1858#[cfg(test)]
1859mod tests {
1860    use proptest::prelude::*;
1861    use serde_json::json;
1862
1863    use super::*;
1864
1865    const MODES: [PartitionMode; 4] =
1866        [PartitionMode::ReadOnly, PartitionMode::Plan, PartitionMode::Ask, PartitionMode::Auto];
1867
1868    #[test]
1869    fn follow_mode_holds_asks_or_schedules_by_the_partitions_mode() {
1870        let agent = AgendaOrigin::Agent { pid: "run-1".into(), confidence: 1.0 };
1871        let routes: Vec<Route> =
1872            MODES.iter().map(|mode| route(ProactiveApproval::FollowMode, *mode, &agent)).collect();
1873        assert_eq!(routes, [Route::Hold, Route::Hold, Route::Ask, Route::Schedule]);
1874        for mode in MODES {
1875            assert_eq!(route(ProactiveApproval::AlwaysAsk, mode, &agent), Route::Ask);
1876            assert_eq!(route(ProactiveApproval::Never, mode, &agent), Route::Hold);
1877        }
1878    }
1879
1880    #[test]
1881    fn consolidation_and_observation_items_never_schedule_without_a_person() {
1882        for origin in
1883            [AgendaOrigin::Consolidation, AgendaOrigin::Observation { id: "obs-1".into() }]
1884        {
1885            let routes: Vec<Route> = MODES
1886                .iter()
1887                .map(|mode| route(ProactiveApproval::FollowMode, *mode, &origin))
1888                .collect();
1889            assert_eq!(
1890                routes,
1891                [Route::Hold, Route::Hold, Route::Ask, Route::Ask],
1892                "Auto asks too (K-I23, spec 3.2 §7.10): {origin}"
1893            );
1894        }
1895    }
1896
1897    fn origin() -> impl Strategy<Value = AgendaOrigin> {
1898        prop_oneof![
1899            Just(AgendaOrigin::User),
1900            Just(AgendaOrigin::Consolidation),
1901            (0.0f32..=1.0)
1902                .prop_map(|confidence| AgendaOrigin::Agent { pid: "run-1".into(), confidence }),
1903            Just(AgendaOrigin::Observation { id: "obs-1".into() }),
1904        ]
1905    }
1906
1907    proptest! {
1908        #![proptest_config(ProptestConfig::with_cases(256))]
1909
1910        /// Only an Auto partition following its mode schedules a proposal without a person
1911        /// (K-I10), never one of the consolidation tick's (K-I23), and never a question
1912        /// (spec 3.2 §7.10).
1913        #[test]
1914        fn only_auto_follow_mode_schedules_and_never_consolidation_or_a_question(
1915            mode in prop::sample::select(MODES.to_vec()),
1916            approval in prop::sample::select(vec![ProactiveApproval::FollowMode, ProactiveApproval::AlwaysAsk, ProactiveApproval::Never]),
1917            origin in origin(),
1918        ) {
1919            let routed = route(approval, mode, &origin);
1920            if routed == Route::Schedule {
1921                prop_assert_eq!(mode, PartitionMode::Auto);
1922                prop_assert_eq!(approval, ProactiveApproval::FollowMode);
1923                prop_assert!(!origin.needs_a_person());
1924                prop_assert!(!origin.is_question());
1925            }
1926        }
1927    }
1928
1929    #[test]
1930    fn an_inbox_edit_changes_only_title_rationale_when_and_expiry() {
1931        let item = AgendaItem::new(
1932            "item-1",
1933            SubjectRef::human("alice"),
1934            "Old",
1935            "Because",
1936            AgendaOrigin::Consolidation,
1937            Utc::now(),
1938        );
1939        let edited = edit(
1940            item.clone(),
1941            &json!({
1942                "title": "New",
1943                "rationale": "Better reason",
1944                "when": { "at": "2026-10-24T07:00:00Z" },
1945                "origin": "user",
1946                "partition": "home",
1947                "subject": { "kind": "human", "id": "mallory" },
1948                "budget": { "maxCostMicroUsd": 1 }
1949            }),
1950        );
1951        assert_eq!((edited.title.as_str(), edited.rationale.as_str()), ("New", "Better reason"));
1952        assert!(matches!(edited.when, Some(Wake::At(_))));
1953        assert_eq!(edited.origin, item.origin, "an edit cannot launder the origin (K-I23)");
1954        assert_eq!(
1955            edit(item.clone(), &json!({ "title": "  " })).title,
1956            "Old",
1957            "a blank title is kept"
1958        );
1959        assert_eq!(
1960            (edited.partition, edited.subject, edited.budget),
1961            (item.partition, item.subject, item.budget)
1962        );
1963    }
1964
1965    #[test]
1966    fn the_prompt_names_the_item_and_its_steps() {
1967        let item = AgendaItem::new(
1968            "item-9",
1969            SubjectRef::human("alice"),
1970            "Re-run the tests",
1971            "The bump landed",
1972            AgendaOrigin::User,
1973            Utc::now(),
1974        )
1975        .with_plan(PlanRef::new(
1976            "sha256:1",
1977            vec![json!({"id": "1", "title": "Test", "instruction": "cargo test"})],
1978        ));
1979        let text = prompt(&item);
1980        assert!(
1981            text.contains("item item-9")
1982                && text.contains("Re-run the tests")
1983                && text.contains("1. Test: cargo test"),
1984            "{text}"
1985        );
1986        assert_eq!(request_id("item-9"), "agenda_item-9");
1987    }
1988}