Skip to content

[Hooks] PreToolUse omits the effective workdir for exec_command and shell_command #37251

Closed

Description

@mmmprod

What version of Codex CLI is running?

codex-cli 0.146.1, which is the latest stable release at the time of filing.

What subscription do you have?

Not relevant to this local CLI hook-dispatch behavior.

Which model were you using?

Not model-dependent. The behavior is in the CLI tool and hook dispatch paths.

What platform is your computer?

Linux 6.18.33.2-microsoft-standard-WSL2 x86_64 x86_64

Codex doctor report

Not included because this is deterministic local hook payload behavior and is also visible in the tagged release and current main source.

What issue are you seeing?

exec_command and shell_command accept a per-call workdir and correctly use it as the command process cwd. However, their PreToolUse hook payload contains only the command. The top-level hook cwd is taken from the turn context, not from the resolved per-call execution cwd.

As a result, a PreToolUse policy hook cannot distinguish these two calls:

  • the same relative command executed in the session worktree;
  • the same relative command executed in another allowed directory or Git worktree.

The command runs in the requested workdir, but the hook sees the session cwd plus a tool_input containing only the command.

This is not a sandbox escape: the sandbox still enforces its configured writable roots. It is a hook contract gap that prevents correct policy enforcement and audit attribution inside those allowed roots, especially in multi-worktree repositories.

Current main still has the mismatch:

  • exec_command resolves environment_args.workdir into the actual cwd:
    let native_environment_cwd = turn_environment.cwd().clone();
    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),
    )
    .map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?;
  • its PreToolUse payload preserves only args.cmd:
    fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option<PreToolUsePayload> {
    let ToolPayload::Function { arguments } = &invocation.payload else {
    return None;
    };
    parse_arguments::<ExecCommandArgs>(arguments)
    .ok()
    .map(|args| PreToolUsePayload {
    tool_name: HookToolName::bash(),
    tool_input: serde_json::json!({ "command": args.cmd }),
    })
  • classic shell_command also preserves only command:
    fn pre_tool_use_payload(&self, invocation: &ToolInvocation) -> Option<PreToolUsePayload> {
    shell_command_payload_command(&invocation.payload).map(|command| PreToolUsePayload {
    tool_name: HookToolName::bash(),
    tool_input: serde_json::json!({ "command": command }),
    })
  • hook_runtime fills request.cwd from turn_context.cwd:
    pub(crate) async fn run_pre_tool_use_hooks(
    sess: &Arc<Session>,
    turn_context: &Arc<TurnContext>,
    tool_use_id: String,
    tool_name: &HookToolName,
    tool_input: &Value,
    ) -> PreToolUseHookResult {
    let request = PreToolUseRequest {
    session_id: sess.session_id().into(),
    turn_id: turn_context.sub_id.clone(),
    subagent: thread_spawn_subagent_hook_context(sess, turn_context),
    #[allow(deprecated)]
    cwd: turn_context.cwd.clone(),
    transcript_path: sess.hook_transcript_path().await,
    model: turn_context.model_info.slug.clone(),
    permission_mode: hook_permission_mode(turn_context),
    tool_name: tool_name.name().to_string(),
    matcher_aliases: tool_name.matcher_aliases().to_vec(),
    tool_use_id,
    tool_input: tool_input.clone(),
    };

What steps can reproduce the bug?

  1. Configure a PreToolUse hook for Bash that records its stdin JSON.
  2. Start Codex in repository or worktree A.
  3. Ask Codex to invoke exec_command with:
    • cmd set to a relative write such as mkdir hook-cwd-probe
    • workdir set to another sandbox-allowed directory or worktree B
  4. Observe that the directory is created under B.
  5. Inspect the hook event:
    • cwd still identifies the turn/session directory A;
    • tool_input is only {"command":"mkdir hook-cwd-probe"};
    • the effective workdir B is absent.
  6. Repeat the same command with workdir A. The hook cannot distinguish the effective targets from the supplied cwd and tool_input.

The same contract loss exists in both unified exec and classic shell handlers.

What is the expected behavior?

Before execution, hooks should receive the effective resolved cwd of the command.

Either of these contracts would make enforcement possible:

  1. set the top-level PreToolUse cwd to the resolved per-call execution cwd for shell-like tools; or
  2. preserve workdir in tool_input and document that top-level cwd remains the turn cwd.

The behavior should be consistent for exec_command and shell_command, with regression coverage proving that two identical relative commands using different workdirs produce distinguishable hook inputs.

Additional information

Related but not duplicate:

A local bridge cannot reconstruct the missing value reliably. Blanket-blocking relative commands or temporary directories would break valid development and test workflows without fixing the contract.

Activity

  1. added
    bug
    CLI
    hooks
    on Aug 6, 2026
  2. CheckPickerUpper commented on Aug 10, 2026

    @CheckPickerUpper

    This is blocking an external policy consumer in oja-gamez/ai-lab (#939): https://github.com/oja-gamez/ai-lab/issues/939

    The consumer receives payload.cwd and derives CommandIntent.workingDirectory and projectRoot; it intentionally refuses when cwd is absent rather than guessing a checkout. A Codex session launched in canonical checkout A with exec_command(workdir=B) currently runs in B but sends PreToolUse cwd=A, so the hook blocks legitimate declared-worktree writes and cannot safely distinguish undeclared B.

    For this consumer, the safest contract is an explicit effective tool_cwd (or equivalent) field alongside the existing hook-process cwd, preserving absent-vs-explicit semantics. Acceptance is three real client cases: canonical A -> refusal; declared linked worktree B -> allow; undeclared linked worktree C -> refusal, with the exact hook payload and derived projectRoot captured.

  3. avivcarmis-bb commented on Oct 15, 2026

    @avivcarmis-bb

    This is critical for monitoring and enforcing the scope of an agent's command execution. An agent can execute a command in a directory outside the session/project scope without the hook knowing that directory. A hook can still inspect or block the command, but it cannot reliably apply directory-scoped monitoring or protection. Treating the session cwd as the execution directory is wrong.

    Also, the existing cwd value is very helpful. ideally, introducing the command worktree does not replace the agent workspace dir.

  4. dcostenco commented on Oct 23, 2026

    @dcostenco

    Additional confirmation on macOS 26.4 arm64 with the VSCode-bundled codex-cli 0.162.0-alpha.17.2.

    A Bash PreToolUse consumer reported that the received tool_input contained only the command field, even though the exec_command invocation supplied an explicit workdir different from the session checkout. This blocked a harmless relative Python script invocation before execution because the consumer could not safely resolve the script against the selected execution directory. That diagnostic establishes the missing metadata; the refused invocation alone does not establish the process cwd.

    The same mismatch is visible in upstream source at de06fd0be4f465bc28c3111bdadaabda5dfdebcd:

    The actionable contract would be an additive effective execution-directory field, leaving the documented session cwd intact. It should come from the same selected-executor/directory resolution as execution and distinguish a host-local directory from a remote executor path. Useful regression cases include a selected environment whose cwd differs from the session cwd, explicit absolute/relative overrides, and empty or omitted workdir.

    This confirmation concerns the exec_command PreToolUse path. No sandbox escape or live runtime fix is claimed.

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

    CLIbughooks

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions