Skip to main content

lean_ctx/core/
wrapped.rs

1use crate::core::security_events::SecurityCounts;
2use crate::core::session::SessionState;
3use crate::core::stats;
4
5pub struct WrappedReport {
6    pub period: String,
7    pub tokens_saved: u64,
8    pub tokens_input: u64,
9    pub cost_avoided_usd: f64,
10    pub total_commands: u64,
11    pub sessions_count: usize,
12    pub top_commands: Vec<(String, u64, f64)>,
13    pub compression_rate_pct: f64,
14    pub files_touched: u64,
15    pub daily_savings: Vec<u64>,
16    /// Tokens netted out of `tokens_saved` because a compressed read later bounced to a
17    /// full re-read (G7). Sourced from the persistent savings ledger for the period.
18    pub bounce_tokens: u64,
19    /// Resolved pricing model key used to value the saved tokens (e.g. "claude-3.5-sonnet").
20    pub model_key: String,
21    /// True when no model could be resolved and a blended fallback price was used.
22    /// Surfaced everywhere so an estimate is never presented as a precise figure.
23    pub pricing_estimated: bool,
24    /// Estimated percentile rank among lean-ctx users (0-100). Based on tokens saved.
25    /// None if insufficient data or user hasn't opted into community metrics.
26    pub percentile: Option<u8>,
27    /// ✓ measured security events of the period, re-counted from the signed
28    /// audit trail. `None` when nothing happened or the chain fails
29    /// verification — an unproven count is never shown.
30    pub security: Option<SecurityCounts>,
31}
32
33impl WrappedReport {
34    pub fn generate(period: &str) -> Self {
35        let store = stats::load_for_display();
36        let sessions = SessionState::list_sessions();
37
38        let (gross_tokens_saved, tokens_input, total_commands) = match period {
39            "week" => aggregate_recent_stats(&store, 7),
40            "month" => aggregate_recent_stats(&store, 30),
41            _ => (
42                store
43                    .total_input_tokens
44                    .saturating_sub(store.total_output_tokens),
45                store.total_input_tokens,
46                store.total_commands,
47            ),
48        };
49
50        // G7: net out compressed->full bounce recorded in the persistent ledger for this
51        // period, so the headline is the *realized* saving, not a gross upper bound.
52        let period_days = match period {
53            "week" => Some(7),
54            "month" => Some(30),
55            _ => None,
56        };
57        let bounce_tokens = crate::core::savings_ledger::bounce_tokens(period_days);
58        let tokens_saved = gross_tokens_saved.saturating_sub(bounce_tokens);
59        let security = crate::core::value::proof::verified_security_since(period_days.map(|d| {
60            lean_ctx_time::UtcDateTime::now() - lean_ctx_time::Duration::days(i64::from(d))
61        }))
62        .filter(|c| !c.is_empty());
63
64        let env_model = std::env::var("LEAN_CTX_MODEL")
65            .or_else(|_| std::env::var("LCTX_MODEL"))
66            .ok();
67        let pricing = crate::core::gain::model_pricing::ModelPricing::load();
68        let quote = pricing.quote(env_model.as_deref());
69        // Saved tokens would have been *input* tokens, so value them at the input rate.
70        // Still an upper bound on the bounce-adjusted figure: it ignores prompt-cache
71        // discounts. We never inflate beyond this.
72        let cost_avoided_usd = quote.cost.estimate_usd(tokens_saved, 0, 0, 0);
73        let pricing_estimated = matches!(
74            quote.match_kind,
75            crate::core::gain::model_pricing::PricingMatchKind::Fallback
76        );
77        let model_key = quote.model_key.clone();
78
79        let sessions_count = match period {
80            "week" => count_recent_sessions(&sessions, 7),
81            "month" => count_recent_sessions(&sessions, 30),
82            _ => sessions.len(),
83        };
84
85        let mut top_commands: Vec<(String, u64, f64)> = store
86            .commands
87            .iter()
88            .map(|(cmd, stats)| {
89                let saved = stats.input_tokens.saturating_sub(stats.output_tokens);
90                let pct = if stats.input_tokens > 0 {
91                    saved as f64 / stats.input_tokens as f64 * 100.0
92                } else {
93                    0.0
94                };
95                (cmd.clone(), saved, pct)
96            })
97            .collect();
98        top_commands.sort_by_key(|x| std::cmp::Reverse(x.1));
99        top_commands.truncate(5);
100
101        let agent_id = crate::core::agent_identity::current_agent_id();
102        let verified_net = crate::core::savings_ledger::roi_report(agent_id).net_saved_tokens;
103        let compression_rate_pct = if tokens_input > 0 {
104            let v = verified_net as f64 / tokens_input as f64 * 100.0;
105            if v > 0.0 {
106                v
107            } else {
108                tokens_saved as f64 / tokens_input as f64 * 100.0
109            }
110        } else {
111            0.0
112        };
113
114        let files_touched: u64 = sessions.iter().map(|s| s.tool_calls as u64).sum();
115
116        let day_saved = |d: &stats::DayStats| d.input_tokens.saturating_sub(d.output_tokens);
117        let take_recent = |n: usize| -> Vec<u64> {
118            store
119                .daily
120                .iter()
121                .rev()
122                .take(n)
123                .collect::<Vec<_>>()
124                .into_iter()
125                .rev()
126                .map(day_saved)
127                .collect()
128        };
129        let daily_savings = match period {
130            "week" => take_recent(7),
131            "month" => take_recent(30),
132            _ => store.daily.iter().map(day_saved).collect(),
133        };
134
135        WrappedReport {
136            period: period.to_string(),
137            tokens_saved,
138            tokens_input,
139            cost_avoided_usd,
140            total_commands,
141            sessions_count,
142            top_commands,
143            compression_rate_pct,
144            files_touched,
145            daily_savings,
146            bounce_tokens,
147            model_key,
148            pricing_estimated,
149            percentile: estimate_percentile(tokens_saved),
150            security,
151        }
152    }
153
154    /// The period's security events in the contract's wording, one phrase per
155    /// kind; empty when there is nothing verified to show.
156    pub fn security_phrases(&self) -> Vec<String> {
157        self.security
158            .as_ref()
159            .map(crate::core::value::format::security_phrases)
160            .unwrap_or_default()
161    }
162
163    /// One-line, conservative explanation of how the headline numbers were derived.
164    /// Reused by the ASCII footer, the compact summary, and the SVG share card so the
165    /// figure is always explainable and never over-claimed.
166    pub fn methodology_line(&self) -> String {
167        let price = if self.pricing_estimated {
168            format!(
169                "{} blended fallback price (set LEAN_CTX_MODEL for exact)",
170                self.model_key
171            )
172        } else {
173            format!("{} input price", self.model_key)
174        };
175        let basis = if self.bounce_tokens > 0 {
176            format!(
177                "measured original - compressed - {} bounce tokens",
178                format_tokens(self.bounce_tokens)
179            )
180        } else {
181            "measured original - compressed tokens".to_string()
182        };
183        format!("Savings = {basis}; USD is an upper bound at {price}")
184    }
185
186    /// Renders a premium, shareable "Wrapped" card. Colors are emitted only when
187    /// stdout is a TTY (see `theme::no_color`), so piping to a file or social post
188    /// yields clean copy-pasteable ASCII.
189    #[allow(clippy::many_single_char_names)] // ANSI formatting helpers: t/r/b/d
190    pub fn format_ascii(&self) -> String {
191        use crate::core::theme;
192
193        let cfg = crate::core::config::Config::load();
194        let t = theme::load_theme(&cfg.theme);
195        let rst = theme::rst();
196        let bold = theme::bold();
197        let dim = theme::dim();
198
199        let period_label = match self.period.as_str() {
200            "week" => format!(
201                "Week of {}",
202                lean_ctx_time::UtcDateTime::now().format("%b %d, %Y")
203            ),
204            "month" => format!(
205                "Month of {}",
206                lean_ctx_time::UtcDateTime::now().format("%B %Y")
207            ),
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        // Primary metric row: tokens saved + cost avoided + commands.
233        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        // Secondary metric row: sessions + compression + energy saved (estimate, same
253        // methodology as the community /metrics page so local & shared figures reconcile).
254        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        // Trend sparkline (only when there is at least a little history).
273        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        // Security: only counts re-derived from the verified audit trail.
280        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        // Top commands (truncated to fit the inner box width).
292        if !self.top_commands.is_empty() {
293            let prefix_visible = 8; // "   top  "
294            let budget = w.saturating_sub(prefix_visible);
295            let mut top_str = self
296                .top_commands
297                .iter()
298                .take(3)
299                .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
300                .collect::<Vec<_>>()
301                .join("  ·  ");
302            if top_str.chars().count() > budget {
303                let truncated: String = top_str.chars().take(budget.saturating_sub(1)).collect();
304                top_str = format!("{truncated}…");
305            }
306            out.push(format!("  {}", t.box_mid(w)));
307            out.push(box_line(&format!(
308                "   {m}top{rst}  {top_str}",
309                m = t.muted.fg()
310            )));
311        }
312
313        out.push(format!("  {}", t.box_bottom(w)));
314        out.push(format!(
315            "    {dim}\"Your AI saw only what mattered.\"{rst}   {accent}leanctx.com{rst}",
316            accent = t.accent.fg(),
317        ));
318        let est_marker = if self.pricing_estimated {
319            " (est.)"
320        } else {
321            ""
322        };
323        out.push(format!(
324            "    {dim}model {model}{est_marker}  ·  USD = upper bound{rst}",
325            model = self.model_key,
326        ));
327        out.push(String::new());
328
329        out.join("\n")
330    }
331
332    pub fn format_compact(&self) -> String {
333        let saved_str = format_tokens(self.tokens_saved);
334        let cost_str = format!("${:.2}", self.cost_avoided_usd);
335        let top_str = self
336            .top_commands
337            .iter()
338            .take(3)
339            .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
340            .collect::<Vec<_>>()
341            .join(" | ");
342
343        let est_marker = if self.pricing_estimated {
344            " (est.)"
345        } else {
346            ""
347        };
348        let security = self.security_phrases();
349        let security_str = if security.is_empty() {
350            String::new()
351        } else {
352            format!(
353                " | Security: {} (audit trail verified)",
354                security.join(", ")
355            )
356        };
357        format!(
358            "WRAPPED [{}]: {} tok saved, {} avoided{}, {} sessions, {} cmds | Top: {} | Compression: {:.1}% | Energy: {}{} | model={}",
359            self.period,
360            saved_str,
361            cost_str,
362            est_marker,
363            self.sessions_count,
364            self.total_commands,
365            top_str,
366            self.compression_rate_pct,
367            crate::core::energy::format_for_tokens(self.tokens_saved),
368            security_str,
369            self.model_key,
370        )
371    }
372}
373
374fn aggregate_recent_stats(store: &stats::StatsStore, days: usize) -> (u64, u64, u64) {
375    let recent_days: Vec<&stats::DayStats> = store.daily.iter().rev().take(days).collect();
376
377    let input: u64 = recent_days.iter().map(|d| d.input_tokens).sum();
378    let output: u64 = recent_days.iter().map(|d| d.output_tokens).sum();
379    let commands: u64 = recent_days.iter().map(|d| d.commands).sum();
380    let saved = input.saturating_sub(output);
381
382    (saved, input, commands)
383}
384
385fn count_recent_sessions(sessions: &[crate::core::session::SessionSummary], days: i64) -> usize {
386    let cutoff = lean_ctx_time::UtcDateTime::now() - lean_ctx_time::Duration::days(days);
387    sessions.iter().filter(|s| s.updated_at > cutoff).count()
388}
389
390pub fn format_tokens(tokens: u64) -> String {
391    if tokens >= 1_000_000_000_000 {
392        format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
393    } else if tokens >= 1_000_000_000 {
394        format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
395    } else if tokens >= 1_000_000 {
396        format!("{:.1}M", tokens as f64 / 1_000_000.0)
397    } else if tokens >= 1_000 {
398        format!("{:.1}K", tokens as f64 / 1_000.0)
399    } else {
400        format!("{tokens}")
401    }
402}
403
404/// Estimate the user's percentile rank among lean-ctx users based on tokens saved.
405/// Uses a rough distribution model derived from community metrics data.
406/// Returns None if insufficient data (< 1000 tokens saved).
407fn estimate_percentile(tokens_saved: u64) -> Option<u8> {
408    if tokens_saved < 1_000 {
409        return None;
410    }
411    // Rough percentile thresholds based on community data distribution
412    // (log-normal distribution of savings across users)
413    let pct = if tokens_saved >= 100_000_000 {
414        99
415    } else if tokens_saved >= 50_000_000 {
416        97
417    } else if tokens_saved >= 10_000_000 {
418        95
419    } else if tokens_saved >= 5_000_000 {
420        90
421    } else if tokens_saved >= 1_000_000 {
422        80
423    } else if tokens_saved >= 500_000 {
424        70
425    } else if tokens_saved >= 100_000 {
426        55
427    } else if tokens_saved >= 50_000 {
428        40
429    } else if tokens_saved >= 10_000 {
430        25
431    } else {
432        10
433    };
434    Some(pct)
435}
436
437#[cfg(test)]
438pub mod tests {
439    use super::*;
440
441    fn sample() -> WrappedReport {
442        WrappedReport {
443            period: "all".into(),
444            tokens_saved: 348_300_000,
445            tokens_input: 580_000_000,
446            cost_avoided_usd: 870.81,
447            total_commands: 17_055,
448            sessions_count: 67,
449            top_commands: vec![
450                ("ctx_search".into(), 100, 60.0),
451                ("cli_grep".into(), 80, 85.0),
452                ("cli_shell".into(), 50, 37.0),
453            ],
454            compression_rate_pct: 60.2,
455            files_touched: 1_234,
456            daily_savings: vec![10, 50, 30, 30, 80, 80, 20, 5, 5, 40, 60, 40, 5, 50, 15],
457            bounce_tokens: 0,
458            model_key: "claude-3.5-sonnet".into(),
459            pricing_estimated: false,
460            percentile: Some(95),
461            security: None,
462        }
463    }
464
465    fn is_box_line(l: &str) -> bool {
466        let trimmed = l.trim_start();
467        ["│", "╭", "├", "╰"].iter().any(|c| trimmed.starts_with(c))
468    }
469
470    #[test]
471    fn wrapped_ascii_box_lines_have_uniform_width() {
472        // `format_ascii` calls `Config::load()` for the theme; serialize against
473        // tests that mutate the data-dir / env (they hold the same lock via
474        // `isolated_data_dir`) so a parallel run can't swap the config — and thus
475        // the theme's box glyphs / brand width — out from under us mid-format.
476        let _env = crate::core::data_dir::test_env_lock();
477        // In the test runner, stdout is not a TTY, so colors are auto-disabled.
478        let out = sample().format_ascii();
479        let widths: Vec<usize> = out
480            .lines()
481            .filter(|l| is_box_line(l))
482            .map(crate::core::theme::visual_len)
483            .collect();
484        assert!(widths.len() >= 4, "expected several box lines:\n{out}");
485        let first = widths[0];
486        for w in &widths {
487            assert_eq!(*w, first, "box line widths must be uniform:\n{out}");
488        }
489    }
490
491    #[test]
492    fn wrapped_ascii_includes_brand_and_metrics() {
493        let out = sample().format_ascii();
494        assert!(out.contains("leanctx.com"), "missing brand footer:\n{out}");
495        assert!(out.contains("Wrapped"));
496        assert!(out.contains("tokens saved"));
497        assert!(out.contains("compression"));
498    }
499
500    #[test]
501    fn wrapped_ascii_truncates_overlong_top_line() {
502        let out = sample().format_ascii();
503        // No box line may exceed the others (top row must be truncated to fit).
504        let max = out
505            .lines()
506            .filter(|l| is_box_line(l))
507            .map(crate::core::theme::visual_len)
508            .max()
509            .unwrap_or(0);
510        let min = out
511            .lines()
512            .filter(|l| is_box_line(l))
513            .map(crate::core::theme::visual_len)
514            .min()
515            .unwrap_or(0);
516        assert_eq!(max, min, "top line overflowed the box:\n{out}");
517    }
518
519    #[test]
520    fn wrapped_compact_is_single_line_summary() {
521        let out = sample().format_compact();
522        assert!(out.starts_with("WRAPPED"), "compact summary changed: {out}");
523        assert!(out.contains("Compression:"));
524        assert!(
525            out.contains("model="),
526            "compact must name the pricing model: {out}"
527        );
528    }
529
530    #[test]
531    fn methodology_is_conservative_and_explainable() {
532        let m = sample().methodology_line();
533        assert!(
534            m.contains("upper bound"),
535            "must state it is an upper bound: {m}"
536        );
537        assert!(m.contains("claude-3.5-sonnet"), "must name the model: {m}");
538    }
539
540    #[test]
541    fn ascii_footer_surfaces_model_and_upper_bound() {
542        let out = sample().format_ascii();
543        assert!(
544            out.contains("model claude-3.5-sonnet"),
545            "footer must name model:\n{out}"
546        );
547        assert!(
548            out.contains("USD = upper bound"),
549            "footer must flag upper bound:\n{out}"
550        );
551    }
552
553    #[test]
554    fn estimated_pricing_is_flagged() {
555        let mut r = sample();
556        r.pricing_estimated = true;
557        assert!(
558            r.format_ascii().contains("(est.)"),
559            "estimated price must show (est.)"
560        );
561        assert!(r.format_compact().contains("(est.)"));
562        assert!(r.methodology_line().contains("fallback"));
563    }
564
565    #[test]
566    fn verified_security_is_shown_and_absent_security_is_not() {
567        assert!(!sample().format_ascii().contains("audit trail"));
568        assert!(!sample().format_compact().contains("Security:"));
569
570        let mut r = sample();
571        r.security = Some(SecurityCounts {
572            secrets_redacted: 2,
573            shell_blocked: 1,
574            ..SecurityCounts::default()
575        });
576        let ascii = r.format_ascii();
577        assert!(ascii.contains("2 secrets kept out of context"), "{ascii}");
578        assert!(ascii.contains("1 risky command blocked"), "{ascii}");
579        assert!(ascii.contains("signed audit trail intact"), "{ascii}");
580        let compact = r.format_compact();
581        assert!(
582            compact.contains("Security: 2 secrets kept out of context, 1 risky command blocked"),
583            "{compact}"
584        );
585        assert!(!compact.contains('\n'));
586    }
587}