vetto 0.2.19

Daemon-less sandbox + security layer for AI coding agents (Landlock/Seatbelt, TUI statusline, post-session audit reports)
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! Self-upgrade command (`vetto upgrade`) with automatic installation method detection.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::checker::check_version;
use super::config::load_user_config;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InstallMethod {
    Npm,
    Cargo,
    Homebrew,
    Binary,
}

impl InstallMethod {
    pub fn label(&self) -> &'static str {
        match self {
            Self::Npm => "npm",
            Self::Cargo => "cargo",
            Self::Homebrew => "homebrew",
            Self::Binary => "binary",
        }
    }
}

fn detect_from_path(p: &Path) -> InstallMethod {
    let path_str = p.to_string_lossy().to_lowercase();

    if path_str.contains("node_modules")
        || path_str.contains(".nvm")
        || path_str.contains("npm")
        || path_str.ends_with(".js")
    {
        InstallMethod::Npm
    } else if path_str.contains("homebrew")
        || path_str.contains("cellar")
        || path_str.contains("/opt/homebrew")
        || path_str.contains(".linuxbrew")
    {
        InstallMethod::Homebrew
    } else if path_str.contains(".cargo")
        || path_str.contains("/target/")
        || path_str.contains("\\target\\")
    {
        InstallMethod::Cargo
    } else {
        InstallMethod::Binary
    }
}

/// Detects how vetto was installed by inspecting its binary executable path.
pub fn detect_install_method(exe_path: &Path) -> InstallMethod {
    if let Ok(canon) = exe_path.canonicalize() {
        let m = detect_from_path(&canon);
        if m != InstallMethod::Binary {
            return m;
        }
    }
    detect_from_path(exe_path)
}

/// Displays clean changelog diff and release highlights.
fn display_changelog_diff(current_version: &str, latest_version: &str) {
    println!();
    println!("Release highlights for v{latest_version}:");
    println!("  • Automated self-updating via `vetto upgrade` across distribution channels (npm, cargo, brew, binary)");
    println!(
        "  • Non-blocking update notification banner cached in ~/.vetto/cache/update-check.json"
    );
    println!("  • Dedicated session audit inspector (`vetto audit [session_id]`) for Landlock, network & syscalls");
    println!("  • Full changelog: https://github.com/shleder/vetto/compare/v{current_version}...v{latest_version}");
    println!();
}

