devsandbox 0.11.1

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
use std::collections::BTreeMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// A running (or previously started) sandbox instance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Instance {
    /// Sandbox config name from devsandboxes.toml.
    pub sandbox: String,
    /// Persistent identity: the instance's name at creation, unique across all
    /// instances and never changed by `rename` (which only moves the state
    /// key). Everything host- or runtime-addressed keys off this — `${instance}`
    /// in mounts/branches, the container name, isolated services/networks,
    /// managed shell history — so a rename never moves per-instance state.
    /// Backfilled to the state key by [`State::load`] for pre-upgrade entries.
    #[serde(default)]
    pub instance_id: String,
    /// Config-root id (see `services::project_id`); scopes this instance's
    /// isolated services and networks so `rm` can find them without the dir.
    #[serde(default)]
    pub project: String,
    /// Docker container name (prefixed).
    pub container: String,
    /// Absolute path of the mounted project folder on the host (the worktree
    /// path for worktree instances, otherwise the base folder).
    pub folder: PathBuf,
    /// Absolute path of the base repo folder this instance derives from. Equals
    /// `folder` for the first instance; differs when `worktree` is set.
    #[serde(default)]
    pub base_folder: PathBuf,
    /// Git worktree path, when this instance runs against a worktree rather than
    /// the base folder directly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktree: Option<PathBuf>,
    /// Git branch created for this instance's worktree, recorded so `rm` deletes
    /// exactly the branch `run` created even if the config changed since. Only
    /// set for worktree instances.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// Whether `run` created `branch` (false when the worktree reused an
    /// existing local branch or one tracking `origin/<branch>`), so `rm` only
    /// offers to delete branches devsandbox made. Defaults to true: entries
    /// from before reuse existed always had a created branch.
    #[serde(default = "yes", skip_serializing_if = "is_true")]
    pub branch_created: bool,
    /// Every `folders` entry as mounted (direct binds included), recorded so
    /// the ownership rule (docs/architecture/instances/worktrees.md) sees other instances'
    /// direct extra mounts and `rm` removes exactly the extra worktrees `run`
    /// created. Empty for pre-upgrade instances until they're rebuilt.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub folders: Vec<FolderMount>,
    /// Host path of this instance's managed `.zsh_history` (inside the
    /// per-instance history dir bind-mounted at `/commandhistory`), when
    /// `persist-shell-history` is on. Kept on `rm` so a rebuilt instance with
    /// the same name inherits its history.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shell_history: Option<PathBuf>,
    /// Workspace folder inside the container.
    pub workspace: String,
    /// Container path of the generated `.code-workspace` file, when one was
    /// written for this instance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_file: Option<String>,
    /// devcontainer `remoteEnv`, applied to every exec in the container.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub remote_env: BTreeMap<String, String>,
    /// The user every exec runs as (`-u`), when set: the identity plan's exec
    /// user (`identity::Plan::exec_user`; docs/architecture/instances/identity.md),
    /// decided at create. Instances from before identity carry the config's
    /// `remoteUser` until rebuilt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_user: Option<String>,
    /// `HOME` for every exec: the adopted account's home on plans that exec
    /// as root with that home (`identity::Plan::root_home`, rootless docker),
    /// as `devsbd identity apply` reported it. Unset elsewhere: the exec
    /// user's own home applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub home: Option<String>,
    /// What `devsbd userns check` found after create: whether Chromium's
    /// sandbox can work here (docs/architecture/instances/identity.md, *Tool
    /// environment*). `None` = unknown: no helper, a helper too old for the
    /// check, or an instance from before it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub browser_sandbox: Option<crate::commands::run::BrowserSandbox>,
    /// The env every exec gets from the plan and `browser_sandbox`
    /// (`commands::run::tool_env`): the sandbox-off knobs, or the opt-in
    /// `DEVSANDBOX_BROWSER_SANDBOX`, and root silencers. Below everything
    /// else in [`Instance::exec_env`]. Empty for instances from before it.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tool_env: BTreeMap<String, String>,
    /// Container path of the forwarded ssh-agent socket, set when `run`
    /// mounted the host agent (see docs/architecture/helper/ssh-agent.md); `exec_argv` uses it
    /// to inject `SSH_AUTH_SOCK` per exec.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ssh_auth_sock: Option<String>,
    /// Arch of the devsbd helper that ran in this container (see
    /// docs/architecture/helper/overview.md); `None` = helper unavailable. Tried first on
    /// the next install so emulated images skip the host-arch attempt.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub devsbd_arch: Option<crate::devsbd::Arch>,
    /// Why the last helper install failed (`devsbd::install`'s note), set
    /// with `devsbd_arch = None` and cleared once it works: the note
    /// otherwise only reaches that one command's stderr.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub devsbd_error: Option<String>,
    /// Per-instance named volumes (sources using `${instance}` /
    /// `${devcontainerId}`, e.g. docker-in-docker's `/var/lib/docker`),
    /// recorded so `rm` deletes exactly these even if the config changed since.
    /// Accumulated across rebuilds, which keep them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub volumes: Vec<String>,
    /// Bind sources `run` created for this instance alone (sources using
    /// `${instance}` / `${devcontainerId}`, e.g. a feature's
    /// `${sharedVolumes}/<name>/${instance}`), canonical, so `rm` deletes
    /// them (`commands::rm::remove_bind_dirs`). Never one that existed
    /// before. Accumulated across rebuilds, like [`Instance::volumes`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bind_dirs: Vec<PathBuf>,
    /// `instance_id` of the dispatcher that created this instance through the
    /// control API (docs/architecture/automations/dispatchers.md); also the container's
    /// `devsandbox.dispatcher` label. `None` for user-created instances.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dispatcher: Option<String>,
    /// The profile this instance is in (docs/architecture/instances/profiles.md),
    /// chosen at `run` (`commands::run::choose_profile`) and kept by
    /// `rebuild`. `None` when its sandbox allowed none at creation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    /// Canonical config root this instance was created from, so a request
    /// arriving with only the instance (the control API) can re-read its
    /// config. `None` for instances created before it was recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_dir: Option<PathBuf>,
    /// Extra `-e K=V` from `run --env` (a dispatcher's `ensure --env`),
    /// recorded so `rebuild` recreates the container with them. `ensure` on an
    /// existing child replaces them; every devsandbox exec applies the saved
    /// values ([`Instance::exec_env`]), so they take effect before a rebuild.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra_env: BTreeMap<String, String>,
    /// Host ports the daemon picked for this instance's `forwardPorts`, keyed by
    /// `ForwardPort::key` (`"8080:3000"` = 8081), so the instance gets the same
    /// ports every time and no other instance takes them while it's stopped.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub forwarded_ports: BTreeMap<String, u16>,
    /// Random, minted at create and kept by `rebuild`; a `run` after `rm`
    /// gets a new one, though `unique_instance_id` may hand it the same id
    /// (docs/plans/active/credential-broker.md, *Identity is the bridge*).
    /// `None` for instances created before it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub incarnation: Option<String>,
    /// The credential claims `run` wired, with their phantoms, broker
    /// listeners and phantom files (`credentials::instance`), kept by
    /// `rebuild`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub claims: Vec<crate::credentials::instance::InstanceClaim>,
    /// With intercept claims: the shared proxy port, the container's own
    /// proxy env and its CA trust (`credentials::instance::Intercept`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intercept: Option<crate::credentials::instance::Intercept>,
    /// The GitHub repo fence's recorded part: the `owner/repo`s of
    /// [`State::folder_remotes`] for its folder and `folders`, taken at
    /// `run`/`rebuild` and refreshed at `start`, so `access forget` reaches
    /// it there (docs/architecture/credentials/fence.md). The config's
    /// `access.github.repos` isn't in it: read per call.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub github_repos: Vec<String>,
    /// The notes the last `run`/`rebuild`/`start` printed (the identity
    /// summary, the browser sandbox, the GitHub fence, `warning:`/`note:`
    /// lines; `commands::run::notes`), replaced by each, a failed one's
    /// included, so the dashboard shows them once the build log scrolled by.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub build_notes: Vec<String>,
    /// git's command-scope env (`GIT_CONFIG_COUNT`/`_KEY_<n>`/`_VALUE_<n>`)
    /// for every exec, when `remoteEnv` or `--env` set some of it: theirs
    /// merged ahead of a git-host claim's settings, which they'd otherwise
    /// replace (docs/architecture/credentials/git.md). Empty otherwise: the
    /// container's env carries it.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub git_env: BTreeMap<String, String>,
    /// Unix secs since the instance was marked done (docs/architecture/automations/dispatchers.md
    /// "Done children"): the user (or its dispatcher) is finished with it,
    /// but it's kept as is until removed. Only display and dispatcher policy
    /// read it; `start`/autostart leave it set. `None` = not done.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub done: Option<u64>,
    /// Set while a `run`/`rebuild` is materializing this instance, and kept
    /// when one fails from the container on (docs/architecture/instances/lifecycle.md). It's
    /// what lets `run` record the instance before any of its resources
    /// exist, so a failed or killed run leaves a record `rm` can find
    /// instead of an orphaned worktree, branch and services. `None` = ready.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub progress: Option<Progress>,
    pub created_unix: u64,
}

