shimpz-cli 0.5.26

Fast local tooling for Shimpz Assistants
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
//! Native install, reconcile, status, and reset orchestration.

use std::fs::{self, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::Duration;

use sha2::{Digest, Sha256};
use ureq::Agent;
use zeroize::Zeroizing;

use crate::args::{GraphProfile, SpaceInstall, SpaceStart};
use crate::output;

use super::docker::{Engine, ResolvedRelease};
use super::graph::{self, StorageProfile};
use super::paths::Paths;
use super::resources::Inventory;
use super::scheduler;
use super::state::{self, Environment, Installed, Lock};
use super::storage::evidence::HostProfile;
use super::storage::{linux, managed};

const ADMIN_REPOSITORY: &str = "ghcr.io/theshimpz/shimpz-admin";
const TEAM_REPOSITORY: &str = "ghcr.io/theshimpz/shimpz-team-local";
const BRAIN_REPOSITORY: &str = "ghcr.io/theshimpz/shimpz-brain";
const EGRESS_REPOSITORY: &str = "ghcr.io/theshimpz/shimpz-egress";

pub(crate) fn install(options: &SpaceInstall) -> Result<String, String> {
    if let Some(profile) = options.print_graph {
        return Ok(graph::render(match profile {
            GraphProfile::LinuxLuks => StorageProfile::LinuxLuks,
            GraphProfile::ManagedDisk => StorageProfile::ManagedDisk,
        }));
    }
    let context = Context::open(false)?;
    let _lock = (!options.candidate)
        .then(|| Lock::acquire(&context.paths))
        .transpose()?;
    context.install(options.release.as_deref())
}

pub(crate) fn start(options: &SpaceStart) -> Result<String, String> {
    let context = Context::open(options.scheduled)?;
    let _lock = (!options.candidate)
        .then(|| Lock::acquire(&context.paths))
        .transpose()?;
    context.start(options)
}

pub(crate) fn status() -> Result<String, String> {
    let paths = Paths::discover()?;
    if !paths.marker_is_current()? {
        return Ok("Shimpz Space is not installed. Nothing needs attention.".into());
    }
    let profile = managed::detect()?;
    let engine = Engine::connect(profile, &paths)?;
    let installed = state::read_installed(&paths, profile)?;
    Inventory::inspect(&engine, &paths, profile.storage())?;
    let runtime = engine.run_output([
        "compose",
        "--project-directory",
        &paths.home.to_string_lossy(),
        "--env-file",
        &paths.environment.to_string_lossy(),
        "--file",
        &paths.compose.to_string_lossy(),
        "ps",
        "--format",
        "json",
    ])?;
    if runtime.len() > 32 * 1024 {
        return Err("Docker returned an oversized Local status".into());
    }
    Ok(format!(
        "Shimpz Space {}\nRelease {} (ordinal {})\nAdmin http://127.0.0.1:{}\n{}",
        installed.space_id,
        installed.release_ref,
        installed.ordinal,
        installed.port,
        runtime.trim()
    ))
}

pub(crate) fn reset() -> Result<String, String> {
    let context = Context::open(false)?;
    let _lock = Lock::acquire(&context.paths)?;
    context.reset()
}

struct Context {
    paths: Paths,
    profile: HostProfile,
    engine: Engine,
    scheduled: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AdminAttestation {
    Running { port: u16 },
    Stopped,
    Absent,
}

impl Context {
    fn open(scheduled: bool) -> Result<Self, String> {
        let paths = Paths::discover()?;
        ensure_install_home(&paths)?;
        let profile = managed::detect()?;
        let engine = Engine::connect(profile, &paths)?;
        scheduler::validate(profile, &paths)?;
        Ok(Self {
            paths,
            profile,
            engine,
            scheduled,
        })
    }

    fn install(&self, exact_release: Option<&str>) -> Result<String, String> {
        let marker = self.paths.marker_is_current()?;
        let inventory = Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        let installed = if marker {
            match self
                .current_installation()
                .and_then(|installed| self.validate_installation_storage(installed))
            {
                Ok(installed) => Some(installed),
                Err(reason) => {
                    self.recover_corrupt(&inventory, &reason)?;
                    None
                }
            }
        } else {
            if !inventory.empty() {
                return Err(
                    "refusing to install over Docker resources without the exact Local marker"
                        .into(),
                );
            }
            None
        };
        let release = self
            .engine
            .resolve_release(exact_release, &self.paths.home)?;
        if exact_release.is_none() && self.handoff_if_needed(&release, false)? {
            return Ok("The release-bound CLI completed the installation.".into());
        }
        self.apply(&release, installed.as_ref(), false)
    }

    fn validate_installation_storage(&self, installed: Installed) -> Result<Installed, String> {
        if self.profile == HostProfile::Linux
            && (!self.paths.security.exists() || linux::incomplete(&self.paths)?)
        {
            return Err("the encrypted Local storage transaction was interrupted".into());
        }
        Ok(installed)
    }

    fn start(&self, options: &SpaceStart) -> Result<String, String> {
        if !self.paths.marker_is_current()? {
            return Err("Shimpz Space is not installed; run shimpz install".into());
        }
        let installed = self.current_installation()?;
        Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        let release = self
            .engine
            .resolve_release(options.release.as_deref(), &self.paths.home)?;
        if options.release.is_none()
            && state::failed_release_matches(&self.paths, &release.reference)?
        {
            return Ok("The selected Local release previously failed health; the current Space remains unchanged.".into());
        }
        if options.release.is_none() && self.handoff_if_needed(&release, options.scheduled)? {
            return Ok("The release-bound CLI completed reconciliation.".into());
        }
        if options.candidate && options.release.is_none() {
            return Err("a candidate start requires an exact release".into());
        }
        self.apply(&release, Some(&installed), options.scheduled)
    }

    fn apply(
        &self,
        release: &ResolvedRelease,
        installed: Option<&Installed>,
        scheduled: bool,
    ) -> Result<String, String> {
        validate_forward_release(release, installed)?;
        verify_running_cli(release, self.profile)?;
        output::progress("Pulling the release-pinned Space images...");
        self.engine
            .pull_exact(&release.metadata.admin, ADMIN_REPOSITORY)?;
        self.engine
            .pull_exact(&release.metadata.team, TEAM_REPOSITORY)?;
        self.engine
            .pull_exact(&release.metadata.brain, BRAIN_REPOSITORY)?;
        self.engine
            .pull_exact(&release.metadata.egress, EGRESS_REPOSITORY)?;
        let space_id = match installed {
            Some(installed) => installed.space_id.clone(),
            None => state::random_space_id()?,
        };
        let fresh = installed.is_none();
        if fresh {
            state::write_marker(&self.paths)?;
        }
        match self.apply_owned(release, installed, scheduled, &space_id) {
            Ok(outcome) => Ok(outcome),
            Err(error) if fresh => match self.compensate_fresh_failure(&space_id) {
                Ok(()) => Err(error),
                Err(cleanup) => Err(format!(
                    "{error}; fresh-install compensation also failed: {cleanup}"
                )),
            },
            Err(error) => Err(error),
        }
    }

    fn apply_owned(
        &self,
        release: &ResolvedRelease,
        installed: Option<&Installed>,
        scheduled: bool,
        space_id: &str,
    ) -> Result<String, String> {
        match self.ensure_storage(space_id, installed.is_none(), scheduled)? {
            linux::Admission::Locked => {
                return Ok("Encrypted Local storage is locked. No workloads were started.".into());
            }
            linux::Admission::Verified => {}
        }
        let port = state::selected_port(installed)?;
        let (docker_socket, docker_gid) = self
            .engine
            .controller_socket(self.profile, &release.metadata.team)?;
        let previous = installed.map(|_| self.backup_current()).transpose()?;
        state::write_environment(
            &self.paths,
            &Environment {
                release,
                profile: self.profile,
                space_id,
                port,
                docker_gid,
                docker_socket: &docker_socket,
                cpuset: &self.engine.cpuset,
                secure_root: &self.paths.pool_mount,
            },
        )?;
        state::write_private(&self.paths.compose, &graph::render(self.profile.storage()))?;
        output::progress("Starting the Shimpz Space...");
        let started = self.engine.compose(
            &self.paths,
            [
                "up",
                "-d",
                "--wait",
                "--wait-timeout",
                "120",
                "--no-build",
                "--pull",
                "never",
                "--remove-orphans",
            ],
        )?;
        if !started.success() {
            return self.rollback(release, space_id, previous);
        }
        if let Err(storage_error) = self.validate_started_storage(space_id) {
            let rollback = self.rollback(release, space_id, previous);
            return match rollback {
                Ok(outcome) | Err(outcome) => Err(format!("{storage_error}; {outcome}")),
            };
        }
        let status =
            state::write_status(&self.paths, release, release_outcome(release, installed))?;
        if self
            .engine
            .project_release_status(&release.metadata.admin, status.as_bytes())
            .is_err()
        {
            return self.rollback(release, space_id, previous);
        }
        remove_backup(previous)?;
        scheduler::install(self.profile, &self.paths)?;
        remove_regular_if_present(&self.paths.failed_release)?;
        Ok(format!(
            "Shimpz Space is ready.\nAdmin http://127.0.0.1:{port}\nRelease {} (ordinal {})",
            release.reference, release.metadata.ordinal
        ))
    }

    fn reset(&self) -> Result<String, String> {
        let marker = self.paths.marker_is_current()?;
        let inventory = Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        if self.profile != HostProfile::Linux && self.paths.security.exists() {
            return Err(
                "unexpected Local security content is outside the managed host profile".into(),
            );
        }
        if !marker && inventory.empty() && !self.paths.security.exists() {
            scheduler::remove(self.profile, &self.paths)?;
            let preserved = self.remove_files()?;
            return Ok(reset_outcome(true, &preserved));
        }
        let installed = if marker {
            self.current_installation().ok()
        } else {
            None
        };
        if !inventory.empty() && installed.is_none() {
            return Err(
                "the current Local Space cannot be authenticated safely; run shimpz install for bounded recovery"
                    .into(),
            );
        }
        if !inventory.empty()
            && let Some(current) = &installed
        {
            self.start_admin_for_reset()?;
            authenticated_admin_reset(current.port)?;
        }
        let remaining = Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        remaining.remove(&self.engine)?;
        if self.profile == HostProfile::Linux && self.paths.security.exists() {
            let space_id = installed
                .map(|current| current.space_id)
                .or(inventory.space_id);
            linux::reset(&self.paths, space_id.as_deref())?;
        }
        scheduler::remove(self.profile, &self.paths)?;
        let preserved = self.remove_files()?;
        Ok(reset_outcome(false, &preserved))
    }

    fn current_installation(&self) -> Result<Installed, String> {
        let installed = state::read_installed(&self.paths, self.profile)?;
        let expected = graph::render(self.profile.storage());
        let actual = fs::read_to_string(&self.paths.compose)
            .map_err(|error| format!("could not read the installed Local graph: {error}"))?;
        if actual != expected {
            return Err("the installed Local graph is not current".into());
        }
        Ok(installed)
    }

    fn validate_started_storage(&self, space_id: &str) -> Result<(), String> {
        if self.profile == HostProfile::Linux {
            linux::Pool::new(&self.paths, space_id)?.validate_mounted()
        } else {
            Ok(())
        }
    }

    fn recover_corrupt(&self, inventory: &Inventory, reason: &str) -> Result<(), String> {
        if self.scheduled {
            return Err(reason.into());
        }
        let admin = self.prepare_admin_for_recovery()?;
        let names = inventory.container_names(&self.engine)?;
        let confirmed = recovery_prompt(reason, inventory, &names)?;
        if !confirmed {
            return Err("the corrupt Local Space was preserved; nothing changed".into());
        }
        let admin_port = match admin {
            AdminAttestation::Running { port } if admin_available(port) => Some(port),
            _ => None,
        };
        if let Some(port) = admin_port {
            authenticated_admin_reset(port)?;
        }
        scheduler::remove(self.profile, &self.paths)?;
        let space_id = inventory.space_id.clone();
        let remaining = if admin_port.is_some() {
            Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?
        } else {
            inventory.clone()
        };
        remaining.remove(&self.engine)?;
        if self.profile == HostProfile::Linux && self.paths.security.exists() {
            linux::reset(&self.paths, space_id.as_deref())?;
        }
        self.remove_runtime_files()?;
        output::info("Corrupt Local Space removed; continuing with a fresh installation.");
        Ok(())
    }

    fn ensure_storage(
        &self,
        space_id: &str,
        fresh: bool,
        scheduled: bool,
    ) -> Result<linux::Admission, String> {
        match self.profile {
            HostProfile::Linux => linux::Pool::new(&self.paths, space_id)?.ensure(fresh, scheduled),
            HostProfile::MacOs | HostProfile::Wsl => {
                managed::verify(self.profile, &self.paths)?;
                Ok(linux::Admission::Verified)
            }
        }
    }

    fn handoff_if_needed(
        &self,
        release: &ResolvedRelease,
        scheduled: bool,
    ) -> Result<bool, String> {
        let running = std::env::current_exe().map_err(|_| "the running CLI path is unavailable")?;
        reconcile_previous_cli(&self.paths.managed_cli, &running)?;
        let expected = expected_cli_hash(release, self.profile);
        if hash_file(&running)? == expected {
            return Ok(false);
        }
        let bin = self
            .paths
            .managed_cli
            .parent()
            .ok_or_else(|| "the managed CLI directory is invalid".to_owned())?;
        fs::create_dir_all(bin).map_err(io_error)?;
        fs::set_permissions(bin, fs::Permissions::from_mode(0o700)).map_err(io_error)?;
        let candidate = self.paths.managed_cli.with_extension("candidate");
        if candidate.exists() {
            fs::remove_file(&candidate).map_err(io_error)?;
        }
        self.engine
            .extract_cli(&release.reference, self.profile, &candidate)?;
        fs::set_permissions(&candidate, fs::Permissions::from_mode(0o700)).map_err(io_error)?;
        if hash_file(&candidate)? != expected {
            fs::remove_file(&candidate).map_err(io_error)?;
            return Err("the extracted CLI hash does not match the atomic release".into());
        }
        let previous = self.paths.managed_cli.with_extension("previous");
        if self.paths.managed_cli.exists() {
            validate_private_cli(&self.paths.managed_cli)?;
            fs::rename(&self.paths.managed_cli, &previous).map_err(io_error)?;
        }
        if let Err(error) = fs::rename(&candidate, &self.paths.managed_cli) {
            restore_previous_cli(&self.paths.managed_cli, &previous)?;
            return Err(io_error(error));
        }
        let mut command = Command::new(&self.paths.managed_cli);
        if self.paths.marker.exists() {
            command.arg("start");
            if scheduled {
                command.arg("--scheduled");
            }
            command
                .arg("--release")
                .arg(&release.reference)
                .arg("--candidate");
        } else {
            command
                .arg("install")
                .arg("--release")
                .arg(&release.reference)
                .arg("--candidate");
        }
        let status = command
            .stdin(Stdio::null())
            .status()
            .map_err(|error| format!("could not start the release-bound CLI: {error}"));
        let completed = status.is_ok_and(|status| status.success());
        if !completed {
            restore_previous_cli(&self.paths.managed_cli, &previous)?;
            return Err(
                "the release-bound CLI did not complete; the previous CLI was restored".into(),
            );
        }
        remove_regular_if_present(&previous)?;
        ensure_public_cli(&self.paths)?;
        Ok(true)
    }

    fn backup_current(&self) -> Result<Backup, String> {
        let compose = self.paths.compose.with_extension("previous");
        let environment = self.paths.environment.with_extension("previous");
        fs::copy(&self.paths.compose, &compose).map_err(io_error)?;
        fs::copy(&self.paths.environment, &environment).map_err(io_error)?;
        Ok(Backup {
            compose,
            environment,
        })
    }

    fn rollback(
        &self,
        release: &ResolvedRelease,
        space_id: &str,
        backup: Option<Backup>,
    ) -> Result<String, String> {
        let _ = self
            .engine
            .compose(&self.paths, ["down", "--remove-orphans"]);
        let Some(backup) = backup else {
            return match self.compensate_fresh_failure(space_id) {
                Ok(()) => Err(
                    "the fresh Local release did not become healthy; its partial state was removed, so installation can be retried"
                        .into(),
                ),
                Err(cleanup) => Err(format!(
                    "the fresh Local release did not become healthy; compensation also failed: {cleanup}"
                )),
            };
        };
        let memory_error = state::remember_failed_release(&self.paths, release).err();
        fs::rename(&backup.compose, &self.paths.compose).map_err(io_error)?;
        fs::rename(&backup.environment, &self.paths.environment).map_err(io_error)?;
        let installed = state::read_installed(&self.paths, self.profile)?;
        match self.ensure_storage(&installed.space_id, false, self.scheduled)? {
            linux::Admission::Verified => {}
            linux::Admission::Locked => {
                state::write_status(&self.paths, release, "rollback-needed")?;
                if memory_error.is_some() {
                    scheduler::remove(self.profile, &self.paths)?;
                    return Err(
                        "the previous release remained stopped because storage was locked, and automatic updates were disabled because the failed release could not be remembered"
                            .into(),
                    );
                }
                return Err(
                    "the update failed; the previous release remained stopped because encrypted storage was locked"
                        .into(),
                );
            }
        }
        let restored = self.engine.compose(
            &self.paths,
            [
                "up",
                "-d",
                "--wait",
                "--wait-timeout",
                "120",
                "--no-build",
                "--pull",
                "never",
                "--remove-orphans",
            ],
        )?;
        let status = state::write_status(&self.paths, release, "rollback-needed")?;
        if restored.success()
            && self
                .engine
                .project_release_status(&release.metadata.admin, status.as_bytes())
                .is_err()
        {
            output::warning(
                "the previous release was restored, but Admin could not receive the rollback status",
            );
        }
        if memory_error.is_some() {
            scheduler::remove(self.profile, &self.paths)?;
            return Err(
                "the previous release was restored, but automatic updates were disabled because the failed release could not be remembered"
                    .into(),
            );
        }
        if restored.success() {
            Err("the update failed; the previous healthy release was restored".into())
        } else {
            Err("the update and its rollback both failed".into())
        }
    }

    fn compensate_fresh_failure(&self, space_id: &str) -> Result<(), String> {
        let inventory = Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        inventory.remove(&self.engine)?;
        let remaining = Inventory::inspect(&self.engine, &self.paths, self.profile.storage())?;
        if !remaining.empty() {
            return Err("managed Docker residue remains after fresh-install compensation".into());
        }
        if self.profile == HostProfile::Linux && self.paths.security.exists() {
            linux::reset(&self.paths, Some(space_id))?;
        }
        self.remove_runtime_files()
    }

    fn start_admin_for_reset(&self) -> Result<(), String> {
        self.start_container_if_present("shimpz-team")?;
        let mut attestation = self.admin_attestation()?;
        if attestation == AdminAttestation::Stopped {
            let status = self.engine.run_status(["start", "shimpz-admin"])?;
            if !status.success() {
                return Err("the owned Admin container could not be started".into());
            }
            attestation = self.admin_attestation()?;
        }
        let expected = state::read_installed(&self.paths, self.profile)?.port;
        if attestation == (AdminAttestation::Running { port: expected })
            && admin_available(expected)
        {
            return Ok(());
        }
        Err("the Local Supervisor is unavailable; run shimpz install for bounded recovery".into())
    }

    fn prepare_admin_for_recovery(&self) -> Result<AdminAttestation, String> {
        let mut attestation = self.admin_attestation()?;
        if attestation == AdminAttestation::Absent {
            return Ok(attestation);
        }
        if self.start_container_if_present("shimpz-team").is_err() {
            output::info(
                "Admin could not be started; confirmed recovery will use owned-resource cleanup.",
            );
            return Ok(AdminAttestation::Stopped);
        }
        if attestation == AdminAttestation::Stopped {
            let started = self
                .engine
                .run_status(["start", "shimpz-admin"])
                .is_ok_and(|status| status.success());
            if !started {
                output::info(
                    "Admin could not be started; confirmed recovery will use owned-resource cleanup.",
                );
                return Ok(AdminAttestation::Stopped);
            }
            attestation = self.admin_attestation()?;
        }
        Ok(attestation)
    }

    fn start_container_if_present(&self, name: &str) -> Result<(), String> {
        let state = self.engine.run_output([
            "inspect",
            "--type=container",
            "--format",
            "{{.State.Running}}",
            name,
        ]);
        match state.as_deref().map(str::trim) {
            Err(_) | Ok("true") => Ok(()),
            Ok("false") => {
                let status = self.engine.run_status(["start", name])?;
                if status.success() {
                    Ok(())
                } else {
                    Err(format!("the owned container could not be started: {name}"))
                }
            }
            Ok(_) => Err(format!("the owned container state is malformed: {name}")),
        }
    }

    fn admin_attestation(&self) -> Result<AdminAttestation, String> {
        let record = self.engine.run_output([
            "inspect",
            "--type=container",
            "--format",
            "{{.State.Running}}|{{index .Config.Labels \"com.docker.compose.project\"}}|{{index .Config.Labels \"com.docker.compose.service\"}}|{{json .HostConfig.PortBindings}}",
            "shimpz-admin",
        ]);
        match record {
            Ok(record) => parse_admin_attestation(&record),
            Err(_) => Ok(AdminAttestation::Absent),
        }
    }

    fn remove_runtime_files(&self) -> Result<(), String> {
        for path in [
            &self.paths.compose,
            &self.paths.environment,
            &self.paths.status,
            &self.paths.failed_release,
            &self.paths.compose.with_extension("previous"),
            &self.paths.environment.with_extension("previous"),
            &self.paths.compose.with_extension("tmp"),
            &self.paths.environment.with_extension("tmp"),
            &self.paths.status.with_extension("tmp"),
            &self.paths.failed_release.with_extension("tmp"),
            &self.paths.marker.with_extension("tmp"),
            &self.paths.marker,
        ] {
            remove_regular_if_present(path)?;
        }
        Ok(())
    }

    fn remove_files(&self) -> Result<Vec<String>, String> {
        self.remove_runtime_files()?;
        remove_regular_if_present(&self.paths.managed_cli.with_extension("candidate"))?;
        remove_regular_if_present(&self.paths.managed_cli.with_extension("previous"))?;
        let mut preserved = Vec::new();
        if self.paths.home.exists() {
            for entry in fs::read_dir(&self.paths.home).map_err(io_error)? {
                let path = entry.map_err(io_error)?.path();
                if path
                    == self
                        .paths
                        .managed_cli
                        .parent()
                        .expect("managed CLI has a parent")
                {
                    validate_unmarked_bin(&self.paths)?;
                } else {
                    preserved.push(path.display().to_string());
                }
            }
        }
        Ok(preserved)
    }
}

fn release_outcome(release: &ResolvedRelease, installed: Option<&Installed>) -> &'static str {
    if installed.is_some_and(|current| current.release_ref == release.reference) {
        "current"
    } else {
        "updated"
    }
}

fn reset_outcome(already_reset: bool, preserved: &[String]) -> String {
    let action = if already_reset {
        "Shimpz Space was already reset."
    } else {
        "Shimpz Space was reset successfully."
    };
    let suffix = if preserved.is_empty() {
        "No managed Space data remains; the shimpz command and lifecycle lock are retained."
            .to_owned()
    } else {
        format!("Preserved unrecognized content: {}", preserved.join(", "))
    };
    format!("{action} {suffix}")
}

#[derive(Debug)]
struct Backup {
    compose: PathBuf,
    environment: PathBuf,
}

fn ensure_install_home(paths: &Paths) -> Result<(), String> {
    if paths.home.exists() {
        let metadata = paths.home.symlink_metadata().map_err(io_error)?;
        if metadata.file_type().is_symlink()
            || !metadata.is_dir()
            || metadata.uid() != rustix::process::getuid().as_raw()
            || metadata.permissions().mode() & 0o077 != 0
        {
            return Err("refusing to use an invalid Local Space directory".into());
        }
        if !paths.marker.exists() {
            for temporary in [
                paths.home.join("release.env.tmp"),
                paths.marker.with_extension("tmp"),
            ] {
                remove_regular_if_present(&temporary)?;
            }
            for entry in fs::read_dir(&paths.home).map_err(io_error)? {
                let path = entry.map_err(io_error)?.path();
                if path
                    != paths
                        .managed_cli
                        .parent()
                        .expect("managed CLI has a parent")
                {
                    return Err(format!(
                        "refusing to use existing unowned directory: {}",
                        paths.home.display()
                    ));
                }
            }
            validate_unmarked_bin(paths)?;
        }
    } else {
        fs::create_dir(&paths.home).map_err(io_error)?;
        fs::set_permissions(&paths.home, fs::Permissions::from_mode(0o700)).map_err(io_error)?;
    }
    Ok(())
}

fn validate_unmarked_bin(paths: &Paths) -> Result<(), String> {
    let bin = paths
        .managed_cli
        .parent()
        .expect("managed CLI has a parent");
    if !bin.exists() {
        return Ok(());
    }
    let metadata = bin.symlink_metadata().map_err(io_error)?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err("the managed CLI directory is invalid".into());
    }
    for entry in fs::read_dir(bin).map_err(io_error)? {
        let path = entry.map_err(io_error)?.path();
        if path != paths.managed_cli
            && path != paths.managed_cli.with_extension("candidate")
            && path != paths.managed_cli.with_extension("previous")
        {
            return Err("the unmarked managed CLI directory contains unrecognized content".into());
        }
        let metadata = path.symlink_metadata().map_err(io_error)?;
        if metadata.file_type().is_symlink() || !metadata.is_file() {
            return Err("the managed CLI artifact is invalid".into());
        }
        if metadata.uid() != rustix::process::getuid().as_raw()
            || metadata.permissions().mode() & 0o077 != 0
        {
            return Err("the managed CLI artifact ownership or permissions are invalid".into());
        }
    }
    Ok(())
}