/// Executes the upgrade workflow.
pub fn run_upgrade(channel_opt: Option<&str>, check_only: bool, dry_run: bool) -> Result<()> {
    let user_config = load_user_config().unwrap_or_default();
    let channel = channel_opt.unwrap_or(user_config.channel.as_str()).trim();

    let current_version = env!("CARGO_PKG_VERSION");
    let exe_path = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("vetto"));
    let method = detect_install_method(&exe_path);

    println!("vetto upgrade: checking updates on channel '{channel}'...");
    println!(
        "current version: v{current_version} (installed via {})",
        method.label()
    );

    let notice = check_version(current_version, channel, true);

    match notice {
        Some(update) => {
            println!(
                "Update available: v{} → v{} (channel: {})",
                update.current_version, update.latest_version, update.channel
            );

            display_changelog_diff(&update.current_version, &update.latest_version);

            if check_only {
                println!("Run 'vetto upgrade' to perform the upgrade.");
                return Ok(());
            }

            match update.install_method {
                InstallMethod::Npm => {
                    let pkg_target = if channel == "stable" {
                        "@shledery/vetto@latest".to_string()
                    } else {
                        format!("@shledery/vetto@{channel}")
                    };

                    let cmd_str = format!("npm install -g {pkg_target}");
                    if dry_run {
                        println!("[dry-run] Would execute: {cmd_str}");
                        return Ok(());
                    }

                    println!("Executing: {cmd_str}");
                    let status = Command::new("npm")
                        .args(["install", "-g", &pkg_target])
                        .status()
                        .context("failed to invoke npm; ensure npm is available in PATH")?;

                    if status.success() {
                        println!(
                            "Successfully upgraded vetto to v{} via npm.",
                            update.latest_version
                        );
                        Ok(())
                    } else {
                        bail!("npm upgrade command failed with status {status}");
                    }
                }
                InstallMethod::Cargo => {
                    let cmd_str = if channel != "stable" {
                        format!("cargo install vetto --version {}", update.latest_version)
                    } else {
                        "cargo install vetto --locked".to_string()
                    };

                    if dry_run {
                        println!("[dry-run] Would execute: {cmd_str}");
                        return Ok(());
                    }

                    println!("Executing: {cmd_str}");
                    let mut cmd = Command::new("cargo");
                    cmd.arg("install").arg("vetto");
                    if channel != "stable" {
                        cmd.arg("--version").arg(&update.latest_version);
                    } else {
                        cmd.arg("--locked");
                    }

                    let status = cmd
                        .status()
                        .context("failed to invoke cargo; ensure cargo is in PATH")?;
                    if status.success() {
                        println!(
                            "Successfully upgraded vetto to v{} via cargo.",
                            update.latest_version
                        );
                        Ok(())
                    } else {
                        bail!("cargo install failed with status {status}");
                    }
                }
                InstallMethod::Homebrew => {
                    let cmd_str = "brew upgrade vetto".to_string();
                    if dry_run {
                        println!("[dry-run] Would execute: {cmd_str}");
                        return Ok(());
                    }

                    println!("Executing: {cmd_str}");
                    let status = Command::new("brew")
                        .args(["upgrade", "vetto"])
                        .status()
                        .context("failed to invoke brew; ensure brew is in PATH")?;

                    if status.success() {
                        println!(
                            "Successfully upgraded vetto to v{} via Homebrew.",
                            update.latest_version
                        );
                        Ok(())
                    } else {
                        bail!("brew upgrade failed with status {status}");
                    }
                }
                InstallMethod::Binary => {
                    let (target, ext) = match (std::env::consts::OS, std::env::consts::ARCH) {
                        ("macos", "aarch64") => ("macos-aarch64", "tar.gz"),
                        ("macos", "x86_64") => ("macos-x86_64", "tar.gz"),
                        ("linux", "aarch64") => ("linux-aarch64", "tar.gz"),
                        ("linux", "x86_64") => ("linux-x86_64", "tar.gz"),
                        ("windows", "x86_64") => ("windows-x86_64", "zip"),
                        (os, arch) => {
                            println!(
                                "vetto was installed as a direct binary ({})\n\
                                 Automatic download not supported for {os}-{arch}.\n\
                                 Please download release v{} from:\n\
                                 https://github.com/shleder/vetto/releases/tag/v{}",
                                exe_path.display(),
                                update.latest_version,
                                update.latest_version
                            );
                            return Ok(());
                        }
                    };

                    let archive_url = format!(
                        "https://github.com/shleder/vetto/releases/download/v{}/vetto-{target}.{ext}",
                        update.latest_version
                    );

                    if dry_run {
                        println!(
                            "[dry-run] Would download binary from {archive_url} and atomically replace {}",
                            exe_path.display()
                        );
                        return Ok(());
                    }

                    println!("Downloading binary release from: {archive_url}");
                    perform_atomic_binary_upgrade(&exe_path, &archive_url, ext)?;
                    println!(
                        "Successfully upgraded vetto binary to v{}.",
                        update.latest_version
                    );
                    Ok(())
                }
            }
        }
        None => {
            println!("vetto is already up to date (v{current_version}).");
            Ok(())
        }
    }
}

/// Downloads a release archive and fails closed unless its .sha256 sidecar
/// verifies. Shared by interactive upgrades and background staging.
fn download_and_verify_archive(
    archive_url: &str,
    ext: &str,
    staging_dir: &Path,
) -> Result<PathBuf> {
    let archive_path = staging_dir.join(format!("vetto_download.{ext}"));
    let status = Command::new("curl")
        .args([
            "-fsSL",
            "-A",
            "vetto-updater",
            "-o",
            archive_path.to_str().unwrap_or("vetto_download"),
            archive_url,
        ])
        .status()
        .context("failed to download release binary via curl")?;

    if !status.success() {
        bail!("download failed with status {status}");
    }

    verify_archive_sha256(&archive_path, &format!("{archive_url}.sha256"), staging_dir)?;
    Ok(archive_path)
}

/// Root for staged background updates: ~/.vetto/updates/<version>/.
pub fn staged_update_dir(version: &str) -> Option<PathBuf> {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)?;
    Some(home.join(".vetto").join("updates").join(version))
}

const STAGED_READY_MARKER: &str = "READY";

