Skip to content

fix: toolchain path resolution, constraint solving, and uninstall improvements - #2172

Merged
Andriy Knysh (aknysh) merged 22 commits into
mainfrom
osterman/fix-tofu-path
Mar 13, 2026
Merged

Andriy Knysh (aknysh) merged 22 commits into
mainfrom
osterman/fix-tofu-path

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Comprehensive improvements to the toolchain subsystem covering binary path resolution, semver constraint resolution, and uninstall reliability.

Toolchain binary path resolution

  • Resolve toolchain executables to absolute paths before execution (fixes exec.LookPath failures)
  • Centralize PATH construction via ToolchainEnvironment to eliminate scattered resolution logic
  • Fix cross-platform path handling for Windows CI

Semver constraint resolution

  • Resolve semver constraints (e.g., ^1.10.0) to concrete versions before tool install
  • Cache-first resolution: skip network call when an installed version already satisfies the constraint
  • Show resolved version on cache hit (e.g., "Using opentofu 1.11.5 (satisfies ^1.10.0)")
  • Add spinner during network-based constraint resolution
  • Add retry with exponential backoff (3 attempts) for transient network errors (stream cancel, connection reset, timeouts)
    • Hybrid error detection: gates on registry.ErrHTTPRequest sentinel, then string-matches for transient patterns

Uninstall improvements

  • Fix blank tool names in uninstall output caused by glamour linkify interpreting @ as email autolinks — backtick-wrap tool specs
  • Add --all flag to atmos toolchain uninstall to remove tools installed via component dependencies.tools (not just .tool-versions)
  • ListAllInstalledTools() scans install directory two levels deep to discover all installed tools

Testing

  • Add CI test cases for examples/toolchain (describe component, show dependencies, command detection)
  • Add glamour regression tests at both goldmark and formatter levels
  • Make TestForWorkflow_WithToolVersions deterministic with mockgen
  • Fix cross-platform test assertions

Test plan

  • go build ./... compiles cleanly
  • go test ./pkg/dependencies/... -count=1 passes
  • go test ./pkg/toolchain/... -count=1 passes
  • go test ./pkg/ui/... -count=1 passes
  • Pre-commit hooks pass (golangci-lint, go-fumpt, go mod tidy)
  • Manual: atmos toolchain uninstall --all removes dependency-installed tools
  • Manual: constraint resolution retries on transient network failure

🤖 Generated with Claude Code

Template functions like atmos.Component() and YAML functions like !terraform.output
were failing with "exec: tofu: executable file not found in $PATH" even when tofu
was installed via `atmos toolchain install`. The executor in pkg/terraform/output
never set up the toolchain PATH, unlike the direct terraform command execution path.

Changes:
- Export ExtractDependenciesFromConfig in pkg/dependencies/resolver.go
  so the executor can extract dependencies.tools from component sections
- Add ResolveExecutablePath method to Installer to resolve bare executable names
  (e.g., "tofu") to their absolute toolchain install paths
- Add toolchain dependency resolution in executor.execute() between config
  extraction and runner creation: ensure tools are installed, resolve the
  executable to an absolute path, and build the toolchain PATH for subprocesses
- Add comprehensive tests demonstrating the fix resolves toolchain executables

This ensures all code paths that need to execute terraform/tofu (template functions,
YAML functions, describe-stacks) can find toolchain-installed binaries.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
@github-actions github-actions Bot added the size/m Medium size PR label Mar 12, 2026
@github-actions

github-actions Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@coderabbitai

coderabbitai Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Adds a ToolchainEnvironment for resolving/installing toolchain binaries, exposes ExtractDependenciesFromConfig, integrates toolchain-aware executable resolution and PATH/env propagation across executors and internal commands, and updates tests and messaging related to CI artifact discovery.

Changes

