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 crate::core::data_dir::lean_ctx_data_dir().ok()
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 write_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
103fn merge_and_save(current: &StatsStore, baseline: &StatsStore) -> StatsStore {
104 let dir = match stats_dir() {
105 Some(d) => d,
106 None => {
107 let disk = load_from_disk();
108 return apply_deltas(&disk, current, baseline);
109 }
110 };
111
112 let lock_path = dir.join(".stats.lock");
113 let _lock = acquire_file_lock(&lock_path);
114
115 let disk = load_from_disk();
116 let merged = apply_deltas(&disk, current, baseline);
117 write_to_disk(&merged);
118 merged
119}
120
121struct FileLockGuard(PathBuf);
122
123impl Drop for FileLockGuard {
124 fn drop(&mut self) {
125 let _ = std::fs::remove_file(&self.0);
126 }
127}
128
129fn acquire_file_lock(lock_path: &std::path::Path) -> Option<FileLockGuard> {
130 for _ in 0..20 {
131 match std::fs::OpenOptions::new()
132 .create_new(true)
133 .write(true)
134 .open(lock_path)
135 {
136 Ok(_) => return Some(FileLockGuard(lock_path.to_path_buf())),
137 Err(_) => {
138 if let Ok(meta) = std::fs::metadata(lock_path) {
139 if let Ok(modified) = meta.modified() {
140 if modified.elapsed().unwrap_or_default().as_secs() > 5 {
141 let _ = std::fs::remove_file(lock_path);
142 continue;
143 }
144 }
145 }
146 std::thread::sleep(std::time::Duration::from_millis(5));
147 }
148 }
149 }
150 None
151}
152
153fn apply_deltas(disk: &StatsStore, current: &StatsStore, baseline: &StatsStore) -> StatsStore {
154 let mut merged = disk.clone();
155
156 let delta_commands = current
157 .total_commands
158 .saturating_sub(baseline.total_commands);
159 let delta_input = current
160 .total_input_tokens
161 .saturating_sub(baseline.total_input_tokens);
162 let delta_output = current
163 .total_output_tokens
164 .saturating_sub(baseline.total_output_tokens);
165
166 merged.total_commands += delta_commands;
167 merged.total_input_tokens += delta_input;
168 merged.total_output_tokens += delta_output;
169
170 for (cmd, stats) in ¤t.commands {
171 let base = baseline.commands.get(cmd);
172 let dc = stats.count.saturating_sub(base.map_or(0, |b| b.count));
173 let di = stats
174 .input_tokens
175 .saturating_sub(base.map_or(0, |b| b.input_tokens));
176 let do_ = stats
177 .output_tokens
178 .saturating_sub(base.map_or(0, |b| b.output_tokens));
179 if dc > 0 || di > 0 || do_ > 0 {
180 let entry = merged.commands.entry(cmd.clone()).or_default();
181 entry.count += dc;
182 entry.input_tokens += di;
183 entry.output_tokens += do_;
184 }
185 }
186
187 merge_daily(&mut merged.daily, ¤t.daily, &baseline.daily);
188
189 if let Some(ref ts) = current.last_use {
190 match merged.last_use {
191 Some(ref existing) if existing >= ts => {}
192 _ => merged.last_use = Some(ts.clone()),
193 }
194 }
195 if merged.first_use.is_none() {
196 merged.first_use = current.first_use.clone();
197 } else if let Some(ref cur_first) = current.first_use {
198 if let Some(ref merged_first) = merged.first_use {
199 if cur_first < merged_first {
200 merged.first_use = Some(cur_first.clone());
201 }
202 }
203 }
204
205 merge_cep(&mut merged.cep, ¤t.cep, &baseline.cep);
206
207 merged
208}
209
210fn merge_daily(merged: &mut Vec<DayStats>, current: &[DayStats], baseline: &[DayStats]) {
211 let base_map: HashMap<String, &DayStats> =
212 baseline.iter().map(|d| (d.date.clone(), d)).collect();
213
214 for day in current {
215 let base = base_map.get(&day.date);
216 let dc = day.commands.saturating_sub(base.map_or(0, |b| b.commands));
217 let di = day
218 .input_tokens
219 .saturating_sub(base.map_or(0, |b| b.input_tokens));
220 let do_ = day
221 .output_tokens
222 .saturating_sub(base.map_or(0, |b| b.output_tokens));
223 if dc == 0 && di == 0 && do_ == 0 {
224 continue;
225 }
226 if let Some(existing) = merged.iter_mut().find(|d| d.date == day.date) {
227 existing.commands += dc;
228 existing.input_tokens += di;
229 existing.output_tokens += do_;
230 } else {
231 merged.push(DayStats {
232 date: day.date.clone(),
233 commands: dc,
234 input_tokens: di,
235 output_tokens: do_,
236 });
237 }
238 }
239
240 if merged.len() > 90 {
241 merged.sort_by(|a, b| a.date.cmp(&b.date));
242 merged.drain(..merged.len() - 90);
243 }
244}
245
246fn merge_cep(merged: &mut CepStats, current: &CepStats, baseline: &CepStats) {
247 merged.sessions += current.sessions.saturating_sub(baseline.sessions);
248 merged.total_cache_hits += current
249 .total_cache_hits
250 .saturating_sub(baseline.total_cache_hits);
251 merged.total_cache_reads += current
252 .total_cache_reads
253 .saturating_sub(baseline.total_cache_reads);
254 merged.total_tokens_original += current
255 .total_tokens_original
256 .saturating_sub(baseline.total_tokens_original);
257 merged.total_tokens_compressed += current
258 .total_tokens_compressed
259 .saturating_sub(baseline.total_tokens_compressed);
260
261 for (mode, count) in ¤t.modes {
262 let base_count = baseline.modes.get(mode).copied().unwrap_or(0);
263 let delta = count.saturating_sub(base_count);
264 if delta > 0 {
265 *merged.modes.entry(mode.clone()).or_insert(0) += delta;
266 }
267 }
268
269 let base_scores_len = baseline.scores.len();
270 if current.scores.len() > base_scores_len {
271 for snapshot in ¤t.scores[base_scores_len..] {
272 merged.scores.push(snapshot.clone());
273 }
274 }
275 if merged.scores.len() > 100 {
276 merged.scores.drain(..merged.scores.len() - 100);
277 }
278
279 if current.last_session_pid.is_some() {
280 merged.last_session_pid = current.last_session_pid;
281 merged.last_session_original = current.last_session_original;
282 merged.last_session_compressed = current.last_session_compressed;
283 }
284}
285
286pub fn load() -> StatsStore {
287 let guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
288 if let Some((ref current, ref baseline, _)) = *guard {
289 let disk = load_from_disk();
290 return apply_deltas(&disk, current, baseline);
291 }
292 drop(guard);
293 load_from_disk()
294}
295
296pub fn save(store: &StatsStore) {
297 write_to_disk(store);
298}
299
300const FLUSH_INTERVAL_SECS: u64 = 30;
301
302static STATS_BUFFER: Mutex<Option<(StatsStore, StatsStore, Instant)>> = Mutex::new(None);
304
305fn maybe_flush(store: &mut StatsStore, baseline: &mut StatsStore, last_flush: &mut Instant) {
306 if last_flush.elapsed().as_secs() >= FLUSH_INTERVAL_SECS {
307 let merged = merge_and_save(store, baseline);
308 *store = merged.clone();
309 *baseline = merged;
310 *last_flush = Instant::now();
311 }
312}
313
314pub fn flush() {
315 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
316 if let Some((ref mut store, ref mut baseline, ref mut last_flush)) = *guard {
317 let merged = merge_and_save(store, baseline);
318 *store = merged.clone();
319 *baseline = merged;
320 *last_flush = Instant::now();
321 }
322}
323
324pub fn record(command: &str, input_tokens: usize, output_tokens: usize) {
325 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
326 if guard.is_none() {
327 let disk = load_from_disk();
328 *guard = Some((disk.clone(), disk, Instant::now()));
329 }
330 let (store, baseline, last_flush) = guard.as_mut().unwrap();
331
332 let is_first_command = store.total_commands == baseline.total_commands;
333 let now = chrono::Local::now();
334 let today = now.format("%Y-%m-%d").to_string();
335 let timestamp = now.to_rfc3339();
336
337 store.total_commands += 1;
338 store.total_input_tokens += input_tokens as u64;
339 store.total_output_tokens += output_tokens as u64;
340
341 if store.first_use.is_none() {
342 store.first_use = Some(timestamp.clone());
343 }
344 store.last_use = Some(timestamp);
345
346 let cmd_key = normalize_command(command);
347 let entry = store.commands.entry(cmd_key).or_default();
348 entry.count += 1;
349 entry.input_tokens += input_tokens as u64;
350 entry.output_tokens += output_tokens as u64;
351
352 if let Some(day) = store.daily.last_mut() {
353 if day.date == today {
354 day.commands += 1;
355 day.input_tokens += input_tokens as u64;
356 day.output_tokens += output_tokens as u64;
357 } else {
358 store.daily.push(DayStats {
359 date: today,
360 commands: 1,
361 input_tokens: input_tokens as u64,
362 output_tokens: output_tokens as u64,
363 });
364 }
365 } else {
366 store.daily.push(DayStats {
367 date: today,
368 commands: 1,
369 input_tokens: input_tokens as u64,
370 output_tokens: output_tokens as u64,
371 });
372 }
373
374 if store.daily.len() > 90 {
375 store.daily.drain(..store.daily.len() - 90);
376 }
377
378 if is_first_command {
379 let merged = merge_and_save(store, baseline);
380 *store = merged.clone();
381 *baseline = merged;
382 *last_flush = Instant::now();
383 } else {
384 maybe_flush(store, baseline, last_flush);
385 }
386}
387
388fn normalize_command(command: &str) -> String {
389 let parts: Vec<&str> = command.split_whitespace().collect();
390 if parts.is_empty() {
391 return command.to_string();
392 }
393
394 let base = std::path::Path::new(parts[0])
395 .file_name()
396 .and_then(|n| n.to_str())
397 .unwrap_or(parts[0]);
398
399 match base {
400 "git" => {
401 if parts.len() > 1 {
402 format!("git {}", parts[1])
403 } else {
404 "git".to_string()
405 }
406 }
407 "cargo" => {
408 if parts.len() > 1 {
409 format!("cargo {}", parts[1])
410 } else {
411 "cargo".to_string()
412 }
413 }
414 "npm" | "yarn" | "pnpm" => {
415 if parts.len() > 1 {
416 format!("{} {}", base, parts[1])
417 } else {
418 base.to_string()
419 }
420 }
421 "docker" => {
422 if parts.len() > 1 {
423 format!("docker {}", parts[1])
424 } else {
425 "docker".to_string()
426 }
427 }
428 _ => base.to_string(),
429 }
430}
431
432pub fn reset_cep() {
433 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
434 let mut store = load_from_disk();
435 store.cep = CepStats::default();
436 write_to_disk(&store);
437 *guard = Some((store.clone(), store, Instant::now()));
438}
439
440pub fn reset_all() {
441 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
442 let store = StatsStore::default();
443 write_to_disk(&store);
444 *guard = Some((store.clone(), store, Instant::now()));
445}
446
447pub struct GainSummary {
448 pub total_saved: u64,
449 pub total_calls: u64,
450}
451
452pub fn load_stats() -> GainSummary {
453 let store = load();
454 let input_saved = store
455 .total_input_tokens
456 .saturating_sub(store.total_output_tokens);
457 GainSummary {
458 total_saved: input_saved,
459 total_calls: store.total_commands,
460 }
461}
462
463fn cmd_total_saved(s: &CommandStats, _cm: &CostModel) -> u64 {
464 s.input_tokens.saturating_sub(s.output_tokens)
465}
466
467fn day_total_saved(d: &DayStats, _cm: &CostModel) -> u64 {
468 d.input_tokens.saturating_sub(d.output_tokens)
469}
470
471#[allow(clippy::too_many_arguments)]
472pub fn record_cep_session(
473 score: u32,
474 cache_hits: u64,
475 cache_reads: u64,
476 tokens_original: u64,
477 tokens_compressed: u64,
478 modes: &HashMap<String, u64>,
479 tool_calls: u64,
480 complexity: &str,
481) {
482 let mut guard = STATS_BUFFER.lock().unwrap_or_else(|e| e.into_inner());
483 if guard.is_none() {
484 let disk = load_from_disk();
485 *guard = Some((disk.clone(), disk, Instant::now()));
486 }
487 let (store, baseline, last_flush) = guard.as_mut().unwrap();
488
489 let cep = &mut store.cep;
490
491 let pid = std::process::id();
492 let prev_original = cep.last_session_original.unwrap_or(0);
493 let prev_compressed = cep.last_session_compressed.unwrap_or(0);
494 let is_same_session = cep.last_session_pid == Some(pid);
495
496 if is_same_session {
497 let delta_original = tokens_original.saturating_sub(prev_original);
498 let delta_compressed = tokens_compressed.saturating_sub(prev_compressed);
499 cep.total_tokens_original += delta_original;
500 cep.total_tokens_compressed += delta_compressed;
501 } else {
502 cep.sessions += 1;
503 cep.total_cache_hits += cache_hits;
504 cep.total_cache_reads += cache_reads;
505 cep.total_tokens_original += tokens_original;
506 cep.total_tokens_compressed += tokens_compressed;
507
508 for (mode, count) in modes {
509 *cep.modes.entry(mode.clone()).or_insert(0) += count;
510 }
511 }
512
513 cep.last_session_pid = Some(pid);
514 cep.last_session_original = Some(tokens_original);
515 cep.last_session_compressed = Some(tokens_compressed);
516
517 let cache_hit_rate = if cache_reads > 0 {
518 (cache_hits as f64 / cache_reads as f64 * 100.0).round() as u32
519 } else {
520 0
521 };
522
523 let compression_rate = if tokens_original > 0 {
524 ((tokens_original - tokens_compressed) as f64 / tokens_original as f64 * 100.0).round()
525 as u32
526 } else {
527 0
528 };
529
530 let total_modes = 6u32;
531 let mode_diversity =
532 ((modes.len() as f64 / total_modes as f64).min(1.0) * 100.0).round() as u32;
533
534 let tokens_saved = tokens_original.saturating_sub(tokens_compressed);
535
536 cep.scores.push(CepSessionSnapshot {
537 timestamp: chrono::Local::now().to_rfc3339(),
538 score,
539 cache_hit_rate,
540 mode_diversity,
541 compression_rate,
542 tool_calls,
543 tokens_saved,
544 complexity: complexity.to_string(),
545 });
546
547 if cep.scores.len() > 100 {
548 cep.scores.drain(..cep.scores.len() - 100);
549 }
550
551 maybe_flush(store, baseline, last_flush);
552}
553
554use super::theme::{self, Theme};
555
556fn active_theme() -> Theme {
557 let cfg = super::config::Config::load();
558 theme::load_theme(&cfg.theme)
559}
560
561pub const DEFAULT_INPUT_PRICE_PER_M: f64 = 2.50;
563pub const DEFAULT_OUTPUT_PRICE_PER_M: f64 = 10.0;
564
565pub struct CostModel {
566 pub input_price_per_m: f64,
567 pub output_price_per_m: f64,
568 pub avg_verbose_output_per_call: u64,
569 pub avg_concise_output_per_call: u64,
570}
571
572impl Default for CostModel {
573 fn default() -> Self {
574 let env_model = std::env::var("LEAN_CTX_MODEL")
575 .or_else(|_| std::env::var("LCTX_MODEL"))
576 .ok();
577 let pricing = crate::core::gain::model_pricing::ModelPricing::load();
578 let quote = pricing.quote(env_model.as_deref());
579 Self {
580 input_price_per_m: quote.cost.input_per_m,
581 output_price_per_m: quote.cost.output_per_m,
582 avg_verbose_output_per_call: 180,
583 avg_concise_output_per_call: 120,
584 }
585 }
586}
587
588pub struct CostBreakdown {
589 pub input_cost_without: f64,
590 pub input_cost_with: f64,
591 pub output_cost_without: f64,
592 pub output_cost_with: f64,
593 pub total_cost_without: f64,
594 pub total_cost_with: f64,
595 pub total_saved: f64,
596 pub estimated_output_tokens_without: u64,
597 pub estimated_output_tokens_with: u64,
598 pub output_tokens_saved: u64,
599}
600
601impl CostModel {
602 pub fn calculate(&self, store: &StatsStore) -> CostBreakdown {
603 let input_cost_without =
604 store.total_input_tokens as f64 / 1_000_000.0 * self.input_price_per_m;
605 let input_cost_with =
606 store.total_output_tokens as f64 / 1_000_000.0 * self.input_price_per_m;
607
608 let input_saved = store
609 .total_input_tokens
610 .saturating_sub(store.total_output_tokens);
611 let compression_rate = if store.total_input_tokens > 0 {
612 input_saved as f64 / store.total_input_tokens as f64
613 } else {
614 0.0
615 };
616 let est_output_without = store.total_commands * self.avg_verbose_output_per_call;
617 let est_output_with = if compression_rate > 0.01 {
618 store.total_commands * self.avg_concise_output_per_call
619 } else {
620 est_output_without
621 };
622 let output_saved = est_output_without.saturating_sub(est_output_with);
623
624 let output_cost_without = est_output_without as f64 / 1_000_000.0 * self.output_price_per_m;
625 let output_cost_with = est_output_with as f64 / 1_000_000.0 * self.output_price_per_m;
626
627 let total_without = input_cost_without + output_cost_without;
628 let total_with = input_cost_with + output_cost_with;
629
630 CostBreakdown {
631 input_cost_without,
632 input_cost_with,
633 output_cost_without,
634 output_cost_with,
635 total_cost_without: total_without,
636 total_cost_with: total_with,
637 total_saved: total_without - total_with,
638 estimated_output_tokens_without: est_output_without,
639 estimated_output_tokens_with: est_output_with,
640 output_tokens_saved: output_saved,
641 }
642 }
643}
644
645fn format_usd(amount: f64) -> String {
646 if amount >= 0.01 {
647 format!("${amount:.2}")
648 } else {
649 format!("${amount:.3}")
650 }
651}
652
653fn usd_estimate(tokens: u64) -> String {
654 let env_model = std::env::var("LEAN_CTX_MODEL")
655 .or_else(|_| std::env::var("LCTX_MODEL"))
656 .ok();
657 let pricing = crate::core::gain::model_pricing::ModelPricing::load();
658 let quote = pricing.quote(env_model.as_deref());
659 let cost = tokens as f64 * quote.cost.input_per_m / 1_000_000.0;
660 format_usd(cost)
661}
662
663fn format_big(n: u64) -> String {
664 if n >= 1_000_000 {
665 format!("{:.1}M", n as f64 / 1_000_000.0)
666 } else if n >= 1_000 {
667 format!("{:.1}K", n as f64 / 1_000.0)
668 } else {
669 format!("{n}")
670 }
671}
672
673fn format_num(n: u64) -> String {
674 if n >= 1_000_000 {
675 format!("{:.1}M", n as f64 / 1_000_000.0)
676 } else if n >= 1_000 {
677 format!("{},{:03}", n / 1_000, n % 1_000)
678 } else {
679 format!("{n}")
680 }
681}
682
683fn truncate_cmd(cmd: &str, max: usize) -> String {
684 if cmd.len() <= max {
685 cmd.to_string()
686 } else {
687 format!("{}…", &cmd[..max - 1])
688 }
689}
690
691fn format_cep_live(lv: &serde_json::Value, t: &Theme) -> String {
692 let mut o = Vec::new();
693 let r = theme::rst();
694 let b = theme::bold();
695 let d = theme::dim();
696
697 let score = lv["cep_score"].as_u64().unwrap_or(0) as u32;
698 let cache_util = lv["cache_utilization"].as_u64().unwrap_or(0);
699 let mode_div = lv["mode_diversity"].as_u64().unwrap_or(0);
700 let comp_rate = lv["compression_rate"].as_u64().unwrap_or(0);
701 let tok_saved = lv["tokens_saved"].as_u64().unwrap_or(0);
702 let tok_orig = lv["tokens_original"].as_u64().unwrap_or(0);
703 let tool_calls = lv["tool_calls"].as_u64().unwrap_or(0);
704 let cache_hits = lv["cache_hits"].as_u64().unwrap_or(0);
705 let total_reads = lv["total_reads"].as_u64().unwrap_or(0);
706 let complexity = lv["task_complexity"].as_str().unwrap_or("Standard");
707
708 o.push(String::new());
709 o.push(format!(
710 " {icon} {brand} {cep} {d}Live Session (no historical data yet){r}",
711 icon = t.header_icon(),
712 brand = t.brand_title(),
713 cep = t.section_title("CEP"),
714 ));
715 o.push(format!(" {ln}", ln = t.border_line(56)));
716 o.push(String::new());
717
718 let txt = t.text.fg();
719 let sc = t.success.fg();
720 let sec = t.secondary.fg();
721
722 o.push(format!(
723 " {b}{txt}CEP Score{r} {b}{pc}{score:>3}/100{r}",
724 pc = t.pct_color(score as f64),
725 ));
726 o.push(format!(
727 " {b}{txt}Cache Hit Rate{r} {b}{pc}{cache_util}%{r} {d}({cache_hits} hits / {total_reads} reads){r}",
728 pc = t.pct_color(cache_util as f64),
729 ));
730 o.push(format!(
731 " {b}{txt}Mode Diversity{r} {b}{pc}{mode_div}%{r}",
732 pc = t.pct_color(mode_div as f64),
733 ));
734 o.push(format!(
735 " {b}{txt}Compression{r} {b}{pc}{comp_rate}%{r} {d}({} → {}){r}",
736 format_big(tok_orig),
737 format_big(tok_orig.saturating_sub(tok_saved)),
738 pc = t.pct_color(comp_rate as f64),
739 ));
740 o.push(format!(
741 " {b}{txt}Tokens Saved{r} {b}{sc}{}{r} {d}(≈ {}){r}",
742 format_big(tok_saved),
743 usd_estimate(tok_saved),
744 ));
745 o.push(format!(
746 " {b}{txt}Tool Calls{r} {b}{sec}{tool_calls}{r}"
747 ));
748 o.push(format!(" {b}{txt}Complexity{r} {d}{complexity}{r}"));
749 o.push(String::new());
750 o.push(format!(" {ln}", ln = t.border_line(56)));
751 o.push(format!(
752 " {d}This is live data from the current MCP session.{r}"
753 ));
754 o.push(format!(
755 " {d}Historical CEP trends appear after more sessions.{r}"
756 ));
757 o.push(String::new());
758
759 o.join("\n")
760}
761
762fn load_mcp_live() -> Option<serde_json::Value> {
763 let path = dirs::home_dir()?.join(".lean-ctx/mcp-live.json");
764 let content = std::fs::read_to_string(path).ok()?;
765 serde_json::from_str(&content).ok()
766}
767
768pub fn format_cep_report() -> String {
769 let t = active_theme();
770 let store = load();
771 let cep = &store.cep;
772 let live = load_mcp_live();
773 let mut o = Vec::new();
774 let r = theme::rst();
775 let b = theme::bold();
776 let d = theme::dim();
777
778 if cep.sessions == 0 && live.is_none() {
779 return format!(
780 "{d}No CEP sessions recorded yet.{r}\n\
781 Use lean-ctx as an MCP server in your editor to start tracking.\n\
782 CEP metrics are recorded automatically during MCP sessions."
783 );
784 }
785
786 if cep.sessions == 0 {
787 if let Some(ref lv) = live {
788 return format_cep_live(lv, &t);
789 }
790 }
791
792 let total_saved = cep
793 .total_tokens_original
794 .saturating_sub(cep.total_tokens_compressed);
795 let overall_compression = if cep.total_tokens_original > 0 {
796 total_saved as f64 / cep.total_tokens_original as f64 * 100.0
797 } else {
798 0.0
799 };
800 let cache_hit_rate = if cep.total_cache_reads > 0 {
801 cep.total_cache_hits as f64 / cep.total_cache_reads as f64 * 100.0
802 } else {
803 0.0
804 };
805 let avg_score = if !cep.scores.is_empty() {
806 cep.scores.iter().map(|s| s.score as f64).sum::<f64>() / cep.scores.len() as f64
807 } else {
808 0.0
809 };
810 let latest_score = cep.scores.last().map(|s| s.score).unwrap_or(0);
811
812 let shell_saved = store
813 .total_input_tokens
814 .saturating_sub(store.total_output_tokens)
815 .saturating_sub(total_saved);
816 let total_all_saved = store
817 .total_input_tokens
818 .saturating_sub(store.total_output_tokens);
819 let cep_share = if total_all_saved > 0 {
820 total_saved as f64 / total_all_saved as f64 * 100.0
821 } else {
822 0.0
823 };
824
825 let txt = t.text.fg();
826 let sc = t.success.fg();
827 let sec = t.secondary.fg();
828 let wrn = t.warning.fg();
829
830 o.push(String::new());
831 o.push(format!(
832 " {icon} {brand} {cep} {d}Cognitive Efficiency Protocol Report{r}",
833 icon = t.header_icon(),
834 brand = t.brand_title(),
835 cep = t.section_title("CEP"),
836 ));
837 o.push(format!(" {ln}", ln = t.border_line(56)));
838 o.push(String::new());
839
840 o.push(format!(
841 " {b}{txt}CEP Score{r} {b}{pc}{:>3}/100{r} {d}(avg: {avg_score:.0}, latest: {latest_score}){r}",
842 latest_score,
843 pc = t.pct_color(latest_score as f64),
844 ));
845 o.push(format!(
846 " {b}{txt}Sessions{r} {b}{sec}{}{r}",
847 cep.sessions
848 ));
849 o.push(format!(
850 " {b}{txt}Cache Hit Rate{r} {b}{pc}{:.1}%{r} {d}({} hits / {} reads){r}",
851 cache_hit_rate,
852 cep.total_cache_hits,
853 cep.total_cache_reads,
854 pc = t.pct_color(cache_hit_rate),
855 ));
856 o.push(format!(
857 " {b}{txt}MCP Compression{r} {b}{pc}{:.1}%{r} {d}({} → {}){r}",
858 overall_compression,
859 format_big(cep.total_tokens_original),
860 format_big(cep.total_tokens_compressed),
861 pc = t.pct_color(overall_compression),
862 ));
863 o.push(format!(
864 " {b}{txt}Tokens Saved{r} {b}{sc}{}{r} {d}(≈ {}){r}",
865 format_big(total_saved),
866 usd_estimate(total_saved),
867 ));
868 o.push(String::new());
869
870 o.push(format!(" {}", t.section_title("Savings Breakdown")));
871 o.push(format!(" {ln}", ln = t.border_line(56)));
872
873 let bar_w = 30;
874 let shell_ratio = if total_all_saved > 0 {
875 shell_saved as f64 / total_all_saved as f64
876 } else {
877 0.0
878 };
879 let cep_ratio = if total_all_saved > 0 {
880 total_saved as f64 / total_all_saved as f64
881 } else {
882 0.0
883 };
884 let m = t.muted.fg();
885 let shell_bar = theme::pad_right(&t.gradient_bar(shell_ratio, bar_w), bar_w);
886 o.push(format!(
887 " {m}Shell Hook{r} {shell_bar} {b}{:>6}{r} {d}({:.0}%){r}",
888 format_big(shell_saved),
889 (1.0 - cep_share) * 100.0 / 100.0 * 100.0,
890 ));
891 let cep_bar = theme::pad_right(&t.gradient_bar(cep_ratio, bar_w), bar_w);
892 o.push(format!(
893 " {m}MCP/CEP{r} {cep_bar} {b}{:>6}{r} {d}({cep_share:.0}%){r}",
894 format_big(total_saved),
895 ));
896 o.push(String::new());
897
898 if total_saved == 0 && cep.modes.is_empty() {
899 if store.total_commands > 20 {
900 o.push(format!(
901 " {wrn}⚠ MCP tools configured but not being used by your AI client.{r}"
902 ));
903 o.push(
904 " Your AI client may be using native Read/Shell instead of ctx_read/ctx_shell."
905 .to_string(),
906 );
907 o.push(format!(
908 " Run {sec}lean-ctx init{r} to update rules, then restart your AI session."
909 ));
910 o.push(format!(
911 " Run {sec}lean-ctx doctor{r} for detailed adoption diagnostics."
912 ));
913 } else {
914 o.push(format!(
915 " {wrn}⚠ MCP server not configured.{r} Shell hook compresses output, but"
916 ));
917 o.push(
918 " full token savings require MCP tools (ctx_read, ctx_shell, ctx_search)."
919 .to_string(),
920 );
921 o.push(format!(
922 " Run {sec}lean-ctx setup{r} to auto-configure your editors."
923 ));
924 }
925 o.push(String::new());
926 }
927
928 if !cep.modes.is_empty() {
929 o.push(format!(" {}", t.section_title("Read Modes Used")));
930 o.push(format!(" {ln}", ln = t.border_line(56)));
931
932 let mut sorted_modes: Vec<_> = cep.modes.iter().collect();
933 sorted_modes.sort_by(|a, b2| b2.1.cmp(a.1));
934 let max_mode = *sorted_modes.first().map(|(_, c)| *c).unwrap_or(&1);
935 let max_mode = max_mode.max(1);
936
937 for (mode, count) in &sorted_modes {
938 let ratio = **count as f64 / max_mode as f64;
939 let bar = theme::pad_right(&t.gradient_bar(ratio, 20), 20);
940 o.push(format!(" {sec}{:<14}{r} {:>4}x {bar}", mode, count,));
941 }
942
943 let total_mode_calls: u64 = sorted_modes.iter().map(|(_, c)| **c).sum();
944 let full_count = cep.modes.get("full").copied().unwrap_or(0);
945 let optimized = total_mode_calls.saturating_sub(full_count);
946 let opt_pct = if total_mode_calls > 0 {
947 optimized as f64 / total_mode_calls as f64 * 100.0
948 } else {
949 0.0
950 };
951 o.push(format!(
952 " {d}{optimized}/{total_mode_calls} reads used optimized modes ({opt_pct:.0}% non-full){r}"
953 ));
954 }
955
956 if cep.scores.len() >= 2 {
957 o.push(String::new());
958 o.push(format!(" {}", t.section_title("CEP Score Trend")));
959 o.push(format!(" {ln}", ln = t.border_line(56)));
960
961 let score_values: Vec<u64> = cep.scores.iter().map(|s| s.score as u64).collect();
962 let spark = t.gradient_sparkline(&score_values);
963 o.push(format!(" {spark}"));
964
965 let recent: Vec<_> = cep.scores.iter().rev().take(5).collect();
966 for snap in recent.iter().rev() {
967 let ts = snap.timestamp.get(..16).unwrap_or(&snap.timestamp);
968 let pc = t.pct_color(snap.score as f64);
969 o.push(format!(
970 " {m}{ts}{r} {pc}{b}{:>3}{r}/100 cache:{:>3}% modes:{:>3}% {d}{}{r}",
971 snap.score, snap.cache_hit_rate, snap.mode_diversity, snap.complexity,
972 ));
973 }
974 }
975
976 o.push(String::new());
977 o.push(format!(" {ln}", ln = t.border_line(56)));
978 o.push(format!(" {d}Improve your CEP score:{r}"));
979 if cache_hit_rate < 50.0 {
980 o.push(format!(
981 " {wrn}↑{r} Re-read files with ctx_read to leverage caching"
982 ));
983 }
984 let modes_count = cep.modes.len();
985 if modes_count < 3 {
986 o.push(format!(
987 " {wrn}↑{r} Use map/signatures modes for context-only files"
988 ));
989 }
990 if avg_score >= 70.0 {
991 o.push(format!(
992 " {sc}✓{r} Great score! You're using lean-ctx effectively"
993 ));
994 }
995 o.push(String::new());
996
997 o.join("\n")
998}
999
1000pub fn format_gain() -> String {
1001 format_gain_themed(&active_theme())
1002}
1003
1004pub fn format_gain_themed(t: &Theme) -> String {
1005 format_gain_themed_at(t, None)
1006}
1007
1008pub fn format_gain_themed_at(t: &Theme, tick: Option<u64>) -> String {
1009 let store = load();
1010 let mut o = Vec::new();
1011 let r = theme::rst();
1012 let b = theme::bold();
1013 let d = theme::dim();
1014
1015 if store.total_commands == 0 {
1016 return format!(
1017 "{d}No commands recorded yet.{r} Use {cmd}lean-ctx -c \"command\"{r} to start tracking.",
1018 cmd = t.secondary.fg(),
1019 );
1020 }
1021
1022 let input_saved = store
1023 .total_input_tokens
1024 .saturating_sub(store.total_output_tokens);
1025 let pct = if store.total_input_tokens > 0 {
1026 input_saved as f64 / store.total_input_tokens as f64 * 100.0
1027 } else {
1028 0.0
1029 };
1030 let cost_model = CostModel::default();
1031 let cost = cost_model.calculate(&store);
1032 let total_saved = input_saved;
1033 let days_active = store.daily.len();
1034
1035 let w = 62;
1036 let side = t.box_side();
1037
1038 let box_line = |content: &str| -> String {
1039 let padded = theme::pad_right(content, w);
1040 format!(" {side}{padded}{side}")
1041 };
1042
1043 o.push(String::new());
1044 o.push(format!(" {}", t.box_top(w)));
1045 o.push(box_line(""));
1046
1047 let header = format!(
1048 " {icon} {b}{title}{r} {d}Token Savings Dashboard{r}",
1049 icon = t.header_icon(),
1050 title = t.brand_title(),
1051 );
1052 o.push(box_line(&header));
1053 o.push(box_line(""));
1054 o.push(format!(" {}", t.box_mid(w)));
1055 o.push(box_line(""));
1056
1057 let tok_val = format_big(total_saved);
1058 let pct_val = format!("{pct:.1}%");
1059 let cmd_val = format_num(store.total_commands);
1060 let usd_val = format_usd(cost.total_saved);
1061
1062 let c1 = t.success.fg();
1063 let c2 = t.secondary.fg();
1064 let c3 = t.warning.fg();
1065 let c4 = t.accent.fg();
1066
1067 let kw = 14;
1068 let v1 = theme::pad_right(&format!("{c1}{b}{tok_val}{r}"), kw);
1069 let v2 = theme::pad_right(&format!("{c2}{b}{pct_val}{r}"), kw);
1070 let v3 = theme::pad_right(&format!("{c3}{b}{cmd_val}{r}"), kw);
1071 let v4 = theme::pad_right(&format!("{c4}{b}{usd_val}{r}"), kw);
1072 o.push(box_line(&format!(" {v1}{v2}{v3}{v4}")));
1073
1074 let l1 = theme::pad_right(&format!("{d}tokens saved{r}"), kw);
1075 let l2 = theme::pad_right(&format!("{d}compression{r}"), kw);
1076 let l3 = theme::pad_right(&format!("{d}commands{r}"), kw);
1077 let l4 = theme::pad_right(&format!("{d}USD saved{r}"), kw);
1078 o.push(box_line(&format!(" {l1}{l2}{l3}{l4}")));
1079 o.push(box_line(""));
1080 o.push(format!(" {}", t.box_bottom(w)));
1081
1082 {
1084 let cfg = crate::core::config::Config::load();
1085 if cfg.buddy_enabled {
1086 let buddy = crate::core::buddy::BuddyState::compute();
1087 o.push(crate::core::buddy::format_buddy_block_at(&buddy, t, tick));
1088 }
1089 }
1090
1091 o.push(String::new());
1092
1093 let cost_title = t.section_title("Cost Breakdown");
1094 o.push(format!(
1095 " {cost_title} {d}@ ${:.2}/M input · ${:.2}/M output{r}",
1096 cost_model.input_price_per_m, cost_model.output_price_per_m,
1097 ));
1098 o.push(format!(" {ln}", ln = t.border_line(w)));
1099 o.push(String::new());
1100 let lbl_w = 20;
1101 let lbl_without = theme::pad_right(&format!("{m}Without lean-ctx{r}", m = t.muted.fg()), lbl_w);
1102 let lbl_with = theme::pad_right(&format!("{m}With lean-ctx{r}", m = t.muted.fg()), lbl_w);
1103 let lbl_saved = theme::pad_right(&format!("{c}{b}You saved{r}", c = t.success.fg()), lbl_w);
1104
1105 o.push(format!(
1106 " {lbl_without} {:>8} {d}{} input + {} output{r}",
1107 format_usd(cost.total_cost_without),
1108 format_usd(cost.input_cost_without),
1109 format_usd(cost.output_cost_without),
1110 ));
1111 o.push(format!(
1112 " {lbl_with} {:>8} {d}{} input + {} output{r}",
1113 format_usd(cost.total_cost_with),
1114 format_usd(cost.input_cost_with),
1115 format_usd(cost.output_cost_with),
1116 ));
1117 o.push(String::new());
1118 o.push(format!(
1119 " {lbl_saved} {c}{b}{:>8}{r} {d}input {} + output {}{r}",
1120 format_usd(cost.total_saved),
1121 format_usd(cost.input_cost_without - cost.input_cost_with),
1122 format_usd(cost.output_cost_without - cost.output_cost_with),
1123 c = t.success.fg(),
1124 ));
1125
1126 {
1128 let mut mcp_saved = 0u64;
1129 let mut mcp_input = 0u64;
1130 let mut mcp_calls = 0u64;
1131 let mut hook_saved = 0u64;
1132 let mut hook_input = 0u64;
1133 let mut hook_calls = 0u64;
1134 for (cmd, s) in &store.commands {
1135 let sv = s.input_tokens.saturating_sub(s.output_tokens);
1136 if cmd.starts_with("ctx_") {
1137 mcp_saved += sv;
1138 mcp_input += s.input_tokens;
1139 mcp_calls += s.count;
1140 } else {
1141 hook_saved += sv;
1142 hook_input += s.input_tokens;
1143 hook_calls += s.count;
1144 }
1145 }
1146 if mcp_calls > 0 || hook_calls > 0 {
1147 o.push(String::new());
1148 o.push(format!(" {}", t.section_title("Savings by Source")));
1149 o.push(format!(" {ln}", ln = t.border_line(w)));
1150 o.push(String::new());
1151
1152 let total = (mcp_saved + hook_saved).max(1) as f64;
1153 let mcp_pct = mcp_saved as f64 / total * 100.0;
1154 let hook_pct = hook_saved as f64 / total * 100.0;
1155 let mcp_rate = if mcp_input > 0 {
1156 mcp_saved as f64 / mcp_input as f64 * 100.0
1157 } else {
1158 0.0
1159 };
1160 let hook_rate = if hook_input > 0 {
1161 hook_saved as f64 / hook_input as f64 * 100.0
1162 } else {
1163 0.0
1164 };
1165
1166 let mcp_bar = t.gradient_bar(mcp_saved as f64 / total, 18);
1167 let hook_bar = t.gradient_bar(hook_saved as f64 / total, 18);
1168
1169 let mc = t.success.fg();
1170 let hc = t.secondary.fg();
1171 o.push(format!(
1172 " {mc}{b}MCP Tools{r} {:>5}x {mcp_bar} {b}{:>6}{r} {d}{mcp_rate:>4.0}% rate · {mcp_pct:>4.0}% of total{r}",
1173 mcp_calls,
1174 format_big(mcp_saved),
1175 ));
1176 o.push(format!(
1177 " {hc}{b}Shell Hooks{r} {:>5}x {hook_bar} {b}{:>6}{r} {d}{hook_rate:>4.0}% rate · {hook_pct:>4.0}% of total{r}",
1178 hook_calls,
1179 format_big(hook_saved),
1180 ));
1181 }
1182 }
1183
1184 o.push(String::new());
1185
1186 if let (Some(first), Some(_last)) = (&store.first_use, &store.last_use) {
1187 let first_short = first.get(..10).unwrap_or(first);
1188 let daily_savings: Vec<u64> = store
1189 .daily
1190 .iter()
1191 .map(|d2| day_total_saved(d2, &cost_model))
1192 .collect();
1193 let spark = t.gradient_sparkline(&daily_savings);
1194 o.push(format!(
1195 " {d}Since {first_short} · {days_active} day{plural}{r} {spark}",
1196 plural = if days_active != 1 { "s" } else { "" }
1197 ));
1198 o.push(String::new());
1199 }
1200
1201 o.push(String::new());
1202
1203 if !store.commands.is_empty() {
1204 o.push(format!(" {}", t.section_title("Top Commands")));
1205 o.push(format!(" {ln}", ln = t.border_line(w)));
1206 o.push(String::new());
1207
1208 let mut sorted: Vec<_> = store.commands.iter().collect();
1209 sorted.sort_by(|a, b2| {
1210 let sa = cmd_total_saved(a.1, &cost_model);
1211 let sb = cmd_total_saved(b2.1, &cost_model);
1212 sb.cmp(&sa)
1213 });
1214
1215 let max_cmd_saved = sorted
1216 .first()
1217 .map(|(_, s)| cmd_total_saved(s, &cost_model))
1218 .unwrap_or(1)
1219 .max(1);
1220
1221 for (cmd, stats) in sorted.iter().take(10) {
1222 let cmd_saved = cmd_total_saved(stats, &cost_model);
1223 let cmd_input_saved = stats.input_tokens.saturating_sub(stats.output_tokens);
1224 let cmd_pct = if stats.input_tokens > 0 {
1225 cmd_input_saved as f64 / stats.input_tokens as f64 * 100.0
1226 } else {
1227 0.0
1228 };
1229 let ratio = cmd_saved as f64 / max_cmd_saved as f64;
1230 let bar = theme::pad_right(&t.gradient_bar(ratio, 22), 22);
1231 let pc = t.pct_color(cmd_pct);
1232 let cmd_col = theme::pad_right(
1233 &format!("{m}{}{r}", truncate_cmd(cmd, 16), m = t.muted.fg()),
1234 18,
1235 );
1236 let saved_col = theme::pad_right(&format!("{b}{pc}{}{r}", format_big(cmd_saved)), 8);
1237 o.push(format!(
1238 " {cmd_col} {:>5}x {bar} {saved_col} {d}{cmd_pct:>3.0}%{r}",
1239 stats.count,
1240 ));
1241 }
1242
1243 if sorted.len() > 10 {
1244 o.push(format!(
1245 " {d}... +{} more commands{r}",
1246 sorted.len() - 10
1247 ));
1248 }
1249 }
1250
1251 if store.daily.len() >= 2 {
1252 o.push(String::new());
1253 o.push(String::new());
1254 o.push(format!(" {}", t.section_title("Recent Days")));
1255 o.push(format!(" {ln}", ln = t.border_line(w)));
1256 o.push(String::new());
1257
1258 let recent: Vec<_> = store.daily.iter().rev().take(7).collect();
1259 for day in recent.iter().rev() {
1260 let day_saved = day_total_saved(day, &cost_model);
1261 let day_input_saved = day.input_tokens.saturating_sub(day.output_tokens);
1262 let day_pct = if day.input_tokens > 0 {
1263 day_input_saved as f64 / day.input_tokens as f64 * 100.0
1264 } else {
1265 0.0
1266 };
1267 let pc = t.pct_color(day_pct);
1268 let date_short = day.date.get(5..).unwrap_or(&day.date);
1269 let date_col = theme::pad_right(&format!("{m}{date_short}{r}", m = t.muted.fg()), 7);
1270 let saved_col = theme::pad_right(&format!("{pc}{b}{}{r}", format_big(day_saved)), 9);
1271 o.push(format!(
1272 " {date_col} {:>5} cmds {saved_col} saved {pc}{day_pct:>5.1}%{r}",
1273 day.commands,
1274 ));
1275 }
1276 }
1277
1278 o.push(String::new());
1279 o.push(String::new());
1280
1281 if let Some(tip) = contextual_tip(&store) {
1282 o.push(format!(" {w}💡 {tip}{r}", w = t.warning.fg()));
1283 o.push(String::new());
1284 }
1285
1286 {
1288 let project_root = std::env::current_dir()
1289 .map(|p| p.to_string_lossy().to_string())
1290 .unwrap_or_default();
1291 if !project_root.is_empty() {
1292 let gotcha_store = crate::core::gotcha_tracker::GotchaStore::load(&project_root);
1293 if gotcha_store.stats.total_errors_detected > 0 || !gotcha_store.gotchas.is_empty() {
1294 let a = t.accent.fg();
1295 o.push(format!(" {a}🧠 Bug Memory{r}"));
1296 o.push(format!(
1297 " {m} Active gotchas: {}{r} Bugs prevented: {}{r}",
1298 gotcha_store.gotchas.len(),
1299 gotcha_store.stats.total_prevented,
1300 m = t.muted.fg(),
1301 ));
1302 o.push(String::new());
1303 }
1304 }
1305 }
1306
1307 let m = t.muted.fg();
1308 o.push(format!(
1309 " {m}🐛 Found a bug? Run: lean-ctx report-issue{r}"
1310 ));
1311 o.push(format!(
1312 " {m}📊 Help improve lean-ctx: lean-ctx contribute{r}"
1313 ));
1314 o.push(format!(" {m}🧠 View bug memory: lean-ctx gotchas{r}"));
1315
1316 o.push(String::new());
1317 o.push(String::new());
1318
1319 o.join("\n")
1320}
1321
1322fn contextual_tip(store: &StatsStore) -> Option<String> {
1323 let tips = build_tips(store);
1324 if tips.is_empty() {
1325 return None;
1326 }
1327 let seed = std::time::SystemTime::now()
1328 .duration_since(std::time::UNIX_EPOCH)
1329 .unwrap_or_default()
1330 .as_secs()
1331 / 86400;
1332 Some(tips[(seed as usize) % tips.len()].clone())
1333}
1334
1335fn build_tips(store: &StatsStore) -> Vec<String> {
1336 let mut tips = Vec::new();
1337
1338 if store.cep.modes.get("map").copied().unwrap_or(0) == 0 {
1339 tips.push("Try mode=\"map\" for files you only need as context — shows deps + exports, skips implementation.".into());
1340 }
1341
1342 if store.cep.modes.get("signatures").copied().unwrap_or(0) == 0 {
1343 tips.push("Try mode=\"signatures\" for large files — returns only the API surface.".into());
1344 }
1345
1346 if store.cep.total_cache_reads > 0
1347 && store.cep.total_cache_hits as f64 / store.cep.total_cache_reads as f64 > 0.8
1348 {
1349 tips.push(
1350 "High cache hit rate! Use ctx_compress periodically to keep context compact.".into(),
1351 );
1352 }
1353
1354 if store.total_commands > 50 && store.cep.sessions == 0 {
1355 tips.push("Use ctx_session to track your task — enables cross-session memory.".into());
1356 }
1357
1358 if store.cep.modes.get("entropy").copied().unwrap_or(0) == 0 && store.total_commands > 20 {
1359 tips.push("Try mode=\"entropy\" for maximum compression on large files.".into());
1360 }
1361
1362 if store.daily.len() >= 7 {
1363 tips.push("Run lean-ctx gain --graph for a 30-day sparkline chart.".into());
1364 }
1365
1366 tips.push("Run ctx_overview(task) at session start for a task-aware project map.".into());
1367 tips.push("Run lean-ctx dashboard for a live web UI with all your stats.".into());
1368
1369 let cfg = crate::core::config::Config::load();
1370 if cfg.theme == "default" {
1371 tips.push(
1372 "Customize your dashboard! Try: lean-ctx theme set cyberpunk (or neon, ocean, sunset, monochrome)".into(),
1373 );
1374 tips.push(
1375 "Want a unique look? Run lean-ctx theme list to see all available themes.".into(),
1376 );
1377 } else {
1378 tips.push(format!(
1379 "Current theme: {}. Run lean-ctx theme list to explore others.",
1380 cfg.theme
1381 ));
1382 }
1383
1384 tips.push(
1385 "Create your own theme with lean-ctx theme create <name> and set custom colors!".into(),
1386 );
1387
1388 tips
1389}
1390
1391pub fn gain_live() {
1392 use std::io::Write;
1393
1394 let interval = std::time::Duration::from_secs(1);
1395 let mut line_count = 0usize;
1396 let d = theme::dim();
1397 let r = theme::rst();
1398
1399 eprintln!(" {d}▸ Live mode (1s refresh) · Ctrl+C to exit{r}");
1400
1401 loop {
1402 if line_count > 0 {
1403 print!("\x1B[{line_count}A\x1B[J");
1404 }
1405
1406 let tick = std::time::SystemTime::now()
1407 .duration_since(std::time::UNIX_EPOCH)
1408 .ok()
1409 .map(|d| d.as_millis() as u64);
1410 let output = format_gain_themed_at(&active_theme(), tick);
1411 let footer = format!("\n {d}▸ Live · updates every 1s · Ctrl+C to exit{r}\n");
1412 let full = format!("{output}{footer}");
1413 line_count = full.lines().count();
1414
1415 print!("{full}");
1416 let _ = std::io::stdout().flush();
1417
1418 std::thread::sleep(interval);
1419 }
1420}
1421
1422pub fn format_gain_graph() -> String {
1423 let t = active_theme();
1424 let store = load();
1425 let r = theme::rst();
1426 let b = theme::bold();
1427 let d = theme::dim();
1428
1429 if store.daily.is_empty() {
1430 return format!("{d}No daily data yet.{r} Use lean-ctx for a few days to see the graph.");
1431 }
1432
1433 let cm = CostModel::default();
1434 let days: Vec<_> = store
1435 .daily
1436 .iter()
1437 .rev()
1438 .take(30)
1439 .collect::<Vec<_>>()
1440 .into_iter()
1441 .rev()
1442 .collect();
1443
1444 let savings: Vec<u64> = days.iter().map(|day| day_total_saved(day, &cm)).collect();
1445
1446 let max_saved = *savings.iter().max().unwrap_or(&1);
1447 let max_saved = max_saved.max(1);
1448
1449 let bar_width = 36;
1450 let mut o = Vec::new();
1451
1452 o.push(String::new());
1453 o.push(format!(
1454 " {icon} {title} {d}Token Savings Graph (last 30 days){r}",
1455 icon = t.header_icon(),
1456 title = t.brand_title(),
1457 ));
1458 o.push(format!(" {ln}", ln = t.border_line(58)));
1459 o.push(format!(
1460 " {d}{:>58}{r}",
1461 format!("peak: {}", format_big(max_saved))
1462 ));
1463 o.push(String::new());
1464
1465 for (i, day) in days.iter().enumerate() {
1466 let saved = savings[i];
1467 let ratio = saved as f64 / max_saved as f64;
1468 let bar = theme::pad_right(&t.gradient_bar(ratio, bar_width), bar_width);
1469
1470 let input_saved = day.input_tokens.saturating_sub(day.output_tokens);
1471 let pct = if day.input_tokens > 0 {
1472 input_saved as f64 / day.input_tokens as f64 * 100.0
1473 } else {
1474 0.0
1475 };
1476 let date_short = day.date.get(5..).unwrap_or(&day.date);
1477
1478 o.push(format!(
1479 " {m}{date_short}{r} {brd}│{r} {bar} {b}{:>6}{r} {d}{pct:.0}%{r}",
1480 format_big(saved),
1481 m = t.muted.fg(),
1482 brd = t.border.fg(),
1483 ));
1484 }
1485
1486 let total_saved: u64 = savings.iter().sum();
1487 let total_cmds: u64 = days.iter().map(|day| day.commands).sum();
1488 let spark = t.gradient_sparkline(&savings);
1489
1490 o.push(String::new());
1491 o.push(format!(" {ln}", ln = t.border_line(58)));
1492 o.push(format!(
1493 " {spark} {b}{txt}{}{r} saved across {b}{}{r} commands",
1494 format_big(total_saved),
1495 format_num(total_cmds),
1496 txt = t.text.fg(),
1497 ));
1498 o.push(String::new());
1499
1500 o.join("\n")
1501}
1502
1503pub fn format_gain_daily() -> String {
1504 let t = active_theme();
1505 let store = load();
1506 let r = theme::rst();
1507 let b = theme::bold();
1508 let d = theme::dim();
1509
1510 if store.daily.is_empty() {
1511 return format!("{d}No daily data yet.{r}");
1512 }
1513
1514 let mut o = Vec::new();
1515 let w = 64;
1516
1517 let side = t.box_side();
1518 let daily_box = |content: &str| -> String {
1519 let padded = theme::pad_right(content, w);
1520 format!(" {side}{padded}{side}")
1521 };
1522
1523 o.push(String::new());
1524 o.push(format!(
1525 " {icon} {title} {d}Daily Breakdown{r}",
1526 icon = t.header_icon(),
1527 title = t.brand_title(),
1528 ));
1529 o.push(format!(" {}", t.box_top(w)));
1530 let hdr = format!(
1531 " {b}{txt}{:<12} {:>6} {:>10} {:>10} {:>7} {:>6}{r}",
1532 "Date",
1533 "Cmds",
1534 "Input",
1535 "Saved",
1536 "Rate",
1537 "USD",
1538 txt = t.text.fg(),
1539 );
1540 o.push(daily_box(&hdr));
1541 o.push(format!(" {}", t.box_mid(w)));
1542
1543 let days: Vec<_> = store
1544 .daily
1545 .iter()
1546 .rev()
1547 .take(30)
1548 .collect::<Vec<_>>()
1549 .into_iter()
1550 .rev()
1551 .cloned()
1552 .collect();
1553
1554 let cm = CostModel::default();
1555 for day in &days {
1556 let saved = day_total_saved(day, &cm);
1557 let input_saved = day.input_tokens.saturating_sub(day.output_tokens);
1558 let pct = if day.input_tokens > 0 {
1559 input_saved as f64 / day.input_tokens as f64 * 100.0
1560 } else {
1561 0.0
1562 };
1563 let pc = t.pct_color(pct);
1564 let usd = usd_estimate(saved);
1565 let row = format!(
1566 " {m}{:<12}{r} {:>6} {:>10} {pc}{b}{:>10}{r} {pc}{:>6.1}%{r} {d}{:>6}{r}",
1567 &day.date,
1568 day.commands,
1569 format_big(day.input_tokens),
1570 format_big(saved),
1571 pct,
1572 usd,
1573 m = t.muted.fg(),
1574 );
1575 o.push(daily_box(&row));
1576 }
1577
1578 let total_input: u64 = store.daily.iter().map(|day| day.input_tokens).sum();
1579 let total_saved: u64 = store
1580 .daily
1581 .iter()
1582 .map(|day| day_total_saved(day, &cm))
1583 .sum();
1584 let total_pct = if total_input > 0 {
1585 let input_saved: u64 = store
1586 .daily
1587 .iter()
1588 .map(|day| day.input_tokens.saturating_sub(day.output_tokens))
1589 .sum();
1590 input_saved as f64 / total_input as f64 * 100.0
1591 } else {
1592 0.0
1593 };
1594 let total_usd = usd_estimate(total_saved);
1595 let sc = t.success.fg();
1596
1597 o.push(format!(" {}", t.box_mid(w)));
1598 let total_row = format!(
1599 " {b}{txt}{:<12}{r} {:>6} {:>10} {sc}{b}{:>10}{r} {sc}{b}{:>6.1}%{r} {b}{:>6}{r}",
1600 "TOTAL",
1601 format_num(store.total_commands),
1602 format_big(total_input),
1603 format_big(total_saved),
1604 total_pct,
1605 total_usd,
1606 txt = t.text.fg(),
1607 );
1608 o.push(daily_box(&total_row));
1609 o.push(format!(" {}", t.box_bottom(w)));
1610
1611 let daily_savings: Vec<u64> = days.iter().map(|day| day_total_saved(day, &cm)).collect();
1612 let spark = t.gradient_sparkline(&daily_savings);
1613 o.push(format!(" {d}Trend:{r} {spark}"));
1614 o.push(String::new());
1615
1616 o.join("\n")
1617}
1618
1619pub fn format_gain_json() -> String {
1620 let store = load();
1621 serde_json::to_string_pretty(&store).unwrap_or_else(|_| "{}".to_string())
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626 use super::*;
1627
1628 fn make_store(commands: u64, input: u64, output: u64) -> StatsStore {
1629 StatsStore {
1630 total_commands: commands,
1631 total_input_tokens: input,
1632 total_output_tokens: output,
1633 ..Default::default()
1634 }
1635 }
1636
1637 #[test]
1638 fn apply_deltas_merges_mcp_and_shell() {
1639 let baseline = make_store(0, 0, 0);
1640 let mut current = make_store(0, 0, 0);
1641 current.total_commands = 5;
1642 current.total_input_tokens = 1000;
1643 current.total_output_tokens = 200;
1644 current.commands.insert(
1645 "ctx_read".to_string(),
1646 CommandStats {
1647 count: 5,
1648 input_tokens: 1000,
1649 output_tokens: 200,
1650 },
1651 );
1652
1653 let mut disk = make_store(20, 500, 490);
1654 disk.commands.insert(
1655 "echo".to_string(),
1656 CommandStats {
1657 count: 20,
1658 input_tokens: 500,
1659 output_tokens: 490,
1660 },
1661 );
1662
1663 let merged = apply_deltas(&disk, ¤t, &baseline);
1664
1665 assert_eq!(merged.total_commands, 25);
1666 assert_eq!(merged.total_input_tokens, 1500);
1667 assert_eq!(merged.total_output_tokens, 690);
1668 assert_eq!(merged.commands["ctx_read"].count, 5);
1669 assert_eq!(merged.commands["echo"].count, 20);
1670 }
1671
1672 #[test]
1673 fn apply_deltas_incremental_flush() {
1674 let baseline = make_store(10, 200, 100);
1675 let current = make_store(15, 700, 300);
1676
1677 let disk = make_store(30, 600, 500);
1678
1679 let merged = apply_deltas(&disk, ¤t, &baseline);
1680
1681 assert_eq!(merged.total_commands, 35);
1682 assert_eq!(merged.total_input_tokens, 1100);
1683 assert_eq!(merged.total_output_tokens, 700);
1684 }
1685
1686 #[test]
1687 fn apply_deltas_preserves_disk_commands() {
1688 let baseline = make_store(0, 0, 0);
1689 let mut current = make_store(2, 100, 50);
1690 current.commands.insert(
1691 "ctx_read".to_string(),
1692 CommandStats {
1693 count: 2,
1694 input_tokens: 100,
1695 output_tokens: 50,
1696 },
1697 );
1698
1699 let mut disk = make_store(10, 300, 280);
1700 disk.commands.insert(
1701 "echo".to_string(),
1702 CommandStats {
1703 count: 8,
1704 input_tokens: 200,
1705 output_tokens: 200,
1706 },
1707 );
1708 disk.commands.insert(
1709 "ctx_read".to_string(),
1710 CommandStats {
1711 count: 3,
1712 input_tokens: 150,
1713 output_tokens: 80,
1714 },
1715 );
1716
1717 let merged = apply_deltas(&disk, ¤t, &baseline);
1718
1719 assert_eq!(merged.commands["echo"].count, 8);
1720 assert_eq!(merged.commands["ctx_read"].count, 5);
1721 assert_eq!(merged.commands["ctx_read"].input_tokens, 250);
1722 }
1723
1724 #[test]
1725 fn merge_daily_combines_same_date() {
1726 let baseline_daily = vec![];
1727 let current_daily = vec![DayStats {
1728 date: "2026-04-18".to_string(),
1729 commands: 5,
1730 input_tokens: 1000,
1731 output_tokens: 200,
1732 }];
1733 let mut merged_daily = vec![DayStats {
1734 date: "2026-04-18".to_string(),
1735 commands: 20,
1736 input_tokens: 500,
1737 output_tokens: 490,
1738 }];
1739
1740 merge_daily(&mut merged_daily, ¤t_daily, &baseline_daily);
1741
1742 assert_eq!(merged_daily.len(), 1);
1743 assert_eq!(merged_daily[0].commands, 25);
1744 assert_eq!(merged_daily[0].input_tokens, 1500);
1745 }
1746}