fn validate_private_cli(path: &Path) -> Result<(), String> {
    let metadata = path.symlink_metadata().map_err(io_error)?;
    if metadata.file_type().is_symlink()
        || !metadata.is_file()
        || metadata.uid() != rustix::process::getuid().as_raw()
        || metadata.permissions().mode() & 0o077 != 0
    {
        return Err("the managed CLI artifact ownership or permissions are invalid".into());
    }
    Ok(())
}

fn restore_previous_cli(managed: &Path, previous: &Path) -> Result<(), String> {
    remove_regular_if_present(managed)?;
    if previous.exists() {
        fs::rename(previous, managed).map_err(io_error)?;
    }
    Ok(())
}

fn reconcile_previous_cli(managed: &Path, running: &Path) -> Result<(), String> {
    let previous = managed.with_extension("previous");
    if !previous.exists() {
        return Ok(());
    }
    validate_private_cli(&previous)?;
    if !managed.exists() {
        fs::rename(previous, managed).map_err(io_error)?;
        return Ok(());
    }
    validate_private_cli(managed)?;
    if hash_file(managed)? != hash_file(running)? {
        return Err(
            "an interrupted CLI handoff remains; run the managed ~/.shimpz/bin/shimpz command directly"
                .into(),
        );
    }
    remove_regular_if_present(&previous)
}

