Skip to main content

lean_ctx/core/
autonomy.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::Mutex;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
5
6use crate::core::config::AutonomyConfig;
7
8#[cfg(test)]
9const SEARCH_REPEAT_IDLE_RESET: Duration = Duration::from_millis(500);
10#[cfg(not(test))]
11const SEARCH_REPEAT_IDLE_RESET: Duration = Duration::from_mins(5);
12
13/// Per-key stats for progressive search hints (`ctx_search` / `ctx_semantic_search`).
14#[derive(Debug, Clone)]
15pub struct SearchHistory {
16    pub call_count: u32,
17    pub last_call: Instant,
18}
19
20/// Tracks autonomous action state independently of the MCP tool layer.
21pub struct AutonomyState {
22    /// Set once the session's wake-up briefing was delivered.
23    pub session_briefed: AtomicBool,
24    pub last_consolidation_unix: AtomicU64,
25    pub config: AutonomyConfig,
26    /// Repeated `pattern|path` keys for search tools (see [`AutonomyState::track_search`]).
27    pub search_repetition: Mutex<HashMap<String, SearchHistory>>,
28    /// One-shot keys for large-output hints (`ctx_shell` bytes, `ctx_read` full tokens).
29    pub large_output_hints_shown: Mutex<HashSet<String>>,
30}
31
32impl Default for AutonomyState {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl AutonomyState {
39    /// Creates a new autonomy state with config loaded from disk.
40    pub fn new() -> Self {
41        Self {
42            session_briefed: AtomicBool::new(false),
43            last_consolidation_unix: AtomicU64::new(0),
44            config: AutonomyConfig::load(),
45            search_repetition: Mutex::new(HashMap::new()),
46            large_output_hints_shown: Mutex::new(HashSet::new()),
47        }
48    }
49
50    /// Returns true if autonomous actions are enabled in configuration.
51    pub fn is_enabled(&self) -> bool {
52        self.config.enabled
53    }
54
55    /// Records a search (`pattern` + `path` key) and returns a progressive hint after repeated calls.
56    ///
57    /// Uses interior mutability so this can be called on `Arc<AutonomyState>`. Counters reset when
58    /// the idle gap since the last call for that key is at least five minutes (500ms in unit tests).
59    pub fn track_search(&self, pattern: &str, path: &str) -> Option<String> {
60        if !autonomy_enabled_effective(self) {
61            return None;
62        }
63        let key = format!("{pattern}|{path}");
64        let now = Instant::now();
65        let mut map = self
66            .search_repetition
67            .lock()
68            .unwrap_or_else(std::sync::PoisonError::into_inner);
69        let hist = map.entry(key).or_insert(SearchHistory {
70            call_count: 0,
71            last_call: now,
72        });
73        if hist.last_call.elapsed() >= SEARCH_REPEAT_IDLE_RESET {
74            hist.call_count = 0;
75        }
76        hist.call_count = hist.call_count.saturating_add(1);
77        hist.last_call = now;
78        let n = hist.call_count;
79
80        match n {
81            1..=3 => None,
82            4..=6 => Some(format!(
83                "[hint: repeated search ({n}/6). Consider ctx_knowledge remember to store findings]"
84            )),
85            _ => Some(format!(
86                "[throttle: search repeated {n} times on same pattern. Use ctx_pack or ctx_knowledge to consolidate]"
87            )),
88        }
89    }
90}
91
92fn autonomy_enabled_effective(state: &AutonomyState) -> bool {
93    state.is_enabled()
94        && crate::core::profiles::active_profile()
95            .autonomy
96            .enabled_effective()
97}
98
99/// Returns true if enough tool calls have elapsed to trigger auto-consolidation.
100pub fn should_auto_consolidate(state: &AutonomyState, tool_calls: u32) -> bool {
101    if !state.is_enabled() || !state.config.auto_consolidate {
102        return false;
103    }
104    let every = state.config.consolidate_every_calls.max(1);
105    if !tool_calls.is_multiple_of(every) {
106        return false;
107    }
108
109    let now = SystemTime::now()
110        .duration_since(UNIX_EPOCH)
111        .map_or(0, |d| d.as_secs());
112    let last = state.last_consolidation_unix.load(Ordering::SeqCst);
113    if now.saturating_sub(last) < state.config.consolidate_cooldown_secs {
114        return false;
115    }
116    state.last_consolidation_unix.store(now, Ordering::SeqCst);
117    true
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn consolidation_respects_call_interval_and_cooldown() {
126        let mut state = AutonomyState::new();
127        state.config.enabled = true;
128        state.config.auto_consolidate = true;
129        state.config.consolidate_every_calls = 5;
130        state.config.consolidate_cooldown_secs = 60;
131
132        assert!(!should_auto_consolidate(&state, 4));
133        assert!(should_auto_consolidate(&state, 5));
134        assert!(!should_auto_consolidate(&state, 10));
135    }
136
137    #[test]
138    fn consolidation_disabled_never_triggers() {
139        let mut state = AutonomyState::new();
140        state.config.enabled = false;
141        state.config.auto_consolidate = true;
142        state.config.consolidate_every_calls = 1;
143        state.config.consolidate_cooldown_secs = 0;
144
145        assert!(!should_auto_consolidate(&state, 1));
146    }
147}