Skip to content

feat(auth): interactive profile suggestion + profiles.default - #2333

Merged
Andriy Knysh (aknysh) merged 11 commits into
mainfrom
osterman/interactive-profile-select
Apr 21, 2026
Merged

Andriy Knysh (aknysh) merged 11 commits into
mainfrom
osterman/interactive-profile-select

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

what

  • Add interactive profile suggestion for two scenarios where the loaded atmos.yaml lacks the auth config the user is asking for:
    • Identity-specific: atmos … --identity foo when foo isn't defined in the base config but exists in one or more profiles.
    • Identity-agnostic: atmos auth login/exec/shell/env/console/whoami when the base config has no auth.identities / auth.providers at all but at least one profile does.
  • Interactive terminals get a themed huh prompt (yes/no for a single match, select list for multiple). Picking a profile re-execs Atmos with --profile <picked> prepended to the original argv.
  • Non-interactive terminals (CI, pipes) get the original error enriched with hints naming the candidate profile(s) and the exact --profile <name> flag to re-run.
  • Add profiles.default config field — implicit default profile loaded when --profile and ATMOS_PROFILE are unset; explicit selection always wins; nested defaults are ignored to prevent recursion.
  • Loop guard ATMOS_PROFILE_FALLBACK=1 prevents infinite re-prompt cycles when the picked profile also fails to resolve the identity.
  • Ctrl+C / Esc abort the prompt cleanly with a single User aborted. message instead of cascading identity-not-found / authentication-failed errors.
  • Prompt titles use ui.FormatInline() so backticks render as styled inline code, matching the rest of Atmos.
  • New cfg.ProfilesWithIdentity() and cfg.ProfilesWithAuthConfig() helpers (scoped Viper, no global state pollution) to discover candidate profiles.
  • New AuthManager.MaybeOfferAnyProfileFallback() interface method called by every relevant auth command before returning the terminal "no identity" error.

why

  • Profile-based repos (e.g. cloudposse/infra-live patterns) put all auth.identities / auth.providers inside profiles/<name>/atmos.yaml and leave the root atmos.yaml minimal. Running atmos auth login there errored with no providers available and no actionable next step — users had to read source / docs to discover they needed --profile.
  • The fix turns a dead-end error into a one-keystroke recovery in interactive sessions and a copy-pasteable command in CI logs.
  • profiles.default lets teams pin a sensible profile (e.g. developer) without forcing every shell to export ATMOS_PROFILE, while keeping explicit overrides authoritative.

references

  • PRD: docs/prd/interactive-profile-suggestion.md
  • Blog: website/blog/2026-04-16-interactive-profile-suggestion.mdx
  • Docs: website/docs/cli/configuration/profiles.mdx

Summary by CodeRabbit

  • New Features

    • profiles.default in atmos.yaml (precedence: --profile → ATMOS_PROFILE → profiles.default). Interactive profile suggestion to re-run with --profile when identities or auth config are missing; non‑TTY flows provide enriched rerun hints. Re-exec depth guard and portable re-exec helpers for safer re-run behavior.
  • Bug Fixes

    • Clearer, more actionable error messages and improved fallback routing when identities or auth config are absent.
  • Documentation

    • Added PRD, CLI docs, and blog post describing the behavior.
  • Tests

    • Extensive unit/integration tests covering fallback flows, profile discovery, re-exec, and helpers.

When an identity or auth command can't find its config in the base
`atmos.yaml` but one or more profiles define it, Atmos now prompts
(interactive) or enriches the error with hints (non-interactive) to
suggest switching profiles. Covers `--identity <name>` lookups and the
identity-agnostic `atmos auth login/exec/shell/env/console/whoami`
flows. Also adds `profiles.default` config.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@atmos-pro

atmos-pro Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More.

View pull request changes on Atmos Pro

@github-actions github-actions Bot added the size/l Large size PR label Apr 17, 2026
@mergify

mergify Bot commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label Apr 17, 2026
@github-actions

github-actions Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

The global --interactive flag was registered with env-var binding but
its cobra pflag was never bound to the global viper. As a result,
viper.GetBool("interactive") always returned the default true, and
passing --interactive=false on the command line was silently ignored
by callers that read the flag via viper (e.g. pkg/auth.isInteractive).
Mirror the existing --mask binding so CLI precedence works.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 82626ee3-a926-49c2-914e-7ce66495ad1a

📥 Commits

Reviewing files that changed from the base of the PR and between e2fe626 and 9320ed7.

📒 Files selected for processing (1)
  • cmd/auth_identity_flow_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/auth_identity_flow_test.go

📝 Walkthrough

Walkthrough

Adds interactive and non-interactive profile-fallback flows for auth failures, a profiles.default option in atmos.yaml, a manager hook MaybeOfferAnyProfileFallback, re-exec/chdir utilities, profile-discovery helpers, many tests, and documentation updates. Command wiring now uses command-aware CLI config sources.

Changes