fn ensure_public_cli(paths: &Paths) -> Result<(), String> {
    if paths.public_cli.exists() {
        let metadata = paths.public_cli.symlink_metadata().map_err(io_error)?;
        if metadata.file_type().is_symlink()
            && fs::read_link(&paths.public_cli).map_err(io_error)? == paths.managed_cli
        {
            return Ok(());
        }
        return Err("refusing to replace an unowned public shimpz command".into());
    }
    let parent = paths
        .public_cli
        .parent()
        .ok_or_else(|| "the public CLI directory is invalid".to_owned())?;
    if parent.exists() {
        let metadata = parent.symlink_metadata().map_err(io_error)?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            return Err("the public CLI directory is invalid".into());
        }
    } else {
        fs::create_dir_all(parent).map_err(io_error)?;
    }
    symlink(&paths.managed_cli, &paths.public_cli).map_err(io_error)
}

fn parse_admin_attestation(record: &str) -> Result<AdminAttestation, String> {
    if record.len() > 4_096 || record.contains('\r') {
        return Err("the owned Admin listener attestation is malformed".into());
    }
    let mut lines = record.lines();
    let line = lines
        .next()
        .filter(|line| !line.is_empty() && lines.next().is_none())
        .ok_or_else(|| "the owned Admin listener attestation is malformed".to_owned())?;
    let fields: Vec<_> = line.splitn(4, '|').collect();
    if fields.len() != 4 || fields[1] != "shimpz-space" || fields[2] != "admin" {
        return Err("the owned Admin listener identity is invalid".into());
    }
    let binding_map = serde_json::from_str::<serde_json::Value>(fields[3])
        .map_err(|_| "the owned Admin listener binding is malformed".to_owned())?;
    let binding_map = binding_map
        .as_object()
        .filter(|bindings| bindings.len() == 1 && bindings.contains_key("4600/tcp"))
        .ok_or_else(|| "the owned Admin listener binding is invalid".to_owned())?;
    let bindings = binding_map["4600/tcp"]
        .as_array()
        .filter(|bindings| !bindings.is_empty() && bindings.len() <= 2)
        .ok_or_else(|| "the owned Admin listener binding is invalid".to_owned())?;
    let mut port = None;
    let mut ipv4 = false;
    for binding in bindings {
        let binding = binding
            .as_object()
            .filter(|binding| {
                binding.len() == 2
                    && binding.contains_key("HostIp")
                    && binding.contains_key("HostPort")
            })
            .ok_or_else(|| "the owned Admin listener binding is malformed".to_owned())?;
        let host = binding["HostIp"]
            .as_str()
            .filter(|host| matches!(*host, "127.0.0.1" | "::1"))
            .ok_or_else(|| "the owned Admin listener is not loopback-only".to_owned())?;
        let current = binding["HostPort"]
            .as_str()
            .and_then(|value| value.parse::<u16>().ok())
            .filter(|value| *value >= 1024)
            .ok_or_else(|| "the owned Admin listener port is invalid".to_owned())?;
        if port.is_some_and(|expected| expected != current) || (host == "127.0.0.1" && ipv4) {
            return Err("the owned Admin listener binding is ambiguous".into());
        }
        port = Some(current);
        ipv4 |= host == "127.0.0.1";
    }
    if !ipv4 {
        return Err("the owned Admin listener has no IPv4 loopback binding".into());
    }
    match fields[0] {
        "true" => Ok(AdminAttestation::Running {
            port: port.expect("a valid binding has a port"),
        }),
        "false" => Ok(AdminAttestation::Stopped),
        _ => Err("the owned Admin container state is malformed".into()),
    }
}

