1pub(crate) fn print_savings(original: usize, sent: usize) {
2 let footer = crate::core::protocol::format_savings(original, sent);
3 if !footer.is_empty() {
4 println!("{footer}");
5 }
6}
7
8#[cfg(unix)]
10pub(crate) fn filter_daemon_output(text: &str) -> String {
11 if crate::core::protocol::savings_footer_visible() {
12 return text.to_string();
13 }
14 text.lines()
15 .filter(|l| {
16 let t = l.trim();
17 !(t.starts_with('[')
18 && t.contains("tok")
19 && t.ends_with(']')
20 && (t.contains("tok saved") || t.contains("lean-ctx:") || t.contains("vs native")))
21 })
22 .collect::<Vec<_>>()
23 .join("\n")
24}
25
26pub fn load_shell_history_pub() -> Vec<String> {
27 load_shell_history()
28}
29
30pub(crate) fn load_shell_history() -> Vec<String> {
31 let shell = std::env::var("SHELL").unwrap_or_default();
32 let Some(home) = dirs::home_dir() else {
33 return Vec::new();
34 };
35
36 let history_file = if shell.contains("zsh") {
37 home.join(".zsh_history")
38 } else if shell.contains("fish") {
39 home.join(".local/share/fish/fish_history")
40 } else if cfg!(windows) && shell.is_empty() {
41 home.join("AppData")
42 .join("Roaming")
43 .join("Microsoft")
44 .join("Windows")
45 .join("PowerShell")
46 .join("PSReadLine")
47 .join("ConsoleHost_history.txt")
48 } else {
49 home.join(".bash_history")
50 };
51
52 match std::fs::read(&history_file) {
56 Ok(bytes) => String::from_utf8_lossy(&bytes)
57 .lines()
58 .filter_map(|l| {
59 let trimmed = l.trim();
60 if trimmed.starts_with(':') {
61 trimmed
62 .split(';')
63 .nth(1)
64 .map(std::string::ToString::to_string)
65 } else {
66 Some(trimmed.to_string())
67 }
68 })
69 .filter(|l| !l.is_empty())
70 .collect(),
71 Err(_) => Vec::new(),
72 }
73}
74
75pub(crate) fn daemon_fallback_hint() {
76 use std::sync::Once;
77 static HINT: Once = Once::new();
78 HINT.call_once(|| {
79 if crate::core::protocol::meta_visible() {
80 eprintln!("\x1b[2;33mhint: daemon not running — stats tracked locally (lean-ctx serve -d for full tracking)\x1b[0m");
81 }
82 });
83}
84
85pub(crate) fn format_tokens_cli(tokens: u64) -> String {
86 if tokens >= 1_000_000_000_000 {
87 format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
88 } else if tokens >= 1_000_000_000 {
89 format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
91 } else if tokens >= 1_000_000 {
92 format!("{:.1}M", tokens as f64 / 1_000_000.0)
93 } else if tokens >= 1_000 {
94 format!("{:.1}K", tokens as f64 / 1_000.0)
95 } else {
96 format!("{tokens}")
97 }
98}
99
100pub(crate) fn cli_track_read(path: &str, mode: &str, original_tokens: usize, output_tokens: usize) {
101 crate::core::tool_lifecycle::record_file_read(
102 path,
103 mode,
104 original_tokens,
105 output_tokens,
106 false,
107 );
108}
109
110pub(crate) fn cli_track_read_cached(
111 path: &str,
112 mode: &str,
113 original_tokens: usize,
114 output_tokens: usize,
115) {
116 crate::core::tool_lifecycle::record_file_read(path, mode, original_tokens, output_tokens, true);
117}
118
119pub(crate) fn cli_track_search(
120 modeled_baseline: usize,
121 observed_tokens: usize,
122 output_tokens: usize,
123) {
124 crate::core::tool_lifecycle::record_search(modeled_baseline, observed_tokens, output_tokens);
125}
126
127pub(crate) fn cli_track_tree(original_tokens: usize, output_tokens: usize) {
128 crate::core::tool_lifecycle::record_tree(original_tokens, output_tokens);
129}
130
131pub(crate) fn detect_project_root(args: &[String]) -> String {
132 let mut it = args.iter().peekable();
133 while let Some(a) = it.next() {
134 if let Some(v) = a.strip_prefix("--root=")
135 && !v.trim().is_empty()
136 {
137 return promote_to_git_root(v);
138 }
139 if let Some(v) = a.strip_prefix("--project-root=")
140 && !v.trim().is_empty()
141 {
142 return promote_to_git_root(v);
143 }
144 if (a == "--root" || a == "--project-root")
145 && let Some(v) = it.peek()
146 && !v.starts_with("--")
147 && !v.trim().is_empty()
148 {
149 return promote_to_git_root(v);
150 }
151 }
152 let cwd = std::env::current_dir()
153 .ok()
154 .map_or_else(|| ".".to_string(), |p| p.to_string_lossy().to_string());
155 promote_to_git_root(&cwd)
156}
157
158fn promote_to_git_root(path: &str) -> String {
159 let mut p = std::path::Path::new(path);
160 loop {
161 if p.join(".git").exists() {
162 return p.to_string_lossy().to_string();
163 }
164 match p.parent() {
165 Some(parent) => p = parent,
166 None => return path.to_string(),
167 }
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use super::format_tokens_cli;
174
175 #[test]
176 fn format_tokens_cli_scales_through_billions() {
177 assert_eq!(format_tokens_cli(742), "742");
178 assert_eq!(format_tokens_cli(2_500), "2.5K");
179 assert_eq!(format_tokens_cli(3_400_000), "3.4M");
180 assert_eq!(format_tokens_cli(1_310_000_000), "1.31B");
182 assert_eq!(format_tokens_cli(1_500_000_000_000), "1.50T");
183 }
184}