Skip to main content

lean_ctx/core/
wrapped.rs

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    /// Tokens netted out of `tokens_saved` because a compressed read later bounced to a
18    /// full re-read (G7). Sourced from the persistent savings ledger for the period.
19    pub bounce_tokens: u64,
20    /// Resolved pricing model key used to value the saved tokens (e.g. "claude-3.5-sonnet").
21    pub model_key: String,
22    /// True when no model could be resolved and a blended fallback price was used.
23    /// Surfaced everywhere so an estimate is never presented as a precise figure.
24    pub pricing_estimated: bool,
25    /// Estimated percentile rank among lean-ctx users (0-100). Based on tokens saved.
26    /// None if insufficient data or user hasn't opted into community metrics.
27    pub percentile: Option<u8>,
28    /// ✓ measured security events of the period, re-counted from the signed
29    /// audit trail. `None` when nothing happened or the chain fails
30    /// verification — an unproven count is never shown.
31    pub security: Option<SecurityCounts>,
32    /// The latest `lean-ctx prove speed` result, only when its signature
33    /// verifies and lean-ctx was faster without answering worse. Speed is
34    /// never extrapolated from live sessions.
35    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        // G7: net out compressed->full bounce recorded in the persistent ledger for this
56        // period, so the headline is the *realized* saving, not a gross upper bound.
57        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        // Saved tokens would have been *input* tokens, so value them at the input rate.
75        // Still an upper bound on the bounce-adjusted figure: it ignores prompt-cache
76        // discounts. We never inflate beyond this.
77        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    /// The period's security events in the contract's wording, one phrase per
161    /// kind; empty when there is nothing verified to show.
162    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    /// One-line, conservative explanation of how the headline numbers were derived.
170    /// Reused by the ASCII footer, the compact summary, and the SVG share card so the
171    /// figure is always explainable and never over-claimed.
172    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    /// Renders a premium, shareable "Wrapped" card. Colors are emitted only when
193    /// stdout is a TTY (see `theme::no_color`), so piping to a file or social post
194    /// yields clean copy-pasteable ASCII.
195    #[allow(clippy::many_single_char_names)] // ANSI formatting helpers: t/r/b/d
196    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        // 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        // Speed: only from a signed A/B proof (`lean-ctx prove speed`).
292        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        // Top commands (truncated to fit the inner box width).
303        if !self.top_commands.is_empty() {
304            let prefix_visible = 8; // "   top  "
305            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
419/// Estimate the user's percentile rank among lean-ctx users based on tokens saved.
420/// Uses a rough distribution model derived from community metrics data.
421/// Returns None if insufficient data (< 1000 tokens saved).
422fn estimate_percentile(tokens_saved: u64) -> Option<u8> {
423    if tokens_saved < 1_000 {
424        return None;
425    }
426    // Rough percentile thresholds based on community data distribution
427    // (log-normal distribution of savings across users)
428    let pct = if tokens_saved >= 100_000_000 {
429        99
430    } else if tokens_saved >= 50_000_000 {
431        97
432    } else if tokens_saved >= 10_000_000 {
433        95
434    } else if tokens_saved >= 5_000_000 {
435        90
436    } else if tokens_saved >= 1_000_000 {
437        80
438    } else if tokens_saved >= 500_000 {
439        70
440    } else if tokens_saved >= 100_000 {
441        55
442    } else if tokens_saved >= 50_000 {
443        40
444    } else if tokens_saved >= 10_000 {
445        25
446    } else {
447        10
448    };
449    Some(pct)
450}
451
452#[cfg(test)]
453pub mod tests {
454    use super::*;
455
456    fn sample() -> WrappedReport {
457        WrappedReport {
458            period: "all".into(),
459            tokens_saved: 348_300_000,
460            tokens_input: 580_000_000,
461            cost_avoided_usd: 870.81,
462            total_commands: 17_055,
463            sessions_count: 67,
464            top_commands: vec![
465                ("ctx_search".into(), 100, 60.0),
466                ("cli_grep".into(), 80, 85.0),
467                ("cli_shell".into(), 50, 37.0),
468            ],
469            compression_rate_pct: 60.2,
470            files_touched: 1_234,
471            daily_savings: vec![10, 50, 30, 30, 80, 80, 20, 5, 5, 40, 60, 40, 5, 50, 15],
472            bounce_tokens: 0,
473            model_key: "claude-3.5-sonnet".into(),
474            pricing_estimated: false,
475            percentile: Some(95),
476            security: None,
477            speed: None,
478        }
479    }
480
481    fn is_box_line(l: &str) -> bool {
482        let trimmed = l.trim_start();
483        ["│", "╭", "├", "╰"].iter().any(|c| trimmed.starts_with(c))
484    }
485
486    #[test]
487    fn wrapped_ascii_box_lines_have_uniform_width() {
488        // `format_ascii` calls `Config::load()` for the theme; serialize against
489        // tests that mutate the data-dir / env (they hold the same lock via
490        // `isolated_data_dir`) so a parallel run can't swap the config — and thus
491        // the theme's box glyphs / brand width — out from under us mid-format.
492        let _env = crate::core::data_dir::test_env_lock();
493        // In the test runner, stdout is not a TTY, so colors are auto-disabled.
494        let out = sample().format_ascii();
495        let widths: Vec<usize> = out
496            .lines()
497            .filter(|l| is_box_line(l))
498            .map(crate::core::theme::visual_len)
499            .collect();
500        assert!(widths.len() >= 4, "expected several box lines:\n{out}");
501        let first = widths[0];
502        for w in &widths {
503            assert_eq!(*w, first, "box line widths must be uniform:\n{out}");
504        }
505    }
506
507    #[test]
508    fn wrapped_ascii_includes_brand_and_metrics() {
509        let out = sample().format_ascii();
510        assert!(out.contains("leanctx.com"), "missing brand footer:\n{out}");
511        assert!(out.contains("Wrapped"));
512        assert!(out.contains("tokens saved"));
513        assert!(out.contains("compression"));
514    }
515
516    #[test]
517    fn wrapped_ascii_truncates_overlong_top_line() {
518        let out = sample().format_ascii();
519        // No box line may exceed the others (top row must be truncated to fit).
520        let max = out
521            .lines()
522            .filter(|l| is_box_line(l))
523            .map(crate::core::theme::visual_len)
524            .max()
525            .unwrap_or(0);
526        let min = out
527            .lines()
528            .filter(|l| is_box_line(l))
529            .map(crate::core::theme::visual_len)
530            .min()
531            .unwrap_or(0);
532        assert_eq!(max, min, "top line overflowed the box:\n{out}");
533    }
534
535    #[test]
536    fn wrapped_compact_is_single_line_summary() {
537        let out = sample().format_compact();
538        assert!(out.starts_with("WRAPPED"), "compact summary changed: {out}");
539        assert!(out.contains("Compression:"));
540        assert!(
541            out.contains("model="),
542            "compact must name the pricing model: {out}"
543        );
544    }
545
546    #[test]
547    fn methodology_is_conservative_and_explainable() {
548        let m = sample().methodology_line();
549        assert!(
550            m.contains("upper bound"),
551            "must state it is an upper bound: {m}"
552        );
553        assert!(m.contains("claude-3.5-sonnet"), "must name the model: {m}");
554    }
555
556    #[test]
557    fn ascii_footer_surfaces_model_and_upper_bound() {
558        let out = sample().format_ascii();
559        assert!(
560            out.contains("model claude-3.5-sonnet"),
561            "footer must name model:\n{out}"
562        );
563        assert!(
564            out.contains("USD = upper bound"),
565            "footer must flag upper bound:\n{out}"
566        );
567    }
568
569    #[test]
570    fn estimated_pricing_is_flagged() {
571        let mut r = sample();
572        r.pricing_estimated = true;
573        assert!(
574            r.format_ascii().contains("(est.)"),
575            "estimated price must show (est.)"
576        );
577        assert!(r.format_compact().contains("(est.)"));
578        assert!(r.methodology_line().contains("fallback"));
579    }
580
581    #[test]
582    fn verified_security_is_shown_and_absent_security_is_not() {
583        assert!(!sample().format_ascii().contains("audit trail"));
584        assert!(!sample().format_compact().contains("Security:"));
585
586        let mut r = sample();
587        r.security = Some(SecurityCounts {
588            secrets_redacted: 2,
589            shell_blocked: 1,
590            ..SecurityCounts::default()
591        });
592        let ascii = r.format_ascii();
593        assert!(ascii.contains("2 secrets kept out of context"), "{ascii}");
594        assert!(ascii.contains("1 risky command blocked"), "{ascii}");
595        assert!(ascii.contains("signed audit trail intact"), "{ascii}");
596        let compact = r.format_compact();
597        assert!(
598            compact.contains("Security: 2 secrets kept out of context, 1 risky command blocked"),
599            "{compact}"
600        );
601        assert!(!compact.contains('\n'));
602    }
603
604    #[test]
605    fn speed_is_shown_only_from_a_proof() {
606        assert!(!sample().format_ascii().contains("faster"));
607        assert!(!sample().format_compact().contains("Speed:"));
608
609        let mut r = sample();
610        r.speed = Some(SpeedHeadline {
611            faster_pct: 41.2,
612            measured_on: "2026-09-25".into(),
613            tasks: 12,
614            runs: 3,
615            model: "gpt-4o-mini".into(),
616        });
617        let ascii = r.format_ascii();
618        assert!(
619            ascii.contains("41% faster model answers with lean-ctx"),
620            "{ascii}"
621        );
622        assert!(
623            ascii.contains("measured 2026-09-25 · 12 tasks × 3 runs"),
624            "{ascii}"
625        );
626        // The speed rows keep the box closed: same width as the title row.
627        let width_of = |needle: &str| {
628            ascii
629                .lines()
630                .find(|l| l.contains(needle))
631                .map(crate::core::theme::visual_len)
632        };
633        assert_eq!(width_of("faster"), width_of("Wrapped"), "{ascii}");
634        assert_eq!(width_of("measured 2026"), width_of("Wrapped"), "{ascii}");
635        let compact = r.format_compact();
636        assert!(
637            compact.contains("Speed: model answered 41% faster with lean-ctx context"),
638            "{compact}"
639        );
640    }
641}