Skip to main content

lean_ctx/core/session_summary/
mod.rs

1//! AI session summaries (#292): periodically distil the working session into a
2//! compact, semantically-recallable digest.
3//!
4//! Pipeline: `generate::build_candidate` (under the session lock, cheap, owned)
5//! → [`maybe_record_periodic`] (off the hot path: cadence check + persist) →
6//! [`recall::recall`] (semantic when embeddings are warm, else lexical).
7//!
8//! Deterministic and local-first: no LLM is required to produce or recall a
9//! summary.
10
11pub(crate) mod generate;
12pub mod recall;
13pub(crate) mod record;
14pub(crate) mod store;
15
16pub use recall::recall;
17pub(crate) use record::{SummaryCandidate, SummaryRecord};
18
19use crate::core::session::SessionState;
20use store::SummaryStore;
21
22fn config() -> crate::core::config::SummariesConfig {
23    crate::core::config::Config::load().summaries
24}
25
26/// Build a lock-free candidate from the live session. Call while holding the
27/// session lock; persist the result off the hot path with [`maybe_record_periodic`].
28pub fn build_candidate(session: &SessionState) -> SummaryCandidate {
29    generate::build_candidate(session)
30}
31
32/// Record `candidate` iff enabled and the turn cadence is due. Returns the title
33/// of the recorded summary, or `None` if skipped.
34pub fn maybe_record_periodic(project_root: &str, candidate: SummaryCandidate) -> Option<String> {
35    let cfg = config();
36    if !cfg.enabled || !candidate.has_content {
37        return None;
38    }
39    // The cadence watermark is read and advanced under the same store lock.
40    SummaryStore::mutate_locked(project_root, |store| {
41        if candidate.tool_calls < store.last_recorded_calls + u64::from(cfg.every_n_turns) {
42            return None;
43        }
44        record_into(store, candidate, cfg.max_kept as usize)
45    })
46    .unwrap_or_else(|error| {
47        tracing::warn!(event = "session_summary_not_recorded", %error);
48        None
49    })
50}
51
52/// Force-record a summary now (explicit action), ignoring the turn cadence.
53pub fn record_now(project_root: &str, candidate: SummaryCandidate) -> Result<String, String> {
54    if !candidate.has_content {
55        return Err("session has nothing to summarize yet".to_string());
56    }
57    let cfg = config();
58    match SummaryStore::mutate_locked(project_root, |store| {
59        record_into(store, candidate, cfg.max_kept as usize)
60    }) {
61        Ok(Some(title)) => Ok(title),
62        Ok(None) => Err("failed to persist summary".to_string()),
63        Err(error) => Err(format!("failed to persist summary: {error}")),
64    }
65}
66
67/// Adds the admitted record to `store`; the caller persists it.
68fn record_into(
69    store: &mut SummaryStore,
70    candidate: SummaryCandidate,
71    max_kept: usize,
72) -> Option<String> {
73    let calls = candidate.tool_calls;
74    let seq = store.next_seq();
75    // Stored bytes: the ADMITTED record only. A candidate with a field the
76    // gateway withholds or classifies as restricted is not recorded at all.
77    let rec = candidate.into_record(seq).admitted_for_store()?;
78    let title = rec.title.clone();
79    store.last_recorded_calls = calls;
80    store.push(rec, max_kept);
81    Some(title)
82}
83
84/// The stored summaries of a project as they may be served NOW (oldest
85/// first): each record through the originless rule, a record that is not
86/// released left out. The store on disk is not touched by this view.
87pub fn list(project_root: &str) -> Vec<SummaryRecord> {
88    served(SummaryStore::load_or_create(project_root)).summaries
89}
90
91/// `store` reduced to the records that may be served now. A read-only view:
92/// callers never save it.
93pub(crate) fn served(mut store: SummaryStore) -> SummaryStore {
94    store.summaries = store
95        .summaries
96        .iter()
97        .filter_map(SummaryRecord::served)
98        .collect();
99    store
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::core::session::SessionState;
106
107    fn isolated() -> (tempfile::TempDir, String) {
108        let tmp = tempfile::tempdir().unwrap();
109        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path().join("data"));
110        let root = tmp.path().join("proj").to_string_lossy().to_string();
111        (tmp, root)
112    }
113
114    fn session_with_work(calls: u32) -> SessionState {
115        let mut s = SessionState::new();
116        s.set_task("Implement traversal edges", None);
117        s.add_decision("Use Hebbian decay for co-access weights", None);
118        s.touch_file("src/core/cooccurrence.rs", None, "full", 1200);
119        s.stats.total_tool_calls = calls;
120        s
121    }
122
123    #[test]
124    fn cadence_gates_then_records() {
125        let _g = crate::core::data_dir::test_env_lock();
126        let (_tmp, root) = isolated();
127
128        // Below cadence (default every_n_turns=25): skipped.
129        let c = build_candidate(&session_with_work(5));
130        assert!(maybe_record_periodic(&root, c).is_none());
131
132        // At/over cadence: recorded.
133        let c = build_candidate(&session_with_work(30));
134        assert!(maybe_record_periodic(&root, c).is_some());
135        assert_eq!(list(&root).len(), 1);
136
137        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
138    }
139
140    /// E3 / G04: a summary was persisted exactly as it was distilled and
141    /// recalled exactly as it was stored. It is now stored admitted (a masked
142    /// value stays masked on disk) and served under the originless rule (not
143    /// at all once a project policy is active).
144    #[test]
145    fn summaries_are_stored_admitted_and_served_under_the_originless_rule() {
146        const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
147        let _data = crate::core::data_dir::isolated_data_dir();
148        let project = tempfile::tempdir().unwrap();
149        let root = project.path().to_string_lossy().to_string();
150        {
151            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
152            let mut session = session_with_work(3);
153            session.add_decision(&format!("Rotate the deploy key {AWS_KEY} weekly"), None);
154            record_now(&root, build_candidate(&session)).unwrap();
155
156            let on_disk = SummaryStore::load_or_create(&root);
157            assert_eq!(on_disk.summaries.len(), 1);
158            let stored = serde_json::to_string(&on_disk.summaries).unwrap();
159            assert!(!stored.contains(AWS_KEY), "the store holds a raw key");
160
161            // Control: a clean summary is recalled as before.
162            let hits = recall(&root, "traversal edges", 5);
163            assert!(!hits.is_empty());
164            assert!(hits[0].record.title.contains("traversal"));
165            assert_eq!(list(&root).len(), 1);
166        }
167        let policy = crate::core::policy::load(
168            "name = \"session-summary-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n",
169        )
170        .unwrap();
171        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
172        assert!(list(&root).is_empty(), "no source authority, not served");
173        assert!(recall(&root, "traversal edges", 5).is_empty());
174        assert_eq!(
175            SummaryStore::load_or_create(&root).summaries.len(),
176            1,
177            "the served view never changes the store"
178        );
179    }
180
181    /// AP07-G7: the store was loaded and written without a lock (and not
182    /// atomically), so parallel recorders dropped each other's summaries.
183    #[test]
184    fn parallel_recorders_keep_every_summary() {
185        use std::sync::{Arc, Barrier};
186        const RECORDERS: usize = 8;
187        let _data = crate::core::data_dir::isolated_data_dir();
188        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
189        let project = tempfile::tempdir().unwrap();
190        let root = project.path().to_string_lossy().to_string();
191        let barrier = Arc::new(Barrier::new(RECORDERS));
192        let recorders: Vec<_> = (0..RECORDERS)
193            .map(|_| {
194                let candidate = build_candidate(&session_with_work(3));
195                let (barrier, root) = (Arc::clone(&barrier), root.clone());
196                std::thread::spawn(move || {
197                    barrier.wait();
198                    record_now(&root, candidate)
199                })
200            })
201            .collect();
202        for recorder in recorders {
203            recorder.join().unwrap().unwrap();
204        }
205        assert_eq!(
206            SummaryStore::load_or_create(&root).summaries.len(),
207            RECORDERS
208        );
209    }
210
211    #[test]
212    fn record_now_and_lexical_recall() {
213        let _g = crate::core::data_dir::test_env_lock();
214        let (_tmp, root) = isolated();
215
216        let c = build_candidate(&session_with_work(3));
217        record_now(&root, c).unwrap();
218
219        let hits = recall(&root, "traversal edges cooccurrence", 5);
220        assert!(!hits.is_empty(), "should recall the summary lexically");
221        assert!(hits[0].record.title.contains("traversal"));
222
223        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
224    }
225}