Skip to main content

lean_ctx/core/
solution_tracker.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::{Mutex, OnceLock};
4
5use chrono::Local;
6use serde::{Deserialize, Serialize};
7
8const STORE_FILE: &str = "solution_tracker.json";
9
10#[derive(Default, Deserialize, Serialize)]
11struct SolutionStore {
12    decisions_total: u64,
13    decisions_stdlib: u64,
14    decisions_native: u64,
15    decisions_reuse: u64,
16    decisions_yagni: u64,
17    decisions_oneline: u64,
18    decisions_debt: u64,
19    loc_added: u64,
20    loc_removed: u64,
21    loc_net_saved: i64,
22    output_tokens_baseline: u64,
23    output_tokens_actual: u64,
24    #[serde(default)]
25    daily_records: Vec<DayRecord>,
26}
27
28#[derive(Clone, Deserialize, Serialize)]
29struct DayRecord {
30    date: String,
31    decisions: u64,
32    loc_net_saved: i64,
33}
34
35#[derive(Clone, Serialize)]
36pub struct SolutionSnapshot {
37    pub decisions_total: u64,
38    pub decisions_by_kind: HashMap<String, u64>,
39    pub loc_added: u64,
40    pub loc_removed: u64,
41    pub loc_net_saved: i64,
42    pub output_tokens_baseline: u64,
43    pub output_tokens_actual: u64,
44    pub output_reduction_pct: u8,
45}
46
47fn store_path() -> PathBuf {
48    crate::core::paths::data_dir()
49        .unwrap_or_else(|_| {
50            std::env::var_os("HOME")
51                .map(PathBuf::from)
52                .unwrap_or_else(|| PathBuf::from("."))
53                .join(".lean-ctx")
54        })
55        .join(STORE_FILE)
56}
57
58static STORE: OnceLock<Mutex<SolutionStore>> = OnceLock::new();
59
60fn store() -> &'static Mutex<SolutionStore> {
61    STORE.get_or_init(|| {
62        let loaded = std::fs::read(store_path())
63            .ok()
64            .and_then(|contents| serde_json::from_slice(&contents).ok())
65            .unwrap_or_default();
66        Mutex::new(loaded)
67    })
68}
69
70/// Reload the store from disk. Called by `snapshot()` so the dashboard
71/// daemon sees changes written by short-lived `hook observe` processes.
72fn reload_from_disk() {
73    if let Ok(bytes) = std::fs::read(store_path()) {
74        if let Ok(fresh) = serde_json::from_slice::<SolutionStore>(&bytes) {
75            if let Ok(mut guard) = store().lock() {
76                *guard = fresh;
77            }
78        }
79    }
80}
81
82fn flush(store: &SolutionStore) {
83    let path = store_path();
84    let Some(parent) = path.parent() else {
85        return;
86    };
87    if std::fs::create_dir_all(parent).is_err() {
88        return;
89    }
90
91    let Ok(contents) = serde_json::to_vec(store) else {
92        return;
93    };
94    let temporary = path.with_extension(format!("tmp-{}", std::process::id()));
95    if std::fs::write(&temporary, contents).is_ok() {
96        let _ = std::fs::rename(temporary, path);
97    }
98}
99
100fn with_store<F: FnOnce(&mut SolutionStore)>(f: F) {
101    let mut store = store()
102        .lock()
103        .unwrap_or_else(std::sync::PoisonError::into_inner);
104    f(&mut store);
105    flush(&store);
106}
107
108fn current_day_record(store: &mut SolutionStore) -> &mut DayRecord {
109    let date = Local::now().format("%F").to_string();
110    if let Some(index) = store
111        .daily_records
112        .iter()
113        .position(|record| record.date == date)
114    {
115        return &mut store.daily_records[index];
116    }
117
118    store.daily_records.push(DayRecord {
119        date,
120        decisions: 0,
121        loc_net_saved: 0,
122    });
123    store
124        .daily_records
125        .last_mut()
126        .expect("daily record was just inserted")
127}
128
129pub fn record_decision(kind: &str) {
130    with_store(|store| {
131        store.decisions_total = store.decisions_total.saturating_add(1);
132        let record = current_day_record(store);
133        record.decisions = record.decisions.saturating_add(1);
134        match kind {
135            "stdlib" => store.decisions_stdlib = store.decisions_stdlib.saturating_add(1),
136            "native" => store.decisions_native = store.decisions_native.saturating_add(1),
137            "reuse" => store.decisions_reuse = store.decisions_reuse.saturating_add(1),
138            "yagni" => store.decisions_yagni = store.decisions_yagni.saturating_add(1),
139            "oneline" => store.decisions_oneline = store.decisions_oneline.saturating_add(1),
140            "debt" => store.decisions_debt = store.decisions_debt.saturating_add(1),
141            _ => {}
142        }
143    });
144}
145
146pub fn record_loc_change(added: u64, removed: u64) {
147    with_store(|store| {
148        store.loc_added = store.loc_added.saturating_add(added);
149        store.loc_removed = store.loc_removed.saturating_add(removed);
150        let added = i64::try_from(added).unwrap_or(i64::MAX);
151        let removed = i64::try_from(removed).unwrap_or(i64::MAX);
152        let loc_net_saved = removed.saturating_sub(added);
153        store.loc_net_saved = store.loc_net_saved.saturating_add(loc_net_saved);
154        let record = current_day_record(store);
155        record.loc_net_saved = record.loc_net_saved.saturating_add(loc_net_saved);
156    });
157}
158
159pub fn trend_7d() -> Vec<(String, u64, i64)> {
160    reload_from_disk();
161    let store = store()
162        .lock()
163        .unwrap_or_else(std::sync::PoisonError::into_inner);
164    let mut records = store.daily_records.clone();
165    records.sort_unstable_by(|left, right| left.date.cmp(&right.date));
166    let mut trend: Vec<_> = records
167        .into_iter()
168        .rev()
169        .take(7)
170        .map(|record| (record.date, record.decisions, record.loc_net_saved))
171        .collect();
172    trend.reverse();
173    trend
174}
175
176pub fn record_output_tokens(baseline: u64, actual: u64) {
177    with_store(|store| {
178        store.output_tokens_baseline = store.output_tokens_baseline.saturating_add(baseline);
179        store.output_tokens_actual = store.output_tokens_actual.saturating_add(actual);
180    });
181}
182
183pub fn snapshot() -> SolutionSnapshot {
184    reload_from_disk();
185    let store = store()
186        .lock()
187        .unwrap_or_else(std::sync::PoisonError::into_inner);
188    let mut decisions_by_kind = HashMap::new();
189    if store.decisions_stdlib > 0 {
190        decisions_by_kind.insert("stdlib".to_owned(), store.decisions_stdlib);
191    }
192    if store.decisions_native > 0 {
193        decisions_by_kind.insert("native".to_owned(), store.decisions_native);
194    }
195    if store.decisions_reuse > 0 {
196        decisions_by_kind.insert("reuse".to_owned(), store.decisions_reuse);
197    }
198    if store.decisions_yagni > 0 {
199        decisions_by_kind.insert("yagni".to_owned(), store.decisions_yagni);
200    }
201    if store.decisions_oneline > 0 {
202        decisions_by_kind.insert("oneline".to_owned(), store.decisions_oneline);
203    }
204    if store.decisions_debt > 0 {
205        decisions_by_kind.insert("debt".to_owned(), store.decisions_debt);
206    }
207    let output_reduction_pct = store
208        .output_tokens_baseline
209        .checked_sub(store.output_tokens_actual)
210        .and_then(|reduction| reduction.checked_mul(100))
211        .and_then(|reduction| reduction.checked_div(store.output_tokens_baseline))
212        .and_then(|reduction| u8::try_from(reduction).ok())
213        .unwrap_or(0);
214
215    SolutionSnapshot {
216        decisions_total: store.decisions_total,
217        decisions_by_kind,
218        loc_added: store.loc_added,
219        loc_removed: store.loc_removed,
220        loc_net_saved: store.loc_net_saved,
221        output_tokens_baseline: store.output_tokens_baseline,
222        output_tokens_actual: store.output_tokens_actual,
223        output_reduction_pct,
224    }
225}
226
227pub fn reset() {
228    with_store(|store| *store = SolutionStore::default());
229}
230
231pub fn gain_summary() -> String {
232    let snapshot = snapshot();
233    format!(
234        "{} decisions; {} net LOC saved; {}% output-token reduction",
235        snapshot.decisions_total, snapshot.loc_net_saved, snapshot.output_reduction_pct
236    )
237}