Skip to content

PreToolUse drops exec_command workdir and reports the turn cwd instead of the effective tool cwd #32360

Open

Description

@TTC-DEV-PUBLIC

What version of Codex CLI is running?

codex-cli 0.144.1. The bug is also present on main at 5c19155cbd93bfa099016e7487259f61669823ff.

What platform is your computer?

macOS 15.7.3, arm64. The payload loss is platform-independent.

What issue are you seeing?

exec_command honors its workdir when executing a command, but its PreToolUse hook receives only the turn/session cwd and { "command": ... }. The requested and resolved command cwd are both absent from hook stdin.

Example tool call while the Codex turn cwd is /Users/me:

{
  "cmd": "git push -u origin main",
  "workdir": "/Users/me/knowledge"
}

Relevant fields observed by a PreToolUse hook:

{
  "cwd": "/Users/me",
  "tool_name": "Bash",
  "tool_input": {
    "command": "git push -u origin main"
  }
}

A repository-aware policy hook therefore evaluates /Users/me rather than /Users/me/knowledge. A fail-closed hook blocks a legitimate operation as a false positive; a hook that trusts the reported cwd can apply policy to the wrong repository and fail open.

Embedding the repository in the command (git -C /Users/me/knowledge push ...) makes the call classifiable, but that is only a workaround.

