waterui-cli 0.4.1

Cross-platform tooling for WaterUI applications
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
//! Management of the global Water home and per-project managed backend build cache.
//!
//! Playground projects store generated backends under
//! `~/.water/build_cache/<absolute-project-path>/managed_backends/` instead of
//! scattering `.water` directories into user projects. Compiled Cargo artifacts
//! live in the sibling `~/.water/build_cache/target/` — one directory shared by
//! every project, so a machine compiles each dependency revision once no matter
//! how many projects use it. The price of that sharing is serialization: Cargo
//! takes one build-directory lock per target, so concurrent `water` invocations
//! on different projects build one at a time — the second reports `Blocking
//! waiting for file lock on build directory`, which the piped progress render
//! surfaces rather than swallowing — instead of each compiling the same
//! dependency graph in parallel. Sharing wins overall for the workflows the
//! CLI targets, where the alternative is N cold framework compiles.

use std::{
    ffi::OsStr,
    path::{Component, Path, PathBuf, Prefix, PrefixComponent},
    process::Stdio,
    time::{SystemTime, UNIX_EPOCH},
};

use eyre::WrapErr;
use fs4::{FileExt, TryLockError};
use serde::{Deserialize, Serialize};
use smol::fs;
use tracing::{info, warn};
use walkdir::WalkDir;

/// The CLI commit hash embedded at build time.
pub const CLI_COMMIT: &str = env!("WATERUI_CLI_COMMIT");

