Repository navigation
Description
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
workdiris a first-class tool argument and defaults to the turn cwd: shell_spec.rs#L26-L36.- The unified exec handler resolves
environment_id/workdirfor actual execution: exec_command.rs#L131-L150. - Its pre-hook payload independently parses only
ExecCommandArgsand emits{ "command": args.cmd }, droppingworkdir: exec_command.rs#L408-L418. - Classic
shell_commandhas 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). run_pre_tool_use_hooksalways constructs the request withturn_context.cwd: hook_runtime.rs#L163-L183.- 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_cwdthrough the same path used by actual execution for bothexec_commandandshell_command. - Add optional
tool_cwdto the hook request/input schema without changing hook process cwd. - Do not swallow invalid
workdir/environment_idresolution in the security-hook path. - Cover absent, absolute, and relative workdir; selected environments; denying hooks;
updatedInputcommand rewrites; invalid paths; and remote/foreign environment semantics. - Assert that the hook-observed
tool_cwdand command-observedpwdare identical.
Related but not duplicate
- Native apply_patch lacks per-call workdir context for Hooks in multi-worktree repositories #20879 covers native
apply_patchlacking per-call workdir context. - Plugin PostToolUse hook relative command resolves from workspace cwd #26675 covers relative plugin hook command resolution.
This report is specifically about shell-like tools already having workdir for execution but losing it at the PreToolUse boundary.
Activity
ctoth commentedon Jul 13, 2026
Confirmed on Windows x86_64 with Codex CLI 0.144.3.
I reproduced this with the turn cwd set to
C:\\work\\barnand anexec_commandcall whoseworkdirwasC:\\work\\wardand whose command wasgit status --short. ThePreToolUsehook 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
mainat8acaec73b6:exec_commandresolvesargs.workdirfor execution, whilepre_tool_use_payloadserializes onlyargs.cmd, and the hook request uses the turn cwd. So the report remains reproducible on a newer release and appears platform-independent.mtmitchel commentedon Jul 20, 2026
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.
harr1sz commentedon Sep 11, 2026
I hit this while integrating a repository policy plugin with Codex CLI
0.153.4on macOS. The missing information extends beyondworkdir: hooks also cannot inspect the resolved shell arguments, effectiveloginandttyvalues, or selected execution environment.The same projection is still present in
mainat624ccf794703e2d84e748fc3ef547d6191a8c0a4:exec_commandemits onlycommand, and the hook request takescwdfrom the turn. I checked that source snapshot; my runtime tests used0.153.4.In an isolated real CLI run, a normally installed and trusted plugin had to reject even
cat marker.txtbecause it could not verify the launch context. The call explicitly supplied its working directory,shell: "/bin/sh",login: false, andtty: 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-levelexecution_contextexposes:{ "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.
argvdescribes 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
cwdand command-onlytool_input. A command-onlyupdatedInputrewrite 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.4because metadata was missing.just fmtand scopedjust fixalso passed.The prototype covers
exec_command. I have not validated it across the Desktop host matrix or extended it to classicshell_command. These results support resolving the launch settings once and exposing them separately from the model's tool input.soycarts commentedon Sep 18, 2026
Reproduced on codex-cli 0.152.1, macOS arm64, with
features.hooks=trueand aPreToolUsecommand hook matchingBash|apply_patchthat appends its stdin to a file.Top-level keys on every
PreToolUseevent at this version:tool_inputkeys on everyBashevent:command, and nothing else. A call the model directed at a nested subdirectory landed its file there, while the event'scwdand the hook process's own cwd both stayed at the session root. A patch sent as anapply_patchheredoc through unified execution arrives astool_name: "Bash"with the whole heredoc intool_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
Bashpre-event unconditionally, because the samecommandstring means different things in different directories and the payload cannot say which. Either of the shapes proposed above (tool_cwdalongside the existingcwd, or acwdinsidetool_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:
CtrlCarlitos commentedon Sep 25, 2026
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/pwdcommands. 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:
In both environments the hook input contained only
tool_input.command, and envelopecwdremained 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:
Use
pythonon Windows. The probe prints retained artifact paths and records advertised tool schemas, hook payloads and tool outputs.--require-contextdeliberately 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 sessioncwdand command-only input compatibility: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
updatedInputcommand 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.
CtrlCarlitos commentedon Sep 30, 2026
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.tools.exec_command({cmd:"echo probe2", workdir:"C:\\Users\\carlitos\\Documents", …}).PreToolUsepayload'stool_inputhad a single key,command. Our hook records the key names; there was noworkdir.cwdwas the session directory. The command then ran in the requestedworkdir.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):
transcript_pathpoints at the session rollout. Its environment block records the shell (<shell>powershell</shell>).updatedInputwith a precondition. It compares(Get-Location).ProviderPathwith the evaluatedcwd, exits 1 with guidance on a mismatch, and otherwise runs the original command unchanged.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) inPreToolUsetool_inputforexec_command/Bash, so policy hooks can evaluate the command where it will run without either.murillodutt commentedon Oct 1, 2026
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.
noctowlx commentedon Oct 13, 2026
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>throughexec_commandwithworkdirpointing at a separate topic-branch checkout, the hook only seestool_input.commandand 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:
command;workdiris resolved separately on the execution path.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, thetool_inputkeys andtool_input.workdir, then have the agent runpwdviaexec_commandwithworkdirset 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.
ivv19041994 commentedon Oct 14, 2026
Additional runtime verification on macOS arm64 with Codex CLI 0.162.1: an explicitly supplied
exec_command.workdirwas absent from the PreToolUse hook input, while the eventcwdremained 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
workdirintool_input:ivv19041994@5a5be02
After resuming the session using the patched CLI with
--no-daemonand confirming the hook was enabled:/tmpworkdir succeeded without addingcdto the shell command.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.git diff --checkpassed.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
cwdand 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 eventcwd, particularly with selected environments. A host-owned effective execution context would still be the more complete solution.avivcarmis-bb commentedon Oct 15, 2026
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
cwdas the execution directory is wrong.Also, the existing
cwdvalue is very helpful. ideally, introducing the command worktree does not replace the agent workspace dir.creatornader commentedon Oct 16, 2026
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, andis_remote. The host prepares the selected environment and resolved launch directory once before PreToolUse, then execution reuses that state. Existing command-onlytool_inputand 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
workdirtotool_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.
iamdotk commentedon Oct 18, 2026
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 onlytool_input.command, while Codex runs the command incwd.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, ortool_input.workdiras the model sent it. Happy to test a build.TyceHerrman commentedon Oct 27, 2026
one concrete release-workflow consequence of the missing effective workdir is documented in #50271. Its hook receives the supervisor workspace as
cwdwhile the canonical release command runs in the package worktree. The guard then blocks that command, and Codex selects a different release pathseems relevant for the workdir contract issue here
gandalfsaxe commentedon Oct 29, 2026
Looks like this is fixed on main by #57198 (and #57203 for PermissionRequest/PostToolUse): for a local executor, PreToolUse
cwdis now the resolved command directory. Both are inrust-v0.166.0-alpha.4+, not in 0.165.0.Two questions before this closes:
cwdthe "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 definecwdper event/tool, and is a session-root field planned?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.
check/hooks: resolve a path argument the way the filesystem does (#201)…