Skip to content

fix(config): resolve atmos.yaml imports relative to config dir - #2772

Merged
Andriy Knysh (aknysh) merged 11 commits into
cloudposse:mainfrom
sgtoj:fix/config-imports-relative-to-config-dir
Jul 21, 2026
Merged

Andriy Knysh (aknysh) merged 11 commits into
cloudposse:mainfrom
sgtoj:fix/config-imports-relative-to-config-dir

Conversation

@sgtoj

@sgtoj Brian Ojeda (sgtoj) commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

what

  • Top-level import: entries in atmos.yaml now resolve relative to the directory containing that atmos.yaml, not the current working directory. Running a command from a subdirectory no longer breaks imports like import: [".atmos/commands/**/*"].
  • Anchoring is scoped to config-sourced empty and dot-relative base paths ("", ., ./, .., ../…). Bare paths (foo), absolute paths, !cwd, and runtime overrides (ATMOS_BASE_PATH, --base-path, the atmos_base_path provider parameter) keep their existing resolution semantics.
  • Base-path provenance is tracked across multiple --config files and through imported declarations, so a later --config file's imports anchor to the file that actually declared the effective base_path.
  • Nested imports (local and go-getter adapters) resolve a declared relative base_path against the importing file's directory via a shared helper.

why

  • mergeImports resolved the import base path with filepath.Abs(base_path), which anchors to the current working directory. With the common empty or dot-relative base_path (e.g. .), running atmos from a nested directory resolved import: globs against the subdirectory and failed to find them — for example, atmos.yaml at /repo/acme with import: [".atmos/commands/**/*"], invoked from /repo/acme/somepath, looked for .atmos/commands under somepath.
  • Imports should anchor to the atmos root (the directory of the discovered atmos.yaml), consistent with how base_path is resolved for config-file sources.
  • The change preserves the established source-aware convention (runtime/CLI/env dot paths → CWD; bare paths → git-root search; !cwd → CWD), so anchoring is limited to config-sourced empty and dot-relative values.

references

  • Fix record: docs/fixes/2026-07-20-config-imports-relative-to-config-dir.md.
  • Related base-path work: docs/prd/base-path-resolution-semantics.md, docs/fixes/2026-03-17-failed-to-find-import-base-path-resolution.md.
  • Testing: go build ./...; go test ./pkg/config/... ./internal/exec/... ./cmd/...; the new CWD-independence tests fail on the pre-fix code (import resolves against CWD) and pass after; go test ./pkg/config ./pkg/config/adapters -shuffle=on -count=10 for registry isolation.

Summary by CodeRabbit

  • Bug Fixes
    • Resolved import: globs and relative import paths relative to the declaring config file’s directory (not the process working directory).
    • Fixed how imported base_path is anchored and prioritized across nested imports and multi-file merges, including correct handling of CWD-anchored (!cwd) behavior and bare/empty base paths.
    • Improved resilience when nested import base paths can’t be resolved or provenance read fails—continuing without breaking the whole resolve.
  • Documentation
    • Documented the updated config-relative import behavior and compatibility rules.
  • Tests
    • Expanded validation for base-path resolution, glob/relative imports, merge precedence, and new error-path scenarios.

mergeImports resolved the import base path with filepath.Abs(base_path), which anchors to the current working directory. With the common empty or dot-relative base_path (e.g. '.'), running atmos from a subdirectory resolved 'import:' entries against that subdirectory and failed to find them (e.g. import: [".atmos/commands/**/*"] when atmos.yaml is in a parent directory).

Anchor config-sourced empty and dot-relative import base paths to the directory of the declaring atmos.yaml, matching how base_path is resolved for config-file sources. Bare paths, absolute paths, !cwd, and runtime overrides (ATMOS_BASE_PATH, --base-path, provider param) keep their existing resolution. Base-path provenance is tracked across multiple --config files and imported declarations, and nested imports resolve a declared relative base_path against the importing file's directory.

Adds pkg/config/import_base_path_test.go (helper, CWD-independent resolution, bare-path and !cwd compatibility, multi --config provenance) and docs/fixes/2026-07-20-config-imports-relative-to-config-dir.md.
@atmos-pro

atmos-pro Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

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

@github-actions github-actions Bot added the size/m Medium size PR label Jul 20, 2026
@sgtoj
Brian Ojeda (sgtoj) marked this pull request as ready for review July 20, 2026 17:45
@sgtoj
Brian Ojeda (sgtoj) requested a review from a team as a code owner July 20, 2026 17:45
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Import paths in atmos.yaml are resolved relative to the declaring config directory. Base-path provenance is propagated through merges, multi-config loading, and nested adapters, while runtime/CWD and absolute-path semantics remain supported. Tests cover resolution, precedence, deep merging, and nested imports.

Changes

Config import resolution

Layer / File(s) Summary
Base-path resolution and provenance
pkg/config/load.go, pkg/config/imports.go
Adds config-aware base-path parsing and resolution, propagates imported declaration provenance, and derives imported configuration base paths from declaration context.
Multi-config merge behavior
pkg/config/load_config_args.go, pkg/config/config_import_test.go
Tracks base-path directories across multiple config files and updates merge tests for adapter setup, command and settings merging, deep merges, import hierarchies, and provisioned identities.
Nested adapter resolution
pkg/config/adapters/local_adapter.go, pkg/config/adapters/gogetter_adapter.go, pkg/config/adapters/adapters_test.go
Uses the shared resolver for nested local and GoGetter imports and validates resolved paths and resolution-failure handling.
Import resolution validation
pkg/config/import_base_path_test.go, pkg/config/imports_error_paths_test.go, pkg/config/load_error_paths_unix_test.go
Tests config-directory, glob, git-root, CWD, inherited, imported, direct, empty base-path, and error-path behavior.
Fix documentation and validation
docs/fixes/...
Documents path-resolution rules, implementation touchpoints, and validation commands.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested labels: patch

Suggested reviewers: osterman

Sequence Diagram(s)

sequenceDiagram
  participant ConfigLoader
  participant mergeImports
  participant processConfigImports
  participant ImportedConfig
  ConfigLoader->>mergeImports: pass config directory and base-path source
  mergeImports->>processConfigImports: resolve imports with base-path context
  processConfigImports->>ImportedConfig: inspect imported base_path declaration
  ImportedConfig-->>processConfigImports: return declaration provenance
  processConfigImports-->>mergeImports: return resolved base-path directory
  mergeImports-->>ConfigLoader: merge imported configuration
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: resolving atmos.yaml imports relative to the config directory.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pkg/config/adapters/gogetter_adapter.go (1)

91-105: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Base-path resolution failure aborts the whole remote import resolution instead of degrading gracefully.

Unlike local_adapter.go's processNestedImports (logs + skips just the nested imports for that file), a ResolveConfigImportBasePath failure here returns nil, err, discarding all resolvedPaths accumulated so far — including entries from other, already-successfully-downloaded tempFiles in this same loop. This is a new failure mode not present before the PR (the old inline GetString+fallback never errored).

