Skip to main content

lean_ctx/core/
wrapped.rs

1use crate::core::session::SessionState;
2use crate::core::stats;
3
4pub struct WrappedReport {
5    pub period: String,
6    pub tokens_saved: u64,
7    pub tokens_input: u64,
8    pub cost_avoided_usd: f64,
9    pub total_commands: u64,
10    pub sessions_count: usize,
11    pub top_commands: Vec<(String, u64, f64)>,
12    pub compression_rate_pct: f64,
13    pub files_touched: u64,
14    pub daily_savings: Vec<u64>,
15    /// Tokens netted out of `tokens_saved` because a compressed read later bounced to a
16    /// full re-read (G7). Sourced from the persistent savings ledger for the period.
17    pub bounce_tokens: u64,
18    /// Resolved pricing model key used to value the saved tokens (e.g. "claude-3.5-sonnet").
19    pub model_key: String,
20    /// True when no model could be resolved and a blended fallback price was used.
21    /// Surfaced everywhere so an estimate is never presented as a precise figure.
22    pub pricing_estimated: bool,
23    /// Estimated percentile rank among lean-ctx users (0-100). Based on tokens saved.
24    /// None if insufficient data or user hasn't opted into community metrics.
25    pub percentile: Option<u8>,
26}
27
28impl WrappedReport {
29    pub fn generate(period: &str) -> Self {
30        let store = stats::load_for_display();
31        let sessions = SessionState::list_sessions();
32
33        let (gross_tokens_saved, tokens_input, total_commands) = match period {
34            "week" => aggregate_recent_stats(&store, 7),
35            "month" => aggregate_recent_stats(&store, 30),
36            _ => (
37                store
38                    .total_input_tokens
39                    .saturating_sub(store.total_output_tokens),
40                store.total_input_tokens,
41                store.total_commands,
42            ),
43        };
44
45        // G7: net out compressed->full bounce recorded in the persistent ledger for this
46        // period, so the headline is the *realized* saving, not a gross upper bound.
47        let period_days = match period {
48            "week" => Some(7),
49            "month" => Some(30),
50            _ => None,
51        };
52        let bounce_tokens = crate::core::savings_ledger::bounce_tokens(period_days);
53        let tokens_saved = gross_tokens_saved.saturating_sub(bounce_tokens);
54
55        let env_model = std::env::var("LEAN_CTX_MODEL")
56            .or_else(|_| std::env::var("LCTX_MODEL"))
57            .ok();
58        let pricing = crate::core::gain::model_pricing::ModelPricing::load();
59        let quote = pricing.quote(env_model.as_deref());
60        // Saved tokens would have been *input* tokens, so value them at the input rate.
61        // Still an upper bound on the bounce-adjusted figure: it ignores prompt-cache
62        // discounts. We never inflate beyond this.
63        let cost_avoided_usd = quote.cost.estimate_usd(tokens_saved, 0, 0, 0);
64        let pricing_estimated = matches!(
65            quote.match_kind,
66            crate::core::gain::model_pricing::PricingMatchKind::Fallback
67        );
68        let model_key = quote.model_key.clone();
69
70        let sessions_count = match period {
71            "week" => count_recent_sessions(&sessions, 7),
72            "month" => count_recent_sessions(&sessions, 30),
73            _ => sessions.len(),
74        };
75
76        let mut top_commands: Vec<(String, u64, f64)> = store
77            .commands
78            .iter()
79            .map(|(cmd, stats)| {
80                let saved = stats.input_tokens.saturating_sub(stats.output_tokens);
81                let pct = if stats.input_tokens > 0 {
82                    saved as f64 / stats.input_tokens as f64 * 100.0
83                } else {
84                    0.0
85                };
86                (cmd.clone(), saved, pct)
87            })
88            .collect();
89        top_commands.sort_by_key(|x| std::cmp::Reverse(x.1));
90        top_commands.truncate(5);
91
92        let agent_id = crate::core::agent_identity::current_agent_id();
93        let verified_net = crate::core::savings_ledger::roi_report(agent_id).net_saved_tokens;
94        let compression_rate_pct = if tokens_input > 0 {
95            let v = verified_net as f64 / tokens_input as f64 * 100.0;
96            if v > 0.0 {
97                v
98            } else {
99                tokens_saved as f64 / tokens_input as f64 * 100.0
100            }
101        } else {
102            0.0
103        };
104
105        let files_touched: u64 = sessions.iter().map(|s| s.tool_calls as u64).sum();
106
107        let day_saved = |d: &stats::DayStats| d.input_tokens.saturating_sub(d.output_tokens);
108        let take_recent = |n: usize| -> Vec<u64> {
109            store
110                .daily
111                .iter()
112                .rev()
113                .take(n)
114                .collect::<Vec<_>>()
115                .into_iter()
116                .rev()
117                .map(day_saved)
118                .collect()
119        };
120        let daily_savings = match period {
121            "week" => take_recent(7),
122            "month" => take_recent(30),
123            _ => store.daily.iter().map(day_saved).collect(),
124        };
125
126        WrappedReport {
127            period: period.to_string(),
128            tokens_saved,
129            tokens_input,
130            cost_avoided_usd,
131            total_commands,
132            sessions_count,
133            top_commands,
134            compression_rate_pct,
135            files_touched,
136            daily_savings,
137            bounce_tokens,
138            model_key,
139            pricing_estimated,
140            percentile: estimate_percentile(tokens_saved),
141        }
142    }
143
144    /// One-line, conservative explanation of how the headline numbers were derived.
145    /// Reused by the ASCII footer, the compact summary, and the SVG share card so the
146    /// figure is always explainable and never over-claimed.
147    pub fn methodology_line(&self) -> String {
148        let price = if self.pricing_estimated {
149            format!(
150                "{} blended fallback price (set LEAN_CTX_MODEL for exact)",
151                self.model_key
152            )
153        } else {
154            format!("{} input price", self.model_key)
155        };
156        let basis = if self.bounce_tokens > 0 {
157            format!(
158                "measured original - compressed - {} bounce tokens",
159                format_tokens(self.bounce_tokens)
160            )
161        } else {
162            "measured original - compressed tokens".to_string()
163        };
164        format!("Savings = {basis}; USD is an upper bound at {price}")
165    }
166
167    /// Renders a premium, shareable "Wrapped" card. Colors are emitted only when
168    /// stdout is a TTY (see `theme::no_color`), so piping to a file or social post
169    /// yields clean copy-pasteable ASCII.
170    #[allow(clippy::many_single_char_names)] // ANSI formatting helpers: t/r/b/d
171    pub fn format_ascii(&self) -> String {
172        use crate::core::theme;
173
174        let cfg = crate::core::config::Config::load();
175        let t = theme::load_theme(&cfg.theme);
176        let rst = theme::rst();
177        let bold = theme::bold();
178        let dim = theme::dim();
179
180        let period_label = match self.period.as_str() {
181            "week" => format!("Week of {}", chrono::Utc::now().format("%b %d, %Y")),
182            "month" => format!("Month of {}", chrono::Utc::now().format("%B %Y")),
183            _ => "All Time".to_string(),
184        };
185
186        let w = 52;
187        let side = t.box_side();
188        let box_line = |content: &str| -> String {
189            let padded = theme::pad_right(content, w);
190            format!("  {side}{padded}{side}")
191        };
192
193        let mut out: Vec<String> = Vec::new();
194        out.push(String::new());
195        out.push(format!("  {}", t.box_top(w)));
196        out.push(box_line(""));
197        out.push(box_line(&format!(
198            "   {icon}  {brand} {accent}Wrapped{rst}  {dim}· {period_label}{rst}",
199            icon = t.header_icon(),
200            brand = t.brand_title(),
201            accent = t.accent.fg(),
202        )));
203        out.push(box_line(""));
204        out.push(format!("  {}", t.box_mid(w)));
205        out.push(box_line(""));
206
207        // Primary metric row: tokens saved + cost avoided + commands.
208        let kw = 16;
209        let sc = t.success.fg();
210        let c2 = t.secondary.fg();
211        let c3 = t.warning.fg();
212        let c4 = t.accent.fg();
213
214        let v1 = theme::pad_right(
215            &format!("{sc}{bold}{}{rst}", format_tokens(self.tokens_saved)),
216            kw,
217        );
218        let v2 = theme::pad_right(&format!("{c4}{bold}${:.2}{rst}", self.cost_avoided_usd), kw);
219        let v3 = theme::pad_right(&format!("{c3}{bold}{}{rst}", self.total_commands), kw);
220        out.push(box_line(&format!("   {v1}{v2}{v3}")));
221        let l1 = theme::pad_right(&format!("{dim}tokens saved{rst}"), kw);
222        let l2 = theme::pad_right(&format!("{dim}cost avoided{rst}"), kw);
223        let l3 = theme::pad_right(&format!("{dim}commands{rst}"), kw);
224        out.push(box_line(&format!("   {l1}{l2}{l3}")));
225        out.push(box_line(""));
226
227        // Secondary metric row: sessions + compression + energy saved (estimate, same
228        // methodology as the community /metrics page so local & shared figures reconcile).
229        let v4 = theme::pad_right(&format!("{c2}{bold}{}{rst}", self.sessions_count), kw);
230        let v5 = theme::pad_right(
231            &format!(
232                "{pc}{bold}{:.1}%{rst}",
233                self.compression_rate_pct,
234                pc = t.pct_color(self.compression_rate_pct),
235            ),
236            kw,
237        );
238        let energy = crate::core::energy::format_for_tokens(self.tokens_saved);
239        let v6 = theme::pad_right(&format!("{c4}{bold}{energy}{rst}"), kw);
240        out.push(box_line(&format!("   {v4}{v5}{v6}")));
241        let l4 = theme::pad_right(&format!("{dim}sessions{rst}"), kw);
242        let l5 = theme::pad_right(&format!("{dim}compression{rst}"), kw);
243        let l6 = theme::pad_right(&format!("{dim}energy saved{rst}"), kw);
244        out.push(box_line(&format!("   {l4}{l5}{l6}")));
245        out.push(box_line(""));
246
247        // Trend sparkline (only when there is at least a little history).
248        if self.daily_savings.iter().filter(|v| **v > 0).count() >= 2 {
249            let spark = t.gradient_sparkline(&self.daily_savings);
250            out.push(box_line(&format!("   {dim}trend{rst}  {spark}")));
251            out.push(box_line(""));
252        }
253
254        // Top commands (truncated to fit the inner box width).
255        if !self.top_commands.is_empty() {
256            let prefix_visible = 8; // "   top  "
257            let budget = w.saturating_sub(prefix_visible);
258            let mut top_str = self
259                .top_commands
260                .iter()
261                .take(3)
262                .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
263                .collect::<Vec<_>>()
264                .join("  ·  ");
265            if top_str.chars().count() > budget {
266                let truncated: String = top_str.chars().take(budget.saturating_sub(1)).collect();
267                top_str = format!("{truncated}…");
268            }
269            out.push(format!("  {}", t.box_mid(w)));
270            out.push(box_line(&format!(
271                "   {m}top{rst}  {top_str}",
272                m = t.muted.fg()
273            )));
274        }
275
276        out.push(format!("  {}", t.box_bottom(w)));
277        out.push(format!(
278            "    {dim}\"Your AI saw only what mattered.\"{rst}   {accent}leanctx.com{rst}",
279            accent = t.accent.fg(),
280        ));
281        let est_marker = if self.pricing_estimated {
282            " (est.)"
283        } else {
284            ""
285        };
286        out.push(format!(
287            "    {dim}model {model}{est_marker}  ·  USD = upper bound{rst}",
288            model = self.model_key,
289        ));
290        out.push(String::new());
291
292        out.join("\n")
293    }
294
295    pub fn format_compact(&self) -> String {
296        let saved_str = format_tokens(self.tokens_saved);
297        let cost_str = format!("${:.2}", self.cost_avoided_usd);
298        let top_str = self
299            .top_commands
300            .iter()
301            .take(3)
302            .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
303            .collect::<Vec<_>>()
304            .join(" | ");
305
306        let est_marker = if self.pricing_estimated {
307            " (est.)"
308        } else {
309            ""
310        };
311        format!(
312            "WRAPPED [{}]: {} tok saved, {} avoided{}, {} sessions, {} cmds | Top: {} | Compression: {:.1}% | Energy: {} | model={}",
313            self.period,
314            saved_str,
315            cost_str,
316            est_marker,
317            self.sessions_count,
318            self.total_commands,
319            top_str,
320            self.compression_rate_pct,
321            crate::core::energy::format_for_tokens(self.tokens_saved),
322            self.model_key,
323        )
324    }
325}
326
327fn aggregate_recent_stats(store: &stats::StatsStore, days: usize) -> (u64, u64, u64) {
328    let recent_days: Vec<&stats::DayStats> = store.daily.iter().rev().take(days).collect();
329
330    let input: u64 = recent_days.iter().map(|d| d.input_tokens).sum();
331    let output: u64 = recent_days.iter().map(|d| d.output_tokens).sum();
332    let commands: u64 = recent_days.iter().map(|d| d.commands).sum();
333    let saved = input.saturating_sub(output);
334
335    (saved, input, commands)
336}
337
338fn count_recent_sessions(sessions: &[crate::core::session::SessionSummary], days: i64) -> usize {
339    let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
340    sessions.iter().filter(|s| s.updated_at > cutoff).count()
341}
342
343pub fn format_tokens(tokens: u64) -> String {
344    if tokens >= 1_000_000_000_000 {
345        format!("{:.2}T", tokens as f64 / 1_000_000_000_000.0)
346    } else if tokens >= 1_000_000_000 {
347        format!("{:.2}B", tokens as f64 / 1_000_000_000.0)
348    } else if tokens >= 1_000_000 {
349        format!("{:.1}M", tokens as f64 / 1_000_000.0)
350    } else if tokens >= 1_000 {
351        format!("{:.1}K", tokens as f64 / 1_000.0)
352    } else {
353        format!("{tokens}")
354    }
355}
356
357/// Domain-separated proof signed when recovering control of an existing card.
358/// Both client and cloud server must use these exact bytes.
359pub fn edit_token_recovery_message(card_id: &str, nonce: &str) -> String {
360    format!("lean-ctx:wrapped-edit-token-recovery:v1\ncard_id:{card_id}\nnonce:{nonce}")
361}
362
363/// Estimate the user's percentile rank among lean-ctx users based on tokens saved.
364/// Uses a rough distribution model derived from community metrics data.
365/// Returns None if insufficient data (< 1000 tokens saved).
366fn estimate_percentile(tokens_saved: u64) -> Option<u8> {
367    if tokens_saved < 1_000 {
368        return None;
369    }
370    // Rough percentile thresholds based on community data distribution
371    // (log-normal distribution of savings across users)
372    let pct = if tokens_saved >= 100_000_000 {
373        99
374    } else if tokens_saved >= 50_000_000 {
375        97
376    } else if tokens_saved >= 10_000_000 {
377        95
378    } else if tokens_saved >= 5_000_000 {
379        90
380    } else if tokens_saved >= 1_000_000 {
381        80
382    } else if tokens_saved >= 500_000 {
383        70
384    } else if tokens_saved >= 100_000 {
385        55
386    } else if tokens_saved >= 50_000 {
387        40
388    } else if tokens_saved >= 10_000 {
389        25
390    } else {
391        10
392    };
393    Some(pct)
394}
395
396#[cfg(test)]
397pub mod tests {
398    use super::*;
399
400    fn sample() -> WrappedReport {
401        WrappedReport {
402            period: "all".into(),
403            tokens_saved: 348_300_000,
404            tokens_input: 580_000_000,
405            cost_avoided_usd: 870.81,
406            total_commands: 17_055,
407            sessions_count: 67,
408            top_commands: vec![
409                ("ctx_search".into(), 100, 60.0),
410                ("cli_grep".into(), 80, 85.0),
411                ("cli_shell".into(), 50, 37.0),
412            ],
413            compression_rate_pct: 60.2,
414            files_touched: 1_234,
415            daily_savings: vec![10, 50, 30, 30, 80, 80, 20, 5, 5, 40, 60, 40, 5, 50, 15],
416            bounce_tokens: 0,
417            model_key: "claude-3.5-sonnet".into(),
418            pricing_estimated: false,
419            percentile: Some(95),
420        }
421    }
422
423    #[test]
424    fn edit_token_recovery_proof_is_domain_separated_and_stable() {
425        assert_eq!(
426            edit_token_recovery_message("card-1", "nonce-1"),
427            "lean-ctx:wrapped-edit-token-recovery:v1\ncard_id:card-1\nnonce:nonce-1"
428        );
429    }
430
431    fn is_box_line(l: &str) -> bool {
432        let trimmed = l.trim_start();
433        ["│", "╭", "├", "╰"].iter().any(|c| trimmed.starts_with(c))
434    }
435
436    #[test]
437    fn wrapped_ascii_box_lines_have_uniform_width() {
438        // `format_ascii` calls `Config::load()` for the theme; serialize against
439        // tests that mutate the data-dir / env (they hold the same lock via
440        // `isolated_data_dir`) so a parallel run can't swap the config — and thus
441        // the theme's box glyphs / brand width — out from under us mid-format.
442        let _env = crate::core::data_dir::test_env_lock();
443        // In the test runner, stdout is not a TTY, so colors are auto-disabled.
444        let out = sample().format_ascii();
445        let widths: Vec<usize> = out
446            .lines()
447            .filter(|l| is_box_line(l))
448            .map(crate::core::theme::visual_len)
449            .collect();
450        assert!(widths.len() >= 4, "expected several box lines:\n{out}");
451        let first = widths[0];
452        for w in &widths {
453            assert_eq!(*w, first, "box line widths must be uniform:\n{out}");
454        }
455    }
456
457    #[test]
458    fn wrapped_ascii_includes_brand_and_metrics() {
459        let out = sample().format_ascii();
460        assert!(out.contains("leanctx.com"), "missing brand footer:\n{out}");
461        assert!(out.contains("Wrapped"));
462        assert!(out.contains("tokens saved"));
463        assert!(out.contains("compression"));
464    }
465
466    #[test]
467    fn wrapped_ascii_truncates_overlong_top_line() {
468        let out = sample().format_ascii();
469        // No box line may exceed the others (top row must be truncated to fit).
470        let max = out
471            .lines()
472            .filter(|l| is_box_line(l))
473            .map(crate::core::theme::visual_len)
474            .max()
475            .unwrap_or(0);
476        let min = out
477            .lines()
478            .filter(|l| is_box_line(l))
479            .map(crate::core::theme::visual_len)
480            .min()
481            .unwrap_or(0);
482        assert_eq!(max, min, "top line overflowed the box:\n{out}");
483    }
484
485    #[test]
486    fn wrapped_compact_is_single_line_summary() {
487        let out = sample().format_compact();
488        assert!(out.starts_with("WRAPPED"), "compact summary changed: {out}");
489        assert!(out.contains("Compression:"));
490        assert!(
491            out.contains("model="),
492            "compact must name the pricing model: {out}"
493        );
494    }
495
496    #[test]
497    fn methodology_is_conservative_and_explainable() {
498        let m = sample().methodology_line();
499        assert!(
500            m.contains("upper bound"),
501            "must state it is an upper bound: {m}"
502        );
503        assert!(m.contains("claude-3.5-sonnet"), "must name the model: {m}");
504    }
505
506    #[test]
507    fn ascii_footer_surfaces_model_and_upper_bound() {
508        let out = sample().format_ascii();
509        assert!(
510            out.contains("model claude-3.5-sonnet"),
511            "footer must name model:\n{out}"
512        );
513        assert!(
514            out.contains("USD = upper bound"),
515            "footer must flag upper bound:\n{out}"
516        );
517    }
518
519    #[test]
520    fn estimated_pricing_is_flagged() {
521        let mut r = sample();
522        r.pricing_estimated = true;
523        assert!(
524            r.format_ascii().contains("(est.)"),
525            "estimated price must show (est.)"
526        );
527        assert!(r.format_compact().contains("(est.)"));
528        assert!(r.methodology_line().contains("fallback"));
529    }
530}