1use lean_ctx::core::{
5 savings_ledger,
6 value_gate::{self, ValueAssessment},
7};
8
9#[rustfmt::skip]
10#[derive(serde::Serialize)]
11struct Report {
12 period: String,
13 total_tasks: usize,
14 accepted_tasks: usize,
15 tokens_processed: u64,
16 tokens_saved: u64,
17 compression_percent: f64,
18 estimated_cost_usd: f64,
19 actual_cost_usd: f64,
20 total_savings_usd: f64,
21 savings_percent: f64,
22 cpao_usd: Option<f64>,
23 etpao: Option<u64>,
24 top_sources: Vec<(String, u64)>,
25}
26
27#[rustfmt::skip]
28pub(crate) fn cmd_savings_report(args: &[String]) {
29 if args
30 .iter()
31 .any(|arg| matches!(arg.as_str(), "-h" | "--help"))
32 {
33 usage();
34 return;
35 }
36 let Some((period, format)) = parse(args) else {
37 eprintln!("savings: expected --period day|week|month|all and --format table|json|markdown");
38 usage();
39 std::process::exit(2);
40 };
41 let report = build_report(
42 period,
43 savings_ledger::all_events(),
44 value_gate::store().recent(usize::MAX),
45 );
46 match format {
47 "json" => println!(
48 "{}",
49 serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".into())
50 ),
51 "markdown" => print_markdown(&report),
52 _ => print!("{}", table(&report)),
53 }
54}
55
56#[rustfmt::skip]
57fn build_report(
58 period: &str,
59 events: Vec<savings_ledger::SavingsEvent>,
60 tasks: Vec<ValueAssessment>,
61) -> Report {
62 let cutoff = days(period).map(|d| lean_ctx_time::UtcDateTime::now() - lean_ctx_time::Duration::days(d));
63 let events: Vec<_> = events
64 .into_iter()
65 .filter(|e| e.mechanism == savings_ledger::MECHANISM_COMPRESSION)
66 .filter(|e| in_period(&e.ts, cutoff))
67 .collect();
68 let tasks: Vec<_> = tasks
69 .into_iter()
70 .filter(|t| in_period(&t.timestamp, cutoff))
71 .collect();
72 let raw = events.iter().map(|e| e.baseline_tokens).sum::<u64>();
73 let actual = events.iter().map(|e| e.actual_tokens).sum::<u64>();
74 let saved = raw.saturating_sub(actual);
75 let estimated = events
76 .iter()
77 .map(|e| e.baseline_tokens as f64 * e.unit_price_per_m_usd / 1e6)
78 .sum();
79 let actual_cost = events
80 .iter()
81 .map(|e| e.actual_tokens as f64 * e.unit_price_per_m_usd / 1e6)
82 .sum();
83 let accepted = tasks.iter().filter(|t| t.outcome_accepted).count();
84 let cost_micros = tasks.iter().map(|t| t.cost_micros).sum::<u64>();
85 Report {
86 period: period.into(),
87 total_tasks: tasks.len(),
88 accepted_tasks: accepted,
89 tokens_processed: raw,
90 tokens_saved: saved,
91 compression_percent: pct(saved, raw),
92 estimated_cost_usd: estimated,
93 actual_cost_usd: actual_cost,
94 total_savings_usd: estimated - actual_cost,
95 savings_percent: pct(saved, raw),
96 cpao_usd: (accepted > 0).then_some(cost_micros as f64 / accepted as f64 / 1e6),
97 etpao: (accepted > 0).then(|| {
98 tasks.iter().map(|t| t.total_tokens).sum::<u64>() / accepted as u64
99 }),
100 top_sources: top_sources(&events),
101 }
102}
103
104#[rustfmt::skip] fn days(period: &str) -> Option<i64> { match period { "day" => Some(1), "week" => Some(7), "month" => Some(30), _ => None } }
106#[rustfmt::skip] fn period_label(period: &str) -> String { days(period).map_or_else(|| "all time".into(), |d| format!("last {d} days")) }
107#[rustfmt::skip] fn in_period(timestamp: &str, cutoff: Option<lean_ctx_time::UtcDateTime>) -> bool { cutoff.is_none_or(|cutoff| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(timestamp).map(|t| t.to_utc() >= cutoff).unwrap_or(false)) }
108#[rustfmt::skip] fn pct(value: u64, total: u64) -> f64 { if total == 0 { 0.0 } else { value as f64 * 100.0 / total as f64 } }
109#[rustfmt::skip]
110fn top_sources(events: &[savings_ledger::SavingsEvent]) -> Vec<(String, u64)> {
111 let mut out = std::collections::BTreeMap::new();
112 for event in events {
113 *out.entry(event.tool.clone()).or_insert(0) +=
114 event.baseline_tokens.saturating_sub(event.actual_tokens);
115 }
116 let mut out: Vec<_> = out.into_iter().collect();
117 out.sort_by_key(|(_, saved)| std::cmp::Reverse(*saved));
118 out.truncate(5);
119 out
120}
121fn parse(args: &[String]) -> Option<(&str, &str)> {
122 let mut period = "week";
123 let mut format = "table";
124 let mut index = 0;
125 while index < args.len() {
126 match args[index].as_str() {
127 "--period" => {
128 period = args.get(index + 1)?.as_str();
129 index += 2;
130 }
131 "--format" => {
132 format = args.get(index + 1)?.as_str();
133 index += 2;
134 }
135 _ => return None,
136 }
137 }
138 (matches!(period, "day" | "week" | "month" | "all")
139 && matches!(format, "table" | "json" | "markdown"))
140 .then_some((period, format))
141}
142fn usage() {
143 println!(
144 "Show compression savings from the local ledger.\n\nUsage: lean-ctx savings [--period <day|week|month|all>] [--format <table|json|markdown>]\n\nExamples:\n lean-ctx savings\n lean-ctx savings --period month\n lean-ctx savings --period all --format json"
145 );
146}
147#[rustfmt::skip]
148fn table(r: &Report) -> String {
149 if r.tokens_processed == 0 {
150 return format!("LeanCTX Savings Report ({})\nNo compression savings recorded for this period.\n", r.period);
151 }
152 let mut out = format!(
153 "LeanCTX Savings Report ({})\nTotal Tasks: {}\nAccepted Tasks: {} ({:.1}%)\nTokens Processed: {}\nTokens Saved (Compression): {} ({:.1}% reduction)\nEstimated Cost without LeanCTX: ${:.2}\nActual Cost with LeanCTX: ${:.2}\nTotal Savings: ${:.2} ({:.1}%)\nCPAO (Cost per Accepted Outcome): {}\nETPAO (Effective Tokens per Accepted Outcome): {}\nTop 5 Savings Sources:\n",
154 period_label(&r.period),
155 r.total_tasks,
156 r.accepted_tasks,
157 pct(r.accepted_tasks as u64, r.total_tasks as u64),
158 r.tokens_processed,
159 r.tokens_saved,
160 r.compression_percent,
161 r.estimated_cost_usd,
162 r.actual_cost_usd,
163 r.total_savings_usd,
164 r.savings_percent,
165 r.cpao_usd.map_or("n/a".into(), |v| format!("${v:.2}")),
166 r.etpao.map_or("n/a".into(), |v| v.to_string())
167 );
168 for (tool, saved) in &r.top_sources {
169 out.push_str(&format!(" {tool}: {saved} tokens\n"));
170 }
171 out
172}
173#[rustfmt::skip]
174fn print_markdown(r: &Report) {
175 if r.tokens_processed == 0 {
176 println!(
177 "# LeanCTX Savings Report ({})\n\nNo compression savings recorded for this period.",
178 r.period
179 );
180 return;
181 }
182 println!(
183 "# LeanCTX Savings Report ({})\n\n| Metric | Value |\n|---|---|\n| Total Tasks | {} |\n| Accepted Tasks | {} |\n| Tokens Processed | {} |\n| Tokens Saved (Compression) | {} ({:.1}%) |\n| Total Savings | ${:.2} |",
184 period_label(&r.period),
185 r.total_tasks,
186 r.accepted_tasks,
187 r.tokens_processed,
188 r.tokens_saved,
189 r.compression_percent,
190 r.total_savings_usd
191 );
192}
193
194#[cfg(test)] #[rustfmt::skip] mod tests { use super::*;
195 #[test] fn test_savings_calculation() {
196 assert_eq!((1_000u64).saturating_sub(600), 400);
197 assert_eq!(pct(400, 1_000), 40.0);
198 }
199 #[test] fn test_cost_estimation() {
200 assert_eq!(
201 lean_ctx::core::value_gate::cost_tracker::calculate_cost(400, 0, 0, "gpt-4o"),
202 1_000
203 );
204 }
205 #[test] fn test_period_filter() {
206 let now = lean_ctx_time::UtcDateTime::now();
207 assert!(in_period(
208 &now.to_rfc3339(),
209 Some(now - lean_ctx_time::Duration::days(1))
210 ));
211 assert!(!in_period(
212 "2000-01-01T00:00:00Z",
213 Some(now - lean_ctx_time::Duration::days(30))
214 ));
215 }
216 #[test] fn test_period_all_has_no_cutoff() {
217 assert_eq!(build_report("all", vec![], vec![]).period, "all");
218 }
219 #[test] fn test_empty_data() {
220 let r = build_report("week", vec![], vec![]);
221 assert_eq!(r.tokens_processed, 0);
222 }
223 #[test] fn test_format_table() {
224 assert!(table(&build_report("week", vec![], vec![])).contains("No compression savings"));
225 }
226 #[test] fn test_parse_rejects_missing_values_and_unknown_options() { assert!(parse(&["--period".into()]).is_none()); assert!(parse(&["--unknown".into()]).is_none()); }
227 #[test] fn test_format_json() {
228 let json = serde_json::to_string(&build_report("week", vec![], vec![])).unwrap();
229 assert!(serde_json::from_str::<serde_json::Value>(&json).is_ok());
230 }
231}