const BUILD_CACHE_DIR_NAME: &str = "build_cache";
const MANAGED_BACKENDS_DIR_NAME: &str = "managed_backends";
const SHARED_TARGET_DIR_NAME: &str = "target";
const CONFIG_FILE_NAME: &str = "config.toml";
const METADATA_FILE_NAME: &str = "metadata.toml";
const CLEANUP_LOCK_FILE_NAME: &str = ".cleanup.lock";
const LEGACY_LOCAL_WATER_DIR_NAME: &str = ".water";
const DEFAULT_BUILD_CACHE_CLEANUP_AFTER_UNUSED_DAYS: u64 = 30;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
/// Global Water CLI configuration persisted to `~/.water/config.toml`.
pub struct WaterConfig {
    /// Managed build-cache policy.
    #[serde(default)]
    pub build_cache: BuildCacheConfig,
    /// The device `water run` last used per target, keyed by
    /// `"<backend>/<platform>"` (for example `"apple/ios"`). The value is the
    /// device's stable identifier — a simulator UDID, a physical-device
    /// identifier, an Android serial, or an AVD name.
    #[serde(default)]
    pub last_used_device: std::collections::BTreeMap<String, String>,
    /// Unix seconds of the last passive `water update` check, which runs at
    /// most once per 24 hours.
    #[serde(default)]
    pub last_update_check_unix_seconds: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
/// Cleanup policy for the global managed build cache.
pub struct BuildCacheConfig {
    /// Remove build-cache entries that have been unused for more than this many days.
    #[serde(default = "default_build_cache_cleanup_after_unused_days")]
    pub cleanup_after_unused_days: u64,
}

impl Default for BuildCacheConfig {
    fn default() -> Self {
        Self {
            cleanup_after_unused_days: default_build_cache_cleanup_after_unused_days(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct CacheMetadata {
    project_root: String,
    cli_commit: String,
    last_used_unix_seconds: u64,
}

/// Summary of one managed build-cache garbage-collection pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BuildCacheGcSummary {
    /// Number of managed cache entries inspected, excluding the active project cache.
    pub scanned_entries: usize,
    /// Number of stale managed cache entries removed during this pass.
    pub removed_entries: usize,
}

/// Result of attempting to garbage-collect stale managed build-cache entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuildCacheGcOutcome {
    /// Cleanup ran to completion and produced a removal summary.
    Ran(BuildCacheGcSummary),
    /// Cleanup did not run because another `water gc build-cache` process already holds the lock.
    SkippedAlreadyRunning,
}

const fn default_build_cache_cleanup_after_unused_days() -> u64 {
    DEFAULT_BUILD_CACHE_CLEANUP_AFTER_UNUSED_DAYS
}

/// The current user's home directory could not be determined.
#[derive(Debug, thiserror::Error)]
#[error("Could not determine home directory")]
pub struct HomeDirError;

/// Return the Water home directory root at `~/.water`.
///
/// # Errors
/// Returns an error if the current user's home directory cannot be determined.
pub fn water_home_dir() -> Result<PathBuf, HomeDirError> {
    let home = dirs::home_dir().ok_or(HomeDirError)?;
    Ok(home.join(".water"))
}

/// Return the Water home directory root at `~/.water` for `host`.
///
/// # Errors
/// Returns an error if the host's home directory cannot be determined.
pub fn water_home_dir_in(host: &crate::toolchain::Host) -> Result<PathBuf, HomeDirError> {
    let home = host.home_dir().ok_or(HomeDirError)?;
    Ok(home.join(".water"))
}

/// Ensure `~/.water/config.toml` exists and return the parsed configuration.
///
/// # Errors
/// Returns an error if the Water home cannot be created or the config cannot be read or written.
pub async fn ensure_global_config() -> eyre::Result<WaterConfig> {
    let water_home = water_home_dir()?;
    ensure_global_config_in(&water_home).await
}

/// Return the global managed build-cache root at `~/.water/build_cache`.
///
/// # Errors
/// Returns an error if the Water config cannot be loaded or the cache root cannot be created.
pub async fn build_cache_root() -> eyre::Result<PathBuf> {
    let water_home = water_home_dir()?;
    let (_, cache_root) = resolved_build_cache_root_in(&water_home).await?;
    Ok(cache_root)
}

/// Return the Cargo target directory every project's CLI-managed builds share,
/// creating it if needed.
///
/// Compiled units are fingerprint-keyed, so one `~/.water/build_cache/target`
/// serves every project on the machine: a second `water run` reuses the
/// dependency graph the first one compiled instead of cold-building it per
/// project. The directory sits beside the per-project `managed_backends`
/// containers rather than inside one — generated sources are wiped when the
/// CLI's scaffold templates change, while compiled artifacts do not go stale
/// for that reason.
///
/// The directory is a first-class cache entry: it carries the same
/// `metadata.toml` the per-project containers do, so the garbage collector
/// reports it in usage surveys and reclaims it under the same unused-days
/// policy once nothing has built for that long. One target also means one
/// Cargo build-directory lock: builds of different projects serialize, and a
/// waiting build prints `Blocking waiting for file lock on build directory` —
/// visible through the piped progress render — for the holder's duration.
///
/// # Errors
/// Returns an error if the Water home cannot be determined, the global config
/// cannot be loaded, or the cache directory cannot be created.
pub async fn shared_target_dir() -> eyre::Result<PathBuf> {
    let cache_root = build_cache_root().await?;
    ensure_shared_target_dir_in(&cache_root).await
}

/// Return the shared target directory host-side rlib builds use.
///
/// `build_host_rlib` compiles the project's library for the host to read its
/// `waterui_meta_*` symbols; the dependency graph it compiles is the same for
/// every project on the machine, so it shares the per-user target root.
///
/// # Errors
/// Returns an error if the shared build-cache directory cannot be resolved.
pub async fn shared_host_target_dir() -> eyre::Result<PathBuf> {
    Ok(shared_target_dir().await?.join("host"))
}

async fn ensure_shared_target_dir_in(cache_root: &Path) -> eyre::Result<PathBuf> {
    let target_dir = cache_root.join(SHARED_TARGET_DIR_NAME);
    fs::create_dir_all(&target_dir).await.wrap_err_with(|| {
        format!(
            "Failed to create shared target dir {}",
            target_dir.display()
        )
    })?;
    // `project_root` is the entry itself: it exists exactly as long as the
    // cache does, so only the unused-days policy can collect it.
    write_metadata(
        &target_dir,
        &CacheMetadata {
            project_root: target_dir.display().to_string(),
            cli_commit: CLI_COMMIT.to_string(),
            last_used_unix_seconds: now_unix_seconds()?,
        },
    )
    .await?;
    Ok(target_dir)
}

/// Remove the shared Cargo target directory every project's builds write
/// into, returning the disk space it held — `None` when no shared target
/// exists.
///
/// The garbage collector only reclaims the directory once it has been unused
/// for the configured window; this is the explicit drop, for when a user
/// wants the space back now. Unlike `cargo clean`, it refuses while a Cargo
/// build is in flight — detected by the `.cargo-lock` every build holds in
/// its profile directory — since deleting a target mid-build leaves the
/// survivor's own project with a half-written graph.
///
/// # Errors
/// Returns an error if the cache root cannot be resolved, a Cargo build is
/// using the directory, or the directory cannot be removed.
pub async fn remove_shared_target_dir() -> eyre::Result<Option<u64>> {
    let water_home = water_home_dir()?;
    let (_, cache_root) = resolved_build_cache_root_in(&water_home).await?;
    remove_shared_target_dir_in(&cache_root).await
}

async fn remove_shared_target_dir_in(cache_root: &Path) -> eyre::Result<Option<u64>> {
    let target_dir = cache_root.join(SHARED_TARGET_DIR_NAME);
    if !target_dir.exists() {
        return Ok(None);
    }
    shared_target_in_use(&target_dir).await?;
    let bytes = directory_disk_usage(target_dir.clone()).await?;
    fs::remove_dir_all(&target_dir).await.wrap_err_with(|| {
        format!(
            "Failed to remove shared target dir {}",
            target_dir.display()
        )
    })?;
    Ok(Some(bytes))
}

/// Refuse while a Cargo build holds a build-directory lock anywhere under
/// `target_dir`.
///
/// Cargo locks `<triple>/<profile>/.cargo-lock` for the duration of a build,
/// and those profile dirs sit at most three levels under the shared root —
/// `<variant>/<triple>/<profile>` — so probing directories only, never
/// listing profile contents, keeps the check bounded no matter how large the
/// tree grows.
async fn shared_target_in_use(target_dir: &Path) -> eyre::Result<()> {
    let target_dir = target_dir.to_path_buf();
    smol::unblock(move || -> eyre::Result<()> {
        let mut profile_dirs = Vec::new();
        let mut pending = vec![(target_dir.clone(), 0usize)];
        while let Some((dir, depth)) = pending.pop() {
            if depth == 3 {
                continue;
            }
            for entry in std::fs::read_dir(&dir)? {
                let entry = entry?;
                if entry.file_type()?.is_dir() {
                    let path = entry.path();
                    if path.join(".cargo-lock").exists() {
                        profile_dirs.push(path.clone());
                    }
                    pending.push((path, depth + 1));
                }
            }
        }
        for dir in &profile_dirs {
            let lock_path = dir.join(".cargo-lock");
            let file = std::fs::OpenOptions::new()
                .write(true)
                .open(&lock_path)
                .wrap_err_with(|| format!("Failed to open {}", lock_path.display()))?;
            match FileExt::try_lock(&file) {
                Ok(()) => {}
                Err(TryLockError::WouldBlock) => {
                    return Err(eyre::eyre!(
                        "the shared Cargo target {} is in use by a running build \
                         ({} is locked) — drop it once the build finishes",
                        target_dir.display(),
                        lock_path.display()
                    ));
                }
                Err(TryLockError::Error(error)) => {
                    return Err(eyre::Report::from(error))
                        .wrap_err_with(|| format!("Failed to lock {}", lock_path.display()));
                }
            }
        }
        Ok(())
    })
    .await
}

/// Return the managed build-cache directory for a project.
///
/// # Errors
/// Returns an error if the project root cannot be canonicalized or the global cache root cannot be resolved.
pub async fn project_build_cache_dir(project_root: &Path) -> eyre::Result<PathBuf> {
    let project_root = canonicalize_project_root(project_root)?;
    let cache_root = build_cache_root().await?;
    Ok(project_build_cache_dir_in(&project_root, &cache_root))
}

/// Return the whole managed cache container for a project directory, which need
/// not exist.
///
/// A generated backend workspace lives in the cache rather than in the project,
/// so a project that has been thrown away leaves its cache behind — and that
/// cache is what the next build reads. Canonicalizing the project root is not
/// available in that case, so the nearest existing ancestor is canonicalized
/// and the rest of the path appended as written.
///
/// # Errors
/// Returns an error if no ancestor of `project_root` can be canonicalized or the
/// global cache root cannot be resolved.
pub async fn build_cache_container_for(project_root: &Path) -> eyre::Result<PathBuf> {
    let mut trailing = Vec::new();
    let mut existing = project_root.to_path_buf();
    let resolved = loop {
        if let Ok(resolved) = existing.canonicalize() {
            break resolved;
        }
        let name = existing.file_name().map(std::ffi::OsString::from);
        let parent = existing.parent().map(Path::to_path_buf);
        let (Some(name), Some(parent)) = (name, parent) else {
            return Err(eyre::eyre!(
                "Failed to resolve any existing ancestor of {}",
                project_root.display()
            ));
        };
        trailing.push(name);
        existing = parent;
    };
    let mut project_root = resolved;
    for name in trailing.iter().rev() {
        project_root.push(name);
    }
    let cache_root = build_cache_root().await?;
    Ok(project_cache_container_in(&project_root, &cache_root))
}

/// Ensure the managed build-cache directory exists for a project and return it.
///
/// # Errors
/// Returns an error if the project root cannot be canonicalized, config loading fails, or cache directories cannot be created.
pub async fn ensure_project_build_cache(project_root: &Path) -> eyre::Result<PathBuf> {
    let project_root = canonicalize_project_root(project_root)?;
    let water_home = water_home_dir()?;
    let (config, cache_root) = resolved_build_cache_root_in(&water_home).await?;
    if let Err(error) = spawn_build_cache_cleanup_process(&project_root).await {
        warn!(
            current_project_root = %project_root.display(),
            "Failed to spawn build-cache cleanup process: {error}"
        );
    }
    ensure_project_build_cache_in(&project_root, &cache_root, &config).await
}

/// Garbage-collect stale managed build-cache entries while preserving the current project's cache.
///
/// # Errors
/// Returns an error if the project root cannot be canonicalized, config loading fails,
/// or stale cache removal fails.
pub async fn cleanup_stale_build_caches_for_project(
    project_root: &Path,
) -> eyre::Result<BuildCacheGcOutcome> {
    let project_root = canonicalize_project_root(project_root)?;
    let water_home = water_home_dir()?;
    let (config, cache_root) = resolved_build_cache_root_in(&water_home).await?;
    cleanup_stale_caches_if_idle(&cache_root, &project_root, &config).await
}

async fn spawn_build_cache_cleanup_process(project_root: &Path) -> eyre::Result<()> {
    let current_executable = std::env::current_exe()
        .wrap_err("Failed to resolve current water executable for build-cache cleanup")?;
    let project_root = project_root.to_path_buf();

    smol::unblock(move || -> eyre::Result<()> {
        std::process::Command::new(&current_executable)
            .arg("gc")
            .arg("build-cache")
            .arg("--path")
            .arg(&project_root)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map(|_| ())
            .map_err(eyre::Report::from)
            .wrap_err_with(|| {
                format!(
                    "Failed to spawn build-cache cleanup process for {}",
                    project_root.display()
                )
            })
    })
    .await
}

/// Remove the managed build cache for a project.
///
/// # Errors
/// Returns an error if the project root cannot be canonicalized or cache entries cannot be removed.
pub async fn remove_project_build_cache(project_root: &Path) -> eyre::Result<()> {
    let project_root = canonicalize_project_root(project_root)?;
    let cache_root = build_cache_root().await?;
    remove_project_build_cache_in(&project_root, &cache_root).await
}

async fn resolved_build_cache_root_in(water_home: &Path) -> eyre::Result<(WaterConfig, PathBuf)> {
    let config = ensure_global_config_in(water_home).await?;
    let cache_root = water_home.join(BUILD_CACHE_DIR_NAME);
    fs::create_dir_all(&cache_root)
        .await
        .wrap_err_with(|| format!("Failed to create build cache root {}", cache_root.display()))?;
    Ok((config, cache_root))
}

pub(crate) async fn ensure_global_config_in(water_home: &Path) -> eyre::Result<WaterConfig> {
    fs::create_dir_all(water_home)
        .await
        .wrap_err_with(|| format!("Failed to create Water home {}", water_home.display()))?;

    let config_path = water_home.join(CONFIG_FILE_NAME);
    if config_path.exists() {
        let contents = fs::read_to_string(&config_path)
            .await
            .wrap_err_with(|| format!("Failed to read Water config {}", config_path.display()))?;
        return toml::from_str(&contents)
            .wrap_err_with(|| format!("Failed to parse Water config {}", config_path.display()));
    }

    let config = WaterConfig::default();
    write_global_config_in(water_home, &config).await?;
    Ok(config)
}

/// Persist `config` to `~/.water/config.toml`.
///
/// # Errors
/// Returns an error if the config cannot be serialized or written.
pub async fn write_global_config(config: &WaterConfig) -> eyre::Result<()> {
    let water_home = water_home_dir()?;
    write_global_config_in(&water_home, config).await
}

pub(crate) async fn write_global_config_in(
    water_home: &Path,
    config: &WaterConfig,
) -> eyre::Result<()> {
    let config_path = water_home.join(CONFIG_FILE_NAME);
    let contents = toml::to_string_pretty(config).wrap_err("Failed to serialize Water config")?;
    fs::write(&config_path, contents)
        .await
        .wrap_err_with(|| format!("Failed to write Water config {}", config_path.display()))
}

async fn ensure_project_build_cache_in(
    project_root: &Path,
    cache_root: &Path,
    _config: &WaterConfig,
) -> eyre::Result<PathBuf> {
    remove_legacy_local_water_dir(project_root).await?;

    let cache_dir = project_build_cache_dir_in(project_root, cache_root);
    if cache_dir.exists() {
        let should_clean = match read_metadata(&cache_dir).await {
            Ok(metadata) => {
                metadata.project_root != project_root.display().to_string()
                    || metadata.cli_commit != CLI_COMMIT
            }
            Err(_) => true,
        };

        if should_clean {
            info!(
                "Managed build cache changed shape, cleaning {}",
                cache_dir.display()
            );
            fs::remove_dir_all(&cache_dir).await?;
            prune_empty_build_cache_ancestors(
                cache_root,
                cache_dir
                    .parent()
                    .expect("managed build cache dir should always have a parent"),
            )
            .await?;
        }
    }

    fs::create_dir_all(&cache_dir)
        .await
        .wrap_err_with(|| format!("Failed to create build cache dir {}", cache_dir.display()))?;
    write_metadata(
        &cache_dir,
        &CacheMetadata {
            project_root: project_root.display().to_string(),
            cli_commit: CLI_COMMIT.to_string(),
            last_used_unix_seconds: now_unix_seconds()?,
        },
    )
    .await?;

    Ok(cache_dir)
}

async fn remove_project_build_cache_in(project_root: &Path, cache_root: &Path) -> eyre::Result<()> {
    let cache_dir = project_build_cache_dir_in(project_root, cache_root);
    if cache_dir.exists() {
        fs::remove_dir_all(&cache_dir).await?;
        prune_empty_build_cache_ancestors(
            cache_root,
            cache_dir
                .parent()
                .expect("managed build cache dir should always have a parent"),
        )
        .await?;
    }
    remove_legacy_local_water_dir(project_root).await
}

fn project_build_cache_dir_in(project_root: &Path, cache_root: &Path) -> PathBuf {
    project_cache_container_in(project_root, cache_root).join(MANAGED_BACKENDS_DIR_NAME)
}

fn project_cache_container_in(project_root: &Path, cache_root: &Path) -> PathBuf {
    let mut path = cache_root.to_path_buf();
    for component in project_root.components() {
        match component {
            Component::Prefix(prefix) => path.push(normalize_prefix_component(prefix)),
            Component::RootDir => {}
            Component::Normal(segment) => path.push(segment),
            Component::CurDir | Component::ParentDir => {
                panic!(
                    "Canonical project root {} must not contain relative path components",
                    project_root.display()
                );
            }
        }
    }
    path
}

fn normalize_prefix_component(prefix: PrefixComponent<'_>) -> String {
    match prefix.kind() {
        Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
            format!("drive-{}", char::from(letter).to_ascii_uppercase())
        }
        Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
            format!("unc-{}-{}", sanitize_os_str(server), sanitize_os_str(share))
        }
        Prefix::DeviceNS(device) => format!("device-{}", sanitize_os_str(device)),
        Prefix::Verbatim(component) => format!("verbatim-{}", sanitize_os_str(component)),
    }
}

fn sanitize_os_str(value: &OsStr) -> String {
    let sanitized = value
        .to_string_lossy()
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() {
                character
            } else {
                '_'
            }
        })
        .collect::<String>();
    if sanitized.is_empty() {
        return String::from("empty");
    }
    sanitized
}