/// Removes staged updates other than `keep_version` (only dirs carrying our
/// marker are touched — never user data).
fn prune_staged_updates(updates_root: &Path, keep_version: &str) {
    let entries = match std::fs::read_dir(updates_root) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let keep = path
            .file_name()
            .map(|n| n.to_string_lossy() == keep_version)
            .unwrap_or(false);
        if !keep && path.join(STAGED_READY_MARKER).is_file() {
            let _ = std::fs::remove_dir_all(&path);
        }
    }
}

/// Downloads and verifies a release into the staged dir (idempotent: a
/// version already staged is returned as-is). Applied on a later startup,
/// never mid-session.
pub fn stage_update(version: &str, archive_url: &str, ext: &str) -> Result<PathBuf> {
    let dir = staged_update_dir(version).context("resolve staged update dir")?;
    if dir.join(STAGED_READY_MARKER).is_file() {
        return Ok(dir);
    }
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("create staged update dir {}", dir.display()))?;
    let archive = download_and_verify_archive(archive_url, ext, &dir)?;
    // Marker carries the verified hash so apply-time re-checks close the
    // TOCTOU window between staging (T1) and application (T2).
    let digest = sha256_file(&archive)?;
    std::fs::write(
        dir.join(STAGED_READY_MARKER),
        format!("{digest}\n{}", archive.display()),
    )
    .with_context(|| format!("write staged marker in {}", dir.display()))?;
    if let Some(root) = dir.parent() {
        prune_staged_updates(root, version);
    }
    Ok(dir)
}

/// Archive URL + extension for a direct-binary release, if this OS/arch
/// combination is published. Shared by interactive upgrades and staging.
pub fn binary_archive_url(version: &str) -> Option<(String, &'static str)> {
    let (target, ext) = match (std::env::consts::OS, std::env::consts::ARCH) {
        ("macos", "aarch64") => ("macos-aarch64", "tar.gz"),
        ("macos", "x86_64") => ("macos-x86_64", "tar.gz"),
        ("linux", "aarch64") => ("linux-aarch64", "tar.gz"),
        ("linux", "x86_64") => ("linux-x86_64", "tar.gz"),
        ("windows", "x86_64") => ("windows-x86_64", "zip"),
        _ => return None,
    };
    Some((
        format!(
            "https://github.com/shleder/vetto/releases/download/v{version}/vetto-{target}.{ext}"
        ),
        ext,
    ))
}

/// Newest staged version dir carrying a READY marker, if any.
fn newest_staged_update() -> Option<(String, PathBuf)> {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)?;
    let root = home.join(".vetto").join("updates");
    let entries = std::fs::read_dir(&root).ok()?;
    let mut best: Option<(super::parser::SemVer, String, PathBuf)> = None;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() || !path.join(STAGED_READY_MARKER).is_file() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().into_owned();
        let ver = super::parser::SemVer::parse(&name)?;
        let replace = match &best {
            Some((cur, _, _)) => ver.is_newer_than(cur),
            None => true,
        };
        if replace {
            best = Some((ver, name, path));
        }
    }
    best.map(|(_, name, path)| (name, path))
}

/// Applies a staged update (if any) by installing its verified archive over
/// the current executable. Runs at startup, never mid-session. Returns true
/// when an update was applied.
pub fn apply_pending_staged_update() -> Result<bool> {
    let current = env!("CARGO_PKG_VERSION");
    let (version, dir) = match newest_staged_update() {
        Some(v) => v,
        None => return Ok(false),
    };
    // Stale stage (user upgraded manually meanwhile): drop it silently.
    let is_newer = super::parser::SemVer::parse(&version)
        .and_then(|v| super::parser::SemVer::parse(current).map(|c| v.is_newer_than(&c)))
        .unwrap_or(false);
    if !is_newer {
        let _ = std::fs::remove_dir_all(&dir);
        return Ok(false);
    }
    let marker = std::fs::read_to_string(dir.join(STAGED_READY_MARKER))
        .with_context(|| format!("read staged marker in {}", dir.display()))?;
    let mut lines = marker.lines();
    // Legacy single-line markers (path only, pre-hash) are distrusted:
    // drop the stage so the next run re-stages with a hash.
    let (expected_digest, archive_path) = match (lines.next(), lines.next()) {
        (Some(digest), Some(path)) => (digest.trim().to_string(), PathBuf::from(path.trim())),
        _ => {
            let _ = std::fs::remove_dir_all(&dir);
            return Ok(false);
        }
    };
    if !archive_path.exists() {
        let _ = std::fs::remove_dir_all(&dir);
        bail!("staged update {version} is incomplete; re-staging on next run");
    }
    // TOCTOU close: re-hash at apply time, not just at stage time.
    let actual_digest = sha256_file(&archive_path)?;
    if actual_digest != expected_digest {
        let _ = std::fs::remove_dir_all(&dir);
        bail!("staged update {version} failed integrity re-check; stage dropped");
    }
    let ext = if archive_path.extension().and_then(|e| e.to_str()) == Some("zip") {
        "zip"
    } else {
        "tar.gz"
    };
    let exe_path = std::env::current_exe().context("resolve current executable")?;
    println!("vetto: applying staged update v{current} → v{version}...");
    install_archive_over_exe(&exe_path, &archive_path, ext, &dir)?;
    let _ = std::fs::remove_dir_all(&dir);
    println!("vetto: updated to v{version} (previous copy kept for `vetto upgrade --rollback`).");
    Ok(true)
}