fn validate_forward_release(
    release: &ResolvedRelease,
    installed: Option<&Installed>,
) -> Result<(), String> {
    let Some(installed) = installed else {
        return Ok(());
    };
    if release.metadata.ordinal < installed.ordinal
        || (release.metadata.ordinal == installed.ordinal
            && release.reference != installed.release_ref)
    {
        return Err("the Local release channel moved backward or became ambiguous".into());
    }
    Ok(())
}

fn expected_cli_hash(release: &ResolvedRelease, profile: HostProfile) -> &str {
    match profile {
        HostProfile::Linux | HostProfile::Wsl => &release.metadata.cli_linux_amd64_sha256,
        HostProfile::MacOs => &release.metadata.cli_macos_arm64_sha256,
    }
}

fn verify_running_cli(release: &ResolvedRelease, profile: HostProfile) -> Result<(), String> {
    let current = std::env::current_exe().map_err(|_| "the running CLI path is unavailable")?;
    if hash_file(&current)? == expected_cli_hash(release, profile) {
        Ok(())
    } else {
        Err("the running CLI is not bound to the selected Local release".into())
    }
}

fn hash_file(path: &Path) -> Result<String, String> {
    let mut file = fs::File::open(path).map_err(io_error)?;
    let mut hasher = Sha256::new();
    let mut buffer = vec![0_u8; 16 * 1024];
    loop {
        let count = file.read(&mut buffer).map_err(io_error)?;
        if count == 0 {
            break;
        }
        hasher.update(&buffer[..count]);
    }
    Ok(format!("{:x}", hasher.finalize()))
}

