securegit 0.8.5

Zero-trust git replacement with 12 built-in security scanners, LLM redteam bridge, universal undo, durable backups, and a 50-tool MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use crate::ops::utils::short_oid;
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;

// ── Types ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BackupConfig {
    pub destinations: Vec<BackupDestination>,
    #[serde(default)]
    pub retention: RetentionConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupDestination {
    pub name: String,
    pub backend: BackendType,
    pub destination: String,
    #[serde(default)]
    pub auto_backup: bool,
    pub last_backup: Option<String>,
    pub last_sha: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BackendType {
    Local,
    Rsync,
    Rclone,
}

impl fmt::Display for BackendType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Local => write!(f, "local"),
            Self::Rsync => write!(f, "rsync"),
            Self::Rclone => write!(f, "rclone"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetentionConfig {
    pub max_backups: usize,
    pub max_age_days: u32,
}

impl Default for RetentionConfig {
    fn default() -> Self {
        Self {
            max_backups: 10,
            max_age_days: 90,
        }
    }
}

pub struct BundleInfo {
    pub objects: usize,
    pub size_bytes: u64,
    pub path: PathBuf,
}

// ── Config persistence ─────────────────────────────────────────────────

fn config_path(repo_path: &Path) -> Result<PathBuf> {
    let repo = git2::Repository::discover(repo_path).context("Not a git repository")?;
    let git_dir = repo.path().to_path_buf();
    Ok(git_dir.join("securegit").join("backup.json"))
}

pub fn load_config(repo_path: &Path) -> Result<BackupConfig> {
    let path = config_path(repo_path)?;
    if !path.exists() {
        return Ok(BackupConfig::default());
    }
    let data = std::fs::read_to_string(&path).context("Failed to read backup config")?;
    serde_json::from_str(&data).context("Failed to parse backup config")
}

pub fn save_config(repo_path: &Path, config: &BackupConfig) -> Result<()> {
    let path = config_path(repo_path)?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let data = serde_json::to_string_pretty(config)?;
    std::fs::write(&path, data).context("Failed to write backup config")
}

// ── Backend detection ──────────────────────────────────────────────────

pub fn detect_backend(dest: &str) -> BackendType {
    // user@host:/path → rsync
    if dest.contains('@') && dest.contains(':') {
        return BackendType::Rsync;
    }
    // remote:bucket/path → rclone (colon but no @ before it, not a windows drive letter)
    if let Some(colon_pos) = dest.find(':') {
        let before = &dest[..colon_pos];
        // Not a Windows drive letter (single char) and not a slash-containing path
        if before.len() > 1 && !before.contains('/') && !before.contains('\\') {
            return BackendType::Rclone;
        }
    }
    BackendType::Local
}

// ── Destination management ─────────────────────────────────────────────

pub fn add_destination(
    repo_path: &Path,
    name: &str,
    dest: &str,
    type_hint: Option<&str>,
    auto: bool,
) -> Result<()> {
    let mut config = load_config(repo_path)?;

    if config.destinations.iter().any(|d| d.name == name) {
        bail!(
            "Backup destination '{}' already exists. Remove it first.",
            name
        );
    }

    let backend = match type_hint {
        Some("local") => BackendType::Local,
        Some("rsync") => BackendType::Rsync,
        Some("rclone") => BackendType::Rclone,
        Some(other) => bail!(
            "Unknown backend type '{}'. Use: local, rsync, rclone",
            other
        ),
        None => detect_backend(dest),
    };

    // Check tool availability
    check_tool_available(backend)?;

    config.destinations.push(BackupDestination {
        name: name.to_string(),
        backend,
        destination: dest.to_string(),
        auto_backup: auto,
        last_backup: None,
        last_sha: None,
    });

    save_config(repo_path, &config)
}

pub fn remove_destination(repo_path: &Path, name: &str) -> Result<()> {
    let mut config = load_config(repo_path)?;
    let before = config.destinations.len();
    config.destinations.retain(|d| d.name != name);
    if config.destinations.len() == before {
        bail!("No backup destination named '{}'", name);
    }
    save_config(repo_path, &config)
}

// ── Bundle creation ────────────────────────────────────────────────────

pub fn create_bundle(repo_path: &Path, all_branches: bool) -> Result<BundleInfo> {
    let repo = git2::Repository::discover(repo_path)?;
    let workdir = repo.workdir().unwrap_or(repo_path);

    let repo_name = workdir
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "repo".to_string());

    let head = repo.head().context("No HEAD — is the repo empty?")?;
    let commit = head.peel_to_commit()?;
    let short_sha = short_oid(&commit.id());
    let branch = head.shorthand().unwrap_or("HEAD");
    let timestamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");

    let filename = format!(
        "{}-{}-{}-{}.bundle",
        repo_name, branch, short_sha, timestamp
    );
    let tmp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
    let bundle_path = tmp_dir.keep().join(&filename);

    let mut cmd = Command::new("git");
    cmd.arg("bundle").arg("create").arg(&bundle_path);

    if all_branches {
        cmd.arg("--all");
    } else {
        cmd.arg("HEAD");
        cmd.arg(format!("refs/heads/{}", branch));
        // Also include tags
        cmd.arg("--tags");
    }

    cmd.current_dir(workdir);

    let output = cmd.output().context("Failed to run git bundle create")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git bundle create failed: {}", stderr.trim());
    }

    let meta = std::fs::metadata(&bundle_path)?;

    Ok(BundleInfo {
        objects: 0, // git bundle doesn't report this easily
        size_bytes: meta.len(),
        path: bundle_path,
    })
}

