Skip to main content

lean_ctx_ext/core/
autonomy.rs

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