fn canonicalize_project_root(project_root: &Path) -> eyre::Result<PathBuf> {
    project_root.canonicalize().wrap_err_with(|| {
        format!(
            "Failed to canonicalize project root {}",
            project_root.display()
        )
    })
}

fn metadata_path(cache_dir: &Path) -> PathBuf {
    cache_dir.join(METADATA_FILE_NAME)
}

async fn read_metadata(cache_dir: &Path) -> eyre::Result<CacheMetadata> {
    let metadata_path = metadata_path(cache_dir);
    let contents = fs::read_to_string(&metadata_path)
        .await
        .wrap_err_with(|| format!("Failed to read cache metadata {}", metadata_path.display()))?;
    toml::from_str(&contents)
        .wrap_err_with(|| format!("Failed to parse cache metadata {}", metadata_path.display()))
}

async fn write_metadata(cache_dir: &Path, metadata: &CacheMetadata) -> eyre::Result<()> {
    let metadata_path = metadata_path(cache_dir);
    let contents = toml::to_string(metadata).wrap_err("Failed to serialize cache metadata")?;
    fs::write(&metadata_path, contents)
        .await
        .wrap_err_with(|| format!("Failed to write cache metadata {}", metadata_path.display()))
}

async fn remove_legacy_local_water_dir(project_root: &Path) -> eyre::Result<()> {
    let legacy_dir = project_root.join(LEGACY_LOCAL_WATER_DIR_NAME);
    if legacy_dir.exists() {
        info!(
            "Removing legacy local playground cache at {}",
            legacy_dir.display()
        );
        fs::remove_dir_all(&legacy_dir).await?;
    }
    Ok(())
}