fn recovery_prompt(reason: &str, inventory: &Inventory, names: &[String]) -> Result<bool, String> {
    let mut tty = OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/tty")
        .map_err(|_| "recovery requires an interactive terminal; nothing changed".to_owned())?;
    writeln!(tty, "The existing Local Space is corrupt: {reason}").map_err(io_error)?;
    writeln!(
        tty,
        "Owned scope: {} containers, {} volumes, {} networks",
        inventory.project_containers.len() + inventory.dynamic_containers.len(),
        inventory.project_volumes.len(),
        inventory.project_networks.len() + inventory.dynamic_networks.len()
    )
    .map_err(io_error)?;
    if !names.is_empty() {
        writeln!(tty, "Containers: {}", names.join(", ")).map_err(io_error)?;
    }
    loop {
        write!(
            tty,
            "Permanently remove this exact owned state and install a fresh Space? [Yes/No] "
        )
        .map_err(io_error)?;
        tty.flush().map_err(io_error)?;
        let mut answer = String::new();
        let mut byte = [0_u8; 1];
        while tty.read(&mut byte).map_err(io_error)? == 1 {
            if byte[0] == b'\n' {
                break;
            }
            if answer.len() >= 8 || byte[0].is_ascii_control() {
                return Err("the recovery answer is invalid; nothing changed".into());
            }
            answer.push(char::from(byte[0]));
        }
        match answer.as_str() {
            "Yes" => return Ok(true),
            "No" | "" => return Ok(false),
            _ => writeln!(tty, "Please answer exactly Yes or No.").map_err(io_error)?,
        }
    }
}

