mino 1.6.0

Secure AI agent sandbox using rootless containers
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Version awareness for mino run
//!
//! Three concerns:
//! 1. Stale image detection — after a version change, cached composed images may need rebuilding
//! 2. Update check — periodic (24h) check for newer stable releases on GitHub
//! 3. Image clearing — remove composed images so layers rebuild with the new version
//!
//! Checks are silent-on-failure and never block the primary workflow.

use crate::config::{schema::Config, ConfigManager};
use crate::error::MinoResult;
use crate::orchestration::ContainerRuntime;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tracing::{debug, warn};

const STATE_FILENAME: &str = "version_state.json";
const GITHUB_RELEASES_URL: &str = "https://api.github.com/repos/dean0x/mino/releases/latest";

/// Persisted version state at `~/.local/share/mino/version_state.json`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct VersionState {
    pub installed_version: Option<String>,
    pub last_update_check: Option<DateTime<Utc>>,
    pub latest_available: Option<String>,
}

/// Info about stale composed images after a mino version change
pub struct StaleImageInfo {
    pub old: String,
    pub new: String,
}

/// Info about an available mino update
pub struct UpdateInfo {
    pub latest: String,
    pub current: String,
}

/// How mino was installed (for upgrade hints)
pub enum InstallMethod {
    Homebrew,
    Cargo,
    Npm,
    Unknown,
}

// --- Pure functions ---

/// Returns `Some` if stored version differs from current (upgrade or downgrade).
/// Returns `None` on first run (no stored version = no baseline).
pub fn should_warn_stale_images(
    state: &VersionState,
    current_version: &str,
) -> Option<StaleImageInfo> {
    let stored = state.installed_version.as_deref()?;
    if stored == current_version {
        return None;
    }
    Some(StaleImageInfo {
        old: stored.to_string(),
        new: current_version.to_string(),
    })
}

/// Returns true if no previous update check or >24h since last check.
pub fn should_check_update(state: &VersionState) -> bool {
    let Some(last_check) = state.last_update_check else {
        return true;
    };
    Utc::now() - last_check > chrono::Duration::hours(24)
}

/// Returns true if `latest` is newer than `current` per semver.
pub fn is_newer_version(latest: &str, current: &str) -> bool {
    let Ok(latest_ver) = semver::Version::parse(latest) else {
        return false;
    };
    let Ok(current_ver) = semver::Version::parse(current) else {
        return false;
    };
    latest_ver > current_ver
}

/// Extracts version string from GitHub releases/latest JSON response.
/// Strips leading `v` prefix if present.
pub fn parse_github_release(json: &str) -> Option<String> {
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    let tag = value.get("tag_name")?.as_str()?;
    let version_str = tag.strip_prefix('v').unwrap_or(tag);
    semver::Version::parse(version_str).ok()?;
    Some(version_str.to_string())
}

/// Detects how mino was installed based on the executable path.
pub fn detect_install_method() -> InstallMethod {
    let Ok(exe) = std::env::current_exe() else {
        return InstallMethod::Unknown;
    };
    let path = exe.to_string_lossy();
    if path.contains("/opt/homebrew/") || path.contains("/usr/local/Cellar/") {
        InstallMethod::Homebrew
    } else if path.contains(".cargo/") {
        InstallMethod::Cargo
    } else if path.contains("node_modules") {
        InstallMethod::Npm
    } else {
        InstallMethod::Unknown
    }
}

/// Returns an install-method-specific update command hint.
pub fn update_hint(method: &InstallMethod) -> &'static str {
    match method {
        InstallMethod::Homebrew => "Update: brew upgrade mino",
        InstallMethod::Cargo => "Update: cargo install mino",
        InstallMethod::Npm => "Update: npm update -g mino",
        InstallMethod::Unknown => "Visit https://github.com/dean0x/mino/releases",
    }
}

// --- State IO ---

fn state_path() -> PathBuf {
    ConfigManager::state_dir().join(STATE_FILENAME)
}