🔧 Proposed fix: log and skip nested imports for this file instead of aborting
 		if len(imports) > 0 {
 			importBasePath, err := config.ResolveConfigImportBasePath(v.GetString("base_path"), tempFile, basePath)
 			if err != nil {
-				return nil, fmt.Errorf(errUtils.ErrWrapFormat, errUtils.ErrProcessNestedImports, err)
+				log.Debug("failed to resolve nested import base path", "path", tempFile, "error", err)
+				continue
 			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/config/adapters/gogetter_adapter.go` around lines 91 - 105, Update the
nested-import handling in the adapter’s import-processing loop so a
ResolveConfigImportBasePath failure is logged and skipped for the current remote
file, matching local_adapter.go’s processNestedImports behavior. Do not return
nil or discard previously accumulated resolvedPaths; continue processing other
files while preserving the existing error handling for ProcessImportsFromAdapter
failures.
pkg/config/load_config_args.go (1)

75-108: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

!cwd base_path provenance silently dropped for --config files.

importBasePathDeclaration(content)'s detected source is discarded (_) and mergeImports is always called with a hardcoded "" for basePathSource. A --config file declaring base_path: !cwd ./x will therefore have its own (or an inherited) import: entries incorrectly anchored to the config directory instead of the CWD, contradicting the PR's stated !cwd-preservation guarantee. This path also has no test coverage.

🐛 Proposed fix: track and thread the detected source alongside the directory
 	basePathConfigDir := ""
+	basePathSource := ""
 	for _, configPath := range configFilePaths {
 		configDir := filepath.Dir(configPath)
 		content, readErr := os.ReadFile(configPath)
 		if readErr != nil {
 			return fmt.Errorf("%w: %s: %w", errUtils.ErrReadConfig, configPath, readErr)
 		}
-		declaresBasePath, _, parseErr := importBasePathDeclaration(content)
+		declaresBasePath, source, parseErr := importBasePathDeclaration(content)
 		if parseErr != nil {
 			return fmt.Errorf("%w: %s: %w", errUtils.ErrMergeConfiguration, configPath, parseErr)
 		}
 		if declaresBasePath || basePathConfigDir == "" {
 			basePathConfigDir = configDir
+			basePathSource = source
 		}
 		...
-		importBasePathDir, importErr := mergeImports(v, importConfigDir, "")
+		importBasePathDir, importErr := mergeImports(v, importConfigDir, basePathSource)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/config/load_config_args.go` around lines 75 - 108, Preserve the base-path
source detected by importBasePathDeclaration instead of discarding it, and
thread that source through the config-loading flow. Update the mergeImports call
in the surrounding config-file loop to pass the detected or inherited
basePathSource rather than always passing "", while retaining the existing
directory selection and updating source state from imported configurations as
needed so !cwd declarations remain anchored to the CWD.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pkg/config/adapters/gogetter_adapter.go`:
- Around line 91-105: Update the nested-import handling in the adapter’s
import-processing loop so a ResolveConfigImportBasePath failure is logged and
skipped for the current remote file, matching local_adapter.go’s
processNestedImports behavior. Do not return nil or discard previously
accumulated resolvedPaths; continue processing other files while preserving the
existing error handling for ProcessImportsFromAdapter failures.

In `@pkg/config/load_config_args.go`:
- Around line 75-108: Preserve the base-path source detected by
importBasePathDeclaration instead of discarding it, and thread that source
through the config-loading flow. Update the mergeImports call in the surrounding
config-file loop to pass the detected or inherited basePathSource rather than
always passing "", while retaining the existing directory selection and updating
source state from imported configurations as needed so !cwd declarations remain
anchored to the CWD.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 34fa0814-8ca2-43ec-b67e-bc93770e454b

📥 Commits

Reviewing files that changed from the base of the PR and between 6325b89 and 3a62ee2.

📒 Files selected for processing (9)
  • docs/fixes/2026-07-20-config-imports-relative-to-config-dir.md
  • pkg/config/adapters/adapters_test.go
  • pkg/config/adapters/gogetter_adapter.go
  • pkg/config/adapters/local_adapter.go
  • pkg/config/config_import_test.go
  • pkg/config/import_base_path_test.go
  • pkg/config/imports.go
  • pkg/config/load.go
  • pkg/config/load_config_args.go

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 20, 2026
…fails to resolve

GoGetterAdapter.Resolve returned nil (discarding already-resolved paths) when ResolveConfigImportBasePath failed for a remote file's nested imports. Log and skip the current file instead, matching local_adapter's processNestedImports, while keeping the existing error handling for ProcessImportsFromAdapter failures.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 20, 2026
…p; dedupe --config tests

Add TestResolveConfigImportBasePath (declared/fallback/missing-file/invalid-yaml) and a LocalAdapter processNestedImports test for the resolve-failure skip branch, raising added-line coverage. Dedupe two TestMergeFiles_* cases into a helper to clear a dupl finding on the test file.
@aknysh Andriy Knysh (aknysh) added the patch A minor, backward compatible change label Jul 20, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/config/import_base_path_test.go (1)

226-256: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Refactor to use a table-driven test.

It looks like we have a few scenarios tested sequentially here! As per coding guidelines, use table-driven tests for testing multiple scenarios in Go. Consolidating these blocks into a slice of test cases keeps our testing structure tidy and uniform.

♻️ Proposed refactor for a table-driven test
-func TestResolveConfigImportBasePath(t *testing.T) {
-	dir := t.TempDir()
-
-	t.Run("declared dot-relative anchors to the config file's directory", func(t *testing.T) {
-		cfg := filepath.Join(dir, "declared.yaml")
-		require.NoError(t, os.WriteFile(cfg, []byte("base_path: ./sub\n"), 0o644))
-		got, err := ResolveConfigImportBasePath("./sub", cfg, filepath.Join(dir, "fallback"))
-		require.NoError(t, err)
-		assert.Equal(t, filepath.Join(dir, "sub"), got)
-	})
-
-	t.Run("no base_path declaration returns the fallback", func(t *testing.T) {
-		cfg := filepath.Join(dir, "nodecl.yaml")
-		require.NoError(t, os.WriteFile(cfg, []byte("settings:\n  x: 1\n"), 0o644))
-		got, err := ResolveConfigImportBasePath("", cfg, filepath.Join(dir, "fallback"))
-		require.NoError(t, err)
-		assert.Equal(t, filepath.Join(dir, "fallback"), got)
-	})
-
-	t.Run("missing config file returns an error", func(t *testing.T) {
-		_, err := ResolveConfigImportBasePath("./sub", filepath.Join(dir, "does-not-exist.yaml"), dir)
-		require.Error(t, err)
-	})
-
-	t.Run("invalid yaml returns an error", func(t *testing.T) {
-		cfg := filepath.Join(dir, "invalid.yaml")
-		require.NoError(t, os.WriteFile(cfg, []byte("base_path: [unterminated\n"), 0o644))
-		_, err := ResolveConfigImportBasePath("x", cfg, dir)
-		require.Error(t, err)
-	})
-}
+func TestResolveConfigImportBasePath(t *testing.T) {
+	dir := t.TempDir()
+
+	tests := []struct {
+		name        string
+		fileName    string
+		fileContent string
+		basePath    string
+		fallback    string
+		want        string
+		wantErr     bool
+	}{
+		{
+			name:        "declared dot-relative anchors to the config file's directory",
+			fileName:    "declared.yaml",
+			fileContent: "base_path: ./sub\n",
+			basePath:    "./sub",
+			fallback:    filepath.Join(dir, "fallback"),
+			want:        filepath.Join(dir, "sub"),
+		},
+		{
+			name:        "no base_path declaration returns the fallback",
+			fileName:    "nodecl.yaml",
+			fileContent: "settings:\n  x: 1\n",
+			basePath:    "",
+			fallback:    filepath.Join(dir, "fallback"),
+			want:        filepath.Join(dir, "fallback"),
+		},
+		{
+			name:     "missing config file returns an error",
+			fileName: "does-not-exist.yaml",
+			basePath: "./sub",
+			fallback: dir,
+			wantErr:  true,
+		},
+		{
+			name:        "invalid yaml returns an error",
+			fileName:    "invalid.yaml",
+			fileContent: "base_path: [unterminated\n",
+			basePath:    "x",
+			fallback:    dir,
+			wantErr:     true,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			cfg := filepath.Join(dir, tt.fileName)
+			if tt.fileContent != "" {
+				require.NoError(t, os.WriteFile(cfg, []byte(tt.fileContent), 0o644))
+			}
+			got, err := ResolveConfigImportBasePath(tt.basePath, cfg, tt.fallback)
+			if tt.wantErr {
+				require.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+			assert.Equal(t, tt.want, got)
+		})
+	}
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/config/import_base_path_test.go` around lines 226 - 256, Refactor
TestResolveConfigImportBasePath into a table-driven test with a slice of named
scenarios covering declared relative paths, missing declarations, missing config
files, and invalid YAML. Iterate with t.Run, keeping each case’s setup, expected
path, and expected error assertions equivalent to the current behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/config/import_base_path_test.go`:
- Around line 226-256: Refactor TestResolveConfigImportBasePath into a
table-driven test with a slice of named scenarios covering declared relative
paths, missing declarations, missing config files, and invalid YAML. Iterate
with t.Run, keeping each case’s setup, expected path, and expected error
assertions equivalent to the current behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 08d254e5-9880-4f4a-8ed8-40e4e950b59e

📥 Commits

Reviewing files that changed from the base of the PR and between f86890b and da953a9.

📒 Files selected for processing (2)
  • pkg/config/adapters/adapters_test.go
  • pkg/config/import_base_path_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/config/adapters/adapters_test.go

@osterman

Copy link
Copy Markdown
Member

CodeRabbit (@coderabbitai) please evaluate this against our extensive PRDs related to path handling imports and configs.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Candidate PRD/design documents =='
fd -HI -t f . | rg -i '(^|/)(prd|design|spec|rfc|adr|roadmap|requirements)([-_/\.]|$)|prd' | head -200 || true

echo
echo '== Documentation mentions: path/import/config/base_path =='
rg -n -i --glob '*.md' --glob '*.yaml' --glob '*.yml' \
  '(PRD|base_path|base path|config import|configuration import|nested import|!cwd|relative path|path handling)' \
  . | head -500 || true

echo
echo '== PR diff summary =='
git diff --stat 'HEAD^' 'HEAD'
git diff --name-status 'HEAD^' 'HEAD'

echo
echo '== Changed Go file outlines =='
for f in pkg/config/load.go pkg/config/imports.go pkg/config/load_config_args.go \
         pkg/config/adapters/local_adapter.go pkg/config/adapters/gogetter_adapter.go \
         pkg/config/import_base_path_test.go; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    ast-grep outline "$f" --items all --view compact || true
  fi
done

Length of output: 60830


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
pr="2772"

echo '== PR metadata =='
gh pr view "$pr" --repo "$repo" --json number,title,baseRefName,headRefName,commits,files \
  --jq '{number,title,baseRefName,headRefName,commits:[.commits[].oid],files:[.files[].path]}'

echo
echo '== PR file patches =='
gh api --paginate "repos/$repo/pulls/$pr/files?per_page=100" \
  --jq '.[] | "### \(.filename)\n\(.patch // "[patch unavailable]")\n"' \
  | sed -n '1,2400p'

echo
echo '== Targeted PRD outlines =='
for f in \
  docs/prd/provenance-import-resolution.md \
  docs/prd/import-provenance.md \
  docs/prd/import-adapter-registry.md \
  docs/prd/path-construction-vs-validation.md \
  docs/prd/git-root-discovery-default-behavior.md \
  docs/prd/deferred-yaml-functions-evaluation-in-merge.md; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    rg -n '^(#|##|###) ' "$f"
  fi
done

echo
echo '== Targeted PRD requirements and compatibility language =='
rg -n -i -C 4 \
  '(MUST|SHOULD|required|acceptance criteria|compatib|base_path|base path|import|relative|absolute|cwd|repo-root|provenance|nested)' \
  docs/prd/provenance-import-resolution.md \
  docs/prd/import-provenance.md \
  docs/prd/import-adapter-registry.md \
  docs/prd/path-construction-vs-validation.md \
  docs/prd/git-root-discovery-default-behavior.md \
  docs/prd/deferred-yaml-functions-evaluation-in-merge.md \
  | sed -n '1,2600p'

Length of output: 243665


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
ref="fix/config-imports-relative-to-config-dir"

echo '== Additional PRDs specifically about config/import/path semantics =='
rg -l -i --glob '*.md' \
  '(atmos\.yaml.{0,100}(import|base_path)|base_path.{0,100}(import|atmos\.yaml)|nested_imports|config import)' \
  docs/prd | sort

echo
echo '== Adapter PRD: nested remote resolution, errors, and testing =='
sed -n '110,138p' docs/prd/import-adapter-registry.md
sed -n '584,686p' docs/prd/import-adapter-registry.md
sed -n '749,766p' docs/prd/import-adapter-registry.md

echo
echo '== Exact PR source: nested-import mode and resolver plumbing =='
for f in \
  pkg/config/adapters/gogetter_adapter.go \
  pkg/config/adapters/local_adapter.go \
  pkg/config/imports.go \
  pkg/config/load.go \
  pkg/config/load_config_args.go \
  pkg/config/import_base_path_test.go; do
  echo "--- $f"
  gh api "repos/$repo/contents/$f?ref=$ref" --jq '.content' \
    | base64 --decode \
    | nl -ba \
    | rg -n -C 8 \
      '(nested_imports|ResolveConfigImportBasePath|resolveImportBasePath|importBasePathDeclaration|basePathSourceRuntime|ProcessImportsFromAdapter|processNestedImports|mergeImports|func Test)' \
    || true
done

echo
echo '== PR tests: direct coverage inventory =='
gh api "repos/$repo/contents/pkg/config/import_base_path_test.go?ref=$ref" --jq '.content' \
  | base64 --decode \
  | rg -n '^func Test|^func mergeFiles'

echo
echo '== Related existing tests outside this PR =='
rg -n -i -C 3 \
  '(nested_imports|!cwd|ATMOS_BASE_PATH|--base-path|atmos_base_path|base_path.*import|import.*base_path)' \
  pkg/config tests internal \
  -g '*_test.go' \
  | head -1000

Length of output: 8550


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
pr="2772"
sha="$(gh api "repos/$repo/pulls/$pr" --jq '.head.sha')"
echo "== PR head SHA =="
echo "$sha"

echo
echo '== Base-path resolution semantics PRD =='
cat -n docs/prd/base-path-resolution-semantics.md | sed -n '1,2600p'

echo
echo '== Exact PR source: configuration resolver and nested import behavior =='
for f in \
  pkg/config/adapters/gogetter_adapter.go \
  pkg/config/adapters/local_adapter.go \
  pkg/config/imports.go \
  pkg/config/load.go \
  pkg/config/load_config_args.go \
  pkg/config/import_base_path_test.go; do
  echo "--- $f"
  gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' \
    | base64 --decode \
    | cat -n \
    | rg -n -C 10 \
      '(nested_imports|ResolveConfigImportBasePath|resolveImportBasePath|importBasePathDeclaration|basePathSourceRuntime|ProcessImportsFromAdapter|processNestedImports|mergeImports|func Test|func \(g \*GoGetterAdapter\) Resolve)' \
    || true
done

echo
echo '== Source locations: nested mode and source provenance definitions =='
gh api "repos/$repo/git/trees/$sha?recursive=1" --jq -r '.tree[].path' \
  | rg '(^|/)(import|adapter|load).*\.go$' \
  | while read -r f; do
      gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' 2>/dev/null \
        | base64 --decode 2>/dev/null \
        | rg -n -i -C 3 '(nested_imports|basePathSourceRuntime|atmos_base_path)' \
        && echo "--- $f"
    done

echo
echo '== Exact PR test names =='
gh api "repos/$repo/contents/pkg/config/import_base_path_test.go?ref=$sha" --jq '.content' \
  | base64 --decode \
  | rg -n '^func Test|^func mergeFiles'

Length of output: 48556


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Base-path source definitions and propagation in the checked-out codebase =='
rg -n -C 6 \
  '(basePathSourceRuntime|BasePathSource|ATMOS_BASE_PATH|AtmosBasePath|atmos_base_path|mergeFiles\()' \
  pkg/config pkg/schema internal cmd \
  -g '*.go' \
  | sed -n '1,2400p'

echo
echo '== PR `#2772` commit: all references to nested_imports and nested resolver errors =='
repo="cloudposse/atmos"
sha="ded9899368dda733c9386f9f963795cfbb32dc13"
for f in pkg/config/adapters/gogetter_adapter.go pkg/config/imports.go pkg/config/import.go pkg/config/import_adapter.go; do
  content="$(gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' 2>/dev/null || true)"
  if [[ -n "$content" ]]; then
    echo "--- $f"
    printf '%s' "$content" | base64 --decode | cat -n \
      | rg -n -i -C 10 '(nested_imports|remote|ResolveConfigImportBasePath|failed to resolve nested)' \
      || true
  fi
done

echo
echo '== Tests covering runtime source + imports in the checked-out codebase =='
rg -n -i -C 4 \
  '(ATMOS_BASE_PATH|--base-path|atmos_base_path|basePathSourceRuntime).*(import|mergeFiles)|((import|mergeFiles).*(ATMOS_BASE_PATH|--base-path|atmos_base_path|basePathSourceRuntime))' \
  pkg/config internal tests \
  -g '*_test.go' \
  | sed -n '1,1600p'

Length of output: 180128


@osterman: Evaluated against the path/import/config PRDs. The main fix is aligned, but the PR is not fully PRD-compliant yet.

Aligned

  • Config-file dot paths: base_path: ., ./foo, .., and ../foo are now anchored to the declaring config directory. This matches docs/prd/base-path-resolution-semantics.md FR3.
  • CWD independence: the added subdirectory/glob regression tests support the git-like execution goal in docs/prd/git-root-discovery-default-behavior.md.
  • Nested imports and multi---config provenance: the direction is sound and consistent with the import-adapter PRD’s recursive-import requirements.
  • !cwd handling: preserving CWD semantics for tagged config values is correct.

Gaps to resolve

  1. Empty base_path is treated as config-dir-relative, not as an empty smart-default value.
    resolveImportBasePath("", configDir, ...) returns configDir.

    The base-path PRD explicitly defines empty as:

    git root → config directory → CWD
    

    Empty is intentionally distinct from "."; it must not be collapsed into config-directory anchoring. This also conflicts with the existing empty-base-path regression coverage that expects git-root resolution for nested configs.

  2. Bare paths remain CWD-resolved in the import path.
    The new resolver leaves "workspace" / "foo/bar" unchanged, then processConfigImportsWithFSAndBasePathSource applies filepath.Abs(source.BasePath), which anchors it to the process CWD.

    That conflicts with FR4: bare paths must use the source-independent git-root search, then the documented fallback order. The new test TestMergeImports_BareBasePathRetainsCWDResolution codifies the behavior the PRD specifically rejects.

  3. Runtime provenance is not propagated through mergeFiles / mergeImports.
    The codebase already tracks runtime origin through AtmosConfiguration.BasePathSource, covering ATMOS_BASE_PATH, --base-path, and atmos_base_path. But this PR passes either an empty source or a raw-!cwd marker into mergeImports.

    A runtime override such as ATMOS_BASE_PATH=. must keep CWD semantics when resolving top-level imports. Add end-to-end import tests for:

    • ATMOS_BASE_PATH=.
    • --base-path=.
    • atmos_base_path=.
    • config-file base_path: . as the contrasting config-dir case
  4. Remote nested-import resolution errors are silently skipped.
    GoGetterAdapter.Resolve logs a ResolveConfigImportBasePath error and continues. The import-adapter PRD requires an actionable error when an explicitly remote nested-import base cannot be inferred. At minimum, this behavior needs to be scoped so explicit remote mode returns a wrapped error rather than silently omitting nested imports.

Recommendation

Keep the dot-relative fix, but route import base-path resolution through the existing canonical source-aware resolver/category model rather than adding a parallel interpretation. That preserves the PRD’s intentional distinctions:

Value Required behavior
"" git root → config dir → CWD
., ./x, ../x from config declaring config directory
same dot paths from runtime CWD
foo, .hidden, foo/bar git-root search with documented fallback
absolute unchanged

The PR has strong coverage for the reported regression, but it needs the above adjustments and compatibility tests before it fully satisfies the path-handling PRDs.

@codecov

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.69%. Comparing base (acebf93) to head (111414d).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2772      +/-   ##
==========================================
+ Coverage   81.67%   81.69%   +0.02%     
==========================================
  Files        1778     1778              
  Lines      170559   170640      +81     
==========================================
+ Hits       139302   139409     +107     
+ Misses      23526    23506      -20     
+ Partials     7731     7725       -6     
Flag Coverage Δ
unittests 81.69% <100.00%> (+0.02%) ⬆️

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

Files with missing lines Coverage Δ
pkg/config/adapters/gogetter_adapter.go 95.16% <100.00%> (ø)
pkg/config/adapters/local_adapter.go 93.61% <100.00%> (+0.13%) ⬆️
pkg/config/imports.go 91.12% <100.00%> (+3.22%) ⬆️
pkg/config/load.go 86.35% <100.00%> (+0.73%) ⬆️
pkg/config/load_config_args.go 90.83% <100.00%> (+0.44%) ⬆️

... and 11 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…solver

Address PRD review: resolve config import base paths via the canonical resolveAbsolutePath category model instead of a parallel interpretation. Empty base paths now use git-root discovery (git root -> config dir -> CWD), bare paths use git-root search, config dot paths anchor to the config dir, !cwd/runtime dot paths anchor to CWD, and absolute paths pass through — matching docs/prd/base-path-resolution-semantics.md.

Restore the actionable wrapped error for remote (go-getter) nested-import base-path inference failures per import-adapter-registry.md FR-7.6; local nested imports still skip (FR-7.2).

Tests: drop the bare->CWD assertion that contradicted the PRD; add empty->git-root and bare->git-root import tests; disable git-root discovery where multi-config fixtures rely on the config-dir fallback.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 20, 2026
Add tests for the realistically-triggerable error paths introduced by the
import base-path rework, raising net-new coverage from 84% to 89%:

- mergeFiles: os.ReadFile failure after stat-only validation (unreadable
  --config file) and non-fatal mergeImports failure (malformed base_path).
- processConfigImports: tolerated provenance re-read failure.

Route the provenance re-read through the injected FileSystem seam
(fs.ReadFile) instead of os.ReadFile, consistent with the fs.MkdirTemp and
fs.RemoveAll calls already in that function, so the branch is testable.

Remaining uncovered lines are defensive error propagation from filepath.Abs
(os.Getwd failures) and re-parses of bytes viper already parsed; forcing
coverage on them would be theater, matching the deleted tests documented in
imports_error_paths_test.go.
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 20, 2026
Cover every remaining error branch introduced by the import base-path rework,
using genuine failure conditions and minimal seams rather than skipping them:

- Remove the redundant filepath.Abs in processConfigImportsWithFSAndBasePathSource;
  processImports already resolves and validates the base path, so an empty base
  path now surfaces ErrBasePath instead of silently defaulting to the CWD.
- Extract mergeResolvedImports to keep the caller under the complexity limit.
- Add a parseBasePathDeclaration seam so the two sites that re-parse content Viper
  has already validated can exercise their error-propagation branches.
- Widen defaultFileSystem to the FileSystem interface so temp-dir creation failures
  are injectable.

Tests trigger resolveAbsolutePath's real permission-denied stat error (bare
base_path under an unreadable git-root dir) for mergeImports, mergeConfigFileWithImports,
and the go-getter nested-import path; a failing --config read; a non-fatal import
merge failure; and a MkdirTemp failure. Permission tests are Unix-only and skipped
as root.

Patch coverage for the five changed production files is now 100% (113/113 lines).
@aknysh

Copy link
Copy Markdown
Member

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain
🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Candidate PRD/design documents =='
fd -HI -t f . | rg -i '(^|/)(prd|design|spec|rfc|adr|roadmap|requirements)([-_/\.]|$)|prd' | head -200 || true

echo
echo '== Documentation mentions: path/import/config/base_path =='
rg -n -i --glob '*.md' --glob '*.yaml' --glob '*.yml' \
  '(PRD|base_path|base path|config import|configuration import|nested import|!cwd|relative path|path handling)' \
  . | head -500 || true

echo
echo '== PR diff summary =='
git diff --stat 'HEAD^' 'HEAD'
git diff --name-status 'HEAD^' 'HEAD'

echo
echo '== Changed Go file outlines =='
for f in pkg/config/load.go pkg/config/imports.go pkg/config/load_config_args.go \
         pkg/config/adapters/local_adapter.go pkg/config/adapters/gogetter_adapter.go \
         pkg/config/import_base_path_test.go; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    ast-grep outline "$f" --items all --view compact || true
  fi
done

Length of output: 60830

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
pr="2772"

echo '== PR metadata =='
gh pr view "$pr" --repo "$repo" --json number,title,baseRefName,headRefName,commits,files \
  --jq '{number,title,baseRefName,headRefName,commits:[.commits[].oid],files:[.files[].path]}'

echo
echo '== PR file patches =='
gh api --paginate "repos/$repo/pulls/$pr/files?per_page=100" \
  --jq '.[] | "### \(.filename)\n\(.patch // "[patch unavailable]")\n"' \
  | sed -n '1,2400p'

echo
echo '== Targeted PRD outlines =='
for f in \
  docs/prd/provenance-import-resolution.md \
  docs/prd/import-provenance.md \
  docs/prd/import-adapter-registry.md \
  docs/prd/path-construction-vs-validation.md \
  docs/prd/git-root-discovery-default-behavior.md \
  docs/prd/deferred-yaml-functions-evaluation-in-merge.md; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    rg -n '^(#|##|###) ' "$f"
  fi
done

echo
echo '== Targeted PRD requirements and compatibility language =='
rg -n -i -C 4 \
  '(MUST|SHOULD|required|acceptance criteria|compatib|base_path|base path|import|relative|absolute|cwd|repo-root|provenance|nested)' \
  docs/prd/provenance-import-resolution.md \
  docs/prd/import-provenance.md \
  docs/prd/import-adapter-registry.md \
  docs/prd/path-construction-vs-validation.md \
  docs/prd/git-root-discovery-default-behavior.md \
  docs/prd/deferred-yaml-functions-evaluation-in-merge.md \
  | sed -n '1,2600p'

Length of output: 243665

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
ref="fix/config-imports-relative-to-config-dir"

echo '== Additional PRDs specifically about config/import/path semantics =='
rg -l -i --glob '*.md' \
  '(atmos\.yaml.{0,100}(import|base_path)|base_path.{0,100}(import|atmos\.yaml)|nested_imports|config import)' \
  docs/prd | sort

echo
echo '== Adapter PRD: nested remote resolution, errors, and testing =='
sed -n '110,138p' docs/prd/import-adapter-registry.md
sed -n '584,686p' docs/prd/import-adapter-registry.md
sed -n '749,766p' docs/prd/import-adapter-registry.md

echo
echo '== Exact PR source: nested-import mode and resolver plumbing =='
for f in \
  pkg/config/adapters/gogetter_adapter.go \
  pkg/config/adapters/local_adapter.go \
  pkg/config/imports.go \
  pkg/config/load.go \
  pkg/config/load_config_args.go \
  pkg/config/import_base_path_test.go; do
  echo "--- $f"
  gh api "repos/$repo/contents/$f?ref=$ref" --jq '.content' \
    | base64 --decode \
    | nl -ba \
    | rg -n -C 8 \
      '(nested_imports|ResolveConfigImportBasePath|resolveImportBasePath|importBasePathDeclaration|basePathSourceRuntime|ProcessImportsFromAdapter|processNestedImports|mergeImports|func Test)' \
    || true
done

echo
echo '== PR tests: direct coverage inventory =='
gh api "repos/$repo/contents/pkg/config/import_base_path_test.go?ref=$ref" --jq '.content' \
  | base64 --decode \
  | rg -n '^func Test|^func mergeFiles'

echo
echo '== Related existing tests outside this PR =='
rg -n -i -C 3 \
  '(nested_imports|!cwd|ATMOS_BASE_PATH|--base-path|atmos_base_path|base_path.*import|import.*base_path)' \
  pkg/config tests internal \
  -g '*_test.go' \
  | head -1000

Length of output: 8550

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

repo="cloudposse/atmos"
pr="2772"
sha="$(gh api "repos/$repo/pulls/$pr" --jq '.head.sha')"
echo "== PR head SHA =="
echo "$sha"

echo
echo '== Base-path resolution semantics PRD =='
cat -n docs/prd/base-path-resolution-semantics.md | sed -n '1,2600p'

echo
echo '== Exact PR source: configuration resolver and nested import behavior =='
for f in \
  pkg/config/adapters/gogetter_adapter.go \
  pkg/config/adapters/local_adapter.go \
  pkg/config/imports.go \
  pkg/config/load.go \
  pkg/config/load_config_args.go \
  pkg/config/import_base_path_test.go; do
  echo "--- $f"
  gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' \
    | base64 --decode \
    | cat -n \
    | rg -n -C 10 \
      '(nested_imports|ResolveConfigImportBasePath|resolveImportBasePath|importBasePathDeclaration|basePathSourceRuntime|ProcessImportsFromAdapter|processNestedImports|mergeImports|func Test|func \(g \*GoGetterAdapter\) Resolve)' \
    || true
done

echo
echo '== Source locations: nested mode and source provenance definitions =='
gh api "repos/$repo/git/trees/$sha?recursive=1" --jq -r '.tree[].path' \
  | rg '(^|/)(import|adapter|load).*\.go$' \
  | while read -r f; do
      gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' 2>/dev/null \
        | base64 --decode 2>/dev/null \
        | rg -n -i -C 3 '(nested_imports|basePathSourceRuntime|atmos_base_path)' \
        && echo "--- $f"
    done

echo
echo '== Exact PR test names =='
gh api "repos/$repo/contents/pkg/config/import_base_path_test.go?ref=$sha" --jq '.content' \
  | base64 --decode \
  | rg -n '^func Test|^func mergeFiles'

Length of output: 48556

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Base-path source definitions and propagation in the checked-out codebase =='
rg -n -C 6 \
  '(basePathSourceRuntime|BasePathSource|ATMOS_BASE_PATH|AtmosBasePath|atmos_base_path|mergeFiles\()' \
  pkg/config pkg/schema internal cmd \
  -g '*.go' \
  | sed -n '1,2400p'

echo
echo '== PR `#2772` commit: all references to nested_imports and nested resolver errors =='
repo="cloudposse/atmos"
sha="ded9899368dda733c9386f9f963795cfbb32dc13"
for f in pkg/config/adapters/gogetter_adapter.go pkg/config/imports.go pkg/config/import.go pkg/config/import_adapter.go; do
  content="$(gh api "repos/$repo/contents/$f?ref=$sha" --jq '.content' 2>/dev/null || true)"
  if [[ -n "$content" ]]; then
    echo "--- $f"
    printf '%s' "$content" | base64 --decode | cat -n \
      | rg -n -i -C 10 '(nested_imports|remote|ResolveConfigImportBasePath|failed to resolve nested)' \
      || true
  fi
done

echo
echo '== Tests covering runtime source + imports in the checked-out codebase =='
rg -n -i -C 4 \
  '(ATMOS_BASE_PATH|--base-path|atmos_base_path|basePathSourceRuntime).*(import|mergeFiles)|((import|mergeFiles).*(ATMOS_BASE_PATH|--base-path|atmos_base_path|basePathSourceRuntime))' \
  pkg/config internal tests \
  -g '*_test.go' \
  | sed -n '1,1600p'

Length of output: 180128

@osterman: Evaluated against the path/import/config PRDs. The main fix is aligned, but the PR is not fully PRD-compliant yet.

Aligned

  • Config-file dot paths: base_path: ., ./foo, .., and ../foo are now anchored to the declaring config directory. This matches docs/prd/base-path-resolution-semantics.md FR3.
  • CWD independence: the added subdirectory/glob regression tests support the git-like execution goal in docs/prd/git-root-discovery-default-behavior.md.
  • Nested imports and multi---config provenance: the direction is sound and consistent with the import-adapter PRD’s recursive-import requirements.
  • !cwd handling: preserving CWD semantics for tagged config values is correct.

Gaps to resolve

  1. Empty base_path is treated as config-dir-relative, not as an empty smart-default value.
    resolveImportBasePath("", configDir, ...) returns configDir.
    The base-path PRD explicitly defines empty as:

    git root → config directory → CWD
    

    Empty is intentionally distinct from "."; it must not be collapsed into config-directory anchoring. This also conflicts with the existing empty-base-path regression coverage that expects git-root resolution for nested configs.

  2. Bare paths remain CWD-resolved in the import path.
    The new resolver leaves "workspace" / "foo/bar" unchanged, then processConfigImportsWithFSAndBasePathSource applies filepath.Abs(source.BasePath), which anchors it to the process CWD.
    That conflicts with FR4: bare paths must use the source-independent git-root search, then the documented fallback order. The new test TestMergeImports_BareBasePathRetainsCWDResolution codifies the behavior the PRD specifically rejects.

  3. Runtime provenance is not propagated through mergeFiles / mergeImports.
    The codebase already tracks runtime origin through AtmosConfiguration.BasePathSource, covering ATMOS_BASE_PATH, --base-path, and atmos_base_path. But this PR passes either an empty source or a raw-!cwd marker into mergeImports.
    A runtime override such as ATMOS_BASE_PATH=. must keep CWD semantics when resolving top-level imports. Add end-to-end import tests for:

    • ATMOS_BASE_PATH=.
    • --base-path=.
    • atmos_base_path=.
    • config-file base_path: . as the contrasting config-dir case
  4. Remote nested-import resolution errors are silently skipped.
    GoGetterAdapter.Resolve logs a ResolveConfigImportBasePath error and continues. The import-adapter PRD requires an actionable error when an explicitly remote nested-import base cannot be inferred. At minimum, this behavior needs to be scoped so explicit remote mode returns a wrapped error rather than silently omitting nested imports.

Recommendation

Keep the dot-relative fix, but route import base-path resolution through the existing canonical source-aware resolver/category model rather than adding a parallel interpretation. That preserves the PRD’s intentional distinctions:

Value Required behavior
"" git root → config dir → CWD
., ./x, ../x from config declaring config directory
same dot paths from runtime CWD
foo, .hidden, foo/bar git-root search with documented fallback
absolute unchanged
The PR has strong coverage for the reported regression, but it needs the above adjustments and compatibility tests before it fully satisfies the path-handling PRDs.

CodeRabbit (@coderabbitai) please evaluate/check if the latest commits addressed your comments and suggestions

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Current PR head and recent commits =='
gh pr view 2772 --repo cloudposse/atmos \
  --json headRefOid,baseRefOid,commits,files \
  --jq '{headRefOid, baseRefOid, commits:[.commits[] | {oid:.oid,messageHeadline:.messageHeadline}], files:[.files[].path]}'

echo
echo '== Changed-file summary against PR base =='
base="$(gh pr view 2772 --repo cloudposse/atmos --json baseRefOid --jq .baseRefOid)"
git diff --stat "$base"...HEAD
git diff --name-status "$base"...HEAD

echo
echo '== Relevant source maps =='
for f in \
  pkg/config/load.go \
  pkg/config/load_config_args.go \
  pkg/config/imports.go \
  pkg/config/adapters/local_adapter.go \
  pkg/config/adapters/gogetter_adapter.go \
  pkg/config/import_base_path_test.go \
  pkg/config/adapters/adapters_test.go \
  docs/prd/base-path-resolution-semantics.md \
  docs/prd/import-adapter-registry.md; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    ast-grep outline "$f" --items all --view compact 2>/dev/null || true
  fi
done

echo
echo '== Current resolver, provenance, and nested-error code =='
rg -n -C 10 \
  '(ResolveConfigImportBasePath|resolveImportBasePath|resolveAbsolutePath|basePathSource|BasePathSource|mergeFiles\(|mergeImports\(|processConfigImportsWithFSAndBasePathSource|processNestedImports|ErrProcessNestedImports)' \
  pkg/config \
  -g '*.go'

echo
echo '== Current targeted test inventory and assertions =='
rg -n -C 5 \
  '(EmptyBasePath|BareBasePath|ATMOS_BASE_PATH|atmos_base_path|base-path|CwdBasePath|Runtime|NestedImports.*ResolveFailure|ResolveConfigImportBasePath|ErrProcessNestedImports)' \
  pkg/config \
  -g '*_test.go'

echo
echo '== PRD excerpts for categories and error handling =='
rg -n -i -C 5 \
  '(empty|bare|git root|git-root|runtime|ATMOS_BASE_PATH|atmos_base_path|--base-path|declaring config|nested|remote|actionable|error)' \
  docs/prd/base-path-resolution-semantics.md \
  docs/prd/import-adapter-registry.md

Length of output: 224981


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Exact current call sites and surrounding load order =='
rg -n -C 14 'mergeImports\(' pkg/config -g '*.go'
rg -n -C 14 '(loadConfigFromCLIArgs\(|processConfigImportsAndReapply\(|processEnvVars\(|setBasePaths\(|BasePathSource)' \
  pkg/config/config.go pkg/config/load.go pkg/config/load_config_args.go pkg/config/utils.go

echo
echo '== Current implementations needed to trace source propagation =='
sed -n '70,112p' pkg/config/load_config_args.go
sed -n '1170,1220p' pkg/config/load.go
sed -n '1510,1592p' pkg/config/load.go
sed -n '30,70p' pkg/config/config.go
sed -n '570,645p' pkg/config/utils.go

echo
echo '== Canonical-routing commit patch =='
git show --format=fuller --find-renames --find-copies d3685a0ac79c2f520f684be88e8123444280a4f6 -- \
  pkg/config/load.go pkg/config/load_config_args.go pkg/config/imports.go \
  pkg/config/adapters/gogetter_adapter.go pkg/config/adapters/local_adapter.go \
  pkg/config/import_base_path_test.go

echo
echo '== Nested import mode representation and GoGetter call contexts =='
rg -n -C 10 '(nested_imports|NestedImports|GoGetterAdapter|ProcessImportsFromAdapter)' \
  pkg/config \
  -g '*.go'

Length of output: 107400


@aknysh: I checked the current head (561ad78a). The follow-up commits addressed three of the four findings.

Addressed

  1. Empty base_path

    • Resolved. mergeImports and ResolveConfigImportBasePath now call the canonical resolveAbsolutePath.
    • TestMergeImports_EmptyBasePathResolvesViaGitRoot verifies git-root behavior rather than config-directory anchoring.
  2. Bare-path resolution

    • Resolved. Bare paths now use the canonical git-root search.
    • TestMergeImports_BareBasePathResolvesViaGitRoot covers this behavior.
  3. Remote nested-import resolution errors

    • The former silent skip is resolved: pkg/config/adapters/gogetter_adapter.go now returns a wrapped ErrProcessNestedImports error when nested base-path resolution fails.
    • TestGoGetterAdapter_NestedImportBasePathResolveError covers the error path.

Still unresolved: runtime base-path provenance during imports

Runtime overrides are still applied after imports are processed:

  • LoadConfig resolves imports.
  • Only afterward does processAtmosConfigs run processEnvVars and processCommandLineArgs, which set AtmosConfiguration.BasePathSource = "runtime".

Further, mergeFiles still calls:

mergeImports(v, importConfigDir, "")

So top-level imports cannot distinguish:

  • ATMOS_BASE_PATH=.
  • --base-path=.
  • atmos_base_path=.

from a config-file-sourced base_path: . during the import phase. This retains config-directory anchoring where runtime dot paths require CWD anchoring under the PRD.

The PR needs runtime source/value plumbing into import processing, plus end-to-end coverage for those three runtime mechanisms and the contrasting config-file case.

One nuance: the GoGetter change propagates failures for all remote nested imports. That fixes the reported silent failure, but I could not verify the PRD’s narrower nested_imports: remote mode semantics because no nested_imports mode propagation is present in this path.

@aknysh

Copy link
Copy Markdown
Member

Brian Ojeda (@sgtoj) please review and address the latest CodeRabbit (@coderabbitai) comment/suggestion

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@aknysh Acknowledged. The remaining item is runtime base-path provenance during import resolution; I’ll re-check the implementation and end-to-end coverage once the update is available.

Runtime base-path overrides (ATMOS_BASE_PATH, --base-path, atmos_base_path)
were applied only after imports were processed, so top-level imports could not
distinguish a runtime dot base path (which must anchor to the CWD) from a
config-file base_path: . (which anchors to the config directory).

LoadConfig now records any runtime override on the main Viper instance and
threads it into import resolution (mergeImports, mergeConfigFileWithImports, and
the --config mergeFiles path). When present, the override wins over the declared
base_path and resolves through the canonical source-aware resolver with runtime
(CWD) semantics for dot-prefixed values. The carrier key lives only on the main
Viper instance, which is never marshaled, so it does not leak into merged config.

Tests cover runtime-override detection and precedence (flag/provider over env),
CWD anchoring in mergeImports and mergeConfigFileWithImports, the contrasting
config-file case, and an end-to-end LoadConfig run with ATMOS_BASE_PATH.

Addresses the remaining CodeRabbit finding on PR cloudposse#2772.
@github-actions github-actions Bot added size/l Large size PR and removed size/m Medium size PR labels Jul 21, 2026
@sgtoj

Copy link
Copy Markdown
Contributor Author

Addressed the remaining finding (runtime base-path provenance during imports) in be28d92.

What changed: LoadConfig now records any runtime base-path override — ATMOS_BASE_PATH, --base-path, or the atmos_base_path provider param (via configAndStacksInfo.AtmosBasePath, which takes precedence over the env var) — and threads it into import resolution: mergeImports (both the discovery flow and the --config/mergeFiles path) and mergeConfigFileWithImports (profiles). When a runtime override is present it wins over the config-file base_path and resolves through the canonical resolveAbsolutePath, so dot-prefixed values anchor to the CWD per the PRD; bare paths still use git-root search and absolute paths pass through unchanged.

The override is carried on the main Viper instance via an internal key that is never marshaled, so it does not leak into merged config.

Coverage — all three runtime mechanisms plus the contrasting config-file case:

  • TestResolveRuntimeBasePath — AtmosBasePath (flag/provider) precedence over ATMOS_BASE_PATH, env fallback, empty = unset.
  • TestMergeImports_RuntimeBasePathOverrideAnchorsToCWD and TestMergeConfigFileWithImports_RuntimeBasePathOverrideAnchorsToCWD — a runtime dot base path anchors imports to the CWD.
  • TestMergeImports_ConfigDotBasePathAnchorsToConfigDir — the contrasting config-file base_path: . stays config-dir-anchored.
  • TestLoadConfig_RuntimeBasePathAnchorsImportsToCWD — end-to-end through LoadConfig with ATMOS_BASE_PATH.

On the nested_imports: remote nuance: there is no nested_imports mode in the current adapter registry — the go-getter adapter wraps nested base-path resolution failures as ErrProcessNestedImports uniformly. A narrower per-mode policy would be a separate enhancement to the registry and is out of scope here.

Patch coverage on the changed production files is 100% (verified locally with Codecov's hits/(hits+partials+misses) formula).

@aknysh

Copy link
Copy Markdown
Member

Addressed the remaining finding (runtime base-path provenance during imports) in be28d92.

What changed: LoadConfig now records any runtime base-path override — ATMOS_BASE_PATH, --base-path, or the atmos_base_path provider param (via configAndStacksInfo.AtmosBasePath, which takes precedence over the env var) — and threads it into import resolution: mergeImports (both the discovery flow and the --config/mergeFiles path) and mergeConfigFileWithImports (profiles). When a runtime override is present it wins over the config-file base_path and resolves through the canonical resolveAbsolutePath, so dot-prefixed values anchor to the CWD per the PRD; bare paths still use git-root search and absolute paths pass through unchanged.

The override is carried on the main Viper instance via an internal key that is never marshaled, so it does not leak into merged config.

Coverage — all three runtime mechanisms plus the contrasting config-file case:

  • TestResolveRuntimeBasePath — AtmosBasePath (flag/provider) precedence over ATMOS_BASE_PATH, env fallback, empty = unset.
  • TestMergeImports_RuntimeBasePathOverrideAnchorsToCWD and TestMergeConfigFileWithImports_RuntimeBasePathOverrideAnchorsToCWD — a runtime dot base path anchors imports to the CWD.
  • TestMergeImports_ConfigDotBasePathAnchorsToConfigDir — the contrasting config-file base_path: . stays config-dir-anchored.
  • TestLoadConfig_RuntimeBasePathAnchorsImportsToCWD — end-to-end through LoadConfig with ATMOS_BASE_PATH.

On the nested_imports: remote nuance: there is no nested_imports mode in the current adapter registry — the go-getter adapter wraps nested base-path resolution failures as ErrProcessNestedImports uniformly. A narrower per-mode policy would be a separate enhancement to the registry and is out of scope here.

Patch coverage on the changed production files is 100% (verified locally with Codecov's hits/(hits+partials+misses) formula).

CodeRabbit (@coderabbitai) please analyze

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

commit="be28d92c853164481519b2bd06205d8f48e2e892"

echo '== Current PR head and commits after the reported fix =='
gh pr view 2772 --repo cloudposse/atmos \
  --json headRefOid,commits \
  --jq '{head:.headRefOid, commits:[.commits[] | {oid:.oid,message:.messageHeadline}]}'

echo
echo '== Files changed by the runtime-provenance commit =='
git show --format='commit %H%n%s' --stat "$commit"
git show --format='' --name-only "$commit"

echo
echo '== Relevant file outlines =='
for f in pkg/config/load.go pkg/config/load_config_args.go pkg/config/config.go pkg/config/utils.go pkg/config/imports.go pkg/config/import_base_path_test.go; do
  if [[ -f "$f" ]]; then
    echo "--- $f"
    ast-grep outline "$f" --items all --view compact || true
  fi
done

echo
echo '== Runtime override definitions, data flow, and all import-merge call sites =='
rg -n -C 8 \
  '(runtime.*[Bb]ase[Pp]ath|[Bb]ase[Pp]ath.*[Rr]untime|AtmosBasePath|ATMOS_BASE_PATH|mergeImports\s*\(|mergeConfigFileWithImports\s*\(|resolveAbsolutePath\s*\(|Set\(|GetString\()' \
  pkg/config \
  -g '*.go'

echo
echo '== Patch for production and test changes =='
git diff "${commit}^" "$commit" -- \
  pkg/config/load.go pkg/config/load_config_args.go pkg/config/imports.go \
  pkg/config/import_base_path_test.go pkg/config/config.go pkg/config/utils.go \
  '*_test.go'

echo
echo '== Stated test definitions and their complete nearby bodies =='
rg -n -A90 -B5 \
  'func Test(ResolveRuntimeBasePath|MergeImports_RuntimeBasePathOverrideAnchorsToCWD|MergeConfigFileWithImports_RuntimeBasePathOverrideAnchorsToCWD|MergeImports_ConfigDotBasePathAnchorsToConfigDir|LoadConfig_RuntimeBasePathAnchorsImportsToCWD)\b' \
  pkg/config \
  -g '*_test.go'

echo
echo '== Config serialization/marshaling paths that could expose the internal key =='
rg -n -C 5 \
  '(AllSettings\s*\(|Marshal|Unmarshal|WriteConfig|MergeConfigMap|viper\.Viper)' \
  pkg/config \
  -g '*.go'

Length of output: 160531


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo '== Load order and override setup =='
sed -n '360,535p' pkg/config/load.go

echo
echo '== Every mergeImports call and all callers of mergeConfigFileWithImports =='
rg -n -C 5 '\bmergeImports\s*\(' pkg/config -g '*.go'
rg -n -C 5 '\bmergeConfigFileWithImports\s*\(' pkg/config -g '*.go'

echo
echo '== Import merge implementations and immediate serialization paths =='
sed -n '1270,1335p' pkg/config/load.go
sed -n '1595,1665p' pkg/config/load.go
sed -n '1770,1830p' pkg/config/load.go
sed -n '69,112p' pkg/config/load_config_args.go

echo
echo '== Main-Viper AllSettings/marshal/copy paths and private-key references =='
rg -n -C 6 \
  '(runtimeBasePathOverrideKey|marshalViperToYAML\s*\(|\.AllSettings\s*\(|MergeConfig\(|ReadConfig\()' \
  pkg/config \
  -g '*.go'

echo
echo '== Existing tests that exercise actual LoadConfig or profiles with AtmosBasePath =='
rg -n -C 8 \
  '(LoadConfig\s*\(|loadProfiles\s*\(|ProfilesFromArg|AtmosBasePath)' \
  pkg/config \
  -g '*_test.go'

echo
echo '== Current diff after the reported fix =='
git diff be28d92c853164481519b2bd06205d8f48e2e892..HEAD -- \
  pkg/config/load.go pkg/config/load_config_args.go pkg/config/import_base_path_runtime_test.go pkg/config/profiles.go

Length of output: 126401


@aknysh Verified against the current PR head: the runtime base-path provenance finding is addressed.

  • LoadConfig records the runtime override before any imports are resolved.
  • The override reaches both configuration import flows:
    • standard discovery via mergeConfig → processConfigImportsAndReapply → mergeImports;
    • explicit --config inputs via mergeFiles → mergeImports.
  • Profile imports also use the runtime override through mergeConfigFileWithImports.
  • effectiveImportBasePath gives a runtime value precedence and labels it runtime, so dot-prefixed paths resolve from CWD via the canonical resolver. Config-sourced base_path: . remains config-directory-relative.
  • The private Viper key does not enter the temporary Viper instance serialized by mergeConfig; it is retained only on the main instance for loader coordination and is ignored by the returned schema.

The prior concern is therefore resolved.

One minor test-coverage note: the end-to-end test exercises ATMOS_BASE_PATH=.. --base-path and atmos_base_path share ConfigAndStacksInfo.AtmosBasePath, and that precedence is unit-tested, but neither has its own end-to-end import-resolution test. Adding one LoadConfig test with AtmosBasePath: "." would explicitly cover both field-backed runtime sources. This is a coverage improvement, not a remaining correctness blocker.

@aknysh
Andriy Knysh (aknysh) merged commit 1e58bbb into cloudposse:main Jul 21, 2026
75 checks passed
@atmos-pro

atmos-pro Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

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

@github-actions

Copy link
Copy Markdown

These changes were released in v1.223.1-rc.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants