Skip to main content

lean_ctx/core/
protocol.rs

1use std::path::Path;
2
3// ── Shared types moved here from tools/ to break reverse-dependency ──
4
5/// Context Reduction Protocol mode controlling output verbosity.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum CrpMode {
8    Off,
9    Compact,
10    Tdd,
11}
12
13impl CrpMode {
14    pub fn parse(s: &str) -> Option<Self> {
15        match s.trim().to_lowercase().as_str() {
16            "off" => Some(Self::Off),
17            "compact" => Some(Self::Compact),
18            "tdd" => Some(Self::Tdd),
19            _ => None,
20        }
21    }
22
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::Off => "off",
26            Self::Compact => "compact",
27            Self::Tdd => "tdd",
28        }
29    }
30
31    /// The single CRP resolver (#1890): tool output, MCP instructions and
32    /// `lean-ctx instructions` all go through here, so they can never disagree.
33    /// `profile_crp` is the profile's own `compression.crp_mode`, if it sets one.
34    pub fn resolve(profile_crp: Option<&str>) -> Self {
35        use crate::core::config::{CompressionLevel, Config};
36        let env = std::env::var("LEAN_CTX_CRP_MODE").ok();
37        let forced = CompressionLevel::session_degrade_level().or_else(CompressionLevel::from_env);
38        let configured = CompressionLevel::effective(&Config::load());
39        Self::resolve_from(env.as_deref(), forced, configured, profile_crp)
40    }
41
42    /// Precedence: `LEAN_CTX_CRP_MODE` → a forced level (correction-loop
43    /// degrade, `LEAN_CTX_COMPRESSION`) → a configured `compression_level` that
44    /// implies CRP (standard/max/raw) → the profile's `crp_mode` → off.
45    /// `off`/`lite` only shape prose, so they leave the choice to the profile.
46    pub(crate) fn resolve_from(
47        env: Option<&str>,
48        forced: Option<crate::core::config::CompressionLevel>,
49        configured: crate::core::config::CompressionLevel,
50        profile_crp: Option<&str>,
51    ) -> Self {
52        let level_crp = |level: crate::core::config::CompressionLevel| {
53            Self::parse(level.to_components().2).unwrap_or(Self::Off)
54        };
55        if let Some(v) = env.filter(|v| !v.trim().is_empty()) {
56            return Self::parse(v).unwrap_or(Self::Off);
57        }
58        if let Some(level) = forced {
59            return level_crp(level);
60        }
61        let configured = level_crp(configured);
62        if configured != Self::Off {
63            return configured;
64        }
65        profile_crp.and_then(Self::parse).unwrap_or(Self::Off)
66    }
67}
68
69/// Recorded metrics for a single MCP tool invocation.
70#[derive(Clone, Debug)]
71pub struct ToolCallRecord {
72    pub tool: String,
73    pub original_tokens: usize,
74    pub saved_tokens: usize,
75    pub mode: Option<String>,
76    pub duration_ms: u64,
77    pub timestamp: String,
78}
79
80/// Finds the outermost project root by walking up from `file_path`.
81/// For monorepos with nested `.git` dirs (e.g. `mono/backend/.git` + `mono/frontend/.git`),
82/// returns the outermost ancestor containing `.git`, a workspace marker, or a known
83/// monorepo config file — so the whole monorepo is treated as one project.
84pub fn detect_project_root(file_path: &str) -> Option<String> {
85    let start = Path::new(file_path);
86    let mut dir = if start.is_dir() {
87        start
88    } else {
89        start.parent()?
90    };
91    let mut best: Option<String> = None;
92
93    loop {
94        // `~` with a dotfiles `.git`, `/` or an agent directory carries a
95        // marker without being a project (AP04-G6).
96        if is_project_root_marker(dir) && !crate::core::pathutil::is_broad_or_unsafe_root(dir) {
97            best = Some(dir.to_string_lossy().to_string());
98        }
99        match dir.parent() {
100            Some(parent) if parent != dir => dir = parent,
101            _ => break,
102        }
103    }
104    best
105}
106
107/// True inside a request that is bound to no project: project-keyed writes
108/// are refused there (`project_unresolved`, AP01 §3) instead of keying them
109/// on a file's location.
110pub(crate) fn request_project_unresolved() -> bool {
111    crate::core::policy::runtime::REQUEST_PROJECT
112        .try_with(|slot| slot.borrow().is_none())
113        .unwrap_or(false)
114}
115
116/// Checks if a directory looks like a project root (has `.git`, workspace config, etc.).
117fn is_project_root_marker(dir: &Path) -> bool {
118    const MARKERS: &[&str] = &[
119        ".git",
120        "Cargo.toml",
121        "package.json",
122        "go.work",
123        "pnpm-workspace.yaml",
124        "lerna.json",
125        "nx.json",
126        "turbo.json",
127        ".projectile",
128        "pyproject.toml",
129        "setup.py",
130        "Makefile",
131        "CMakeLists.txt",
132        "BUILD.bazel",
133    ];
134    MARKERS.iter().any(|m| dir.join(m).exists())
135}
136
137/// Returns the project root for `file_path`, falling back to cwd if none found.
138/// Outside a request, checks LEAN_CTX_PROJECT_ROOT env var and config.toml
139/// `project_root` first.
140/// Logs a warning when the fallback is a broad directory (home, root).
141pub fn detect_project_root_or_cwd(file_path: &str) -> String {
142    // Inside a request its bound project is the partition everything it
143    // touches belongs to; a pin, the global config or the process cwd never
144    // replace it. Without a bound project only the file's own location counts
145    // (AP01 §3, AP04-G4).
146    if let Ok(project) =
147        crate::core::policy::runtime::REQUEST_PROJECT.try_with(|slot| slot.borrow().clone())
148    {
149        return match project {
150            Some(root) => root.to_string_lossy().into_owned(),
151            None => detect_project_root(file_path).unwrap_or_else(|| {
152                let path = Path::new(file_path);
153                if path.is_dir() {
154                    file_path.to_string()
155                } else {
156                    path.parent().map_or_else(
157                        || file_path.to_string(),
158                        |p| p.to_string_lossy().into_owned(),
159                    )
160                }
161            }),
162        };
163    }
164    if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
165        && !env_root.is_empty()
166    {
167        return env_root;
168    }
169    let cfg = crate::core::config::Config::load();
170    if let Some(ref cfg_root) = cfg.project_root
171        && !cfg_root.is_empty()
172    {
173        return cfg_root.clone();
174    }
175    if let Some(ide_root) = resolve_ide_path(&cfg, file_path) {
176        return ide_root;
177    }
178    if let Some(root) = detect_project_root(file_path) {
179        return root;
180    }
181
182    let fallback = {
183        let p = Path::new(file_path);
184        if p.exists() {
185            if p.is_dir() {
186                file_path.to_string()
187            } else {
188                p.parent().map_or_else(
189                    || file_path.to_string(),
190                    |pp| pp.to_string_lossy().to_string(),
191                )
192            }
193        } else {
194            std::env::current_dir()
195                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
196        }
197    };
198
199    if is_broad_directory(&fallback) && !crate::core::runtime_flags::is_dashboard_server() {
200        use std::sync::Once;
201        static WARN_ONCE: Once = Once::new();
202        WARN_ONCE.call_once(|| {
203            tracing::warn!(
204                "[protocol: no project detected — current directory is {fallback} which is not a project root.\n  \
205                 To fix: run from inside a project (with .git, Cargo.toml, package.json, etc.)\n  \
206                 Or set: export LEAN_CTX_PROJECT_ROOT=/path/to/your/project]"
207            );
208        });
209    }
210
211    fallback
212}
213
214fn is_broad_directory(path: &str) -> bool {
215    if path == "/" || path == "\\" || path == "." {
216        return true;
217    }
218    if let Some(home) = dirs::home_dir() {
219        let home_str = home.to_string_lossy();
220        if path == home_str.as_ref() || path == format!("{home_str}/") {
221            return true;
222        }
223    }
224    false
225}
226
227/// Resolves per-IDE allowed paths from config. If the active agent has
228/// `ide_paths` configured, returns the first path that contains `file_path`.
229fn resolve_ide_path(cfg: &crate::core::config::Config, file_path: &str) -> Option<String> {
230    if cfg.ide_paths.is_empty() {
231        return None;
232    }
233    let agent = std::env::var("LEAN_CTX_AGENT").ok()?;
234    let agent_lower = agent.to_lowercase();
235    let paths = cfg.ide_paths.get(&agent_lower)?;
236    let fp = Path::new(file_path);
237    for allowed in paths {
238        let ap = Path::new(allowed.as_str());
239        if fp.starts_with(ap) {
240            return Some(allowed.clone());
241        }
242    }
243    // file_path is outside all allowed paths — return first allowed path as root
244    paths.first().cloned()
245}
246
247/// Returns the file name component of a path for compact display.
248/// Normalize a path for display by converting Windows backslashes to forward
249/// slashes. Forward slashes are valid path separators on Windows, and unlike
250/// backslashes they are never misinterpreted as escape sequences by the JSON,
251/// markdown, or terminal layers of MCP clients — which corrupted Windows paths
252/// in tool output (e.g. `C:\Users\…` rendered as `CUsers…`). See issue #324.
253pub fn display_path(path: &str) -> String {
254    path.replace('\\', "/")
255}
256
257pub fn shorten_path(path: &str) -> String {
258    let normalized = display_path(path);
259    let p = Path::new(&normalized);
260    if let Some(name) = p.file_name() {
261        return name.to_string_lossy().to_string();
262    }
263    normalized
264}
265
266/// Returns a path relative to `root` for disambiguated display, always with
267/// forward slashes. Falls back to the basename if stripping fails.
268///
269/// Relativization is done on slash-normalized strings so it works regardless of
270/// the separator style the client sent (Windows backslashes, mixed separators).
271/// A component boundary is required so that root `a/b` never matches `a/bc`.
272pub fn shorten_path_relative(path: &str, root: &str) -> String {
273    let norm_path = display_path(path);
274    let norm_root = display_path(root);
275    let norm_root = norm_root.strip_suffix('/').unwrap_or(&norm_root);
276    if let Some(rest) = norm_path.strip_prefix(norm_root)
277        && let Some(rel) = rest.strip_prefix('/')
278        && !rel.is_empty()
279    {
280        return rel.to_string();
281    }
282    shorten_path(&norm_path)
283}
284
285/// Whether savings footers should be suppressed in tool output.
286///
287/// Default config is `never` to keep CLI output quiet; `auto` remains available for
288/// legacy compatibility and still follows transport context when explicitly enabled.
289static MCP_CONTEXT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
290
291/// Mark the current process as serving MCP tool calls (suppresses savings footers in `auto` mode).
292pub fn set_mcp_context(active: bool) {
293    MCP_CONTEXT.store(active, std::sync::atomic::Ordering::Relaxed);
294}
295
296/// Returns true if savings footers should be shown based on config + transport context.
297///
298/// Suppressed when `LEAN_CTX_QUIET=1`, `LEAN_CTX_SHOW_SAVINGS=0`, or compression is `Max` (ultra).
299pub fn savings_footer_visible() -> bool {
300    if matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1") {
301        return false;
302    }
303    if matches!(std::env::var("LEAN_CTX_SHOW_SAVINGS"), Ok(v) if v.trim() == "0") {
304        return false;
305    }
306    if matches!(std::env::var("LEAN_CTX_SHOW_SAVINGS"), Ok(v) if v.trim() == "1") {
307        return true;
308    }
309    let mode = super::config::SavingsFooter::effective();
310    match mode {
311        super::config::SavingsFooter::Always => true,
312        super::config::SavingsFooter::Never => false,
313        super::config::SavingsFooter::Auto => {
314            !MCP_CONTEXT.load(std::sync::atomic::Ordering::Relaxed)
315        }
316    }
317}
318
319/// Whether non-essential meta lines (cache refs, budget warnings, repetition hints) should be shown.
320///
321/// Default is false to keep tool outputs clean for agents; opt-in via env var.
322pub fn meta_visible() -> bool {
323    if matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1") {
324        return false;
325    }
326    matches!(std::env::var("LEAN_CTX_META"), Ok(v) if v.trim() == "1")
327        || matches!(std::env::var("LEAN_CTX_DIAGNOSTICS"), Ok(v) if v.trim() == "1")
328}
329
330/// Formats a token savings footer with box-drawing delimiters.
331///
332/// Output: `─── 4,200 → 840 tok (↓80%) ───`
333///
334/// Returns an empty string when savings footers are suppressed.
335pub fn format_savings(original: usize, compressed: usize) -> String {
336    super::savings_footer::format_footer_basic(original, compressed)
337}
338
339/// Formats a savings footer with mode and optional detail context.
340///
341/// Output: `─── 4,200 → 840 tok (↓80%) | mode: map ───`
342pub fn format_savings_with_info(
343    original: usize,
344    compressed: usize,
345    mode: Option<&str>,
346    detail: Option<&str>,
347) -> String {
348    super::savings_footer::format_footer(&super::savings_footer::SavingsInfo {
349        original,
350        compressed,
351        mode,
352        detail,
353    })
354}
355
356/// Appends a savings footer to `output` with a newline separator, but only if the footer is non-empty.
357pub fn append_savings(output: &str, original: usize, compressed: usize) -> String {
358    super::savings_footer::append_footer_basic(output, original, compressed)
359}
360
361/// Appends a savings footer with mode/detail context.
362pub fn append_savings_with_info(
363    output: &str,
364    original: usize,
365    compressed: usize,
366    mode: Option<&str>,
367    detail: Option<&str>,
368) -> String {
369    super::savings_footer::append_footer(
370        output,
371        &super::savings_footer::SavingsInfo {
372            original,
373            compressed,
374            mode,
375            detail,
376        },
377    )
378}
379
380/// Removes a single trailing savings footer line, if present.
381///
382/// The compression funnel appends at most one footer as the final line — either
383/// the box-drawing form (`─── 4,200 → 840 tok (↓80%) ───`) or the verbatim
384/// truncation form (`[lean-ctx: 4200→840 tok, verbatim truncated]`). The
385/// `/v1/compress` contract surfaces savings in a structured `stats` field, so
386/// message bodies must stay footer-free and byte-stable for prompt caching
387/// (#498). This strips that trailing line regardless of the ambient
388/// `savings_footer` setting; content without a footer is returned untouched.
389pub fn strip_trailing_savings_footer(output: &str) -> &str {
390    let body = output.trim_end_matches('\n');
391    let (head, last_line) = match body.rfind('\n') {
392        Some(nl) => (&body[..nl], &body[nl + 1..]),
393        None => ("", body),
394    };
395    if is_savings_footer_line(last_line) {
396        head
397    } else {
398        output
399    }
400}
401
402fn is_savings_footer_line(line: &str) -> bool {
403    let l = line.trim();
404    (l.starts_with("\u{2500}\u{2500}\u{2500} ") && l.ends_with(" \u{2500}\u{2500}\u{2500}"))
405        || (l.starts_with("[lean-ctx: ") && l.ends_with(']'))
406}
407
408/// A terse instruction code and its human-readable expansion.
409pub struct InstructionTemplate {
410    pub code: &'static str,
411    pub full: &'static str,
412}
413
414/// Exactly the codes `encode_instructions` can emit — the decoder block rides
415/// in every tdd-mode session, so codes that are never emitted (NODOC,
416/// ACTFIRST, NOMOCK) or already explained inline by the CRP suffix (ABBREV,
417/// SYMBOLS) must not be re-defined here (#579).
418const TEMPLATES: &[InstructionTemplate] = &[
419    InstructionTemplate {
420        code: "ACT1",
421        full: "act now, 1-line result",
422    },
423    InstructionTemplate {
424        code: "BRIEF",
425        full: "1-2 line approach, then act",
426    },
427    InstructionTemplate {
428        code: "FULL",
429        full: "outline+edge cases first",
430    },
431    InstructionTemplate {
432        code: "DELTA",
433        full: "changed lines only",
434    },
435    InstructionTemplate {
436        code: "NOREPEAT",
437        full: "use Fn refs",
438    },
439    InstructionTemplate {
440        code: "STRUCT",
441        full: "+/-/~",
442    },
443    InstructionTemplate {
444        code: "1LINE",
445        full: "1 line/action",
446    },
447    InstructionTemplate {
448        code: "QUALITY",
449        full: "keep edge cases",
450    },
451    InstructionTemplate {
452        code: "FREF",
453        full: "Fn refs, no paths",
454    },
455    InstructionTemplate {
456        code: "DIFF",
457        full: "diff lines only",
458    },
459];
460
461/// Generates the INSTRUCTION CODES block for agent system prompts.
462/// Only emits content when the instructions being built are in Tdd CRP mode
463/// (otherwise returns empty — the codes are only emitted in tdd outputs, so
464/// defining them would waste ~60 tokens per MCP instructions payload, #579).
465pub fn instruction_decoder_block(tdd_active: bool) -> String {
466    if !tdd_active {
467        return String::new();
468    }
469    let pairs: Vec<String> = TEMPLATES
470        .iter()
471        .map(|t| format!("{}={}", t.code, t.full))
472        .collect();
473    format!("INSTRUCTION CODES:\n  {}", pairs.join(" | "))
474}
475
476/// Encode an instruction suffix using short codes with budget hints.
477/// Response budget is dynamic based on task complexity to shape LLM output length.
478pub fn encode_instructions(complexity: &str) -> String {
479    match complexity {
480        "mechanical" => "MODE: ACT1 DELTA 1LINE | BUDGET: <=50 tokens, 1 line answer".to_string(),
481        "simple" => "MODE: BRIEF DELTA 1LINE | BUDGET: <=100 tokens, structured".to_string(),
482        "standard" => "MODE: BRIEF DELTA NOREPEAT STRUCT | BUDGET: <=200 tokens".to_string(),
483        "complex" => {
484            "MODE: FULL QUALITY NOREPEAT STRUCT FREF DIFF | BUDGET: <=500 tokens".to_string()
485        }
486        "architectural" => {
487            "MODE: FULL QUALITY NOREPEAT STRUCT FREF | BUDGET: unlimited".to_string()
488        }
489        _ => "MODE: BRIEF | BUDGET: <=200 tokens".to_string(),
490    }
491}
492
493/// Encode instructions with SNR metric for context quality awareness.
494pub fn encode_instructions_with_snr(complexity: &str, compression_pct: f64) -> String {
495    let snr = if compression_pct > 0.0 {
496        1.0 - (compression_pct / 100.0)
497    } else {
498        1.0
499    };
500    let base = encode_instructions(complexity);
501    format!("{base} | SNR: {snr:.2}")
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    /// AP04-G4: a pinned `LEAN_CTX_PROJECT_ROOT` (or global config root) does
509    /// not replace the project a request is bound to.
510    #[test]
511    fn a_pin_does_not_replace_the_request_project() {
512        let _data = crate::core::data_dir::isolated_data_dir();
513        let (request, pinned) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
514        let file = request.path().join("lib.rs");
515        std::fs::write(&file, "fn main() {}\n").unwrap();
516        let _pin = crate::test_env::VarGuard::set("LEAN_CTX_PROJECT_ROOT", pinned.path());
517
518        let root = crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
519            std::cell::RefCell::new(Some(request.path().to_path_buf())),
520            || detect_project_root_or_cwd(&file.to_string_lossy()),
521        );
522
523        assert_eq!(root, request.path().to_string_lossy());
524    }
525
526    #[test]
527    fn strip_trailing_savings_footer_handles_both_styles() {
528        // Box-drawing footer.
529        let boxed = "body line one\nbody line two\n\u{2500}\u{2500}\u{2500} 4,200 \u{2192} 840 tok (\u{2193}80%) \u{2500}\u{2500}\u{2500}";
530        assert_eq!(
531            strip_trailing_savings_footer(boxed),
532            "body line one\nbody line two"
533        );
534        // Verbatim-truncation footer.
535        let verbatim = "out\n[lean-ctx: 4200\u{2192}840 tok, verbatim truncated]";
536        assert_eq!(strip_trailing_savings_footer(verbatim), "out");
537        // No footer → untouched (including trailing newline).
538        assert_eq!(
539            strip_trailing_savings_footer("plain body\n"),
540            "plain body\n"
541        );
542        // A footer-only string collapses to empty.
543        assert_eq!(
544            strip_trailing_savings_footer("[lean-ctx: 10\u{2192}5 tok, verbatim truncated]"),
545            ""
546        );
547        // A body line that merely mentions the marker mid-text is preserved.
548        assert_eq!(
549            strip_trailing_savings_footer("see [lean-ctx: docs] for details"),
550            "see [lean-ctx: docs] for details"
551        );
552    }
553
554    #[test]
555    fn display_path_normalizes_windows_separators() {
556        // Issue #324: backslashes were dropped/escaped by client render layers.
557        assert_eq!(
558            display_path(r"C:\Users\zir\AppData\Local\Temp\win-build-log.txt"),
559            "C:/Users/zir/AppData/Local/Temp/win-build-log.txt"
560        );
561        assert_eq!(display_path("src/main.rs"), "src/main.rs");
562    }
563
564    #[test]
565    fn shorten_path_basename_for_windows_abs_path() {
566        assert_eq!(
567            shorten_path(r"D:\Temp\win-build-raw.log"),
568            "win-build-raw.log"
569        );
570        assert_eq!(shorten_path("a/b/c.txt"), "c.txt");
571    }
572
573    #[test]
574    fn shorten_path_relative_handles_windows_separators() {
575        // Relative display keeps forward slashes regardless of input style.
576        assert_eq!(
577            shorten_path_relative(r"C:\proj\src\app\main.rs", r"C:\proj"),
578            "src/app/main.rs"
579        );
580        // Mixed separators between path and root still relativize.
581        assert_eq!(
582            shorten_path_relative(r"C:\proj\src\main.rs", "C:/proj/"),
583            "src/main.rs"
584        );
585        // A non-prefix abs path falls back to a clean basename, never a
586        // separator-stripped blob like "CUserszir…".
587        assert_eq!(
588            shorten_path_relative(r"C:\Users\zir\Temp\build.log", r"D:\proj"),
589            "build.log"
590        );
591    }
592
593    #[test]
594    fn shorten_path_relative_requires_component_boundary() {
595        // Root "a/b" must not match sibling "a/bc".
596        assert_eq!(shorten_path_relative("a/bc/d.rs", "a/b"), "d.rs");
597        assert_eq!(shorten_path_relative("a/b/d.rs", "a/b"), "d.rs");
598    }
599
600    #[test]
601    fn is_project_root_marker_detects_git() {
602        let tmp = std::env::temp_dir().join("lean-ctx-test-root-marker");
603        let _ = std::fs::create_dir_all(&tmp);
604        let git_dir = tmp.join(".git");
605        let _ = std::fs::create_dir_all(&git_dir);
606        assert!(is_project_root_marker(&tmp));
607        let _ = std::fs::remove_dir_all(&tmp);
608    }
609
610    #[test]
611    fn is_project_root_marker_detects_cargo_toml() {
612        let tmp = std::env::temp_dir().join("lean-ctx-test-cargo-marker");
613        let _ = std::fs::create_dir_all(&tmp);
614        let _ = std::fs::write(tmp.join("Cargo.toml"), "[package]");
615        assert!(is_project_root_marker(&tmp));
616        let _ = std::fs::remove_dir_all(&tmp);
617    }
618
619    #[test]
620    fn detect_project_root_finds_outermost() {
621        let base = std::env::temp_dir().join("lean-ctx-test-monorepo");
622        let inner = base.join("packages").join("app");
623        let _ = std::fs::create_dir_all(&inner);
624        let _ = std::fs::create_dir_all(base.join(".git"));
625        let _ = std::fs::create_dir_all(inner.join(".git"));
626
627        let test_file = inner.join("main.rs");
628        let _ = std::fs::write(&test_file, "fn main() {}");
629
630        let root = detect_project_root(test_file.to_str().unwrap());
631        assert!(root.is_some(), "should find a project root for nested .git");
632        let root_path = std::path::PathBuf::from(root.unwrap());
633        assert_eq!(
634            crate::core::pathutil::safe_canonicalize(&root_path).ok(),
635            crate::core::pathutil::safe_canonicalize(&base).ok(),
636            "should return outermost .git, not inner"
637        );
638
639        let _ = std::fs::remove_dir_all(&base);
640    }
641
642    #[test]
643    fn decoder_block_contains_all_codes() {
644        let block = instruction_decoder_block(true);
645        for t in TEMPLATES {
646            assert!(
647                block.contains(t.code),
648                "decoder should contain code {}",
649                t.code
650            );
651        }
652    }
653
654    #[test]
655    fn decoder_block_empty_outside_tdd() {
656        {
657            let found = &instruction_decoder_block(false);
658            assert!(found.is_empty(), "{found:?}");
659        }
660    }
661
662    #[test]
663    fn decoder_codes_match_what_encode_can_emit() {
664        // Every defined code must appear in at least one encode_instructions
665        // output — dead definitions tax every tdd session (#579).
666        let all_modes: Vec<String> = [
667            "mechanical",
668            "simple",
669            "standard",
670            "complex",
671            "architectural",
672            "unknown",
673        ]
674        .iter()
675        .map(|c| encode_instructions(c))
676        .collect();
677        for t in TEMPLATES {
678            assert!(
679                all_modes.iter().any(|m| m.contains(t.code)),
680                "code {} is defined but never emitted",
681                t.code
682            );
683        }
684    }
685
686    #[test]
687    fn encoded_instructions_are_compact() {
688        use super::super::tokens::count_tokens;
689        let full = "TASK COMPLEXITY: mechanical\nMinimal reasoning needed. Act immediately, report result in one line. Show only changed lines, not full files.";
690        let encoded = encode_instructions("mechanical");
691        assert!(
692            count_tokens(&encoded) <= count_tokens(full),
693            "encoded ({}) should be <= full ({})",
694            count_tokens(&encoded),
695            count_tokens(full)
696        );
697    }
698
699    #[test]
700    fn all_complexity_levels_encode() {
701        for level in &["mechanical", "standard", "architectural"] {
702            let encoded = encode_instructions(level);
703            assert!(encoded.starts_with("MODE:"), "should start with MODE:");
704        }
705    }
706
707    #[test]
708    fn savings_footer_env_gated_tests() {
709        let _lock = crate::core::data_dir::test_env_lock();
710
711        // Use full annotation mode for exact percentage checks
712        super::MCP_CONTEXT.store(false, std::sync::atomic::Ordering::Relaxed);
713        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "always");
714        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "1");
715        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");
716        crate::test_env::remove_var("LEAN_CTX_QUIET");
717
718        let s = super::format_savings(100, 50);
719        assert!(s.contains("\u{2192}"), "expected arrow: {s}");
720        assert!(s.contains("\u{2193}50%"), "expected pct: {s}");
721        assert!(
722            s.starts_with("\u{2500}\u{2500}\u{2500}"),
723            "expected box-drawing: {s}"
724        );
725
726        let s = super::format_savings_with_info(4200, 840, Some("map"), None);
727        assert!(s.contains("mode: map"), "expected mode: {s}");
728        assert!(s.contains("\u{2193}80%"), "expected 80%: {s}");
729
730        // Test: never mode suppresses
731        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
732        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "0");
733        let s = super::format_savings(100, 50);
734        assert!(s.is_empty(), "expected empty with never: {s}");
735
736        let result = super::append_savings("hello", 100, 50);
737        assert_eq!(result, "hello");
738
739        // Test: MCP auto mode suppresses
740        super::MCP_CONTEXT.store(true, std::sync::atomic::Ordering::Relaxed);
741        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "auto");
742        crate::test_env::remove_var("LEAN_CTX_SHOW_SAVINGS");
743        let s = super::format_savings(100, 50);
744        assert!(s.is_empty(), "expected empty in MCP+auto: {s}");
745        super::MCP_CONTEXT.store(false, std::sync::atomic::Ordering::Relaxed);
746
747        // Test: SHOW_SAVINGS overrides config
748        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
749        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "1");
750        assert!(super::savings_footer_visible());
751        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "0");
752        assert!(!super::savings_footer_visible());
753
754        crate::test_env::remove_var("LEAN_CTX_SHOW_SAVINGS");
755        crate::test_env::remove_var("LEAN_CTX_SAVINGS_FOOTER");
756        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
757    }
758
759    /// #1890: one precedence chain — env → forced level → CRP-implying
760    /// configured level → profile → off.
761    #[test]
762    fn crp_resolution_precedence() {
763        use crate::core::config::CompressionLevel as L;
764        let r = CrpMode::resolve_from;
765        // Default config (Lite) + default profile (no crp_mode) → off.
766        assert_eq!(r(None, None, L::Lite, None), CrpMode::Off);
767        // A profile's crp_mode is honoured when nothing overrides it.
768        assert_eq!(r(None, None, L::Lite, Some("tdd")), CrpMode::Tdd);
769        assert_eq!(r(None, None, L::Off, Some("compact")), CrpMode::Compact);
770        // A configured level that implies CRP beats the profile.
771        assert_eq!(r(None, None, L::Standard, Some("tdd")), CrpMode::Compact);
772        assert_eq!(r(None, None, L::Max, Some("off")), CrpMode::Tdd);
773        // A forced level (env / correction-loop degrade) beats the profile.
774        assert_eq!(r(None, Some(L::Lite), L::Max, Some("tdd")), CrpMode::Off);
775        // LEAN_CTX_CRP_MODE wins over everything; invalid values fail safe.
776        assert_eq!(
777            r(Some("tdd"), Some(L::Off), L::Off, Some("off")),
778            CrpMode::Tdd
779        );
780        assert_eq!(r(Some("bogus"), None, L::Max, Some("tdd")), CrpMode::Off);
781        assert_eq!(r(Some("  "), None, L::Lite, Some("tdd")), CrpMode::Tdd);
782        // Unknown profile values fall back to off.
783        assert_eq!(r(None, None, L::Lite, Some("weird")), CrpMode::Off);
784    }
785
786    #[test]
787    fn crp_mode_str_round_trips() {
788        for m in [CrpMode::Off, CrpMode::Compact, CrpMode::Tdd] {
789            assert_eq!(CrpMode::parse(m.as_str()), Some(m));
790        }
791    }
792}