Skip to main content

lean_ctx_ext/core/
session_diff.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Session diffing — structured comparison of two session states.
3//!
4//! Produces a diff showing added/removed/changed files, findings,
5//! decisions, and tool-call pattern differences between sessions.
6
7use serde::Serialize;
8use std::collections::{HashMap, HashSet};
9
10use crate::core::session::SessionState;
11
12#[derive(Debug, Clone, Serialize)]
13pub struct SessionDiff {
14    pub session_a: String,
15    pub session_b: String,
16    pub files: FilesDiff,
17    pub findings: CountDiff,
18    pub decisions: CountDiff,
19    pub stats: StatsDiff,
20    pub modes: ModesDiff,
21}
22
23#[derive(Debug, Clone, Serialize)]
24pub struct FilesDiff {
25    pub added: Vec<String>,
26    pub removed: Vec<String>,
27    pub changed_mode: Vec<FileModeChange>,
28    pub common_count: usize,
29}
30
31#[derive(Debug, Clone, Serialize)]
32pub struct FileModeChange {
33    pub path: String,
34    pub mode_a: String,
35    pub mode_b: String,
36}
37
38#[derive(Debug, Clone, Serialize)]
39pub struct CountDiff {
40    pub count_a: usize,
41    pub count_b: usize,
42    pub added: Vec<String>,
43    pub removed: Vec<String>,
44}
45
46#[derive(Debug, Clone, Serialize)]
47pub struct StatsDiff {
48    pub tool_calls_a: u32,
49    pub tool_calls_b: u32,
50    pub tokens_saved_a: u64,
51    pub tokens_saved_b: u64,
52    pub files_read_a: u32,
53    pub files_read_b: u32,
54    pub commands_a: u32,
55    pub commands_b: u32,
56}
57
58#[derive(Debug, Clone, Serialize)]
59pub struct ModesDiff {
60    pub modes_a: HashMap<String, usize>,
61    pub modes_b: HashMap<String, usize>,
62}
63
64pub fn diff_sessions(a: &SessionState, b: &SessionState) -> SessionDiff {
65    SessionDiff {
66        session_a: a.id.clone(),
67        session_b: b.id.clone(),
68        files: diff_files(a, b),
69        findings: diff_findings(a, b),
70        decisions: diff_decisions(a, b),
71        stats: diff_stats(a, b),
72        modes: diff_modes(a, b),
73    }
74}
75
76fn diff_files(a: &SessionState, b: &SessionState) -> FilesDiff {
77    let paths_a: HashSet<&str> = a.files_touched.iter().map(|f| f.path.as_str()).collect();
78    let paths_b: HashSet<&str> = b.files_touched.iter().map(|f| f.path.as_str()).collect();
79
80    let added: Vec<String> = paths_b
81        .difference(&paths_a)
82        .map(ToString::to_string)
83        .collect();
84    let removed: Vec<String> = paths_a
85        .difference(&paths_b)
86        .map(ToString::to_string)
87        .collect();
88
89    let common: HashSet<&&str> = paths_a.intersection(&paths_b).collect();
90    let common_count = common.len();
91
92    let mode_map_a: HashMap<&str, &str> = a
93        .files_touched
94        .iter()
95        .map(|f| (f.path.as_str(), f.last_mode.as_str()))
96        .collect();
97    let mode_map_b: HashMap<&str, &str> = b
98        .files_touched
99        .iter()
100        .map(|f| (f.path.as_str(), f.last_mode.as_str()))
101        .collect();
102
103    let mut changed_mode = Vec::new();
104    for path in &common {
105        if let (Some(&ma), Some(&mb)) = (mode_map_a.get(**path), mode_map_b.get(**path))
106            && ma != mb
107        {
108            changed_mode.push(FileModeChange {
109                path: path.to_string(),
110                mode_a: ma.to_string(),
111                mode_b: mb.to_string(),
112            });
113        }
114    }
115
116    FilesDiff {
117        added,
118        removed,
119        changed_mode,
120        common_count,
121    }
122}
123
124fn diff_findings(a: &SessionState, b: &SessionState) -> CountDiff {
125    let summaries_a: HashSet<&str> = a.findings.iter().map(|f| f.summary.as_str()).collect();
126    let summaries_b: HashSet<&str> = b.findings.iter().map(|f| f.summary.as_str()).collect();
127
128    CountDiff {
129        count_a: a.findings.len(),
130        count_b: b.findings.len(),
131        added: summaries_b
132            .difference(&summaries_a)
133            .map(ToString::to_string)
134            .collect(),
135        removed: summaries_a
136            .difference(&summaries_b)
137            .map(ToString::to_string)
138            .collect(),
139    }
140}
141
142fn diff_decisions(a: &SessionState, b: &SessionState) -> CountDiff {
143    let summaries_a: HashSet<&str> = a.decisions.iter().map(|d| d.summary.as_str()).collect();
144    let summaries_b: HashSet<&str> = b.decisions.iter().map(|d| d.summary.as_str()).collect();
145
146    CountDiff {
147        count_a: a.decisions.len(),
148        count_b: b.decisions.len(),
149        added: summaries_b
150            .difference(&summaries_a)
151            .map(ToString::to_string)
152            .collect(),
153        removed: summaries_a
154            .difference(&summaries_b)
155            .map(ToString::to_string)
156            .collect(),
157    }
158}
159
160fn diff_stats(a: &SessionState, b: &SessionState) -> StatsDiff {
161    StatsDiff {
162        tool_calls_a: a.stats.total_tool_calls,
163        tool_calls_b: b.stats.total_tool_calls,
164        tokens_saved_a: a.stats.total_tokens_saved,
165        tokens_saved_b: b.stats.total_tokens_saved,
166        files_read_a: a.stats.files_read,
167        files_read_b: b.stats.files_read,
168        commands_a: a.stats.commands_run,
169        commands_b: b.stats.commands_run,
170    }
171}
172
173fn diff_modes(a: &SessionState, b: &SessionState) -> ModesDiff {
174    let mut modes_a: HashMap<String, usize> = HashMap::new();
175    for f in &a.files_touched {
176        *modes_a.entry(f.last_mode.clone()).or_insert(0) += 1;
177    }
178    let mut modes_b: HashMap<String, usize> = HashMap::new();
179    for f in &b.files_touched {
180        *modes_b.entry(f.last_mode.clone()).or_insert(0) += 1;
181    }
182    ModesDiff { modes_a, modes_b }
183}
184
185impl SessionDiff {
186    pub fn format_summary(&self) -> String {
187        let mut lines = Vec::new();
188        lines.push(format!(
189            "Session Diff: {} vs {}",
190            &self.session_a[..8.min(self.session_a.len())],
191            &self.session_b[..8.min(self.session_b.len())]
192        ));
193
194        lines.push(format!(
195            "Files: {} common, +{} added, -{} removed, ~{} mode-changed",
196            self.files.common_count,
197            self.files.added.len(),
198            self.files.removed.len(),
199            self.files.changed_mode.len()
200        ));
201
202        if !self.files.added.is_empty() {
203            for f in &self.files.added {
204                lines.push(format!("  + {f}"));
205            }
206        }
207        if !self.files.removed.is_empty() {
208            for f in &self.files.removed {
209                lines.push(format!("  - {f}"));
210            }
211        }
212        for mc in &self.files.changed_mode {
213            lines.push(format!("  ~ {} ({} -> {})", mc.path, mc.mode_a, mc.mode_b));
214        }
215
216        lines.push(format!(
217            "Findings: {} vs {} (+{} / -{})",
218            self.findings.count_a,
219            self.findings.count_b,
220            self.findings.added.len(),
221            self.findings.removed.len()
222        ));
223
224        lines.push(format!(
225            "Decisions: {} vs {} (+{} / -{})",
226            self.decisions.count_a,
227            self.decisions.count_b,
228            self.decisions.added.len(),
229            self.decisions.removed.len()
230        ));
231
232        lines.push(format!(
233            "Stats: calls {}/{}, saved {}/{}, files {}/{}, cmds {}/{}",
234            self.stats.tool_calls_a,
235            self.stats.tool_calls_b,
236            self.stats.tokens_saved_a,
237            self.stats.tokens_saved_b,
238            self.stats.files_read_a,
239            self.stats.files_read_b,
240            self.stats.commands_a,
241            self.stats.commands_b,
242        ));
243
244        lines.join("\n")
245    }
246
247    pub fn format_json(&self) -> String {
248        serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".into())
249    }
250}
251
252// ---------------------------------------------------------------------------
253// Tests
254// ---------------------------------------------------------------------------
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    fn make_session(id: &str) -> SessionState {
261        let mut s = SessionState::new();
262        s.id = id.to_string();
263        s
264    }
265
266    #[test]
267    fn empty_sessions_produce_empty_diff() {
268        let a = make_session("aaa");
269        let b = make_session("bbb");
270        let d = diff_sessions(&a, &b);
271        assert!(d.files.added.is_empty(), "{:?}", d.files.added);
272        assert!(d.files.removed.is_empty(), "{:?}", d.files.removed);
273        assert_eq!(d.files.common_count, 0);
274    }
275
276    #[test]
277    fn added_files_detected() {
278        let a = make_session("a");
279        let mut b = make_session("b");
280        b.touch_file("src/new.rs", None, "full", 100);
281        let d = diff_sessions(&a, &b);
282        assert_eq!(d.files.added, vec!["src/new.rs"]);
283    }
284
285    #[test]
286    fn removed_files_detected() {
287        let mut a = make_session("a");
288        a.touch_file("src/old.rs", None, "full", 100);
289        let b = make_session("b");
290        let d = diff_sessions(&a, &b);
291        assert_eq!(d.files.removed, vec!["src/old.rs"]);
292    }
293
294    #[test]
295    fn mode_changes_detected() {
296        let mut a = make_session("a");
297        let mut b = make_session("b");
298        a.touch_file("src/lib.rs", None, "full", 500);
299        b.touch_file("src/lib.rs", None, "signatures", 100);
300        let d = diff_sessions(&a, &b);
301        assert_eq!(d.files.changed_mode.len(), 1);
302        assert_eq!(d.files.changed_mode[0].mode_a, "full");
303        assert_eq!(d.files.changed_mode[0].mode_b, "signatures");
304    }
305
306    #[test]
307    fn findings_diff() {
308        let mut a = make_session("a");
309        let mut b = make_session("b");
310        a.add_finding(None, None, "old finding");
311        b.add_finding(None, None, "new finding");
312        let d = diff_sessions(&a, &b);
313        assert_eq!(d.findings.added, vec!["new finding"]);
314        assert_eq!(d.findings.removed, vec!["old finding"]);
315    }
316
317    #[test]
318    fn format_summary_includes_key_info() {
319        let mut a = make_session("session_aaa");
320        let mut b = make_session("session_bbb");
321        a.touch_file("src/main.rs", None, "full", 500);
322        b.touch_file("src/main.rs", None, "map", 100);
323        b.touch_file("src/new.rs", None, "full", 200);
324        let d = diff_sessions(&a, &b);
325        let summary = d.format_summary();
326        assert!(summary.contains("session_"));
327        assert!(summary.contains("+ src/new.rs"));
328        assert!(summary.contains("full -> map"));
329    }
330}