Skip to content

Initial implementation - #1

Merged
Andriy Knysh (aknysh) merged 40 commits into
masterfrom
init
Oct 14, 2020
Merged

Andriy Knysh (aknysh) merged 40 commits into
masterfrom
init

Conversation

@aknysh

Copy link
Copy Markdown
Member

what

  • Initial implementation of variants CLI cloud automation tool
  • Add README
  • Add example

why

  • Create a CLI tool and provide usage example for

    • Provisioning Terraform projects
    • Deploying helm charts to Kubernetes clusters using helmfiles
    • Executing helm commands on Kubernetes clusters
    • Provisioning istio on Kubernetes clusters using [istio operator (https://istio.io/latest/blog/2019/introducing-istio-operator/) and helmfile
    • Combining various commands into workflows to execute many commands sequentially in just one step
    • ... and many more

Comment thread README.md Resolved
Comment thread README.md Resolved
@osterman

Copy link
Copy Markdown
Member

Please move README.md to README.yaml

Comment thread README.md Resolved
Comment thread README.md Resolved
@osterman

Copy link
Copy Markdown
Member

Please remove the current examples. They are too complex, too much tech debt to maintain, and not something we can more easily test, ideally without an AWS account.

@osterman

Copy link
Copy Markdown
Member

Keep in mind, we'll be using this in https://github.com/cloudposse/reference-architectures so we'll have more advanced examples that we actually test and maintain. Just not here.

Comment thread README.md Resolved
Comment thread README.md Resolved
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 5, 2026
- 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]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 23, 2026
Adds comprehensive tests for:
- CleanExpiredWorkdirs with mock filesystem
- formatDuration for human-readable output
- getLastAccessedTime with atime fallback to mtime
- checkWorkdirExpiry with valid/corrupt/missing metadata
- isLocalSource for local vs remote URI detection

Also fixes linter issues:
- godot: Fix comment in duration.go
- revive: Refactor formatWithOptions to map-based dispatch

Addresses CodeRabbit comment #1 requesting improved patch coverage.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 23, 2026
Adds comprehensive tests for:
- CleanExpiredWorkdirs with mock filesystem
- formatDuration for human-readable output
- getLastAccessedTime with atime fallback to mtime
- checkWorkdirExpiry with valid/corrupt/missing metadata
- isLocalSource for local vs remote URI detection

Also fixes linter issues:
- godot: Fix comment in duration.go
- revive: Refactor formatWithOptions to map-based dispatch

Addresses CodeRabbit comment #1 requesting improved patch coverage.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 23, 2026
This commit addresses the second round of CodeRabbit review comments:

Comment #1 - Global flags in planfile commands:
- Add global flag parsing (--base-path, --config, --config-path, --profile)
  to delete.go, download.go, and upload.go using flags.ParseGlobalFlags()
- Refactored upload.go to extract helper functions and reduce function length

Comment #3 - GenerateKey placeholder validation:
- Add validation for required fields (Stack, Component, SHA) when used in pattern
- Return ErrPlanfileKeyInvalid error instead of leaving placeholders unreplaced
- Update interface_test.go with new test cases for validation behavior

Comments #4-5 - Golden file anchor mismatches:
- Update templates to use user-content- prefix on anchor IDs for proper
  markdown link fragment resolution
- Regenerate all golden files to match new template output

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 23, 2026
This commit addresses the second round of CodeRabbit review comments:

Comment #1 - Global flags in planfile commands:
- Add global flag parsing (--base-path, --config, --config-path, --profile)
  to delete.go, download.go, and upload.go using flags.ParseGlobalFlags()
- Refactored upload.go to extract helper functions and reduce function length

Comment #3 - GenerateKey placeholder validation:
- Add validation for required fields (Stack, Component, SHA) when used in pattern
- Return ErrPlanfileKeyInvalid error instead of leaving placeholders unreplaced
- Update interface_test.go with new test cases for validation behavior

Comments #4-5 - Golden file anchor mismatches:
- Update templates to use user-content- prefix on anchor IDs for proper
  markdown link fragment resolution
- Regenerate all golden files to match new template output

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 24, 2026
Adds comprehensive tests for:
- CleanExpiredWorkdirs with mock filesystem
- formatDuration for human-readable output
- getLastAccessedTime with atime fallback to mtime
- checkWorkdirExpiry with valid/corrupt/missing metadata
- isLocalSource for local vs remote URI detection

Also fixes linter issues:
- godot: Fix comment in duration.go
- revive: Refactor formatWithOptions to map-based dispatch

Addresses CodeRabbit comment #1 requesting improved patch coverage.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 30, 2026
- Use filepath.Join for OS-safe test paths (Comments #1, #6)
- Route FileCache operations through injected FileSystem interface (Comment #2)
- Add ErrCacheFetch sentinel and wrap fetch() errors (Comment #3)
- Fix misleading "log" comment in GetOrFetch (Comment #4)
- Add missing BrowserSessionWarningShown assertion (Comment #5)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jan 30, 2026
- Use filepath.Join for OS-safe test paths (Comments #1, #6)
- Route FileCache operations through injected FileSystem interface (Comment #2)
- Add ErrCacheFetch sentinel and wrap fetch() errors (Comment #3)
- Fix misleading "log" comment in GetOrFetch (Comment #4)
- Add missing BrowserSessionWarningShown assertion (Comment #5)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Andriy Knysh (aknysh) added a commit that referenced this pull request Feb 5, 2026
…2010)

* fix: JIT source provisioning now takes precedence over local components

When both source.uri and provision.workdir.enabled are configured on a
component, the JIT source provisioner now always runs, even if a local
component already exists. This ensures that source + workdir provisioning
always vendors from the remote source to the workdir path, respecting the
version specified in stack config rather than using a potentially stale
local component.

Added regression test to verify source provisioning takes precedence when
both local component and source config are present.

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

* feat: version-aware JIT source provisioning with TTL-based cleanup

- Implement intelligent re-provisioning for remote sources based on version/URI changes
- Add incremental local sync with per-file checksum comparison using SyncDir
- Support TTL-based cleanup for stale workdirs via duration parsing
- Move workdir metadata from flat file to .atmos/metadata.json for better organization
- Track source_uri, source_version, and last_accessed timestamps
- Add new CLI flags: --expired, --ttl, --dry-run for workdir clean command
- Update workdir list and show commands with version and access information
- Extract duration parsing to new pkg/duration package for reusability

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

* refactor: Reduce cyclomatic and cognitive complexity in workdir/source packages

- Extract helper functions to reduce function complexity:
  - duration.go: Use maps for unit multipliers and keywords, extract parseInteger/parseWithSuffix/parseKeyword
  - provision_hook.go: Extract isNonEmptyDir and checkMetadataChanges
  - clean.go: Extract checkWorkdirExpiry, getLastAccessedTime, getModTimeFromEntry
  - fs.go: Extract syncSourceToDest, fileNeedsCopy, deleteRemovedFiles
  - workdir.go: Extract validateComponentPath, computeContentHash, create localMetadataParams struct

- Pass localMetadataParams by pointer to avoid hugeParam warning

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

* docs: Update source-provisioning example to use demo-library

Replace terraform-null-label (which is a module, not a component) with
demo-library components that can actually be run with terraform apply.

The example now demonstrates both source types:
- weather: LOCAL source (../demo-library/weather)
- ipinfo: REMOTE source (github.com/cloudposse/atmos//examples/demo-library/ipinfo)

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

* fix: Address PR review comments for JIT source provisioning

- Add duration overflow guard in ParseDuration (Comment #6)
- Fix non-workdir re-provisioning: skip metadata check for non-workdir targets (Comments #7, #11)
- Detect version removal: trigger re-provisioning when version is removed (Comments #8, #14)
- Fix blog date 2025 → 2026 (Comments #9, #16)
- Surface metadata read failures as warnings in ListWorkdirs (Comment #10)
- Add periods to comment block in needsProvisioning (Comment #12)
- Treat .atmos-only directories as empty in isNonEmptyDir (Comment #13)
- Skip .atmos during source walk in syncSourceToDest (Comment #15)

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

* fix: Update golden snapshot for atmos describe config

Add the new provision.workdir section to the expected output,
matching the new JIT source provisioning configuration schema.

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

* fix: Address additional PR review comments

- Guard against int64 overflow in parseWithSuffix (Comment #2)
- Branch metadata writing by source type - local vs remote (Comment #3)
- Add permission checks to fileNeedsCopy for mode changes (Comment #4)

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

* test: Add tests to improve coverage for workdir and source provisioning

Adds comprehensive tests for:
- CleanExpiredWorkdirs with mock filesystem
- formatDuration for human-readable output
- getLastAccessedTime with atime fallback to mtime
- checkWorkdirExpiry with valid/corrupt/missing metadata
- isLocalSource for local vs remote URI detection

Also fixes linter issues:
- godot: Fix comment in duration.go
- revive: Refactor formatWithOptions to map-based dispatch

Addresses CodeRabbit comment #1 requesting improved patch coverage.

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

* fix: Return wrapped error from ReadMetadata instead of warning

Changes error handling in ListWorkdirs to return a wrapped error when
ReadMetadata fails, surfacing permission/corruption issues to callers.
Directories without metadata (metadata == nil) still skip silently.

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

* test: Improve test coverage and address CodeRabbit review comments

- Add metadata_test.go with tests for UpdateLastAccessed and readMetadataUnlocked
- Add buildLocalMetadata tests covering all timestamp preservation branches
- Add cleanExpiredWorkdirs and CleanExpiredWorkdirs tests
- Fix ListWorkdirs to skip invalid metadata instead of failing entire operation
- Fix zero timestamp display to show "-" instead of "0001-01-01"
- Fix isLocalSource to use filepath.IsAbs for Windows path support
- Fix godot lint issues in log_utils.go

Coverage improvements:
- pkg/provisioner/workdir: 82.1% -> 88.1%
- cmd/terraform/workdir: 58.7% -> 92.2% (function coverage)
- UpdateLastAccessed: 0% -> 84.2%
- readMetadataUnlocked: 0% -> 100%
- buildLocalMetadata: 57% -> 100%
- cleanExpiredWorkdirs: 0% -> 100%

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

* test: Add JIT source provisioning tests for destroy and init commands

Add test coverage to confirm that JIT source provisioning correctly
takes precedence over local components for all terraform subcommands,
not just plan. These tests verify that when:
- source.uri is configured
- provision.workdir.enabled: true
- A local component exists at components/terraform/<component>/

The workdir is populated from the remote source, NOT copied from
the local component. This confirms the fix in ExecuteTerraform()
works universally for destroy and init commands.

Uses table-driven test pattern to avoid code duplication.

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

* test: Expand JIT source tests to cover all terraform subcommands

Expand table-driven test to verify JIT source provisioning works for
all 22 terraform subcommands that operate on a component with a stack:

Core execution: apply, deploy, destroy, init, workspace
State/resource: console, force-unlock, get, graph, import, output,
                refresh, show, state, taint, untaint
Validation/info: metadata, modules, providers, test, validate

All commands correctly trigger JIT source provisioning when:
- source.uri is configured
- provision.workdir.enabled: true
- A local component exists

The workdir is populated from remote source, not local component.

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

* test: Improve test coverage and address CodeRabbit review comments

- Make tests fail-fast instead of silently skipping when files don't exist
- Verify context.tf exists (proving remote source was used)
- Assert main.tf does NOT exist (proving local component wasn't copied)
- Remove unused strings import
- Update roadmap with JIT source provisioning precedence milestone
- Update vendoring initiative progress from 86% to 89%

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

* fix: Add JIT source provisioning to generate commands (#2019)

- Add JIT source provisioning to terraform generate varfile
- Add JIT source provisioning to terraform generate backend
- Add JIT source provisioning to helmfile generate varfile
- Add JIT source provisioning to packer output
- Update golden snapshot for secrets-masking_describe_config test

The generate commands were missing JIT source provisioning that exists
in ExecuteTerraform(), causing them to fail with JIT-vendored components.
This fix adds the same pattern to all affected commands.

Closes #2019

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

* docs: Add automatic component refresh milestone to roadmap

Add new milestone to Vendoring & Resilience initiative:
- "Automatic component refresh on version changes"
- Links to PR #2010 and version-aware-jit-provisioning blog post
- Update progress from 89% to 95%

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

* test: Improve test coverage and address CodeRabbit review comments

- Add tests for workdir clean command edge cases
- Add tests for workdir show command scenarios
- Add duration parsing tests for TTL validation
- Add filesystem tests for workdir operations
- Add metadata lock tests for Unix file locking

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

* fix: Windows test compatibility and improve error hint accuracy

- Skip permission-based tests on Windows (Unix permissions not supported)
  - TestFileNeedsCopy_DifferentPermissions
  - TestCopyFile_PreservesPermissions
  - TestServiceProvision_WriteMetadataFails (read-only dirs work differently)
- Use actual componentPath in error hint instead of hardcoded path

Addresses CodeRabbit review feedback.

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

* fix: Address CodeRabbit review comments

- Wrap auto-provision error with ErrSourceProvision sentinel (packer_output.go)
- Add error wrapping with ErrWorkdirMetadata in Windows metadata loader
- Document circular import limitation preventing cmd.NewTestKit usage

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

* fix: Use runtime.GOOS instead of os.Getenv for Windows detection

GOOS is a compile-time constant, not a runtime environment variable.
os.Getenv("GOOS") returns empty unless explicitly set.

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

* chore: Ignore flaky kubernetes.io URLs in link checker

The kubernetes.io domain frequently has connection failures/timeouts
in CI, causing spurious link check failures.

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

* test: Improve JIT source test assertions with explicit failure

Instead of silently passing when main.tf doesn't exist, the tests now:
- Explicitly fail if main.tf exists (unexpected)
- Read and check for LOCAL_VERSION_MARKER to provide better diagnostics
- Use t.Fatalf to fail fast with clear error messages

Addresses CodeRabbit feedback about test assertion clarity.

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

* test: improve coverage for JIT source provisioning

Add comprehensive tests for:

- pkg/provisioner/workdir/metadata.go:
  - MetadataPath function
  - WriteMetadata with all fields populated
  - ReadMetadata new location priority over legacy
  - UpdateLastAccessed preserves all fields

- pkg/provisioner/workdir/clean.go:
  - checkWorkdirExpiry for expired/non-expired workdirs
  - getModTimeFromEntry
  - findExpiredWorkdirs with mixed workdirs
  - CleanExpiredWorkdirs with empty base path
  - Clean with Expired option precedence
  - formatDuration edge cases

- pkg/provisioner/workdir/fs.go:
  - DefaultPathFilter.Match with patterns
  - SyncDir with nested directories
  - SyncDir updating changed files

- pkg/provisioner/source/provision_hook.go:
  - checkMetadataChanges with version scenarios
  - isNonEmptyDir edge cases
  - needsProvisioning for non-workdir targets
  - writeWorkdirMetadata source type detection
  - writeWorkdirMetadata preserving ContentHash

Coverage improvements:
- workdir package: ~79% → 92.5%
- source package: ~76% → 83.6%

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

---------

Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: aknysh <[email protected]>
Igor Rodionov (goruha) added a commit that referenced this pull request Mar 16, 2026
…cle (#2079)

* feat: Add CI Summary Templates and --ci flag for automated pipelines

Implement comprehensive CI integration with rich tfcmt-style templates for terraform plan/apply outputs. Auto-generates job summaries, outputs, and artifact management.

- Add CIProvider interface for extensible CI component support
- Implement terraform CI provider with JSON-based output parsing
- Create embedded default templates (plan.md, apply.md) with resource counts, badges, and collapsible sections
- Add template loader with atmos.yaml override support (base_path, per-component templates)
- Add generic CI provider for local testing (--ci flag without platform detection)
- Implement unified CI executor with hook bindings and declarative actions
- Add golden file tests for template regression testing
- Add --ci flag to plan/apply commands (respects CI env var precedence)
- Wire CI hooks through terraform PostRunE for automatic execution

Template features match existing GitHub Actions with tfcmt formatting:
- Plan summaries with resource change badges (CREATE, CHANGE, REPLACE, DESTROY)
- Caution warning when resources will be deleted
- Terraform output variables table after apply
- Error/warning extraction from command output
- Markdown rendering with collapsible sections

CI integration is controlled by:
1. ci.enabled in atmos.yaml (enables/disables integration)
2. CI environment detection (GitHub Actions auto-detected)
3. --ci flag on plan/apply (forces CI mode for testing)

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

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

* fix: Add perf.Track and linting fixes for CI package

- Add defer perf.Track() to all public functions in CI package
- Fix import ordering (go-fumpt)
- Fix octal literal formatting (0644 → 0o644)
- Update golangci.yml to exclude pkg/ci/github/ from depguard
- Update lintroller to exclude pkg/ci/ from some checks
- Fix test file permission literals

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

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

* docs: Add blog post announcing native CI integration

Announces the new native CI integration feature with:
- Simple GitHub Actions workflow examples
- Explanation of auto-detection and --ci flag
- Matrix strategy for multiple components
- Local testing instructions
- Configuration options

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

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

* fix: Add missing planfile packages and fix broken blog link

The planfile command and pkg/ci/planfile packages were not committed
because .gitignore had a rule `**/planfile` which ignored any directory
named "planfile". Changed the rule to only ignore files matching
`*.planfile` pattern (already covered by existing rules).

Also:
- Fixed broken link in CI integration blog post that referenced /ci
- Added pkg/ci/planfile/s3/ to golangci exclusions for AWS SDK imports
- Fixed lint issues in internal/exec/describe_affected.go

Note: The newly tracked files have pre-existing lint issues that will
need to be addressed in a follow-up commit.

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

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

* fix: Remove duplicate defaultFilePermissions constant

The constant was already defined in docs_generate.go in the same package.

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

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

* fix: Address all lint issues in CI integration code

Refactored CI integration code to resolve all lint issues without
using nolint directives:

- Extract helper functions to reduce cyclomatic/cognitive complexity
- Use pointer parameters for large structs (hugeParam fixes)
- Extract constants for magic numbers
- Refactor nested if blocks into early returns
- Split long functions into focused helpers

Files refactored:
- cmd/ci/status.go: Split getRepoContext into helper functions
- cmd/terraform/planfile/*.go: Extract format/download helpers
- pkg/ci/executor.go: Extract platform detection and binding logic
- pkg/ci/terraform/parser.go: Extract resource processing functions
- pkg/ci/planfile/github/store.go: Extract repo info and zip handling
- pkg/ci/templates/loader.go: Extract template loading by source

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

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

* test: Update golden snapshots for CI integration

Regenerated golden snapshots to reflect new CI integration features:
- New `ci` command in atmos --help output
- New `planfile` subcommand under `terraform`
- New `--ci` flag for terraform plan/apply commands
- New CI configuration fields in describe config output

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

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

* fix: Make TestLoaderResolvePath cross-platform compatible

Use filepath.FromSlash() for path literals in test expectations to
ensure the test passes on both Unix and Windows, where path separators
differ.

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

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

* docs: Update CI PRDs with implementation status

- native-ci-integration.md: Added Implementation Status section showing
  Phase 1 complete, Phase 2 ~70%, and Phases 3-6 pending. Updated
  package structure and Files to Create table with status indicators.
  Documented additional components implemented beyond original PRD.

- ci-summary-templates.md: Marked as complete with all files implemented.
  Added missing test files to the implementation table.

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

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

* docs: Clarify CI mode activation in blog post

Address review comment: clarify that ci.enabled: true in atmos.yaml
is respected as a way to enable CI mode. Added numbered list of
activation conditions and clarified precedence order.

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

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

* fix: Address CodeRabbit review comments on CI integration

This commit addresses multiple CodeRabbit review comments:

- cmd/terraform/planfile/download.go: Fix double %w error wrapping using
  errors.Join, fix Windows path handling using filepath.Base()
- cmd/terraform/planfile/upload.go: Fix unreachable GitHub Actions detection
  by reordering store type logic
- pkg/ci/github/checks.go: Add documentation for completed status mapping,
  remove unused mapGitHubConclusionToCheckRunState function
- pkg/ci/planfile/github/store.go: Add HTTP timeout (30s) for artifact
  downloads, fix error wrapping with errors.Join
- pkg/ci/planfile/local/store.go: Fix file filter to only skip .metadata.json
  files
- pkg/ci/planfile/s3/store.go: Simplify error check functions by removing
  unused second parameter
- pkg/ci/terraform/provider.go: Add nil check for result parameter in
  GetOutputVariables
- tools/lintroller/rule_perf_track.go: Add pkg/template exclusion with proper
  documentation

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

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

* fix: Address additional CodeRabbit review comments on CI integration

This commit addresses the second round of CodeRabbit review comments:

Comment #1 - Global flags in planfile commands:
- Add global flag parsing (--base-path, --config, --config-path, --profile)
  to delete.go, download.go, and upload.go using flags.ParseGlobalFlags()
- Refactored upload.go to extract helper functions and reduce function length

Comment #3 - GenerateKey placeholder validation:
- Add validation for required fields (Stack, Component, SHA) when used in pattern
- Return ErrPlanfileKeyInvalid error instead of leaving placeholders unreplaced
- Update interface_test.go with new test cases for validation behavior

Comments #4-5 - Golden file anchor mismatches:
- Update templates to use user-content- prefix on anchor IDs for proper
  markdown link fragment resolution
- Regenerate all golden files to match new template output

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

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

* test: Add comprehensive CI integration test coverage

Add test files for CI integration packages to improve code coverage:

- pkg/ci/planfile/github/store_test.go: GitHub Artifacts store tests
- pkg/ci/planfile/s3/store_test.go: S3 store helper function tests
- pkg/ci/github/status_test.go: GitHub status fetching tests
- pkg/ci/github/checks_test.go: Check run creation/update tests
- cmd/ci/status_test.go: CI status command helper tests
- pkg/ci/output_test.go: Output writer tests
- cmd/terraform/planfile/upload_test.go: Upload command helper tests
- cmd/terraform/planfile/list_test.go: List formatting tests
- Expanded pkg/ci/executor_test.go with data structure tests
- Expanded pkg/ci/planfile/local/store_test.go with edge cases

Also removes accidentally committed lintroller binary and adds it to
.gitignore.

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

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

* refactor: Restructure CI config schema for provider-agnostic naming

Reorganize CI configuration from confusing nested structure to a cleaner,
provider-agnostic structure with four top-level capabilities:

- output: key=value pairs for downstream jobs (GitHub: $GITHUB_OUTPUT)
- summary: markdown job summary (GitHub: $GITHUB_STEP_SUMMARY)
- checks: commit status checks (GitHub: Check Runs API)
- comments: PR/MR comments (GitHub: PR comments, GitLab: MR notes)

Key changes:
- Rename status_checks -> checks
- Rename pr_comment -> comments
- Move variables under output where it belongs
- Remove outputs wrapper (was conflating concepts)
- Add template field to summary and comments configs

This structure supports GitHub Actions, GitLab CI, and other CI providers
with consistent, intuitive naming.

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

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

* feat: Wire up CI config settings to executor implementation

- Add isActionEnabled() to check if CI actions are enabled based on config
- Summary and Output enabled by default, Checks disabled by default
- Upload/Download always enabled (controlled by planfile config)
- Add filterVariables() to filter output variables by CI.Output.Variables
- Update executeSummaryAction() to support custom template from config
- Add comprehensive tests for config-aware behavior

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

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

* fix: Address CodeRabbit review comments on CI integration

- Use ErrNotImplemented for GitHub Artifacts upload limitation
- Fix broken internal link fragment in plan_no_changes.md template
- Remove non-deterministic TestGetDefaultProvider test
- Remove tautological TestTableHeaderWidth and TestPlanfileInfoSorting tests
- Use errors.Is() for specific error sentinel verification in upload_test.go
- Handle JSON decode errors in checks_test.go mock handlers
- Check url.Parse errors in checks_test.go
- Fix config key names in PRD docs (ci.checks.enabled, ci.comments.enabled)
- Add Screengrab component to ci/status.mdx per documentation standards

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

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

* fix: Address error handling patterns in CI and config code

Changes:
- Use consistent fmt.Errorf("%w: ...") pattern in planfile store instead
  of errors.Join() for consistency with other methods
- Make error messages unique to avoid linter warning about duplicate
  string literals
- Fix type switch on error to use errors.As() in config loading
- Add nolint comment for ATMOS_CLI_CONFIG_PATH os.Getenv (bootstrap config)

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

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

* docs: Move ATMOS_PROFILE/ATMOS_IDENTITY env vars to job level

Move environment variables from step level to job level in workflow
examples for better practice. This ensures all steps in the job have
access to the environment variables without repetition.

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

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

* docs: Restructure PRD and blog with reproducibility narrative

Lead with WHY before WHAT: complex bash scripts in CI workflows signal
hidden complexity from tools not designed for CI. The reproducibility
principle—same command, same behavior everywhere—is now the core
narrative for native CI integration.

PRD changes:
- Add Executive Summary with key insight
- Expand Problem Statement with Hidden Complexity Problem
- Add The Reproducibility Principle section with before/after examples
- Rename "What You Get" to "What This Enables" (after context)
- Remove duplicate Problem Statement section

Blog post changes:
- Lead with reproducibility narrative
- Add "The Problem with CI Glue Code" section
- Add "The Reproducibility Principle" with concrete examples
- Add "What This Enables" to connect solution to problem

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

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

* docs: Add formal functional requirements and fix matrix examples

Add Functional Requirements (FR-1 through FR-9):
- FR-1: CI Environment Detection
- FR-2: Job Summary Output
- FR-3: CI Output Variables
- FR-4: Status Checks
- FR-5: Planfile Storage
- FR-6: Plan Verification
- FR-7: Command Parity
- FR-8: Describe Affected Matrix Format
- FR-9: CI Status Command

Add Non-Functional Requirements (NFR-1 through NFR-4):
- NFR-1: Performance targets
- NFR-2: Reliability (graceful degradation)
- NFR-3: Security boundaries
- NFR-4: Extensibility

Fix matrix examples to use --output-file flag:
- Add --output-file="$GITHUB_OUTPUT" usage pattern
- Show complete workflow example with affected job
- Document key=value output format for $GITHUB_OUTPUT

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

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

* fix: Remove pkg/template from perf-track exclusions

The pkg/template package performs template.Parse and recursive AST
tree traversal, which are non-trivial operations requiring perf
tracking per coding guidelines. Only trivial String() methods qualify
for exclusion.

Addresses CodeRabbit review comment.

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

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

* fix: Address CodeRabbit review comments on CI integration

- Parse global flags before loading config in ci status command
- Add static error sentinels for planfile operations
- Add validation to planfile registry Register function
- Wrap errors with static sentinels in local and S3 stores
- Fix MD028 violations in markdown templates with HTML comments

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

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

* test: Update golden snapshots for CI schema and terraform flags

Update snapshots to reflect:
- CI config schema changes (outputs->output, status_checks->checks,
  pr_comment->comments, added summary section)
- New terraform apply flags (--auto-generate-backend-file,
  --init-run-reconfigure)

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

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

* test: Regenerate terraform plan help snapshot

Update snapshot for terraform plan --help to include new flags:
- --auto-generate-backend-file
- --init-run-reconfigure

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

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

* fix: Use platform-specific absolute paths in TestLoaderResolvePath

On Windows, filepath.IsAbs() requires a drive letter (e.g., C:\) for a
path to be considered absolute. The test was using Unix-style paths
(/absolute/path) which become \absolute\path on Windows - not absolute.

This fix uses runtime.GOOS to select appropriate absolute paths for
each platform, ensuring the test works correctly on both Windows and
Unix systems.

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

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

* fix: Address CodeRabbit review comments on planfile commands

1. delete.go: Require --force flag for deletion (returns error instead
   of silently exiting), using static error ErrPlanfileDeleteRequireForce
2. list.go: Add global flag parsing (--base-path, --config, etc.)
3. show.go: Add global flag parsing (--base-path, --config, etc.)
4. check.go: Add Name field to UpdateCheckRunOptions (distinct from Title)
5. checks.go: Use opts.Name instead of opts.Title for GitHub API

Note: Comment #5 about template field access was investigated and found
to be a false positive. The templates correctly access fields from
TerraformTemplateContext which provides .Resources, .HasChanges() etc.
at the top level (not under .Result).

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

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

* refactor: Use StandardParser pattern and pkg/list for planfile commands

Refactor all 5 planfile commands (list, show, delete, download, upload) to:
1. Use StandardParser pattern for flag handling (instead of package-level variables)
2. Use pkg/list infrastructure for list output formatting (instead of custom formatters)

Benefits:
- Automatic environment variable support (ATMOS_PLANFILE_*)
- Proper precedence handling (CLI > ENV > config > defaults)
- Type-safe options structs
- Consistent output formatting with TTY detection
- Less code to maintain

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

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

* chore: Add .claude/plans/ to .gitignore

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

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

* fix: Rename shadowed fmt variable to outputFmt in list.go

The local variable `fmt` was shadowing the imported fmt package.
Renamed to `outputFmt` to avoid the shadowing issue.

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

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

* fix: Address CodeRabbit review comments on CI integration

- Use *bool pointer types for CI config Enabled fields to distinguish
  "not set" from "explicitly false" (fixes isActionEnabled defaults)
- Document Detect() non-deterministic map iteration order in registry.go
- Replace manual mock with mockgen-generated MockComponentCIProvider
- Add validation for empty Stack/ComponentFromArg in GetArtifactKey
- Add perf.Track() to RunCIHooks function per coding guidelines

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

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

* chore: Add TODO comment for GetArtifactKey interface consideration

Address CodeRabbit feedback about aligning with planfile.GenerateKey
validation pattern. The current defensive approach with placeholders
is appropriate since the key is only used for debug logging, but noted
for future consideration if the interface is used for actual operations.

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

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

* fix: Remove unused PlanFile and Content fields from Hook struct

These fields were placeholders for deprecated CI hook commands
(ci.upload, ci.download, ci.summary). The modern approach uses
RunCIHooks which delegates to ci.Execute() with provider bindings.

Added comment explaining the deprecation and pointing to pkg/ci/.

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

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

* fix: Address CodeRabbit review comments on CI integration (part 2)

- GenericProvider: Return ErrCIOperationNotSupported error instead of
  (nil, nil) for GetStatus, CreateCheckRun, and UpdateCheckRun methods
  to prevent nil dereference panics at call sites
- s3/store.go: Wrap loadMetadata errors with ErrPlanfileMetadataFailed
  sentinel for consistent error handling
- loader_test.go: Handle fs.Sub error explicitly with panic for the
  (impossible) failure case since the directory is compile-time embedded

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

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

* fix: Address CodeRabbit review comments on CI integration (part 3)

Security fixes:
- Add path traversal validation in local planfile store to prevent
  directory escape attacks via malicious keys

Bug fixes:
- Fix type assertion panic in hooks.go when "hooks" section is missing
- Replace custom errorAs with stdlib errors.As in S3 store

Code quality improvements:
- Replace custom replaceAll/indexOf functions with strings.ReplaceAll
- Fix comment/constant name mismatch in status.go
- Add error logging in GitHub provider init
- Simplify error wrapping in download.go using errUtils.Build()
- Use errUtils.Build() pattern in delete.go for consistency
- Refactor store detection into helper functions in upload.go

Implementation:
- Implement actual upload/download actions in executor.go instead of
  no-op placeholders. Actions now read/write planfiles to configured
  storage backends with proper metadata.

Documentation:
- Add thread-safety documentation for regex compilation in parser.go
- Add comment about file permissions in describe_affected.go
- Add planfile subcommand documentation (upload, download, list,
  delete, show)

Testing:
- Add path traversal prevention tests for local store
- Remove obsolete tests for deleted custom helper functions

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

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

* fix: Wrap errors with static sentinels per CodeRabbit review

- Wrap file open errors in output.go with ErrCIOutputWriteFailed and
  ErrCISummaryWriteFailed sentinels
- Wrap JSON unmarshal errors in parser.go with ErrParseFile sentinel

This ensures consistent error checking using errors.Is() throughout
the codebase.

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

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

* fix: Wrap write errors with static sentinels per CodeRabbit review

- Wrap fmt.Fprintf error in WriteOutput with ErrCIOutputWriteFailed
- Wrap WriteString error in WriteSummary with ErrCISummaryWriteFailed

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

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

* test: Regenerate golden snapshots for CI/terraform features

Update golden snapshot files to include new features added to this branch:
- ci command (CI/CD integration)
- planfile subcommand for terraform
- --ci flag for terraform plan
- planfiles configuration section

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

* fix: Update ui.* calls to match new void-return API

Main branch merged #1980 which removed error returns from ui.* functions.
Updated cmd/ci/status.go and cmd/terraform/planfile/*.go to match the
new API that doesn't return values.

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

* [autofix.ci] apply automated fixes

* fix: Wrap CI status fetch failures with sentinel error

Address CodeRabbit feedback: Wrap provider.GetStatus errors with
ErrCIStatusFetchFailed sentinel so callers can reliably detect the
failure class, following coding guidelines for error handling.

Also fixes:
- gofumpt formatting in schema.go
- godot (comment periods) in log_utils.go

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

* [autofix.ci] apply automated fixes

* Added native ci fixtures

* Added test to clarify atmos terraform planfile list works

* Added terraform planfile cmd

* Move planfile name from options to flags

* Added planfile storage on terraform plan

* Regenerate snapshots for planfile subcommand in terraform help

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

* Regenerate secrets-masking snapshot for planfiles and ci config sections

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

* Fix readme and tests

* Refactor ci pkg - defnine providers and plugins

* Move generic provider to separate package

* [autofix.ci] apply automated fixes

* Separate provider and plugin interfaces

* Refactor code

* Refactor

* Refactor

* Refactoring

* Added before.terraform.plan hook

* Added before.terraform.plan

* Add CI failure test case and refactor generic provider UI output

Refactor UpdateCheckRun to use consistent UI method per status (success,
error, warning) for title and summary lines. Add mock-failure component
and acceptance test verifying check run failure reporting with --ci flag.

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

* Added error checks

* Prepare cancel check test case

* Added outputs

* Fix outputs

* Fix tests

* Fix hooks

* Fix hooks

* Force local storage usage

* Force local storage usage

* Force local storage usage

* Added debug logs

* Fix golden snapshot

* Fix golden snapshot

* Install GHA

* Fix mock component

* Fix ci summary

* Fix tests

* Fix markdown

* Fix outputs parse

* [autofix.ci] apply automated fixes

* Fix parser

* Fix warning

* [autofix.ci] apply automated fixes

* Fix templating

* Fix templating

* Macos Tests takes more the 45 minutes

* Macos Tests takes more the 45 minutes

* Fix macos longs running tests

* Fix macos atmos vendor pull

* [autofix.ci] apply automated fixes

* Added native ci fixtures

* Added test to clarify atmos terraform planfile list works

* Added terraform planfile cmd

* Move planfile name from options to flags

* Added planfile storage on terraform plan

* Regenerate snapshots for planfile subcommand in terraform help

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

* Regenerate secrets-masking snapshot for planfiles and ci config sections

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

* Fix readme and tests

* Refactor ci pkg - defnine providers and plugins

* Move generic provider to separate package

* Separate provider and plugin interfaces

* [autofix.ci] apply automated fixes

* Refactor code

* Refactor

* Refactor

* Refactoring

* Added before.terraform.plan hook

* Added before.terraform.plan

* Add CI failure test case and refactor generic provider UI output

Refactor UpdateCheckRun to use consistent UI method per status (success,
error, warning) for title and summary lines. Add mock-failure component
and acceptance test verifying check run failure reporting with --ci flag.

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

* Added error checks

* Prepare cancel check test case

* Added outputs

* Fix outputs

* Fix tests

* Fix hooks

* Fix hooks

* Force local storage usage

* Force local storage usage

* Force local storage usage

* Added debug logs

* Fix golden snapshot

* Install GHA

* Fix mock component

* Fix ci summary

* Fix tests

* Fix markdown

* Fix outputs parse

* Fix parser

* [autofix.ci] apply automated fixes

* Fix warning

* Fix templating

* [autofix.ci] apply automated fixes

* Fix templating

* Macos Tests takes more the 45 minutes

* Macos Tests takes more the 45 minutes

* Fix macos longs running tests

* Fix macos atmos vendor pull

* Fix git toolchain

* Added summary output

* [autofix.ci] apply automated fixes

* Improve terraform output parse

* Change release workflow to use feature release file

* Change release workflow to use auto-release script

* Fix plugin terraform outputs

* Fix terraform summary output

* Fix no changes template

* Fix test

* Fix ci summary

* Fix summary template

* Added test

* Added failure summary

* Parse errors

* Fix test

* Fix test

* Added github upload implementation

* [autofix.ci] apply automated fixes

* Added github upload implementation

* Fix github storage

* [autofix.ci] apply automated fixes

* Fix github storage

* Added md5

* Added artifacts storage

* Update PRD

* Update PRD

* FR-6: CI-integrated stored vs fresh plan verification (#2147)

* Added artifacts storage

* Update PRD

* Update PRD

* Accept artifact storage interface

* Updated PRD

* Implement phase 2

* Added planfile storage

* Update atmos in native-ci

* Update PRD

* Update native-ci-integration PRD

* Added deceompose PRD

* Decompose PRD

* Clarify questions

* Decompose clarification

* Decompose clarification

* Decompose clarification

* Decompose clarification

* Decompose clarification

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Update implemented features

* Refactor executor-plugin

* Refactor executor-plugin

* Refactor executor-plugin

* Update PRDs

* Update PRDs

* Move checkrun storage to github implementation

* planfile storage validation PRD

* Make local get sha from git

* Added PRD to fix planfile storage metadata

* Fix planfile storage medatada

* Store planfile with lock file

* Store planfile with lock file

* Store planfile with lock file

* Added planfile artifact store multiple files

* Added planfile artifact store multiple files

* Added planfile artifact store multiple files

* Added planfile artifact store multiple files

* Planfile and artifact store integration

* Define responsibility between planfile storage, artifact storage and backend storage

* Move github and s3 storage to artifact package

* Generaliza github storage

* Generaliza github storage

* Improve planfile cli

* Update status

* Added terraform apply ci

* Update prds

* Apply terraform outputs

* Update PRds with the status

* Apply CI plan verfication step 1

* planfile download fix prd

* Fix planfile download

* Fix planfile download

* Added apply verification plan

* [autofix.ci] apply automated fixes

* Fix CI test failures: update snapshots and stderr patterns

- Add --verify-plan flag to apply help golden snapshots
- Fix CI test stderr patterns: "CI action failed" → "CI hook" to match
  actual warning output ("CI hook handler failed", "CI check run creation failed")

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

* Update apply planfile storage prd

* Clarify PRds

* Added apply ci integration

* [autofix.ci] apply automated fixes

* Fix tests

* fix tests

* fix tests

* Set atmos.config ci.enabled top priority

* Update PRD

* Fix auth problem

* Fix outputs

* Fix output

* Added outputs parser

* [autofix.ci] apply automated fixes

* Fix github provider detection

* Fix apply output summary

* Enrich apply summary with resource lists and per-action badges

Rewrite apply.md template to match plan.md style: CloudPosse logo,
per-action-type badges (CREATE/CHANGE/DESTROY), CAUTION block for
destroys, and resource lists by action type in diff code blocks.

Parse resource names from apply progress lines (Creating/Modifying/
Destroying) to populate CreatedResources, UpdatedResources, and
DeletedResources. Downgrade check run token errors to Debug level.

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

* Render badges inline on a single line in plan and apply summaries

Use right-trimming (-}}) on badge template blocks so multiple badges
(CREATE/CHANGE/REPLACE/DESTROY) render on the same line instead of
each appearing on a separate line.

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

* Show plan diffs in apply summary instead of just result line

Rework cleanApplyOutput to strip pre-plan noise and apply progress
lines while keeping the plan resource diffs, apply result, and
outputs. This gives the apply summary the same detail as the plan
summary.

Add OpenTofu marker support for plan output stripping. Use
case-insensitive regex for progress lines since terraform outputs
"Still modifying..." with lowercase after Still.

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

* Added apply warnings

* Skip planfile storages if prirorities are empty

* Fix github statuses update

* Make CI experementatl

* [autofix.ci] apply automated fixes

* Decrease timeout for jobs in test workflow

Reduced timeout for job and acceptance tests from 60 to 45 minutes.

* Fix tests with experimental message

* Update implementation status

* Fix tests

* Update documentation

* Update documentation

* Fix links

* Fix documentation

* Fix broken links

* Update documentation

* Address documentation comments

* Address documentation comments

* Fix tests

* Create PRD for storage rename

* Rename storage

* Update website documentation

* Resolve sha based on git for github

* Fix tests

* [autofix.ci] apply automated fixes

* Rollback generate command

* Rollback generate command

* PRD for commit statuses (#2206)

* PRD for commit statuses

* Added checks based on github commit status

* Fix tests

* [autofix.ci] apply automated fixes

* Fix tests

* Fix status check url

* Fix status check url

* Update website docs

* Update website docs

* Update website docs

---------

Co-authored-by: Erik Osterman <[email protected]>
Co-authored-by: Claude Haiku 4.5 <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Copilot AI added a commit that referenced this pull request Mar 18, 2026
…elpers file to 3 files <600 lines each

- Remove dead `varFile string` param from printAndWriteVarFiles (CodeRabbit 🔴 #1)
- Remove setupTerraformAuthCreator, reuse defaultAuthManagerCreator (CodeRabbit 🔴 #2)
- Split terraform_execute_helpers.go (786 lines) into 3 files all <600 lines (CodeRabbit 🔴 #3):
  - terraform_execute_helpers.go: auth/env/init/validation helpers (488 lines)
  - terraform_execute_helpers_args.go: arg builders (156 lines)
  - terraform_execute_helpers_exec.go: execution pipeline + workspace/TTY/cleanup (320 lines)
- Add mutual exclusion comments to buildInitSubcommandArgs + executeTerraformInitPhase (CodeRabbit 🟡 #4)
- Document buildInitArgs vs buildInitSubcommandArgs workspace/reconfigure asymmetry (CodeRabbit 🟡 #5)
- Restore 'Resolving auth config for terraform command' debug entry log (CodeRabbit 🟡 #6)
- Restore 'Stored authenticated identity for hooks' suffix in utils_auth.go (CodeRabbit 🟡 #7)
- Extract prepareComponentExecution + executeCommandPipeline from ExecuteTerraform,
  reducing cyclomatic complexity from 25 → 9 (well below the 15 target)
- Add tests: resolveExitCode (nil/ExitCodeError/generic/wrapped), buildWorkspaceSubcommandArgs
  (delete/select/no-subcommand2), buildTerraformCommandArgs (validate subcommand),
  prepareComponentExecution (no path error), executeCommandPipeline (TTY error via nil stdin)

Co-authored-by: nitrocode <[email protected]>
Andriy Knysh (aknysh) added a commit that referenced this pull request Mar 20, 2026
…e test coverage (#2226)

* Initial plan

* refactor: extract helpers from ExecuteTerraform (complexity 160→26) with unit tests

Co-authored-by: nitrocode <[email protected]>

* docs: add blog post, roadmap entry, CLAUDE.md update for ExecuteTerraform refactor

Co-authored-by: nitrocode <[email protected]>

* [autofix.ci] apply automated fixes

* fix: address CodeRabbit issues and improve test coverage for ExecuteTerraform helpers

Co-authored-by: nitrocode <[email protected]>

* fix: address all CodeRabbit issues, reduce complexity to ≤12, split helpers file to 3 files <600 lines each

- Remove dead `varFile string` param from printAndWriteVarFiles (CodeRabbit 🔴 #1)
- Remove setupTerraformAuthCreator, reuse defaultAuthManagerCreator (CodeRabbit 🔴 #2)
- Split terraform_execute_helpers.go (786 lines) into 3 files all <600 lines (CodeRabbit 🔴 #3):
  - terraform_execute_helpers.go: auth/env/init/validation helpers (488 lines)
  - terraform_execute_helpers_args.go: arg builders (156 lines)
  - terraform_execute_helpers_exec.go: execution pipeline + workspace/TTY/cleanup (320 lines)
- Add mutual exclusion comments to buildInitSubcommandArgs + executeTerraformInitPhase (CodeRabbit 🟡 #4)
- Document buildInitArgs vs buildInitSubcommandArgs workspace/reconfigure asymmetry (CodeRabbit 🟡 #5)
- Restore 'Resolving auth config for terraform command' debug entry log (CodeRabbit 🟡 #6)
- Restore 'Stored authenticated identity for hooks' suffix in utils_auth.go (CodeRabbit 🟡 #7)
- Extract prepareComponentExecution + executeCommandPipeline from ExecuteTerraform,
  reducing cyclomatic complexity from 25 → 9 (well below the 15 target)
- Add tests: resolveExitCode (nil/ExitCodeError/generic/wrapped), buildWorkspaceSubcommandArgs
  (delete/select/no-subcommand2), buildTerraformCommandArgs (validate subcommand),
  prepareComponentExecution (no path error), executeCommandPipeline (TTY error via nil stdin)

Co-authored-by: nitrocode <[email protected]>

* [autofix.ci] apply automated fixes

* Fix setupTerraformAuth error wrapping and document pre-hook termination behavior

Co-authored-by: nitrocode <[email protected]>

* Add setupTerraformAuth unit tests to fix unused import compile error

Co-authored-by: nitrocode <[email protected]>

* fix(tests): address CodeRabbit Pass 4 feedback — strengthen assertions, add ErrInvalidAuthConfig test, clean up empty section

- Add require.Error(t, err) to TestPrepareComponentExecution_NoComponentPath_ReturnsError
  (was coverage theater: _ = err with no assertion)
- Add defaultMergedAuthConfigGetter injectable var to setupTerraformAuth so the
  ErrInvalidAuthConfig wrap branch is testable without requiring a real MergeComponentAuthFromConfig failure
- Add TestSetupTerraformAuth_MergedConfigError_WrapsWithInvalidAuthConfig covering the
  previously-untested ErrInvalidAuthConfig wrap path (non-ErrInvalidComponent errors)
- Remove empty addRegionEnvVarForImport section placeholder from coverage test file
  (those 3 tests already exist in terraform_execute_helpers_test.go)
- Update coverage test file header to reflect the correct list of covered functions

Co-authored-by: nitrocode <[email protected]>

* fix(tests): address CodeRabbit Pass 5 — split oversized test files, fix misleading wsOpts comment, add wsOpts branch test, document defaultMergedAuthConfigGetter injection layers

Co-authored-by: nitrocode <[email protected]>

* [autofix.ci] apply automated fixes

* fix(tests): remove unused 'os' import from terraform_execute_helpers_test.go after file split

Co-authored-by: nitrocode <[email protected]>

* fix: audit ExecuteTerraform refactor — lint fixes, test cleanup, fix doc

Lint fixes (16 issues):
- Fix hugeParam: handleVersionSubcommand now takes pointers
- Fix unlambda: defaultMergedAuthConfigGetter uses direct function ref
- Fix filepathJoin: split "infra/networking" into separate segments
- Fix unparam: remove unused planFile from buildApplySubcommandArgs
- Fix forbidigo: add nolint for TF_WORKSPACE (Terraform convention)
- Fix nestif: extract handlePlanStatusUpload from executeMainTerraformCommand
- Fix argument-limit: add nolint for variadic opts parameter
- Fix cyclomatic: extract shouldSkipWorkspaceSetup from runWorkspaceSetup
- Fix cyclomatic: extract runPreExecutionSteps from prepareComponentExecution
- Fix cyclomatic: extract autoGenerateComponentFiles, provisionComponentSource
- Fix cyclomatic/funlen: extract logAndWriteComponentVars, logCliVarsOverrides
- Fix add-constant: add subcommandApply/Deploy/Init/Workspace, dirPermissions

Test cleanup:
- Remove 4 duplicate resolveExitCode tests from _pipeline_test.go
- Clarify tautological cleanup test comment
- Remove unused writeTestFile helper

Add fix doc documenting all audit findings.

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

* fix: address CodeRabbit audit pass 7 — remove duplicates, add coverage

- Remove duplicate TestBuildWorkspaceSubcommandArgs_NoSubCommand2 from _pipeline_test.go
- Remove tautological cleanup tests from _args_test.go (real tests in _coverage_test.go)
- Remove redundant TestWarnOnConflictingEnvVars_NoConflictsNoError
- Add TestAssembleComponentEnvVars_NonNilTenv (tenv != nil branch coverage)
- Add TestBuildTerraformCommandArgs_Init (init switch-case dispatch)
- Add comment to generateConfigFiles re: double GenerateFilesForComponent invocation
- Document logTerraformContext tests as logging-only (not coverage theater)
- Update fix doc with all 10 audit pass 7 items and resolutions

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

* fix: address audit pass 8 — debug-level branch coverage, final cleanup

- Add TestPrintAndWriteVarFiles_DebugLogLevel_Success (item 8)
- Add TestPrintAndWriteVarFiles_DebugLogLevel_CliVarsSection (item 8)
- Add TestPrintAndWriteVarFiles_TraceLogLevel (item 8)
- Validate item 5: storeAutoDetectedIdentity already tested in utils_auth_test.go
  (gomock strict controller implicitly verifies GetChain not called)
- Validate item 10: generateConfigFiles comment already added in previous commit
- Update fix doc with all audit pass 8 resolutions

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

* fix: address audit pass 9 — explicit identity guard test, call-site comment

- Add TestStoreAutoDetectedIdentity_ExistingIdentity_NotOverwritten with
  explicit GetChain().Times(0) assertion (item 5)
- Add double-invocation comment at generateConfigFiles call site in
  runPreExecutionSteps (item 10)
- Update fix doc with pass 9 resolutions

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

* fix: address CodeRabbit review — error masking, empty workdir, cross-platform test

- Separate provisioning errors from "component does not exist" in
  resolveAndProvisionComponentPath — propagate original error directly
- Guard empty _workdir_path in provisionComponentSource to match
  prepareInitExecution behavior
- Replace Unix-only "false" command with cross-platform "go run" in
  TestResolveExitCode_OsExecExitError
- Remove warnOnConflictingEnvVars coverage theater tests (logging-only
  function, NotPanics assertions add no value)

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

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: nitrocode <[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: Claude Opus 4.6 (1M context) <[email protected]>
Copilot AI added a commit that referenced this pull request Mar 22, 2026
… stacks

Critical #1: Fail closed when --stack filter finds no matching raw manifests
Critical #2: Normalize non-glob relative imports to absolute paths in buildImportGraph
High #3: Use cfg.TerraformSectionName/cfg.HelmfileSectionName in L-05
High #4: Key L-02 baseVars by '<stack>/<component>' to prevent cross-stack collisions
High #5: Add test for ATMOS_LINT_RULE env binding in cmd/lint
High #6: Build StackNameToFileIndex in LintStacks for reliable L-08 file attribution
Medium #7: Add CohesionMaxGroups to schema for configurable L-05 threshold
Medium #8: Add golden test for rulesRelNorm consistency with L-07 relNorm
Medium #9: Clarify L-03 depth semantics (node-count vs edge-count) in description
Low #12: Add ui.Error call before returning from renderLintJSON error path
Update authors.yml to fix duplicate nitrocode entry (RB, CEO @ Infralicious)

Co-authored-by: nitrocode <[email protected]>
Agent-Logs-Url: https://github.com/cloudposse/atmos/sessions/9708e2c0-9c09-48c8-a447-323fe5ad065d
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>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 16, 2026
Per docs/fixes/2026-05-15-mcp-review-fixes.md, three production paths
still had thin coverage after the punch-list shipped — most notably
the refactored `executeMCPExport` and the previously-unreachable
`Server.Run`. This commit adds 6 tests that drive those paths
end-to-end without spawning external processes.

Coverage delta:

  cmd/mcp/client          49.3% → 54.6%
  pkg/mcp                 86.8% → 91.2%

Per-function gains (the ones tied to the fix-doc work):

  cmd/mcp/client/export.go::executeMCPExport            0%  → 84.2%
  pkg/mcp/server.go::Server.Run                         0%  → 100%
  pkg/mcp/client/mcpconfig.go::WriteMCPConfigToTempFile 52% → 57%

Tests added:

* cmd/mcp/client/export_test.go (+4 tests, +167 LOC)
  - TestExecuteMCPExport_NoServersEarlyReturn pins the "no servers
    configured" branch (info notice, return nil, no file written).
  - TestExecuteMCPExport_HappyPath is the end-to-end regression for
    fix-doc issue #1: writes a minimal atmos.yaml with one server,
    calls executeMCPExport, asserts the file is created with valid
    MCPJSONConfig JSON, the server entry survives the round trip,
    and the file mode is 0600.
  - TestExecuteMCPExport_OverwritesExistingFile guards the explicit
    os.Chmod after WriteFile — WriteFile preserves OLD permission
    bits when overwriting, so this test pre-creates a 0644 file and
    asserts the function tightens it to 0600.
  - TestExecuteMCPExport_WriteFailure_NonExistentDir hits the
    os.WriteFile error path by pointing --output at a missing
    directory; verifies the offending path is in the error message.

  Shared helpers (newExportTestCmd, writeMinimalAtmosYAMLForExport)
  factored so the four tests share fixture setup.

* pkg/mcp/client/mcpconfig_test.go (+2 tests, +69 LOC)
  - TestWriteMCPConfigToTempFile_CreateTempFailure exercises the
    os.CreateTemp failure branch by pointing TMPDIR at a missing
    directory; asserts the error wraps errUtils.ErrMCPConfigWriteFailed
    so callers can errors.Is-match the sentinel.
  - TestWriteMCPConfigToTempFile_TempDirHonored confirms the
    cooperative contract with os.TempDir — TMPDIR override is
    respected. Robust to macOS /tmp → /private/tmp symlink quirk via
    filepath.EvalSymlinks on both sides.

  Both tests skip on Windows because TMPDIR override semantics differ.

* pkg/mcp/server_test.go (+1 test, +49 LOC)
  - TestServer_Run_TerminatesOnContextCancel uses the MCP SDK's
    NewInMemoryTransports() so the test can drive Server.Run without
    stdio or HTTP. Asserts Run returns when its context is cancelled
    — the only meaningful contract for a long-running server method.

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

* updates

* chore(deps): bump Go module dependencies to latest minor/patch versions

Ran `go get -u ./...` + `go mod tidy`. Two transitive pins from
existing go.mod comments were intentionally restored after the auto-
upgrade tried to violate them:

* `github.com/invopop/jsonschema` held at v0.13.0 — anthropic-sdk-go
  uses `wk8/go-ordered-map/v2` for `jsonschema.Schema.Properties`;
  v0.14.0 switched the upstream to `pb33f/ordered-map/v2`, breaking
  type compatibility (build error: `cannot use orderedmap.New[...]
  (wk8) as ...(pb33f) value`). Bump after anthropic-sdk-go migrates.
* `gocloud.dev` held at v0.41.0 — gomplate/v3's s3blob code references
  `s3blob.URLOpener.ConfigProvider`, removed in gocloud.dev v0.42+
  (build error: `unknown field ConfigProvider`). Bump when gomplate/v3
  updates or when we migrate gomplate/v3 usages to gomplate/v4.

Notable updates:
* anthropic-sdk-go v1.41.0 → v1.43.0
* terraform-docs v0.23.0 → v0.24.0
* aws-sdk-go-v2/service/s3 v1.100.1 → v1.101.0
* aws-sdk-go-v2/service/securityhub v1.69.2 → v1.70.0
* azblob v1.6.4 → v1.7.0
* k8s.io/client-go v0.36.0 → v0.36.1
* golang.org/x/{term,text,sys,net,tools,mod,exp,crypto} bumps
* google.golang.org/{api,genai,grpc} bumps
* modernc.org/sqlite v1.50.0 → v1.50.1
* open-policy-agent/opa v1.16.1 → v1.16.2

`go build ./...` passes after the rollback of the two pinned deps.

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

* fix(mcp): address 9 issues from MCP implementation review

See docs/fixes/2026-05-15-mcp-review-fixes.md for the full punch list,
root causes, and per-issue test coverage. Headline changes:

* **P1 — `atmos mcp export` now injects toolchain PATH.**
  Delete the cmd-local mcpJSONConfig/mcpJSONServer/buildMCPJSONEntry
  duplicates in cmd/mcp/client/export.go and delegate to
  mcpclient.GenerateMCPConfig with toolchainPATH from a new
  buildToolchainPATH helper. IDE-spawned subprocesses can now find
  toolchain-managed `uvx` / `npx`.

* **P1 — MCP server registers the full Atmos AI tool set.**
  Replace the hand-rolled 7-tool list in
  cmd/mcp/server/start.go::initializeAIComponents with a call to the
  canonical atmosTools.RegisterTools factory (the same one cmd/ai
  uses). Adds describe_affected (docs already advertised it),
  search_files, execute_atmos_command, and the rest of the AI tool
  surface to the MCP server.

* **P2 — `atmos mcp restart` help text disambiguates the validation
  semantics.** Update Short and the embedded long-form markdown to
  spell out that the command validates a stop+start cycle without
  leaving the server running.

* **P2 — Concurrent-safe temp file in WriteMCPConfigToTempFile.**
  Switch to os.CreateTemp with the pattern `atmos-mcp-config-*.json`.
  Each invocation gets a unique path; concurrent writers no longer
  race. Suppress gosec G703 false positives — tmpPath comes from
  os.CreateTemp, no untrusted-input chain.

* **P3 — Defensive copy in Session.Tools().** Returns a slice copy.

* **P3 — Hardened firstSentence helper.** Recognizes `! ` and `? `,
  applies a 80-rune hard ceiling with ellipsis.

* **P3 — `atmos mcp tools` uses the renderer pipeline.** Exposes
  --format / --columns / --sort / --delimiter (same as `mcp list`).

* **P4 — Drop unused ScopedAuthProvider.baseConfig.** Cleanup.

* **P4 — `atmos mcp test` no longer double-prints errors.** Returns
  nil from RunE so main.go's errUtils.Format pipeline is skipped.

Also incidentally regenerates pkg/telemetry/mock/mock_posthog_client.go
to add the EvaluateFlags method the posthog-go SDK added in a recent
release — golangci-lint was blocking on this unrelated pre-existing
issue. Side effect, not a feature change.

Test coverage:

* cmd/mcp/client/export_test.go: TestExport_DelegatesToPackageGenerator
  and TestBuildToolchainPATH_NoToolchainReturnsEmpty.
* cmd/mcp/server/start_test.go: TestInitializeAIComponents_RegistersDescribeAffected
  and TestInitializeAIComponents_RegistersSharedFactoryTools.
* cmd/mcp/client/restart_test.go: TestRestartCmd_HelpMentionsValidationSemantics.
* pkg/mcp/client/mcpconfig_test.go: TestWriteMCPConfigToTempFile_ConcurrentWritesGetDistinctPaths
  drives 16 parallel writers and asserts pairwise-distinct paths plus
  no content cross-talk.
* pkg/mcp/client/session_test.go: TestSession_ToolsReturnsDefensiveCopy.
* cmd/mcp/client/helpers_test.go: TestFirstSentence extended.
* cmd/mcp/client/tools_test.go: TestRenderMCPTools_FormatJSON et al.
* cmd/mcp/client/test_cmd_test.go: TestExecuteMCPTest_ReturnsNilEvenOnFailure.

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

* docs(examples): add mcp-for-ai-coding-assistants + blog post

New example showing how to configure MCP servers (the Atmos MCP server
itself plus the awslabs/mcp AWS suite) ONCE in atmos.yaml, then use the
same toolset from Claude Code, OpenAI Codex CLI, and Google Gemini CLI.
Atmos Auth injects AWS credentials per-server; the Atmos toolchain pins
`uvx` so every AI assistant uses the same binary version.

Example files (examples/mcp-for-ai-coding-assistants/):

* atmos.yaml — toolchain alias (uv → astral-sh/uv), mcp.enabled: true,
  nine MCP servers (atmos + aws-docs, aws-knowledge, aws-pricing,
  aws-billing, aws-iam, aws-cloudtrail, aws-security, aws-api), Atmos
  Auth (aws-sso + readonly identity), and an optional AI block.
* .tool-versions — pins uv to a known version so the toolchain PATH
  injection in the exported .mcp.json gives every AI CLI the same uvx.
* README.md — full workflow plus three CLI-specific subsections
  (Claude Code via `claude mcp add` / .mcp.json, Codex CLI via
  ~/.codex/config.toml, Gemini CLI via .gemini/settings.json or
  `gemini mcp add`). Includes a "What the atmos MCP server does"
  section listing all ~20 tools the embedded server exposes, with the
  "AWS servers = what's deployed / Atmos server = what's defined"
  framing.
* stacks/example.yaml + components/terraform/vpc/ — mock fixtures so the
  Atmos MCP tools have something concrete to report when the AI asks
  about this project.

Blog post (website/blog/2026-05-16-mcp-for-ai-coding-assistants.mdx):

* Tags: feature, dx.
* Walks through the problem (three config files, three auth setups,
  three toolchain stories) and the solution (one atmos.yaml, exported
  per CLI). Includes condensed CLI-specific wiring sections and a
  short overview of what the embedded `atmos` MCP server contributes
  on top of the AWS servers.

Also adds an entry to .gitignore so the example's checked-in
.tool-versions isn't ignored by the global `.tool-versions` pattern
(mirrors the existing carve-out for examples/toolchain/.tool-versions).

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

* docs(examples): add Atmos Pro MCP server to mcp-for-ai-coding-assistants

The Atmos Pro MCP server (https://atmos-pro.com/mcp) complements the
local Atmos + AWS servers with operational history: drift detection,
deployment runs, workflow runs, audit logs, repair recommendations.
Unlike the stdio servers in atmos.yaml, atmos-pro is HTTP-transport
(`https://atmos-pro.com/mcp`) with a browser-based GitHub OAuth flow —
no API keys, tokens stored in the OS keychain.

Because the current MCPServerConfig schema in pkg/schema/mcp.go only
models stdio servers (command/args/env), atmos-pro can't be added to
mcp.servers in atmos.yaml today; it's registered with each AI CLI
directly via `claude mcp add --transport http`, `gemini mcp add
--transport http`, or a TOML/JSON entry in the CLI's config. Both the
README and blog post document this asymmetry up front so users aren't
confused when `atmos mcp export` produces a config without atmos-pro.

README updates (examples/mcp-for-ai-coding-assistants/README.md):

* Servers table grew a "Transport" column and a new atmos-pro row. The
  AWS rows now group under "AWS (via Atmos Auth)" rather than just
  "Yes/No" for clearer auth semantics.
* New "What the `atmos-pro` MCP Server Does" section pulls capability
  bullets directly from the Atmos Pro changelog
  (https://atmos-pro.com/changelog/2026-05-09-mcp-server) — triage,
  workflows/deployments, historical context, security/access.
* Updated mental model from two layers to three:
    AWS = what's deployed
    atmos = what's defined
    atmos-pro = what's happening over time
  With a concrete cross-layer example prompt that pulls from all three.
* New "Atmos Pro server (HTTP transport)" install subsection right after
  the per-CLI sections, with `claude mcp add --transport http`, the TOML
  entry for Codex's `~/.codex/config.toml`, the `gemini mcp add` command,
  and the raw JSON/TOML config blocks for manual merging.
* Example questions expanded with atmos-pro-specific prompts
  ("Which workspaces have drift right now?", "Has this stack been
  flapping?") and a cross-layer prompt.
* Prereqs gained an optional Atmos Pro account/workspace step.
* Learn More links to the Atmos Pro site, install docs, and changelog.

Blog post updates (website/blog/2026-05-16-mcp-for-ai-coding-assistants.mdx):

* Opening hook now mentions atmos-pro alongside atmos and the awslabs
  suite, including the "browser OAuth, no API keys" angle.
* Servers table gained Transport/Auth columns and the atmos-pro row;
  "ten MCP servers" replaces "nine".
* New "The Atmos Pro MCP server" section (sibling to the
  "What the atmos MCP server does" section) covering the four
  capability buckets and the HTTP transport / OAuth flow.
* Mental model updated to the three-layer framing.
* New "Atmos Pro (all three CLIs)" install subsection in the
  wiring-up section.
* "What You Can Ask" gained atmos-pro questions and a cross-layer
  example prompt.
* Related Reading links to atmos-pro.com, the install page, and the
  capability-overview changelog.

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

* docs(examples): add CTA to mcp-for-ai-coding-assistants README and blog

A short, punchy call-to-action right after the intro of both files, to
steer the reader's attention to the three things this setup unlocks:

  Your AI knows your stacks. And your cloud. And your history.

  In one prompt, your AI coding assistant answers:
  - What's configured in your infrastructure
  - What's deployed in your cloud accounts
  - What changed — when, why, how, and by whom

  Centralized auth. Centralized permissions. One atmos.yaml.

Placed at the top of the README (right after the intro) and at the top
of the blog post (right after the lede / <!--truncate--> marker) so it
hooks readers before they decide to bounce. The README version links to
the in-page #one-time-setup section; the blog version links out to the
example directory on GitHub.

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

* docs(examples): expand Related Examples section with mental map

Both the README and blog post now have a sharper "pick the example that
matches your workflow" section covering all three sibling examples, plus
a 2×2 mental map (Atmos-driven vs CLI-driven × API-key vs subscription
AI providers) so readers can self-select quickly.

* examples/mcp/ — same MCP server config, but Atmos drives the loop via
  `atmos ai ask`. The "stay inside atmos CLI" sibling.
* examples/ai-claude-code/ — Claude Pro/Max subscription as Atmos's AI
  provider (no API key); Atmos hosts the conversation.
* examples/ai/ — multi-provider Atmos AI (Anthropic API, OpenAI API,
  Ollama). API-key flow, no external CLI.

The blog post version uses GitHub URLs since blog readers haven't cloned
the repo yet; the README version uses relative paths within the repo.

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

* docs(examples): switch example links to atmos.tools/examples URLs

The blog post previously linked sibling examples via raw
github.com/cloudposse/atmos/tree/main/examples/<name> URLs, and the
README used relative paths (../mcp/, ../ai/, ../ai-claude-code/). Both
now point to the canonical docs URLs at https://atmos.tools/examples/<name>
so readers land on the rendered docs page (with cross-links, search,
TOC) rather than the raw GitHub source tree or a file-system path that
only works inside the repo.

Also adds a one-liner pointing at the full examples index
(https://atmos.tools/examples) so readers can discover other examples
beyond the four mentioned here.

Link labels updated from bare directory paths to human-readable titles
matching the docs page names ("Atmos MCP integrations",
"Atmos AI with Claude Code", "Atmos AI (multi-provider)") — better for
scanning and accessibility.

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

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* updates

* test(mcp): boost coverage for fix-doc regression paths

Per docs/fixes/2026-05-15-mcp-review-fixes.md, three production paths
still had thin coverage after the punch-list shipped — most notably
the refactored `executeMCPExport` and the previously-unreachable
`Server.Run`. This commit adds 6 tests that drive those paths
end-to-end without spawning external processes.

Coverage delta:

  cmd/mcp/client          49.3% → 54.6%
  pkg/mcp                 86.8% → 91.2%

Per-function gains (the ones tied to the fix-doc work):

  cmd/mcp/client/export.go::executeMCPExport            0%  → 84.2%
  pkg/mcp/server.go::Server.Run                         0%  → 100%
  pkg/mcp/client/mcpconfig.go::WriteMCPConfigToTempFile 52% → 57%

Tests added:

* cmd/mcp/client/export_test.go (+4 tests, +167 LOC)
  - TestExecuteMCPExport_NoServersEarlyReturn pins the "no servers
    configured" branch (info notice, return nil, no file written).
  - TestExecuteMCPExport_HappyPath is the end-to-end regression for
    fix-doc issue #1: writes a minimal atmos.yaml with one server,
    calls executeMCPExport, asserts the file is created with valid
    MCPJSONConfig JSON, the server entry survives the round trip,
    and the file mode is 0600.
  - TestExecuteMCPExport_OverwritesExistingFile guards the explicit
    os.Chmod after WriteFile — WriteFile preserves OLD permission
    bits when overwriting, so this test pre-creates a 0644 file and
    asserts the function tightens it to 0600.
  - TestExecuteMCPExport_WriteFailure_NonExistentDir hits the
    os.WriteFile error path by pointing --output at a missing
    directory; verifies the offending path is in the error message.

  Shared helpers (newExportTestCmd, writeMinimalAtmosYAMLForExport)
  factored so the four tests share fixture setup.

* pkg/mcp/client/mcpconfig_test.go (+2 tests, +69 LOC)
  - TestWriteMCPConfigToTempFile_CreateTempFailure exercises the
    os.CreateTemp failure branch by pointing TMPDIR at a missing
    directory; asserts the error wraps errUtils.ErrMCPConfigWriteFailed
    so callers can errors.Is-match the sentinel.
  - TestWriteMCPConfigToTempFile_TempDirHonored confirms the
    cooperative contract with os.TempDir — TMPDIR override is
    respected. Robust to macOS /tmp → /private/tmp symlink quirk via
    filepath.EvalSymlinks on both sides.

  Both tests skip on Windows because TMPDIR override semantics differ.

* pkg/mcp/server_test.go (+1 test, +49 LOC)
  - TestServer_Run_TerminatesOnContextCancel uses the MCP SDK's
    NewInMemoryTransports() so the test can drive Server.Run without
    stdio or HTTP. Asserts Run returns when its context is cancelled
    — the only meaningful contract for a long-running server method.

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

* updates

* updates

* updates

* updates

* updates

* fix(docs): repair broken links in mcp-for-ai-coding-assistants README

Use absolute https://atmos.tools URLs for `/ai/mcp-server`,
`/ai/agent-skills`, and `/changelog/ai-agent-skills` so the markdown
link-checker can resolve them from the example's own README (relative
docs paths only work inside the Docusaurus site, not from a standalone
file).

Update Gemini trusted-folders link to its new path under
`docs/cli/trusted-folders.md` (was 404 at `docs/trusted-folders.md`).

* [autocommit] formatting fixes

* [autocommit] formatting fixes

* fix(mcp): address CodeRabbit review feedback

Major:
- cmd/mcp/client/test_cmd.go: surface `result.Error` in printTestResult so
  users see why a failed start happened, not just that it did. Preserves
  the executeMCPTest "always return nil" contract — printTestResult
  remains the single source of stderr output.
- pkg/mcp/server_test.go: replace `context.Background().Done()` (which
  never fires) with `time.After(2s)` so the Server.Run termination
  test fails fast instead of hanging until the global `go test` timeout.
- cmd/mcp/client/export_test.go: normalize path separators with
  `filepath.ToSlash` in the WriteFailure_NonExistentDir error assertion
  so it passes on Windows where Join uses backslashes.

Minor:
- cmd/mcp/client/tools.go: enforce firstSentenceMaxLen ceiling on every
  return path of firstSentence (terminated sentences and markdown-header
  breaks too). Docstring promised "never exceeds" but only the
  no-terminator path enforced it — a 150-rune sentence ending in `. `
  could leak into the `atmos mcp tools` table. Helper extracted as
  `truncateToMaxLen`. Tests updated accordingly.
- cmd/mcp/client/markdown/atmos_mcp_restart.md: sample output now wraps
  the server name in backticks to match the actual `ui.Successf` format.
- examples/mcp-for-ai-coding-assistants/README.md: change `###` →`##` so
  heading levels increment by one (MD001).
- docs/fixes/2026-05-15-mcp-review-fixes.md: remove trailing spaces from
  inline code spans (MD038) and update Fix description to reflect the
  new "ceiling always applies" contract.

Skipped (3 nitpicks): "use cmd.NewTestKit(t) in cmd/mcp/client tests"
cannot be applied — cmd/mcp/client cannot import cmd (cmd imports
cmd/mcp which imports cmd/mcp/client → circular). Tests also don't
mutate RootCmd state; they read package-local cobra commands or build
fresh ones.

* test(mcp): boost patch coverage to clear Codecov gate

Codecov reported 60.87% patch coverage with the four affected files at
62-31%. This pushes function-level coverage on the changed code up to
>=90% across the patch surface.

New tests in cmd/mcp/client/tools_coverage_test.go:
- TestRenderMCPTools_DirectCallSucceeds: drives the production
  renderMCPTools(r.Render → data.Writer) path rather than the test-only
  RenderToString seam. Takes renderMCPTools from 0% → 91.7%.
- TestRenderMCPTools_InvalidSortSpecReturnsWrappedError: covers the
  sort-parse error wrap path inside renderMCPTools.
- TestExecuteMCPTools_NonexistentServerReturnsError /
  TestExecuteMCPTools_UnknownServerNameReturnsError: exercise the
  mgr.Start error paths. Takes executeMCPTools from 0% → 53.3%.
  Happy-path coverage isn't reachable without a real MCP subprocess.
- TestParseMCPToolsColumnSpec: table-driven coverage of all three
  spec forms (simple name, Name=plain, Name={{ template }}) plus the
  `=`-at-position-0 edge case → 88.9% → 100%.
- TestParseMCPToolsColumnsFlag_FiltersEmptyAndNamelessEntries: covers
  the empty-entry skip branch → 87.5% → 100%.
- TestMCPToolsContainsTemplate: 7-case table covering all branches
  (double-brace, single brace, no braces, empty, short inputs) →
  75% → 100%.
- TestBuildMCPToolsSorters_CustomSortSpec /
  TestBuildMCPToolsSorters_InvalidSpecReturnsError: covers the
  non-default branch and the error-return contract → 66.7% → 100%.

New tests in cmd/mcp/client/start_options_toolchain_test.go:
- TestResolveToolchainEnvironment_LoadsFromToolVersions: writes a
  `.tool-versions` file so resolveToolchainEnvironment takes the
  `len(deps) > 0 → NewEnvironmentFromDeps` branch rather than only
  the terraform-component fallback. Pushes coverage on the deps>0
  short-circuit.
- TestBuildToolchainOption_WithToolVersionsReturnsOption: composition
  guard for the matching opt-emit case.
- TestBuildStartOptions_WithAuthIncludesAuthOption: composition guard
  for the auth-only path through buildStartOptions.

Updated test in cmd/mcp/client/test_cmd_test.go:
- TestPrintTestResult_SurfacesUnderlyingError: covers the new
  `result.Error != nil` branch added in the previous commit (the
  ui.Errorf("Error: %v", result.Error) line that surfaces the
  underlying failure to the user).

Remaining coverage gaps and why they're not pursued:
- WriteMCPConfigToTempFile is at 57.1% — the Chmod/Write/Close error
  wraps require file-system mocking or refactoring the function to
  inject the writer; not in scope here. Existing tests cover all
  meaningful flow paths (MarshalIndent ok/fail, CreateTemp ok/fail,
  full happy path, TMPDIR contract, concurrent invocations).
- executeMCPServer default-case in the transport switch is unreachable
  because getTransportConfig validates first.
- BindToViper panic paths are defensive and only fire if the
  StandardParser surface is misconfigured at init time.

* test(mcp): strengthen coverage-test assertions per CodeRabbit review

CodeRabbit flagged four tests as "coverage theater" — passing assertions
that don't actually pin behavior. Each is replaced with a behavioral
assertion that would catch a real regression.

cmd/mcp/client/test_cmd_test.go::TestPrintTestResult_SurfacesUnderlyingError:
- Before: assert.NotPanics — would still pass if the new
  `ui.Errorf("Error: %v", result.Error)` line was deleted.
- After: wires ui.* to an in-memory iolib.Streams via the new
  setupCapturedUI helper, then asserts the captured stderr contains
  both the failure message ("connection refused on /tmp/mcp.sock")
  and the "Error:" prefix the contract requires.

Added negative-path partner:
TestPrintTestResult_OmitsErrorPrefixWhenSuccessful — verifies the
"Error:" line is absent when result.Error is nil. Without this,
a future "always print Error: <nil>" regression would still pass.

cmd/mcp/client/tools_coverage_test.go::TestBuildMCPToolsSorters_CustomSortSpec:
- Before: require.NotEmpty — would still pass if the parser silently
  ignored the column name and direction.
- After: applies the parsed sorter to a 3-row sample and pins the
  resulting order (carrot first, apple last for descending sort on
  the Description column). A direction/column-parse regression would
  reorder the rows the other way.

cmd/mcp/client/start_options_toolchain_test.go::TestResolveToolchainEnvironment_LoadsFromToolVersions:
- Before: `_ = got` — passed regardless of return value.
- After: asserts the returned env is non-nil and that Resolve()
  returns a non-empty path for "terraform". This proves the deps>0
  branch produced a usable environment, not a half-built one. The
  Resolve contract is broad enough (toolchain path / system PATH /
  original name) to work cross-platform without machine-specific
  install assumptions.

cmd/mcp/client/start_options_toolchain_test.go::TestBuildStartOptions_WithAuthIncludesAuthOption:
- Before: assert.GreaterOrEqual(len(got), 1) — could pass with a
  toolchain option alone, never proving the auth option was added.
- After: computes a baseline count by building options for the SAME
  config but with no identity, then asserts the with-auth count is
  exactly baseline+1. Only the auth-only delta can satisfy this.

* test(mcp): address remaining CodeRabbit nitpicks

- Document the cmd.NewTestKit(t) circular-import constraint on
  initMCPToolsTestIO so future readers don't re-ask the question:
  cmd → cmd/mcp → cmd/mcp/client, so cmd/mcp/client cannot import cmd.
  Same workaround documented in cmd/auth/helpers_test.go.

- Replace `command: "echo"` with `"placeholder-never-executed"` in the
  two new test fixtures that don't spawn the command. The flagged tests
  exit upstream of mgr.Start's binary resolution (unknown-server
  lookup, option-builder composition), so the string is data-only —
  using a real binary couples the test to platform behavior we never
  exercise.

* test(mcp): strip ANSI escapes before asserting captured stderr

CI failed on TestPrintTestResult_SurfacesUnderlyingError because the
UI formatter wraps styled text in TrueColor ANSI escape sequences,
which can split a single logical message across multiple escape
blocks:

    "...Error: connection refused on\x1b[0m\x1b[97m /tmp/mcp.sock\x1b[0m"

The naive substring search for "connection refused on /tmp/mcp.sock"
misses because of the `\x1b[0m\x1b[97m` in the middle. Locally
(without forced color) the formatter emits a contiguous string and
the test passes; on CI (Linux + Windows runners, TrueColor on) the
split breaks it.

Fix: add a stripANSI helper that drops CSI sequences via the
`\x1b\[[0-9;]*m` regex, and run captured stderr through it before
asserting. Verified the fix locally with
ATMOS_FORCE_COLOR=true ATMOS_FORCE_TTY=true.

* updates

* updates

* updates

* docs(mcp-example): fix README atmos.yaml scope claims + blog anchor

README — Comment from CodeRabbit (valid):
- "every MCP server is defined in atmos.yaml" was wrong because the
  table includes atmos-pro, which is an HTTP-transport server and not
  representable in atmos.yaml's stdio-only MCPServerConfig today. Now
  reads "every stdio MCP server" and explains the asymmetry inline.
- "Each external MCP server is spawned by `atmos auth exec`" was wrong
  for aws-docs and aws-knowledge, which have no `identity` (public
  endpoints). Now reads "Each server with an `identity`" and names
  the two exceptions explicitly.
- atmos-pro row Auth column updated to make the "registered separately,
  HTTP" detail visible at table-glance rather than only in prose. Realigned
  table separator/widths to fit the longer Auth value.

Blog — Comment from CodeRabbit (valid):
- Anchor `#option-2--openai-codex-cli` doesn't match any heading in the
  example README (the heading is `### OpenAI Codex CLI` → slug
  `openai-codex-cli`). Updated the link target to match.

Skipped (CodeRabbit suggestion not adopted):
- Pinning `awslabs.<name>@latest` to specific versions. The @latest
  convention is consistent across all other Atmos MCP examples, all
  MCP docs (configuration/mcp/index.mdx, commands/mcp/{export,list}.mdx),
  the PRD, test fixtures, and the prior MCP blog post — and matches
  upstream awslabs' own canonical install instructions. Diverging here
  would create inconsistency, and the suggested `<pinned-version>`
  placeholder is itself non-functional.

* updates

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: atmos-pro[bot] <173522224+atmos-pro[bot]@users.noreply.github.com>
Andriy Knysh (aknysh) added a commit that referenced this pull request May 25, 2026
* feat: implement remote stack imports

Add support for importing stack configurations from remote URLs using go-getter.
Stack imports now work consistently with remote atmos.yaml imports.

## What Changed

- New pkg/stack/imports package with URL detection and remote downloading
- Stack imports detect remote URLs (HTTP, Git, S3, GCS) and download via go-getter
- Integration with stack_processor_utils.go for unified import handling
- New sentinel errors for remote import failures
- Comprehensive unit tests with mock HTTP server
- Integration tests verifying end-to-end functionality
- Complete example demonstrating local and remote imports
- Blog post announcing the feature and roadmap update

## Architecture

- pkg/stack/imports/uri.go: URL detection functions (IsLocalPath, IsGitURI, IsHTTPURI, IsS3URI, IsGCSURI)
- pkg/stack/imports/remote.go: Remote downloading with caching
- pkg/stack/imports/imports.go: Main ProcessImportPath entry point
- stack_processor_utils.go: Updated to use remote import logic

## Testing

All 60+ unit tests pass:
- URL detection for local vs remote paths
- Remote imports from mock HTTP server
- Graceful handling of missing remotes with skip_if_missing
- End-to-end integration tests

Closes #2036

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

* refactor: extract generic cache infrastructure into pkg/cache

Extract the robust file-based caching infrastructure from pkg/config into
a reusable pkg/cache package. This includes:

- pkg/cache/filelock.go: Platform-agnostic FileLock interface
- pkg/cache/filelock_unix.go: Unix flock implementation with retries
- pkg/cache/filelock_windows.go: Windows graceful degradation
- pkg/cache/file_cache.go: Generic FileCache with atomic writes and locking

Update pkg/config/cache.go to use the new pkg/cache.FileLock interface.

Update pkg/stack/imports/remote.go to properly use FileCache.GetOrFetch()
for thread-safe caching with atomic writes, instead of bypassing the
cache's locking mechanism.

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

* fix: address PR feedback for remote stack imports

- Fix isDomainLikeURI incorrectly flagging version paths (e.g., configs/v1.0/base)
- Preserve file extension in cached filenames for proper template processing
- Use errors.Is() for sentinel error assertions in tests
- Use httptest mock server for skip_if_missing test instead of real network
- Add PR 2037 link to roadmap milestone
- Clarify go-getter URL format coverage in blog post

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

* chore: ignore kubernetes.io and runatlantis.io in link checker

These sites block automated requests but URLs are manually verified as valid:
- https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/
- https://www.runatlantis.io/docs/pre-workflow-hooks.html

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

* fix: address PR review comments for remote imports

- Add periods to example comments in uri.go for godot lint compliance
- Use errors.Is() with sentinel error in TestRemoteImporter_Download_NotFound
- Change assert.Error to require.Error for proper test flow

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

* fix: ensure cache directory exists after options applied

When WithBaseDir is used to specify a custom cache path, the directory
might not exist. This adds directory creation after options are applied
to handle custom paths correctly.

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

* fix: ignore cache read errors on Windows

On Windows, file locking is a no-op for graceful degradation. Cache read
errors from corrupted files should also be silently ignored so they don't
block normal operation.

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

* test: improve coverage for cache and stack imports packages

Add comprehensive tests to reach 80%+ coverage threshold:
- pkg/stack/imports: Test ResolveImportPaths function (35% → 86%)
- pkg/cache: Add filelock_unix tests and file_cache edge cases (64% → 86%)
- pkg/config: Test cache edge cases (64% → 87%)
- internal/exec: Test ProcessImportSection edge cases (79% → 80%)

Fix bugs discovered during testing:
- file_cache.go: Create lock after options applied so WithBaseDir works
- cache.go: Return empty CacheConfig consistently on Windows read errors

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

* fix: handle deleted cache directory in Clear() method

Add early return in Clear() when the cache directory doesn't exist,
avoiding lock acquisition errors when the directory was deleted
externally.

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

* fix: address CodeRabbit review comments

- Use filepath.Join for OS-safe test paths (Comments #1, #6)
- Route FileCache operations through injected FileSystem interface (Comment #2)
- Add ErrCacheFetch sentinel and wrap fetch() errors (Comment #3)
- Fix misleading "log" comment in GetOrFetch (Comment #4)
- Add missing BrowserSessionWarningShown assertion (Comment #5)

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

* fix: persist BrowserSessionWarningShown in cache

Add missing browser_session_warning_shown field to SaveCache and
UpdateCache data maps so the field is properly persisted to disk.

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

* fix: preserve lock file during cache Clear() and improve test coverage

Fix a bug where FileCache.Clear() would delete the lock file (cache.lock)
while walking the cache directory, breaking mutual exclusion for concurrent
processes. Add lockFilePath field to FileCache and skip it during Clear().

Improve test coverage across cache, imports, and config packages:
- pkg/cache: 72%/70% -> 91.7% (lock error paths, retry exhaustion, fallback)
- pkg/stack/imports: 85%/89% -> 95.7% (memory cache invalidation, URI helpers)
- pkg/config: 72% -> 86.8% (corrupted file handling, docstring for CacheConfig)

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

* fix: data race on downloadCount and improve test coverage

Use atomic.Int32 for downloadCount in TestRemoteImporter_Download_MemoryCacheInvalidation
to fix race between httptest handler goroutine and test goroutine.

Add test coverage for error paths:
- FileCache.Get() with non-NotExist read errors
- FileCache.Set() with write errors on read-only directory
- FileCache.Clear() with file removal errors
- IsGitURI() with malformed URL containing invalid escape sequence

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

* fix: clarify ignored cache write errors

* chore: retrigger ci

* fix: stabilize vendor acceptance test

* fix: harden import and cache path handling

* fix: preserve template cache extensions

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Andriy Knysh <[email protected]>
Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jun 18, 2026
…reate errors

Three fixes to the `type: container` step path, surfaced by running
`atmos container build-run` against examples/container-step:

1. credentialFileMounts bind-mounted every absolute-path value in the step env.
   Because the custom-command path hands the step the entire host environment,
   it mounted SHELL=/bin/zsh (absent in the runtime VM) and SSH_AUTH_SOCK (a
   unix socket podman cannot statfs), so `podman create` failed with
   "statfs … operation not supported". Restrict to an allowlist of credential
   env keys and only mount existing regular files (skip dirs/sockets/devices).

2. The container build was silent (runtime.Build swallows output on success).
   Wrap it in spinner.ExecWithSpinner like the devcontainer build path, so the
   build shows a spinner and a ✓ "Built image <tag>" line (degrades off-TTY).

3. createEphemeralContainer pulled-and-retried on ANY create failure, masking
   the real cause behind a misleading "pull localhost/<image>" error. Only
   retry when the create error actually indicates a missing image.

Adds the missing unit coverage that let #1 through: credentialFileMounts was
untested, and the build-config test fed a curated 2-var env instead of a
realistic full host environment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Andriy Knysh (aknysh) pushed a commit that referenced this pull request Jun 23, 2026
* feat: native container steps for workflows and custom commands

Add a native `type: container` step (build/push/run) to the shared step
library used by workflows and custom commands, plus a formal step-outputs
contract so one step can build an image and later steps push/run the exact
produced artifact. Built on the existing pkg/container Docker/Podman runtime
(ephemeral one-shot runner, image build/tag/push/inspect helpers) with
per-step identity for registry auth and Docker Buildx Bake support.

Includes the examples/container-step example, a hermetic GitHub Actions job
that exercises build -> push -> run against a registry:2 service on
localhost:5000 (plus failure-propagation), workflow step-type docs, a
changelog blog post, and a roadmap update marking container steps and step
outputs shipped.

Also lands the design PRDs for the follow-on primitives (container
components, compose components, and membership-based compositions) and trims
the container-step PRD to cover only the procedural step. The earlier
targets-based composition scaffolding is removed in favor of those PRDs.

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

* docs: fix dead core-concepts links in compositions PRD

lychee resolves /core-concepts/* as repo-relative file paths, which do not
exist; use plain text in the PRD intro instead of website-route links.

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

* fix(container): parse container ID from last line of docker create output

DockerRuntime.Create() returned the full CombinedOutput of `docker create`
as the container ID. When the image was missing locally, `docker create`
pulled it inline and the pull progress was captured alongside the ID, so the
multi-line blob was passed to `docker start`, producing
"Error response from daemon: page not found" (the container-step example job).

Extract the container ID as the last non-empty line of output via a shared
extractContainerID() helper, used by both the Docker and Podman runtimes
(de-duplicating Podman's inline loop). Add an empty-ID guard and a regression
test covering the exact inline-pull output from CI.

Also bundles related container refinements already in the worktree: runtime
resolution/recovery ordering in detector.go, error wrapping and
cancellation-safe cleanup in ephemeral.go, and PRD doc link fixes.

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

* feat(container): inject runtime env into container CLI subprocesses

Adds an EnvSetter seam so container runtimes (Docker/Podman) run their CLI
subprocesses with a materialized environment (e.g. DOCKER_CONFIG for ECR
login) instead of always inheriting os.Environ(). Wires the env through the
runner container steps (build/push/run) and updates the container-step
example, step-type docs, and the native-container-steps blog post.

Includes new env_test.go and container_env_test.go coverage.

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

* ci: run linux acceptance tests on the `large` runner to avoid OOM

The linux Acceptance Tests job runs `make testacc-cover` with
`-coverpkg=./...` across the whole repo, which is memory-heavy. It ran on the
`terraform` runner whose RunsOn config has an 8 GiB RAM floor (`ram: [8, 64]`),
so spot instances as small as 8 GiB were provisioned. The coverage build was
killed (exit 137, "runner received a shutdown signal") at the coverage step on
consecutive runs — every test package passed; only the coverage collection OOMed.

Switch the linux matrix entry to `runner=large` (`ram: [16, 128]`, `disk: large`),
the same runner the `release` job already uses. macos/windows run plain
`testacc` (no coverage instrumentation) and are unaffected.

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

* refactor(container): combine create+pull errors with errors.Join

createEphemeralContainer used a single fmt.Errorf with two %w verbs to wrap the
create and pull errors. Per the project error-handling guidelines, combine
multiple error causes with errors.Join: wrap each cause with its context label
and join them under the outer message. Preserves both error chains for errors.Is.

Addresses CodeRabbit review on PR #2626.

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

* Revert "ci: run linux acceptance tests on the `large` runner to avoid OOM"

This reverts commit b13f9e9.

* fix(commands): stop routing shell/atmos custom-command steps through step handlers

Custom-command step dispatch had a broad pre-check that sent every *registered*
step type (except `exec`) — including `shell` and `atmos` — through the new
pkg/runner/step handlers, making the legacy switch cases dead code. That
regressed two ways:

- Windows: the shell handler hardcodes `exec.Command("sh", "-c", ...)`, so
  shell-based custom commands (greet/echo/deploy/show) failed with
  `exit status 126`, breaking their golden snapshots.
- Linux: the handler path spawned `atmos` grandchildren without process-group
  cleanup, leaking orphaned `atmos` processes (32 in one acceptance run vs 0 on
  main). Accumulated coverage-instrumented `atmos` processes exhausted memory and
  the on-demand runner was torn down (exit 137 / "runner received a shutdown
  signal") — which looked like an OOM/spot flake but was a process leak.

Gate on stepPkg.IsExtendedStepType instead (matching internal/exec/workflow_utils.go
and pkg/workflow/executor.go): shell/atmos/exec keep the legacy, cross-platform,
child-reaping paths; only genuinely-extended types (container, input, …) route
through the registered handlers via the default case, which now also carries the
resolved step env. Removes the now-dead runRegisteredStepHandler helper.

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

* Add container workflow sandbox

* fix(workflow): normalize rel path in container workspace-escape guard

filepath.Rel returns OS-native separators, so the "../" prefix check in
mapHostWorkDirToContainer missed escapes on Windows (..\tmp\outside),
letting out-of-workspace working_directory values through. Normalize with
filepath.ToSlash before the guard so it is separator-agnostic.

Fixes the failing Windows acceptance test
TestWorkflowSandboxExecShellRejectsWorkingDirectoryOutsideWorkspace.

Also resolve pre-existing golangci-lint findings in the container-sandbox
code surfaced by the --new-from-rev gate:
- schema: wrap the dynamic container-decode error with a static sentinel
  (ErrInvalidWorkflowContainer) for err113.
- container: pass SandboxConfig by pointer (hugeParam), name the
  sandbox-name length constant, add perf.Track to Sandbox.ID/Name.
- workflow: introduce SandboxParams to keep StartWorkflowSandbox,
  RunStepContainerOverride and ExecShell within the argument limit;
  split mergeWorkflowContainer and extract Execute/runCommand helpers to
  satisfy cyclomatic/function-length; use homedir.Dir over os.UserHomeDir;
  name the "." constant; convert the shell-dispatch if-else to a switch.

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

* refactor(workflow): rename container sandbox file and symbols to container/session

The workflow-level container feature is driven by the `container:` block on
workflows/steps; "sandbox" leaked in from the lower pkg/container runtime
primitive and read as an implementation detail at this layer. Rename the file
and the workflow-package symbols to match the feature name.

- pkg/workflow/container_sandbox.go -> container.go (+ _test.go)
- WorkflowSandbox -> ContainerSession
- SandboxParams -> ContainerStepParams
- StartWorkflowSandbox -> StartWorkflowContainer
- internal helpers/fields: sandboxContainer -> containerBackend,
  buildSandboxConfig -> buildContainerConfig, ensureWorkflowSandbox /
  cleanupWorkflowSandbox -> ...Container, ContainerSession.sandbox ->
  .backend, Executor.sandbox -> .containerSession.

The shared pkg/container layer (container.Sandbox, StartSandbox,
NewWorkflowSandboxConfig, SandboxConfig, SandboxLabel*, SandboxTypeWorkflow)
is left unchanged - it is the correct runtime primitive there. No behavior
change.

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

* fix(container): make workflow sandbox teardown immediate

The long-lived workflow sandbox (and step-override ephemeral containers) run
`/bin/sh -c "sleep infinity"` as PID 1. The kernel applies no default signal
disposition to PID 1, so SIGTERM is ignored — `docker stop`/`podman rm -f`
then block for the full 10s stop grace period before sending SIGKILL, adding
~10s to every workflow that uses a container.

Set `--stop-signal=SIGKILL` at create time for these keep-alive containers
(scoped to OverrideCommand). SIGKILL cannot be caught or ignored, even by
PID 1, so stop/rm -f are immediate on both docker and podman. Also drop the
now-redundant graceful Stop from Sandbox.Cleanup, aligning it with the
ephemeral path which already only force-removes.

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

* fix(container): scope credential mounts, add build spinner, clarify create errors

Three fixes to the `type: container` step path, surfaced by running
`atmos container build-run` against examples/container-step:

1. credentialFileMounts bind-mounted every absolute-path value in the step env.
   Because the custom-command path hands the step the entire host environment,
   it mounted SHELL=/bin/zsh (absent in the runtime VM) and SSH_AUTH_SOCK (a
   unix socket podman cannot statfs), so `podman create` failed with
   "statfs … operation not supported". Restrict to an allowlist of credential
   env keys and only mount existing regular files (skip dirs/sockets/devices).

2. The container build was silent (runtime.Build swallows output on success).
   Wrap it in spinner.ExecWithSpinner like the devcontainer build path, so the
   build shows a spinner and a ✓ "Built image <tag>" line (degrades off-TTY).

3. createEphemeralContainer pulled-and-retried on ANY create failure, masking
   the real cause behind a misleading "pull localhost/<image>" error. Only
   retry when the create error actually indicates a missing image.

Adds the missing unit coverage that let #1 through: credentialFileMounts was
untested, and the build-config test fed a curated 2-var env instead of a
realistic full host environment.

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

* feat(container): add `inspect` step action and rename example command

Add a `type: container, action: inspect` step that renders curated image
metadata (ID, digest, tags, created, size, platform, layers, notable OCI
labels) as a themed table — not a raw JSON dump. Enrich the runtime ImageInfo
and inspect parser with size/created/architecture/os/labels/layers, available
from the existing `image inspect --format {{json .}}` output.

Also polish the example for newcomers:
- Rename the `container` custom command to `example` so it's clear these are
  user-defined custom commands, not a built-in `atmos container` subcommand.
- The `example build-run` flow now builds, inspects (shows metadata), then runs.

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

* fix(config): preserve case of nested step-level env keys

Viper lowercases all YAML map keys, so a custom-command step's `env:` block
(e.g. `EXAMPLE_MESSAGE`) reached the step as `example_message` — a container
step's `echo "$EXAMPLE_MESSAGE"` then found nothing. The existing case-sensitive
env support (pkg/config/casemap) only collected the top-level `env:` keys.

Collect env-var key casing recursively from every `env:` mapping at any depth
(top-level, custom-command, and step-level) into the shared "env" case map, and
apply it to a custom-command step's declared env before merging it over the
command/process env. Command-level `env:` written as a {key,value} list is
already case-preserved by Viper and is intentionally left untouched.

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

* fix(container): address PR review feedback

CodeRabbit review on #2626:

- sandbox: gate the create→pull-retry on image-missing errors only
  (createSandboxContainer), matching the ephemeral path, so a non-image
  create failure (e.g. a bad mount) surfaces as-is instead of being masked
  by a misleading pull error. Join create+pull errors when both fail.
- workflow/container: add perf.Track to the public StartWorkflowContainer,
  ContainerSession.ExecShell, and RunStepContainerOverride entry points;
  guard params.WorkflowDef/params.Step before dereferencing them; extract
  resolveStepHostWorkspace to keep RunStepContainerOverride under the
  cyclomatic limit.
- schema: wrap the WorkflowContainer mapping-decode error with
  ErrInvalidWorkflowContainer so errors.Is works across all input forms.
- tests: correct the mismatched doc comment on TestIsImageMissingError and
  restore it on TestRunEphemeralContainer_PullMissingNonImageErrorDoesNotPull;
  add createSandboxContainer pull-gating coverage.
- docs: document container.shell, container.user, and container.run_args in
  the workflows parameter reference.

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

* test(container): raise patch coverage on the container-step paths

Codecov flagged the PR patch coverage at 59% (below the 80% gate), driven by
under-tested new code. Add focused unit tests for the testable logic (no
container runtime required):

- pkg/workflow/container.go (25.7% -> ~93%): config build + validation, the
  scalar/collection/toggle merge, host-workdir mapping incl. the
  workspace-escape guard, mount/port/env conversion, env-slice merge, home
  expansion, runtime/pull/cleanup validators, dry-run StartWorkflowContainer
  and RunStepContainerOverride, ExecShell nil guards + dry-run, and the
  executor's cleanup/ensure/runShellStep container helpers.
- pkg/container/sandbox.go (57% -> ~84%): NewWorkflowSandboxConfig,
  normalizeSandboxConfig, buildSandboxCreateConfig, matchesSandboxLabels,
  isContainerRunning, sanitizeSandboxName, Sandbox ID/Name/Exec.
- pkg/runner/step/output_mode.go (17% -> ~92%): the new ExecuteWithIO family
  across every mode + error propagation.
- pkg/runner/step container handlers: buildSpinnerMessage, validateBuildAction,
  resolveBuildBake, validateInspectAction, executeInspect dry-run, and the
  effective-step/resolve helpers.

Tests only; no production code changes.

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

* test(container): cover dry-run actions and executor container branches

Second coverage pass on the container-step paths, targeting the remaining
unit-testable lines Codecov flagged:

- step handlers: the dry-run branches of executeRun/executeBuild/executePush
  (which build their config and render a preview without a runtime), plus
  validatePushAction, effectivePushStep, metadataString, containerStepName,
  expandHostPath, resolveRunCommand, and writeOutput.
- pkg/workflow/executor.go (51% -> ~90%): the runShellStep step-override and
  workflow-container branches (both via dry-run / a cached dry-run session) and
  envSliceToMap.
- pkg/container: buildImageInspectArgs.

The still-uncovered lines are integration-only: the docker/podman runtime
methods that shell out to the real CLI (no injection seam), and the
custom-command / workflow execution loops. Those are exercised by the
container-step acceptance job, not unit tests. Tests only.

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

* test(container): end inline test comments with periods (godot)

CodeRabbit flagged inline trailing comments missing a terminal period per the
repo's godot guideline (godot's default `declarations` scope doesn't catch
inline comments, so local lint stayed green). Add the missing periods across the
container-step test files. Comments only — no code changes.

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

* feat(container): top-level container.runtime namespace + auto-start flag

Introduce the top-level `container:` config namespace (forward-compatible with the
upcoming container component kind / `atmos container` command) and standardize the
docker/podman selector on Atmos's pluggable-system vocabulary, `provider`:

```yaml
container:
  runtime:
    provider: podman      # docker | podman (default: auto-detect)
    auto_start: true      # auto-init/start the Podman machine when none is running
```

- schema: add `ContainerConfig`/`ContainerRuntimeConfig` and the top-level
  `Container` field; rename the per-step docker/podman selector `runtime:` →
  `provider:` across ContainerBuild/Push/Run/InspectStep, WorkflowContainer, and
  WorkflowStep/Task (the buildx `engine:` field is unrelated and unchanged).
- config: bridge `container.runtime.auto_start` → the
  ATMOS_CONTAINER_RUNTIME_AUTO_START env var via PromoteAtmosEnv (env wins over
  config), so the global default reaches the runtime detector which has no
  atmosConfig.
- container: DetectRuntimeWithPreferenceAndRecovery now ORs in the env flag, so a
  stopped Podman machine is auto-started for every action and the workflow sandbox
  without per-step config. Fixes `atmos example build-run` failing with
  "neither docker nor podman is available" when the machine is stopped.
- example: enable `container.runtime.auto_start` so the demo works out of the box.
- docs/schema: document the namespace + env override; add the JSON config schema
  entry; rename the `runtime` step param to `provider`.

Adds schema-decode, config-bridge (incl. env-precedence), and detector
auto-start (executor-mocked) tests.

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

* refactor(container): render inspect metadata as a borderless key/value list

The inspect output used a Markdown table; glamour padded the "Property" column
to a fixed, absurdly wide size. Replace it with a theme-aware, borderless
two-column layout: bold keys, no header row, and a column width driven by the
longest present key so values align tightly to the content.

- renderImageInspect builds the styled string (theme styles, graceful no-color
  degradation) and the caller prints it via ui.Writeln instead of ui.Markdown.
- Extract collectInspectRows so renderImageInspect stays under the cyclomatic
  limit.
- Tests strip ANSI and assert on plain content.

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

* fix(container): restore Markdown heading title for image inspect

The flat `Image: <name>` title rendered all-blue (the same Label/Title style as
the body keys), so it had no visual hierarchy. Restore the previous Markdown
heading (`## Image <name>` → bold heading + the image name as cyan inline code)
for the title, while keeping the new borderless bold-key/value body.

renderImageInspect now renders only the body; executeInspect prints the heading
via ui.Markdown and the body via ui.Writeln.

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

* style(container): left-margin the inspect body to align under the heading

The key/value body rendered flush-left while the Markdown heading is indented,
so they didn't line up. Indent the body block with a lipgloss MarginLeft(2)
(idiomatic left margin) so it aligns under the heading.

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

* style(container): bottom margin + strip lipgloss padding on inspect table

Add a one-line bottom margin under the inspect table to separate it from the
following step output, and strip lipgloss's uniform-block right-padding with the
shared ANSI-aware per-line trimmer (ansi.TrimLinesRight) so rows carry no
trailing whitespace.

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

* test(container): regenerate describe-config snapshots for container.runtime

The new top-level `container:` namespace surfaces a `container.runtime` block in
`atmos describe config` output. Regenerate the two affected golden snapshots
(via -regenerate-snapshots) so the Acceptance Tests match.

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

* test: raise container coverage

* test: share fake container runtime helper

* docs: reorganize workflow docs sidebar

* docs(workflows): standardize step Intros, document container nested fields, fix dev-server OOM

Website/docs:
- Reorder reference sidebar so Workflows sits between Vendor and How-To Guides.
- Add the <Intro> component to every workflow step reference page: the parent
  `type` page, all 27 `type/*` step-type pages, and the remaining
  workflow-level and step-level field pages. Step-type intros lead with the
  value: each type exposes an Atmos CLI primitive (interactive prompts,
  spinner, tables, themed output, command/container execution, structured
  logging) so users can build their own custom commands and workflows.
- Workflow-level `container` field page: example now uses every field, plus
  dedicated Mounts, Ports, and Per-step overrides sections with concrete
  nested YAML and accurate merge-vs-replace semantics.
- `type: container` step page: per-action Build (+ Bake), Push, Run
  (+ Mounts/Ports), and Inspect sections with full nested YAML and sub-field
  definitions, verified against pkg/schema/workflow.go and pkg/workflow.

Tooling:
- Add website/.npmrc raising Node's heap ceiling (node-options=
  --max-old-space-size=8192) to stop the Docusaurus dev server and build from
  running out of memory on this large site.

Verified with `pnpm build` (exit 0; no new broken links or anchors).

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

* docs(commands): split Custom Commands page into per-key subpages

The 1,284-line `cli/configuration/commands.mdx` is replaced by a browsable tree
mirroring the workflows docs, so each command key has its own reference page and
the shared-step-types relationship with workflows is obvious.

- New `cli/configuration/commands/` tree (autogenerated under CLI Configuration via
  `_category_.json`): index (the `commands` array) → `command/` object → per-key
  pages: arguments, flags, env, steps, component, dependencies, working_directory,
  identity, and nested commands. Index slug `/cli/configuration/commands` preserved.
- The `steps` page leads with "commands run the same step engine as workflows" and
  links to the shared `/workflows/steps` + `/workflows/steps/type` reference (reusing
  the `<StepTypes/>` partial) instead of duplicating the 27 step-type pages —
  confirmed in source: command `Tasks` dispatch through the same `pkg/runner/step`
  registry as workflow steps.
- Repoint all inbound anchor links that moved to subpages, across docs, blog posts,
  `roadmap.js`, the file-browser plugin (custom-components example sidebar), and two
  user-facing doc URLs in `cmd/cmd_utils.go`.

Verified with `pnpm build` (exit 0) and `go build ./cmd/...`; no new broken links or
anchors (the only remaining warning is the pre-existing /changelog page).

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

* docs(commands): fix two carried-over inaccuracies flagged in review

- arguments: drop `required: true` from the `name` example that sets
  `default: John Doe` (a defaulted argument is optional; the prose already
  says it falls back when omitted).
- identity: separate the temporary credential-file vars
  (AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE) from the profile selector
  (AWS_PROFILE), which is not a file path.

Both were carried over verbatim from the original commands page. Verified with
`pnpm build` (exit 0; no new broken links/anchors).

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

* ci(link-check): exclude no-color.org (unreachable from CI runners)

The "Check Markdown Links" job failed with a network connection error to
https://no-color.org/ (referenced from docs/prd/help-system-architecture.md and
docs/prd/io-handling-strategy.md). The URL is the canonical NO_COLOR spec site
and resolves in a real browser; it just intermittently refuses connections from
CI runners. Add it to the lychee exclude list, consistent with the existing
entries for gnu.org, tldp.org, kubernetes.io, nx.dev, and other valid-but-flaky
external links.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants