Skip to main content

vtcode_session_store/
retention.rs

1//! Retention and garbage-collection for the unified session store.
2
3use std::path::Path;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use walkdir::WalkDir;
7
8use crate::error::SessionStoreError;
9use crate::query::SessionSummary;
10use crate::sessions_root;
11
12/// Retention policy applied to the set of per-session stores.
13#[derive(Debug, Clone, Copy)]
14pub struct RetentionPolicy {
15    /// Maximum number of sessions to keep (oldest evicted first).
16    pub max_sessions: usize,
17    /// Maximum age of a session in days before eviction.
18    pub max_age_days: u64,
19}
20
21impl Default for RetentionPolicy {
22    fn default() -> Self {
23        Self { max_sessions: 50, max_age_days: 30 }
24    }
25}
26
27/// Apply the retention policy, removing the oldest / stale sessions.
28///
29/// Returns the number of sessions removed. This bounds the otherwise
30/// unbounded growth of `.vtcode/sessions/` so overhead does not accumulate
31/// on disk across a long-lived agent.
32pub fn apply_retention(
33    workspace: &Path,
34    policy: RetentionPolicy,
35) -> Result<usize, SessionStoreError> {
36    let root = sessions_root(workspace);
37    if !root.exists() {
38        return Ok(0);
39    }
40    let mut sessions: Vec<SessionSummary> = crate::query::recent_sessions(workspace, usize::MAX);
41    let mut removed = 0usize;
42
43    // Phase 1: evict oldest sessions beyond the count cap.
44    if sessions.len() > policy.max_sessions {
45        sessions.sort_by(|a, b| a.updated_at.cmp(&b.updated_at));
46        let to_remove = sessions.len() - policy.max_sessions;
47        for s in sessions.iter().take(to_remove) {
48            remove_session(&root.join(&s.session_id))?;
49            removed += 1;
50        }
51        // Drop evicted entries so phase 2 doesn't double-remove.
52        sessions.drain(..to_remove);
53    }
54
55    // Phase 2: evict sessions older than max_age_days (regardless of count).
56    let cutoff = age_cutoff(policy.max_age_days);
57    for s in &sessions {
58        if older_than(s.updated_at.as_str(), cutoff) {
59            remove_session(&root.join(&s.session_id))?;
60            removed += 1;
61        }
62    }
63
64    Ok(removed)
65}
66
67/// Remove the legacy `history/` and `logs/` directories after they have been
68/// imported into the unified store by [`crate::migrate_legacy`].
69///
70/// Returns the number of bytes freed. The legacy `checkpoints/` directory is
71/// intentionally left in place until `/revert` is rewired to the unified
72/// store; callers should confirm revert behavior before deleting it manually.
73pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
74    let vt = workspace.join(".vtcode");
75    let mut freed = 0u64;
76    for name in ["history", "logs"] {
77        let dir = vt.join(name);
78        if dir.exists() {
79            freed += dir_size(&dir);
80            std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
81        }
82    }
83    Ok(freed)
84}
85
86fn remove_session(dir: &Path) -> Result<(), SessionStoreError> {
87    if dir.exists() {
88        std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
89    }
90    Ok(())
91}
92
93fn dir_size(dir: &Path) -> u64 {
94    WalkDir::new(dir)
95        .into_iter()
96        .filter_map(Result::ok)
97        .filter(|e| e.file_type().is_file())
98        .filter_map(|e| e.metadata().ok())
99        .map(|m| m.len())
100        .sum()
101}
102
103fn age_cutoff(max_age_days: u64) -> SystemTime {
104    SystemTime::now() - Duration::from_secs(max_age_days * 24 * 3600)
105}
106
107fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
108    let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
109        return false;
110    };
111    let cutoff_secs = cutoff
112        .duration_since(UNIX_EPOCH)
113        .map(|d| d.as_secs() as i64)
114        .unwrap_or(i64::MAX);
115    dt.timestamp() < cutoff_secs
116}