Skip to main content

vtcode_memory/
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, PathBuf};
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, successfully imported source files are
34/// removed after verifying their contents; other files are preserved.
35/// Removal stages each source aside with an atomic rename and re-verifies the
36/// moved file, so a concurrent replacement at the original path is never
37/// deleted; a mismatch preserves the staged copy and aborts with an error.
38/// Existing session directories are never overwritten; exact completed imports
39/// are reused, while a collision stops migration and preserves legacy sources.
40pub fn migrate_legacy(workspace: &Path, remove_legacy: bool) -> Result<MigrationReport, SessionStoreError> {
41    let mut report = MigrationReport::default();
42    let mut imported = Vec::new();
43    let mut guards = Vec::new();
44    let vt = workspace.join(".vtcode");
45
46    let history_dir = vt.join("history");
47    if legacy_directory_exists(&history_dir)? {
48        for entry in std::fs::read_dir(&history_dir).map_err(|e| SessionStoreError::io(history_dir.clone(), e))? {
49            let entry = entry.map_err(|error| SessionStoreError::io(&history_dir, error))?;
50            if !entry
51                .file_type()
52                .map_err(|error| SessionStoreError::io(entry.path(), error))?
53                .is_file()
54            {
55                continue;
56            }
57            let path = entry.path();
58            if path.extension().and_then(|e| e.to_str()) != Some("json") {
59                continue;
60            }
61            let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
62                continue;
63            };
64            let session_id = name.to_string();
65            let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
66            let dir = session_dir(workspace, &session_id);
67            let dest = dir.join(crate::DERIVED_DIR).join("memory.json");
68            let (guard, exists) = claim_session(workspace, &dir, &session_id, &path, &dest, &bytes)?;
69            if !exists {
70                crate::ensure_private_directory(&dir)?;
71                crate::ensure_private_directory(&dir.join(crate::DERIVED_DIR))?;
72                vtcode_commons::VtCodePaths::write_private_file_atomic(&dest, &bytes)
73                    .map_err(|error| SessionStoreError::io(&dest, std::io::Error::other(error)))?;
74                write_manifest(&dir, &session_id, &path, "completed")?;
75                report.sessions_created += 1;
76                report.memory_imported += 1;
77                report.bytes_migrated += bytes.len() as u64;
78            }
79            guards.push(guard);
80            imported.push((path, dest));
81        }
82    }
83
84    let logs_dir = vt.join("logs");
85    if legacy_directory_exists(&logs_dir)? {
86        for entry in std::fs::read_dir(&logs_dir).map_err(|e| SessionStoreError::io(logs_dir.clone(), e))? {
87            let entry = entry.map_err(|error| SessionStoreError::io(&logs_dir, error))?;
88            if !entry
89                .file_type()
90                .map_err(|error| SessionStoreError::io(entry.path(), error))?
91                .is_file()
92            {
93                continue;
94            }
95            let path = entry.path();
96            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
97                continue;
98            }
99            let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
100                continue;
101            };
102            // `trajectory-<ts>` → session id `traj-<ts>` to avoid colliding with
103            // history session ids.
104            let session_id = format!("traj-{}", name.trim_start_matches("trajectory-"));
105            let bytes = std::fs::read(&path).map_err(|e| SessionStoreError::io(path.clone(), e))?;
106            let dir = session_dir(workspace, &session_id);
107            let dest = dir.join(crate::DERIVED_DIR).join("trajectory.jsonl");
108            let (guard, exists) = claim_session(workspace, &dir, &session_id, &path, &dest, &bytes)?;
109            if !exists {
110                crate::ensure_private_directory(&dir)?;
111                crate::ensure_private_directory(&dir.join(crate::DERIVED_DIR))?;
112                vtcode_commons::VtCodePaths::write_private_file_atomic(&dest, &bytes)
113                    .map_err(|error| SessionStoreError::io(&dest, std::io::Error::other(error)))?;
114                write_manifest(&dir, &session_id, &path, "completed")?;
115                report.sessions_created += 1;
116                report.trajectory_imported += 1;
117                report.bytes_migrated += bytes.len() as u64;
118            }
119            guards.push(guard);
120            imported.push((path, dest));
121        }
122    }
123
124    if remove_legacy {
125        remove_imported_sources(&imported)?;
126    }
127    // Guards stay held through cleanup so retention cannot remove an imported
128    // destination between verification and legacy-source removal.
129    drop(guards);
130
131    Ok(report)
132}
133
134fn legacy_directory_exists(dir: &Path) -> Result<bool, SessionStoreError> {
135    match std::fs::symlink_metadata(dir) {
136        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true),
137        Ok(_) => Err(SessionStoreError::io(dir, std::io::Error::other("legacy path is not a directory"))),
138        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
139        Err(error) => Err(SessionStoreError::io(dir, error)),
140    }
141}
142
143fn remove_imported_sources(imported: &[(PathBuf, PathBuf)]) -> Result<(), SessionStoreError> {
144    for (source, dest) in imported {
145        verify_imported(source, dest)?;
146    }
147    for (source, dest) in imported {
148        let staged = staged_removal_path(source)?;
149        // Best-effort collision check: planting a staged file here needs
150        // directory write access, which already permits deleting sources.
151        if std::fs::symlink_metadata(&staged).is_ok() {
152            return Err(SessionStoreError::io(
153                &staged,
154                std::io::Error::other("staged removal target already exists; refusing to overwrite"),
155            ));
156        }
157        std::fs::rename(source, &staged).map_err(|error| SessionStoreError::io(source, error))?;
158        if read_no_follow(&staged)? != read_no_follow(dest)? {
159            return Err(staged_mismatch_error(&staged));
160        }
161        std::fs::remove_file(&staged).map_err(|error| SessionStoreError::io(&staged, error))?;
162    }
163    Ok(())
164}
165
166fn verify_imported(source: &Path, dest: &Path) -> Result<(), SessionStoreError> {
167    if read_no_follow(source)? != read_no_follow(dest)? {
168        return Err(SessionStoreError::io(source, std::io::Error::other("legacy source changed after import")));
169    }
170    Ok(())
171}
172
173fn read_no_follow(path: &Path) -> Result<Vec<u8>, SessionStoreError> {
174    vtcode_commons::VtCodePaths::read_file_no_follow(path)
175        .map_err(|error| SessionStoreError::io(path, std::io::Error::other(error)))
176}
177
178/// Staging path for fail-closed legacy cleanup: same directory (so the rename
179/// stays on one filesystem), hidden, and never matching the importer's
180/// `.json`/`.jsonl` extension filter.
181fn staged_removal_path(source: &Path) -> Result<PathBuf, SessionStoreError> {
182    let missing = || SessionStoreError::io(source, std::io::Error::other("legacy source has no file name"));
183    let name = source.file_name().ok_or_else(missing)?;
184    let mut staged = std::ffi::OsString::from(".");
185    staged.push(name);
186    staged.push(format!(".migrated-{}", std::process::id()));
187    source.parent().ok_or_else(missing).map(|parent| parent.join(staged))
188}
189
190fn staged_mismatch_error(staged: &Path) -> SessionStoreError {
191    SessionStoreError::io(
192        staged,
193        std::io::Error::other("legacy source changed after import; staged copy preserved for manual recovery"),
194    )
195}
196
197fn claim_session(
198    workspace: &Path,
199    dir: &Path,
200    session_id: &str,
201    source: &Path,
202    dest: &Path,
203    bytes: &[u8],
204) -> Result<(std::fs::File, bool), SessionStoreError> {
205    let name = dir
206        .file_name()
207        .ok_or_else(|| SessionStoreError::io(dir, std::io::Error::other("missing session name")))?;
208    let guard = crate::session_guard::try_exclusive(workspace, name)?
209        .ok_or_else(|| SessionStoreError::SessionBusy { session: session_id.to_owned() })?;
210    match std::fs::symlink_metadata(dir) {
211        Ok(metadata)
212            if metadata.is_dir()
213                && !metadata.file_type().is_symlink()
214                && vtcode_commons::VtCodePaths::read_file_no_follow(dir.join("manifest.json"))
215                    .ok()
216                    .and_then(|bytes| serde_json::from_slice::<SessionManifest>(&bytes).ok())
217                    .is_some_and(|manifest| manifest == migrated_manifest(session_id, source, "completed"))
218                && vtcode_commons::VtCodePaths::read_file_no_follow(dest).is_ok_and(|stored| stored == bytes) =>
219        {
220            Ok((guard, true))
221        }
222        Ok(_) => Err(SessionStoreError::io(
223            dir,
224            std::io::Error::new(std::io::ErrorKind::AlreadyExists, "migration would overwrite an existing session"),
225        )),
226        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok((guard, false)),
227        Err(error) => Err(SessionStoreError::io(dir, error)),
228    }
229}
230
231fn write_manifest(dir: &Path, session_id: &str, source: &Path, status: &str) -> Result<(), SessionStoreError> {
232    let manifest = migrated_manifest(session_id, source, status);
233    let path = dir.join("manifest.json");
234    let bytes = serde_json::to_vec(&manifest)?;
235    vtcode_commons::VtCodePaths::write_private_file_atomic(&path, &bytes)
236        .map_err(|error| SessionStoreError::io(path, std::io::Error::other(error)))?;
237    Ok(())
238}
239
240fn migrated_manifest(session_id: &str, source: &Path, status: &str) -> SessionManifest {
241    let ts = source
242        .metadata()
243        .ok()
244        .and_then(|m| m.modified().ok())
245        .map(|t| chrono::DateTime::<Utc>::from(t).to_rfc3339())
246        .unwrap_or_else(|| Utc::now().to_rfc3339());
247    let mut manifest = SessionManifest::new(session_id);
248    manifest.created_at = ts.clone();
249    manifest.updated_at = ts;
250    manifest.status = status.to_string();
251    manifest
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn cleanup_preserves_all_sources_when_one_changed() {
260        let dir = tempfile::tempdir().expect("tempdir");
261        let first = dir.path().join("first");
262        let second = dir.path().join("second");
263        let first_copy = dir.path().join("first-copy");
264        let second_copy = dir.path().join("second-copy");
265        std::fs::write(&first, b"same").expect("first");
266        std::fs::write(&first_copy, b"same").expect("first copy");
267        std::fs::write(&second, b"new").expect("changed source");
268        std::fs::write(&second_copy, b"old").expect("second copy");
269        let error = remove_imported_sources(&[(first.clone(), first_copy), (second.clone(), second_copy)])
270            .expect_err("changed source must stop cleanup");
271        assert!(error.to_string().contains("changed after import"));
272        assert_eq!(std::fs::read(first).expect("first retained"), b"same");
273        assert_eq!(std::fs::read(second).expect("second retained"), b"new");
274    }
275
276    #[test]
277    fn cleanup_refuses_to_overwrite_existing_staged_copy() {
278        let dir = tempfile::tempdir().expect("tempdir");
279        let source = dir.path().join("source");
280        let dest = dir.path().join("dest");
281        std::fs::write(&source, b"same").expect("source");
282        std::fs::write(&dest, b"same").expect("dest");
283        let staged = staged_removal_path(&source).expect("staged path");
284        std::fs::write(&staged, b"stale").expect("stale staged");
285        let error = remove_imported_sources(&[(source.clone(), dest)]).expect_err("staged collision must stop cleanup");
286        assert!(error.to_string().contains("already exists"));
287        assert_eq!(std::fs::read(&source).expect("source retained"), b"same");
288        assert_eq!(std::fs::read(&staged).expect("staged retained"), b"stale");
289    }
290
291    #[test]
292    fn cleanup_removes_source_without_leaving_a_staged_copy() {
293        let dir = tempfile::tempdir().expect("tempdir");
294        let source = dir.path().join("source");
295        let dest = dir.path().join("dest");
296        std::fs::write(&source, b"same").expect("source");
297        std::fs::write(&dest, b"same").expect("dest");
298        let staged = staged_removal_path(&source).expect("staged path");
299        remove_imported_sources(&[(source.clone(), dest)]).expect("cleanup");
300        assert!(!source.exists());
301        assert!(!staged.exists());
302    }
303
304    #[test]
305    fn staged_removal_names_are_never_imported() {
306        for name in ["session.memory.json", "trajectory-1.jsonl"] {
307            let staged = staged_removal_path(Path::new(name)).expect("staged path");
308            let ext = staged.extension().and_then(|e| e.to_str());
309            assert_ne!(ext, Some("json"), "{staged:?}");
310            assert_ne!(ext, Some("jsonl"), "{staged:?}");
311        }
312    }
313
314    #[test]
315    fn staged_mismatch_error_names_the_preserved_copy() {
316        let error = staged_mismatch_error(Path::new("/tmp/.source.migrated-1"));
317        assert!(error.to_string().contains("changed after import"));
318        assert!(error.to_string().contains("staged copy preserved"));
319    }
320}