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
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
//! Feature image build: the derived image with devcontainer features installed,
//! the generated Dockerfile and entrypoint chain, and what features ask of the
//! container (mounts, `--privileged`).

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use anyhow::{bail, Context, Result};

use crate::commands::services;
use crate::config::{
    parse_shorthand, FeatureOptions, MountContext, ResolvedSandbox, SandboxProperties,
};
use crate::features::{self, FeatureMetadata};
use crate::runtime::{backend, NAME_PREFIX};

use super::mounts::{
    creatable_feature_source, feature_mount_decision, guard_create, provision_bind_source, MountDecision,
};

/// What the sandbox's enabled features ask of the container itself (the image
/// side lives in [`build_features_image`]).
pub(super) struct FeatureContainerOpts {
    /// `--mount` args.
    pub(super) mounts: Vec<String>,
    /// Per-instance volume names among `mounts` (for `rm`).
    pub(super) volumes: Vec<String>,
    /// Per-instance bind sources created here (for `rm`), applied or not.
    pub(super) bind_dirs: Vec<std::path::PathBuf>,
    /// Refs of the enabled features declaring `privileged: true`; the backend
    /// check happens in [`privileged_decision`].
    pub(super) privileged_by: Vec<String>,
    /// Every enabled feature's credential claims, by feature ref, in config
    /// order (`claims::wire` decides which apply).
    pub(super) claims: Vec<(String, crate::credentials::claim::Claim)>,
}

/// Whether to pass `--privileged`, plus the warnings to print. Requested by the
/// sandbox's `privileged = true` or any enabled feature's `privileged: true`;
/// on a backend without the flag every request is skipped with a warning, like
/// an unsatisfiable feature mount.
pub(super) fn privileged_decision(sandbox: bool, features: &[String], supported: bool) -> (bool, Vec<String>) {
    let requested = sandbox || !features.is_empty();
    if supported || !requested {
        return (requested, Vec::new());
    }
    let skip = "this runtime cannot run privileged containers; skipping `privileged`";
    let mut warnings: Vec<String> =
        features.iter().map(|r| format!("feature `{r}`: {skip}")).collect();
    if sandbox {
        warnings.insert(0, skip.to_string());
    }
    (false, warnings)
}

/// Resolve the container-side settings declared by the sandbox's enabled
/// features (fetches hit the per-user cache also used by the image build).
///
/// Mounts are turned into `--mount` args. The
/// sandbox always wins: a feature mount whose target is already claimed is
/// dropped, so the config can replace e.g. docker-outside-of-docker's hardcoded
/// `/var/run/docker.sock` source with a rootless socket path. Mounts the
/// backend cannot apply, or whose bind source is missing on the host, are
/// skipped with a warning — auto-creating the source (the config-mount
/// behavior) would hand the container an empty stub instead of a clear signal.
/// The exception is a source under `${sharedVolumes}`: that is devsandbox's own
/// persistent state, so it is created like a config mount's (a devsandbox
/// feature's per-instance dirs don't exist before the first run), once a
/// worker `policy` has seen it resolve under the fleet root
/// ([`guard_create`]).
pub(super) fn feature_container_opts(
    props: &SandboxProperties,
    ctx: &MountContext,
    existing: &[String],
    workspace: &str,
    policy: Option<&crate::worker_policy::Policy>,
) -> Result<FeatureContainerOpts> {
    let mut opts = FeatureContainerOpts {
        mounts: Vec::new(),
        volumes: Vec::new(),
        bind_dirs: Vec::new(),
        privileged_by: Vec::new(),
        claims: Vec::new(),
    };
    let Some(features) = &props.features else {
        return Ok(opts);
    };
    let mut taken: BTreeSet<String> = existing
        .iter()
        .filter_map(|arg| parse_shorthand(arg).ok().map(|(_, _, target, _)| target))
        .collect();
    taken.insert(workspace.to_string());
    for (reference, options) in features {
        if feature_option_values(options)
            .with_context(|| format!("feature `{reference}`: invalid options"))?
            .is_none()
        {
            continue; // `= false`: disabled.
        }
        let source = features::FeatureSource::parse(reference)?;
        let feature = features::resolve(&source, Path::new(ctx.config_dir))
            .with_context(|| format!("fetching feature `{reference}`"))?;
        if feature.metadata.privileged == Some(true) {
            opts.privileged_by.push(reference.clone());
        }
        opts.claims.extend(feature.metadata.credentials.iter().map(|c| (reference.clone(), c.clone())));
        for mount in &feature.metadata.mounts {
            let mut resolved = mount.resolve(ctx)?;
            // The feature schema's mounts can't say `readonly`; an update's
            // dir is written by the update alone, never by a sandbox.
            if feature.metadata.updates.iter().any(|u| u.mount == resolved.target) {
                resolved.readonly = true;
            }
            if let Some(source) = resolved.source.as_deref() {
                if creatable_feature_source(&resolved.kind, source, ctx.shared_volumes) {
                    guard_create(policy, Path::new(source))?;
                    opts.bind_dirs.extend(provision_bind_source(source, resolved.instance_source)?);
                }
            }
            let probe = |source: &str| std::fs::metadata(source).ok().map(|m| !m.is_dir());
            match feature_mount_decision(
                &resolved,
                &taken,
                backend().supports_file_binds(),
                probe,
            ) {
                MountDecision::Apply => {
                    taken.insert(resolved.target.clone());
                    opts.mounts.push(resolved.to_arg());
                    if resolved.per_instance {
                        opts.volumes.extend(resolved.source.clone());
                    }
                }
                MountDecision::Overridden => {}
                MountDecision::Skip(reason) => {
                    super::notes::noted!("warning: feature `{reference}`: {reason}");
                }
            }
        }
    }
    Ok(opts)
}

