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
10const PROJECT_HISTORY_LIMIT: usize = 8;
13
14const SAVE_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
18
19#[derive(Debug, Default, Deserialize, Serialize)]
20struct ProjectSessionIndex {
21 version: u8,
22 project_root: String,
23 session_ids: Vec<String>,
25}
26
27fn normalized_safe_project_root(project_root: &str) -> Option<String> {
28 let path = std::path::Path::new(project_root);
29 if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
30 return None;
31 }
32 Some(
33 crate::core::pathutil::safe_canonicalize_or_self(path)
34 .to_string_lossy()
35 .to_string(),
36 )
37}
38
39fn project_index_path(dir: &std::path::Path, project_root: &str) -> std::path::PathBuf {
40 let key = blake3::hash(project_root.as_bytes()).to_hex();
41 dir.join("project-index").join(format!("{key}.json"))
42}
43
44fn read_project_index(dir: &std::path::Path, project_root: &str) -> Option<ProjectSessionIndex> {
45 std::fs::read_to_string(project_index_path(dir, project_root))
46 .ok()
47 .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
48 .filter(|index| index.version == 1 && index.project_root == project_root)
49}
50
51fn write_project_index(
52 index_path: &std::path::Path,
53 index: &ProjectSessionIndex,
54) -> Result<(), String> {
55 let json = serde_json::to_string(index).map_err(|e| format!("serialize project index: {e}"))?;
56 let tmp = index_path.with_extension(format!("{}.tmp", std::process::id()));
57 std::fs::write(&tmp, json).map_err(|e| format!("write project index: {e}"))?;
58 restrict_file_permissions(&tmp);
59 std::fs::rename(tmp, index_path).map_err(|e| format!("commit project index: {e}"))
60}
61
62fn with_project_index_lock<T>(
63 dir: &std::path::Path,
64 project_root: &str,
65 operation: impl FnOnce(&std::path::Path) -> Result<T, String>,
66) -> Result<T, String> {
67 use fs2::FileExt;
68 use std::time::Duration;
69
70 const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
71
72 let index_path = project_index_path(dir, project_root);
73 let index_dir = index_path.parent().ok_or("project index has no parent")?;
74 std::fs::create_dir_all(index_dir).map_err(|e| format!("create project index: {e}"))?;
75 let lock = std::fs::OpenOptions::new()
76 .create(true)
77 .truncate(false)
78 .write(true)
79 .open(index_path.with_extension("lock"))
80 .map_err(|e| format!("project index lock: {e}"))?;
81 crate::core::file_lock::acquire_exclusive_timeout(&lock, LOCK_TIMEOUT)
82 .map_err(|e| format!("project index lock: {e}"))?;
83 let result = operation(&index_path);
84 let _ = FileExt::unlock(&lock);
85 result
86}
87
88fn update_project_index(dir: &std::path::Path, project_root: &str, id: &str) -> Result<(), String> {
92 with_project_index_lock(dir, project_root, |index_path| {
93 let mut index =
94 read_project_index(dir, project_root).unwrap_or_else(|| ProjectSessionIndex {
95 version: 1,
96 project_root: project_root.to_string(),
97 session_ids: Vec::new(),
98 });
99 index.session_ids.retain(|existing| existing != id);
100 index.session_ids.push(id.to_string());
101 let excess = index
102 .session_ids
103 .len()
104 .saturating_sub(PROJECT_HISTORY_LIMIT);
105 if excess > 0 {
106 index.session_ids.drain(..excess);
107 }
108 write_project_index(index_path, &index)
109 })
110}
111
112fn repair_project_index(dir: &std::path::Path, project_root: &str) -> Option<SessionState> {
113 let mut matches = Vec::new();
114 for entry in std::fs::read_dir(dir).ok()?.flatten() {
115 let path = entry.path();
116 if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
117 continue;
118 }
119 let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
120 continue;
121 };
122 if id == "latest" || id.starts_with('.') {
123 continue;
124 }
125 let Some(session) = SessionState::load_by_id(id) else {
126 continue;
127 };
128 if session_matches_project_root(&session, std::path::Path::new(project_root)) {
129 matches.push(session);
130 }
131 }
132 matches.sort_by_key(|session| session.updated_at);
133 let latest = matches.last().cloned();
134 let first_retained = matches.len().saturating_sub(PROJECT_HISTORY_LIMIT);
135 let session_ids = matches[first_retained..]
136 .iter()
137 .map(|session| session.id.clone())
138 .collect();
139 if let Err(error) = with_project_index_lock(dir, project_root, |index_path| {
140 write_project_index(
141 index_path,
142 &ProjectSessionIndex {
143 version: 1,
144 project_root: project_root.to_string(),
145 session_ids,
146 },
147 )
148 }) {
149 tracing::debug!("lean-ctx: session project index repair skipped: {error}");
150 }
151 latest
152}
153
154#[cfg(unix)]
155fn restrict_file_permissions(path: &std::path::Path) {
156 use std::os::unix::fs::PermissionsExt;
157 let perms = std::fs::Permissions::from_mode(0o600);
158 let _ = std::fs::set_permissions(path, perms);
159}
160
161#[cfg(not(unix))]
162fn restrict_file_permissions(_path: &std::path::Path) {}
163
164fn validate_session_id(id: &str) -> Result<(), String> {
165 if id.is_empty()
166 || id == "latest"
167 || id.starts_with('.')
168 || id.contains('/')
169 || id.contains('\\')
170 || id.contains(std::path::MAIN_SEPARATOR)
171 {
172 return Err("invalid session id".to_string());
173 }
174 Ok(())
175}
176
177fn persist_session_facts(session: &SessionState) -> Result<(), String> {
178 let Some(project_root) = session
179 .project_root
180 .as_deref()
181 .filter(|project_root| !project_root.trim().is_empty())
182 else {
183 return Ok(());
184 };
185
186 let facts = extract_session_facts(session);
187 if facts.is_empty() {
188 return Ok(());
189 }
190
191 let mut knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
192 for fact in facts {
193 knowledge.add_fact(fact);
194 }
195 knowledge.save()
196}
197
198impl PreparedSave {
199 pub fn write_to_disk(self) -> Result<(), String> {
210 use fs2::FileExt;
211
212 if !self.dir.exists() {
213 std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
214 }
215 let lock_path = self.dir.join(format!(".{}.save.lock", self.id));
216 let lock = std::fs::OpenOptions::new()
217 .create(true)
218 .truncate(false)
219 .write(true)
220 .open(lock_path)
221 .map_err(|e| format!("open session save lock: {e}"))?;
222 crate::core::file_lock::acquire_exclusive_timeout(&lock, SAVE_LOCK_TIMEOUT)
223 .map_err(|e| format!("lock session save: {e}"))?;
224
225 let result = (|| {
226 let path = self.dir.join(format!("{}.json", self.id));
227 if persisted_session_version(&path).is_some_and(|version| version > self.version) {
228 return Ok(());
229 }
230 let tmp = self.dir.join(format!(".{}.json.tmp", self.id));
231 std::fs::write(&tmp, &self.json).map_err(|e| e.to_string())?;
232 restrict_file_permissions(&tmp);
233 std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
234
235 let latest_path = self.dir.join("latest.json");
236 let latest_tmp = self.dir.join(".latest.json.tmp");
237 std::fs::write(&latest_tmp, &self.pointer_json).map_err(|e| e.to_string())?;
238 restrict_file_permissions(&latest_tmp);
239 std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
240
241 if let Some(snapshot) = self.compaction_snapshot {
242 let snap_path = self.dir.join(format!("{}_snapshot.txt", self.id));
243 if let Err(error) = crate::core::atomic_fs::write_bytes_with_fallback(
244 &snap_path,
245 snapshot.as_bytes(),
246 None,
247 ) {
248 tracing::debug!("lean-ctx: compaction snapshot update skipped: {error}");
249 } else {
250 restrict_file_permissions(&snap_path);
251 }
252 }
253 if let Some(project_root) = self.project_index_root.as_deref()
254 && let Err(error) = update_project_index(&self.dir, project_root, &self.id)
255 {
256 tracing::debug!("lean-ctx: session warm-history index update skipped: {error}");
257 }
258 Ok(())
259 })();
260 let _ = FileExt::unlock(&lock);
261 result
262 }
263}
264
265fn persisted_session_version(path: &std::path::Path) -> Option<u32> {
266 let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
267 value["version"].as_u64()?.try_into().ok()
268}
269
270impl SessionState {
271 #[must_use]
273 pub fn decision_count_this_week() -> u64 {
274 let cutoff = Utc::now() - chrono::Duration::days(7);
275 Self::list_sessions()
276 .into_iter()
277 .filter_map(|summary| Self::load_by_id(&summary.id))
278 .flat_map(|session| session.decisions)
279 .filter(|decision| decision.timestamp >= cutoff)
280 .count()
281 .try_into()
282 .unwrap_or(u64::MAX)
283 }
284
285 pub fn save(&mut self) -> Result<(), String> {
287 let prepared = self.prepare_save()?;
288 match prepared.write_to_disk() {
289 Ok(()) => Ok(()),
290 Err(e) => {
291 self.stats.unsaved_changes = BATCH_SAVE_INTERVAL;
292 Err(e)
293 }
294 }
295 }
296
297 pub fn prepare_save(&mut self) -> Result<PreparedSave, String> {
301 if self
302 .project_root
303 .as_deref()
304 .is_some_and(|root| normalized_safe_project_root(root).is_none())
305 {
306 return Err(
307 "refusing to persist a session for a broad or unsafe project root".to_string(),
308 );
309 }
310 let dir = sessions_dir().ok_or("cannot determine home directory")?;
311 let compaction_snapshot = if self.stats.total_tool_calls > 0 {
312 Some(self.build_compaction_snapshot())
313 } else {
314 None
315 };
316 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
317 let pointer_json = serde_json::to_string(&LatestPointer {
318 id: self.id.clone(),
319 })
320 .map_err(|e| e.to_string())?;
321 self.stats.unsaved_changes = 0;
322 self.last_flush = Some(std::time::Instant::now());
324 Ok(PreparedSave {
325 dir,
326 id: self.id.clone(),
327 version: self.version,
328 json,
329 pointer_json,
330 compaction_snapshot,
331 project_index_root: self
332 .project_root
333 .as_deref()
334 .and_then(normalized_safe_project_root),
335 })
336 }
337
338 pub(crate) fn load_recent_for_project_root(project_root: &str, limit: usize) -> Vec<Self> {
345 let Some(project_root) = normalized_safe_project_root(project_root) else {
346 return Vec::new();
347 };
348 let Some(dir) = sessions_dir() else {
349 return Vec::new();
350 };
351 let Some(index) = std::fs::read_to_string(project_index_path(&dir, &project_root))
352 .ok()
353 .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
354 .filter(|index| index.version == 1 && index.project_root == project_root)
355 else {
356 return Vec::new();
357 };
358
359 index
360 .session_ids
361 .iter()
362 .rev()
363 .take(limit.min(PROJECT_HISTORY_LIMIT))
364 .filter_map(|id| Self::load_by_id(id))
365 .collect()
366 }
367
368 pub fn load_latest() -> Option<Self> {
381 let cwd = std::env::current_dir().ok()?;
382 if crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
383 return None;
384 }
385 Self::load_latest_for_project_root(&cwd.to_string_lossy())
386 }
387
388 pub fn load_global_latest_pointer() -> Option<Self> {
393 let dir = sessions_dir()?;
394 let latest_path = dir.join("latest.json");
395 let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
396 let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
397 Self::load_by_id(&pointer.id)
398 }
399
400 pub fn load_latest_for_project_root(project_root: &str) -> Option<Self> {
406 let target_root = normalized_safe_project_root(project_root)?;
407 let dir = sessions_dir()?;
408
409 if let Some(index) = read_project_index(&dir, &target_root)
410 && let Some(id) = index.session_ids.last()
411 && let Some(session) = Self::load_by_id(id)
412 && session_matches_project_root(&session, std::path::Path::new(&target_root))
413 {
414 return Some(session);
415 }
416
417 repair_project_index(&dir, &target_root)
418 }
419
420 pub fn load_by_id(id: &str) -> Option<Self> {
422 validate_session_id(id).ok()?;
423 let dir = sessions_dir()?;
424 let path = dir.join(format!("{id}.json"));
425 let json = std::fs::read_to_string(&path).ok()?;
426 let session: Self = serde_json::from_str(&json).ok()?;
427 Some(normalize_loaded_session(session))
428 }
429
430 pub fn delete_session(id: &str) -> Result<bool, String> {
435 validate_session_id(id)?;
436 let Some(dir) = sessions_dir() else {
437 return Ok(false);
438 };
439 let path = dir.join(format!("{id}.json"));
440 if !path.exists() {
441 return Ok(false);
442 }
443
444 if let Some(session) = Self::load_by_id(id) {
445 persist_session_facts(&session)?;
446 }
447 std::fs::remove_file(&path).map_err(|e| e.to_string())?;
448
449 let snapshot = dir.join(format!("{id}_snapshot.txt"));
450 match std::fs::remove_file(&snapshot) {
451 Ok(()) => {}
452 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
453 Err(e) => return Err(e.to_string()),
454 }
455
456 let latest_path = dir.join("latest.json");
457 let points_to_deleted = std::fs::read_to_string(&latest_path)
458 .ok()
459 .and_then(|json| serde_json::from_str::<LatestPointer>(&json).ok())
460 .is_some_and(|pointer| pointer.id == id);
461 if points_to_deleted {
462 if let Some(next) = Self::list_sessions().into_iter().next() {
463 let latest_tmp = dir.join(".latest.json.tmp");
464 let pointer_json = serde_json::to_string(&LatestPointer { id: next.id })
465 .map_err(|e| e.to_string())?;
466 std::fs::write(&latest_tmp, pointer_json).map_err(|e| e.to_string())?;
467 restrict_file_permissions(&latest_tmp);
468 std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
469 } else {
470 match std::fs::remove_file(&latest_path) {
471 Ok(()) => {}
472 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
473 Err(e) => return Err(e.to_string()),
474 }
475 }
476 }
477
478 Ok(true)
479 }
480
481 pub fn list_sessions() -> Vec<SessionSummary> {
483 let Some(dir) = sessions_dir() else {
484 return Vec::new();
485 };
486
487 let mut summaries = Vec::new();
488 if let Ok(entries) = std::fs::read_dir(&dir) {
489 for entry in entries.flatten() {
490 let path = entry.path();
491 if path.extension().and_then(|e| e.to_str()) != Some("json") {
492 continue;
493 }
494 if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
495 continue;
496 }
497 if let Ok(json) = std::fs::read_to_string(&path)
498 && let Ok(session) = serde_json::from_str::<SessionState>(&json)
499 {
500 summaries.push(SessionSummary {
501 id: session.id,
502 started_at: session.started_at,
503 updated_at: session.updated_at,
504 version: session.version,
505 task: session.task.as_ref().map(|t| t.description.clone()),
506 tool_calls: session.stats.total_tool_calls,
507 tokens_saved: session.stats.total_tokens_saved,
508 project_root: session.project_root,
509 });
510 }
511 }
512 }
513
514 summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
515 summaries
516 }
517
518 pub fn doctor_quarantine_unsafe_roots(apply: bool) -> (Vec<(String, String)>, usize) {
527 let mut found: Vec<(String, String)> = Vec::new();
528 let mut quarantined = 0usize;
529 let Some(dir) = sessions_dir() else {
530 return (found, quarantined);
531 };
532 let Ok(entries) = std::fs::read_dir(&dir) else {
533 return (found, quarantined);
534 };
535 for entry in entries.flatten() {
536 let path = entry.path();
537 if path.extension().and_then(|e| e.to_str()) != Some("json") {
538 continue;
539 }
540 let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
541 continue;
542 };
543 if id == "latest" || id.starts_with('.') {
544 continue;
545 }
546 let Some(session) = Self::load_by_id(id) else {
547 continue;
548 };
549 let Some(root) = session.project_root.as_deref() else {
550 continue;
551 };
552 let root_path = std::path::Path::new(root);
553 if crate::core::pathutil::is_broad_or_unsafe_root(root_path) {
554 found.push((id.to_string(), root.to_string()));
555 if apply {
556 let q_dir = dir.join("quarantine");
557 if std::fs::create_dir_all(&q_dir).is_ok()
558 && std::fs::rename(&path, q_dir.join(format!("{id}.json"))).is_ok()
559 {
560 quarantined += 1;
561 }
562 }
563 }
564 }
565 (found, quarantined)
566 }
567
568 pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
574 let Some(dir) = sessions_dir() else { return 0 };
575 let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
576 let global_latest = Self::load_global_latest_pointer().map(|session| session.id);
577 let mut sessions = Vec::new();
578
579 if let Ok(entries) = std::fs::read_dir(&dir) {
580 for entry in entries.flatten() {
581 let path = entry.path();
582 if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
583 continue;
584 }
585 let Some(id) = path.file_stem().and_then(|stem| stem.to_str()) else {
586 continue;
587 };
588 if id == "latest" || id.starts_with('.') {
589 continue;
590 }
591 if let Some(session) = Self::load_by_id(id) {
592 sessions.push((path, session));
593 }
594 }
595 }
596
597 let mut newest_by_project = std::collections::HashMap::new();
598 for (_, session) in &sessions {
599 let Some(project_root) = session
600 .project_root
601 .as_deref()
602 .filter(|root| !root.trim().is_empty())
603 else {
604 continue;
605 };
606 newest_by_project
607 .entry(project_root)
608 .and_modify(|current: &mut &SessionState| {
609 if session.updated_at > current.updated_at {
610 *current = session;
611 }
612 })
613 .or_insert(session);
614 }
615
616 let mut retained_ids: std::collections::HashSet<String> = newest_by_project
617 .values()
618 .map(|session| session.id.clone())
619 .collect();
620 if let Some(id) = global_latest {
621 retained_ids.insert(id);
622 }
623
624 sessions
625 .into_iter()
626 .filter(|(_, session)| {
627 session.updated_at < cutoff && !retained_ids.contains(&session.id)
628 })
629 .filter(|(_, session)| persist_session_facts(session).is_ok())
630 .filter(|(path, _)| std::fs::remove_file(path).is_ok())
631 .map(|(path, session)| {
632 let snapshot = path.with_file_name(format!("{}_snapshot.txt", session.id));
633 let _ = std::fs::remove_file(snapshot);
634 })
635 .count() as u32
636 }
637}
638
639#[cfg(test)]
640mod tests {
641 use super::{
642 ProjectSessionIndex, SessionState, normalized_safe_project_root, project_index_path,
643 write_project_index,
644 };
645 use chrono::{Duration, Utc};
646
647 #[test]
648 fn recent_project_sessions_use_bounded_index_without_scanning_legacy_store() {
649 let _data = crate::core::data_dir::isolated_data_dir();
650 let project = tempfile::tempdir().expect("project tempdir");
651 let root = project.path().to_string_lossy().to_string();
652
653 for id in ["first", "second", "third"] {
654 let mut session = SessionState::new();
655 session.id = id.to_string();
656 session.project_root = Some(root.clone());
657 session.save().expect("save indexed session");
658 }
659
660 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
663 std::fs::write(sessions.join("legacy-unreadable.json"), "not json")
664 .expect("write legacy artifact");
665
666 let ids: Vec<_> = SessionState::load_recent_for_project_root(&root, 8)
667 .into_iter()
668 .map(|session| session.id)
669 .collect();
670 assert_eq!(ids, ["third", "second", "first"]);
671 }
672
673 #[test]
674 fn recent_project_sessions_refuse_broad_roots() {
675 let _data = crate::core::data_dir::isolated_data_dir();
676 assert!(SessionState::load_recent_for_project_root("/", 8).is_empty());
677 }
678
679 #[test]
685 fn save_gives_up_when_another_holder_keeps_the_session_lock() {
686 use fs2::FileExt;
687
688 let _data = crate::core::data_dir::isolated_data_dir();
689 let project = tempfile::tempdir().expect("project tempdir");
690 let mut session = SessionState::new();
691 session.id = "wedged".to_string();
692 session.project_root = Some(project.path().to_string_lossy().to_string());
693
694 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
695 std::fs::create_dir_all(&sessions).expect("create sessions dir");
696 let holder = std::fs::File::create(sessions.join(".wedged.save.lock")).expect("lock file");
697 holder.lock_exclusive().expect("hold the save lock");
698
699 let started = std::time::Instant::now();
700 let error = session
701 .save()
702 .expect_err("a held lock must not be waited out");
703 let waited = started.elapsed();
704
705 assert!(
706 error.contains("lock session save"),
707 "unexpected error: {error}"
708 );
709 assert!(
710 waited < super::SAVE_LOCK_TIMEOUT * 4,
711 "save must return on its own deadline, waited {waited:?}"
712 );
713 assert_ne!(
714 session.stats.unsaved_changes, 0,
715 "a failed save must stay pending so the next batch retries"
716 );
717 FileExt::unlock(&holder).expect("release");
718 }
719
720 #[test]
721 fn broad_root_sessions_are_never_persisted() {
722 let _data = crate::core::data_dir::isolated_data_dir();
723 let mut session = SessionState::new();
724 session.project_root = Some("/".to_string());
725
726 let error = session
727 .save()
728 .expect_err("broad root save must be rejected");
729
730 assert!(error.contains("broad or unsafe"));
731 assert!(
732 crate::core::session::paths::sessions_dir()
733 .expect("sessions dir")
734 .read_dir()
735 .map_or(true, |mut entries| entries.next().is_none())
736 );
737 }
738
739 #[test]
740 fn latest_project_session_uses_valid_index_without_scanning_unindexed_sessions() {
741 let _data = crate::core::data_dir::isolated_data_dir();
742 let project = tempfile::tempdir().expect("project tempdir");
743 let root = project.path().to_string_lossy().to_string();
744
745 let mut indexed = SessionState::new();
746 indexed.id = "indexed".to_string();
747 indexed.project_root = Some(root.clone());
748 indexed.updated_at = Utc::now() - Duration::hours(1);
749 indexed.save().expect("save indexed session");
750
751 let mut unindexed = SessionState::new();
754 unindexed.id = "unindexed".to_string();
755 unindexed.project_root = Some(root.clone());
756 unindexed.updated_at = Utc::now();
757 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
758 std::fs::write(
759 sessions.join("unindexed.json"),
760 serde_json::to_string(&unindexed).expect("serialize legacy session"),
761 )
762 .expect("write unindexed session");
763
764 assert_eq!(
765 SessionState::load_latest_for_project_root(&root)
766 .expect("load indexed session")
767 .id,
768 "indexed"
769 );
770 }
771
772 #[test]
773 fn latest_project_session_repairs_a_missing_index() {
774 let _data = crate::core::data_dir::isolated_data_dir();
775 let project = tempfile::tempdir().expect("project tempdir");
776 let root = project.path().to_string_lossy().to_string();
777 let mut session = SessionState::new();
778 session.id = "repair-missing".to_string();
779 session.project_root = Some(root.clone());
780 session.save().expect("save indexed session");
781
782 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
783 let canonical_root = normalized_safe_project_root(&root).expect("safe root");
784 let index_path = project_index_path(&sessions, &canonical_root);
785 std::fs::remove_file(&index_path).expect("remove project index");
786
787 assert_eq!(
788 SessionState::load_latest_for_project_root(&root)
789 .expect("repair and load session")
790 .id,
791 "repair-missing"
792 );
793 let repaired: ProjectSessionIndex =
794 serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
795 .expect("valid repaired index");
796 assert_eq!(repaired.session_ids, ["repair-missing"]);
797 }
798
799 #[test]
800 fn latest_project_session_repairs_an_empty_index() {
801 let _data = crate::core::data_dir::isolated_data_dir();
802 let project = tempfile::tempdir().expect("project tempdir");
803 let root = project.path().to_string_lossy().to_string();
804 let mut session = SessionState::new();
805 session.id = "repair-empty".to_string();
806 session.project_root = Some(root.clone());
807 session.save().expect("save indexed session");
808
809 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
810 let canonical_root = normalized_safe_project_root(&root).expect("safe root");
811 let index_path = project_index_path(&sessions, &canonical_root);
812 write_project_index(
813 &index_path,
814 &ProjectSessionIndex {
815 version: 1,
816 project_root: canonical_root,
817 session_ids: Vec::new(),
818 },
819 )
820 .expect("empty project index");
821
822 assert_eq!(
823 SessionState::load_latest_for_project_root(&root)
824 .expect("repair and load session")
825 .id,
826 "repair-empty"
827 );
828 let repaired: ProjectSessionIndex =
829 serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
830 .expect("valid repaired index");
831 assert_eq!(repaired.session_ids, ["repair-empty"]);
832 }
833
834 #[test]
835 fn latest_project_session_repairs_a_corrupt_index() {
836 let _data = crate::core::data_dir::isolated_data_dir();
837 let project = tempfile::tempdir().expect("project tempdir");
838 let root = project.path().to_string_lossy().to_string();
839 let mut session = SessionState::new();
840 session.id = "repair-corrupt".to_string();
841 session.project_root = Some(root.clone());
842 session.save().expect("save indexed session");
843
844 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
845 let canonical_root = normalized_safe_project_root(&root).expect("safe root");
846 let index_path = project_index_path(&sessions, &canonical_root);
847 std::fs::write(&index_path, "not json").expect("corrupt project index");
848
849 assert_eq!(
850 SessionState::load_latest_for_project_root(&root)
851 .expect("repair and load session")
852 .id,
853 "repair-corrupt"
854 );
855 let repaired: ProjectSessionIndex =
856 serde_json::from_str(&std::fs::read_to_string(index_path).expect("repaired index"))
857 .expect("valid repaired index");
858 assert_eq!(repaired.session_ids, ["repair-corrupt"]);
859 }
860
861 #[test]
862 fn latest_project_session_repairs_an_index_with_a_missing_session() {
863 let _data = crate::core::data_dir::isolated_data_dir();
864 let project = tempfile::tempdir().expect("project tempdir");
865 let root = project.path().to_string_lossy().to_string();
866
867 let mut older = SessionState::new();
868 older.id = "repair-older".to_string();
869 older.project_root = Some(root.clone());
870 older.updated_at = Utc::now() - Duration::hours(1);
871 older.save().expect("save older session");
872
873 let mut missing = SessionState::new();
874 missing.id = "repair-missing-file".to_string();
875 missing.project_root = Some(root.clone());
876 missing.save().expect("save missing session");
877 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
878 std::fs::remove_file(sessions.join("repair-missing-file.json"))
879 .expect("remove indexed session");
880
881 assert_eq!(
882 SessionState::load_latest_for_project_root(&root)
883 .expect("repair and load fallback")
884 .id,
885 "repair-older"
886 );
887 let repaired: ProjectSessionIndex = serde_json::from_str(
888 &std::fs::read_to_string(project_index_path(
889 &sessions,
890 &normalized_safe_project_root(&root).expect("safe root"),
891 ))
892 .expect("repaired index"),
893 )
894 .expect("valid repaired index");
895 assert_eq!(repaired.session_ids, ["repair-older"]);
896 }
897
898 #[test]
899 fn cleanup_old_sessions_preserves_the_latest_session_for_each_project() {
900 let _data = crate::core::data_dir::isolated_data_dir();
901 let project_a = tempfile::tempdir().expect("project A");
902 let project_b = tempfile::tempdir().expect("project B");
903 let root_a = project_a.path().to_string_lossy().to_string();
904 let root_b = project_b.path().to_string_lossy().to_string();
905
906 for (id, root, age_days) in [
907 ("a-old", root_a.as_str(), 10),
908 ("a-latest", root_a.as_str(), 8),
909 ("b-old", root_b.as_str(), 10),
910 ("b-latest", root_b.as_str(), 8),
911 ] {
912 let mut session = SessionState::new();
913 session.id = id.to_string();
914 session.project_root = Some(root.to_string());
915 session.updated_at = Utc::now() - Duration::days(age_days);
916 session.save().expect("save session");
917 }
918
919 assert_eq!(SessionState::cleanup_old_sessions(7), 2);
920 assert!(SessionState::load_by_id("a-latest").is_some());
921 assert!(SessionState::load_by_id("b-latest").is_some());
922 assert!(SessionState::load_by_id("a-old").is_none());
923 assert!(SessionState::load_by_id("b-old").is_none());
924 }
925
926 #[test]
927 fn deferred_save_cannot_replace_a_newer_session_version() {
928 let _data = crate::core::data_dir::isolated_data_dir();
929 let mut session = SessionState::new();
930 let id = session.id.clone();
931 let older = session.prepare_save().expect("prepare older save");
932 session.increment();
933 let expected_version = session.version;
934 let newer = session.prepare_save().expect("prepare newer save");
935
936 newer.write_to_disk().expect("write newer save");
937 older.write_to_disk().expect("skip older save");
938
939 assert_eq!(
940 SessionState::load_by_id(&id)
941 .expect("load persisted session")
942 .version,
943 expected_version
944 );
945 }
946}