// ── Upload to destination ──────────────────────────────────────────────

pub fn push_to_destination(dest: &BackupDestination, bundle: &Path) -> Result<()> {
    check_tool_available(dest.backend)?;

    match dest.backend {
        BackendType::Local => {
            let dest_dir = Path::new(&dest.destination);
            std::fs::create_dir_all(dest_dir).context("Failed to create local backup directory")?;
            let target = dest_dir.join(
                bundle
                    .file_name()
                    .ok_or_else(|| anyhow::anyhow!("Invalid bundle path"))?,
            );
            std::fs::copy(bundle, &target).context("Failed to copy bundle to local destination")?;
        }
        BackendType::Rsync => {
            let status = Command::new("rsync")
                .args(["-az", "--progress"])
                .arg(bundle)
                .arg(&dest.destination)
                .status()
                .context("Failed to run rsync")?;
            if !status.success() {
                bail!(
                    "rsync failed with exit code {}",
                    status.code().unwrap_or(-1)
                );
            }
        }
        BackendType::Rclone => {
            let bundle_dir = bundle
                .parent()
                .ok_or_else(|| anyhow::anyhow!("Invalid bundle path"))?;
            let bundle_name = bundle
                .file_name()
                .ok_or_else(|| anyhow::anyhow!("Invalid bundle path"))?
                .to_string_lossy();
            let status = Command::new("rclone")
                .args(["copy", "--progress"])
                .arg(format!("{}/{}", bundle_dir.display(), bundle_name))
                .arg(&dest.destination)
                .status()
                .context("Failed to run rclone")?;
            if !status.success() {
                bail!(
                    "rclone failed with exit code {}",
                    status.code().unwrap_or(-1)
                );
            }
        }
    }
    Ok(())
}

// ── Verify bundle ──────────────────────────────────────────────────────

pub fn verify_bundle(bundle_path: &Path) -> Result<String> {
    if !bundle_path.exists() {
        bail!("Bundle file not found: {}", bundle_path.display());
    }

    let output = Command::new("git")
        .args(["bundle", "verify"])
        .arg(bundle_path)
        .output()
        .context("Failed to run git bundle verify")?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if !output.status.success() {
        bail!("Bundle verification failed:\n{}{}", stdout, stderr);
    }

    // Combine stdout and stderr (git bundle verify outputs to stderr)
    Ok(format!("{}{}", stdout, stderr))
}

// ── Restore from bundle ────────────────────────────────────────────────