/// Tag of a `build.dockerfile` sandbox's image: `project` is the config
/// root's [`services::project_id`], so same-named sandboxes of two roots
/// never share (or clobber) a tag.
///
/// No two of devsandbox's image tags collide: after `devsandbox-` each
/// kind has its own head (`img-<project>-` here, `feat-` for
/// [`features_image`], `img-svc-` for [`services::service_image_tag`]; a
/// project id is 8 lowercase hex chars, and `s` isn't hex), and within a
/// kind the fixed-length, `-`-free project id ends at a known offset, so
/// the rest is the sandbox (or service) name exactly. A suffix scheme
/// (`…-<sandbox>-feat`) wasn't: sandbox `web-feat`'s image was sandbox
/// `web`'s features image.
pub(super) fn sandbox_image(project: &str, sandbox: &str) -> String {
    format!("{NAME_PREFIX}img-{project}-{sandbox}")
}

/// Tag of a sandbox's derived features image (scoped like [`sandbox_image`],
/// whose doc has why no tag collides with it).
pub(crate) fn features_image(project: &str, sandbox: &str) -> String {
    format!("{NAME_PREFIX}feat-{project}-{sandbox}")
}

/// Image to run: the `image` property as-is, or a local build for
/// `build.dockerfile` sandboxes ([`sandbox_image`]). When the sandbox declares
/// `features`, the base (image or build) is extended into a derived image
/// tagged [`features_image`]. `project` is the config root's
/// [`services::project_id`].
pub(super) fn image_for(dir: &Path, project: &str, sandbox: &ResolvedSandbox) -> Result<String> {
    let base = base_image_for(dir, project, sandbox)?;
    let props = &sandbox.properties;
    match &props.features {
        Some(features) if !features.is_empty() => {
            build_features_image(dir, project, sandbox, &base, features)
        }
        _ => Ok(base),
    }
}

/// The base image: the `image` property as-is, or a local build for
/// `build.dockerfile` sandboxes.
fn base_image_for(dir: &Path, project: &str, sandbox: &ResolvedSandbox) -> Result<String> {
    let props = &sandbox.properties;
    if let Some(image) = &props.image {
        return Ok(image.clone());
    }
    let build = props
        .build
        .as_ref()
        .with_context(|| format!("sandbox `{}` has neither `image` nor `build`", sandbox.name))?;
    let dockerfile = build
        .dockerfile
        .as_deref()
        .with_context(|| format!("sandbox `{}`: `build.dockerfile` is required", sandbox.name))?;
    let tag = sandbox_image(project, &sandbox.name);
    let args = services::build_args(
        backend(),
        dir,
        &tag,
        dockerfile,
        build,
        &format!("sandbox `{}`", sandbox.name),
    );
    crate::key_guard::check_argv(&args)?;
    crate::worker_policy::enforce_argv(dir, &args)?;
    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
    backend().run_checked(&arg_refs)?;
    Ok(tag)
}

// Derived-image build from devcontainer `features`.
//
// The impure orchestration (`build_features_image`) fetches + orders the
// features, assembles a build context, and shells out to the runtime. The
// generation of the Dockerfile, env-files, and install wrapper is factored into
// pure functions (below) so they're unit-testable without docker or network.
// The layout mirrors the official devcontainers CLI
// (`containerFeaturesConfiguration.ts`, `containerFeatures.ts`).

/// A feature ready to be baked in: its build-context directory name, its id,
/// metadata, and the resolved option map (defaults merged under user values).
struct FeatureBuild {
    /// `<idx>-<id>`, the per-feature directory name in the build context.
    dir_name: String,
    metadata: FeatureMetadata,
}

/// Fetch + order the sandbox's features, assemble a build context under the
/// features cache, and build the derived image. Returns its tag. `dir` is the
/// config dir local feature folders resolve against.
fn build_features_image(
    dir: &Path,
    project: &str,
    sandbox: &ResolvedSandbox,
    base: &str,
    features: &BTreeMap<String, FeatureOptions>,
) -> Result<String> {
    let props = &sandbox.properties;

    let mut resolved = Vec::new();
    let mut options_by_key: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
    for (reference, opts) in features {
        let Some(values) = feature_option_values(opts)
            .with_context(|| format!("feature `{reference}`: invalid options"))?
        else {
            continue; // `= false`: skip entirely.
        };
        let source = features::FeatureSource::parse(reference)?;
        let feature = features::resolve(&source, dir)
            .with_context(|| format!("fetching feature `{reference}`"))?;
        options_by_key.insert(feature.key(), values);
        resolved.push(feature);
    }
    if resolved.is_empty() {
        return Ok(base.to_string());
    }

    let ordered = features::install_order(resolved)?;

    let container_user = props.container_user.as_deref().unwrap_or("root");
    let remote_user = props.remote_user.as_deref().unwrap_or(container_user);

    let context = features::build_context_dir(project, &sandbox.name)?;
    std::fs::write(
        context.join("devcontainer-features.builtin.env"),
        builtin_env(container_user, remote_user),
    )
    .with_context(|| format!("cannot write builtin env in {}", context.display()))?;

    let mut builds = Vec::with_capacity(ordered.len());
    for (idx, feature) in ordered.iter().enumerate() {
        let key = feature.key();
        let id = feature.metadata.id.clone().unwrap_or_else(|| feature.id());
        let dir_name = format!("{idx}-{id}");
        let dest = context.join(&dir_name);
        copy_dir(&feature.dir, &dest)
            .with_context(|| format!("copying feature `{key}` into build context"))?;

        let values = options_by_key.remove(&key).unwrap_or_default();
        let env_file = feature_env_file(&feature.metadata, &values);
        std::fs::write(dest.join("devcontainer-features.env"), &env_file)
            .with_context(|| format!("cannot write env file for `{key}`"))?;
        let wrapper = install_wrapper(&feature.metadata, &feature.without_tag(), &env_file);
        std::fs::write(dest.join("devcontainer-features-install.sh"), wrapper)
            .with_context(|| format!("cannot write install wrapper for `{key}`"))?;

        builds.push(FeatureBuild {
            dir_name,
            metadata: feature.metadata.clone(),
        });
    }

    let dockerfile =
        generate_dockerfile(base, &builds, props.container_user.as_deref(), remote_user);
    let dockerfile_path = context.join("Dockerfile.devsandbox-features");
    std::fs::write(&dockerfile_path, dockerfile)
        .with_context(|| format!("cannot write {}", dockerfile_path.display()))?;

    let baked: Vec<crate::updates::Baked> = ordered
        .iter()
        .flat_map(|f| crate::updates::baked(&f.key(), &f.metadata.updates, &f.metadata.mounts))
        .collect();
    let updates_label = format!("{}={}", crate::updates::LABEL, crate::updates::to_label(&baked));

    let tag = features_image(project, &sandbox.name);
    features_build(&tag, &dockerfile_path, &context, &updates_label)?;

    // Feature entrypoints: a second, metadata-only build on the same tag. The
    // image's own ENTRYPOINT is read from the first build (which inherits the
    // base's untouched) because a Dockerfile cannot reference its parent's.
    let entrypoints: Vec<(String, String)> = ordered
        .iter()
        .filter_map(|f| {
            let entrypoint = f.metadata.entrypoint.as_deref()?.trim();
            (!entrypoint.is_empty()).then(|| (f.without_tag(), entrypoint.to_string()))
        })
        .collect();
    if !entrypoints.is_empty() {
        let image_entrypoint = backend()
            .image_entrypoint(&tag)
            .with_context(|| format!("cannot read the ENTRYPOINT of `{tag}`"))?;
        std::fs::write(context.join(ENTRYPOINT_WRAPPER_FILE), entrypoint_wrapper(&entrypoints))
            .with_context(|| format!("cannot write entrypoint wrapper in {}", context.display()))?;
        let dockerfile_path = context.join("Dockerfile.devsandbox-entrypoint");
        std::fs::write(&dockerfile_path, entrypoint_dockerfile(&tag, &image_entrypoint))
            .with_context(|| format!("cannot write {}", dockerfile_path.display()))?;
        features_build(&tag, &dockerfile_path, &context, &updates_label)?;
    }
    Ok(tag)
}