fn admin_available(port: u16) -> bool {
    let config = Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(2)))
        .max_redirects(0)
        .http_status_as_error(false)
        .build();
    let agent = Agent::new_with_config(config);
    for _ in 0..30 {
        if agent
            .post(format!("http://127.0.0.1:{port}/api/session"))
            .send_empty()
            .is_ok_and(|response| response.status().as_u16() == 200)
        {
            return true;
        }
        thread::sleep(Duration::from_millis(500));
    }
    false
}

fn authenticated_admin_reset(port: u16) -> Result<(), String> {
    let password = Zeroizing::new(
        rpassword::prompt_password("Supervisor password: ")
            .map_err(|_| "could not read the Supervisor password".to_owned())?,
    );
    if password.is_empty() {
        return Err("the Supervisor password is required".into());
    }
    let config = Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(30)))
        .max_redirects(0)
        .http_status_as_error(false)
        .build();
    let agent = Agent::new_with_config(config);
    let url = format!("http://127.0.0.1:{port}");
    let login = agent
        .post(format!("{url}/api/login"))
        .send_json(serde_json::json!({"password": password.as_str()}))
        .map_err(|_| "the Local Supervisor login is unavailable".to_owned())?;
    if login.status().as_u16() != 200 {
        return Err("the Supervisor password was rejected".into());
    }
    let cookie = login
        .headers()
        .get("set-cookie")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split(';').next())
        .filter(|value| value.starts_with("shimpz_admin="))
        .ok_or_else(|| "Admin returned an invalid Supervisor session".to_owned())?;
    let reset_body = serde_json::to_string(&serde_json::json!({"password": password.as_str()}))
        .map_err(|_| "could not encode the authenticated reset".to_owned())?;
    let request = ureq::http::Request::delete(format!("{url}/api/space"))
        .header("Cookie", cookie)
        .header("Content-Type", "application/json")
        .body(reset_body)
        .map_err(|_| "could not build the authenticated reset".to_owned())?;
    let mut response = agent
        .run(request)
        .map_err(|_| "the authenticated Space reset is unavailable".to_owned())?;
    if response.status().as_u16() != 200 {
        return Err("the authenticated Space reset did not complete".into());
    }
    let body: serde_json::Value = response
        .body_mut()
        .with_config()
        .limit(1_024)
        .read_json()
        .map_err(|_| "Admin returned an invalid Space reset response".to_owned())?;
    if body.as_object().is_some_and(|object| {
        object.len() == 1 && object.get("reset") == Some(&serde_json::Value::Bool(true))
    }) {
        Ok(())
    } else {
        Err("Admin returned an invalid Space reset response".into())
    }
}

