Skip to main content

lean_ctx/tools/
autonomy.rs

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