Skip to main content

lean_ctx/core/gain/
mod.rs

1pub mod bridge_status;
2pub mod gain_score;
3pub mod model_pricing;
4pub mod task_classifier;
5
6use serde::{Deserialize, Serialize};
7
8use crate::core::a2a::cost_attribution::CostStore;
9use crate::core::gain::gain_score::GainScore;
10use crate::core::gain::model_pricing::{ModelPricing, ModelQuote};
11use crate::core::gain::task_classifier::{TaskCategory, TaskClassifier};
12use crate::core::heatmap::HeatMap;
13use crate::core::stats::StatsStore;
14
15#[derive(Clone)]
16pub struct GainEngine {
17    pub stats: StatsStore,
18    pub costs: CostStore,
19    pub heatmap: HeatMap,
20    pub pricing: ModelPricing,
21    pub events: Vec<crate::core::events::LeanCtxEvent>,
22    pub session: Option<crate::core::session::SessionState>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct GainSummary {
27    pub model: ModelQuote,
28    pub total_commands: u64,
29    pub input_tokens: u64,
30    pub output_tokens: u64,
31    pub tokens_saved: u64,
32    pub gain_rate_pct: f64,
33    /// Fixed per-turn context lean-ctx injects (tool schemas + server
34    /// instructions + rules block). On a provider WITHOUT prompt caching this
35    /// rides — and is re-billed on — every turn, so the net bill impact is
36    /// `tokens_saved − injected_overhead_tokens_per_turn × turns`. Note that
37    /// `tokens_saved` / `gain_rate_pct` are measured against lean-ctx-touched
38    /// traffic (their denominator), not the full provider bill (GitHub #361).
39    #[serde(default)]
40    pub injected_overhead_tokens_per_turn: u64,
41    /// Provider turns (requests) the proxy actually saw carry the injected
42    /// prefix. `0` when the proxy is not in the request path, in which case the
43    /// net figure below collapses to the gross `tokens_saved` (we cannot count
44    /// turns we never observed, and we refuse to guess).
45    #[serde(default)]
46    pub turns: u64,
47    /// `injected_overhead_tokens_per_turn × turns` — the total fixed context tax
48    /// re-billed across the run on a provider without prompt caching.
49    #[serde(default)]
50    pub injected_overhead_total_tokens: u64,
51    /// The honest bill impact: `tokens_saved − injected_overhead_total_tokens`.
52    /// Signed, because on a non-caching rail a short run can legitimately go
53    /// net-negative until savings outgrow the per-turn injection.
54    #[serde(default)]
55    pub net_tokens_saved: i64,
56    pub avoided_usd: f64,
57    /// Estimated grid energy avoided (Wh) by keeping `tokens_saved` out of context.
58    pub energy_wh: f64,
59    /// Estimated CO₂-equivalent avoided (grams), derived from `energy_wh`.
60    pub co2_grams: f64,
61    pub tool_spend_usd: f64,
62    pub roi: Option<f64>,
63    pub score: GainScore,
64    #[serde(skip_serializing_if = "Option::is_none", default)]
65    pub daemon_hint: Option<String>,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct TaskGainRow {
70    pub category: TaskCategory,
71    pub commands: u64,
72    pub tokens_saved: u64,
73    pub tool_calls: u64,
74    pub tool_spend_usd: f64,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct FileGainRow {
79    pub path: String,
80    pub access_count: u32,
81    pub tokens_saved: u64,
82    pub compression_pct: f32,
83}
84
85impl GainEngine {
86    pub fn load() -> Self {
87        Self {
88            stats: crate::core::stats::load(),
89            costs: crate::core::a2a::cost_attribution::CostStore::load(),
90            heatmap: crate::core::heatmap::HeatMap::load(),
91            pricing: ModelPricing::load(),
92            events: crate::core::events::load_events_from_file(500),
93            session: crate::core::session::SessionState::load_latest(),
94        }
95    }
96
97    pub fn summary(&self, model: Option<&str>) -> GainSummary {
98        let quote = self.pricing.quote(model);
99        let tokens_saved = self
100            .stats
101            .total_input_tokens
102            .saturating_sub(self.stats.total_output_tokens);
103        let gain_rate_pct = if self.stats.total_input_tokens > 0 {
104            tokens_saved as f64 / self.stats.total_input_tokens as f64 * 100.0
105        } else {
106            0.0
107        };
108        let avoided_usd = quote.cost.estimate_usd(tokens_saved, 0, 0, 0);
109        let tool_spend_usd = self.costs.total_cost().max(0.0);
110        let roi = if tool_spend_usd > 0.0 {
111            Some(avoided_usd / tool_spend_usd)
112        } else {
113            None
114        };
115        let score = GainScore::compute(&self.stats, &self.costs, &self.pricing, model);
116        #[cfg(unix)]
117        let daemon_hint = if crate::daemon::is_daemon_running() {
118            None
119        } else {
120            Some(
121                "daemon not running — stats tracked locally (lean-ctx serve -d for full tracking)"
122                    .to_string(),
123            )
124        };
125        #[cfg(not(unix))]
126        let daemon_hint: Option<String> = None;
127        let injected_overhead_tokens_per_turn =
128            crate::core::context_overhead::ContextOverhead::cached().total_tokens() as u64;
129        // Reconcile to the real bill: the proxy is the only component that sees
130        // every provider turn, so its persisted request count is the honest
131        // multiplier for the per-turn injection tax (GitHub #361). The math is
132        // shared with the verified savings ledger/ROI (#685).
133        let turns = crate::core::context_overhead::observed_turns();
134        let (injected_overhead_total_tokens, net_tokens_saved) =
135            crate::core::context_overhead::net_of_injection(
136                tokens_saved,
137                injected_overhead_tokens_per_turn,
138                turns,
139            );
140        GainSummary {
141            model: quote,
142            total_commands: self.stats.total_commands,
143            input_tokens: self.stats.total_input_tokens,
144            output_tokens: self.stats.total_output_tokens,
145            tokens_saved,
146            gain_rate_pct,
147            injected_overhead_tokens_per_turn,
148            turns,
149            injected_overhead_total_tokens,
150            net_tokens_saved,
151            avoided_usd,
152            energy_wh: crate::core::energy::wh_for_tokens(tokens_saved),
153            co2_grams: crate::core::energy::co2_grams_for_tokens(tokens_saved),
154            tool_spend_usd,
155            roi,
156            score,
157            daemon_hint,
158        }
159    }
160
161    pub fn gain_score(&self, model: Option<&str>) -> GainScore {
162        GainScore::compute(&self.stats, &self.costs, &self.pricing, model)
163    }
164
165    pub fn task_breakdown(&self) -> Vec<TaskGainRow> {
166        use std::collections::HashMap;
167
168        let mut by_cat: HashMap<TaskCategory, TaskGainRow> = HashMap::new();
169
170        for (cmd_key, st) in &self.stats.commands {
171            let cat = TaskClassifier::classify_command_key(cmd_key);
172            let row = by_cat.entry(cat).or_insert(TaskGainRow {
173                category: cat,
174                commands: 0,
175                tokens_saved: 0,
176                tool_calls: 0,
177                tool_spend_usd: 0.0,
178            });
179            row.commands += st.count;
180            row.tokens_saved += st.input_tokens.saturating_sub(st.output_tokens);
181        }
182
183        for (tool, tc) in &self.costs.tools {
184            let cat = TaskClassifier::classify_tool(tool);
185            let row = by_cat.entry(cat).or_insert(TaskGainRow {
186                category: cat,
187                commands: 0,
188                tokens_saved: 0,
189                tool_calls: 0,
190                tool_spend_usd: 0.0,
191            });
192            row.tool_calls += tc.total_calls;
193            row.tool_spend_usd += tc.cost_usd;
194        }
195
196        let mut out: Vec<TaskGainRow> = by_cat.into_values().collect();
197        out.sort_by_key(|x| std::cmp::Reverse(x.tokens_saved));
198        out
199    }
200
201    pub fn heatmap_gains(&self, limit: usize) -> Vec<FileGainRow> {
202        let mut items: Vec<_> = self.heatmap.entries.values().collect();
203        items.sort_by_key(|x| std::cmp::Reverse(x.total_tokens_saved));
204        items.truncate(limit);
205        items
206            .into_iter()
207            .map(|e| FileGainRow {
208                path: e.path.clone(),
209                access_count: e.access_count,
210                tokens_saved: e.total_tokens_saved,
211                compression_pct: e.avg_compression_ratio * 100.0,
212            })
213            .collect()
214    }
215}