fn remove_backup(backup: Option<Backup>) -> Result<(), String> {
    if let Some(backup) = backup {
        fs::remove_file(backup.compose).map_err(io_error)?;
        fs::remove_file(backup.environment).map_err(io_error)?;
    }
    Ok(())
}

fn remove_regular_if_present(path: &Path) -> Result<(), String> {
    if !path.exists() {
        return Ok(());
    }
    let metadata = path.symlink_metadata().map_err(io_error)?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(format!(
            "refusing to remove invalid managed file: {}",
            path.display()
        ));
    }
    fs::remove_file(path).map_err(io_error)
}

fn io_error(error: std::io::Error) -> String {
    let message = format!("Local lifecycle operation failed: {error}");
    drop(error);
    message
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::space::release::Release;

    const HEX: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    fn release(ordinal: u64, digest: char) -> ResolvedRelease {
        ResolvedRelease {
            reference: format!(
                "ghcr.io/theshimpz/shimpz-local-release@sha256:{}",
                digest.to_string().repeat(64)
            ),
            metadata: Release {
                ordinal,
                umbrella_revision: "a".repeat(40),
                cli_revision: "b".repeat(40),
                cli_linux_amd64_sha256: HEX.into(),
                cli_macos_arm64_sha256: HEX.into(),
                admin: format!("ghcr.io/theshimpz/shimpz-admin@sha256:{HEX}"),
                team: format!("ghcr.io/theshimpz/shimpz-team-local@sha256:{HEX}"),
                brain: format!("ghcr.io/theshimpz/shimpz-brain@sha256:{HEX}"),
                egress: format!("ghcr.io/theshimpz/shimpz-egress@sha256:{HEX}"),
            },
        }
    }

    #[test]
    fn admits_only_monotonic_unambiguous_releases() {
        let installed = Installed {
            space_id: "space-0123456789abcdef01234567".into(),
            release_ref: release(2, 'b').reference,
            ordinal: 2,
            port: 7777,
        };
        assert!(validate_forward_release(&release(3, 'c'), Some(&installed)).is_ok());
        assert!(validate_forward_release(&release(2, 'b'), Some(&installed)).is_ok());
        assert!(validate_forward_release(&release(1, 'a'), Some(&installed)).is_err());
        assert!(validate_forward_release(&release(2, 'c'), Some(&installed)).is_err());
        assert!(validate_forward_release(&release(1, 'a'), None).is_ok());
    }

    #[test]
    fn reports_fresh_and_changed_releases_as_updated() {
        let current = release(2, 'b');
        let installed = Installed {
            space_id: "space-0123456789abcdef01234567".into(),
            release_ref: current.reference.clone(),
            ordinal: 2,
            port: 7777,
        };
        assert_eq!(release_outcome(&current, Some(&installed)), "current");
        assert_eq!(
            release_outcome(&release(3, 'c'), Some(&installed)),
            "updated"
        );
        assert_eq!(release_outcome(&release(1, 'a'), None), "updated");
    }

    #[test]
    fn reset_outcomes_are_positive_and_report_preserved_content() {
        assert_eq!(
            reset_outcome(true, &[]),
            "Shimpz Space was already reset. No managed Space data remains; the shimpz command and lifecycle lock are retained."
        );
        assert_eq!(
            reset_outcome(false, &["/home/ada/.shimpz/notes".to_owned()]),
            "Shimpz Space was reset successfully. Preserved unrecognized content: /home/ada/.shimpz/notes"
        );
    }

    #[test]
    fn accepts_only_an_attested_loopback_admin_listener() {
        assert_eq!(
            parse_admin_attestation(
                "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}]}\n"
            ),
            Ok(AdminAttestation::Running { port: 7777 })
        );
        assert_eq!(
            parse_admin_attestation(
                "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"},{\"HostIp\":\"::1\",\"HostPort\":\"7777\"}]}\n"
            ),
            Ok(AdminAttestation::Running { port: 7777 })
        );
        assert_eq!(
            parse_admin_attestation(
                "false|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}]}\n"
            ),
            Ok(AdminAttestation::Stopped)
        );
        for invalid in [
            "true|foreign|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}]}",
            "true|shimpz-space|team|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}]}",
            "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"0.0.0.0\",\"HostPort\":\"7777\"}]}",
            "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"::1\",\"HostPort\":\"7777\"}]}",
            "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"80\"}]}",
            "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"},{\"HostIp\":\"::1\",\"HostPort\":\"8888\"}]}",
            "true|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}],\"80/tcp\":[]}",
            "true|shimpz-space|admin|null",
            "true|shimpz-space|admin|{}",
            "maybe|shimpz-space|admin|{\"4600/tcp\":[{\"HostIp\":\"127.0.0.1\",\"HostPort\":\"7777\"}]}",
        ] {
            assert!(parse_admin_attestation(invalid).is_err(), "{invalid}");
        }
    }

    #[test]
    fn unmarked_home_accepts_only_private_managed_cli_artifacts() {
        let home = tempfile::tempdir().unwrap();
        let paths = Paths::under(home.path()).unwrap();
        fs::create_dir(&paths.home).unwrap();
        fs::set_permissions(&paths.home, fs::Permissions::from_mode(0o700)).unwrap();
        fs::create_dir(paths.managed_cli.parent().unwrap()).unwrap();
        fs::write(paths.managed_cli.with_extension("candidate"), "candidate").unwrap();
        fs::set_permissions(
            paths.managed_cli.with_extension("candidate"),
            fs::Permissions::from_mode(0o700),
        )
        .unwrap();
        assert!(ensure_install_home(&paths).is_ok());
        fs::write(
            paths.managed_cli.parent().unwrap().join("foreign"),
            "foreign",
        )
        .unwrap();
        assert!(ensure_install_home(&paths).is_err());
    }

    #[test]
    fn unmarked_home_reconciles_only_pre_marker_temporaries() {
        let home = tempfile::tempdir().unwrap();
        let paths = Paths::under(home.path()).unwrap();
        fs::create_dir(&paths.home).unwrap();
        fs::set_permissions(&paths.home, fs::Permissions::from_mode(0o700)).unwrap();
        let release_temporary = paths.home.join("release.env.tmp");
        let marker_temporary = paths.marker.with_extension("tmp");
        fs::write(&release_temporary, "metadata").unwrap();
        fs::write(&marker_temporary, "marker").unwrap();
        ensure_install_home(&paths).unwrap();
        assert!(!release_temporary.exists());
        assert!(!marker_temporary.exists());
    }

    #[test]
    fn public_command_is_only_the_exact_managed_symlink() {
        let home = tempfile::tempdir().unwrap();
        let paths = Paths::under(home.path()).unwrap();
        fs::create_dir_all(paths.managed_cli.parent().unwrap()).unwrap();
        fs::write(&paths.managed_cli, "managed").unwrap();
        ensure_public_cli(&paths).unwrap();
        assert_eq!(fs::read_link(&paths.public_cli).unwrap(), paths.managed_cli);
        assert!(ensure_public_cli(&paths).is_ok());
        fs::remove_file(&paths.public_cli).unwrap();
        fs::write(&paths.public_cli, "foreign").unwrap();
        assert!(ensure_public_cli(&paths).is_err());
    }

    #[test]
    fn candidate_activation_restores_the_previous_private_cli() {
        let home = tempfile::tempdir().unwrap();
        let paths = Paths::under(home.path()).unwrap();
        fs::create_dir_all(paths.managed_cli.parent().unwrap()).unwrap();
        let previous = paths.managed_cli.with_extension("previous");
        fs::write(&paths.managed_cli, "candidate").unwrap();
        fs::write(&previous, "previous").unwrap();
        restore_previous_cli(&paths.managed_cli, &previous).unwrap();
        assert_eq!(fs::read_to_string(&paths.managed_cli).unwrap(), "previous");
        assert!(!previous.exists());
    }

    #[test]
    fn reconciles_only_a_previous_artifact_for_the_running_managed_cli() {
        let home = tempfile::tempdir().unwrap();
        let paths = Paths::under(home.path()).unwrap();
        fs::create_dir_all(paths.managed_cli.parent().unwrap()).unwrap();
        let previous = paths.managed_cli.with_extension("previous");
        fs::write(&paths.managed_cli, "current").unwrap();
        fs::write(&previous, "previous").unwrap();
        fs::set_permissions(&paths.managed_cli, fs::Permissions::from_mode(0o700)).unwrap();
        fs::set_permissions(&previous, fs::Permissions::from_mode(0o700)).unwrap();
        reconcile_previous_cli(&paths.managed_cli, &paths.managed_cli).unwrap();
        assert!(!previous.exists());

        fs::remove_file(&paths.managed_cli).unwrap();
        fs::write(&previous, "restored").unwrap();
        fs::set_permissions(&previous, fs::Permissions::from_mode(0o700)).unwrap();
        reconcile_previous_cli(&paths.managed_cli, &paths.managed_cli).unwrap();
        assert_eq!(fs::read_to_string(&paths.managed_cli).unwrap(), "restored");

        fs::write(&previous, "previous").unwrap();
        fs::set_permissions(&previous, fs::Permissions::from_mode(0o700)).unwrap();
        let other = paths.managed_cli.parent().unwrap().join("other");
        fs::write(&other, "other").unwrap();
        assert!(reconcile_previous_cli(&paths.managed_cli, &other).is_err());
        assert!(previous.exists());
    }
}