async fn load_state_from(path: &Path) -> VersionState {
    let content = match tokio::fs::read_to_string(path).await {
        Ok(c) => c,
        Err(_) => return VersionState::default(),
    };
    serde_json::from_str(&content).unwrap_or_default()
}

async fn save_state_to(path: &Path, state: &VersionState) {
    if let Some(parent) = path.parent() {
        if let Err(e) = tokio::fs::create_dir_all(parent).await {
            warn!("Failed to create state directory: {}", e);
            return;
        }
    }
    let json = match serde_json::to_string_pretty(state) {
        Ok(j) => j,
        Err(e) => {
            warn!("Failed to serialize version state: {}", e);
            return;
        }
    };
    // Atomic write: write to temp file then rename to avoid partial reads
    // from concurrent mino sessions racing on the same state file.
    let tmp_path = path.with_extension("tmp");
    if let Err(e) = tokio::fs::write(&tmp_path, json).await {
        warn!("Failed to write version state temp file: {}", e);
        return;
    }
    if let Err(e) = tokio::fs::rename(&tmp_path, path).await {
        warn!("Failed to rename version state temp file: {}", e);
        // Clean up orphaned temp file on rename failure
        let _ = tokio::fs::remove_file(&tmp_path).await;
    }
}

/// Clear all composed images. Prunes stopped containers first to avoid
/// "image in use" errors. Returns Ok(count) with number of images removed.
pub async fn clear_composed_images(runtime: &dyn ContainerRuntime) -> MinoResult<usize> {
    let images = runtime.image_list_prefixed("mino-composed-").await?;
    if images.is_empty() {
        return Ok(0);
    }
    runtime.container_prune().await?;
    for img in &images {
        runtime.image_remove(img).await?;
    }
    Ok(images.len())
}

// --- Public async functions ---

/// Check if cached composed images may be stale after a version upgrade.
///
/// Loads persisted state, compares stored version against current. Only queries
/// the runtime for composed images when a version change is detected (avoids
/// unnecessary Podman subprocess on every run). Always writes current version
/// to state file to bootstrap baseline on first run.
pub async fn check_stale_images(runtime: &dyn ContainerRuntime) -> Option<StaleImageInfo> {
    check_stale_images_inner(runtime, &state_path()).await
}

async fn check_stale_images_inner(
    runtime: &dyn ContainerRuntime,
    path: &Path,
) -> Option<StaleImageInfo> {
    let state = load_state_from(path).await;
    let current = env!("CARGO_PKG_VERSION");

    let info = should_warn_stale_images(&state, current);

    // Only query composed images if version actually changed
    let result = if let Some(info) = info {
        match runtime.image_list_prefixed("mino-composed-").await {
            Ok(images) if !images.is_empty() => Some(info),
            Ok(_) => None,
            Err(e) => {
                warn!("Failed to list composed images: {}", e);
                None
            }
        }
    } else {
        None
    };

    // Always write current version to bootstrap baseline
    let updated = VersionState {
        installed_version: Some(current.to_string()),
        ..state
    };
    save_state_to(path, &updated).await;

    result
}

/// Check for a newer mino release on GitHub.
///
/// Rate-limited to once per 24 hours. Between checks, uses cached
/// `latest_available` from state file. Gated on `config.general.update_check`.
/// HTTP request uses a 3-second global timeout via ureq in `spawn_blocking`.
pub async fn check_for_update(config: &Config) -> Option<UpdateInfo> {
    check_for_update_inner(config, &state_path()).await
}

/// Load cached update info without triggering a background refresh.
///
/// Reads the persisted version state and returns `Some(UpdateInfo)` if the
/// cached `latest_available` is newer than the running binary. Unlike
/// `check_for_update`, this never spawns an HTTP request -- ideal for exit
/// notifications where we just want to surface any result cached earlier.
pub async fn load_cached_update(config: &Config) -> Option<UpdateInfo> {
    load_cached_update_inner(config, &state_path()).await
}