/// Where an in-flight (or failed) materialization is, and who's doing it.
/// Serialized flat (see [`ProgressToml`]) so it reads as one small table:
///
/// ```toml
/// [instance.web.progress]
/// phase = "lifecycle"
/// step = "postCreateCommand"
/// pid = 4242
/// boot = "3f2c…"
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(into = "ProgressToml", try_from = "ProgressToml")]
pub struct Progress {
    pub phase: Phase,
    /// The process doing the work: when it's gone the phase can't advance,
    /// so readers show it as interrupted (SIGKILL, OOM) without anyone
    /// rewriting the record.
    pub pid: u32,
    /// Host boot id when the phase was recorded: after a reboot `pid` may
    /// name an unrelated process, so a changed boot id means interrupted too.
    pub boot: Option<String>,
    /// The error a `Failed` phase failed with.
    pub error: Option<String>,
}

/// The materialization phases, in order (`Failed` aside).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Phase {
    /// Worktree, branch, `folders`, links, services.
    Preparing,
    /// The image.
    Building,
    /// The container.
    Creating,
    /// A lifecycle step (`onCreateCommand` … `postAttachCommand`, or
    /// `shell-rc` for the rc wiring), by name.
    Lifecycle(String),
    /// Failed at `at` (an in-flight phase's [`Phase::label`]); the error is
    /// [`Progress::error`].
    Failed { at: String },
}

impl Phase {
    /// What readers show for this phase; a lifecycle step shows as its name.
    pub fn label(&self) -> &str {
        match self {
            Phase::Preparing => "preparing",
            Phase::Building => "building",
            Phase::Creating => "creating",
            Phase::Lifecycle(step) => step,
            Phase::Failed { .. } => "failed",
        }
    }
}

/// What a reader shows for a [`Progress`], liveness and boot id applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PhaseView {
    /// Still being worked on: the phase's [`Phase::label`].
    InFlight(String),
    /// Failed (or interrupted) at `at`.
    Failed { at: String, error: String },
}

