Skip to main content

lean_ctx/core/value/
snapshot.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Per-session value snapshot: the small file every display channel reads.
3//!
4//! Written by the MCP server after tool calls (throttled, atomic) to
5//! `<data_dir>/value/sessions/<id>.json`, `value/current.json` and, keyed by
6//! the session's project root, `value/projects/<hash>.json`. Readers (status
7//! line, prompt segment, hooks, IDE) never open the ledger on their hot path;
8//! `lean-ctx value` re-derives every number from the chains instead.
9
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12use std::time::{Duration, Instant};
13
14use chrono::{DateTime, Utc};
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18use crate::core::security_events::SecurityCounts;
19
20pub const SCHEMA: u32 = 1;
21
22/// Minimum interval between two snapshot writes of one process.
23const WRITE_INTERVAL: Duration = Duration::from_secs(1);
24
25#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
26#[serde(default)]
27pub struct ValueSnapshot {
28    pub schema: u32,
29    pub session_id: String,
30    pub project_root: Option<String>,
31    pub started_at: Option<DateTime<Utc>>,
32    pub updated_at: Option<DateTime<Utc>>,
33    pub tool_calls: u64,
34    /// Tokens lean-ctx's tools would have sent without compression.
35    pub tokens_input: u64,
36    /// Tokens kept out of the model's context (measured, per tool result).
37    pub tokens_saved: u64,
38    pub cache_hits: u64,
39    pub files_read: u64,
40    pub commands_run: u64,
41    pub security: SecurityCounts,
42}
43
44impl ValueSnapshot {
45    pub fn from_session(session: &crate::core::session::SessionState) -> Self {
46        let s = &session.stats;
47        Self {
48            schema: SCHEMA,
49            session_id: session.id.clone(),
50            project_root: session.project_root.clone(),
51            started_at: Some(session.started_at),
52            updated_at: Some(Utc::now()),
53            tool_calls: u64::from(s.total_tool_calls),
54            tokens_input: s.total_tokens_input,
55            tokens_saved: s.total_tokens_saved,
56            cache_hits: u64::from(s.cache_hits),
57            files_read: u64::from(s.files_read),
58            commands_run: u64::from(s.commands_run),
59            security: s.security,
60        }
61    }
62
63    /// Share of tool input kept out of context, in percent (derived).
64    pub fn saved_pct(&self) -> Option<f64> {
65        (self.tokens_input > 0).then(|| self.tokens_saved as f64 * 100.0 / self.tokens_input as f64)
66    }
67
68    /// True when the snapshot was updated within `max_age`. Display channels
69    /// show nothing for a stale snapshot — never a misleading old number.
70    pub fn is_fresh(&self, max_age: Duration) -> bool {
71        let Some(updated) = self.updated_at else {
72            return false;
73        };
74        let age = Utc::now().signed_duration_since(updated);
75        age.to_std().map_or(true, |age| age <= max_age)
76    }
77
78    /// Nothing worth showing yet.
79    pub fn is_empty(&self) -> bool {
80        self.tokens_saved == 0 && self.security.is_empty()
81    }
82}
83
84pub fn value_dir() -> Option<PathBuf> {
85    crate::core::data_dir::lean_ctx_data_dir()
86        .ok()
87        .map(|dir| dir.join("value"))
88}
89
90fn sanitize_id(id: &str) -> Option<&str> {
91    let ok = !id.is_empty()
92        && id.len() <= 128
93        && id
94            .chars()
95            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
96        && !id.starts_with('.');
97    ok.then_some(id)
98}
99
100pub fn session_path(dir: &Path, id: &str) -> Option<PathBuf> {
101    sanitize_id(id).map(|id| dir.join("sessions").join(format!("{id}.json")))
102}
103
104pub fn current_path(dir: &Path) -> PathBuf {
105    dir.join("current.json")
106}
107
108/// Where the latest snapshot for project `root` lives. Hosts (a Claude status
109/// line, a Stop hook) know their working directory but not lean-ctx's session
110/// id; this pointer is how they find the numbers of the session serving them.
111pub fn project_path(dir: &Path, root: &str) -> PathBuf {
112    let digest = crate::core::agent_identity::hex_encode(&Sha256::digest(root.as_bytes()));
113    dir.join("projects").join(format!("{}.json", &digest[..16]))
114}
115
116/// Writes `snap` as the session's snapshot, as `current.json` and, when the
117/// session has a project root, as that project's snapshot.
118pub fn write_to(dir: &Path, snap: &ValueSnapshot) -> Result<(), String> {
119    let path = session_path(dir, &snap.session_id).ok_or("invalid session id")?;
120    let json = serde_json::to_vec(snap).map_err(|e| e.to_string())?;
121    let project = snap
122        .project_root
123        .as_deref()
124        .filter(|root| !root.is_empty())
125        .map(|root| project_path(dir, root));
126    for target in [Some(&path), project.as_ref()].into_iter().flatten() {
127        if let Some(parent) = target.parent() {
128            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
129        }
130        crate::core::atomic_fs::try_atomic_write(target, &json, None).map_err(|e| e.to_string())?;
131    }
132    crate::core::atomic_fs::try_atomic_write(&current_path(dir), &json, None)
133        .map_err(|e| e.to_string())
134}
135
136/// Throttled write used by the MCP server: at most once per
137/// `WRITE_INTERVAL` (1 s), except that a changed security tally always writes so a
138/// blocked command or a kept-out secret shows up immediately.
139pub fn write_throttled(snap: &ValueSnapshot) {
140    static LAST: Mutex<Option<(Instant, SecurityCounts)>> = Mutex::new(None);
141    {
142        let Ok(mut last) = LAST.lock() else { return };
143        if let Some((at, security)) = *last
144            && at.elapsed() < WRITE_INTERVAL
145            && security == snap.security
146        {
147            return;
148        }
149        *last = Some((Instant::now(), snap.security));
150    }
151    let Some(dir) = value_dir() else { return };
152    if let Err(error) = write_to(&dir, snap) {
153        tracing::debug!("lean-ctx: value snapshot write failed: {error}");
154    }
155}
156
157pub fn read_path(path: &Path) -> Option<ValueSnapshot> {
158    let bytes = std::fs::read(path).ok()?;
159    serde_json::from_slice(&bytes).ok()
160}
161
162/// The snapshot of session `id`, or of the most recently active session.
163pub fn load(id: Option<&str>) -> Option<ValueSnapshot> {
164    let dir = value_dir()?;
165    match id {
166        Some(id) => read_path(&session_path(&dir, id)?),
167        None => read_path(&current_path(&dir)),
168    }
169}
170
171/// The latest snapshot of the project containing `cwd`: the nearest ancestor
172/// (canonical first, then as given) that has one.
173pub fn load_for_dir(cwd: &Path) -> Option<ValueSnapshot> {
174    load_for_dir_in(&value_dir()?, cwd)
175}
176
177pub fn load_for_dir_in(dir: &Path, cwd: &Path) -> Option<ValueSnapshot> {
178    let canonical = crate::core::pathutil::safe_canonicalize_or_self(cwd);
179    [canonical.as_path(), cwd]
180        .into_iter()
181        .flat_map(Path::ancestors)
182        .filter_map(Path::to_str)
183        .find_map(|root| {
184            read_path(&project_path(dir, root))
185                .filter(|snap| snap.project_root.as_deref() == Some(root))
186        })
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    fn snap(id: &str) -> ValueSnapshot {
194        ValueSnapshot {
195            schema: SCHEMA,
196            session_id: id.into(),
197            updated_at: Some(Utc::now()),
198            tokens_input: 1_000,
199            tokens_saved: 400,
200            ..ValueSnapshot::default()
201        }
202    }
203
204    #[test]
205    fn project_snapshot_is_found_from_any_subdirectory() {
206        let data = tempfile::tempdir().unwrap();
207        let project = tempfile::tempdir().unwrap();
208        let root = crate::core::pathutil::safe_canonicalize_or_self(project.path());
209        let nested = root.join("src/deep");
210        std::fs::create_dir_all(&nested).unwrap();
211        let mut s = snap("sess-p");
212        s.project_root = Some(root.to_string_lossy().into_owned());
213        write_to(data.path(), &s).unwrap();
214
215        assert_eq!(load_for_dir_in(data.path(), &nested), Some(s.clone()));
216        assert_eq!(load_for_dir_in(data.path(), &root), Some(s));
217        let elsewhere = tempfile::tempdir().unwrap();
218        assert_eq!(load_for_dir_in(data.path(), elsewhere.path()), None);
219    }
220
221    #[test]
222    fn roundtrip_through_session_and_current_file() {
223        let dir = tempfile::tempdir().unwrap();
224        let s = snap("sess-1");
225        write_to(dir.path(), &s).unwrap();
226        assert_eq!(
227            read_path(&session_path(dir.path(), "sess-1").unwrap()),
228            Some(s.clone())
229        );
230        assert_eq!(read_path(&current_path(dir.path())), Some(s));
231    }
232
233    #[test]
234    fn rejects_path_traversal_ids() {
235        let dir = tempfile::tempdir().unwrap();
236        assert!(session_path(dir.path(), "../evil").is_none());
237        assert!(session_path(dir.path(), "a/b").is_none());
238        assert!(session_path(dir.path(), "").is_none());
239        assert!(write_to(dir.path(), &snap("../x")).is_err());
240    }
241
242    #[test]
243    fn staleness_is_detected() {
244        let mut s = snap("s");
245        assert!(s.is_fresh(Duration::from_mins(1)));
246        s.updated_at = Some(Utc::now() - chrono::Duration::hours(2));
247        assert!(!s.is_fresh(Duration::from_mins(1)));
248        s.updated_at = None;
249        assert!(!s.is_fresh(Duration::from_mins(1)));
250    }
251
252    #[test]
253    fn saved_pct_is_derived_from_measured_counts() {
254        assert_eq!(snap("s").saved_pct(), Some(40.0));
255        assert_eq!(ValueSnapshot::default().saved_pct(), None);
256    }
257
258    #[test]
259    fn unknown_fields_and_missing_fields_are_tolerated() {
260        let s: ValueSnapshot =
261            serde_json::from_str(r#"{"session_id":"x","future_field":1}"#).unwrap();
262        assert_eq!(s.session_id, "x");
263        assert!(s.is_empty());
264    }
265}