Skip to main content

lean_ctx/tools/
autonomy.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
3use std::sync::Mutex;
4use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
5
6use crate::core::autonomy_drivers::{
7    AutonomyDriverDecisionV1, AutonomyDriverEventV1, AutonomyDriverKindV1, AutonomyPhaseV1,
8    AutonomyVerdictV1,
9};
10use crate::core::cache::SessionCache;
11use crate::core::config::AutonomyConfig;
12use crate::core::graph_index::ProjectIndex;
13use crate::core::protocol;
14use crate::core::tokens::count_tokens;
15use crate::tools::CrpMode;
16
17#[cfg(test)]
18const SEARCH_REPEAT_IDLE_RESET: Duration = Duration::from_millis(50);
19#[cfg(not(test))]
20const SEARCH_REPEAT_IDLE_RESET: Duration = Duration::from_mins(5);
21
22/// Per-key stats for progressive search hints (`ctx_search` / `ctx_semantic_search`).
23#[derive(Debug, Clone)]
24pub struct SearchHistory {
25    pub call_count: u32,
26    pub last_call: Instant,
27}
28
29/// Tracks autonomous action state: session init, dedup, and consolidation timing.
30pub struct AutonomyState {
31    pub session_initialized: AtomicBool,
32    pub dedup_applied: AtomicBool,
33    pub last_consolidation_unix: AtomicU64,
34    pub config: AutonomyConfig,
35    /// Repeated `pattern|path` keys for search tools (see [`AutonomyState::track_search`]).
36    pub search_repetition: Mutex<HashMap<String, SearchHistory>>,
37    /// One-shot keys for large-output hints (`ctx_shell` bytes, `ctx_read` full tokens).
38    pub large_output_hints_shown: Mutex<HashSet<String>>,
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_initialized: AtomicBool::new(false),
52            dedup_applied: AtomicBool::new(false),
53            last_consolidation_unix: AtomicU64::new(0),
54            config: AutonomyConfig::load(),
55            search_repetition: Mutex::new(HashMap::new()),
56            large_output_hints_shown: Mutex::new(HashSet::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 (50ms 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 profile_autonomy() -> crate::core::profiles::ProfileAutonomy {
103    crate::core::profiles::active_profile().autonomy
104}
105
106fn autonomy_enabled_effective(state: &AutonomyState) -> bool {
107    state.is_enabled() && profile_autonomy().enabled_effective()
108}
109
110fn policy_allows(tool: &str) -> Result<(), (String, String)> {
111    let policy = crate::core::degradation_policy::evaluate_v1_for_tool(tool, None);
112    match policy.decision.verdict {
113        crate::core::degradation_policy::DegradationVerdictV1::Ok
114        | crate::core::degradation_policy::DegradationVerdictV1::Warn => Ok(()),
115        crate::core::degradation_policy::DegradationVerdictV1::Throttle
116        | crate::core::degradation_policy::DegradationVerdictV1::Block => {
117            Err((policy.decision.reason_code, policy.decision.reason))
118        }
119    }
120}
121
122fn record_event(
123    phase: AutonomyPhaseV1,
124    tool: &str,
125    action: Option<&str>,
126    decisions: Vec<AutonomyDriverDecisionV1>,
127) {
128    let mut store = crate::core::autonomy_drivers::AutonomyDriversV1::load();
129    let ev = AutonomyDriverEventV1 {
130        seq: 0,
131        created_at: chrono::Utc::now().to_rfc3339(),
132        phase,
133        role: crate::core::roles::active_role_name(),
134        profile: crate::core::profiles::active_profile_name(),
135        tool: tool.to_string(),
136        action: action.map(std::string::ToString::to_string),
137        decisions,
138    };
139    store.record(ev);
140    let _ = store.save();
141}
142
143/// Auto-preloads project context on the first tool call of a session.
144pub fn session_lifecycle_pre_hook(
145    state: &AutonomyState,
146    tool_name: &str,
147    cache: &mut SessionCache,
148    task: Option<&str>,
149    project_root: Option<&str>,
150    crp_mode: CrpMode,
151) -> Option<String> {
152    if !autonomy_enabled_effective(state) {
153        return None;
154    }
155
156    if tool_name == "ctx_overview" || tool_name == "ctx_preload" {
157        return None;
158    }
159
160    let prof = profile_autonomy();
161    let root = match project_root {
162        Some(r) if !r.is_empty() && r != "." => r.to_string(),
163        _ => return None,
164    };
165
166    if state
167        .session_initialized
168        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
169        .is_err()
170    {
171        return None;
172    }
173
174    let mut decisions = Vec::new();
175
176    if !state.config.auto_preload || !prof.auto_preload_effective() {
177        decisions.push(AutonomyDriverDecisionV1 {
178            driver: AutonomyDriverKindV1::Preload,
179            verdict: AutonomyVerdictV1::Skip,
180            reason_code: "disabled".to_string(),
181            reason: "auto_preload disabled by config/profile".to_string(),
182            detail: None,
183        });
184        record_event(AutonomyPhaseV1::PreCall, tool_name, None, decisions);
185        return None;
186    }
187
188    let chosen_tool = if task.is_some() {
189        "ctx_preload"
190    } else {
191        "ctx_overview"
192    };
193    if let Err((code, reason)) = policy_allows(chosen_tool) {
194        decisions.push(AutonomyDriverDecisionV1 {
195            driver: AutonomyDriverKindV1::Preload,
196            verdict: AutonomyVerdictV1::Skip,
197            reason_code: code,
198            reason,
199            detail: Some("policy guard (budget/slo)".to_string()),
200        });
201        record_event(AutonomyPhaseV1::PreCall, tool_name, None, decisions);
202        return None;
203    }
204
205    let result = if let Some(task_desc) = task {
206        crate::tools::ctx_preload::handle(cache, task_desc, Some(&root), crp_mode)
207    } else {
208        let cache_readonly = &*cache;
209        crate::tools::ctx_overview::handle(cache_readonly, None, Some(&root), crp_mode)
210    };
211
212    let empty = result.trim().is_empty()
213        || result.contains("No directly relevant files")
214        || result.contains("INDEXING IN PROGRESS");
215    decisions.push(AutonomyDriverDecisionV1 {
216        driver: AutonomyDriverKindV1::Preload,
217        verdict: AutonomyVerdictV1::Run,
218        reason_code: "session_start".to_string(),
219        reason: "first tool call in session".to_string(),
220        detail: Some(format!("tool={chosen_tool} empty={empty}")),
221    });
222    record_event(AutonomyPhaseV1::PreCall, tool_name, None, decisions);
223
224    if empty {
225        return None;
226    }
227
228    Some(format!(
229        "--- AUTO CONTEXT ---\n{result}\n--- END AUTO CONTEXT ---"
230    ))
231}
232
233/// Appends related-file hints and silently preloads imports after a file read.
234pub fn enrich_after_read(
235    state: &AutonomyState,
236    cache: &mut SessionCache,
237    file_path: &str,
238    project_root: Option<&str>,
239    task: Option<&str>,
240    crp_mode: CrpMode,
241    minimal_overhead: bool,
242) -> EnrichResult {
243    let mut result = EnrichResult::default();
244
245    if !autonomy_enabled_effective(state) {
246        return result;
247    }
248
249    let prof = profile_autonomy();
250    let root = match project_root {
251        Some(r) if !r.is_empty() && r != "." => r.to_string(),
252        _ => return result,
253    };
254
255    let index = crate::core::graph_index::load_or_build(&root);
256    if index.files.is_empty() {
257        return result;
258    }
259
260    if state.config.auto_related && prof.auto_related_effective() {
261        result.related_hint = build_related_hints(cache, file_path, &index);
262    }
263
264    if state.config.silent_preload && prof.silent_preload_effective() {
265        silent_preload_imports(cache, file_path, &index, &root);
266    }
267
268    if !minimal_overhead && prof.auto_prefetch_effective() {
269        let mut decisions = Vec::new();
270        if let Err((code, reason)) = policy_allows("ctx_prefetch") {
271            decisions.push(AutonomyDriverDecisionV1 {
272                driver: AutonomyDriverKindV1::Prefetch,
273                verdict: AutonomyVerdictV1::Skip,
274                reason_code: code,
275                reason,
276                detail: Some("policy guard (budget/slo)".to_string()),
277            });
278            record_event(AutonomyPhaseV1::PostRead, "ctx_read", None, decisions);
279        } else {
280            let changed = vec![file_path.to_string()];
281            let out = crate::tools::ctx_prefetch::handle(
282                cache,
283                &root,
284                task,
285                Some(&changed),
286                prof.prefetch_budget_tokens_effective(),
287                Some(prof.prefetch_max_files_effective()),
288                crp_mode,
289            );
290            let summary = out.lines().next().unwrap_or("").trim().to_string();
291            decisions.push(AutonomyDriverDecisionV1 {
292                driver: AutonomyDriverKindV1::Prefetch,
293                verdict: AutonomyVerdictV1::Run,
294                reason_code: "after_read".to_string(),
295                reason: "bounded prefetch after ctx_read".to_string(),
296                detail: if summary.is_empty() {
297                    None
298                } else {
299                    Some(summary.clone())
300                },
301            });
302            record_event(AutonomyPhaseV1::PostRead, "ctx_read", None, decisions);
303            if !summary.is_empty() {
304                result.prefetch_hint = Some(format!("[prefetch] {summary}"));
305            }
306        }
307    }
308
309    result
310}
311
312/// Output from post-read enrichment: optional related-file hints.
313#[derive(Default)]
314pub struct EnrichResult {
315    pub related_hint: Option<String>,
316    pub prefetch_hint: Option<String>,
317}
318
319fn build_related_hints(
320    cache: &SessionCache,
321    file_path: &str,
322    index: &ProjectIndex,
323) -> Option<String> {
324    let related: Vec<_> = index
325        .edges
326        .iter()
327        .filter(|e| e.from == file_path || e.to == file_path)
328        .map(|e| if e.from == file_path { &e.to } else { &e.from })
329        .filter(|path| cache.get(path).is_none())
330        .take(3)
331        .collect();
332
333    if related.is_empty() {
334        return None;
335    }
336
337    let hints: Vec<String> = related.iter().map(|p| protocol::shorten_path(p)).collect();
338
339    Some(format!("[related: {}]", hints.join(", ")))
340}
341
342fn silent_preload_imports(
343    cache: &mut SessionCache,
344    file_path: &str,
345    index: &ProjectIndex,
346    project_root: &str,
347) {
348    let imports: Vec<String> = index
349        .edges
350        .iter()
351        .filter(|e| e.from == file_path)
352        .map(|e| e.to.clone())
353        .take(2)
354        .collect();
355
356    let jail_root = std::path::Path::new(project_root);
357    for path in imports {
358        let candidate = std::path::Path::new(&path);
359        let candidate = if candidate.is_absolute() {
360            candidate.to_path_buf()
361        } else {
362            jail_root.join(&path)
363        };
364        let Ok((jailed, warning)) = crate::core::io_boundary::jail_and_check_path(
365            "autonomy:silent_preload",
366            &candidate,
367            jail_root,
368        ) else {
369            continue;
370        };
371        if warning.is_some() {
372            continue;
373        }
374        let jailed_s = jailed.to_string_lossy().to_string();
375        if cache.get(&jailed_s).is_some() {
376            continue;
377        }
378
379        if let Ok(content) = std::fs::read_to_string(&jailed) {
380            let tokens = count_tokens(&content);
381            if tokens < 5000 {
382                cache.store(&jailed_s, content);
383            }
384        }
385    }
386}
387
388/// Runs cache deduplication once the entry count exceeds the configured threshold.
389pub fn maybe_auto_dedup(state: &AutonomyState, cache: &mut SessionCache, trigger_tool: &str) {
390    if !autonomy_enabled_effective(state) {
391        return;
392    }
393
394    let prof = profile_autonomy();
395    if !state.config.auto_dedup || !prof.auto_dedup_effective() {
396        return;
397    }
398
399    if state
400        .dedup_applied
401        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
402        .is_err()
403    {
404        return;
405    }
406
407    let entries = cache.get_all_entries();
408    let threshold = state
409        .config
410        .dedup_threshold
411        .max(prof.dedup_threshold_effective())
412        .max(1);
413    if entries.len() < threshold {
414        state.dedup_applied.store(false, Ordering::SeqCst);
415        return;
416    }
417
418    let mut decisions = Vec::new();
419    if let Err((code, reason)) = policy_allows("ctx_dedup") {
420        decisions.push(AutonomyDriverDecisionV1 {
421            driver: AutonomyDriverKindV1::Dedup,
422            verdict: AutonomyVerdictV1::Skip,
423            reason_code: code,
424            reason,
425            detail: Some("policy guard (budget/slo)".to_string()),
426        });
427        record_event(AutonomyPhaseV1::PostRead, trigger_tool, None, decisions);
428        state.dedup_applied.store(false, Ordering::SeqCst);
429        return;
430    }
431
432    let out = crate::tools::ctx_dedup::handle_action(cache, "apply");
433    let summary = out.lines().next().unwrap_or("").trim().to_string();
434    decisions.push(AutonomyDriverDecisionV1 {
435        driver: AutonomyDriverKindV1::Dedup,
436        verdict: AutonomyVerdictV1::Run,
437        reason_code: "threshold_reached".to_string(),
438        reason: format!("cache entries >= {threshold}"),
439        detail: if summary.is_empty() {
440            None
441        } else {
442            Some(summary)
443        },
444    });
445    record_event(AutonomyPhaseV1::PostRead, trigger_tool, None, decisions);
446}
447
448/// Returns true if enough tool calls have elapsed to trigger auto-consolidation.
449pub fn should_auto_consolidate(state: &AutonomyState, tool_calls: u32) -> bool {
450    if !state.is_enabled() || !state.config.auto_consolidate {
451        return false;
452    }
453    let every = state.config.consolidate_every_calls.max(1);
454    if !tool_calls.is_multiple_of(every) {
455        return false;
456    }
457
458    let now = SystemTime::now()
459        .duration_since(UNIX_EPOCH)
460        .map_or(0, |d| d.as_secs());
461    let last = state.last_consolidation_unix.load(Ordering::SeqCst);
462    if now.saturating_sub(last) < state.config.consolidate_cooldown_secs {
463        return false;
464    }
465    state.last_consolidation_unix.store(now, Ordering::SeqCst);
466    true
467}
468
469fn take_large_output_hint_once(state: &AutonomyState, key: &str) -> bool {
470    if !autonomy_enabled_effective(state) {
471        return false;
472    }
473    let mut set = state
474        .large_output_hints_shown
475        .lock()
476        .unwrap_or_else(std::sync::PoisonError::into_inner);
477    set.insert(key.to_string())
478}
479
480/// `ctx_shell`: suggest sandbox / read modes when final output is large (bytes).
481pub fn large_ctx_shell_output_hint(
482    state: &AutonomyState,
483    command: &str,
484    output_bytes: usize,
485) -> Option<String> {
486    const THRESHOLD_BYTES: usize = 5000;
487    if output_bytes <= THRESHOLD_BYTES {
488        return None;
489    }
490    if !take_large_output_hint_once(state, "ctx_shell_large_bytes") {
491        return None;
492    }
493    let n = output_bytes;
494    if shell_command_looks_structured(command) {
495        Some(format!(
496            "[hint: large output ({n} bytes). For structured output (e.g. cargo test, npm test, grep), use ctx_execute for automatic compression; for file contents use ctx_read(mode=\"aggressive\")]"
497        ))
498    } else {
499        Some(format!(
500            "[hint: large output ({n} bytes). Consider piping through ctx_execute for automatic compression, or use ctx_read(mode=\"aggressive\") for file contents]"
501        ))
502    }
503}
504
505fn shell_command_looks_structured(cmd: &str) -> bool {
506    let t = cmd.trim();
507    let lower = t.to_lowercase();
508    lower.contains("cargo test")
509        || lower.contains("npm test")
510        || t.starts_with("grep ")
511        || t.starts_with("rg ")
512}
513
514/// `ctx_read` full mode: suggest compressed read modes when output is very large (tokens).
515pub fn large_ctx_read_full_hint(
516    state: &AutonomyState,
517    mode: Option<&str>,
518    output: &str,
519) -> Option<String> {
520    const THRESHOLD_TOKENS: usize = 10_000;
521    let m = mode.unwrap_or("").trim();
522    if m != "full" {
523        return None;
524    }
525    let n = count_tokens(output);
526    if n <= THRESHOLD_TOKENS {
527        return None;
528    }
529    if !take_large_output_hint_once(state, "ctx_read_full_large_tokens") {
530        return None;
531    }
532    Some(format!(
533        "[hint: large file ({n} tokens). Consider mode=\"map\" or mode=\"aggressive\" for compressed view]"
534    ))
535}
536
537/// Suggests a more token-efficient lean-ctx tool when shell compression is low.
538pub fn shell_efficiency_hint(
539    state: &AutonomyState,
540    command: &str,
541    input_tokens: usize,
542    output_tokens: usize,
543) -> Option<String> {
544    if !autonomy_enabled_effective(state) {
545        return None;
546    }
547
548    if input_tokens == 0 {
549        return None;
550    }
551
552    let savings_pct =
553        (input_tokens.saturating_sub(output_tokens) as f64 / input_tokens as f64) * 100.0;
554    if savings_pct >= 20.0 {
555        return None;
556    }
557
558    let cmd_lower = command.to_lowercase();
559    if cmd_lower.starts_with("grep ")
560        || cmd_lower.starts_with("rg ")
561        || cmd_lower.starts_with("find ")
562        || cmd_lower.starts_with("ag ")
563    {
564        return Some("[hint: ctx_search is more token-efficient for code search]".to_string());
565    }
566
567    if cmd_lower.starts_with("cat ") || cmd_lower.starts_with("head ") {
568        return Some("[hint: ctx_read provides cached, compressed file access]".to_string());
569    }
570
571    None
572}
573
574fn looks_like_json(text: &str) -> bool {
575    let t = text.trim();
576    if !(t.starts_with('{') || t.starts_with('[')) {
577        return false;
578    }
579    serde_json::from_str::<serde_json::Value>(t).is_ok()
580}
581
582/// Applies `ctx_response` automatically for large outputs (guarded + bounded).
583/// Never runs on JSON outputs to avoid breaking machine-readable responses.
584pub fn maybe_auto_response(
585    state: &AutonomyState,
586    tool_name: &str,
587    action: Option<&str>,
588    output: &str,
589    crp_mode: CrpMode,
590    minimal_overhead: bool,
591) -> String {
592    if minimal_overhead || !autonomy_enabled_effective(state) {
593        return output.to_string();
594    }
595
596    let prof = profile_autonomy();
597    if !prof.auto_response_effective() {
598        return output.to_string();
599    }
600    if tool_name == "ctx_response" {
601        return output.to_string();
602    }
603
604    let input_tokens = count_tokens(output);
605    if input_tokens < prof.response_min_tokens_effective() {
606        return output.to_string();
607    }
608    if looks_like_json(output) {
609        record_event(
610            AutonomyPhaseV1::PostCall,
611            tool_name,
612            action,
613            vec![AutonomyDriverDecisionV1 {
614                driver: AutonomyDriverKindV1::Response,
615                verdict: AutonomyVerdictV1::Skip,
616                reason_code: "json_output".to_string(),
617                reason: "skip response shaping for JSON outputs".to_string(),
618                detail: None,
619            }],
620        );
621        return output.to_string();
622    }
623
624    if let Err((code, reason)) = policy_allows("ctx_response") {
625        record_event(
626            AutonomyPhaseV1::PostCall,
627            tool_name,
628            action,
629            vec![AutonomyDriverDecisionV1 {
630                driver: AutonomyDriverKindV1::Response,
631                verdict: AutonomyVerdictV1::Skip,
632                reason_code: code,
633                reason,
634                detail: Some("policy guard (budget/slo)".to_string()),
635            }],
636        );
637        return output.to_string();
638    }
639
640    let start = std::time::Instant::now();
641    let compressed = crate::tools::ctx_response::handle(output, crp_mode);
642    let duration = start.elapsed();
643    let output_tokens = count_tokens(&compressed);
644
645    let (verdict, reason_code, reason) = if compressed == output {
646        (
647            AutonomyVerdictV1::Skip,
648            "no_savings".to_string(),
649            "ctx_response made no changes".to_string(),
650        )
651    } else {
652        (
653            AutonomyVerdictV1::Run,
654            "output_large".to_string(),
655            "response shaping applied".to_string(),
656        )
657    };
658
659    record_event(
660        AutonomyPhaseV1::PostCall,
661        tool_name,
662        action,
663        vec![AutonomyDriverDecisionV1 {
664            driver: AutonomyDriverKindV1::Response,
665            verdict,
666            reason_code,
667            reason,
668            detail: Some(format!(
669                "tokens {}→{} in {:.1}ms",
670                input_tokens,
671                output_tokens,
672                duration.as_micros() as f64 / 1000.0
673            )),
674        }],
675    );
676
677    compressed
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    #[test]
685    fn autonomy_state_starts_uninitialized() {
686        let state = AutonomyState::new();
687        assert!(!state.session_initialized.load(Ordering::SeqCst));
688        assert!(!state.dedup_applied.load(Ordering::SeqCst));
689    }
690
691    #[test]
692    fn session_initialized_fires_once() {
693        let state = AutonomyState::new();
694        let first = state.session_initialized.compare_exchange(
695            false,
696            true,
697            Ordering::SeqCst,
698            Ordering::SeqCst,
699        );
700        assert!(first.is_ok());
701        let second = state.session_initialized.compare_exchange(
702            false,
703            true,
704            Ordering::SeqCst,
705            Ordering::SeqCst,
706        );
707        assert!(second.is_err());
708    }
709
710    #[test]
711    fn shell_hint_for_grep() {
712        let state = AutonomyState::new();
713        let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 95);
714        assert!(hint.is_some());
715        assert!(hint.unwrap().contains("ctx_search"));
716    }
717
718    #[test]
719    fn shell_hint_none_when_good_savings() {
720        let state = AutonomyState::new();
721        let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 50);
722        assert!(hint.is_none());
723    }
724
725    #[test]
726    fn shell_hint_none_for_unknown_command() {
727        let state = AutonomyState::new();
728        let hint = shell_efficiency_hint(&state, "cargo build", 100, 95);
729        assert!(hint.is_none());
730    }
731
732    #[test]
733    fn large_shell_hint_once_per_session() {
734        let state = AutonomyState::new();
735        let h1 = large_ctx_shell_output_hint(&state, "ls -la", 5001).expect("first");
736        assert!(h1.contains("5001 bytes"));
737        assert!(h1.contains("ctx_execute"));
738        assert!(large_ctx_shell_output_hint(&state, "ls -la", 5001).is_none());
739    }
740
741    #[test]
742    fn large_shell_structured_hint_mentions_execute() {
743        let state = AutonomyState::new();
744        let h = large_ctx_shell_output_hint(&state, "cargo test", 6000).expect("hint");
745        assert!(h.contains("structured"));
746        assert!(h.contains("ctx_execute"));
747    }
748
749    #[test]
750    fn large_read_full_hint_respects_mode() {
751        let state = AutonomyState::new();
752        let big = "word ".repeat(20_000);
753        assert!(large_ctx_read_full_hint(&state, Some("map"), &big).is_none());
754        let h = large_ctx_read_full_hint(&state, Some("full"), &big).expect("hint");
755        assert!(h.contains("tokens"));
756        assert!(h.contains("aggressive"));
757        assert!(large_ctx_read_full_hint(&state, Some("full"), &big).is_none());
758    }
759
760    #[test]
761    fn large_hints_disabled_when_autonomy_off() {
762        let mut state = AutonomyState::new();
763        state.config.enabled = false;
764        let big = "word ".repeat(20_000);
765        assert!(large_ctx_shell_output_hint(&state, "cargo test", 6000).is_none());
766        assert!(large_ctx_read_full_hint(&state, Some("full"), &big).is_none());
767    }
768
769    #[test]
770    fn disabled_state_blocks_all() {
771        let mut state = AutonomyState::new();
772        state.config.enabled = false;
773        assert!(!state.is_enabled());
774        let hint = shell_efficiency_hint(&state, "grep foo", 100, 95);
775        assert!(hint.is_none());
776    }
777
778    #[test]
779    fn track_search_none_first_three() {
780        let state = AutonomyState::new();
781        assert!(state.track_search("foo", "src").is_none());
782        assert!(state.track_search("foo", "src").is_none());
783        assert!(state.track_search("foo", "src").is_none());
784    }
785
786    #[test]
787    fn track_search_hint_band() {
788        let state = AutonomyState::new();
789        for _ in 0..3 {
790            assert!(state.track_search("bar", ".").is_none());
791        }
792        let h = state.track_search("bar", ".").expect("hint on 4th");
793        assert!(h.starts_with("[hint: repeated search (4/6)."));
794        assert!(h.contains("ctx_knowledge"));
795    }
796
797    #[test]
798    fn track_search_throttle_seventh() {
799        let state = AutonomyState::new();
800        for _ in 0..6 {
801            let _ = state.track_search("baz", "p");
802        }
803        let h = state.track_search("baz", "p").expect("throttle on 7th");
804        assert!(h.starts_with("[throttle: search repeated 7 times"));
805        assert!(h.contains("ctx_pack"));
806    }
807
808    #[test]
809    fn track_search_resets_after_idle() {
810        let state = AutonomyState::new();
811        for _ in 0..3 {
812            assert!(state.track_search("idle", "x").is_none());
813        }
814        std::thread::sleep(std::time::Duration::from_millis(80));
815        assert!(
816            state.track_search("idle", "x").is_none(),
817            "count should reset after idle window"
818        );
819    }
820
821    #[test]
822    fn track_search_disabled_no_tracking_messages() {
823        let mut state = AutonomyState::new();
824        state.config.enabled = false;
825        for _ in 0..8 {
826            assert!(state.track_search("q", "/").is_none());
827        }
828    }
829
830    #[test]
831    fn track_search_distinct_keys() {
832        let state = AutonomyState::new();
833        assert!(state.track_search("pat", "a").is_none());
834        assert!(state.track_search("pat", "a").is_none());
835        assert!(state.track_search("pat", "a").is_none());
836        assert!(state.track_search("pat", "a").is_some());
837        assert!(state.track_search("pat", "b").is_none());
838    }
839}