vtcode_memory/
retention.rs1use 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#[derive(Debug)]
13struct RetentionCandidate {
14 path: std::path::PathBuf,
15 summary: SessionSummary,
16}
17
18#[derive(Debug, Clone, Copy)]
20pub struct RetentionPolicy {
21 pub max_sessions: usize,
23 pub max_age_days: u64,
25}
26
27impl Default for RetentionPolicy {
28 fn default() -> Self {
29 Self { max_sessions: 50, max_age_days: 30 }
30 }
31}
32
33pub fn apply_retention(workspace: &Path, policy: RetentionPolicy) -> Result<usize, SessionStoreError> {
39 apply_retention_preserving(workspace, policy, None)
40}
41
42pub fn apply_retention_preserving(
49 workspace: &Path,
50 policy: RetentionPolicy,
51 preserve_session_id: Option<&str>,
52) -> Result<usize, SessionStoreError> {
53 let root = sessions_root(workspace);
54 let root_metadata = match std::fs::symlink_metadata(&root) {
55 Ok(metadata) => metadata,
56 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
57 Err(error) => return Err(SessionStoreError::io(root.clone(), error)),
58 };
59 if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() {
60 return Ok(0);
61 }
62 mark_abandoned_active_sessions(workspace, policy.max_age_days, preserve_session_id)?;
66 let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
67 let mut sessions = retention_candidates(&root, preserve_path.as_deref())?;
68 let mut removed = 0usize;
69
70 if sessions.len() > policy.max_sessions {
72 sessions.sort_by(|a, b| a.summary.updated_at.cmp(&b.summary.updated_at));
73 let to_remove = sessions.len() - policy.max_sessions;
74 for s in sessions.iter().take(to_remove) {
75 remove_session(&root, &s.path)?;
76 removed += 1;
77 }
78 sessions.drain(..to_remove);
80 }
81
82 let cutoff = age_cutoff(policy.max_age_days);
84 for s in &sessions {
85 if older_than(s.summary.updated_at.as_str(), cutoff) {
86 remove_session(&root, &s.path)?;
87 removed += 1;
88 }
89 }
90
91 Ok(removed)
92}
93
94pub const RETENTION_PIN_FILE: &str = "retention-pin.json";
97
98#[must_use]
100pub fn session_retention_pinned(session_dir: &Path) -> bool {
101 session_dir.join(RETENTION_PIN_FILE).is_file()
102}
103
104pub(crate) fn session_dir_is_live(session_dir: &Path) -> bool {
113 use crate::event_log::SESSION_LOCK_FILE;
114
115 let lock_path = session_dir.join(SESSION_LOCK_FILE);
116 let file = match std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) {
117 Ok(file) => file,
118 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return false,
119 Err(_) => return true,
120 };
121 file.try_lock()
122 .map_err(std::io::Error::from)
123 .is_err_and(|error| error.kind() == std::io::ErrorKind::WouldBlock)
124}
125
126#[must_use]
133pub fn retention_pinned_session_ids(workspace: &Path) -> Vec<String> {
134 let Ok(entries) = std::fs::read_dir(sessions_root(workspace)) else {
135 return Vec::new();
136 };
137 entries
138 .flatten()
139 .filter(|entry| entry.file_type().map(|file_type| file_type.is_dir()).unwrap_or(false))
140 .filter(|entry| session_retention_pinned(&entry.path()))
141 .filter_map(|entry| entry.file_name().into_string().ok())
142 .collect()
143}
144
145pub fn pin_session_retention(session_dir: &Path, reason: &str) -> Result<(), SessionStoreError> {
147 let path = session_dir.join(RETENTION_PIN_FILE);
148 let body = serde_json::json!({
149 "reason": reason,
150 "pinned_at": chrono::Utc::now().to_rfc3339(),
151 });
152 std::fs::write(&path, body.to_string()).map_err(|e| SessionStoreError::io(path, e))
153}
154
155pub fn unpin_session_retention(session_dir: &Path) -> Result<bool, SessionStoreError> {
157 let path = session_dir.join(RETENTION_PIN_FILE);
158 if !path.is_file() {
159 return Ok(false);
160 }
161 std::fs::remove_file(&path).map_err(|e| SessionStoreError::io(path, e))?;
162 Ok(true)
163}
164
165fn retention_candidates(
169 root: &Path,
170 preserve_path: Option<&Path>,
171) -> Result<Vec<RetentionCandidate>, SessionStoreError> {
172 let entries = std::fs::read_dir(root).map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
173 let mut candidates = Vec::new();
174 for entry in entries {
175 let entry = entry.map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
176 let file_type = entry.file_type().map_err(|e| SessionStoreError::io(entry.path(), e))?;
177 if !file_type.is_dir() || file_type.is_symlink() {
178 continue;
179 }
180 let path = entry.path();
181 if preserve_path.is_some_and(|preserve_path| preserve_path == path) {
182 continue;
183 }
184 if session_retention_pinned(&path) {
186 continue;
187 }
188 if session_dir_is_live(&path) {
192 continue;
193 }
194 let manifest_path = path.join("manifest.json");
195 let Ok(bytes) = std::fs::read(&manifest_path) else {
196 continue;
197 };
198 let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
199 continue;
200 };
201 if summary.status == "active" {
202 continue;
203 }
204 candidates.push(RetentionCandidate { path, summary });
205 }
206 Ok(candidates)
207}
208
209pub fn mark_abandoned_active_sessions(
218 workspace: &Path,
219 max_age_days: u64,
220 preserve_session_id: Option<&str>,
221) -> Result<usize, SessionStoreError> {
222 if max_age_days == 0 {
223 return Ok(0);
224 }
225 let root = sessions_root(workspace);
226 let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
227 let Ok(entries) = std::fs::read_dir(&root) else {
228 return Ok(0);
229 };
230 let cutoff = age_cutoff(max_age_days);
231 let mut marked = 0usize;
232 for entry in entries.flatten() {
233 let path = entry.path();
234 let file_type = match entry.file_type() {
235 Ok(file_type) => file_type,
236 Err(_) => continue,
237 };
238 if !file_type.is_dir() || file_type.is_symlink() {
241 continue;
242 }
243 if preserve_path.as_deref() == Some(path.as_path()) {
244 continue;
245 }
246 if session_retention_pinned(&path) {
247 continue;
248 }
249 if session_dir_is_live(&path) {
253 continue;
254 }
255 let manifest_path = path.join("manifest.json");
256 let Ok(bytes) = std::fs::read(&manifest_path) else {
257 continue;
258 };
259 let Ok(mut summary) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
260 continue;
261 };
262 let is_active = summary.get("status").and_then(serde_json::Value::as_str) == Some("active");
263 if !is_active {
264 continue;
265 }
266 let updated_at = summary
267 .get("updated_at")
268 .and_then(serde_json::Value::as_str)
269 .unwrap_or_default();
270 if !older_than(updated_at, cutoff) {
271 continue;
272 }
273 if let Some(object) = summary.as_object_mut() {
274 object.insert("status".to_string(), serde_json::Value::String("completed".to_string()));
275 } else {
276 continue;
277 }
278 let body = serde_json::to_vec_pretty(&summary)
279 .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
280 vtcode_commons::VtCodePaths::write_private_file_atomic(&manifest_path, &body)
285 .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
286 marked += 1;
287 }
288 Ok(marked)
289}
290
291pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
298 let vt = workspace.join(".vtcode");
299 let mut freed = 0u64;
300 for name in ["history", "logs"] {
301 let dir = vt.join(name);
302 if dir.exists() {
303 freed += dir_size(&dir);
304 std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
305 }
306 }
307 Ok(freed)
308}
309
310fn remove_session(root: &Path, dir: &Path) -> Result<(), SessionStoreError> {
311 if dir.parent() != Some(root) {
314 return Ok(());
315 }
316 let metadata = match std::fs::symlink_metadata(dir) {
317 Ok(metadata) => metadata,
318 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
319 Err(error) => return Err(SessionStoreError::io(dir.to_path_buf(), error)),
320 };
321 if metadata.file_type().is_symlink() || !metadata.is_dir() {
322 return Ok(());
323 }
324 std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
325 Ok(())
326}
327
328fn dir_size(dir: &Path) -> u64 {
329 WalkDir::new(dir)
330 .into_iter()
331 .filter_map(Result::ok)
332 .filter(|e| e.file_type().is_file())
333 .filter_map(|e| e.metadata().ok())
334 .map(|m| m.len())
335 .sum()
336}
337
338fn age_cutoff(max_age_days: u64) -> SystemTime {
339 let seconds = max_age_days.saturating_mul(24 * 3600);
340 SystemTime::now() - Duration::from_secs(seconds)
341}
342
343fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
344 let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
345 return false;
346 };
347 let cutoff_secs = cutoff
348 .duration_since(UNIX_EPOCH)
349 .map(|d| d.as_secs() as i64)
350 .unwrap_or(i64::MAX);
351 dt.timestamp() < cutoff_secs
352}