lean_ctx_server/tools/
autonomy.rs1use std::sync::atomic::Ordering;
8
9use lean_ctx::core::tokens::count_tokens;
10pub use lean_ctx_ext::core::autonomy::{AutonomyState, SearchHistory, should_auto_consolidate};
11
12fn profile_autonomy() -> lean_ctx::core::profiles::ProfileAutonomy {
13 lean_ctx::core::profiles::active_profile().autonomy
14}
15
16fn autonomy_enabled_effective(state: &AutonomyState) -> bool {
17 state.is_enabled() && profile_autonomy().enabled_effective()
18}
19
20pub fn delivers_session_briefing(
25 name: &str,
26 args: Option<&serde_json::Map<String, serde_json::Value>>,
27) -> bool {
28 let (name, args) = if name == "ctx_call" {
29 (
30 args.and_then(|a| a.get("name"))
31 .and_then(serde_json::Value::as_str)
32 .unwrap_or(""),
33 args.and_then(|a| a.get("arguments"))
34 .and_then(serde_json::Value::as_object),
35 )
36 } else {
37 (name, args)
38 };
39 name == "ctx_session"
40 && matches!(
41 args.and_then(|a| a.get("action"))
42 .and_then(serde_json::Value::as_str),
43 Some("load" | "status" | "show")
44 )
45}
46
47pub fn apply_auto_load_packages_once(state: &AutonomyState, project_root: Option<&str>) {
51 if lean_ctx::core::policy::runtime::is_active() || !autonomy_enabled_effective(state) {
52 return;
53 }
54 let Some(root) = project_root.filter(|r| !r.is_empty() && *r != ".") else {
55 return;
56 };
57 if state
58 .packages_applied
59 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
60 .is_ok()
61 {
62 let loaded = lean_ctx::core::context_package::auto_load_packages(root);
63 state
64 .packages_loaded
65 .lock()
66 .unwrap_or_else(std::sync::PoisonError::into_inner)
67 .extend(loaded);
68 }
69}
70
71pub fn session_wakeup_briefing(
81 state: &AutonomyState,
82 tool_name: &str,
83 task: Option<&str>,
84 project_root: Option<&str>,
85) -> Option<String> {
86 if lean_ctx::core::policy::runtime::is_active() || !autonomy_enabled_effective(state) {
88 return None;
89 }
90 if tool_name == "ctx_preload" {
92 return None;
93 }
94 let root = project_root.filter(|r| !r.is_empty() && *r != ".")?;
95 if state
96 .session_briefed
97 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
98 .is_err()
99 {
100 return None;
101 }
102 let mut loaded = std::mem::take(
105 &mut *state
106 .packages_loaded
107 .lock()
108 .unwrap_or_else(std::sync::PoisonError::into_inner),
109 );
110 if !state.packages_applied.swap(true, Ordering::SeqCst) {
111 loaded.extend(lean_ctx::core::context_package::auto_load_packages(root));
112 }
113 let packages = (!loaded.is_empty())
114 .then(|| format!("CONTEXT PACKAGES AUTO-LOADED: {}", loaded.join(", ")));
115 let tasks = lean_ctx_cloud::tasks::briefing(std::path::Path::new(root));
117 let frame = |briefing: &str| format!("{AUTO_CONTEXT_OPEN}\n{briefing}\n{AUTO_CONTEXT_CLOSE}");
118 let fixed = format!(
119 "{}\n{}",
120 packages.as_deref().unwrap_or(""),
121 tasks.as_deref().unwrap_or("")
122 );
123 let rules = lean_ctx_cloud::team_decisions::briefing(std::path::Path::new(root), |block| {
125 count_tokens(&frame(&format!("{fixed}\n{block}"))) <= AUTO_CONTEXT_MAX_TOKENS
126 });
127 let briefing = if lean_ctx::core::config::Config::load().enable_wakeup_ctx {
128 let reserved = count_tokens(&frame(&format!(
129 "{fixed}\n{}",
130 rules.as_deref().unwrap_or("")
131 )));
132 let budget = AUTO_CONTEXT_MAX_TOKENS.saturating_sub(reserved);
133 crate::tools::ctx_overview::build_wakeup_briefing_within(root, task, budget)
134 } else {
135 String::new()
136 };
137 let body = [
138 packages.unwrap_or_default(),
139 tasks.unwrap_or_default(),
140 rules.unwrap_or_default(),
141 briefing,
142 ]
143 .into_iter()
144 .filter(|part| !part.trim().is_empty())
145 .collect::<Vec<_>>()
146 .join("\n");
147 (!body.is_empty()).then(|| frame(&body))
148}
149
150pub const AUTO_CONTEXT_MAX_TOKENS: usize = 400;
153const AUTO_CONTEXT_OPEN: &str = "--- AUTO CONTEXT ---";
154const AUTO_CONTEXT_CLOSE: &str = "--- END AUTO CONTEXT ---";
155
156pub fn shell_efficiency_hint(
158 state: &AutonomyState,
159 command: &str,
160 input_tokens: usize,
161 output_tokens: usize,
162) -> Option<String> {
163 if !autonomy_enabled_effective(state) {
164 return None;
165 }
166
167 if input_tokens == 0 {
168 return None;
169 }
170
171 let savings_pct =
172 (input_tokens.saturating_sub(output_tokens) as f64 / input_tokens as f64) * 100.0;
173 if savings_pct >= 20.0 {
174 return None;
175 }
176
177 let cmd_lower = command.to_lowercase();
178 if cmd_lower.starts_with("grep ")
179 || cmd_lower.starts_with("rg ")
180 || cmd_lower.starts_with("find ")
181 || cmd_lower.starts_with("ag ")
182 {
183 return Some("[hint: ctx_search is more token-efficient for code search]".to_string());
184 }
185
186 if cmd_lower.starts_with("cat ") || cmd_lower.starts_with("head ") {
187 return Some("[hint: ctx_read provides cached, compressed file access]".to_string());
188 }
189
190 None
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 #[test]
198 fn only_ctx_session_load_or_status_delivers_the_briefing() {
199 let args = |v: serde_json::Value| v.as_object().cloned();
200 let status = args(serde_json::json!({"action": "status"}));
201 assert!(delivers_session_briefing("ctx_session", status.as_ref()));
202 let wrapped =
203 args(serde_json::json!({"name": "ctx_session", "arguments": {"action": "load"}}));
204 assert!(delivers_session_briefing("ctx_call", wrapped.as_ref()));
205 let task = args(serde_json::json!({"action": "task", "value": "x"}));
206 assert!(!delivers_session_briefing("ctx_session", task.as_ref()));
207 for tool in ["ctx_compose", "ctx_search", "ctx_read", "ctx_shell"] {
208 assert!(!delivers_session_briefing(tool, status.as_ref()), "{tool}");
209 }
210 }
211
212 #[test]
213 fn shell_hint_for_grep() {
214 let state = AutonomyState::new();
215 let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 95);
216 assert!(hint.is_some());
217 assert!(hint.unwrap().contains("ctx_search"));
218 let hint = shell_efficiency_hint(&state, "cat src/main.rs", 100, 95);
219 assert!(hint.is_some_and(|h| h.contains("ctx_read")));
220 }
221
222 #[test]
223 fn shell_hint_none_when_good_savings() {
224 let state = AutonomyState::new();
225 let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 50);
226 assert!(hint.is_none());
227 }
228
229 #[test]
230 fn shell_hint_none_for_unknown_command() {
231 let state = AutonomyState::new();
232 let hint = shell_efficiency_hint(&state, "cargo build", 100, 95);
233 assert!(hint.is_none());
234 }
235
236 #[test]
237 fn disabled_state_blocks_all() {
238 let mut state = AutonomyState::new();
239 state.config.enabled = false;
240 assert!(!state.is_enabled());
241 let hint = shell_efficiency_hint(&state, "grep foo", 100, 95);
242 assert!(hint.is_none());
243 }
244
245 #[test]
246 fn track_search_none_first_three() {
247 let _lock = lean_ctx::core::data_dir::test_env_lock();
248 let state = AutonomyState::new();
249 assert!(state.track_search("foo", "src").is_none());
250 assert!(state.track_search("foo", "src").is_none());
251 assert!(state.track_search("foo", "src").is_none());
252 }
253
254 #[test]
255 fn track_search_hint_band() {
256 let _lock = lean_ctx::core::data_dir::test_env_lock();
257 let state = AutonomyState::new();
258 for _ in 0..3 {
259 assert!(state.track_search("bar", ".").is_none());
260 }
261 let h = state.track_search("bar", ".").expect("hint on 4th");
262 assert!(h.starts_with("[hint: repeated search (4/6)."));
263 assert!(h.contains("ctx_knowledge"));
264 }
265
266 #[test]
267 fn track_search_throttle_seventh() {
268 let _lock = lean_ctx::core::data_dir::test_env_lock();
269 let state = AutonomyState::new();
270 for _ in 0..6 {
271 let _ = state.track_search("baz", "p");
272 }
273 let h = state.track_search("baz", "p").expect("throttle on 7th");
274 assert!(h.starts_with("[throttle: search repeated 7 times"));
275 assert!(h.contains("ctx_pack"));
276 }
277
278 #[test]
279 fn track_search_resets_after_idle() {
280 let _lock = lean_ctx::core::data_dir::test_env_lock();
281 let state = AutonomyState::new();
282 for _ in 0..3 {
283 assert!(state.track_search("idle", "x").is_none());
284 }
285 std::thread::sleep(std::time::Duration::from_millis(600));
286 assert!(
287 state.track_search("idle", "x").is_none(),
288 "count should reset after idle window"
289 );
290 }
291
292 #[test]
293 fn track_search_disabled_no_tracking_messages() {
294 let _lock = lean_ctx::core::data_dir::test_env_lock();
295 let mut state = AutonomyState::new();
296 state.config.enabled = false;
297 for _ in 0..8 {
298 assert!(state.track_search("q", "/").is_none());
299 }
300 }
301
302 #[test]
303 fn track_search_distinct_keys() {
304 let _lock = lean_ctx::core::data_dir::test_env_lock();
305 let state = AutonomyState::new();
306 assert!(state.track_search("pat", "a").is_none());
307 assert!(state.track_search("pat", "a").is_none());
308 assert!(state.track_search("pat", "a").is_none());
309 assert!(state.track_search("pat", "a").is_some());
310 assert!(state.track_search("pat", "b").is_none());
311 }
312}