holochain_cli_sandbox 0.7.0-dev.8

A library and CLI to help create, run and interact with sandboxed Holochain conductor environments, for testing and development purposes.
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
//! # Manage persistence of sandboxes
//!
//! This module gives basic helpers to save / load your sandboxes
//! to / from a `.hc` file.
//! This is very much WIP and subject to change.

use crate::cmds::Existing;
use holochain_conductor_api::conductor::paths::{ConfigFilePath, ConfigRootPath};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Save all sandbox paths to the `.hc` file in the `hc_dir` directory.
pub fn save(hc_dir: PathBuf, paths: Vec<ConfigRootPath>) -> std::io::Result<()> {
    use std::io::Write;
    std::fs::create_dir_all(&hc_dir).map_err(|err| {
        std::io::Error::new(
            err.kind(),
            format!("Failed to create directory '{}': {}", hc_dir.display(), err),
        )
    })?;
    let hc_file = hc_dir.join(".hc");
    let mut file = std::fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(hc_file)
        .map_err(|err| {
            std::io::Error::new(
                err.kind(),
                format!(
                    "Failed to create `.hc` file at '{}': {}",
                    hc_dir.display(),
                    err
                ),
            )
        })?;
    for path in paths {
        writeln!(file, "{}", path.display())?;
    }
    Ok(())
}

/// Remove sandbox paths from the `.hc` file and attempt to delete the sandbox folders.
///
/// If no sandbox paths remain in the `.hc` file, then the `.hc`, `.hc_auth`, and all `.hc_live*`
/// files will be removed from `hc_dir`.
///
/// Returns the number of removed paths from `.hc`.
pub fn remove(hc_dir: PathBuf, existing: Existing) -> std::io::Result<usize> {
    let sandboxes = load(hc_dir.clone())?;
    // Determine sandbox paths to delete
    let mut to_remove_indices: Vec<usize> = Vec::new();
    if existing.all {
        to_remove_indices = (0..sandboxes.len()).collect();
    } else {
        existing
            .indices
            .into_iter()
            .for_each(|i| match sandboxes.get(i) {
                None => msg!("Warning: Provided index is out of range: {}", i),
                Some(Err(path)) => {
                    msg!(
                        "Warning: Missing or invalid sandbox {}:{}",
                        i,
                        path.display()
                    );
                    to_remove_indices.push(i);
                }
                Some(Ok(_)) => to_remove_indices.push(i),
            });
    }
    // Determine remaining paths
    let indices_to_remove: HashSet<_> = to_remove_indices.iter().collect();
    let remaining: Vec<ConfigRootPath> = sandboxes
        .iter()
        .enumerate()
        .filter_map(|(i, item)| {
            if indices_to_remove.contains(&i) {
                return None;
            }
            let Ok(item) = item else {
                return None;
            };
            Some(ConfigRootPath::from(item.clone()))
        })
        .collect();
    // Attempt to delete each sandbox
    for i in to_remove_indices.iter() {
        let p = match sandboxes.get(*i).unwrap() {
            Ok(p) => p,
            Err(p) => p,
        };
        if let Err(e) = std::fs::remove_dir_all(p) {
            tracing::error!("Failed to remove {} because {:?}", p.display(), e);
            msg!(
                "Failed to remove sandbox {}:{}\nReason: {}",
                i,
                p.display(),
                e
            );
        }
    }
    // Erase .hc file
    let hc_file = hc_dir.join(".hc");
    if hc_file.exists() {
        std::fs::remove_file(&hc_file).map_err(|err| {
            std::io::Error::new(
                err.kind(),
                format!(
                    "Failed to remove '.hc' at {}\nReason: {}",
                    hc_dir.display(),
                    err
                ),
            )
        })?;
    }
    // If some valid paths remain, write a new .hc file.
    // Otherwise, delete all files created by hc-sandbox in `hc_dir`
    if !remaining.is_empty() {
        save(hc_dir, remaining.clone())?;
    } else {
        // Erase all .hc_live* files
        for entry in std::fs::read_dir(&hc_dir)? {
            let Ok(entry) = entry else { continue };
            let Ok(file_type) = entry.file_type() else {
                continue;
            };
            if file_type.is_file() {
                if let Some(s) = entry.file_name().to_str() {
                    if s.starts_with(".hc_live_") {
                        std::fs::remove_file(entry.path()).map_err(|err| {
                            std::io::Error::new(
                                err.kind(),
                                format!(
                                    "Failed to remove '{}' at {}\nReason: {}",
                                    s,
                                    hc_dir.display(),
                                    err
                                ),
                            )
                        })?
                    }
                }
            }
        }
        // Erase .hc_auth file
        let hc_auth = hc_dir.join(".hc_auth");
        if hc_auth.exists() {
            std::fs::remove_file(&hc_auth).map_err(|err| {
                std::io::Error::new(
                    err.kind(),
                    format!(
                        "Failed to remove '.hc_auth' at {}\nReason: {}",
                        hc_dir.display(),
                        err
                    ),
                )
            })?;
        }
    }

    Ok(sandboxes.len() - remaining.len())
}

