Skip to main content

lean_ctx/core/gain/
mod.rs

1pub mod bridge_status;
2#[allow(dead_code)]
3pub mod gain_score;
4#[allow(dead_code)]
5pub mod live_pricing;
6pub mod model_pricing;
7pub mod stream_savings;
8pub mod task_classifier;
9
10use serde::{Deserialize, Serialize};
11
12use crate::core::a2a::cost_attribution::CostStore;
13use crate::core::gain::gain_score::GainScore;
14use crate::core::gain::model_pricing::{ModelPricing, ModelQuote};
15use crate::core::gain::stream_savings::StreamSavings;
16use crate::core::gain::task_classifier::{TaskCategory, TaskClassifier};
17use crate::core::heatmap::HeatMap;
18use crate::core::stats::StatsStore;
19
20#[derive(Clone)]
21pub struct GainEngine {
22    pub stats: StatsStore,
23    pub costs: CostStore,
24    pub heatmap: HeatMap,
25    pub pricing: ModelPricing,
26    pub events: Vec<crate::core::events::LeanCtxEvent>,
27    pub session: Option<crate::core::session::SessionState>,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct GainSummary {
32    pub model: ModelQuote,
33    pub total_commands: u64,
34    pub input_tokens: u64,
35    pub output_tokens: u64,
36    pub tokens_saved: u64,
37    /// Tokens removed from traffic whose output lean-ctx controls.
38    #[serde(default)]
39    pub effective_input_tokens: u64,
40    #[serde(default)]
41    pub effective_output_tokens: u64,
42    #[serde(default)]
43    pub effective_tokens_saved: u64,
44    /// Compression percentage over compressible traffic only.
45    #[serde(default)]
46    pub effective_compression_pct: f64,
47    /// Reduction percentage over all recorded traffic, including passthrough.
48    #[serde(default)]
49    pub total_reduction_pct: f64,
50    pub gain_rate_pct: f64,
51    /// Fixed per-turn context lean-ctx injects (tool schemas + server
52    /// instructions + rules block). On a provider WITHOUT prompt caching this
53    /// rides — and is re-billed on — every turn, so the net bill impact is
54    /// `tokens_saved − injected_overhead_tokens_per_turn × turns`. Note that
55    /// `tokens_saved` / `gain_rate_pct` are measured against lean-ctx-touched
56    /// traffic (their denominator), not the full provider bill (GitHub #361).
57    #[serde(default)]
58    pub injected_overhead_tokens_per_turn: u64,
59    /// Provider turns (requests) the proxy actually saw carry the injected
60    /// prefix. `0` when the proxy is not in the request path, in which case the
61    /// net figure below collapses to the gross `tokens_saved` (we cannot count
62    /// turns we never observed, and we refuse to guess).
63    #[serde(default)]
64    pub turns: u64,
65    /// `injected_overhead_tokens_per_turn × turns` — the total fixed context tax
66    /// re-billed across the run on a provider without prompt caching.
67    #[serde(default)]
68    pub injected_overhead_total_tokens: u64,
69    /// The honest bill impact: `tokens_saved − injected_overhead_total_tokens`.
70    /// Signed, because on a non-caching rail a short run can legitimately go
71    /// net-negative until savings outgrow the per-turn injection.
72    #[serde(default)]
73    pub net_tokens_saved: i64,
74    /// Configured fixed-context budget (`[context] budget_tokens`); 0 disables
75    /// the check (#964). Surfaced so `gain` can flag a bloated injected prefix.
76    #[serde(default)]
77    pub injected_overhead_budget_tokens: u64,
78    /// Whether `injected_overhead_tokens_per_turn` exceeds a non-zero budget (#964).
79    #[serde(default)]
80    pub over_budget: bool,
81    pub avoided_usd: f64,
82    /// Bill-weighted savings split by provider token stream (#1191).
83    #[serde(default)]
84    pub stream_savings: StreamSavings,
85    /// Estimated grid energy avoided (Wh) by keeping `tokens_saved` out of context.
86    pub energy_wh: f64,
87    /// Estimated CO₂-equivalent avoided (grams), derived from `energy_wh`.
88    pub co2_grams: f64,
89    pub tool_spend_usd: f64,
90    pub roi: Option<f64>,
91    pub score: GainScore,
92    #[serde(skip_serializing_if = "Option::is_none", default)]
93    pub daemon_hint: Option<String>,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct TaskGainRow {
98    pub category: TaskCategory,
99    pub commands: u64,
100    pub tokens_saved: u64,
101    pub tool_calls: u64,
102    pub tool_spend_usd: f64,
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct FileGainRow {
107    pub path: String,
108    pub access_count: u32,
109    pub tokens_saved: u64,
110    pub compression_pct: f32,
111}
112
113/// Navigability (0–100) of the project containing the current working dir, from
114/// the persisted Code Health report. `None` when not in a project or the engine
115/// has not computed health yet — the gain score then falls back to its legacy
116/// four-component weighting so users are never penalised (#1086).
117fn current_project_navigability() -> Option<u32> {
118    let root = crate::core::config::Config::find_project_root()?;
119    crate::core::code_health::persist::load(&root).map(|h| h.score.score)
120}
121
122impl GainEngine {
123    pub fn load() -> Self {
124        Self {
125            // Aggregate across split data dirs so the gain score, cost view and
126            // net-of-injection line agree with the hero headline (#500).
127            stats: crate::core::stats::load_for_display(),
128            costs: crate::core::a2a::cost_attribution::CostStore::load(),
129            heatmap: crate::core::heatmap::HeatMap::load(),
130            pricing: ModelPricing::load(),
131            events: crate::core::events::load_events_from_file(500),
132            session: crate::core::session::SessionState::load_latest(),
133        }
134    }
135
136    pub fn summary(&self, model: Option<&str>) -> GainSummary {
137        let quote = self.pricing.quote(model);
138        let total_tokens_saved = self
139            .stats
140            .total_input_tokens
141            .saturating_sub(self.stats.total_output_tokens);
142        let effective = self.stats.compression_totals();
143        let effective_tokens_saved = effective.saved_tokens();
144        let effective_compression_pct = effective.compression_pct();
145        let total_reduction_pct = self.stats.total_reduction_pct();
146        let turns = crate::core::context_overhead::observed_turns();
147        let (first_inject, reread) = self.stats.stream_savings(turns);
148        let injected_overhead_tokens_per_turn =
149            crate::core::context_overhead::ContextOverhead::cached().total_tokens() as u64;
150        let bounce_tokens = crate::core::bounce_tracker::global()
151            .lock()
152            .unwrap_or_else(std::sync::PoisonError::into_inner)
153            .total_wasted_tokens() as u64;
154        let stream_savings = StreamSavings::calculate(
155            first_inject,
156            reread,
157            injected_overhead_tokens_per_turn,
158            turns,
159            bounce_tokens,
160            quote.cost,
161        );
162        let avoided_usd = stream_savings.net_usd_saved;
163        let tool_spend_usd = self.costs.total_cost().max(0.0);
164        let roi = if tool_spend_usd > 0.0 {
165            Some(avoided_usd / tool_spend_usd)
166        } else {
167            None
168        };
169        let score = GainScore::compute(
170            &self.stats,
171            &self.costs,
172            &self.pricing,
173            model,
174            current_project_navigability(),
175        );
176        // is_daemon_running() is cross-platform; the old #[cfg(not(unix))] = None
177        // branch suppressed daemon state on Windows. See #576.
178        let daemon_hint = if crate::daemon::is_daemon_running() {
179            None
180        } else {
181            Some(
182                "daemon not running — stats tracked locally (lean-ctx serve -d for full tracking)"
183                    .to_string(),
184            )
185        };
186        // Reconcile to the real bill: the proxy is the only component that sees
187        // every provider turn, so its persisted request count is the honest
188        // multiplier for the per-turn injection tax (GitHub #361). The math is
189        // shared with the verified savings ledger/ROI (#685).
190        let (injected_overhead_total_tokens, net_tokens_saved) =
191            crate::core::context_overhead::net_of_injection(
192                effective_tokens_saved,
193                injected_overhead_tokens_per_turn,
194                turns,
195            );
196        // Budget awareness (#964): flag when the fixed per-turn prefix outgrows
197        // the configured `[context] budget_tokens` (shared knob with `doctor
198        // overhead`). 0 disables the check.
199        let injected_overhead_budget_tokens =
200            crate::core::config::Config::load().context_budget_tokens_effective() as u64;
201        let over_budget = injected_overhead_budget_tokens > 0
202            && injected_overhead_tokens_per_turn > injected_overhead_budget_tokens;
203        GainSummary {
204            model: quote,
205            total_commands: self.stats.total_commands,
206            input_tokens: self.stats.total_input_tokens,
207            output_tokens: self.stats.total_output_tokens,
208            tokens_saved: total_tokens_saved,
209            effective_input_tokens: effective.input_tokens,
210            effective_output_tokens: effective.output_tokens,
211            effective_tokens_saved,
212            effective_compression_pct,
213            total_reduction_pct,
214            gain_rate_pct: effective_compression_pct,
215            injected_overhead_tokens_per_turn,
216            turns,
217            injected_overhead_total_tokens,
218            net_tokens_saved,
219            injected_overhead_budget_tokens,
220            over_budget,
221            avoided_usd,
222            stream_savings,
223            energy_wh: crate::core::energy::wh_for_tokens(effective_tokens_saved),
224            co2_grams: crate::core::energy::co2_grams_for_tokens(effective_tokens_saved),
225            tool_spend_usd,
226            roi,
227            score,
228            daemon_hint,
229        }
230    }
231
232    pub fn gain_score(&self, model: Option<&str>) -> GainScore {
233        GainScore::compute(
234            &self.stats,
235            &self.costs,
236            &self.pricing,
237            model,
238            current_project_navigability(),
239        )
240    }
241
242    pub fn task_breakdown(&self) -> Vec<TaskGainRow> {
243        use std::collections::HashMap;
244
245        let mut by_cat: HashMap<TaskCategory, TaskGainRow> = HashMap::new();
246
247        for (cmd_key, st) in &self.stats.commands {
248            let cat = TaskClassifier::classify_command_key(cmd_key);
249            let row = by_cat.entry(cat).or_insert(TaskGainRow {
250                category: cat,
251                commands: 0,
252                tokens_saved: 0,
253                tool_calls: 0,
254                tool_spend_usd: 0.0,
255            });
256            row.commands += st.count;
257            row.tokens_saved += st.input_tokens.saturating_sub(st.output_tokens);
258        }
259
260        for (tool, tc) in &self.costs.tools {
261            let cat = TaskClassifier::classify_tool(tool);
262            let row = by_cat.entry(cat).or_insert(TaskGainRow {
263                category: cat,
264                commands: 0,
265                tokens_saved: 0,
266                tool_calls: 0,
267                tool_spend_usd: 0.0,
268            });
269            row.tool_calls += tc.total_calls;
270            row.tool_spend_usd += tc.cost_usd;
271        }
272
273        let mut out: Vec<TaskGainRow> = by_cat.into_values().collect();
274        out.sort_by_key(|x| std::cmp::Reverse(x.tokens_saved));
275        out
276    }
277
278    pub fn heatmap_gains(&self, limit: usize) -> Vec<FileGainRow> {
279        let mut items: Vec<_> = self.heatmap.entries.values().collect();
280        items.sort_by_key(|x| std::cmp::Reverse(x.total_tokens_saved));
281        items.truncate(limit);
282        items
283            .into_iter()
284            .map(|e| FileGainRow {
285                path: e.path.clone(),
286                access_count: e.access_count,
287                tokens_saved: e.total_tokens_saved,
288                compression_pct: e.avg_compression_ratio * 100.0,
289            })
290            .collect()
291    }
292}