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            let _ = summary;
304        }
305    }
306
307    result
308}
309
310/// Output from post-read enrichment: optional related-file hints.
311#[derive(Default)]
312pub struct EnrichResult {
313    pub related_hint: Option<String>,
314}
315
316fn build_related_hints(
317    cache: &SessionCache,
318    file_path: &str,
319    index: &ProjectIndex,
320) -> Option<String> {
321    let related: Vec<_> = index
322        .edges
323        .iter()
324        .filter(|e| e.from == file_path || e.to == file_path)
325        .map(|e| if e.from == file_path { &e.to } else { &e.from })
326        .filter(|path| cache.get(path).is_none())
327        .take(3)
328        .collect();
329
330    if related.is_empty() {
331        return None;
332    }
333
334    let hints: Vec<String> = related.iter().map(|p| protocol::shorten_path(p)).collect();
335
336    Some(format!("[related: {}]", hints.join(", ")))
337}
338
339fn silent_preload_imports(
340    cache: &mut SessionCache,
341    file_path: &str,
342    index: &ProjectIndex,
343    project_root: &str,
344) {
345    let imports: Vec<String> = index
346        .edges
347        .iter()
348        .filter(|e| e.from == file_path)
349        .map(|e| e.to.clone())
350        .take(2)
351        .collect();
352
353    let jail_root = std::path::Path::new(project_root);
354    for path in imports {
355        let candidate = std::path::Path::new(&path);
356        let candidate = if candidate.is_absolute() {
357            candidate.to_path_buf()
358        } else {
359            jail_root.join(&path)
360        };
361        let Ok((jailed, warning)) = crate::core::io_boundary::jail_and_check_path(
362            "autonomy:silent_preload",
363            &candidate,
364            jail_root,
365        ) else {
366            continue;
367        };
368        if warning.is_some() {
369            continue;
370        }
371        let jailed_s = jailed.to_string_lossy().to_string();
372        if cache.get(&jailed_s).is_some() {
373            continue;
374        }
375
376        if let Ok(content) = std::fs::read_to_string(&jailed) {
377            let tokens = count_tokens(&content);
378            if tokens < 5000 {
379                cache.store(&jailed_s, &content);
380            }
381        }
382    }
383}
384
385/// Runs cache deduplication once the entry count exceeds the configured threshold.
386pub fn maybe_auto_dedup(state: &AutonomyState, cache: &mut SessionCache, trigger_tool: &str) {
387    if !autonomy_enabled_effective(state) {
388        return;
389    }
390
391    let prof = profile_autonomy();
392    if !state.config.auto_dedup || !prof.auto_dedup_effective() {
393        return;
394    }
395
396    if state
397        .dedup_applied
398        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
399        .is_err()
400    {
401        return;
402    }
403
404    let entries = cache.get_all_entries();
405    let threshold = state
406        .config
407        .dedup_threshold
408        .max(prof.dedup_threshold_effective())
409        .max(1);
410    if entries.len() < threshold {
411        state.dedup_applied.store(false, Ordering::SeqCst);
412        return;
413    }
414
415    let mut decisions = Vec::new();
416    if let Err((code, reason)) = policy_allows("ctx_dedup") {
417        decisions.push(AutonomyDriverDecisionV1 {
418            driver: AutonomyDriverKindV1::Dedup,
419            verdict: AutonomyVerdictV1::Skip,
420            reason_code: code,
421            reason,
422            detail: Some("policy guard (budget/slo)".to_string()),
423        });
424        record_event(AutonomyPhaseV1::PostRead, trigger_tool, None, decisions);
425        state.dedup_applied.store(false, Ordering::SeqCst);
426        return;
427    }
428
429    let out = crate::tools::ctx_dedup::handle_action(cache, "apply");
430    let summary = out.lines().next().unwrap_or("").trim().to_string();
431    decisions.push(AutonomyDriverDecisionV1 {
432        driver: AutonomyDriverKindV1::Dedup,
433        verdict: AutonomyVerdictV1::Run,
434        reason_code: "threshold_reached".to_string(),
435        reason: format!("cache entries >= {threshold}"),
436        detail: if summary.is_empty() {
437            None
438        } else {
439            Some(summary)
440        },
441    });
442    record_event(AutonomyPhaseV1::PostRead, trigger_tool, None, decisions);
443}
444
445/// Returns true if enough tool calls have elapsed to trigger auto-consolidation.
446pub fn should_auto_consolidate(state: &AutonomyState, tool_calls: u32) -> bool {
447    if !state.is_enabled() || !state.config.auto_consolidate {
448        return false;
449    }
450    let every = state.config.consolidate_every_calls.max(1);
451    if !tool_calls.is_multiple_of(every) {
452        return false;
453    }
454
455    let now = SystemTime::now()
456        .duration_since(UNIX_EPOCH)
457        .map_or(0, |d| d.as_secs());
458    let last = state.last_consolidation_unix.load(Ordering::SeqCst);
459    if now.saturating_sub(last) < state.config.consolidate_cooldown_secs {
460        return false;
461    }
462    state.last_consolidation_unix.store(now, Ordering::SeqCst);
463    true
464}
465
466fn take_large_output_hint_once(state: &AutonomyState, key: &str) -> bool {
467    if !autonomy_enabled_effective(state) {
468        return false;
469    }
470    let mut set = state
471        .large_output_hints_shown
472        .lock()
473        .unwrap_or_else(std::sync::PoisonError::into_inner);
474    set.insert(key.to_string())
475}
476
477/// `ctx_shell`: suggest sandbox / read modes when final output is large (bytes).
478pub fn large_ctx_shell_output_hint(
479    state: &AutonomyState,
480    command: &str,
481    output_bytes: usize,
482) -> Option<String> {
483    const THRESHOLD_BYTES: usize = 5000;
484    if output_bytes <= THRESHOLD_BYTES {
485        return None;
486    }
487    if !take_large_output_hint_once(state, "ctx_shell_large_bytes") {
488        return None;
489    }
490    let n = output_bytes;
491    if shell_command_looks_structured(command) {
492        Some(format!(
493            "[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\")]"
494        ))
495    } else {
496        Some(format!(
497            "[hint: large output ({n} bytes). Consider piping through ctx_execute for automatic compression, or use ctx_read(mode=\"aggressive\") for file contents]"
498        ))
499    }
500}
501
502fn shell_command_looks_structured(cmd: &str) -> bool {
503    let t = cmd.trim();
504    let lower = t.to_lowercase();
505    lower.contains("cargo test")
506        || lower.contains("npm test")
507        || t.starts_with("grep ")
508        || t.starts_with("rg ")
509}
510
511/// `ctx_read` full mode: suggest compressed read modes when output is very large (tokens).
512pub fn large_ctx_read_full_hint(
513    state: &AutonomyState,
514    mode: Option<&str>,
515    output: &str,
516) -> Option<String> {
517    const THRESHOLD_TOKENS: usize = 10_000;
518    let m = mode.unwrap_or("").trim();
519    if m != "full" {
520        return None;
521    }
522    let n = count_tokens(output);
523    if n <= THRESHOLD_TOKENS {
524        return None;
525    }
526    if !take_large_output_hint_once(state, "ctx_read_full_large_tokens") {
527        return None;
528    }
529    Some(format!(
530        "[hint: large file ({n} tokens). Consider mode=\"map\" or mode=\"aggressive\" for compressed view]"
531    ))
532}
533
534/// Suggests a more token-efficient lean-ctx tool when shell compression is low.
535pub fn shell_efficiency_hint(
536    state: &AutonomyState,
537    command: &str,
538    input_tokens: usize,
539    output_tokens: usize,
540) -> Option<String> {
541    if !autonomy_enabled_effective(state) {
542        return None;
543    }
544
545    if input_tokens == 0 {
546        return None;
547    }
548
549    let savings_pct =
550        (input_tokens.saturating_sub(output_tokens) as f64 / input_tokens as f64) * 100.0;
551    if savings_pct >= 20.0 {
552        return None;
553    }
554
555    let cmd_lower = command.to_lowercase();
556    if cmd_lower.starts_with("grep ")
557        || cmd_lower.starts_with("rg ")
558        || cmd_lower.starts_with("find ")
559        || cmd_lower.starts_with("ag ")
560    {
561        return Some("[hint: ctx_search is more token-efficient for code search]".to_string());
562    }
563
564    if cmd_lower.starts_with("cat ") || cmd_lower.starts_with("head ") {
565        return Some("[hint: ctx_read provides cached, compressed file access]".to_string());
566    }
567
568    None
569}
570
571fn looks_like_json(text: &str) -> bool {
572    let t = text.trim();
573    if !(t.starts_with('{') || t.starts_with('[')) {
574        return false;
575    }
576    serde_json::from_str::<serde_json::Value>(t).is_ok()
577}
578
579/// Applies `ctx_response` automatically for large outputs (guarded + bounded).
580/// Never runs on JSON outputs to avoid breaking machine-readable responses.
581pub fn maybe_auto_response(
582    state: &AutonomyState,
583    tool_name: &str,
584    action: Option<&str>,
585    output: &str,
586    crp_mode: CrpMode,
587    minimal_overhead: bool,
588) -> String {
589    if minimal_overhead || !autonomy_enabled_effective(state) {
590        return output.to_string();
591    }
592
593    let prof = profile_autonomy();
594    if !prof.auto_response_effective() {
595        return output.to_string();
596    }
597    if tool_name == "ctx_response" {
598        return output.to_string();
599    }
600
601    let input_tokens = count_tokens(output);
602    if input_tokens < prof.response_min_tokens_effective() {
603        return output.to_string();
604    }
605    if looks_like_json(output) {
606        record_event(
607            AutonomyPhaseV1::PostCall,
608            tool_name,
609            action,
610            vec![AutonomyDriverDecisionV1 {
611                driver: AutonomyDriverKindV1::Response,
612                verdict: AutonomyVerdictV1::Skip,
613                reason_code: "json_output".to_string(),
614                reason: "skip response shaping for JSON outputs".to_string(),
615                detail: None,
616            }],
617        );
618        return output.to_string();
619    }
620
621    if let Err((code, reason)) = policy_allows("ctx_response") {
622        record_event(
623            AutonomyPhaseV1::PostCall,
624            tool_name,
625            action,
626            vec![AutonomyDriverDecisionV1 {
627                driver: AutonomyDriverKindV1::Response,
628                verdict: AutonomyVerdictV1::Skip,
629                reason_code: code,
630                reason,
631                detail: Some("policy guard (budget/slo)".to_string()),
632            }],
633        );
634        return output.to_string();
635    }
636
637    let start = std::time::Instant::now();
638    let compressed = crate::tools::ctx_response::handle(output, crp_mode);
639    let duration = start.elapsed();
640    let output_tokens = count_tokens(&compressed);
641
642    let (verdict, reason_code, reason) = if compressed == output {
643        (
644            AutonomyVerdictV1::Skip,
645            "no_savings".to_string(),
646            "ctx_response made no changes".to_string(),
647        )
648    } else {
649        (
650            AutonomyVerdictV1::Run,
651            "output_large".to_string(),
652            "response shaping applied".to_string(),
653        )
654    };
655
656    record_event(
657        AutonomyPhaseV1::PostCall,
658        tool_name,
659        action,
660        vec![AutonomyDriverDecisionV1 {
661            driver: AutonomyDriverKindV1::Response,
662            verdict,
663            reason_code,
664            reason,
665            detail: Some(format!(
666                "tokens {}→{} in {:.1}ms",
667                input_tokens,
668                output_tokens,
669                duration.as_micros() as f64 / 1000.0
670            )),
671        }],
672    );
673
674    compressed
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680
681    #[test]
682    fn autonomy_state_starts_uninitialized() {
683        let state = AutonomyState::new();
684        assert!(!state.session_initialized.load(Ordering::SeqCst));
685        assert!(!state.dedup_applied.load(Ordering::SeqCst));
686    }
687
688    #[test]
689    fn session_initialized_fires_once() {
690        let state = AutonomyState::new();
691        let first = state.session_initialized.compare_exchange(
692            false,
693            true,
694            Ordering::SeqCst,
695            Ordering::SeqCst,
696        );
697        assert!(first.is_ok());
698        let second = state.session_initialized.compare_exchange(
699            false,
700            true,
701            Ordering::SeqCst,
702            Ordering::SeqCst,
703        );
704        assert!(second.is_err());
705    }
706
707    #[test]
708    fn shell_hint_for_grep() {
709        let state = AutonomyState::new();
710        let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 95);
711        assert!(hint.is_some());
712        assert!(hint.unwrap().contains("ctx_search"));
713    }
714
715    #[test]
716    fn shell_hint_none_when_good_savings() {
717        let state = AutonomyState::new();
718        let hint = shell_efficiency_hint(&state, "grep -rn foo .", 100, 50);
719        assert!(hint.is_none());
720    }
721
722    #[test]
723    fn shell_hint_none_for_unknown_command() {
724        let state = AutonomyState::new();
725        let hint = shell_efficiency_hint(&state, "cargo build", 100, 95);
726        assert!(hint.is_none());
727    }
728
729    #[test]
730    fn large_shell_hint_once_per_session() {
731        let state = AutonomyState::new();
732        let h1 = large_ctx_shell_output_hint(&state, "ls -la", 5001).expect("first");
733        assert!(h1.contains("5001 bytes"));
734        assert!(h1.contains("ctx_execute"));
735        assert!(large_ctx_shell_output_hint(&state, "ls -la", 5001).is_none());
736    }
737
738    #[test]
739    fn large_shell_structured_hint_mentions_execute() {
740        let state = AutonomyState::new();
741        let h = large_ctx_shell_output_hint(&state, "cargo test", 6000).expect("hint");
742        assert!(h.contains("structured"));
743        assert!(h.contains("ctx_execute"));
744    }
745
746    #[test]
747    fn large_read_full_hint_respects_mode() {
748        let state = AutonomyState::new();
749        let big = "word ".repeat(20_000);
750        assert!(large_ctx_read_full_hint(&state, Some("map"), &big).is_none());
751        let h = large_ctx_read_full_hint(&state, Some("full"), &big).expect("hint");
752        assert!(h.contains("tokens"));
753        assert!(h.contains("aggressive"));
754        assert!(large_ctx_read_full_hint(&state, Some("full"), &big).is_none());
755    }
756
757    #[test]
758    fn large_hints_disabled_when_autonomy_off() {
759        let mut state = AutonomyState::new();
760        state.config.enabled = false;
761        let big = "word ".repeat(20_000);
762        assert!(large_ctx_shell_output_hint(&state, "cargo test", 6000).is_none());
763        assert!(large_ctx_read_full_hint(&state, Some("full"), &big).is_none());
764    }
765
766    #[test]
767    fn disabled_state_blocks_all() {
768        let mut state = AutonomyState::new();
769        state.config.enabled = false;
770        assert!(!state.is_enabled());
771        let hint = shell_efficiency_hint(&state, "grep foo", 100, 95);
772        assert!(hint.is_none());
773    }
774
775    #[test]
776    fn track_search_none_first_three() {
777        let state = AutonomyState::new();
778        assert!(state.track_search("foo", "src").is_none());
779        assert!(state.track_search("foo", "src").is_none());
780        assert!(state.track_search("foo", "src").is_none());
781    }
782
783    #[test]
784    fn track_search_hint_band() {
785        let state = AutonomyState::new();
786        for _ in 0..3 {
787            assert!(state.track_search("bar", ".").is_none());
788        }
789        let h = state.track_search("bar", ".").expect("hint on 4th");
790        assert!(h.starts_with("[hint: repeated search (4/6)."));
791        assert!(h.contains("ctx_knowledge"));
792    }
793
794    #[test]
795    fn track_search_throttle_seventh() {
796        let state = AutonomyState::new();
797        for _ in 0..6 {
798            let _ = state.track_search("baz", "p");
799        }
800        let h = state.track_search("baz", "p").expect("throttle on 7th");
801        assert!(h.starts_with("[throttle: search repeated 7 times"));
802        assert!(h.contains("ctx_pack"));
803    }
804
805    #[test]
806    fn track_search_resets_after_idle() {
807        let state = AutonomyState::new();
808        for _ in 0..3 {
809            assert!(state.track_search("idle", "x").is_none());
810        }
811        std::thread::sleep(std::time::Duration::from_millis(80));
812        assert!(
813            state.track_search("idle", "x").is_none(),
814            "count should reset after idle window"
815        );
816    }
817
818    #[test]
819    fn track_search_disabled_no_tracking_messages() {
820        let mut state = AutonomyState::new();
821        state.config.enabled = false;
822        for _ in 0..8 {
823            assert!(state.track_search("q", "/").is_none());
824        }
825    }
826
827    #[test]
828    fn track_search_distinct_keys() {
829        let state = AutonomyState::new();
830        assert!(state.track_search("pat", "a").is_none());
831        assert!(state.track_search("pat", "a").is_none());
832        assert!(state.track_search("pat", "a").is_none());
833        assert!(state.track_search("pat", "a").is_some());
834        assert!(state.track_search("pat", "b").is_none());
835    }
836}