/// Load sandbox paths from the `.hc` file.
pub fn load(hc_dir: PathBuf) -> std::io::Result<Vec<Result<PathBuf, PathBuf>>> {
    let mut paths = Vec::new();
    let hc_file = hc_dir.join(".hc");
    if hc_file.exists() {
        let existing = std::fs::read_to_string(hc_file).map_err(|err| {
            std::io::Error::new(
                err.kind(),
                format!("Failed to read file at '{}': {}", hc_dir.display(), err),
            )
        })?;
        for sandbox in existing.lines() {
            let path = PathBuf::from(sandbox);
            let config_file_path = ConfigFilePath::from(ConfigRootPath::from(path.clone()));
            if config_file_path.as_ref().exists() {
                paths.push(Ok(path));
            } else {
                tracing::error!("Failed to load path {} from existing .hc", path.display());
                paths.push(Err(path));
            }
        }
    }
    Ok(paths)
}

/// Print out the sandboxes contained in the `.hc` file.
pub fn list(hc_dir: PathBuf, verbose: bool) -> std::io::Result<()> {
    let sandboxes = load(hc_dir.clone())?;
    if sandboxes.is_empty() {
        msg!("No sandboxes contained in {}", hc_dir.join(".hc").display());
        return Ok(());
    }
    let out = sandboxes.into_iter().enumerate().try_fold(
        "\nSandboxes contained in `.hc`\n".to_string(),
        |out, (i, result)| {
            let r = match (result, verbose) {
                (Err(path), _) => format!("{}{}: Missing ({})\n", out, i, path.display()),
                (Ok(path), false) => format!("{}{}: {}\n", out, i, path.display()),
                (Ok(path), true) => {
                    let config = holochain_conductor_config::config::read_config(
                        ConfigRootPath::from(path.clone()),
                    )
                    .map_err(std::io::Error::other)?;
                    format!(
                        "{}{}: {}\nConductor Config:\n{:?}\n",
                        out,
                        i,
                        path.display(),
                        config
                    )
                }
            };
            std::io::Result::Ok(r)
        },
    )?;
    msg!("{}", out);
    Ok(())
}

fn get_file_locks() -> &'static tokio::sync::Mutex<Vec<usize>> {
    static FILE_LOCKS: OnceLock<tokio::sync::Mutex<Vec<usize>>> = OnceLock::new();

    FILE_LOCKS.get_or_init(|| tokio::sync::Mutex::new(Vec::new()))
}

/// Lock this setup as running live and advertise the port.
pub async fn lock_live(mut hc_dir: PathBuf, path: &Path, port: u16) -> anyhow::Result<()> {
    use std::io::Write;
    std::fs::create_dir_all(&hc_dir)?;
    let paths = load(hc_dir.clone())?;
    let index = match paths
        .into_iter()
        .enumerate()
        .find(|p| p.1 == Ok(path.to_path_buf()))
    {
        Some((i, _)) => i,
        None => return Ok(()),
    };
    hc_dir.push(format!(".hc_live_{index}"));
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(hc_dir)
    {
        Ok(mut file) => {
            writeln!(file, "{port}")?;
            let mut lock = get_file_locks().lock().await;
            lock.push(index);
        }
        Err(e) => match e.kind() {
            std::io::ErrorKind::AlreadyExists => {}
            _ => return Err(e.into()),
        },
    }

    Ok(())
}

