Repository navigation
Description
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?
- Configure a project
PreToolUsehook forbashthat logs the rawtool_inputit receives. - In a session, have the model run
exec_commandwithcmd: "pwd"and noworkdir, then again with an explicitworkdirpointing at a subdirectory or another worktree. - Observe that both hook deliveries carry identical
tool_input({"command":"pwd"}) and identical top-levelcwd, 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:
- Explicit vs absent stays distinguishable. Include
workdironly 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". - Raw vs resolved semantics are defined. The raw requested
workdirmay be relative and is resolved against the selected environment's cwd — which is not necessarily the sessioncwdthe hook envelope carries. Exposing the effective resolved cwd (the valuehandle_callcomputes) is the stronger contract; if only the raw field is exposed, please document which base it resolves against. - 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
josh87523 commentedon Aug 9, 2026
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 onlycommandwhile 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:The patch includes non-empty raw
exec_command.workdirin Bash PreToolUse, omits it when absent, and preserves the same frozen value through synchronous completion and asynchronouswrite_stdinso PostToolUse receives the original workdir. It also covers parallel-session isolation. It does not changegit -Ctarget semantics or treat workdir as authorization.Validation completed:
cargo fmt --all -- --checkcargo check -p codex-core --testswrite_stdin, preservation of the initial workdir, and parallel sessionsI 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.
josh87523 commentedon Aug 12, 2026
Update: I rebased the tested workdir transport patch onto current
openai/codexmain and resolved the only source conflict without replacing the new implicit-skill invocation path.Current branch and commit:
Current-main validation:
cargo fmt --all -- --checkcargo test -p codex-core exec_command_pre_tool_use_payload_includes_workdir --no-fail-fastcargo test -p codex-core write_stdin_completion_preserves_initial_hook_workdir --no-fail-fastBoth targeted lifecycle tests passed. The contract remains unchanged: the raw non-empty
exec_command.workdiris observational execution context, not authorization; it is included in Bash PreToolUse and preserved through asyncwrite_stdincompletion for PostToolUse.git -Cremains 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.
H5H-Stoven-One commentedon Sep 10, 2026
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 ordinarypwdandpwdwith 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?abhinav-wingback commentedon Sep 24, 2026
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_commandcall, a hook can recoverworkdirtoday. When the hook runs, thefunction_callline whosecall_idequalstool_use_idis already in the rollout attranscript_path:handle_output_item_donerecords the call before it queues the tool, andhook_transcript_path()callspersist()on the same writer first.In code mode that route is gone. The current model catalog sets
tool_mode: code_mode_onlyfor most models, and commands run astools.exec_command({cmd, workdir})inside anexecscript. Each nested call reachesPreToolUsewith atool_use_idminted incode_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_inputis{"command":"cat config.env"}, the hook'scwdis the session root, and the rollout has no line for the id. Nested calls go through the sameExecCommandHandler::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 inpath_with_base. There,D:xfromC:\repoisD:\repo\x, while Node'spath.resolveuses 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
mainat a16381c (2026-09-24). The{"command": …}-only projection goes back to 0.124.0; theshellandshell_commandtools behaved the same way before they were removed.alopezari commentedon Sep 30, 2026
Still present in codex-cli 0.159.0 (macOS arm64).
I captured the payload through a trusted
PreToolUsehook. The model calledexec_commandin code mode withworkdirset to a subdirectory. The hook received{"command": "git status --short"}and the session'scwd, while the rollout'sCommandExecutionitem 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 createonly 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 fromcwd, so a PR opened from another repository withworkdiris judged by the session's repository and passes. Our only safe workaround is to deny PR commands that don'tcdto an absolute path first.A documented, host-resolved execution directory in the payload, as others asked for above, would let us drop that workaround.
coconutbird commentedon Oct 3, 2026
Still reproduces on
codex-cli 0.160.0(Linux x64 and Windows x64).Repro:
codex execagainst a scripted Responses endpoint whose model callsexec_commandwith{"cmd":"rg needle main.rs","workdir":"src"}. The pluginPreToolUsehook receives:{"cwd":"/tmp/.../work","hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rg needle main.rs"},"tool_use_id":"call_semctx_0", ...}workdiris absent andcwdis the session root, so a hook cannot tell thatmain.rsresolves tosrc/main.rs, or that a call runs in a different repository. The rollout transcript already contains the full arguments (includingworkdir) 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. Includingworkdirintool_input(or resolving it into the payloadcwdfor that call) would fix it.kaimallea commentedon Oct 9, 2026
Also affects
PostToolUseoncodex-cli 0.162.0(macOS arm64), and currentmainatc9e0fffbuilds Bash hook input as{"command": ...}only (context.rs#L432-L436).Our use case is telemetry. A
PostToolUsehook records the git commit of the repository a command ran in. The model ranpwdviaexec_commandwithworkdirset to a second repository, and the output shows it ran there. The hook received only the sessioncwd, 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
PostToolUsewould fix it for observational hooks like ours.etraut-openai commentedon Oct 12, 2026
(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.