Source trace

  1. workdir is a first-class tool argument and defaults to the turn cwd: shell_spec.rs#L26-L36.
  2. The unified exec handler resolves environment_id/workdir for actual execution: exec_command.rs#L131-L150.
  3. Its pre-hook payload independently parses only ExecCommandArgs and emits { "command": args.cmd }, dropping workdir: exec_command.rs#L408-L418.
  4. Classic shell_command has the same split: it resolves workdir for execution (shell_command.rs#L184-L213) but emits a command-only pre-hook payload (shell_command.rs#L249-L253).
  5. run_pre_tool_use_hooks always constructs the request with turn_context.cwd: hook_runtime.rs#L163-L183.
  6. That cwd is serialized into hook stdin and used as the hook process cwd: pre_tool_use.rs#L105-L110, pre_tool_use.rs#L164-L185.

Expected behavior

A PreToolUse policy hook must be able to determine the same effective cwd that the pending shell-like tool will use, including relative workdir resolution against the selected environment cwd.

Please preserve the stable Bash tool_input == { "command": ... } shape and expose the resolved tool cwd separately, for example as an optional top-level tool_cwd. Keeping existing top-level cwd as the hook process/turn cwd is safer than repurposing it: today it also controls where relative hook commands are spawned, and a foreign/remote environment path may not be a valid local hook-process cwd.

Suggested contract:

  • cwd: unchanged local cwd used to launch the hook command.
  • tool_cwd: normalized effective cwd of the pending tool execution.
  • tool_input: unchanged command-only Bash contract.
  • Policy hooks use tool_cwd ?? cwd.

Suggested implementation and acceptance tests

  • Resolve tool_cwd through the same path used by actual execution for both exec_command and shell_command.
  • Add optional tool_cwd to the hook request/input schema without changing hook process cwd.
  • Do not swallow invalid workdir/environment_id resolution in the security-hook path.
  • Cover absent, absolute, and relative workdir; selected environments; denying hooks; updatedInput command rewrites; invalid paths; and remote/foreign environment semantics.
  • Assert that the hook-observed tool_cwd and command-observed pwd are identical.

Related but not duplicate

This report is specifically about shell-like tools already having workdir for execution but losing it at the PreToolUse boundary.

Activity

  1. added
    bug
    CLI
    hooks
    tool-calls
    on Jul 11, 2026
  2. ctoth commented on Jul 13, 2026

    @ctoth

    Confirmed on Windows x86_64 with Codex CLI 0.144.3.

    I reproduced this with the turn cwd set to C:\\work\\barn and an exec_command call whose workdir was C:\\work\\ward and whose command was git status --short. The PreToolUse hook received:

    {
      "cwd": "C:\\\\work\\\\barn",
      "hook_event_name": "PreToolUse",
      "tool_name": "Bash",
      "tool_input": { "command": "git status --short" }
    }

    The hook process cwd was also the turn cwd. This caused a real fail-closed false positive in Ward, a repository-aware policy hook: Ward had correctly adopted paths in the target repository, but Codex gave it neither the effective tool cwd nor the requested workdir, so it evaluated the operation against the wrong repository. Rebuilding and reinstalling Ward cannot compensate for information absent from the hook contract.

    I also confirmed the mismatch in current main at 8acaec73b6: exec_command resolves args.workdir for execution, while pre_tool_use_payload serializes only args.cmd, and the hook request uses the turn cwd. So the report remains reproducible on a newer release and appears platform-independent.

  3. mtmitchel commented on Jul 20, 2026

    @mtmitchel

    Confirmed on codex-cli 0.144.6 running on Fedora 43 x86_64.

    I use an unofficial Linux wrapper for the Codex app, so I am not claiming reproduction on an officially supported Linux Desktop release. However, the affected execution path uses the local Codex CLI/app-server, and the observed behavior matches this issue: exec_command honors its per-command workdir, while PreToolUse receives the session cwd and a command-only tool_input.

    This prevents repository-aware hooks from reliably determining which repository a command will modify. The proposed resolved tool_cwd field would address my use case.

  4. harr1sz commented on Sep 11, 2026

    @harr1sz

    I hit this while integrating a repository policy plugin with Codex CLI 0.153.4 on macOS. The missing information extends beyond workdir: hooks also cannot inspect the resolved shell arguments, effective login and tty values, or selected execution environment.

    The same projection is still present in main at 624ccf794703e2d84e748fc3ef547d6191a8c0a4: exec_command emits only command, and the hook request takes cwd from the turn. I checked that source snapshot; my runtime tests used 0.153.4.

    In an isolated real CLI run, a normally installed and trusted plugin had to reject even cat marker.txt because it could not verify the launch context. The call explicitly supplied its working directory, shell: "/bin/sh", login: false, and tty: false. These values were unavailable to the hook. The command was denied before execution.

    I tested a local prototype based on rust-v0.153.4. It prepares the invocation once before running hooks and reuses that prepared invocation for execution. An optional top-level execution_context exposes:

    {
      "kind": "exec_command",
      "argv": ["/bin/sh", "-c", "cat marker.txt"],
      "cwd": "/absolute/path/to/selected/directory",
      "login": false,
      "tty": false,
      "environment_id": "selected-environment-id",
      "is_remote": false,
      "shell_mode": "direct"
    }

    This is an example of the proposed contract. The host supplies the values after resolving the selected environment and shell; copying the requested arguments into hook input would not establish which settings execution actually uses. argv describes the resolved shell invocation before existing shell snapshots, platform wrappers, and sandbox wrappers. It does not represent the final OS process argument list.

    The prototype preserves the existing hook-process cwd and command-only tool_input. A command-only updatedInput rewrite changes the command while retaining the prepared launch settings and parsed permission arguments. Execution still uses Codex's existing process manager, approvals, and sandbox. The existing multi-hook rewrite behavior is unchanged; other hooks do not re-review the final rewritten command.

    Local validation passed 176 Hooks tests, 4 prepared-invocation tests, 16 core Hook integration tests, 32 registry/unified-exec unit tests, and 18 execution/permission integration tests. Eight additional scenarios used real CLI processes with a local deterministic Responses fixture and the installed plugin. The patched CLI read the expected directory's marker, the plugin denied mismatched launch settings before execution, and Codex's outer read-only sandbox still blocked a runner that needed to write. The same plugin rejected the read on unmodified 0.153.4 because metadata was missing. just fmt and scoped just fix also passed.

    The prototype covers exec_command. I have not validated it across the Desktop host matrix or extended it to classic shell_command. These results support resolving the launch settings once and exposing them separately from the model's tool input.

  5. soycarts commented on Sep 18, 2026

    @soycarts

    Reproduced on codex-cli 0.152.1, macOS arm64, with features.hooks=true and a PreToolUse command hook matching Bash|apply_patch that appends its stdin to a file.

    Top-level keys on every PreToolUse event at this version:

    cwd, hook_event_name, model, permission_mode, session_id,
    tool_input, tool_name, tool_use_id, transcript_path, turn_id
    

    tool_input keys on every Bash event: command, and nothing else. A call the model directed at a nested subdirectory landed its file there, while the event's cwd and the hook process's own cwd both stayed at the session root. A patch sent as an apply_patch heredoc through unified execution arrives as tool_name: "Bash" with the whole heredoc in tool_input.command, again with no directory of its own, and lands in the nested directory.

    Impact on my side: the adapter I maintain (an approval layer that classifies a command against a policy and asks a human for the classes that need one) now refuses every native Bash pre-event unconditionally, because the same command string means different things in different directories and the payload cannot say which. Either of the shapes proposed above (tool_cwd alongside the existing cwd, or a cwd inside tool_input) would let it decide instead.

    Sanitized captures (session, turn and tool-use ids replaced by stable pseudonyms; every uncontrolled string redacted) and the runbook that produced them are public:

  6. CtrlCarlitos commented on Sep 25, 2026

    @CtrlCarlitos

    Windows/WSL reproduction and execution-context contract proposal

    Adding cross-platform evidence and a proposal here rather than opening a duplicate. Related shell report: #44836. The prepared-invocation approach described above is relevant; I have not independently tested that prototype.

    Recorded reproduction

    Our observer-only probe at e45b278 drives native Codex with a local deterministic Responses fixture, disposable hook configuration, a read-only sandbox, and fixed echo/pwd commands. It requires no model service or credentials and does not invoke Guardrail.

    Previously recorded results on 2026-09-25, in both direct and code modes:

    Runtime Pre-hooks per run Command execution
    Native Windows, Codex 0.155.1 6 All 6 rejected by native policy
    WSL/Linux, Codex 0.154.0 6 All 6 executed, including alternate workdir

    In both environments the hook input contained only tool_input.command, and envelope cwd remained the session root. WSL output demonstrated execution in the alternate directory (including spaces and Unicode). The Windows result demonstrates dispatch, not execution or the effective execution directory. Versions differ, so this is not an OS-only comparison. Requested shell overrides are not assumed to have been honored.

    Recorded findings and limitations.

    From that checkout, with native Codex and Python in each OS:

    python3 -B test/smoke/codex_execution_contract.py --require-context
    python3 -B test/smoke/codex_execution_contract.py --require-context --code-mode

    Use python on Windows. The probe prints retained artifact paths and records advertised tool schemas, hook payloads and tool outputs. --require-context deliberately cannot succeed until a host-owned schema has been reviewed; a nonzero result alone is not proof of a Codex regression. These are recorded observations, not a claim about newer versions or complete enforcement.

    Proposed contract

    Please expose additive, versioned, host-resolved execution context outside model-controlled tool_input, while preserving existing session cwd and command-only input compatibility:

    • Actual resolved interpreter and exact ordered launch arguments, including login/profile and command-mode flags. Distinguish logical shell invocation from platform/sandbox wrappers; define Windows command-line serialization rather than treating a display string as launch data.
    • Effective per-command cwd and its execution-environment/path namespace. Native WSL and Windows-to-WSL interop must remain distinct.
    • Host-enforced binding between this context and the invocation actually launched. Requested arguments, OS-based dialect guesses, or an ID/hash alone are insufficient. Unsupported context should be explicit.

    No full environment or credential dump is needed. Startup files, inherited state, filesystem replacement races and sandbox guarantees require documented limits; these fields alone do not establish confinement.

    Validate the final plan after rewrites

    The documented hook behavior permits concurrent matching hooks and updatedInput command rewrites. The prototype described above explicitly leaves other hooks without a review of the final rewritten command. Resolving launch settings once addresses the metadata problem, but approving the original command must not authorize an unrelated rewrite.

    Please consider an opt-in final, read-only validation phase after rewrites and host normalization, or an equivalent guarantee. All validators should see the same immutable launch plan; no further rewrite should be accepted in that phase. A later command, shell, argv, environment or cwd change must invalidate prior validation, with bounded revalidation or rejection rather than rewrite loops. Required-validator errors/timeouts should have explicit fail-closed semantics (related: #41979).

    Acceptance tests should cover native Windows and Linux/WSL, direct and nested calls, supported interpreters/flags, cwd overrides, spaces/Unicode, model-forged context, concurrent/conflicting rewrites, stale plans and validator failure. An allowed command must actually execute and a denied one must not; hook dispatch or a native sandbox rejection alone is insufficient.

    The schema and event naming are negotiable. The essential requirement is that the policy validates the same host-owned execution plan the executor consumes.

  7. CtrlCarlitos commented on Sep 30, 2026

    @CtrlCarlitos

    Update: still present on codex-cli 0.159.0 (Windows)

    Re-measured 2026-09-30 on Windows 11 with codex-cli 0.159.0, PowerShell 7 and codex exec.

    • What the model sent. The session rollout shows the code-mode call tools.exec_command({cmd:"echo probe2", workdir:"C:\\Users\\carlitos\\Documents", …}).
    • What the hook got. The PreToolUse payload's tool_input had a single key, command. Our hook records the key names; there was no workdir. cwd was the session directory. The command then ran in the requested workdir.

    So on 0.159, as on 0.152–0.154 above, a hook still cannot resolve a command's relative paths against the directory it actually runs in.

    Workaround we ship (agent-guardrails#454):

    1. The payload's transcript_path points at the session rollout. Its environment block records the shell (<shell>powershell</shell>).
    2. When that proves PowerShell, the hook returns updatedInput with a precondition. It compares (Get-Location).ProviderPath with the evaluated cwd, exits 1 with guidance on a mismatch, and otherwise runs the original command unchanged.
    3. Observed on 0.159: the command runs in the session directory and stops elsewhere. The model then retried with an explicit Set-Location, which the hook could evaluate.

    This relies on an undocumented transcript detail and on rewriting every command.

    Ask: include the effective workdir (and ideally the resolved shell) in PreToolUse tool_input for exec_command/Bash, so policy hooks can evaluate the command where it will run without either.

  8. murillodutt commented on Oct 1, 2026

    @murillodutt

    Additional isolated native reproduction on macOS arm64 with Codex CLI 0.159.2 and 0.159.3:
    a trusted plugin's PreToolUse Bash input contains the command but omits the
    resolved per-call workdir. The session cwd cannot distinguish a command in its
    declared directory from the same command selecting another directory.

    A fail-closed scope hook therefore retained the pending action and denied the
    declared command, including the matching-directory attempt. In a disposable
    locally patched CLI based on commit 67727e7,
    exposing the host-resolved workdir allowed the hook to deny the divergent call
    before execution and then admit the same pending command in the matching
    directory without reinitialization or amendment. Native sandbox and approval
    policies were retained. This laboratory observation does not qualify a Desktop
    runtime replacement. A separate isolated native run on released 0.159.3
    reproduced the omission: both selected directories were denied, the original
    actions remained pending through second-prompt reconciliation, and SessionEnd
    removed only the session state.

    Please expose the resolved invocation directory in a documented host-owned
    field bound to the invocation actually executed, preserving the hook process
    cwd and existing native permissions. An assertion inside the shell command
    cannot satisfy pre-execution denial with an unconsumed pending action.

  9. noctowlx commented on Oct 13, 2026

    @noctowlx

    We're hitting this too, on Codex CLI 0.162.1.

    We run a PreToolUse hook that refuses git commands that would move a repo's default branch. When the agent runs git merge <sha> through exec_command with workdir pointing at a separate topic-branch checkout, the hook only sees tool_input.command and the turn cwd (which is on the default branch), so it blocks a perfectly safe merge. The command never runs. Right now the only way through is to spell the path into the command itself (git -C /abs/path merge ...).

    From reading the source at 237b7d4:

    • The exec_command pre-hook payload only includes command; workdir is resolved separately on the execution path.
    • The hook runtime takes its cwd from the turn environment.
    • In Code Mode, nested dispatch gets its own exec-<UUID> id, so a hook can't recover the workdir by matching the outer transcript call either.

    (I haven't captured the raw hook stdin, so the payload details above come from the source rather than a dump.)

    Quick way to see it: start a session in dir A, register a PreToolUse hook that just logs cwd, the tool_input keys and tool_input.workdir, then have the agent run pwd via exec_command with workdir set to dir B. The command prints B; the hook only ever sees A.

    What would help: pass the effective execution directory for the pending call to the hook (a separate field is fine, the hook process cwd can stay as is), resolved the same way for direct and nested Code Mode calls.

  10. ivv19041994 commented on Oct 14, 2026

    @ivv19041994

    Additional runtime verification on macOS arm64 with Codex CLI 0.162.1: an explicitly supplied exec_command.workdir was absent from the PreToolUse hook input, while the event cwd remained the session directory. This caused a directory-based write guard to reject commands targeting a permitted directory outside the session checkout.

    I built a minimal fix that preserves the explicitly supplied, raw workdir in tool_input:
    ivv19041994@5a5be02

    After resuming the session using the patched CLI with --no-daemon and confirming the hook was enabled:

    • A create/read/delete probe with an explicit permitted /tmp workdir succeeded without adding cd to the shell command.
    • The same kind of mutation targeting the protected session checkout was denied by PreToolUse before execution.
    • Probe files were cleaned up.

    The patch was subsequently rebased onto current main. Validation on that base passed:

    • cargo test -p codex-core --lib exec_command_pre_tool_use_payload: 3 tests passed, including absolute, relative, and empty workdir values and the existing omitted-workdir behavior.
    • cargo test -p codex-core --test all pre_tool_use_json_deny_blocks_exec_command_before_execution: 1 test passed, asserting the workdir delivered to the actual hook and denial before execution. The test ran with its local mock server enabled.
    • Rust formatting checks for the changed files and git diff --check passed.

    This is deliberately narrower than the effective-directory contract proposed here: it exposes the requested raw argument, not a resolved execution directory. It leaves the event cwd and the command-only payload when workdir is omitted unchanged, and does not address other tools or hook events. Hooks must not assume that a relative path can always be resolved against the event cwd, particularly with selected environments. A host-owned effective execution context would still be the more complete solution.

  11. 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.

  12. creatornader commented on Oct 16, 2026

    @creatornader

    Additional compatibility and lifecycle evidence for this issue, building on harr1sz’s prepared-context experiment, the raw-workdir patches by josh87523 and ivv19041994, and the broader contract request in #54427. This is a separate local implementation, not independent validation of those authors’ tests.

    On base 3ee47c1, I implemented a deliberately smaller additive context: cwd, environment_id, and is_remote. The host prepares the selected environment and resolved launch directory once before PreToolUse, then execution reuses that state. Existing command-only tool_input and local hook-process cwd stay unchanged. The same context follows synchronous and asynchronous completion into PostToolUse, including terminal polling. Command rewrites retain the prepared context; unsupported rewrite fields fail explicitly.

    Why this route rather than adding raw workdir to tool_input:

    Validation: 27 scripted native-client scenarios passed on the implementation; the same 27 completed on released macOS arm64 0.163.0, which still lacks the proposed metadata. No fixture errors or runner/client/companion hash drift occurred. Coverage includes strict legacy input, omitted/relative/absolute/symlink paths, sync/async completion, overlapping calls, rewrite completion order, actual PTY, nested Code Mode identity/context/rewrites/denial, PermissionRequest allow/deny, and selection of a secondary loopback exec-server. Five checks with an unchanged worktree guard also passed, including safe-worktree writes and primary-write denial. Focused Rust checks passed 21 unified-exec, 18 registry and 184 hook tests.

    Limits: both clients used the same hashed Desktop-bundled Code Mode companion. Loopback transport does not prove cross-machine filesystem behavior. Windows execution, nested async Code Mode, classic shell_command, human approval UI and the full shell/argv/permission contract in #54427 remain unverified or unimplemented. PermissionRequest decisions are tested, but its missing execution metadata (#48064) is not fixed. Neither the client nor adapter is installed in Desktop, and other hooks do not re-review the final multi-hook rewrite.

    Would an additive Pre/Post context tied to prepared execution and stored terminal state be the preferred direction for this issue? The field names/schema still need maintainer agreement; this evidence does not establish a supported API.

  13. iamdotk commented on Oct 18, 2026

    @iamdotk

    I build OpenMoat, a PreToolUse hook that applies a file and network policy to agent tool calls. We hit the same thing: for exec_command, the hook payload carries only tool_input.command, while Codex runs the command in cwd.join(workdir) (codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs, pre_tool_use_payload). A policy hook then resolves relative paths in the command against the session cwd instead of the directory the command really runs in, so a rule on a path can be checked against the wrong file.

    What would fix it for us: send the effective working directory for that call in the PreToolUse payload, either the resolved absolute directory as the top-level cwd, or tool_input.workdir as the model sent it. Happy to test a build.

  14. TyceHerrman commented on Oct 27, 2026

    @TyceHerrman

    one concrete release-workflow consequence of the missing effective workdir is documented in #50271. Its hook receives the supervisor workspace as cwd while the canonical release command runs in the package worktree. The guard then blocks that command, and Codex selects a different release path

    seems relevant for the workdir contract issue here

  15. gandalfsaxe commented on Oct 29, 2026

    @gandalfsaxe

    Looks like this is fixed on main by #57198 (and #57203 for PermissionRequest/PostToolUse): for a local executor, PreToolUse cwd is now the resolved command directory. Both are in rust-v0.166.0-alpha.4+, not in 0.165.0.

    Two questions before this closes:

    • The hooks reference still calls cwd the "Working directory for the session". With this change it means the command directory for exec tools, and hooks that need the session root no longer have a field for it. Could the docs define cwd per event/tool, and is a session-root field planned?
    • Remote executors keep the host cwd, so hooks still can't see where a remote command runs. Known limit or follow-up?

    Context: I hit this with a git publish guard that decides by working directory. I'll retest on 0.166 once it ships.

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

    CLIbughookstool-calls

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions