Skip to main content

lean_ctx/core/value/
recap.rs

1//! Turn and session recaps: when lean-ctx says something, and what.
2//!
3//! Hosts identify a conversation by their own session id (Claude's Stop and
4//! SessionStart payloads), which is not lean-ctx's session id. Per host
5//! session, [`TurnState`] counts turns and remembers the numbers at the last
6//! recap; the numbers themselves come from the project snapshot. A recap only
7//! ever describes the window since the previous one — never the whole lean-ctx
8//! session as if it happened in the last few turns.
9
10use 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
23/// Host-session turn files older than this are pruned.
24const TURN_STATE_TTL: Duration = Duration::from_hours(24 * 7);
25/// A last-session recap is only offered for a session active this recently.
26const 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    /// The lean-ctx session the baseline below belongs to.
34    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    /// A new host session, baselined at `snap` so nothing that happened before
43    /// it is attributed to its turns.
44    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/// What happened in one recap window.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct TurnRecap {
65    pub turns: u32,
66    pub saved: u64,
67    pub security: SecurityCounts,
68}
69
70/// Counts one finished turn and decides whether it ends a recap window.
71///
72/// A window closes after `recap_every_turns` turns, and only when it saved at
73/// least `recap_min_tokens` or had a security event (`verbose`: anything
74/// measured). Otherwise it keeps growing, and the recap names the real length.
75pub 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        // A lean-ctx session that began inside this host session counts from
85        // zero; one carried over from earlier counts from now on.
86        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
130/// `◆ lean-ctx · last 10 turns: −312.0K tokens · 2 secrets kept out of context`
131pub 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
140// ---------------------------------------------------------------------------
141// Files
142// ---------------------------------------------------------------------------
143
144pub 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
174/// The Stop-hook entry point: counts the turn and returns the recap line when
175/// this turn closes a window worth mentioning.
176pub 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    // No state means the hook was installed mid-conversation: baseline now,
186    // so earlier work is never claimed for these turns.
187    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    /// The lean-ctx session that already got its "last session" recap.
198    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
206/// The SessionStart entry point. Starts the host session's turn count and, on
207/// a fresh start (not a resume or compaction), returns either the weekly
208/// digest (at most once per 7 days) or a one-time recap of the project's last
209/// lean-ctx session.
210pub 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
255/// `◆ lean-ctx · last session (62% of tool input): −1.4M tokens · 3 secrets kept out of context`
256pub 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/// Totals over every session snapshot updated in the last 7 days.
265#[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        // The file time is a cheap pre-filter; the snapshot's own clock decides.
278        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
300/// `◆ lean-ctx · this week (12 sessions): −8.4M tokens · 3 secrets kept out of context`
301pub 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;