async fn load_cached_update_inner(config: &Config, path: &Path) -> Option<UpdateInfo> {
    if !config.general.update_check {
        return None;
    }

    let state = load_state_from(path).await;
    cached_update_from_state(&state)
}

/// Build an `UpdateInfo` from cached state if a newer version is available.
fn cached_update_from_state(state: &VersionState) -> Option<UpdateInfo> {
    let current = env!("CARGO_PKG_VERSION");
    let latest = state.latest_available.as_deref()?;
    if is_newer_version(latest, current) {
        Some(UpdateInfo {
            latest: latest.to_string(),
            current: current.to_string(),
        })
    } else {
        None
    }
}

async fn check_for_update_inner(config: &Config, path: &Path) -> Option<UpdateInfo> {
    if !config.general.update_check {
        return None;
    }

    let state = load_state_from(path).await;

    // Background refresh if cache is stale (fire-and-forget)
    if should_check_update(&state) {
        let path = path.to_path_buf();
        tokio::spawn(async move {
            let body = match tokio::task::spawn_blocking(fetch_latest_release).await {
                Ok(Ok(body)) => body,
                Ok(Err(e)) => {
                    debug!("Background update check failed: {}", e);
                    return;
                }
                Err(e) => {
                    debug!("Background update check task panicked: {}", e);
                    return;
                }
            };
            match parse_github_release(&body) {
                Some(latest) => {
                    let mut state = load_state_from(&path).await;
                    state.last_update_check = Some(Utc::now());
                    state.latest_available = Some(latest);
                    save_state_to(&path, &state).await;
                }
                None => {
                    debug!("Background update check: failed to parse release response");
                }
            }
        });
    }

    // Always use cached result (instant, zero latency)
    cached_update_from_state(&state)
}