Cohort / File(s) Summary
Cmd auth command edits
cmd/auth_console.go, cmd/auth_env.go, cmd/auth_exec.go, cmd/auth_login.go, cmd/auth_shell.go, cmd/auth_whoami.go, cmd/auth_logout.go, cmd/auth_user.go, cmd/auth_validate.go
Pass command-aware CLI config (newAuthConfigAndStacksInfo(cmd)), unify single ctx usage, and route identity/auth-config failures through maybeOfferProfileFallbackOnAuthConfigError(...) instead of returning raw errors.
Cmd helpers & tests
cmd/auth_profile_fallback.go, cmd/auth_profile_fallback_test.go, cmd/auth_config.go, cmd/auth_config_test.go, cmd/auth_identity_flow_test.go, cmd/auth_console_test.go, cmd/auth_profile_fallback_test.go
Add fallback dispatcher to classify auth-config errors and call manager fallback; add newAuthConfigAndStacksInfo helper and tests for fallback gating, identity resolution, and CLI config sourcing.
Auth manager interface & impl
pkg/auth/types/interfaces.go, pkg/auth/types/mock_interfaces.go, pkg/auth/manager.go
Extend AuthManager with MaybeOfferAnyProfileFallback(ctx) error, add mock hooks, persist cliConfigPath on manager, and invoke manager-level fallback on identity-not-found (returning enriched ErrIdentityNotFound when applicable).
Profile fallback implementation & tests
pkg/auth/profile_fallback.go, pkg/auth/profile_fallback_test.go
Implement interactive/non-interactive profile-fallback flows: candidate discovery, interactive prompts, re-exec with --profile (depth guard), non-TTY enriched errors, and comprehensive unit tests including arg/env rewriting.
Profile helpers & tests
pkg/config/profiles.go, pkg/config/profiles_identity_helpers_test.go, pkg/config/profiles_public_test.go
Add profile inspection helpers (HasExplicitProfile, ProfileDefinesIdentity, ProfilesWithIdentity, ProfileDefinesAuthConfig, ProfilesWithAuthConfig) and unit tests for identity/auth discovery and ordering.
profiles.default support & tests
pkg/schema/schema.go, pkg/config/load.go, pkg/config/load_profiles_default_test.go, tests/fixtures/.../config-profiles-default/*
Add profiles.default to schema and make LoadConfig honor it when no CLI/env profile is set; add fixture/tests validating precedence (flag → env → profiles.default).
Re-exec utilities & wiring
pkg/reexec/..., pkg/version/reexec.go, pkg/version/reexec_test.go, cmd/cmd_utils.go, cmd/cmd_utils_test.go, cmd/alias_test.go
New reexec package (StripChdirArgs, FilterChdirEnv, Exec abstraction, depth tracking) and switch consumers to it; change version re-exec to depth-based guard and update related tests.
Auth test stubs & wrapper
pkg/auth/hooks_test.go, pkg/auth/identities/aws/..._test.go, pkg/auth/providers/aws/saml_test.go, internal/exec/terraform_output_utils.go
Add MaybeOfferAnyProfileFallback() no-op implementations to test stubs and to authContextWrapper (panic placeholder) to satisfy the new interface method in tests.
Docs, PRD, website & lint
docs/prd/interactive-profile-suggestion.md, website/docs/cli/configuration/profiles.mdx, website/blog/2026-04-16-interactive-profile-suggestion.mdx, website/src/data/roadmap.js, tools/lintroller/rule_os_args.go
Add PRD, docs, blog, roadmap entry describing profiles.default and interactive fallback; update lint skip-list for tests that read os.Args.
Root & flag binding
cmd/root.go
Bind Cobra persistent interactive flag into Viper so viper.GetBool("interactive") reflects the flag.
Snapshots / golden
tests/snapshots/...whoami...stderr.golden
Update whoami stderr golden to reflect new phrasing and hint changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI as Auth Command
    participant AuthMgr as AuthManager
    participant Profiles as Profile System
    participant OS as OS Exec

    User->>CLI: atmos auth login --identity missing-id
    CLI->>AuthMgr: Authenticate(ctx, "missing-id")
    AuthMgr->>AuthMgr: resolve identity -> not found
    AuthMgr->>AuthMgr: maybeOfferProfileFallback(ctx, "missing-id")
    AuthMgr->>Profiles: ProfilesWithIdentity("missing-id")
    Profiles-->>AuthMgr: ["profile-a","profile-b"]
    alt Interactive (TTY)
        AuthMgr->>User: prompt select profile
        User-->>AuthMgr: "profile-a"
        AuthMgr->>OS: re-exec with [atmos, --profile, profile-a, ...], set ATMOS_REEXEC_DEPTH=1
        OS->>OS: exec (process replaced)
    else Non-Interactive
        AuthMgr->>AuthMgr: build enriched ErrIdentityNotFound with profile hints
        AuthMgr-->>CLI: return enriched error
    end
Loading
sequenceDiagram
    participant User
    participant CLI as Auth Command
    participant AuthMgr as AuthManager
    participant Profiles as Profile System
    participant OS as OS Exec

    User->>CLI: atmos auth console
    CLI->>AuthMgr: detect no identities
    CLI->>AuthMgr: MaybeOfferAnyProfileFallback(ctx)
    AuthMgr->>Profiles: ProfilesWithAuthConfig()
    Profiles-->>AuthMgr: ["dev-profile","prod-profile"]
    alt Interactive (TTY)
        AuthMgr->>User: prompt select profile
        User-->>AuthMgr: "dev-profile"
        AuthMgr->>OS: re-exec with [atmos, --profile, dev-profile, ...], set ATMOS_REEXEC_DEPTH=1
        OS->>OS: exec (process replaced)
    else Non-Interactive
        AuthMgr->>AuthMgr: build enriched ErrNoIdentitiesAvailable with hints
        AuthMgr-->>CLI: return enriched error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • osterman
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.40% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the two main features: interactive profile suggestion for auth scenarios and the new profiles.default configuration option.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch osterman/interactive-profile-select

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (6)
pkg/config/profiles_identity_helpers_test.go (1)

146-148: Misplaced t.Helper() in a test function.

t.Helper() is meaningful only inside test helpers — inside the test function itself it's a no-op and a bit misleading.

♻️ Proposed tweak
 func TestProfilesWithIdentity_SortedOutput(t *testing.T) {
-	t.Helper()
 	tmpDir := t.TempDir()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/config/profiles_identity_helpers_test.go` around lines 146 - 148, The
TestProfilesWithIdentity_SortedOutput function contains a misplaced t.Helper()
call which is only meaningful inside helper functions; remove the t.Helper()
invocation from TestProfilesWithIdentity_SortedOutput (or move it into any real
helper function used by the test) so the test function itself does not call
t.Helper(); locate the t.Helper() line in TestProfilesWithIdentity_SortedOutput
and delete or relocate it to the appropriate helper function.
pkg/auth/profile_fallback.go (3)

136-142: _ = ctx dead assignment reads as a compiler appeasement.

ctx is accepted but never consulted — no cancellation, no deadline respected during the (potentially blocking) form.Run(). Either plumb it through (e.g., an interrupt channel tied to ctx.Done()) or drop the _ = ctx lines; the parameter is still part of the interface contract, but the unused-assignment nudge isn't earning its keep.

Also applies to: 311-317

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/auth/profile_fallback.go` around lines 136 - 142, The `_ = ctx` lines are
dead-assignment appeasements; either actually honor the passed context by wiring
ctx.Done() into the interactive form to allow cancellation (e.g., create an
interrupt channel watched by form.Run() and close it when ctx.Done() fires, or
pass a context-aware reader/handler into form.Run()), or remove the unused `_ =
ctx` assignments entirely; update the function(s) that accept ctx (referencing
reExecWithProfile, the call to form.Run(), and the other occurrence around the
311–317 block) so the code either plumbs ctx through to form.Run() (or a
cancelable interrupt channel) or drops the unused assignment.

437-446: os.Args[0] is the invocation name, not the re-exec target.

You pass exe (from os.Executable()) to execFunc as argv0, which is correct, but newArgs[0] reuses os.Args[0]. That's usually fine, yet if the user invoked atmos via a symlink/alias (ato, atmos-dev), the child sees the aliased name in its own os.Args[0]. Usually harmless, but worth a brief comment — or normalize to filepath.Base(exe) for consistency across platforms.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/auth/profile_fallback.go` around lines 437 - 446, os.Args[0] (used as
newArgs[0]) may be a symlink/alias name while exe (from os.Executable()) is the
real binary passed to execFunc; normalize the argv0 passed to the re-exec by
replacing newArgs[0] with filepath.Base(exe) (or at least document the choice)
so the child process sees a consistent invocation name; update the construction
of newArgs (and any comments) near where exe, newArgs and execFunc are used to
use filepath.Base(exe) as the first arg instead of os.Args[0] (or add a brief
comment explaining why keeping os.Args[0] is acceptable).

213-218: ErrUnsupportedInputType is a strange wrapper for generic huh.Form.Run errors.

The four form.Run() error sites all wrap any non-ErrUserAborted error as ErrUnsupportedInputType, which is semantically misleading — a TTY resize, a rendering failure, or any other internal huh error has nothing to do with "unsupported input type." Consider a more generic sentinel (e.g., ErrPromptFailed) or just wrap with %w against a purpose-fit error.

Also applies to: 242-247, 381-386, 410-415

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/auth/profile_fallback.go` around lines 213 - 218, Replace the misleading
ErrUnsupportedInputType wrapper used around huh.Form.Run errors with a
purpose-built, generic sentinel (e.g., errUtils.ErrPromptFailed) and wrap the
original error with %w using the existing errUtils.ErrWrapFormat; specifically
update the error handling in the huh.Form.Run blocks (the checks that currently
compare errors.Is(err, huh.ErrUserAborted) then return
fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrUnsupportedInputType, err)) to
instead return fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrPromptFailed, err)
(or wrap with %w) for all occurrences referenced (the form.Run sites including
the blocks around the symbols handling user abort and non-abort errors).
website/blog/2026-04-16-interactive-profile-suggestion.mdx (1)

78-88: ### Generic fallback for all auth commands is nested under ## Guardrails.

That H3 describes a feature, not a guardrail — readers skimming the TOC will miss it. Consider promoting it to an H2 so it sits alongside "What Changed" / "Why This Matters" / "Guardrails".

♻️ Suggested
-### Generic fallback for all auth commands
+## Generic fallback for all auth commands
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@website/blog/2026-04-16-interactive-profile-suggestion.mdx` around lines 78 -
88, The heading "### Generic fallback for all auth commands" is currently nested
under "## Guardrails" but describes a feature and should be promoted to a
top-level section; change that H3 to an H2 (replace "###" with "##" for the
"Generic fallback for all auth commands" heading) and move it so it sits
alongside other H2 sections like "What Changed" / "Why This Matters" /
"Guardrails" to ensure it appears in the TOC as a primary section.
pkg/config/profiles.go (1)

386-403: Redundant per-profile location discovery inside the loop.

ProfilesWithIdentity (and ProfilesWithAuthConfig at 469–481) iterate available and call ProfileDefinesIdentity/ProfileDefinesAuthConfig per profile, each of which re-runs discoverProfileLocations + findProfileDirectory. For N profiles that's O(N²) location scans and duplicate os.Stat work. Harmless for typical sizes, but easy to tighten: inline the viper load against the profileDir you already know from available, or factor a shared helper that takes the prebuilt locations slice.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/config/profiles.go` around lines 386 - 403, ProfilesWithIdentity (and
ProfilesWithAuthConfig) currently loop over available profiles and call
ProfileDefinesIdentity/ProfileDefinesAuthConfig which re-run
discoverProfileLocations + findProfileDirectory causing O(N²) scans; instead,
avoid rediscovering per-profile by reusing the profileDir from available (or
precomputing a shared locations slice) and loading the profile viper directly
from that directory: refactor ProfilesWithIdentity and ProfilesWithAuthConfig to
pass the known profileDir or locations into a new helper (or into
ProfileDefinesIdentity/ProfileDefinesAuthConfig signature) so you only call
discoverProfileLocations/findProfileDirectory once and then perform viper reads
per profile without repeated os.Stat work.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cmd/auth_env.go`:
- Around line 69-70: The wrapped error passed into
maybeOfferProfileFallbackOnAuthConfigError currently loses the
ErrNoDefaultIdentity sentinel because it uses fmt.Errorf with a string; change
the wrapping to use errUtils.ErrWrapFormat (the same pattern used in
auth_shell.go and auth_exec.go) so the returned error preserves the
ErrNoDefaultIdentity sentinel and isNoAuthConfigError can detect it; update the
code that creates wrapped (the fmt.Errorf line) to call
errUtils.ErrWrapFormat(ctxError, "no default identity configured and no identity
specified: %w", err) (or the equivalent ErrWrapFormat signature used in the
repo) so maybeOfferProfileFallbackOnAuthConfigError will trigger the profile
fallback correctly.

In `@cmd/auth_login.go`:
- Around line 82-89: The fallback path in cmd/auth_login.go calls
cfg.InitCliConfig with an empty schema.ConfigAndStacksInfo which causes
--profile and other global flags to be ignored and the re-exec to reload the
base config; instead, before routing into
maybeOfferProfileFallbackOnAuthConfigError ensure you pass the already-populated
global config state (or populate a schema.ConfigAndStacksInfo with the current
global flag values such as --profile, --config, --config-path, --base-path) into
cfg.InitCliConfig so the restarted command honors the selected profile; update
the code paths around AuthenticateProvider,
maybeOfferProfileFallbackOnAuthConfigError, and the InitCliConfig invocation to
use that populated ConfigAndStacksInfo rather than an empty struct.

In `@cmd/auth_whoami.go`:
- Around line 53-56: identityFromFlagOrDefault currently wraps
GetDefaultIdentity errors with ErrInvalidAuthConfig, which prevents
isNoAuthConfigError from recognizing the underlying ErrNoDefaultIdentity and
stops maybeOfferProfileFallbackOnAuthConfigError from triggering; change the
wrapping in identityFromFlagOrDefault so that when GetDefaultIdentity returns an
ErrNoDefaultIdentity (or related no-auth errors) you wrap/top-level return using
ErrNoDefaultIdentity (same pattern used in auth_shell.go and auth_exec.go) so
isNoAuthConfigError will detect it and allow
maybeOfferProfileFallbackOnAuthConfigError to run.

In `@pkg/auth/manager.go`:
- Around line 227-236: The new gate using types.SuppressAuthErrors(ctx) prevents
profile-fallback hints for auth whoami because Whoami() wraps Authenticate()
with types.WithSuppressAuthErrors(..., true); to fix, decouple suppression of
error printing from running profile fallback by changing the condition to a
distinct check (e.g., add and use a new context flag like
types.SuppressAuthProfileFallback(ctx) or invert the logic to always call
m.maybeOfferProfileFallback(ctx, identityName) unless a new explicit "suppress
fallback" flag is set); update callers or WithSuppressAuthErrors to not set the
new flag and ensure Authenticate() still respects the original
types.WithSuppressAuthErrors for printing while maybeOfferProfileFallback is
allowed to run via the new check referencing maybeOfferProfileFallback,
Authenticate, types.WithSuppressAuthErrors, and types.SuppressAuthErrors/
types.SuppressAuthProfileFallback.

In `@pkg/auth/profile_fallback.go`:
- Around line 51-53: The variable execFunc currently points to syscall.Exec
which is a stub on Windows and returns EWINDOWS at runtime; fix by making
execFunc platform-specific: create a unix build file that keeps var execFunc =
syscall.Exec (build tag //go:build unix) and a windows build file (//go:build
windows) that implements execFunc using os/exec to spawn the same binary with
os.Args and os.Environ, wait for the child, propagate its exit status (os.Exit
with child exit code) or return a clear error; alternatively, if you prefer
one-file change, add a runtime OS check around execFunc usage to return a
descriptive error when runtime.GOOS == "windows". Ensure you update the symbol
execFunc accordingly so tests can still mock it.

In `@pkg/config/load_profiles_default_test.go`:
- Around line 23-25: Replace the silent skip when the scenario fixture is
missing with a hard assertion: instead of using os.Stat(...)/os.IsNotExist(...)
and t.Skipf, call the testify/require helpers (e.g., require.NoError(t,
os.Stat(absFixture)) or require.DirExists(t, absFixture)) in the tests in
load_profiles_default_test.go so the test fails loudly when the fixture is
absent; apply the same change to the two other test cases in this file that use
the same os.Stat + t.Skipf pattern.

In `@pkg/config/profiles.go`:
- Around line 327-364: Add deferred perf tracking to each exported function that
performs I/O: insert defer perf.Track(atmosConfig,
"pkg.ProfileDefinesIdentity")() (followed by a blank line) at the top of
ProfileDefinesIdentity and do the same for ProfilesWithIdentity,
ProfileDefinesAuthConfig, and ProfilesWithAuthConfig using their respective
names ("pkg.ProfilesWithIdentity", "pkg.ProfileDefinesAuthConfig",
"pkg.ProfilesWithAuthConfig"); ensure the defer uses the atmosConfig parameter
and is placed immediately after function start (before heavy I/O like
discoverProfileLocations/loadProfileFiles).

In `@website/docs/cli/configuration/profiles.mdx`:
- Around line 52-59: There are two identical "### Precedence" headings causing
duplicate anchors and stale content; remove or rename the older section that
only mentions flag vs env (the one that omits "profiles.default") and either
merge any unique example text into the new full Precedence block (which lists:
--profile, ATMOS_PROFILE, profiles.default, No profile) or rename the old
heading to "### Flag vs. Environment Variable" and delete the redundant rule so
only the canonical "### Precedence" section (including mention of
profiles.default) remains.

In `@website/src/data/roadmap.js`:
- Line 220: Update the roadmap entry object for "Interactive profile suggestion
for missing identities" by adding a pr property set to 2333 (i.e. pr: 2333)
inside that existing object literal (the entry that has label 'Interactive
profile suggestion for missing identities' and status 'shipped'), and while
you’re editing confirm the changelog field 'interactive-profile-suggestion'
remains correct and update the related initiative's progress percentage if
required by the new shipped milestone.

---

Nitpick comments:
In `@pkg/auth/profile_fallback.go`:
- Around line 136-142: The `_ = ctx` lines are dead-assignment appeasements;
either actually honor the passed context by wiring ctx.Done() into the
interactive form to allow cancellation (e.g., create an interrupt channel
watched by form.Run() and close it when ctx.Done() fires, or pass a
context-aware reader/handler into form.Run()), or remove the unused `_ = ctx`
assignments entirely; update the function(s) that accept ctx (referencing
reExecWithProfile, the call to form.Run(), and the other occurrence around the
311–317 block) so the code either plumbs ctx through to form.Run() (or a
cancelable interrupt channel) or drops the unused assignment.
- Around line 437-446: os.Args[0] (used as newArgs[0]) may be a symlink/alias
name while exe (from os.Executable()) is the real binary passed to execFunc;
normalize the argv0 passed to the re-exec by replacing newArgs[0] with
filepath.Base(exe) (or at least document the choice) so the child process sees a
consistent invocation name; update the construction of newArgs (and any
comments) near where exe, newArgs and execFunc are used to use
filepath.Base(exe) as the first arg instead of os.Args[0] (or add a brief
comment explaining why keeping os.Args[0] is acceptable).
- Around line 213-218: Replace the misleading ErrUnsupportedInputType wrapper
used around huh.Form.Run errors with a purpose-built, generic sentinel (e.g.,
errUtils.ErrPromptFailed) and wrap the original error with %w using the existing
errUtils.ErrWrapFormat; specifically update the error handling in the
huh.Form.Run blocks (the checks that currently compare errors.Is(err,
huh.ErrUserAborted) then return fmt.Errorf(errUtils.ErrWrapFormat,
errUtils.ErrUnsupportedInputType, err)) to instead return
fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrPromptFailed, err) (or wrap with
%w) for all occurrences referenced (the form.Run sites including the blocks
around the symbols handling user abort and non-abort errors).

In `@pkg/config/profiles_identity_helpers_test.go`:
- Around line 146-148: The TestProfilesWithIdentity_SortedOutput function
contains a misplaced t.Helper() call which is only meaningful inside helper
functions; remove the t.Helper() invocation from
TestProfilesWithIdentity_SortedOutput (or move it into any real helper function
used by the test) so the test function itself does not call t.Helper(); locate
the t.Helper() line in TestProfilesWithIdentity_SortedOutput and delete or
relocate it to the appropriate helper function.

In `@pkg/config/profiles.go`:
- Around line 386-403: ProfilesWithIdentity (and ProfilesWithAuthConfig)
currently loop over available profiles and call
ProfileDefinesIdentity/ProfileDefinesAuthConfig which re-run
discoverProfileLocations + findProfileDirectory causing O(N²) scans; instead,
avoid rediscovering per-profile by reusing the profileDir from available (or
precomputing a shared locations slice) and loading the profile viper directly
from that directory: refactor ProfilesWithIdentity and ProfilesWithAuthConfig to
pass the known profileDir or locations into a new helper (or into
ProfileDefinesIdentity/ProfileDefinesAuthConfig signature) so you only call
discoverProfileLocations/findProfileDirectory once and then perform viper reads
per profile without repeated os.Stat work.

In `@website/blog/2026-04-16-interactive-profile-suggestion.mdx`:
- Around line 78-88: The heading "### Generic fallback for all auth commands" is
currently nested under "## Guardrails" but describes a feature and should be
promoted to a top-level section; change that H3 to an H2 (replace "###" with
"##" for the "Generic fallback for all auth commands" heading) and move it so it
sits alongside other H2 sections like "What Changed" / "Why This Matters" /
"Guardrails" to ensure it appears in the TOC as a primary section.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c2945bae-9f0b-4693-b489-6c687d09a3ce

📥 Commits

Reviewing files that changed from the base of the PR and between a3fc646 and e21aced.

📒 Files selected for processing (31)
  • cmd/auth_console.go
  • cmd/auth_console_test.go
  • cmd/auth_env.go
  • cmd/auth_exec.go
  • cmd/auth_login.go
  • cmd/auth_profile_fallback.go
  • cmd/auth_shell.go
  • cmd/auth_whoami.go
  • docs/prd/interactive-profile-suggestion.md
  • internal/exec/terraform_output_utils.go
  • pkg/auth/hooks_test.go
  • pkg/auth/identities/aws/assume_role_test.go
  • pkg/auth/identities/aws/assume_root_test.go
  • pkg/auth/manager.go
  • pkg/auth/profile_fallback.go
  • pkg/auth/profile_fallback_test.go
  • pkg/auth/providers/aws/saml_test.go
  • pkg/auth/types/interfaces.go
  • pkg/auth/types/mock_interfaces.go
  • pkg/config/load.go
  • pkg/config/load_profiles_default_test.go
  • pkg/config/profiles.go
  • pkg/config/profiles_identity_helpers_test.go
  • pkg/schema/schema.go
  • tests/fixtures/scenarios/config-profiles-default/atmos.yaml
  • tests/fixtures/scenarios/config-profiles-default/profiles/developer/settings.yaml
  • tests/fixtures/scenarios/config-profiles-default/profiles/production/settings.yaml
  • tools/lintroller/rule_os_args.go
  • website/blog/2026-04-16-interactive-profile-suggestion.mdx
  • website/docs/cli/configuration/profiles.mdx
  • website/src/data/roadmap.js

Comment thread cmd/auth_console.go Resolved
Comment thread cmd/auth_env.go Resolved
Comment thread cmd/auth_login.go Resolved
Comment thread cmd/auth_whoami.go Resolved
Comment thread pkg/auth/manager.go Resolved
Comment thread pkg/auth/profile_fallback.go Resolved
Comment thread pkg/config/profiles.go Resolved
Comment thread website/src/data/roadmap.js Resolved
@codecov

codecov Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.20862% with 52 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.38%. Comparing base (d3fb2d2) to head (9320ed7).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/auth/profile_fallback.go 93.11% 12 Missing and 3 partials ⚠️
pkg/config/profiles.go 85.10% 8 Missing and 6 partials ⚠️
cmd/auth_console.go 0.00% 5 Missing ⚠️
internal/exec/terraform_output_utils.go 0.00% 3 Missing ⚠️
cmd/auth_env.go 33.33% 2 Missing ⚠️
cmd/auth_login.go 60.00% 1 Missing and 1 partial ⚠️
cmd/auth_shell.go 50.00% 2 Missing ⚠️
cmd/cmd_utils.go 0.00% 2 Missing ⚠️
cmd/root.go 0.00% 1 Missing and 1 partial ⚠️
pkg/auth/manager.go 77.77% 1 Missing and 1 partial ⚠️
... and 3 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2333      +/-   ##
==========================================
+ Coverage   77.30%   77.38%   +0.07%     
==========================================
  Files        1084     1089       +5     
  Lines      102466   102828     +362     
==========================================
+ Hits        79212    79569     +357     
+ Misses      18890    18887       -3     
- Partials     4364     4372       +8     
Flag Coverage Δ
unittests 77.38% <88.20%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/auth_config.go 100.00% <100.00%> (ø)
cmd/auth_exec.go 84.15% <100.00%> (+0.15%) ⬆️
cmd/auth_profile_fallback.go 100.00% <100.00%> (ø)
cmd/auth_validate.go 59.25% <100.00%> (ø)
pkg/config/load.go 81.91% <100.00%> (+0.67%) ⬆️
pkg/reexec/chdir.go 100.00% <100.00%> (ø)
pkg/reexec/depth.go 100.00% <100.00%> (ø)
pkg/schema/schema.go 87.70% <ø> (ø)
pkg/version/reexec.go 93.44% <100.00%> (-0.50%) ⬇️
cmd/auth_logout.go 72.55% <0.00%> (ø)
... and 12 more

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Consolidate duplicated re-exec and --chdir argv/env stripping logic from
three independent call sites into a new pkg/reexec package:

- StripChdirArgs handles all five flag forms (--chdir VAL, --chdir=VAL,
  -C VAL, -C=VAL, and the previously-missing concatenated -Cvalue form)
- FilterChdirEnv removes ATMOS_CHDIR and appends an empty override so a
  child cannot re-apply the parent's value via env precedence
- Exec provides a platform-neutral syscall.Exec on Unix and an
  exec.Command().Run() + os.Exit(code) shim on Windows, injectable via
  the package-level var for tests

Migrates three call sites to the shared package:
- pkg/version/reexec.go (fixes missing Windows shim and -Cvalue bug)
- pkg/auth/profile_fallback.go (fixes --chdir double-apply in re-exec'd
  child)
- cmd/cmd_utils.go alias re-exec

Also includes related interactive-profile-select branch work for auth
manager, config profiles, and whoami/env commands.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
cmd/auth_whoami.go (1)

50-55: Consider cmd.Context() for cancellation propagation.

Small nit — auth_env.go uses cmd.Context() for the same fallback call, which carries Cobra's cancellation signal (Ctrl+C handling during the interactive prompt). Using context.Background() here works but drops that plumbing. Since the fallback path can launch an interactive prompt, propagating the command context would be a touch friendlier.

♻️ Optional tweak
-	ctx := context.Background()
-
+	ctx := cmd.Context()
+
 	// Determine identity.
 	identityName, err := identityFromFlagOrDefault(cmd, authManager)
 	if err != nil {
 		return maybeOfferProfileFallbackOnAuthConfigError(ctx, authManager, err)
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_whoami.go` around lines 50 - 55, Replace the local background
context with the Cobra command's context so cancellation/interrupts propagate
into the fallback interactive flow: in cmd/auth_whoami.go, use cmd.Context()
instead of context.Background() when creating ctx before calling
identityFromFlagOrDefault and maybeOfferProfileFallbackOnAuthConfigError so the
interactive prompt in maybeOfferProfileFallbackOnAuthConfigError receives the
command cancellation signal.
website/docs/cli/configuration/profiles.mdx (1)

291-315: Interactive Profile Suggestion section reads well and is implementation-accurate.

The two flows (identity-specific vs. generic auth fallback), the interactive-vs-non-interactive split, the "explicit --profile/ATMOS_PROFILE suppresses prompts but profiles.default does not", and the ATMOS_PROFILE_FALLBACK=1 loop guard all match pkg/auth/profile_fallback.go (loopGuardActive, reexecWithProfileAndGuard, maybeOfferAnyProfileFallback).

One tiny wording nit you can take or leave: line 299 says the picked profile is "prepended to your original arguments", but setOrAddProfileArg replaces an existing --profile in argv if present and otherwise adds it — so "prepended or replacing any existing --profile" would be marginally more precise. Not a blocker.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@website/docs/cli/configuration/profiles.mdx` around lines 291 - 315, The doc
text claiming the picked profile is "prepended to your original arguments" is
slightly inaccurate because the implementation (setOrAddProfileArg) will replace
an existing --profile arg instead of always prepending; update the wording in
the "Identity-specific suggestion" sentence to say something like "prepended or
replacing any existing --profile" to match setOrAddProfileArg and the re-exec
behavior (see setOrAddProfileArg and reexecWithProfileAndGuard for reference).
cmd/alias_test.go (1)

84-138: Subtest name no longer matches what's being tested.

The subtest is labeled "filterChdirArgs removes chdir flags" but the call is now reexec.StripChdirArgs. Same story for "filterChdirEnv removes ATMOS_CHDIR from environment" below. Harmless, but future grep-by-name will miss it.

🏷️ Proposed rename
-	t.Run("filterChdirArgs removes chdir flags", func(t *testing.T) {
+	t.Run("StripChdirArgs removes chdir flags", func(t *testing.T) {
 ...
-	t.Run("filterChdirEnv removes ATMOS_CHDIR from environment", func(t *testing.T) {
+	t.Run("FilterChdirEnv removes ATMOS_CHDIR from environment", func(t *testing.T) {

Also note: this test duplicates coverage already in pkg/reexec/chdir_test.go. Keeping an alias-level smoke test is fine, but you could slim it to one case per function and rely on the reexec package tests for exhaustive coverage.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/alias_test.go` around lines 84 - 138, Rename the subtest labels to match
the functions under test and optionally reduce duplication: update the t.Run
main description from "filterChdirArgs removes chdir flags" to reference
reexec.StripChdirArgs (e.g., "StripChdirArgs removes chdir flags") and similarly
rename the other subtest currently saying "filterChdirEnv removes ATMOS_CHDIR
from environment" to reference reexec.StripChdirEnv; if desired, shrink the test
matrix to one representative case per alias-level test since
pkg/reexec/chdir_test.go already has exhaustive coverage. Ensure the referenced
symbols reexec.StripChdirArgs and reexec.StripChdirEnv are used in the renamed
subtest names so future grep-by-name finds them.
pkg/reexec/chdir.go (1)

41-45: Short-flag prefix check is greedy enough to risk future collisions.

strings.HasPrefix(arg, "-C") && len(arg) > 2 matches every short-flag token starting with -C (e.g., a hypothetical -Color, -Credentials). Atmos doesn't have such flags today, but if one is ever added under a subcommand with DisableFlagParsing, this will silently strip it.

A cheap hardening: require the next rune to look like a value (anything non-alpha) or simply document the constraint. Optional, not blocking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/reexec/chdir.go` around lines 41 - 45, The short-flag prefix check in the
arg loop is too greedy; replace the condition (strings.HasPrefix(arg, "-C") &&
len(arg) > 2) with a guarded check that the character/rune after "-C" looks like
a value (not an ASCII/Unicode letter) to avoid stripping longer flags like
"-Color"; e.g. decode the next rune (utf8.DecodeRuneInString(arg[2:])) and only
treat it as a "-C" value form when that rune is not a letter (use
unicode.IsLetter) or when it is '='; update pkg/reexec/chdir.go accordingly and
add the required imports (unicode, utf8).
pkg/version/reexec_test.go (1)

772-796: LGTM.

Good that the concatenated -C../foo case is now asserted end-to-end through reexec.StripChdirArgs + stripUseVersionFlags. If you adopt the -- separator fix in pkg/reexec/chdir.go, consider adding one case here with a trailing -- to lock in pass-through behavior across the combined pipeline.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/version/reexec_test.go` around lines 772 - 796, Add one more subcase to
TestStripBothChdirAndUseVersionFlags that includes a trailing "--" separator to
verify pass-through behavior when combining reexec.StripChdirArgs and
stripUseVersionFlags; construct args similar to the existing cases but include
"--" before the command (e.g. "atmos", "--chdir=...", "--use-version=...", "--",
"terraform", "plan"), run result := reexec.StripChdirArgs(args) then result =
stripUseVersionFlags(result) and assert the output equals []string{"atmos",
"terraform", "plan"} to lock in the separator handling across the pipeline.
pkg/version/reexec.go (1)

48-52: LGTM on the alias-with-deprecation.

Type alias keeps source compatibility while steering new code to reexec.ExecFunc. Consider adding a //lint:ignore or follow-up issue tag to actually remove it on the next minor bump so the deprecation doesn't linger forever.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/version/reexec.go` around lines 48 - 52, Add a short TODO + tracking note
and (optionally) a lint-ignore above the type alias to mark it for removal
later: place a comment immediately above the ExecFunc alias that says something
like "TODO: remove ExecFunc alias in next minor release (follow-up issue `#NNN`)"
and, if you want to suppress deprecation/lint noise, add a lint-ignore directive
on the same comment (e.g. "//lint:ignore <rule> keep alias for source
compatibility") referencing the ExecFunc = reexec.ExecFunc alias so future
maintainers know to remove it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/reexec/chdir.go`:
- Around line 28-58: StripChdirArgs currently continues scanning past the
end-of-flags marker ("--") and may drop or consume positional args that should
be forwarded; update StripChdirArgs to detect a literal "--" token and, when
seen, append that token and all remaining args unchanged to filtered and break
out of the loop so no further flag-stripping or skipNext consumption occurs;
ensure this preserves behavior of the existing handling for "--chdir", "-C", and
their values when encountered before the "--" marker.

---

Nitpick comments:
In `@cmd/alias_test.go`:
- Around line 84-138: Rename the subtest labels to match the functions under
test and optionally reduce duplication: update the t.Run main description from
"filterChdirArgs removes chdir flags" to reference reexec.StripChdirArgs (e.g.,
"StripChdirArgs removes chdir flags") and similarly rename the other subtest
currently saying "filterChdirEnv removes ATMOS_CHDIR from environment" to
reference reexec.StripChdirEnv; if desired, shrink the test matrix to one
representative case per alias-level test since pkg/reexec/chdir_test.go already
has exhaustive coverage. Ensure the referenced symbols reexec.StripChdirArgs and
reexec.StripChdirEnv are used in the renamed subtest names so future
grep-by-name finds them.

In `@cmd/auth_whoami.go`:
- Around line 50-55: Replace the local background context with the Cobra
command's context so cancellation/interrupts propagate into the fallback
interactive flow: in cmd/auth_whoami.go, use cmd.Context() instead of
context.Background() when creating ctx before calling identityFromFlagOrDefault
and maybeOfferProfileFallbackOnAuthConfigError so the interactive prompt in
maybeOfferProfileFallbackOnAuthConfigError receives the command cancellation
signal.

In `@pkg/reexec/chdir.go`:
- Around line 41-45: The short-flag prefix check in the arg loop is too greedy;
replace the condition (strings.HasPrefix(arg, "-C") && len(arg) > 2) with a
guarded check that the character/rune after "-C" looks like a value (not an
ASCII/Unicode letter) to avoid stripping longer flags like "-Color"; e.g. decode
the next rune (utf8.DecodeRuneInString(arg[2:])) and only treat it as a "-C"
value form when that rune is not a letter (use unicode.IsLetter) or when it is
'='; update pkg/reexec/chdir.go accordingly and add the required imports
(unicode, utf8).

In `@pkg/version/reexec_test.go`:
- Around line 772-796: Add one more subcase to
TestStripBothChdirAndUseVersionFlags that includes a trailing "--" separator to
verify pass-through behavior when combining reexec.StripChdirArgs and
stripUseVersionFlags; construct args similar to the existing cases but include
"--" before the command (e.g. "atmos", "--chdir=...", "--use-version=...", "--",
"terraform", "plan"), run result := reexec.StripChdirArgs(args) then result =
stripUseVersionFlags(result) and assert the output equals []string{"atmos",
"terraform", "plan"} to lock in the separator handling across the pipeline.

In `@pkg/version/reexec.go`:
- Around line 48-52: Add a short TODO + tracking note and (optionally) a
lint-ignore above the type alias to mark it for removal later: place a comment
immediately above the ExecFunc alias that says something like "TODO: remove
ExecFunc alias in next minor release (follow-up issue `#NNN`)" and, if you want to
suppress deprecation/lint noise, add a lint-ignore directive on the same comment
(e.g. "//lint:ignore <rule> keep alias for source compatibility") referencing
the ExecFunc = reexec.ExecFunc alias so future maintainers know to remove it.

In `@website/docs/cli/configuration/profiles.mdx`:
- Around line 291-315: The doc text claiming the picked profile is "prepended to
your original arguments" is slightly inaccurate because the implementation
(setOrAddProfileArg) will replace an existing --profile arg instead of always
prepending; update the wording in the "Identity-specific suggestion" sentence to
say something like "prepended or replacing any existing --profile" to match
setOrAddProfileArg and the re-exec behavior (see setOrAddProfileArg and
reexecWithProfileAndGuard for reference).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f4990b7f-b709-4613-87ed-b8c206fe39b9

📥 Commits

Reviewing files that changed from the base of the PR and between 69c816e and e12f106.

📒 Files selected for processing (20)
  • cmd/alias_test.go
  • cmd/auth_env.go
  • cmd/auth_whoami.go
  • cmd/cmd_utils.go
  • cmd/cmd_utils_test.go
  • pkg/auth/manager.go
  • pkg/auth/profile_fallback.go
  • pkg/auth/profile_fallback_test.go
  • pkg/config/load_profiles_default_test.go
  • pkg/config/profiles.go
  • pkg/reexec/chdir.go
  • pkg/reexec/chdir_test.go
  • pkg/reexec/exec.go
  • pkg/reexec/exec_test.go
  • pkg/reexec/exec_unix.go
  • pkg/reexec/exec_windows.go
  • pkg/version/reexec.go
  • pkg/version/reexec_test.go
  • website/docs/cli/configuration/profiles.mdx
  • website/src/data/roadmap.js
✅ Files skipped from review due to trivial changes (6)
  • pkg/reexec/exec.go
  • cmd/cmd_utils_test.go
  • website/src/data/roadmap.js
  • pkg/reexec/chdir_test.go
  • pkg/auth/profile_fallback_test.go
  • pkg/auth/profile_fallback.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/auth/manager.go
  • pkg/config/load_profiles_default_test.go
  • pkg/config/profiles.go

Comment thread pkg/reexec/chdir.go Resolved
Replace two separate re-exec loop-guard env vars with a single shared
ATMOS_REEXEC_DEPTH counter in pkg/reexec:

- ATMOS_PROFILE_FALLBACK (auth) — binary "we re-exec'd, don't loop"
- ATMOS_REEXEC_GUARD (version) — version-string match check

The new Depth/CurrentDepth/NextEnv helpers let both call sites detect
"am I inside a re-exec'd child?" with identical semantics. Version's
guard loses its version-string-matching precision, but gains a harder
guarantee: depth > 0 prevents any further re-exec regardless of what
the child's atmos.yaml asks for, eliminating loop risk.

"Fallback" was a misleading name for what is really a loop-guard
depth counter, and having two separate env vars doing the same job
was pure duplication.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
pkg/reexec/depth_test.go (1)

95-110: Nit: strings.HasPrefix would mirror the production check.

depth.go:55 uses strings.HasPrefix(kv, DepthEnvVar+"="); using the same idiom here makes the intent obvious and drops the length arithmetic.

+	prefix := DepthEnvVar + "="
 	for _, kv := range result {
-		if len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+"=" {
+		if strings.HasPrefix(kv, prefix) {
 			count++
 			lastDepth = kv
 		}
 	}
 	...
 	for _, kv := range tt.input {
-		if len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+"=" {
+		if strings.HasPrefix(kv, prefix) {
 			continue
 		}
 		assert.Contains(t, result, kv, "non-depth entry must be preserved")
 	}

(Would require adding the strings import.)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/reexec/depth_test.go` around lines 95 - 110, Replace the manual prefix
check "len(kv) >= len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] ==
DepthEnvVar+\"=\" " with strings.HasPrefix(kv, DepthEnvVar+\"=\") in the loops
that inspect kv (used alongside variables result and lastDepth) so the test
mirrors the production check in depth.go; add the strings import to the test
file imports. Ensure both places (the counting loop and the
non-depth-preservation loop) use strings.HasPrefix(kv, DepthEnvVar+"=").
pkg/version/reexec.go (1)

242-264: Consider reexec.NextEnv instead of SetEnv + Environ() for depth propagation.

The new pkg/reexec package already ships NextEnv (used by pkg/auth/profile_fallback.go:446) that handles the increment/collapse semantics on a local env slice without mutating the parent process. Two downsides of the current approach:

  • cfg.SetEnv (default os.Setenv) mutates the parent's env, so if cfg.ExecFn returns an error on L261 the counter stays incremented in the orphaned parent.
  • Two call sites now express the same guard two different ways, which makes future changes to the semantics brittle.
♻️ Proposed shape
-	// Increment re-exec depth so the child knows it's inside a re-exec and
-	// must not attempt another version switch.
-	nextDepth := reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar)) + 1
-	if err := cfg.SetEnv(reexec.DepthEnvVar, strconv.Itoa(nextDepth)); err != nil {
-		log.Warn("Failed to set re-exec depth", "error", err)
-		return false
-	}
-
 	// Re-exec with the new binary.
 	ui.Successf("Switching to Atmos version `%s`", requestedVersion)
 
 	// Strip flags that shouldn't be passed to the target version.
 	args := reexec.StripChdirArgs(cfg.Args)
 	args = stripUseVersionFlags(args)
 
-	if err := cfg.ExecFn(binaryPath, args, cfg.Environ()); err != nil {
+	if err := cfg.ExecFn(binaryPath, args, reexec.NextEnv(cfg.Environ())); err != nil {
 		ui.Errorf("Failed to exec %s: %v", binaryPath, err)
 		return false
 	}

This also lets you drop the strconv import and the SetEnv touch in TestCheckAndReexecWithConfig_GuardIsSet (the depth would instead be asserted by inspecting envv in ExecFn).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/version/reexec.go` around lines 242 - 264, Replace the current
SetEnv+Environ depth propagation with reexec.NextEnv to avoid mutating the
parent env and to centralize depth semantics: compute nextDepth using
reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar))+1, then call
reexec.NextEnv(cfg.Environ(), reexec.DepthEnvVar, strconv.Itoa(nextDepth)) (or
equivalent NextEnv overload) and pass that returned slice into
cfg.ExecFn(binaryPath, args, envSlice) instead of calling cfg.SetEnv and
cfg.Environ(); keep the same guard variables (reexec.DepthEnvVar, reexec.Depth)
and preserve argv stripping (reexec.StripChdirArgs / stripUseVersionFlags) and
error handling around cfg.ExecFn so behavior is unchanged but parent env is not
mutated.
pkg/auth/profile_fallback.go (1)

84-137: Unused ctx parameter — consider dropping it (or wiring it in).

Both maybeOfferProfileFallback and maybeOfferAnyProfileFallback accept a ctx context.Context that's never consulted — the _ = ctx after the unreachable re-exec (L135, L310) makes it explicit. Per the coding guideline, context.Context should be used for cancellation/deadlines, not carried around for its own sake.

Two options:

  • Drop ctx from the unexported helpers. MaybeOfferAnyProfileFallback(ctx) can keep it for its public shape and simply not forward it.
  • Forward it into cfg.ProfilesWith… and the prompt form.Run() path once those helpers support cancellation.

Not a blocker for this PR — flagging for hygiene.

As per coding guidelines: "Use context.Context ONLY for cancellation signals, deadlines/timeouts, and request-scoped values ... Do NOT use context for ... avoiding proper function parameters."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/auth/profile_fallback.go` around lines 84 - 137, The ctx parameter is
unused in maybeOfferProfileFallback (and maybeOfferAnyProfileFallback); either
remove it from these unexported helpers or thread it into cancelable calls —
specifically, delete the ctx argument from manager.maybeOfferProfileFallback and
manager.maybeOfferAnyProfileFallback and update all internal callers to call the
no-ctx variants (keeping the public MaybeOfferAnyProfileFallback(ctx) signature
if needed), or alternatively pass ctx into cfg.ProfilesWithIdentity and into
promptForProfileSelection/form.Run if those APIs are changed to accept
cancellation; locate uses by the function names maybeOfferProfileFallback,
maybeOfferAnyProfileFallback, cfg.ProfilesWithIdentity, and
promptForProfileSelection to make the minimal edits and update call sites
accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/auth/profile_fallback.go`:
- Around line 84-137: The ctx parameter is unused in maybeOfferProfileFallback
(and maybeOfferAnyProfileFallback); either remove it from these unexported
helpers or thread it into cancelable calls — specifically, delete the ctx
argument from manager.maybeOfferProfileFallback and
manager.maybeOfferAnyProfileFallback and update all internal callers to call the
no-ctx variants (keeping the public MaybeOfferAnyProfileFallback(ctx) signature
if needed), or alternatively pass ctx into cfg.ProfilesWithIdentity and into
promptForProfileSelection/form.Run if those APIs are changed to accept
cancellation; locate uses by the function names maybeOfferProfileFallback,
maybeOfferAnyProfileFallback, cfg.ProfilesWithIdentity, and
promptForProfileSelection to make the minimal edits and update call sites
accordingly.

In `@pkg/reexec/depth_test.go`:
- Around line 95-110: Replace the manual prefix check "len(kv) >=
len(DepthEnvVar)+1 && kv[:len(DepthEnvVar)+1] == DepthEnvVar+\"=\" " with
strings.HasPrefix(kv, DepthEnvVar+\"=\") in the loops that inspect kv (used
alongside variables result and lastDepth) so the test mirrors the production
check in depth.go; add the strings import to the test file imports. Ensure both
places (the counting loop and the non-depth-preservation loop) use
strings.HasPrefix(kv, DepthEnvVar+"=").

In `@pkg/version/reexec.go`:
- Around line 242-264: Replace the current SetEnv+Environ depth propagation with
reexec.NextEnv to avoid mutating the parent env and to centralize depth
semantics: compute nextDepth using
reexec.Depth(cfg.GetEnv(reexec.DepthEnvVar))+1, then call
reexec.NextEnv(cfg.Environ(), reexec.DepthEnvVar, strconv.Itoa(nextDepth)) (or
equivalent NextEnv overload) and pass that returned slice into
cfg.ExecFn(binaryPath, args, envSlice) instead of calling cfg.SetEnv and
cfg.Environ(); keep the same guard variables (reexec.DepthEnvVar, reexec.Depth)
and preserve argv stripping (reexec.StripChdirArgs / stripUseVersionFlags) and
error handling around cfg.ExecFn so behavior is unchanged but parent env is not
mutated.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 85cc560e-d9f2-41ac-a9b5-8dc7bb383045

📥 Commits

Reviewing files that changed from the base of the PR and between e12f106 and 9c8522a.

📒 Files selected for processing (7)
  • pkg/auth/profile_fallback.go
  • pkg/auth/profile_fallback_test.go
  • pkg/auth/types/interfaces.go
  • pkg/reexec/depth.go
  • pkg/reexec/depth_test.go
  • pkg/version/reexec.go
  • pkg/version/reexec_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/auth/types/interfaces.go

Tokens after the POSIX `--` separator are positional and must be
forwarded verbatim to downstream tools (terraform, helmfile, packer,
custom commands). Previously StripChdirArgs kept scanning past `--`,
so a user-supplied `-C`, `-Cfile`, `--chdir`, or `--chdir=...` meant
for the child tool would be silently dropped or consumed along with
the following token.

Once `--` is encountered, forward it and every remaining arg unchanged.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace back-to-back CheckErrorAndPrint + CheckErrorPrintAndExit with a
single rich error built via errUtils.Build, carrying the explanation,
hint, context, and exit code. Prior behavior printed two nearly-
identical error blocks; a recent SuppressAuthErrors gate hid the inner
block entirely, leaving only a bare "identity not found" line.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Apr 17, 2026
… subcommands

Every auth subcommand passed an empty schema.ConfigAndStacksInfo{} to
InitCliConfig, silently dropping the parent's already-parsed
--config, --base-path, and --config-path flags. After the profile-picker
re-exec, the child process therefore couldn't find the custom config file
that the parent used, reproducing the same ErrInvalidAuthConfig that
triggered the picker in the first place.

Introduce newAuthConfigAndStacksInfo(cmd) in cmd/auth_config.go that reads
the three global flags via the existing flags.ParseGlobalFlags helper
(same pattern as cmd/auth_list.go). Route every auth subcommand's
InitCliConfig call through it.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Adds targeted tests for the fallback dispatcher, the new
newAuthConfigAndStacksInfo helper, the shared identity-resolution helper
that every auth subcommand relies on, and the public profile-discovery
helpers in pkg/config.

Coverage improvements:
- cmd/auth_config.go: 100%
- cmd/auth_profile_fallback.go: 100% (isNoAuthConfigError + dispatcher)
- pkg/auth/profile_fallback.go: MaybeOfferAnyProfileFallback 0->100%,
  newProfileFallbackKeyMap 0->100%, plus reExecWithProfile regression
  guards that verify --chdir is stripped from argv and ATMOS_CHDIR is
  emitted as an empty override (not inherited) on re-exec
- pkg/config/profiles.go: ProfilesWithIdentity 78.9->89.5%,
  ProfilesWithAuthConfig 78.9->89.5%,
  ProfileDefinesAuthConfig 86.4->90.9%

The identity-flow test drives GetIdentityFromFlags through cobra and
viper rather than os.Args to avoid global-state races across tests.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@osterman

Copy link
Copy Markdown
Member Author

Addressing CodeRabbit feedback

Pushed e461bcdf8 covering both structural concerns.

Claim 1: cmd/auth_env.go:69 drops the ErrNoDefaultIdentity sentinel — already correct

The current code already uses the same pattern as auth_shell.go and auth_exec.go:

wrapped := fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrNoDefaultIdentity, err)

ErrWrapFormat is "%w: %w" (errors/errors.go:12). Two %w directives preserve both the sentinel and the underlying error in the chain, so errors.Is(wrapped, errUtils.ErrNoDefaultIdentity) — which is what isNoAuthConfigError uses — returns true. The proposed diff in the bot's suggestion matches the code as-is; no change was needed.

New coverage: cmd/auth_identity_flow_test.go:TestIdentityFromFlagOrDefault explicitly asserts assert.ErrorIs(t, err, errUtils.ErrNoDefaultIdentity) on the wrapped return, and TestIdentityFromFlagOrDefault_ErrorReachesFallbackDispatcher proves the dispatcher fires for that wrapped error end-to-end.

Claim 2: Re-exec into the same broken config — real, fixed in this PR

The bug was subtle: every auth subcommand called cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false) with an empty struct, silently dropping the parent's already-parsed --config, --base-path, and --config-path. After the profile-picker re-exec injected --profile <picked> into child argv, the child still couldn't find the custom config file the parent used, reproducing the same ErrInvalidAuthConfig that triggered the picker.

(Note: the --profile flag itself always survives — it's re-read in the child via parseProfilesFromOsArgs(os.Args) on the DisableFlagParsing commands, and via PersistentPreRun → global viper on normal commands. The bug was specifically the other three global flags.)

Fix: new newAuthConfigAndStacksInfo(cmd) helper in cmd/auth_config.go that reads all three global flags via the existing flags.ParseGlobalFlags (same pattern as cmd/auth_list.go). Every auth subcommand (env, console, login, logout, shell, exec, user, validate, whoami) now routes its InitCliConfig call through it.

New coverage:

  • cmd/auth_config_test.go:TestNewAuthConfigAndStacksInfo — table-driven verification that each global flag propagates into the returned ConfigAndStacksInfo.
  • pkg/auth/profile_fallback_test.go:TestReExecWithProfile_StripsChdirFromArgv / _FiltersChdirFromEnv — regression guards that the re-exec argv contains the picked profile and does not leak --chdir/-C into child args, and that ATMOS_CHDIR= is emitted as an explicit empty override (not inherited).

Coverage

Patch coverage is addressed in the second commit:

  • cmd/auth_config.go → 100%
  • cmd/auth_profile_fallback.go → 100% (both isNoAuthConfigError and the dispatcher)
  • pkg/auth/profile_fallback.go → MaybeOfferAnyProfileFallback 0→100%, newProfileFallbackKeyMap 0→100%, plus new reExecWithProfile chdir regression guards
  • pkg/config/profiles.go → ProfilesWithIdentity 78.9→89.5%, ProfilesWithAuthConfig 78.9→89.5%, ProfileDefinesAuthConfig 86.4→90.9%

Waiting on Codecov for the full patch %.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (5)
pkg/config/profiles_public_test.go (1)

1-239: LGTM — solid coverage for the new profile-discovery helpers.

Fixture is compact and reused cleanly across all three helper tests, nil/whitespace/not-found contracts are exercised, sorted-output expectations match the sort.Strings behavior in pkg/config/profiles.go, and the malformed-YAML skip paths are asserted by outcome (valid profiles still returned) rather than by coupling to loader internals. Table-driven classification test at lines 217-238 is a nice touch.

One tiny optional thought: the two malformed-YAML blocks (lines 102-108 and 163-169) are identical — if a third caller shows up, consider extracting a writeBrokenProfile(t, tmpDir, name) helper. Not worth doing for just two call sites.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/config/profiles_public_test.go` around lines 1 - 239, Two identical
malformed-YAML test setups are duplicated in TestProfilesWithIdentity and
TestProfilesWithAuthConfig; extract a small helper (e.g., writeBrokenProfile(t
*testing.T, tmpDir, name string)) and use it from both tests to create the
"broken" profile directory and atmos.yaml so duplication is removed; update the
two call sites to call writeBrokenProfile and keep existing assertions and
temp-dir usage (references: profilesPublicTestFixture, TestProfilesWithIdentity,
TestProfilesWithAuthConfig).
cmd/auth_identity_flow_test.go (3)

139-142: Minor: assert.Same is a tighter fit than assert.Equal here.

maybeOfferProfileFallbackOnAuthConfigError returns the fallback error instance unchanged, so identity equality is the actual contract. assert.Same(t, fallbackInvoked, result, ...) expresses that intent directly and would catch an accidental wrap/copy that assert.Equal on *errors.errorString might still let through in edge cases.

-	assert.Equal(t, fallbackInvoked, result,
-		"when the fallback returns an error, it must propagate to the caller unchanged")
+	assert.Same(t, fallbackInvoked, result,
+		"when the fallback returns an error, it must propagate to the caller unchanged")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_identity_flow_test.go` around lines 139 - 142, The test should
assert identity equality rather than value equality: in the assertion for the
fallback error returned by maybeOfferProfileFallbackOnAuthConfigError, replace
assert.Equal(t, fallbackInvoked, result, ...) with assert.Same(t,
fallbackInvoked, result, ...) so the test verifies the exact same error instance
(fallbackInvoked) is propagated unchanged by
maybeOfferProfileFallbackOnAuthConfigError.

48-107: Missing coverage for the forceSelect (__SELECT__) branch.

identityFromFlagOrDefault has three distinct branches driven by GetIdentityFromFlags:

  1. explicit identity (covered ✅),
  2. flag unset → default identity (covered ✅),
  3. flag equals IdentityFlagSelectValue (__SELECT__) → forceSelect=true, which bypasses the early return and calls GetDefaultIdentity(true) (not covered).

The third branch has distinct behavior — it forces interactive selection and passes true instead of false — and is precisely the kind of recovery/opt-in path the guidelines ask to pin down with a negative/positive pair. Consider adding a subtest:

♻️ Suggested subtest
t.Run("flag set to __SELECT__ calls GetDefaultIdentity(true) for interactive selection", func(t *testing.T) {
    _ = NewTestKit(t)
    resetIdentityViper(t)

    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    m := types.NewMockAuthManager(ctrl)
    m.EXPECT().GetDefaultIdentity(true).Return("picked-id", nil)

    cmd := newIdentityFlowTestCmd(t)
    require.NoError(t, cmd.Flags().Set(IdentityFlagName, IdentityFlagSelectValue))

    got, err := identityFromFlagOrDefault(cmd, m)
    require.NoError(t, err)
    assert.Equal(t, "picked-id", got)
})

Based on learnings: "Include negative-path tests for recovery logic: whenever a test verifies that a recovery/fallback triggers under condition X, add a corresponding test that verifies the recovery does NOT trigger when condition X is absent."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_identity_flow_test.go` around lines 48 - 107, Missing coverage for
the branch where the identity flag is set to IdentityFlagSelectValue
(__SELECT__), which should set forceSelect=true and call
m.GetDefaultIdentity(true); add a subtest to TestIdentityFromFlagOrDefault that
resets viper (resetIdentityViper), creates a mock AuthManager
(types.NewMockAuthManager) expecting
GetDefaultIdentity(true).Return("picked-id", nil), sets the flag on the command
(newIdentityFlowTestCmd and cmd.Flags().Set(IdentityFlagName,
IdentityFlagSelectValue)), calls identityFromFlagOrDefault(cmd, m) and asserts
no error and the returned value equals "picked-id".

33-39: Global viper mutation — worth a heads-up comment about parallelism.

resetIdentityViper mutates the global viper.GetViper() singleton. That's fine today because these subtests don't call t.Parallel(), but the helper's doc block on lines 18–23 actively encourages driving through viper. If a future contributor adds t.Parallel() to any subtest here (or to another test in the cmd package that touches the identity key), the restore-on-cleanup contract becomes racy.

Consider a one-liner in the doc comment making that invariant explicit, e.g. "callers must not use t.Parallel()", so the constraint is discoverable at the call site.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_identity_flow_test.go` around lines 33 - 39, The helper
resetIdentityViper mutates the global viper.GetViper() singleton and relies on
t.Cleanup to restore IdentityFlagName, so update its top doc comment (the
existing block around lines 18–23) to add a single explicit sentence: callers
must not call t.Parallel() (or otherwise run in parallel) when using
resetIdentityViper because it mutates the global viper state and relies on
serial test execution to restore IdentityFlagName.
cmd/auth_profile_fallback_test.go (1)

118-126: Prefer errors.Is/assert.Same over string equality for the pass-through cases.

For the "original error returned" cases, got is the exact same instance as tt.err (the function returns the caller's err unchanged), so comparing .Error() strings works but is indirect and brittle. For the "ErrNoIdentitiesAvailable triggers fallback" case at lines 100–107, wantErr is a freshly constructed fmt.Errorf that happens to format identically — a silent regression in the pass-through semantics (e.g., re-wrapping) wouldn't be caught. Per coding guidelines, prefer errors.Is() for error checking in tests.

♻️ Proposed tweak
-			got := maybeOfferProfileFallbackOnAuthConfigError(ctx, m, tt.err)
-
-			if tt.wantErr == nil {
-				require.NoError(t, got)
-				return
-			}
-			require.Error(t, got)
-			assert.Equal(t, tt.wantErr.Error(), got.Error())
+			got := maybeOfferProfileFallbackOnAuthConfigError(ctx, m, tt.err)
+
+			if tt.wantErr == nil {
+				require.NoError(t, got)
+				return
+			}
+			require.Error(t, got)
+			// Pass-through cases must return the exact same error instance.
+			// Fallback-propagation cases must surface the fallback sentinel via errors.Is.
+			if tt.err != nil && tt.wantErr != tt.err {
+				assert.ErrorIs(t, got, tt.wantErr)
+			} else {
+				assert.Same(t, tt.err, got)
+			}

For this to work cleanly, tighten the "ErrNoIdentitiesAvailable" row so wantErr is the same instance as err (extract it to a local var like wrappedNoIdentities).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth_profile_fallback_test.go` around lines 118 - 126, Update the test to
use identity-based error checks instead of string equality: for pass-through
cases of maybeOfferProfileFallbackOnAuthConfigError use errors.Is(got,
tt.wantErr) or assert.Same(t, tt.err, got) so the test detects re-wrapping, and
make the "ErrNoIdentitiesAvailable" case supply the exact same error instance
(e.g., extract wrappedNoIdentities := fmt.Errorf(...); set both err and wantErr
to wrappedNoIdentities) so the comparison with errors.Is/assert.Same verifies
the original instance is returned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@cmd/auth_identity_flow_test.go`:
- Around line 139-142: The test should assert identity equality rather than
value equality: in the assertion for the fallback error returned by
maybeOfferProfileFallbackOnAuthConfigError, replace assert.Equal(t,
fallbackInvoked, result, ...) with assert.Same(t, fallbackInvoked, result, ...)
so the test verifies the exact same error instance (fallbackInvoked) is
propagated unchanged by maybeOfferProfileFallbackOnAuthConfigError.
- Around line 48-107: Missing coverage for the branch where the identity flag is
set to IdentityFlagSelectValue (__SELECT__), which should set forceSelect=true
and call m.GetDefaultIdentity(true); add a subtest to
TestIdentityFromFlagOrDefault that resets viper (resetIdentityViper), creates a
mock AuthManager (types.NewMockAuthManager) expecting
GetDefaultIdentity(true).Return("picked-id", nil), sets the flag on the command
(newIdentityFlowTestCmd and cmd.Flags().Set(IdentityFlagName,
IdentityFlagSelectValue)), calls identityFromFlagOrDefault(cmd, m) and asserts
no error and the returned value equals "picked-id".
- Around line 33-39: The helper resetIdentityViper mutates the global
viper.GetViper() singleton and relies on t.Cleanup to restore IdentityFlagName,
so update its top doc comment (the existing block around lines 18–23) to add a
single explicit sentence: callers must not call t.Parallel() (or otherwise run
in parallel) when using resetIdentityViper because it mutates the global viper
state and relies on serial test execution to restore IdentityFlagName.

In `@cmd/auth_profile_fallback_test.go`:
- Around line 118-126: Update the test to use identity-based error checks
instead of string equality: for pass-through cases of
maybeOfferProfileFallbackOnAuthConfigError use errors.Is(got, tt.wantErr) or
assert.Same(t, tt.err, got) so the test detects re-wrapping, and make the
"ErrNoIdentitiesAvailable" case supply the exact same error instance (e.g.,
extract wrappedNoIdentities := fmt.Errorf(...); set both err and wantErr to
wrappedNoIdentities) so the comparison with errors.Is/assert.Same verifies the
original instance is returned.

In `@pkg/config/profiles_public_test.go`:
- Around line 1-239: Two identical malformed-YAML test setups are duplicated in
TestProfilesWithIdentity and TestProfilesWithAuthConfig; extract a small helper
(e.g., writeBrokenProfile(t *testing.T, tmpDir, name string)) and use it from
both tests to create the "broken" profile directory and atmos.yaml so
duplication is removed; update the two call sites to call writeBrokenProfile and
keep existing assertions and temp-dir usage (references:
profilesPublicTestFixture, TestProfilesWithIdentity,
TestProfilesWithAuthConfig).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ecce493c-0d86-4ca2-aa9b-070c5b1ec13e

📥 Commits

Reviewing files that changed from the base of the PR and between 3eba5d8 and e461bcd.

📒 Files selected for processing (15)
  • cmd/auth_config.go
  • cmd/auth_config_test.go
  • cmd/auth_console.go
  • cmd/auth_env.go
  • cmd/auth_exec.go
  • cmd/auth_identity_flow_test.go
  • cmd/auth_login.go
  • cmd/auth_logout.go
  • cmd/auth_profile_fallback_test.go
  • cmd/auth_shell.go
  • cmd/auth_user.go
  • cmd/auth_validate.go
  • cmd/auth_whoami.go
  • pkg/auth/profile_fallback_test.go
  • pkg/config/profiles_public_test.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/auth/profile_fallback_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • cmd/auth_exec.go
  • cmd/auth_whoami.go
  • cmd/auth_login.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Apr 17, 2026
… assertions

Production code (minimal, test-only seams):

pkg/auth/profile_fallback.go
- Add two package-scoped variables so the huh-based interactive paths
  and the isInteractive() gate can be exercised headlessly in tests:
  * runForm wraps form.Run() — huh has no headless mode and a real
    form requires a TTY, so tests stub this var to inject outcomes
    (ErrUserAborted, non-abort form errors, successful submission).
  * interactiveCheck aliases isInteractive() but is scoped to this
    file only — the 5 other isInteractive() call sites in manager.go
    are untouched so we don't widen the blast radius.
- Production code never reassigns either var. Documented inline.

Test coverage — pkg/auth/profile_fallback.go: 44.7% → 91.5%

16 new tests in pkg/auth/profile_fallback_test.go:
- Empty-list early returns for promptForProfileSelection and
  promptForAnyProfileSelection (ErrNoIdentitiesAvailable).
- User-aborted / non-abort error / successful-submission branches
  for every prompt + confirm function. Also pins the contract that
  huh.Select defaults the bound value to the first sorted option
  when form.Run returns nil.
- Interactive-branch tests for maybeOfferProfileFallback and
  maybeOfferAnyProfileFallback: user aborts → ErrUserAborted;
  prompt errors (non-abort) → wrapped with ErrUnsupportedInputType;
  reexec.Exec fails → "failed to re-exec" propagated. Each test
  stubs interactiveCheck + runForm + reexec.Exec so the full
  interactive path runs headless.

Per-function coverage (before → after):
- promptForProfileSelection             0.0% → 100.0%
- confirmSingleProfileSelection         0.0% →  90.9%
- promptForAnyProfileSelection          0.0% → 100.0%
- confirmSingleAnyProfileSelection      0.0% →  90.9%
- maybeOfferProfileFallback            52.0% →  84.0%
- maybeOfferAnyProfileFallback         52.0% →  84.0%

Review-feedback cleanups (no behavior change):

cmd/auth_identity_flow_test.go
- assert.Equal → assert.Same for the fallback-error propagation
  contract. Identity equality is the actual contract;
  assert.Equal could silently accept a wrap/copy.
- New subtest for the __SELECT__ branch of identityFromFlagOrDefault:
  --identity without a value → forceSelect=true →
  GetDefaultIdentity(true). Pins the previously-uncovered branch.
- Documented the parallel-safety invariant on resetIdentityViper:
  callers must NOT use t.Parallel() because the helper mutates the
  global viper.GetViper() singleton with a t.Cleanup restore.

cmd/auth_profile_fallback_test.go
- Rewrote TestMaybeOfferProfileFallbackOnAuthConfigError with an
  assertMode enum. Pass-through cases use assert.Same to catch
  silent re-wrap regressions plus errors.Is against sentinels.
  Fallback-return cases use assert.Same against the fallback
  instance. Replaces the previous .Error()-string equality check.

Platform hygiene:

pkg/auth/profile_fallback_test.go
- TestBuildFallbackAtmosConfig_PopulatesPaths: replaced a hardcoded
  `/some/cli/config/path` Unix literal with filepath.Join("some",
  "cli", "config", "path") per CLAUDE.md ("NEVER hardcode Unix
  paths in expected values"). Round-trip contract is unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cmd/auth_identity_flow_test.go`:
- Around line 161-165: The comment block describing the auth subcommand pattern
must be godot-safe (end with a period); locate the comment around the pattern
using the symbols identityFromFlagOrDefault,
maybeOfferProfileFallbackOnAuthConfigError, cmd and authManager and either
rephrase the fragment-style comment into a complete sentence or append a final
sentence that ends with a period so the comment group no longer ends with `}`.
- Around line 169-176: Add a companion negative-path test for
maybeOfferProfileFallbackOnAuthConfigError that verifies the fallback is NOT
invoked for unrelated errors: create a test similar to the existing one but pass
a non-ErrNoDefaultIdentity error, set the mock expectation that
MaybeOfferAnyProfileFallback is not called (e.g.,
mock.EXPECT().MaybeOfferAnyProfileFallback(gomock.Any()).Times(0) or use
gomock.InOrder with no call), call maybeOfferProfileFallbackOnAuthConfigError
with that error, assert the returned error equals the original error
(assert.Same like fallbackInvoked check), and ensure the test fails if the
fallback is invoked.
- Around line 3-16: Update the tests to exercise the real no-value `--identity`
flag path instead of setting the sentinel directly: modify
newIdentityFlowTestCmd to set the Cobra flag's NoOptDefVal for the `--identity`
flag, then in the test pass the `--identity` flag without a value (so Cobra
populates NoOptDefVal) rather than manually injecting the sentinel value;
additionally add a negative-path test asserting that
maybeOfferProfileFallbackOnAuthConfigError does NOT invoke the fallback when the
error is nil (success case) to cover the non-trigger branch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 89fe638a-6086-4dcb-bfd5-e6a8e2bd49e4

📥 Commits

Reviewing files that changed from the base of the PR and between 0837253 and e2fe626.

📒 Files selected for processing (4)
  • cmd/auth_identity_flow_test.go
  • cmd/auth_profile_fallback_test.go
  • pkg/auth/profile_fallback.go
  • pkg/auth/profile_fallback_test.go
✅ Files skipped from review due to trivial changes (3)
  • cmd/auth_profile_fallback_test.go
  • pkg/auth/profile_fallback.go
  • pkg/auth/profile_fallback_test.go

Comment thread cmd/auth_identity_flow_test.go Resolved
Comment thread cmd/auth_identity_flow_test.go Resolved
Comment thread cmd/auth_identity_flow_test.go Resolved
cmd/auth_identity_flow_test.go

- Swap the direct-sentinel injection in the __SELECT__ subtest for a
  real Cobra NoOptDefVal flow: wire NoOptDefVal on the test cmd,
  set os.Args to include `--identity` (no value), and call
  cmd.ParseFlags([]string{"--identity"}). Renamed the subtest to
  "--identity without value (NoOptDefVal) calls GetDefaultIdentity(true)".
  Added withIdentityFlowArgs helper with t.Cleanup restore so the
  swap is test-scoped and doesn't leak into siblings.

- Add TestAuthCmd_IdentityFlagNoOptDefVal — a tiny regression fence
  that inspects authCmd.PersistentFlags().Lookup(IdentityFlagName).
  NoOptDefVal directly. The previous NoOptDefVal test exercises the
  MECHANISM against a test-owned cmd, so it cannot catch a future
  edit that deletes the wiring from cmd/auth.go's init(). This test
  catches exactly that regression.

- Add TestIdentityFromFlagOrDefault_NoErrorSkipsFallbackDispatcher —
  negative-path companion to the ErrorReachesFallbackDispatcher test.
  Uses gomock's strict "no expectation = fail" semantics to prove
  MaybeOfferAnyProfileFallback is never invoked when
  identityFromFlagOrDefault succeeds. Also explicitly calls the
  dispatcher with nil to assert the short-circuit at the dispatcher
  layer. Pairs with the existing trigger-path test per CLAUDE.md
  "negative-path for recovery logic" rule.

- Add TestMaybeOfferProfileFallbackOnAuthConfigError_IgnoresNonAuthErrors —
  colocated negative companion for the non-auth-config-error path.
  Uses assert.AnError + strict gomock to prove unrelated errors
  pass through verbatim without triggering the fallback. This case
  is also covered in auth_profile_fallback_test.go; duplicated here
  so readers of the identity-flow tests see the positive and
  negative paths side-by-side.

- Godot fixes: rewrote the snippet-style block comment inside
  TestIdentityFromFlagOrDefault_ErrorReachesFallbackDispatcher
  (ended with literal `//   }`) as a one-sentence prose description.
  Capitalized sentence-initial "identityFromFlagOrDefault" / "gomock"
  in three doc blocks so godot accepts them.

- Parallel-safety heads-up on resetIdentityViper: callers must NOT
  use t.Parallel() because the helper mutates the global
  viper.GetViper() singleton with a t.Cleanup restore — a parallel
  subtest elsewhere that touches IdentityFlagName would race the
  cleanup. Documented at the helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit c1bb921 into main Apr 21, 2026
95 of 96 checks passed
@atmos-pro

atmos-pro Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor

Note

Atmos Pro  

Waiting for your GitHub Actions workflow to upload affected stacks.
Learn More.

@aknysh
Andriy Knysh (aknysh) deleted the osterman/interactive-profile-select branch April 21, 2026 02:45
@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label Apr 21, 2026
@atmos-pro

atmos-pro Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor

Note

Atmos Pro  

Waiting for your GitHub Actions workflow to upload affected stacks.
Learn More.

@github-actions

Copy link
Copy Markdown

Warning

Release Documentation Required

This PR is labeled minor or major and requires documentation updates:

  • Changelog entry - Add a blog post in website/blog/YYYY-MM-DD-feature-name.mdx
  • Roadmap update - Update website/src/data/roadmap.js with the new milestone

Alternatively: If this change doesn't require release documentation, remove the minor or major label.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.216.0.

Andriy Knysh (aknysh) added a commit that referenced this pull request May 7, 2026
Backports features from main's cmd/auth_*.go that were not yet present in
HEAD's refactored cmd/auth/* tree. Each item references the upstream PR.

cmd/auth/env.go (#1984):
- Add `--format=github` for $GITHUB_ENV with heredoc multiline support.
- Add `--format=env` (lowercase env-style key=value).
- Add `-o, --output-file` flag (with $GITHUB_ENV auto-detect for github).
- Route formatting through pkg/env.Output() while keeping outputEnvAsExport
  and outputEnvAsDotenv helpers for unit-test coverage.
- Bind ATMOS_AUTH_ENV_FORMAT and ATMOS_AUTH_ENV_OUTPUT_FILE env vars.
- Extract loadAuthManagerForEnv, resolveIdentityNameForEnv, loginIfNeeded,
  resolveEnvOutputTarget, and resolveEnvOutputFile helpers to keep
  executeAuthEnvCommand within complexity and length budgets.

cmd/auth/login.go (provider fallback, #2333):
- Change authenticateIdentity signature to (whoami, needsProviderFallback,
  err). On ErrNoIdentitiesAvailable / ErrNoDefaultIdentity, return the
  fallback flag instead of wrapping; caller routes to provider auth.
- Treat ErrUserAborted as a clean abort (no ErrAuthenticationFailed wrap).
- Add getProviderForFallback / promptForProvider / isInteractive helpers
  for the auto-provision-identities first-login path.
- Wire maybeOfferProfileFallbackOnAuthConfigError around identity-flow
  errors.

cmd/auth/exec.go, cmd/auth/shell.go:
- Surface identity-resolution errors through
  maybeOfferProfileFallbackOnAuthConfigError so a stale base profile no
  longer dead-ends with `no default identity`.

Tests:
- env_test.go: add TestGitHubEnvAutoDetect (auto-detect $GITHUB_ENV +
  heredoc framing), update TestSupportedFormats to expect 5 formats.
- login_test.go: update TestAuthenticateIdentity for the new
  needsProviderFallback signal; add ErrNoIdentitiesAvailable case.
- integration_test.go (new): TestAuthEnvFormatCompletion,
  TestAuthWhoamiOutputCompletion, TestAuthCommandCompletion_FlagInheritance.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 12, 2026
…1919)

* Fix markdown code fence in Nerd Fonts installation instructions (#1917)

* Simplify Nerd Fonts installation instructions

Removed Homebrew tap and search commands from installation instructions. Cask-fonts has been deprecated.

* Fix markdown code fence formatting

The previous commit accidentally removed the opening code fence when deleting
the deprecated Homebrew tap commands.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

---------

Co-authored-by: Matt Topper <[email protected]>
Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Andriy Knysh <[email protected]>

* Address PR review comments for auth registry refactor

- Fix Comment #3: Parse global flags before InitCliConfig in all auth
  commands by adding BuildConfigAndStacksInfo helper to pkg/flags and
  cmd/auth/helpers.go

- Fix Comment #4: Add guard for empty selectable array in configure.go
  to prevent index out of bounds when no AWS user identities found

- Fix Comment #5: Remove duplicate IdentityFlagName constants by using
  cfg.IdentityFlagName from pkg/config/const.go as canonical source

- Remove unused schema imports from login.go, exec.go, shell.go
- Remove unnecessary nolint:gosec directives from env.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Fix NoOptDefVal preprocessing for identity flag in auth commands

The identity flag uses Cobra's NoOptDefVal feature which only works with
equals syntax (--identity=value), not space-separated syntax (--identity value).
This caused explicit identity values to be ignored, falling back to interactive
selection which fails without a TTY.

Fix by adding NoOptDefVal preprocessing in preprocessCompatibilityFlags() to
rewrite --identity value → --identity=value before Cobra parses. This ensures
explicit identity values work correctly in all environments (CI, piped output,
redirected stdin).

Fixes:
- TestInteractiveIdentitySelection/explicit_identity_value_should_work_even_with_piped_output
- TestExplicitIdentityAlwaysWorks/with_CI=true

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Add documentation for --identity flag placement best practices

Document recommended usage patterns for the --identity flag:
- Use equals syntax (--identity=admin) for clarity
- Place flag before -- separator and positional arguments
- Both auth and terraform command docs updated

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Address PR review comments: constants and security annotations

1. Remove redundant constant aliases in cmd/identity_helpers.go
   - Use cfg.IdentityFlagName and cfg.IdentityFlagSelectValue directly
   - Eliminates duplicate definitions (CodeRabbit feedback)

2. Add CodeQL suppression comments in cmd/auth/env.go
   - Document intentional credential output for shell sourcing
   - Add codeql[go/clear-text-logging] annotations
   - Similar to aws configure export-credentials behavior

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Add --identity flag documentation to global flags reference

Document the --identity flag in the Command-Specific Flags section:
- Available in auth, terraform, and describe commands
- Supports multiple modes: explicit value, interactive selector, disabled
- Add ATMOS_IDENTITY environment variable reference
- Include flag placement best practice tip (equals syntax recommended)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Refactor preprocessing architecture with preprocessArgs orchestrator

Separate NoOptDefVal preprocessing and compatibility flag translation into
sibling operations orchestrated by a new preprocessArgs() function.

Architecture:
- preprocessArgs() orchestrates all argument preprocessing
- preprocessNoOptDefValFlags() rewrites --flag value → --flag=value for NoOptDefVal flags
- preprocessCompatibilityFlags() separates Atmos flags from pass-through flags

Key fixes:
- Call SetArgs when NoOptDefVal changes args but no compat flags exist
- This ensures --identity value works correctly for auth commands

New pkg/flags/preprocess/ package:
- Pipeline interface for extensible preprocessing
- NoOptDefValPreprocessor with fixed hasSeparatedValue() using strings.Contains
- FlagInfo interface to avoid circular imports

Tests:
- All auth tests pass (29 tests)
- All preprocess package tests pass
- Pager tests skip gracefully when TTY unavailable

Also fixes pre-existing lint errors in:
- errors/errors.go: Add ErrComponentPathNotFound sentinel
- internal/exec/helmfile.go: Use sentinel errors instead of dynamic errors
- internal/exec/stack_processor_merge.go: Use %w instead of %v for errors
- pkg/downloader/file_downloader.go: Use %w instead of %v for errors
- internal/exec/path_utils_test.go: Use constants for paths with separators

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Address PR review comments

- cmd/auth/shell.go: Use envpkg.MergeGlobalEnv() for consistency with exec.go
  (addresses CodeRabbit comment #3 about env merging inconsistency)

- cmd/auth/whoami.go: Use %w for error wrapping to preserve error chain
  (addresses CodeRabbit comment #4 about error wrapping)

- tests/cli_describe_component_test.go: Use cross-platform TTY detection
  with term.IsTTYSupportForStdout() and close file handle properly
  (addresses CodeRabbit comments #5, #6)

- tests/describe_test.go: Add skipIfNoTTY helper with cross-platform
  TTY detection and proper file handle cleanup
  (addresses CodeRabbit comments #7, #8)

Note: Comments #1 and #2 (codeql clear-text logging) are false positives -
the atmos auth env command intentionally outputs credentials for shell
sourcing, similar to `aws configure export-credentials`. Suppression
comments are already in place.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Add unit tests for cmd/auth package to improve coverage

Add 15 new test files covering pure functions and mock-based tests:
- helpers_test.go: formatDuration, displayAuthSuccess, BuildConfigAndStacksInfo
- whoami_test.go: redactHomeDir, sanitizeEnvMap, buildWhoamiTableRows, validateCredentials
- list_test.go: parseCommaSeparatedNames, filter functions, render functions
- env_test.go: outputEnvAsExport, outputEnvAsDotenv
- login_test.go: authenticateIdentity with MockAuthManager
- shell_test.go: getSeparatedArgs, viper fallback tests
- exec_test.go: getSeparatedArgsForExec, executeCommandWithEnv
- console_test.go: resolveIdentityName, retrieveCredentials, resolveConsoleDuration
- auth_test.go: AuthCommandProvider, GetIdentityFromFlags
- completion_test.go: completion functions
- validate_test.go: command structure
- identity_resolution_test.go: shared identity resolution test helper
- user/user_test.go: AuthUserCmd structure
- user/configure_test.go: command structure
- user/helpers_test.go: selectAWSUserIdentities, extractAWSUserInfo

Coverage improved from ~25.57% to ~36.2% for cmd/auth package.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Fix cross-platform compatibility for exec tests

- Replace Unix-specific "true" command with cross-platform "go version"
- Move "false" command test to exec_unix_test.go with build constraint
- Addresses CodeRabbit review comment about Windows compatibility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* test: Add tests for --profile flag in auth commands (fixes #1973)

Add tests to verify that the --profile global flag is properly extracted
into ProfilesFromArg when using auth exec and auth shell commands.

Test cases:
- Single profile (--profile dev)
- Multiple profiles (--profile dev --profile staging)
- No profile
- Profile with special characters (us-east-1/prod)
- Environment variable fallback (ATMOS_PROFILE)

These tests verify the fix for issue #1973 where --profile didn't work
with auth exec and auth shell commands.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* docs: Reorganize terraform usage examples into distinct sections

Split the "Clean Examples" section into three distinct subsections:
- Clean Examples: terraform clean commands only
- Workspace Examples: terraform workspace commands
- Additional Flag Examples: plan commands with --/--append-user-agent flags

This improves documentation readability by grouping related commands together.

Addresses CodeRabbit review comment on PR #1919.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* test: Regenerate auth command golden snapshots

Update snapshots for auth command refactoring:
- auth exec --help: Updated usage format and added aws CLI example
- auth invalid-command: Removed ecr-login from valid subcommands list

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: Windows test failures and website build

- Make TestRedactHomeDir cross-platform using filepath.Join
- Make TestRedactHomeDirWithOsPathSeparator use consistent path construction
- Fix TestFormatExpiration flaky assertion (timing-dependent)
- Add missing File component import to terraform/usage.mdx

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: Add IsExperimental method to AuthCommandProvider

The CommandProvider interface now requires IsExperimental() after main
branch updates. This fixes CI build failures across Linux, macOS, and
Windows by implementing the required interface method.

Auth commands return true as they are part of Pro Features.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes (attempt 3/3)

* [autofix.ci] apply automated fixes

* fix: Address CodeRabbit review comments for auth-registry-refactor

- Remove undocumented IDENTITY env var fallback (comment #10)
  Only ATMOS_IDENTITY is documented and should be used

- Make HOME path test cases OS-portable (comment #11)
  Use filepath.Join instead of hardcoded Unix paths in tests

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* chore: Regenerate golden snapshots for experimental auth command

The auth command now returns IsExperimental() = true, which adds:
- [EXPERIMENTAL] tag in command listings
- Experimental feature warning message in stderr output

Regenerated all affected golden snapshots to match the new output.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: Address CodeRabbit review findings in auth commands

- console.go: Use data.Writeln/ui.Writef/ui.Success/ui.Warning instead of
  fmt.Fprintf(os.Stdout/Stderr) to follow Atmos I/O conventions
- env.go: Wrap config/manager init errors with sentinel errors
  (ErrFailedToInitializeAtmosConfig, ErrFailedToInitializeAuthManager)
- exec.go: Remove duplicate os.Environ() in executeCommandWithEnv; use
  envpkg.ConvertMapToSlice since prepareAuthenticatedEnv already includes
  the full OS environment
- helpers.go: Stop scanning for --help at "--" separator so pass-through
  commands like `atmos auth exec -- terraform --help` work correctly
- logout.go: Fix misleading --all-realms flag description to accurately
  reflect keychain cleanup scope

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Migrate auth commands from legacy u.Print* to ui/data layer and fix test failures

Replace all antiquated u.PrintfMarkdownToTUI/u.PrintfMessageToTUI calls in auth commands
with the proper ui.MarkdownMessagef/ui.Writef functions. Replace u.PrintAsJSON with
data.WriteJSON. Add missing Realm row to displayAuthSuccess output. Regenerate golden
snapshots to match corrected stderr output.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat(auth): port main features to refactored cmd/auth package

Backports features from main's cmd/auth_*.go that were not yet present in
HEAD's refactored cmd/auth/* tree. Each item references the upstream PR.

cmd/auth/env.go (#1984):
- Add `--format=github` for $GITHUB_ENV with heredoc multiline support.
- Add `--format=env` (lowercase env-style key=value).
- Add `-o, --output-file` flag (with $GITHUB_ENV auto-detect for github).
- Route formatting through pkg/env.Output() while keeping outputEnvAsExport
  and outputEnvAsDotenv helpers for unit-test coverage.
- Bind ATMOS_AUTH_ENV_FORMAT and ATMOS_AUTH_ENV_OUTPUT_FILE env vars.
- Extract loadAuthManagerForEnv, resolveIdentityNameForEnv, loginIfNeeded,
  resolveEnvOutputTarget, and resolveEnvOutputFile helpers to keep
  executeAuthEnvCommand within complexity and length budgets.

cmd/auth/login.go (provider fallback, #2333):
- Change authenticateIdentity signature to (whoami, needsProviderFallback,
  err). On ErrNoIdentitiesAvailable / ErrNoDefaultIdentity, return the
  fallback flag instead of wrapping; caller routes to provider auth.
- Treat ErrUserAborted as a clean abort (no ErrAuthenticationFailed wrap).
- Add getProviderForFallback / promptForProvider / isInteractive helpers
  for the auto-provision-identities first-login path.
- Wire maybeOfferProfileFallbackOnAuthConfigError around identity-flow
  errors.

cmd/auth/exec.go, cmd/auth/shell.go:
- Surface identity-resolution errors through
  maybeOfferProfileFallbackOnAuthConfigError so a stale base profile no
  longer dead-ends with `no default identity`.

Tests:
- env_test.go: add TestGitHubEnvAutoDetect (auto-detect $GITHUB_ENV +
  heredoc framing), update TestSupportedFormats to expect 5 formats.
- login_test.go: update TestAuthenticateIdentity for the new
  needsProviderFallback signal; add ErrNoIdentitiesAvailable case.
- integration_test.go (new): TestAuthEnvFormatCompletion,
  TestAuthWhoamiOutputCompletion, TestAuthCommandCompletion_FlagInheritance.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* updates

* [autocommit] formatting fixes

* test(auth): add regression tests for issues #1973 and #2392

Both issues are addressed by the cmd/auth/* registry refactor + terraform
StandardParser registration of --identity. These tests guard the contracts
so a future regression cannot reintroduce either silent flag-drop bug.

Issue #1973 (--profile global flag silently dropped on auth exec/shell):
- cmd/auth/exec_test.go::TestAuthExec_ProfileFlagAppliedToConfig
- cmd/auth/shell_test.go::TestAuthShell_ProfileFlagAppliedToConfig

  Both call BuildConfigAndStacksInfo(cmd, v) — the helper that exec.go
  and shell.go now use before cfg.InitCliConfig — and assert that the
  --profile values round-trip into ConfigAndStacksInfo.ProfilesFromArg
  for single, multiple, and absent profile cases.

Issue #2392 (--identity silently dropped on atmos terraform plan):
- internal/exec/cli_utils_test.go::TestProcessCommandLineArgs_TerraformIdentityFlag_Issue2392

  Reproduces the bug-report arg shape verbatim — `terraform plan
  account-map -s core-gbl-root --identity core-root/admin` — and asserts
  ProcessCommandLineArgs populates info.Identity = "core-root/admin".

- internal/exec/terraform_execute_helpers_auth_test.go::TestSetupTerraformAuth_IdentityFlagPropagatesToAuthCreator

  Builds a merged auth config containing both a `default: true` identity
  ("core-identity/devops") and a non-default identity ("core-root/admin")
  and asserts that setupTerraformAuth passes the explicit --identity
  value verbatim to the auth manager creator — not the profile default.
  This is the exact override that the issue described as silently
  happening at v1.216.0.

- internal/exec/terraform_execute_helpers_auth_test.go::TestSetupTerraformAuth_EmptyIdentity_AllowsAutoDetection

  Inverse guard: with no --identity flag, info.Identity is empty and the
  creator receives the empty string so pkg/auth.resolveIdentityName can
  auto-detect the profile default. Prevents an over-eager fix from
  breaking the default-identity path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* updates

* test(auth): boost cmd/auth coverage from 33% to 47%

Adds focused unit tests for the testable helpers exposed by the cmd/auth
registry refactor. Targets the lowest-coverage files flagged by Codecov:

cmd/auth/auth.go (CommandProvider getters):
- TestAuthCommandProvider_OptionalMethods covers GetPositionalArgsBuilder,
  GetCompatibilityFlags, GetAliases, IsExperimental.
- TestGetAuthCmd_ReturnsAuthCmd guards the public accessor used by cmd/ai
  to attach subcommands.

cmd/auth/env.go (env command helpers):
- TestResolveEnvOutputFile covers all four branches of the GitHub auto-
  detect: non-github pass-through, explicit output-file, $GITHUB_ENV
  detect, and the missing-GITHUB_ENV error sentinel.
- TestResolveEnvOutputTarget exercises viper-backed format/output-file
  resolution including the bash default and the github auto-detect.
- TestLoginIfNeeded covers cache-hit (no Authenticate), missing-cache
  (Authenticate triggered), ErrUserAborted unwrapping, and generic-
  error wrapping with ErrAuthenticationFailed.
- TestResolveIdentityNameForEnv covers the explicit-flag, viper-fallback,
  default-auto-detect, and __SELECT__ interactive paths.

cmd/auth/console.go (browser isolation helpers):
- TestConsoleSessionDir asserts the deterministic XDG path is stable
  across calls, diverges by identity, and diverges by realm.
- TestResolveConsoleIsolated covers default false, auth.console.isolated
  config honoured, flag overrides config in both directions.
- TestPrintConsoleHelpers smoke-covers printConsoleURL and printConsoleInfo
  with full + showURL=true paths.
- TestRetrieveCredentials_NoCredentialsAvailable covers the
  ErrAuthConsole sentinel for the no-credentials-anywhere branch.

cmd/auth/login.go (provider-fallback helpers):
- TestGetProviderForFallback covers ErrNoProvidersAvailable for empty
  list, single-provider auto-select (no prompt), and multi-provider
  non-interactive ErrNoDefaultProvider.
- TestIsInteractive guards determinism (same env → same answer).

cmd/auth/whoami.go (whoami helpers):
- TestAddGCPReauthExplanation covers nil pass-through, unrelated-error
  pass-through, invalid_grant alone (no enrichment), and invalid_grant
  + invalid_rapt enrichment with gcloud reauth hint.
- TestPrintWhoamiJSON_RedactsCredentials guards the contract that the
  JSON output never mutates the caller's Environment map.
- TestPrintWhoamiHuman covers valid/invalid/no-expiration table render.

cmd/auth/list.go (list command helpers):
- TestParseFilterFlags covers the default, --providers (with comma
  list), --identities (with comma list), and the mutually-exclusive
  ErrMutuallyExclusiveFlags branch.
- TestRenderOutput_InvalidFormatErrors guards the default-case
  ErrInvalidFlag path.
- TestListFlagCompletions_NoConfig covers the no-atmos.yaml early-return
  path of listProvidersFlagCompletion / listIdentitiesFlagCompletion.

cmd/auth/logout.go (new logout_test.go):
- TestBuildKeychainDeletionMessage covers the pure prompt formatter.
- TestConfirmKeychainDeletion_ForceShortCircuit covers --force bypass.
- TestConfirmKeychainDeletion_NonTTYWithoutForceErrors covers the
  ErrKeychainDeletionRequiresConfirmation branch.
- TestDetectExternalCredentials covers GCP/Azure/AWS env-var detection.
- TestBuildLogoutOptions covers the empty-config, identities+providers,
  and provider-cascade-label branches.
- TestExecuteLogoutOption_InvalidType covers ErrInvalidLogoutOption.
- TestDiscoverRealms covers missing dir (no error), no-provider-subdir
  filter, and aws/azure realm reporting.

cmd/auth/completion.go (completion helpers):
- TestIdentityFlagCompletion covers the no-atmos.yaml branch.
- TestAddIdentityCompletion_NoFlag covers the no-flag-registered no-op.

cmd/auth/user/helpers.go (form-builder helper):
- TestBuildCredentialFormField covers all six branches: YAML-managed
  Note, DefaultValue pre-fill, password mode, optional, custom
  ValidateFunc wired, description message wired.

Infra:
- New testmain_test.go initialises pkg/data and pkg/ui formatters once
  for the package so tests that exercise printWhoamiJSON/printWhoamiHuman
  don't panic with "data.InitWriter() must be called".
- Snapshot tests/snapshots/TestCLICommands_atmos_auth_validate_--verbose
  picks up an env-dependent debug line drop (gh CLI not authenticated).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* style: apply gofumpt v0.10 multiline call wrapping

CI's pre-commit hook installs `gofumpt@latest` which is now v0.10.0.
That release tightened the multiline-call rule: when arguments span
multiple lines, the function name + opening paren go on their own
line and the closing paren goes on its own line as well. Local toolchain
was on v0.9.1 which didn't enforce this, so the changes only surfaced
on CI.

Files affected (only PR-touched files reformatted):

- cmd/auth/env.go: env.Output(...) call.
- cmd/describe_dependents.go: getRunnableDescribeDependentsCmd(...) call.
- cmd/describe_stacks.go: PersistentFlags().StringP(...) call.

No behaviour change. Matches the auto-fix diff produced by the
cloudposse/github-action-pre-commit job.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(auth): boost cmd/auth coverage from 47% to 69%

Adds smoke and branch-coverage tests across the auth command tree to lift
patch coverage from the post-merge baseline (47.8%) to ~69%.

Orchestrator smoke tests (no-atmos.yaml tempdir, no-panic contract):
- TestExecuteAuthLoginCommand_SmokeNoConfig
- TestExecuteAuthWhoamiCommand_SmokeNoConfig
- TestExecuteAuthListCommand_SmokeNoConfig
- TestExecuteAuthValidateCommand_SmokeNoConfig
- TestExecuteAuthConsoleCommand_SmokeNoConfig
- TestExecuteAuthEnvCommand_SmokeNoConfig
- TestExecuteAuthExecCommand_SmokeNoConfig
- TestExecuteAuthShellCommand_SmokeNoConfig
- TestExecuteAuthLogoutCommand_SmokeNoConfig
- TestExecuteAuthUserConfigureCommand_SmokeNoConfig (cmd/auth/user)

These cover the config-load error wrap path in each orchestrator and
guard against panics for invalid setup. Where a specific error sentinel
is documented (e.g. ErrInvalidAuthConfig, ErrFailedToInitializeAtmosConfig,
ErrAuthConsole), the test asserts the wrap when an error surfaces.

loadAuthManager* helpers (config init + auth manager init):
- TestLoadAuthManager_SmokeFromEmptyTempDir (whoami)
- TestLoadAuthManagerForEnv_SmokeFromEmptyTempDir (env)
- TestLoadAuthManagerForList_SmokeFromEmptyTempDir (list)
- TestInitializeAuthManager_SmokeFromEmptyTempDir (console)
- TestSuggestProfilesForAuth_NoProfilesReturnsNil

prepareShellEnvironment (cmd/auth/shell.go) — mocked-AuthManager test
covering cache-hit, fresh-auth-success, ErrUserAborted, generic-error
wrap with ErrAuthenticationFailed, PrepareShellEnvironment error, and
atmosConfig.Env propagation through MergeGlobalEnv:
- TestPrepareShellEnvironment (six subtests)

prepareAuthenticatedEnv (cmd/auth/exec.go) — smoke from empty tempdir:
- TestPrepareAuthenticatedEnv_SmokeNoConfig

Display + handleBrowserOpen helpers (smoke):
- TestDisplayExternalCredentialWarnings (with-warnings + clean branch)
- TestDisplayBrowserWarning (first-call + cached-skip branches)
- TestHandleBrowserOpen (skipOpen=true, nil opener, success, error)

Logout perform helpers — mocked AuthManager branch coverage:
- TestPerformIdentityLogout_NotFound (ErrIdentityNotInConfig)
- TestPerformIdentityLogout_DryRun (no Logout call)
- TestPerformProviderLogout_NotFound (missing provider in config)
- TestPerformLogoutAll_DryRun (no LogoutAll call)
- TestPerformLogoutAll_Success (happy path, two identities)

renderOutput dispatcher coverage:
- TestRenderOutput_AllValidFormats covers all 9 valid format branches
  (table/tree/json/yaml/graphviz/dot/mermaid/markdown/md).

Coverage summary:
- cmd/auth: 47.6% → 69.7%
- cmd/auth/user: 51.0% → 58.7%
- combined: 47.8% → 68.9%

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(auth): address review comments and push coverage from 47% to 78%

Addresses CodeRabbit review comments and substantially increases test
coverage of the cmd/auth package using a shared mock-auth fixture.

Review fixes:
- cmd/auth/completion.go, cmd/auth/list.go: all five shell-completion
  helpers now honour --base-path, --config, --config-path, and --profile
  by routing through BuildConfigAndStacksInfo(cmd, v) instead of using
  an empty ConfigAndStacksInfo{}.
- cmd/auth/console.go: --print-only now propagates the data.Writeln
  write error so broken-pipe / stdout failures exit non-zero. The
  empty-identity branch of resolveIdentityName now uses multi-%w so
  ErrNoDefaultIdentity stays in the chain for the profile-fallback
  dispatcher.
- cmd/auth/exec.go: prepareAuthenticatedEnv now returns []string
  directly (was []string → map → []string round-trip) so environment
  ordering is preserved and Windows drive-scoped vars (=C:=...) don't
  collide on the empty key.
- cmd/auth/shell.go: fail fast when positional args are not preceded
  by `--` (`atmos auth shell bash` previously silently dropped "bash").
- cmd/auth/logout.go: add cobra.MaximumNArgs(1) so extra positional
  args are rejected up front.
- cmd/auth/validate.go: wrap config-load failure with the static
  ErrFailedToInitializeAtmosConfig sentinel.
- cmd/auth/login.go: introduce isInteractiveFn package var so
  getProviderForFallback tests can force the non-interactive branch
  deterministically.
- cmd/auth/markdown/*.md: every opening fence now has the `shell`
  language identifier (MD040). The `$ ` prefix on commands is kept
  for consistency with the rest of cmd/markdown/.
- cmd/auth/user/configure.go: switch user-facing messages from
  fmt.Fprintf(cmd.ErrOrStderr()) to ui.Writef / ui.Writeln per the
  I/O layer convention.
- cmd/identity_helpers.go: add the missing perf.Track in
  CreateAuthManagerFromIdentityWithStackScan to match its sibling
  helpers.

Coverage improvements (cmd/auth 47.6% → 79.3%; combined 47.8% → 77.8%):

New shared helpers (helpers_test.go):
- setupMockAuthFixture(t): writes a minimal atmos.yaml wired to the
  mock/aws provider and isolates keyring + XDG env to a tempdir, used
  by 9 deep-coverage tests to exercise the full orchestrator pipeline
  without touching the host's credential store.
- runProfileFlagAppliedRegressionTest(t, commandName): shared
  table-driven driver for the issue #1973 regression so the
  exec_test.go and shell_test.go wrappers feed the same cases through
  one body (and dupl-lint stays clean).
- newTestCommandWithGlobalParser: parser-returning variant of the
  global-flags helper so regression tests can drive the real
  Cobra → Viper binding path (cmd.ParseFlags → BindFlagsToViper).

End-to-end orchestrator tests against the mock fixture:
- TestExecuteAuthEnvCommand_WithMockAuth
- TestExecuteAuthLoginCommand_WithMockAuth
- TestExecuteAuthListCommand_WithMockAuth / _JSONFormat
- TestExecuteAuthValidateCommand_WithMockAuth
- TestExecuteAuthWhoamiCommand_WithMockAuth
- TestExecuteAuthConsoleCommand_WithMockAuth (covers
  ErrProviderNotSupported for mock/aws)
- TestExecuteAuthLogoutCommand_WithMockAuthDryRun
- TestPrepareAuthenticatedEnv_WithMockAuth (asserts AWS_PROFILE +
  AWS_REGION injection)
- TestExecuteAuthExecCommand_NoCommand (ErrNoCommandSpecified guard)

Logout perform-helper branch coverage:
- TestPerformIdentityLogout_Success / _PartialLogout / _LogoutError
- TestPerformProviderLogout_Success / _DryRun
- TestExecuteLogoutOption_DispatchAll / _DispatchIdentity / _DispatchProvider
- TestPerformInteractiveLogout_NoIdentities (empty-identities branch)
- TestPerformLogoutAllRealms_NoRealms / _DryRun / _RealRemove

Pure / smoke helpers:
- TestRetrieveCredentials_InlineCredentials (success path)
- TestPromptForProvider_EmptyList (ErrNoProvidersAvailable guard)
- TestExecuteCommandWithEnv_NonZeroExit (errUtils.ExitCodeError
  propagation via the test-binary subprocess pattern)
- TestExecuteCommandWithEnv_WithValidCommand rewritten to use
  os.Executable() + _ATMOS_AUTH_TEST_EXIT_OK=1 (cross-platform,
  no PATH dependency on `go` / `true` / `false`).
- Subprocess env-flag handlers added to TestMain.

Test infrastructure:
- TestAuthExec_ProfileFlagAppliedToConfig and the shell equivalent
  now use --profile=devops style CLI args + ParseFlags +
  BindFlagsToViper, exercising the full production binding chain
  rather than seeding viper directly.
- Identity-resolution shared test table gains a "flag takes
  precedence over env" case so the precedence rule (flags > env >
  default) is regression-covered for both auth shell and auth exec.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(auth): address review comments — fence repair, helpers, sentinel

Addresses six CodeRabbit review comments from the latest batch:

1. cmd/auth/console_test.go — drop tautological constant tests.
   TestConsoleLabelWidth and TestConsoleOutputFormat just asserted that
   a literal equals itself. The constants are exported but only used
   internally; not part of an external API contract.

2. cmd/auth/console_test.go — fragile test-name dispatch.
   TestResolveConsoleDuration's "invalid provider duration format" case
   keyed its assertion off tt.name. Renaming the case would silently
   skip the error check. Added an explicit `expectParseError bool`
   field; switch case now keys off that.

3. cmd/auth/exec_test.go — single-case table replaced.
   TestGetSeparatedArgsForExec was a one-case table that duplicated the
   sibling TestGetSeparatedArgsForExec_EmptyCommand. Rewrote with five
   meaningful cases (no separator, positional-without-sep, separator+
   single command, separator+command+args, separator-only). Deleted the
   now-redundant sibling test.

4. cmd/auth/env_test.go — safe stdout-capture helper.
   Five sites used the same fragile capture pattern: if require.NoError
   aborted before restoration, os.Stdout stayed redirected and the read
   end of os.Pipe was never closed. Added captureStdout(t) helper in
   helpers_test.go that registers t.Cleanup to guarantee restoration
   and close both pipe ends even when intervening assertions abort.
   All five sites now use `read := captureStdout(t)` / `output := read()`.

5. cmd/auth/env_test.go — replace hardcoded Unix paths with t.TempDir().
   Three paths (/tmp/out.sh, /explicit/path, /path/to/.env) replaced
   with filepath.Join(t.TempDir(), ...) so the tests don't bake in a
   Unix separator.

6. cmd/auth/markdown/atmos_auth_console_usage.md +
   cmd/auth/markdown/atmos_auth_logout_usage.md — fix malformed
   closers. An earlier awk script that added the shell language
   identifier to opening fences had a state-machine flaw on files that
   already mixed labeled/unlabeled fences; six closing fences across
   two files were rewritten as ```shell instead of plain ```. Repaired
   to keep the rest of the doc rendering correctly. Audited all four
   auth markdown files; the other two were already correctly paired.

7. cmd/auth/logout_test.go + sibling _WithMockAuth tests — add a
   cmd-state isolation helper. Tests that mutate package-level
   auth*Cmd via ParseFlags could leak flag.Changed / flag values to
   subsequent tests. cmd.NewTestKit isn't reachable from cmd/auth
   without a circular import, so added a local equivalent
   resetAuthCmdFlags(t, cmd) that snapshots and restores every flag's
   (Value, Changed) pair via t.Cleanup. Applied to all 8 tests that
   ParseFlags a shared cmd: TestExecuteAuthLogoutCommand_SmokeNoConfig
   and _WithMockAuthDryRun (the two reviewer-flagged sites), plus
   _WithMockAuth variants for console, env, exec
   (TestPrepareAuthenticatedEnv_WithMockAuth + TestExecuteAuthExecCommand_NoCommand),
   list (tree + JSON), login, validate, whoami.

8. cmd/auth/shell.go — tighten the pre-dash arg check and fix the hint.
   The previous check only caught the no-separator case; `atmos auth
   shell bash -- -lc env` had ArgsLenAtDash() == 1 and slipped through
   while getSeparatedArgs silently dropped "bash". Condition is now
   `dashIndex == -1 || dashIndex > 0` so positional args appearing
   before "--" are also rejected. The error message no longer suggests
   `-- bash` (which would just feed "bash" as the first arg to the
   default shell) — it points at `--shell` for the shell-binary
   override and "--" only for the shell args.
   Extracted into validateAuthShellArgs to keep executeAuthShellCommand
   under the 60-line revive limit. Added TestValidateAuthShellArgs with
   5 subtests covering the three acceptable and two rejected arg
   shapes plus the ErrInvalidArguments sentinel contract.

9. cmd/auth/shell.go + cmd/auth/exec.go — wrap PrepareShellEnvironment
   failures with a static sentinel. Both helpers had a raw
   fmt.Errorf("failed to prepare ...: %w", err) that didn't satisfy the
   repo-wide "All errors MUST be wrapped using static errors defined in
   errors/errors.go" rule. Added new sentinel
   errUtils.ErrPrepareShellEnvironment and applied to both call sites.
   Updated TestPrepareShellEnvironment to assert the sentinel is in the
   chain (errors.Is) plus the original underlying error.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(auth): apply resetAuthCmdFlags across all smoke tests for state isolation

Add `resetAuthCmdFlags(t, cmd)` to every test that uses a package-level
`auth*Cmd` so flag/Changed state cannot leak across tests under shuffled
runs. This is the in-package equivalent of `cmd.NewTestKit(t)` —
`cmd/auth` cannot import `cmd` (cmd/root.go blank-imports cmd/auth) and
`NewTestKit` is `_test.go`-scoped, so the local helper enforces the same
auto-cleanup contract via t.Cleanup.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Matt Topper <[email protected]>
Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Andriy Knysh <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: aknysh <[email protected]>
Co-authored-by: atmos-pro[bot] <atmos-pro[bot]@users.noreply.github.com>

This branch was successfully deployed

1 active deployment
preview — 9320ed75 Deployed Apr 21, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants