Skip to main content

lean_ctx/core/session/
persistence.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use chrono::Utc;
4use serde::{Deserialize, Serialize};
5use sha2::{Digest as _, Sha256};
6
7use super::heuristics::{normalize_loaded_session, session_matches_project_root};
8use super::paths::sessions_dir;
9use super::save_outcome::SaveOutcome;
10use super::state::extract_session_facts;
11#[allow(clippy::wildcard_imports)]
12use super::types::*;
13
14/// Keep the startup warm set deliberately small: cache warming is an optional
15/// optimisation and must never turn process startup into a session-store scan.
16const PROJECT_HISTORY_LIMIT: usize = 8;
17
18/// How long a save waits for the per-session lock before reporting failure.
19/// Generous enough that an ordinary concurrent save wins it, short enough that
20/// a holder which has stopped making progress cannot hold a caller forever.
21#[cfg(not(test))]
22const SAVE_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
23/// The wedged-holder test waits this out under the global test env lock.
24#[cfg(test)]
25const SAVE_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(crate) enum SessionScopeError {
29    ProjectRootMismatch,
30}
31
32#[derive(Debug, Default, Deserialize, Serialize)]
33struct ProjectSessionIndex {
34    version: u8,
35    project_root: String,
36    /// Oldest to newest; duplicates are removed before appending on every save.
37    session_ids: Vec<String>,
38    /// Set only by a full-store scan that found no session for this root, written
39    /// under the index lock. It makes "no session" a cached answer: without it
40    /// every process (each hook call loads config, which resolves the project
41    /// root) re-parsed the whole session store for a project without sessions.
42    /// Any save for the root appends an id, which ends the empty state.
43    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
44    verified_empty: bool,
45}
46
47fn normalized_safe_project_root(project_root: &str) -> Option<String> {
48    let path = std::path::Path::new(project_root);
49    if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
50        return None;
51    }
52    Some(
53        crate::core::pathutil::safe_canonicalize_or_self(path)
54            .to_string_lossy()
55            .to_string(),
56    )
57}
58
59/// Normalize a receiving project root without accepting an implicit CWD.
60///
61/// The legacy loader intentionally accepts relative roots for compatibility;
62/// session replacement must not use that heuristic as an authority because a
63/// relative value can resolve to a different process working directory.
64fn normalized_strict_project_root(project_root: &str) -> Option<String> {
65    let path = std::path::Path::new(project_root);
66    if project_root.trim().is_empty()
67        || !path.is_absolute()
68        || crate::core::pathutil::is_broad_or_unsafe_root(path)
69    {
70        return None;
71    }
72
73    let normalized = crate::core::pathutil::safe_canonicalize_or_self(path);
74    if !normalized.is_absolute() || crate::core::pathutil::is_broad_or_unsafe_root(&normalized) {
75        return None;
76    }
77    Some(normalized.to_string_lossy().to_string())
78}
79
80fn project_index_path(dir: &std::path::Path, project_root: &str) -> std::path::PathBuf {
81    let key = blake3::hash(project_root.as_bytes()).to_hex();
82    dir.join("project-index").join(format!("{key}.json"))
83}
84
85fn read_project_index(dir: &std::path::Path, project_root: &str) -> Option<ProjectSessionIndex> {
86    std::fs::read_to_string(project_index_path(dir, project_root))
87        .ok()
88        .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
89        .filter(|index| index.version == 1 && index.project_root == project_root)
90}
91
92fn project_head_from_bytes(
93    id: &str,
94    project_root: &str,
95    bytes: &[u8],
96) -> Result<(String, String), String> {
97    let json =
98        std::str::from_utf8(bytes).map_err(|_| "corrupt project session head".to_string())?;
99    let session = SessionState::from_storage_json(json)
100        .map(normalize_loaded_session)
101        .map_err(|_| "corrupt project session head".to_string())?;
102    if session.id != id {
103        return Err("corrupt project session head id".to_string());
104    }
105    if !session_matches_project_root(&session, std::path::Path::new(project_root)) {
106        return Err("project session head root mismatch".to_string());
107    }
108    let digest = Sha256::digest(bytes);
109    Ok((session.id, format!("sha256:{}", hex::encode(digest))))
110}
111
112/// Resolve the canonical project head without changing the index. Callers hold
113/// the project lock so a save cannot move the index between selection and read.
114fn read_project_head_locked(
115    dir: &std::path::Path,
116    project_root: &str,
117) -> Result<Option<(String, String)>, String> {
118    if project_index_path(dir, project_root).exists()
119        && read_project_index(dir, project_root).is_none()
120    {
121        return Err("corrupt project session index".to_string());
122    }
123    if let Some(index) = read_project_index(dir, project_root)
124        && let Some(id) = index.session_ids.last()
125    {
126        validate_session_id(id).map_err(|_| "invalid project session index head".to_string())?;
127        let path = dir.join(format!("{id}.json"));
128        match std::fs::read(path) {
129            Ok(bytes) => {
130                let json = std::str::from_utf8(&bytes)
131                    .map_err(|_| "corrupt project session head".to_string())?;
132                let session = SessionState::from_storage_json(json)
133                    .map(normalize_loaded_session)
134                    .map_err(|_| "corrupt project session head".to_string())?;
135                if session.id.as_str() != id.as_str() {
136                    return Err("corrupt project session head id".to_string());
137                }
138                let Some(session_root) = session.project_root.as_deref() else {
139                    return Err("unsafe project session head root".to_string());
140                };
141                if normalized_safe_project_root(session_root).is_none() {
142                    return Err("unsafe project session head root".to_string());
143                }
144                if session_matches_project_root(&session, std::path::Path::new(project_root)) {
145                    let digest = Sha256::digest(&bytes);
146                    return Ok(Some((
147                        session.id,
148                        format!("sha256:{}", hex::encode(digest)),
149                    )));
150                }
151                // A safe but stale index entry follows the existing loader's
152                // repair semantics; the scan below remains read-only for CAS.
153            }
154            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
155            Err(error) => return Err(format!("read project session head: {error}")),
156        }
157    }
158
159    let entries = match std::fs::read_dir(dir) {
160        Ok(entries) => entries,
161        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
162        Err(error) => return Err(format!("scan project sessions: {error}")),
163    };
164    let mut matches = Vec::new();
165    for entry in entries {
166        let entry = entry.map_err(|error| format!("scan project sessions: {error}"))?;
167        let path = entry.path();
168        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
169            continue;
170        }
171        let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
172            continue;
173        };
174        if id == "latest" || id.starts_with('.') {
175            continue;
176        }
177        let bytes = match std::fs::read(&path) {
178            Ok(bytes) => bytes,
179            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
180            Err(error) => return Err(format!("read project session: {error}")),
181        };
182        let json = std::str::from_utf8(&bytes)
183            .map_err(|_| "unreadable session during project recovery".to_string())?;
184        let session = SessionState::from_storage_json(json)
185            .map(normalize_loaded_session)
186            .map_err(|_| "unreadable session during project recovery".to_string())?;
187        if session.id != id {
188            continue;
189        }
190        if session_matches_project_root(&session, std::path::Path::new(project_root)) {
191            matches.push((session.updated_at, session.id, bytes));
192        }
193    }
194    matches.sort_by_key(|(updated_at, _, _)| *updated_at);
195    matches
196        .pop()
197        .map(|(_, id, bytes)| project_head_from_bytes(&id, project_root, &bytes))
198        .transpose()
199}
200
201fn write_project_index(
202    index_path: &std::path::Path,
203    index: &ProjectSessionIndex,
204) -> Result<(), String> {
205    let json = serde_json::to_string(index).map_err(|e| format!("serialize project index: {e}"))?;
206    let tmp = index_path.with_extension(format!("{}.tmp", std::process::id()));
207    std::fs::write(&tmp, json).map_err(|e| format!("write project index: {e}"))?;
208    restrict_file_permissions(&tmp);
209    std::fs::rename(tmp, index_path).map_err(|e| format!("commit project index: {e}"))
210}
211
212fn with_project_index_lock<T>(
213    dir: &std::path::Path,
214    project_root: &str,
215    operation: impl FnOnce(&std::path::Path) -> Result<T, String>,
216) -> Result<T, String> {
217    use fs2::FileExt;
218    use std::time::Duration;
219
220    const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
221
222    let index_path = project_index_path(dir, project_root);
223    let index_dir = index_path.parent().ok_or("project index has no parent")?;
224    std::fs::create_dir_all(index_dir).map_err(|e| format!("create project index: {e}"))?;
225    let lock = std::fs::OpenOptions::new()
226        .create(true)
227        .truncate(false)
228        .write(true)
229        .open(index_path.with_extension("lock"))
230        .map_err(|e| format!("project index lock: {e}"))?;
231    crate::core::file_lock::acquire_exclusive_timeout(&lock, LOCK_TIMEOUT)
232        .map_err(|e| format!("project index lock: {e}"))?;
233    let result = operation(&index_path);
234    let _ = FileExt::unlock(&lock);
235    result
236}
237
238/// Update one project's bounded warm-history index while its project lock is
239/// already held. The index remains an acceleration structure.
240fn update_project_index_locked(
241    dir: &std::path::Path,
242    project_root: &str,
243    index_path: &std::path::Path,
244    id: &str,
245) -> Result<(), String> {
246    let mut index = read_project_index(dir, project_root).unwrap_or_else(|| ProjectSessionIndex {
247        version: 1,
248        project_root: project_root.to_string(),
249        session_ids: Vec::new(),
250        verified_empty: false,
251    });
252    index.verified_empty = false;
253    index.session_ids.retain(|existing| existing != id);
254    index.session_ids.push(id.to_string());
255    let excess = index
256        .session_ids
257        .len()
258        .saturating_sub(PROJECT_HISTORY_LIMIT);
259    if excess > 0 {
260        index.session_ids.drain(..excess);
261    }
262    write_project_index(index_path, &index)
263}
264
265fn repair_project_index(dir: &std::path::Path, project_root: &str) -> Option<SessionState> {
266    // Scan outside the short index lock. A save can proceed during a slow scan;
267    // its index entry is merged below before the repaired index is written.
268    let entries = std::fs::read_dir(dir).ok()?;
269    let mut matches = Vec::new();
270    for entry in entries.flatten() {
271        let path = entry.path();
272        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
273            continue;
274        }
275        let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
276            continue;
277        };
278        if id == "latest" || id.starts_with('.') {
279            continue;
280        }
281        let Some(session) = SessionState::load_by_id(id) else {
282            continue;
283        };
284        if session_matches_project_root(&session, std::path::Path::new(project_root)) {
285            matches.push(session);
286        }
287    }
288    matches.sort_by_key(|session| session.updated_at);
289    let latest = matches.last().cloned();
290    let scanned_ids: Vec<String> = matches.iter().map(|session| session.id.clone()).collect();
291    let result = with_project_index_lock(dir, project_root, |index_path| {
292        // The scan ran outside the lock; a save may have indexed a session in the
293        // meantime. Merge instead of overwriting so that id is never lost, but drop
294        // ids whose file is gone (the reason this repair ran).
295        let mut session_ids = scanned_ids;
296        if let Some(current) = read_project_index(dir, project_root) {
297            for id in current.session_ids {
298                if validate_session_id(&id).is_err() || !dir.join(format!("{id}.json")).is_file() {
299                    continue;
300                }
301                session_ids.retain(|existing| existing != &id);
302                session_ids.push(id);
303            }
304        }
305        let first_retained = session_ids.len().saturating_sub(PROJECT_HISTORY_LIMIT);
306        session_ids.drain(..first_retained);
307        write_project_index(
308            index_path,
309            &ProjectSessionIndex {
310                version: 1,
311                project_root: project_root.to_string(),
312                verified_empty: session_ids.is_empty(),
313                session_ids,
314            },
315        )?;
316        Ok(latest)
317    });
318    if let Err(error) = &result {
319        tracing::debug!("lean-ctx: session project index repair skipped: {error}");
320    }
321    result.ok().flatten()
322}
323
324#[cfg(unix)]
325fn restrict_file_permissions(path: &std::path::Path) {
326    use std::os::unix::fs::PermissionsExt;
327    let perms = std::fs::Permissions::from_mode(0o600);
328    let _ = std::fs::set_permissions(path, perms);
329}
330
331#[cfg(not(unix))]
332fn restrict_file_permissions(_path: &std::path::Path) {}
333
334fn validate_session_id(id: &str) -> Result<(), String> {
335    if id.is_empty()
336        || id == "latest"
337        || id.starts_with('.')
338        || id.contains('/')
339        || id.contains('\\')
340        || id.contains(std::path::MAIN_SEPARATOR)
341    {
342        return Err("invalid session id".to_string());
343    }
344    Ok(())
345}
346
347fn persist_session_facts(session: &SessionState) -> Result<(), String> {
348    let Some(project_root) = session
349        .project_root
350        .as_deref()
351        .filter(|project_root| !project_root.trim().is_empty())
352    else {
353        return Ok(());
354    };
355
356    let facts = extract_session_facts(session);
357    if facts.is_empty() {
358        return Ok(());
359    }
360
361    let mut knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
362    for fact in facts {
363        knowledge.add_fact(fact);
364    }
365    knowledge.save()
366}
367
368impl PreparedSave {
369    /// Writes the pre-serialized session data, latest pointer, and compaction
370    /// snapshot to disk atomically. A per-session file lock and version check
371    /// make deferred saves monotonic even when background tasks finish out of
372    /// order.
373    ///
374    /// The lock has a deadline. A save that cannot get it reports that instead
375    /// of waiting, because `SessionState::save` restores `unsaved_changes` on
376    /// `Err` and the next batch tries again — whereas a caller stuck in an
377    /// unbounded wait keeps whatever it holds until the other side lets go
378    /// (#1783).
379    pub fn write_to_disk(self) -> Result<(), String> {
380        self.write_to_disk_with_policy(false).result
381    }
382
383    pub(super) fn write_to_disk_with_policy(self, require_new: bool) -> SaveOutcome {
384        let mut outcome = SaveOutcome::new(&self);
385        outcome.result = self.write_primary_and_pointers(require_new, &mut outcome);
386        outcome
387    }
388
389    fn write_new_if_project_head(
390        self,
391        expected: Option<&(String, String)>,
392    ) -> Result<Option<SaveOutcome>, String> {
393        let Some(project_root) = self.project_index_root.clone() else {
394            return Err("project head publication requires a safe project root".to_string());
395        };
396        let dir = self.dir.clone();
397        let mut outcome = SaveOutcome::new(&self);
398        let published = with_project_index_lock(&dir, &project_root, |index_path| {
399            let current = read_project_head_locked(&dir, &project_root)?;
400            if current.as_ref() != expected {
401                return Ok(false);
402            }
403            outcome.result = self.write_primary_and_pointers_locked(
404                true,
405                &mut outcome,
406                Some((&project_root, index_path)),
407            );
408            Ok(true)
409        })?;
410        if published {
411            Ok(Some(outcome))
412        } else {
413            Ok(None)
414        }
415    }
416
417    fn write_primary_and_pointers(
418        self,
419        require_new: bool,
420        outcome: &mut SaveOutcome,
421    ) -> Result<(), String> {
422        if !self.dir.exists() {
423            std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
424        }
425        if let Some(project_root) = self.project_index_root.clone() {
426            let dir = self.dir.clone();
427            return with_project_index_lock(&dir, &project_root, |index_path| {
428                self.write_primary_and_pointers_locked(
429                    require_new,
430                    outcome,
431                    Some((&project_root, index_path)),
432                )
433            });
434        }
435        self.write_primary_and_pointers_locked(require_new, outcome, None)
436    }
437
438    fn write_primary_and_pointers_locked(
439        self,
440        require_new: bool,
441        outcome: &mut SaveOutcome,
442        project_index: Option<(&str, &std::path::Path)>,
443    ) -> Result<(), String> {
444        use fs2::FileExt;
445        let lock_path = self.dir.join(format!(".{}.save.lock", self.id));
446        let lock = std::fs::OpenOptions::new()
447            .create(true)
448            .truncate(false)
449            .write(true)
450            .open(lock_path)
451            .map_err(|e| format!("open session save lock: {e}"))?;
452        crate::core::file_lock::acquire_exclusive_timeout(&lock, SAVE_LOCK_TIMEOUT)
453            .map_err(|e| format!("lock session save: {e}"))?;
454
455        let result = (|| {
456            let path = self.dir.join(format!("{}.json", self.id));
457            if require_new && path.try_exists().map_err(|error| error.to_string())? {
458                return Err("import destination already exists".to_string());
459            }
460            if !self.canonical
461                && persisted_session_version(&path).is_some_and(|version| version > self.version)
462            {
463                return Ok(());
464            }
465            let previous = match std::fs::read(&path) {
466                Ok(bytes) => Some(bytes),
467                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
468                Err(error) => return Err(error.to_string()),
469            };
470            let json = crate::core::context_checkpoint::prepare_session_checkpoint_commit(
471                &self.json,
472                previous.as_deref(),
473            )?;
474            let committed = SessionState::from_storage_json(&json)?.canonical_checkpoint;
475            outcome.primary_sha256 = Some(hex::encode(Sha256::digest(json.as_bytes())));
476            let tmp = self.dir.join(format!(".{}.json.tmp", self.id));
477            if require_new {
478                use std::io::Write as _;
479                let mut options = std::fs::OpenOptions::new();
480                options.write(true).create_new(true);
481                #[cfg(unix)]
482                {
483                    use std::os::unix::fs::OpenOptionsExt as _;
484                    options.mode(0o600);
485                }
486                let mut file = options.open(&tmp).map_err(|error| error.to_string())?;
487                file.write_all(json.as_bytes())
488                    .map_err(|error| error.to_string())?;
489                file.sync_all().map_err(|error| error.to_string())?;
490            } else {
491                std::fs::write(&tmp, &json).map_err(|e| e.to_string())?;
492            }
493            restrict_file_permissions(&tmp);
494            if require_new {
495                // Atomic no-replace publication, including non-cooperating
496                // writers that do not acquire this session's file lock.
497                std::fs::hard_link(&tmp, &path).map_err(|error| error.to_string())?;
498                outcome.committed = committed;
499                std::fs::remove_file(&tmp).map_err(|error| error.to_string())?;
500            } else {
501                std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
502                outcome.committed = committed;
503            }
504
505            let latest_path = self.dir.join("latest.json");
506            let latest_tmp = self.dir.join(format!(".{}.latest.tmp", self.id));
507            std::fs::write(&latest_tmp, &self.pointer_json).map_err(|e| e.to_string())?;
508            restrict_file_permissions(&latest_tmp);
509            std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
510
511            if let Some(snapshot) = self.compaction_snapshot {
512                let snap_path = self.dir.join(format!("{}_snapshot.txt", self.id));
513                if let Err(error) = crate::core::atomic_fs::write_bytes_with_fallback(
514                    &snap_path,
515                    snapshot.as_bytes(),
516                    None,
517                ) {
518                    tracing::debug!("lean-ctx: compaction snapshot update skipped: {error}");
519                } else {
520                    restrict_file_permissions(&snap_path);
521                }
522            }
523            if let Some((project_root, index_path)) = project_index
524                && let Err(error) =
525                    update_project_index_locked(&self.dir, project_root, index_path, &self.id)
526            {
527                tracing::debug!("lean-ctx: session warm-history index update skipped: {error}");
528            }
529            Ok(())
530        })();
531        let _ = FileExt::unlock(&lock);
532        result
533    }
534}
535
536fn persisted_session_version(path: &std::path::Path) -> Option<u32> {
537    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
538    value["version"].as_u64()?.try_into().ok()
539}
540
541impl SessionState {
542    /// Return the exact persisted project head and its primary-file SHA-256.
543    ///
544    /// The project index is consulted first, with the existing repair scan
545    /// semantics used read-only when the index is absent or stale.
546    pub(crate) fn project_head(project_root: &str) -> Result<Option<(String, String)>, String> {
547        let Some(project_root) = normalized_safe_project_root(project_root) else {
548            return Err("unsafe project root".to_string());
549        };
550        let dir = sessions_dir().ok_or("cannot determine home directory")?;
551        with_project_index_lock(&dir, &project_root, |_| {
552            read_project_head_locked(&dir, &project_root)
553        })
554    }
555
556    /// Load the selected session and hash the exact primary file bytes together.
557    /// If the primary changes after head selection, fail closed for caller retry.
558    pub(crate) fn load_project_head_snapshot(
559        project_root: &str,
560    ) -> Result<Option<(Self, String)>, String> {
561        let Some(project_root) = normalized_safe_project_root(project_root) else {
562            return Err("unsafe project root".to_string());
563        };
564        let dir = sessions_dir().ok_or("cannot determine home directory")?;
565        with_project_index_lock(&dir, &project_root, |_| {
566            let Some((id, expected_digest)) = read_project_head_locked(&dir, &project_root)? else {
567                return Ok(None);
568            };
569            let path = dir.join(format!("{id}.json"));
570            let bytes = std::fs::read(path)
571                .map_err(|_| "project session head changed; retry".to_string())?;
572            let actual_hex = hex::encode(Sha256::digest(&bytes));
573            if expected_digest != format!("sha256:{actual_hex}") {
574                return Err("project session head changed; retry".to_string());
575            }
576            let json = std::str::from_utf8(&bytes)
577                .map_err(|_| "corrupt project session head".to_string())?;
578            let session = SessionState::from_storage_json(json)
579                .map(normalize_loaded_session)
580                .map_err(|_| "corrupt project session head".to_string())?;
581            if session.id != id
582                || !session_matches_project_root(&session, std::path::Path::new(&project_root))
583            {
584                return Err("project session head changed; retry".to_string());
585            }
586            Ok(Some((session, actual_hex)))
587        })
588    }
589
590    /// Return the current project root only when it is an absolute, non-broad
591    /// root normalized with the same path rules as scoped session loading.
592    pub(crate) fn strict_project_root(&self) -> Option<String> {
593        self.project_root
594            .as_deref()
595            .and_then(normalized_strict_project_root)
596    }
597
598    /// Compare a loaded session against an already trusted normalized root.
599    ///
600    /// Re-normalizing the expected value keeps this helper safe for callers
601    /// that do not hold the receiving-root invariant themselves.
602    pub(crate) fn has_exact_project_root(&self, expected_root: &str) -> bool {
603        let Some(expected_root) = normalized_strict_project_root(expected_root) else {
604            return false;
605        };
606        self.strict_project_root()
607            .is_some_and(|actual_root| actual_root == expected_root)
608    }
609
610    /// Counts locally recorded decisions from the trailing seven days.
611    #[must_use]
612    pub fn decision_count_this_week() -> u64 {
613        let cutoff = Utc::now() - chrono::Duration::days(7);
614        Self::list_sessions()
615            .into_iter()
616            .filter_map(|summary| Self::load_by_id(&summary.id))
617            .flat_map(|session| session.decisions)
618            .filter(|decision| decision.timestamp >= cutoff)
619            .count()
620            .try_into()
621            .unwrap_or(u64::MAX)
622    }
623
624    /// Serializes and writes the session state to disk synchronously.
625    pub fn save(&mut self) -> Result<(), String> {
626        let prepared = self
627            .prepare_save()
628            .inspect_err(|_| self.note_save_failure())?;
629        self.acknowledge_save(prepared.write_to_disk_with_policy(false))
630    }
631
632    /// Import publication never replaces an existing session archive. A failure
633    /// after primary publication may retain a new recovery candidate, not erase
634    /// the previous live session or source archive.
635    pub(crate) fn save_new(&mut self) -> Result<(), String> {
636        let prepared = self
637            .prepare_save()
638            .inspect_err(|_| self.note_save_failure())?;
639        self.acknowledge_save(prepared.write_to_disk_with_policy(true))
640    }
641
642    /// Publish a new project session only when the persisted project head still
643    /// equals `expected`; a conflict leaves all session files and pointers alone.
644    pub(crate) fn save_new_if_project_head(
645        &mut self,
646        expected: Option<&(String, String)>,
647    ) -> Result<bool, String> {
648        self.save_new_if_project_head_with_digest(expected)
649            .map(|committed| committed.is_some())
650    }
651
652    /// Publish with the existing project-head CAS and return the exact primary
653    /// session file digest produced by this commit.
654    pub(crate) fn save_new_if_project_head_with_digest(
655        &mut self,
656        expected: Option<&(String, String)>,
657    ) -> Result<Option<String>, String> {
658        let prepared = self
659            .prepare_save()
660            .inspect_err(|_| self.note_save_failure())?;
661        match prepared.write_new_if_project_head(expected) {
662            Ok(Some(outcome)) => {
663                let digest = outcome
664                    .primary_sha256
665                    .clone()
666                    .ok_or_else(|| "committed session digest unavailable".to_string())?;
667                self.acknowledge_save(outcome)?;
668                Ok(Some(digest))
669            }
670            Ok(None) => Ok(None),
671            Err(error) => {
672                self.note_save_failure();
673                Err(error)
674            }
675        }
676    }
677
678    /// Serialize session state while holding the lock (CPU-only), retaining the
679    /// unsaved counter until acknowledged, and return I/O that can be deferred
680    /// to a background thread via `write_to_disk()`.
681    pub fn prepare_save(&mut self) -> Result<PreparedSave, String> {
682        validate_session_id(&self.id)?;
683        if self
684            .project_root
685            .as_deref()
686            .is_some_and(|root| normalized_safe_project_root(root).is_none())
687        {
688            return Err(
689                "refusing to persist a session for a broad or unsafe project root".to_string(),
690            );
691        }
692        let dir = sessions_dir().ok_or("cannot determine home directory")?;
693        let compaction_snapshot = if self.stats.total_tool_calls > 0 {
694            Some(self.build_compaction_snapshot())
695        } else {
696            None
697        };
698        let (json, _) = self.storage_json()?;
699        let pointer_json = serde_json::to_string(&LatestPointer {
700            id: self.id.clone(),
701        })
702        .map_err(|e| e.to_string())?;
703        Ok(PreparedSave {
704            canonical: self.canonical_checkpoint.is_some(),
705            expected_storage_digest: self
706                .canonical_checkpoint
707                .as_ref()
708                .and_then(|binding| binding.storage_digest.clone()),
709            dir,
710            id: self.id.clone(),
711            version: self.version,
712            json,
713            pointer_json,
714            compaction_snapshot,
715            project_index_root: self
716                .project_root
717                .as_deref()
718                .and_then(normalized_safe_project_root),
719        })
720    }
721
722    /// Load the bounded warm-history set for one safe project root.
723    ///
724    /// There is intentionally no legacy full-store fallback: cache warming is
725    /// optional, while scanning every persisted session on each MCP launch is
726    /// not acceptable under concurrent agent load. New saves populate the
727    /// index; legacy sessions remain available through explicit session tools.
728    pub(crate) fn load_recent_for_project_root(project_root: &str, limit: usize) -> Vec<Self> {
729        let Some(project_root) = normalized_strict_project_root(project_root) else {
730            return Vec::new();
731        };
732        let Some(dir) = sessions_dir() else {
733            return Vec::new();
734        };
735        let Some(index) = std::fs::read_to_string(project_index_path(&dir, &project_root))
736            .ok()
737            .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
738            .filter(|index| index.version == 1 && index.project_root == project_root)
739        else {
740            return Vec::new();
741        };
742
743        index
744            .session_ids
745            .iter()
746            .rev()
747            .take(limit.min(PROJECT_HISTORY_LIMIT))
748            .filter_map(|id| {
749                Self::load_by_id_for_project_root(id, &project_root)
750                    .ok()
751                    .flatten()
752            })
753            .collect()
754    }
755
756    /// Loads the most recent session matching the current working directory's
757    /// project root.
758    ///
759    /// Returns `None` (a fresh session) rather than falling back to the global
760    /// `latest.json` pointer: that unconditional fallback bypassed project-root
761    /// matching and was the root cause of cross-project session leakage — one
762    /// project's findings/decisions/knowledge bleeding into another project's
763    /// first session. The correct project session is loaded later from the MCP
764    /// `roots` handshake (`load_latest_for_project_root`).
765    ///
766    /// Also refuses to scope to a broad/unsafe cwd (e.g. the MCP daemon's HOME),
767    /// which would otherwise resurrect the contaminated "HOME mega-session".
768    pub fn load_latest() -> Option<Self> {
769        let cwd = std::env::current_dir().ok()?;
770        if crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
771            return None;
772        }
773        Self::load_latest_for_project_root(&cwd.to_string_lossy())
774    }
775
776    /// Loads the session referenced by the global `latest.json` pointer,
777    /// regardless of project. Intended only for explicit, cross-project UX
778    /// (e.g. `lean-ctx session` status from an arbitrary directory) — never for
779    /// injecting knowledge into a new project's context. Prefer `load_latest`.
780    pub fn load_global_latest_pointer() -> Option<Self> {
781        let dir = sessions_dir()?;
782        let latest_path = dir.join("latest.json");
783        let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
784        let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
785        Self::load_by_id(&pointer.id)
786    }
787
788    /// Loads the most recent session matching a specific project root.
789    ///
790    /// A valid per-project index is the only nominal path: one index read and
791    /// one session read, independent of the global session-store cardinality.
792    /// A missing, corrupt, or stale index is repaired by one exceptional scan.
793    pub fn load_latest_for_project_root(project_root: &str) -> Option<Self> {
794        let target_root = normalized_safe_project_root(project_root)?;
795        let dir = sessions_dir()?;
796
797        if let Some(index) = read_project_index(&dir, &target_root) {
798            if let Some(id) = index.session_ids.last()
799                && let Some(session) = Self::load_by_id(id)
800                && session_matches_project_root(&session, std::path::Path::new(&target_root))
801            {
802                return Some(session);
803            }
804            if index.session_ids.is_empty() && index.verified_empty {
805                return None;
806            }
807        }
808
809        repair_project_index(&dir, &target_root)
810    }
811
812    fn load_by_id_raw(id: &str) -> Option<Self> {
813        validate_session_id(id).ok()?;
814        let dir = sessions_dir()?;
815        let path = dir.join(format!("{id}.json"));
816        let json = std::fs::read_to_string(&path).ok()?;
817        Self::from_storage_json(&json).ok()
818    }
819
820    /// Loads a specific session only when its persisted root already matches
821    /// the receiving root; legacy normalization runs after that check.
822    pub(crate) fn load_by_id_for_project_root(
823        id: &str,
824        expected_root: &str,
825    ) -> Result<Option<Self>, SessionScopeError> {
826        let Some(session) = Self::load_by_id_raw(id) else {
827            return Ok(None);
828        };
829        if !session.has_exact_project_root(expected_root) {
830            return Err(SessionScopeError::ProjectRootMismatch);
831        }
832        let persisted_project_root = session.project_root.clone();
833        let mut normalized = normalize_loaded_session(session);
834        // Keep the persisted spelling that was checked above; legacy
835        // normalization may otherwise replace an admitted root from shell_cwd.
836        normalized.project_root = persisted_project_root;
837        Ok(Some(normalized))
838    }
839
840    /// Loads a specific session from disk by its unique ID.
841    pub fn load_by_id(id: &str) -> Option<Self> {
842        Self::load_by_id_raw(id).map(normalize_loaded_session)
843    }
844
845    /// Deletes a saved session and its compaction snapshot.
846    ///
847    /// If the deleted session is the global latest pointer, the pointer is
848    /// moved to the newest remaining session or removed when none remain.
849    pub fn delete_session(id: &str) -> Result<bool, String> {
850        validate_session_id(id)?;
851        let Some(dir) = sessions_dir() else {
852            return Ok(false);
853        };
854        let path = dir.join(format!("{id}.json"));
855        if !path.exists() {
856            return Ok(false);
857        }
858
859        if let Some(session) = Self::load_by_id(id) {
860            persist_session_facts(&session)?;
861        }
862        std::fs::remove_file(&path).map_err(|e| e.to_string())?;
863
864        let snapshot = dir.join(format!("{id}_snapshot.txt"));
865        match std::fs::remove_file(&snapshot) {
866            Ok(()) => {}
867            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
868            Err(e) => return Err(e.to_string()),
869        }
870
871        let latest_path = dir.join("latest.json");
872        let points_to_deleted = std::fs::read_to_string(&latest_path)
873            .ok()
874            .and_then(|json| serde_json::from_str::<LatestPointer>(&json).ok())
875            .is_some_and(|pointer| pointer.id == id);
876        if points_to_deleted {
877            if let Some(next) = Self::list_sessions().into_iter().next() {
878                let latest_tmp = dir.join(".latest.json.tmp");
879                let pointer_json = serde_json::to_string(&LatestPointer { id: next.id })
880                    .map_err(|e| e.to_string())?;
881                std::fs::write(&latest_tmp, pointer_json).map_err(|e| e.to_string())?;
882                restrict_file_permissions(&latest_tmp);
883                std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
884            } else {
885                match std::fs::remove_file(&latest_path) {
886                    Ok(()) => {}
887                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
888                    Err(e) => return Err(e.to_string()),
889                }
890            }
891        }
892
893        Ok(true)
894    }
895
896    /// Lists all saved sessions as summaries, sorted by most recently updated.
897    pub fn list_sessions() -> Vec<SessionSummary> {
898        let Some(dir) = sessions_dir() else {
899            return Vec::new();
900        };
901
902        let mut summaries = Vec::new();
903        if let Ok(entries) = std::fs::read_dir(&dir) {
904            for entry in entries.flatten() {
905                let path = entry.path();
906                if path.extension().and_then(|e| e.to_str()) != Some("json") {
907                    continue;
908                }
909                if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
910                    continue;
911                }
912                if let Ok(json) = std::fs::read_to_string(&path)
913                    && let Ok(session) = SessionState::from_storage_json(&json)
914                {
915                    summaries.push(SessionSummary {
916                        id: session.id,
917                        started_at: session.started_at,
918                        updated_at: session.updated_at,
919                        version: session.version,
920                        task: session.task.as_ref().map(|t| t.description.clone()),
921                        tool_calls: session.stats.total_tool_calls,
922                        tokens_saved: session.stats.total_tokens_saved,
923                        project_root: session.project_root,
924                    });
925                }
926            }
927        }
928
929        summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
930        summaries
931    }
932
933    /// Scans all saved sessions for contaminated ones — those rooted at a
934    /// broad/unsafe path (HOME, filesystem root, agent sandbox dir) without a
935    /// real project marker, i.e. the historic "HOME mega-session" artifact.
936    ///
937    /// Returns `(found, quarantined)` where `found` is `(id, root)` pairs. When
938    /// `apply` is true, each offending session file is moved to a
939    /// `sessions/quarantine/` subdirectory (non-destructive) instead of being
940    /// loaded into any project's context.
941    pub fn doctor_quarantine_unsafe_roots(apply: bool) -> (Vec<(String, String)>, usize) {
942        let mut found: Vec<(String, String)> = Vec::new();
943        let mut quarantined = 0usize;
944        let Some(dir) = sessions_dir() else {
945            return (found, quarantined);
946        };
947        let Ok(entries) = std::fs::read_dir(&dir) else {
948            return (found, quarantined);
949        };
950        for entry in entries.flatten() {
951            let path = entry.path();
952            if path.extension().and_then(|e| e.to_str()) != Some("json") {
953                continue;
954            }
955            let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
956                continue;
957            };
958            if id == "latest" || id.starts_with('.') {
959                continue;
960            }
961            let Some(session) = Self::load_by_id(id) else {
962                continue;
963            };
964            let Some(root) = session.project_root.as_deref() else {
965                continue;
966            };
967            let root_path = std::path::Path::new(root);
968            if crate::core::pathutil::is_broad_or_unsafe_root(root_path) {
969                found.push((id.to_string(), root.to_string()));
970                if apply {
971                    let q_dir = dir.join("quarantine");
972                    if std::fs::create_dir_all(&q_dir).is_ok()
973                        && std::fs::rename(&path, q_dir.join(format!("{id}.json"))).is_ok()
974                    {
975                        quarantined += 1;
976                    }
977                }
978            }
979        }
980        (found, quarantined)
981    }
982
983    /// Deletes sessions older than `max_age_days`, preserving the most recent
984    /// session for every project root. Returns the count removed.
985    ///
986    /// This is an explicit retention operation, so its single store scan stays
987    /// off the command hot path.
988    pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
989        let Some(dir) = sessions_dir() else { return 0 };
990        let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
991        let global_latest = Self::load_global_latest_pointer().map(|session| session.id);
992        let mut sessions = Vec::new();
993
994        if let Ok(entries) = std::fs::read_dir(&dir) {
995            for entry in entries.flatten() {
996                let path = entry.path();
997                if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
998                    continue;
999                }
1000                let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
1001                    continue;
1002                };
1003                if id == "latest" || id.starts_with('.') {
1004                    continue;
1005                }
1006                if let Some(session) = Self::load_by_id(id) {
1007                    sessions.push((path, session));
1008                }
1009            }
1010        }
1011
1012        let mut newest_by_project = std::collections::HashMap::new();
1013        for (_, session) in &sessions {
1014            let Some(project_root) = session
1015                .project_root
1016                .as_deref()
1017                .filter(|root| !root.trim().is_empty())
1018            else {
1019                continue;
1020            };
1021            newest_by_project
1022                .entry(project_root)
1023                .and_modify(|current: &mut &SessionState| {
1024                    if session.updated_at > current.updated_at {
1025                        *current = session;
1026                    }
1027                })
1028                .or_insert(session);
1029        }
1030
1031        let mut retained_ids: std::collections::HashSet<String> = newest_by_project
1032            .values()
1033            .map(|session| session.id.clone())
1034            .collect();
1035        if let Some(id) = global_latest {
1036            retained_ids.insert(id);
1037        }
1038
1039        sessions
1040            .into_iter()
1041            .filter(|(_, session)| {
1042                session.updated_at < cutoff && !retained_ids.contains(&session.id)
1043            })
1044            .filter(|(_, session)| persist_session_facts(session).is_ok())
1045            .filter(|(path, _)| std::fs::remove_file(path).is_ok())
1046            .map(|(path, session)| {
1047                let snapshot = path.with_file_name(format!("{}_snapshot.txt", session.id));
1048                let _ = std::fs::remove_file(snapshot);
1049            })
1050            .count() as u32
1051    }
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056    use super::{
1057        ProjectSessionIndex, SessionState, normalized_safe_project_root, project_index_path,
1058        write_project_index,
1059    };
1060    use chrono::{Duration, Utc};
1061    use sha2::{Digest as _, Sha256};
1062
1063    #[test]
1064    fn recent_project_sessions_use_bounded_index_without_scanning_legacy_store() {
1065        let _data = crate::core::data_dir::isolated_data_dir();
1066        let project = tempfile::tempdir().expect("project tempdir");
1067        let root = project.path().to_string_lossy().to_string();
1068        assert_eq!(SessionState::project_head(&root), Ok(None));
1069
1070        for id in ["first", "second", "third"] {
1071            let mut session = SessionState::new();
1072            session.id = id.to_string();
1073            session.project_root = Some(root.clone());
1074            session.save().expect("save indexed session");
1075        }
1076
1077        // A malformed legacy artifact proves the hot path consults only the
1078        // per-project index, never `list_sessions()` as a hidden fallback.
1079        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1080        std::fs::write(sessions.join("legacy-unreadable.json"), "not json")
1081            .expect("write legacy artifact");
1082
1083        let ids: Vec<_> = SessionState::load_recent_for_project_root(&root, 8)
1084            .into_iter()
1085            .map(|session| session.id)
1086            .collect();
1087        assert_eq!(ids, ["third", "second", "first"]);
1088    }
1089
1090    #[test]
1091    fn recent_project_sessions_refuse_broad_roots() {
1092        let _data = crate::core::data_dir::isolated_data_dir();
1093        assert!(SessionState::load_recent_for_project_root("/", 8).is_empty());
1094    }
1095
1096    /// #1783: a save must never wait on the per-session lock indefinitely. The
1097    /// callers that matter hold a `tokio` guard the rest of the server needs,
1098    /// so an unbounded wait here is a permanent server-wide wedge; a reported
1099    /// failure is recoverable, because `save` re-arms `unsaved_changes` and the
1100    /// next batch writes.
1101    #[test]
1102    fn save_gives_up_when_another_holder_keeps_the_session_lock() {
1103        use fs2::FileExt;
1104
1105        let _data = crate::core::data_dir::isolated_data_dir();
1106        let project = tempfile::tempdir().expect("project tempdir");
1107        let mut session = SessionState::new();
1108        session.id = "wedged".to_string();
1109        session.project_root = Some(project.path().to_string_lossy().to_string());
1110
1111        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1112        std::fs::create_dir_all(&sessions).expect("create sessions dir");
1113        let holder = std::fs::File::create(sessions.join(".wedged.save.lock")).expect("lock file");
1114        holder.lock_exclusive().expect("hold the save lock");
1115
1116        let started = std::time::Instant::now();
1117        let error = session
1118            .save()
1119            .expect_err("a held lock must not be waited out");
1120        let waited = started.elapsed();
1121
1122        assert!(
1123            error.contains("lock session save"),
1124            "unexpected error: {error}"
1125        );
1126        assert!(
1127            waited < super::SAVE_LOCK_TIMEOUT * 4,
1128            "save must return on its own deadline, waited {waited:?}"
1129        );
1130        assert_ne!(
1131            session.stats.unsaved_changes, 0,
1132            "a failed save must stay pending so the next batch retries"
1133        );
1134        FileExt::unlock(&holder).expect("release");
1135    }
1136
1137    #[test]
1138    fn broad_root_sessions_are_never_persisted() {
1139        let _data = crate::core::data_dir::isolated_data_dir();
1140        let mut session = SessionState::new();
1141        session.project_root = Some("/".to_string());
1142
1143        let error = session
1144            .save()
1145            .expect_err("broad root save must be rejected");
1146
1147        assert!(error.contains("broad or unsafe"));
1148        assert!(
1149            crate::core::session::paths::sessions_dir()
1150                .expect("sessions dir")
1151                .read_dir()
1152                .map_or(true, |mut entries| entries.next().is_none())
1153        );
1154    }
1155
1156    #[test]
1157    fn latest_project_session_uses_valid_index_without_scanning_unindexed_sessions() {
1158        let _data = crate::core::data_dir::isolated_data_dir();
1159        let project = tempfile::tempdir().expect("project tempdir");
1160        let root = project.path().to_string_lossy().to_string();
1161
1162        let mut indexed = SessionState::new();
1163        indexed.id = "indexed".to_string();
1164        indexed.project_root = Some(root.clone());
1165        indexed.updated_at = Utc::now() - Duration::hours(1);
1166        indexed.save().expect("save indexed session");
1167
1168        // This valid but unindexed legacy file is newer. The nominal path must
1169        // trust the index and never deserialize unrelated root-level sessions.
1170        let mut unindexed = SessionState::new();
1171        unindexed.id = "unindexed".to_string();
1172        unindexed.project_root = Some(root.clone());
1173        unindexed.updated_at = Utc::now();
1174        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1175        std::fs::write(
1176            sessions.join("unindexed.json"),
1177            serde_json::to_string(&unindexed).expect("serialize legacy session"),
1178        )
1179        .expect("write unindexed session");
1180
1181        assert_eq!(
1182            SessionState::load_latest_for_project_root(&root)
1183                .expect("load indexed session")
1184                .id,
1185            "indexed"
1186        );
1187    }
1188
1189    #[test]
1190    fn latest_project_session_repairs_a_missing_index() {
1191        let _data = crate::core::data_dir::isolated_data_dir();
1192        let project = tempfile::tempdir().expect("project tempdir");
1193        let root = project.path().to_string_lossy().to_string();
1194        let mut session = SessionState::new();
1195        session.id = "repair-missing".to_string();
1196        session.project_root = Some(root.clone());
1197        session.save().expect("save indexed session");
1198
1199        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1200        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
1201        let index_path = project_index_path(&sessions, &canonical_root);
1202        std::fs::remove_file(&index_path).expect("remove project index");
1203
1204        assert_eq!(
1205            SessionState::load_latest_for_project_root(&root)
1206                .expect("repair and load session")
1207                .id,
1208            "repair-missing"
1209        );
1210        let repaired: ProjectSessionIndex =
1211            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
1212                .expect("valid repaired index");
1213        assert_eq!(repaired.session_ids, ["repair-missing"]);
1214    }
1215
1216    #[test]
1217    fn latest_project_session_repairs_an_empty_index() {
1218        let _data = crate::core::data_dir::isolated_data_dir();
1219        let project = tempfile::tempdir().expect("project tempdir");
1220        let root = project.path().to_string_lossy().to_string();
1221        let mut session = SessionState::new();
1222        session.id = "repair-empty".to_string();
1223        session.project_root = Some(root.clone());
1224        session.save().expect("save indexed session");
1225
1226        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1227        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
1228        let index_path = project_index_path(&sessions, &canonical_root);
1229        write_project_index(
1230            &index_path,
1231            &ProjectSessionIndex {
1232                version: 1,
1233                project_root: canonical_root,
1234                session_ids: Vec::new(),
1235                verified_empty: false,
1236            },
1237        )
1238        .expect("empty project index");
1239
1240        assert_eq!(
1241            SessionState::load_latest_for_project_root(&root)
1242                .expect("repair and load session")
1243                .id,
1244            "repair-empty"
1245        );
1246        let repaired: ProjectSessionIndex =
1247            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
1248                .expect("valid repaired index");
1249        assert_eq!(repaired.session_ids, ["repair-empty"]);
1250    }
1251
1252    #[test]
1253    fn a_scan_that_finds_no_session_is_cached_until_the_next_save() {
1254        let _data = crate::core::data_dir::isolated_data_dir();
1255        let project = tempfile::tempdir().expect("project tempdir");
1256        let root = project.path().to_string_lossy().to_string();
1257        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1258        std::fs::create_dir_all(&sessions).expect("session store exists");
1259
1260        // First lookup scans the store, finds nothing and records that.
1261        assert!(SessionState::load_latest_for_project_root(&root).is_none());
1262
1263        // A later unindexed file is not picked up: the verified-empty answer is
1264        // reused instead of re-parsing the whole store on every process start.
1265        let mut unindexed = SessionState::new();
1266        unindexed.id = "unindexed-after-scan".to_string();
1267        unindexed.project_root = Some(root.clone());
1268        std::fs::write(
1269            sessions.join("unindexed-after-scan.json"),
1270            serde_json::to_string(&unindexed).expect("serialize session"),
1271        )
1272        .expect("write unindexed session");
1273        assert!(SessionState::load_latest_for_project_root(&root).is_none());
1274
1275        // A real save indexes the session and ends the empty state.
1276        let mut saved = SessionState::new();
1277        saved.id = "saved-after-scan".to_string();
1278        saved.project_root = Some(root.clone());
1279        saved.save().expect("save session");
1280        assert_eq!(
1281            SessionState::load_latest_for_project_root(&root)
1282                .expect("saved session")
1283                .id,
1284            "saved-after-scan"
1285        );
1286    }
1287
1288    #[test]
1289    fn latest_project_session_repairs_a_corrupt_index() {
1290        let _data = crate::core::data_dir::isolated_data_dir();
1291        let project = tempfile::tempdir().expect("project tempdir");
1292        let root = project.path().to_string_lossy().to_string();
1293        let mut session = SessionState::new();
1294        session.id = "repair-corrupt".to_string();
1295        session.project_root = Some(root.clone());
1296        session.save().expect("save indexed session");
1297
1298        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1299        let canonical_root = normalized_safe_project_root(&root).expect("safe root");
1300        let index_path = project_index_path(&sessions, &canonical_root);
1301        std::fs::write(&index_path, "not json").expect("corrupt project index");
1302
1303        assert_eq!(
1304            SessionState::load_latest_for_project_root(&root)
1305                .expect("repair and load session")
1306                .id,
1307            "repair-corrupt"
1308        );
1309        let repaired: ProjectSessionIndex =
1310            serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
1311                .expect("valid repaired index");
1312        assert_eq!(repaired.session_ids, ["repair-corrupt"]);
1313    }
1314
1315    #[test]
1316    fn latest_project_session_repairs_an_index_with_a_missing_session() {
1317        let _data = crate::core::data_dir::isolated_data_dir();
1318        let project = tempfile::tempdir().expect("project tempdir");
1319        let root = project.path().to_string_lossy().to_string();
1320
1321        let mut older = SessionState::new();
1322        older.id = "repair-older".to_string();
1323        older.project_root = Some(root.clone());
1324        older.updated_at = Utc::now() - Duration::hours(1);
1325        older.save().expect("save older session");
1326
1327        let mut missing = SessionState::new();
1328        missing.id = "repair-missing-file".to_string();
1329        missing.project_root = Some(root.clone());
1330        missing.save().expect("save missing session");
1331        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1332        std::fs::remove_file(sessions.join("repair-missing-file.json"))
1333            .expect("remove indexed session");
1334
1335        assert_eq!(
1336            SessionState::load_latest_for_project_root(&root)
1337                .expect("repair and load fallback")
1338                .id,
1339            "repair-older"
1340        );
1341        let repaired: ProjectSessionIndex = serde_json::from_str(
1342            &std::fs::read_to_string(project_index_path(
1343                &sessions,
1344                &normalized_safe_project_root(&root).expect("safe root"),
1345            ))
1346            .expect("repaired index"),
1347        )
1348        .expect("valid repaired index");
1349        assert_eq!(repaired.session_ids, ["repair-older"]);
1350    }
1351
1352    #[test]
1353    fn cleanup_old_sessions_preserves_the_latest_session_for_each_project() {
1354        let _data = crate::core::data_dir::isolated_data_dir();
1355        let project_a = tempfile::tempdir().expect("project A");
1356        let project_b = tempfile::tempdir().expect("project B");
1357        let root_a = project_a.path().to_string_lossy().to_string();
1358        let root_b = project_b.path().to_string_lossy().to_string();
1359
1360        for (id, root, age_days) in [
1361            ("a-old", root_a.as_str(), 10),
1362            ("a-latest", root_a.as_str(), 8),
1363            ("b-old", root_b.as_str(), 10),
1364            ("b-latest", root_b.as_str(), 8),
1365        ] {
1366            let mut session = SessionState::new();
1367            session.id = id.to_string();
1368            session.project_root = Some(root.to_string());
1369            session.updated_at = Utc::now() - Duration::days(age_days);
1370            session.save().expect("save session");
1371        }
1372
1373        assert_eq!(SessionState::cleanup_old_sessions(7), 2);
1374        assert!(SessionState::load_by_id("a-latest").is_some());
1375        assert!(SessionState::load_by_id("b-latest").is_some());
1376        assert!(SessionState::load_by_id("a-old").is_none());
1377        assert!(SessionState::load_by_id("b-old").is_none());
1378    }
1379
1380    #[test]
1381    fn deferred_save_cannot_replace_a_newer_session_version() {
1382        let _data = crate::core::data_dir::isolated_data_dir();
1383        let mut session = SessionState::new();
1384        let id = session.id.clone();
1385        let older = session.prepare_save().expect("prepare older save");
1386        session.increment();
1387        let expected_version = session.version;
1388        let newer = session.prepare_save().expect("prepare newer save");
1389
1390        newer.write_to_disk().expect("write newer save");
1391        older.write_to_disk().expect("skip older save");
1392
1393        assert_eq!(
1394            SessionState::load_by_id(&id)
1395                .expect("load persisted session")
1396                .version,
1397            expected_version
1398        );
1399    }
1400
1401    #[test]
1402    fn project_head_cas_conflict_preserves_live_files_and_success_returns_exact_digest() {
1403        let _data = crate::core::data_dir::isolated_data_dir();
1404        let project = tempfile::tempdir().expect("project tempdir");
1405        let root = project.path().to_string_lossy().to_string();
1406
1407        let mut initial = SessionState::new();
1408        initial.id = "cas-initial".to_string();
1409        initial.project_root = Some(root.clone());
1410        initial.save().expect("save initial project session");
1411        let stale_head = SessionState::project_head(&root)
1412            .expect("read initial project head")
1413            .expect("initial head exists");
1414
1415        let mut local = SessionState::new();
1416        local.id = "cas-local".to_string();
1417        local.project_root = Some(root.clone());
1418        local.save().expect("save competing local session");
1419
1420        let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
1421        let latest_path = sessions.join("latest.json");
1422        let index_path = project_index_path(
1423            &sessions,
1424            &normalized_safe_project_root(&root).expect("safe root"),
1425        );
1426        let latest_before_conflict = std::fs::read(&latest_path).expect("latest pointer");
1427        let index_before_conflict = std::fs::read(&index_path).expect("project index");
1428
1429        let mut candidate = SessionState::new();
1430        candidate.id = "cas-candidate".to_string();
1431        candidate.project_root = Some(root.clone());
1432        assert!(
1433            !candidate
1434                .save_new_if_project_head(Some(&stale_head))
1435                .expect("stale head is a conflict")
1436        );
1437        assert!(!sessions.join("cas-candidate.json").exists());
1438        assert_eq!(
1439            std::fs::read(&latest_path).expect("latest after conflict"),
1440            latest_before_conflict
1441        );
1442        assert_eq!(
1443            std::fs::read(&index_path).expect("index after conflict"),
1444            index_before_conflict
1445        );
1446
1447        let current_head = SessionState::project_head(&root)
1448            .expect("read current project head")
1449            .expect("current head exists");
1450        assert!(
1451            candidate
1452                .save_new_if_project_head(Some(&current_head))
1453                .expect("publish against current head")
1454        );
1455        let persisted =
1456            std::fs::read(sessions.join("cas-candidate.json")).expect("published primary");
1457        assert_eq!(
1458            SessionState::project_head(&root).expect("read published project head"),
1459            Some((
1460                "cas-candidate".to_string(),
1461                format!("sha256:{}", hex::encode(Sha256::digest(&persisted))),
1462            ))
1463        );
1464    }
1465}