pub fn restore_from_bundle(source: &str, output: Option<&Path>) -> Result<PathBuf> {
    let local_bundle = if source.contains('@') && source.contains(':') {
        // rsync source — download first
        check_tool_available(BackendType::Rsync)?;
        let tmp = tempfile::tempdir()?;
        let local = tmp.keep().join("restore.bundle");
        let status = Command::new("rsync")
            .args(["-az"])
            .arg(source)
            .arg(&local)
            .status()
            .context("Failed to download bundle via rsync")?;
        if !status.success() {
            bail!("rsync download failed");
        }
        local
    } else if detect_backend(source) == BackendType::Rclone {
        // rclone source — download first
        check_tool_available(BackendType::Rclone)?;
        let tmp = tempfile::tempdir()?;
        let tmp_path = tmp.keep();
        let status = Command::new("rclone")
            .args(["copy"])
            .arg(source)
            .arg(&tmp_path)
            .status()
            .context("Failed to download bundle via rclone")?;
        if !status.success() {
            bail!("rclone download failed");
        }
        // Find the downloaded file
        let entry = std::fs::read_dir(&tmp_path)?
            .filter_map(|e| e.ok())
            .next()
            .ok_or_else(|| anyhow::anyhow!("rclone downloaded nothing"))?;
        entry.path()
    } else {
        PathBuf::from(source)
    };

    if !local_bundle.exists() {
        bail!("Bundle file not found: {}", local_bundle.display());
    }

    // Determine output directory
    let out_dir = if let Some(p) = output {
        p.to_path_buf()
    } else {
        // Derive from bundle filename
        let stem = local_bundle
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| "restored".to_string());
        PathBuf::from(&stem)
    };

    let status = Command::new("git")
        .args(["clone"])
        .arg(&local_bundle)
        .arg(&out_dir)
        .status()
        .context("Failed to clone from bundle")?;

    if !status.success() {
        bail!("git clone from bundle failed");
    }

    Ok(out_dir)
}

// ── Auto-backup trigger ────────────────────────────────────────────────

pub fn trigger_auto_backup(repo_path: &Path) {
    let config = match load_config(repo_path) {
        Ok(c) => c,
        Err(_) => return,
    };

    let auto_dests: Vec<_> = config
        .destinations
        .iter()
        .filter(|d| d.auto_backup)
        .collect();
    if auto_dests.is_empty() {
        return;
    }

    let bundle = match create_bundle(repo_path, false) {
        Ok(b) => b,
        Err(e) => {
            tracing::warn!("Auto-backup: failed to create bundle: {}", e);
            return;
        }
    };

    for dest in auto_dests {
        match push_to_destination(dest, &bundle.path) {
            Ok(()) => {
                tracing::info!("Auto-backup: pushed to '{}' ({})", dest.name, dest.backend);
            }
            Err(e) => {
                tracing::warn!("Auto-backup: failed to push to '{}': {}", dest.name, e);
            }
        }
    }

    // Update last_backup timestamps
    if let Ok(mut config) = load_config(repo_path) {
        let now = chrono::Utc::now().to_rfc3339();
        let sha = git2::Repository::discover(repo_path).ok().and_then(|r| {
            let head = r.head().ok()?;
            let commit = head.peel_to_commit().ok()?;
            Some(commit.id().to_string())
        });

        for dest in &mut config.destinations {
            if dest.auto_backup {
                dest.last_backup = Some(now.clone());
                dest.last_sha = sha.clone();
            }
        }
        let _ = save_config(repo_path, &config);
    }

    // Clean up temp bundle
    let _ = std::fs::remove_file(&bundle.path);
    if let Some(parent) = bundle.path.parent() {
        let _ = std::fs::remove_dir(parent);
    }
}

// ── Tool availability ──────────────────────────────────────────────────

fn check_tool_available(backend: BackendType) -> Result<()> {
    let tool = match backend {
        BackendType::Local => return Ok(()),
        BackendType::Rsync => "rsync",
        BackendType::Rclone => "rclone",
    };

    if which::which(tool).is_err() {
        let install_hint = match (tool, std::env::consts::OS) {
            ("rsync", "linux") => "sudo dnf install rsync  (or: sudo apt install rsync)",
            ("rsync", "macos") => "brew install rsync",
            ("rclone", "linux") => {
                "sudo dnf install rclone  (or: curl https://rclone.org/install.sh | sudo bash)"
            }
            ("rclone", "macos") => "brew install rclone",
            _ => "See installation docs for your platform",
        };
        bail!(
            "{} is not installed. Install it with:\n  {}",
            tool,
            install_hint
        );
    }
    Ok(())
}

