Skip to content

unified-exec exec_command: Bash PreToolUse tool_input drops the honored per-call workdir, so hooks cannot attribute the execution root #33986

Closed as duplicate

Description

@duhlink

What version of Codex are you using?

codex-cli 0.144.5 (Homebrew, macOS arm64). The behavior is unchanged on current main as of 2026-07-18.

What platform is your computer?

macOS (Apple Silicon). The projection lives in codex-rs/core, so this is platform-independent.

What issue are you seeing?

When the model calls unified-exec exec_command with a per-call workdir, the Bash PreToolUse hook payload drops that field, even though execution honors it.

In codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs, ExecCommandHandler::pre_tool_use_payload parses ExecCommandArgs and projects only the command:

parse_arguments::<ExecCommandArgs>(arguments)
    .ok()
    .map(|args| PreToolUsePayload {
        tool_name: HookToolName::bash(),
        tool_input: serde_json::json!({ "command": args.cmd }),
    })

while handle_call in the same handler separately parses ExecCommandEnvironmentArgs, resolves workdir against the selected environment's cwd, and executes there:

let cwd = environment_args
    .workdir
    .as_deref()
    .filter(|workdir| !workdir.is_empty())
    .map_or_else(
        || Ok(native_environment_cwd.clone()),
        |workdir| native_environment_cwd.join(workdir),
    )

So two exec_command calls with identical cmd but different workdir values deliver byte-identical tool_input to the hook while running in different directories. The hook envelope's top-level cwd is the session working directory (per the Hooks docs), not the per-call execution root, so a hook cannot reconstruct where the command will actually run. The command-only projection is regression-locked by exec_command_pre_tool_use_payload_uses_raw_command in codex-rs/core/src/tools/handlers/unified_exec_tests.rs.

Authorization impact: in multi-worktree repositories where a PreToolUse hook enforces "mutations happen only in the assigned task worktree", a relative mutation (e.g. git add ., a formatter -w run) with workdir=<task worktree> is observationally identical to the same command running in the primary checkout or a foreign directory. A strict hook must fail closed and deny legitimate worktree work; a permissive hook silently misattributes the execution root and fails open.

I verified this with paired read-only probes on 0.144.5: two exec_command calls, both cmd: "pwd", one with the task-worktree workdir and one with the primary-checkout workdir. Both hook deliveries carried tool_input whose SHA-256 matches canonical {"command":"pwd"} exactly (proving no other distinguishing field was present), while the captured outputs showed the two distinct physical directories.

What steps can reproduce the bug?

  1. Configure a project PreToolUse hook for bash that logs the raw tool_input it receives.
  2. In a session, have the model run exec_command with cmd: "pwd" and no workdir, then again with an explicit workdir pointing at a subdirectory or another worktree.
  3. Observe that both hook deliveries carry identical tool_input ({"command":"pwd"}) and identical top-level cwd, while the tool outputs show different directories.

What is the expected behavior?

Bash PreToolUse tool_input should carry a trustworthy per-call workdir. Three properties matter for authorization-grade consumers:

  1. Explicit vs absent stays distinguishable. Include workdir only when the call supplied a non-empty one; omit it otherwise, so hooks can tell "no per-call workdir — environment cwd applies" apart from "explicit workdir".
  2. Raw vs resolved semantics are defined. The raw requested workdir may be relative and is resolved against the selected environment's cwd — which is not necessarily the session cwd the hook envelope carries. Exposing the effective resolved cwd (the value handle_call computes) is the stronger contract; if only the raw field is exposed, please document which base it resolves against.
  3. Read-only is sufficient. Hook input rewriting currently only rewrites command (with_updated_hook_input), so adding the field does not need to grant hooks a workdir-rewrite capability.

Minimal seam sketch for the raw-field variant (the resolved-cwd variant would instead thread the selected environment cwd into the payload — either works for consumers as long as the semantics are documented):

fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option<PreToolUsePayload> {
    let ToolPayload::Function { arguments } = &invocation.payload else {
        return None;
    };
    let args = parse_arguments::<ExecCommandArgs>(arguments).ok()?;
    let workdir = parse_arguments::<ExecCommandEnvironmentArgs>(arguments)
        .ok()
        .and_then(|env| env.workdir)
        .filter(|workdir| !workdir.is_empty());
    let mut tool_input = serde_json::json!({ "command": args.cmd });
    if let Some(workdir) = workdir {
        tool_input["workdir"] = serde_json::Value::String(workdir);
    }
    Some(PreToolUsePayload {
        tool_name: HookToolName::bash(),
        tool_input,
    })
}

plus updating exec_command_pre_tool_use_payload_uses_raw_command and adding a case asserting the field is omitted when no workdir was supplied.

Related

#20879 reports the same class of gap for native apply_patch (no per-call workdir context for hooks). This issue is specifically about unified-exec exec_command, where a per-call workdir already exists and is honored by execution but is dropped from the hook projection.

Activity

  1. added
    bug
    CLI
    hooks
    exec
    on Jul 18, 2026
  2. josh87523 commented on Aug 9, 2026

    @josh87523

    Independent reproduction and a tested patch branch are available.

    I reproduced this on the ChatGPT/Codex host (26.803.41515): calls supplied an explicit per-call workdir, but the Bash PreToolUse payload still exposed only command while the top-level cwd remained the session directory. I observed the same contract loss across relative Git fetch, add, worktree, init, and remote-read shapes.

    I implemented the raw-field variant for unified exec on base 3aae5d885bac39c1262491aa3fd100dfd8b3919f:

    Validation completed:

    • cargo fmt --all -- --check
      • cargo check -p codex-core --tests
        • 5 targeted nextest cases covering PreToolUse, synchronous PostToolUse, asynchronous write_stdin, preservation of the initial workdir, and parallel sessions
          I checked the current contribution policy and understand external PRs are invitation-only. I am sharing the branch and test evidence here for maintainer evaluation. If this raw-field contract aligns with the intended solution, the branch is ready to rebase or submit if invited.
  3. josh87523 commented on Aug 12, 2026

    @josh87523

    Update: I rebased the tested workdir transport patch onto current openai/codex main and resolved the only source conflict without replacing the new implicit-skill invocation path.

    Current branch and commit:

    Current-main validation:

    • cargo fmt --all -- --check
    • cargo test -p codex-core exec_command_pre_tool_use_payload_includes_workdir --no-fail-fast
    • cargo test -p codex-core write_stdin_completion_preserves_initial_hook_workdir --no-fail-fast

    Both targeted lifecycle tests passed. The contract remains unchanged: the raw non-empty exec_command.workdir is observational execution context, not authorization; it is included in Bash PreToolUse and preserved through async write_stdin completion for PostToolUse. git -C remains the explicit Git target override. No hook policy or guard behavior is relaxed.

    I am not opening an unsolicited PR because the repository contribution policy remains invitation-only. The current-main branch is ready if a maintainer wants to adopt it or invite a PR.

  4. H5H-Stoven-One commented on Sep 10, 2026

    @H5H-Stoven-One

    The command-only hook payload remains present in 0.154.0 and upstream main at 6baa076. Our native checks confirm that a guard requiring execution-directory metadata blocks both ordinary pwd and pwd with explicit workdir. We need a documented, host-resolved execution directory, including when workdir is omitted or relative, while preserving session cwd separately. Is a maintainer-supported contract planned?

  5. abhinav-wingback commented on Sep 24, 2026

    @abhinav-wingback

    Adding data from a second consumer: an endpoint DLP hook that scans the files a shell command is about to read. Two things make this more pressing than the issue body suggests.

    1. In code mode there is no workaround. For a direct exec_command call, a hook can recover workdir today. When the hook runs, the function_call line whose call_id equals tool_use_id is already in the rollout at transcript_path: handle_output_item_done records the call before it queues the tool, and hook_transcript_path() calls persist() on the same writer first.

    In code mode that route is gone. The current model catalog sets tool_mode: code_mode_only for most models, and commands run as tools.exec_command({cmd, workdir}) inside an exec script. Each nested call reaches PreToolUse with a tool_use_id minted in code_mode/delegate.rs (exec-<uuid>), and no rollout line carries that id before the command runs. Only the script source is there.

    Reproduced with codex-cli 0.155.0-alpha.9.2 and features.code_mode_only=true. tool_input is {"command":"cat config.env"}, the hook's cwd is the session root, and the rollout has no line for the id. Nested calls go through the same ExecCommandHandler::pre_tool_use_payload, so the fix proposed above covers them too.

    2. A resolved execution directory is the better contract (point 2 in the issue). With only the raw value, every hook has to reimplement AbsolutePathBuf::join: ~ expansion, lexical .., and on Windows the drive rules in path_with_base. There, D:x from C:\repo is D:\repo\x, while Node's path.resolve uses D:'s own current directory. A hook that gets this wrong looks in a different directory from the one Codex runs in.

    This is still present on main at a16381c (2026-09-24). The {"command": …}-only projection goes back to 0.124.0; the shell and shell_command tools behaved the same way before they were removed.

  6. alopezari commented on Sep 30, 2026

    @alopezari

    Still present in codex-cli 0.159.0 (macOS arm64).

    I captured the payload through a trusted PreToolUse hook. The model called exec_command in code mode with workdir set to a subdirectory. The hook received {"command": "git status --short"} and the session's cwd, while the rollout's CommandExecution item shows the command ran in the subdirectory.

    Another consumer this breaks: hooks that allow a command based on the state of the repository it runs in. For example, a hook that allows gh pr create only when a local check has passed for that repository's current changes (in our case, a marker file written after tests and review). The hook reads the repository from cwd, so a PR opened from another repository with workdir is judged by the session's repository and passes. Our only safe workaround is to deny PR commands that don't cd to an absolute path first.

    A documented, host-resolved execution directory in the payload, as others asked for above, would let us drop that workaround.

  7. coconutbird commented on Oct 3, 2026

    @coconutbird

    Still reproduces on codex-cli 0.160.0 (Linux x64 and Windows x64).

    Repro: codex exec against a scripted Responses endpoint whose model calls exec_command with {"cmd":"rg needle main.rs","workdir":"src"}. The plugin PreToolUse hook receives:

    {"cwd":"/tmp/.../work","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rg needle main.rs"},"tool_use_id":"call_semctx_0", ...}

    workdir is absent and cwd is the session root, so a hook cannot tell that main.rs resolves to src/main.rs, or that a call runs in a different repository. The rollout transcript already contains the full arguments (including workdir) when the hook fires, so the data is available; it is only dropped from the projection.

    Downstream impact: semctl classifies shell searches by scope (single file vs. repository-wide) from tool_input + cwd, and misclassifies these calls. Including workdir in tool_input (or resolving it into the payload cwd for that call) would fix it.

  8. kaimallea commented on Oct 9, 2026

    @kaimallea

    Also affects PostToolUse on codex-cli 0.162.0 (macOS arm64), and current main at c9e0fff builds Bash hook input as {"command": ...} only (context.rs#L432-L436).

    Our use case is telemetry. A PostToolUse hook records the git commit of the repository a command ran in. The model ran pwd via exec_command with workdir set to a second repository, and the output shows it ran there. The hook received only the session cwd, so the record was filed under the session repository's commit. Nothing in the record shows it is wrong.

    Passing the resolved execution directory to PostToolUse would fix it for observational hooks like ours.

  9. etraut-openai commented on Oct 12, 2026

    @etraut-openai
    Contributor

    (response from codex)

    Closing as a duplicate of #32360. Both reports track the Bash hook payload losing the execution directory even though the shell call honors workdir. Please keep the recent Linux/Windows/code-mode evidence and the PostToolUse 0.162.0 observation from this issue in view when working on #32360; hooks need the effective execution location, not just the session cwd. This remains an open problem.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugexechooks

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions