Skip to main content

adk_kernel/
consolidation.rs

1//! The consolidation tick (spec 3.2 §7.5, §13 Q1, Q12).
2//!
3//! The tick is a `Maintenance` process on the distiller's model that distils the sessions
4//! the spec 3.1 distiller never reached and consolidates a partition's `Assumed` facts in
5//! two passes. [`ConsolidationTick`] holds its admission gates, its spend caps and the
6//! thresholds of both passes; [`ProactivityPolicy::consolidation`](crate::ProactivityPolicy::consolidation)
7//! turns it on for a partition. It is on in the CLI's Ask and Auto partitions and off in
8//! the library and on servers, so the policy's default is `None`.
9//!
10//! | Part | Role |
11//! |---|---|
12//! | [`Consolidator`] | What the harness gives the kernel (spec 3.2 §6 D-1, §10 HK2): a partition's new material since the last tick, and one tick's work on its memory |
13//! | [`admit_tick`] | The admission gate: new material **and** `min_interval` **and** `debounce` idle, outside quiet hours, under the daily proactive budget and `budget_share` of it; a bare `schedule` only when set |
14//! | `kernel.consolidation` ([`CONSOLIDATION_TARGET`]) | The workflow a tick runs as: a [`ProcessKind::Maintenance`] durable run on the `maintenance` queue with no tools (K-I1); its spend counts toward the partition's daily proactive budget, and its proposals go to the agenda as [`AgendaOrigin::Consolidation`] items, which a person approves in every mode (K-I23) |
15//!
16//! The kernel evaluates the gate on its scheduler tick, at most once a minute of the kernel's
17//! clock per partition, when [`KernelBuilder::consolidator`](crate::KernelBuilder::consolidator)
18//! registered a consolidator for the partition and the policy turns the tick on.
19
20use std::collections::BTreeMap;
21use std::fmt;
22use std::sync::{Arc, Mutex};
23use std::time::Duration;
24
25use adk_core::principal::SubjectRef;
26use adk_core::{NewRun, OnConflict, RunBudget};
27use adk_server::background::{WorkflowExecutor, WorkflowRunContext, WorkflowState};
28use async_trait::async_trait;
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31use serde_json::{Value, json};
32use tokio_util::sync::CancellationToken;
33
34use crate::agenda::{AgendaHandle, AgendaItem, AgendaOrigin};
35use crate::bus::SpendDelta;
36use crate::error::Result;
37use crate::partition::{PartitionId, PartitionMode};
38use crate::process::{ProcessKind, ProcessSpec, ProcessTable};
39use crate::sched::{QueueClass, QuietHours};
40use crate::supervise::Supervision;
41use crate::wake::KERNEL_WAKE_TARGET;
42
43/// The consolidation tick of one partition (spec 3.2 §7.5, §13 Q1, Q12).
44///
45/// | Field | Default | Meaning |
46/// |---|---|---|
47/// | `min_new_sessions` | 3 | Distilled sessions since the last tick that admit one, or |
48/// | `min_new_facts` | 25 | new facts since the last tick that admit one |
49/// | `min_interval` | 6 h | Least time between two ticks |
50/// | `debounce` | 30 min | Least idle time in the partition before a tick |
51/// | `schedule` | `None` | A bare cron schedule, only as an explicit setting |
52/// | `budget_share` | 0.10 | Most of the partition's daily proactive budget one day's ticks spend |
53/// | `max_tokens_per_tick` | 50 000 | Hard token cap of one tick |
54/// | `dedup_score` | 0.92 | Pass 1 collapses `Assumed` near-duplicates at or above this cosine |
55/// | `expire_confidence` | 0.5 | Pass 1 expires unused `Assumed` facts under this confidence |
56/// | `assumed_ttl` | 90 days | and older than this |
57/// | `max_clusters_per_tick` | 20 | Most clusters pass 2 sends to the model in one tick |
58/// | `max_loss_fraction` | 0.25 | Most of a scope's live facts one tick may lose, rounded down, and at least one; a merge loses the facts it supersedes less the one it writes |
59///
60/// A tick is admitted only when the partition has new material **and** `min_interval` has
61/// passed **and** the partition has been idle for `debounce`, outside quiet hours and under
62/// the daily budget. Durations serialize as whole milliseconds (`minIntervalMs`,
63/// `debounceMs`, `assumedTtlMs`); a missing field takes its default.
64///
65/// # Example
66///
67/// ```rust
68/// use std::time::Duration;
69/// use adk_kernel::ConsolidationTick;
70///
71/// let tick = ConsolidationTick::default();
72/// assert_eq!((tick.min_new_sessions, tick.min_new_facts), (3, 25));
73/// assert_eq!(tick.min_interval, Duration::from_secs(6 * 60 * 60));
74/// assert_eq!(tick.debounce, Duration::from_secs(30 * 60));
75/// assert_eq!(tick.assumed_ttl, Duration::from_secs(90 * 24 * 60 * 60));
76/// assert!(tick.schedule.is_none());
77///
78/// let nightly = ConsolidationTick::new().with_schedule("0 3 * * *").with_max_tokens_per_tick(20_000);
79/// let json = serde_json::to_value(&nightly).unwrap();
80/// assert_eq!(json["schedule"], "0 3 * * *");
81/// assert_eq!(json["debounceMs"], 1_800_000);
82/// let back: ConsolidationTick = serde_json::from_value(serde_json::json!({ "minNewFacts": 10 })).unwrap();
83/// assert_eq!((back.min_new_facts, back.min_new_sessions), (10, 3));
84/// ```
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase", default)]
87#[non_exhaustive]
88pub struct ConsolidationTick {
89    /// Distilled sessions since the last tick that admit a tick (3).
90    pub min_new_sessions: usize,
91    /// New facts since the last tick that admit a tick (25).
92    pub min_new_facts: usize,
93    /// Least time since the last tick (6 h).
94    #[serde(rename = "minIntervalMs", with = "crate::serde_util::millis")]
95    pub min_interval: Duration,
96    /// Least idle time in the partition before a tick (30 min).
97    #[serde(rename = "debounceMs", with = "crate::serde_util::millis")]
98    pub debounce: Duration,
99    /// A bare cron schedule; only as an explicit setting, never the default.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub schedule: Option<String>,
102    /// The share of the partition's daily proactive budget the ticks may spend (0.10).
103    pub budget_share: f32,
104    /// The hard token cap of one tick (50 000).
105    pub max_tokens_per_tick: u64,
106    /// Pass 1 marks the older of two `Assumed` facts whose cosine is at or above this
107    /// `Superseded` by the newer one (0.92).
108    pub dedup_score: f32,
109    /// Pass 1 expires an unused `Assumed` fact whose confidence is under this (0.5).
110    pub expire_confidence: f32,
111    /// and whose age is over this (90 days).
112    #[serde(rename = "assumedTtlMs", with = "crate::serde_util::millis")]
113    pub assumed_ttl: Duration,
114    /// The most clusters pass 2 sends to the model in one tick (20).
115    pub max_clusters_per_tick: usize,
116    /// The most of a scope's live facts one tick may lose (0.25), rounded down and at least
117    /// one fact, so a small scope can still collapse one duplicate; a merge loses the facts
118    /// it supersedes less the one it writes. A result over it is refused whole.
119    pub max_loss_fraction: f32,
120}
121
122impl ConsolidationTick {
123    /// The default `max_tokens_per_tick`; the spec names the cap without a number.
124    pub const DEFAULT_MAX_TOKENS_PER_TICK: u64 = 50_000;
125
126    /// The tick with the CLI's defaults (spec 3.2 §7.5).
127    pub fn new() -> Self {
128        Self::default()
129    }
130
131    /// Sets the distilled sessions that admit a tick.
132    #[must_use]
133    pub fn with_min_new_sessions(mut self, sessions: usize) -> Self {
134        self.min_new_sessions = sessions;
135        self
136    }
137
138    /// Sets the new facts that admit a tick.
139    #[must_use]
140    pub fn with_min_new_facts(mut self, facts: usize) -> Self {
141        self.min_new_facts = facts;
142        self
143    }
144
145    /// Sets the least time between two ticks.
146    #[must_use]
147    pub fn with_min_interval(mut self, interval: Duration) -> Self {
148        self.min_interval = interval;
149        self
150    }
151
152    /// Sets the least idle time in the partition before a tick.
153    #[must_use]
154    pub fn with_debounce(mut self, debounce: Duration) -> Self {
155        self.debounce = debounce;
156        self
157    }
158
159    /// Sets a bare cron schedule.
160    #[must_use]
161    pub fn with_schedule(mut self, schedule: impl Into<String>) -> Self {
162        self.schedule = Some(schedule.into());
163        self
164    }
165
166    /// Sets the share of the partition's daily proactive budget the ticks may spend.
167    #[must_use]
168    pub fn with_budget_share(mut self, share: f32) -> Self {
169        self.budget_share = share;
170        self
171    }
172
173    /// Sets the hard token cap of one tick.
174    #[must_use]
175    pub fn with_max_tokens_per_tick(mut self, tokens: u64) -> Self {
176        self.max_tokens_per_tick = tokens;
177        self
178    }
179
180    /// Sets pass 1's near-duplicate cosine threshold.
181    #[must_use]
182    pub fn with_dedup_score(mut self, score: f32) -> Self {
183        self.dedup_score = score;
184        self
185    }
186
187    /// Sets pass 1's expiry confidence threshold.
188    #[must_use]
189    pub fn with_expire_confidence(mut self, confidence: f32) -> Self {
190        self.expire_confidence = confidence;
191        self
192    }
193
194    /// Sets the age past which pass 1 expires an unused `Assumed` fact.
195    #[must_use]
196    pub fn with_assumed_ttl(mut self, ttl: Duration) -> Self {
197        self.assumed_ttl = ttl;
198        self
199    }
200
201    /// Sets the most clusters pass 2 sends to the model in one tick.
202    #[must_use]
203    pub fn with_max_clusters_per_tick(mut self, clusters: usize) -> Self {
204        self.max_clusters_per_tick = clusters;
205        self
206    }
207
208    /// Sets the most of a scope's live facts one tick may lose.
209    #[must_use]
210    pub fn with_max_loss_fraction(mut self, fraction: f32) -> Self {
211        self.max_loss_fraction = fraction;
212        self
213    }
214}
215
216impl Default for ConsolidationTick {
217    fn default() -> Self {
218        Self {
219            min_new_sessions: 3,
220            min_new_facts: 25,
221            min_interval: Duration::from_secs(6 * 60 * 60),
222            debounce: Duration::from_secs(30 * 60),
223            schedule: None,
224            budget_share: 0.10,
225            max_tokens_per_tick: Self::DEFAULT_MAX_TOKENS_PER_TICK,
226            dedup_score: 0.92,
227            expire_confidence: 0.5,
228            assumed_ttl: Duration::from_secs(90 * 24 * 60 * 60),
229            max_clusters_per_tick: 20,
230            max_loss_fraction: 0.25,
231        }
232    }
233}
234
235/// The workflow a consolidation tick runs as (spec 3.2 §7.5): a `Maintenance` durable run
236/// on the `maintenance` queue.
237///
238/// # Example
239///
240/// ```rust
241/// assert_eq!(adk_kernel::CONSOLIDATION_TARGET, "kernel.consolidation");
242/// ```
243pub const CONSOLIDATION_TARGET: &str = "kernel.consolidation";
244
245/// The label a tick's process carries, with the value `consolidation` (spec 3.2 §7.5).
246///
247/// # Example
248///
249/// ```rust
250/// assert_eq!(adk_kernel::CONSOLIDATION_LABEL, "kernel.tick");
251/// ```
252pub const CONSOLIDATION_LABEL: &str = "kernel.tick";
253
254/// How often, on the kernel's clock, the kernel evaluates a partition's tick gate.
255const EVALUATE_EVERY: chrono::Duration = chrono::Duration::seconds(60);
256
257/// What the consolidation ticks of a partition spent today (spec 3.2 §7.5): what
258/// `budget_share` is measured against.
259///
260/// # Example
261///
262/// ```rust
263/// let spend = adk_kernel::TickSpend::new(120, 4_000, 3);
264/// assert_eq!(spend.total_tokens, 4_000);
265/// ```
266#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase")]
268#[non_exhaustive]
269pub struct TickSpend {
270    /// Cost in millionths of a US dollar.
271    pub cost_micro_usd: u64,
272    /// Tokens.
273    pub total_tokens: u64,
274    /// Model calls.
275    pub model_calls: u64,
276}
277
278impl TickSpend {
279    /// A spend of `cost_micro_usd`, `total_tokens` and `model_calls`.
280    pub fn new(cost_micro_usd: u64, total_tokens: u64, model_calls: u64) -> Self {
281        Self { cost_micro_usd, total_tokens, model_calls }
282    }
283}
284
285/// What a partition holds for a consolidation tick, as its [`Consolidator`] reports it
286/// (spec 3.2 §7.5).
287///
288/// # Example
289///
290/// ```rust
291/// use adk_kernel::{PartitionMode, TickMaterial};
292///
293/// let material = TickMaterial::new("alice", PartitionMode::Ask).with_new_material(3, 0);
294/// assert_eq!((material.new_sessions, material.new_facts), (3, 0));
295/// ```
296#[derive(Debug, Clone, PartialEq)]
297#[non_exhaustive]
298pub struct TickMaterial {
299    /// The user whose memory the tick consolidates; its process runs as this user.
300    pub user: String,
301    /// The partition's mode: a ReadOnly or Plan partition is never consolidated.
302    pub mode: PartitionMode,
303    /// When the last tick ran.
304    pub last_tick: Option<DateTime<Utc>>,
305    /// Sessions distilled since the last tick.
306    pub new_sessions: usize,
307    /// Facts written since the last tick, the ticks' own aside.
308    pub new_facts: usize,
309    /// The latest activity of the partition's sessions.
310    pub last_activity: Option<DateTime<Utc>>,
311    /// Sessions the tick distils when the per-session distiller never reached them.
312    pub sessions: Vec<String>,
313    /// What the partition's ticks spent today.
314    pub spent_today: TickSpend,
315}
316
317impl TickMaterial {
318    /// No material of `user` in a partition in `mode`.
319    pub fn new(user: impl Into<String>, mode: PartitionMode) -> Self {
320        Self {
321            user: user.into(),
322            mode,
323            last_tick: None,
324            new_sessions: 0,
325            new_facts: 0,
326            last_activity: None,
327            sessions: Vec::new(),
328            spent_today: TickSpend::default(),
329        }
330    }
331
332    /// Sets the last tick's time.
333    #[must_use]
334    pub fn with_last_tick(mut self, at: DateTime<Utc>) -> Self {
335        self.last_tick = Some(at);
336        self
337    }
338
339    /// Sets the sessions distilled and the facts written since the last tick.
340    #[must_use]
341    pub fn with_new_material(mut self, sessions: usize, facts: usize) -> Self {
342        self.new_sessions = sessions;
343        self.new_facts = facts;
344        self
345    }
346
347    /// Sets the latest activity.
348    #[must_use]
349    pub fn with_last_activity(mut self, at: DateTime<Utc>) -> Self {
350        self.last_activity = Some(at);
351        self
352    }
353
354    /// Sets the sessions to distil.
355    #[must_use]
356    pub fn with_sessions(mut self, sessions: impl IntoIterator<Item = impl Into<String>>) -> Self {
357        self.sessions = sessions.into_iter().map(Into::into).collect();
358        self
359    }
360
361    /// Sets what the ticks spent today.
362    #[must_use]
363    pub fn with_spent_today(mut self, spend: TickSpend) -> Self {
364        self.spent_today = spend;
365        self
366    }
367}
368
369/// One tick a [`Consolidator`] runs (spec 3.2 §7.5).
370///
371/// # Example
372///
373/// ```rust
374/// use adk_kernel::{ConsolidationTick, TickRun};
375///
376/// let run = TickRun::new("pid-1", "default", "alice", ConsolidationTick::default(), chrono::Utc::now());
377/// assert!(run.sessions.is_empty());
378/// ```
379#[derive(Debug, Clone, PartialEq)]
380#[non_exhaustive]
381pub struct TickRun {
382    /// The tick's id: its process's pid.
383    pub tick_id: String,
384    /// The partition.
385    pub partition: PartitionId,
386    /// The user whose memory it consolidates.
387    pub user: String,
388    /// The sessions to distil when the per-session distiller never reached them.
389    pub sessions: Vec<String>,
390    /// The thresholds of the passes and the per-tick token cap.
391    pub tick: ConsolidationTick,
392    /// The tick's budget: its share of the daily proactive budget, `max_tokens_per_tick`
393    /// at most.
394    pub budget: RunBudget,
395    /// The kernel's clock reading.
396    pub at: DateTime<Utc>,
397}
398
399impl TickRun {
400    /// A tick `tick_id` of `user` in `partition`, with no session to distil and an
401    /// unlimited budget.
402    pub fn new(
403        tick_id: impl Into<String>,
404        partition: impl Into<PartitionId>,
405        user: impl Into<String>,
406        tick: ConsolidationTick,
407        at: DateTime<Utc>,
408    ) -> Self {
409        Self {
410            tick_id: tick_id.into(),
411            partition: partition.into(),
412            user: user.into(),
413            sessions: Vec::new(),
414            tick,
415            budget: RunBudget::new(),
416            at,
417        }
418    }
419
420    /// Sets the sessions to distil.
421    #[must_use]
422    pub fn with_sessions(mut self, sessions: Vec<String>) -> Self {
423        self.sessions = sessions;
424        self
425    }
426
427    /// Sets the budget.
428    #[must_use]
429    pub fn with_budget(mut self, budget: RunBudget) -> Self {
430        self.budget = budget;
431        self
432    }
433}
434
435/// A follow-up a tick proposes; the kernel files it as an
436/// [`AgendaOrigin::Consolidation`] item, which a person approves in every mode (K-I23).
437///
438/// # Example
439///
440/// ```rust
441/// let proposal = adk_kernel::TickProposal::new("Confirm two assumptions", "They disagree with known facts");
442/// assert_eq!(proposal.title, "Confirm two assumptions");
443/// ```
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445#[serde(rename_all = "camelCase")]
446#[non_exhaustive]
447pub struct TickProposal {
448    /// A short title.
449    pub title: String,
450    /// Why it is worth doing.
451    pub rationale: String,
452}
453
454impl TickProposal {
455    /// A proposal titled `title` for `rationale`.
456    pub fn new(title: impl Into<String>, rationale: impl Into<String>) -> Self {
457        Self { title: title.into(), rationale: rationale.into() }
458    }
459}
460
461/// What one tick did, in counts, and what it proposes (spec 3.2 §7.5).
462///
463/// # Example
464///
465/// ```rust
466/// let outcome = adk_kernel::TickOutcome::new("pid-1").with_counts(2, 1, 0, 3);
467/// assert_eq!(outcome.superseded, 2);
468/// ```
469#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(rename_all = "camelCase")]
471#[non_exhaustive]
472pub struct TickOutcome {
473    /// The tick's id.
474    pub tick_id: String,
475    /// Facts superseded.
476    pub superseded: usize,
477    /// Facts forgotten.
478    pub forgotten: usize,
479    /// Facts merged by pass 2.
480    pub merged: usize,
481    /// Facts distilled from sessions the distiller never reached.
482    pub distilled: usize,
483    /// Why the passes applied nothing, when the loss cap refused them.
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub refused: Option<String>,
486    /// What it spent.
487    pub spend: TickSpend,
488    /// What it proposes.
489    #[serde(default, skip_serializing_if = "Vec::is_empty")]
490    pub proposals: Vec<TickProposal>,
491}
492
493impl TickOutcome {
494    /// An outcome of tick `tick_id` that changed nothing.
495    pub fn new(tick_id: impl Into<String>) -> Self {
496        Self { tick_id: tick_id.into(), ..Self::default() }
497    }
498
499    /// Sets the facts superseded, forgotten, merged and distilled.
500    #[must_use]
501    pub fn with_counts(
502        mut self,
503        superseded: usize,
504        forgotten: usize,
505        merged: usize,
506        distilled: usize,
507    ) -> Self {
508        self.superseded = superseded;
509        self.forgotten = forgotten;
510        self.merged = merged;
511        self.distilled = distilled;
512        self
513    }
514
515    /// Sets the loss cap's refusal.
516    #[must_use]
517    pub fn with_refused(mut self, reason: impl Into<String>) -> Self {
518        self.refused = Some(reason.into());
519        self
520    }
521
522    /// Sets the spend.
523    #[must_use]
524    pub fn with_spend(mut self, spend: TickSpend) -> Self {
525        self.spend = spend;
526        self
527    }
528
529    /// Adds a proposal.
530    #[must_use]
531    pub fn with_proposal(mut self, proposal: TickProposal) -> Self {
532        self.proposals.push(proposal);
533        self
534    }
535}
536
537/// The memory a consolidation tick works on (spec 3.2 §7.5, §6 D-1): the kernel reads no
538/// harness type, so the harness implements this for a partition
539/// (`adk_harness::Harness::consolidator`) and registers it with
540/// [`KernelBuilder::consolidator`](crate::KernelBuilder::consolidator).
541///
542/// # Example
543///
544/// ```rust
545/// use adk_kernel::{Consolidator, PartitionId, PartitionMode, TickMaterial, TickOutcome, TickRun};
546///
547/// struct Nothing;
548///
549/// #[async_trait::async_trait]
550/// impl Consolidator for Nothing {
551///     async fn material(&self, _: &PartitionId, _: chrono::DateTime<chrono::Utc>) -> adk_kernel::Result<TickMaterial> {
552///         Ok(TickMaterial::new("alice", PartitionMode::Ask))
553///     }
554///     async fn consolidate(&self, run: TickRun) -> adk_kernel::Result<TickOutcome> {
555///         Ok(TickOutcome::new(run.tick_id))
556///     }
557/// }
558/// ```
559#[async_trait]
560pub trait Consolidator: Send + Sync {
561    /// What `partition` holds at `now`: its new material since the last tick, its latest
562    /// activity, the sessions to distil and what its ticks spent today.
563    async fn material(&self, partition: &PartitionId, now: DateTime<Utc>) -> Result<TickMaterial>;
564
565    /// Runs one tick: distillation of `run.sessions` the per-session distiller never
566    /// reached, the two passes, the loss cap and the tick's record, inside `run.budget`.
567    async fn consolidate(&self, run: TickRun) -> Result<TickOutcome>;
568}
569
570/// What the tick gate reads (spec 3.2 §7.5): a partition's [`TickMaterial`] with the
571/// kernel's view of it.
572///
573/// # Example
574///
575/// ```rust
576/// use adk_kernel::{PartitionMode, TickInputs, TickMaterial};
577///
578/// let inputs = TickInputs::new(chrono::Utc::now(), TickMaterial::new("alice", PartitionMode::Auto));
579/// assert!(!inputs.busy);
580/// ```
581#[derive(Debug, Clone)]
582#[non_exhaustive]
583pub struct TickInputs {
584    /// The kernel's clock reading.
585    pub now: DateTime<Utc>,
586    /// The partition's material.
587    pub material: TickMaterial,
588    /// Whether a process of the partition runs now, a tick included.
589    pub busy: bool,
590    /// Every quiet-hours window that applies.
591    pub quiet_hours: Vec<QuietHours>,
592    /// The partition's daily proactive budget.
593    pub daily_budget: RunBudget,
594    /// The partition's proactive spend today, in micro-USD, ticks included.
595    pub proactive_spent: u64,
596    /// The partition's proactive model calls today, ticks included.
597    pub proactive_model_calls: u64,
598    /// The partition's proactive tokens today, ticks included.
599    pub proactive_tokens: u64,
600}
601
602impl TickInputs {
603    /// The gate's inputs at `now` for `material`: not busy, no quiet hours, an unlimited
604    /// daily budget.
605    pub fn new(now: DateTime<Utc>, material: TickMaterial) -> Self {
606        Self {
607            now,
608            material,
609            busy: false,
610            quiet_hours: Vec::new(),
611            daily_budget: RunBudget::new(),
612            proactive_spent: 0,
613            proactive_model_calls: 0,
614            proactive_tokens: 0,
615        }
616    }
617
618    /// Sets whether a process of the partition runs.
619    #[must_use]
620    pub fn with_busy(mut self, busy: bool) -> Self {
621        self.busy = busy;
622        self
623    }
624
625    /// Sets the quiet-hours windows.
626    #[must_use]
627    pub fn with_quiet_hours(mut self, windows: impl IntoIterator<Item = QuietHours>) -> Self {
628        self.quiet_hours = windows.into_iter().collect();
629        self
630    }
631
632    /// Sets the daily proactive budget and what the partition's proactive processes spent
633    /// of it today.
634    #[must_use]
635    pub fn with_daily_budget(mut self, budget: RunBudget, spent_micro_usd: u64) -> Self {
636        self.daily_budget = budget;
637        self.proactive_spent = spent_micro_usd;
638        self
639    }
640
641    /// Sets the model calls and tokens the partition's proactive processes used today, which
642    /// the daily budget's `max_model_calls` and `max_total_tokens` cap.
643    ///
644    /// # Example
645    ///
646    /// ```rust
647    /// use adk_core::RunBudget;
648    /// use adk_kernel::{PartitionMode, TickInputs, TickMaterial};
649    ///
650    /// let now = chrono::Utc::now();
651    /// let inputs = TickInputs::new(now, TickMaterial::new("alice", PartitionMode::Ask))
652    ///     .with_daily_budget(RunBudget::new().max_total_tokens(50_000), 0)
653    ///     .with_proactive_calls_and_tokens(4, 12_000);
654    /// assert_eq!((inputs.proactive_model_calls, inputs.proactive_tokens), (4, 12_000));
655    /// ```
656    #[must_use]
657    pub fn with_proactive_calls_and_tokens(mut self, model_calls: u64, tokens: u64) -> Self {
658        self.proactive_model_calls = model_calls;
659        self.proactive_tokens = tokens;
660        self
661    }
662}
663
664/// The tick gate's decision (spec 3.2 §7.5).
665///
666/// # Example
667///
668/// ```rust
669/// assert_eq!(adk_kernel::TickAdmission::NoMaterial.reason(), "no_material");
670/// ```
671#[derive(Debug, Clone, PartialEq)]
672#[non_exhaustive]
673pub enum TickAdmission {
674    /// Run a tick within `budget`.
675    Admit {
676        /// The tick's budget: its share of the day, `max_tokens_per_tick` at most.
677        budget: RunBudget,
678    },
679    /// The partition is ReadOnly or Plan.
680    Mode,
681    /// Too few distilled sessions and new facts since the last tick.
682    NoMaterial,
683    /// A bare schedule is set and not due.
684    NotDue {
685        /// The schedule's next fire time, if it parses.
686        next: Option<DateTime<Utc>>,
687    },
688    /// The last tick is less than `min_interval` ago.
689    Interval {
690        /// When the interval has passed.
691        until: DateTime<Utc>,
692    },
693    /// A process of the partition runs.
694    Busy,
695    /// The partition has been active within `debounce`.
696    Debounce {
697        /// When it has been idle long enough, without more activity.
698        until: DateTime<Utc>,
699    },
700    /// Inside quiet hours.
701    QuietHours {
702        /// When the windows end.
703        until: DateTime<Utc>,
704    },
705    /// The partition's daily proactive budget is spent.
706    Budget,
707    /// The ticks' share of the daily proactive budget is spent.
708    Share,
709}
710
711impl TickAdmission {
712    /// The decision's name: `admit`, `mode`, `no_material`, `not_due`, `interval`, `busy`,
713    /// `debounce`, `quiet_hours`, `budget` or `share`.
714    pub fn reason(&self) -> &'static str {
715        match self {
716            Self::Admit { .. } => "admit",
717            Self::Mode => "mode",
718            Self::NoMaterial => "no_material",
719            Self::NotDue { .. } => "not_due",
720            Self::Interval { .. } => "interval",
721            Self::Busy => "busy",
722            Self::Debounce { .. } => "debounce",
723            Self::QuietHours { .. } => "quiet_hours",
724            Self::Budget => "budget",
725            Self::Share => "share",
726        }
727    }
728}
729
730fn chrono_of(duration: Duration) -> chrono::Duration {
731    chrono::Duration::from_std(duration).unwrap_or(chrono::Duration::MAX)
732}
733
734/// `share` of `cap`, rounded down.
735fn share_of(cap: u64, share: f32) -> u64 {
736    (cap as f64 * f64::from(share.clamp(0.0, 1.0))).floor() as u64
737}
738
739/// The bare schedule's next fire time after `after`, in UTC.
740fn next_fire(expr: &str, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
741    adk_core::schedule::ScheduleSpec::Cron { expr: expr.to_string(), timezone: "UTC".into() }
742        .next_after(after)
743        .ok()
744        .flatten()
745}
746
747/// Whether `tick` admits a consolidation tick on `inputs` (spec 3.2 §7.5, §13 Q1), and with
748/// what budget.
749///
750/// | Gate | Holds when |
751/// |---|---|
752/// | Mode | the partition is Ask or Auto |
753/// | Quiet hours | `now` is outside every window (K-I11) |
754/// | Daily budget | the partition's proactive spend today is under the daily cost cap |
755/// | Share | the ticks' spend today is under `budget_share` of each daily cap |
756/// | New material | at least `min_new_sessions` distilled sessions or `min_new_facts` new facts since the last tick |
757/// | Interval | `min_interval` has passed since the last tick |
758/// | Debounce | no process of the partition runs and its latest activity is `debounce` ago |
759///
760/// With a bare `schedule` set, the schedule's fire time since the last tick replaces new
761/// material, interval and debounce; quiet hours and the budgets still hold. The admitted
762/// budget is `max_tokens_per_tick` tokens at most, and the share of each daily cap the
763/// ticks have left, within what the day has left.
764///
765/// # Example
766///
767/// ```rust
768/// use std::time::Duration;
769/// use adk_kernel::{ConsolidationTick, PartitionMode, TickAdmission, TickInputs, TickMaterial, admit_tick};
770///
771/// let now = chrono::Utc::now();
772/// let idle = now - chrono::Duration::hours(1);
773/// let material = TickMaterial::new("alice", PartitionMode::Ask).with_new_material(3, 0).with_last_activity(idle);
774/// let decision = admit_tick(&ConsolidationTick::default(), &TickInputs::new(now, material.clone()));
775/// assert!(matches!(decision, TickAdmission::Admit { .. }));
776/// let busy = admit_tick(&ConsolidationTick::default(), &TickInputs::new(now, material).with_busy(true));
777/// assert_eq!(busy, TickAdmission::Busy);
778/// ```
779pub fn admit_tick(tick: &ConsolidationTick, inputs: &TickInputs) -> TickAdmission {
780    let now = inputs.now;
781    let material = &inputs.material;
782    if matches!(material.mode, PartitionMode::ReadOnly | PartitionMode::Plan) {
783        return TickAdmission::Mode;
784    }
785    let quiet: Vec<&QuietHours> =
786        inputs.quiet_hours.iter().filter(|window| window.contains(now)).collect();
787    if !quiet.is_empty() {
788        // The windows can overlap: release once none holds.
789        let mut until = now;
790        for _ in 0..=inputs.quiet_hours.len() {
791            let next = inputs
792                .quiet_hours
793                .iter()
794                .map(|window| window.release_at(until))
795                .max()
796                .unwrap_or(until);
797            if next == until {
798                break;
799            }
800            until = next;
801        }
802        return TickAdmission::QuietHours { until };
803    }
804    let daily = &inputs.daily_budget;
805    let spent = material.spent_today;
806    if daily.max_cost_micro_usd.is_some_and(|cap| inputs.proactive_spent >= cap)
807        || daily.max_model_calls.is_some_and(|cap| inputs.proactive_model_calls >= cap)
808        || daily.max_total_tokens.is_some_and(|cap| inputs.proactive_tokens >= cap)
809    {
810        return TickAdmission::Budget;
811    }
812    let remaining = |cap: Option<u64>, used: u64| {
813        cap.map(|cap| share_of(cap, tick.budget_share).saturating_sub(used))
814    };
815    let cost = remaining(daily.max_cost_micro_usd, spent.cost_micro_usd);
816    let tokens = remaining(daily.max_total_tokens, spent.total_tokens);
817    let calls = remaining(daily.max_model_calls, spent.model_calls);
818    if [cost, tokens, calls].contains(&Some(0)) {
819        return TickAdmission::Share;
820    }
821    match &tick.schedule {
822        Some(expr) => {
823            let anchor = material.last_tick.unwrap_or(now - chrono::Duration::days(1));
824            let next = next_fire(expr, anchor);
825            if next.is_none_or(|next| next > now) {
826                return TickAdmission::NotDue { next };
827            }
828        }
829        None => {
830            if material.new_sessions < tick.min_new_sessions
831                && material.new_facts < tick.min_new_facts
832            {
833                return TickAdmission::NoMaterial;
834            }
835            if let Some(last) = material.last_tick {
836                let until = last + chrono_of(tick.min_interval);
837                if now < until {
838                    return TickAdmission::Interval { until };
839                }
840            }
841            if inputs.busy {
842                return TickAdmission::Busy;
843            }
844            if let Some(active) = material.last_activity {
845                let until = active + chrono_of(tick.debounce);
846                if now < until {
847                    return TickAdmission::Debounce { until };
848                }
849            }
850        }
851    }
852    // A tick spends at most its share and what the day leaves of the proactive budget.
853    let day_left = |cap: Option<u64>, used: u64| cap.map(|cap| cap.saturating_sub(used));
854    let tokens_left = day_left(daily.max_total_tokens, inputs.proactive_tokens);
855    let mut budget = RunBudget::new().max_total_tokens(
856        [tokens, tokens_left].into_iter().flatten().fold(tick.max_tokens_per_tick, u64::min),
857    );
858    if let Some(cost) = cost {
859        let day_left =
860            daily.max_cost_micro_usd.map_or(cost, |cap| cap.saturating_sub(inputs.proactive_spent));
861        budget = budget.max_cost_micro_usd(cost.min(day_left));
862    }
863    if let Some(calls) = calls {
864        let day_left = day_left(daily.max_model_calls, inputs.proactive_model_calls);
865        budget = budget.max_model_calls(day_left.map_or(calls, |left| calls.min(left)));
866    }
867    if daily.allow_unpriced_models {
868        budget = budget.allow_unpriced_models();
869    }
870    TickAdmission::Admit { budget }
871}
872
873/// The input of a `kernel.consolidation` run.
874#[derive(Debug, Clone, Serialize, Deserialize)]
875#[serde(rename_all = "camelCase")]
876struct TickInput {
877    partition: PartitionId,
878    user: String,
879    mode: PartitionMode,
880    sessions: Vec<String>,
881    tick: ConsolidationTick,
882    #[serde(with = "crate::serde_util::run_budget")]
883    budget: RunBudget,
884}
885
886/// Runs `kernel.consolidation`: one tick through the partition's [`Consolidator`], its
887/// spend added to the process's daily total, its proposals filed with the agenda.
888/// Workflow ids it does not run go to `user`, the caller's workflows.
889pub(crate) struct ConsolidationExecutor {
890    sup: Arc<Supervision>,
891    consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
892    agenda: AgendaHandle,
893    user: Option<Arc<dyn WorkflowExecutor>>,
894}
895
896impl fmt::Debug for ConsolidationExecutor {
897    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898        f.debug_struct("ConsolidationExecutor")
899            .field("partitions", &self.consolidators.keys().collect::<Vec<_>>())
900            .finish_non_exhaustive()
901    }
902}
903
904impl ConsolidationExecutor {
905    pub(crate) fn new(
906        sup: Arc<Supervision>,
907        consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
908        agenda: AgendaHandle,
909        user: Option<Arc<dyn WorkflowExecutor>>,
910    ) -> Self {
911        Self { sup, consolidators, agenda, user }
912    }
913
914    async fn run_tick(
915        &self,
916        run_id: &str,
917        input: WorkflowState,
918    ) -> std::result::Result<Value, String> {
919        let input: TickInput = serde_json::from_value(Value::Object(input.into_iter().collect()))
920            .map_err(|error| {
921            format!(
922                "a `{CONSOLIDATION_TARGET}` run's input is not a tick the kernel spawned: {error}"
923            )
924        })?;
925        let now = self.sup.clock.now();
926        // Spawned just before a window opened: no proactive process starts inside it (K-I11).
927        if self.sup.quiet_release(&input.partition, now).await > now {
928            return Ok(json!({ "tickId": run_id, "skipped": "quiet_hours" }));
929        }
930        let consolidator = self.consolidators.get(&input.partition).ok_or_else(|| {
931            format!("no consolidator is registered for partition {}", input.partition)
932        })?;
933        let run = TickRun::new(run_id, input.partition.clone(), &input.user, input.tick, now)
934            .with_sessions(input.sessions)
935            .with_budget(input.budget);
936        let outcome = consolidator.consolidate(run).await.map_err(|error| error.to_string())?;
937        // The tick's spend is proactive spend of the partition (spec 3.2 §7.5, §7.9).
938        let spend = SpendDelta::new(outcome.spend.cost_micro_usd)
939            .with_model_calls(outcome.spend.model_calls)
940            .with_total_tokens(outcome.spend.total_tokens);
941        if !spend.is_empty()
942            && let Err(error) = self
943                .sup
944                .processes
945                .add_spend(run_id, &input.partition, now.date_naive(), spend)
946                .await
947        {
948            tracing::warn!(process.pid = run_id, error = %error, "could not record a consolidation tick's spend");
949        }
950        let mut proposed = Vec::new();
951        if let Some(agenda) = self.agenda.get() {
952            for proposal in &outcome.proposals {
953                let item = AgendaItem::new(
954                    format!("consolidation-{}", uuid::Uuid::new_v4()),
955                    SubjectRef::human(input.user.clone()),
956                    proposal.title.clone(),
957                    proposal.rationale.clone(),
958                    AgendaOrigin::Consolidation,
959                    now,
960                )
961                .with_partition(input.partition.clone());
962                let id = item.id.clone();
963                match agenda.propose(item, input.mode).await {
964                    Ok(_) => proposed.push(id),
965                    Err(error) => {
966                        tracing::warn!(error = %error, "could not file a consolidation proposal")
967                    }
968                }
969            }
970        }
971        tracing::info!(
972            process.pid = run_id,
973            memory.superseded = outcome.superseded,
974            memory.forgotten = outcome.forgotten,
975            memory.merged = outcome.merged,
976            memory.distilled = outcome.distilled,
977            agenda.proposed = proposed.len(),
978            "consolidation tick finished"
979        );
980        Ok(json!({ "outcome": outcome, "proposed": proposed }))
981    }
982}
983
984#[async_trait]
985impl WorkflowExecutor for ConsolidationExecutor {
986    fn has_workflow(&self, workflow_id: &str) -> bool {
987        workflow_id == CONSOLIDATION_TARGET
988            || self.user.as_ref().is_some_and(|user| user.has_workflow(workflow_id))
989    }
990
991    async fn execute(
992        &self,
993        workflow_id: &str,
994        input: WorkflowState,
995        cancel_token: CancellationToken,
996    ) -> std::result::Result<Value, String> {
997        match &self.user {
998            Some(user) if workflow_id != CONSOLIDATION_TARGET => {
999                user.execute(workflow_id, input, cancel_token).await
1000            }
1001            _ => Err(format!("`{CONSOLIDATION_TARGET}` runs only as a durable run")),
1002        }
1003    }
1004
1005    async fn execute_durable(
1006        &self,
1007        workflow_id: &str,
1008        input: WorkflowState,
1009        run: WorkflowRunContext,
1010    ) -> std::result::Result<Value, String> {
1011        if workflow_id != CONSOLIDATION_TARGET {
1012            return match &self.user {
1013                Some(user) => user.execute_durable(workflow_id, input, run).await,
1014                None => Err(format!("no workflow `{workflow_id}`")),
1015            };
1016        }
1017        tokio::select! {
1018            result = self.run_tick(&run.run_id, input) => result,
1019            () = run.cancel.cancelled() => Err("the consolidation tick was cancelled".to_string()),
1020        }
1021    }
1022}
1023
1024/// Evaluates each registered partition's tick gate on the kernel's scheduler tick and spawns
1025/// an admitted tick (spec 3.2 §7.5).
1026#[derive(Clone)]
1027pub(crate) struct ConsolidationTicker {
1028    sup: Arc<Supervision>,
1029    processes: ProcessTable,
1030    consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
1031    evaluated: Arc<Mutex<BTreeMap<PartitionId, DateTime<Utc>>>>,
1032}
1033
1034impl ConsolidationTicker {
1035    pub(crate) fn new(
1036        sup: Arc<Supervision>,
1037        processes: ProcessTable,
1038        consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
1039    ) -> Self {
1040        Self { sup, processes, consolidators, evaluated: Arc::default() }
1041    }
1042
1043    /// Whether a process of `partition` runs, a tick included; the kernel's own wake runs
1044    /// aside.
1045    async fn busy(&self, partition: &PartitionId) -> bool {
1046        for run in self.sup.running().await {
1047            if run.target == KERNEL_WAKE_TARGET {
1048                continue;
1049            }
1050            let meta =
1051                self.sup.stored_meta(&run).await.unwrap_or_else(|| Supervision::infer_meta(&run));
1052            if meta.partition == *partition {
1053                return true;
1054            }
1055        }
1056        false
1057    }
1058
1059    /// One evaluation of every partition whose last one is a minute old on the kernel's clock.
1060    pub(crate) async fn tick(&self) {
1061        let Some(tick) = self.sup.proactivity.consolidation.clone() else {
1062            return;
1063        };
1064        if self.sup.governance.is_frozen() {
1065            return;
1066        }
1067        let now = self.sup.clock.now();
1068        for (partition, consolidator) in self.consolidators.iter() {
1069            {
1070                let mut evaluated = self.evaluated.lock().unwrap_or_else(|e| e.into_inner());
1071                if evaluated.get(partition).is_some_and(|at| now - *at < EVALUATE_EVERY) {
1072                    continue;
1073                }
1074                evaluated.insert(partition.clone(), now);
1075            }
1076            if let Err(error) = self.evaluate(&tick, partition, consolidator.as_ref(), now).await {
1077                tracing::debug!(partition = %partition, error = %error, "consolidation tick not spawned");
1078            }
1079        }
1080    }
1081
1082    async fn evaluate(
1083        &self,
1084        tick: &ConsolidationTick,
1085        partition: &PartitionId,
1086        consolidator: &dyn Consolidator,
1087        now: DateTime<Utc>,
1088    ) -> Result<()> {
1089        let mut material = consolidator.material(partition, now).await?;
1090        // A mode tightened while the kernel runs holds the tick back (spec 3.3 §10 K3).
1091        material.mode = self.sup.area_mode(partition, material.mode).await;
1092        let daily = self.sup.proactivity.daily_budget.clone();
1093        let used = if daily.max_cost_micro_usd.is_some()
1094            || daily.max_model_calls.is_some()
1095            || daily.max_total_tokens.is_some()
1096        {
1097            self.sup.proactive_usage(partition).await
1098        } else {
1099            crate::stores::UsageTotals::default()
1100        };
1101        let quiet = self.sup.quiet_windows(partition).await;
1102        let inputs = TickInputs::new(now, material.clone())
1103            .with_busy(self.busy(partition).await)
1104            .with_quiet_hours(quiet)
1105            .with_daily_budget(daily, used.micro_usd)
1106            .with_proactive_calls_and_tokens(used.model_calls, used.total_tokens);
1107        let budget = match admit_tick(tick, &inputs) {
1108            TickAdmission::Admit { budget } => budget,
1109            held => {
1110                tracing::debug!(partition = %partition, admission = held.reason(), "consolidation tick held");
1111                return Ok(());
1112            }
1113        };
1114        let input = TickInput {
1115            partition: partition.clone(),
1116            user: material.user.clone(),
1117            mode: material.mode,
1118            sessions: material.sessions.clone(),
1119            tick: tick.clone(),
1120            budget,
1121        };
1122        // One tick per window since the last one, across replicas; a failed tick is not
1123        // retried in place, since its record would be overwritten, but by the next window.
1124        let window = now.timestamp() / EVALUATE_EVERY.num_seconds().max(1);
1125        let last = material.last_tick.map_or(0, |at| at.timestamp_millis());
1126        let run = NewRun::new(
1127            QueueClass::MAINTENANCE,
1128            &self.sup.app_name,
1129            &material.user,
1130            CONSOLIDATION_TARGET,
1131            serde_json::to_value(&input)?,
1132        )
1133        .with_idempotency_key(format!("consolidation:{partition}:{last}:{window}"))
1134        .with_concurrency_key(format!("consolidation:{partition}"), OnConflict::Reject)
1135        .with_max_attempts(1)
1136        .with_service_subject();
1137        let spec = ProcessSpec::new(ProcessKind::Maintenance)
1138            .with_partition(partition.clone())
1139            .with_label(CONSOLIDATION_LABEL, "consolidation");
1140        let process = self.processes.spawn(run, spec).await?;
1141        self.sup.nudge();
1142        tracing::info!(partition = %partition, process.pid = %process.meta.pid, "consolidation tick spawned");
1143        Ok(())
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use chrono::TimeZone;
1150
1151    use super::*;
1152
1153    fn noon() -> DateTime<Utc> {
1154        Utc.with_ymd_and_hms(2026, 10, 23, 12, 0, 0).unwrap()
1155    }
1156
1157    fn minutes(n: i64) -> chrono::Duration {
1158        chrono::Duration::minutes(n)
1159    }
1160
1161    /// Material that admits a tick at noon: three distilled sessions, the last tick seven
1162    /// hours ago, the partition idle for an hour.
1163    fn ready() -> TickMaterial {
1164        TickMaterial::new("alice", PartitionMode::Ask)
1165            .with_new_material(3, 0)
1166            .with_last_tick(noon() - minutes(7 * 60))
1167            .with_last_activity(noon() - minutes(60))
1168    }
1169
1170    fn decide(material: TickMaterial) -> TickAdmission {
1171        admit_tick(&ConsolidationTick::default(), &TickInputs::new(noon(), material))
1172    }
1173
1174    fn admitted(decision: &TickAdmission) -> bool {
1175        matches!(decision, TickAdmission::Admit { .. })
1176    }
1177
1178    #[test]
1179    fn the_admission_table() {
1180        let tick = ConsolidationTick::default();
1181        let six_hours = minutes(6 * 60);
1182        let cases: Vec<(&str, TickMaterial, TickAdmission)> = vec![
1183            (
1184                "new sessions at the threshold",
1185                ready(),
1186                TickAdmission::Admit {
1187                    budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1188                },
1189            ),
1190            (
1191                "one session short, no facts",
1192                ready().with_new_material(2, 24),
1193                TickAdmission::NoMaterial,
1194            ),
1195            (
1196                "facts at the threshold",
1197                ready().with_new_material(0, 25),
1198                TickAdmission::Admit {
1199                    budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1200                },
1201            ),
1202            (
1203                "interval one minute short",
1204                ready().with_last_tick(noon() - six_hours + minutes(1)),
1205                TickAdmission::Interval { until: noon() + minutes(1) },
1206            ),
1207            (
1208                "interval exactly passed",
1209                ready().with_last_tick(noon() - six_hours),
1210                TickAdmission::Admit {
1211                    budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1212                },
1213            ),
1214            (
1215                "active 29 minutes ago",
1216                ready().with_last_activity(noon() - minutes(29)),
1217                TickAdmission::Debounce { until: noon() + minutes(1) },
1218            ),
1219            (
1220                "idle exactly 30 minutes",
1221                ready().with_last_activity(noon() - minutes(30)),
1222                TickAdmission::Admit {
1223                    budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1224                },
1225            ),
1226            (
1227                "first tick ever",
1228                TickMaterial::new("alice", PartitionMode::Auto).with_new_material(3, 0),
1229                TickAdmission::Admit {
1230                    budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1231                },
1232            ),
1233            (
1234                "read-only partition",
1235                TickMaterial { mode: PartitionMode::ReadOnly, ..ready() },
1236                TickAdmission::Mode,
1237            ),
1238            (
1239                "plan partition",
1240                TickMaterial { mode: PartitionMode::Plan, ..ready() },
1241                TickAdmission::Mode,
1242            ),
1243        ];
1244        for (name, material, expected) in cases {
1245            assert_eq!(decide(material), expected, "{name}");
1246        }
1247        let busy = admit_tick(&tick, &TickInputs::new(noon(), ready()).with_busy(true));
1248        assert_eq!(busy, TickAdmission::Busy, "a running process is activity");
1249    }
1250
1251    #[test]
1252    fn quiet_hours_hold_a_ready_tick_until_they_end() {
1253        let quiet: QuietHours = "11:00-13:00".parse().unwrap();
1254        let quiet = quiet.with_utc_offset_minutes(0);
1255        let inputs = TickInputs::new(noon(), ready()).with_quiet_hours([quiet]);
1256        assert_eq!(
1257            admit_tick(&ConsolidationTick::default(), &inputs),
1258            TickAdmission::QuietHours { until: noon() + minutes(60) }
1259        );
1260        let after = TickInputs::new(noon() + minutes(60), ready()).with_quiet_hours([quiet]);
1261        assert!(admitted(&admit_tick(&ConsolidationTick::default(), &after)));
1262    }
1263
1264    #[test]
1265    fn the_budget_share_bounds_the_tick() {
1266        let tick = ConsolidationTick::default().with_max_tokens_per_tick(50_000);
1267        let daily = RunBudget::new().max_cost_micro_usd(1_000_000).max_total_tokens(200_000);
1268        // A tenth of the day: 100,000 micro-USD and 20,000 tokens for the ticks.
1269        let spent = TickSpend::new(30_000, 5_000, 2);
1270        let inputs = TickInputs::new(noon(), ready().with_spent_today(spent))
1271            .with_daily_budget(daily.clone(), 400_000);
1272        assert_eq!(
1273            admit_tick(&tick, &inputs),
1274            TickAdmission::Admit {
1275                budget: RunBudget::new().max_total_tokens(15_000).max_cost_micro_usd(70_000)
1276            }
1277        );
1278        // The day's proactive budget almost spent: the tick gets what is left of it.
1279        let tight = TickInputs::new(noon(), ready()).with_daily_budget(daily.clone(), 960_000);
1280        assert_eq!(
1281            admit_tick(&tick, &tight),
1282            TickAdmission::Admit {
1283                budget: RunBudget::new().max_total_tokens(20_000).max_cost_micro_usd(40_000)
1284            }
1285        );
1286        let spent_day =
1287            TickInputs::new(noon(), ready()).with_daily_budget(daily.clone(), 1_000_000);
1288        assert_eq!(admit_tick(&tick, &spent_day), TickAdmission::Budget);
1289        let share_spent =
1290            TickInputs::new(noon(), ready().with_spent_today(TickSpend::new(100_000, 0, 0)))
1291                .with_daily_budget(daily, 100_000);
1292        assert_eq!(admit_tick(&tick, &share_spent), TickAdmission::Share);
1293        // Without a daily token cap, the per-tick cap holds alone.
1294        let uncapped = TickInputs::new(noon(), ready());
1295        assert_eq!(
1296            admit_tick(&tick.with_max_tokens_per_tick(9_000), &uncapped),
1297            TickAdmission::Admit { budget: RunBudget::new().max_total_tokens(9_000) }
1298        );
1299    }
1300
1301    #[test]
1302    fn a_bare_schedule_replaces_material_interval_and_debounce() {
1303        let nightly = ConsolidationTick::default().with_schedule("0 3 * * *");
1304        let quiet = TickMaterial::new("alice", PartitionMode::Ask)
1305            .with_last_tick(Utc.with_ymd_and_hms(2026, 10, 22, 3, 0, 5).unwrap())
1306            .with_last_activity(noon() - minutes(1));
1307        // Yesterday's tick: today's 03:00 fire has passed, so the tick is due, recent
1308        // activity and no material notwithstanding.
1309        assert_eq!(
1310            admit_tick(&nightly, &TickInputs::new(noon(), quiet.clone())),
1311            TickAdmission::Admit {
1312                budget: RunBudget::new().max_total_tokens(nightly.max_tokens_per_tick)
1313            },
1314            "today's 03:00 passed since yesterday's tick"
1315        );
1316        let ticked_today =
1317            quiet.with_last_tick(Utc.with_ymd_and_hms(2026, 10, 23, 3, 0, 5).unwrap());
1318        assert_eq!(
1319            admit_tick(&nightly, &TickInputs::new(noon(), ticked_today)),
1320            TickAdmission::NotDue {
1321                next: Some(Utc.with_ymd_and_hms(2026, 10, 24, 3, 0, 0).unwrap())
1322            }
1323        );
1324        let broken = ConsolidationTick::default().with_schedule("not cron");
1325        assert_eq!(
1326            admit_tick(&broken, &TickInputs::new(noon(), ready())),
1327            TickAdmission::NotDue { next: None }
1328        );
1329    }
1330}