Skip to main content

agentmux_srv_core/backend/memory/
dream_schedule.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which queued dream runs next, and why a dream waits (SPEC_DREAMS §3, §5).
5//!
6//! A trigger only adds a dream to the queue; this module decides whether a queued dream may run now. It is a pure
7//! decision over facts the caller reads (the person's activity, the host's load, the queue, the memory), so every rule
8//! is tested without a machine and the caller's loop stays small. It reads nothing and runs nothing.
9//!
10//! Not here yet (step 4 of the build): the pull-forward into a quota window about to reset, and the cheaper-route
11//! choice beyond the `cheaper_route` flag below.
12
13use crate::backend::storage::dreams::{memory_kind, trigger, Dream};
14
15/// What is true of the machine and the settings right now.
16#[derive(Debug, Clone, Copy, Default)]
17pub struct Signals {
18    /// The switch "Pause all dreams": holds every queued pass and keeps the queue.
19    pub paused: bool,
20    /// A pass is running: one at a time.
21    pub pass_running: bool,
22    /// The person has used the keyboard or mouse in the last minute.
23    pub person_active: bool,
24    /// The host-pressure signal says the machine is busy.
25    pub host_under_load: bool,
26    /// The account the pass would use is short of quota.
27    pub account_short: bool,
28    /// The person set a cheaper route (the API account or a cheaper model), so a short account does not hold a pass.
29    pub cheaper_route: bool,
30    /// The most one agent's passes may spend a day, in millionths of a dollar; `None` is no cap.
31    pub daily_cap_micro_usd: Option<u64>,
32}
33
34/// One queued dream and the facts about its memory.
35#[derive(Debug, Clone)]
36pub struct Candidate<'a> {
37    pub dream: &'a Dream,
38    /// The agent is in a turn now (only an `idle` dream waits for it to end).
39    pub agent_mid_turn: bool,
40    /// A memory version was written since the last pass.
41    pub memory_changed: bool,
42    /// The agent has session text since the last pass.
43    pub new_session_text: bool,
44    /// How many `__conflict_` copies the memory holds: the clearest thing a pass can tidy.
45    pub conflict_copies: usize,
46    pub memory_bytes: u64,
47    /// What this agent's passes spent today, in millionths of a dollar.
48    pub spent_today_micro_usd: u64,
49}
50
51/// Why a dream waits. The strings are what the entry shows.
52pub mod hold {
53    pub const PAUSED: &str = "dreams are paused";
54    pub const RUNNING: &str = "another pass is running";
55    pub const PERSON_ACTIVE: &str = "you are using the machine";
56    pub const HOST_LOAD: &str = "the machine is busy";
57    pub const QUOTA: &str = "the account is short of quota";
58    pub const UNCHANGED: &str = "nothing new since the last pass";
59    pub const MID_TURN: &str = "the agent is in a turn";
60    pub const DAILY_CAP: &str = "this agent's daily spend cap is reached";
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Verdict {
65    Run,
66    Hold(&'static str),
67}
68
69/// May this dream run now, and if not, why.
70///
71/// A dream the person asked for ("Dream now") ignores the rules about their own activity, the host's load, an agent
72/// mid-turn and an unchanged memory: they asked for it. It still waits for a pause, a pass already running, the
73/// account's quota and the daily cap.
74pub fn verdict(c: &Candidate, s: &Signals) -> Verdict {
75    if s.paused {
76        return Verdict::Hold(hold::PAUSED);
77    }
78    if s.pass_running {
79        return Verdict::Hold(hold::RUNNING);
80    }
81    if s.account_short && !s.cheaper_route {
82        return Verdict::Hold(hold::QUOTA);
83    }
84    if s.daily_cap_micro_usd.is_some_and(|cap| c.spent_today_micro_usd >= cap) {
85        return Verdict::Hold(hold::DAILY_CAP);
86    }
87    if c.dream.trigger_kind == trigger::PERSON {
88        return Verdict::Run;
89    }
90    if s.person_active {
91        return Verdict::Hold(hold::PERSON_ACTIVE);
92    }
93    if s.host_under_load {
94        return Verdict::Hold(hold::HOST_LOAD);
95    }
96    if !c.memory_changed && !c.new_session_text {
97        return Verdict::Hold(hold::UNCHANGED);
98    }
99    if c.dream.trigger_kind == trigger::IDLE && c.agent_mid_turn {
100        return Verdict::Hold(hold::MID_TURN);
101    }
102    Verdict::Run
103}
104
105/// The index of the dream to run next among those that may run now, or `None`. Order of value: one a person asked for,
106/// then Global Memory, then the memory with the most conflict copies, then the largest, then the oldest.
107pub fn pick(candidates: &[Candidate], s: &Signals) -> Option<usize> {
108    candidates
109        .iter()
110        .enumerate()
111        .filter(|(_, c)| verdict(c, s) == Verdict::Run)
112        .min_by_key(|(_, c)| {
113            (
114                c.dream.trigger_kind != trigger::PERSON,
115                c.dream.memory_kind != memory_kind::GLOBAL,
116                std::cmp::Reverse(c.conflict_copies),
117                std::cmp::Reverse(c.memory_bytes),
118                c.dream.created_at_ms,
119                c.dream.id.clone(),
120            )
121        })
122        .map(|(i, _)| i)
123}
124
125/// Whether the nightly sweep (T4) is due for a memory: its last sweep was on an earlier local day. Days are counted
126/// in the person's local time by the caller, so the sweep follows their day, not UTC.
127pub fn nightly_due(last_sweep_local_day: Option<i64>, today_local_day: i64) -> bool {
128    last_sweep_local_day.is_none_or(|d| d < today_local_day)
129}
130
131#[cfg(test)]
132#[path = "dream_schedule_tests.rs"]
133mod tests;