/// `build -t tag --label label -f dockerfile context` of the features image's
/// generated context, past the member key's guard like every build. The
/// label is set even when empty, so none is inherited from the base image.
fn features_build(tag: &str, dockerfile: &Path, context: &Path, label: &str) -> Result<()> {
    let args: Vec<String> =
        ["build", "-t", tag, "--label", label, "-f", &dockerfile.to_string_lossy(), &context.to_string_lossy()]
            .map(str::to_string)
            .into();
    crate::key_guard::check_argv(&args)?;
    let refs: Vec<&str> = args.iter().map(String::as_str).collect();
    backend().run_checked(&refs)
}

/// Build-context name of the generated entrypoint chain.
const ENTRYPOINT_WRAPPER_FILE: &str = "devsandbox-entrypoint.sh";

/// Where the entrypoint chain lives in the derived image.
const ENTRYPOINT_WRAPPER_PATH: &str = "/usr/local/share/devsandbox-entrypoint.sh";

/// The entrypoint chain: each feature's `entrypoint` (`(id, command)` pairs,
/// in install order), then `exec "$@"`, which is the image's own ENTRYPOINT
/// followed by the container command. Each feature entrypoint runs with no
/// arguments, so its trailing `exec "$@"` is a no-op and it returns. The
/// command is inserted verbatim, as the official CLI does. A failing one warns
/// and the chain continues (no `set -e`, same as the CLI), so a broken feature
/// can't keep the sandbox from starting.
fn entrypoint_wrapper(entrypoints: &[(String, String)]) -> String {
    let mut out = String::from(
        "#!/bin/sh\n\
# Generated by devsandbox: feature entrypoints (install order), then the\n\
# image's own ENTRYPOINT + the container command.\n",
    );
    for (id, entrypoint) in entrypoints {
        out.push_str(&format!(
            "{entrypoint} || echo \"devsandbox: entrypoint of feature '{id}' exited with status $?; continuing\" >&2\n"
        ));
    }
    out.push_str("exec \"$@\"\n");
    out
}

/// The second-stage Dockerfile that installs the entrypoint chain on top of
/// `image`, keeping `image_entrypoint` (the image's own ENTRYPOINT) as the
/// chain's arguments. The chain runs through `/bin/sh` so it needs no exec bit
/// (COPY mode handling differs between builders).
fn entrypoint_dockerfile(image: &str, image_entrypoint: &[String]) -> String {
    let mut entrypoint = vec!["/bin/sh".to_string(), ENTRYPOINT_WRAPPER_PATH.to_string()];
    entrypoint.extend(image_entrypoint.iter().cloned());
    format!(
        "FROM {image}\n\
COPY {ENTRYPOINT_WRAPPER_FILE} {ENTRYPOINT_WRAPPER_PATH}\n\
ENTRYPOINT {}\n",
        serde_json::to_string(&entrypoint).expect("strings serialize"),
    )
}

/// Turn a config `FeatureOptions` into a stringified option map, or `None` when
/// the feature is disabled (`= false`). `Options` tables reject array/table
/// values with a clear error; scalars stringify (strings as-is, bools
/// `true`/`false`, ints/floats via their `Display`).
pub(crate) fn feature_option_values(opts: &FeatureOptions) -> Result<Option<BTreeMap<String, String>>> {
    match opts {
        FeatureOptions::Enabled(false) => Ok(None),
        FeatureOptions::Enabled(true) => Ok(Some(BTreeMap::new())),
        FeatureOptions::Version(v) => {
            Ok(Some(BTreeMap::from([("version".to_string(), v.clone())])))
        }
        FeatureOptions::Options(table) => {
            let mut out = BTreeMap::new();
            for (key, value) in table {
                out.insert(key.clone(), toml_option_value(key, value)?);
            }
            Ok(Some(out))
        }
    }
}

/// Stringify a scalar TOML option value. Arrays and tables are rejected: feature
/// options are flat scalars.
fn toml_option_value(key: &str, value: &toml::Value) -> Result<String> {
    match value {
        toml::Value::String(s) => Ok(s.clone()),
        toml::Value::Boolean(b) => Ok(b.to_string()),
        toml::Value::Integer(i) => Ok(i.to_string()),
        toml::Value::Float(f) => Ok(f.to_string()),
        toml::Value::Datetime(d) => Ok(d.to_string()),
        toml::Value::Array(_) | toml::Value::Table(_) => {
            bail!("option `{key}` must be a string, bool, or number, not an array or table")
        }
    }
}