impl Progress {
    /// An in-flight phase whose process is dead, or that was recorded in an
    /// earlier boot, is interrupted: derived here at read time rather than
    /// written back, so no daemon (or later command) has to clean it up.
    /// `alive` and `boot` are injected to keep this pure.
    pub fn view(&self, alive: impl Fn(u32) -> bool, boot: Option<&str>) -> PhaseView {
        if let Phase::Failed { at } = &self.phase {
            return PhaseView::Failed {
                at: at.clone(),
                error: self.error.clone().unwrap_or_else(|| "failed".into()),
            };
        }
        let rebooted = matches!((self.boot.as_deref(), boot), (Some(then), Some(now)) if then != now);
        if rebooted || !alive(self.pid) {
            return PhaseView::Failed { at: self.phase.label().into(), error: "interrupted".into() };
        }
        PhaseView::InFlight(self.phase.label().into())
    }

    /// [`Progress::view`] against this host: real pid liveness, current boot.
    pub fn current_view(&self) -> PhaseView {
        self.view(pid_alive, crate::commands::autostart::boot_id().as_deref())
    }
}

/// Whether process `pid` exists. EPERM means it exists under another user.
/// Non-unix has no cheap probe, so it's assumed alive (never a false
/// "interrupted").
pub fn pid_alive(pid: u32) -> bool {
    #[cfg(unix)]
    {
        // 0 would probe our own process group, not a process.
        let Ok(pid @ 1..) = libc::pid_t::try_from(pid) else { return false };
        // SAFETY: signal 0 only checks for existence and permission.
        let ok = unsafe { libc::kill(pid, 0) } == 0;
        ok || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
    }
    #[cfg(not(unix))]
    {
        let _ = pid;
        true
    }
}

/// [`Progress`] as stored: `phase` names the variant, `step` carries a
/// lifecycle step's name or the label a `failed` phase failed at. Flat
/// scalars, so it's plain TOML whatever the variant (an externally tagged
/// enum would mix a string and tables under one key).
#[derive(Serialize, Deserialize)]
struct ProgressToml {
    phase: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    step: Option<String>,
    pid: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    boot: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

impl From<Progress> for ProgressToml {
    fn from(p: Progress) -> Self {
        let (phase, step) = match p.phase {
            Phase::Preparing => ("preparing", None),
            Phase::Building => ("building", None),
            Phase::Creating => ("creating", None),
            Phase::Lifecycle(step) => ("lifecycle", Some(step)),
            Phase::Failed { at } => ("failed", Some(at)),
        };
        ProgressToml { phase: phase.into(), step, pid: p.pid, boot: p.boot, error: p.error }
    }
}

impl TryFrom<ProgressToml> for Progress {
    type Error = String;

    /// Lenient on purpose: a bad `progress` would otherwise fail loading the
    /// whole `state.toml`, so a phase a newer binary added (or a missing
    /// `step`) reads as an in-flight step named after it, which the pid and
    /// boot checks in [`Progress::view`] still resolve.
    fn try_from(t: ProgressToml) -> Result<Self, String> {
        let step = |phase: &str| t.step.clone().unwrap_or_else(|| phase.to_string());
        let phase = match t.phase.as_str() {
            "preparing" => Phase::Preparing,
            "building" => Phase::Building,
            "creating" => Phase::Creating,
            "lifecycle" => Phase::Lifecycle(step("lifecycle")),
            "failed" => Phase::Failed { at: step("failed") },
            other => Phase::Lifecycle(other.to_string()),
        };
        Ok(Progress { phase, pid: t.pid, boot: t.boot, error: t.error })
    }
}

/// One `folders` entry of an instance: where it's mounted, the host folder it
/// derives from, and the detached worktree mounted instead, if any.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FolderMount {
    /// Container path.
    pub target: String,
    /// Canonical host folder the entry names.
    pub base: PathBuf,
    /// Detached worktree of `base` mounted at `target`; `None` = `base` is
    /// bind-mounted directly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktree: Option<PathBuf>,
}

fn yes() -> bool {
    true
}

fn is_true(b: &bool) -> bool {
    *b
}

impl Instance {
    pub fn now() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    }

    /// The env every devsandbox exec into this instance sets (CLI/TUI exec,
    /// dispatcher run ops, lifecycle commands, the boot file): the recorded
    /// `tool_env` and `home` as `HOME`, overlaid by `remoteEnv`, overlaid by
    /// `extra_env`. A `HOME` or knob the user sets wins over the plan's. The instance-specific value
    /// wins, as at `docker run` where `--env` comes after `containerEnv`; and
    /// the saved `extra_env` may be newer than the container's own env (an
    /// `ensure` replaced it), so it must override whatever the image or
    /// config set. `git_env` goes last: it already holds what those set of it.
    pub fn exec_env(&self) -> BTreeMap<String, String> {
        let mut env = self.tool_env.clone();
        env.extend(self.home.iter().map(|h| ("HOME".to_string(), h.clone())));
        env.extend(self.remote_env.iter().map(|(k, v)| (k.clone(), v.clone())));
        env.extend(self.extra_env.iter().map(|(k, v)| (k.clone(), v.clone())));
        env.extend(self.git_env.iter().map(|(k, v)| (k.clone(), v.clone())));
        env
    }

    /// Where this instance's materialization stands on this host
    /// ([`Progress::current_view`]); `None` = ready.
    pub fn phase_view(&self) -> Option<PhaseView> {
        self.progress.as_ref().map(Progress::current_view)
    }
}