/// On-disk usage of one managed build-cache entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildCacheEntryUsage {
    /// Project the cache entry belongs to.
    pub project_root: PathBuf,
    /// Managed cache directory holding the entry.
    pub cache_dir: PathBuf,
    /// Disk space the entry occupies, in bytes.
    pub bytes: u64,
    /// Whether the entry is currently eligible for removal.
    pub stale: bool,
    /// Whether the entry belongs to the project the survey was run from.
    pub active: bool,
}

/// What the managed build cache is currently spending disk on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildCacheUsageReport {
    /// Entries, largest first.
    pub entries: Vec<BuildCacheEntryUsage>,
    /// Total disk space across every entry, in bytes.
    pub total_bytes: u64,
    /// Disk space held by entries eligible for removal, in bytes.
    pub reclaimable_bytes: u64,
}

/// Survey the managed build cache without removing anything.
///
/// Sizes are measured in allocated blocks and each inode is counted once, so
/// copy-on-write clones and hard links are reported at what they actually cost
/// rather than at the sum of their apparent lengths.
///
/// # Errors
/// Returns an error if the cache root cannot be read or the Water config cannot be loaded.
pub async fn survey_build_cache_usage(
    current_project_root: &Path,
) -> eyre::Result<BuildCacheUsageReport> {
    let water_home = water_home_dir()?;
    let (config, cache_root) = resolved_build_cache_root_in(&water_home).await?;
    let current_cache_dir = project_build_cache_dir_in(current_project_root, &cache_root);
    let max_unused_seconds = config
        .build_cache
        .cleanup_after_unused_days
        .saturating_mul(24 * 60 * 60);
    let now = now_unix_seconds()?;

    let mut entries = Vec::new();
    for cache_dir in discover_managed_build_cache_dirs(&cache_root).await? {
        let metadata = read_metadata(&cache_dir).await.ok();
        let project_root = metadata.as_ref().map_or_else(
            || cache_dir.clone(),
            |metadata| PathBuf::from(&metadata.project_root),
        );
        let active = cache_dir == current_cache_dir;
        let stale = !active
            && metadata.as_ref().is_none_or(|metadata| {
                !PathBuf::from(&metadata.project_root).exists()
                    || now.saturating_sub(metadata.last_used_unix_seconds) > max_unused_seconds
            });
        let bytes = directory_disk_usage(cache_dir.clone()).await?;
        entries.push(BuildCacheEntryUsage {
            project_root,
            cache_dir,
            bytes,
            stale,
            active,
        });
    }

    entries.sort_by(|left, right| {
        right
            .bytes
            .cmp(&left.bytes)
            .then_with(|| left.cache_dir.cmp(&right.cache_dir))
    });
    let total_bytes = entries.iter().map(|entry| entry.bytes).sum();
    let reclaimable_bytes = entries
        .iter()
        .filter(|entry| entry.stale)
        .map(|entry| entry.bytes)
        .sum();

    Ok(BuildCacheUsageReport {
        entries,
        total_bytes,
        reclaimable_bytes,
    })
}