/// For each registered setup, if it has a lockfile, return the port of the running conductor,
/// otherwise return None.
/// The resulting Vec has the same number of elements as lines in the `.hc` file.
pub fn load_ports(hc_dir: PathBuf) -> anyhow::Result<Vec<Option<u16>>> {
    let mut ports = Vec::new();
    let paths = load(hc_dir.clone())?;
    for (i, _) in paths.into_iter().enumerate() {
        let mut hc = hc_dir.clone();
        hc.push(format!(".hc_live_{i}"));
        if hc.exists() {
            let live = std::fs::read_to_string(hc)?;
            let p = live.lines().next().and_then(|l| l.parse::<u16>().ok());
            ports.push(p)
        } else {
            ports.push(None);
        }
    }
    Ok(ports)
}

/// Same as load_ports but only returns ports for paths passed in.
pub fn find_ports(hc_dir: PathBuf, paths: &[PathBuf]) -> anyhow::Result<Vec<Option<u16>>> {
    let mut ports = Vec::new();
    let all_paths = load(hc_dir.clone())?;
    for path in paths {
        let index = all_paths.iter().position(|p| *p == Ok(path.to_path_buf()));
        match index {
            Some(i) => {
                let mut hc = hc_dir.clone();
                hc.push(format!(".hc_live_{i}"));
                if hc.exists() {
                    let live = std::fs::read_to_string(hc)?;
                    let p = live.lines().next().and_then(|l| l.parse::<u16>().ok());
                    ports.push(p)
                } else {
                    ports.push(None);
                }
            }
            None => ports.push(None),
        }
    }
    Ok(ports)
}

