Skip to main content

lean_ctx/core/
auto_mode_resolver.rs

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
10/// Per-process counters of which signal decided each auto-mode resolution.
11/// Surfaced by `ctx_metrics` so the learning loops are observable (#496).
12static 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
23/// Snapshot of auto-mode decision sources, sorted by count descending.
24pub 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
42/// Persist the in-process counters by *adding* them into the cumulative
43/// on-disk file, then reset the process counters. The counters live in the
44/// MCP/CLI process — the dashboard is a separate process and can only see
45/// them through this file (#505).
46pub 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
75/// Cumulative auto-mode decision sources from disk (all processes, all time),
76/// sorted by count descending. Used by the dashboard's Live Signals panel.
77pub 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
103/// Resolves read-mode sources with one documented precedence order:
104/// explicit request > configured default > learned selection > built-in default.
105pub 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
117/// Returns the configured read-mode default, excluding the profile's `auto`
118/// sentinel so callers can ask the learned resolver for a per-file decision.
119pub 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 mode = profile.read.default_mode_effective();
126            (mode != "auto").then(|| mode.to_string())
127        })
128}
129
130/// Single entry point for auto-mode resolution.
131/// Merges Pipeline A (select_mode_with_task) and Pipeline B (resolve_auto_mode).
132pub fn resolve(ctx: &AutoModeContext) -> ResolvedMode {
133    // Quality loop (#1008): a ctx_patch anchor went stale — hand back fresh line
134    // anchors (not `full`) so the agent retries by reference, one-shot. Checked
135    // before the `full` escalation: it is the strictly better recovery for a
136    // model already editing via anchors.
137    if crate::core::edit_quality::take_pending_anchored_escalation(ctx.path) {
138        return resolved("anchored", "anchored_edit_fail_escalation");
139    }
140
141    // Quality loop (#494), signal 1: an edit on this file just failed after a
142    // compressed read — the agent needs the real body now, one-shot.
143    if crate::core::edit_quality::take_pending_escalation(ctx.path) {
144        return resolved("full", "edit_fail_escalation");
145    }
146
147    let r = resolve_inner(ctx);
148
149    // Quality loop (#494), signal 2: this mode keeps producing edit failures
150    // for this file type — compression here is a proven net loss. Instead of
151    // jumping straight to `full`, try `signatures` first (the next-safest
152    // compressed mode). This preserves ~85% compression when only `map` is risky.
153    if r.mode != "full" && crate::core::edit_quality::is_risky_mode(ctx.path, &r.mode) {
154        if r.mode != "signatures"
155            && !crate::core::edit_quality::is_risky_mode(ctx.path, "signatures")
156        {
157            return resolved("signatures", "edit_quality_fallback");
158        }
159        return resolved("full", "edit_quality_penalty");
160    }
161    r
162}
163
164fn resolve_inner(ctx: &AutoModeContext) -> ResolvedMode {
165    if crate::tools::ctx_read::is_instruction_file(ctx.path) {
166        return resolved("full", "instruction_file");
167    }
168
169    if crate::core::binary_detect::is_binary_file(ctx.path) {
170        return resolved("full", "binary");
171    }
172
173    // Context Kits are task-specific and intentionally sit ahead of the
174    // generic cache/heuristic flow. Explicit caller modes still win at the
175    // public entry points; this only resolves an automatic read.
176    if let Some(mode) = crate::kits::active_mode_for_path(ctx.path) {
177        return resolved(&mode, "context_kit");
178    }
179
180    if let Some(cache) = ctx.cache
181        && let Some(cached) = cache.get(ctx.path)
182    {
183        if !file_unchanged(ctx.path, cached) {
184            return resolved("diff", "cache_changed");
185        }
186        // Unchanged. Resolving to "full" is only a cheap stub hit when full
187        // content was actually delivered before.
188        if cache.is_full_delivered(ctx.path) {
189            return resolved("full", "cache_hit");
190        }
191        // Reuse the last compressed mode so the dispatcher can serve its cached
192        // output rather than re-running the predictor and compression pipeline.
193        if let Some(prev_mode) = cache.last_mode(ctx.path)
194            && prev_mode != "full"
195        {
196            return resolved(&prev_mode, "cache_hit_compressed");
197        }
198    }
199
200    if ctx.token_count <= 200 {
201        return resolved("full", "small_file");
202    }
203
204    let ext = std::path::Path::new(ctx.path)
205        .extension()
206        .and_then(|e| e.to_str())
207        .unwrap_or("");
208
209    if ctx.token_count <= 400 && is_code(ext) {
210        return resolved("full", "small_code_file");
211    }
212
213    if is_config_or_data(ext, ctx.path) {
214        if ctx.token_count <= 1000 {
215            return resolved("full", "config_data");
216        }
217        return resolved("map", "config_data_large");
218    }
219
220    // Active compiler error (#499): the agent reads this file to fix the
221    // build — compressed modes would hide the error region.
222    if crate::core::diagnostics_store::has_error(ctx.path) {
223        return resolved("full", "active_diagnostic");
224    }
225
226    // Suspect file (#361 capability): the task explicitly names this file
227    // (e.g. "fix the version sort in versioncmp.c"), so the agent is about to
228    // inspect it for the defect. Keep the full body it needs to localize and
229    // edit, ahead of any task-type intent default that might compress it.
230    if task_names_file(ctx.task, ctx.path)
231        && intent_recommended_mode(ctx.task).as_deref() == Some("full")
232    {
233        return resolved("full", "task_suspect_file");
234    }
235
236    if let Some(mode) = intent_recommended_mode(ctx.task) {
237        // "full" is intentionally skipped here: only the `task_suspect_file`
238        // guard above is allowed to force full mode for a specific file. The
239        // general intent should never broadcast "full" to every file in the
240        // session — that kills compression for the 90%+ of reads that are
241        // context-gathering, not editing.
242        if mode != "full" {
243            return resolved(&mode, "intent");
244        }
245    }
246
247    // Adaptive learning signals (predictor, bandit, heatmap, adaptive policy,
248    // bounce/path memory) are opt-in (#683). Off by default, the capability
249    // guards above plus the deterministic heuristic below make `auto` a pure
250    // function of (file, task) — byte-stable for provider prompt caching (#498)
251    // and free of the per-read disk I/O these stores incur.
252    if crate::core::config::Config::load().auto_mode_learning_effective()
253        && let Some(r) = resolve_adaptive(ctx)
254    {
255        return r;
256    }
257
258    // Science-driven mode selection: when cognitive science features are enabled,
259    // use semantic chunking (cognitive mode) instead of structural-only modes.
260    // Cognitive mode returns 7±2 task-relevant code chunks with bodies — more
261    // useful than signatures-only and still 44-68% savings on medium files.
262    if crate::core::cognitive_gate::basic_science_enabled()
263        && is_code(ext)
264        && ctx.token_count > 500
265        && !crate::core::edit_quality::has_any_penalty(ctx.path)
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    // Progressive disclosure (#1309): large files default to compact overviews.
277    // File line count drives the tier; falls back to token-based approximation.
278    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    // Deterministic cold-read fallback. Every read that reaches here missed the
295    // session cache (a warm hit returns `full`/`diff` above). `structure_first`
296    // lets a phase-isolated host opt into a lower `map` floor for medium code
297    // files; all capability guards (diagnostic / edit-fail / intent) already ran
298    // above, and the anti-inflation guarantee keeps `map` break-even at worst.
299    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
309/// The opt-in adaptive block (#683): bounce/path memory plus the predictor /
310// OSS: adaptive read-mode selection. Not related to commercial
311// Adaptive Intensity (Solution Intelligence Section 8).
312/// bandit / heatmap / adaptive-policy learning loop. Returns `Some` when a
313/// learning signal decides the mode, `None` to fall through to the deterministic
314/// heuristic. Only invoked when `auto_mode_learning` is enabled, so its disk I/O
315/// and non-determinism never touch the default cascade.
316fn 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    // Per-path long-term memory (#496): a file that historically bounced in
324    // the majority of its reads will bounce again — compression is a proven
325    // net loss for it, across process restarts.
326    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    // Heatmap signal (#496): a frequently-read file where compression barely
346    // saves anything will likely trigger a follow-up read — step one mode more
347    // conservative. avg_compression_ratio is the historical fraction saved.
348    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
410/// Unified pressure downgrade table.
411/// Used by both context_gate and intent_router pressure paths.
412pub 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
433/// True when the task text explicitly names this file (basename match). A real
434/// filename mention ("versioncmp.c") is a strong suspect signal for a bug-fix;
435/// requiring an extension-bearing, non-trivial basename keeps it precise — the
436/// bare stem in "improve the parser" must not match `parser.rs`. A rare false
437/// positive only costs a little compression on a file the user literally named,
438/// so the failure mode is capability-safe.
439fn 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    // #4: deterministic argmax-of-mean by default; Thompson only under the flag.
486    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    // Large code files need an overview rather than an API-only surface.
511    if token_count > 6000 && is_code(ext) {
512        return "map".to_string();
513    }
514    // Structure-first cold-read floor (#361): on a phase-isolated harness a cold
515    // `full` read never amortizes, so medium code files default to `map`
516    // (deps + exports + key signatures) — cheaper and a better localization
517    // surface. `map` keeps far more than `signatures` (no empty bodies), so the
518    // follow-up-read risk that justifies the 6000 floor above is much lower; the
519    // 500-token floor stays above the trivial files where `full` is already best.
520    if structure_first && token_count > 500 && is_code(ext) {
521        return "map".to_string();
522    }
523    // Medium code files (500–6000 tok): use `signatures` for compression.
524    // Safe because tree-sitter is wrapped in catch_unwind with per-language
525    // blocklist fallback to regex — a panic degrades to regex signatures,
526    // never crashes the session.
527    if token_count > 500 && is_code(ext) {
528        return "signatures".to_string();
529    }
530    "full".to_string()
531}
532
533/// Fast O(1) staleness check: if the file's mtime still matches what was
534/// stored when the cache entry was created, the content is unchanged — no need
535/// to read the file or compute any hash. Falls back to "changed" when metadata
536/// is unavailable (e.g. file deleted) or when the cache entry predates mtime
537/// tracking (legacy entries with `stored_mtime = None`).
538///
539/// mtime comparison is sufficient for correctness on all major filesystems:
540/// every `write(2)` / `truncate(2)` updates mtime (POSIX guarantee).
541fn 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
611/// Approximate line count from tokens when actual line count is unavailable.
612/// Uses 4 tokens/line as a conservative estimate for typical source code.
613fn 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        // Unique test-only keys: parallel resolve() tests count real sources
740        // into the same process-global map, so shared keys would be flaky.
741        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        // A compressed first read records its mode without marking full content
798        // delivered. An unchanged re-read must reuse that mode and its cached
799        // compressed output rather than re-entering the prediction pipeline.
800        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        // Once full content was actually delivered, the cache_hit shortcut still
829        // applies: a re-read resolves to "full" (a cheap `[unchanged]` stub).
830        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        // A bare stem mention must not match the file.
885        assert!(!task_names_file(
886            Some("improve the parser"),
887            "src/parser.rs"
888        ));
889        assert!(!task_names_file(None, "src/parser.rs"));
890        // Trivial / extension-less basenames are excluded.
891        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        // An explore-style task that would otherwise map (cf.
903        // intent_explore_returns_map) — but it names the file, so the suspect
904        // guard keeps the full body for localization.
905        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        // A coding task (e.g. "fix the bug in parser.rs") should NOT force
923        // `full` mode on unrelated files. Only the named file (parser.rs)
924        // gets `full` via `task_suspect_file`; other files fall through to
925        // compressed modes so the 90%+ context-gathering reads still save
926        // tokens.
927        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        // Structure-first: medium code becomes `map` on a cold read.
955        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        // Below the 500-token floor `full` is already best.
962        assert_eq!(heuristic_mode("rs", 400, true), "full");
963        // Prose / markup now gets `aggressive` above 2000 tokens.
964        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        // Markdown is prose, not code — must NOT be in is_code().
984        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    /// Bug-fix read pattern: while localizing a planted defect the agent reads
994    /// many medium source files cold. With structure_first the resolver returns
995    /// `map` (cheap, localization-friendly) instead of an un-amortized `full`,
996    /// while every capability guard still takes precedence because it runs
997    /// before this fallback (here: the small-file guard keeps a tiny file full).
998    #[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    /// #683: with learning off (the default), a medium code file with no task
1076    /// resolves through the deterministic size heuristic — never a learning
1077    /// source — and is byte-stable across repeated calls.
1078    #[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    /// #683: the `LEAN_CTX_AUTO_MODE_LEARNING` env var gates the adaptive block
1111    /// and wins over the (default-off) config field.
1112    #[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}