1use crate::core::eval_ab::speed::SpeedHeadline;
2use crate::core::security_events::SecurityCounts;
3use crate::core::session::SessionState;
4use crate::core::stats;
5
6pub struct WrappedReport {
7 pub period: String,
8 pub tokens_saved: u64,
9 pub tokens_input: u64,
10 pub cost_avoided_usd: f64,
11 pub total_commands: u64,
12 pub sessions_count: usize,
13 pub top_commands: Vec<(String, u64, f64)>,
14 pub compression_rate_pct: f64,
15 pub files_touched: u64,
16 pub daily_savings: Vec<u64>,
17 pub bounce_tokens: u64,
20 pub model_key: String,
22 pub pricing_estimated: bool,
25 pub percentile: Option<u8>,
28 pub security: Option<SecurityCounts>,
32 pub speed: Option<SpeedHeadline>,
36}
37
38impl WrappedReport {
39 pub fn generate(period: &str) -> Self {
40 let store = stats::load_for_display();
41 let sessions = SessionState::list_sessions();
42
43 let (gross_tokens_saved, tokens_input, total_commands) = match period {
44 "week" => aggregate_recent_stats(&store, 7),
45 "month" => aggregate_recent_stats(&store, 30),
46 _ => (
47 store
48 .total_input_tokens
49 .saturating_sub(store.total_output_tokens),
50 store.total_input_tokens,
51 store.total_commands,
52 ),
53 };
54
55 let period_days = match period {
58 "week" => Some(7),
59 "month" => Some(30),
60 _ => None,
61 };
62 let bounce_tokens = crate::core::savings_ledger::bounce_tokens(period_days);
63 let tokens_saved = gross_tokens_saved.saturating_sub(bounce_tokens);
64 let security = crate::core::value::proof::verified_security_since(
65 period_days.map(|d| chrono::Utc::now() - chrono::Duration::days(i64::from(d))),
66 )
67 .filter(|c| !c.is_empty());
68
69 let env_model = std::env::var("LEAN_CTX_MODEL")
70 .or_else(|_| std::env::var("LCTX_MODEL"))
71 .ok();
72 let pricing = crate::core::gain::model_pricing::ModelPricing::load();
73 let quote = pricing.quote(env_model.as_deref());
74 let cost_avoided_usd = quote.cost.estimate_usd(tokens_saved, 0, 0, 0);
78 let pricing_estimated = matches!(
79 quote.match_kind,
80 crate::core::gain::model_pricing::PricingMatchKind::Fallback
81 );
82 let model_key = quote.model_key.clone();
83
84 let sessions_count = match period {
85 "week" => count_recent_sessions(&sessions, 7),
86 "month" => count_recent_sessions(&sessions, 30),
87 _ => sessions.len(),
88 };
89
90 let mut top_commands: Vec<(String, u64, f64)> = store
91 .commands
92 .iter()
93 .map(|(cmd, stats)| {
94 let saved = stats.input_tokens.saturating_sub(stats.output_tokens);
95 let pct = if stats.input_tokens > 0 {
96 saved as f64 / stats.input_tokens as f64 * 100.0
97 } else {
98 0.0
99 };
100 (cmd.clone(), saved, pct)
101 })
102 .collect();
103 top_commands.sort_by_key(|x| std::cmp::Reverse(x.1));
104 top_commands.truncate(5);
105
106 let agent_id = crate::core::agent_identity::current_agent_id();
107 let verified_net = crate::core::savings_ledger::roi_report(agent_id).net_saved_tokens;
108 let compression_rate_pct = if tokens_input > 0 {
109 let v = verified_net as f64 / tokens_input as f64 * 100.0;
110 if v > 0.0 {
111 v
112 } else {
113 tokens_saved as f64 / tokens_input as f64 * 100.0
114 }
115 } else {
116 0.0
117 };
118
119 let files_touched: u64 = sessions.iter().map(|s| s.tool_calls as u64).sum();
120
121 let day_saved = |d: &stats::DayStats| d.input_tokens.saturating_sub(d.output_tokens);
122 let take_recent = |n: usize| -> Vec<u64> {
123 store
124 .daily
125 .iter()
126 .rev()
127 .take(n)
128 .collect::<Vec<_>>()
129 .into_iter()
130 .rev()
131 .map(day_saved)
132 .collect()
133 };
134 let daily_savings = match period {
135 "week" => take_recent(7),
136 "month" => take_recent(30),
137 _ => store.daily.iter().map(day_saved).collect(),
138 };
139
140 WrappedReport {
141 period: period.to_string(),
142 tokens_saved,
143 tokens_input,
144 cost_avoided_usd,
145 total_commands,
146 sessions_count,
147 top_commands,
148 compression_rate_pct,
149 files_touched,
150 daily_savings,
151 bounce_tokens,
152 model_key,
153 pricing_estimated,
154 percentile: estimate_percentile(tokens_saved),
155 security,
156 speed: SpeedHeadline::latest(),
157 }
158 }
159
160 pub fn security_phrases(&self) -> Vec<String> {
163 self.security
164 .as_ref()
165 .map(crate::core::value::format::security_phrases)
166 .unwrap_or_default()
167 }
168
169 pub fn methodology_line(&self) -> String {
173 let price = if self.pricing_estimated {
174 format!(
175 "{} blended fallback price (set LEAN_CTX_MODEL for exact)",
176 self.model_key
177 )
178 } else {
179 format!("{} input price", self.model_key)
180 };
181 let basis = if self.bounce_tokens > 0 {
182 format!(
183 "measured original - compressed - {} bounce tokens",
184 format_tokens(self.bounce_tokens)
185 )
186 } else {
187 "measured original - compressed tokens".to_string()
188 };
189 format!("Savings = {basis}; USD is an upper bound at {price}")
190 }
191
192 #[allow(clippy::many_single_char_names)] pub fn format_ascii(&self) -> String {
197 use crate::core::theme;
198
199 let cfg = crate::core::config::Config::load();
200 let t = theme::load_theme(&cfg.theme);
201 let rst = theme::rst();
202 let bold = theme::bold();
203 let dim = theme::dim();
204
205 let period_label = match self.period.as_str() {
206 "week" => format!("Week of {}", chrono::Utc::now().format("%b %d, %Y")),
207 "month" => format!("Month of {}", chrono::Utc::now().format("%B %Y")),
208 _ => "All Time".to_string(),
209 };
210
211 let w = 52;
212 let side = t.box_side();
213 let box_line = |content: &str| -> String {
214 let padded = theme::pad_right(content, w);
215 format!(" {side}{padded}{side}")
216 };
217
218 let mut out: Vec<String> = Vec::new();
219 out.push(String::new());
220 out.push(format!(" {}", t.box_top(w)));
221 out.push(box_line(""));
222 out.push(box_line(&format!(
223 " {icon} {brand} {accent}Wrapped{rst} {dim}· {period_label}{rst}",
224 icon = t.header_icon(),
225 brand = t.brand_title(),
226 accent = t.accent.fg(),
227 )));
228 out.push(box_line(""));
229 out.push(format!(" {}", t.box_mid(w)));
230 out.push(box_line(""));
231
232 let kw = 16;
234 let sc = t.success.fg();
235 let c2 = t.secondary.fg();
236 let c3 = t.warning.fg();
237 let c4 = t.accent.fg();
238
239 let v1 = theme::pad_right(
240 &format!("{sc}{bold}{}{rst}", format_tokens(self.tokens_saved)),
241 kw,
242 );
243 let v2 = theme::pad_right(&format!("{c4}{bold}${:.2}{rst}", self.cost_avoided_usd), kw);
244 let v3 = theme::pad_right(&format!("{c3}{bold}{}{rst}", self.total_commands), kw);
245 out.push(box_line(&format!(" {v1}{v2}{v3}")));
246 let l1 = theme::pad_right(&format!("{dim}tokens saved{rst}"), kw);
247 let l2 = theme::pad_right(&format!("{dim}cost avoided{rst}"), kw);
248 let l3 = theme::pad_right(&format!("{dim}commands{rst}"), kw);
249 out.push(box_line(&format!(" {l1}{l2}{l3}")));
250 out.push(box_line(""));
251
252 let v4 = theme::pad_right(&format!("{c2}{bold}{}{rst}", self.sessions_count), kw);
255 let v5 = theme::pad_right(
256 &format!(
257 "{pc}{bold}{:.1}%{rst}",
258 self.compression_rate_pct,
259 pc = t.pct_color(self.compression_rate_pct),
260 ),
261 kw,
262 );
263 let energy = crate::core::energy::format_for_tokens(self.tokens_saved);
264 let v6 = theme::pad_right(&format!("{c4}{bold}{energy}{rst}"), kw);
265 out.push(box_line(&format!(" {v4}{v5}{v6}")));
266 let l4 = theme::pad_right(&format!("{dim}sessions{rst}"), kw);
267 let l5 = theme::pad_right(&format!("{dim}compression{rst}"), kw);
268 let l6 = theme::pad_right(&format!("{dim}energy saved{rst}"), kw);
269 out.push(box_line(&format!(" {l4}{l5}{l6}")));
270 out.push(box_line(""));
271
272 if self.daily_savings.iter().filter(|v| **v > 0).count() >= 2 {
274 let spark = t.gradient_sparkline(&self.daily_savings);
275 out.push(box_line(&format!(" {dim}trend{rst} {spark}")));
276 out.push(box_line(""));
277 }
278
279 let security = self.security_phrases();
281 if !security.is_empty() {
282 out.push(format!(" {}", t.box_mid(w)));
283 for phrase in &security {
284 out.push(box_line(&format!(" {sc}✓{rst} {phrase}")));
285 }
286 out.push(box_line(&format!(
287 " {dim}measured · signed audit trail intact{rst}"
288 )));
289 }
290
291 if let Some(speed) = &self.speed {
293 out.push(format!(" {}", t.box_mid(w)));
294 out.push(box_line(&format!(
295 " {c3}⚡{rst} {:.0}% faster model answers with lean-ctx",
296 speed.faster_pct
297 )));
298 let detail = theme::truncate_visual(&speed.detail(), w - 6);
299 out.push(box_line(&format!(" {dim}{detail}{rst}")));
300 }
301
302 if !self.top_commands.is_empty() {
304 let prefix_visible = 8; let budget = w.saturating_sub(prefix_visible);
306 let mut top_str = self
307 .top_commands
308 .iter()
309 .take(3)
310 .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
311 .collect::<Vec<_>>()
312 .join(" · ");
313 if top_str.chars().count() > budget {
314 let truncated: String = top_str.chars().take(budget.saturating_sub(1)).collect();
315 top_str = format!("{truncated}…");
316 }
317 out.push(format!(" {}", t.box_mid(w)));
318 out.push(box_line(&format!(
319 " {m}top{rst} {top_str}",
320 m = t.muted.fg()
321 )));
322 }
323
324 out.push(format!(" {}", t.box_bottom(w)));
325 out.push(format!(
326 " {dim}\"Your AI saw only what mattered.\"{rst} {accent}leanctx.com{rst}",
327 accent = t.accent.fg(),
328 ));
329 let est_marker = if self.pricing_estimated {
330 " (est.)"
331 } else {
332 ""
333 };
334 out.push(format!(
335 " {dim}model {model}{est_marker} · USD = upper bound{rst}",
336 model = self.model_key,
337 ));
338 out.push(String::new());
339
340 out.join("\n")
341 }
342
343 pub fn format_compact(&self) -> String {
344 let saved_str = format_tokens(self.tokens_saved);
345 let cost_str = format!("${:.2}", self.cost_avoided_usd);
346 let top_str = self
347 .top_commands
348 .iter()
349 .take(3)
350 .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
351 .collect::<Vec<_>>()
352 .join(" | ");
353
354 let est_marker = if self.pricing_estimated {
355 " (est.)"
356 } else {
357 ""
358 };
359 let security = self.security_phrases();
360 let security_str = if security.is_empty() {
361 String::new()
362 } else {
363 format!(
364 " | Security: {} (audit trail verified)",
365 security.join(", ")
366 )
367 };
368 let speed_str = self.speed.as_ref().map_or_else(String::new, |s| {
369 format!(" | Speed: {} ({}, signed)", s.phrase(), s.detail())
370 });
371 format!(
372 "WRAPPED [{}]: {} tok saved, {} avoided{}, {} sessions, {} cmds | Top: {} | Compression: {:.1}% | Energy: {}{}{} | model={}",
373 self.period,
374 saved_str,
375 cost_str,
376 est_marker,
377 self.sessions_count,
378 self.total_commands,
379 top_str,
380 self.compression_rate_pct,
381 crate::core::energy::format_for_tokens(self.tokens_saved),
382 security_str,
383 speed_str,
384 self.model_key,
385 )
386 }
387}
388
389fn aggregate_recent_stats(store: &stats::StatsStore, days: usize) -> (u64, u64, u64) {
390 let recent_days: Vec<&stats::DayStats> = store.daily.iter().rev().take(days).collect();
391
392 let input: u64 = recent_days.iter().map(|d| d.input_tokens).sum();
393 let output: u64 = recent_days.iter().map(|d| d.output_tokens).sum();
394 let commands: u64 = recent_days.iter().map(|d| d.commands).sum();
395 let saved = input.saturating_sub(output);
396
397 (saved, input, commands)
398}
399
400fn count_recent_sessions(sessions: &[crate::core::session::SessionSummary], days: i64) -> usize {
401 let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
402 sessions.iter().filter(|s| s.updated_at > cutoff).count()
403}
404
405pub fn format_tokens(tokens: u64) -> String {
406 if tokens >= 1_000_000_000_000 {
407 format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
408 } else if tokens >= 1_000_000_000 {
409 format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
410 } else if tokens >= 1_000_000 {
411 format!("{:.1}M", tokens as f64 / 1_000_000.0)
412 } else if tokens >= 1_000 {
413 format!("{:.1}K", tokens as f64 / 1_000.0)
414 } else {
415 format!("{tokens}")
416 }
417}
418
419pub fn edit_token_recovery_message(card_id: &str, nonce: &str) -> String {
422 format!("lean-ctx:wrapped-edit-token-recovery:v1\ncard_id:{card_id}\nnonce:{nonce}")
423}
424
425fn estimate_percentile(tokens_saved: u64) -> Option<u8> {
429 if tokens_saved < 1_000 {
430 return None;
431 }
432 let pct = if tokens_saved >= 100_000_000 {
435 99
436 } else if tokens_saved >= 50_000_000 {
437 97
438 } else if tokens_saved >= 10_000_000 {
439 95
440 } else if tokens_saved >= 5_000_000 {
441 90
442 } else if tokens_saved >= 1_000_000 {
443 80
444 } else if tokens_saved >= 500_000 {
445 70
446 } else if tokens_saved >= 100_000 {
447 55
448 } else if tokens_saved >= 50_000 {
449 40
450 } else if tokens_saved >= 10_000 {
451 25
452 } else {
453 10
454 };
455 Some(pct)
456}
457
458#[cfg(test)]
459pub mod tests {
460 use super::*;
461
462 fn sample() -> WrappedReport {
463 WrappedReport {
464 period: "all".into(),
465 tokens_saved: 348_300_000,
466 tokens_input: 580_000_000,
467 cost_avoided_usd: 870.81,
468 total_commands: 17_055,
469 sessions_count: 67,
470 top_commands: vec![
471 ("ctx_search".into(), 100, 60.0),
472 ("cli_grep".into(), 80, 85.0),
473 ("cli_shell".into(), 50, 37.0),
474 ],
475 compression_rate_pct: 60.2,
476 files_touched: 1_234,
477 daily_savings: vec![10, 50, 30, 30, 80, 80, 20, 5, 5, 40, 60, 40, 5, 50, 15],
478 bounce_tokens: 0,
479 model_key: "claude-3.5-sonnet".into(),
480 pricing_estimated: false,
481 percentile: Some(95),
482 security: None,
483 speed: None,
484 }
485 }
486
487 #[test]
488 fn edit_token_recovery_proof_is_domain_separated_and_stable() {
489 assert_eq!(
490 edit_token_recovery_message("card-1", "nonce-1"),
491 "lean-ctx:wrapped-edit-token-recovery:v1\ncard_id:card-1\nnonce:nonce-1"
492 );
493 }
494
495 fn is_box_line(l: &str) -> bool {
496 let trimmed = l.trim_start();
497 ["│", "╭", "├", "╰"].iter().any(|c| trimmed.starts_with(c))
498 }
499
500 #[test]
501 fn wrapped_ascii_box_lines_have_uniform_width() {
502 let _env = crate::core::data_dir::test_env_lock();
507 let out = sample().format_ascii();
509 let widths: Vec<usize> = out
510 .lines()
511 .filter(|l| is_box_line(l))
512 .map(crate::core::theme::visual_len)
513 .collect();
514 assert!(widths.len() >= 4, "expected several box lines:\n{out}");
515 let first = widths[0];
516 for w in &widths {
517 assert_eq!(*w, first, "box line widths must be uniform:\n{out}");
518 }
519 }
520
521 #[test]
522 fn wrapped_ascii_includes_brand_and_metrics() {
523 let out = sample().format_ascii();
524 assert!(out.contains("leanctx.com"), "missing brand footer:\n{out}");
525 assert!(out.contains("Wrapped"));
526 assert!(out.contains("tokens saved"));
527 assert!(out.contains("compression"));
528 }
529
530 #[test]
531 fn wrapped_ascii_truncates_overlong_top_line() {
532 let out = sample().format_ascii();
533 let max = out
535 .lines()
536 .filter(|l| is_box_line(l))
537 .map(crate::core::theme::visual_len)
538 .max()
539 .unwrap_or(0);
540 let min = out
541 .lines()
542 .filter(|l| is_box_line(l))
543 .map(crate::core::theme::visual_len)
544 .min()
545 .unwrap_or(0);
546 assert_eq!(max, min, "top line overflowed the box:\n{out}");
547 }
548
549 #[test]
550 fn wrapped_compact_is_single_line_summary() {
551 let out = sample().format_compact();
552 assert!(out.starts_with("WRAPPED"), "compact summary changed: {out}");
553 assert!(out.contains("Compression:"));
554 assert!(
555 out.contains("model="),
556 "compact must name the pricing model: {out}"
557 );
558 }
559
560 #[test]
561 fn methodology_is_conservative_and_explainable() {
562 let m = sample().methodology_line();
563 assert!(
564 m.contains("upper bound"),
565 "must state it is an upper bound: {m}"
566 );
567 assert!(m.contains("claude-3.5-sonnet"), "must name the model: {m}");
568 }
569
570 #[test]
571 fn ascii_footer_surfaces_model_and_upper_bound() {
572 let out = sample().format_ascii();
573 assert!(
574 out.contains("model claude-3.5-sonnet"),
575 "footer must name model:\n{out}"
576 );
577 assert!(
578 out.contains("USD = upper bound"),
579 "footer must flag upper bound:\n{out}"
580 );
581 }
582
583 #[test]
584 fn estimated_pricing_is_flagged() {
585 let mut r = sample();
586 r.pricing_estimated = true;
587 assert!(
588 r.format_ascii().contains("(est.)"),
589 "estimated price must show (est.)"
590 );
591 assert!(r.format_compact().contains("(est.)"));
592 assert!(r.methodology_line().contains("fallback"));
593 }
594
595 #[test]
596 fn verified_security_is_shown_and_absent_security_is_not() {
597 assert!(!sample().format_ascii().contains("audit trail"));
598 assert!(!sample().format_compact().contains("Security:"));
599
600 let mut r = sample();
601 r.security = Some(SecurityCounts {
602 secrets_redacted: 2,
603 shell_blocked: 1,
604 ..SecurityCounts::default()
605 });
606 let ascii = r.format_ascii();
607 assert!(ascii.contains("2 secrets kept out of context"), "{ascii}");
608 assert!(ascii.contains("1 risky command blocked"), "{ascii}");
609 assert!(ascii.contains("signed audit trail intact"), "{ascii}");
610 let compact = r.format_compact();
611 assert!(
612 compact.contains("Security: 2 secrets kept out of context, 1 risky command blocked"),
613 "{compact}"
614 );
615 assert!(!compact.contains('\n'));
616 }
617
618 #[test]
619 fn speed_is_shown_only_from_a_proof() {
620 assert!(!sample().format_ascii().contains("faster"));
621 assert!(!sample().format_compact().contains("Speed:"));
622
623 let mut r = sample();
624 r.speed = Some(SpeedHeadline {
625 faster_pct: 41.2,
626 measured_on: "2026-09-25".into(),
627 tasks: 12,
628 runs: 3,
629 model: "gpt-4o-mini".into(),
630 });
631 let ascii = r.format_ascii();
632 assert!(
633 ascii.contains("41% faster model answers with lean-ctx"),
634 "{ascii}"
635 );
636 assert!(
637 ascii.contains("measured 2026-09-25 · 12 tasks × 3 runs"),
638 "{ascii}"
639 );
640 let width_of = |needle: &str| {
642 ascii
643 .lines()
644 .find(|l| l.contains(needle))
645 .map(crate::core::theme::visual_len)
646 };
647 assert_eq!(width_of("faster"), width_of("Wrapped"), "{ascii}");
648 assert_eq!(width_of("measured 2026"), width_of("Wrapped"), "{ascii}");
649 let compact = r.format_compact();
650 assert!(
651 compact.contains("Speed: model answered 41% faster with lean-ctx context"),
652 "{compact}"
653 );
654 }
655}