Skip to main content

vtcode_commons/
vtcode_paths_migration.rs

1//! Rollback-safe migration from the pre-XDG `~/.vtcode` layout.
2
3use std::ffi::OsStr;
4use std::fs::{self, File};
5use std::io::{self, Read, Write};
6use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use anyhow::{Context, Result, anyhow, bail};
10use serde::Serialize;
11
12use super::{VtCodePaths, create_private_new_file, ensure_migration_dir, ensure_private_dir, open_no_follow};
13
14/// Performs one idempotent migration using an immutable path-policy snapshot.
15#[derive(Debug, Clone)]
16pub struct LegacyMigrator {
17    paths: VtCodePaths,
18}
19
20impl LegacyMigrator {
21    /// Creates a migrator bound to one resolved global path policy.
22    pub fn new(paths: VtCodePaths) -> Self {
23        Self { paths }
24    }
25
26    /// Scans and copies eligible legacy content without modifying its source.
27    pub fn run(&self) -> Result<MigrationReport> {
28        let marker = self.paths.migration_marker_path();
29        let mut report = MigrationReport::default();
30        let marker_parent = marker.parent().ok_or_else(|| anyhow!("migration marker has no parent"))?;
31        if let Err(error) = ensure_private_dir(marker_parent) {
32            report.failures.push(MigrationFailure {
33                path: marker_parent.to_path_buf(),
34                error: error.to_string(),
35            });
36            persist_report_best_effort(&self.paths, &report);
37            return Ok(report);
38        }
39        let marker_blocked = match fs::symlink_metadata(&marker) {
40            Ok(metadata) if metadata.file_type().is_symlink() => {
41                report.failures.push(MigrationFailure {
42                    path: marker.clone(),
43                    error: "migration marker is a symlink; refusing to follow it".to_string(),
44                });
45                true
46            }
47            Ok(metadata) if metadata.is_file() => match valid_migration_marker(&marker) {
48                Ok(true) => {
49                    return Ok(MigrationReport {
50                        already_completed: true,
51                        ..MigrationReport::default()
52                    });
53                }
54                Ok(false) => {
55                    report.failures.push(MigrationFailure {
56                        path: marker.clone(),
57                        error: "migration marker has invalid contents or permissions".to_string(),
58                    });
59                    true
60                }
61                Err(error) => {
62                    report.failures.push(MigrationFailure {
63                        path: marker.clone(),
64                        error: format!("could not validate migration marker: {error}"),
65                    });
66                    true
67                }
68            },
69            Ok(_) => {
70                report.failures.push(MigrationFailure {
71                    path: marker.clone(),
72                    error: "migration marker is not a regular file".to_string(),
73                });
74                true
75            }
76            Err(error) if error.kind() == io::ErrorKind::NotFound => false,
77            Err(error) => {
78                report.failures.push(MigrationFailure {
79                    path: marker.clone(),
80                    error: format!("could not inspect migration marker: {error}"),
81                });
82                true
83            }
84        };
85
86        let legacy_root = self.paths.legacy_home_dir();
87        let legacy_root_is_safe = match fs::symlink_metadata(legacy_root) {
88            Ok(metadata) if metadata.file_type().is_symlink() => {
89                report.failures.push(MigrationFailure {
90                    path: legacy_root.to_path_buf(),
91                    error: "legacy root is a symlink; refusing to traverse it".to_string(),
92                });
93                false
94            }
95            Ok(metadata) if !metadata.is_dir() => {
96                report.failures.push(MigrationFailure {
97                    path: legacy_root.to_path_buf(),
98                    error: "legacy root is not a directory".to_string(),
99                });
100                false
101            }
102            Ok(_) => true,
103            Err(error) if error.kind() == io::ErrorKind::NotFound => true,
104            Err(error) => {
105                report.failures.push(MigrationFailure {
106                    path: legacy_root.to_path_buf(),
107                    error: format!("could not inspect legacy root: {error}"),
108                });
109                false
110            }
111        };
112
113        if legacy_root_is_safe {
114            let mappings = legacy_mappings(&self.paths);
115            for mapping in &mappings {
116                if mapping.source == mapping.destination {
117                    continue;
118                }
119                if mapping.skip {
120                    if fs::symlink_metadata(&mapping.source).is_ok() {
121                        report.skipped.push(MigrationSkip {
122                            path: mapping.source.clone(),
123                            reason: MigrationSkipReason::Excluded,
124                        });
125                    }
126                    continue;
127                }
128                if let Err(error) = copy_legacy_tree_with_exclusions(
129                    &mapping.source,
130                    &mapping.destination,
131                    &mut report,
132                    mapping.excluded_children,
133                ) {
134                    report.failures.push(MigrationFailure {
135                        path: mapping.source.clone(),
136                        error: error.to_string(),
137                    });
138                }
139            }
140            record_unmapped_entries(legacy_root, &mappings, &mut report);
141        }
142
143        if report.has_retryable_failures() || marker_blocked {
144            persist_report_best_effort(&self.paths, &report);
145            return Ok(report);
146        }
147
148        // Persist the complete scan report before publishing the completion
149        // marker. If diagnostics cannot be recorded, retry the migration
150        // rather than claiming a successful one-time migration.
151        if let Err(error) = persist_report(&self.paths, &report) {
152            report.failures.push(MigrationFailure {
153                path: self.paths.migration_report_path(),
154                error: error.to_string(),
155            });
156            persist_report_best_effort(&self.paths, &report);
157            return Ok(report);
158        }
159
160        if let Err(error) = write_private_atomic(&marker, b"legacy migration completed\n") {
161            if error
162                .downcast_ref::<io::Error>()
163                .is_some_and(|io_error| io_error.kind() == io::ErrorKind::AlreadyExists)
164            {
165                if valid_migration_marker(&marker).unwrap_or(false) {
166                    report.already_completed = true;
167                } else {
168                    report.failures.push(MigrationFailure {
169                        path: marker,
170                        error: "migration marker appeared but is invalid".to_string(),
171                    });
172                }
173                return Ok(report);
174            }
175            report
176                .failures
177                .push(MigrationFailure { path: marker, error: error.to_string() });
178            persist_report_best_effort(&self.paths, &report);
179            return Ok(report);
180        }
181        report.marker_written = true;
182        if let Err(error) = persist_report(&self.paths, &report) {
183            report.failures.push(MigrationFailure {
184                path: self.paths.migration_report_path(),
185                error: error.to_string(),
186            });
187        }
188        Ok(report)
189    }
190}
191
192/// Outcome of a legacy migration attempt.
193#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
194pub struct MigrationReport {
195    pub migrated: Vec<MigrationEntry>,
196    pub skipped: Vec<MigrationSkip>,
197    pub failures: Vec<MigrationFailure>,
198    pub marker_written: bool,
199    pub already_completed: bool,
200}
201
202impl MigrationReport {
203    /// Returns whether a later startup should retry the migration.
204    pub fn has_retryable_failures(&self) -> bool {
205        !self.failures.is_empty()
206    }
207}
208
209/// A source file copied by migration.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
211pub struct MigrationEntry {
212    pub source: PathBuf,
213    pub destination: PathBuf,
214}
215
216/// A legacy item that was deliberately left untouched.
217#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
218pub struct MigrationSkip {
219    pub path: PathBuf,
220    pub reason: MigrationSkipReason,
221}
222
223/// An individual migration failure; remaining entries are still scanned.
224#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
225pub struct MigrationFailure {
226    pub path: PathBuf,
227    pub error: String,
228}
229
230/// Reason a legacy item was not copied.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
232#[serde(rename_all = "snake_case")]
233pub enum MigrationSkipReason {
234    DestinationExists,
235    Symlink,
236    SpecialFile,
237    Excluded,
238    Unmapped,
239}
240
241struct LegacyMapping {
242    source: PathBuf,
243    destination: PathBuf,
244    skip: bool,
245    excluded_children: &'static [&'static str],
246}
247
248fn legacy_mappings(paths: &VtCodePaths) -> Vec<LegacyMapping> {
249    let legacy = paths.legacy_home_dir();
250    let mut mappings = Vec::with_capacity(50);
251    for name in [
252        "vtcode.toml",
253        "update.toml",
254        "config.toml",
255        "AGENTS.md",
256        "AGENTS.override.md",
257        "CLAUDE.md",
258        "commands",
259        "agents",
260        "rules",
261        "prompts",
262        "tool-policy.json",
263        "mcp.json",
264        "mcp.toml",
265        "mcp-config.json",
266        "mcp-config.toml",
267        "mcp",
268        "auth",
269        "output-styles",
270        "output_styles",
271        // Desktop GUI preferences. The desktop app also reads the legacy file
272        // directly (it may launch before the CLI runs this migration), but
273        // mapping it here keeps the report accurate and populates the
274        // canonical location for installs that start through the CLI.
275        "desktop",
276    ] {
277        add_mapping(&mut mappings, legacy, name, paths.config_dir().join(name));
278    }
279    add_mapping(&mut mappings, legacy, "auth.json", paths.auth_file());
280    for name in [
281        "plugins",
282        "skills",
283        "installed-skills",
284        "assets",
285        "durable-assets",
286        "tools",
287    ] {
288        add_mapping(&mut mappings, legacy, name, paths.data_dir().join(name));
289    }
290    add_mapping(&mut mappings, legacy, "bin", paths.executable_dir().to_path_buf());
291    for name in [
292        "projects",
293        "sessions",
294        "history",
295        "memory",
296        "agent-memory",
297        "audit",
298        "logs",
299        "scheduler",
300        "pods",
301        "checkpoints",
302        "backups",
303    ] {
304        add_mapping(&mut mappings, legacy, name, paths.state_dir().join(name));
305    }
306    // Before the centralized path policy, DotManager kept cache, logs,
307    // sessions, and backups directly below the configuration directory. On
308    // native platforms that directory is still the current config root, so
309    // those files are outside the legacy-home scan above and need explicit
310    // compatibility mappings.
311    for (name, destination) in [
312        ("cache", paths.cache_dir().to_path_buf()),
313        ("logs", paths.state_dir().join("logs")),
314        ("sessions", paths.state_dir().join("sessions")),
315        ("backups", paths.state_dir().join("backups")),
316    ] {
317        let source = paths.config_dir().join(name);
318        if source != legacy.join(name) {
319            mappings.push(LegacyMapping {
320                source,
321                destination,
322                skip: false,
323                excluded_children: &[],
324            });
325        }
326    }
327
328    for name in [
329        "model-cache",
330        "prompt-cache",
331        "approval-data",
332        "ast-grep",
333        "ast-grep.lock",
334        "web-fetch",
335        "large-output",
336    ] {
337        add_mapping(&mut mappings, legacy, name, paths.cache_dir().join(name));
338    }
339    // Keep the pre-XDG configuration root ahead of the legacy home cache when
340    // both layouts exist; it is the most recent location used by DotManager.
341    add_mapping(&mut mappings, legacy, "cache", paths.cache_dir().to_path_buf());
342    add_mapping(&mut mappings, legacy, ".cache", paths.cache_dir().to_path_buf());
343
344    mappings.push(LegacyMapping {
345        source: legacy.join("state"),
346        destination: paths.state_dir().to_path_buf(),
347        skip: false,
348        // Migration metadata is owned by this protocol. Copying a legacy
349        // marker could make an incomplete scan look completed.
350        excluded_children: &["migration"],
351    });
352    mappings.push(LegacyMapping {
353        source: legacy.join("tmp"),
354        destination: paths.runtime_dir().join("tmp"),
355        skip: true,
356        excluded_children: &[],
357    });
358    mappings
359}
360
361fn add_mapping(mappings: &mut Vec<LegacyMapping>, legacy: &Path, name: &str, destination: PathBuf) {
362    mappings.push(LegacyMapping {
363        source: legacy.join(name),
364        destination,
365        skip: false,
366        excluded_children: &[],
367    });
368}
369
370fn record_unmapped_entries(legacy_root: &Path, mappings: &[LegacyMapping], report: &mut MigrationReport) {
371    let entries = match fs::read_dir(legacy_root) {
372        Ok(entries) => entries,
373        Err(error) if error.kind() == io::ErrorKind::NotFound => return,
374        Err(error) => {
375            report.failures.push(MigrationFailure {
376                path: legacy_root.to_path_buf(),
377                error: format!("could not list legacy root: {error}"),
378            });
379            return;
380        }
381    };
382    for entry in entries {
383        let entry = match entry {
384            Ok(entry) => entry,
385            Err(error) => {
386                report.failures.push(MigrationFailure {
387                    path: legacy_root.to_path_buf(),
388                    error: format!("could not inspect legacy entry: {error}"),
389                });
390                continue;
391            }
392        };
393        if !mappings.iter().any(|mapping| mapping.source == entry.path()) {
394            report.skipped.push(MigrationSkip {
395                path: entry.path(),
396                reason: MigrationSkipReason::Unmapped,
397            });
398        }
399    }
400}
401
402fn copy_legacy_tree(source: &Path, destination: &Path, report: &mut MigrationReport) -> Result<()> {
403    copy_legacy_tree_with_exclusions(source, destination, report, &[])
404}
405
406fn copy_legacy_tree_with_exclusions(
407    source: &Path,
408    destination: &Path,
409    report: &mut MigrationReport,
410    excluded_children: &[&str],
411) -> Result<()> {
412    let metadata = match fs::symlink_metadata(source) {
413        Ok(metadata) => metadata,
414        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
415        Err(error) => return Err(error).with_context(|| format!("could not inspect legacy path {}", source.display())),
416    };
417    if metadata.file_type().is_symlink() {
418        report.skipped.push(MigrationSkip {
419            path: source.to_path_buf(),
420            reason: MigrationSkipReason::Symlink,
421        });
422        return Ok(());
423    }
424    if metadata.is_file() {
425        return copy_regular_file(source, destination, report);
426    }
427    if !metadata.is_dir() {
428        report.skipped.push(MigrationSkip {
429            path: source.to_path_buf(),
430            reason: MigrationSkipReason::SpecialFile,
431        });
432        return Ok(());
433    }
434    ensure_migration_dir(destination)?;
435    let entries =
436        fs::read_dir(source).with_context(|| format!("could not read legacy directory {}", source.display()))?;
437    for entry in entries {
438        let entry = match entry {
439            Ok(entry) => entry,
440            Err(error) => {
441                report.failures.push(MigrationFailure {
442                    path: source.to_path_buf(),
443                    error: format!("could not inspect legacy entry: {error}"),
444                });
445                continue;
446            }
447        };
448        let child_source = entry.path();
449        let child_destination = destination.join(entry.file_name());
450        if excluded_children.iter().any(|name| entry.file_name() == OsStr::new(name)) {
451            report.skipped.push(MigrationSkip {
452                path: child_source,
453                reason: MigrationSkipReason::Excluded,
454            });
455            continue;
456        }
457        if let Err(error) = copy_legacy_tree(&child_source, &child_destination, report) {
458            report
459                .failures
460                .push(MigrationFailure { path: child_source, error: error.to_string() });
461        }
462    }
463    Ok(())
464}
465
466fn copy_regular_file(source: &Path, destination: &Path, report: &mut MigrationReport) -> Result<()> {
467    if let Ok(metadata) = fs::symlink_metadata(destination) {
468        report.skipped.push(MigrationSkip {
469            path: source.to_path_buf(),
470            reason: if metadata.file_type().is_symlink() {
471                MigrationSkipReason::Symlink
472            } else {
473                MigrationSkipReason::DestinationExists
474            },
475        });
476        return Ok(());
477    }
478    let parent = destination
479        .parent()
480        .ok_or_else(|| anyhow!("migration destination {} has no parent", destination.display()))?;
481    ensure_migration_dir(parent)?;
482    let (temporary, mut output) = unique_private_file(parent, destination.file_name().unwrap_or(OsStr::new("file")))?;
483    let mut input =
484        open_no_follow(source).with_context(|| format!("could not safely open legacy file {}", source.display()))?;
485    let result: Result<()> = (|| {
486        let _bytes_copied = io::copy(&mut input, &mut output)?;
487        output.sync_all()?;
488        drop(output);
489        match fs::hard_link(&temporary, destination) {
490            Ok(()) => {
491                fs::remove_file(&temporary)?;
492                report.migrated.push(MigrationEntry {
493                    source: source.to_path_buf(),
494                    destination: destination.to_path_buf(),
495                });
496                Ok(())
497            }
498            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
499                report.skipped.push(MigrationSkip {
500                    path: source.to_path_buf(),
501                    reason: MigrationSkipReason::DestinationExists,
502                });
503                Ok(())
504            }
505            Err(error) => Err(error).with_context(|| format!("could not atomically publish {}", destination.display())),
506        }
507    })();
508    if result.is_err() {
509        remove_temporary_file(&temporary);
510    }
511    result
512}
513
514fn persist_report(paths: &VtCodePaths, report: &MigrationReport) -> Result<()> {
515    let serialized = serde_json::to_vec_pretty(report).context("could not serialize legacy migration report")?;
516    VtCodePaths::write_private_file_atomic(paths.migration_report_path(), &serialized)
517        .with_context(|| format!("could not write migration report {}", paths.migration_report_path().display()))
518}
519
520fn persist_report_best_effort(paths: &VtCodePaths, report: &MigrationReport) {
521    if let Err(error) = persist_report(paths, report) {
522        tracing::debug!(error = %error, "could not persist legacy migration report");
523    }
524}
525
526fn write_private_atomic(destination: &Path, contents: &[u8]) -> Result<()> {
527    let parent = destination
528        .parent()
529        .ok_or_else(|| anyhow!("private file {} has no parent", destination.display()))?;
530    ensure_private_dir(parent)?;
531    let (temporary, mut file) = unique_private_file(parent, destination.file_name().unwrap_or(OsStr::new("file")))?;
532    let result: io::Result<()> = (|| {
533        file.write_all(contents)?;
534        file.sync_all()?;
535        drop(file);
536        fs::hard_link(&temporary, destination)?;
537        fs::remove_file(&temporary)?;
538        Ok(())
539    })();
540    if result.is_err() {
541        remove_temporary_file(&temporary);
542    }
543    result.with_context(|| format!("could not publish {}", destination.display()))
544}
545
546fn valid_migration_marker(path: &Path) -> io::Result<bool> {
547    let metadata = fs::symlink_metadata(path)?;
548    if !metadata.is_file() || metadata.file_type().is_symlink() {
549        return Ok(false);
550    }
551    #[cfg(unix)]
552    {
553        use std::os::unix::fs::PermissionsExt;
554        if metadata.permissions().mode() & 0o077 != 0 {
555            return Ok(false);
556        }
557    }
558    let mut file = open_no_follow(path)?;
559    let mut contents = Vec::new();
560    let _bytes_read = file.read_to_end(&mut contents)?;
561    Ok(contents == b"legacy migration completed\n")
562}
563
564fn unique_private_file(parent: &Path, stem: &OsStr) -> Result<(PathBuf, File)> {
565    let timestamp = SystemTime::now()
566        .duration_since(UNIX_EPOCH)
567        .map(|duration| duration.as_nanos())
568        .unwrap_or_default();
569    let stem = stem.to_string_lossy();
570    for attempt in 0..32u8 {
571        let temporary = parent.join(format!(".{stem}.{}.{}.{}.migration", std::process::id(), timestamp, attempt));
572        match create_private_new_file(&temporary) {
573            Ok(file) => return Ok((temporary, file)),
574            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
575            Err(error) => return Err(error).with_context(|| format!("could not create {}", temporary.display())),
576        }
577    }
578    bail!("could not allocate a unique migration temporary file in {}", parent.display())
579}
580
581fn remove_temporary_file(path: &Path) {
582    if let Err(error) = fs::remove_file(path)
583        && error.kind() != io::ErrorKind::NotFound
584    {
585        tracing::debug!(path = %path.display(), %error, "failed to remove temporary migration file");
586    }
587}