/// Host-side runtime state, stored in the user data dir. This file, not the
/// daemon, is the truth (docs/decisions/0001-*): docker is the source of
/// truth for liveness, this only maps names to containers.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct State {
    #[serde(default, rename = "instance")]
    pub instances: BTreeMap<String, Instance>,
    /// Project id (`services::project_id`) -> host boot id of the last
    /// autostart pass for that config root, so autostart runs once per boot.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub autostart_boot: BTreeMap<String, String>,
    /// Project id (`services::project_id`) -> the identity findings
    /// (`config_identity::Finding::id`) the user chose to "continue as is"
    /// on: they leave the prompts and the header. Pruned of ids no longer
    /// among that root's findings on every write (`config_identity::ops::ack`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub identity_acks: BTreeMap<String, std::collections::BTreeSet<String>>,
    /// Project id -> `forwardPorts` entry key -> host port, for entries that
    /// forward a `global` service: one forward per config root however many
    /// instances declare it, so its port can't live on any one instance.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub global_forwarded_ports: BTreeMap<String, BTreeMap<String, u16>>,
    /// Project id (`services::project_id`) -> sandbox -> the profile last
    /// chosen for it with `run --profile` or switched to
    /// (`commands::profile::set_profile_at`): `run`'s default
    /// (`commands::run::choose_profile`). Never pruned, so it outlives the
    /// sandbox's last instance.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub last_profile: BTreeMap<String, BTreeMap<String, String>>,
    /// A repo's canonical common dir -> the origin URL host git fetches for
    /// it (`commands::run::fetch_trusted_origin`): pinned on the first fetch,
    /// so a sandbox rewriting `remote.origin.url` in its checkout can't point
    /// host git elsewhere. Moved only by `devsandbox trust-origin`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub trusted_origins: BTreeMap<String, String>,
    /// Runtime context key (`runtime::identity::context_key`) -> its probed
    /// user-namespace mode, so a context is probed once (until `--reprobe`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub identity_probes: BTreeMap<String, crate::runtime::identity::Probe>,
    /// Image id (`Backend::image_id`) -> what `run` reads from that image,
    /// so an image is read once: at most [`IMAGE_FACTS_CAP`] entries, the
    /// oldest dropped ([`State::remember_image_facts`]).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub image_facts: BTreeMap<String, ImageFacts>,
    /// Canonical host folder -> its remotes as its first `run` ever read
    /// them (`commands::run::remotes`): never re-read, since the folder is
    /// container-writable from then on, and kept past `rm`. Narrowed only
    /// by `devsandbox access forget`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub folder_remotes: BTreeMap<String, FolderRemotes>,
    /// GitHub repo fence entry (normalized `owner/repo`, from a folder's
    /// record or `access.github.repos`) -> the repository it named when the
    /// broker first resolved it (`broker::github`): a later owner of that
    /// name never matches it (docs/architecture/credentials/fence.md#ids).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub github_ids: BTreeMap<String, GithubPin>,
    /// Project id (`services::project_id`) -> feature update name -> its
    /// last run and the daemon's last attempt (`commands::update`,
    /// `serve::updates`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub updates: BTreeMap<String, BTreeMap<String, UpdateRecord>>,
}

/// One [`State::updates`] entry, unix seconds. Kept apart so a failed
/// attempt never moves the last success.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateRecord {
    /// The last successful run, by the verb or the daemon.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ok: Option<u64>,
    /// When the daemon last claimed a run, whatever came of it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tried: Option<u64>,
}

/// One [`State::github_ids`] pin.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GithubPin {
    pub id: u64,
    pub node_id: String,
    /// Unix seconds.
    #[serde(default)]
    pub pinned_at: u64,
}

/// One folder's [`State::folder_remotes`] record.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderRemotes {
    /// Every remote with a URL naming a network host, as `.git/config`
    /// spelled it (`credentials::fence::parse` keeps it).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub remotes: Vec<FolderRemote>,
    /// The GitHub fence: the `owner/repo` (normalized) each `remotes` URL
    /// names on github.com, ssh aliases resolved when recorded; sorted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub github: Vec<String>,
    /// Why the remotes couldn't be read (no git repo, a refused `.git`, an
    /// unparsable config): recorded empty all the same, never retried.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unread: Option<String>,
    /// Unix seconds ([`Instance::now`]).
    #[serde(default)]
    pub recorded_at: u64,
}

/// A `[remote "<name>"]`'s kept `url` and `pushurl` values, in order.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderRemote {
    pub name: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub urls: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pushurls: Vec<String>,
}

/// How many images' facts `state.toml` keeps.
pub const IMAGE_FACTS_CAP: usize = 32;

/// What `run` reads from a built image (docs/architecture/runtimes.md,
/// *Image facts*): the account fallbacks and `${containerEnv:…}` come from
/// it. An image id is content-addressed, so the facts never go stale.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageFacts {
    /// `Config.Env`, in order (`Backend::image_env`).
    #[serde(default)]
    pub env: Vec<(String, String)>,
    /// `Config.User` (`Backend::image_user`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    /// `/etc/passwd` (`Backend::image_passwd`); `None` when unreadable (no
    /// `sh`, or Apple `container`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub passwd: Option<String>,
    /// When it was read (unix seconds, [`Instance::now`]): the cap drops the
    /// oldest.
    #[serde(default)]
    pub at: u64,
}

impl State {
    /// Cache `facts` under image `id`, then drop the oldest (by `at`)
    /// beyond [`IMAGE_FACTS_CAP`].
    pub fn remember_image_facts(&mut self, id: String, facts: ImageFacts) {
        self.image_facts.insert(id, facts);
        while self.image_facts.len() > IMAGE_FACTS_CAP {
            let oldest = self.image_facts.iter().min_by_key(|(_, f)| f.at).map(|(id, _)| id.clone());
            match oldest {
                Some(id) => self.image_facts.remove(&id),
                None => break,
            };
        }
    }

    pub fn path() -> Result<PathBuf> {
        let base = std::env::var_os("XDG_DATA_HOME")
            .map(PathBuf::from)
            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
            .context("cannot determine user data dir ($XDG_DATA_HOME or $HOME)")?;
        Ok(base.join("devsandbox/state.toml"))
    }

    /// The saved state; a missing file is an empty one. Unlocked: writes are
    /// atomic, so a read always sees a complete file. A snapshot is only for
    /// reading; changes go through [`State::update`].
    pub fn load() -> Result<Self> {
        Self::load_at(&Self::path()?)
    }