/// Measure how much disk a directory tree actually occupies.
async fn directory_disk_usage(root: PathBuf) -> eyre::Result<u64> {
    smol::unblock(move || {
        let mut seen_inodes = std::collections::HashSet::new();
        let mut total = 0u64;
        for entry in WalkDir::new(&root).follow_links(false) {
            let Ok(entry) = entry else { continue };
            if !entry.file_type().is_file() {
                continue;
            }
            let Ok(metadata) = entry.metadata() else {
                continue;
            };
            total = total.saturating_add(file_disk_usage(&metadata, &mut seen_inodes));
        }
        Ok(total)
    })
    .await
}

#[cfg(unix)]
fn file_disk_usage(
    metadata: &std::fs::Metadata,
    seen_inodes: &mut std::collections::HashSet<(u64, u64)>,
) -> u64 {
    use std::os::unix::fs::MetadataExt as _;

    if !seen_inodes.insert((metadata.dev(), metadata.ino())) {
        return 0;
    }
    // `blocks` is always in 512-byte units, independent of the filesystem's own
    // block size, and already excludes extents shared with a clone source.
    metadata.blocks().saturating_mul(512)
}

#[cfg(not(unix))]
fn file_disk_usage(
    metadata: &std::fs::Metadata,
    _seen_inodes: &mut std::collections::HashSet<(u64, u64)>,
) -> u64 {
    metadata.len()
}

async fn cleanup_stale_caches(
    cache_root: &Path,
    current_project_root: &Path,
    config: &WaterConfig,
) -> eyre::Result<BuildCacheGcSummary> {
    fs::create_dir_all(cache_root).await?;

    let current_cache_dir = project_build_cache_dir_in(current_project_root, cache_root);
    let max_unused_seconds = config
        .build_cache
        .cleanup_after_unused_days
        .saturating_mul(24 * 60 * 60);
    let now = now_unix_seconds()?;

    let mut scanned_entries = 0usize;
    let mut removed_entries = 0usize;

    for cache_dir in discover_managed_build_cache_dirs(cache_root).await? {
        if cache_dir == current_cache_dir {
            continue;
        }

        scanned_entries += 1;

        let should_remove = match read_metadata(&cache_dir).await {
            Ok(metadata) => {
                let project_root = PathBuf::from(&metadata.project_root);
                !project_root.exists()
                    || now.saturating_sub(metadata.last_used_unix_seconds) > max_unused_seconds
            }
            Err(error) => {
                warn!(
                    "Removing stale build cache with invalid metadata at {}: {error}",
                    cache_dir.display()
                );
                true
            }
        };

        if should_remove {
            if let Err(error) = fs::remove_dir_all(&cache_dir).await {
                warn!(
                    "Failed to remove stale build cache {}: {error}",
                    cache_dir.display()
                );
                continue;
            }
            prune_empty_build_cache_ancestors(
                cache_root,
                cache_dir
                    .parent()
                    .expect("managed build cache dir should always have a parent"),
            )
            .await?;
            removed_entries += 1;
        }
    }

    Ok(BuildCacheGcSummary {
        scanned_entries,
        removed_entries,
    })
}

async fn cleanup_stale_caches_if_idle(
    cache_root: &Path,
    current_project_root: &Path,
    config: &WaterConfig,
) -> eyre::Result<BuildCacheGcOutcome> {
    let lock_path = cache_root.join(CLEANUP_LOCK_FILE_NAME);
    let Some(lock_file) = try_acquire_cleanup_lock(&lock_path).await? else {
        return Ok(BuildCacheGcOutcome::SkippedAlreadyRunning);
    };

    let cleanup_result = cleanup_stale_caches(cache_root, current_project_root, config).await;
    // Closing the descriptor releases the lock. The file stays behind on
    // purpose: it is what the next sweep locks, and leaving it means no exit
    // path — including one that never runs — can stop cleanup happening again.
    drop(lock_file);

    cleanup_result.map(BuildCacheGcOutcome::Ran)
}

