1use 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 if !is_sessions_root(&root)? {
55 return Ok(0);
56 }
57 mark_abandoned_active_sessions(workspace, policy.max_age_days, preserve_session_id)?;
61 let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
62 let sessions = retention_candidates(&root, preserve_path.as_deref())?;
63 let mut removed = 0usize;
64
65 let (empty, mut sessions): (Vec<_>, Vec<_>) = sessions
69 .into_iter()
70 .partition(|s| s.summary.turn_count == 0 && s.summary.status != "active");
71 for s in &empty {
72 removed += usize::from(remove_candidate(workspace, &root, s)?);
73 }
74
75 if sessions.len() > policy.max_sessions {
77 sessions.sort_by(|a, b| a.summary.updated_at.cmp(&b.summary.updated_at));
78 let to_remove = sessions.len() - policy.max_sessions;
79 for s in sessions.iter().take(to_remove) {
80 removed += usize::from(remove_candidate(workspace, &root, s)?);
81 }
82 sessions.drain(..to_remove);
84 }
85
86 let cutoff = age_cutoff(policy.max_age_days);
88 for s in &sessions {
89 if older_than(s.summary.updated_at.as_str(), cutoff) {
90 removed += usize::from(remove_candidate(workspace, &root, s)?);
91 }
92 }
93
94 Ok(removed)
95}
96
97pub const RETENTION_PIN_FILE: &str = "retention-pin.json";
100
101pub fn evict_zero_turn_completed_store(workspace: &Path, session_id: &str) -> Result<bool, SessionStoreError> {
109 let root = sessions_root(workspace);
110 if !is_sessions_root(&root)? {
111 return Ok(false);
112 }
113 let dir = crate::session_dir(workspace, session_id);
114 if dir.parent() != Some(&root) {
115 return Ok(false);
116 }
117 let Some(name) = dir.file_name() else { return Ok(false) };
118 let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
119 return Ok(false);
120 };
121 if session_retention_pinned(&dir) || session_dir_may_be_live(&dir) {
122 return Ok(false);
123 }
124 let manifest_path = dir.join("manifest.json");
125 let Ok(bytes) = std::fs::read(&manifest_path) else {
126 return Ok(false);
127 };
128 let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
129 return Ok(false);
130 };
131 if summary.turn_count > 0 || summary.status == "active" {
132 return Ok(false);
133 }
134 remove_session(&root, &dir)?;
135 Ok(true)
136}
137
138#[must_use]
140pub fn session_retention_pinned(session_dir: &Path) -> bool {
141 match std::fs::symlink_metadata(session_dir.join(RETENTION_PIN_FILE)) {
142 Ok(_) => true,
143 Err(error) => error.kind() != std::io::ErrorKind::NotFound,
144 }
145}
146
147pub(crate) fn session_dir_is_live(session_dir: &Path) -> bool {
155 matches!(session_lock_state(session_dir), SessionLockState::Live)
156}
157
158fn session_dir_may_be_live(session_dir: &Path) -> bool {
159 !matches!(session_lock_state(session_dir), SessionLockState::Inactive)
160}
161
162enum SessionLockState {
163 Live,
164 Inactive,
165 Unknown,
166}
167
168fn session_lock_state(session_dir: &Path) -> SessionLockState {
169 use crate::event_log::SESSION_LOCK_FILE;
170
171 let lock_path = session_dir.join(SESSION_LOCK_FILE);
172 match std::fs::symlink_metadata(&lock_path) {
173 Ok(metadata) if metadata.file_type().is_file() => {}
174 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return SessionLockState::Inactive,
175 _ => return SessionLockState::Unknown,
176 }
177 let file = match std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) {
178 Ok(file) => file,
179 Err(_) => return SessionLockState::Unknown,
180 };
181 match file.try_lock().map_err(std::io::Error::from) {
182 Ok(()) => SessionLockState::Inactive,
183 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => SessionLockState::Live,
184 Err(_) => SessionLockState::Unknown,
185 }
186}
187
188#[must_use]
195pub fn retention_pinned_session_ids(workspace: &Path) -> Vec<String> {
196 let Ok(entries) = std::fs::read_dir(sessions_root(workspace)) else {
197 return Vec::new();
198 };
199 entries
200 .flatten()
201 .filter(|entry| entry.file_type().map(|file_type| file_type.is_dir()).unwrap_or(false))
202 .filter(|entry| session_retention_pinned(&entry.path()))
203 .filter_map(|entry| entry.file_name().into_string().ok())
204 .collect()
205}
206
207pub fn pin_session_retention(session_dir: &Path, reason: &str) -> Result<(), SessionStoreError> {
209 let _guard = crate::session_guard::shared_for_session_dir(session_dir)?;
210 let path = session_dir.join(RETENTION_PIN_FILE);
211 let metadata = std::fs::symlink_metadata(session_dir).map_err(|error| SessionStoreError::io(session_dir, error))?;
212 if !metadata.is_dir() || metadata.file_type().is_symlink() {
213 return Err(SessionStoreError::io(session_dir, std::io::Error::other("session is not a directory")));
214 }
215 let body = serde_json::json!({
216 "reason": reason,
217 "pinned_at": chrono::Utc::now().to_rfc3339(),
218 });
219 vtcode_commons::VtCodePaths::write_private_file_atomic(&path, body.to_string().as_bytes())
220 .map_err(|error| SessionStoreError::io(path, std::io::Error::other(error)))
221}
222
223pub fn unpin_session_retention(session_dir: &Path) -> Result<bool, SessionStoreError> {
225 let _guard = crate::session_guard::shared_for_session_dir(session_dir)?;
226 let path = session_dir.join(RETENTION_PIN_FILE);
227 if !path.is_file() {
228 return Ok(false);
229 }
230 std::fs::remove_file(&path).map_err(|e| SessionStoreError::io(path, e))?;
231 Ok(true)
232}
233
234fn retention_candidates(
238 root: &Path,
239 preserve_path: Option<&Path>,
240) -> Result<Vec<RetentionCandidate>, SessionStoreError> {
241 let entries = std::fs::read_dir(root).map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
242 let mut candidates = Vec::new();
243 for entry in entries {
244 let entry = entry.map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
245 let file_type = entry.file_type().map_err(|e| SessionStoreError::io(entry.path(), e))?;
246 if !file_type.is_dir() || file_type.is_symlink() {
247 continue;
248 }
249 let path = entry.path();
250 if preserve_path.is_some_and(|preserve_path| preserve_path == path) {
251 continue;
252 }
253 if session_retention_pinned(&path) {
255 continue;
256 }
257 if session_dir_may_be_live(&path) {
261 continue;
262 }
263 let manifest_path = path.join("manifest.json");
264 let Ok(bytes) = std::fs::read(&manifest_path) else {
265 continue;
266 };
267 let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
268 continue;
269 };
270 if summary.status == "active" {
271 continue;
272 }
273 candidates.push(RetentionCandidate { path, summary });
274 }
275 Ok(candidates)
276}
277
278pub fn mark_abandoned_active_sessions(
287 workspace: &Path,
288 max_age_days: u64,
289 preserve_session_id: Option<&str>,
290) -> Result<usize, SessionStoreError> {
291 if max_age_days == 0 {
292 return Ok(0);
293 }
294 let root = sessions_root(workspace);
295 if !is_sessions_root(&root)? {
296 return Ok(0);
297 }
298 let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
299 let Ok(entries) = std::fs::read_dir(&root) else {
300 return Ok(0);
301 };
302 let cutoff = age_cutoff(max_age_days);
303 let mut marked = 0usize;
304 for entry in entries.flatten() {
305 let path = entry.path();
306 let file_type = match entry.file_type() {
307 Ok(file_type) => file_type,
308 Err(_) => continue,
309 };
310 if !file_type.is_dir() || file_type.is_symlink() {
313 continue;
314 }
315 if preserve_path.as_deref() == Some(path.as_path()) {
316 continue;
317 }
318 let Some(name) = path.file_name() else { continue };
319 let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
320 continue;
321 };
322 if session_retention_pinned(&path) {
323 continue;
324 }
325 if session_dir_may_be_live(&path) {
329 continue;
330 }
331 let manifest_path = path.join("manifest.json");
332 let Ok(bytes) = std::fs::read(&manifest_path) else {
333 continue;
334 };
335 let Ok(mut summary) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
336 continue;
337 };
338 let is_active = summary.get("status").and_then(serde_json::Value::as_str) == Some("active");
339 if !is_active {
340 continue;
341 }
342 let updated_at = summary
343 .get("updated_at")
344 .and_then(serde_json::Value::as_str)
345 .unwrap_or_default();
346 if !older_than(updated_at, cutoff) {
347 continue;
348 }
349 if let Some(object) = summary.as_object_mut() {
350 object.insert("status".to_string(), serde_json::Value::String("completed".to_string()));
351 } else {
352 continue;
353 }
354 let body = serde_json::to_vec_pretty(&summary)
355 .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
356 vtcode_commons::VtCodePaths::write_private_file_atomic(&manifest_path, &body)
361 .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
362 marked += 1;
363 }
364 Ok(marked)
365}
366
367#[deprecated(note = "removes files migration never imports; re-run `migrate_legacy(workspace, true)` instead")]
379pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
380 let vt = workspace.join(".vtcode");
381 let mut freed = 0u64;
382 for name in ["history", "logs"] {
383 let dir = vt.join(name);
384 if dir.exists() {
385 freed += dir_size(&dir);
386 std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
387 }
388 }
389 Ok(freed)
390}
391
392fn is_sessions_root(root: &Path) -> Result<bool, SessionStoreError> {
393 match std::fs::symlink_metadata(root) {
394 Ok(metadata) => Ok(!metadata.file_type().is_symlink() && metadata.is_dir()),
395 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
396 Err(error) => Err(SessionStoreError::io(root.to_path_buf(), error)),
397 }
398}
399
400fn remove_candidate(workspace: &Path, root: &Path, candidate: &RetentionCandidate) -> Result<bool, SessionStoreError> {
401 let Some(name) = candidate.path.file_name() else {
402 return Ok(false);
403 };
404 let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
405 return Ok(false);
406 };
407 if session_retention_pinned(&candidate.path) || session_dir_may_be_live(&candidate.path) {
408 return Ok(false);
409 }
410 let Ok(bytes) = std::fs::read(candidate.path.join("manifest.json")) else {
411 return Ok(false);
412 };
413 if serde_json::from_slice::<SessionSummary>(&bytes).ok().as_ref() != Some(&candidate.summary) {
414 return Ok(false);
415 }
416 remove_session(root, &candidate.path)?;
417 Ok(true)
418}
419
420fn remove_session(root: &Path, dir: &Path) -> Result<(), SessionStoreError> {
421 if dir.parent() != Some(root) {
424 return Ok(());
425 }
426 let metadata = match std::fs::symlink_metadata(dir) {
427 Ok(metadata) => metadata,
428 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
429 Err(error) => return Err(SessionStoreError::io(dir.to_path_buf(), error)),
430 };
431 if metadata.file_type().is_symlink() || !metadata.is_dir() {
432 return Ok(());
433 }
434 std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
435 Ok(())
436}
437
438fn dir_size(dir: &Path) -> u64 {
439 WalkDir::new(dir)
440 .into_iter()
441 .filter_map(Result::ok)
442 .filter(|e| e.file_type().is_file())
443 .filter_map(|e| e.metadata().ok())
444 .map(|m| m.len())
445 .sum()
446}
447
448fn age_cutoff(max_age_days: u64) -> SystemTime {
449 let seconds = max_age_days.saturating_mul(24 * 3600);
450 SystemTime::now() - Duration::from_secs(seconds)
451}
452
453fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
454 let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
455 return false;
456 };
457 let cutoff_secs = cutoff
458 .duration_since(UNIX_EPOCH)
459 .map(|d| d.as_secs() as i64)
460 .unwrap_or(i64::MAX);
461 dt.timestamp() < cutoff_secs
462}
463
464#[cfg(test)]
465mod candidate_tests {
466 use super::*;
467
468 #[test]
469 fn stale_candidate_is_rechecked_before_removal() {
470 let workspace = tempfile::tempdir().expect("workspace");
471 let root = sessions_root(workspace.path());
472 let dir = root.join("candidate");
473 std::fs::create_dir_all(&dir).expect("session dir");
474 let manifest = dir.join("manifest.json");
475 let mut summary = SessionSummary {
476 session_id: "candidate".to_string(),
477 turn_count: 1,
478 event_count: 2,
479 status: "completed".to_string(),
480 updated_at: "2020-01-01T00:00:00Z".to_string(),
481 };
482 std::fs::write(&manifest, serde_json::to_vec(&summary).expect("serialize")).expect("manifest");
483 let candidates = retention_candidates(&root, None).expect("candidates");
484 assert_eq!(candidates.len(), 1);
485 summary.turn_count = 2;
486 std::fs::write(&manifest, serde_json::to_vec(&summary).expect("serialize")).expect("update manifest");
487 assert!(!remove_candidate(workspace.path(), &root, &candidates[0]).expect("recheck"));
488 assert!(manifest.exists());
489 }
490}