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) && !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
107pub(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
116fn 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
137pub fn detect_project_root_or_cwd(file_path: &str) -> String {
142 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
227fn 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 paths.first().cloned()
245}
246
247pub 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
266pub 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
285static MCP_CONTEXT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
290
291pub fn set_mcp_context(active: bool) {
293 MCP_CONTEXT.store(active, std::sync::atomic::Ordering::Relaxed);
294}
295
296pub 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
319pub 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
330pub fn format_savings(original: usize, compressed: usize) -> String {
336 super::savings_footer::format_footer_basic(original, compressed)
337}
338
339pub 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
356pub fn append_savings(output: &str, original: usize, compressed: usize) -> String {
358 super::savings_footer::append_footer_basic(output, original, compressed)
359}
360
361pub 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
380pub 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
408pub struct InstructionTemplate {
410 pub code: &'static str,
411 pub full: &'static str,
412}
413
414const 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
461pub 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
476pub 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
493pub 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 #[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 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 let verbatim = "out\n[lean-ctx: 4200\u{2192}840 tok, verbatim truncated]";
536 assert_eq!(strip_trailing_savings_footer(verbatim), "out");
537 assert_eq!(
539 strip_trailing_savings_footer("plain body\n"),
540 "plain body\n"
541 );
542 assert_eq!(
544 strip_trailing_savings_footer("[lean-ctx: 10\u{2192}5 tok, verbatim truncated]"),
545 ""
546 );
547 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 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 assert_eq!(
577 shorten_path_relative(r"C:\proj\src\app\main.rs", r"C:\proj"),
578 "src/app/main.rs"
579 );
580 assert_eq!(
582 shorten_path_relative(r"C:\proj\src\main.rs", "C:/proj/"),
583 "src/main.rs"
584 );
585 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 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 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 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 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 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 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 #[test]
762 fn crp_resolution_precedence() {
763 use crate::core::config::CompressionLevel as L;
764 let r = CrpMode::resolve_from;
765 assert_eq!(r(None, None, L::Lite, None), CrpMode::Off);
767 assert_eq!(r(None, None, L::Lite, Some("tdd")), CrpMode::Tdd);
769 assert_eq!(r(None, None, L::Off, Some("compact")), CrpMode::Compact);
770 assert_eq!(r(None, None, L::Standard, Some("tdd")), CrpMode::Compact);
772 assert_eq!(r(None, None, L::Max, Some("off")), CrpMode::Tdd);
773 assert_eq!(r(None, Some(L::Lite), L::Max, Some("tdd")), CrpMode::Off);
775 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 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}