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
14#[derive(Debug, Default, Deserialize, Serialize)]
15struct ProjectSessionIndex {
16 version: u8,
17 project_root: String,
18 session_ids: Vec<String>,
20}
21
22fn normalized_safe_project_root(project_root: &str) -> Option<String> {
23 let path = std::path::Path::new(project_root);
24 if project_root.trim().is_empty() || crate::core::pathutil::is_broad_or_unsafe_root(path) {
25 return None;
26 }
27 Some(
28 crate::core::pathutil::safe_canonicalize_or_self(path)
29 .to_string_lossy()
30 .to_string(),
31 )
32}
33
34fn project_index_path(dir: &std::path::Path, project_root: &str) -> std::path::PathBuf {
35 let key = blake3::hash(project_root.as_bytes()).to_hex();
36 dir.join("project-index").join(format!("{key}.json"))
37}
38
39fn update_project_index(dir: &std::path::Path, project_root: &str, id: &str) -> Result<(), String> {
43 use fs2::FileExt;
44 use std::time::{Duration, Instant};
45
46 const LOCK_TIMEOUT: Duration = Duration::from_millis(200);
47 const RETRY_INTERVAL: Duration = Duration::from_millis(10);
48
49 let index_path = project_index_path(dir, project_root);
50 let index_dir = index_path.parent().ok_or("project index has no parent")?;
51 std::fs::create_dir_all(index_dir).map_err(|e| format!("create project index: {e}"))?;
52
53 let lock_path = index_path.with_extension("lock");
54 let lock = std::fs::OpenOptions::new()
55 .create(true)
56 .truncate(false)
57 .write(true)
58 .open(lock_path)
59 .map_err(|e| format!("project index lock: {e}"))?;
60 let deadline = Instant::now() + LOCK_TIMEOUT;
61 loop {
62 match lock.try_lock_exclusive() {
63 Ok(()) => break,
64 Err(error)
65 if crate::core::file_lock::is_contended(&error) && Instant::now() < deadline =>
66 {
67 std::thread::sleep(RETRY_INTERVAL);
68 }
69 Err(error) if crate::core::file_lock::is_contended(&error) => {
70 return Err("project index lock timed out".to_string());
71 }
72 Err(error) => return Err(format!("project index lock: {error}")),
73 }
74 }
75
76 let result = (|| {
77 let mut index = std::fs::read_to_string(&index_path)
78 .ok()
79 .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
80 .filter(|index| index.version == 1 && index.project_root == project_root)
81 .unwrap_or_else(|| ProjectSessionIndex {
82 version: 1,
83 project_root: project_root.to_string(),
84 session_ids: Vec::new(),
85 });
86
87 index.session_ids.retain(|existing| existing != id);
88 index.session_ids.push(id.to_string());
89 let excess = index
90 .session_ids
91 .len()
92 .saturating_sub(PROJECT_HISTORY_LIMIT);
93 if excess > 0 {
94 index.session_ids.drain(..excess);
95 }
96
97 let json =
98 serde_json::to_string(&index).map_err(|e| format!("serialize project index: {e}"))?;
99 let tmp = index_path.with_extension(format!("{}.tmp", std::process::id()));
100 std::fs::write(&tmp, json).map_err(|e| format!("write project index: {e}"))?;
101 restrict_file_permissions(&tmp);
102 std::fs::rename(tmp, index_path).map_err(|e| format!("commit project index: {e}"))
103 })();
104 let _ = FileExt::unlock(&lock);
105 result
106}
107
108#[cfg(unix)]
109fn restrict_file_permissions(path: &std::path::Path) {
110 use std::os::unix::fs::PermissionsExt;
111 let perms = std::fs::Permissions::from_mode(0o600);
112 let _ = std::fs::set_permissions(path, perms);
113}
114
115#[cfg(not(unix))]
116fn restrict_file_permissions(_path: &std::path::Path) {}
117
118fn validate_session_id(id: &str) -> Result<(), String> {
119 if id.is_empty()
120 || id == "latest"
121 || id.starts_with('.')
122 || id.contains('/')
123 || id.contains('\\')
124 || id.contains(std::path::MAIN_SEPARATOR)
125 {
126 return Err("invalid session id".to_string());
127 }
128 Ok(())
129}
130
131fn persist_session_facts(session: &SessionState) -> Result<(), String> {
132 let Some(project_root) = session
133 .project_root
134 .as_deref()
135 .filter(|project_root| !project_root.trim().is_empty())
136 else {
137 return Ok(());
138 };
139
140 let facts = extract_session_facts(session);
141 if facts.is_empty() {
142 return Ok(());
143 }
144
145 let mut knowledge = crate::core::knowledge::ProjectKnowledge::load_or_create(project_root);
146 for fact in facts {
147 knowledge.add_fact(fact);
148 }
149 knowledge.save()
150}
151
152impl PreparedSave {
153 pub fn write_to_disk(self) -> Result<(), String> {
158 use fs2::FileExt;
159
160 if !self.dir.exists() {
161 std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
162 }
163 let lock_path = self.dir.join(format!(".{}.save.lock", self.id));
164 let lock = std::fs::OpenOptions::new()
165 .create(true)
166 .truncate(false)
167 .write(true)
168 .open(lock_path)
169 .map_err(|e| format!("open session save lock: {e}"))?;
170 lock.lock_exclusive()
171 .map_err(|e| format!("lock session save: {e}"))?;
172
173 let result = (|| {
174 let path = self.dir.join(format!("{}.json", self.id));
175 if persisted_session_version(&path).is_some_and(|version| version > self.version) {
176 return Ok(());
177 }
178 let tmp = self.dir.join(format!(".{}.json.tmp", self.id));
179 std::fs::write(&tmp, &self.json).map_err(|e| e.to_string())?;
180 restrict_file_permissions(&tmp);
181 std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
182
183 let latest_path = self.dir.join("latest.json");
184 let latest_tmp = self.dir.join(".latest.json.tmp");
185 std::fs::write(&latest_tmp, &self.pointer_json).map_err(|e| e.to_string())?;
186 restrict_file_permissions(&latest_tmp);
187 std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
188
189 if let Some(snapshot) = self.compaction_snapshot {
190 let snap_path = self.dir.join(format!("{}_snapshot.txt", self.id));
191 if let Err(error) = crate::core::atomic_fs::write_bytes_with_fallback(
192 &snap_path,
193 snapshot.as_bytes(),
194 None,
195 ) {
196 tracing::debug!("lean-ctx: compaction snapshot update skipped: {error}");
197 } else {
198 restrict_file_permissions(&snap_path);
199 }
200 }
201 if let Some(project_root) = self.project_index_root.as_deref()
202 && let Err(error) = update_project_index(&self.dir, project_root, &self.id)
203 {
204 tracing::debug!("lean-ctx: session warm-history index update skipped: {error}");
205 }
206 Ok(())
207 })();
208 let _ = FileExt::unlock(&lock);
209 result
210 }
211}
212
213fn persisted_session_version(path: &std::path::Path) -> Option<u32> {
214 let value: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
215 value["version"].as_u64()?.try_into().ok()
216}
217
218impl SessionState {
219 #[must_use]
221 pub fn decision_count_this_week() -> u64 {
222 let cutoff = Utc::now() - chrono::Duration::days(7);
223 Self::list_sessions()
224 .into_iter()
225 .filter_map(|summary| Self::load_by_id(&summary.id))
226 .flat_map(|session| session.decisions)
227 .filter(|decision| decision.timestamp >= cutoff)
228 .count()
229 .try_into()
230 .unwrap_or(u64::MAX)
231 }
232
233 pub fn save(&mut self) -> Result<(), String> {
235 let prepared = self.prepare_save()?;
236 match prepared.write_to_disk() {
237 Ok(()) => Ok(()),
238 Err(e) => {
239 self.stats.unsaved_changes = BATCH_SAVE_INTERVAL;
240 Err(e)
241 }
242 }
243 }
244
245 pub fn prepare_save(&mut self) -> Result<PreparedSave, String> {
249 if self
250 .project_root
251 .as_deref()
252 .is_some_and(|root| normalized_safe_project_root(root).is_none())
253 {
254 return Err(
255 "refusing to persist a session for a broad or unsafe project root".to_string(),
256 );
257 }
258 let dir = sessions_dir().ok_or("cannot determine home directory")?;
259 let compaction_snapshot = if self.stats.total_tool_calls > 0 {
260 Some(self.build_compaction_snapshot())
261 } else {
262 None
263 };
264 let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
265 let pointer_json = serde_json::to_string(&LatestPointer {
266 id: self.id.clone(),
267 })
268 .map_err(|e| e.to_string())?;
269 self.stats.unsaved_changes = 0;
270 self.last_flush = Some(std::time::Instant::now());
272 Ok(PreparedSave {
273 dir,
274 id: self.id.clone(),
275 version: self.version,
276 json,
277 pointer_json,
278 compaction_snapshot,
279 project_index_root: self
280 .project_root
281 .as_deref()
282 .and_then(normalized_safe_project_root),
283 })
284 }
285
286 pub(crate) fn load_recent_for_project_root(project_root: &str, limit: usize) -> Vec<Self> {
293 let Some(project_root) = normalized_safe_project_root(project_root) else {
294 return Vec::new();
295 };
296 let Some(dir) = sessions_dir() else {
297 return Vec::new();
298 };
299 let Some(index) = std::fs::read_to_string(project_index_path(&dir, &project_root))
300 .ok()
301 .and_then(|json| serde_json::from_str::<ProjectSessionIndex>(&json).ok())
302 .filter(|index| index.version == 1 && index.project_root == project_root)
303 else {
304 return Vec::new();
305 };
306
307 index
308 .session_ids
309 .iter()
310 .rev()
311 .take(limit.min(PROJECT_HISTORY_LIMIT))
312 .filter_map(|id| Self::load_by_id(id))
313 .collect()
314 }
315
316 pub fn load_latest() -> Option<Self> {
329 let cwd = std::env::current_dir().ok()?;
330 if crate::core::pathutil::is_broad_or_unsafe_root(&cwd) {
331 return None;
332 }
333 Self::load_latest_for_project_root(&cwd.to_string_lossy())
334 }
335
336 pub fn load_global_latest_pointer() -> Option<Self> {
341 let dir = sessions_dir()?;
342 let latest_path = dir.join("latest.json");
343 let pointer_json = std::fs::read_to_string(&latest_path).ok()?;
344 let pointer: LatestPointer = serde_json::from_str(&pointer_json).ok()?;
345 Self::load_by_id(&pointer.id)
346 }
347
348 pub fn load_latest_for_project_root(project_root: &str) -> Option<Self> {
350 if crate::core::pathutil::is_broad_or_unsafe_root(std::path::Path::new(project_root)) {
358 return None;
359 }
360 let dir = sessions_dir()?;
361 let target_root =
362 crate::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(project_root));
363 let mut latest_match: Option<Self> = None;
364
365 for entry in std::fs::read_dir(&dir).ok()?.flatten() {
366 let path = entry.path();
367 if path.extension().and_then(|e| e.to_str()) != Some("json") {
368 continue;
369 }
370 if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
371 continue;
372 }
373
374 let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
375 continue;
376 };
377 let Some(session) = Self::load_by_id(id) else {
378 continue;
379 };
380
381 if !session_matches_project_root(&session, &target_root) {
382 continue;
383 }
384
385 if latest_match
386 .as_ref()
387 .is_none_or(|existing| session.updated_at > existing.updated_at)
388 {
389 latest_match = Some(session);
390 }
391 }
392
393 latest_match
394 }
395
396 pub fn load_by_id(id: &str) -> Option<Self> {
398 validate_session_id(id).ok()?;
399 let dir = sessions_dir()?;
400 let path = dir.join(format!("{id}.json"));
401 let json = std::fs::read_to_string(&path).ok()?;
402 let session: Self = serde_json::from_str(&json).ok()?;
403 Some(normalize_loaded_session(session))
404 }
405
406 pub fn delete_session(id: &str) -> Result<bool, String> {
411 validate_session_id(id)?;
412 let Some(dir) = sessions_dir() else {
413 return Ok(false);
414 };
415 let path = dir.join(format!("{id}.json"));
416 if !path.exists() {
417 return Ok(false);
418 }
419
420 if let Some(session) = Self::load_by_id(id) {
421 persist_session_facts(&session)?;
422 }
423 std::fs::remove_file(&path).map_err(|e| e.to_string())?;
424
425 let snapshot = dir.join(format!("{id}_snapshot.txt"));
426 match std::fs::remove_file(&snapshot) {
427 Ok(()) => {}
428 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
429 Err(e) => return Err(e.to_string()),
430 }
431
432 let latest_path = dir.join("latest.json");
433 let points_to_deleted = std::fs::read_to_string(&latest_path)
434 .ok()
435 .and_then(|json| serde_json::from_str::<LatestPointer>(&json).ok())
436 .is_some_and(|pointer| pointer.id == id);
437 if points_to_deleted {
438 if let Some(next) = Self::list_sessions().into_iter().next() {
439 let latest_tmp = dir.join(".latest.json.tmp");
440 let pointer_json = serde_json::to_string(&LatestPointer { id: next.id })
441 .map_err(|e| e.to_string())?;
442 std::fs::write(&latest_tmp, pointer_json).map_err(|e| e.to_string())?;
443 restrict_file_permissions(&latest_tmp);
444 std::fs::rename(&latest_tmp, &latest_path).map_err(|e| e.to_string())?;
445 } else {
446 match std::fs::remove_file(&latest_path) {
447 Ok(()) => {}
448 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
449 Err(e) => return Err(e.to_string()),
450 }
451 }
452 }
453
454 Ok(true)
455 }
456
457 pub fn list_sessions() -> Vec<SessionSummary> {
459 let Some(dir) = sessions_dir() else {
460 return Vec::new();
461 };
462
463 let mut summaries = Vec::new();
464 if let Ok(entries) = std::fs::read_dir(&dir) {
465 for entry in entries.flatten() {
466 let path = entry.path();
467 if path.extension().and_then(|e| e.to_str()) != Some("json") {
468 continue;
469 }
470 if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
471 continue;
472 }
473 if let Ok(json) = std::fs::read_to_string(&path)
474 && let Ok(session) = serde_json::from_str::<SessionState>(&json)
475 {
476 summaries.push(SessionSummary {
477 id: session.id,
478 started_at: session.started_at,
479 updated_at: session.updated_at,
480 version: session.version,
481 task: session.task.as_ref().map(|t| t.description.clone()),
482 tool_calls: session.stats.total_tool_calls,
483 tokens_saved: session.stats.total_tokens_saved,
484 project_root: session.project_root,
485 });
486 }
487 }
488 }
489
490 summaries.sort_by_key(|x| std::cmp::Reverse(x.updated_at));
491 summaries
492 }
493
494 pub fn doctor_quarantine_unsafe_roots(apply: bool) -> (Vec<(String, String)>, usize) {
503 let mut found: Vec<(String, String)> = Vec::new();
504 let mut quarantined = 0usize;
505 let Some(dir) = sessions_dir() else {
506 return (found, quarantined);
507 };
508 let Ok(entries) = std::fs::read_dir(&dir) else {
509 return (found, quarantined);
510 };
511 for entry in entries.flatten() {
512 let path = entry.path();
513 if path.extension().and_then(|e| e.to_str()) != Some("json") {
514 continue;
515 }
516 let Some(id) = path.file_stem().and_then(|n| n.to_str()) else {
517 continue;
518 };
519 if id == "latest" || id.starts_with('.') {
520 continue;
521 }
522 let Some(session) = Self::load_by_id(id) else {
523 continue;
524 };
525 let Some(root) = session.project_root.as_deref() else {
526 continue;
527 };
528 let root_path = std::path::Path::new(root);
529 if crate::core::pathutil::is_broad_or_unsafe_root(root_path) {
530 found.push((id.to_string(), root.to_string()));
531 if apply {
532 let q_dir = dir.join("quarantine");
533 if std::fs::create_dir_all(&q_dir).is_ok()
534 && std::fs::rename(&path, q_dir.join(format!("{id}.json"))).is_ok()
535 {
536 quarantined += 1;
537 }
538 }
539 }
540 }
541 (found, quarantined)
542 }
543
544 pub fn cleanup_old_sessions(max_age_days: i64) -> u32 {
546 let Some(dir) = sessions_dir() else { return 0 };
547
548 let cutoff = Utc::now() - chrono::Duration::days(max_age_days);
549 let latest = Self::load_latest().map(|s| s.id);
550 let mut removed = 0u32;
551
552 if let Ok(entries) = std::fs::read_dir(&dir) {
553 for entry in entries.flatten() {
554 let path = entry.path();
555 if path.extension().and_then(|e| e.to_str()) != Some("json") {
556 continue;
557 }
558 let filename = path.file_stem().and_then(|n| n.to_str()).unwrap_or("");
559 if filename == "latest" || filename.starts_with('.') {
560 continue;
561 }
562 if latest.as_deref() == Some(filename) {
563 continue;
564 }
565 if let Ok(json) = std::fs::read_to_string(&path)
566 && let Ok(session) = serde_json::from_str::<SessionState>(&json)
567 && session.updated_at < cutoff
568 && std::fs::read_to_string(&path)
569 .ok()
570 .and_then(|content| serde_json::from_str::<Self>(&content).ok())
571 .is_none_or(|session| persist_session_facts(&session).is_ok())
572 && std::fs::remove_file(&path).is_ok()
573 {
574 removed += 1;
575 }
576 }
577 }
578
579 removed
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use super::SessionState;
586
587 #[test]
588 fn recent_project_sessions_use_bounded_index_without_scanning_legacy_store() {
589 let _data = crate::core::data_dir::isolated_data_dir();
590 let project = tempfile::tempdir().expect("project tempdir");
591 let root = project.path().to_string_lossy().to_string();
592
593 for id in ["first", "second", "third"] {
594 let mut session = SessionState::new();
595 session.id = id.to_string();
596 session.project_root = Some(root.clone());
597 session.save().expect("save indexed session");
598 }
599
600 let sessions = crate::core::session::paths::sessions_dir().expect("sessions dir");
603 std::fs::write(sessions.join("legacy-unreadable.json"), "not json")
604 .expect("write legacy artifact");
605
606 let ids: Vec<_> = SessionState::load_recent_for_project_root(&root, 8)
607 .into_iter()
608 .map(|session| session.id)
609 .collect();
610 assert_eq!(ids, ["third", "second", "first"]);
611 }
612
613 #[test]
614 fn recent_project_sessions_refuse_broad_roots() {
615 let _data = crate::core::data_dir::isolated_data_dir();
616 assert!(SessionState::load_recent_for_project_root("/", 8).is_empty());
617 }
618
619 #[test]
620 fn broad_root_sessions_are_never_persisted() {
621 let _data = crate::core::data_dir::isolated_data_dir();
622 let mut session = SessionState::new();
623 session.project_root = Some("/".to_string());
624
625 let error = session
626 .save()
627 .expect_err("broad root save must be rejected");
628
629 assert!(error.contains("broad or unsafe"));
630 assert!(
631 crate::core::session::paths::sessions_dir()
632 .expect("sessions dir")
633 .read_dir()
634 .map_or(true, |mut entries| entries.next().is_none())
635 );
636 }
637
638 #[test]
639 fn deferred_save_cannot_replace_a_newer_session_version() {
640 let _data = crate::core::data_dir::isolated_data_dir();
641 let mut session = SessionState::new();
642 let id = session.id.clone();
643 let older = session.prepare_save().expect("prepare older save");
644 session.increment();
645 let expected_version = session.version;
646 let newer = session.prepare_save().expect("prepare newer save");
647
648 newer.write_to_disk().expect("write newer save");
649 older.write_to_disk().expect("skip older save");
650
651 assert_eq!(
652 SessionState::load_by_id(&id)
653 .expect("load persisted session")
654 .version,
655 expected_version
656 );
657 }
658}