/// Takes the cleanup lock, or reports that another sweep already holds it.
///
/// The lock has to be released even when the process holding it dies, and
/// creating the file exclusively is not that: a sweep that is killed leaves the
/// file behind, and since then every run takes the "already running" path
/// against a process that no longer exists. Cleanup is spawned detached with its
/// output discarded, so nothing says so — one interrupted sweep in May left the
/// cache unswept until August, by which point it had grown to 149 GB, most of it
/// belonging to workspaces deleted months earlier.
///
/// `flock` is released by the kernel when the descriptor closes, which a crash
/// does too. The file itself stays: it is the thing being locked, not the
/// signal, so nothing has to remove it and nothing is stranded if a process
/// dies before it can.
async fn try_acquire_cleanup_lock(lock_path: &Path) -> eyre::Result<Option<std::fs::File>> {
    let lock_path = lock_path.to_path_buf();
    smol::unblock(move || {
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(&lock_path)
            .wrap_err_with(|| format!("Failed to open cleanup lock {}", lock_path.display()))?;
        match FileExt::try_lock(&file) {
            Ok(()) => Ok(Some(file)),
            Err(TryLockError::WouldBlock) => Ok(None),
            Err(TryLockError::Error(error)) => Err(eyre::Report::from(error))
                .wrap_err_with(|| format!("Failed to lock {}", lock_path.display())),
        }
    })
    .await
}

/// Every managed cache entry under `cache_root`.
///
/// Entries are per-project `managed_backends` containers plus the shared
/// Cargo `target/` every project's builds write into. Neither interior is
/// walked: the shared target's marker is read directly — descending into a
/// cargo target costs as much as the GC itself — and a `managed_backends`
/// marker is checked the moment its directory surfaces, so the walk only
/// ever sees the container path hierarchy.
async fn discover_managed_build_cache_dirs(cache_root: &Path) -> eyre::Result<Vec<PathBuf>> {
    let cache_root = cache_root.to_path_buf();
    smol::unblock(move || -> eyre::Result<Vec<PathBuf>> {
        let shared_target_dir = cache_root.join(SHARED_TARGET_DIR_NAME);
        let mut cache_dirs = Vec::new();
        if shared_target_dir.join(METADATA_FILE_NAME).is_file() {
            cache_dirs.push(shared_target_dir.clone());
        }
        for entry in WalkDir::new(&cache_root)
            .follow_links(false)
            .into_iter()
            .filter_entry(|entry| {
                // A project path can itself end in `target`, so only the
                // shared target at the root is pruned.
                if entry.depth() == 1 && entry.path() == shared_target_dir {
                    return false;
                }
                if entry.file_type().is_dir()
                    && entry.file_name() == OsStr::new(MANAGED_BACKENDS_DIR_NAME)
                {
                    if entry.path().join(METADATA_FILE_NAME).is_file() {
                        cache_dirs.push(entry.path().to_path_buf());
                    }
                    return false;
                }
                true
            })
        {
            entry.map_err(eyre::Report::from)?;
        }
        Ok(cache_dirs)
    })
    .await
}

