Skip to main content

vtcode_session_store/
migration.rs

1//! One-off migration of the legacy, overlapping history stores into the
2//! unified per-session store.
3//!
4//! Legacy inputs:
5//! - `.vtcode/history/session-*.memory.json` → `<session>/derived/memory.json`
6//! - `.vtcode/logs/trajectory-*.jsonl`  → `<session>/derived/trajectory.jsonl`
7//!
8//! Legacy `checkpoints/` are intentionally *not* migrated here: they require a
9//! lossy `Message` → `ThreadEvent` mapping and `/revert` must be rewired first.
10
11use std::path::Path;
12
13use chrono::Utc;
14
15use crate::error::SessionStoreError;
16use crate::{SessionManifest, session_dir};
17
18/// Outcome of a legacy migration run.
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct MigrationReport {
21    /// Number of session directories created.
22    pub sessions_created: usize,
23    /// Number of session memory envelopes imported.
24    pub memory_imported: usize,
25    /// Number of trajectory logs imported.
26    pub trajectory_imported: usize,
27    /// Total bytes copied into the unified store.
28    pub bytes_migrated: u64,
29}
30
31/// Migrate legacy history/trajectory stores into the unified session store.
32///
33/// When `remove_legacy` is true, the now-imported `history/` and `logs/`
34/// directories are deleted (the `checkpoints/` directory is preserved).
35pub fn migrate_legacy(
36    workspace: &Path,
37    remove_legacy: bool,
38) -> Result<MigrationReport, SessionStoreError> {
39    let mut report = MigrationReport::default();
40    let vt = workspace.join(".vtcode");
41
42    let history_dir = vt.join("history");
43    if history_dir.is_dir() {
44        for entry in std::fs::read_dir(&history_dir)
45            .map_err(|e| SessionStoreError::io(history_dir.clone(), e))?
46            .filter_map(Result::ok)
47        {
48            let path = entry.path();
49            if path.extension().and_then(|e| e.to_str()) != Some("json") {
50                continue;
51            }
52            let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
53                continue;
54            };
55            let session_id = name.to_string();
56            let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
57            let dir = session_dir(workspace, &session_id);
58            std::fs::create_dir_all(dir.join(crate::DERIVED_DIR))
59                .map_err(|e| SessionStoreError::CreateDir { path: dir.clone(), source: e })?;
60            let dest = dir.join(crate::DERIVED_DIR).join("memory.json");
61            std::fs::write(&dest, &bytes).map_err(|e| SessionStoreError::io(dest, e))?;
62            write_manifest(&dir, &session_id, &path, "completed")?;
63            report.sessions_created += 1;
64            report.memory_imported += 1;
65            report.bytes_migrated += bytes.len() as u64;
66        }
67    }
68
69    let logs_dir = vt.join("logs");
70    if logs_dir.is_dir() {
71        for entry in std::fs::read_dir(&logs_dir)
72            .map_err(|e| SessionStoreError::io(logs_dir.clone(), e))?
73            .filter_map(Result::ok)
74        {
75            let path = entry.path();
76            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
77                continue;
78            }
79            let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
80                continue;
81            };
82            // `trajectory-<ts>` → session id `traj-<ts>` to avoid colliding with
83            // history session ids.
84            let session_id = format!("traj-{}", name.trim_start_matches("trajectory-"));
85            let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
86            let dir = session_dir(workspace, &session_id);
87            std::fs::create_dir_all(dir.join(crate::DERIVED_DIR))
88                .map_err(|e| SessionStoreError::CreateDir { path: dir.clone(), source: e })?;
89            let dest = dir.join(crate::DERIVED_DIR).join("trajectory.jsonl");
90            std::fs::write(&dest, &bytes).map_err(|e| SessionStoreError::io(dest, e))?;
91            write_manifest(&dir, &session_id, &path, "completed")?;
92            report.sessions_created += 1;
93            report.trajectory_imported += 1;
94            report.bytes_migrated += bytes.len() as u64;
95        }
96    }
97
98    if remove_legacy {
99        let freed = crate::retention::gc_legacy(workspace)?;
100        let _ = freed;
101    }
102
103    Ok(report)
104}
105
106fn write_manifest(
107    dir: &Path,
108    session_id: &str,
109    source: &Path,
110    status: &str,
111) -> Result<(), SessionStoreError> {
112    let ts = source
113        .metadata()
114        .ok()
115        .and_then(|m| m.modified().ok())
116        .map(|t| chrono::DateTime::<Utc>::from(t).to_rfc3339())
117        .unwrap_or_else(|| Utc::now().to_rfc3339());
118    let mut manifest = SessionManifest::new(session_id);
119    manifest.created_at = ts.clone();
120    manifest.updated_at = ts;
121    manifest.status = status.to_string();
122    let path = dir.join("manifest.json");
123    let bytes = serde_json::to_string_pretty(&manifest)?;
124    std::fs::write(&path, bytes).map_err(|e| SessionStoreError::io(path, e))?;
125    Ok(())
126}