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