diff --git a/CLAUDE.md b/CLAUDE.md index 443423043..b9c107c37 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -121,11 +121,11 @@ Created automatically on first run with defaults. Supports emulator types: `aws` Only one `[[containers]]` block may be enabled at a time. `container.Start` rejects a config with more than one block up front (before health/auth checks and image pulls), since running multiple emulators together (e.g. AWS + Snowflake) is unsupported and would otherwise fail later during startup with container-name conflicts or port collisions. The guard lives on the start path (not `config.Get()`) on purpose: recovery/reporting commands like `stop`, `status`, and `logout` must still enumerate multiple running emulators. -Each `[[containers]]` block may set an optional `image` (override the default Docker Hub image) and a `volumes` list of Docker-style bind specs (persistence dir, init hooks, arbitrary mounts). Image/tag precedence, `volume` vs `volumes` semantics, and path-resolution rules are documented in `internal/config/CLAUDE.md`. +Each `[[containers]]` block may set an optional `container_name` (override the derived container name; also what the emulator reports as `MAIN_CONTAINER_NAME`), an optional `image` (override the default Docker Hub image), and a `volumes` list of Docker-style bind specs (persistence dir, init hooks, arbitrary mounts). Container-name derivation and its deliberate decoupling from the default persistence directory, image/tag precedence, `volume` vs `volumes` semantics, and path-resolution rules are documented in `internal/config/CLAUDE.md`. ## Selecting the emulator (`--type`) -`lstk start --type ` (shorthand `-t`; also on the bare root) is the non-interactive answer to the first-run emulator picker. It is a flag only — a positional (`lstk start azure`) is rejected with a hint pointing at `--type`, to avoid implying the root-level `lstk aws`/`lstk az` proxy names mean "start that emulator". It is defined as "rewrite the `type` line in config", not an ephemeral per-run override — downstream commands (`stop`, `status`, `logs`, `volume`, snapshot auto-load) all resolve from the configured type, so persisting keeps config and reality in sync. First run creates the config with the selected type (same `EnsureCreated`/`SetEmulatorType` path the picker uses); a matching config is a no-op; a differing config is switched in place via the surgical type-line rewrite (comments/formatting preserved) with a note naming the file. On switch: a custom `image` is a hard error (it pins a product that can't be reinterpreted under a new type — use `--config` for a separate profile), a non-`latest` `tag` and any `volumes`/`volume` are kept with a warning, and `port`/`env`/`snapshot` are kept silently. Domain logic is `container.ApplyEmulatorType` (parallel to `container.SelectEmulator`); it is applied at the top of `startEmulator` (`cmd/root.go`) before snapshot/start-options are resolved, so it runs before the TUI and its messages go through a plain sink. +`lstk start --type ` (shorthand `-t`; also on the bare root) is the non-interactive answer to the first-run emulator picker. It is a flag only — a positional (`lstk start azure`) is rejected with a hint pointing at `--type`, to avoid implying the root-level `lstk aws`/`lstk az` proxy names mean "start that emulator". It is defined as "rewrite the `type` line in config", not an ephemeral per-run override — downstream commands (`stop`, `status`, `logs`, `volume`, snapshot auto-load) all resolve from the configured type, so persisting keeps config and reality in sync. First run creates the config with the selected type (same `EnsureCreated`/`SetEmulatorType` path the picker uses); a matching config is a no-op; a differing config is switched in place via the surgical type-line rewrite (comments/formatting preserved) with a note naming the file. On switch: a custom `image` is a hard error (it pins a product that can't be reinterpreted under a new type — use `--config` for a separate profile), a non-`latest` `tag` and any `volumes`/`volume` are kept with a warning, and `container_name`/`port`/`env`/`snapshot` are kept silently (they describe the user's topology rather than pinning a product). Domain logic is `container.ApplyEmulatorType` (parallel to `container.SelectEmulator`); it is applied at the top of `startEmulator` (`cmd/root.go`) before snapshot/start-options are resolved, so it runs before the TUI and its messages go through a plain sink. `GATEWAY_LISTEN` (host exposure and published ports) is read from the container's resolved env, not hardcoded; parsing and derivation are documented in `internal/container/CLAUDE.md`. diff --git a/internal/config/CLAUDE.md b/internal/config/CLAUDE.md index 743f9fd04..8dd5ce08e 100644 --- a/internal/config/CLAUDE.md +++ b/internal/config/CLAUDE.md @@ -2,6 +2,16 @@ Detail moved out of the root CLAUDE.md; see the root file for the config search order and creation policy. +## Container name + +Each `[[containers]]` block may set an optional `container_name` to override the derived container name. The key is `container_name` rather than a bare `name` because a `[[containers]]` block already carries several names (the image, the emulator type) and an unqualified `name` reads ambiguously against them. The struct field is `CustomName` (not `Name`) because `ContainerConfig.Name()` is already a method — the same pairing as `CustomImage`/`Image()`. `Name()` returns `CustomName` when set, otherwise `defaultName()` (`localstack-{type}`, or `localstack-{type}-{tag}` when the tag is set and not `latest`). + +The name is load-bearing, not cosmetic: `start.go` exports it as `MAIN_CONTAINER_NAME`, which the emulator uses to introspect itself over the Docker socket and to derive the names of containers it spawns (e.g. `-lambda--`). Setting `MAIN_CONTAINER_NAME` in an `[env.*]` profile instead is a trap — it never reached `docker run --name`, so the container's real and self-reported names disagreed; `startOnce` now warns and points at this field. + +`VolumeDir()`'s default deliberately uses `defaultName()`, **not** `Name()`, so setting or changing `container_name` never silently orphans the persistence directory (and the path stays byte-identical to what existing users already have). Per-instance state is expressible explicitly via `volume`/`volumes`. + +Validation is `validate.ContainerName` (`internal/validate`), called from `ContainerConfig.Validate()`; it mirrors Docker's own `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$` rule so an invalid name fails at config load rather than at container creation. A custom `container_name` survives a `lstk start --type` switch silently (like `port`/`env`/`snapshot`) — it identifies the user's container, it does not pin a product the way `image` does. + ## Container image override Each `[[containers]]` block may set an optional `image` to override the default Docker Hub image (e.g. an internal registry mirror or a locally loaded offline image). `ContainerConfig.Image()` returns `image` as-is when it already carries a tag (so the separately-configured `tag` is dropped in that case), otherwise it appends `tag` (or `latest`); the default `localstack/:` is used when `image` is unset. diff --git a/internal/config/containers.go b/internal/config/containers.go index 3b2794165..d7c7f799d 100644 --- a/internal/config/containers.go +++ b/internal/config/containers.go @@ -11,6 +11,8 @@ import ( "strconv" "strings" "time" + + "github.com/localstack/lstk/internal/validate" ) type EmulatorType string @@ -122,6 +124,12 @@ type ContainerConfig struct { // the default localstack image from Docker Hub. If it carries no tag, Tag (or "latest") // is appended; if it already carries a tag, Tag is dropped. CustomImage string `mapstructure:"image"` + // CustomName overrides the derived container name (see Name). It is also exported into + // the container as MAIN_CONTAINER_NAME, which the emulator uses to introspect itself over + // the Docker socket and to name the containers it spawns (e.g. Lambda). Set it when + // something outside lstk has to address the emulator by a fixed name, such as a sidecar + // proxy on a CI agent. + CustomName string `mapstructure:"container_name"` // Volume is the legacy single-host-directory knob for the persistence mount // (target /var/lib/localstack). It is still honored; new configs can express the // same mount as a Volumes entry targeting persistenceTarget instead. @@ -274,7 +282,11 @@ func (c *ContainerConfig) ExtraVolumes() ([]VolumeMount, error) { // (the mount targeting /var/lib/localstack). Resolution precedence: // 1. A Volumes entry targeting persistenceTarget — its resolved host source. // 2. The legacy Volume field, if set — returned as-is. -// 3. The default os.UserCacheDir()/lstk/volume/. +// 3. The default os.UserCacheDir()/lstk/volume/. +// +// The default deliberately uses defaultName rather than Name: keying it to the derived name +// means setting or changing the container's `container_name` never silently orphans existing state. +// Per-instance state is still expressible explicitly via Volume/Volumes. func (c *ContainerConfig) VolumeDir() (string, error) { mounts, err := c.parsedVolumes() if err != nil { @@ -292,7 +304,7 @@ func (c *ContainerConfig) VolumeDir() (string, error) { if err != nil { return "", fmt.Errorf("failed to determine cache directory: %w", err) } - return filepath.Join(cacheDir, "lstk", "volume", c.Name()), nil + return filepath.Join(cacheDir, "lstk", "volume", c.defaultName()), nil } // TagSuggestion returns an actionable hint naming a recent calendar tag and @@ -339,6 +351,11 @@ func (c *ContainerConfig) Validate() error { if err := validateTag(c.Tag); err != nil { return err } + if c.CustomName != "" { + if err := validate.ContainerName(c.CustomName); err != nil { + return fmt.Errorf("invalid container name %q: %w", c.CustomName, err) + } + } if c.Port == "" { return fmt.Errorf("port is required for %s emulator", c.Type) } @@ -424,8 +441,16 @@ func imageHasTag(image string) bool { return strings.Contains(lastSegment, ":") } -// Name returns the container name: "localstack-{type}" or "localstack-{type}-{tag}" if tag != latest +// Name returns the container name: CustomName when set, otherwise the derived defaultName. func (c *ContainerConfig) Name() string { + if c.CustomName != "" { + return c.CustomName + } + return c.defaultName() +} + +// defaultName is the derived container name: "localstack-{type}" or "localstack-{type}-{tag}" if tag != latest +func (c *ContainerConfig) defaultName() string { tag := c.Tag if tag == "" || tag == "latest" { return fmt.Sprintf("localstack-%s", c.Type) diff --git a/internal/config/containers_test.go b/internal/config/containers_test.go index f9654a6ad..a91dd194a 100644 --- a/internal/config/containers_test.go +++ b/internal/config/containers_test.go @@ -174,6 +174,77 @@ func TestImage_DefaultWhenNoCustomImage(t *testing.T) { assert.Equal(t, "localstack/localstack-pro:latest", image) } +func TestName_DerivedWhenNoCustomName(t *testing.T) { + tests := []struct { + name string + emulatorType EmulatorType + tag string + want string + }{ + {"aws latest", EmulatorAWS, "latest", "localstack-aws"}, + {"aws empty tag", EmulatorAWS, "", "localstack-aws"}, + {"aws pinned tag", EmulatorAWS, "2026.4", "localstack-aws-2026.4"}, + {"snowflake latest", EmulatorSnowflake, "latest", "localstack-snowflake"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &ContainerConfig{Type: tt.emulatorType, Port: "4566", Tag: tt.tag} + assert.Equal(t, tt.want, c.Name()) + }) + } +} + +func TestName_CustomNameWins(t *testing.T) { + c := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "2026.4", CustomName: "ls-jenkins"} + assert.Equal(t, "ls-jenkins", c.Name()) +} + +// A custom name must not move the default persistence directory: renaming the +// container would otherwise silently start the emulator from empty state. +func TestVolumeDir_DefaultIgnoresCustomName(t *testing.T) { + cacheDir, err := os.UserCacheDir() + require.NoError(t, err) + want := filepath.Join(cacheDir, "lstk", "volume", "localstack-aws") + + plain := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest"} + plainDir, err := plain.VolumeDir() + require.NoError(t, err) + assert.Equal(t, want, plainDir) + + renamed := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest", CustomName: "ls-jenkins"} + renamedDir, err := renamed.VolumeDir() + require.NoError(t, err) + assert.Equal(t, want, renamedDir) +} + +func TestValidate_ContainerName(t *testing.T) { + tests := []struct { + name string + customName string + wantErr bool + }{ + {"unset is allowed", "", false}, + {"simple name", "ls-jenkins", false}, + {"dots and underscores", "ls.jenkins_1", false}, + {"leading hyphen rejected", "-ls", true}, + {"slash rejected", "team/ls", true}, + {"shell metachar rejected", "ls;rm -rf /", true}, + {"space rejected", "my emulator", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest", CustomName: tt.customName} + err := c.Validate() + if tt.wantErr { + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid container name") + } else { + require.NoError(t, err) + } + }) + } +} + func TestSelfValidatesLicense(t *testing.T) { // Snowflake and Azure containers activate their own license against the // licensing server, so lstk skips its pre-flight platform license check. diff --git a/internal/config/default_config.toml b/internal/config/default_config.toml index ec37df3e9..4c07d7232 100644 --- a/internal/config/default_config.toml +++ b/internal/config/default_config.toml @@ -10,6 +10,10 @@ type = "aws" # Emulator type. Currently supported: "aws", "snowflake", "azure" tag = "latest" # Docker image tag, e.g. "latest", "2026.4" port = "4566" # Host port the emulator will be accessible on +# container_name = "" # Container name (default: "localstack-", plus "-" +# # when tag is not "latest"). Set it when something outside lstk +# # addresses the emulator by a fixed name, e.g. a sidecar proxy on a +# # CI agent. It is also what the emulator reports as MAIN_CONTAINER_NAME. # image = "" # Custom image to use instead of the default Docker Hub image, e.g. # # an internal registry mirror or a locally loaded offline image. # # If it carries no tag, 'tag' above is appended; if it already diff --git a/internal/container/start.go b/internal/container/start.go index 30ae4af25..2bc43e095 100644 --- a/internal/container/start.go +++ b/internal/container/start.go @@ -195,6 +195,18 @@ func startOnce(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts S gatewayDefaulted := strings.TrimSpace(gatewayValue) == "" containerName := c.Name() + + // MAIN_CONTAINER_NAME is derived from the container's name, not taken from an + // [env.*] profile: the profile value never reached `docker run --name`, so setting + // it there produced a container whose real name and self-reported name disagreed. + // lstk's value is appended after resolvedEnv and wins; say so rather than let the + // user's value vanish silently. + if envHasKey(resolvedEnv, "MAIN_CONTAINER_NAME") { + sink.Emit(output.MessageEvent{ + Severity: output.SeverityWarning, + Text: fmt.Sprintf("Ignoring MAIN_CONTAINER_NAME from your env profile — the emulator is named %q. Set 'container_name' in the [[containers]] block to rename it.", containerName), + }) + } env := append(resolvedEnv, "LOCALSTACK_AUTH_TOKEN="+token, "GATEWAY_LISTEN="+gateway.containerEnvValue(), diff --git a/internal/validate/validate.go b/internal/validate/validate.go index cdb5a9020..6a142ecd7 100644 --- a/internal/validate/validate.go +++ b/internal/validate/validate.go @@ -111,6 +111,36 @@ func PodName(value string) error { return nil } +// containerNameRegexp mirrors Docker's own container-name rule: the first character +// must be alphanumeric, the rest may also include underscores, dots, and hyphens. +// The daemon rejects anything else with "Invalid container name", so accepting it +// here would only defer the failure to container creation. +var containerNameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`) + +// ContainerName validates a user-supplied Docker container name. Like PodName it runs +// ordered deny-checks so the most specific reason wins, then the allow-list. The +// 128-character cap is a local sanity limit against absurd inputs, not a Docker rule. +func ContainerName(value string) error { + const field = "container name" + switch { + case value == "": + return newError(field, RuleEmpty, "must not be empty") + case containsControlChars(value): + return newError(field, RuleControlChars, "contains control characters") + case strings.Contains(value, "%"): + return newError(field, RuleEncoding, "contains percent-encoding (pass the decoded value)") + case strings.ContainsAny(value, "/?#"): + return newError(field, RuleEmbedded, "contains path or query characters (/, ?, #)") + case strings.ContainsAny(value, shellMetaChars): + return newError(field, RuleMetachars, "contains shell metacharacters") + case len(value) > 128: + return newError(field, RuleRange, "must be 128 characters or fewer") + case !containerNameRegexp.MatchString(value): + return newError(field, RuleFormat, "must start with a letter or digit and use only letters, digits, dots, hyphens, and underscores") + } + return nil +} + // serviceListRegexp matches a comma-delimited list of service-name tokens: // letters, digits, underscores, and hyphens, with optional whitespace around // each item and separator. Mirrors the legacy CLI's is_comma_delimited_list diff --git a/internal/validate/validate_test.go b/internal/validate/validate_test.go index 2826c84a5..54629a9f5 100644 --- a/internal/validate/validate_test.go +++ b/internal/validate/validate_test.go @@ -84,6 +84,58 @@ func TestPodName(t *testing.T) { } } +func TestContainerName(t *testing.T) { + t.Parallel() + tests := []struct { + name string + value string + wantErr bool + wantRule string + }{ + {"default derived name", "localstack-aws", false, ""}, + {"derived name with tag", "localstack-aws-2026.4", false, ""}, + {"single char", "a", false, ""}, + {"digit start", "1st-emulator", false, ""}, + {"underscore", "ls_jenkins", false, ""}, + {"period", "ls.jenkins", false, ""}, + {"maximum length", strings.Repeat("a", 128), false, ""}, + {"too long", strings.Repeat("a", 129), true, RuleRange}, + {"empty", "", true, RuleEmpty}, + {"control char", "ba\x00d", true, RuleControlChars}, + {"percent encoding", "ls%2Fmain", true, RuleEncoding}, + {"slash", "team/ls", true, RuleEmbedded}, + {"path traversal", "../etc", true, RuleEmbedded}, + {"embedded query", "ls?fields=name", true, RuleEmbedded}, + {"fragment", "ls#frag", true, RuleEmbedded}, + {"shell metachar semicolon", "ls;rm", true, RuleMetachars}, + {"shell metachar subshell", "ls$(id)", true, RuleMetachars}, + {"shell metachar backtick", "ls`id`", true, RuleMetachars}, + {"leading hyphen", "-ls", true, RuleFormat}, + {"leading underscore", "_ls", true, RuleFormat}, + {"leading dot", ".ls", true, RuleFormat}, + {"space", "my emulator", true, RuleFormat}, + {"colon", "ls:1", true, RuleFormat}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := ContainerName(tt.value) + if (err != nil) != tt.wantErr { + t.Fatalf("ContainerName(%q) error = %v, wantErr %v", tt.value, err, tt.wantErr) + } + if tt.wantRule != "" { + var ve *Error + if !errors.As(err, &ve) { + t.Fatalf("ContainerName(%q) error is not *validate.Error: %v", tt.value, err) + } + if ve.Rule != tt.wantRule { + t.Errorf("ContainerName(%q) Rule = %q, want %q", tt.value, ve.Rule, tt.wantRule) + } + } + }) + } +} + func TestAuthToken(t *testing.T) { t.Parallel() tests := []struct { diff --git a/openspec/changes/json-output-schema/design.md b/openspec/changes/json-output-schema/design.md index f72e15a61..4cd3fa3eb 100644 --- a/openspec/changes/json-output-schema/design.md +++ b/openspec/changes/json-output-schema/design.md @@ -184,7 +184,7 @@ Cobra's built-in version flag (`root.InitDefaultVersionFlag()`) is handled insid ## Command Catalog -This is the artifact meant for human review: every built-in command, whether it gets `--json` support in this proposal, its `data` shape inside the envelope, and the `error.code`s it can realistically produce. Field names are `camelCase` JSON; durations are seconds (`uptimeSeconds`), timestamps are RFC 3339 strings, byte counts are `sizeBytes`. Example `name` values below (e.g. `"localstack-aws"`) are the real default container name for the AWS emulator — `fmt.Sprintf("localstack-%s", c.Type)` in `internal/config/containers.go`'s `ContainerConfig.Name()`, not a placeholder — since a custom `container_name` isn't currently configurable, this is what every reader will actually see. It names the **container**, not the underlying Docker **image** (`localstack/localstack:latest`, resolved separately by `ContainerConfig.Image()`); the two are easy to conflate but the `name` field here is always the former, matching `InstanceInfoEvent.ContainerName`. Commands and flags not listed (`aws`, `terraform`, `cdk`, `sam`, `az` passthrough, extension dispatch, `docs`, `completion`, `help`, `login`, `config profile`, and the `-v`/`--version` flag) are explicitly out of scope — see Non-Goals. +This is the artifact meant for human review: every built-in command, whether it gets `--json` support in this proposal, its `data` shape inside the envelope, and the `error.code`s it can realistically produce. Field names are `camelCase` JSON; durations are seconds (`uptimeSeconds`), timestamps are RFC 3339 strings, byte counts are `sizeBytes`. Example `name` values below (e.g. `"localstack-aws"`) are the real default container name for the AWS emulator — `fmt.Sprintf("localstack-%s", c.Type)` in `internal/config/containers.go`'s `ContainerConfig.defaultName()`, not a placeholder — so this is what a reader sees unless the `[[containers]]` block sets a custom `name`, which `ContainerConfig.Name()` returns in preference. It names the **container**, not the underlying Docker **image** (`localstack/localstack:latest`, resolved separately by `ContainerConfig.Image()`); the two are easy to conflate but the `name` field here is always the former, matching `InstanceInfoEvent.ContainerName`. Commands and flags not listed (`aws`, `terraform`, `cdk`, `sam`, `az` passthrough, extension dispatch, `docs`, `completion`, `help`, `login`, `config profile`, and the `-v`/`--version` flag) are explicitly out of scope — see Non-Goals. ### Emulator lifecycle diff --git a/test/integration/config_test.go b/test/integration/config_test.go index 337ce500e..f1fbbb411 100644 --- a/test/integration/config_test.go +++ b/test/integration/config_test.go @@ -166,6 +166,25 @@ tag = "latest" assert.Contains(t, stderr, "port is required") } +func TestConfigWithInvalidContainerNameFails(t *testing.T) { + t.Parallel() + configContent := ` +[[containers]] +type = "aws" +tag = "latest" +port = "4566" +container_name = "my emulator" +` + configFile := filepath.Join(t.TempDir(), "config.toml") + require.NoError(t, os.WriteFile(configFile, []byte(configContent), 0644)) + + // Rejected at config load, so the failure needs no Docker daemon and no token. + stdout, stderr, err := runLstk(t, testContext(t), t.TempDir(), testEnvWithHome(t.TempDir(), ""), "--config", configFile, "stop") + require.Error(t, err) + requireExitCode(t, 1, err) + assert.Contains(t, stdout+stderr, `invalid container name "my emulator"`) +} + func TestStartWithMultipleContainersFailsFast(t *testing.T) { t.Parallel() configContent := ` diff --git a/test/integration/start_test.go b/test/integration/start_test.go index c9f98b6ee..74ec85bed 100644 --- a/test/integration/start_test.go +++ b/test/integration/start_test.go @@ -688,6 +688,72 @@ func TestStartCommandSetsUpContainerCorrectly(t *testing.T) { }) } +func TestStartCommandUsesCustomContainerName(t *testing.T) { + requireDocker(t) + _ = env.Require(t, env.AuthToken) + + const customName = "lstk-custom-name" + cleanupCustom := func() { + _, _ = dockerClient.ContainerRemove(context.Background(), customName, client.ContainerRemoveOptions{Force: true}) + } + cleanup() + cleanupCustom() + t.Cleanup(cleanup) + t.Cleanup(cleanupCustom) + + mockServer := createMockLicenseServer(true) + defer mockServer.Close() + + configContent := fmt.Sprintf(` +[[containers]] +type = "aws" +tag = "latest" +port = "4566" +container_name = %q +`, customName) + configFile := filepath.Join(t.TempDir(), "config.toml") + require.NoError(t, os.WriteFile(configFile, []byte(configContent), 0644)) + + ctx := testContext(t) + testEnv := env.With(env.APIEndpoint, mockServer.URL) + + stdout, stderr, err := runLstk(t, ctx, "", testEnv, "--config", configFile, "start") + require.NoError(t, err, "lstk start failed: %s%s", stdout, stderr) + + inspect, err := dockerClient.ContainerInspect(ctx, customName, client.ContainerInspectOptions{}) + require.NoError(t, err, "expected a container named %q", customName) + require.True(t, inspect.Container.State.Running) + + // The name Docker gave the container and the name the emulator reports for itself + // (used to introspect itself and to name the containers it spawns) must agree. + envVars := containerEnvToMap(inspect.Container.Config.Env) + assert.Equal(t, customName, envVars["MAIN_CONTAINER_NAME"]) + + _, err = dockerClient.ContainerInspect(ctx, containerName, client.ContainerInspectOptions{}) + assert.Error(t, err, "the derived name %q must not be used when 'name' is set", containerName) + + // The default persistence directory stays keyed to the derived name, so setting or + // changing 'name' never silently orphans existing state. + volumePath, stderr, err := runLstk(t, ctx, "", testEnv, "--config", configFile, "volume", "path") + require.NoError(t, err, "lstk volume path failed: %s", stderr) + assert.Contains(t, volumePath, filepath.Join("lstk", "volume", containerName)) + + // Discovery resolves the custom name for the downstream commands. + statusOut, stderr, err := runLstk(t, ctx, "", testEnv, "--config", configFile, "status") + require.NoError(t, err, "lstk status failed: %s", stderr) + assert.Contains(t, statusOut, "Container: "+customName) + + _, stderr, err = runLstk(t, ctx, "", testEnv, "--config", configFile, "stop") + require.NoError(t, err, "lstk stop failed: %s", stderr) + + // Removal is asynchronous — the container is created with AutoRemove, so an inspect + // immediately after `stop` can still catch it mid-removal. Poll rather than assert once. + require.Eventually(t, func() bool { + _, err := dockerClient.ContainerInspect(ctx, customName, client.ContainerInspectOptions{}) + return err != nil + }, 30*time.Second, 200*time.Millisecond, "lstk stop should have removed %q", customName) +} + func TestStartCommandMountsExtraVolumes(t *testing.T) { requireDocker(t) _ = env.Require(t, env.AuthToken)