Skip to main content

lean_ctx/core/session/
persistence.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3
4use super::heuristics::{normalize_loaded_session, session_matches_project_root};
5use super::paths::sessions_dir;
6use super::state::{BATCH_SAVE_INTERVAL, extract_session_facts};
7#[allow(clippy::wildcard_imports)]
8use super::types::*;
9
10/// Keep the startup warm set deliberately small: cache warming is an optional
11/// optimisation and must never turn process startup into a session-store scan.
12const PROJECT_HISTORY_LIMIT: usize = 8;
13
14#[derive(Debug, Default, Deserialize, Serialize)]
15struct ProjectSessionIndex {
16    version: u8,
17    project_root: String,
18    /// Oldest to newest; duplicates are removed before appending on every save.
19    session_ids: Vec<String>,
20}
21
22fn normalized_safe_project_root(project_root: &str) -> Option<String> {
23    let path = std::path::Path::new(project_root);
24    if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
25        return None;
26    }
27    Some(
28        crate::core::pathutil::safe_canonicalize_or_self(path)
29            .to_string_lossy()
30            .to_string(),
31    )
32}
33
34fn project_index_path(dir: &std::path::Path, project_root: &str) -> std::path::PathBuf {
35    let key = blake3::hash(project_root.as_bytes()).to_hex();
36    dir.join("project-index").join(format!("{key}.json"))
37}
38
39fn read_project_index(dir: &std::path::Path, project_root: &str) -> Option<ProjectSessionIndex> {
40    std::fs::read_to_string(project_index_path(dir, project_root))
41        .ok()
42        .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
43        .filter(|index| index.version == 1 && index.project_root == project_root)
44}
45
46fn write_project_index(
47    index_path: &std::path::Path,
48    index: &ProjectSessionIndex,
49) -> Result<(), String> {
50    let json = serde_json::to_string(index).map_err(|e| format!("serialize project index: {e}"))?;
51    let tmp = index_path.with_extension(format!("{}.tmp", std::process::id()));
52    std::fs::write(&tmp, json).map_err(|e| format!("write project index: {e}"))?;
53    restrict_file_permissions(&tmp);
54    std::fs::rename(tmp, index_path).map_err(|e| format!("commit project index: {e}"))
55}
56
57fn with_project_index_lock<T>(
58    dir: &std::path::Path,
59    project_root: &str,
60    operation: impl FnOnce(&std::path::Path) -> Result<T, String>,
61) -> Result<T, String> {
62    use fs2::FileExt;
63    use std::time::{Duration, Instant};
64
65    const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
66    const RETRY_INTERVAL: Duration = Duration::from_millis(10);
67
68    let index_path = project_index_path(dir, project_root);
69    let index_dir = index_path.parent().ok_or("project index has no parent")?;
70    std::fs::create_dir_all(index_dir).map_err(|e| format!("create project index: {e}"))?;
71    let lock = std::fs::OpenOptions::new()
72        .create(true)
73        .truncate(false)
74        .write(true)
75        .open(index_path.with_extension("lock"))
76        .map_err(|e| format!("project index lock: {e}"))?;
77    let deadline = Instant::now() + LOCK_TIMEOUT;
78    loop {
79        match lock.try_lock_exclusive() {
80            Ok(()) => break,
81            Err(error)
82                if crate::core::file_lock::is_contended(&error) && Instant::now() < deadline =>
83            {
84                std::thread::sleep(RETRY_INTERVAL);
85            }
86            Err(error) if crate::core::file_lock::is_contended(&error) => {
87                return Err("project index lock timed out".to_string());
88            }
89            Err(error) => return Err(format!("project index lock: {error}")),
90        }
91    }
92    let result = operation(&index_path);
93    let _ = FileExt::unlock(&lock);
94    result
95}
96
97/// Update one project's bounded warm-history index under a short, local lock.
98/// The index is strictly an acceleration structure: a failure never invalidates
99/// the already-committed session save.
100fn update_project_index(dir: &std::path::Path, project_root: &str, id: &str) -> Result<(), String> {
101    with_project_index_lock(dir, project_root, |index_path| {
102        let mut index =
103            read_project_index(dir, project_root).unwrap_or_else(|| ProjectSessionIndex {
104                version: 1,
105                project_root: project_root.to_string(),
106                session_ids: Vec::new(),
107            });
108        index.session_ids.retain(|existing| existing != id);
109        index.session_ids.push(id.to_string());
110        let excess = index
111            .session_ids
112            .len()
113            .saturating_sub(PROJECT_HISTORY_LIMIT);
114        if excess > 0 {
115            index.session_ids.drain(..excess);
116        }
117        write_project_index(index_path, &index)
118    })
119}
120
121fn repair_project_index(dir: &std::path::Path, project_root: &str) -> Option<SessionState> {
122    let mut matches = Vec::new();
123    for entry in std::fs::read_dir(dir).ok()?.flatten() {
124        let path = entry.path();
125        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
126            continue;
127        }
128        let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
129            continue;
130        };
131        if id == "latest" || id.starts_with('.') {
132            continue;
133        }
134        let Some(session) = SessionState::load_by_id(id) else {
135            continue;
136        };
137        if session_matches_project_root(&session, std::path::Path::new(project_root)) {
138            matches.push(session);
139        }
140    }
141    matches.sort_by_key(|session| session.updated_at);
142    let latest = matches.last().cloned();
143    let first_retained = matches.len().saturating_sub(PROJECT_HISTORY_LIMIT);
144    let session_ids = matches[first_retained..]
145        .iter()
146        .map(|session| session.id.clone())
147        .collect();
148    if let Err(error) = with_project_index_lock(dir, project_root, |index_path| {
149        write_project_index(
150            index_path,
151            &ProjectSessionIndex {
152                version: 1,
153                project_root: project_root.to_string(),
154                session_ids,
155            },
156        )
157    }) {
158        tracing::debug!("lean-ctx: session project index repair skipped: {error}");
159    }
160    latest
161}
162
163#[cfg(unix)]
164fn restrict_file_permissions(path: &std::path::Path) {
165    use std::os::unix::fs::PermissionsExt;
166    let perms = std::fs::Permissions::from_mode(0o600);
167    let _ = std::fs::set_permissions(path, perms);
168}
169
170#[cfg(not(unix))]
171fn restrict_file_permissions(_path: &std::path::Path) {}
172
173fn validate_session_id(id: &str) -> Result<(), String> {
174    if id.is_empty()
175        || id == "latest"
176        || id.starts_with('.')
177        || id.contains('/')
178        || id.contains('\\')
179        || id.contains(std::path::MAIN_SEPARATOR)
180    {
181        return Err("invalid session id".to_string());
182    }
183    Ok(())
184}
185
186fn persist_session_facts(session: &SessionState) -> Result<(), String> {
187    let Some(project_root) = session
188        .project_root
189        .as_deref()
190        .filter(|project_root| !project_root.trim().is_empty())
191    else {
192        return Ok(());
193    };
194
195    let facts = extract_session_facts(session);
196    if facts.is_empty() {
197        return Ok(());
198    }
199
200    let mut knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
201    for fact in facts {
202        knowledge.add_fact(fact);
203    }
204    knowledge.save()
205}
206
207impl PreparedSave {
208    /// Writes the pre-serialized session data, latest pointer, and compaction
209    /// snapshot to disk atomically. A per-session file lock and version check
210    /// make deferred saves monotonic even when background tasks finish out of
211    /// order.
212    pub fn write_to_disk(self) -> Result<(), String> {
213        use fs2::FileExt;
214
215        if !self.dir.exists() {
216            std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
217        }
218        let lock_path = self.dir.join(format!(".{}.save.lock", self.id));
219        let lock = std::fs::OpenOptions::new()
220            .create(true)
221            .truncate(false)
222            .write(true)
223            .open(lock_path)
224            .map_err(|e| format!("open session save lock: {e}"))?;
225        lock.lock_exclusive()
226            .map_err(|e| format!("lock session save: {e}"))?;
227
228        let result = (|| {
229            let path = self.dir.join(format!("{}.json", self.id));
230            if persisted_session_version(&path).is_some_and(|version| version > self.version) {
231                return Ok(());
232            }
233            let tmp = self.dir.join(format!(".{}.json.tmp", self.id));
234            std::fs::write(&tmp, &self.json).map_err(|e| e.to_string())?;
235            restrict_file_permissions(&tmp);
236            std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
237
238            let latest_path = self.dir.join("latest.json");
239            let latest_tmp = self.dir.join(".latest.json.tmp");
240            std::fs::write(&latest_tmp, &self.pointer_json).map_err(|e| e.to_string())?;
241            restrict_file_permissions(&latest_tmp);
242            std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
243
244            if let Some(snapshot) = self.compaction_snapshot {
245                let snap_path = self.dir.join(format!("{}_snapshot.txt", self.id));
246                if let Err(error) = crate::core::atomic_fs::write_bytes_with_fallback(
247                    &snap_path,
248                    snapshot.as_bytes(),
249                    None,
250                ) {
251                    tracing::debug!("lean-ctx: compaction snapshot update skipped: {error}");
252                } else {
253                    restrict_file_permissions(&snap_path);
254                }
255            }
256            if let Some(project_root) = self.project_index_root.as_deref()
257                && let Err(error) = update_project_index(&self.dir, project_root, &self.id)
258            {
259                tracing::debug!("lean-ctx: session warm-history index update skipped: {error}");
260            }
261            Ok(())
262        })();
263        let _ = FileExt::unlock(&lock);
264        result
265    }
266}
267
268fn persisted_session_version(path: &std::path::Path) -> Option<u32> {
269    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
270    value["version"].as_u64()?.try_into().ok()
271}
272
273impl SessionState {
274    /// Counts locally recorded decisions from the trailing seven days.
275    #[must_use]
276    pub fn decision_count_this_week() -> u64 {
277        let cutoff = Utc::now() - chrono::Duration::days(7);
278        Self::list_sessions()
279            .into_iter()
280            .filter_map(|summary| Self::load_by_id(&summary.id))
281            .flat_map(|session| session.decisions)
282            .filter(|decision| decision.timestamp >= cutoff)
283            .count()
284            .try_into()
285            .unwrap_or(u64::MAX)
286    }
287
288    /// Serializes and writes the session state to disk synchronously.
289    pub fn save(&mut self) -> Result<(), String> {
290        let prepared = self.prepare_save()?;
291        match prepared.write_to_disk() {
292            Ok(()) => Ok(()),
293            Err(e) => {
294                self.stats.unsaved_changes = BATCH_SAVE_INTERVAL;
295                Err(e)
296            }
297        }
298    }
299
300    /// Serialize session state while holding the lock (CPU-only), reset the
301    /// unsaved counter, and return a `PreparedSave` whose I/O can be deferred
302    /// to a background thread via `write_to_disk()`.
303    pub fn prepare_save(&mut self) -> Result<PreparedSave, String> {
304        if self
305            .project_root
306            .as_deref()
307            .is_some_and(|root| normalized_safe_project_root(root).is_none())
308        {
309            return Err(
310                "refusing to persist a session for a broad or unsafe project root".to_string(),
311            );
312        }
313        let dir = sessions_dir().ok_or("cannot determine home directory")?;
314        let compaction_snapshot = if self.stats.total_tool_calls > 0 {
315            Some(self.build_compaction_snapshot())
316        } else {
317            None
318        };
319        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
320        let pointer_json = serde_json::to_string(&LatestPointer {
321            id: self.id.clone(),
322        })
323        .map_err(|e| e.to_string())?;
324        self.stats.unsaved_changes = 0;
325        // #717: arm the time-based flush window.
326        self.last_flush = Some(std::time::Instant::now());
327        Ok(PreparedSave {
328            dir,
329            id: self.id.clone(),
330            version: self.version,
331            json,
332            pointer_json,
333            compaction_snapshot,
334            project_index_root: self
335                .project_root
336                .as_deref()
337                .and_then(normalized_safe_project_root),
338        })
339    }
340
341    /// Load the bounded warm-history set for one safe project root.
342    ///
343    /// There is intentionally no legacy full-store fallback: cache warming is
344    /// optional, while scanning every persisted session on each MCP launch is
345    /// not acceptable under concurrent agent load. New saves populate the
346    /// index; legacy sessions remain available through explicit session tools.
347    pub(crate) fn load_recent_for_project_root(project_root: &str, limit: usize) -> Vec<Self> {
348        let Some(project_root) = normalized_safe_project_root(project_root) else {
349            return Vec::new();
350        };
351        let Some(dir) = sessions_dir() else {
352            return Vec::new();
353        };
354        let Some(index) = std::fs::read_to_string(project_index_path(&dir, &project_root))
355            .ok()
356            .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
357            .filter(|index| index.version == 1 && index.project_root == project_root)
358        else {
359            return Vec::new();
360        };
361
362        index
363            .session_ids
364            .iter()
365            .rev()
366            .take(limit.min(PROJECT_HISTORY_LIMIT))
367            .filter_map(|id| Self::load_by_id(id))
368            .collect()
369    }
370
371    /// Loads the most recent session matching the current working directory's
372    /// project root.
373    ///
374    /// Returns `None` (a fresh session) rather than falling back to the global
375    /// `latest.json` pointer: that unconditional fallback bypassed project-root
376    /// matching and was the root cause of cross-project session leakage — one
377    /// project's findings/decisions/knowledge bleeding into another project's
378    /// first session. The correct project session is loaded later from the MCP
379    /// `roots` handshake (`load_latest_for_project_root`).
380    ///
381    /// Also refuses to scope to a broad/unsafe cwd (e.g. the MCP daemon's HOME),
382    /// which would otherwise resurrect the contaminated "HOME mega-session".
383    pub fn load_latest() -> Option<Self> {
384        let cwd = std::env::current_dir().ok()?;
385        if crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
386            return None;
387        }
388        Self::load_latest_for_project_root(&cwd.to_string_lossy())
389    }
390
391    /// Loads the session referenced by the global `latest.json` pointer,
392    /// regardless of project. Intended only for explicit, cross-project UX
393    /// (e.g. `lean-ctx session` status from an arbitrary directory) — never for
394    /// injecting knowledge into a new project's context. Prefer `load_latest`.
395    pub fn load_global_latest_pointer() -> Option<Self> {
396        let dir = sessions_dir()?;
397        let latest_path = dir.join("latest.json");
398        let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
399        let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
400        Self::load_by_id(&pointer.id)
401    }
402
403    /// Loads the most recent session matching a specific project root.
404    ///
405    /// A valid per-project index is the only nominal path: one index read and
406    /// one session read, independent of the global session-store cardinality.
407    /// A missing, corrupt, or stale index is repaired by one exceptional scan.
408    pub fn load_latest_for_project_root(project_root: &str) -> Option<Self> {
409        let target_root = normalized_safe_project_root(project_root)?;
410        let dir = sessions_dir()?;
411
412        if let Some(index) = read_project_index(&dir, &target_root)
413            && let Some(id) = index.session_ids.last()
414            && let Some(session) = Self::load_by_id(id)
415            && session_matches_project_root(&session, std::path::Path::new(&target_root))
416        {
417            return Some(session);
418        }
419
420        repair_project_index(&dir, &target_root)
421    }
422
423    /// Loads a specific session from disk by its unique ID.
424    pub fn load_by_id(id: &str) -> Option<Self> {
425        validate_session_id(id).ok()?;
426        let dir = sessions_dir()?;
427        let path = dir.join(format!("{id}.json"));
428        let json = std::fs::read_to_string(&path).ok()?;
429        let session: Self = serde_json::from_str(&json).ok()?;
430        Some(normalize_loaded_session(session))
431    }
432
433    /// Deletes a saved session and its compaction snapshot.
434    ///
435    /// If the deleted session is the global latest pointer, the pointer is
436    /// moved to the newest remaining session or removed when none remain.
437    pub fn delete_session(id: &str) -> Result<bool, String> {
438        validate_session_id(id)?;
439        let Some(dir) = sessions_dir() else {
440            return Ok(false);
441        };
442        let path = dir.join(format!("{id}.json"));
443        if !path.exists() {
444            return Ok(false);
445        }
446
447        if let Some(session) = Self::load_by_id(id) {
448            persist_session_facts(&session)?;
449        }
450        std::fs::remove_file(&path).map_err(|e| e.to_string())?;
451
452        let snapshot = dir.join(format!("{id}_snapshot.txt"));
453        match std::fs::remove_file(&snapshot) {
454            Ok(()) => {}
455            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
456            Err(e) => return Err(e.to_string()),
457        }
458
459        let latest_path = dir.join("latest.json");
460        let points_to_deleted = std::fs::read_to_string(&latest_path)
461            .ok()
462            .and_then(|json| serde_json::from_str::<LatestPointer>(&json).ok())
463            .is_some_and(|pointer| pointer.id == id);
464        if points_to_deleted {
465            if let Some(next) = Self::list_sessions().into_iter().next() {
466                let latest_tmp = dir.join(".latest.json.tmp");
467                let pointer_json = serde_json::to_string(&LatestPointer { id: next.id })
468                    .map_err(|e| e.to_string())?;
469                std::fs::write(&latest_tmp, pointer_json).map_err(|e| e.to_string())?;
470                restrict_file_permissions(&latest_tmp);
471                std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
472            } else {
473                match std::fs::remove_file(&latest_path) {
474                    Ok(()) => {}
475                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
476                    Err(e) => return Err(e.to_string()),
477                }
478            }
479        }
480
481        Ok(true)
482    }
483
484    /// Lists all saved sessions as summaries, sorted by most recently updated.
485    pub fn list_sessions() -> Vec<SessionSummary> {
486        let Some(dir) = sessions_dir() else {
487            return Vec::new();
488        };
489
490        let mut summaries = Vec::new();
491        if let Ok(entries) = std::fs::read_dir(&dir) {
492            for entry in entries.flatten() {
493                let path = entry.path();
494                if path.extension().and_then(|e| e.to_str()) != Some("json") {
495                    continue;
496                }
497                if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
498                    continue;
499                }
500                if let Ok(json) = std::fs::read_to_string(&path)
501                    && let Ok(session) = serde_json::from_str::<SessionState>(&json)
502                {
503                    summaries.push(SessionSummary {
504                        id: session.id,
505                        started_at: session.started_at,
506                        updated_at: session.updated_at,
507                        version: session.version,
508                        task: session.task.as_ref().map(|t| t.description.clone()),
509                        tool_calls: session.stats.total_tool_calls,
510                        tokens_saved: session.stats.total_tokens_saved,
511                        project_root: session.project_root,
512                    });
513                }
514            }
515        }
516
517        summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
518        summaries
519    }
520
521    /// Scans all saved sessions for contaminated ones — those rooted at a
522    /// broad/unsafe path (HOME, filesystem root, agent sandbox dir) without a
523    /// real project marker, i.e. the historic "HOME mega-session" artifact.
524    ///
525    /// Returns `(found, quarantined)` where `found` is `(id, root)` pairs. When
526    /// `apply` is true, each offending session file is moved to a
527    /// `sessions/quarantine/` subdirectory (non-destructive) instead of being
528    /// loaded into any project's context.
529    pub fn doctor_quarantine_unsafe_roots(apply: bool) -> (Vec<(String, String)>, usize) {
530        let mut found: Vec<(String, String)> = Vec::new();
531        let mut quarantined = 0usize;
532        let Some(dir) = sessions_dir() else {
533            return (found, quarantined);
534        };
535        let Ok(entries) = std::fs::read_dir(&dir) else {
536            return (found, quarantined);
537        };
538        for entry in entries.flatten() {
539            let path = entry.path();
540            if path.extension().and_then(|e| e.to_str()) != Some("json") {
541                continue;
542            }
543            let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
544                continue;
545            };
546            if id == "latest" || id.starts_with('.') {
547                continue;
548            }
549            let Some(session) = Self::load_by_id(id) else {
550                continue;
551            };
552            let Some(root) = session.project_root.as_deref() else {
553                continue;
554            };
555            let root_path = std::path::Path::new(root);
556            if crate::core::pathutil::is_broad_or_unsafe_root(root_path) {
557                found.push((id.to_string(), root.to_string()));
558                if apply {
559                    let q_dir = dir.join("quarantine");
560                    if std::fs::create_dir_all(&q_dir).is_ok()
561                        && std::fs::rename(&path, q_dir.join(format!("{id}.json"))).is_ok()
562                    {
563                        quarantined += 1;
564                    }
565                }
566            }
567        }
568        (found, quarantined)
569    }
570
571    /// Deletes sessions older than `max_age_days`, preserving the most recent
572    /// session for every project root. Returns the count removed.
573    ///
574    /// This is an explicit retention operation, so its single store scan stays
575    /// off the command hot path.
576    pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
577        let Some(dir) = sessions_dir() else { return 0 };
578        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
579        let global_latest = Self::load_global_latest_pointer().map(|session| session.id);
580        let mut sessions = Vec::new();
581
582        if let Ok(entries) = std::fs::read_dir(&dir) {
583            for entry in entries.flatten() {
584                let path = entry.path();
585                if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
586                    continue;
587                }
588                let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
589                    continue;
590                };
591                if id == "latest" || id.starts_with('.') {
592                    continue;
593                }
594                if let Some(session) = Self::load_by_id(id) {
595                    sessions.push((path, session));
596                }
597            }
598        }
599
600        let mut newest_by_project = std::collections::HashMap::new();
601        for (_, session) in &sessions {
602            let Some(project_root) = session
603                .project_root
604                .as_deref()
605                .filter(|root| !root.trim().is_empty())
606            else {
607                continue;
608            };
609            newest_by_project
610                .entry(project_root)
611                .and_modify(|current: &mut &SessionState| {
612                    if session.updated_at > current.updated_at {
613                        *current = session;
614                    }
615                })
616                .or_insert(session);
617        }
618
619        let mut retained_ids: std::collections::HashSet<String> = newest_by_project
620            .values()
621            .map(|session| session.id.clone())
622            .collect();
623        if let Some(id) = global_latest {
624            retained_ids.insert(id);
625        }
626
627        sessions
628            .into_iter()
629            .filter(|(_, session)| {
630                session.updated_at < cutoff && !retained_ids.contains(&session.id)
631            })
632            .filter(|(_, session)| persist_session_facts(session).is_ok())
633            .filter(|(path, _)| std::fs::remove_file(path).is_ok())
634            .map(|(path, session)| {
635                let snapshot = path.with_file_name(format!("{}_snapshot.txt", session.id));
636                let _ = std::fs::remove_file(snapshot);
637            })
638            .count() as u32
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::{
645        ProjectSessionIndex, SessionState, normalized_safe_project_root, project_index_path,
646        write_project_index,
647    };
648    use chrono::{Duration, Utc};
649
650    #[test]
651    fn recent_project_sessions_use_bounded_index_without_scanning_legacy_store() {
652        let _data = crate::core::data_dir::isolated_data_dir();
653        let project = tempfile::tempdir().expect("project tempdir");
654        let root = project.path().to_string_lossy().to_string();
655
656        for id in ["first", "second", "third"] {
657            let mut session = SessionState::new();
658            session.id = id.to_string();
659            session.project_root = Some(root.clone());
660            session.save().expect("save indexed session");
661        }
662
663        // A malformed legacy artifact proves the hot path consults only the
664        // per-project index, never `list_sessions()` as a hidden fallback.
665        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
666        std::fs::write(sessions.join("legacy-unreadable.json"), "not json")
667            .expect("write legacy artifact");
668
669        let ids: Vec<_> = SessionState::load_recent_for_project_root(&root, 8)
670            .into_iter()
671            .map(|session| session.id)
672            .collect();
673        assert_eq!(ids, ["third", "second", "first"]);
674    }
675
676    #[test]
677    fn recent_project_sessions_refuse_broad_roots() {
678        let _data = crate::core::data_dir::isolated_data_dir();
679        assert!(SessionState::load_recent_for_project_root("/", 8).is_empty());
680    }
681
682    #[test]
683    fn broad_root_sessions_are_never_persisted() {
684        let _data = crate::core::data_dir::isolated_data_dir();
685        let mut session = SessionState::new();
686        session.project_root = Some("/".to_string());
687
688        let error = session
689            .save()
690            .expect_err("broad root save must be rejected");
691
692        assert!(error.contains("broad or unsafe"));
693        assert!(
694            crate::core::session::paths::sessions_dir()
695                .expect("sessions dir")
696                .read_dir()
697                .map_or(true, |mut entries| entries.next().is_none())
698        );
699    }
700
701    #[test]
702    fn latest_project_session_uses_valid_index_without_scanning_unindexed_sessions() {
703        let _data = crate::core::data_dir::isolated_data_dir();
704        let project = tempfile::tempdir().expect("project tempdir");
705        let root = project.path().to_string_lossy().to_string();
706
707        let mut indexed = SessionState::new();
708        indexed.id = "indexed".to_string();
709        indexed.project_root = Some(root.clone());
710        indexed.updated_at = Utc::now() - Duration::hours(1);
711        indexed.save().expect("save indexed session");
712
713        // This valid but unindexed legacy file is newer. The nominal path must
714        // trust the index and never deserialize unrelated root-level sessions.
715        let mut unindexed = SessionState::new();
716        unindexed.id = "unindexed".to_string();
717        unindexed.project_root = Some(root.clone());
718        unindexed.updated_at = Utc::now();
719        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
720        std::fs::write(
721            sessions.join("unindexed.json"),
722            serde_json::to_string(&unindexed).expect("serialize legacy session"),
723        )
724        .expect("write unindexed session");
725
726        assert_eq!(
727            SessionState::load_latest_for_project_root(&root)
728                .expect("load indexed session")
729                .id,
730            "indexed"
731        );
732    }
733
734    #[test]
735    fn latest_project_session_repairs_a_missing_index() {
736        let _data = crate::core::data_dir::isolated_data_dir();
737        let project = tempfile::tempdir().expect("project tempdir");
738        let root = project.path().to_string_lossy().to_string();
739        let mut session = SessionState::new();
740        session.id = "repair-missing".to_string();
741        session.project_root = Some(root.clone());
742        session.save().expect("save indexed session");
743
744        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
745        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
746        let index_path = project_index_path(&sessions, &canonical_root);
747        std::fs::remove_file(&index_path).expect("remove project index");
748
749        assert_eq!(
750            SessionState::load_latest_for_project_root(&root)
751                .expect("repair and load session")
752                .id,
753            "repair-missing"
754        );
755        let repaired: ProjectSessionIndex =
756            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
757                .expect("valid repaired index");
758        assert_eq!(repaired.session_ids, ["repair-missing"]);
759    }
760
761    #[test]
762    fn latest_project_session_repairs_an_empty_index() {
763        let _data = crate::core::data_dir::isolated_data_dir();
764        let project = tempfile::tempdir().expect("project tempdir");
765        let root = project.path().to_string_lossy().to_string();
766        let mut session = SessionState::new();
767        session.id = "repair-empty".to_string();
768        session.project_root = Some(root.clone());
769        session.save().expect("save indexed session");
770
771        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
772        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
773        let index_path = project_index_path(&sessions, &canonical_root);
774        write_project_index(
775            &index_path,
776            &ProjectSessionIndex {
777                version: 1,
778                project_root: canonical_root,
779                session_ids: Vec::new(),
780            },
781        )
782        .expect("empty project index");
783
784        assert_eq!(
785            SessionState::load_latest_for_project_root(&root)
786                .expect("repair and load session")
787                .id,
788            "repair-empty"
789        );
790        let repaired: ProjectSessionIndex =
791            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
792                .expect("valid repaired index");
793        assert_eq!(repaired.session_ids, ["repair-empty"]);
794    }
795
796    #[test]
797    fn latest_project_session_repairs_a_corrupt_index() {
798        let _data = crate::core::data_dir::isolated_data_dir();
799        let project = tempfile::tempdir().expect("project tempdir");
800        let root = project.path().to_string_lossy().to_string();
801        let mut session = SessionState::new();
802        session.id = "repair-corrupt".to_string();
803        session.project_root = Some(root.clone());
804        session.save().expect("save indexed session");
805
806        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
807        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
808        let index_path = project_index_path(&sessions, &canonical_root);
809        std::fs::write(&index_path, "not json").expect("corrupt project index");
810
811        assert_eq!(
812            SessionState::load_latest_for_project_root(&root)
813                .expect("repair and load session")
814                .id,
815            "repair-corrupt"
816        );
817        let repaired: ProjectSessionIndex =
818            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
819                .expect("valid repaired index");
820        assert_eq!(repaired.session_ids, ["repair-corrupt"]);
821    }
822
823    #[test]
824    fn latest_project_session_repairs_an_index_with_a_missing_session() {
825        let _data = crate::core::data_dir::isolated_data_dir();
826        let project = tempfile::tempdir().expect("project tempdir");
827        let root = project.path().to_string_lossy().to_string();
828
829        let mut older = SessionState::new();
830        older.id = "repair-older".to_string();
831        older.project_root = Some(root.clone());
832        older.updated_at = Utc::now() - Duration::hours(1);
833        older.save().expect("save older session");
834
835        let mut missing = SessionState::new();
836        missing.id = "repair-missing-file".to_string();
837        missing.project_root = Some(root.clone());
838        missing.save().expect("save missing session");
839        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
840        std::fs::remove_file(sessions.join("repair-missing-file.json"))
841            .expect("remove indexed session");
842
843        assert_eq!(
844            SessionState::load_latest_for_project_root(&root)
845                .expect("repair and load fallback")
846                .id,
847            "repair-older"
848        );
849        let repaired: ProjectSessionIndex = serde_json::from_str(
850            &std::fs::read_to_string(project_index_path(
851                &sessions,
852                &normalized_safe_project_root(&root).expect("safe root"),
853            ))
854            .expect("repaired index"),
855        )
856        .expect("valid repaired index");
857        assert_eq!(repaired.session_ids, ["repair-older"]);
858    }
859
860    #[test]
861    fn cleanup_old_sessions_preserves_the_latest_session_for_each_project() {
862        let _data = crate::core::data_dir::isolated_data_dir();
863        let project_a = tempfile::tempdir().expect("project A");
864        let project_b = tempfile::tempdir().expect("project B");
865        let root_a = project_a.path().to_string_lossy().to_string();
866        let root_b = project_b.path().to_string_lossy().to_string();
867
868        for (id, root, age_days) in [
869            ("a-old", root_a.as_str(), 10),
870            ("a-latest", root_a.as_str(), 8),
871            ("b-old", root_b.as_str(), 10),
872            ("b-latest", root_b.as_str(), 8),
873        ] {
874            let mut session = SessionState::new();
875            session.id = id.to_string();
876            session.project_root = Some(root.to_string());
877            session.updated_at = Utc::now() - Duration::days(age_days);
878            session.save().expect("save session");
879        }
880
881        assert_eq!(SessionState::cleanup_old_sessions(7), 2);
882        assert!(SessionState::load_by_id("a-latest").is_some());
883        assert!(SessionState::load_by_id("b-latest").is_some());
884        assert!(SessionState::load_by_id("a-old").is_none());
885        assert!(SessionState::load_by_id("b-old").is_none());
886    }
887
888    #[test]
889    fn deferred_save_cannot_replace_a_newer_session_version() {
890        let _data = crate::core::data_dir::isolated_data_dir();
891        let mut session = SessionState::new();
892        let id = session.id.clone();
893        let older = session.prepare_save().expect("prepare older save");
894        session.increment();
895        let expected_version = session.version;
896        let newer = session.prepare_save().expect("prepare newer save");
897
898        newer.write_to_disk().expect("write newer save");
899        older.write_to_disk().expect("skip older save");
900
901        assert_eq!(
902            SessionState::load_by_id(&id)
903                .expect("load persisted session")
904                .version,
905            expected_version
906        );
907    }
908}