/// Extracts a verified archive and atomically replaces the executable,
/// keeping a last-good backup. `scratch` hosts extraction temp state.
fn install_archive_over_exe(
    exe_path: &Path,
    archive_path: &Path,
    ext: &str,
    _scratch: &Path,
) -> Result<()> {
    // Unpack on the SAME filesystem as the executable: rename() across
    // mounts fails with EXDEV (staged dir lives under $HOME, the binary may
    // live in /usr/local/bin). Scratch is always cleaned, success or not.
    let parent_dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let unpack_root = tempfile_dir(parent_dir)?;
    let res = install_from_unpack_root(exe_path, archive_path, ext, &unpack_root);
    let _ = std::fs::remove_dir_all(&unpack_root);
    res
}

fn install_from_unpack_root(
    exe_path: &Path,
    archive_path: &Path,
    ext: &str,
    unpack_root: &Path,
) -> Result<()> {
    let unpack_dir = unpack_root.join("unpack");
    std::fs::create_dir_all(&unpack_dir)
        .with_context(|| format!("create {}", unpack_dir.display()))?;
    let unpack_status = if ext == "zip" {
        // Built-in tar on Windows 10/11 handles zip, otherwise fall back to powershell
        let tar_res = Command::new("tar")
            .args([
                "-xf",
                archive_path.to_str().unwrap_or("vetto_download.zip"),
                "-C",
                unpack_dir.to_str().unwrap_or("."),
            ])
            .status();
        match tar_res {
            Ok(s) if s.success() => s,
            _ => Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-Command",
                    &format!(
                        "Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
                        archive_path.display(),
                        unpack_dir.display()
                    ),
                ])
                .status()
                .context("failed to unpack zip archive via tar or powershell")?,
        }
    } else {
        Command::new("tar")
            .args([
                "-xzf",
                archive_path.to_str().unwrap_or("vetto_download.tar.gz"),
                "-C",
                unpack_dir.to_str().unwrap_or("."),
            ])
            .status()
            .context("failed to unpack binary archive via tar")?
    };

    if !unpack_status.success() {
        bail!("archive unpack failed with status {unpack_status}");
    }

    let extracted_bin = if unpack_dir.join("vetto.exe").exists() {
        unpack_dir.join("vetto.exe")
    } else if unpack_dir.join("vetto").exists() {
        unpack_dir.join("vetto")
    } else if unpack_dir.join("bin").join("vetto").exists() {
        unpack_dir.join("bin").join("vetto")
    } else {
        find_binary_in_dir(&unpack_dir).unwrap_or_else(|| unpack_dir.join("vetto"))
    };

    if !extracted_bin.exists() {
        bail!("extracted archive did not contain 'vetto' executable");
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&extracted_bin, std::fs::Permissions::from_mode(0o755));
    }

    let durable_backup = backup_path_for(exe_path);
    std::fs::copy(exe_path, &durable_backup).with_context(|| {
        format!(
            "failed to back up current executable to {}",
            durable_backup.display()
        )
    })?;

    #[cfg(windows)]
    {
        // Renaming a running image aside is allowed; overwriting is not.
        let _ = std::fs::rename(exe_path, exe_path.with_extension("stale-tmp"));
    }

    std::fs::rename(&extracted_bin, exe_path).with_context(|| {
        format!(
            "failed to replace executable at {}. Try running with elevated permissions (e.g. sudo).",
            exe_path.display()
        )
    })?;
    // Best-effort cleanup of the Windows move-aside leftover (no-op on Unix).
    let _ = std::fs::remove_file(exe_path.with_extension("stale-tmp"));
    Ok(())
}

