1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::PathBuf;
4use std::sync::Mutex;
5use std::time::Instant;
6
7#[derive(Serialize, Deserialize, Default, Clone)]
8pub struct StatsStore {
9 pub total_commands: u64,
10 pub total_input_tokens: u64,
11 pub total_output_tokens: u64,
12 pub first_use: Option<String>,
13 pub last_use: Option<String>,
14 pub commands: HashMap<String, CommandStats>,
15 pub daily: Vec<DayStats>,
16 #[serde(default)]
17 pub cep: CepStats,
18}
19
20#[derive(Serialize, Deserialize, Clone, Default)]
21pub struct CepStats {
22 pub sessions: u64,
23 pub total_cache_hits: u64,
24 pub total_cache_reads: u64,
25 pub total_tokens_original: u64,
26 pub total_tokens_compressed: u64,
27 pub modes: HashMap<String, u64>,
28 pub scores: Vec<CepSessionSnapshot>,
29 #[serde(default)]
30 pub last_session_pid: Option<u32>,
31 #[serde(default)]
32 pub last_session_original: Option<u64>,
33 #[serde(default)]
34 pub last_session_compressed: Option<u64>,
35}
36
37#[derive(Serialize, Deserialize, Clone)]
38pub struct CepSessionSnapshot {
39 pub timestamp: String,
40 pub score: u32,
41 pub cache_hit_rate: u32,
42 pub mode_diversity: u32,
43 pub compression_rate: u32,
44 pub tool_calls: u64,
45 pub tokens_saved: u64,
46 pub complexity: String,
47}
48
49#[derive(Serialize, Deserialize, Clone, Default, Debug)]
50pub struct CommandStats {
51 pub count: u64,
52 pub input_tokens: u64,
53 pub output_tokens: u64,
54}
55
56#[derive(Serialize, Deserialize, Clone)]
57pub struct DayStats {
58 pub date: String,
59 pub commands: u64,
60 pub input_tokens: u64,
61 pub output_tokens: u64,
62}
63
64fn stats_dir() -> Option<PathBuf> {
65 dirs::home_dir().map(|h| h.join(".lean-ctx"))
66}
67
68fn stats_path() -> Option<PathBuf> {
69 stats_dir().map(|d| d.join("stats.json"))
70}
71
72fn load_from_disk() -> StatsStore {
73 let path = match stats_path() {
74 Some(p) => p,
75 None => return StatsStore::default(),
76 };
77
78 match std::fs::read_to_string(&path) {
79 Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
80 Err(_) => StatsStore::default(),
81 }
82}
83
84fn save_to_disk(store: &StatsStore) {
85 let dir = match stats_dir() {
86 Some(d) => d,
87 None => return,
88 };
89
90 if !dir.exists() {
91 let _ = std::fs::create_dir_all(&dir);
92 }
93
94 let path = dir.join("stats.json");
95 if let Ok(json) = serde_json::to_string(store) {
96 let tmp = dir.join(".stats.json.tmp");
97 if std::fs::write(&tmp, &json).is_ok() {
98 let _ = std::fs::rename(&tmp, &path);
99 }
100 }
101}
102
103pub fn load() -> StatsStore {
104 let guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
105 if let Some((ref store, _)) = *guard {
106 return store.clone();
107 }
108 drop(guard);
109 load_from_disk()
110}
111
112pub fn save(store: &StatsStore) {
113 save_to_disk(store);
114}
115
116const FLUSH_INTERVAL_SECS: u64 = 30;
117
118static STATS_BUFFER: Mutex<Option<(StatsStore, Instant)>> = Mutex::new(None);
119
120fn with_buffer<F, R>(f: F) -> R
121where
122 F: FnOnce(&mut StatsStore, &mut Instant) -> R,
123{
124 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
125 let (store, last_flush) = guard.get_or_insert_with(|| (load_from_disk(), Instant::now()));
126 f(store, last_flush)
127}
128
129fn maybe_flush(store: &StatsStore, last_flush: &mut Instant) {
130 if last_flush.elapsed().as_secs() >= FLUSH_INTERVAL_SECS {
131 save_to_disk(store);
132 *last_flush = Instant::now();
133 }
134}
135
136pub fn flush() {
137 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
138 if let Some((ref store, ref mut last_flush)) = *guard {
139 save_to_disk(store);
140 *last_flush = Instant::now();
141 }
142}
143
144pub fn record(command: &str, input_tokens: usize, output_tokens: usize) {
145 with_buffer(|store, last_flush| {
146 let now = chrono::Local::now();
147 let today = now.format("%Y-%m-%d").to_string();
148 let timestamp = now.to_rfc3339();
149
150 store.total_commands += 1;
151 store.total_input_tokens += input_tokens as u64;
152 store.total_output_tokens += output_tokens as u64;
153
154 if store.first_use.is_none() {
155 store.first_use = Some(timestamp.clone());
156 }
157 store.last_use = Some(timestamp);
158
159 let cmd_key = normalize_command(command);
160 let entry = store.commands.entry(cmd_key).or_default();
161 entry.count += 1;
162 entry.input_tokens += input_tokens as u64;
163 entry.output_tokens += output_tokens as u64;
164
165 if let Some(day) = store.daily.last_mut() {
166 if day.date == today {
167 day.commands += 1;
168 day.input_tokens += input_tokens as u64;
169 day.output_tokens += output_tokens as u64;
170 } else {
171 store.daily.push(DayStats {
172 date: today,
173 commands: 1,
174 input_tokens: input_tokens as u64,
175 output_tokens: output_tokens as u64,
176 });
177 }
178 } else {
179 store.daily.push(DayStats {
180 date: today,
181 commands: 1,
182 input_tokens: input_tokens as u64,
183 output_tokens: output_tokens as u64,
184 });
185 }
186
187 if store.daily.len() > 90 {
188 store.daily.drain(..store.daily.len() - 90);
189 }
190
191 maybe_flush(store, last_flush);
192 });
193}
194
195fn normalize_command(command: &str) -> String {
196 let parts: Vec<&str> = command.split_whitespace().collect();
197 if parts.is_empty() {
198 return command.to_string();
199 }
200
201 let base = std::path::Path::new(parts[0])
202 .file_name()
203 .and_then(|n| n.to_str())
204 .unwrap_or(parts[0]);
205
206 match base {
207 "git" => {
208 if parts.len() > 1 {
209 format!("git {}", parts[1])
210 } else {
211 "git".to_string()
212 }
213 }
214 "cargo" => {
215 if parts.len() > 1 {
216 format!("cargo {}", parts[1])
217 } else {
218 "cargo".to_string()
219 }
220 }
221 "npm" | "yarn" | "pnpm" => {
222 if parts.len() > 1 {
223 format!("{} {}", base, parts[1])
224 } else {
225 base.to_string()
226 }
227 }
228 "docker" => {
229 if parts.len() > 1 {
230 format!("docker {}", parts[1])
231 } else {
232 "docker".to_string()
233 }
234 }
235 _ => base.to_string(),
236 }
237}
238
239pub fn reset_cep() {
240 with_buffer(|store, last_flush| {
241 store.cep = CepStats::default();
242 save_to_disk(store);
243 *last_flush = Instant::now();
244 });
245}
246
247pub fn reset_all() {
248 with_buffer(|store, last_flush| {
249 *store = StatsStore::default();
250 save_to_disk(store);
251 *last_flush = Instant::now();
252 });
253}
254
255pub struct GainSummary {
256 pub total_saved: u64,
257 pub total_calls: u64,
258}
259
260pub fn load_stats() -> GainSummary {
261 let store = load();
262 let cm = CostModel::default();
263 let input_saved = store
264 .total_input_tokens
265 .saturating_sub(store.total_output_tokens);
266 let output_saved =
267 store.total_commands * (cm.avg_verbose_output_per_call - cm.avg_concise_output_per_call);
268 GainSummary {
269 total_saved: input_saved + output_saved,
270 total_calls: store.total_commands,
271 }
272}
273
274fn cmd_total_saved(s: &CommandStats, cm: &CostModel) -> u64 {
275 let input_saved = s.input_tokens.saturating_sub(s.output_tokens);
276 let output_saved = s.count * (cm.avg_verbose_output_per_call - cm.avg_concise_output_per_call);
277 input_saved + output_saved
278}
279
280fn day_total_saved(d: &DayStats, cm: &CostModel) -> u64 {
281 let input_saved = d.input_tokens.saturating_sub(d.output_tokens);
282 let output_saved =
283 d.commands * (cm.avg_verbose_output_per_call - cm.avg_concise_output_per_call);
284 input_saved + output_saved
285}
286
287#[allow(clippy::too_many_arguments)]
288pub fn record_cep_session(
289 score: u32,
290 cache_hits: u64,
291 cache_reads: u64,
292 tokens_original: u64,
293 tokens_compressed: u64,
294 modes: &HashMap<String, u64>,
295 tool_calls: u64,
296 complexity: &str,
297) {
298 with_buffer(|store, last_flush| {
299 let cep = &mut store.cep;
300
301 let pid = std::process::id();
302 let prev_original = cep.last_session_original.unwrap_or(0);
303 let prev_compressed = cep.last_session_compressed.unwrap_or(0);
304 let is_same_session = cep.last_session_pid == Some(pid);
305
306 if is_same_session {
307 let delta_original = tokens_original.saturating_sub(prev_original);
308 let delta_compressed = tokens_compressed.saturating_sub(prev_compressed);
309 cep.total_tokens_original += delta_original;
310 cep.total_tokens_compressed += delta_compressed;
311 } else {
312 cep.sessions += 1;
313 cep.total_cache_hits += cache_hits;
314 cep.total_cache_reads += cache_reads;
315 cep.total_tokens_original += tokens_original;
316 cep.total_tokens_compressed += tokens_compressed;
317
318 for (mode, count) in modes {
319 *cep.modes.entry(mode.clone()).or_insert(0) += count;
320 }
321 }
322
323 cep.last_session_pid = Some(pid);
324 cep.last_session_original = Some(tokens_original);
325 cep.last_session_compressed = Some(tokens_compressed);
326
327 let cache_hit_rate = if cache_reads > 0 {
328 (cache_hits as f64 / cache_reads as f64 * 100.0).round() as u32
329 } else {
330 0
331 };
332
333 let compression_rate = if tokens_original > 0 {
334 ((tokens_original - tokens_compressed) as f64 / tokens_original as f64 * 100.0).round()
335 as u32
336 } else {
337 0
338 };
339
340 let total_modes = 6u32;
341 let mode_diversity =
342 ((modes.len() as f64 / total_modes as f64).min(1.0) * 100.0).round() as u32;
343
344 let tokens_saved = tokens_original.saturating_sub(tokens_compressed);
345
346 cep.scores.push(CepSessionSnapshot {
347 timestamp: chrono::Local::now().to_rfc3339(),
348 score,
349 cache_hit_rate,
350 mode_diversity,
351 compression_rate,
352 tool_calls,
353 tokens_saved,
354 complexity: complexity.to_string(),
355 });
356
357 if cep.scores.len() > 100 {
358 cep.scores.drain(..cep.scores.len() - 100);
359 }
360
361 maybe_flush(store, last_flush);
362 });
363}
364
365use super::theme::{self, Theme};
366
367fn active_theme() -> Theme {
368 let cfg = super::config::Config::load();
369 theme::load_theme(&cfg.theme)
370}
371
372pub const DEFAULT_INPUT_PRICE_PER_M: f64 = 2.50;
374pub const DEFAULT_OUTPUT_PRICE_PER_M: f64 = 10.0;
375
376pub struct CostModel {
377 pub input_price_per_m: f64,
378 pub output_price_per_m: f64,
379 pub avg_verbose_output_per_call: u64,
380 pub avg_concise_output_per_call: u64,
381}
382
383impl Default for CostModel {
384 fn default() -> Self {
385 Self {
386 input_price_per_m: DEFAULT_INPUT_PRICE_PER_M,
387 output_price_per_m: DEFAULT_OUTPUT_PRICE_PER_M,
388 avg_verbose_output_per_call: 180,
389 avg_concise_output_per_call: 120,
390 }
391 }
392}
393
394pub struct CostBreakdown {
395 pub input_cost_without: f64,
396 pub input_cost_with: f64,
397 pub output_cost_without: f64,
398 pub output_cost_with: f64,
399 pub total_cost_without: f64,
400 pub total_cost_with: f64,
401 pub total_saved: f64,
402 pub estimated_output_tokens_without: u64,
403 pub estimated_output_tokens_with: u64,
404 pub output_tokens_saved: u64,
405}
406
407impl CostModel {
408 pub fn calculate(&self, store: &StatsStore) -> CostBreakdown {
409 let input_cost_without =
410 store.total_input_tokens as f64 / 1_000_000.0 * self.input_price_per_m;
411 let input_cost_with =
412 store.total_output_tokens as f64 / 1_000_000.0 * self.input_price_per_m;
413
414 let est_output_without = store.total_commands * self.avg_verbose_output_per_call;
415 let est_output_with = store.total_commands * self.avg_concise_output_per_call;
416 let output_saved = est_output_without.saturating_sub(est_output_with);
417
418 let output_cost_without = est_output_without as f64 / 1_000_000.0 * self.output_price_per_m;
419 let output_cost_with = est_output_with as f64 / 1_000_000.0 * self.output_price_per_m;
420
421 let total_without = input_cost_without + output_cost_without;
422 let total_with = input_cost_with + output_cost_with;
423
424 CostBreakdown {
425 input_cost_without,
426 input_cost_with,
427 output_cost_without,
428 output_cost_with,
429 total_cost_without: total_without,
430 total_cost_with: total_with,
431 total_saved: total_without - total_with,
432 estimated_output_tokens_without: est_output_without,
433 estimated_output_tokens_with: est_output_with,
434 output_tokens_saved: output_saved,
435 }
436 }
437}
438
439fn format_usd(amount: f64) -> String {
440 if amount >= 0.01 {
441 format!("${amount:.2}")
442 } else {
443 format!("${amount:.3}")
444 }
445}
446
447fn usd_estimate(tokens: u64) -> String {
448 let cost = tokens as f64 * DEFAULT_INPUT_PRICE_PER_M / 1_000_000.0;
449 format_usd(cost)
450}
451
452fn format_big(n: u64) -> String {
453 if n >= 1_000_000 {
454 format!("{:.1}M", n as f64 / 1_000_000.0)
455 } else if n >= 1_000 {
456 format!("{:.1}K", n as f64 / 1_000.0)
457 } else {
458 format!("{n}")
459 }
460}
461
462fn format_num(n: u64) -> String {
463 if n >= 1_000_000 {
464 format!("{:.1}M", n as f64 / 1_000_000.0)
465 } else if n >= 1_000 {
466 format!("{},{:03}", n / 1_000, n % 1_000)
467 } else {
468 format!("{n}")
469 }
470}
471
472fn truncate_cmd(cmd: &str, max: usize) -> String {
473 if cmd.len() <= max {
474 cmd.to_string()
475 } else {
476 format!("{}…", &cmd[..max - 1])
477 }
478}
479
480fn format_cep_live(lv: &serde_json::Value, t: &Theme) -> String {
481 let mut o = Vec::new();
482 let r = theme::rst();
483 let b = theme::bold();
484 let d = theme::dim();
485
486 let score = lv["cep_score"].as_u64().unwrap_or(0) as u32;
487 let cache_util = lv["cache_utilization"].as_u64().unwrap_or(0);
488 let mode_div = lv["mode_diversity"].as_u64().unwrap_or(0);
489 let comp_rate = lv["compression_rate"].as_u64().unwrap_or(0);
490 let tok_saved = lv["tokens_saved"].as_u64().unwrap_or(0);
491 let tok_orig = lv["tokens_original"].as_u64().unwrap_or(0);
492 let tool_calls = lv["tool_calls"].as_u64().unwrap_or(0);
493 let cache_hits = lv["cache_hits"].as_u64().unwrap_or(0);
494 let total_reads = lv["total_reads"].as_u64().unwrap_or(0);
495 let complexity = lv["task_complexity"].as_str().unwrap_or("Standard");
496
497 o.push(String::new());
498 o.push(format!(
499 " {icon} {brand} {cep} {d}Live Session (no historical data yet){r}",
500 icon = t.header_icon(),
501 brand = t.brand_title(),
502 cep = t.section_title("CEP"),
503 ));
504 o.push(format!(" {ln}", ln = t.border_line(56)));
505 o.push(String::new());
506
507 let txt = t.text.fg();
508 let sc = t.success.fg();
509 let sec = t.secondary.fg();
510
511 o.push(format!(
512 " {b}{txt}CEP Score{r} {b}{pc}{score:>3}/100{r}",
513 pc = t.pct_color(score as f64),
514 ));
515 o.push(format!(
516 " {b}{txt}Cache Hit Rate{r} {b}{pc}{cache_util}%{r} {d}({cache_hits} hits / {total_reads} reads){r}",
517 pc = t.pct_color(cache_util as f64),
518 ));
519 o.push(format!(
520 " {b}{txt}Mode Diversity{r} {b}{pc}{mode_div}%{r}",
521 pc = t.pct_color(mode_div as f64),
522 ));
523 o.push(format!(
524 " {b}{txt}Compression{r} {b}{pc}{comp_rate}%{r} {d}({} → {}){r}",
525 format_big(tok_orig),
526 format_big(tok_orig.saturating_sub(tok_saved)),
527 pc = t.pct_color(comp_rate as f64),
528 ));
529 o.push(format!(
530 " {b}{txt}Tokens Saved{r} {b}{sc}{}{r} {d}(≈ {}){r}",
531 format_big(tok_saved),
532 usd_estimate(tok_saved),
533 ));
534 o.push(format!(
535 " {b}{txt}Tool Calls{r} {b}{sec}{tool_calls}{r}"
536 ));
537 o.push(format!(" {b}{txt}Complexity{r} {d}{complexity}{r}"));
538 o.push(String::new());
539 o.push(format!(" {ln}", ln = t.border_line(56)));
540 o.push(format!(
541 " {d}This is live data from the current MCP session.{r}"
542 ));
543 o.push(format!(
544 " {d}Historical CEP trends appear after more sessions.{r}"
545 ));
546 o.push(String::new());
547
548 o.join("\n")
549}
550
551fn load_mcp_live() -> Option<serde_json::Value> {
552 let path = dirs::home_dir()?.join(".lean-ctx/mcp-live.json");
553 let content = std::fs::read_to_string(path).ok()?;
554 serde_json::from_str(&content).ok()
555}
556
557pub fn format_cep_report() -> String {
558 let t = active_theme();
559 let store = load();
560 let cep = &store.cep;
561 let live = load_mcp_live();
562 let mut o = Vec::new();
563 let r = theme::rst();
564 let b = theme::bold();
565 let d = theme::dim();
566
567 if cep.sessions == 0 && live.is_none() {
568 return format!(
569 "{d}No CEP sessions recorded yet.{r}\n\
570 Use lean-ctx as an MCP server in your editor to start tracking.\n\
571 CEP metrics are recorded automatically during MCP sessions."
572 );
573 }
574
575 if cep.sessions == 0 {
576 if let Some(ref lv) = live {
577 return format_cep_live(lv, &t);
578 }
579 }
580
581 let total_saved = cep
582 .total_tokens_original
583 .saturating_sub(cep.total_tokens_compressed);
584 let overall_compression = if cep.total_tokens_original > 0 {
585 total_saved as f64 / cep.total_tokens_original as f64 * 100.0
586 } else {
587 0.0
588 };
589 let cache_hit_rate = if cep.total_cache_reads > 0 {
590 cep.total_cache_hits as f64 / cep.total_cache_reads as f64 * 100.0
591 } else {
592 0.0
593 };
594 let avg_score = if !cep.scores.is_empty() {
595 cep.scores.iter().map(|s| s.score as f64).sum::<f64>() / cep.scores.len() as f64
596 } else {
597 0.0
598 };
599 let latest_score = cep.scores.last().map(|s| s.score).unwrap_or(0);
600
601 let shell_saved = store
602 .total_input_tokens
603 .saturating_sub(store.total_output_tokens)
604 .saturating_sub(total_saved);
605 let total_all_saved = store
606 .total_input_tokens
607 .saturating_sub(store.total_output_tokens);
608 let cep_share = if total_all_saved > 0 {
609 total_saved as f64 / total_all_saved as f64 * 100.0
610 } else {
611 0.0
612 };
613
614 let txt = t.text.fg();
615 let sc = t.success.fg();
616 let sec = t.secondary.fg();
617 let wrn = t.warning.fg();
618
619 o.push(String::new());
620 o.push(format!(
621 " {icon} {brand} {cep} {d}Cognitive Efficiency Protocol Report{r}",
622 icon = t.header_icon(),
623 brand = t.brand_title(),
624 cep = t.section_title("CEP"),
625 ));
626 o.push(format!(" {ln}", ln = t.border_line(56)));
627 o.push(String::new());
628
629 o.push(format!(
630 " {b}{txt}CEP Score{r} {b}{pc}{:>3}/100{r} {d}(avg: {avg_score:.0}, latest: {latest_score}){r}",
631 latest_score,
632 pc = t.pct_color(latest_score as f64),
633 ));
634 o.push(format!(
635 " {b}{txt}Sessions{r} {b}{sec}{}{r}",
636 cep.sessions
637 ));
638 o.push(format!(
639 " {b}{txt}Cache Hit Rate{r} {b}{pc}{:.1}%{r} {d}({} hits / {} reads){r}",
640 cache_hit_rate,
641 cep.total_cache_hits,
642 cep.total_cache_reads,
643 pc = t.pct_color(cache_hit_rate),
644 ));
645 o.push(format!(
646 " {b}{txt}MCP Compression{r} {b}{pc}{:.1}%{r} {d}({} → {}){r}",
647 overall_compression,
648 format_big(cep.total_tokens_original),
649 format_big(cep.total_tokens_compressed),
650 pc = t.pct_color(overall_compression),
651 ));
652 o.push(format!(
653 " {b}{txt}Tokens Saved{r} {b}{sc}{}{r} {d}(≈ {}){r}",
654 format_big(total_saved),
655 usd_estimate(total_saved),
656 ));
657 o.push(String::new());
658
659 o.push(format!(" {}", t.section_title("Savings Breakdown")));
660 o.push(format!(" {ln}", ln = t.border_line(56)));
661
662 let bar_w = 30;
663 let shell_ratio = if total_all_saved > 0 {
664 shell_saved as f64 / total_all_saved as f64
665 } else {
666 0.0
667 };
668 let cep_ratio = if total_all_saved > 0 {
669 total_saved as f64 / total_all_saved as f64
670 } else {
671 0.0
672 };
673 let m = t.muted.fg();
674 let shell_bar = theme::pad_right(&t.gradient_bar(shell_ratio, bar_w), bar_w);
675 o.push(format!(
676 " {m}Shell Hook{r} {shell_bar} {b}{:>6}{r} {d}({:.0}%){r}",
677 format_big(shell_saved),
678 (1.0 - cep_share) * 100.0 / 100.0 * 100.0,
679 ));
680 let cep_bar = theme::pad_right(&t.gradient_bar(cep_ratio, bar_w), bar_w);
681 o.push(format!(
682 " {m}MCP/CEP{r} {cep_bar} {b}{:>6}{r} {d}({cep_share:.0}%){r}",
683 format_big(total_saved),
684 ));
685 o.push(String::new());
686
687 if total_saved == 0 && cep.modes.is_empty() {
688 o.push(format!(
689 " {wrn}⚠ MCP server not configured.{r} Shell hook compresses output, but"
690 ));
691 o.push(
692 " full token savings require MCP tools (ctx_read, ctx_shell, ctx_search)."
693 .to_string(),
694 );
695 o.push(format!(
696 " Run {sec}lean-ctx setup{r} to auto-configure your editors."
697 ));
698 o.push(String::new());
699 }
700
701 if !cep.modes.is_empty() {
702 o.push(format!(" {}", t.section_title("Read Modes Used")));
703 o.push(format!(" {ln}", ln = t.border_line(56)));
704
705 let mut sorted_modes: Vec<_> = cep.modes.iter().collect();
706 sorted_modes.sort_by(|a, b2| b2.1.cmp(a.1));
707 let max_mode = *sorted_modes.first().map(|(_, c)| *c).unwrap_or(&1);
708 let max_mode = max_mode.max(1);
709
710 for (mode, count) in &sorted_modes {
711 let ratio = **count as f64 / max_mode as f64;
712 let bar = theme::pad_right(&t.gradient_bar(ratio, 20), 20);
713 o.push(format!(" {sec}{:<14}{r} {:>4}x {bar}", mode, count,));
714 }
715
716 let total_mode_calls: u64 = sorted_modes.iter().map(|(_, c)| **c).sum();
717 let full_count = cep.modes.get("full").copied().unwrap_or(0);
718 let optimized = total_mode_calls.saturating_sub(full_count);
719 let opt_pct = if total_mode_calls > 0 {
720 optimized as f64 / total_mode_calls as f64 * 100.0
721 } else {
722 0.0
723 };
724 o.push(format!(
725 " {d}{optimized}/{total_mode_calls} reads used optimized modes ({opt_pct:.0}% non-full){r}"
726 ));
727 }
728
729 if cep.scores.len() >= 2 {
730 o.push(String::new());
731 o.push(format!(" {}", t.section_title("CEP Score Trend")));
732 o.push(format!(" {ln}", ln = t.border_line(56)));
733
734 let score_values: Vec<u64> = cep.scores.iter().map(|s| s.score as u64).collect();
735 let spark = t.gradient_sparkline(&score_values);
736 o.push(format!(" {spark}"));
737
738 let recent: Vec<_> = cep.scores.iter().rev().take(5).collect();
739 for snap in recent.iter().rev() {
740 let ts = snap.timestamp.get(..16).unwrap_or(&snap.timestamp);
741 let pc = t.pct_color(snap.score as f64);
742 o.push(format!(
743 " {m}{ts}{r} {pc}{b}{:>3}{r}/100 cache:{:>3}% modes:{:>3}% {d}{}{r}",
744 snap.score, snap.cache_hit_rate, snap.mode_diversity, snap.complexity,
745 ));
746 }
747 }
748
749 o.push(String::new());
750 o.push(format!(" {ln}", ln = t.border_line(56)));
751 o.push(format!(" {d}Improve your CEP score:{r}"));
752 if cache_hit_rate < 50.0 {
753 o.push(format!(
754 " {wrn}↑{r} Re-read files with ctx_read to leverage caching"
755 ));
756 }
757 let modes_count = cep.modes.len();
758 if modes_count < 3 {
759 o.push(format!(
760 " {wrn}↑{r} Use map/signatures modes for context-only files"
761 ));
762 }
763 if avg_score >= 70.0 {
764 o.push(format!(
765 " {sc}✓{r} Great score! You're using lean-ctx effectively"
766 ));
767 }
768 o.push(String::new());
769
770 o.join("\n")
771}
772
773pub fn format_gain() -> String {
774 format_gain_themed(&active_theme())
775}
776
777pub fn format_gain_themed(t: &Theme) -> String {
778 let store = load();
779 let mut o = Vec::new();
780 let r = theme::rst();
781 let b = theme::bold();
782 let d = theme::dim();
783
784 if store.total_commands == 0 {
785 return format!(
786 "{d}No commands recorded yet.{r} Use {cmd}lean-ctx -c \"command\"{r} to start tracking.",
787 cmd = t.secondary.fg(),
788 );
789 }
790
791 let input_saved = store
792 .total_input_tokens
793 .saturating_sub(store.total_output_tokens);
794 let pct = if store.total_input_tokens > 0 {
795 input_saved as f64 / store.total_input_tokens as f64 * 100.0
796 } else {
797 0.0
798 };
799 let cost_model = CostModel::default();
800 let cost = cost_model.calculate(&store);
801 let total_saved = input_saved + cost.output_tokens_saved;
802 let days_active = store.daily.len();
803
804 let w = 62;
805 let side = t.box_side();
806
807 let box_line = |content: &str| -> String {
808 let padded = theme::pad_right(content, w);
809 format!(" {side}{padded}{side}")
810 };
811
812 o.push(String::new());
813 o.push(format!(" {}", t.box_top(w)));
814 o.push(box_line(""));
815
816 let header = format!(
817 " {icon} {b}{title}{r} {d}Token Savings Dashboard{r}",
818 icon = t.header_icon(),
819 title = t.brand_title(),
820 );
821 o.push(box_line(&header));
822 o.push(box_line(""));
823 o.push(format!(" {}", t.box_mid(w)));
824 o.push(box_line(""));
825
826 let tok_val = format_big(total_saved);
827 let pct_val = format!("{pct:.1}%");
828 let cmd_val = format_num(store.total_commands);
829 let usd_val = format_usd(cost.total_saved);
830
831 let c1 = t.success.fg();
832 let c2 = t.secondary.fg();
833 let c3 = t.warning.fg();
834 let c4 = t.accent.fg();
835
836 let kw = 14;
837 let v1 = theme::pad_right(&format!("{c1}{b}{tok_val}{r}"), kw);
838 let v2 = theme::pad_right(&format!("{c2}{b}{pct_val}{r}"), kw);
839 let v3 = theme::pad_right(&format!("{c3}{b}{cmd_val}{r}"), kw);
840 let v4 = theme::pad_right(&format!("{c4}{b}{usd_val}{r}"), kw);
841 o.push(box_line(&format!(" {v1}{v2}{v3}{v4}")));
842
843 let l1 = theme::pad_right(&format!("{d}tokens saved{r}"), kw);
844 let l2 = theme::pad_right(&format!("{d}compression{r}"), kw);
845 let l3 = theme::pad_right(&format!("{d}commands{r}"), kw);
846 let l4 = theme::pad_right(&format!("{d}USD saved{r}"), kw);
847 o.push(box_line(&format!(" {l1}{l2}{l3}{l4}")));
848 o.push(box_line(""));
849 o.push(format!(" {}", t.box_bottom(w)));
850
851 o.push(String::new());
852 o.push(String::new());
853
854 let cost_title = t.section_title("Cost Breakdown");
855 o.push(format!(
856 " {cost_title} {d}@ ${}/M input · ${}/M output{r}",
857 DEFAULT_INPUT_PRICE_PER_M, DEFAULT_OUTPUT_PRICE_PER_M,
858 ));
859 o.push(format!(" {ln}", ln = t.border_line(w)));
860 o.push(String::new());
861 let lbl_w = 20;
862 let lbl_without = theme::pad_right(&format!("{m}Without lean-ctx{r}", m = t.muted.fg()), lbl_w);
863 let lbl_with = theme::pad_right(&format!("{m}With lean-ctx{r}", m = t.muted.fg()), lbl_w);
864 let lbl_saved = theme::pad_right(&format!("{c}{b}You saved{r}", c = t.success.fg()), lbl_w);
865
866 o.push(format!(
867 " {lbl_without} {:>8} {d}{} input + {} output{r}",
868 format_usd(cost.total_cost_without),
869 format_usd(cost.input_cost_without),
870 format_usd(cost.output_cost_without),
871 ));
872 o.push(format!(
873 " {lbl_with} {:>8} {d}{} input + {} output{r}",
874 format_usd(cost.total_cost_with),
875 format_usd(cost.input_cost_with),
876 format_usd(cost.output_cost_with),
877 ));
878 o.push(String::new());
879 o.push(format!(
880 " {lbl_saved} {c}{b}{:>8}{r} {d}input {} + output {}{r}",
881 format_usd(cost.total_saved),
882 format_usd(cost.input_cost_without - cost.input_cost_with),
883 format_usd(cost.output_cost_without - cost.output_cost_with),
884 c = t.success.fg(),
885 ));
886
887 o.push(String::new());
888
889 if let (Some(first), Some(_last)) = (&store.first_use, &store.last_use) {
890 let first_short = first.get(..10).unwrap_or(first);
891 let daily_savings: Vec<u64> = store
892 .daily
893 .iter()
894 .map(|d2| day_total_saved(d2, &cost_model))
895 .collect();
896 let spark = t.gradient_sparkline(&daily_savings);
897 o.push(format!(
898 " {d}Since {first_short} · {days_active} day{plural}{r} {spark}",
899 plural = if days_active != 1 { "s" } else { "" }
900 ));
901 o.push(String::new());
902 }
903
904 o.push(String::new());
905
906 if !store.commands.is_empty() {
907 o.push(format!(" {}", t.section_title("Top Commands")));
908 o.push(format!(" {ln}", ln = t.border_line(w)));
909 o.push(String::new());
910
911 let mut sorted: Vec<_> = store.commands.iter().collect();
912 sorted.sort_by(|a, b2| {
913 let sa = cmd_total_saved(a.1, &cost_model);
914 let sb = cmd_total_saved(b2.1, &cost_model);
915 sb.cmp(&sa)
916 });
917
918 let max_cmd_saved = sorted
919 .first()
920 .map(|(_, s)| cmd_total_saved(s, &cost_model))
921 .unwrap_or(1)
922 .max(1);
923
924 for (cmd, stats) in sorted.iter().take(10) {
925 let cmd_saved = cmd_total_saved(stats, &cost_model);
926 let cmd_input_saved = stats.input_tokens.saturating_sub(stats.output_tokens);
927 let cmd_pct = if stats.input_tokens > 0 {
928 cmd_input_saved as f64 / stats.input_tokens as f64 * 100.0
929 } else {
930 0.0
931 };
932 let ratio = cmd_saved as f64 / max_cmd_saved as f64;
933 let bar = theme::pad_right(&t.gradient_bar(ratio, 22), 22);
934 let pc = t.pct_color(cmd_pct);
935 let cmd_col = theme::pad_right(
936 &format!("{m}{}{r}", truncate_cmd(cmd, 16), m = t.muted.fg()),
937 18,
938 );
939 let saved_col = theme::pad_right(&format!("{b}{pc}{}{r}", format_big(cmd_saved)), 8);
940 o.push(format!(
941 " {cmd_col} {:>5}x {bar} {saved_col} {d}{cmd_pct:>3.0}%{r}",
942 stats.count,
943 ));
944 }
945
946 if sorted.len() > 10 {
947 o.push(format!(
948 " {d}... +{} more commands{r}",
949 sorted.len() - 10
950 ));
951 }
952 }
953
954 if store.daily.len() >= 2 {
955 o.push(String::new());
956 o.push(String::new());
957 o.push(format!(" {}", t.section_title("Recent Days")));
958 o.push(format!(" {ln}", ln = t.border_line(w)));
959 o.push(String::new());
960
961 let recent: Vec<_> = store.daily.iter().rev().take(7).collect();
962 for day in recent.iter().rev() {
963 let day_saved = day_total_saved(day, &cost_model);
964 let day_input_saved = day.input_tokens.saturating_sub(day.output_tokens);
965 let day_pct = if day.input_tokens > 0 {
966 day_input_saved as f64 / day.input_tokens as f64 * 100.0
967 } else {
968 0.0
969 };
970 let pc = t.pct_color(day_pct);
971 let date_short = day.date.get(5..).unwrap_or(&day.date);
972 let date_col = theme::pad_right(&format!("{m}{date_short}{r}", m = t.muted.fg()), 7);
973 let saved_col = theme::pad_right(&format!("{pc}{b}{}{r}", format_big(day_saved)), 9);
974 o.push(format!(
975 " {date_col} {:>5} cmds {saved_col} saved {pc}{day_pct:>5.1}%{r}",
976 day.commands,
977 ));
978 }
979 }
980
981 o.push(String::new());
982 o.push(String::new());
983
984 if let Some(tip) = contextual_tip(&store) {
985 o.push(format!(" {w}💡 {tip}{r}", w = t.warning.fg()));
986 o.push(String::new());
987 }
988
989 o.push(String::new());
990 o.push(String::new());
991
992 o.join("\n")
993}
994
995fn contextual_tip(store: &StatsStore) -> Option<String> {
996 let tips = build_tips(store);
997 if tips.is_empty() {
998 return None;
999 }
1000 let seed = std::time::SystemTime::now()
1001 .duration_since(std::time::UNIX_EPOCH)
1002 .unwrap_or_default()
1003 .as_secs()
1004 / 86400;
1005 Some(tips[(seed as usize) % tips.len()].clone())
1006}
1007
1008fn build_tips(store: &StatsStore) -> Vec<String> {
1009 let mut tips = Vec::new();
1010
1011 if store.cep.modes.get("map").copied().unwrap_or(0) == 0 {
1012 tips.push("Try mode=\"map\" for files you only need as context — shows deps + exports, skips implementation.".into());
1013 }
1014
1015 if store.cep.modes.get("signatures").copied().unwrap_or(0) == 0 {
1016 tips.push("Try mode=\"signatures\" for large files — returns only the API surface.".into());
1017 }
1018
1019 if store.cep.total_cache_reads > 0
1020 && store.cep.total_cache_hits as f64 / store.cep.total_cache_reads as f64 > 0.8
1021 {
1022 tips.push(
1023 "High cache hit rate! Use ctx_compress periodically to keep context compact.".into(),
1024 );
1025 }
1026
1027 if store.total_commands > 50 && store.cep.sessions == 0 {
1028 tips.push("Use ctx_session to track your task — enables cross-session memory.".into());
1029 }
1030
1031 if store.cep.modes.get("entropy").copied().unwrap_or(0) == 0 && store.total_commands > 20 {
1032 tips.push("Try mode=\"entropy\" for maximum compression on large files.".into());
1033 }
1034
1035 if store.daily.len() >= 7 {
1036 tips.push("Run lean-ctx gain --graph for a 30-day sparkline chart.".into());
1037 }
1038
1039 tips.push("Run ctx_overview(task) at session start for a task-aware project map.".into());
1040 tips.push("Run lean-ctx dashboard for a live web UI with all your stats.".into());
1041
1042 let cfg = crate::core::config::Config::load();
1043 if cfg.theme == "default" {
1044 tips.push(
1045 "Customize your dashboard! Try: lean-ctx theme set cyberpunk (or neon, ocean, sunset, monochrome)".into(),
1046 );
1047 tips.push(
1048 "Want a unique look? Run lean-ctx theme list to see all available themes.".into(),
1049 );
1050 } else {
1051 tips.push(format!(
1052 "Current theme: {}. Run lean-ctx theme list to explore others.",
1053 cfg.theme
1054 ));
1055 }
1056
1057 tips.push(
1058 "Create your own theme with lean-ctx theme create <name> and set custom colors!".into(),
1059 );
1060
1061 tips
1062}
1063
1064pub fn gain_live() {
1065 use std::io::Write;
1066
1067 let interval = std::time::Duration::from_secs(2);
1068 let mut line_count = 0usize;
1069 let d = theme::dim();
1070 let r = theme::rst();
1071
1072 eprintln!(" {d}▸ Live mode (2s refresh) · Ctrl+C to exit{r}");
1073
1074 loop {
1075 if line_count > 0 {
1076 print!("\x1B[{line_count}A\x1B[J");
1077 }
1078
1079 let output = format_gain();
1080 let footer = format!("\n {d}▸ Live · updates every 2s · Ctrl+C to exit{r}\n");
1081 let full = format!("{output}{footer}");
1082 line_count = full.lines().count();
1083
1084 print!("{full}");
1085 let _ = std::io::stdout().flush();
1086
1087 std::thread::sleep(interval);
1088 }
1089}
1090
1091pub fn format_gain_graph() -> String {
1092 let t = active_theme();
1093 let store = load();
1094 let r = theme::rst();
1095 let b = theme::bold();
1096 let d = theme::dim();
1097
1098 if store.daily.is_empty() {
1099 return format!("{d}No daily data yet.{r} Use lean-ctx for a few days to see the graph.");
1100 }
1101
1102 let cm = CostModel::default();
1103 let days: Vec<_> = store
1104 .daily
1105 .iter()
1106 .rev()
1107 .take(30)
1108 .collect::<Vec<_>>()
1109 .into_iter()
1110 .rev()
1111 .collect();
1112
1113 let savings: Vec<u64> = days.iter().map(|day| day_total_saved(day, &cm)).collect();
1114
1115 let max_saved = *savings.iter().max().unwrap_or(&1);
1116 let max_saved = max_saved.max(1);
1117
1118 let bar_width = 36;
1119 let mut o = Vec::new();
1120
1121 o.push(String::new());
1122 o.push(format!(
1123 " {icon} {title} {d}Token Savings Graph (last 30 days){r}",
1124 icon = t.header_icon(),
1125 title = t.brand_title(),
1126 ));
1127 o.push(format!(" {ln}", ln = t.border_line(58)));
1128 o.push(format!(
1129 " {d}{:>58}{r}",
1130 format!("peak: {}", format_big(max_saved))
1131 ));
1132 o.push(String::new());
1133
1134 for (i, day) in days.iter().enumerate() {
1135 let saved = savings[i];
1136 let ratio = saved as f64 / max_saved as f64;
1137 let bar = theme::pad_right(&t.gradient_bar(ratio, bar_width), bar_width);
1138
1139 let input_saved = day.input_tokens.saturating_sub(day.output_tokens);
1140 let pct = if day.input_tokens > 0 {
1141 input_saved as f64 / day.input_tokens as f64 * 100.0
1142 } else {
1143 0.0
1144 };
1145 let date_short = day.date.get(5..).unwrap_or(&day.date);
1146
1147 o.push(format!(
1148 " {m}{date_short}{r} {brd}│{r} {bar} {b}{:>6}{r} {d}{pct:.0}%{r}",
1149 format_big(saved),
1150 m = t.muted.fg(),
1151 brd = t.border.fg(),
1152 ));
1153 }
1154
1155 let total_saved: u64 = savings.iter().sum();
1156 let total_cmds: u64 = days.iter().map(|day| day.commands).sum();
1157 let spark = t.gradient_sparkline(&savings);
1158
1159 o.push(String::new());
1160 o.push(format!(" {ln}", ln = t.border_line(58)));
1161 o.push(format!(
1162 " {spark} {b}{txt}{}{r} saved across {b}{}{r} commands",
1163 format_big(total_saved),
1164 format_num(total_cmds),
1165 txt = t.text.fg(),
1166 ));
1167 o.push(String::new());
1168
1169 o.join("\n")
1170}
1171
1172pub fn format_gain_daily() -> String {
1173 let t = active_theme();
1174 let store = load();
1175 let r = theme::rst();
1176 let b = theme::bold();
1177 let d = theme::dim();
1178
1179 if store.daily.is_empty() {
1180 return format!("{d}No daily data yet.{r}");
1181 }
1182
1183 let mut o = Vec::new();
1184 let w = 64;
1185
1186 let side = t.box_side();
1187 let daily_box = |content: &str| -> String {
1188 let padded = theme::pad_right(content, w);
1189 format!(" {side}{padded}{side}")
1190 };
1191
1192 o.push(String::new());
1193 o.push(format!(
1194 " {icon} {title} {d}Daily Breakdown{r}",
1195 icon = t.header_icon(),
1196 title = t.brand_title(),
1197 ));
1198 o.push(format!(" {}", t.box_top(w)));
1199 let hdr = format!(
1200 " {b}{txt}{:<12} {:>6} {:>10} {:>10} {:>7} {:>6}{r}",
1201 "Date",
1202 "Cmds",
1203 "Input",
1204 "Saved",
1205 "Rate",
1206 "USD",
1207 txt = t.text.fg(),
1208 );
1209 o.push(daily_box(&hdr));
1210 o.push(format!(" {}", t.box_mid(w)));
1211
1212 let days: Vec<_> = store
1213 .daily
1214 .iter()
1215 .rev()
1216 .take(30)
1217 .collect::<Vec<_>>()
1218 .into_iter()
1219 .rev()
1220 .cloned()
1221 .collect();
1222
1223 let cm = CostModel::default();
1224 for day in &days {
1225 let saved = day_total_saved(day, &cm);
1226 let input_saved = day.input_tokens.saturating_sub(day.output_tokens);
1227 let pct = if day.input_tokens > 0 {
1228 input_saved as f64 / day.input_tokens as f64 * 100.0
1229 } else {
1230 0.0
1231 };
1232 let pc = t.pct_color(pct);
1233 let usd = usd_estimate(saved);
1234 let row = format!(
1235 " {m}{:<12}{r} {:>6} {:>10} {pc}{b}{:>10}{r} {pc}{:>6.1}%{r} {d}{:>6}{r}",
1236 &day.date,
1237 day.commands,
1238 format_big(day.input_tokens),
1239 format_big(saved),
1240 pct,
1241 usd,
1242 m = t.muted.fg(),
1243 );
1244 o.push(daily_box(&row));
1245 }
1246
1247 let total_input: u64 = store.daily.iter().map(|day| day.input_tokens).sum();
1248 let total_saved: u64 = store
1249 .daily
1250 .iter()
1251 .map(|day| day_total_saved(day, &cm))
1252 .sum();
1253 let total_pct = if total_input > 0 {
1254 let input_saved: u64 = store
1255 .daily
1256 .iter()
1257 .map(|day| day.input_tokens.saturating_sub(day.output_tokens))
1258 .sum();
1259 input_saved as f64 / total_input as f64 * 100.0
1260 } else {
1261 0.0
1262 };
1263 let total_usd = usd_estimate(total_saved);
1264 let sc = t.success.fg();
1265
1266 o.push(format!(" {}", t.box_mid(w)));
1267 let total_row = format!(
1268 " {b}{txt}{:<12}{r} {:>6} {:>10} {sc}{b}{:>10}{r} {sc}{b}{:>6.1}%{r} {b}{:>6}{r}",
1269 "TOTAL",
1270 format_num(store.total_commands),
1271 format_big(total_input),
1272 format_big(total_saved),
1273 total_pct,
1274 total_usd,
1275 txt = t.text.fg(),
1276 );
1277 o.push(daily_box(&total_row));
1278 o.push(format!(" {}", t.box_bottom(w)));
1279
1280 let daily_savings: Vec<u64> = days.iter().map(|day| day_total_saved(day, &cm)).collect();
1281 let spark = t.gradient_sparkline(&daily_savings);
1282 o.push(format!(" {d}Trend:{r} {spark}"));
1283 o.push(String::new());
1284
1285 o.join("\n")
1286}
1287
1288pub fn format_gain_json() -> String {
1289 let store = load();
1290 serde_json::to_string_pretty(&store).unwrap_or_else(|_| "{}".to_string())
1291}