async fn prune_empty_build_cache_ancestors(
    cache_root: &Path,
    starting_dir: &Path,
) -> eyre::Result<()> {
    let mut current = starting_dir.to_path_buf();
    while current.starts_with(cache_root) && current != cache_root {
        match fs::remove_dir(&current).await {
            Ok(()) => {
                let Some(parent) = current.parent() else {
                    break;
                };
                current = parent.to_path_buf();
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                let Some(parent) = current.parent() else {
                    break;
                };
                current = parent.to_path_buf();
            }
            Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => break,
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

fn now_unix_seconds() -> eyre::Result<u64> {
    Ok(SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .wrap_err("System clock is before UNIX_EPOCH")?
        .as_secs())
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use tempfile::tempdir;

    use super::{
        CLI_COMMIT, WaterConfig, ensure_global_config_in, ensure_project_build_cache_in,
        metadata_path, now_unix_seconds, project_build_cache_dir_in, remove_project_build_cache_in,
        write_global_config_in,
    };

    #[test]
    fn global_config_round_trips_last_used_devices() {
        smol::block_on(async {
            let water_home = tempdir().expect("water home");

            let mut config = WaterConfig::default();
            config.last_used_device.insert(
                "apple/ios".to_owned(),
                "00008140-00011C210CF3001C".to_owned(),
            );
            config
                .last_used_device
                .insert("android/android".to_owned(), "emulator-5554".to_owned());
            write_global_config_in(water_home.path(), &config)
                .await
                .expect("write config");

            let loaded = ensure_global_config_in(water_home.path())
                .await
                .expect("read config back");
            assert_eq!(
                loaded.last_used_device.get("apple/ios").map(String::as_str),
                Some("00008140-00011C210CF3001C")
            );
            assert_eq!(
                loaded
                    .last_used_device
                    .get("android/android")
                    .map(String::as_str),
                Some("emulator-5554")
            );
        });
    }

    #[test]
    fn ensure_global_config_writes_default_build_cache_policy() {
        smol::block_on(async {
            let water_home = tempdir().expect("water home");

            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");

            assert_eq!(
                config.build_cache.cleanup_after_unused_days,
                super::DEFAULT_BUILD_CACHE_CLEANUP_AFTER_UNUSED_DAYS
            );
            let saved = smol::fs::read_to_string(water_home.path().join("config.toml"))
                .await
                .expect("read config");
            assert!(saved.contains("[build_cache]"));
            assert!(saved.contains("cleanup_after_unused_days = 30"));
        });
    }

    #[test]
    fn project_build_cache_dir_uses_absolute_project_path_components() {
        let cache_root = Path::new("/tmp/water-cache-root");
        let project_root = if cfg!(windows) {
            PathBuf::from(r"C:\Users\lexo\demo")
        } else {
            PathBuf::from("/Users/lexo/demo")
        };

        let cache_dir = project_build_cache_dir_in(&project_root, cache_root);

        let expected = if cfg!(windows) {
            cache_root.join("drive-C/Users/lexo/demo/managed_backends")
        } else {
            cache_root.join("Users/lexo/demo/managed_backends")
        };
        assert_eq!(cache_dir, expected);
    }

    #[test]
    fn ensure_project_build_cache_uses_global_build_cache_dir() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");

            let cache_dir = ensure_project_build_cache_in(project.path(), &cache_root, &config)
                .await
                .expect("ensure cache");

            assert!(cache_dir.starts_with(&cache_root));
            assert_ne!(cache_dir, project.path().join(".water"));
            assert!(cache_dir.ends_with("managed_backends"));
            assert!(cache_dir.exists());
        });
    }

    #[test]
    fn ensure_project_build_cache_removes_legacy_local_water_dir() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");
            let legacy_dir = project.path().join(".water");
            smol::fs::create_dir_all(&legacy_dir)
                .await
                .expect("create legacy dir");
            smol::fs::write(legacy_dir.join("stale"), b"stale")
                .await
                .expect("write legacy file");

            ensure_project_build_cache_in(project.path(), &cache_root, &config)
                .await
                .expect("ensure cache");

            assert!(!legacy_dir.exists());
        });
    }

    #[test]
    fn ensure_project_build_cache_cleans_cache_when_cli_commit_changes() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");
            let cache_dir = project_build_cache_dir_in(project.path(), &cache_root);
            smol::fs::create_dir_all(&cache_dir)
                .await
                .expect("create cache dir");
            smol::fs::write(cache_dir.join("stale"), b"stale")
                .await
                .expect("write stale file");
            let stale_metadata = super::CacheMetadata {
                project_root: project.path().display().to_string(),
                cli_commit: String::from("old-commit"),
                last_used_unix_seconds: 1,
            };
            let stale_contents =
                toml::to_string(&stale_metadata).expect("serialize stale metadata");
            smol::fs::write(metadata_path(&cache_dir), stale_contents)
                .await
                .expect("write stale metadata");

            ensure_project_build_cache_in(project.path(), &cache_root, &config)
                .await
                .expect("ensure cache");

            assert!(!cache_dir.join("stale").exists());
            let fresh_metadata = super::read_metadata(&cache_dir)
                .await
                .expect("read metadata");
            assert_eq!(fresh_metadata.cli_commit, CLI_COMMIT);
        });
    }

    #[test]
    fn cleanup_stale_caches_removes_stale_orphaned_caches() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = WaterConfig::default();
            let cache_root = water_home.path().join("build_cache");
            let stale_cache = cache_root.join("definitely/missing/project/managed_backends");
            smol::fs::create_dir_all(&stale_cache)
                .await
                .expect("create stale cache");
            let stale_metadata = super::CacheMetadata {
                project_root: Path::new("/definitely/missing/project")
                    .display()
                    .to_string(),
                cli_commit: CLI_COMMIT.to_string(),
                last_used_unix_seconds: now_unix_seconds().expect("now"),
            };
            let stale_contents =
                toml::to_string(&stale_metadata).expect("serialize stale metadata");
            smol::fs::write(metadata_path(&stale_cache), stale_contents)
                .await
                .expect("write stale metadata");

            let outcome = super::cleanup_stale_caches_if_idle(&cache_root, project.path(), &config)
                .await
                .expect("cleanup caches");

            assert_eq!(
                outcome,
                super::BuildCacheGcOutcome::Ran(super::BuildCacheGcSummary {
                    scanned_entries: 1,
                    removed_entries: 1,
                })
            );
            assert!(!stale_cache.exists());
        });
    }

    #[test]
    fn remove_project_build_cache_deletes_only_managed_backends_leaf() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let child_project = project.path().join("nested/child");
            smol::fs::create_dir_all(&child_project)
                .await
                .expect("create child project");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");

            let parent_cache = ensure_project_build_cache_in(project.path(), &cache_root, &config)
                .await
                .expect("ensure parent cache");
            let child_cache = ensure_project_build_cache_in(&child_project, &cache_root, &config)
                .await
                .expect("ensure child cache");

            remove_project_build_cache_in(project.path(), &cache_root)
                .await
                .expect("remove parent cache");

            assert!(!parent_cache.exists());
            assert!(child_cache.exists());
        });
    }

    /// A sweep that dies leaves the lock file behind, because only the happy
    /// path could ever remove it. Cleanup must still run afterwards: when it did
    /// not, one interrupted sweep stopped every later one for three months, and
    /// silently, since cleanup is spawned with its output discarded.
    #[test]
    fn cleanup_runs_again_after_a_sweep_dies_holding_the_lock() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");
            smol::fs::create_dir_all(&cache_root)
                .await
                .expect("create cache root");

            // What a killed sweep leaves on disk: the lock file, with no live
            // process behind it.
            let lock_path = cache_root.join(super::CLEANUP_LOCK_FILE_NAME);
            smol::fs::write(&lock_path, [])
                .await
                .expect("leave a lock file behind");

            let stale_project = tempdir().expect("stale project");
            let stale_cache =
                ensure_project_build_cache_in(stale_project.path(), &cache_root, &config)
                    .await
                    .expect("ensure stale cache");
            drop(stale_project);

            let outcome = super::cleanup_stale_caches_if_idle(&cache_root, project.path(), &config)
                .await
                .expect("cleanup");

            assert!(
                matches!(outcome, super::BuildCacheGcOutcome::Ran(_)),
                "an abandoned lock file must not be read as a running sweep, got {outcome:?}"
            );
            assert!(!stale_cache.exists());
        });
    }

    /// The other half: while a sweep really is holding the lock, a second one
    /// stands down instead of walking the same tree.
    #[test]
    fn a_second_sweep_stands_down_while_the_first_holds_the_lock() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let water_home = tempdir().expect("water home");
            let config = ensure_global_config_in(water_home.path())
                .await
                .expect("ensure config");
            let cache_root = water_home.path().join("build_cache");
            smol::fs::create_dir_all(&cache_root)
                .await
                .expect("create cache root");

            let lock_path = cache_root.join(super::CLEANUP_LOCK_FILE_NAME);
            let held = super::try_acquire_cleanup_lock(&lock_path)
                .await
                .expect("acquire lock")
                .expect("lock is free");

            let outcome = super::cleanup_stale_caches_if_idle(&cache_root, project.path(), &config)
                .await
                .expect("cleanup");
            assert_eq!(outcome, super::BuildCacheGcOutcome::SkippedAlreadyRunning);

            drop(held);
        });
    }

    /// Discovery reads the shared target's marker directly and never descends
    /// into the tree — a `managed_backends` directory inside `target/` is not
    /// a cache entry and must not surface, while the real ones still do.
    #[test]
    fn discovery_never_walks_inside_the_shared_target() {
        smol::block_on(async {
            let cache_root = tempdir().expect("cache root");
            let target_dir = super::ensure_shared_target_dir_in(cache_root.path())
                .await
                .expect("ensure shared target dir");
            // A marker-shaped dir buried in the target tree — the shape a
            // recursive walk would wrongly report.
            let buried = target_dir.join("debug/managed_backends");
            smol::fs::create_dir_all(&buried)
                .await
                .expect("create buried dir");
            smol::fs::write(
                buried.join(super::METADATA_FILE_NAME),
                "project_root = \"x\"",
            )
            .await
            .expect("write buried marker");

            let project = tempdir().expect("project dir");
            let config = WaterConfig::default();
            let managed =
                super::ensure_project_build_cache_in(project.path(), cache_root.path(), &config)
                    .await
                    .expect("ensure managed cache");

            let mut discovered = super::discover_managed_build_cache_dirs(cache_root.path())
                .await
                .expect("discover cache dirs");
            let mut expected = vec![managed, target_dir];
            discovered.sort();
            expected.sort();
            assert_eq!(discovered, expected);
        });
    }

    /// Dropping the shared target while a Cargo build holds a profile
    /// `.cargo-lock` refuses rather than deleting a live build's tree.
    #[test]
    fn shared_target_dir_refuses_while_a_build_lock_is_held() {
        smol::block_on(async {
            let cache_root = tempdir().expect("cache root");
            let target_dir = super::ensure_shared_target_dir_in(cache_root.path())
                .await
                .expect("ensure shared target dir");
            let profile = target_dir.join("shared/aarch64-apple-darwin/debug");
            smol::fs::create_dir_all(&profile)
                .await
                .expect("create profile dir");
            let lock_file =
                std::fs::File::create(profile.join(".cargo-lock")).expect("create cargo lock");
            fs4::FileExt::lock(&lock_file).expect("hold the build lock");

            let error = super::remove_shared_target_dir_in(cache_root.path())
                .await
                .expect_err("a held build lock must refuse the drop");
            assert!(
                error.to_string().contains("in use"),
                "the error says why: {error}"
            );

            fs4::FileExt::unlock(&lock_file).expect("release the build lock");
            super::remove_shared_target_dir_in(cache_root.path())
                .await
                .expect("an unlocked target drops")
                .expect("the target existed");
        });
    }

    /// The survey reports the shared target, and an explicit drop removes it
    /// immediately instead of waiting out the unused-days policy.
    #[test]
    fn shared_target_dir_can_be_dropped_on_demand() {
        smol::block_on(async {
            let cache_root = tempdir().expect("cache root");
            let target_dir = super::ensure_shared_target_dir_in(cache_root.path())
                .await
                .expect("ensure shared target dir");
            smol::fs::create_dir_all(target_dir.join("debug"))
                .await
                .expect("create a unit dir");
            smol::fs::write(target_dir.join("debug/unit.rlib"), [0u8; 1024])
                .await
                .expect("write a unit");

            let freed = super::remove_shared_target_dir_in(cache_root.path())
                .await
                .expect("drop the shared target");
            assert!(
                freed.is_some_and(|bytes| bytes > 0),
                "the drop reports the space it held: {freed:?}"
            );
            assert!(!target_dir.exists());
            assert_eq!(
                super::remove_shared_target_dir_in(cache_root.path())
                    .await
                    .expect("a second drop"),
                None,
                "dropping an absent shared target is a no-op"
            );
        });
    }

    #[test]
    fn shared_target_dir_is_discovered_and_kept_while_in_use() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let config = WaterConfig::default();
            let cache_root = tempdir().expect("cache root");

            let target_dir = super::ensure_shared_target_dir_in(cache_root.path())
                .await
                .expect("ensure shared target dir");

            assert_eq!(target_dir, cache_root.path().join("target"));

            let discovered = super::discover_managed_build_cache_dirs(cache_root.path())
                .await
                .expect("discover cache dirs");
            assert_eq!(discovered, vec![target_dir.clone()]);

            let outcome =
                super::cleanup_stale_caches_if_idle(cache_root.path(), project.path(), &config)
                    .await
                    .expect("cleanup caches");
            assert_eq!(
                outcome,
                super::BuildCacheGcOutcome::Ran(super::BuildCacheGcSummary {
                    scanned_entries: 1,
                    removed_entries: 0,
                })
            );
            assert!(target_dir.exists());
        });
    }

    #[test]
    fn stale_shared_target_dir_is_collected() {
        smol::block_on(async {
            let project = tempdir().expect("project dir");
            let config = WaterConfig::default();
            let cache_root = tempdir().expect("cache root");

            let target_dir = super::ensure_shared_target_dir_in(cache_root.path())
                .await
                .expect("ensure shared target dir");
            let stale_metadata = super::CacheMetadata {
                project_root: target_dir.display().to_string(),
                cli_commit: CLI_COMMIT.to_string(),
                last_used_unix_seconds: 1,
            };
            smol::fs::write(
                metadata_path(&target_dir),
                toml::to_string(&stale_metadata).expect("serialize stale metadata"),
            )
            .await
            .expect("write stale metadata");

            let outcome =
                super::cleanup_stale_caches_if_idle(cache_root.path(), project.path(), &config)
                    .await
                    .expect("cleanup caches");
            assert_eq!(
                outcome,
                super::BuildCacheGcOutcome::Ran(super::BuildCacheGcSummary {
                    scanned_entries: 1,
                    removed_entries: 1,
                })
            );
            assert!(!target_dir.exists());
        });
    }
}