/// Downloads release archive and performs atomic replacement of the current executable.
fn perform_atomic_binary_upgrade(exe_path: &Path, archive_url: &str, ext: &str) -> Result<()> {
    let parent_dir = exe_path.parent().unwrap_or_else(|| Path::new("."));
    let temp_dir = tempfile_dir(parent_dir)?;

    let archive_path = match download_and_verify_archive(archive_url, ext, &temp_dir) {
        Ok(path) => path,
        Err(e) => {
            let _ = std::fs::remove_dir_all(&temp_dir);
            return Err(e);
        }
    };

    // Single install path shared with staged updates (extract, verify
    // contents, keep last-good backup, atomic replace).
    let res = install_from_unpack_root(exe_path, &archive_path, ext, &temp_dir);
    let _ = std::fs::remove_dir_all(&temp_dir);
    res
}

/// Durable last-good location next to the executable: `vetto` → `vetto.prev`,
/// `vetto.exe` → `vetto.exe.prev`. Exactly one backup is kept (overwritten).
fn backup_path_for(exe_path: &Path) -> PathBuf {
    let file_name = exe_path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "vetto".to_string());
    exe_path
        .parent()
        .unwrap_or_else(|| Path::new("."))
        .join(format!("{file_name}.prev"))
}

/// First whitespace-separated token of a `<hash>  <filename>` sidecar file.
fn parse_sha256_sidecar(text: &str) -> Option<String> {
    let token = text.split_whitespace().next()?.trim().to_lowercase();
    if token.len() == 64 && token.chars().all(|c| c.is_ascii_hexdigit()) {
        Some(token)
    } else {
        None
    }
}

fn sha256_file(path: &Path) -> Result<String> {
    let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
    let mut hasher = Sha256::new();
    hasher.update(&bytes);
    Ok(format!("{:x}", hasher.finalize()))
}

/// Downloads `{archive_url}.sha256` and fails closed unless the downloaded
/// archive matches. Every release publishes the sidecar next to the archive.
fn verify_archive_sha256(archive_path: &Path, sidecar_url: &str, temp_dir: &Path) -> Result<()> {
    let sidecar_path = temp_dir.join("vetto_download.sha256");
    let status = Command::new("curl")
        .args([
            "-fsSL",
            "-A",
            "vetto-updater",
            "-o",
            sidecar_path.to_str().unwrap_or("vetto_download.sha256"),
            sidecar_url,
        ])
        .status()
        .context("failed to download release checksum via curl")?;
    if !status.success() {
        let _ = std::fs::remove_dir_all(temp_dir);
        bail!("checksum sidecar missing at {sidecar_url}: refusing to install unverified bytes");
    }
    let text = std::fs::read_to_string(&sidecar_path)
        .with_context(|| format!("read checksum sidecar {}", sidecar_path.display()))?;
    let expected = parse_sha256_sidecar(&text)
        .with_context(|| format!("malformed checksum sidecar at {sidecar_url}"))?;
    let actual = sha256_file(archive_path)?;
    if actual != expected {
        let _ = std::fs::remove_dir_all(temp_dir);
        bail!("checksum mismatch for downloaded archive: refusing to install");
    }
    Ok(())
}

/// Restores the last-good executable saved by the previous binary upgrade.
pub fn run_rollback(dry_run: bool) -> Result<()> {
    let exe_path = std::env::current_exe().context("resolve current executable")?;
    let backup = backup_path_for(&exe_path);
    if dry_run {
        println!(
            "[dry-run] Would restore {} from backup {}",
            exe_path.display(),
            backup.display()
        );
        return Ok(());
    }
    if !backup.exists() {
        bail!(
            "no rollback backup found at {} (binary upgrades keep exactly one last-good copy)",
            backup.display()
        );
    }
    // Move the current binary aside first so a failed restore can be undone.
    // Renaming a running image aside is allowed on both Unix and Windows.
    let stale = exe_path.with_extension("stale-tmp");
    if exe_path.exists() {
        std::fs::rename(&exe_path, &stale)
            .with_context(|| format!("move aside {}", exe_path.display()))?;
    }
    match std::fs::rename(&backup, &exe_path) {
        Ok(()) => {
            let _ = std::fs::remove_file(&stale);
            println!(
                "Rolled back {} from backup {}.",
                exe_path.display(),
                backup.display()
            );
            Ok(())
        }
        Err(e) => {
            let _ = std::fs::rename(&stale, &exe_path);
            bail!("rollback failed, original restored: {e}");
        }
    }
}