// ── Helpers ────────────────────────────────────────────────────────────

pub fn format_size(bytes: u64) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{} B", bytes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── detect_backend tests ────────────────────────────────────────

    #[test]
    fn test_detect_backend_local() {
        assert_eq!(detect_backend("/tmp/backups"), BackendType::Local);
        assert_eq!(detect_backend("/home/user/backup-dir"), BackendType::Local);
        assert_eq!(detect_backend("./relative/path"), BackendType::Local);
        assert_eq!(detect_backend("backups"), BackendType::Local);
    }

    #[test]
    fn test_detect_backend_rsync() {
        assert_eq!(
            detect_backend("user@host:/path/to/backup"),
            BackendType::Rsync
        );
        assert_eq!(
            detect_backend("deploy@192.168.1.1:/backups"),
            BackendType::Rsync
        );
        assert_eq!(
            detect_backend("root@server.example.com:/var/backups"),
            BackendType::Rsync
        );
    }

    #[test]
    fn test_detect_backend_rclone() {
        assert_eq!(detect_backend("remote:bucket/"), BackendType::Rclone);
        assert_eq!(detect_backend("s3:my-bucket/backups"), BackendType::Rclone);
        assert_eq!(
            detect_backend("gdrive:securegit-backups"),
            BackendType::Rclone
        );
    }

    #[test]
    fn test_detect_backend_windows_drive() {
        // Single-letter prefix before colon = Windows drive letter -> Local
        assert_eq!(detect_backend("C:\\Users\\backup"), BackendType::Local);
        assert_eq!(detect_backend("D:\\backups"), BackendType::Local);
    }

    // ── BackupConfig default tests ──────────────────────────────────

    #[test]
    fn test_backup_config_default() {
        let config = BackupConfig::default();
        assert!(config.destinations.is_empty());
        assert_eq!(config.retention.max_backups, 10);
        assert_eq!(config.retention.max_age_days, 90);
    }

    #[test]
    fn test_retention_config_default() {
        let retention = RetentionConfig::default();
        assert_eq!(retention.max_backups, 10);
        assert_eq!(retention.max_age_days, 90);
    }

    // ── add / remove destination (with tempdir + git init) ──────────

    fn create_test_repo() -> (tempfile::TempDir, PathBuf) {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        let repo_path = tmpdir.path().to_path_buf();
        git2::Repository::init(&repo_path).expect("git init");
        (tmpdir, repo_path)
    }

    #[test]
    fn test_add_remove_destination() {
        let (_tmpdir, repo_path) = create_test_repo();

        // Add a local destination
        add_destination(&repo_path, "local-backup", "/tmp/test-backup", None, false)
            .expect("add destination should succeed");

        // Verify it was added
        let config = load_config(&repo_path).expect("load config");
        assert_eq!(config.destinations.len(), 1);
        assert_eq!(config.destinations[0].name, "local-backup");
        assert_eq!(config.destinations[0].backend, BackendType::Local);
        assert_eq!(config.destinations[0].destination, "/tmp/test-backup");
        assert!(!config.destinations[0].auto_backup);

        // Remove it
        remove_destination(&repo_path, "local-backup").expect("remove destination should succeed");

        // Verify it was removed
        let config = load_config(&repo_path).expect("load config");
        assert!(config.destinations.is_empty());
    }

    #[test]
    fn test_add_duplicate_fails() {
        let (_tmpdir, repo_path) = create_test_repo();

        add_destination(&repo_path, "dup-name", "/tmp/backup1", None, false)
            .expect("first add should succeed");

        let result = add_destination(&repo_path, "dup-name", "/tmp/backup2", None, false);
        assert!(result.is_err(), "Adding duplicate name should fail");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("already exists"),
            "Error should mention 'already exists', got: {}",
            err_msg
        );
    }

    #[test]
    fn test_remove_nonexistent_fails() {
        let (_tmpdir, repo_path) = create_test_repo();

        let result = remove_destination(&repo_path, "does-not-exist");
        assert!(
            result.is_err(),
            "Removing nonexistent destination should fail"
        );
    }

    #[test]
    fn test_add_destination_with_auto() {
        let (_tmpdir, repo_path) = create_test_repo();

        add_destination(&repo_path, "auto-backup", "/tmp/auto", None, true)
            .expect("add with auto should succeed");

        let config = load_config(&repo_path).expect("load config");
        assert!(config.destinations[0].auto_backup);
    }

    #[test]
    fn test_add_destination_with_type_hint() {
        let (_tmpdir, repo_path) = create_test_repo();

        // Force local type even though destination looks like rclone
        add_destination(
            &repo_path,
            "forced-local",
            "remote:bucket",
            Some("local"),
            false,
        )
        .expect("add with type hint should succeed");

        let config = load_config(&repo_path).expect("load config");
        assert_eq!(config.destinations[0].backend, BackendType::Local);
    }

    #[test]
    fn test_add_destination_invalid_type_hint() {
        let (_tmpdir, repo_path) = create_test_repo();

        let result = add_destination(&repo_path, "bad-type", "/tmp/x", Some("ftp"), false);
        assert!(result.is_err(), "Invalid type hint should fail");
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Unknown backend type"));
    }

    // ── format_size tests ───────────────────────────────────────────

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(0), "0 B");
        assert_eq!(format_size(1), "1 B");
        assert_eq!(format_size(512), "512 B");
        assert_eq!(format_size(1023), "1023 B");
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
        assert_eq!(format_size(10240), "10.0 KB");
        assert_eq!(format_size(1_048_576), "1.0 MB");
        assert_eq!(format_size(1_572_864), "1.5 MB");
        assert_eq!(format_size(10_485_760), "10.0 MB");
        assert_eq!(format_size(1_073_741_824), "1024.0 MB");
    }

    // ── verify_bundle tests ─────────────────────────────────────────

    #[test]
    fn test_verify_bundle_nonexistent() {
        let result = verify_bundle(Path::new("/tmp/nonexistent-bundle-12345.bundle"));
        assert!(result.is_err(), "Verifying nonexistent bundle should fail");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not found"),
            "Error should mention file not found, got: {}",
            err_msg
        );
    }

    // ── Config serialization roundtrip ──────────────────────────────

    #[test]
    fn test_config_save_load_roundtrip() {
        let (_tmpdir, repo_path) = create_test_repo();

        let config = BackupConfig {
            destinations: vec![
                BackupDestination {
                    name: "nas".to_string(),
                    backend: BackendType::Local,
                    destination: "/mnt/nas/backups".to_string(),
                    auto_backup: true,
                    last_backup: Some("2026-01-01T00:00:00Z".to_string()),
                    last_sha: Some("abc1234".to_string()),
                },
                BackupDestination {
                    name: "s3".to_string(),
                    backend: BackendType::Rclone,
                    destination: "s3:my-bucket/backups".to_string(),
                    auto_backup: false,
                    last_backup: None,
                    last_sha: None,
                },
            ],
            retention: RetentionConfig {
                max_backups: 5,
                max_age_days: 30,
            },
        };

        save_config(&repo_path, &config).expect("save config");
        let loaded = load_config(&repo_path).expect("load config");

        assert_eq!(loaded.destinations.len(), 2);
        assert_eq!(loaded.destinations[0].name, "nas");
        assert_eq!(loaded.destinations[0].backend, BackendType::Local);
        assert!(loaded.destinations[0].auto_backup);
        assert_eq!(loaded.destinations[1].name, "s3");
        assert_eq!(loaded.destinations[1].backend, BackendType::Rclone);
        assert_eq!(loaded.retention.max_backups, 5);
        assert_eq!(loaded.retention.max_age_days, 30);
    }

    #[test]
    fn test_load_config_no_file_returns_default() {
        let (_tmpdir, repo_path) = create_test_repo();
        let config = load_config(&repo_path).expect("load config from empty repo");
        assert!(config.destinations.is_empty());
    }

    // ── BackendType Display ─────────────────────────────────────────

    #[test]
    fn test_backend_type_display() {
        assert_eq!(format!("{}", BackendType::Local), "local");
        assert_eq!(format!("{}", BackendType::Rsync), "rsync");
        assert_eq!(format!("{}", BackendType::Rclone), "rclone");
    }
}