Cohort / File(s) Summary
Dependencies: environment & tests
pkg/dependencies/environment.go, pkg/dependencies/environment_test.go
Introduce ToolchainEnvironment type with ForComponent/ForSections/ForWorkflow constructors, Resolve/EnvVars/PATH/ToolchainDirs/PrependToPath methods, pluggable env options, binary resolution/installation and PATH construction; add extensive unit tests.
Installer: executable lookup & tests
pkg/dependencies/installer.go, pkg/dependencies/installer_test.go
Add Installer.ResolveExecutablePath to prefer toolchain binaries (resolver + binaryPathFinder), fallback to exec.LookPath, handle absolute paths and perf tracking; tests cover toolchain resolution, PATH fallback, platform extension matching, and error cases.
Dependency extraction export
pkg/dependencies/resolver.go, pkg/dependencies/resolver_test.go
Export extractDependenciesFromConfig → ExtractDependenciesFromConfig and add perf tracking; tests updated to call the exported function.
Terraform output executor & test
pkg/terraform/output/executor.go, pkg/terraform/output/executor_test.go
Resolve executables via dependencies.ForSections → tenv.Resolve, prepend toolchain dirs to PATH for subprocesses, reorder steps to apply toolchain env before runner creation; add test asserting resolved executable is absolute toolchain path.
Internal command integrations
internal/exec/...
internal/exec/aws_eks_update_kubeconfig.go, internal/exec/helmfile.go, internal/exec/packer.go, internal/exec/terraform.go, internal/exec/terraform_detection.go, internal/exec/workflow_utils.go, internal/exec/utils.go
Replace ad-hoc toolchain PATH/installer logic with dependencies.ForComponent/ForWorkflow returning tenv; use tenv.Resolve(...) and tenv.EnvVars() for subprocesses; change resolveAndInstallToolchainDeps to return (*ToolchainEnvironment,error); update IsOpenTofu signature to accept tenv; remove ensureWorkflowToolchainDependencies helper.
Internal tests: adjustments
internal/exec/*_test.go, internal/exec/workflow_utils_test.go
Update tests to account for new tenv APIs: pass nil for new IsOpenTofu param, use dependencies.ForWorkflow and tenv.PATH(), rename tests and adjust assertions to new behavior.
GitHub/toolchain messaging & artifacts
pkg/github/artifacts.go, pkg/github/artifacts_test.go, pkg/toolchain/pr_artifact.go, pkg/toolchain/sha_artifact.go
Change wording to prefer “completed” workflow runs over “successful”, rename findSuccessfulWorkflowRun → findCompletedWorkflowRun and relax conclusion filtering; simplify and reword user-facing error hints for PR/SHA artifact lookups.
Miscellaneous
pkg/version/reexec.go, pkg/terraform/output/platform_windows.go, other imports
Remove some error hint text, shorten Windows retry delays, update imports and call sites to new exported functions and ToolchainEnvironment methods.

Sequence Diagram(s)

sequenceDiagram
    participant Executor as Terraform Executor
    participant Resolver as Dependency Resolver
    participant Installer as Tool Installer
    participant PathFinder as Binary Path Finder
    participant Runner as Runner Factory

    Executor->>+Resolver: ExtractDependenciesFromConfig(config)
    Resolver-->>-Executor: deps map

    alt deps exist
        Executor->>+Installer: ForSections/ForComponent(deps)
        Installer-->>-Executor: ToolchainEnvironment (tenv)
        Executor->>+PathFinder: tenv.Resolve(executable)
        PathFinder-->>-Executor: resolved toolchain path or empty
        alt found in toolchain
            Executor->>Executor: use absolute toolchain path
        else not found
            Executor->>Executor: exec.LookPath(executable)
            Executor-->>Executor: system PATH result or original name
        end
        Executor->>Executor: updatedPATH = tenv.PrependToPath(os.Getenv("PATH"))
    end

    Executor->>Runner: Create runner with resolved executable + env (updatedPATH + tenv.EnvVars())
    Runner-->>Executor: execution result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title clearly describes the main change: improving toolchain path resolution, constraint solving, and uninstall. However, the raw summary and objectives reveal the PR is primarily about resolving toolchain executables in template functions and YAML functions, not constraint solving or uninstall. The title is partially related but overstates scope. Revise the title to focus on the primary change: 'fix: resolve toolchain executables in template and YAML functions' or similar, removing the broader 'constraint solving and uninstall improvements' which aren't substantiated by the actual changes.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 86.84% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch osterman/fix-tofu-path
📝 Coding Plan
  • Generate coding plan for human review comments

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

Inline comments:
In `@pkg/dependencies/installer.go`:
- Around line 218-225: Normalize the names before comparing in
ResolveExecutablePath: when you get binaryPath from
i.binaryPathFinder.FindBinaryPath(owner, repo, version) strip the extension from
filepath.Base(binaryPath) (use strings.TrimSuffix(..., filepath.Ext(...))) and
also strip any extension from the requested executable variable, then compare
those normalized basenames instead of comparing filepath.Base(binaryPath) ==
executable; update the comparison logic around binaryPath/executable in
installer.go and add a Windows-specific unit test (similar to
TestIsToolInstalled_DifferentBinaryName) that asserts ResolveExecutablePath
returns the .exe path when executable is provided without extension.

In `@pkg/terraform/output/executor_test.go`:
- Around line 1231-1258: The test sets a package-global toolchain config via
toolchain.SetAtmosConfig() and must restore the original config to avoid leaking
t.TempDir() into other tests; capture the original config with
toolchain.GetAtmosConfig() at the start of the test (e.g., origToolchainConfig
:= toolchain.GetAtmosConfig()) and register a t.Cleanup that restores it via
toolchain.SetAtmosConfig(origToolchainConfig) so the package-global state is
reset after the test (apply the same guard near the other occurrence at lines
~1288-1289).

In `@pkg/terraform/output/executor.go`:
- Line 406: BuildToolchainPATH currently builds a full PATH from the process
environment and you overwrite environMap["PATH"] with it, which drops any PATH
set by SetupEnvironment() (the component env section); change the flow so you
call dependencies.BuildToolchainPATH using the PATH value already in environMap
(i.e., pass environMap["PATH"] or otherwise base the toolchain prefix on
environMap after calling SetupEnvironment()), then prepend the resulting
toolchain prefix to environMap["PATH"] instead of replacing it; update the code
around the calls to SetupEnvironment, environMap, and
dependencies.BuildToolchainPATH so the toolchain entries are injected before the
existing PATH value to preserve component overrides.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 19553d29-0ed3-4ab4-aadd-530a1035d0ef

📥 Commits

Reviewing files that changed from the base of the PR and between 5e87975 and e086027.

📒 Files selected for processing (6)
  • pkg/dependencies/installer.go
  • pkg/dependencies/installer_test.go
  • pkg/dependencies/resolver.go
  • pkg/dependencies/resolver_test.go
  • pkg/terraform/output/executor.go
  • pkg/terraform/output/executor_test.go

Comment thread pkg/dependencies/installer.go Resolved
Comment thread pkg/terraform/output/executor_test.go Resolved
Comment thread pkg/terraform/output/executor.go Resolved
@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.99352% with 88 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.30%. Comparing base (dd9fa5b) to head (a7bd577).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/toolchain/installer/version.go 0.00% 29 Missing ⚠️
pkg/toolchain/uninstall.go 22.72% 16 Missing and 1 partial ⚠️
cmd/toolchain/uninstall.go 38.88% 10 Missing and 1 partial ⚠️
internal/exec/helmfile.go 30.00% 6 Missing and 1 partial ⚠️
internal/exec/packer.go 60.00% 3 Missing and 1 partial ⚠️
internal/exec/terraform.go 73.33% 2 Missing and 2 partials ⚠️
pkg/dependencies/installer.go 97.67% 2 Missing and 2 partials ⚠️
internal/exec/aws_eks_update_kubeconfig.go 50.00% 1 Missing and 1 partial ⚠️
internal/exec/terraform_detection.go 33.33% 1 Missing and 1 partial ⚠️
pkg/dependencies/environment.go 98.44% 1 Missing and 1 partial ⚠️
... and 4 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2172      +/-   ##
==========================================
+ Coverage   77.24%   77.30%   +0.05%     
==========================================
  Files         959      960       +1     
  Lines       90782    91088     +306     
==========================================
+ Hits        70124    70413     +289     
- Misses      16574    16591      +17     
  Partials     4084     4084              
Flag Coverage Δ
unittests 77.30% <80.99%> (+0.05%) ⬆️

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

Files with missing lines Coverage Δ
internal/exec/utils.go 82.31% <100.00%> (ø)
internal/exec/workflow_utils.go 75.62% <100.00%> (+4.95%) ⬆️
pkg/dependencies/resolver.go 90.24% <100.00%> (+0.12%) ⬆️
pkg/toolchain/sha_artifact.go 72.86% <100.00%> (-0.62%) ⬇️
pkg/version/reexec.go 93.93% <ø> (-0.07%) ⬇️
cmd/version/uninstall.go 25.00% <0.00%> (ø)
pkg/github/artifacts.go 76.40% <90.00%> (-0.57%) ⬇️
internal/exec/aws_eks_update_kubeconfig.go 59.28% <50.00%> (-0.57%) ⬇️
internal/exec/terraform_detection.go 82.35% <33.33%> (-3.37%) ⬇️
pkg/dependencies/environment.go 98.44% <98.44%> (ø)
... and 9 more

... and 3 files with indirect coverage changes

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

… resolution

Replace scattered toolchain boilerplate (resolver + installer + EnsureTools +
BuildToolchainPATH + ResolveExecutablePath) with a single ToolchainEnvironment
type in pkg/dependencies/. Three constructors match caller shapes: ForComponent,
ForSections, ForWorkflow. Each returns an object with Resolve(command) for
executable path lookup and EnvVars() for subprocess environment configuration.

This fixes exec call sites that were bypassing toolchain-managed paths:
- Version commands (terraform/helmfile/packer) now resolve through toolchain
- IsOpenTofu detection resolves the command through toolchain before detection
- AWS eks update-kubeconfig resolves "aws" through toolchain with proper env

Net reduction: ~105 lines removed across callers, replaced by 2-3 line calls.
Test coverage on environment.go: 92-100% across all functions.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@github-actions github-actions Bot added size/l Large size PR and removed size/m Medium size PR labels Mar 12, 2026
@osterman Erik Osterman (Cloud Posse) (osterman) added the patch A minor, backward compatible change label Mar 12, 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.

Actionable comments posted: 6

Caution

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

⚠️ Outside diff range comments (1)
internal/exec/utils.go (1)

886-892: ⚠️ Potential issue | 🟠 Major

Don't drop back to nil here.

Line 892 bypasses the new toolchain-aware resolution and falls back to the parent PATH. If the configured Terraform command resolves to an OpenTofu binary via ToolchainEnvironment (for example through a symlink, alias, or toolchain-installed path), this branch can still misclassify it as Terraform and raise a false terraform-config-inspect error for valid OpenTofu syntax. Pass the current toolchain environment into IsOpenTofu, or derive one from configAndStacksInfo.StackSection and configAndStacksInfo.ComponentSection before detecting.

Based on learnings, "command names don't reliably indicate the actual binary being executed (symlinks, aliases)."

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

In `@internal/exec/utils.go` around lines 886 - 892, The code currently calls
IsOpenTofu(&effectiveConfig, nil) which ignores the toolchain-aware resolution
and can misclassify a configured Terraform command that actually resolves to an
OpenTofu binary; instead derive or obtain the relevant ToolchainEnvironment from
configAndStacksInfo (e.g., using the StackSection and ComponentSection or the
project's toolchain resolver) and pass that toolchainEnv into IsOpenTofu (call
IsOpenTofu(&effectiveConfig, toolchainEnv)) so detection considers
symlinks/aliases/toolchain-installed paths when deciding whether to skip
validation.
♻️ Duplicate comments (2)
pkg/dependencies/environment.go (1)

281-283: ⚠️ Potential issue | 🟠 Major

Store the bare executable name here too.

On Windows this key becomes tofu.exe/aws.exe, but callers resolve bare names like tofu and aws. Resolve() then misses the toolchain entry and falls back to the system PATH, so toolchain-installed binaries still won't resolve there.

Patch sketch
-		env.resolved[filepath.Base(binaryPath)] = binaryPath
+		base := filepath.Base(binaryPath)
+		env.resolved[base] = binaryPath
+		env.resolved[strings.TrimSuffix(base, filepath.Ext(base))] = binaryPath

As per coding guidelines, "Cross-Platform Compatibility (MANDATORY): Ensure Linux/macOS/Windows compatibility."

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

In `@pkg/dependencies/environment.go` around lines 281 - 283, The map assignment
only stores the OS-specific basename (e.g., "tofu.exe") so Resolve() misses bare
names; update the code that sets env.resolved (the place using
filepath.Base(binaryPath)) to also store the bare executable name by deriving
base := filepath.Base(binaryPath), computing bare := strings.TrimSuffix(base,
filepath.Ext(base)) (guarding against empty strings), and set env.resolved[bare]
= binaryPath in addition to env.resolved[base] = binaryPath so both "tofu.exe"
and "tofu" resolve across platforms.
internal/exec/workflow_utils.go (1)

330-333: ⚠️ Potential issue | 🟠 Major

Prepend into the merged PATH instead of appending another PATH=.

baseEnv already carries PATH from os.Environ() plus atmosConfig.Env. tenv.EnvVars() is built from the process PATH again, so appending it here can drop workflow/global PATH overrides and leaves duplicate PATH keys in the subprocess env. Replace the existing PATH value with tenv.PrependToPath(...) instead.

Based on learnings, "non-identity steps intentionally use baseWorkflowEnv, which is constructed from the parent environment with PATH modifications for the toolchain. Avoid appending os.Environ() again; prefer documenting this behavior and testing that standard environment variables are preserved."

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

In `@internal/exec/workflow_utils.go` around lines 330 - 333, baseEnv is currently
built by merging os.Environ() and atmosConfig.Env and then appending
tenv.EnvVars(), which reintroduces PATH and can override workflow/global PATH
entries and produce duplicate PATH keys; instead, stop appending tenv.EnvVars()
and update baseEnv's PATH entry by calling tenv.PrependToPath(...) (using the
existing baseEnv, envpkg.MergeGlobalEnv, os.Environ(), atmosConfig.Env and
tenv.PrependToPath symbols) so the toolchain PATH is prepended to the
already-merged environment while preserving any PATH set by the workflow/global
envs; remove the append of tenv.EnvVars() and add logic to replace the PATH
value in baseEnv via tenv.PrependToPath to avoid duplicate PATH entries.
🧹 Nitpick comments (1)
internal/exec/terraform_detection_test.go (1)

72-72: Add one non-nil toolchain case.

All of the updated call sites here still exercise IsOpenTofu(..., nil), so the new tenv.Resolve(...) branch and resolved-command cache key never run under test. One case that drives IsOpenTofu with a real or test-specific ToolchainEnvironment would lock in the behavior this PR adds.

As per coding guidelines, "Every new feature must include comprehensive unit tests targeting >80% code coverage for all packages."

Also applies to: 94-108, 126-126, 154-174, 355-356, 472-473, 495-517

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

In `@internal/exec/terraform_detection_test.go` at line 72, Add a unit test that
calls IsOpenTofu with a non-nil ToolchainEnvironment so the tenv.Resolve(...)
branch and the resolved-command cache key are exercised; specifically, create a
test-specific ToolchainEnvironment (or mock) that returns a determinable
resolution for Resolve and pass it into IsOpenTofu(atmosConfig, yourTenv) to
assert expected behavior and cache interactions, and add similar non-nil cases
for the other call sites mentioned so coverage includes the tenv.Resolve path
and resolved-command caching logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/exec/aws_eks_update_kubeconfig.go`:
- Around line 251-256: The call to dependencies.ForComponent currently discards
component context and thus misses component-level tools; update the call to pass
the discovered component context from ProcessStacks by supplying
configAndStacksInfo.ComponentType, configAndStacksInfo.StackSection and
configAndStacksInfo.ComponentSection (instead of empty/ nil placeholders) so
ForComponent can resolve component-level dependencies; keep the returned tenv
and then call ExecuteShellCommand(atmosConfig, tenv.Resolve("aws"), args,
shellCommandWorkingDir, tenv.EnvVars(), dryRun, "") as before.

In `@internal/exec/terraform.go`:
- Around line 296-299: The code calls resolveAndInstallToolchainDeps(...) but
discards the returned toolchain environment (tenv) and leaves info.Command as
the bare name, causing OS lookup failures; change the call to capture the
returned tenv from resolveAndInstallToolchainDeps (when shouldProcess is true),
then call tenv.Resolve(info.Command) and assign the resolved path back to
info.Command before calling ExecuteShellCommand (or other execution paths),
ensuring you reference resolveAndInstallToolchainDeps, tenv, tenv.Resolve,
info.Command, and ExecuteShellCommand when making the change.

In `@internal/exec/workflow_utils_test.go`:
- Around line 1565-1572: The tests around ForWorkflow in workflow_utils_test.go
are nondeterministic because they accept any error and may trigger real
installs; update both test blocks that call dependencies.ForWorkflow(...) to
create a deterministic fixture by pre-creating a fake executable under the
Toolchain.InstallPath (simulate installed tools) before calling
dependencies.ForWorkflow, then assert that tenv.PATH() is non-empty and that
tenv.Resolve("terraform") (or the specific tool name used) returns the expected
path, and no longer swallow errors from ForWorkflow — fail the test if it
returns an unexpected error; apply the same change pattern to the second block
that currently mirrors this behavior.

In `@pkg/dependencies/environment_test.go`:
- Around line 186-209: The test currently succeeds even when ForWorkflow fails
to install or resolve tools, so change ForWorkflow (or overload/new helper used
by tests) to accept a ToolInstaller/PathResolver interface (e.g., an installer
interface used by ForWorkflow) and update the test to inject a mock
implementation generated with go.uber.org/mock/mockgen that simulates successful
tool installation and a fixed PATH; then assert that tenv.PATH() equals the
expected mocked value (or is non-empty) to deterministically verify the
.tool-versions handling instead of relying on real network installs. Ensure
references to ForWorkflow and the installer/path-resolution abstraction are used
so the test can stub behavior without performing network installs.
- Around line 16-82: Tests in TestToolchainEnvironment_* hardcode Unix-style
paths, PATH separators and use "sh"; update assertions to be OS-neutral by
building expected paths with filepath.Join (for e.g. the resolved tool paths)
and constructing PATH using string(os.PathListSeparator) instead of ":"; in the
Resolve "system PATH tool" case avoid using "sh"—use a platform-neutral lookup
like the current process executable (e.g., base := filepath.Base(os.Args[0]) and
exec.LookPath(base)) so Resolve("base") is expected to return an absolute path;
update assertions in TestToolchainEnvironment_Resolve,
TestToolchainEnvironment_EnvVars, and TestToolchainEnvironment_PATH to use these
changes and reference the ToolchainEnvironment.Resolve, EnvVars, and PATH
methods.

In `@pkg/dependencies/environment.go`:
- Around line 228-237: BuildToolchainPATH can return the current process PATH
when nothing changed, so avoid treating that as an augmentation: after calling
buildPATH(atmosConfig, deps) check whether toolchainPATH equals the current
process environment PATH (os.Getenv("PATH")) or equals the existing env.path
and, if so, do not set env.path (leave it nil/unchanged) so EnvVars() won't emit
a redundant "PATH="; update the block around buildPATH, BuildToolchainPATH, and
env.path assignment (referencing buildPATH variable, BuildToolchainPATH,
toolchainPATH, and env.path) to only assign when toolchainPATH is meaningfully
different.

---

Outside diff comments:
In `@internal/exec/utils.go`:
- Around line 886-892: The code currently calls IsOpenTofu(&effectiveConfig,
nil) which ignores the toolchain-aware resolution and can misclassify a
configured Terraform command that actually resolves to an OpenTofu binary;
instead derive or obtain the relevant ToolchainEnvironment from
configAndStacksInfo (e.g., using the StackSection and ComponentSection or the
project's toolchain resolver) and pass that toolchainEnv into IsOpenTofu (call
IsOpenTofu(&effectiveConfig, toolchainEnv)) so detection considers
symlinks/aliases/toolchain-installed paths when deciding whether to skip
validation.

---

Duplicate comments:
In `@internal/exec/workflow_utils.go`:
- Around line 330-333: baseEnv is currently built by merging os.Environ() and
atmosConfig.Env and then appending tenv.EnvVars(), which reintroduces PATH and
can override workflow/global PATH entries and produce duplicate PATH keys;
instead, stop appending tenv.EnvVars() and update baseEnv's PATH entry by
calling tenv.PrependToPath(...) (using the existing baseEnv,
envpkg.MergeGlobalEnv, os.Environ(), atmosConfig.Env and tenv.PrependToPath
symbols) so the toolchain PATH is prepended to the already-merged environment
while preserving any PATH set by the workflow/global envs; remove the append of
tenv.EnvVars() and add logic to replace the PATH value in baseEnv via
tenv.PrependToPath to avoid duplicate PATH entries.

In `@pkg/dependencies/environment.go`:
- Around line 281-283: The map assignment only stores the OS-specific basename
(e.g., "tofu.exe") so Resolve() misses bare names; update the code that sets
env.resolved (the place using filepath.Base(binaryPath)) to also store the bare
executable name by deriving base := filepath.Base(binaryPath), computing bare :=
strings.TrimSuffix(base, filepath.Ext(base)) (guarding against empty strings),
and set env.resolved[bare] = binaryPath in addition to env.resolved[base] =
binaryPath so both "tofu.exe" and "tofu" resolve across platforms.

---

Nitpick comments:
In `@internal/exec/terraform_detection_test.go`:
- Line 72: Add a unit test that calls IsOpenTofu with a non-nil
ToolchainEnvironment so the tenv.Resolve(...) branch and the resolved-command
cache key are exercised; specifically, create a test-specific
ToolchainEnvironment (or mock) that returns a determinable resolution for
Resolve and pass it into IsOpenTofu(atmosConfig, yourTenv) to assert expected
behavior and cache interactions, and add similar non-nil cases for the other
call sites mentioned so coverage includes the tenv.Resolve path and
resolved-command caching logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2f9342bd-2bc6-4585-9c17-629830149848

📥 Commits

Reviewing files that changed from the base of the PR and between e086027 and 2c5336d.

📒 Files selected for processing (15)
  • internal/exec/aws_eks_update_kubeconfig.go
  • internal/exec/helmfile.go
  • internal/exec/packer.go
  • internal/exec/terraform.go
  • internal/exec/terraform_detection.go
  • internal/exec/terraform_detection_test.go
  • internal/exec/utils.go
  • internal/exec/workflow_utils.go
  • internal/exec/workflow_utils_test.go
  • pkg/dependencies/environment.go
  • pkg/dependencies/environment_test.go
  • pkg/dependencies/installer.go
  • pkg/dependencies/installer_test.go
  • pkg/terraform/output/executor.go
  • pkg/terraform/output/executor_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/terraform/output/executor_test.go

Comment thread internal/exec/terraform.go Resolved
Comment thread internal/exec/workflow_utils_test.go Resolved
Comment thread pkg/dependencies/environment_test.go Resolved
Comment thread pkg/dependencies/environment_test.go Resolved
Comment thread pkg/dependencies/environment.go Resolved
…t downloads, improve error messages, fix cross-platform tests

- Change artifact fetcher to accept any completed workflow run, not just successful ones,
  so build artifacts can be downloaded even when unrelated jobs fail
- Pass component type and sections to ForComponent in EKS kubeconfig for proper toolchain resolution
- Use tenv.Resolve for command in ExecuteTerraform to resolve toolchain paths
- Fix environment.go to not set PATH when it equals system PATH
- Make environment tests cross-platform (use filepath.Join, os.PathListSeparator)
- Remove flaky network-dependent workflow tests
- Simplify error hints to be more concise and actionable
- Remove redundant authentication hints from reexec error builders

Co-Authored-By: Claude Opus 4.6 <[email protected]>
When tools are installed on-demand via dependencies.tools, each tool is resolved
to its absolute path per-component (since different components can declare
different tool versions). The bug was that the resolved absolute path wasn't
being used when invoking the binary — only the subprocess env was updated, but
exec.Command resolves binaries against the parent process PATH.

Also addresses CodeRabbit review feedback: pass component context to ForComponent
in aws_eks, guard against redundant PATH emission, make tests OS-neutral and
deterministic, and remove nondeterministic workflow tests.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

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

⚠️ Outside diff range comments (1)
pkg/github/artifacts.go (1)

284-321: ⚠️ Potential issue | 🟠 Major

Completed-run lookup can miss a usable artifact.

The new comment says this helper finds a run that “produced artifacts”, but the loop still returns the first Tests run in the response without checking that. After widening the filter to completed, that first match can be a failed/cancelled rerun with no upload, which makes callers return ErrNoArtifactFound even when another completed run for the same SHA does have the artifact. Please only select a run after confirming the target artifact exists.

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

In `@pkg/github/artifacts.go` around lines 284 - 321, The loop in
findCompletedWorkflowRun currently returns the first workflow run named by
workflowName without verifying it actually produced artifacts; change it to
iterate all runs named workflowName and for each call the ActionsService
artifact-listing method (e.g. actions.ListWorkflowRunArtifacts or equivalent)
for run.GetID(), check the response/artifacts total count > 0 (and handle errors
via handleGitHubAPIError), and only return the workflowRunInfo for the first run
that has artifacts; if no matching run with artifacts is found, return the
existing ErrNoWorkflowRunFound error.
🧹 Nitpick comments (1)
pkg/github/artifacts_test.go (1)

332-366: Assert the workflow-run query options in these mocks.

All of these expectations accept gomock.Any() for *github.ListWorkflowRunsOptions, so the suite would still pass if findCompletedWorkflowRun stopped sending Status: "completed" or dropped the HeadSHA filter. Since that request shape is the behavior this change is protecting, it’s worth asserting those fields in the mock callback.

🧪 Tighten one expectation pattern
 mockActions.EXPECT().
-	ListRepositoryWorkflowRuns(gomock.Any(), "owner", "repo", gomock.Any()).
-	Return(runs, nil, nil)
+	ListRepositoryWorkflowRuns(gomock.Any(), "owner", "repo", gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{})).
+	DoAndReturn(func(_ context.Context, owner, repo string, opts *github.ListWorkflowRunsOptions) (*github.WorkflowRuns, *github.Response, error) {
+		assert.Equal(t, "abc123", opts.HeadSHA)
+		assert.Equal(t, "completed", opts.Status)
+		return runs, nil, nil
+	})
As per coding guidelines: "Test Quality (MANDATORY): Test behavior, not implementation."

Also applies to: 373-400, 409-442, 945-957

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

In `@pkg/github/artifacts_test.go` around lines 332 - 366, The mock expectation is
too loose because it uses gomock.Any() for the *github.ListWorkflowRunsOptions;
update the expectation in TestFindCompletedWorkflowRun to assert the request
shape by replacing the final gomock.Any() with
gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{}) and add a
Do/DoAndReturn callback that inspects the passed *github.ListWorkflowRunsOptions
(the fourth arg) and asserts opts.Status == "completed" and opts.HeadSHA ==
"abc123"; locate the expectation on mockActions.ListRepositoryWorkflowRuns and
apply the same pattern to the other mentioned tests (around the other ranges) to
ensure the Status and HeadSHA filters are validated.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/exec/terraform.go`:
- Around line 59-65: Do not append tenv.EnvVars() into info.ComponentEnvList
here; instead carry the tenv value forward and remove the append so
ExecuteTerraform can merge tenv.EnvVars() into the final PATH when building the
complete environment. Concretely, stop mutating info.ComponentEnvList in this
function (remove the call that appends tenv.EnvVars()), keep returning tenv as
before, and modify ExecuteTerraform to incorporate tenv.EnvVars() only when
computing the effective PATH (merge toolchain dirs with any later PATH entries
so later sources can override but toolchain dirs are preserved).

In `@pkg/dependencies/environment.go`:
- Around line 283-284: The map env.resolved is only indexed by
filepath.Base(binaryPath), so Resolve(...) can miss matches when the configured
command is an alias or symlink; update the code that sets env.resolved (the line
using filepath.Base(binaryPath) and binaryPath) to also set
env.resolved[requestedName] = binaryPath (i.e., store the resolved path under
the requested tool/command name used by Resolve()), keeping the existing
filepath.Base entry as well so both lookup forms succeed.

In `@pkg/toolchain/pr_artifact.go`:
- Around line 623-626: The hint "CI build may be failing on this PR" is
misleading in the github.ErrNoWorkflowRunFound branch; in the
WithExplanationf/... hint chain starting at the WithExplanationf("No completed
CI run found for PR #%d", prNumber) call in pr_artifact.go, remove the
WithHint("CI build may be failing on this PR") entry so only hints about
workflow completion and fork artifact access remain; if you still want to
suggest a failing build, add that WithHint to the artifact-missing handling path
instead (the branch that reports missing artifacts).
- Around line 601-603: The three WithHint(...) messages in pr_artifact.go that
currently hardcode "brew install gh" and "export GITHUB_TOKEN=..." should be
made OS-neutral: either replace them with a single generic hint like "Install
GitHub CLI or set a GITHUB_TOKEN environment variable" and a platform-agnostic
link to GitHub token docs, or branch on runtime.GOOS inside the code that
constructs these hints (using the same WithHint call sites) to emit
Windows-specific instructions (PowerShell setx or set) vs POSIX export and an
alternative install command for Linux vs macOS; update the WithHint invocations
accordingly so the error message is accurate on Windows and non-Homebrew
systems.

In `@pkg/toolchain/sha_artifact.go`:
- Around line 219-224: The error hints in the errUtils.Build call in
sha_artifact.go (the return that starts with
errUtils.Build(errUtils.ErrToolNotFound)) are incorrect for this branch; replace
the hint "CI build may be failing for this commit" with a
trigger/visibility-focused hint such as "CI run completed but may be
inaccessible due to fork/visibility or trigger settings" (or similar), and
ensure the other hints remain (No completed CI run message, fork
artifacts/accessibility hint, and the commit URL hint) so the error points to
trigger/visibility causes rather than a failing build.

---

Outside diff comments:
In `@pkg/github/artifacts.go`:
- Around line 284-321: The loop in findCompletedWorkflowRun currently returns
the first workflow run named by workflowName without verifying it actually
produced artifacts; change it to iterate all runs named workflowName and for
each call the ActionsService artifact-listing method (e.g.
actions.ListWorkflowRunArtifacts or equivalent) for run.GetID(), check the
response/artifacts total count > 0 (and handle errors via handleGitHubAPIError),
and only return the workflowRunInfo for the first run that has artifacts; if no
matching run with artifacts is found, return the existing ErrNoWorkflowRunFound
error.

---

Nitpick comments:
In `@pkg/github/artifacts_test.go`:
- Around line 332-366: The mock expectation is too loose because it uses
gomock.Any() for the *github.ListWorkflowRunsOptions; update the expectation in
TestFindCompletedWorkflowRun to assert the request shape by replacing the final
gomock.Any() with gomock.AssignableToTypeOf(&github.ListWorkflowRunsOptions{})
and add a Do/DoAndReturn callback that inspects the passed
*github.ListWorkflowRunsOptions (the fourth arg) and asserts opts.Status ==
"completed" and opts.HeadSHA == "abc123"; locate the expectation on
mockActions.ListRepositoryWorkflowRuns and apply the same pattern to the other
mentioned tests (around the other ranges) to ensure the Status and HeadSHA
filters are validated.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f8c868d9-bcac-438e-b1c1-1e388d8bb16a

📥 Commits

Reviewing files that changed from the base of the PR and between 2c5336d and 1d0c6c4.

📒 Files selected for processing (9)
  • internal/exec/aws_eks_update_kubeconfig.go
  • internal/exec/terraform.go
  • internal/exec/workflow_utils_test.go
  • pkg/dependencies/environment.go
  • pkg/github/artifacts.go
  • pkg/github/artifacts_test.go
  • pkg/toolchain/pr_artifact.go
  • pkg/toolchain/sha_artifact.go
  • pkg/version/reexec.go
💤 Files with no reviewable changes (1)
  • pkg/version/reexec.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/exec/aws_eks_update_kubeconfig.go

Comment thread internal/exec/terraform.go Resolved
Comment thread pkg/dependencies/environment.go Resolved
Comment thread pkg/toolchain/pr_artifact.go Resolved
Comment thread pkg/toolchain/pr_artifact.go Resolved
Comment thread pkg/toolchain/sha_artifact.go Resolved
Strip file extensions when storing/looking up resolved executables so
that Resolve("tofu") finds "tofu.exe" on Windows. Reduce Windows file
delay from 200ms to 50ms and retry delays from 200/500/1000ms to
50/100/200ms to cut CI runtime.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/dependencies/environment.go (1)

285-289: Consider storing resolved path under the tool name as well.

Currently only the binary basename is used as the key. If the tool name differs from the binary name (e.g., tool "opentofu" installs binary "tofu"), calling Resolve("opentofu") won't find the path.

Suggested fix
 		// Store by binary basename without extension so Resolve("tofu") works
 		// cross-platform (e.g. binary is "tofu.exe" on Windows, lookup is "tofu").
 		base := filepath.Base(binaryPath)
 		key := strings.TrimSuffix(base, filepath.Ext(base))
 		env.resolved[key] = binaryPath
+		// Also store by tool name for alias/symlink scenarios where tool name
+		// differs from binary name (e.g., "opentofu" → "tofu" binary).
+		toolKey := strings.TrimSuffix(tool, filepath.Ext(tool))
+		if toolKey != key {
+			env.resolved[toolKey] = binaryPath
+		}

Based on learnings: "command names don't reliably indicate the actual binary being executed (symlinks, aliases)."

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

In `@pkg/dependencies/environment.go` around lines 285 - 289, The code stores
resolved binary paths only under the binary basename (key computed from
binaryPath) which breaks Resolve("toolName") when the tool name differs from the
binary (e.g., "opentofu" -> "tofu"); update the population logic in the
environment resolver (where env.resolved is assigned) to also store the same
binaryPath under the declared tool name (lookup name used by Resolve), e.g.,
derive the tool name from the discovered package metadata or the provided tool
identifier and set env.resolved[toolName] = binaryPath in addition to the
existing env.resolved[key] = binaryPath so Resolve can find by either name
(ensure you handle empty/toolName == key to avoid duplicates).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/dependencies/environment.go`:
- Around line 285-289: The code stores resolved binary paths only under the
binary basename (key computed from binaryPath) which breaks Resolve("toolName")
when the tool name differs from the binary (e.g., "opentofu" -> "tofu"); update
the population logic in the environment resolver (where env.resolved is
assigned) to also store the same binaryPath under the declared tool name (lookup
name used by Resolve), e.g., derive the tool name from the discovered package
metadata or the provided tool identifier and set env.resolved[toolName] =
binaryPath in addition to the existing env.resolved[key] = binaryPath so Resolve
can find by either name (ensure you handle empty/toolName == key to avoid
duplicates).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fef48607-2ccd-4b9b-95e4-bac2f0c89eea

📥 Commits

Reviewing files that changed from the base of the PR and between 1d0c6c4 and 1facf65.

📒 Files selected for processing (3)
  • pkg/dependencies/environment.go
  • pkg/terraform/output/executor_test.go
  • pkg/terraform/output/platform_windows.go

…S-neutral hints

- Defer toolchain PATH injection until after all env assembly in
  ExecuteTerraform so toolchain dirs always take precedence over
  PATH entries from ComponentEnvSection or auth hooks
- Store resolved binary paths under both the tool name and binary
  basename so aliases/symlinks are found by Resolve()
- Make brew install hint conditional on macOS or brew availability,
  use OS-neutral wording for GITHUB_TOKEN hint

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (2)
pkg/toolchain/pr_artifact.go (1)

637-640: ⚠️ Potential issue | 🟡 Minor

The "CI build may be failing" hint is misleading here.

This branch handles ErrNoWorkflowRunFound, meaning no completed run exists. A failed CI run is still a completed run. This hint creates confusion about the actual error state. Consider removing it or moving it to the ErrNoArtifactFound branch where it would fit better.

Suggested fix
 	if errors.Is(err, github.ErrNoWorkflowRunFound) {
 		return errUtils.Build(errUtils.ErrToolNotFound).
 			WithExplanationf("No completed CI run found for PR #%d", prNumber).
 			WithHint("CI workflow may not have completed yet").
-			WithHint("CI build may be failing on this PR").
 			WithHint("Artifacts from fork PRs are not accessible").
 			WithHintf("Check PR status: %s", prURL).
 			WithExitCode(1).
 			Err()
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/toolchain/pr_artifact.go` around lines 637 - 640, In the block that
constructs the error for ErrNoWorkflowRunFound (the chain calling
WithExplanationf("No completed CI run found for PR #%d") and subsequent WithHint
calls), remove the misleading WithHint("CI build may be failing on this PR")
because a failed run would still be a completed run; alternatively move that
hint into the ErrNoArtifactFound error branch where a failing build is a
plausible cause. Update the code that builds the error (the chained
WithExplanationf/WithHint calls) to either drop that hint or add it to the
ErrNoArtifactFound branch so the hints accurately match the error condition.
internal/exec/terraform.go (1)

463-467: ⚠️ Potential issue | 🟠 Major

Merge the toolchain dirs into the final PATH, don’t replace it.

Appending tenv.EnvVars() here still overwrites any earlier PATH= in info.ComponentEnvList with a value built from the parent process PATH. That keeps toolchain precedence, but it also drops component/auth PATH additions entirely and can hide helper binaries those hooks rely on. Build one merged PATH= from the effective PATH assembled so far and tenv.PrependToPath(...), then append only that entry.

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

In `@internal/exec/terraform.go` around lines 463 - 467, The current append of
tenv.EnvVars() overwrites any existing PATH entries in info.ComponentEnvList;
instead compute the effective PATH from info.ComponentEnvList (extract existing
PATH if present or use os.Getenv("PATH")), call
tenv.PrependToPath(effectivePath) to get the toolchain-prefixed PATH, replace or
append a single PATH entry with that merged value, and only append the resulting
PATH env var (not the full tenv.EnvVars()) so component/auth-added PATH entries
are preserved while still giving toolchain precedence.
🧹 Nitpick comments (1)
pkg/dependencies/environment.go (1)

243-251: Keep ToolchainDirs() derived from the same source as PATH().

env.path comes from buildPATH(...), but env.dirs is rebuilt from env.resolved, and resolveBinaryPaths() explicitly skips failures. That means PrependToPath() can emit a different toolchain prefix than EnvVars()/PATH() for the same environment. Derive dirs from the ordered PATH builder result so the two APIs stay consistent.

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

In `@pkg/dependencies/environment.go` around lines 243 - 251, The toolchain dirs
are being built from env.resolved but PATH() is created by buildPATH(...),
causing inconsistent prefixes; instead derive env.dirs from the same ordered
PATH string used by buildPATH so ToolchainDirs()/PrependToPath() match
EnvVars()/PATH(). Replace the loop that populates env.dirs from env.resolved
with logic that splits the built PATH (the value assigned to env.path or the
string returned by buildPATH), iterate the split list in order, append each
unique directory (use a seen map) into env.dirs to preserve order and
deduplicate; keep the rest of resolveBinaryPaths() behavior unchanged so
failures stay skipped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@internal/exec/terraform.go`:
- Around line 463-467: The current append of tenv.EnvVars() overwrites any
existing PATH entries in info.ComponentEnvList; instead compute the effective
PATH from info.ComponentEnvList (extract existing PATH if present or use
os.Getenv("PATH")), call tenv.PrependToPath(effectivePath) to get the
toolchain-prefixed PATH, replace or append a single PATH entry with that merged
value, and only append the resulting PATH env var (not the full tenv.EnvVars())
so component/auth-added PATH entries are preserved while still giving toolchain
precedence.

In `@pkg/toolchain/pr_artifact.go`:
- Around line 637-640: In the block that constructs the error for
ErrNoWorkflowRunFound (the chain calling WithExplanationf("No completed CI run
found for PR #%d") and subsequent WithHint calls), remove the misleading
WithHint("CI build may be failing on this PR") because a failed run would still
be a completed run; alternatively move that hint into the ErrNoArtifactFound
error branch where a failing build is a plausible cause. Update the code that
builds the error (the chained WithExplanationf/WithHint calls) to either drop
that hint or add it to the ErrNoArtifactFound branch so the hints accurately
match the error condition.

---

Nitpick comments:
In `@pkg/dependencies/environment.go`:
- Around line 243-251: The toolchain dirs are being built from env.resolved but
PATH() is created by buildPATH(...), causing inconsistent prefixes; instead
derive env.dirs from the same ordered PATH string used by buildPATH so
ToolchainDirs()/PrependToPath() match EnvVars()/PATH(). Replace the loop that
populates env.dirs from env.resolved with logic that splits the built PATH (the
value assigned to env.path or the string returned by buildPATH), iterate the
split list in order, append each unique directory (use a seen map) into env.dirs
to preserve order and deduplicate; keep the rest of resolveBinaryPaths()
behavior unchanged so failures stay skipped.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e306cdaf-e055-4065-b181-780230c85efd

📥 Commits

Reviewing files that changed from the base of the PR and between 1facf65 and f0adfcf.

📒 Files selected for processing (3)
  • internal/exec/terraform.go
  • pkg/dependencies/environment.go
  • pkg/toolchain/pr_artifact.go

Replace hardcoded Unix paths, PATH separators, and "sh" lookups with
filepath.Join, os.PathListSeparator, and os.Args[0] so tests pass on
Windows.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The 50ms delays were too aggressive and caused terraform state file
locking errors on Windows CI. Restore the original 200/500/1000ms
retry delays that give Windows enough time to release file locks
between sequential terraform operations.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes Mar 12, 2026
Add ToolProvisioner interface and inject a mockgen-generated mock into
the test so it no longer depends on real network installs. The test now
asserts PATH() and Resolve() equal exact expected values.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Version constraints like "^1.10.0" were passed directly to the download
URL, producing 404s (e.g., github.com/.../releases/download/^1.10.0/...).

Add VersionLister interface and resolveConstraints() to the dependencies
Installer. Before building tool specs, any constraint is resolved to the
highest matching release via the GitHub releases API, then the concrete
version flows through to install, PATH building, and binary lookup.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The GetAvailableVersions network call had no user feedback, making the
CLI appear frozen. Wrap each constraint resolution in a spinner that
shows progress and the resolved version on completion.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Two fixes:
- resolveBinaryPaths now converts relative paths to absolute before
  storing in the resolved map, preventing "no such file" errors when
  the install path is relative (e.g., .tools).
- examples/toolchain sets command: tofu since the example uses OpenTofu,
  not HashiCorp Terraform.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Before this change, every `atmos terraform plan` with a constraint like
`^1.10.0` hit the GitHub API to resolve it, even when a matching version
was already installed locally. This added seconds of latency per run.

Now resolveConstraints checks locally installed versions first via
ListInstalledVersions (a fast directory scan). The network call only
happens when no installed version satisfies the constraint.

Also adds missing `variable "stage"` to the toolchain example mock
component to suppress the OpenTofu undeclared variable warning.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Display an info message when a semver constraint is resolved from the
local cache, so users see which concrete version is being used without
needing a network call (e.g., "Using opentofu 1.11.5 (satisfies ^1.10.0)").

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Verify the toolchain example stack configuration loads correctly:
- describe component mock in dev stack
- component-level tool dependencies (opentofu) present in output
- terraform command set to tofu
- describe stacks produces valid JSON

These tests validate config parsing without requiring tool installation
or network access, making them safe for CI.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Glamour's GFM linkify interprets owner/repo@version as email autolinks
(e.g., [email protected] → mailto:), stripping tool names from output. The custom
StrictLinkifyExtension works at goldmark level but not through glamour's
rendering pipeline.

Fix by wrapping tool specs in backticks (code spans are never autolinked).
Also change skip messages from ui.Successf to ui.Info since skipping is
informational, not a success.

Add regression tests at both levels:
- goldmark: extensions_test.go (passes, confirming extension works)
- glamour: formatter_test.go (catches the rendering pipeline bug)

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

Tools installed via component-level dependencies.tools in stack YAML
are not tracked in .tool-versions and were invisible to uninstall.
The --all flag scans the install directory and removes everything found,
including tools installed through dependency resolution.

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

Transient network errors (stream cancel, connection reset, timeouts)
during GetAvailableVersions now retry up to 3 times with exponential
backoff. Uses hybrid approach: gates on registry.ErrHTTPRequest sentinel
to avoid retrying non-HTTP errors, then string-matches for transient
patterns.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@osterman Erik Osterman (Cloud Posse) (osterman) changed the title fix: resolve toolchain executables in template functions fix: toolchain path resolution, constraint solving, and uninstall improvements Mar 13, 2026
The --all flag addition gave UninstallCommandProvider a StandardParser,
but the test still expected GetFlagsBuilder() to return nil.

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

Covers ~90 previously untested lines in pkg/dependencies to bring patch
coverage above 80%. Adds tests for isConstraint, highestMatch,
isRetryableHTTPError, findInstalledMatch, resolveConstraints,
resolveOneConstraint, fetchAvailableVersionsWithRetry, PrependToPath,
ToolchainDirs, and resolveBinaryPaths relative-to-absolute conversion.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit bbac3f8 into main Mar 13, 2026
56 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the osterman/fix-tofu-path branch March 13, 2026 21:56
@github-actions

Copy link
Copy Markdown

These changes were released in v1.210.0-rc.0.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.210.0-test.25.

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.

2 participants