/// The `devcontainer-features.builtin.env` body: `_CONTAINER_USER` and
/// `_REMOTE_USER`. The `_*_HOME` lines are appended in-container by the Dockerfile.
fn builtin_env(container_user: &str, remote_user: &str) -> String {
    format!("_CONTAINER_USER={container_user}\n_REMOTE_USER={remote_user}\n")
}

/// A feature's option env-name, mirroring the CLI's `getSafeId`: non-word chars
/// (outside `[A-Za-z0-9_]`) become `_`, then any leading run of digits and
/// underscores collapses to a single `_`, then the whole thing is uppercased.
fn safe_id(name: &str) -> String {
    let mapped: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
        .collect();
    let trimmed = mapped.trim_start_matches(|c: char| c.is_ascii_digit() || c == '_');
    let out = if trimmed.len() == mapped.len() {
        mapped
    } else {
        format!("_{trimmed}")
    };
    out.to_uppercase()
}

/// Escape a value for a double-quoted context: backslash and double-quote only.
/// A literal dollar sign is left intact so a value like /usr/local/go/bin:${PATH}
/// still expands at build time when emitted as an ENV instruction.
fn escape_dq(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

/// The `devcontainer-features.env` body: one `NAME="value"` per option, names via
/// [`safe_id`], values = metadata defaults overridden by user-provided values.
fn feature_env_file(metadata: &FeatureMetadata, values: &BTreeMap<String, String>) -> String {
    // BTreeMap keeps a stable (alphabetical) order.
    let mut merged: BTreeMap<String, String> = BTreeMap::new();
    for (name, option) in &metadata.options {
        if let Some(default) = &option.default {
            merged.insert(name.clone(), json_scalar(default));
        }
    }
    for (name, value) in values {
        merged.insert(name.clone(), value.clone());
    }
    merged
        .iter()
        .map(|(name, value)| format!("{}=\"{}\"", safe_id(name), escape_dq(value)))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Stringify a JSON scalar option default: strings as-is, everything else via its
/// JSON rendering (bool becomes `true`/`false`, numbers become their text).
fn json_scalar(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Single-quote escape for a value printed inside `'...'` in the wrapper banner,
/// mirroring the CLI's `escapeQuotesForShell`: each `'` becomes `'\''`.
fn escape_sq(value: &str) -> String {
    value.replace('\'', "'\\''")
}

/// The per-feature `devcontainer-features-install.sh` wrapper: a banner echoing
/// the feature identity + options, then `set -a` sourcing of the builtin and
/// feature env-files, then `./install.sh`. `env_file` is the already-generated
/// `devcontainer-features.env` body, echoed (indented) in the banner.
fn install_wrapper(metadata: &FeatureMetadata, id: &str, env_file: &str) -> String {
    let name = metadata.name.as_deref().unwrap_or("Unknown");
    let version = metadata.version.as_deref().unwrap_or("");
    let documentation = metadata.documentation_url.as_deref().unwrap_or("");
    let options_indented = env_file
        .lines()
        .map(|l| format!("    {l}"))
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        "#!/bin/sh\n\
set -e\n\
\n\
echo ===========================================================================\n\
echo 'Feature       : {name}'\n\
echo 'Id            : {id}'\n\
echo 'Version       : {version}'\n\
echo 'Documentation : {documentation}'\n\
echo 'Options       :'\n\
echo '{options}'\n\
echo ===========================================================================\n\
\n\
set -a\n\
. ../devcontainer-features.builtin.env\n\
. ./devcontainer-features.env\n\
set +a\n\
\n\
chmod +x ./install.sh\n\
./install.sh\n",
        name = escape_sq(name),
        id = escape_sq(id),
        version = escape_sq(version),
        documentation = escape_sq(documentation),
        options = escape_sq(&options_indented),
    )
}

/// Generate the derived-image Dockerfile. `container_user` is `Some` only when
/// the sandbox set `containerUser`; when `None` the final stage stays `root`.
/// `remote_user` is the effective remote user (used for the `_*_HOME` probe).
fn generate_dockerfile(
    base: &str,
    features: &[FeatureBuild],
    container_user: Option<&str>,
    remote_user: &str,
) -> String {
    let effective_container_user = container_user.unwrap_or("root");
    let mut out = String::new();
    out.push_str(&format!("FROM {base}\n"));
    out.push_str("USER root\n");
    out.push_str("RUN mkdir -p /tmp/dev-container-features\n");
    out.push_str("COPY devcontainer-features.builtin.env /tmp/dev-container-features/\n");
    out.push_str(&format!(
        "RUN echo \"_CONTAINER_USER_HOME=$(getent passwd {cu} | cut -d: -f6)\" \
>> /tmp/dev-container-features/devcontainer-features.builtin.env && \
echo \"_REMOTE_USER_HOME=$(getent passwd {ru} | cut -d: -f6)\" \
>> /tmp/dev-container-features/devcontainer-features.builtin.env\n",
        cu = effective_container_user,
        ru = remote_user,
    ));
    for feature in features {
        for (key, value) in &feature.metadata.container_env {
            out.push_str(&format!("ENV {key}=\"{}\"\n", escape_dq(value)));
        }
        let dir = &feature.dir_name;
        out.push_str(&format!("COPY {dir} /tmp/dev-container-features/{dir}\n"));
        out.push_str(&format!(
            "RUN chmod -R 0755 /tmp/dev-container-features/{dir} && \
cd /tmp/dev-container-features/{dir} && \
chmod +x ./devcontainer-features-install.sh && \
./devcontainer-features-install.sh\n",
        ));
    }
    if let Some(user) = container_user {
        out.push_str(&format!("USER {user}\n"));
    }
    out
}

/// Recursively copy `src` into `dst` (created if missing), using plain `std::fs`
/// (no external deps).
fn copy_dir(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst).with_context(|| format!("cannot create {}", dst.display()))?;
    for entry in std::fs::read_dir(src).with_context(|| format!("cannot read {}", src.display()))? {
        let entry = entry?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir(&from, &to)?;
        } else {
            std::fs::copy(&from, &to)
                .with_context(|| format!("cannot copy {} to {}", from.display(), to.display()))?;
        }
    }
    Ok(())
}

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

    #[test]
    fn image_tags_are_scoped_by_project() {
        assert_eq!(sandbox_image("ab12cd34", "web"), "devsandbox-img-ab12cd34-web");
        assert_eq!(features_image("ab12cd34", "web"), "devsandbox-feat-ab12cd34-web");
        // Sandbox `web-feat`'s build used to be sandbox `web`'s features image.
        assert_ne!(sandbox_image("ab12cd34", "web-feat"), features_image("ab12cd34", "web"));
        // Nor does a sandbox image meet a service's (`svc` isn't hex).
        assert_ne!(sandbox_image("ab12cd34", "db"), services::service_image_tag("ab12cd34", "db"));
        // Two roots, one sandbox name: nothing shared.
        assert_ne!(sandbox_image("ab12cd34", "web"), sandbox_image("00ff00ff", "web"));
        assert_ne!(features_image("ab12cd34", "web"), features_image("00ff00ff", "web"));
        assert_ne!(
            features::build_context_name("ab12cd34", "web"),
            features::build_context_name("00ff00ff", "web")
        );
        assert_eq!(features::build_context_name("ab12cd34", "web"), "build-ab12cd34-web");
    }

    #[test]
    fn privileged_decision_ors_sandbox_and_features() {
        let dind = ["ghcr.io/devcontainers/features/docker-in-docker:2".to_string()];
        assert_eq!(privileged_decision(false, &[], true), (false, vec![]));
        assert_eq!(privileged_decision(true, &[], true), (true, vec![]));
        assert_eq!(privileged_decision(false, &dind, true), (true, vec![]));
        assert_eq!(privileged_decision(true, &dind, true), (true, vec![]));
    }

    #[test]
    fn privileged_decision_unsupported_warns_per_request() {
        // Apple `container` has no `--privileged`.
        let dind = ["ghcr.io/devcontainers/features/docker-in-docker:2".to_string()];
        assert_eq!(privileged_decision(false, &[], false), (false, vec![]));
        let (on, warnings) = privileged_decision(true, &dind, false);
        assert!(!on);
        assert_eq!(warnings.len(), 2, "{warnings:?}");
        assert!(warnings[0].starts_with("this runtime cannot"), "{warnings:?}");
        assert!(warnings[1].contains("docker-in-docker"), "{warnings:?}");
    }

    fn md() -> FeatureMetadata {
        FeatureMetadata::default()
    }

    fn opt_default(v: serde_json::Value) -> FeatureOption {
        FeatureOption { default: Some(v) }
    }

    #[test]
    fn safe_id_maps_like_get_safe_id() {
        assert_eq!(safe_id("install-jq"), "INSTALL_JQ");
        assert_eq!(safe_id("version"), "VERSION");
        assert_eq!(safe_id("2fa"), "_FA");
        assert_eq!(safe_id("123abc"), "_ABC");
        assert_eq!(safe_id("_1_x"), "_X");
        assert_eq!(safe_id("NODE_gyp"), "NODE_GYP");
    }

    #[test]
    fn escape_dq_escapes_quote_and_backslash_not_dollar() {
        assert_eq!(escape_dq(r#"a"b"#), r#"a\"b"#);
        assert_eq!(escape_dq(r"a\b"), r"a\\b");
        // Dollar stays literal so ENV expands ${PATH} at build time.
        assert_eq!(escape_dq("/usr/local/go/bin:${PATH}"), "/usr/local/go/bin:${PATH}");
    }

    #[test]
    fn feature_option_values_scalar_forms() {
        assert_eq!(
            feature_option_values(&FeatureOptions::Version("1.22".into())).unwrap(),
            Some(BTreeMap::from([("version".to_string(), "1.22".to_string())]))
        );
        assert_eq!(
            feature_option_values(&FeatureOptions::Enabled(true)).unwrap(),
            Some(BTreeMap::new())
        );
        assert_eq!(feature_option_values(&FeatureOptions::Enabled(false)).unwrap(), None);

        let table = BTreeMap::from([
            ("version".to_string(), toml::Value::String("lts".into())),
            ("installTools".to_string(), toml::Value::Boolean(true)),
            ("uid".to_string(), toml::Value::Integer(1000)),
        ]);
        let values = feature_option_values(&FeatureOptions::Options(table)).unwrap().unwrap();
        assert_eq!(values["version"], "lts");
        assert_eq!(values["installTools"], "true");
        assert_eq!(values["uid"], "1000");
    }

    #[test]
    fn feature_option_values_rejects_arrays_and_tables() {
        let table = BTreeMap::from([(
            "list".to_string(),
            toml::Value::Array(vec![toml::Value::String("a".into())]),
        )]);
        let err = feature_option_values(&FeatureOptions::Options(table)).unwrap_err().to_string();
        assert!(err.contains("array or table"), "{err}");
    }

    #[test]
    fn feature_env_file_merges_defaults_then_user_override() {
        let mut m = md();
        m.options.insert("version".into(), opt_default(serde_json::json!("latest")));
        m.options.insert("installTools".into(), opt_default(serde_json::json!(true)));
        m.options.insert("uid".into(), opt_default(serde_json::json!(1000)));
        // User overrides `version`; leaves the others at their default.
        let values = BTreeMap::from([("version".to_string(), "1.22".to_string())]);
        let env = feature_env_file(&m, &values);
        // BTreeMap => alphabetical option order (installTools, uid, version).
        assert_eq!(
            env,
            "INSTALLTOOLS=\"true\"\nUID=\"1000\"\nVERSION=\"1.22\""
        );
    }

    #[test]
    fn feature_env_file_escapes_values() {
        let values = BTreeMap::from([("flag".to_string(), r#"a"b\c"#.to_string())]);
        let env = feature_env_file(&md(), &values);
        assert_eq!(env, r#"FLAG="a\"b\\c""#);
    }

    #[test]
    fn install_wrapper_has_banner_sourcing_and_exec() {
        let mut m = md();
        m.name = Some("O'Brien's Feature".into());
        m.version = Some("1.0.0".into());
        let env_file = "VERSION=\"1.22\"";
        let w = install_wrapper(&m, "ghcr.io/x/y", env_file);
        assert!(w.starts_with("#!/bin/sh\nset -e\n"), "{w}");
        assert!(w.contains("echo 'Feature       : O'\\''Brien'\\''s Feature'"), "{w}");
        assert!(w.contains("echo 'Id            : ghcr.io/x/y'"), "{w}");
        assert!(w.contains("echo '    VERSION=\"1.22\"'"), "{w}");
        assert!(w.contains("set -a\n. ../devcontainer-features.builtin.env\n. ./devcontainer-features.env\nset +a"), "{w}");
        assert!(w.trim_end().ends_with("chmod +x ./install.sh\n./install.sh"), "{w}");
    }

    #[test]
    fn entrypoint_dockerfile_chains_image_entrypoint() {
        let df = entrypoint_dockerfile("devsandbox-feat-s", &["/usr/bin/tini".into(), "--".into()]);
        assert_eq!(
            df,
            "FROM devsandbox-feat-s\n\
COPY devsandbox-entrypoint.sh /usr/local/share/devsandbox-entrypoint.sh\n\
ENTRYPOINT [\"/bin/sh\",\"/usr/local/share/devsandbox-entrypoint.sh\",\"/usr/bin/tini\",\"--\"]\n"
        );
        // No image ENTRYPOINT: the chain execs the container command directly.
        assert!(entrypoint_dockerfile("i", &[])
            .contains("ENTRYPOINT [\"/bin/sh\",\"/usr/local/share/devsandbox-entrypoint.sh\"]\n"));
    }

    /// Runs the generated chain under the real `/bin/sh`: feature entrypoints
    /// in order with no arguments, a failing one warns without stopping the
    /// chain, then `exec "$@"` hands over to the image entrypoint + command.
    #[test]
    fn entrypoint_wrapper_runs_in_order_and_execs_args() {
        let dir = std::env::temp_dir().join(format!(
            "devsandbox-ep-test-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let log = dir.join("log");
        let script = |name: &str, body: &str| {
            let path = dir.join(name);
            std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
            path.display().to_string()
        };
        // Same shape as docker-in-docker's docker-init.sh: work, then exec "$@".
        let first = script("a.sh", &format!("echo \"a:$#\" >> {}\nexec \"$@\"", log.display()));
        let broken = script("b.sh", "exit 3");
        let wrapper = entrypoint_wrapper(&[
            ("ghcr.io/x/a".into(), format!("sh {first}")),
            ("ghcr.io/x/b".into(), format!("sh {broken}")),
        ]);
        let out = std::process::Command::new("/bin/sh")
            .args(["-c", &wrapper, "sh", "sh", "-c"])
            .arg(format!("echo \"cmd:$0\" >> {}", log.display()))
            .arg("sleep")
            .output()
            .unwrap();
        let logged = std::fs::read_to_string(&log).unwrap_or_default();
        let stderr = String::from_utf8_lossy(&out.stderr).to_string();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(out.status.success(), "{stderr}");
        assert_eq!(logged, "a:0\ncmd:sleep\n");
        assert!(stderr.contains("entrypoint of feature 'ghcr.io/x/b' exited with status 3; continuing"), "{stderr}");
    }

    #[test]
    fn builtin_env_lines() {
        assert_eq!(builtin_env("root", "vscode"), "_CONTAINER_USER=root\n_REMOTE_USER=vscode\n");
    }

    fn fb(dir_name: &str, container_env: &[(&str, &str)]) -> FeatureBuild {
        let mut m = md();
        m.container_env = container_env
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        FeatureBuild { dir_name: dir_name.into(), metadata: m }
    }

    #[test]
    fn dockerfile_base_env_escaping_and_copy_run() {
        let features = vec![fb(
            "0-go",
            &[
                ("PATH", "/usr/local/go/bin:${PATH}"),
                ("QUOTED", r#"a"b\c"#),
            ],
        )];
        let df = generate_dockerfile("alpine:3.20", &features, None, "root");
        assert!(df.starts_with("FROM alpine:3.20\nUSER root\n"), "{df}");
        assert!(df.contains("RUN mkdir -p /tmp/dev-container-features\n"), "{df}");
        assert!(
            df.contains("COPY devcontainer-features.builtin.env /tmp/dev-container-features/\n"),
            "{df}"
        );
        assert!(
            df.contains("_CONTAINER_USER_HOME=$(getent passwd root | cut -d: -f6)")
                && df.contains("_REMOTE_USER_HOME=$(getent passwd root | cut -d: -f6)"),
            "{df}"
        );
        assert!(df.contains("ENV PATH=\"/usr/local/go/bin:${PATH}\"\n"), "{df}");
        assert!(df.contains("ENV QUOTED=\"a\\\"b\\\\c\"\n"), "{df}");
        assert!(df.contains("COPY 0-go /tmp/dev-container-features/0-go\n"), "{df}");
        assert!(
            df.contains(
                "RUN chmod -R 0755 /tmp/dev-container-features/0-go && \
cd /tmp/dev-container-features/0-go && \
chmod +x ./devcontainer-features-install.sh && \
./devcontainer-features-install.sh\n"
            ),
            "{df}"
        );
        assert!(!df.contains("\nUSER root\nUSER"), "{df}");
        assert_eq!(df.matches("USER ").count(), 1, "only the initial USER root: {df}");
    }

    #[test]
    fn dockerfile_restores_container_user_when_set() {
        let features = vec![fb("0-common-utils", &[])];
        let df = generate_dockerfile("debian:bookworm", &features, Some("vscode"), "vscode");
        assert!(df.trim_end().ends_with("USER vscode"), "{df}");
        assert!(df.contains("_CONTAINER_USER_HOME=$(getent passwd vscode | cut -d: -f6)"), "{df}");
        assert!(df.contains("_REMOTE_USER_HOME=$(getent passwd vscode | cut -d: -f6)"), "{df}");
    }

    /// Docker-gated: builds a derived image from a synthetic pre-extracted feature
    /// (no network) using the pure generators, then runs it and checks the option
    /// value and remote user landed. Skips (with a message) when `docker info`
    /// fails — so it's a no-op in a sandbox without docker, but exercises the real
    /// build on CI (where it fails instead of skipping).
    #[test_utils::docker_test]
    fn derived_image_builds_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let ctx = std::env::temp_dir().join(format!("devsandbox-feat-build-{stamp}"));
        std::fs::create_dir_all(&ctx).unwrap();
        let tag = format!("devsandbox-feat-test-{stamp}");

        let cleanup = |ctx: &Path, tag: &str| {
            let _ = std::fs::remove_dir_all(ctx);
            let _ = crate::test_support::runtime_cmd().args(["rmi", "-f", tag]).output();
        };

        // Synthetic feature: one option `myopt` (default "fallback"), a
        // containerEnv, and an install.sh writing a marker with the option and
        // remote user. Uses /bin/sh (alpine busybox).
        let mut m = md();
        m.id = Some("marker".into());
        m.name = Some("Marker".into());
        m.version = Some("1.0.0".into());
        m.options.insert("myopt".into(), opt_default(serde_json::json!("fallback")));
        m.container_env = BTreeMap::from([("MARKER_ENV".to_string(), "from-env".to_string())]);

        let feat_dir = ctx.join("0-marker");
        std::fs::create_dir_all(&feat_dir).unwrap();
        std::fs::write(
            feat_dir.join("install.sh"),
            "#!/bin/sh\nset -e\nmkdir -p /opt\n\
             echo \"myopt=$MYOPT remote=$_REMOTE_USER env=$MARKER_ENV\" > /opt/marker\n",
        )
        .unwrap();

        let values = BTreeMap::from([("myopt".to_string(), "chosen".to_string())]);
        let env_file = feature_env_file(&m, &values);
        std::fs::write(feat_dir.join("devcontainer-features.env"), &env_file).unwrap();
        std::fs::write(
            feat_dir.join("devcontainer-features-install.sh"),
            install_wrapper(&m, "local/marker", &env_file),
        )
        .unwrap();
        std::fs::write(
            ctx.join("devcontainer-features.builtin.env"),
            builtin_env("root", "root"),
        )
        .unwrap();

        let builds = vec![FeatureBuild { dir_name: "0-marker".into(), metadata: m }];
        let dockerfile = generate_dockerfile("alpine:3.20", &builds, None, "root");
        let dockerfile_path = ctx.join("Dockerfile.devsandbox-features");
        std::fs::write(&dockerfile_path, dockerfile).unwrap();

        let build = crate::test_support::runtime_cmd()
            .args([
                "build",
                "-t",
                &tag,
                "-f",
                &dockerfile_path.to_string_lossy(),
                &ctx.to_string_lossy(),
            ])
            .output()
            .unwrap();
        if !build.status.success() {
            let stderr = String::from_utf8_lossy(&build.stderr).into_owned();
            cleanup(&ctx, &tag);
            panic!("docker build failed: {stderr}");
        }

        let run = crate::test_support::runtime_cmd()
            .args(["run", "--rm", &tag, "cat", "/opt/marker"])
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&run.stdout).into_owned();
        let ok = run.status.success();
        cleanup(&ctx, &tag);
        assert!(ok, "docker run failed: {}", String::from_utf8_lossy(&run.stderr));
        assert_eq!(stdout.trim(), "myopt=chosen remote=root env=from-env", "marker: {stdout}");
        Ok(())
    }

    #[test]
    fn update_mount_is_read_only_though_the_feature_does_not_say_so() {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("devsandbox-update-ro-{stamp}"));
        let feat = dir.join("cfg/features/upd");
        std::fs::create_dir_all(&feat).unwrap();
        std::fs::write(
            feat.join("devcontainer-feature.json"),
            r#"{"id": "upd",
            "mounts": [
                {"type": "bind", "source": "${sharedVolumes}/upd-bin", "target": "/opt/upd"},
                {"type": "bind", "source": "${sharedVolumes}/upd-rw", "target": "/opt/rw"}
            ],
            "customizations": {"devsandbox": {"updates": [
                {"name": "upd", "mount": "/opt/upd", "command": ["/bin/up"]}
            ]}}}"#,
        )
        .unwrap();
        let config_dir = dir.join("cfg");
        let shared = dir.join("shared");
        let ctx = MountContext {
            config_dir: config_dir.to_str().unwrap(),
            workspace_folder: "/host/app",
            workspace_folder_basename: "app",
            shared_volumes: shared.to_str().unwrap(),
            instance: "app",
            container_env: None,
        };
        let props = SandboxProperties {
            features: Some(BTreeMap::from([(
                "./features/upd".to_string(),
                FeatureOptions::Options(BTreeMap::new()),
            )])),
            ..Default::default()
        };
        let opts = feature_container_opts(&props, &ctx, &[], "/workspaces/app", None);
        let _ = std::fs::remove_dir_all(&dir);
        let shared = shared.to_str().unwrap();
        assert_eq!(
            opts.unwrap().mounts,
            [
                format!("type=bind,source={shared}/upd-bin,target=/opt/upd,readonly"),
                format!("type=bind,source={shared}/upd-rw,target=/opt/rw"),
            ]
        );
    }

    /// Docker-gated: the real derived-image build with a local-folder feature
    /// (`./features/marker` in a temp config dir, not the cwd): resolved in
    /// place, copied into the context as-is (a nested helper file included),
    /// option override and metadata default both land.
    #[test_utils::docker_test]
    fn derived_image_builds_with_local_feature() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let config_dir = std::env::temp_dir().join(format!("devsandbox-local-feat-build-{stamp}"));
        let feat = config_dir.join("features/marker");
        std::fs::create_dir_all(feat.join("lib")).unwrap();
        std::fs::write(
            feat.join("devcontainer-feature.json"),
            r#"{"id": "marker", "name": "Marker", "options": {
                "myopt": {"type": "string", "default": "fallback"},
                "other": {"type": "string", "default": "dflt"}
            },
            "mounts": [{"type": "bind", "source": "${sharedVolumes}/marker", "target": "/opt/m"}],
            "customizations": {"devsandbox": {"updates": [
                {"name": "marker", "mount": "/opt/m", "command": ["/bin/up"], "every": "1d"}
            ]}}}"#,
        )
        .unwrap();
        std::fs::write(feat.join("lib/value.txt"), "nested").unwrap();
        std::fs::write(
            feat.join("install.sh"),
            "#!/bin/sh\nset -e\nmkdir -p /opt\n\
             echo \"myopt=$MYOPT other=$OTHER lib=$(cat lib/value.txt)\" > /opt/marker\n",
        )
        .unwrap();

        let name = format!("localfeat-test-{stamp}");
        let sandbox = ResolvedSandbox {
            name: name.clone(),
            properties: SandboxProperties {
                image: Some("alpine:3.20".into()),
                ..Default::default()
            },
            config_hash: "h".into(),
        };
        let features = BTreeMap::from([(
            "./features/marker".to_string(),
            FeatureOptions::Options(BTreeMap::from([(
                "myopt".to_string(),
                toml::Value::String("chosen".into()),
            )])),
        )]);

        let project = services::project_id(&config_dir).unwrap();
        let result = build_features_image(&config_dir, &project, &sandbox, "alpine:3.20", &features)
            .map_err(|e| format!("{e:#}"))
            .and_then(|tag| {
                let run = crate::test_support::runtime_cmd()
                    .args(["run", "--rm", &tag, "cat", "/opt/marker"])
                    .output()
                    .unwrap();
                let labels = backend().image_labels(&tag);
                let _ = crate::test_support::runtime_cmd().args(["rmi", "-f", &tag]).output();
                let label = labels.map_err(|e| format!("{e:#}"))?.unwrap_or_default();
                let baked = crate::updates::from_label(&label[crate::updates::LABEL]).map_err(|e| format!("{e:#}"))?;
                if baked.len() != 1 || baked[0].source != "${sharedVolumes}/marker" || baked[0].feature != "./features/marker" {
                    return Err(format!("label: {baked:?}"));
                }
                if !run.status.success() {
                    return Err(String::from_utf8_lossy(&run.stderr).into_owned());
                }
                Ok(String::from_utf8_lossy(&run.stdout).trim().to_string())
            });
        let _ = std::fs::remove_dir_all(&config_dir);
        if let Ok(context) = features::build_context_dir(&project, &name) {
            let _ = std::fs::remove_dir_all(context);
        }
        let marker = result.unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(marker, "myopt=chosen other=dflt lib=nested");
        Ok(())
    }

    /// Docker-gated: an image with its own ENTRYPOINT gets the feature
    /// entrypoint chain via the real inspect + same-tag rebuild, and a run
    /// executes feature entrypoint, then image entrypoint, then the command.
    #[test_utils::docker_test]
    fn entrypoint_chain_builds_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let ctx = std::env::temp_dir().join(format!("devsandbox-ep-build-{stamp}"));
        std::fs::create_dir_all(&ctx).unwrap();
        let tag = format!("devsandbox-ep-test-{stamp}");
        let build = |dockerfile: &str| {
            let path = ctx.join("Dockerfile");
            std::fs::write(&path, dockerfile).unwrap();
            crate::test_support::runtime_cmd()
                .args(["build", "-q", "-t", &tag, "-f", &path.to_string_lossy(), &ctx.to_string_lossy()])
                .output()
                .unwrap()
        };
        let cleanup = || {
            let _ = std::fs::remove_dir_all(&ctx);
            let _ = crate::test_support::runtime_cmd().args(["rmi", "-f", &tag]).output();
        };

        // Stand-in for the features build: a feature entrypoint baked in, and
        // an image ENTRYPOINT that must keep running (and pass the command on).
        let base = build(
            "FROM alpine:3.20\n\
RUN printf '#!/bin/sh\\necho feature >> /tmp/log\\nexec \"$@\"\\n' > /usr/local/share/f-init.sh && chmod +x /usr/local/share/f-init.sh\n\
ENTRYPOINT [\"/bin/sh\", \"-c\", \"echo image >> /tmp/log; exec \\\"$@\\\"\", \"image-ep\"]\n",
        );
        if !base.status.success() {
            let stderr = String::from_utf8_lossy(&base.stderr).into_owned();
            cleanup();
            panic!("base build failed: {stderr}");
        }

        let result = (|| -> Result<String, String> {
            let image_entrypoint = crate::runtime::backend()
                .image_entrypoint(&tag)
                .map_err(|e| format!("{e:#}"))?;
            std::fs::write(
                ctx.join(ENTRYPOINT_WRAPPER_FILE),
                entrypoint_wrapper(&[("local/f".into(), "/usr/local/share/f-init.sh".into())]),
            )
            .unwrap();
            let chained = build(&entrypoint_dockerfile(&tag, &image_entrypoint));
            if !chained.status.success() {
                return Err(String::from_utf8_lossy(&chained.stderr).into_owned());
            }
            let run = crate::test_support::runtime_cmd()
                .args(["run", "--rm", &tag, "sh", "-c", "echo cmd >> /tmp/log; cat /tmp/log"])
                .output()
                .unwrap();
            if !run.status.success() {
                return Err(String::from_utf8_lossy(&run.stderr).into_owned());
            }
            Ok(String::from_utf8_lossy(&run.stdout).trim().to_string())
        })();
        cleanup();
        let log = result.unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(log, "feature\nimage\ncmd", "log: {log}");
        Ok(())
    }
}