fn fetch_latest_release() -> Result<String, String> {
    use std::time::Duration;
    use ureq::Agent;

    let agent_config = Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(3)))
        .build();
    let agent: Agent = agent_config.new_agent();

    let body: String = agent
        .get(GITHUB_RELEASES_URL)
        .header("User-Agent", &format!("mino/{}", env!("CARGO_PKG_VERSION")))
        .header("Accept", "application/vnd.github.v3+json")
        .call()
        .map_err(|e| e.to_string())?
        .body_mut()
        .read_to_string()
        .map_err(|e| e.to_string())?;

    Ok(body)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::orchestration::mock::{MockResponse, MockRuntime};
    use tempfile::TempDir;

    // --- Pure function tests ---

    #[test]
    fn stale_images_version_changed() {
        let state = VersionState {
            installed_version: Some("1.3.0".to_string()),
            ..Default::default()
        };
        let result = should_warn_stale_images(&state, "1.4.0").unwrap();
        assert_eq!(result.old, "1.3.0");
        assert_eq!(result.new, "1.4.0");
    }

    #[test]
    fn stale_images_same_version() {
        let state = VersionState {
            installed_version: Some("1.4.0".to_string()),
            ..Default::default()
        };
        assert!(should_warn_stale_images(&state, "1.4.0").is_none());
    }

    #[test]
    fn stale_images_no_stored_version() {
        let state = VersionState::default();
        assert!(should_warn_stale_images(&state, "1.4.0").is_none());
    }

    #[test]
    fn stale_images_downgrade() {
        let state = VersionState {
            installed_version: Some("1.5.0".to_string()),
            ..Default::default()
        };
        let result = should_warn_stale_images(&state, "1.4.0").unwrap();
        assert_eq!(result.old, "1.5.0");
        assert_eq!(result.new, "1.4.0");
    }

    #[test]
    fn check_update_no_previous() {
        let state = VersionState::default();
        assert!(should_check_update(&state));
    }

    #[test]
    fn check_update_over_24h() {
        let state = VersionState {
            last_update_check: Some(Utc::now() - chrono::Duration::hours(25)),
            ..Default::default()
        };
        assert!(should_check_update(&state));
    }

    #[test]
    fn check_update_within_24h() {
        let state = VersionState {
            last_update_check: Some(Utc::now() - chrono::Duration::hours(1)),
            ..Default::default()
        };
        assert!(!should_check_update(&state));
    }

    #[test]
    fn newer_version_detected() {
        assert!(is_newer_version("2.0.0", "1.4.1"));
        assert!(is_newer_version("1.5.0", "1.4.1"));
        assert!(is_newer_version("1.4.2", "1.4.1"));
    }

    #[test]
    fn same_version_not_newer() {
        assert!(!is_newer_version("1.4.1", "1.4.1"));
    }

    #[test]
    fn older_version_not_newer() {
        assert!(!is_newer_version("1.3.0", "1.4.1"));
    }

    #[test]
    fn prerelease_not_newer_than_release() {
        assert!(!is_newer_version("1.4.1-alpha", "1.4.1"));
    }

    #[test]
    fn invalid_version_not_newer() {
        assert!(!is_newer_version("not-a-version", "1.4.1"));
        assert!(!is_newer_version("1.5.0", "not-a-version"));
    }

    #[test]
    fn parse_release_valid() {
        let json = r#"{"tag_name": "v1.5.0", "name": "Release 1.5.0"}"#;
        assert_eq!(parse_github_release(json), Some("1.5.0".to_string()));
    }

    #[test]
    fn parse_release_no_v_prefix() {
        let json = r#"{"tag_name": "1.5.0"}"#;
        assert_eq!(parse_github_release(json), Some("1.5.0".to_string()));
    }

    #[test]
    fn parse_release_missing_tag() {
        let json = r#"{"name": "Release"}"#;
        assert!(parse_github_release(json).is_none());
    }

    #[test]
    fn parse_release_empty_object() {
        assert!(parse_github_release("{}").is_none());
    }

    #[test]
    fn parse_release_invalid_json() {
        assert!(parse_github_release("not json").is_none());
    }

    #[test]
    fn parse_release_invalid_version() {
        let json = r#"{"tag_name": "not-semver"}"#;
        assert!(parse_github_release(json).is_none());
    }

    #[test]
    fn version_state_serde_roundtrip() {
        let state = VersionState {
            installed_version: Some("1.4.1".to_string()),
            last_update_check: Some(Utc::now()),
            latest_available: Some("1.5.0".to_string()),
        };
        let json = serde_json::to_string(&state).unwrap();
        let parsed: VersionState = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.installed_version, state.installed_version);
        assert_eq!(parsed.latest_available, state.latest_available);
    }

    #[test]
    fn version_state_empty_json() {
        let state: VersionState = serde_json::from_str("{}").unwrap();
        assert!(state.installed_version.is_none());
        assert!(state.last_update_check.is_none());
        assert!(state.latest_available.is_none());
    }

    #[test]
    fn version_state_partial_json() {
        let state: VersionState =
            serde_json::from_str(r#"{"installed_version": "1.4.0"}"#).unwrap();
        assert_eq!(state.installed_version.as_deref(), Some("1.4.0"));
        assert!(state.last_update_check.is_none());
    }

    #[test]
    fn version_state_corrupt_returns_error() {
        let result: Result<VersionState, _> = serde_json::from_str("not json");
        assert!(result.is_err());
    }

    #[test]
    fn update_hint_homebrew() {
        assert!(update_hint(&InstallMethod::Homebrew).contains("brew"));
    }

    #[test]
    fn update_hint_cargo() {
        assert!(update_hint(&InstallMethod::Cargo).contains("cargo install"));
    }

    #[test]
    fn update_hint_npm() {
        assert!(update_hint(&InstallMethod::Npm).contains("npm"));
    }

    #[test]
    fn update_hint_unknown() {
        assert!(update_hint(&InstallMethod::Unknown).contains("github.com"));
    }

    // --- State IO tests ---

    #[tokio::test]
    async fn load_nonexistent_returns_default() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("nonexistent.json");
        let state = load_state_from(&path).await;
        assert!(state.installed_version.is_none());
    }

    #[tokio::test]
    async fn save_load_roundtrip() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");
        let state = VersionState {
            installed_version: Some("1.4.1".to_string()),
            last_update_check: Some(Utc::now()),
            latest_available: Some("1.5.0".to_string()),
        };
        save_state_to(&path, &state).await;
        let loaded = load_state_from(&path).await;
        assert_eq!(loaded.installed_version, state.installed_version);
        assert_eq!(loaded.latest_available, state.latest_available);
    }

    #[tokio::test]
    async fn load_corrupt_returns_default() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("corrupt.json");
        tokio::fs::write(&path, "not json").await.unwrap();
        let state = load_state_from(&path).await;
        assert!(state.installed_version.is_none());
    }

    #[tokio::test]
    async fn first_run_bootstraps_state() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let mock = MockRuntime::new();
        let result = check_stale_images_inner(&mock, &path).await;
        assert!(result.is_none());

        let state = load_state_from(&path).await;
        assert_eq!(
            state.installed_version.as_deref(),
            Some(env!("CARGO_PKG_VERSION"))
        );
        mock.assert_called("image_list_prefixed", 0);
    }

    // --- Integration tests with MockRuntime ---

    #[tokio::test]
    async fn stale_check_version_changed_with_images() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some("1.0.0".to_string()),
            ..Default::default()
        };
        save_state_to(&path, &state).await;

        let mock = MockRuntime::new().on(
            "image_list_prefixed",
            Ok(MockResponse::StringVec(vec![
                "mino-composed-abc123".to_string()
            ])),
        );

        let result = check_stale_images_inner(&mock, &path).await;
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.old, "1.0.0");
        assert_eq!(info.new, env!("CARGO_PKG_VERSION"));

        mock.assert_called("image_list_prefixed", 1);
        mock.assert_called_with("image_list_prefixed", &["mino-composed-"]);
    }

    #[tokio::test]
    async fn stale_check_version_changed_no_images() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some("1.0.0".to_string()),
            ..Default::default()
        };
        save_state_to(&path, &state).await;

        let mock = MockRuntime::new();
        let result = check_stale_images_inner(&mock, &path).await;
        assert!(result.is_none());

        mock.assert_called("image_list_prefixed", 1);

        let updated = load_state_from(&path).await;
        assert_eq!(
            updated.installed_version.as_deref(),
            Some(env!("CARGO_PKG_VERSION"))
        );
    }

    #[tokio::test]
    async fn stale_check_same_version_skips_runtime() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            ..Default::default()
        };
        save_state_to(&path, &state).await;

        let mock = MockRuntime::new();
        let result = check_stale_images_inner(&mock, &path).await;
        assert!(result.is_none());

        mock.assert_called("image_list_prefixed", 0);
    }

    #[tokio::test]
    async fn stale_check_image_list_error_silent() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some("1.0.0".to_string()),
            ..Default::default()
        };
        save_state_to(&path, &state).await;

        let mock = MockRuntime::new().on_err(
            "image_list_prefixed",
            crate::error::MinoError::Internal("test error".to_string()),
        );

        let result = check_stale_images_inner(&mock, &path).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn update_check_disabled_by_config() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let mut config = Config::default();
        config.general.update_check = false;

        let result = check_for_update_inner(&config, &path).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn update_check_cached_newer() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            last_update_check: Some(Utc::now()),
            latest_available: Some("99.0.0".to_string()),
        };
        save_state_to(&path, &state).await;

        let config = Config::default();
        let result = check_for_update_inner(&config, &path).await;
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.latest, "99.0.0");
        assert_eq!(info.current, env!("CARGO_PKG_VERSION"));
    }

    #[tokio::test]
    async fn update_check_cached_same() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        let state = VersionState {
            installed_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            last_update_check: Some(Utc::now()),
            latest_available: Some(env!("CARGO_PKG_VERSION").to_string()),
        };
        save_state_to(&path, &state).await;

        let config = Config::default();
        let result = check_for_update_inner(&config, &path).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn update_check_no_cached_result() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        // Within 24h but no latest_available cached
        let state = VersionState {
            installed_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            last_update_check: Some(Utc::now()),
            latest_available: None,
        };
        save_state_to(&path, &state).await;

        let config = Config::default();
        let result = check_for_update_inner(&config, &path).await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn update_check_first_call_no_cache_returns_none() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        // No state file at all — first run
        let config = Config::default();
        let result = check_for_update_inner(&config, &path).await;
        // Returns None because there's no cached latest_available yet
        // (background task would populate it for next session)
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn update_check_stale_cache_returns_cached_result() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("state.json");

        // Stale cache (>24h) but has a cached newer version
        let state = VersionState {
            installed_version: Some(env!("CARGO_PKG_VERSION").to_string()),
            last_update_check: Some(Utc::now() - chrono::Duration::hours(25)),
            latest_available: Some("99.0.0".to_string()),
        };
        save_state_to(&path, &state).await;

        let config = Config::default();
        let result = check_for_update_inner(&config, &path).await;
        // Returns cached result immediately even though cache is stale
        // (background task refreshes for next time)
        assert!(result.is_some());
        let info = result.unwrap();
        assert_eq!(info.latest, "99.0.0");
    }

    // --- clear_composed_images tests ---

    #[tokio::test]
    async fn clear_composed_images_prunes_and_removes() {
        let mock = MockRuntime::new().on(
            "image_list_prefixed",
            Ok(MockResponse::StringVec(vec![
                "mino-composed-abc123".to_string(),
                "mino-composed-def456".to_string(),
            ])),
        );

        let count = clear_composed_images(&mock).await.unwrap();
        assert_eq!(count, 2);

        mock.assert_called("image_list_prefixed", 1);
        mock.assert_called_with("image_list_prefixed", &["mino-composed-"]);
        mock.assert_called("container_prune", 1);
        mock.assert_called("image_remove", 2);
        mock.assert_called_with("image_remove", &["mino-composed-abc123"]);
        mock.assert_called_with("image_remove", &["mino-composed-def456"]);
    }

    #[tokio::test]
    async fn clear_composed_images_empty_returns_zero() {
        let mock = MockRuntime::new();

        let count = clear_composed_images(&mock).await.unwrap();
        assert_eq!(count, 0);

        mock.assert_called("image_list_prefixed", 1);
        mock.assert_called("container_prune", 0);
        mock.assert_called("image_remove", 0);
    }

    #[tokio::test]
    async fn clear_composed_images_propagates_list_error() {
        let mock = MockRuntime::new().on_err(
            "image_list_prefixed",
            crate::error::MinoError::Internal("list failed".to_string()),
        );

        let result = clear_composed_images(&mock).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn clear_composed_images_propagates_prune_error() {
        let mock = MockRuntime::new()
            .on(
                "image_list_prefixed",
                Ok(MockResponse::StringVec(vec![
                    "mino-composed-abc123".to_string()
                ])),
            )
            .on_err(
                "container_prune",
                crate::error::MinoError::Internal("prune failed".to_string()),
            );

        let result = clear_composed_images(&mock).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn clear_composed_images_propagates_remove_error() {
        let mock = MockRuntime::new()
            .on(
                "image_list_prefixed",
                Ok(MockResponse::StringVec(vec![
                    "mino-composed-abc123".to_string()
                ])),
            )
            .on_err(
                "image_remove",
                crate::error::MinoError::Internal("remove failed".to_string()),
            );

        let result = clear_composed_images(&mock).await;
        assert!(result.is_err());
    }
}