lean_ctx/core/value/
snapshot.rs1use 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
22const 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 pub tokens_input: u64,
36 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 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 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 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
108pub 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
116pub 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(¤t_path(dir), &json, None)
133 .map_err(|e| e.to_string())
134}
135
136pub 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
162pub 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(¤t_path(&dir)),
168 }
169}
170
171pub 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(¤t_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}