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 lean_ctx_time::LocalDateTime;
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 Some(fresh) = read_store_file() {
74        if let Ok(mut guard) = store().lock() {
75            *guard = fresh;
76        }
77    }
78}
79
80fn read_store_file() -> Option<SolutionStore> {
81    let bytes = std::fs::read(store_path()).ok()?;
82    serde_json::from_slice(&bytes).ok()
83}
84
85/// Exclusive lock on a stable companion file; released when the guard drops.
86/// Writes still happen without it if the lock cannot be taken, as before.
87fn lock_store_file() -> Option<crate::core::file_lock::FlockGuard> {
88    let lock_path = store_path().with_extension("json.lock");
89    std::fs::create_dir_all(lock_path.parent()?).ok()?;
90    let lock = std::fs::OpenOptions::new()
91        .create(true)
92        .truncate(false)
93        .read(true)
94        .write(true)
95        .open(lock_path)
96        .ok()?;
97    crate::core::file_lock::FlockGuard::exclusive(lock).ok()
98}
99
100fn flush(store: &SolutionStore) {
101    let path = store_path();
102    let Some(parent) = path.parent() else {
103        return;
104    };
105    if std::fs::create_dir_all(parent).is_err() {
106        return;
107    }
108
109    let Ok(contents) = serde_json::to_vec(store) else {
110        return;
111    };
112    let temporary = path.with_extension(format!("tmp-{}", std::process::id()));
113    if std::fs::write(&temporary, contents).is_ok() {
114        let _ = std::fs::rename(temporary, path);
115    }
116}
117
118/// Several long-lived MCP servers record into the same file. Each mutation is
119/// a locked read-modify-write so no process writes back a stale copy and
120/// drops counts the others recorded since it started.
121fn with_store<F: FnOnce(&mut SolutionStore)>(f: F) {
122    let mut store = store()
123        .lock()
124        .unwrap_or_else(std::sync::PoisonError::into_inner);
125    let _file_lock = lock_store_file();
126    if let Some(fresh) = read_store_file() {
127        *store = fresh;
128    }
129    f(&mut store);
130    flush(&store);
131}
132
133fn current_day_record(store: &mut SolutionStore) -> &mut DayRecord {
134    let date = LocalDateTime::now().format("%F").to_string();
135    if let Some(index) = store
136        .daily_records
137        .iter()
138        .position(|record| record.date == date)
139    {
140        return &mut store.daily_records[index];
141    }
142
143    store.daily_records.push(DayRecord {
144        date,
145        decisions: 0,
146        loc_net_saved: 0,
147    });
148    store
149        .daily_records
150        .last_mut()
151        .expect("daily record was just inserted")
152}
153
154pub fn record_decision(kind: &str) {
155    with_store(|store| {
156        store.decisions_total = store.decisions_total.saturating_add(1);
157        let record = current_day_record(store);
158        record.decisions = record.decisions.saturating_add(1);
159        match kind {
160            "stdlib" => store.decisions_stdlib = store.decisions_stdlib.saturating_add(1),
161            "native" => store.decisions_native = store.decisions_native.saturating_add(1),
162            "reuse" => store.decisions_reuse = store.decisions_reuse.saturating_add(1),
163            "yagni" => store.decisions_yagni = store.decisions_yagni.saturating_add(1),
164            "oneline" => store.decisions_oneline = store.decisions_oneline.saturating_add(1),
165            "debt" => store.decisions_debt = store.decisions_debt.saturating_add(1),
166            _ => {}
167        }
168    });
169}
170
171pub fn record_loc_change(added: u64, removed: u64) {
172    with_store(|store| {
173        store.loc_added = store.loc_added.saturating_add(added);
174        store.loc_removed = store.loc_removed.saturating_add(removed);
175        let added = i64::try_from(added).unwrap_or(i64::MAX);
176        let removed = i64::try_from(removed).unwrap_or(i64::MAX);
177        let loc_net_saved = removed.saturating_sub(added);
178        store.loc_net_saved = store.loc_net_saved.saturating_add(loc_net_saved);
179        let record = current_day_record(store);
180        record.loc_net_saved = record.loc_net_saved.saturating_add(loc_net_saved);
181    });
182}
183
184pub fn trend_7d() -> Vec<(String, u64, i64)> {
185    reload_from_disk();
186    let store = store()
187        .lock()
188        .unwrap_or_else(std::sync::PoisonError::into_inner);
189    let mut records = store.daily_records.clone();
190    records.sort_unstable_by(|left, right| left.date.cmp(&right.date));
191    let mut trend: Vec<_> = records
192        .into_iter()
193        .rev()
194        .take(7)
195        .map(|record| (record.date, record.decisions, record.loc_net_saved))
196        .collect();
197    trend.reverse();
198    trend
199}
200
201pub fn record_output_tokens(baseline: u64, actual: u64) {
202    with_store(|store| {
203        store.output_tokens_baseline = store.output_tokens_baseline.saturating_add(baseline);
204        store.output_tokens_actual = store.output_tokens_actual.saturating_add(actual);
205    });
206}
207
208pub fn snapshot() -> SolutionSnapshot {
209    reload_from_disk();
210    let store = store()
211        .lock()
212        .unwrap_or_else(std::sync::PoisonError::into_inner);
213    let mut decisions_by_kind = HashMap::new();
214    if store.decisions_stdlib > 0 {
215        decisions_by_kind.insert("stdlib".to_owned(), store.decisions_stdlib);
216    }
217    if store.decisions_native > 0 {
218        decisions_by_kind.insert("native".to_owned(), store.decisions_native);
219    }
220    if store.decisions_reuse > 0 {
221        decisions_by_kind.insert("reuse".to_owned(), store.decisions_reuse);
222    }
223    if store.decisions_yagni > 0 {
224        decisions_by_kind.insert("yagni".to_owned(), store.decisions_yagni);
225    }
226    if store.decisions_oneline > 0 {
227        decisions_by_kind.insert("oneline".to_owned(), store.decisions_oneline);
228    }
229    if store.decisions_debt > 0 {
230        decisions_by_kind.insert("debt".to_owned(), store.decisions_debt);
231    }
232    let output_reduction_pct = store
233        .output_tokens_baseline
234        .checked_sub(store.output_tokens_actual)
235        .and_then(|reduction| reduction.checked_mul(100))
236        .and_then(|reduction| reduction.checked_div(store.output_tokens_baseline))
237        .and_then(|reduction| u8::try_from(reduction).ok())
238        .unwrap_or(0);
239
240    SolutionSnapshot {
241        decisions_total: store.decisions_total,
242        decisions_by_kind,
243        loc_added: store.loc_added,
244        loc_removed: store.loc_removed,
245        loc_net_saved: store.loc_net_saved,
246        output_tokens_baseline: store.output_tokens_baseline,
247        output_tokens_actual: store.output_tokens_actual,
248        output_reduction_pct,
249    }
250}
251
252pub fn reset() {
253    with_store(|store| *store = SolutionStore::default());
254}
255
256pub fn gain_summary() -> String {
257    let snapshot = snapshot();
258    format!(
259        "{} decisions; {} net LOC saved; {}% output-token reduction",
260        snapshot.decisions_total, snapshot.loc_net_saved, snapshot.output_reduction_pct
261    )
262}