1use std::path::Path;
2
3#[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 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 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#[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
80pub 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 if is_project_root_marker(dir) {
95 best = Some(dir.to_string_lossy().to_string());
96 }
97 match dir.parent() {
98 Some(parent) if parent != dir => dir = parent,
99 _ => break,
100 }
101 }
102 best
103}
104
105fn is_project_root_marker(dir: &Path) -> bool {
107 const MARKERS: &[&str] = &[
108 ".git",
109 "Cargo.toml",
110 "package.json",
111 "go.work",
112 "pnpm-workspace.yaml",
113 "lerna.json",
114 "nx.json",
115 "turbo.json",
116 ".projectile",
117 "pyproject.toml",
118 "setup.py",
119 "Makefile",
120 "CMakeLists.txt",
121 "BUILD.bazel",
122 ];
123 MARKERS.iter().any(|m| dir.join(m).exists())
124}
125
126pub fn detect_project_root_or_cwd(file_path: &str) -> String {
130 if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
131 && !env_root.is_empty()
132 {
133 return env_root;
134 }
135 let cfg = crate::core::config::Config::load();
136 if let Some(ref cfg_root) = cfg.project_root
137 && !cfg_root.is_empty()
138 {
139 return cfg_root.clone();
140 }
141 if let Some(ide_root) = resolve_ide_path(&cfg, file_path) {
142 return ide_root;
143 }
144 if let Some(root) = detect_project_root(file_path) {
145 return root;
146 }
147
148 let fallback = {
149 let p = Path::new(file_path);
150 if p.exists() {
151 if p.is_dir() {
152 file_path.to_string()
153 } else {
154 p.parent().map_or_else(
155 || file_path.to_string(),
156 |pp| pp.to_string_lossy().to_string(),
157 )
158 }
159 } else {
160 std::env::current_dir()
161 .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
162 }
163 };
164
165 if is_broad_directory(&fallback) && !crate::core::runtime_flags::is_dashboard_server() {
166 use std::sync::Once;
167 static WARN_ONCE: Once = Once::new();
168 WARN_ONCE.call_once(|| {
169 tracing::warn!(
170 "[protocol: no project detected — current directory is {fallback} which is not a project root.\n \
171 To fix: run from inside a project (with .git, Cargo.toml, package.json, etc.)\n \
172 Or set: export LEAN_CTX_PROJECT_ROOT=/path/to/your/project]"
173 );
174 });
175 }
176
177 fallback
178}
179
180fn is_broad_directory(path: &str) -> bool {
181 if path == "/" || path == "\\" || path == "." {
182 return true;
183 }
184 if let Some(home) = dirs::home_dir() {
185 let home_str = home.to_string_lossy();
186 if path == home_str.as_ref() || path == format!("{home_str}/") {
187 return true;
188 }
189 }
190 false
191}
192
193fn resolve_ide_path(cfg: &crate::core::config::Config, file_path: &str) -> Option<String> {
196 if cfg.ide_paths.is_empty() {
197 return None;
198 }
199 let agent = std::env::var("LEAN_CTX_AGENT").ok()?;
200 let agent_lower = agent.to_lowercase();
201 let paths = cfg.ide_paths.get(&agent_lower)?;
202 let fp = Path::new(file_path);
203 for allowed in paths {
204 let ap = Path::new(allowed.as_str());
205 if fp.starts_with(ap) {
206 return Some(allowed.clone());
207 }
208 }
209 paths.first().cloned()
211}
212
213pub fn display_path(path: &str) -> String {
220 path.replace('\\', "/")
221}
222
223pub fn shorten_path(path: &str) -> String {
224 let normalized = display_path(path);
225 let p = Path::new(&normalized);
226 if let Some(name) = p.file_name() {
227 return name.to_string_lossy().to_string();
228 }
229 normalized
230}
231
232pub fn shorten_path_relative(path: &str, root: &str) -> String {
239 let norm_path = display_path(path);
240 let norm_root = display_path(root);
241 let norm_root = norm_root.strip_suffix('/').unwrap_or(&norm_root);
242 if let Some(rest) = norm_path.strip_prefix(norm_root)
243 && let Some(rel) = rest.strip_prefix('/')
244 && !rel.is_empty()
245 {
246 return rel.to_string();
247 }
248 shorten_path(&norm_path)
249}
250
251static MCP_CONTEXT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
256
257pub fn set_mcp_context(active: bool) {
259 MCP_CONTEXT.store(active, std::sync::atomic::Ordering::Relaxed);
260}
261
262pub fn savings_footer_visible() -> bool {
266 if matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1") {
267 return false;
268 }
269 if matches!(std::env::var("LEAN_CTX_SHOW_SAVINGS"), Ok(v) if v.trim() == "0") {
270 return false;
271 }
272 if matches!(std::env::var("LEAN_CTX_SHOW_SAVINGS"), Ok(v) if v.trim() == "1") {
273 return true;
274 }
275 let mode = super::config::SavingsFooter::effective();
276 match mode {
277 super::config::SavingsFooter::Always => true,
278 super::config::SavingsFooter::Never => false,
279 super::config::SavingsFooter::Auto => {
280 !MCP_CONTEXT.load(std::sync::atomic::Ordering::Relaxed)
281 }
282 }
283}
284
285pub fn meta_visible() -> bool {
289 if matches!(std::env::var("LEAN_CTX_QUIET"), Ok(v) if v.trim() == "1") {
290 return false;
291 }
292 matches!(std::env::var("LEAN_CTX_META"), Ok(v) if v.trim() == "1")
293 || matches!(std::env::var("LEAN_CTX_DIAGNOSTICS"), Ok(v) if v.trim() == "1")
294}
295
296pub fn format_savings(original: usize, compressed: usize) -> String {
302 super::savings_footer::format_footer_basic(original, compressed)
303}
304
305pub fn format_savings_with_info(
309 original: usize,
310 compressed: usize,
311 mode: Option<&str>,
312 detail: Option<&str>,
313) -> String {
314 super::savings_footer::format_footer(&super::savings_footer::SavingsInfo {
315 original,
316 compressed,
317 mode,
318 detail,
319 })
320}
321
322pub fn append_savings(output: &str, original: usize, compressed: usize) -> String {
324 super::savings_footer::append_footer_basic(output, original, compressed)
325}
326
327pub fn append_savings_with_info(
329 output: &str,
330 original: usize,
331 compressed: usize,
332 mode: Option<&str>,
333 detail: Option<&str>,
334) -> String {
335 super::savings_footer::append_footer(
336 output,
337 &super::savings_footer::SavingsInfo {
338 original,
339 compressed,
340 mode,
341 detail,
342 },
343 )
344}
345
346pub fn strip_trailing_savings_footer(output: &str) -> &str {
356 let body = output.trim_end_matches('\n');
357 let (head, last_line) = match body.rfind('\n') {
358 Some(nl) => (&body[..nl], &body[nl + 1..]),
359 None => ("", body),
360 };
361 if is_savings_footer_line(last_line) {
362 head
363 } else {
364 output
365 }
366}
367
368fn is_savings_footer_line(line: &str) -> bool {
369 let l = line.trim();
370 (l.starts_with("\u{2500}\u{2500}\u{2500} ") && l.ends_with(" \u{2500}\u{2500}\u{2500}"))
371 || (l.starts_with("[lean-ctx: ") && l.ends_with(']'))
372}
373
374pub struct InstructionTemplate {
376 pub code: &'static str,
377 pub full: &'static str,
378}
379
380const TEMPLATES: &[InstructionTemplate] = &[
385 InstructionTemplate {
386 code: "ACT1",
387 full: "act now, 1-line result",
388 },
389 InstructionTemplate {
390 code: "BRIEF",
391 full: "1-2 line approach, then act",
392 },
393 InstructionTemplate {
394 code: "FULL",
395 full: "outline+edge cases first",
396 },
397 InstructionTemplate {
398 code: "DELTA",
399 full: "changed lines only",
400 },
401 InstructionTemplate {
402 code: "NOREPEAT",
403 full: "use Fn refs",
404 },
405 InstructionTemplate {
406 code: "STRUCT",
407 full: "+/-/~",
408 },
409 InstructionTemplate {
410 code: "1LINE",
411 full: "1 line/action",
412 },
413 InstructionTemplate {
414 code: "QUALITY",
415 full: "keep edge cases",
416 },
417 InstructionTemplate {
418 code: "FREF",
419 full: "Fn refs, no paths",
420 },
421 InstructionTemplate {
422 code: "DIFF",
423 full: "diff lines only",
424 },
425];
426
427pub fn instruction_decoder_block(tdd_active: bool) -> String {
432 if !tdd_active {
433 return String::new();
434 }
435 let pairs: Vec<String> = TEMPLATES
436 .iter()
437 .map(|t| format!("{}={}", t.code, t.full))
438 .collect();
439 format!("INSTRUCTION CODES:\n {}", pairs.join(" | "))
440}
441
442pub fn encode_instructions(complexity: &str) -> String {
445 match complexity {
446 "mechanical" => "MODE: ACT1 DELTA 1LINE | BUDGET: <=50 tokens, 1 line answer".to_string(),
447 "simple" => "MODE: BRIEF DELTA 1LINE | BUDGET: <=100 tokens, structured".to_string(),
448 "standard" => "MODE: BRIEF DELTA NOREPEAT STRUCT | BUDGET: <=200 tokens".to_string(),
449 "complex" => {
450 "MODE: FULL QUALITY NOREPEAT STRUCT FREF DIFF | BUDGET: <=500 tokens".to_string()
451 }
452 "architectural" => {
453 "MODE: FULL QUALITY NOREPEAT STRUCT FREF | BUDGET: unlimited".to_string()
454 }
455 _ => "MODE: BRIEF | BUDGET: <=200 tokens".to_string(),
456 }
457}
458
459pub fn encode_instructions_with_snr(complexity: &str, compression_pct: f64) -> String {
461 let snr = if compression_pct > 0.0 {
462 1.0 - (compression_pct / 100.0)
463 } else {
464 1.0
465 };
466 let base = encode_instructions(complexity);
467 format!("{base} | SNR: {snr:.2}")
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 #[test]
475 fn strip_trailing_savings_footer_handles_both_styles() {
476 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}";
478 assert_eq!(
479 strip_trailing_savings_footer(boxed),
480 "body line one\nbody line two"
481 );
482 let verbatim = "out\n[lean-ctx: 4200\u{2192}840 tok, verbatim truncated]";
484 assert_eq!(strip_trailing_savings_footer(verbatim), "out");
485 assert_eq!(
487 strip_trailing_savings_footer("plain body\n"),
488 "plain body\n"
489 );
490 assert_eq!(
492 strip_trailing_savings_footer("[lean-ctx: 10\u{2192}5 tok, verbatim truncated]"),
493 ""
494 );
495 assert_eq!(
497 strip_trailing_savings_footer("see [lean-ctx: docs] for details"),
498 "see [lean-ctx: docs] for details"
499 );
500 }
501
502 #[test]
503 fn display_path_normalizes_windows_separators() {
504 assert_eq!(
506 display_path(r"C:\Users\zir\AppData\Local\Temp\win-build-log.txt"),
507 "C:/Users/zir/AppData/Local/Temp/win-build-log.txt"
508 );
509 assert_eq!(display_path("src/main.rs"), "src/main.rs");
510 }
511
512 #[test]
513 fn shorten_path_basename_for_windows_abs_path() {
514 assert_eq!(
515 shorten_path(r"D:\Temp\win-build-raw.log"),
516 "win-build-raw.log"
517 );
518 assert_eq!(shorten_path("a/b/c.txt"), "c.txt");
519 }
520
521 #[test]
522 fn shorten_path_relative_handles_windows_separators() {
523 assert_eq!(
525 shorten_path_relative(r"C:\proj\src\app\main.rs", r"C:\proj"),
526 "src/app/main.rs"
527 );
528 assert_eq!(
530 shorten_path_relative(r"C:\proj\src\main.rs", "C:/proj/"),
531 "src/main.rs"
532 );
533 assert_eq!(
536 shorten_path_relative(r"C:\Users\zir\Temp\build.log", r"D:\proj"),
537 "build.log"
538 );
539 }
540
541 #[test]
542 fn shorten_path_relative_requires_component_boundary() {
543 assert_eq!(shorten_path_relative("a/bc/d.rs", "a/b"), "d.rs");
545 assert_eq!(shorten_path_relative("a/b/d.rs", "a/b"), "d.rs");
546 }
547
548 #[test]
549 fn is_project_root_marker_detects_git() {
550 let tmp = std::env::temp_dir().join("lean-ctx-test-root-marker");
551 let _ = std::fs::create_dir_all(&tmp);
552 let git_dir = tmp.join(".git");
553 let _ = std::fs::create_dir_all(&git_dir);
554 assert!(is_project_root_marker(&tmp));
555 let _ = std::fs::remove_dir_all(&tmp);
556 }
557
558 #[test]
559 fn is_project_root_marker_detects_cargo_toml() {
560 let tmp = std::env::temp_dir().join("lean-ctx-test-cargo-marker");
561 let _ = std::fs::create_dir_all(&tmp);
562 let _ = std::fs::write(tmp.join("Cargo.toml"), "[package]");
563 assert!(is_project_root_marker(&tmp));
564 let _ = std::fs::remove_dir_all(&tmp);
565 }
566
567 #[test]
568 fn detect_project_root_finds_outermost() {
569 let base = std::env::temp_dir().join("lean-ctx-test-monorepo");
570 let inner = base.join("packages").join("app");
571 let _ = std::fs::create_dir_all(&inner);
572 let _ = std::fs::create_dir_all(base.join(".git"));
573 let _ = std::fs::create_dir_all(inner.join(".git"));
574
575 let test_file = inner.join("main.rs");
576 let _ = std::fs::write(&test_file, "fn main() {}");
577
578 let root = detect_project_root(test_file.to_str().unwrap());
579 assert!(root.is_some(), "should find a project root for nested .git");
580 let root_path = std::path::PathBuf::from(root.unwrap());
581 assert_eq!(
582 crate::core::pathutil::safe_canonicalize(&root_path).ok(),
583 crate::core::pathutil::safe_canonicalize(&base).ok(),
584 "should return outermost .git, not inner"
585 );
586
587 let _ = std::fs::remove_dir_all(&base);
588 }
589
590 #[test]
591 fn decoder_block_contains_all_codes() {
592 let block = instruction_decoder_block(true);
593 for t in TEMPLATES {
594 assert!(
595 block.contains(t.code),
596 "decoder should contain code {}",
597 t.code
598 );
599 }
600 }
601
602 #[test]
603 fn decoder_block_empty_outside_tdd() {
604 assert!(instruction_decoder_block(false).is_empty());
605 }
606
607 #[test]
608 fn decoder_codes_match_what_encode_can_emit() {
609 let all_modes: Vec<String> = [
612 "mechanical",
613 "simple",
614 "standard",
615 "complex",
616 "architectural",
617 "unknown",
618 ]
619 .iter()
620 .map(|c| encode_instructions(c))
621 .collect();
622 for t in TEMPLATES {
623 assert!(
624 all_modes.iter().any(|m| m.contains(t.code)),
625 "code {} is defined but never emitted",
626 t.code
627 );
628 }
629 }
630
631 #[test]
632 fn encoded_instructions_are_compact() {
633 use super::super::tokens::count_tokens;
634 let full = "TASK COMPLEXITY: mechanical\nMinimal reasoning needed. Act immediately, report result in one line. Show only changed lines, not full files.";
635 let encoded = encode_instructions("mechanical");
636 assert!(
637 count_tokens(&encoded) <= count_tokens(full),
638 "encoded ({}) should be <= full ({})",
639 count_tokens(&encoded),
640 count_tokens(full)
641 );
642 }
643
644 #[test]
645 fn all_complexity_levels_encode() {
646 for level in &["mechanical", "standard", "architectural"] {
647 let encoded = encode_instructions(level);
648 assert!(encoded.starts_with("MODE:"), "should start with MODE:");
649 }
650 }
651
652 #[test]
653 fn savings_footer_env_gated_tests() {
654 let _lock = crate::core::data_dir::test_env_lock();
655
656 super::MCP_CONTEXT.store(false, std::sync::atomic::Ordering::Relaxed);
658 crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "always");
659 crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "1");
660 crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");
661 crate::test_env::remove_var("LEAN_CTX_QUIET");
662
663 let s = super::format_savings(100, 50);
664 assert!(s.contains("\u{2192}"), "expected arrow: {s}");
665 assert!(s.contains("\u{2193}50%"), "expected pct: {s}");
666 assert!(
667 s.starts_with("\u{2500}\u{2500}\u{2500}"),
668 "expected box-drawing: {s}"
669 );
670
671 let s = super::format_savings_with_info(4200, 840, Some("map"), None);
672 assert!(s.contains("mode: map"), "expected mode: {s}");
673 assert!(s.contains("\u{2193}80%"), "expected 80%: {s}");
674
675 crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
677 crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "0");
678 let s = super::format_savings(100, 50);
679 assert!(s.is_empty(), "expected empty with never: {s}");
680
681 let result = super::append_savings("hello", 100, 50);
682 assert_eq!(result, "hello");
683
684 super::MCP_CONTEXT.store(true, std::sync::atomic::Ordering::Relaxed);
686 crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "auto");
687 crate::test_env::remove_var("LEAN_CTX_SHOW_SAVINGS");
688 let s = super::format_savings(100, 50);
689 assert!(s.is_empty(), "expected empty in MCP+auto: {s}");
690 super::MCP_CONTEXT.store(false, std::sync::atomic::Ordering::Relaxed);
691
692 crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
694 crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "1");
695 assert!(super::savings_footer_visible());
696 crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "0");
697 assert!(!super::savings_footer_visible());
698
699 crate::test_env::remove_var("LEAN_CTX_SHOW_SAVINGS");
700 crate::test_env::remove_var("LEAN_CTX_SAVINGS_FOOTER");
701 crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
702 }
703
704 #[test]
707 fn crp_resolution_precedence() {
708 use crate::core::config::CompressionLevel as L;
709 let r = CrpMode::resolve_from;
710 assert_eq!(r(None, None, L::Lite, None), CrpMode::Off);
712 assert_eq!(r(None, None, L::Lite, Some("tdd")), CrpMode::Tdd);
714 assert_eq!(r(None, None, L::Off, Some("compact")), CrpMode::Compact);
715 assert_eq!(r(None, None, L::Standard, Some("tdd")), CrpMode::Compact);
717 assert_eq!(r(None, None, L::Max, Some("off")), CrpMode::Tdd);
718 assert_eq!(r(None, Some(L::Lite), L::Max, Some("tdd")), CrpMode::Off);
720 assert_eq!(
722 r(Some("tdd"), Some(L::Off), L::Off, Some("off")),
723 CrpMode::Tdd
724 );
725 assert_eq!(r(Some("bogus"), None, L::Max, Some("tdd")), CrpMode::Off);
726 assert_eq!(r(Some(" "), None, L::Lite, Some("tdd")), CrpMode::Tdd);
727 assert_eq!(r(None, None, L::Lite, Some("weird")), CrpMode::Off);
729 }
730
731 #[test]
732 fn crp_mode_str_round_trips() {
733 for m in [CrpMode::Off, CrpMode::Compact, CrpMode::Tdd] {
734 assert_eq!(CrpMode::parse(m.as_str()), Some(m));
735 }
736 }
737}