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