Skip to content

[BUG] [v0.0.7] CommandBuilder::build() places env vars before 'cd' — variables are scoped to cd instead of the intended command (parse_command.rs:632-638) #18536

Description

@echoforge2200

Bug Report

Project: cortex

Description

In CommandBuilder::build() (parse_command.rs lines 628–650), environment variable assignments are emitted before the cd subcommand when a working_dir is set. In POSIX shell, a bare VAR=value cmd assignment is scoped only to that single command. This means the env var is passed to cd, not to the intended command that follows the &&.

Error Message

No panic — silently wrong behavior: the env var is never visible to the actual command.

Debug Logs

Concrete trace for:

CommandBuilder::new("git")
    .env("GIT_SSH_COMMAND", "ssh -i /key")
    .working_dir("/repo")
    .arg("fetch")
    .build()

Generated shell string:

GIT_SSH_COMMAND='ssh -i /key' cd '/repo' && git fetch

In POSIX shell, GIT_SSH_COMMAND='ssh -i /key' cd '/repo' sets GIT_SSH_COMMAND only for the cd builtin, not for git fetch. The git fetch command runs without GIT_SSH_COMMAND set.

The correct output should be:

cd '/repo' && GIT_SSH_COMMAND='ssh -i /key' git fetch

The relevant code:

// parse_command.rs:631-643
// Add environment variables
for (k, v) in &self.env {
    parts.push(format!("{}={}", k, shell_escape(v)));  // ← emitted first
}

// Add cd if working directory is set
if let Some(ref wd) = self.working_dir {
    parts.push(format!("cd {} &&", shell_escape(&wd.display().to_string())));  // ← cd comes after env vars
}

// Add command
parts.push(shell_escape(&self.executable));  // ← actual command comes last

The env var assignments must be placed immediately before the actual command, not before the cd.

System Information

OS: Linux (Ubuntu)
Affected file: src/cortex-engine/src/parse_command.rs
Lines: 628-650 (CommandBuilder::build)

Steps to Reproduce

  1. Create a CommandBuilder with both .env() and .working_dir() set
  2. Call .build()
  3. Observe that the generated shell string has env vars before cd, not before the actual command
  4. Run the generated string in a shell — the env var is not visible to the intended command

Expected Behavior

Env var assignments should appear immediately before the actual command:

cd '/repo' && FOO=bar git fetch

Actual Behavior

Env var assignments appear before cd, scoping them to cd only:

FOO=bar cd '/repo' && git fetch

Additional Context

This affects any caller that uses both .env() and .working_dir() on a CommandBuilder. The env var is silently dropped from the intended command's environment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions