Skip to main content

adk_kernel/
process.rs

1//! The process model (spec 3.2 §7.3).
2//!
3//! A process is a durable run (§6 D-2, K-I1): its id is the run id, its state is the run's
4//! [`RunState`], and `Waiting` is sleep. The kernel keeps what the run
5//! store does not in a side table, [`ProcessMeta`] in a [`ProcessStore`],
6//! and serves a live [`ProcessView`] of each process without `adk-eval` (§7.10, §13 Q4).
7//!
8//! | OS notion | Kernel mapping |
9//! |---|---|
10//! | Process states | `RunState::{Queued, Running, Waiting, Completed, Failed, Cancelled}`; `Waiting` is sleep |
11//! | Process tree | [`ProcessMeta::parent`]: the run that caused the process |
12//! | Time slice | The lease; a process yields at every model-call boundary |
13//! | `kill -TERM` / `kill -KILL` | `request_cancel` at the next checkpoint / lease revocation |
14//! | Zombie | A `Running` run whose lease expired; the next claim resumes it |
15//!
16//! [`ProcessTable`] is the view over `DurableRunStore` plus the side table, with
17//! `ps`, `kill`, `nice`, `suspend` and `resume`.
18
19use std::collections::BTreeMap;
20use std::fmt;
21use std::sync::Arc;
22use std::time::Duration;
23
24use adk_core::{
25    AdkError, DurableRunStore, Enqueued, ErrorCategory, ErrorComponent, NewRun, RunFilter,
26    RunRecord, RunState, SpendLedger,
27};
28use async_trait::async_trait;
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31use serde_json::json;
32
33use crate::audit;
34use crate::bus::KernelEvent;
35use crate::error::{KernelError, Result};
36use crate::partition::PartitionId;
37use crate::sched::QueueClass;
38use crate::stores::{ProcessFilter, ProcessStore, SpendScope};
39use crate::supervise::{ASLEEP_KEY_PREFIX, SPAWN_KEY_PREFIX, Supervision, transcript_counts};
40use crate::wake::WakeSet;
41
42/// A process as `ps` shows it: the run, the kernel's side table and the live view
43/// (spec 3.2 §7.3).
44///
45/// # Example
46///
47/// ```rust
48/// use adk_core::{NewRun, RunRecord};
49/// use adk_kernel::{Process, ProcessKind, ProcessMeta, QueueClass};
50///
51/// let run = RunRecord::queued("run-1", NewRun::new("background", "adk-rust", "alice", "adk-rust", serde_json::json!({})), chrono::Utc::now());
52/// let meta = ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal);
53/// let process = Process::new(run, meta);
54/// assert_eq!(process.meta.pid, process.run.run_id);
55/// assert_eq!(process.view.model_calls, 0);
56/// ```
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub struct Process {
61    /// The durable run (`adk-core/src/run_store.rs`).
62    pub run: RunRecord,
63    /// The kernel-owned side table, keyed by run id.
64    pub meta: ProcessMeta,
65    /// Live aggregates, served by the kernel without `adk-eval` (spec 3.2 §7.10).
66    pub view: ProcessView,
67}
68
69impl Process {
70    /// A process with an empty view.
71    pub fn new(run: RunRecord, meta: ProcessMeta) -> Self {
72        Self { run, meta, view: ProcessView::default() }
73    }
74
75    /// Sets the live view.
76    #[must_use]
77    pub fn with_view(mut self, view: ProcessView) -> Self {
78        self.view = view;
79        self
80    }
81}
82
83/// A process's live aggregates (spec 3.2 §7.3, §7.10, §13 Q4): what `ps` and `top` show,
84/// computed by sum and count over the kernel's records. Spend is in micro-USD, as
85/// `SpendLedger` counts it; the kernel attributes each charge to the run that made it and
86/// keeps daily totals per process ([`ProcessStore::spend`]).
87///
88/// # Example
89///
90/// ```rust
91/// use std::time::Duration;
92/// use adk_kernel::ProcessView;
93///
94/// let mut view = ProcessView::default();
95/// view.age = Duration::from_secs(90);
96/// view.model_calls = 3;
97/// let json = serde_json::to_value(&view).unwrap();
98/// assert_eq!(json["ageMs"], 90_000);
99/// assert_eq!(json["modelCalls"], 3);
100/// ```
101#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase")]
103#[non_exhaustive]
104pub struct ProcessView {
105    /// Since the last state change: a `Waiting` process's time asleep, a parked run's wait.
106    #[serde(rename = "ageMs", with = "crate::serde_util::millis")]
107    pub age: Duration,
108    /// Spend today (UTC), from the kernel's daily totals.
109    pub spend_today: u64,
110    /// Spend over the last seven UTC days, today included, from the kernel's daily totals.
111    #[serde(rename = "spend7d")]
112    pub spend_7d: u64,
113    /// A `Running` process's spend per minute.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub burn_rate: Option<f64>,
116    /// A `Running` process's spend by the end of the UTC day at its burn rate.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub projection: Option<u64>,
119    /// Model calls the process made.
120    pub model_calls: u64,
121    /// Tool calls the process made.
122    pub tool_calls: u64,
123    /// The loop guard's last verdict (spec 3.1 §7.13).
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub loop_guard: Option<String>,
126    /// A goal process's progress (spec 3.1 §7.11, spec 3.2 §10 HK3).
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub goal: Option<GoalProgress>,
129}
130
131/// Where a goal process stands (spec 3.2 §7.3, §10 HK3): iteration of max, spend, duration,
132/// and the last check's exit code and output tail.
133///
134/// The kernel cannot read harness types (§6 D-1), so the harness reports it through a
135/// [`ProgressSource`].
136///
137/// # Example
138///
139/// ```rust
140/// use std::time::Duration;
141/// use adk_kernel::GoalProgress;
142///
143/// let progress = GoalProgress::new(3, 10)
144///     .with_spend(12_500)
145///     .with_duration(Duration::from_secs(240))
146///     .with_last_check(1, "test result: FAILED. 1 passed; 2 failed");
147/// assert_eq!((progress.iteration, progress.max_iterations), (3, 10));
148/// assert_eq!(progress.last_check_exit, Some(1));
149/// ```
150#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152#[non_exhaustive]
153pub struct GoalProgress {
154    /// The current iteration.
155    pub iteration: u32,
156    /// The most iterations the goal may take.
157    pub max_iterations: u32,
158    /// Spend so far, in micro-USD, from the `SpendLedger`.
159    pub spend: u64,
160    /// How long the goal has run.
161    #[serde(rename = "durationMs", with = "crate::serde_util::millis")]
162    pub duration: Duration,
163    /// The last check's exit code.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub last_check_exit: Option<i32>,
166    /// The tail of the last check's output.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub last_check_tail: Option<String>,
169}
170
171impl GoalProgress {
172    /// Progress at `iteration` of `max_iterations`.
173    pub fn new(iteration: u32, max_iterations: u32) -> Self {
174        Self { iteration, max_iterations, ..Self::default() }
175    }
176
177    /// Sets the spend so far, in micro-USD.
178    #[must_use]
179    pub fn with_spend(mut self, micro_usd: u64) -> Self {
180        self.spend = micro_usd;
181        self
182    }
183
184    /// Sets how long the goal has run.
185    #[must_use]
186    pub fn with_duration(mut self, duration: Duration) -> Self {
187        self.duration = duration;
188        self
189    }
190
191    /// Sets the last check's exit code and output tail.
192    #[must_use]
193    pub fn with_last_check(mut self, exit: i32, tail: impl Into<String>) -> Self {
194        self.last_check_exit = Some(exit);
195        self.last_check_tail = Some(tail.into());
196        self
197    }
198}
199
200/// The kernel-owned side table of one process, keyed by run id (spec 3.2 §7.3, §6 D-2).
201///
202/// `RunRecord` already carries the run's principal and whether its user was authenticated;
203/// this holds only what the run store does not.
204///
205/// # Example
206///
207/// ```rust
208/// use adk_kernel::{PartitionId, ProcessKind, ProcessMeta, QueueClass, Suspension};
209///
210/// let meta = ProcessMeta::new("run-9", QueueClass::Background, ProcessKind::Triggered { source: "file".into() })
211///     .with_parent("run-1")
212///     .with_suspension(Suspension::Freeze)
213///     .with_label("repo", "adk-rust");
214/// assert_eq!(meta.partition, PartitionId::default());
215/// let json = serde_json::to_value(&meta).unwrap();
216/// assert_eq!(json["suspendedBy"], "freeze");
217/// assert_eq!(json["kind"]["triggered"]["source"], "file");
218/// ```
219#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
220#[serde(rename_all = "camelCase")]
221#[non_exhaustive]
222pub struct ProcessMeta {
223    /// The process id, equal to the run id.
224    pub pid: String,
225    /// The run that caused it: a proposal, a run-finished wake, a trigger.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub parent: Option<String>,
228    /// The partition it runs in.
229    #[serde(default)]
230    pub partition: PartitionId,
231    /// Its priority class (spec 3.2 §7.9).
232    pub queue: QueueClass,
233    /// What kind of work it is.
234    pub kind: ProcessKind,
235    /// Its wake set, while `Waiting`.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub wake: Option<WakeSet>,
238    /// Why it is suspended, while parked by a suspension.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub suspended_by: Option<Suspension>,
241    /// A suspension was requested and the run has not parked yet. Every replica's kernel
242    /// mirrors pending requests and suspends the runs its own workers lease, so a process
243    /// leased by another replica suspends too; the requester clears the flag once the run
244    /// parks (spec 3.2 §7.3).
245    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
246    pub suspend_requested: bool,
247    /// The agenda item it runs (spec 3.2 §7.5, phase 2).
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub agenda_item: Option<String>,
250    /// Free-form labels.
251    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
252    pub labels: BTreeMap<String, String>,
253}
254
255impl ProcessMeta {
256    /// The side table of process `pid` in the default partition, with no parent, wake set,
257    /// suspension, agenda item or labels.
258    pub fn new(pid: impl Into<String>, queue: QueueClass, kind: ProcessKind) -> Self {
259        Self {
260            pid: pid.into(),
261            parent: None,
262            partition: PartitionId::default(),
263            queue,
264            kind,
265            wake: None,
266            suspended_by: None,
267            suspend_requested: false,
268            agenda_item: None,
269            labels: BTreeMap::new(),
270        }
271    }
272
273    /// Sets the run that caused the process.
274    #[must_use]
275    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
276        self.parent = Some(parent.into());
277        self
278    }
279
280    /// Sets the partition.
281    #[must_use]
282    pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
283        self.partition = partition.into();
284        self
285    }
286
287    /// Sets the wake set.
288    #[must_use]
289    pub fn with_wake(mut self, wake: WakeSet) -> Self {
290        self.wake = Some(wake);
291        self
292    }
293
294    /// Sets why the process is suspended.
295    #[must_use]
296    pub fn with_suspension(mut self, suspension: Suspension) -> Self {
297        self.suspended_by = Some(suspension);
298        self
299    }
300
301    /// Sets the agenda item.
302    #[must_use]
303    pub fn with_agenda_item(mut self, item: impl Into<String>) -> Self {
304        self.agenda_item = Some(item.into());
305        self
306    }
307
308    /// Adds a label.
309    #[must_use]
310    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
311        self.labels.insert(key.into(), value.into());
312        self
313    }
314}
315
316/// What kind of work a process is (spec 3.2 §7.3).
317///
318/// # Example
319///
320/// ```rust
321/// use adk_kernel::ProcessKind;
322///
323/// assert_eq!(ProcessKind::Goal.to_string(), "goal");
324/// assert_eq!(ProcessKind::Triggered { source: "cron".into() }.to_string(), "triggered:cron");
325/// assert_eq!(serde_json::to_value(ProcessKind::Interactive).unwrap(), "interactive");
326/// ```
327#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
328#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
329#[non_exhaustive]
330pub enum ProcessKind {
331    /// A human turn.
332    Interactive,
333    /// A goal (spec 3.1 §7.11).
334    Goal,
335    /// A firing of a schedule.
336    Scheduled,
337    /// A run a wake source started.
338    Triggered {
339        /// The wake source's name.
340        source: String,
341    },
342    /// A follow-up the agent proposed (spec 3.2 §7.5, phase 2).
343    Proposed,
344    /// The kernel's own work.
345    Maintenance,
346    /// A background sub-agent's run, started by the process its
347    /// [`parent`](ProcessMeta::parent) names; its labels `subagent` and `subagent.name` carry
348    /// the sub-agent's id and name.
349    Subagent,
350}
351
352impl fmt::Display for ProcessKind {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        match self {
355            Self::Interactive => f.write_str("interactive"),
356            Self::Goal => f.write_str("goal"),
357            Self::Scheduled => f.write_str("scheduled"),
358            Self::Triggered { source } => write!(f, "triggered:{source}"),
359            Self::Proposed => f.write_str("proposed"),
360            Self::Maintenance => f.write_str("maintenance"),
361            Self::Subagent => f.write_str("subagent"),
362        }
363    }
364}
365
366/// Why a process is parked by a suspension rather than a wake set (spec 3.2 §7.3).
367///
368/// A suspended or freeze-parked process has no expiry of its own; `ps` shows its age
369/// (§7.4).
370///
371/// # Example
372///
373/// ```rust
374/// use adk_kernel::Suspension;
375///
376/// assert_eq!(serde_json::to_value(Suspension::Freeze).unwrap(), "freeze");
377/// assert_eq!(Suspension::Preempted { by: "run-3".into() }.to_string(), "preempted by run-3");
378/// ```
379#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
380#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
381#[non_exhaustive]
382pub enum Suspension {
383    /// `adk-rust suspend` or [`ProcessTable::suspend`]; resumes on `resume`.
384    Manual,
385    /// An interactive run preempted it (spec 3.2 §7.9, phase 2); resumes when that run
386    /// finishes.
387    Preempted {
388        /// The process that preempted it.
389        by: String,
390    },
391    /// A freeze parked it (`ParkReason::Frozen`, §10 S3); resumes only on `unfreeze`
392    /// (K-I21).
393    Freeze,
394    /// `Kernel::drain` parked it; resumes when the kernel starts again.
395    Drain,
396    /// A person paused the agent it runs (spec 3.3 §5.7); resumes only when the agent is
397    /// resumed, never on `unfreeze` or a drain's end (K-I21).
398    Paused {
399        /// The paused agent's id.
400        agent: String,
401    },
402}
403
404impl fmt::Display for Suspension {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        match self {
407            Self::Manual => f.write_str("manual"),
408            Self::Preempted { by } => write!(f, "preempted by {by}"),
409            Self::Freeze => f.write_str("freeze"),
410            Self::Drain => f.write_str("drain"),
411            Self::Paused { agent } => write!(f, "{agent} paused"),
412        }
413    }
414}
415
416/// What [`ProcessTable::spawn`] records beside the run it enqueues (spec 3.2 §7.3).
417///
418/// # Example
419///
420/// ```rust
421/// use std::time::Duration;
422/// use adk_kernel::{ProcessKind, ProcessSpec, Wake, WakeSet};
423///
424/// let spec = ProcessSpec::new(ProcessKind::Goal)
425///     .with_partition("work")
426///     .with_wake(WakeSet::any_of([Wake::FileChange {
427///         root: ".".into(),
428///         glob: "Cargo.lock".into(),
429///         debounce: Duration::from_millis(500),
430///     }]));
431/// assert!(spec.wake.is_some());
432/// ```
433#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
434#[serde(rename_all = "camelCase")]
435#[non_exhaustive]
436pub struct ProcessSpec {
437    /// What kind of work it is.
438    pub kind: ProcessKind,
439    /// The run that caused it.
440    #[serde(default, skip_serializing_if = "Option::is_none")]
441    pub parent: Option<String>,
442    /// The partition it runs in.
443    #[serde(default)]
444    pub partition: PartitionId,
445    /// When set, the process starts asleep on this wake set: it parks `Waiting` before its
446    /// first model call.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub wake: Option<WakeSet>,
449    /// The agenda item it runs (phase 2).
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub agenda_item: Option<String>,
452    /// Free-form labels.
453    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
454    pub labels: BTreeMap<String, String>,
455}
456
457impl ProcessSpec {
458    /// A spec of `kind` in the default partition that starts at once.
459    pub fn new(kind: ProcessKind) -> Self {
460        Self {
461            kind,
462            parent: None,
463            partition: PartitionId::default(),
464            wake: None,
465            agenda_item: None,
466            labels: BTreeMap::new(),
467        }
468    }
469
470    /// Sets the run that caused the process.
471    #[must_use]
472    pub fn with_parent(mut self, parent: impl Into<String>) -> Self {
473        self.parent = Some(parent.into());
474        self
475    }
476
477    /// Sets the partition.
478    #[must_use]
479    pub fn with_partition(mut self, partition: impl Into<PartitionId>) -> Self {
480        self.partition = partition.into();
481        self
482    }
483
484    /// Starts the process asleep on `wake`.
485    #[must_use]
486    pub fn with_wake(mut self, wake: WakeSet) -> Self {
487        self.wake = Some(wake);
488        self
489    }
490
491    /// Sets the agenda item.
492    #[must_use]
493    pub fn with_agenda_item(mut self, item: impl Into<String>) -> Self {
494        self.agenda_item = Some(item.into());
495        self
496    }
497
498    /// Adds a label.
499    #[must_use]
500    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
501        self.labels.insert(key.into(), value.into());
502        self
503    }
504}
505
506/// What a session's runs have used so far, as the hosted agent counts it (spec 3.2 §7.3,
507/// §7.10): model calls, tool calls, cost in micro-USD, total tokens and the usage per
508/// [`UsageUnit`](adk_core::UsageUnit) (`BudgetTracker::units`).
509///
510/// The counter is monotonic for the life of the agent: the kernel attributes the
511/// difference between two readings to the process running in the session, so a process
512/// sees only what it used.
513///
514/// # Example
515///
516/// ```rust
517/// use adk_core::{UsageUnit, UsageVector};
518/// use adk_kernel::RunUsage;
519///
520/// let usage = RunUsage::new(3, 2, 12_500)
521///     .with_total_tokens(4_000)
522///     .with_units(UsageVector::new().with(UsageUnit::AudioMillis, 90_000));
523/// assert_eq!(usage.cost_micro_usd, 12_500);
524/// assert_eq!(usage.units.get(UsageUnit::AudioMillis), 90_000);
525/// ```
526#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
527#[serde(rename_all = "camelCase")]
528#[non_exhaustive]
529pub struct RunUsage {
530    /// Model calls.
531    pub model_calls: u64,
532    /// Tool calls.
533    pub tool_calls: u64,
534    /// Cost, in micro-USD.
535    pub cost_micro_usd: u64,
536    /// Input plus output tokens.
537    #[serde(default)]
538    pub total_tokens: u64,
539    /// Usage per unit.
540    #[serde(default)]
541    pub units: adk_core::UsageVector,
542}
543
544impl RunUsage {
545    /// Usage of `model_calls`, `tool_calls` and `cost_micro_usd`.
546    pub fn new(model_calls: u64, tool_calls: u64, cost_micro_usd: u64) -> Self {
547        Self { model_calls, tool_calls, cost_micro_usd, ..Self::default() }
548    }
549
550    /// Sets the total tokens.
551    #[must_use]
552    pub fn with_total_tokens(mut self, total_tokens: u64) -> Self {
553        self.total_tokens = total_tokens;
554        self
555    }
556
557    /// Sets the usage per unit.
558    #[must_use]
559    pub fn with_units(mut self, units: adk_core::UsageVector) -> Self {
560        self.units = units;
561        self
562    }
563}
564
565/// Reports what only the hosted agent knows about a process: a goal's progress, the loop
566/// guard's verdict and the session's usage (spec 3.2 §7.3, §10 HK3).
567///
568/// `adk-kernel` depends on no harness type (§6 D-1); the `kernel` feature of `adk-harness`
569/// implements this over its goal store, loop guard and spend accounts and registers it with
570/// [`KernelBuilder::progress_source`](crate::KernelBuilder::progress_source). Every method
571/// has a default that reports nothing.
572///
573/// # Example
574///
575/// ```rust
576/// use adk_core::RunRecord;
577/// use adk_kernel::{GoalProgress, ProgressSource};
578/// use async_trait::async_trait;
579///
580/// struct FixedProgress;
581///
582/// #[async_trait]
583/// impl ProgressSource for FixedProgress {
584///     async fn goal_progress(&self, _run: &RunRecord) -> adk_kernel::Result<Option<GoalProgress>> {
585///         Ok(Some(GoalProgress::new(2, 10)))
586///     }
587/// }
588/// ```
589#[async_trait]
590pub trait ProgressSource: Send + Sync {
591    /// The progress of the goal `run` executes, or `None` when it runs no goal.
592    ///
593    /// # Errors
594    ///
595    /// Returns the source's store error; the view then omits the goal.
596    async fn goal_progress(&self, _run: &RunRecord) -> Result<Option<GoalProgress>> {
597        Ok(None)
598    }
599
600    /// The loop guard's last verdict for `run`, or `None` when it has none.
601    ///
602    /// # Errors
603    ///
604    /// Returns the source's store error; the view then omits the verdict.
605    async fn loop_guard(&self, _run: &RunRecord) -> Result<Option<String>> {
606        Ok(None)
607    }
608
609    /// The [`RunUsage`] counter of the session `run` continues, or `None` when the agent
610    /// keeps none. The kernel reads it when a claim starts and on every scheduler tick, and
611    /// attributes the cost between readings to the process ([`ProcessStore::add_spend`]).
612    /// For a claim this returns `None` for, the kernel counts the usage the agent turn's
613    /// events carry instead, so a plain `Runner` is accounted without a source.
614    ///
615    /// # Errors
616    ///
617    /// Returns the source's error; the kernel then attributes nothing for that reading.
618    async fn usage(&self, _run: &RunRecord) -> Result<Option<RunUsage>> {
619        Ok(None)
620    }
621
622    /// Called by [`Kernel::start`](crate::Kernel::start) with a handle on the kernel's
623    /// processes, so a source that detects a condition that should park a process — a goal
624    /// that stopped making progress (spec 3.2 §7.3, §10 HK3) — can suspend it at once.
625    fn attach(&self, _processes: ProcessHandle) {}
626
627    /// Called by [`Kernel::start`](crate::Kernel::start) with the kernel's ledger when it
628    /// keeps one (spec 3.2 §7.10, feature `proc`), so the hosted runtime writes its own
629    /// activity: the harness writes its tool events and audit records through it.
630    #[cfg(feature = "proc")]
631    fn attach_ledger(&self, _ledger: Arc<dyn crate::proc::LedgerSink>) {}
632}
633
634/// A handle on a running kernel's processes that does not keep the kernel alive, given to
635/// a [`ProgressSource`] by [`ProgressSource::attach`] (spec 3.2 §7.3).
636///
637/// # Example
638///
639/// ```rust
640/// use adk_kernel::{ProcessHandle, ProgressSource};
641/// use std::sync::OnceLock;
642///
643/// #[derive(Default)]
644/// struct Stalls(OnceLock<ProcessHandle>);
645///
646/// impl ProgressSource for Stalls {
647///     fn attach(&self, processes: ProcessHandle) {
648///         let _ = self.0.set(processes);
649///     }
650/// }
651/// ```
652#[derive(Clone)]
653pub struct ProcessHandle {
654    sup: std::sync::Weak<Supervision>,
655}
656
657impl fmt::Debug for ProcessHandle {
658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659        f.debug_struct("ProcessHandle").field("alive", &(self.sup.strong_count() > 0)).finish()
660    }
661}
662
663impl ProcessHandle {
664    pub(crate) fn new(sup: &Arc<Supervision>) -> Self {
665        Self { sup: Arc::downgrade(sup) }
666    }
667
668    /// Suspends `pid` as [`ProcessTable::suspend`] does: a running process parks at its
669    /// next model-call boundary with [`Suspension::Manual`]. Returns `false` when the
670    /// kernel is gone.
671    ///
672    /// # Errors
673    ///
674    /// Returns the errors of [`ProcessTable::suspend`].
675    pub async fn suspend(&self, pid: &str) -> Result<bool> {
676        let Some(sup) = self.sup.upgrade() else { return Ok(false) };
677        ProcessTable::supervised(sup, None).suspend(pid).await?;
678        Ok(true)
679    }
680}
681
682/// The process table: a view over `DurableRunStore` plus the kernel's
683/// [`ProcessStore`] (spec 3.2 §7.3).
684///
685/// [`Kernel::processes`](crate::Kernel::processes) returns the kernel's table, which also
686/// lists runs of the kernel's queues the side table has no row for yet, reaches the
687/// kernel's workers for `suspend`, and reads transcripts for the call counts; a table built
688/// with [`new`](Self::new) reads and writes the stores only.
689///
690/// # Example
691///
692/// ```rust,no_run
693/// use std::sync::Arc;
694/// use adk_core::InMemoryRunStore;
695/// use adk_kernel::{InMemoryProcessStore, ProcessFilter, ProcessTable};
696///
697/// # async fn example() -> adk_kernel::Result<()> {
698/// let table = ProcessTable::new(Arc::new(InMemoryRunStore::new()), Arc::new(InMemoryProcessStore::new()));
699/// for process in table.ps(ProcessFilter::default()).await? {
700///     println!("{} {:?} {}", process.meta.pid, process.run.state, process.meta.kind);
701/// }
702/// # Ok(())
703/// # }
704/// ```
705#[derive(Clone)]
706pub struct ProcessTable {
707    runs: Arc<dyn DurableRunStore>,
708    processes: Arc<dyn ProcessStore>,
709    spend: Option<Arc<dyn SpendLedger>>,
710    progress: Option<Arc<dyn ProgressSource>>,
711    sup: Option<Arc<Supervision>>,
712}
713
714impl fmt::Debug for ProcessTable {
715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716        f.debug_struct("ProcessTable")
717            .field("spend", &self.spend.is_some())
718            .field("progress", &self.progress.is_some())
719            .field("supervised", &self.sup.is_some())
720            .finish_non_exhaustive()
721    }
722}
723
724fn not_found(pid: &str) -> KernelError {
725    KernelError::NotFound { pid: pid.to_string() }
726}
727
728impl ProcessTable {
729    /// A table over `runs` and `processes`.
730    pub fn new(runs: Arc<dyn DurableRunStore>, processes: Arc<dyn ProcessStore>) -> Self {
731        Self { runs, processes, spend: None, progress: None, sup: None }
732    }
733
734    /// The kernel's table: the stores, progress and workers of `sup`.
735    pub(crate) fn supervised(sup: Arc<Supervision>, spend: Option<Arc<dyn SpendLedger>>) -> Self {
736        Self {
737            runs: Arc::clone(&sup.runs),
738            processes: Arc::clone(&sup.processes),
739            spend,
740            progress: sup.progress.clone(),
741            sup: Some(sup),
742        }
743    }
744
745    /// The ledger the processes' spend is budgeted against. The view reads the kernel's
746    /// own daily totals ([`ProcessStore::spend`]) rather than this ledger, which has no
747    /// per-run dimension.
748    #[must_use]
749    pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
750        self.spend = Some(ledger);
751        self
752    }
753
754    /// Reads goal progress, loop-guard verdicts and usage from `source` for each view.
755    #[must_use]
756    pub fn with_progress_source(mut self, source: Arc<dyn ProgressSource>) -> Self {
757        self.progress = Some(source);
758        self
759    }
760
761    /// The run store the table reads.
762    pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
763        &self.runs
764    }
765
766    /// The side table the table reads.
767    pub fn process_store(&self) -> &Arc<dyn ProcessStore> {
768        &self.processes
769    }
770
771    /// The kernel's clock for a kernel's table, the system clock otherwise.
772    fn now(&self) -> DateTime<Utc> {
773        self.sup.as_ref().map_or_else(Utc::now, |sup| sup.clock.now())
774    }
775
776    /// Lists the processes `filter` selects, each with its live [`ProcessView`]; `Waiting`
777    /// processes show their age (spec 3.2 §7.3, §8.1 `adk-rust ps`). Processes are ordered
778    /// by creation. A side-table row whose run the run store pruned is deleted. The
779    /// kernel's `kernel.wake` runs, which route wake events, are not listed.
780    ///
781    /// # Errors
782    ///
783    /// Returns [`KernelError::Store`] or [`KernelError::Core`] when a store fails.
784    pub async fn ps(&self, filter: ProcessFilter) -> Result<Vec<Process>> {
785        let mut meta_filter = filter.clone();
786        meta_filter.states = Vec::new();
787        meta_filter.limit = None;
788        let mut rows: BTreeMap<String, (RunRecord, ProcessMeta)> = BTreeMap::new();
789        for meta in self.processes.list(&meta_filter).await? {
790            match self.runs.get(&meta.pid).await? {
791                Some(run) => {
792                    rows.insert(meta.pid.clone(), (run, meta));
793                }
794                None => {
795                    self.processes.delete(&meta.pid).await?;
796                }
797            }
798        }
799        if let Some(sup) = &self.sup {
800            for queue in &sup.queues {
801                let mut runs = RunFilter::default().queue(queue.as_str());
802                if !filter.states.is_empty() {
803                    runs = runs.states(filter.states.iter().copied());
804                }
805                for run in self.runs.list(runs).await? {
806                    if rows.contains_key(&run.run_id) {
807                        continue;
808                    }
809                    let meta = sup.inferred_meta(&run);
810                    if filter.matches(&meta) {
811                        rows.insert(run.run_id.clone(), (run, meta));
812                    }
813                }
814            }
815        }
816        let mut rows: Vec<(RunRecord, ProcessMeta)> = rows
817            .into_values()
818            .filter(|(run, _)| run.target != crate::wake::KERNEL_WAKE_TARGET)
819            .filter(|(run, _)| filter.states.is_empty() || filter.states.contains(&run.state))
820            .filter(|(run, _)| filter.target.as_ref().is_none_or(|target| *target == run.target))
821            .collect();
822        rows.sort_by(|(a, _), (b, _)| {
823            a.created_at.cmp(&b.created_at).then(a.run_id.cmp(&b.run_id))
824        });
825        if let Some(limit) = filter.limit {
826            rows.truncate(limit);
827        }
828        let now = self.now();
829        let mut processes = Vec::with_capacity(rows.len());
830        for (run, meta) in rows {
831            let view = self.view(&run, &meta, now).await;
832            processes.push(Process { run, meta, view });
833        }
834        Ok(processes)
835    }
836
837    /// The process `pid` with its live view, or `None` when no run has that id.
838    ///
839    /// # Errors
840    ///
841    /// Returns [`KernelError::Store`] or [`KernelError::Core`] when a store fails.
842    pub async fn get(&self, pid: &str) -> Result<Option<Process>> {
843        let Some(run) = self.runs.get(pid).await? else {
844            return Ok(None);
845        };
846        let meta = self.meta(&run).await?;
847        let view = self.view(&run, &meta, self.now()).await;
848        Ok(Some(Process { run, meta, view }))
849    }
850
851    /// Enqueues `run` and records its process (spec 3.2 §7.3, §7.4). The process's queue is
852    /// the run's queue. With [`ProcessSpec::wake`] the process starts asleep: it parks
853    /// `Waiting` on its wake set before its first model call and holds no lease (K-I2).
854    ///
855    /// The run's idempotency key is prefixed `kernel:asleep:` for a sleeper and
856    /// `kernel:spawn:` otherwise, before the caller's key or a generated one: the prefix
857    /// carries the sleep intent to the worker's claim, so a sleeper never depends on its
858    /// side-table row being written first. A key already held in the queue returns the
859    /// existing process.
860    ///
861    /// # Errors
862    ///
863    /// Returns [`KernelError::Frozen`] while the kernel is frozen, [`KernelError::Config`]
864    /// when `run`'s target is a partition agent of a partition other than `spec.partition`,
865    /// or `run` continues a session another partition's agent ran (spec 3.2 §7.8, K-I15),
866    /// [`KernelError::Quota`] when the partition already queues its `max_queued` processes
867    /// (spec 3.2 §7.9), the run store's error when `run` is invalid or its concurrency key
868    /// refuses it, or a store error. A spawn of a partition agent's target in the default
869    /// partition runs in the target's partition.
870    pub async fn spawn(&self, mut run: NewRun, mut spec: ProcessSpec) -> Result<Process> {
871        self.refuse_while_frozen()?;
872        if let Some(sup) = &self.sup {
873            // A paused or removed agent takes no work; an added agent runs only in its area
874            // (spec 3.3 §5.7, K-I15).
875            if let Some(agent) = sup.targets.admit_spawn(&run.target).await? {
876                // A replica that has not built it yet hands its claim back rather than
877                // failing it (spec 3.3 §10 S4).
878                sup.targets.expect(&agent.id);
879                if spec.partition.as_str() == PartitionId::DEFAULT {
880                    spec.partition = agent.area;
881                } else if spec.partition != agent.area {
882                    return Err(KernelError::Config {
883                        reason: format!(
884                            "{} works in area `{}`, so a process of `{}` cannot run it \
885                             (spec 3.2 K-I15)",
886                            agent.display_name, agent.area, spec.partition
887                        ),
888                    });
889                }
890            }
891            // A partition agent's target runs only its own partition (spec 3.2 §7.8, K-I15).
892            spec.partition = sup.partition_for(&run.target, spec.partition)?;
893            sup.check_session_partition(&run, &spec.partition).await?;
894            if let Some(max) = sup.quotas_of(&spec.partition).await.max_queued {
895                let queued = sup.queued_in(&spec.partition).await;
896                if queued >= max {
897                    return Err(KernelError::Quota {
898                        partition: spec.partition.to_string(),
899                        reason: format!(
900                            "{queued} processes queued, the most max_queued ({max}) allows"
901                        ),
902                    });
903                }
904            }
905        }
906        let asleep = spec.wake.is_some();
907        // The key carries the sleep intent to the claim, so a sleeper parks before its first
908        // model call however long its row below takes to write; the caller's key follows
909        // the prefix, so a repeated spawn still finds its run.
910        let prefix = if asleep { ASLEEP_KEY_PREFIX } else { SPAWN_KEY_PREFIX };
911        let key = run.idempotency_key.take().unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
912        run.idempotency_key = Some(format!("{prefix}{key}"));
913        let record = match self.runs.enqueue(run).await? {
914            Enqueued::Created(record) => record,
915            Enqueued::Existing(record) => {
916                let meta = self.meta(&record).await?;
917                let view = self.view(&record, &meta, self.now()).await;
918                return Ok(Process { run: record, meta, view });
919            }
920            Enqueued::Rejected { blocking_run_id } => {
921                return Err(AdkError::new(
922                    ErrorComponent::Server,
923                    ErrorCategory::Conflict,
924                    crate::error::SPAWN_REJECTED_CODE,
925                    format!(
926                        "run {blocking_run_id} holds the concurrency key and the run refuses to \
927                         queue behind it; wait for it to finish or enqueue with OnConflict::Enqueue"
928                    ),
929                )
930                .into());
931            }
932        };
933        let mut labels = spec.labels;
934        // A cron sleeper recurs: its successor sleeps on the same set (spec 3.2 §8.1).
935        if let Some(wake) = &spec.wake
936            && wake.any_of.iter().any(|wake| matches!(wake, crate::wake::Wake::Cron { .. }))
937        {
938            labels.insert(crate::supervise::RECUR_LABEL.to_string(), serde_json::to_string(wake)?);
939        }
940        let meta = ProcessMeta {
941            pid: record.run_id.clone(),
942            parent: spec.parent,
943            partition: spec.partition,
944            queue: QueueClass::from_name(&record.queue),
945            kind: spec.kind,
946            wake: spec.wake,
947            suspended_by: None,
948            suspend_requested: asleep,
949            agenda_item: spec.agenda_item,
950            labels,
951        };
952        self.processes.put(meta.clone()).await?;
953        if let Some(sup) = &self.sup {
954            if asleep {
955                sup.roots_changed.notify_one();
956            }
957            sup.publish(KernelEvent::Process {
958                pid: meta.pid.clone(),
959                from: RunState::Queued,
960                to: RunState::Queued,
961                reason: Some(if asleep { "spawned asleep" } else { "spawned" }.to_string()),
962            });
963            sup.record(
964                audit::PROCESS_SPAWNED,
965                sup.actor_for(Some(&record)),
966                Supervision::process_fields(&meta, None, None),
967            )
968            .await;
969            sup.nudge();
970        }
971        let view = self.view(&record, &meta, self.now()).await;
972        Ok(Process { run: record, meta, view })
973    }
974
975    /// Kills `pid` through `DurableRunStore::request_cancel`: cooperative at the next
976    /// checkpoint, never leaving a lease held (K-I5); a `Queued` or `Waiting` process,
977    /// freeze-parked ones included, is `Cancelled` at once (K-I21).
978    ///
979    /// # Errors
980    ///
981    /// Returns [`KernelError::NotFound`] for an unknown `pid`, [`KernelError::InvalidState`]
982    /// for a finished one, or a store error.
983    pub async fn kill(&self, pid: &str, reason: &str) -> Result<()> {
984        let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
985        if run.state.is_terminal() {
986            return Err(KernelError::InvalidState {
987                pid: pid.to_string(),
988                state: run.state,
989                action: "killed",
990            });
991        }
992        self.runs.request_cancel(pid).await?;
993        let meta = self.meta(&run).await?;
994        if run.state != RunState::Running {
995            // Cancelled at once, so it will not sleep again; a running one clears its wake
996            // set when its attempt finishes.
997            let mut cleared = meta.clone();
998            if cleared.wake.take().is_some() {
999                self.processes.put(cleared).await?;
1000                if let Some(sup) = &self.sup {
1001                    sup.roots_changed.notify_one();
1002                }
1003            }
1004        }
1005        if let Some(sup) = &self.sup {
1006            sup.heartbeat_now();
1007            if run.state != RunState::Running {
1008                sup.publish(KernelEvent::Process {
1009                    pid: pid.to_string(),
1010                    from: run.state,
1011                    to: RunState::Cancelled,
1012                    reason: Some(reason.to_string()),
1013                });
1014            }
1015            sup.record(
1016                audit::PROCESS_KILLED,
1017                sup.actor_for(Some(&run)),
1018                Supervision::process_fields(&meta, Some(reason), None),
1019            )
1020            .await;
1021        }
1022        Ok(())
1023    }
1024
1025    /// Moves a `Queued` run or a sleeping process (`Waiting` with a wake set) to `queue`
1026    /// (spec 3.2 §6 D-5) and returns the moved process.
1027    ///
1028    /// The run store has no queue change, so `nice` cancels the run and enqueues it again on
1029    /// `queue`, in the same session, with the same wake set: **the pid changes**. The new
1030    /// process's [`ProcessMeta::parent`] is the old pid. A sleeper whose turn already reached
1031    /// the session continues it with an empty user turn, as a resumed run does, so its
1032    /// prompt is not sent twice.
1033    ///
1034    /// # Errors
1035    ///
1036    /// Returns [`KernelError::NotFound`] for an unknown `pid`; [`KernelError::InvalidState`]
1037    /// for a `Running` process (suspend it first), a suspended or approval-parked one, or a
1038    /// finished one; or a store error.
1039    pub async fn nice(&self, pid: &str, queue: QueueClass) -> Result<Process> {
1040        let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
1041        let meta = self.meta(&run).await?;
1042        let movable = match run.state {
1043            RunState::Queued => true,
1044            RunState::Waiting => meta.wake.is_some() && meta.suspended_by.is_none(),
1045            _ => false,
1046        };
1047        if !movable {
1048            return Err(KernelError::InvalidState {
1049                pid: pid.to_string(),
1050                state: run.state,
1051                action: "moved to another queue (only a queued or sleeping process moves; \
1052                         suspend a running one first)",
1053            });
1054        }
1055        if meta.queue == queue {
1056            let view = self.view(&run, &meta, self.now()).await;
1057            return Ok(Process { run, meta, view });
1058        }
1059        // Checked before the cancel, so a freeze never leaves the process cancelled and not
1060        // re-enqueued.
1061        self.refuse_while_frozen()?;
1062        self.runs.request_cancel(pid).await?;
1063        if meta.wake.is_some() {
1064            let mut cleared = meta.clone();
1065            cleared.wake = None;
1066            self.processes.put(cleared).await?;
1067        }
1068        let input = if run.checkpoint.is_some() {
1069            serde_json::Value::String(String::new())
1070        } else {
1071            run.input.clone()
1072        };
1073        let mut next = NewRun::new(
1074            queue.as_str(),
1075            run.app_name.clone(),
1076            run.user_id.clone(),
1077            run.target.clone(),
1078            input,
1079        )
1080        .with_max_attempts(run.max_attempts);
1081        next.session_id = Some(crate::supervise::run_session(&run));
1082        if let Some(key) = &run.concurrency_key {
1083            next = next.with_concurrency_key(key.clone(), run.on_conflict);
1084        }
1085        next.not_before = run.not_before;
1086        next.principal = run.principal.clone();
1087        next.authenticated = run.authenticated;
1088        let mut spec = ProcessSpec::new(meta.kind.clone()).with_parent(pid);
1089        spec.partition = meta.partition.clone();
1090        spec.wake = meta.wake.clone();
1091        spec.agenda_item = meta.agenda_item.clone();
1092        spec.labels = meta.labels.clone();
1093        let moved = self.spawn(next, spec).await?;
1094        if let Some(sup) = &self.sup {
1095            sup.record(
1096                audit::PROCESS_REQUEUED,
1097                sup.actor_for(Some(&run)),
1098                json!({
1099                    "pid": moved.meta.pid,
1100                    "parent": pid,
1101                    "partition": moved.meta.partition,
1102                    "queue": queue,
1103                    "kind": moved.meta.kind,
1104                    "from": meta.queue,
1105                }),
1106            )
1107            .await;
1108        }
1109        Ok(moved)
1110    }
1111
1112    /// Suspends `pid` through the worker's suspend path (§10 S1): it stops at its next
1113    /// model-call boundary and parks `Waiting` with [`Suspension::Manual`]; a `Queued` or
1114    /// `Waiting` process is marked suspended where it is.
1115    ///
1116    /// A `Running` process gets [`ProcessMeta::suspend_requested`]: every replica's kernel
1117    /// mirrors pending requests every 250 ms and suspends the runs its own workers lease, so
1118    /// the request reaches the replica that holds the lease without a run-store change; the
1119    /// flag is cleared once the run parks.
1120    ///
1121    /// # Errors
1122    ///
1123    /// Returns [`KernelError::NotFound`] for an unknown `pid`, [`KernelError::InvalidState`]
1124    /// for a finished one, or a store error.
1125    pub async fn suspend(&self, pid: &str) -> Result<()> {
1126        self.suspend_marked(pid, |by| {
1127            by.get_or_insert(Suspension::Manual);
1128        })
1129        .await
1130    }
1131
1132    /// Suspends `pid` as [`suspend`](Self::suspend) does, marked as `suspension` unless a
1133    /// person suspended it by hand: a paused agent's processes are marked
1134    /// [`Suspension::Paused`], so only its resume wakes them (spec 3.3 §5.7, K-I21).
1135    pub(crate) async fn suspend_as(&self, pid: &str, suspension: Suspension) -> Result<()> {
1136        self.suspend_marked(pid, |by| {
1137            if *by != Some(Suspension::Manual) {
1138                *by = Some(suspension);
1139            }
1140        })
1141        .await
1142    }
1143
1144    async fn suspend_marked(
1145        &self,
1146        pid: &str,
1147        mark: impl FnOnce(&mut Option<Suspension>),
1148    ) -> Result<()> {
1149        let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
1150        if run.state.is_terminal() {
1151            return Err(KernelError::InvalidState {
1152                pid: pid.to_string(),
1153                state: run.state,
1154                action: "suspended",
1155            });
1156        }
1157        let mut meta = self.meta(&run).await?;
1158        mark(&mut meta.suspended_by);
1159        // A running or queued process parks at its next model-call boundary; a waiting
1160        // one is already parked.
1161        meta.suspend_requested = run.state != RunState::Waiting;
1162        self.processes.put(meta.clone()).await?;
1163        match (run.state, &self.sup) {
1164            (RunState::Running, Some(sup)) => {
1165                sup.suspend_local(pid);
1166            }
1167            (RunState::Waiting, Some(sup)) => {
1168                sup.record(
1169                    audit::PROCESS_SUSPENDED,
1170                    sup.actor_for(Some(&run)),
1171                    Supervision::process_fields(&meta, Some("suspended"), None),
1172                )
1173                .await;
1174            }
1175            _ => {}
1176        }
1177        Ok(())
1178    }
1179
1180    /// Resumes a suspended or sleeping `pid` through `DurableRunStore::wake`. A process a
1181    /// freeze parked resumes only on `unfreeze` (K-I21).
1182    ///
1183    /// # Errors
1184    ///
1185    /// Returns [`KernelError::NotFound`] for an unknown `pid`, [`KernelError::InvalidState`]
1186    /// when it is not `Waiting` or was parked by a freeze, or a store error.
1187    pub async fn resume(&self, pid: &str) -> Result<()> {
1188        let run = self.runs.get(pid).await?.ok_or_else(|| not_found(pid))?;
1189        let mut meta = self.meta(&run).await?;
1190        let queued_and_suspended = run.state == RunState::Queued && meta.suspend_requested;
1191        if run.state != RunState::Waiting && !queued_and_suspended {
1192            return Err(KernelError::InvalidState {
1193                pid: pid.to_string(),
1194                state: run.state,
1195                action: "resumed (it is not suspended or asleep)",
1196            });
1197        }
1198        if meta.suspended_by == Some(Suspension::Freeze) {
1199            return Err(KernelError::InvalidState {
1200                pid: pid.to_string(),
1201                state: run.state,
1202                action: "resumed before the freeze is lifted; run `adk-rust unfreeze`",
1203            });
1204        }
1205        meta.suspended_by = None;
1206        meta.suspend_requested = false;
1207        meta.wake = None;
1208        // Written before the wake, so the claim that follows reads no suspension to honour.
1209        self.processes.put(meta.clone()).await?;
1210        if run.state == RunState::Waiting {
1211            self.runs.wake(pid).await?;
1212        }
1213        if let Some(sup) = &self.sup {
1214            sup.record(
1215                audit::PROCESS_RESUMED,
1216                sup.actor_for(Some(&run)),
1217                Supervision::process_fields(&meta, Some("resumed"), None),
1218            )
1219            .await;
1220            sup.nudge();
1221        }
1222        Ok(())
1223    }
1224
1225    /// [`KernelError::Frozen`] while the kernel's control refuses work.
1226    fn refuse_while_frozen(&self) -> Result<()> {
1227        match &self.sup {
1228            Some(sup) => sup.governance.check().map_err(|error| KernelError::Frozen {
1229                reason: sup.governance.reason().unwrap_or(error.message),
1230            }),
1231            None => Ok(()),
1232        }
1233    }
1234
1235    /// The stored side table of `run`, or the inferred one when nothing recorded it.
1236    async fn meta(&self, run: &RunRecord) -> Result<ProcessMeta> {
1237        let inferred = || match &self.sup {
1238            Some(sup) => sup.inferred_meta(run),
1239            None => Supervision::infer_meta(run),
1240        };
1241        Ok(self.processes.get(&run.run_id).await?.unwrap_or_else(inferred))
1242    }
1243
1244    /// The live view of one process (spec 3.2 §7.3, §7.10). A part a store cannot answer is
1245    /// left at its default rather than failing the listing.
1246    async fn view(&self, run: &RunRecord, meta: &ProcessMeta, now: DateTime<Utc>) -> ProcessView {
1247        let mut view = ProcessView::default();
1248        let local = self.sup.as_ref().and_then(|sup| {
1249            sup.local.lock().unwrap_or_else(|e| e.into_inner()).get(&run.run_id).cloned()
1250        });
1251        let since = match (run.state, &local) {
1252            (RunState::Running, Some(local)) => local.claimed_at,
1253            _ => run.updated_at,
1254        };
1255        view.age = (now - since).to_std().unwrap_or_default();
1256        let today = now.date_naive();
1257        let scope = SpendScope::Process(run.run_id.clone());
1258        match self.processes.spend(&scope, today, today).await {
1259            Ok(spend) => view.spend_today = spend,
1260            Err(error) => {
1261                tracing::debug!(process.pid = %run.run_id, error = %error, "could not read today's spend")
1262            }
1263        }
1264        match self.processes.spend(&scope, today - chrono::Days::new(6), today).await {
1265            Ok(spend) => view.spend_7d = spend,
1266            Err(error) => {
1267                tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the week's spend")
1268            }
1269        }
1270        if run.state == RunState::Running
1271            && let Some(local) = &local
1272            && let (Some((first_at, first)), Some((last_at, last))) =
1273                (local.samples.front(), local.samples.back())
1274        {
1275            let minutes = (*last_at - *first_at).num_milliseconds() as f64 / 60_000.0;
1276            if minutes > 0.0 {
1277                let rate = (last.saturating_sub(*first)) as f64 / minutes;
1278                view.burn_rate = Some(rate);
1279                let end_of_day =
1280                    (today + chrono::Days::new(1)).and_time(chrono::NaiveTime::MIN).and_utc();
1281                let remaining = (end_of_day - now).num_milliseconds().max(0) as f64 / 60_000.0;
1282                view.projection = Some(view.spend_today + (rate * remaining) as u64);
1283            }
1284        }
1285        let sessions = self.sup.as_ref().and_then(|sup| sup.sessions.clone());
1286        if let Some(sessions) = sessions
1287            && let Some(counts) = transcript_counts(sessions.as_ref(), run).await
1288        {
1289            view.model_calls = counts.model_calls;
1290            view.tool_calls = counts.tool_calls;
1291        } else if let Some(local) = &local
1292            && let Some(last) = &local.last
1293        {
1294            let base = local.baseline.clone().unwrap_or_default();
1295            view.model_calls = last.model_calls.saturating_sub(base.model_calls);
1296            view.tool_calls = last.tool_calls.saturating_sub(base.tool_calls);
1297        } else if let Some(local) = &local {
1298            view.model_calls = local.turn.model_calls;
1299            view.tool_calls = local.turn.tool_calls;
1300        }
1301        // A partition's own source answers for its processes (spec 3.2 §7.8).
1302        let progress = self
1303            .sup
1304            .as_ref()
1305            .and_then(|sup| {
1306                sup.targets
1307                    .progress_of(&run.target)
1308                    .or_else(|| sup.partition_progress.get(&meta.partition).cloned())
1309            })
1310            .or_else(|| self.progress.clone());
1311        if let Some(progress) = progress {
1312            match progress.loop_guard(run).await {
1313                Ok(verdict) => view.loop_guard = verdict,
1314                Err(error) => {
1315                    tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the loop guard")
1316                }
1317            }
1318            if meta.kind == ProcessKind::Goal || run.target == crate::supervise::GOAL_TARGET {
1319                match progress.goal_progress(run).await {
1320                    Ok(Some(mut goal)) => {
1321                        if goal.spend == 0 {
1322                            let from = run.created_at.date_naive();
1323                            goal.spend =
1324                                self.processes.spend(&scope, from, today).await.unwrap_or(0);
1325                        }
1326                        view.goal = Some(goal);
1327                    }
1328                    Ok(None) => {}
1329                    Err(error) => {
1330                        tracing::debug!(process.pid = %run.run_id, error = %error, "could not read the goal's progress")
1331                    }
1332                }
1333            }
1334        }
1335        view
1336    }
1337}