1use std::collections::HashMap;
2use std::sync::Mutex;
3
4use crate::core::cache::SessionCache;
5use crate::core::context_ledger::PressureAction;
6use crate::core::mode_predictor::{FileSignature, ModePredictor};
7use crate::core::ocla::registry::OclaRegistry;
8use crate::core::ocla::types::{ConfigTuningRequest, OclaRequestContext};
9
10static SOURCE_COUNTS: Mutex<Option<HashMap<&'static str, u64>>> = Mutex::new(None);
13
14pub fn count_source(source: &'static str) {
15 if let Ok(mut guard) = SOURCE_COUNTS.lock() {
16 *guard
17 .get_or_insert_with(HashMap::new)
18 .entry(source)
19 .or_insert(0) += 1;
20 }
21}
22
23pub fn source_counts() -> Vec<(&'static str, u64)> {
25 let Ok(guard) = SOURCE_COUNTS.lock() else {
26 return Vec::new();
27 };
28 let mut items: Vec<(&'static str, u64)> = guard
29 .as_ref()
30 .map(|m| m.iter().map(|(k, v)| (*k, *v)).collect())
31 .unwrap_or_default();
32 items.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
33 items
34}
35
36fn sources_path() -> Option<std::path::PathBuf> {
37 crate::core::data_dir::lean_ctx_data_dir()
38 .ok()
39 .map(|d| d.join("auto_mode_sources.json"))
40}
41
42pub fn flush_sources() {
47 let drained: Vec<(String, u64)> = {
48 let Ok(mut guard) = SOURCE_COUNTS.lock() else {
49 return;
50 };
51 match guard.take() {
52 Some(m) if !m.is_empty() => m.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
53 _ => return,
54 }
55 };
56 let Some(path) = sources_path() else {
57 return;
58 };
59 let mut on_disk: HashMap<String, u64> = std::fs::read_to_string(&path)
60 .ok()
61 .and_then(|s| serde_json::from_str(&s).ok())
62 .unwrap_or_default();
63 for (k, v) in drained {
64 *on_disk.entry(k).or_insert(0) += v;
65 }
66 let Ok(json) = serde_json::to_string_pretty(&on_disk) else {
67 return;
68 };
69 let tmp = path.with_extension("json.tmp");
70 if std::fs::write(&tmp, json).is_ok() {
71 let _ = std::fs::rename(&tmp, &path);
72 }
73}
74
75pub fn persisted_source_counts() -> Vec<(String, u64)> {
78 let Some(path) = sources_path() else {
79 return Vec::new();
80 };
81 let map: HashMap<String, u64> = std::fs::read_to_string(&path)
82 .ok()
83 .and_then(|s| serde_json::from_str(&s).ok())
84 .unwrap_or_default();
85 let mut items: Vec<(String, u64)> = map.into_iter().collect();
86 items.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
87 items
88}
89
90pub struct AutoModeContext<'a> {
91 pub path: &'a str,
92 pub token_count: usize,
93 pub line_count: Option<usize>,
94 pub task: Option<&'a str>,
95 pub cache: Option<&'a SessionCache>,
96}
97
98pub struct ResolvedMode {
99 pub mode: String,
100 pub source: &'static str,
101}
102
103pub fn resolve_mode_precedence(
106 explicit: Option<String>,
107 configured: Option<String>,
108 learned: Option<String>,
109 default: &str,
110) -> String {
111 explicit
112 .or(configured)
113 .or(learned)
114 .unwrap_or_else(|| default.to_string())
115}
116
117pub fn configured_default_mode() -> Option<String> {
120 crate::core::policy::runtime::active()
121 .and_then(|policy| policy.resolved.default_read_mode.clone())
122 .or_else(|| crate::core::persona::active().read_mode_override())
123 .or_else(|| {
124 let profile = crate::core::profiles::active_profile();
125 let engine = profile.engine_config();
126 let mode = engine.read.default_mode;
127 (mode != "auto").then(|| mode.to_string())
128 })
129}
130
131pub fn resolve(ctx: &AutoModeContext) -> ResolvedMode {
134 if crate::core::edit_quality::take_pending_anchored_escalation(ctx.path) {
139 return resolved("anchored", "anchored_edit_fail_escalation");
140 }
141
142 if crate::core::edit_quality::take_pending_escalation(ctx.path) {
145 return resolved("full", "edit_fail_escalation");
146 }
147
148 let r = resolve_inner(ctx);
149
150 if r.mode != "full" && crate::core::edit_quality::is_risky_mode(ctx.path, &r.mode) {
156 return resolved("full", "edit_quality_penalty");
157 }
158 r
159}
160
161fn resolve_inner(ctx: &AutoModeContext) -> ResolvedMode {
162 if crate::tools::ctx_read::is_instruction_file(ctx.path) {
163 return resolved("full", "instruction_file");
164 }
165
166 if crate::core::binary_detect::is_binary_file(ctx.path) {
167 return resolved("full", "binary");
168 }
169
170 if let Some(mode) = crate::kits::active_mode_for_path(ctx.path) {
174 return resolved(&mode, "context_kit");
175 }
176
177 if let Some(cache) = ctx.cache
178 && let Some(cached) = cache.get(ctx.path)
179 {
180 if !file_unchanged(ctx.path, cached) {
181 return resolved("diff", "cache_changed");
182 }
183 if cache.is_full_delivered(ctx.path) {
186 return resolved("full", "cache_hit");
187 }
188 if let Some(prev_mode) = cache.last_mode(ctx.path)
191 && prev_mode != "full"
192 {
193 return resolved(&prev_mode, "cache_hit_compressed");
194 }
195 }
196
197 if ctx.token_count <= 200 {
198 return resolved("full", "small_file");
199 }
200
201 let ext = std::path::Path::new(ctx.path)
202 .extension()
203 .and_then(|e| e.to_str())
204 .unwrap_or("");
205
206 if ctx.token_count <= 400 && is_code(ext) {
207 return resolved("full", "small_code_file");
208 }
209
210 if is_config_or_data(ext, ctx.path) {
211 if ctx.token_count <= 1000 {
212 return resolved("full", "config_data");
213 }
214 return resolved("map", "config_data_large");
215 }
216
217 if crate::core::diagnostics_store::has_error(ctx.path) {
220 return resolved("full", "active_diagnostic");
221 }
222
223 if task_names_file(ctx.task, ctx.path)
228 && intent_recommended_mode(ctx.task).as_deref() == Some("full")
229 {
230 return resolved("full", "task_suspect_file");
231 }
232
233 if let Some(mode) = intent_recommended_mode(ctx.task) {
234 if mode != "full" {
240 return resolved(&mode, "intent");
241 }
242 }
243
244 if crate::core::config::Config::load().auto_mode_learning_effective()
250 && let Some(r) = resolve_adaptive(ctx)
251 {
252 return r;
253 }
254
255 if crate::core::cognitive_gate::basic_science_enabled() && is_code(ext) && ctx.token_count > 500
266 {
267 if ctx.token_count > 8000 {
268 return resolved("cognitive", "science_cognitive_large");
269 }
270 if ctx.token_count > 2000 {
271 return resolved("cognitive", "science_cognitive_medium");
272 }
273 return resolved("cognitive", "science_cognitive_small");
274 }
275
276 let cfg = crate::core::config::Config::load();
279 if cfg.progressive_disclosure_effective() {
280 let lines = ctx
281 .line_count
282 .unwrap_or_else(|| estimate_lines(ctx.token_count));
283 let threshold = cfg.progressive_threshold_lines as usize;
284 let sig_max = cfg.progressive_signatures_max as usize;
285
286 if lines >= sig_max && is_code(ext) {
287 return resolved("map", "progressive_manifest");
288 }
289 if lines >= threshold && is_code(ext) {
290 return resolved("signatures", "progressive_signatures");
291 }
292 }
293
294 let structure_first = cfg.structure_first_effective();
300 let heuristic = heuristic_mode(ext, ctx.token_count, structure_first);
301 let source = if structure_first && heuristic == "map" && ctx.token_count <= 6000 {
302 "structure_first"
303 } else {
304 "heuristic"
305 };
306 resolved(&heuristic, source)
307}
308
309fn resolve_adaptive(ctx: &AutoModeContext) -> Option<ResolvedMode> {
317 if let Ok(bt) = crate::core::bounce_tracker::global().lock()
318 && bt.should_force_full(ctx.path)
319 {
320 return Some(resolved("full", "bounce_tracker"));
321 }
322
323 if crate::core::path_mode_memory::should_force_full(ctx.path) {
327 return Some(resolved("full", "path_bounce_memory"));
328 }
329
330 let sig = FileSignature::from_path(ctx.path, ctx.token_count);
331 let predictor = ModePredictor::new();
332 let mut predicted = predictor
333 .predict_best_mode(&sig)
334 .unwrap_or_else(|| "full".to_string());
335 if predicted == "auto" {
336 predicted = "full".to_string();
337 }
338
339 if predicted != "full"
340 && let Some(bandit_override) = bandit_explore(ctx.path, ctx.token_count)
341 {
342 predicted = bandit_override;
343 }
344
345 if predicted != "full"
349 && let Some((access_count, avg_ratio)) = crate::core::heatmap::entry_stats(ctx.path)
350 && access_count >= 5
351 && avg_ratio < 0.30
352 {
353 let conservative = match predicted.as_str() {
354 "signatures" | "aggressive" | "entropy" => "map".to_string(),
355 "map" if ctx.token_count <= 6000 => "full".to_string(),
356 other => other.to_string(),
357 };
358 if conservative != predicted {
359 return Some(resolved(&conservative, "heatmap_conservative"));
360 }
361 }
362
363 let request_id = "auto-mode-resolution";
364 let request = ConfigTuningRequest {
365 context: OclaRequestContext {
366 request_id: request_id.to_string(),
367 session_id: "auto-mode".to_string(),
368 agent_id: "lean-ctx".to_string(),
369 content_ref: ctx.path.to_string(),
370 tenant_id: None,
371 trace_id: "tr-unit".into(),
372 task_id: None,
373 parent_task_id: None,
374 },
375 config_ref: predicted.clone(),
376 objective_ref: ctx.task.unwrap_or_default().to_string(),
377 };
378 let chosen = match OclaRegistry::global().config_tuner.propose_tuning(request) {
379 Ok(proposal) => proposal
380 .proposal_ref
381 .strip_prefix(&format!("proposal:{predicted}->"))
382 .and_then(|value| value.strip_suffix(&format!(":{request_id}")))
383 .map_or_else(|| predicted.clone(), ToString::to_string),
384 Err(_) => predicted.clone(),
385 };
386
387 if ctx.token_count > 2000 {
388 if (predicted == "map" || predicted == "signatures")
389 && chosen != "map"
390 && chosen != "signatures"
391 {
392 return Some(resolved(&predicted, "predictor_guard"));
393 }
394 if chosen == "full" && predicted != "full" {
395 return Some(resolved(&predicted, "predictor_override"));
396 }
397 }
398
399 if chosen != predicted {
400 return Some(resolved(&chosen, "adaptive_policy"));
401 }
402
403 if predicted != "full" {
404 return Some(resolved(&predicted, "predictor"));
405 }
406
407 None
408}
409
410pub fn pressure_downgrade(requested_mode: &str, action: &PressureAction) -> Option<String> {
413 match action {
414 PressureAction::SuggestCompression => match requested_mode {
415 "auto" | "full" => Some("map".to_string()),
416 _ => None,
417 },
418 PressureAction::ForceCompression => match requested_mode {
419 "full" => Some("map".to_string()),
420 "auto" | "map" | "cognitive" => Some("signatures".to_string()),
421 _ => None,
422 },
423 PressureAction::EvictLeastRelevant => match requested_mode {
424 "full" => Some("map".to_string()),
425 "auto" | "map" | "cognitive" => Some("signatures".to_string()),
426 "signatures" => Some("reference".to_string()),
427 _ => None,
428 },
429 PressureAction::NoAction => None,
430 }
431}
432
433fn task_names_file(task: Option<&str>, path: &str) -> bool {
440 let Some(task) = task else {
441 return false;
442 };
443 let basename = std::path::Path::new(path)
444 .file_name()
445 .and_then(|n| n.to_str())
446 .unwrap_or("");
447 if basename.len() < 4 || !basename.contains('.') {
448 return false;
449 }
450 task.to_ascii_lowercase()
451 .contains(&basename.to_ascii_lowercase())
452}
453
454fn intent_recommended_mode(task: Option<&str>) -> Option<String> {
455 let task_desc = task?;
456 let classification = crate::core::intent_engine::classify(task_desc);
457 if classification.confidence < 0.4 {
458 return None;
459 }
460 let route = crate::core::intent_engine::route_intent(task_desc, &classification);
461 let mode =
462 crate::core::intent_router::read_mode_for_tier(route.model_tier, classification.task_type);
463 if mode == "auto" {
464 return None;
465 }
466 Some(mode)
467}
468
469fn bandit_explore(file_path: &str, token_count: usize) -> Option<String> {
470 let project_root =
471 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)?;
472 let ext = std::path::Path::new(file_path)
473 .extension()
474 .and_then(|e| e.to_str())
475 .unwrap_or("");
476 let bucket = match token_count {
477 0..=2000 => "sm",
478 2001..=10000 => "md",
479 10001..=50000 => "lg",
480 _ => "xl",
481 };
482 let bandit_key = crate::core::bandit::bandit_key("mode", ext, Some(bucket));
483 let mut store = crate::core::bandit::BanditStore::load(&project_root);
484 let bandit = store.get_or_create(&bandit_key);
485 let arm = bandit.choose_arm();
487 if arm.budget_ratio < 0.25 && token_count > 2000 {
488 Some("aggressive".to_string())
489 } else {
490 None
491 }
492}
493
494fn heuristic_mode(ext: &str, token_count: usize, structure_first: bool) -> String {
495 if token_count > 8000 {
496 if is_code(ext) {
497 return "map".to_string();
498 }
499 return "aggressive".to_string();
500 }
501 if token_count > 2000 && is_prose(ext) {
502 return "aggressive".to_string();
503 }
504 if token_count > 500 && is_prose(ext) {
505 return "map".to_string();
506 }
507 if token_count > 500 && !is_code(ext) && !is_prose(ext) {
508 return "map".to_string();
509 }
510 if token_count > 6000 && is_code(ext) {
512 return "map".to_string();
513 }
514 if structure_first && token_count > 500 && is_code(ext) {
521 return "map".to_string();
522 }
523 if token_count > 500 && is_code(ext) {
528 return "signatures".to_string();
529 }
530 "full".to_string()
531}
532
533fn file_unchanged(path: &str, cached: &crate::core::cache::CacheEntry) -> bool {
542 let Some(stored_mtime) = cached.stored_mtime else {
543 return false;
544 };
545 let Ok(meta) = std::fs::metadata(path) else {
546 return false;
547 };
548 let Ok(current_mtime) = meta.modified() else {
549 return false;
550 };
551 current_mtime == stored_mtime
552}
553
554fn is_code(ext: &str) -> bool {
555 matches!(
556 ext,
557 "rs" | "ts"
558 | "tsx"
559 | "js"
560 | "jsx"
561 | "py"
562 | "go"
563 | "java"
564 | "c"
565 | "cpp"
566 | "cc"
567 | "h"
568 | "hpp"
569 | "rb"
570 | "cs"
571 | "kt"
572 | "swift"
573 | "php"
574 | "zig"
575 | "ex"
576 | "exs"
577 | "scala"
578 | "sc"
579 | "dart"
580 | "toml"
581 | "yaml"
582 | "yml"
583 | "json"
584 | "sh"
585 | "bash"
586 | "svelte"
587 | "vue"
588 | "astro"
589 | "mdx"
590 | "njk"
591 | "hbs"
592 | "ejs"
593 | "erb"
594 | "jinja"
595 | "jinja2"
596 | "twig"
597 | "pug"
598 | "slim"
599 | "haml"
600 | "liquid"
601 )
602}
603
604fn is_prose(ext: &str) -> bool {
605 matches!(
606 ext,
607 "md" | "mdx" | "txt" | "rst" | "adoc" | "org" | "tex" | "html" | "htm"
608 )
609}
610
611fn estimate_lines(token_count: usize) -> usize {
614 token_count / 4
615}
616
617fn is_config_or_data(ext: &str, path: &str) -> bool {
618 if matches!(ext, "xml" | "ini" | "cfg" | "env") {
619 return true;
620 }
621 let name = std::path::Path::new(path)
622 .file_name()
623 .and_then(|n| n.to_str())
624 .unwrap_or("");
625 matches!(
626 name,
627 "Cargo.toml"
628 | "package.json"
629 | "tsconfig.json"
630 | "Makefile"
631 | "Dockerfile"
632 | "docker-compose.yml"
633 | ".gitignore"
634 | ".env"
635 | "pyproject.toml"
636 | "go.mod"
637 | "build.gradle"
638 | "pom.xml"
639 )
640}
641
642fn resolved(mode: &str, source: &'static str) -> ResolvedMode {
643 count_source(source);
644 ResolvedMode {
645 mode: mode.to_string(),
646 source,
647 }
648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653
654 #[test]
655 fn mode_precedence_is_explicit_then_configured_then_learned_then_default() {
656 assert_eq!(
657 resolve_mode_precedence(
658 Some("raw".to_string()),
659 Some("map".to_string()),
660 Some("signatures".to_string()),
661 "full",
662 ),
663 "raw"
664 );
665 assert_eq!(
666 resolve_mode_precedence(
667 None,
668 Some("map".to_string()),
669 Some("signatures".to_string()),
670 "full",
671 ),
672 "map"
673 );
674 assert_eq!(
675 resolve_mode_precedence(None, None, Some("signatures".to_string()), "full"),
676 "signatures"
677 );
678 assert_eq!(resolve_mode_precedence(None, None, None, "full"), "full");
679 }
680
681 #[test]
682 fn pressure_suggest_full_to_map() {
683 assert_eq!(
684 pressure_downgrade("full", &PressureAction::SuggestCompression),
685 Some("map".to_string())
686 );
687 }
688
689 #[test]
690 fn pressure_suggest_auto_to_map() {
691 assert_eq!(
692 pressure_downgrade("auto", &PressureAction::SuggestCompression),
693 Some("map".to_string())
694 );
695 }
696
697 #[test]
698 fn pressure_suggest_does_not_touch_signatures() {
699 assert!(pressure_downgrade("signatures", &PressureAction::SuggestCompression).is_none());
700 }
701
702 #[test]
703 fn pressure_force_full_to_map() {
704 assert_eq!(
705 pressure_downgrade("full", &PressureAction::ForceCompression),
706 Some("map".to_string())
707 );
708 }
709
710 #[test]
711 fn pressure_force_map_to_signatures() {
712 assert_eq!(
713 pressure_downgrade("map", &PressureAction::ForceCompression),
714 Some("signatures".to_string())
715 );
716 }
717
718 #[test]
719 fn pressure_evict_signatures_to_reference() {
720 assert_eq!(
721 pressure_downgrade("signatures", &PressureAction::EvictLeastRelevant),
722 Some("reference".to_string())
723 );
724 }
725
726 #[test]
727 fn pressure_noaction_returns_none() {
728 assert!(pressure_downgrade("full", &PressureAction::NoAction).is_none());
729 }
730
731 #[test]
732 fn flush_sources_merges_additively_into_disk_file() {
733 let _lock = crate::core::data_dir::test_env_lock();
734 let dir = std::env::temp_dir().join(format!("lctx-amr-flush-{}", std::process::id()));
735 let _ = std::fs::create_dir_all(&dir);
736 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
737 let _ = std::fs::remove_file(dir.join("auto_mode_sources.json"));
738
739 count_source("test_flush_alpha");
742 count_source("test_flush_alpha");
743 count_source("test_flush_beta");
744 flush_sources();
745
746 count_source("test_flush_alpha");
747 flush_sources();
748
749 let persisted = persisted_source_counts();
750 let get = |k: &str| {
751 persisted
752 .iter()
753 .find(|(s, _)| s == k)
754 .map_or(0, |(_, n)| *n)
755 };
756 assert_eq!(
757 get("test_flush_alpha"),
758 3,
759 "two flushes must merge additively"
760 );
761 assert_eq!(get("test_flush_beta"), 1);
762
763 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
764 let _ = std::fs::remove_dir_all(&dir);
765 }
766
767 #[test]
768 fn small_file_always_full() {
769 let ctx = AutoModeContext {
770 path: "test.rs",
771 token_count: 100,
772 line_count: None,
773 task: None,
774 cache: None,
775 };
776 let result = resolve(&ctx);
777 assert_eq!(result.mode, "full");
778 assert_eq!(result.source, "small_file");
779 }
780
781 #[test]
782 fn config_file_returns_full() {
783 let ctx = AutoModeContext {
784 path: "config.ini",
785 token_count: 500,
786 line_count: None,
787 task: None,
788 cache: None,
789 };
790 let result = resolve(&ctx);
791 assert_eq!(result.mode, "full");
792 assert_eq!(result.source, "config_data");
793 }
794
795 #[test]
796 fn cached_compressed_only_file_reuses_cached_mode() {
797 let dir = tempfile::tempdir().unwrap();
801 let file = dir.path().join("large.rs");
802 let body = "fn placeholder() { let _ = 1; }\n".repeat(900);
803 std::fs::write(&file, &body).unwrap();
804 let path = file.to_str().unwrap();
805
806 let mut cache = SessionCache::new();
807 cache.store(path, &body);
808 cache.get_mut(path).unwrap().last_mode = "map".to_string();
809
810 let ctx = AutoModeContext {
811 path,
812 token_count: 7000,
813 line_count: None,
814 task: None,
815 cache: Some(&cache),
816 };
817 let result = resolve(&ctx);
818 assert!(
819 result.mode == "map" || result.mode == "cognitive",
820 "expected map or cognitive, got: {}",
821 result.mode
822 );
823 assert_eq!(result.source, "cache_hit_compressed");
824 }
825
826 #[test]
827 fn cached_full_delivered_file_short_circuits_to_stub() {
828 let dir = tempfile::tempdir().unwrap();
831 let file = dir.path().join("medium.rs");
832 let body = "fn placeholder() { let _ = 1; }\n".repeat(400);
833 std::fs::write(&file, &body).unwrap();
834 let path = file.to_str().unwrap();
835
836 let mut cache = SessionCache::new();
837 cache.store(path, &body);
838 cache.mark_full_delivered(path);
839
840 let ctx = AutoModeContext {
841 path,
842 token_count: 3000,
843 line_count: None,
844 task: None,
845 cache: Some(&cache),
846 };
847 let result = resolve(&ctx);
848 assert_eq!(result.mode, "full");
849 assert_eq!(result.source, "cache_hit");
850 }
851
852 #[test]
853 fn intent_explore_returns_map() {
854 let ctx = AutoModeContext {
855 path: "large.rs",
856 token_count: 5000,
857 line_count: None,
858 task: Some("how does the cache work?"),
859 cache: None,
860 };
861 let result = resolve(&ctx);
862 assert!(
863 result.mode == "map" || result.mode == "cognitive",
864 "expected map or cognitive, got: {}",
865 result.mode
866 );
867 assert_eq!(result.source, "intent");
868 }
869
870 #[test]
871 fn task_names_file_matches_explicit_filename() {
872 assert!(task_names_file(
873 Some("fix the version sort in versioncmp.c"),
874 "src/versioncmp.c"
875 ));
876 assert!(task_names_file(
877 Some("why does graph.ts loop?"),
878 "web/src/graph.ts"
879 ));
880 }
881
882 #[test]
883 fn task_names_file_ignores_bare_stems_and_trivia() {
884 assert!(!task_names_file(
886 Some("improve the parser"),
887 "src/parser.rs"
888 ));
889 assert!(!task_names_file(None, "src/parser.rs"));
890 assert!(!task_names_file(Some("touch a.c"), "a.c"));
892 assert!(!task_names_file(Some("look at Makefile"), "Makefile"));
893 }
894
895 #[test]
896 fn task_suspect_file_overrides_intent() {
897 let _lock = crate::core::data_dir::test_env_lock();
898 let dir = std::env::temp_dir().join(format!("lctx-amr-suspect-{}", std::process::id()));
899 let _ = std::fs::create_dir_all(&dir);
900 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
901
902 let ctx = AutoModeContext {
906 path: "large.rs",
907 token_count: 5000,
908 line_count: None,
909 task: Some("how does large.rs build the cache?"),
910 cache: None,
911 };
912 let result = resolve(&ctx);
913 assert_eq!(result.mode, "full");
914 assert_eq!(result.source, "task_suspect_file");
915
916 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
917 let _ = std::fs::remove_dir_all(&dir);
918 }
919
920 #[test]
921 fn intent_full_skipped_for_non_suspect_files() {
922 let _iso = crate::core::data_dir::isolated_data_dir();
928 let ctx = AutoModeContext {
929 path: "unrelated_module.rs",
930 token_count: 5000,
931 line_count: None,
932 task: Some("fix the bug in parser.rs"),
933 cache: None,
934 };
935 let result = resolve(&ctx);
936 assert_ne!(
937 result.mode, "full",
938 "non-suspect file must not get full mode from a coding task intent"
939 );
940 assert_ne!(
941 result.source, "intent",
942 "general intent must not force full on non-suspect files"
943 );
944 }
945
946 #[test]
947 fn heuristic_medium_code_uses_signatures_by_default() {
948 assert_eq!(heuristic_mode("rs", 1500, false), "signatures");
949 assert_eq!(heuristic_mode("ts", 1000, false), "signatures");
950 }
951
952 #[test]
953 fn heuristic_structure_first_maps_medium_code() {
954 assert_eq!(heuristic_mode("rs", 1500, true), "map");
956 assert_eq!(heuristic_mode("c", 800, true), "map");
957 }
958
959 #[test]
960 fn heuristic_structure_first_keeps_tiny_and_prose_full() {
961 assert_eq!(heuristic_mode("rs", 400, true), "full");
963 assert_eq!(heuristic_mode("md", 4000, true), "aggressive");
965 assert_eq!(heuristic_mode("md", 1500, true), "map");
966 assert_eq!(heuristic_mode("txt", 3000, true), "aggressive");
967 assert_eq!(heuristic_mode("txt", 1000, true), "map");
968 }
969
970 #[test]
971 fn code_and_data_extensions_cover_progressive_formats() {
972 for ext in [
973 "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "rb", "swift",
974 "kt", "scala", "toml", "yaml", "yml", "json", "sh", "bash", "svelte", "vue", "astro",
975 "mdx", "njk", "hbs", "ejs", "erb", "jinja", "jinja2", "twig", "pug", "slim", "haml",
976 "liquid",
977 ] {
978 assert!(
979 is_code(ext),
980 "{ext} should participate in structure-first modes"
981 );
982 }
983 assert!(!is_code("md"));
985 }
986
987 #[test]
988 fn heuristic_large_code_maps_regardless() {
989 assert_eq!(heuristic_mode("rs", 9000, false), "map");
990 assert_eq!(heuristic_mode("rs", 9000, true), "map");
991 }
992
993 #[test]
999 fn structure_first_resolve_bugfix_cold_read() {
1000 let _lock = crate::core::data_dir::test_env_lock();
1001 let dir = std::env::temp_dir().join(format!("lctx-amr-sf-{}", std::process::id()));
1002 let _ = std::fs::create_dir_all(&dir);
1003 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1004 crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "1");
1005 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1006
1007 let suspect = AutoModeContext {
1008 path: "src/versioncmp.c",
1009 token_count: 1500,
1010 line_count: None,
1011 task: None,
1012 cache: None,
1013 };
1014 let result = resolve(&suspect);
1015 assert!(
1016 result.mode == "map" || result.mode == "cognitive",
1017 "expected map or cognitive, got: {}",
1018 result.mode
1019 );
1020 assert!(
1021 result.source == "structure_first" || result.source.starts_with("science_"),
1022 "source: {}",
1023 result.source
1024 );
1025
1026 let tiny = AutoModeContext {
1027 path: "src/util.c",
1028 token_count: 120,
1029 line_count: None,
1030 task: None,
1031 cache: None,
1032 };
1033 assert_eq!(resolve(&tiny).mode, "full");
1034
1035 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1036 crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1037 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1038 let _ = std::fs::remove_dir_all(&dir);
1039 }
1040
1041 #[test]
1042 fn structure_first_off_uses_signatures_for_medium_code() {
1043 let _lock = crate::core::data_dir::test_env_lock();
1044 let dir = std::env::temp_dir().join(format!("lctx-amr-sfoff-{}", std::process::id()));
1045 let _ = std::fs::create_dir_all(&dir);
1046 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1047 crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "0");
1048 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1049
1050 let ctx = AutoModeContext {
1051 path: "src/versioncmp.c",
1052 token_count: 1500,
1053 line_count: None,
1054 task: None,
1055 cache: None,
1056 };
1057 let result = resolve(&ctx);
1058 assert!(
1059 result.mode == "signatures" || result.mode == "cognitive",
1060 "sf=off → signatures or cognitive, got: {}",
1061 result.mode
1062 );
1063 assert!(
1064 result.source == "heuristic" || result.source.starts_with("science_"),
1065 "source: {}",
1066 result.source
1067 );
1068
1069 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1070 crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1071 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1072 let _ = std::fs::remove_dir_all(&dir);
1073 }
1074
1075 #[test]
1079 fn learning_off_by_default_is_deterministic() {
1080 let _lock = crate::core::data_dir::test_env_lock();
1081 let dir = std::env::temp_dir().join(format!("lctx-amr-det-{}", std::process::id()));
1082 let _ = std::fs::create_dir_all(&dir);
1083 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1084 crate::test_env::remove_var("LEAN_CTX_AUTO_MODE_LEARNING");
1085 crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1086 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1087
1088 let ctx = AutoModeContext {
1089 path: "src/widget.rs",
1090 token_count: 1500,
1091 line_count: None,
1092 task: None,
1093 cache: None,
1094 };
1095 let a = resolve(&ctx);
1096 let b = resolve(&ctx);
1097 assert!(a.mode == "map" || a.mode == "cognitive", "got: {}", a.mode);
1098 assert!(
1099 a.source == "structure_first" || a.source.starts_with("science_"),
1100 "source: {}",
1101 a.source
1102 );
1103 assert_eq!((a.mode, a.source), (b.mode, b.source));
1104
1105 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1106 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1107 let _ = std::fs::remove_dir_all(&dir);
1108 }
1109
1110 #[test]
1113 fn auto_mode_learning_env_opt_in_is_honored() {
1114 let _lock = crate::core::data_dir::test_env_lock();
1115 crate::test_env::set_var("LEAN_CTX_AUTO_MODE_LEARNING", "1");
1116 assert!(crate::core::config::Config::default().auto_mode_learning_effective());
1117 crate::test_env::set_var("LEAN_CTX_AUTO_MODE_LEARNING", "0");
1118 assert!(!crate::core::config::Config::default().auto_mode_learning_effective());
1119 crate::test_env::remove_var("LEAN_CTX_AUTO_MODE_LEARNING");
1120 }
1121
1122 #[test]
1123 fn progressive_small_file_stays_full() {
1124 let _lock = crate::core::data_dir::test_env_lock();
1125 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1126
1127 let ctx = AutoModeContext {
1128 path: "small.rs",
1129 token_count: 200,
1130 line_count: Some(50),
1131 task: None,
1132 cache: None,
1133 };
1134 let result = resolve(&ctx);
1135 assert_eq!(result.mode, "full", "50 lines → full");
1136
1137 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1138 }
1139
1140 #[test]
1141 fn progressive_medium_file_gets_signatures() {
1142 let _lock = crate::core::data_dir::test_env_lock();
1143 let dir = std::env::temp_dir().join(format!("lctx-pd-sig-{}", std::process::id()));
1144 let _ = std::fs::create_dir_all(&dir);
1145 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1146 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1147
1148 let ctx = AutoModeContext {
1149 path: "medium.rs",
1150 token_count: 800,
1151 line_count: Some(200),
1152 task: None,
1153 cache: None,
1154 };
1155 let result = resolve(&ctx);
1156 assert!(
1157 result.mode == "signatures" || result.mode == "cognitive",
1158 "200 lines → signatures or cognitive, got: {}",
1159 result.mode
1160 );
1161 assert!(
1162 result.source == "progressive_signatures" || result.source.starts_with("science_"),
1163 "source: {}",
1164 result.source
1165 );
1166
1167 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1168 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1169 let _ = std::fs::remove_dir_all(&dir);
1170 }
1171
1172 #[test]
1173 fn progressive_large_file_gets_map() {
1174 let _lock = crate::core::data_dir::test_env_lock();
1175 let dir = std::env::temp_dir().join(format!("lctx-pd-map-{}", std::process::id()));
1176 let _ = std::fs::create_dir_all(&dir);
1177 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1178 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1179
1180 let ctx = AutoModeContext {
1181 path: "large.rs",
1182 token_count: 3200,
1183 line_count: Some(800),
1184 task: None,
1185 cache: None,
1186 };
1187 let result = resolve(&ctx);
1188 assert!(
1189 result.mode == "map" || result.mode == "cognitive",
1190 "800 lines → map or cognitive, got: {}",
1191 result.mode
1192 );
1193 assert!(
1194 result.source == "progressive_manifest" || result.source.starts_with("science_"),
1195 "source: {}",
1196 result.source
1197 );
1198
1199 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1200 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1201 let _ = std::fs::remove_dir_all(&dir);
1202 }
1203
1204 #[test]
1205 fn progressive_disabled_skips_tiering() {
1206 let _lock = crate::core::data_dir::test_env_lock();
1207 let dir = std::env::temp_dir().join(format!("lctx-pd-off-{}", std::process::id()));
1208 let _ = std::fs::create_dir_all(&dir);
1209 crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1210 crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1211 crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "0");
1212
1213 let ctx = AutoModeContext {
1214 path: "medium.rs",
1215 token_count: 800,
1216 line_count: Some(200),
1217 task: None,
1218 cache: None,
1219 };
1220 let result = resolve(&ctx);
1221 assert!(
1222 result.mode == "signatures" || result.mode == "cognitive",
1223 "progressive off → signatures or cognitive, got: {}",
1224 result.mode
1225 );
1226
1227 crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1228 crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1229 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1230 let _ = std::fs::remove_dir_all(&dir);
1231 }
1232
1233 #[test]
1234 fn estimate_lines_approximation() {
1235 assert_eq!(estimate_lines(400), 100);
1236 assert_eq!(estimate_lines(2000), 500);
1237 assert_eq!(estimate_lines(0), 0);
1238 }
1239}