    /// [`State::load`] from `path`: the daemon's verb tracking reads an
    /// injected path, so its tests never touch the user's state.
    pub(crate) fn load_at(path: &Path) -> Result<Self> {
        match std::fs::read_to_string(path) {
            Ok(contents) => {
                let mut state: Self = toml::from_str(&contents)
                    .with_context(|| format!("invalid state file {}", path.display()))?;
                // Pre-upgrade entries carry no id; the key is the best available
                // identity (equal to the creation name unless the instance was
                // renamed before ids existed).
                for (key, instance) in &mut state.instances {
                    if instance.instance_id.is_empty() {
                        instance.instance_id = key.clone();
                    }
                }
                Ok(state)
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
            Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
        }
    }

    /// Read-modify-write under an exclusive lock: re-read the file, apply `f`,
    /// and write it back (atomically, only if it changed). The only way to
    /// change state: saving a snapshot loaded earlier wrote back everything
    /// as of that load, so a long `run`/`rm` racing another command dropped
    /// the instance that command had recorded meanwhile, leaving its
    /// container and worktree with no state entry. `f` must apply only its
    /// own change, and must not call back into `update` (the lock isn't
    /// reentrant). An `Err` from `f` writes nothing.
    pub fn update<T>(f: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
        Self::update_at(&Self::path()?, f)
    }

    /// [`State::update`] of the file at `path`: the daemon's instance
    /// mutations take an injected path, so their tests never touch the
    /// user's state.
    pub(crate) fn update_at<T>(path: &Path, f: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
        let dir = path.parent().context("state path has no parent")?;
        std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
        // Separate from the state file, which the atomic write replaces.
        let lock_path = path.with_file_name("state.lock");
        let _lock = File::options()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
            .and_then(|file| file.lock().map(|()| file))
            .with_context(|| format!("cannot lock {}", lock_path.display()))?;
        let mut state = Self::load_at(path)?;
        let before = toml::to_string_pretty(&state).context("cannot serialize state")?;
        let out = f(&mut state)?;
        let after = toml::to_string_pretty(&state).context("cannot serialize state")?;
        if after != before {
            // Pid in the temp name: a stale temp from a killed writer is never reused.
            let tmp = path.with_file_name(format!(".state.toml.{}.tmp", std::process::id()));
            std::fs::write(&tmp, after).with_context(|| format!("cannot write {}", tmp.display()))?;
            std::fs::rename(&tmp, path).with_context(|| format!("cannot write {}", path.display()))?;
        }
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrips() {
        let mut state = State::default();
        state.instances.insert(
            "repo-abc1".into(),
            Instance {
                sandbox: "repository-1".into(),
                instance_id: "repo-abc1".into(),
                project: "abc12345".into(),
                container: "devsandbox-repo-abc1".into(),
                folder: "/home/u/repository-1".into(),
                base_folder: "/home/u/repository-1".into(),
                worktree: None,
                branch: None,
                branch_created: true,
                folders: Vec::new(),
                shell_history: None,
                workspace: "/workspaces/repository-1".into(),
                workspace_file: None,
                remote_env: BTreeMap::new(),
                remote_user: None,
                home: Some("/home/vscode".into()),
                browser_sandbox: None,
                tool_env: Default::default(),
                ssh_auth_sock: None,
                devsbd_arch: None,
                devsbd_error: None,
                volumes: Vec::new(),
                bind_dirs: Vec::new(),
                dispatcher: Some("pr-dispatcher".into()),
                profile: Some("work".into()),
                config_dir: Some("/home/u/.devsandboxes".into()),
                extra_env: BTreeMap::from([("PR_NUMBER".into(), "42".into())]),
                forwarded_ports: BTreeMap::from([("8080:3000".into(), 8081)]),
                done: Some(1_790_900_000),
                incarnation: Some("Zx9".into()),
                claims: vec![crate::credentials::instance::InstanceClaim {
                    kind: "sentry".into(),
                    feature: "./features/sentry".into(),
                    version: "ab12".into(),
                    claim: "{\"kind\":\"sentry\"}".into(),
                    phantom: "sntrys_x".into(),
                    listeners: vec![crate::credentials::instance::Listener { port: 29000, upstream: "sentry.io".into() }],
                    files: vec![crate::credentials::instance::File {
                        path: "/home/vscode/.sentryclirc".into(),
                        owner: "vscode".into(),
                        content: "[auth]\ntoken = sntrys_x\n".into(),
                    }],
                    git_hosts: Vec::new(),
                }],
                intercept: Some(crate::credentials::instance::Intercept {
                    port: 29001,
                    hosts: vec!["api.github.com".into()],
                    git: Some(crate::credentials::instance::ProxyPort { port: 29002, hosts: vec!["github.com".into()] }),
                    lfs: Some(29003),
                    proxy_env: vec![("HTTPS_PROXY".into(), "http://corp:3128".into())],
                    bundle: "/etc/ssl/certs/ca-certificates.crt".into(),
                    installed: Some("ab".repeat(32)),
                }),
                github_repos: vec!["o/r".into()],
                build_notes: vec!["warning: w".into()],
                git_env: Default::default(),
                progress: None,
                created_unix: Instance::now(),
            },
        );
        state.autostart_boot.insert("abc12345".into(), "3f2c-boot".into());
        let probe = crate::runtime::identity::Probe { mode: crate::runtime::identity::Mode::RootlessPodman, selinux: true };
        state.identity_probes.insert("podman:host=unix:///run/user/1000/podman/podman.sock".into(), probe);
        let remotes = FolderRemotes {
            remotes: vec![FolderRemote {
                name: "origin".into(),
                urls: vec!["git@github.com:o/r.git".into()],
                pushurls: vec!["https://github.com/o/r".into()],
            }],
            github: vec!["o/r".into()],
            unread: None,
            recorded_at: 7,
        };
        state.folder_remotes.insert("/home/u/repository-1".into(), remotes.clone());
        let text = toml::to_string_pretty(&state).unwrap();
        let back: State = toml::from_str(&text).unwrap();
        assert_eq!(back.identity_probes["podman:host=unix:///run/user/1000/podman/podman.sock"], probe);
        assert_eq!(back.instances["repo-abc1"].sandbox, "repository-1");
        assert_eq!(back.instances["repo-abc1"].instance_id, "repo-abc1");
        assert_eq!(back.autostart_boot["abc12345"], "3f2c-boot");
        assert_eq!(back.instances["repo-abc1"].dispatcher.as_deref(), Some("pr-dispatcher"));
        assert_eq!(
            back.instances["repo-abc1"].config_dir.as_deref(),
            Some(std::path::Path::new("/home/u/.devsandboxes"))
        );
        assert_eq!(back.instances["repo-abc1"].extra_env["PR_NUMBER"], "42");
        assert_eq!(back.instances["repo-abc1"].forwarded_ports["8080:3000"], 8081);
        assert_eq!(back.instances["repo-abc1"].done, Some(1_790_900_000));
        assert_eq!(back.instances["repo-abc1"].home.as_deref(), Some("/home/vscode"));
        assert_eq!(back.instances["repo-abc1"].profile.as_deref(), Some("work"));
        assert_eq!(back.instances["repo-abc1"].incarnation.as_deref(), Some("Zx9"));
        assert_eq!(back.instances["repo-abc1"].claims, state.instances["repo-abc1"].claims);
        assert_eq!(back.instances["repo-abc1"].intercept, state.instances["repo-abc1"].intercept);
        assert_eq!(back.instances["repo-abc1"].created_unix, state.instances["repo-abc1"].created_unix);
        assert_eq!(back.instances["repo-abc1"].github_repos, ["o/r"]);
        assert_eq!(back.instances["repo-abc1"].build_notes, ["warning: w"]);
        assert_eq!(back.folder_remotes["/home/u/repository-1"], remotes);
    }

    #[test]
    fn last_profile_roundtrips_and_empty_is_omitted() {
        let text = toml::to_string_pretty(&State::default()).unwrap();
        assert!(!text.contains("last_profile"), "{text}");
        let mut state = State::default();
        state.last_profile.entry("abc12345".into()).or_default().insert("web".into(), "work".into());
        let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
        assert_eq!(back.last_profile, state.last_profile);
    }

    #[test]
    fn empty_autostart_boot_is_omitted() {
        let text = toml::to_string_pretty(&State::default()).unwrap();
        assert!(!text.contains("autostart_boot"), "{text}");
        let back: State = toml::from_str(&text).unwrap();
        assert!(back.autostart_boot.is_empty());
    }

    #[test]
    fn identity_acks_roundtrip_and_empty_is_omitted() {
        let text = toml::to_string_pretty(&State::default()).unwrap();
        assert!(!text.contains("identity_acks"), "{text}");
        let mut state = State::default();
        state.identity_acks.insert("abc12345".into(), ["f1".to_string(), "f2".to_string()].into());
        let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
        assert_eq!(back.identity_acks, state.identity_acks);
    }

    #[test]
    fn image_facts_roundtrip_and_empty_is_omitted() {
        let text = toml::to_string_pretty(&State::default()).unwrap();
        assert!(!text.contains("image_facts"), "{text}");
        let mut state = State::default();
        let facts = ImageFacts {
            env: vec![("PATH".into(), "/usr/bin:/bin".into()), ("OPTS".into(), "a=b".into())],
            user: Some("node".into()),
            passwd: Some("root:x:0:0:root:/root:/bin/sh\nnode:x:1000:1000::/home/node:/bin/sh\n".into()),
            at: 7,
        };
        state.remember_image_facts("sha256:abc".into(), facts.clone());
        state.remember_image_facts("sha256:none".into(), ImageFacts::default());
        let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
        assert_eq!(back.image_facts["sha256:abc"], facts);
        assert_eq!(back.image_facts["sha256:none"], ImageFacts::default());
    }

    #[test]
    fn image_facts_cap_drops_the_oldest() {
        let mut state = State::default();
        for i in 0..IMAGE_FACTS_CAP as u64 {
            // Inserted newest first: the oldest isn't the first key.
            state.remember_image_facts(format!("sha256:{i:02}"), ImageFacts { at: 1000 - i, ..Default::default() });
        }
        assert_eq!(state.image_facts.len(), IMAGE_FACTS_CAP);
        state.remember_image_facts("sha256:new".into(), ImageFacts { at: 2000, ..Default::default() });
        assert_eq!(state.image_facts.len(), IMAGE_FACTS_CAP);
        let oldest = format!("sha256:{:02}", IMAGE_FACTS_CAP - 1);
        assert!(!state.image_facts.contains_key(&oldest));
        assert!(state.image_facts.contains_key("sha256:new") && state.image_facts.contains_key("sha256:00"));
    }

    #[test]
    fn empty_identity_probes_is_omitted() {
        let text = toml::to_string_pretty(&State::default()).unwrap();
        assert!(!text.contains("identity_probes"), "{text}");
        let back: State = toml::from_str(&text).unwrap();
        assert!(back.identity_probes.is_empty());
    }

    #[test]
    fn missing_instance_id_deserializes_empty() {
        // Pre-upgrade state files have no `instance_id`; serde defaults it to
        // empty and `load()` backfills it from the key (exercised there, not
        // here, since `load()` reads the real state path).
        let state: State = toml::from_str(
            r#"
            [instance.repo]
            sandbox = "web"
            container = "devsandbox-repo"
            folder = "/home/u/web"
            workspace = "/workspaces/web"
            created_unix = 0
            "#,
        )
        .unwrap();
        assert_eq!(state.instances["repo"].instance_id, "");
        assert_eq!(state.instances["repo"].dispatcher, None);
        assert_eq!(state.instances["repo"].profile, None);
        assert_eq!(state.instances["repo"].config_dir, None);
        assert!(state.instances["repo"].extra_env.is_empty());
        assert_eq!(state.instances["repo"].done, None);
        // Pre-reuse entries always had a created branch: `rm` keeps offering it.
        assert!(state.instances["repo"].branch_created);
        let text = toml::to_string_pretty(&state).unwrap();
        assert!(!text.contains("dispatcher") && !text.contains("config_dir"), "{text}");
        assert!(!text.contains("profile"), "{text}");
        assert!(!text.contains("branch_created"), "{text}");
        assert!(!text.contains("extra_env"), "{text}");
        assert!(!text.contains("done"), "{text}");
        assert_eq!(state.instances["repo"].home, None);
        assert!(!text.contains("home ="), "{text}");
        // Before the userns check: no verdict, no tool env.
        assert_eq!(state.instances["repo"].browser_sandbox, None);
        assert!(state.instances["repo"].tool_env.is_empty());
        assert!(!text.contains("browser_sandbox") && !text.contains("tool_env"), "{text}");
    }

    #[test]
    fn browser_sandbox_and_tool_env_roundtrip() {
        use crate::commands::run::BrowserSandbox;
        let mut state: State = toml::from_str(
            "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
        )
        .unwrap();
        let inst = state.instances.get_mut("a").unwrap();
        inst.browser_sandbox = Some(BrowserSandbox::On);
        inst.tool_env = BTreeMap::from([("DEVSANDBOX_BROWSER_SANDBOX".into(), "1".into())]);
        let text = toml::to_string_pretty(&state).unwrap();
        assert!(text.contains("browser_sandbox = \"on\""), "{text}");
        let back: State = toml::from_str(&text).unwrap();
        assert_eq!(back.instances["a"].browser_sandbox, Some(BrowserSandbox::On));
        assert_eq!(back.instances["a"].tool_env["DEVSANDBOX_BROWSER_SANDBOX"], "1");
        let why = "no user namespaces: seccomp";
        state.instances.get_mut("a").unwrap().browser_sandbox = Some(BrowserSandbox::Off(why.into()));
        let text = toml::to_string_pretty(&state).unwrap();
        let back: State = toml::from_str(&text).unwrap();
        assert_eq!(back.instances["a"].browser_sandbox, Some(BrowserSandbox::Off(why.into())), "{text}");
    }

    #[test]
    fn exec_env_overlays_extra_env_on_remote_env() {
        let mut state: State = toml::from_str(
            "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
        )
        .unwrap();
        let inst = state.instances.get_mut("a").unwrap();
        assert!(inst.exec_env().is_empty());
        inst.remote_env = BTreeMap::from([("A".into(), "remote".into()), ("B".into(), "b".into())]);
        inst.extra_env = BTreeMap::from([("A".into(), "extra".into()), ("C".into(), "c".into())]);
        assert_eq!(
            inst.exec_env(),
            BTreeMap::from([
                ("A".into(), "extra".into()),
                ("B".into(), "b".into()),
                ("C".into(), "c".into()),
            ])
        );
        // The plan's HOME comes first: remoteEnv and `--env` override it.
        inst.home = Some("/home/vscode".into());
        assert_eq!(inst.exec_env()["HOME"], "/home/vscode");
        inst.remote_env.insert("HOME".into(), "/srv/me".into());
        assert_eq!(inst.exec_env()["HOME"], "/srv/me");
        inst.extra_env.insert("HOME".into(), "/tmp/x".into());
        assert_eq!(inst.exec_env()["HOME"], "/tmp/x");
        // The tool env comes first too.
        inst.tool_env = BTreeMap::from([("B".into(), "tool".into()), ("T".into(), "t".into())]);
        assert_eq!((inst.exec_env()["B"].as_str(), inst.exec_env()["T"].as_str()), ("b", "t"));
    }

    /// The orphaned-child bug: two writers holding snapshots from before each
    /// other's change must both land, which a snapshot `save` didn't do.
    #[test]
    fn updates_apply_to_the_current_file_not_a_snapshot() {
        let dir = std::env::temp_dir().join(format!("devsandbox-state-update-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("state.toml");
        let entry = |name: &str| -> Instance {
            toml::from_str(&format!(
                "sandbox = \"web\"\ninstance_id = \"{name}\"\ncontainer = \"devsandbox-{name}\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n"
            ))
            .unwrap()
        };
        State::update_at(&path, |s| {
            s.instances.insert("a".into(), entry("a"));
            Ok(())
        })
        .unwrap();
        // A long command loaded state now, before the child below exists.
        let stale = State::load_at(&path).unwrap();
        State::update_at(&path, |s| {
            s.instances.insert("child".into(), entry("child"));
            Ok(())
        })
        .unwrap();
        // Then it records its own change: the child must survive.
        assert!(!stale.instances.contains_key("child"));
        State::update_at(&path, |s| {
            s.instances.remove("a");
            Ok(())
        })
        .unwrap();
        let now = State::load_at(&path).unwrap();
        assert_eq!(now.instances.keys().collect::<Vec<_>>(), ["child"]);

        // A failed update writes nothing; an unchanged one doesn't rewrite.
        let mtime = || std::fs::metadata(&path).unwrap().modified().unwrap();
        let before = mtime();
        std::thread::sleep(std::time::Duration::from_millis(20));
        let err = State::update_at(&path, |s| -> Result<()> {
            s.instances.clear();
            anyhow::bail!("boom")
        });
        assert!(err.is_err());
        State::update_at(&path, |_| Ok(())).unwrap();
        assert_eq!(mtime(), before);
        assert!(State::load_at(&path).unwrap().instances.contains_key("child"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn progress(phase: Phase) -> Progress {
        Progress { phase, pid: 4242, boot: Some("boot-a".into()), error: None }
    }

    #[test]
    fn progress_roundtrips_every_phase() {
        let phases = [
            Phase::Preparing,
            Phase::Building,
            Phase::Creating,
            Phase::Lifecycle("postCreateCommand".into()),
            Phase::Lifecycle("shell-rc".into()),
            Phase::Failed { at: "building".into() },
        ];
        for phase in phases {
            let mut state: State = toml::from_str(
                "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
            )
            .unwrap();
            let mut p = progress(phase);
            if matches!(p.phase, Phase::Failed { .. }) {
                p.error = Some("docker build exited 1".into());
            }
            state.instances.get_mut("a").unwrap().progress = Some(p.clone());
            let text = toml::to_string_pretty(&state).unwrap();
            let back: State = toml::from_str(&text).unwrap();
            assert_eq!(back.instances["a"].progress, Some(p), "{text}");
        }
    }

    #[test]
    fn progress_toml_shape() {
        let mut state: State = toml::from_str(
            "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
        )
        .unwrap();
        state.instances.get_mut("a").unwrap().progress = Some(progress(Phase::Lifecycle("postCreateCommand".into())));
        let text = toml::to_string_pretty(&state).unwrap();
        let back: toml::Table = toml::from_str(&text).unwrap();
        let p = back["instance"]["a"]["progress"].as_table().unwrap();
        assert_eq!(p["phase"].as_str(), Some("lifecycle"), "{text}");
        assert_eq!(p["step"].as_str(), Some("postCreateCommand"), "{text}");
        assert_eq!(p["pid"].as_integer(), Some(4242), "{text}");
        assert_eq!(p["boot"].as_str(), Some("boot-a"), "{text}");
        assert!(!p.contains_key("error"), "{text}");
    }

    #[test]
    fn no_progress_loads_and_is_omitted() {
        let state: State = toml::from_str(
            "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
        )
        .unwrap();
        assert_eq!(state.instances["a"].progress, None);
        let text = toml::to_string_pretty(&state).unwrap();
        assert!(!text.contains("progress"), "{text}");
    }

    #[test]
    fn odd_progress_still_loads() {
        let base = "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n";
        for (progress, phase) in [
            ("phase = \"lifecycle\"\npid = 1\n", Phase::Lifecycle("lifecycle".into())),
            ("phase = \"failed\"\npid = 1\n", Phase::Failed { at: "failed".into() }),
            ("phase = \"teleporting\"\npid = 1\n", Phase::Lifecycle("teleporting".into())),
        ] {
            let text = format!("{base}[instance.a.progress]\n{progress}");
            let state: State = toml::from_str(&text).unwrap();
            assert_eq!(state.instances["a"].progress.as_ref().unwrap().phase, phase, "{text}");
        }
    }

    #[test]
    fn view_in_flight_when_alive_and_same_boot() {
        let alive = |_| true;
        assert_eq!(progress(Phase::Preparing).view(alive, Some("boot-a")), PhaseView::InFlight("preparing".into()));
        assert_eq!(progress(Phase::Building).view(alive, Some("boot-a")), PhaseView::InFlight("building".into()));
        assert_eq!(progress(Phase::Creating).view(alive, Some("boot-a")), PhaseView::InFlight("creating".into()));
        assert_eq!(
            progress(Phase::Lifecycle("postCreateCommand".into())).view(alive, Some("boot-a")),
            PhaseView::InFlight("postCreateCommand".into())
        );
        // An unknown boot on either side can't prove a reboot.
        assert_eq!(progress(Phase::Building).view(alive, None), PhaseView::InFlight("building".into()));
        let mut unbooted = progress(Phase::Building);
        unbooted.boot = None;
        assert_eq!(unbooted.view(alive, Some("boot-b")), PhaseView::InFlight("building".into()));
    }

    #[test]
    fn view_interrupted_when_dead_or_rebooted() {
        let interrupted = |at: &str| PhaseView::Failed { at: at.into(), error: "interrupted".into() };
        let p = progress(Phase::Lifecycle("shell-rc".into()));
        assert_eq!(p.view(|pid| pid != 4242, Some("boot-a")), interrupted("shell-rc"));
        assert_eq!(p.view(|_| true, Some("boot-b")), interrupted("shell-rc"));
        assert_eq!(progress(Phase::Creating).view(|_| false, None), interrupted("creating"));
    }

    #[test]
    fn view_failed_stays_failed() {
        let mut p = progress(Phase::Failed { at: "postCreateCommand".into() });
        p.error = Some("exit status 1".into());
        let failed = PhaseView::Failed { at: "postCreateCommand".into(), error: "exit status 1".into() };
        // Liveness and boot don't matter once it's recorded failed.
        assert_eq!(p.view(|_| true, Some("boot-a")), failed);
        assert_eq!(p.view(|_| false, Some("boot-b")), failed);
        p.error = None;
        assert_eq!(
            p.view(|_| true, Some("boot-a")),
            PhaseView::Failed { at: "postCreateCommand".into(), error: "failed".into() }
        );
    }

    #[test]
    fn pid_alive_probes_real_processes() {
        assert!(pid_alive(std::process::id()));
        #[cfg(unix)]
        {
            // Above any pid_max, and not representable as a pid_t at all.
            assert!(!pid_alive(i32::MAX as u32));
            assert!(!pid_alive(u32::MAX));
            assert!(!pid_alive(0));
            // pid 1 exists; as non-root that's EPERM, still alive.
            assert!(pid_alive(1));
        }
    }

    #[test]
    fn reused_branch_roundtrips() {
        let mut state: State = toml::from_str(
            "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
        )
        .unwrap();
        state.instances.get_mut("a").unwrap().branch_created = false;
        let text = toml::to_string_pretty(&state).unwrap();
        let back: State = toml::from_str(&text).unwrap();
        assert!(!back.instances["a"].branch_created, "{text}");
    }
}