shine-cli 1.7.0

Give personal automation a reviewable lifecycle
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
use super::report::{
    print_already_managed, print_dry_run_install, print_install_error, print_install_success,
    print_install_success_with_backup,
};
use super::{
    install_prepared_content, materialize_file_content, metadata, resolve_install_destination,
    validate_unique_install_destinations,
};
use crate::colors;
use crate::config::Config;
use crate::env::EnvConfig;
use crate::install_core::manifest::{AppEntry, AppManifest};
use crate::output;
use anyhow::Result;
use file_ops::InstallOutcome;
use std::collections::{BTreeMap, BTreeSet};

use crate::install_core::file_ops;

pub async fn handle_install(
    config: &Config,
    category: Option<&str>,
    dry_run: bool,
    force: bool,
) -> Result<()> {
    crate::config::print_presets_note(config);
    if dry_run {
        println!("{}", colors::dim("[dry-run] No files will be modified."));
    }

    let prefix = match category {
        Some(cat) => format!("app/{cat}"),
        None => "app".to_string(),
    };

    // Load env config once — used by the `template` transform.
    let env = EnvConfig::load_or_init(config).await?;
    let env_map = env.as_map();

    // When the user has configured a custom presets directory, the app preset
    // files are already there — skip the embedded-asset extraction step.
    if !config.is_external_presets {
        // Refresh the managed embedded preset cache on each install so metadata
        // and transformed source updates from the current binary take effect.
        let _extract_report =
            crate::presets::extract_prefix(&prefix, config.presets_dir(), true).await?;
    }
    let categories = metadata::load_active_categories(config, category).await?;
    if let Some(category) = category
        && categories.is_empty()
    {
        anyhow::bail!("app preset category not found: {category}");
    }
    validate_unique_install_destinations(&categories, config)?;
    let total_available: usize = categories.iter().map(|c| c.files.len()).sum();
    output::summary_line(
        "App Configs",
        &[colors::dim(&format!("{total_available} files available"))],
    );

    let mut manifest = AppManifest::load(config.shine_dir()).await?;
    let mut generated_content: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    let mut unavailable_generators: BTreeSet<String> = BTreeSet::new();

    // Run enabled generators before any install writes. A first-time failure
    // aborts cleanly; an existing managed destination is the last-known-good
    // snapshot and is kept with a warning.
    for cat in &categories {
        for file in &cat.files {
            let Some(generator) = &file.generator else {
                continue;
            };
            if !env_map.contains_key(&generator.when_env) {
                continue;
            }
            let key = format!("{}/{}", cat.name, file.source_rel.display());
            let destination = resolve_install_destination(cat, file, config)?;
            match materialize_file_content(config, cat, file, env_map).await {
                Ok(content) => {
                    generated_content.insert(key, content);
                }
                Err(error)
                    if manifest.find_by_dest(&destination).is_some() && destination.exists() =>
                {
                    eprintln!(
                        "  {} {}/{}: generator unavailable; installed copy kept ({error:#})",
                        colors::symbol("!"),
                        cat.name,
                        file.source_rel.display()
                    );
                    unavailable_generators.insert(key);
                }
                Err(error) => return Err(error),
            }
        }
    }

    let mut installed = 0usize;
    let mut skipped = 0usize;
    let mut backed_up = 0usize;
    let mut restart_hints = BTreeSet::new();
    // Categories with at least one file actually written this run — the trigger
    // set for `post_install` hooks (mirrors `post_upgrade`'s changed-only rule).
    let mut changed_categories: BTreeSet<String> = BTreeSet::new();

    for cat in &categories {
        for file in &cat.files {
            let display_name = format!("{}/{}", cat.name, file.source_rel.display());
            if unavailable_generators.contains(&display_name) {
                skipped += 1;
                continue;
            }
            let destination = match resolve_install_destination(cat, file, config) {
                Ok(d) => d,
                Err(e) => {
                    eprintln!(
                        "  {} {display_name}: bad destination: {e:#}",
                        colors::symbol("")
                    );
                    continue;
                }
            };

            let is_managed = manifest.find_by_dest(&destination).is_some();

            let file_uses_env =
                file.transforms.iter().any(|t| t == "template") || file.generator.is_some();

            let content = if let Some(content) = generated_content.remove(&display_name) {
                content
            } else {
                match materialize_file_content(config, cat, file, env_map).await {
                    Ok(content) => content,
                    Err(error) => {
                        eprintln!("  {} {display_name}: {error:#}", colors::symbol_stderr(""));
                        continue;
                    }
                }
            };
            let outcome =
                install_prepared_content(file, &content, &destination, is_managed, dry_run, force)
                    .await;

            let transform_label = if !file.transforms.is_empty() {
                format!(
                    "  {}",
                    colors::dim(&format!("[{}]", file.transforms.join(", ")))
                )
            } else {
                String::new()
            };

            let file_label = file.source_rel.display().to_string();

            match outcome {
                Ok(InstallOutcome::Installed { hash }) => {
                    print_install_success(&file_label, &transform_label, &destination, config);
                    manifest.upsert(AppEntry {
                        source: format!("app/{}/{}", cat.name, file.source_rel.display()),
                        destination,
                        backup: None,
                        content_hash: hash,
                        install_strategy: file.install_strategy.clone(),
                        uses_env: file_uses_env,
                        requires_admin: file.requires_admin,
                    });
                    installed += 1;
                    changed_categories.insert(cat.name.clone());
                    if let Some(hint) = &file.restart_hint {
                        restart_hints.insert(hint.clone());
                    }
                }
                Ok(InstallOutcome::AlreadyManaged) => {
                    print_already_managed(&file_label);
                    skipped += 1;
                }
                Ok(InstallOutcome::BackedUpAndInstalled { backup, hash }) => {
                    print_install_success_with_backup(
                        &file_label,
                        &transform_label,
                        &destination,
                        &backup,
                        config,
                    );
                    manifest.upsert(AppEntry {
                        source: format!("app/{}/{}", cat.name, file.source_rel.display()),
                        destination,
                        backup: Some(backup),
                        content_hash: hash,
                        install_strategy: file.install_strategy.clone(),
                        uses_env: file_uses_env,
                        requires_admin: file.requires_admin,
                    });
                    installed += 1;
                    backed_up += 1;
                    changed_categories.insert(cat.name.clone());
                    if let Some(hint) = &file.restart_hint {
                        restart_hints.insert(hint.clone());
                    }
                }
                Ok(InstallOutcome::DryRun) => {
                    print_dry_run_install(&file_label, &transform_label, &destination, config);
                    skipped += 1;
                }
                Err(e) => {
                    print_install_error(&display_name, &e);
                }
            }
        }
    }

    if !dry_run {
        manifest.save(config.shine_dir()).await?;
        super::hooks::run_app_hooks(
            config,
            |name| categories.iter().find(|c| c.name == name),
            &changed_categories,
            super::hooks::HookPhase::PostInstall,
            true,
        )
        .await;
    }

    let mut summary_parts: Vec<String> = Vec::new();
    if installed > 0 {
        let backup_note = if backed_up > 0 {
            format!(", {backed_up} backed up")
        } else {
            String::new()
        };
        summary_parts.push(colors::green(&format!(
            "{installed} installed{backup_note}"
        )));
    }
    if skipped > 0 {
        summary_parts.push(colors::dim(&format!("{skipped} skipped")));
    }
    output::footer("Done", &summary_parts);
    for hint in restart_hints {
        println!("  {} {}", colors::symbol("!"), colors::yellow(&hint));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(clippy::await_holding_lock)]
    use super::super::uninstall::handle_uninstall;
    use super::*;
    use crate::config::Config;
    use crate::install_core::manifest::AppManifest;
    #[cfg(unix)]
    use crate::presets;
    #[cfg(unix)]
    use crate::test_support::env_lock;
    use tokio::fs;

    async fn make_temp_dir() -> std::path::PathBuf {
        crate::test_support::make_temp_dir("shine-apps").await
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn install_then_uninstall_roundtrip() {
        let _admin_guard = crate::test_support::admin_category_test_lock().await;
        let _guard = env_lock();
        let dir = make_temp_dir().await;

        // Point HOME at the temp dir so ~ expands there
        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::set_var("HOME", dir.to_str().unwrap()) };

        let config = Config::new_for_test(&dir);
        fs::create_dir_all(config.presets_dir()).await.unwrap();
        fs::create_dir_all(config.shine_dir()).await.unwrap();

        handle_install(&config, None, false, false).await.unwrap();

        // At least the manifest should have entries
        let manifest = AppManifest::load(config.shine_dir()).await.unwrap();
        assert!(
            !manifest.entries.is_empty(),
            "manifest should have entries after install"
        );

        // Each installed file should exist
        for entry in &manifest.entries {
            assert!(
                entry.destination.exists(),
                "installed file should exist: {}",
                entry.destination.display()
            );
        }

        handle_uninstall(&config, None, false, false, false)
            .await
            .unwrap();

        let manifest_after = AppManifest::load(config.shine_dir()).await.unwrap();
        assert!(
            manifest_after.entries.is_empty(),
            "manifest should be empty after uninstall"
        );

        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::remove_var("HOME") };
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn install_is_idempotent() {
        let _admin_guard = crate::test_support::admin_category_test_lock().await;
        let _guard = env_lock();
        let dir = make_temp_dir().await;
        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::set_var("HOME", dir.to_str().unwrap()) };

        let config = Config::new_for_test(&dir);
        fs::create_dir_all(config.presets_dir()).await.unwrap();
        fs::create_dir_all(config.shine_dir()).await.unwrap();

        handle_install(&config, None, false, false).await.unwrap();
        let manifest_first = AppManifest::load(config.shine_dir()).await.unwrap();
        let count_first = manifest_first.entries.len();

        handle_install(&config, None, false, false).await.unwrap();
        let manifest_second = AppManifest::load(config.shine_dir()).await.unwrap();

        assert_eq!(
            manifest_second.entries.len(),
            count_first,
            "re-install must not duplicate manifest entries"
        );

        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::remove_var("HOME") };
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn post_install_hook_runs_only_when_a_file_changes() {
        let dir = make_temp_dir().await;
        let dest_root = dir.join("dest").to_string_lossy().replace('\\', "/");
        let marker = dir.join("post-install-ran");
        let category_dir = dir.join("presets/app/hooktest");
        fs::create_dir_all(&category_dir).await.unwrap();
        fs::write(
            category_dir.join("shine.toml"),
            format!(
                "description = \"hook test\"\n\
dest = \"{dest_root}\"\n\
post_install = {{ command = \"/bin/sh\", args = [\"-c\", \"touch {marker}\"] }}\n\n\
[[files]]\n\
source = \"file.conf\"\n",
                marker = marker.display()
            ),
        )
        .await
        .unwrap();
        fs::write(category_dir.join("file.conf"), b"hello\n")
            .await
            .unwrap();

        let mut config = Config::new_for_test(&dir);
        config.is_external_presets = true;
        config.allow_app_hooks = true;
        fs::create_dir_all(config.shine_dir()).await.unwrap();

        // First install writes the file → post_install fires.
        handle_install(&config, Some("hooktest"), false, false)
            .await
            .unwrap();
        assert!(marker.exists(), "post_install must run on first install");

        // Second install changes nothing → hook must not fire again.
        fs::remove_file(&marker).await.unwrap();
        handle_install(&config, Some("hooktest"), false, false)
            .await
            .unwrap();
        assert!(
            !marker.exists(),
            "post_install must not run when no file changed"
        );

        // Replacement install (force) rewrites the file → post_install fires again.
        handle_install(&config, Some("hooktest"), false, true)
            .await
            .unwrap();
        assert!(
            marker.exists(),
            "post_install must run on replacement install"
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[test]
    fn install_missing_category_errors() {
        let dir = std::env::temp_dir().join("shine-apps-missing-category");
        let config = Config::new_for_test(&dir);

        let err = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(handle_install(&config, Some("docker"), true, false))
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("app preset category not found: docker")
        );
    }

    #[cfg(windows)]
    #[tokio::test(flavor = "current_thread")]
    async fn docker_desktop_install_and_uninstall_only_manage_proxy_keys() {
        let dir = make_temp_dir().await;
        let dest_root = dir
            .join("desktop-settings")
            .to_string_lossy()
            .replace('\\', "/");
        let category_dir = dir.join("presets/app/docker-desktop-test");
        fs::create_dir_all(&category_dir).await.unwrap();
        fs::write(
            category_dir.join("shine.toml"),
            format!(
                "description = \"Docker Desktop proxy settings\"\n\
dest = \"{dest_root}\"\n\n\
[[files]]\n\
source = \"settings-store.jsonc\"\n\
target = \"settings-store.json\"\n\
transforms = [\"template\", \"jsonc-to-json\"]\n\
install_mode = \"json-merge\"\n\
managed_keys = [\"proxy\", \"containersProxy\"]\n"
            ),
        )
        .await
        .unwrap();
        fs::write(
            category_dir.join("settings-store.jsonc"),
            br#"{
  "proxy": {
    "mode": "manual",
    "http": "http://@@PROXY_HOST@@:@@HTTP_PROXY_PORT@@",
    "https": "http://@@PROXY_HOST@@:@@HTTP_PROXY_PORT@@"
  },
  "containersProxy": {
    "mode": "manual",
    "http": "http://@@PROXY_HOST@@:@@HTTP_PROXY_PORT@@",
    "https": "http://@@PROXY_HOST@@:@@HTTP_PROXY_PORT@@"
  }
}"#,
        )
        .await
        .unwrap();

        let mut config = Config::new_for_test(&dir);
        config.is_external_presets = true;
        fs::create_dir_all(config.shine_dir()).await.unwrap();

        let destination = dir.join("desktop-settings").join("settings-store.json");
        fs::create_dir_all(destination.parent().unwrap())
            .await
            .unwrap();
        fs::write(
            &destination,
            br#"{
  "theme": "dark",
  "analyticsEnabled": true
}"#,
        )
        .await
        .unwrap();

        handle_install(&config, Some("docker-desktop-test"), false, false)
            .await
            .unwrap();

        let mut installed: serde_json::Value =
            serde_json::from_slice(&fs::read(&destination).await.unwrap()).unwrap();
        assert_eq!(installed["theme"], serde_json::json!("dark"));
        assert_eq!(installed["analyticsEnabled"], serde_json::json!(true));
        assert_eq!(installed["proxy"]["mode"], serde_json::json!("manual"));
        assert_eq!(
            installed["containersProxy"]["mode"],
            serde_json::json!("manual")
        );

        installed["theme"] = serde_json::json!("light");
        fs::write(&destination, serde_json::to_vec_pretty(&installed).unwrap())
            .await
            .unwrap();

        handle_uninstall(&config, Some("docker-desktop-test"), false, false, false)
            .await
            .unwrap();

        let removed: serde_json::Value =
            serde_json::from_slice(&fs::read(&destination).await.unwrap()).unwrap();
        assert_eq!(
            removed,
            serde_json::json!({
                "analyticsEnabled": true,
                "theme": "light"
            })
        );

        let manifest = AppManifest::load(config.shine_dir()).await.unwrap();
        assert!(
            manifest.entries.is_empty(),
            "docker-desktop uninstall should clear manifest entries"
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn install_places_vim_under_directory_root() {
        let _guard = env_lock();
        let dir = make_temp_dir().await;
        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::set_var("HOME", dir.to_str().unwrap()) };

        let config = Config::new_for_test(&dir);
        fs::create_dir_all(config.presets_dir()).await.unwrap();
        fs::create_dir_all(config.shine_dir()).await.unwrap();
        presets::extract_prefix("app/vim", config.presets_dir(), false)
            .await
            .unwrap();

        let categories = metadata::load_installed_categories(&config, Some("vim"))
            .await
            .unwrap();
        let vim = categories.iter().find(|c| c.name == "vim").unwrap();
        let vimrc = vim
            .files
            .iter()
            .find(|f| f.source_rel == std::path::Path::new("vimrc"))
            .unwrap();
        let destination = resolve_install_destination(vim, vimrc, &config).unwrap();
        assert_eq!(destination, dir.join(".vim").join("vimrc"));

        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::remove_var("HOME") };
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn install_places_ghostty_config_under_config_root() {
        let _guard = env_lock();
        let dir = make_temp_dir().await;
        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::set_var("HOME", dir.to_str().unwrap()) };

        let config = Config::new_for_test(&dir);
        fs::create_dir_all(config.presets_dir()).await.unwrap();
        fs::create_dir_all(config.shine_dir()).await.unwrap();
        presets::extract_prefix("app/ghostty", config.presets_dir(), false)
            .await
            .unwrap();

        let categories = metadata::load_installed_categories(&config, Some("ghostty"))
            .await
            .unwrap();
        let ghostty = categories.iter().find(|c| c.name == "ghostty").unwrap();
        let config_file = ghostty
            .files
            .iter()
            .find(|f| f.source_rel == std::path::Path::new("config.ghostty"))
            .unwrap();
        let destination = resolve_install_destination(ghostty, config_file, &config).unwrap();
        assert_eq!(
            destination,
            dir.join(".config/ghostty").join("config.ghostty")
        );

        let light_theme = ghostty
            .files
            .iter()
            .find(|f| f.source_rel == std::path::Path::new("themes/iTerm2 Solarized Light"))
            .unwrap();
        let light_destination = resolve_install_destination(ghostty, light_theme, &config).unwrap();
        assert_eq!(
            light_destination,
            dir.join(".config/ghostty")
                .join("themes/light_iTerm2 Solarized Light")
        );

        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::remove_var("HOME") };
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[cfg(unix)]
    #[tokio::test(flavor = "current_thread")]
    async fn install_renders_ghostty_light_and_dark_background_images() {
        let _guard = env_lock();
        let dir = make_temp_dir().await;
        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::set_var("HOME", dir.to_str().unwrap()) };

        let mut config = Config::new_for_test(&dir);
        config.env.insert(
            "GHOSTTY_BG_LIGHT".into(),
            "/tmp/shine-light-wallpaper.png".into(),
        );
        config.env.insert(
            "GHOSTTY_BG_DARK".into(),
            "/tmp/shine-dark-wallpaper.png".into(),
        );
        fs::create_dir_all(config.presets_dir()).await.unwrap();
        fs::create_dir_all(config.shine_dir()).await.unwrap();

        handle_install(&config, Some("ghostty"), false, false)
            .await
            .unwrap();

        let config_text = fs::read_to_string(dir.join(".config/ghostty/config.ghostty"))
            .await
            .unwrap();
        assert!(config_text.contains("theme = light:Shine Light,dark:dark_Alien Blood"));

        let default_light_theme =
            fs::read_to_string(dir.join(".config/ghostty/themes/Shine Light"))
                .await
                .unwrap();
        assert!(default_light_theme.contains("background-image = /tmp/shine-light-wallpaper.png"));

        let light_theme =
            fs::read_to_string(dir.join(".config/ghostty/themes/light_Github Light Default"))
                .await
                .unwrap();
        assert!(light_theme.contains("background = #ffffff"));
        assert!(light_theme.contains("palette = 4=#0969da"));
        assert!(light_theme.contains("cursor-color = #0969da"));
        assert!(light_theme.contains("background-image = /tmp/shine-light-wallpaper.png"));

        let dark_theme = fs::read_to_string(dir.join(".config/ghostty/themes/dark_Alien Blood"))
            .await
            .unwrap();
        assert!(dark_theme.contains("background = #0f1610"));
        assert!(dark_theme.contains("palette = 10=#18e000"));
        assert!(dark_theme.contains("cursor-color = #73fa91"));
        assert!(dark_theme.contains("background-image = /tmp/shine-dark-wallpaper.png"));

        // SAFETY: `_guard` holds `env_lock()`, serialising HOME mutations across test threads.
        unsafe { std::env::remove_var("HOME") };
        fs::remove_dir_all(&dir).await.unwrap();
    }
}