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 engine = profile.engine_config();
126            let mode = engine.read.default_mode;
127            (mode != "auto").then(|| mode.to_string())
128        })
129}
130
131/// Single entry point for auto-mode resolution.
132/// Merges Pipeline A (select_mode_with_task) and Pipeline B (resolve_auto_mode).
133pub fn resolve(ctx: &AutoModeContext) -> ResolvedMode {
134    // Quality loop (#1008): a ctx_patch anchor went stale — hand back fresh line
135    // anchors (not `full`) so the agent retries by reference, one-shot. Checked
136    // before the `full` escalation: it is the strictly better recovery for a
137    // model already editing via anchors.
138    if crate::core::edit_quality::take_pending_anchored_escalation(ctx.path) {
139        return resolved("anchored", "anchored_edit_fail_escalation");
140    }
141
142    // Quality loop (#494), signal 1: an edit on this file just failed after a
143    // compressed read — the agent needs the real body now, one-shot.
144    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    // Quality loop (#494), signal 2: this mode keeps producing edit failures
151    // for this file type — compression here is a proven net loss. Instead of
152    // jumping straight to `full`, try `signatures` first (the next-safest
153    // compressed mode). This preserves ~85% compression when only `map` is risky.
154    if r.mode != "full" && crate::core::edit_quality::is_risky_mode(ctx.path, &r.mode) {
155        if r.mode != "signatures"
156            && !crate::core::edit_quality::is_risky_mode(ctx.path, "signatures")
157        {
158            return resolved("signatures", "edit_quality_fallback");
159        }
160        return resolved("full", "edit_quality_penalty");
161    }
162    r
163}
164
165fn resolve_inner(ctx: &AutoModeContext) -> ResolvedMode {
166    if crate::tools::ctx_read::is_instruction_file(ctx.path) {
167        return resolved("full", "instruction_file");
168    }
169
170    if crate::core::binary_detect::is_binary_file(ctx.path) {
171        return resolved("full", "binary");
172    }
173
174    // Context Kits are task-specific and intentionally sit ahead of the
175    // generic cache/heuristic flow. Explicit caller modes still win at the
176    // public entry points; this only resolves an automatic read.
177    if let Some(mode) = crate::kits::active_mode_for_path(ctx.path) {
178        return resolved(&mode, "context_kit");
179    }
180
181    if let Some(cache) = ctx.cache
182        && let Some(cached) = cache.get(ctx.path)
183    {
184        if !file_unchanged(ctx.path, cached) {
185            return resolved("diff", "cache_changed");
186        }
187        // Unchanged. Resolving to "full" is only a cheap stub hit when full
188        // content was actually delivered before.
189        if cache.is_full_delivered(ctx.path) {
190            return resolved("full", "cache_hit");
191        }
192        // Reuse the last compressed mode so the dispatcher can serve its cached
193        // output rather than re-running the predictor and compression pipeline.
194        if let Some(prev_mode) = cache.last_mode(ctx.path)
195            && prev_mode != "full"
196        {
197            return resolved(&prev_mode, "cache_hit_compressed");
198        }
199    }
200
201    if ctx.token_count <= 200 {
202        return resolved("full", "small_file");
203    }
204
205    let ext = std::path::Path::new(ctx.path)
206        .extension()
207        .and_then(|e| e.to_str())
208        .unwrap_or("");
209
210    if ctx.token_count <= 400 && is_code(ext) {
211        return resolved("full", "small_code_file");
212    }
213
214    if is_config_or_data(ext, ctx.path) {
215        if ctx.token_count <= 1000 {
216            return resolved("full", "config_data");
217        }
218        return resolved("map", "config_data_large");
219    }
220
221    // Active compiler error (#499): the agent reads this file to fix the
222    // build — compressed modes would hide the error region.
223    if crate::core::diagnostics_store::has_error(ctx.path) {
224        return resolved("full", "active_diagnostic");
225    }
226
227    // Suspect file (#361 capability): the task explicitly names this file
228    // (e.g. "fix the version sort in versioncmp.c"), so the agent is about to
229    // inspect it for the defect. Keep the full body it needs to localize and
230    // edit, ahead of any task-type intent default that might compress it.
231    if task_names_file(ctx.task, ctx.path)
232        && intent_recommended_mode(ctx.task).as_deref() == Some("full")
233    {
234        return resolved("full", "task_suspect_file");
235    }
236
237    if let Some(mode) = intent_recommended_mode(ctx.task) {
238        // "full" is intentionally skipped here: only the `task_suspect_file`
239        // guard above is allowed to force full mode for a specific file. The
240        // general intent should never broadcast "full" to every file in the
241        // session — that kills compression for the 90%+ of reads that are
242        // context-gathering, not editing.
243        if mode != "full" {
244            return resolved(&mode, "intent");
245        }
246    }
247
248    // Adaptive learning signals (predictor, bandit, heatmap, adaptive policy,
249    // bounce/path memory) are opt-in (#683). Off by default, the capability
250    // guards above plus the deterministic heuristic below make `auto` a pure
251    // function of (file, task) — byte-stable for provider prompt caching (#498)
252    // and free of the per-read disk I/O these stores incur.
253    if crate::core::config::Config::load().auto_mode_learning_effective()
254        && let Some(r) = resolve_adaptive(ctx)
255    {
256        return r;
257    }
258
259    // Science-driven mode selection: when cognitive science features are enabled,
260    // use semantic chunking (cognitive mode) instead of structural-only modes.
261    // Cognitive mode returns 7±2 task-relevant code chunks with bodies — more
262    // useful than signatures-only and still 44-68% savings on medium files.
263    if crate::core::cognitive_gate::basic_science_enabled()
264        && is_code(ext)
265        && ctx.token_count > 500
266        && !crate::core::edit_quality::has_any_penalty(ctx.path)
267    {
268        if ctx.token_count > 8000 {
269            return resolved("cognitive", "science_cognitive_large");
270        }
271        if ctx.token_count > 2000 {
272            return resolved("cognitive", "science_cognitive_medium");
273        }
274        return resolved("cognitive", "science_cognitive_small");
275    }
276
277    // Progressive disclosure (#1309): large files default to compact overviews.
278    // File line count drives the tier; falls back to token-based approximation.
279    let cfg = crate::core::config::Config::load();
280    if cfg.progressive_disclosure_effective() {
281        let lines = ctx
282            .line_count
283            .unwrap_or_else(|| estimate_lines(ctx.token_count));
284        let threshold = cfg.progressive_threshold_lines as usize;
285        let sig_max = cfg.progressive_signatures_max as usize;
286
287        if lines >= sig_max && is_code(ext) {
288            return resolved("map", "progressive_manifest");
289        }
290        if lines >= threshold && is_code(ext) {
291            return resolved("signatures", "progressive_signatures");
292        }
293    }
294
295    // Deterministic cold-read fallback. Every read that reaches here missed the
296    // session cache (a warm hit returns `full`/`diff` above). `structure_first`
297    // lets a phase-isolated host opt into a lower `map` floor for medium code
298    // files; all capability guards (diagnostic / edit-fail / intent) already ran
299    // above, and the anti-inflation guarantee keeps `map` break-even at worst.
300    let structure_first = cfg.structure_first_effective();
301    let heuristic = heuristic_mode(ext, ctx.token_count, structure_first);
302    let source = if structure_first && heuristic == "map" && ctx.token_count <= 6000 {
303        "structure_first"
304    } else {
305        "heuristic"
306    };
307    resolved(&heuristic, source)
308}
309
310/// The opt-in adaptive block (#683): bounce/path memory plus the predictor /
311// OSS: adaptive read-mode selection. Not related to commercial
312// Adaptive Intensity (Solution Intelligence Section 8).
313/// bandit / heatmap / adaptive-policy learning loop. Returns `Some` when a
314/// learning signal decides the mode, `None` to fall through to the deterministic
315/// heuristic. Only invoked when `auto_mode_learning` is enabled, so its disk I/O
316/// and non-determinism never touch the default cascade.
317fn resolve_adaptive(ctx: &AutoModeContext) -> Option<ResolvedMode> {
318    if let Ok(bt) = crate::core::bounce_tracker::global().lock()
319        && bt.should_force_full(ctx.path)
320    {
321        return Some(resolved("full", "bounce_tracker"));
322    }
323
324    // Per-path long-term memory (#496): a file that historically bounced in
325    // the majority of its reads will bounce again — compression is a proven
326    // net loss for it, across process restarts.
327    if crate::core::path_mode_memory::should_force_full(ctx.path) {
328        return Some(resolved("full", "path_bounce_memory"));
329    }
330
331    let sig = FileSignature::from_path(ctx.path, ctx.token_count);
332    let predictor = ModePredictor::new();
333    let mut predicted = predictor
334        .predict_best_mode(&sig)
335        .unwrap_or_else(|| "full".to_string());
336    if predicted == "auto" {
337        predicted = "full".to_string();
338    }
339
340    if predicted != "full"
341        && let Some(bandit_override) = bandit_explore(ctx.path, ctx.token_count)
342    {
343        predicted = bandit_override;
344    }
345
346    // Heatmap signal (#496): a frequently-read file where compression barely
347    // saves anything will likely trigger a follow-up read — step one mode more
348    // conservative. avg_compression_ratio is the historical fraction saved.
349    if predicted != "full"
350        && let Some((access_count, avg_ratio)) = crate::core::heatmap::entry_stats(ctx.path)
351        && access_count >= 5
352        && avg_ratio < 0.30
353    {
354        let conservative = match predicted.as_str() {
355            "signatures" | "aggressive" | "entropy" => "map".to_string(),
356            "map" if ctx.token_count <= 6000 => "full".to_string(),
357            other => other.to_string(),
358        };
359        if conservative != predicted {
360            return Some(resolved(&conservative, "heatmap_conservative"));
361        }
362    }
363
364    let request_id = "auto-mode-resolution";
365    let request = ConfigTuningRequest {
366        context: OclaRequestContext {
367            request_id: request_id.to_string(),
368            session_id: "auto-mode".to_string(),
369            agent_id: "lean-ctx".to_string(),
370            content_ref: ctx.path.to_string(),
371            tenant_id: None,
372            trace_id: "tr-unit".into(),
373            task_id: None,
374            parent_task_id: None,
375        },
376        config_ref: predicted.clone(),
377        objective_ref: ctx.task.unwrap_or_default().to_string(),
378    };
379    let chosen = match OclaRegistry::global().config_tuner.propose_tuning(request) {
380        Ok(proposal) => proposal
381            .proposal_ref
382            .strip_prefix(&format!("proposal:{predicted}->"))
383            .and_then(|value| value.strip_suffix(&format!(":{request_id}")))
384            .map_or_else(|| predicted.clone(), ToString::to_string),
385        Err(_) => predicted.clone(),
386    };
387
388    if ctx.token_count > 2000 {
389        if (predicted == "map" || predicted == "signatures")
390            && chosen != "map"
391            && chosen != "signatures"
392        {
393            return Some(resolved(&predicted, "predictor_guard"));
394        }
395        if chosen == "full" && predicted != "full" {
396            return Some(resolved(&predicted, "predictor_override"));
397        }
398    }
399
400    if chosen != predicted {
401        return Some(resolved(&chosen, "adaptive_policy"));
402    }
403
404    if predicted != "full" {
405        return Some(resolved(&predicted, "predictor"));
406    }
407
408    None
409}
410
411/// Unified pressure downgrade table.
412/// Used by both context_gate and intent_router pressure paths.
413pub fn pressure_downgrade(requested_mode: &str, action: &PressureAction) -> Option<String> {
414    match action {
415        PressureAction::SuggestCompression => match requested_mode {
416            "auto" | "full" => Some("map".to_string()),
417            _ => None,
418        },
419        PressureAction::ForceCompression => match requested_mode {
420            "full" => Some("map".to_string()),
421            "auto" | "map" | "cognitive" => Some("signatures".to_string()),
422            _ => None,
423        },
424        PressureAction::EvictLeastRelevant => match requested_mode {
425            "full" => Some("map".to_string()),
426            "auto" | "map" | "cognitive" => Some("signatures".to_string()),
427            "signatures" => Some("reference".to_string()),
428            _ => None,
429        },
430        PressureAction::NoAction => None,
431    }
432}
433
434/// True when the task text explicitly names this file (basename match). A real
435/// filename mention ("versioncmp.c") is a strong suspect signal for a bug-fix;
436/// requiring an extension-bearing, non-trivial basename keeps it precise — the
437/// bare stem in "improve the parser" must not match `parser.rs`. A rare false
438/// positive only costs a little compression on a file the user literally named,
439/// so the failure mode is capability-safe.
440fn task_names_file(task: Option<&str>, path: &str) -> bool {
441    let Some(task) = task else {
442        return false;
443    };
444    let basename = std::path::Path::new(path)
445        .file_name()
446        .and_then(|n| n.to_str())
447        .unwrap_or("");
448    if basename.len() < 4 || !basename.contains('.') {
449        return false;
450    }
451    task.to_ascii_lowercase()
452        .contains(&basename.to_ascii_lowercase())
453}
454
455fn intent_recommended_mode(task: Option<&str>) -> Option<String> {
456    let task_desc = task?;
457    let classification = crate::core::intent_engine::classify(task_desc);
458    if classification.confidence < 0.4 {
459        return None;
460    }
461    let route = crate::core::intent_engine::route_intent(task_desc, &classification);
462    let mode =
463        crate::core::intent_router::read_mode_for_tier(route.model_tier, classification.task_type);
464    if mode == "auto" {
465        return None;
466    }
467    Some(mode)
468}
469
470fn bandit_explore(file_path: &str, token_count: usize) -> Option<String> {
471    let project_root =
472        crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)?;
473    let ext = std::path::Path::new(file_path)
474        .extension()
475        .and_then(|e| e.to_str())
476        .unwrap_or("");
477    let bucket = match token_count {
478        0..=2000 => "sm",
479        2001..=10000 => "md",
480        10001..=50000 => "lg",
481        _ => "xl",
482    };
483    let bandit_key = crate::core::bandit::bandit_key("mode", ext, Some(bucket));
484    let mut store = crate::core::bandit::BanditStore::load(&project_root);
485    let bandit = store.get_or_create(&bandit_key);
486    // #4: deterministic argmax-of-mean by default; Thompson only under the flag.
487    let arm = bandit.choose_arm();
488    if arm.budget_ratio < 0.25 && token_count > 2000 {
489        Some("aggressive".to_string())
490    } else {
491        None
492    }
493}
494
495fn heuristic_mode(ext: &str, token_count: usize, structure_first: bool) -> String {
496    if token_count > 8000 {
497        if is_code(ext) {
498            return "map".to_string();
499        }
500        return "aggressive".to_string();
501    }
502    if token_count > 2000 && is_prose(ext) {
503        return "aggressive".to_string();
504    }
505    if token_count > 500 && is_prose(ext) {
506        return "map".to_string();
507    }
508    if token_count > 500 && !is_code(ext) && !is_prose(ext) {
509        return "map".to_string();
510    }
511    // Large code files need an overview rather than an API-only surface.
512    if token_count > 6000 && is_code(ext) {
513        return "map".to_string();
514    }
515    // Structure-first cold-read floor (#361): on a phase-isolated harness a cold
516    // `full` read never amortizes, so medium code files default to `map`
517    // (deps + exports + key signatures) — cheaper and a better localization
518    // surface. `map` keeps far more than `signatures` (no empty bodies), so the
519    // follow-up-read risk that justifies the 6000 floor above is much lower; the
520    // 500-token floor stays above the trivial files where `full` is already best.
521    if structure_first && token_count > 500 && is_code(ext) {
522        return "map".to_string();
523    }
524    // Medium code files (500–6000 tok): use `signatures` for compression.
525    // Safe because tree-sitter is wrapped in catch_unwind with per-language
526    // blocklist fallback to regex — a panic degrades to regex signatures,
527    // never crashes the session.
528    if token_count > 500 && is_code(ext) {
529        return "signatures".to_string();
530    }
531    "full".to_string()
532}
533
534/// Fast O(1) staleness check: if the file's mtime still matches what was
535/// stored when the cache entry was created, the content is unchanged — no need
536/// to read the file or compute any hash. Falls back to "changed" when metadata
537/// is unavailable (e.g. file deleted) or when the cache entry predates mtime
538/// tracking (legacy entries with `stored_mtime = None`).
539///
540/// mtime comparison is sufficient for correctness on all major filesystems:
541/// every `write(2)` / `truncate(2)` updates mtime (POSIX guarantee).
542fn file_unchanged(path: &str, cached: &crate::core::cache::CacheEntry) -> bool {
543    let Some(stored_mtime) = cached.stored_mtime else {
544        return false;
545    };
546    let Ok(meta) = std::fs::metadata(path) else {
547        return false;
548    };
549    let Ok(current_mtime) = meta.modified() else {
550        return false;
551    };
552    current_mtime == stored_mtime
553}
554
555fn is_code(ext: &str) -> bool {
556    matches!(
557        ext,
558        "rs" | "ts"
559            | "tsx"
560            | "js"
561            | "jsx"
562            | "py"
563            | "go"
564            | "java"
565            | "c"
566            | "cpp"
567            | "cc"
568            | "h"
569            | "hpp"
570            | "rb"
571            | "cs"
572            | "kt"
573            | "swift"
574            | "php"
575            | "zig"
576            | "ex"
577            | "exs"
578            | "scala"
579            | "sc"
580            | "dart"
581            | "toml"
582            | "yaml"
583            | "yml"
584            | "json"
585            | "sh"
586            | "bash"
587            | "svelte"
588            | "vue"
589            | "astro"
590            | "mdx"
591            | "njk"
592            | "hbs"
593            | "ejs"
594            | "erb"
595            | "jinja"
596            | "jinja2"
597            | "twig"
598            | "pug"
599            | "slim"
600            | "haml"
601            | "liquid"
602    )
603}
604
605fn is_prose(ext: &str) -> bool {
606    matches!(
607        ext,
608        "md" | "mdx" | "txt" | "rst" | "adoc" | "org" | "tex" | "html" | "htm"
609    )
610}
611
612/// Approximate line count from tokens when actual line count is unavailable.
613/// Uses 4 tokens/line as a conservative estimate for typical source code.
614fn estimate_lines(token_count: usize) -> usize {
615    token_count / 4
616}
617
618fn is_config_or_data(ext: &str, path: &str) -> bool {
619    if matches!(ext, "xml" | "ini" | "cfg" | "env") {
620        return true;
621    }
622    let name = std::path::Path::new(path)
623        .file_name()
624        .and_then(|n| n.to_str())
625        .unwrap_or("");
626    matches!(
627        name,
628        "Cargo.toml"
629            | "package.json"
630            | "tsconfig.json"
631            | "Makefile"
632            | "Dockerfile"
633            | "docker-compose.yml"
634            | ".gitignore"
635            | ".env"
636            | "pyproject.toml"
637            | "go.mod"
638            | "build.gradle"
639            | "pom.xml"
640    )
641}
642
643fn resolved(mode: &str, source: &'static str) -> ResolvedMode {
644    count_source(source);
645    ResolvedMode {
646        mode: mode.to_string(),
647        source,
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    #[test]
656    fn mode_precedence_is_explicit_then_configured_then_learned_then_default() {
657        assert_eq!(
658            resolve_mode_precedence(
659                Some("raw".to_string()),
660                Some("map".to_string()),
661                Some("signatures".to_string()),
662                "full",
663            ),
664            "raw"
665        );
666        assert_eq!(
667            resolve_mode_precedence(
668                None,
669                Some("map".to_string()),
670                Some("signatures".to_string()),
671                "full",
672            ),
673            "map"
674        );
675        assert_eq!(
676            resolve_mode_precedence(None, None, Some("signatures".to_string()), "full"),
677            "signatures"
678        );
679        assert_eq!(resolve_mode_precedence(None, None, None, "full"), "full");
680    }
681
682    #[test]
683    fn pressure_suggest_full_to_map() {
684        assert_eq!(
685            pressure_downgrade("full", &PressureAction::SuggestCompression),
686            Some("map".to_string())
687        );
688    }
689
690    #[test]
691    fn pressure_suggest_auto_to_map() {
692        assert_eq!(
693            pressure_downgrade("auto", &PressureAction::SuggestCompression),
694            Some("map".to_string())
695        );
696    }
697
698    #[test]
699    fn pressure_suggest_does_not_touch_signatures() {
700        assert!(pressure_downgrade("signatures", &PressureAction::SuggestCompression).is_none());
701    }
702
703    #[test]
704    fn pressure_force_full_to_map() {
705        assert_eq!(
706            pressure_downgrade("full", &PressureAction::ForceCompression),
707            Some("map".to_string())
708        );
709    }
710
711    #[test]
712    fn pressure_force_map_to_signatures() {
713        assert_eq!(
714            pressure_downgrade("map", &PressureAction::ForceCompression),
715            Some("signatures".to_string())
716        );
717    }
718
719    #[test]
720    fn pressure_evict_signatures_to_reference() {
721        assert_eq!(
722            pressure_downgrade("signatures", &PressureAction::EvictLeastRelevant),
723            Some("reference".to_string())
724        );
725    }
726
727    #[test]
728    fn pressure_noaction_returns_none() {
729        assert!(pressure_downgrade("full", &PressureAction::NoAction).is_none());
730    }
731
732    #[test]
733    fn flush_sources_merges_additively_into_disk_file() {
734        let _lock = crate::core::data_dir::test_env_lock();
735        let dir = std::env::temp_dir().join(format!("lctx-amr-flush-{}", std::process::id()));
736        let _ = std::fs::create_dir_all(&dir);
737        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
738        let _ = std::fs::remove_file(dir.join("auto_mode_sources.json"));
739
740        // Unique test-only keys: parallel resolve() tests count real sources
741        // into the same process-global map, so shared keys would be flaky.
742        count_source("test_flush_alpha");
743        count_source("test_flush_alpha");
744        count_source("test_flush_beta");
745        flush_sources();
746
747        count_source("test_flush_alpha");
748        flush_sources();
749
750        let persisted = persisted_source_counts();
751        let get = |k: &str| {
752            persisted
753                .iter()
754                .find(|(s, _)| s == k)
755                .map_or(0, |(_, n)| *n)
756        };
757        assert_eq!(
758            get("test_flush_alpha"),
759            3,
760            "two flushes must merge additively"
761        );
762        assert_eq!(get("test_flush_beta"), 1);
763
764        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
765        let _ = std::fs::remove_dir_all(&dir);
766    }
767
768    #[test]
769    fn small_file_always_full() {
770        let ctx = AutoModeContext {
771            path: "test.rs",
772            token_count: 100,
773            line_count: None,
774            task: None,
775            cache: None,
776        };
777        let result = resolve(&ctx);
778        assert_eq!(result.mode, "full");
779        assert_eq!(result.source, "small_file");
780    }
781
782    #[test]
783    fn config_file_returns_full() {
784        let ctx = AutoModeContext {
785            path: "config.ini",
786            token_count: 500,
787            line_count: None,
788            task: None,
789            cache: None,
790        };
791        let result = resolve(&ctx);
792        assert_eq!(result.mode, "full");
793        assert_eq!(result.source, "config_data");
794    }
795
796    #[test]
797    fn cached_compressed_only_file_reuses_cached_mode() {
798        // A compressed first read records its mode without marking full content
799        // delivered. An unchanged re-read must reuse that mode and its cached
800        // compressed output rather than re-entering the prediction pipeline.
801        let dir = tempfile::tempdir().unwrap();
802        let file = dir.path().join("large.rs");
803        let body = "fn placeholder() { let _ = 1; }\n".repeat(900);
804        std::fs::write(&file, &body).unwrap();
805        let path = file.to_str().unwrap();
806
807        let mut cache = SessionCache::new();
808        cache.store(path, &body);
809        cache.get_mut(path).unwrap().last_mode = "map".to_string();
810
811        let ctx = AutoModeContext {
812            path,
813            token_count: 7000,
814            line_count: None,
815            task: None,
816            cache: Some(&cache),
817        };
818        let result = resolve(&ctx);
819        assert!(
820            result.mode == "map" || result.mode == "cognitive",
821            "expected map or cognitive, got: {}",
822            result.mode
823        );
824        assert_eq!(result.source, "cache_hit_compressed");
825    }
826
827    #[test]
828    fn cached_full_delivered_file_short_circuits_to_stub() {
829        // Once full content was actually delivered, the cache_hit shortcut still
830        // applies: a re-read resolves to "full" (a cheap `[unchanged]` stub).
831        let dir = tempfile::tempdir().unwrap();
832        let file = dir.path().join("medium.rs");
833        let body = "fn placeholder() { let _ = 1; }\n".repeat(400);
834        std::fs::write(&file, &body).unwrap();
835        let path = file.to_str().unwrap();
836
837        let mut cache = SessionCache::new();
838        cache.store(path, &body);
839        cache.mark_full_delivered(path);
840
841        let ctx = AutoModeContext {
842            path,
843            token_count: 3000,
844            line_count: None,
845            task: None,
846            cache: Some(&cache),
847        };
848        let result = resolve(&ctx);
849        assert_eq!(result.mode, "full");
850        assert_eq!(result.source, "cache_hit");
851    }
852
853    #[test]
854    fn intent_explore_returns_map() {
855        let ctx = AutoModeContext {
856            path: "large.rs",
857            token_count: 5000,
858            line_count: None,
859            task: Some("how does the cache work?"),
860            cache: None,
861        };
862        let result = resolve(&ctx);
863        assert!(
864            result.mode == "map" || result.mode == "cognitive",
865            "expected map or cognitive, got: {}",
866            result.mode
867        );
868        assert_eq!(result.source, "intent");
869    }
870
871    #[test]
872    fn task_names_file_matches_explicit_filename() {
873        assert!(task_names_file(
874            Some("fix the version sort in versioncmp.c"),
875            "src/versioncmp.c"
876        ));
877        assert!(task_names_file(
878            Some("why does graph.ts loop?"),
879            "web/src/graph.ts"
880        ));
881    }
882
883    #[test]
884    fn task_names_file_ignores_bare_stems_and_trivia() {
885        // A bare stem mention must not match the file.
886        assert!(!task_names_file(
887            Some("improve the parser"),
888            "src/parser.rs"
889        ));
890        assert!(!task_names_file(None, "src/parser.rs"));
891        // Trivial / extension-less basenames are excluded.
892        assert!(!task_names_file(Some("touch a.c"), "a.c"));
893        assert!(!task_names_file(Some("look at Makefile"), "Makefile"));
894    }
895
896    #[test]
897    fn task_suspect_file_overrides_intent() {
898        let _lock = crate::core::data_dir::test_env_lock();
899        let dir = std::env::temp_dir().join(format!("lctx-amr-suspect-{}", std::process::id()));
900        let _ = std::fs::create_dir_all(&dir);
901        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
902
903        // An explore-style task that would otherwise map (cf.
904        // intent_explore_returns_map) — but it names the file, so the suspect
905        // guard keeps the full body for localization.
906        let ctx = AutoModeContext {
907            path: "large.rs",
908            token_count: 5000,
909            line_count: None,
910            task: Some("how does large.rs build the cache?"),
911            cache: None,
912        };
913        let result = resolve(&ctx);
914        assert_eq!(result.mode, "full");
915        assert_eq!(result.source, "task_suspect_file");
916
917        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
918        let _ = std::fs::remove_dir_all(&dir);
919    }
920
921    #[test]
922    fn intent_full_skipped_for_non_suspect_files() {
923        // A coding task (e.g. "fix the bug in parser.rs") should NOT force
924        // `full` mode on unrelated files. Only the named file (parser.rs)
925        // gets `full` via `task_suspect_file`; other files fall through to
926        // compressed modes so the 90%+ context-gathering reads still save
927        // tokens.
928        let _iso = crate::core::data_dir::isolated_data_dir();
929        let ctx = AutoModeContext {
930            path: "unrelated_module.rs",
931            token_count: 5000,
932            line_count: None,
933            task: Some("fix the bug in parser.rs"),
934            cache: None,
935        };
936        let result = resolve(&ctx);
937        assert_ne!(
938            result.mode, "full",
939            "non-suspect file must not get full mode from a coding task intent"
940        );
941        assert_ne!(
942            result.source, "intent",
943            "general intent must not force full on non-suspect files"
944        );
945    }
946
947    #[test]
948    fn heuristic_medium_code_uses_signatures_by_default() {
949        assert_eq!(heuristic_mode("rs", 1500, false), "signatures");
950        assert_eq!(heuristic_mode("ts", 1000, false), "signatures");
951    }
952
953    #[test]
954    fn heuristic_structure_first_maps_medium_code() {
955        // Structure-first: medium code becomes `map` on a cold read.
956        assert_eq!(heuristic_mode("rs", 1500, true), "map");
957        assert_eq!(heuristic_mode("c", 800, true), "map");
958    }
959
960    #[test]
961    fn heuristic_structure_first_keeps_tiny_and_prose_full() {
962        // Below the 500-token floor `full` is already best.
963        assert_eq!(heuristic_mode("rs", 400, true), "full");
964        // Prose / markup now gets `aggressive` above 2000 tokens.
965        assert_eq!(heuristic_mode("md", 4000, true), "aggressive");
966        assert_eq!(heuristic_mode("md", 1500, true), "map");
967        assert_eq!(heuristic_mode("txt", 3000, true), "aggressive");
968        assert_eq!(heuristic_mode("txt", 1000, true), "map");
969    }
970
971    #[test]
972    fn code_and_data_extensions_cover_progressive_formats() {
973        for ext in [
974            "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "rb", "swift",
975            "kt", "scala", "toml", "yaml", "yml", "json", "sh", "bash", "svelte", "vue", "astro",
976            "mdx", "njk", "hbs", "ejs", "erb", "jinja", "jinja2", "twig", "pug", "slim", "haml",
977            "liquid",
978        ] {
979            assert!(
980                is_code(ext),
981                "{ext} should participate in structure-first modes"
982            );
983        }
984        // Markdown is prose, not code — must NOT be in is_code().
985        assert!(!is_code("md"));
986    }
987
988    #[test]
989    fn heuristic_large_code_maps_regardless() {
990        assert_eq!(heuristic_mode("rs", 9000, false), "map");
991        assert_eq!(heuristic_mode("rs", 9000, true), "map");
992    }
993
994    /// Bug-fix read pattern: while localizing a planted defect the agent reads
995    /// many medium source files cold. With structure_first the resolver returns
996    /// `map` (cheap, localization-friendly) instead of an un-amortized `full`,
997    /// while every capability guard still takes precedence because it runs
998    /// before this fallback (here: the small-file guard keeps a tiny file full).
999    #[test]
1000    fn structure_first_resolve_bugfix_cold_read() {
1001        let _lock = crate::core::data_dir::test_env_lock();
1002        let dir = std::env::temp_dir().join(format!("lctx-amr-sf-{}", std::process::id()));
1003        let _ = std::fs::create_dir_all(&dir);
1004        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1005        crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "1");
1006        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1007
1008        let suspect = AutoModeContext {
1009            path: "src/versioncmp.c",
1010            token_count: 1500,
1011            line_count: None,
1012            task: None,
1013            cache: None,
1014        };
1015        let result = resolve(&suspect);
1016        assert!(
1017            result.mode == "map" || result.mode == "cognitive",
1018            "expected map or cognitive, got: {}",
1019            result.mode
1020        );
1021        assert!(
1022            result.source == "structure_first" || result.source.starts_with("science_"),
1023            "source: {}",
1024            result.source
1025        );
1026
1027        let tiny = AutoModeContext {
1028            path: "src/util.c",
1029            token_count: 120,
1030            line_count: None,
1031            task: None,
1032            cache: None,
1033        };
1034        assert_eq!(resolve(&tiny).mode, "full");
1035
1036        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1037        crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1038        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1039        let _ = std::fs::remove_dir_all(&dir);
1040    }
1041
1042    #[test]
1043    fn structure_first_off_uses_signatures_for_medium_code() {
1044        let _lock = crate::core::data_dir::test_env_lock();
1045        let dir = std::env::temp_dir().join(format!("lctx-amr-sfoff-{}", std::process::id()));
1046        let _ = std::fs::create_dir_all(&dir);
1047        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1048        crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "0");
1049        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1050
1051        let ctx = AutoModeContext {
1052            path: "src/versioncmp.c",
1053            token_count: 1500,
1054            line_count: None,
1055            task: None,
1056            cache: None,
1057        };
1058        let result = resolve(&ctx);
1059        assert!(
1060            result.mode == "signatures" || result.mode == "cognitive",
1061            "sf=off → signatures or cognitive, got: {}",
1062            result.mode
1063        );
1064        assert!(
1065            result.source == "heuristic" || result.source.starts_with("science_"),
1066            "source: {}",
1067            result.source
1068        );
1069
1070        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1071        crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1072        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1073        let _ = std::fs::remove_dir_all(&dir);
1074    }
1075
1076    /// #683: with learning off (the default), a medium code file with no task
1077    /// resolves through the deterministic size heuristic — never a learning
1078    /// source — and is byte-stable across repeated calls.
1079    #[test]
1080    fn learning_off_by_default_is_deterministic() {
1081        let _lock = crate::core::data_dir::test_env_lock();
1082        let dir = std::env::temp_dir().join(format!("lctx-amr-det-{}", std::process::id()));
1083        let _ = std::fs::create_dir_all(&dir);
1084        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1085        crate::test_env::remove_var("LEAN_CTX_AUTO_MODE_LEARNING");
1086        crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1087        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1088
1089        let ctx = AutoModeContext {
1090            path: "src/widget.rs",
1091            token_count: 1500,
1092            line_count: None,
1093            task: None,
1094            cache: None,
1095        };
1096        let a = resolve(&ctx);
1097        let b = resolve(&ctx);
1098        assert!(a.mode == "map" || a.mode == "cognitive", "got: {}", a.mode);
1099        assert!(
1100            a.source == "structure_first" || a.source.starts_with("science_"),
1101            "source: {}",
1102            a.source
1103        );
1104        assert_eq!((a.mode, a.source), (b.mode, b.source));
1105
1106        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1107        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1108        let _ = std::fs::remove_dir_all(&dir);
1109    }
1110
1111    /// #683: the `LEAN_CTX_AUTO_MODE_LEARNING` env var gates the adaptive block
1112    /// and wins over the (default-off) config field.
1113    #[test]
1114    fn auto_mode_learning_env_opt_in_is_honored() {
1115        let _lock = crate::core::data_dir::test_env_lock();
1116        crate::test_env::set_var("LEAN_CTX_AUTO_MODE_LEARNING", "1");
1117        assert!(crate::core::config::Config::default().auto_mode_learning_effective());
1118        crate::test_env::set_var("LEAN_CTX_AUTO_MODE_LEARNING", "0");
1119        assert!(!crate::core::config::Config::default().auto_mode_learning_effective());
1120        crate::test_env::remove_var("LEAN_CTX_AUTO_MODE_LEARNING");
1121    }
1122
1123    #[test]
1124    fn progressive_small_file_stays_full() {
1125        let _lock = crate::core::data_dir::test_env_lock();
1126        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1127
1128        let ctx = AutoModeContext {
1129            path: "small.rs",
1130            token_count: 200,
1131            line_count: Some(50),
1132            task: None,
1133            cache: None,
1134        };
1135        let result = resolve(&ctx);
1136        assert_eq!(result.mode, "full", "50 lines → full");
1137
1138        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1139    }
1140
1141    #[test]
1142    fn progressive_medium_file_gets_signatures() {
1143        let _lock = crate::core::data_dir::test_env_lock();
1144        let dir = std::env::temp_dir().join(format!("lctx-pd-sig-{}", std::process::id()));
1145        let _ = std::fs::create_dir_all(&dir);
1146        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1147        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1148
1149        let ctx = AutoModeContext {
1150            path: "medium.rs",
1151            token_count: 800,
1152            line_count: Some(200),
1153            task: None,
1154            cache: None,
1155        };
1156        let result = resolve(&ctx);
1157        assert!(
1158            result.mode == "signatures" || result.mode == "cognitive",
1159            "200 lines → signatures or cognitive, got: {}",
1160            result.mode
1161        );
1162        assert!(
1163            result.source == "progressive_signatures" || result.source.starts_with("science_"),
1164            "source: {}",
1165            result.source
1166        );
1167
1168        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1169        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1170        let _ = std::fs::remove_dir_all(&dir);
1171    }
1172
1173    #[test]
1174    fn progressive_large_file_gets_map() {
1175        let _lock = crate::core::data_dir::test_env_lock();
1176        let dir = std::env::temp_dir().join(format!("lctx-pd-map-{}", std::process::id()));
1177        let _ = std::fs::create_dir_all(&dir);
1178        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1179        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "1");
1180
1181        let ctx = AutoModeContext {
1182            path: "large.rs",
1183            token_count: 3200,
1184            line_count: Some(800),
1185            task: None,
1186            cache: None,
1187        };
1188        let result = resolve(&ctx);
1189        assert!(
1190            result.mode == "map" || result.mode == "cognitive",
1191            "800 lines → map or cognitive, got: {}",
1192            result.mode
1193        );
1194        assert!(
1195            result.source == "progressive_manifest" || result.source.starts_with("science_"),
1196            "source: {}",
1197            result.source
1198        );
1199
1200        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1201        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1202        let _ = std::fs::remove_dir_all(&dir);
1203    }
1204
1205    #[test]
1206    fn progressive_disabled_skips_tiering() {
1207        let _lock = crate::core::data_dir::test_env_lock();
1208        let dir = std::env::temp_dir().join(format!("lctx-pd-off-{}", std::process::id()));
1209        let _ = std::fs::create_dir_all(&dir);
1210        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
1211        crate::test_env::set_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE", "0");
1212        crate::test_env::set_var("LEAN_CTX_STRUCTURE_FIRST", "0");
1213
1214        let ctx = AutoModeContext {
1215            path: "medium.rs",
1216            token_count: 800,
1217            line_count: Some(200),
1218            task: None,
1219            cache: None,
1220        };
1221        let result = resolve(&ctx);
1222        assert!(
1223            result.mode == "signatures" || result.mode == "cognitive",
1224            "progressive off → signatures or cognitive, got: {}",
1225            result.mode
1226        );
1227
1228        crate::test_env::remove_var("LEAN_CTX_PROGRESSIVE_DISCLOSURE");
1229        crate::test_env::remove_var("LEAN_CTX_STRUCTURE_FIRST");
1230        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1231        let _ = std::fs::remove_dir_all(&dir);
1232    }
1233
1234    #[test]
1235    fn estimate_lines_approximation() {
1236        assert_eq!(estimate_lines(400), 100);
1237        assert_eq!(estimate_lines(2000), 500);
1238        assert_eq!(estimate_lines(0), 0);
1239    }
1240}