/// Remove all lockfiles, releasing all locked ports.
pub async fn release_ports(hc_dir: PathBuf) -> anyhow::Result<()> {
    let files = get_file_locks().lock().await;
    for file in files.iter() {
        let mut hc = hc_dir.clone();
        hc.push(format!(".hc_live_{file}"));
        if hc.exists() {
            std::fs::remove_file(hc)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use holochain_conductor_api::conductor::paths::ConfigRootPath;
    use std::fs;

    #[test]
    fn test_save_single_path() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create a test sandbox directory
        let sandbox_dir = test_dir.join("sandbox1");
        fs::create_dir_all(&sandbox_dir)?;

        // Save the path
        let paths = vec![ConfigRootPath::from(sandbox_dir.clone())];
        save(hc_dir.clone(), paths)?;

        // Verify the .hc file was created and contains the correct path
        let hc_file = hc_dir.join(".hc");
        assert!(hc_file.exists());
        let content = fs::read_to_string(hc_file)?;
        assert_eq!(content.trim(), sandbox_dir.to_string_lossy());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_save_multiple_paths() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Save the paths
        let paths = vec![
            ConfigRootPath::from(sandbox1.clone()),
            ConfigRootPath::from(sandbox2.clone()),
        ];
        save(hc_dir.clone(), paths)?;

        // Verify the .hc file was created and contains the correct paths
        let hc_file = hc_dir.join(".hc");
        assert!(hc_file.exists());
        let content = fs::read_to_string(hc_file)?;
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], sandbox1.to_string_lossy());
        assert_eq!(lines[1], sandbox2.to_string_lossy());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_save_to_nonexistent_directory() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("nonexistent");

        // Create a test sandbox directory
        let sandbox_dir = test_dir.join("sandbox1");
        fs::create_dir_all(&sandbox_dir)?;

        // Save the path to a nonexistent directory (should create it)
        let paths = vec![ConfigRootPath::from(sandbox_dir.clone())];
        save(hc_dir.clone(), paths)?;

        // Verify the directory and .hc file were created
        assert!(hc_dir.exists());
        let hc_file = hc_dir.join(".hc");
        assert!(hc_file.exists());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_save_append() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Save the first path
        let paths1 = vec![ConfigRootPath::from(sandbox1.clone())];
        save(hc_dir.clone(), paths1)?;

        // Save the second path (should append)
        let paths2 = vec![ConfigRootPath::from(sandbox2.clone())];
        save(hc_dir.clone(), paths2)?;

        // Verify the .hc file contains both paths
        let hc_file = hc_dir.join(".hc");
        let content = fs::read_to_string(hc_file)?;
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], sandbox1.to_string_lossy());
        assert_eq!(lines[1], sandbox2.to_string_lossy());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_load_empty_directory() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Load from an empty directory (no .hc file)
        let paths = load(hc_dir.clone())?;

        // Verify the result is an empty vector
        assert!(paths.is_empty());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_load_valid_paths() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Load the paths
        let loaded_paths = load(hc_dir.clone())?;

        // Verify the loaded paths
        assert_eq!(loaded_paths.len(), 2);
        assert_eq!(loaded_paths[0], Ok(sandbox1.clone()));
        assert_eq!(loaded_paths[1], Ok(sandbox2.clone()));

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_load_after_directory_removal() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Remove one of the directories
        fs::remove_dir_all(&sandbox2)?;

        // Load the paths
        let loaded_paths = load(hc_dir.clone())?;

        // Verify the loaded paths
        assert_eq!(loaded_paths.len(), 2);
        assert_eq!(loaded_paths[0], Ok(sandbox1.clone()));
        assert_eq!(loaded_paths[1], Err(sandbox2.clone()));

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_load_after_file_removal() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Remove the config files but keep the directories
        fs::remove_file(config_file_path2.as_ref())?;

        // Load the paths
        let loaded_paths = load(hc_dir.clone())?;

        // Verify the loaded paths
        assert_eq!(loaded_paths.len(), 2);
        assert_eq!(loaded_paths[0], Ok(sandbox1.clone()));
        assert_eq!(loaded_paths[1], Err(sandbox2.clone()));

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_remove_specific_sandboxes() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        let sandbox3 = test_dir.join("sandbox3");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;
        fs::create_dir_all(&sandbox3)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        let config_path3 = ConfigRootPath::from(sandbox3.clone());
        let config_file_path3 = ConfigFilePath::from(config_path3.clone());
        fs::create_dir_all(config_file_path3.as_ref().parent().unwrap())?;
        fs::write(config_file_path3.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2, config_path3];
        save(hc_dir.clone(), paths)?;

        // Clean specific sandboxes (index 1, which is sandbox2)
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![1],
            },
        )?;

        // Verify sandbox2 was removed but sandbox1 and sandbox3 still exist
        assert!(sandbox1.exists());
        assert!(!sandbox2.exists());
        assert!(sandbox3.exists());

        // .hc file must still exist
        let hc_file = hc_dir.join(".hc");
        assert!(hc_file.exists());

        let loaded_paths = load(hc_dir.clone())?;
        assert_eq!(loaded_paths.len(), 2);
        assert_eq!(loaded_paths[0], Ok(sandbox1.clone()));
        assert_eq!(loaded_paths[1], Ok(sandbox3.clone()));

        // Clean specific sandboxes (index 1, which is sandbox2)
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![0, 1],
            },
        )?;

        // Verify sandbox2 was removed but sandbox1 and sandbox3 still exist
        assert!(!sandbox1.exists());
        assert!(!sandbox3.exists());

        // .hc file must still exist
        let hc_file = hc_dir.join(".hc");
        assert!(!hc_file.exists());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_remove_all_sandboxes() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Remove all in empty folder
        remove(
            hc_dir.clone(),
            Existing {
                all: true,
                indices: vec![],
            },
        )?;
        // Verify the .hc file does not exist
        let hc_file = hc_dir.join(".hc");
        assert!(!hc_file.exists());

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Create a live lock file
        let live_file = hc_dir.join(".hc_live_0");
        fs::write(&live_file, "12345")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Clean all sandboxes (empty vector)
        remove(
            hc_dir.clone(),
            Existing {
                all: true,
                indices: vec![],
            },
        )?;

        // Verify all sandboxes were removed
        assert!(!sandbox1.exists());
        assert!(!sandbox2.exists());

        // Verify the .hc file was removed
        let hc_file = hc_dir.join(".hc");
        assert!(!hc_file.exists());

        // Verify the live lock file was removed
        assert!(!live_file.exists());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_remove_with_missing_directories() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        let hc_file = hc_dir.join(".hc");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        let sandbox3 = test_dir.join("sandbox3");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;
        fs::create_dir_all(&sandbox3)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        let config_path3 = ConfigRootPath::from(sandbox3.clone());
        let config_file_path3 = ConfigFilePath::from(config_path3.clone());
        fs::create_dir_all(config_file_path3.as_ref().parent().unwrap())?;
        fs::write(config_file_path3.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2, config_path3];
        save(hc_dir.clone(), paths)?;

        // Remove one of the directories manually
        fs::remove_dir_all(&sandbox1)?;

        // Remove missing sandbox
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![0],
            },
        )?;
        assert!(!sandbox1.exists());
        assert!(sandbox2.exists());
        assert!(sandbox3.exists());
        assert!(hc_file.exists());
        let loaded_paths = load(hc_dir.clone())?;
        assert_eq!(loaded_paths.len(), 2);
        assert_eq!(loaded_paths[0], Ok(sandbox2.clone()));
        assert_eq!(loaded_paths[1], Ok(sandbox3.clone()));

        // Remove one of the directories manually
        fs::remove_dir_all(&sandbox2)?;

        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![0, 1],
            },
        )?;

        // Verify sandbox2 was removed (sandbox1 was already removed)
        assert!(!sandbox2.exists());
        assert!(!sandbox3.exists());
        // Verify the .hc file was removed (since all sandboxes were cleaned)
        assert!(!hc_file.exists());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_remove_with_missing_config_file() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        let hc_file = hc_dir.join(".hc");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Remove one of the directories manually
        fs::remove_file(config_file_path1.as_ref())?;

        // Remove missing sandbox
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![0],
            },
        )?;
        assert!(!sandbox1.exists());
        assert!(sandbox2.exists());
        assert!(hc_file.exists());

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_remove_nonexistent_sandbox_index() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        let hc_file = hc_dir.join(".hc");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Try to clean a nonexistent sandbox index
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![2],
            },
        )?;
        // Verify sandboxes still exists
        assert!(sandbox1.exists());
        assert!(sandbox2.exists());
        // Verify the .hc file still exists
        assert!(hc_file.exists());

        // Try to clean a valid and nonexistent sandbox index
        remove(
            hc_dir.clone(),
            Existing {
                all: false,
                indices: vec![0, 2],
            },
        )?;
        // Verify sandboxes still exists
        assert!(!sandbox1.exists());
        assert!(sandbox2.exists());
        // Verify the .hc file still exists
        assert!(hc_file.exists());

        // Load the paths
        let loaded_paths = load(hc_dir.clone())?;
        // Verify the loaded paths
        assert_eq!(loaded_paths.len(), 1);
        assert_eq!(loaded_paths[0], Ok(sandbox2.clone()));

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    // Note: The list function primarily uses the load function and then formats the output
    // for display. Since we've already thoroughly tested the load function, we'll focus
    // on testing that the list function doesn't error with various inputs.

    #[test]
    fn test_list_with_valid_paths() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Call list with verbose=false (just testing that it doesn't error)
        list(hc_dir.clone(), false)?;

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_list_with_verbose() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        fs::create_dir_all(&sandbox1)?;

        // Create a valid conductor config file
        let config_root_path = ConfigRootPath::from(sandbox1.clone());
        let config =
            holochain_conductor_config::config::create_config(config_root_path.clone(), None)?;
        holochain_conductor_config::config::write_config(config_root_path.clone(), &config)?;

        // Save the path
        let paths = vec![config_root_path];
        save(hc_dir.clone(), paths)?;

        // Call list with verbose=true (just testing that it doesn't error)
        list(hc_dir.clone(), true)?;

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_list_with_missing_paths() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Create test sandbox directories
        let sandbox1 = test_dir.join("sandbox1");
        let sandbox2 = test_dir.join("sandbox2");
        fs::create_dir_all(&sandbox1)?;
        fs::create_dir_all(&sandbox2)?;

        // Create conductor config files
        let config_path1 = ConfigRootPath::from(sandbox1.clone());
        let config_file_path1 = ConfigFilePath::from(config_path1.clone());
        fs::create_dir_all(config_file_path1.as_ref().parent().unwrap())?;
        fs::write(config_file_path1.as_ref(), "dummy config")?;

        let config_path2 = ConfigRootPath::from(sandbox2.clone());
        let config_file_path2 = ConfigFilePath::from(config_path2.clone());
        fs::create_dir_all(config_file_path2.as_ref().parent().unwrap())?;
        fs::write(config_file_path2.as_ref(), "dummy config")?;

        // Save the paths
        let paths = vec![config_path1, config_path2];
        save(hc_dir.clone(), paths)?;

        // Remove one of the directories
        fs::remove_dir_all(&sandbox2)?;

        // Call list (just testing that it doesn't error when a path is missing)
        list(hc_dir.clone(), false)?;

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }

    #[test]
    fn test_list_empty_directory() -> anyhow::Result<()> {
        // Create a temporary directory for testing
        let temp_dir = tempfile::tempdir()?;
        let test_dir = temp_dir.path();
        let hc_dir = test_dir.join("hc_dir");
        fs::create_dir_all(&hc_dir)?;

        // Call list on an empty directory (no .hc file)
        list(hc_dir.clone(), false)?;

        // No need for explicit cleanup, TempDir will handle it

        Ok(())
    }
}