fn find_binary_in_dir(dir: &Path) -> Option<PathBuf> {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() {
                let fname = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if fname == "vetto" || fname == "vetto.exe" {
                    return Some(path);
                }
            } else if path.is_dir() {
                if let Some(found) = find_binary_in_dir(&path) {
                    return Some(found);
                }
            }
        }
    }
    None
}

fn tempfile_dir(base: &Path) -> Result<PathBuf> {
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let dir = base.join(format!(".vetto-upgrade-{}-{}", std::process::id(), nonce));
    if let Err(e) = std::fs::create_dir_all(&dir) {
        bail!(
            "failed to create temporary upgrade staging directory {}: {e}. Try running with elevated permissions (e.g. sudo vetto upgrade).",
            dir.display()
        );
    }
    Ok(dir)
}

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

    #[test]
    fn sidecar_parsing_accepts_release_format() {
        let good = "6401092d62b8388809eece60b764851c596b78f3423952d699ea6f673604b493  vetto-macos-aarch64.tar.gz\n";
        assert_eq!(
            parse_sha256_sidecar(good),
            Some("6401092d62b8388809eece60b764851c596b78f3423952d699ea6f673604b493".to_string())
        );
        assert_eq!(parse_sha256_sidecar(""), None);
        assert_eq!(parse_sha256_sidecar("notahash  file.tgz\n"), None);
    }

    #[test]
    fn prune_keeps_only_current_staged_version() {
        let root = std::env::temp_dir().join(format!(
            "vetto-prune-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        for v in ["0.2.13", "0.2.14"] {
            let d = root.join(v);
            std::fs::create_dir_all(&d).unwrap();
            std::fs::write(d.join("READY"), "x").unwrap();
        }
        // Foreign dir without our marker must survive.
        std::fs::create_dir_all(root.join("user-stuff")).unwrap();

        prune_staged_updates(&root, "0.2.14");

        assert!(root.join("0.2.14").exists());
        assert!(!root.join("0.2.13").exists());
        assert!(root.join("user-stuff").exists());
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn backup_path_sits_next_to_executable() {
        // Platform-native case (path semantics differ per OS).
        #[cfg(unix)]
        assert_eq!(
            backup_path_for(Path::new("/opt/vetto/bin/vetto")),
            PathBuf::from("/opt/vetto/bin/vetto.prev")
        );
        #[cfg(windows)]
        assert_eq!(
            backup_path_for(Path::new(r"C:\tools\vetto.exe")),
            PathBuf::from(r"C:\tools\vetto.exe.prev")
        );
    }

    #[test]
    fn test_detect_install_method() {
        assert_eq!(
            detect_install_method(Path::new("/home/user/.cargo/bin/vetto")),
            InstallMethod::Cargo
        );
        assert_eq!(
            detect_install_method(Path::new(r"C:\Users\user\.cargo\bin\vetto.exe")),
            InstallMethod::Cargo
        );
        assert_eq!(
            detect_install_method(Path::new(
                "/usr/local/lib/node_modules/@shledery/vetto/native/linux-x64/vetto"
            )),
            InstallMethod::Npm
        );
        assert_eq!(
            detect_install_method(Path::new("/home/user/.nvm/versions/node/v20.0.0/bin/vetto")),
            InstallMethod::Npm
        );
        assert_eq!(
            detect_install_method(Path::new(
                r"C:\Users\user\AppData\Roaming\npm\node_modules\@shledery\vetto\native\win32-x64\vetto.exe"
            )),
            InstallMethod::Npm
        );
        assert_eq!(
            detect_install_method(Path::new("/opt/homebrew/bin/vetto")),
            InstallMethod::Homebrew
        );
        assert_eq!(
            detect_install_method(Path::new("/usr/local/Cellar/vetto/0.2.11/bin/vetto")),
            InstallMethod::Homebrew
        );
        assert_eq!(
            detect_install_method(Path::new("/opt/vetto/bin/vetto")),
            InstallMethod::Binary
        );
        assert_eq!(
            detect_install_method(Path::new("/usr/bin/vetto")),
            InstallMethod::Binary
        );
    }
}