1use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15
16use crate::core::config::{ValueDisplayConfig, ValueDisplayMode};
17use crate::core::security_events::SecurityCounts;
18use crate::core::wrapped::format_tokens;
19
20use super::format::{Style, security_phrases};
21use super::snapshot::{ValueSnapshot, read_path};
22
23const TURN_STATE_TTL: Duration = Duration::from_hours(24 * 7);
25const RECAP_MAX_AGE: Duration = Duration::from_hours(24 * 7);
27const DIGEST_EVERY: chrono::TimeDelta = chrono::TimeDelta::days(7);
28
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(default)]
31pub struct TurnState {
32 pub created_at: Option<DateTime<Utc>>,
33 pub lean_session: String,
35 pub turns: u32,
36 pub last_recap_turn: u32,
37 pub base_saved: u64,
38 pub base_security: SecurityCounts,
39}
40
41impl TurnState {
42 pub fn start(now: DateTime<Utc>, snap: Option<&ValueSnapshot>) -> Self {
45 let mut state = Self {
46 created_at: Some(now),
47 ..Self::default()
48 };
49 if let Some(snap) = snap {
50 state.rebase(snap);
51 }
52 state
53 }
54
55 fn rebase(&mut self, snap: &ValueSnapshot) {
56 self.lean_session.clone_from(&snap.session_id);
57 self.base_saved = snap.tokens_saved;
58 self.base_security = snap.security;
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct TurnRecap {
65 pub turns: u32,
66 pub saved: u64,
67 pub security: SecurityCounts,
68}
69
70pub fn advance(
76 state: &mut TurnState,
77 snap: Option<&ValueSnapshot>,
78 cfg: &ValueDisplayConfig,
79 verbose: bool,
80) -> Option<TurnRecap> {
81 state.turns = state.turns.saturating_add(1);
82 let snap = snap?;
83 if snap.session_id != state.lean_session {
84 let began_here = matches!(
87 (snap.started_at, state.created_at),
88 (Some(started), Some(created)) if started >= created
89 );
90 state.rebase(snap);
91 if began_here {
92 state.base_saved = 0;
93 state.base_security = SecurityCounts::default();
94 }
95 }
96 let window = state.turns.saturating_sub(state.last_recap_turn);
97 if window < cfg.recap_every_turns.max(1) {
98 return None;
99 }
100 let saved = snap.tokens_saved.saturating_sub(state.base_saved);
101 let security = snap.security.since(&state.base_security);
102 let worth = !security.is_empty()
103 || if verbose {
104 saved > 0
105 } else {
106 saved > 0 && saved >= cfg.recap_min_tokens
107 };
108 if !worth {
109 return None;
110 }
111 state.last_recap_turn = state.turns;
112 state.rebase(snap);
113 Some(TurnRecap {
114 turns: window,
115 saved,
116 security,
117 })
118}
119
120fn line(style: Style, label: &str, saved: u64, security: &SecurityCounts) -> String {
121 let mut parts = Vec::new();
122 if saved > 0 {
123 parts.push(format!("{}{} tokens", style.minus(), format_tokens(saved)));
124 }
125 parts.extend(security_phrases(security));
126 let sep = style.sep();
127 format!("{} lean-ctx{sep}{label}: {}", style.mark(), parts.join(sep))
128}
129
130pub fn turn_line(recap: &TurnRecap, style: Style) -> String {
132 let label = if recap.turns == 1 {
133 "last turn".to_string()
134 } else {
135 format!("last {} turns", recap.turns)
136 };
137 line(style, &label, recap.saved, &recap.security)
138}
139
140pub fn turn_state_path(dir: &Path, host_session: &str) -> Option<PathBuf> {
145 let ok = !host_session.is_empty()
146 && host_session.len() <= 128
147 && !host_session.starts_with('.')
148 && host_session
149 .chars()
150 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
151 ok.then(|| dir.join("turns").join(format!("{host_session}.json")))
152}
153
154fn read_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Option<T> {
155 serde_json::from_slice(&std::fs::read(path).ok()?).ok()
156}
157
158fn write_json<T: Serialize>(path: &Path, value: &T) {
159 let Ok(json) = serde_json::to_vec(value) else {
160 return;
161 };
162 if let Some(parent) = path.parent() {
163 let _ = std::fs::create_dir_all(parent);
164 }
165 if let Err(error) = crate::core::atomic_fs::try_atomic_write(path, &json, None) {
166 tracing::debug!("lean-ctx: value recap state write failed: {error}");
167 }
168}
169
170pub fn load_turn_state(dir: &Path, host_session: &str) -> Option<TurnState> {
171 read_json(&turn_state_path(dir, host_session)?)
172}
173
174pub fn on_turn_end(
177 dir: &Path,
178 host_session: &str,
179 snap: Option<&ValueSnapshot>,
180 cfg: &ValueDisplayConfig,
181 now: DateTime<Utc>,
182 style: Style,
183) -> Option<String> {
184 let path = turn_state_path(dir, host_session)?;
185 let mut state = read_json(&path).unwrap_or_else(|| TurnState::start(now, snap));
188 let verbose = cfg.effective_mode() == ValueDisplayMode::Verbose;
189 let recap = advance(&mut state, snap, cfg, verbose);
190 write_json(&path, &state);
191 recap.map(|r| turn_line(&r, style))
192}
193
194#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(default)]
196pub struct RecapState {
197 pub last_session_recapped: String,
199 pub last_digest_at: Option<DateTime<Utc>>,
200}
201
202fn recap_state_path(dir: &Path) -> PathBuf {
203 dir.join("recap_state.json")
204}
205
206pub fn on_session_start(
211 dir: &Path,
212 host_session: &str,
213 source: &str,
214 snap: Option<&ValueSnapshot>,
215 cfg: &ValueDisplayConfig,
216 now: DateTime<Utc>,
217 style: Style,
218) -> Option<String> {
219 prune_turn_states(dir);
220 if let Some(path) = turn_state_path(dir, host_session)
221 && !path.exists()
222 {
223 write_json(&path, &TurnState::start(now, snap));
224 }
225 if !matches!(source, "" | "startup") {
226 return None;
227 }
228 let state_path = recap_state_path(dir);
229 let mut state: RecapState = read_json(&state_path).unwrap_or_default();
230 let verbose = cfg.effective_mode() == ValueDisplayMode::Verbose;
231
232 let digest_due = state
233 .last_digest_at
234 .is_none_or(|at| now.signed_duration_since(at) >= DIGEST_EVERY);
235 if digest_due && let Some(digest) = weekly_digest(dir, now) {
236 state.last_digest_at = Some(now);
237 if let Some(snap) = snap {
238 state.last_session_recapped.clone_from(&snap.session_id);
239 }
240 write_json(&state_path, &state);
241 return Some(digest_line(&digest, style));
242 }
243
244 let snap = snap?;
245 let worth = !snap.security.is_empty()
246 || snap.tokens_saved > 0 && (verbose || snap.tokens_saved >= cfg.recap_min_tokens);
247 if !worth || snap.session_id == state.last_session_recapped || !snap.is_fresh(RECAP_MAX_AGE) {
248 return None;
249 }
250 state.last_session_recapped.clone_from(&snap.session_id);
251 write_json(&state_path, &state);
252 Some(session_line(snap, style))
253}
254
255pub fn session_line(snap: &ValueSnapshot, style: Style) -> String {
257 let label = match snap.saved_pct() {
258 Some(pct) if snap.tokens_saved > 0 => format!("last session ({pct:.0}% of tool input)"),
259 _ => "last session".to_string(),
260 };
261 line(style, &label, snap.tokens_saved, &snap.security)
262}
263
264#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
266pub struct Digest {
267 pub sessions: u64,
268 pub saved: u64,
269 pub security: SecurityCounts,
270}
271
272pub fn weekly_digest(dir: &Path, now: DateTime<Utc>) -> Option<Digest> {
273 let since = now - DIGEST_EVERY;
274 let window = DIGEST_EVERY.to_std().unwrap_or_default();
275 let mut digest = Digest::default();
276 for entry in std::fs::read_dir(dir.join("sessions")).ok()?.flatten() {
277 let recent = entry
279 .metadata()
280 .and_then(|m| m.modified())
281 .ok()
282 .and_then(|t| t.elapsed().ok())
283 .is_none_or(|age| age <= window);
284 if !recent {
285 continue;
286 }
287 let Some(snap) = read_path(&entry.path()) else {
288 continue;
289 };
290 if snap.updated_at.is_none_or(|at| at < since) || snap.is_empty() {
291 continue;
292 }
293 digest.sessions += 1;
294 digest.saved = digest.saved.saturating_add(snap.tokens_saved);
295 digest.security.merge(&snap.security);
296 }
297 (digest.sessions > 0).then_some(digest)
298}
299
300pub fn digest_line(digest: &Digest, style: Style) -> String {
302 let label = if digest.sessions == 1 {
303 "this week (1 session)".to_string()
304 } else {
305 format!("this week ({} sessions)", digest.sessions)
306 };
307 line(style, &label, digest.saved, &digest.security)
308}
309
310fn prune_turn_states(dir: &Path) {
311 let Ok(entries) = std::fs::read_dir(dir.join("turns")) else {
312 return;
313 };
314 for entry in entries.flatten() {
315 let stale = entry
316 .metadata()
317 .and_then(|m| m.modified())
318 .ok()
319 .and_then(|t| t.elapsed().ok())
320 .is_some_and(|age| age > TURN_STATE_TTL);
321 if stale {
322 let _ = std::fs::remove_file(entry.path());
323 }
324 }
325}
326
327#[cfg(test)]
328#[path = "recap_tests.rs"]
329mod tests;