Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(plugin): run the Codex Windows hooks through Git Bash, not the WSL launcher (#4008)
Worktrunk Bot80e795b271cd
diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.mdindex d24f02bef..77e9b700b 100644--- a/.claude/skills/release/SKILL.md+++ b/.claude/skills/release/SKILL.md@@ -36,7 +36,7 @@ metadata:cargo release X.Y.Z -p worktrunk -x --no-publish --no-push --no-tag --no-verify --no-confirm && cargo check```This bumps `Cargo.toml` and `Cargo.lock`, then auto-commits. We'll reset this commit in step 10 to fold in the CHANGELOG.-9. **Update CHANGELOG**: Add `## X.Y.Z` section at top with changes (see MANDATORY verification below)+9. **Update CHANGELOG**: the top section holds this release's changes (see MANDATORY verification below). If it is `## Unreleased`, rename that heading to `## X.Y.Z` and fold the remaining entries into it β inserting a new heading above it ships a stale `## Unreleased` in the release notes. Otherwise the top section is the last shipped version: add a `## X.Y.Z` section above it, never append to it.10. **Commit**: Reset the auto-commit from step 8, stage everything, and create the final release commit:```bashgit reset --soft HEAD~1 && git add -A && git commit -m "Release vX.Y.Z"diff --git a/.gitattributes b/.gitattributesindex 994f42f94..9beac5ce4 100644--- a/.gitattributes+++ b/.gitattributes@@ -28,6 +28,11 @@ dev/*.example.toml linguist-generated=true# Shell templates are embedded into the binary at compile time (askama); a# CRLF checkout would leak \r into the shell code Windows-built binaries emit.templates/* text eol=lf+# cmd.exe resolves a `goto` label by seeking through the batch file, and an+# LF-only batch file can fail that search ("The system cannot find the batch+# label specified"). The hook shim is only ever run by cmd.exe, so pin its+# checkout to CRLF regardless of the platform cloning it.+plugins/worktrunk/hooks/*.cmd text eol=crlf# A fixture's object store and index are git's own binary formats, but git only# calls a file binary when it finds a NUL in the first 8000 bytes, and a small# enough zlib object may have none. Those diff as text, so `git diff` writes rawdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 778c8fd1b..dd0fdac38 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## Unreleased++### Fixed++- **Codex on Windows: the activity hooks no longer fail on every event**: each hook led with a bare `bash`, which `cmd.exe` resolves to the WSL launcher rather than Git Bash; in a sandboxed session it refuses to start, so every event raised a `Hook failed` banner. Each hook now carries a Windows-only command that runs the same `wt.sh` through a `cmd.exe` shim, which finds Git Bash by path rather than by name. ([#4008](https://github.com/max-sixty/worktrunk/pull/4008), fixes [#4007](https://github.com/max-sixty/worktrunk/issues/4007), thanks @McNultyyy for reporting and diagnosing)+## 0.76.0### Improveddiff --git a/plugins/worktrunk/.codex-plugin/plugin.json b/plugins/worktrunk/.codex-plugin/plugin.jsonindex 0378314fa..daa38880d 100644--- a/plugins/worktrunk/.codex-plugin/plugin.json+++ b/plugins/worktrunk/.codex-plugin/plugin.json@@ -16,7 +16,8 @@"hooks": [{"type": "command",- "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π€ || true"+ "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π€ || true",+ "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set π€ || exit /b 0"}]}@@ -27,7 +28,8 @@"hooks": [{"type": "command",- "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π¬ || true"+ "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π¬ || true",+ "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set π¬ || exit /b 0"}]}@@ -37,7 +39,8 @@"hooks": [{"type": "command",- "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π¬ || true"+ "command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set π¬ || true",+ "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set π¬ || exit /b 0"}]}@@ -48,6 +51,7 @@{"type": "command","command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker clear || true",+ "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker clear || exit /b 0","timeout": 3}]diff --git a/plugins/worktrunk/CLAUDE.md b/plugins/worktrunk/CLAUDE.mdindex 9a8778e1f..8b3c8371d 100644--- a/plugins/worktrunk/CLAUDE.md+++ b/plugins/worktrunk/CLAUDE.md@@ -31,6 +31,8 @@ worktrunk/ β repo root = marketplace rootβ $CLAUDE_PLUGIN_ROOT, Codex via $PLUGIN_ROOT,β Gemini viaβ ${extensionPath}/plugins/worktrunk/hooks/wt.sh+ βββ hooks/wt.cmd β finds Git Bash for cmd.exe, which is what runs+ β a Codex `commandWindows`, then runs wt.sh (#4007)βββ skills/ β generated real-file mirror of repo-rootβ skills/ (test_docs_are_in_sync; neverβ hand-edit) β real files because Codex's@@ -147,6 +149,8 @@ Claude's hooks live in the standalone `hooks/hooks.json` its loader discovers by- **Why inline for Codex, not a path or an absent key.** Claude and Codex share one payload dir, and Codex *also* auto-discovers `hooks/hooks.json` at the plugin root by convention (`DEFAULT_HOOKS_CONFIG_FILE`, the `None` branch of `load_plugin_hooks`) β which once surfaced Worktrunk's *Claude* events in a Codex session ([#3362](https://github.com/max-sixty/worktrunk/issues/3362)). The Codex manifest carries its own hooks **inline**, taking Codex's `Some(Inline)` branch (`resolve_manifest_hooks` in `codex-rs/core-plugins/src/manifest.rs`), which **overrides** convention discovery. The inline object is both the functional definition of the Codex-native events and the thing that keeps Codex off the shared `hooks/hooks.json`, so the two toolchains coexist on one file: Claude discovers it, Codex ignores it. (Scoping via the filename instead β `hooks/claude-hooks.json` β breaks Claude's discovery, [#3417](https://github.com/max-sixty/worktrunk/issues/3417); the inline override makes it unnecessary.)- **Why `$PLUGIN_ROOT`, not `$CLAUDE_PLUGIN_ROOT`.** Codex exports both to hook commands (`PLUGIN_ROOT` native, `CLAUDE_PLUGIN_ROOT` as an OOTB-compat alias β `codex-rs/hooks/src/engine/discovery.rs`). The Codex file uses the native `$PLUGIN_ROOT` so nothing Claude-branded appears in a Codex session.+- **Why every hook also carries `commandWindows`.** Codex runs a hook `command` through the platform shell β `/bin/sh -lc` on Unix, `cmd.exe /C` on Windows (`default_shell_command` in `codex-rs/hooks/src/engine/command_runner.rs`). Under `cmd.exe` the leading bare `bash` resolves through the Windows PATH to `System32\bash.exe`, the WSL launcher rather than Git Bash, which in a sandboxed session fails outright (`Bash/Service/CreateInstance/E_ACCESSDENIED`) and turns every prompt, permission, stop, and session-end event into a "Hook failed" banner ([#4007](https://github.com/max-sixty/worktrunk/issues/4007)). Only the bare *name* is the problem β Git for Windows is a requirement either way β so the per-handler `commandWindows` key, which **replaces** `command` on Windows (`command_windows.unwrap_or(command)` in `codex-rs/hooks/src/engine/discovery.rs`), calls `hooks/wt.cmd`: a shim that resolves `bash.exe` by path the way `find_git_bash` does in `src/shell_exec.rs` (derived from `where git.exe`, then the system-wide and per-user install defaults, `Git\bin\bash.exe` before `Git\usr\bin\bash.exe` because the former is the wrapper that puts `uname` and friends on PATH for a caller outside Git Bash) and then runs the same `wt.sh` every other integration goes through, so worktrunk's own resolution order lives in one script rather than in two languages. The `git.exe` lookup uses `where`'s `$PATH:` prefix and runs the absolute path it returns: an unscoped `where`, like cmd's own bare-name lookup, searches the current directory first, which for a hook is the user's project β so a `git.exe` committed to a repo would choose the bash every event runs (`test_shim_ignores_a_git_in_the_current_directory`). `where` itself is spelled `%SystemRoot%\System32\where.exe` for the same reason β it is `System32\where.exe` rather than a cmd built-in, so cmd resolves that bare name from the current directory too (`test_shim_ignores_a_where_in_the_current_directory`). Both of those see only the *wrong* bash; a lookup that finds nothing falls through to `%ProgramFiles%\Git`, which resolves on any Windows box, so `test_shim_derives_bash_from_the_git_on_path` points both install-default variables at an empty directory and leaves the derive branch as the only route to a bash. The Windows commands brace the plugin root as `${PLUGIN_ROOT}`, which Codex substitutes textually before the shell runs (`source.env` fold in `discovery.rs`); the unbraced `$PLUGIN_ROOT` the Unix commands use survives to the shell, and `cmd.exe` would pass it through literally. `|| exit /b 0` is the cmd.exe spelling of the Unix `|| true` β a marker is decoration, and a nonzero exit is what raises the banner. `test_codex_windows_hook_commands_set_the_marker` runs the real commands the way Codex spawns them, on the Windows leg of CI. `SessionEnd` carries `timeout: 3` because that is Codex's ceiling for the event (`SESSION_END_MAX_TIMEOUT_SEC` in `codex-rs/hooks/src/events/session_end.rs`; omitting the key takes the 1s default, and a larger value is clamped with a warning), and a hook that exceeds it is reported as an error β the same "Hook failed" banner β so the longer Windows chain has no more budget to ask for.+The events (Codex's `HookEventsToml` vocabulary, verified against `codex-rs/config/src/hook_config.rs`):- `UserPromptSubmit` β π€ (working)- `PermissionRequest`, `Stop` β π¬ (waiting for input)diff --git a/plugins/worktrunk/hooks/wt.cmd b/plugins/worktrunk/hooks/wt.cmdnew file mode 100644index 000000000..ddca2db0c--- /dev/null+++ b/plugins/worktrunk/hooks/wt.cmd@@ -0,0 +1,59 @@+@echo off+rem Windows counterpart of the `bash "$PLUGIN_ROOT/hooks/wt.sh"` that the Unix+rem hook commands lead with: it finds Git Bash by path, then runs wt.sh through+rem it, so every integration resolves the worktrunk binary through that one+rem script.+rem+rem Codex runs hook commands through `cmd.exe /C` on Windows, where a bare+rem `bash` resolves through PATH to System32\bash.exe -- the WSL launcher, not+rem Git Bash -- and in a sandboxed session refuses to start at all (#4007). Only+rem the bare name is the problem, so this resolves bash.exe the way find_git_bash+rem does in src/shell_exec.rs and changes nothing else.+rem Usage: wt.cmd [args...]+rem+rem Every branch here is a bare `goto` or `call`: `if <cond> <cmd1> & <cmd2>`+rem runs cmd2 unconditionally, and `if <cond> <cmd1> || <cmd2>` tests the `if`+rem rather than cmd1, so neither connector can carry the control flow.+setlocal EnableExtensions+rem Clear the local: `setlocal` inherits the caller's environment, and Codex+rem hands each hook the session env snapshot, so an inherited BASH would name+rem what every event runs.+set "BASH="++rem git.exe installs at Git\cmd\git.exe or Git\bin\git.exe, and bash.exe at+rem Git\bin\bash.exe or Git\usr\bin\bash.exe. The lookup uses `where`'s `$var:`+rem prefix, which searches the directories named in that variable and nowhere+rem else: a bare `where git.exe` searches the current directory first, as cmd's+rem own bare-name lookup does, and a hook's current directory is the user's+rem project -- so a `git.exe` committed to a repo would otherwise choose the+rem bash every event runs. `where` itself is spelled absolutely for the same+rem reason: cmd resolves that name from the current directory too.+for /f "delims=" %%I in ('"%SystemRoot%\System32\where.exe" "$PATH:git.exe" 2^>nul') do if not defined BASH call :derive "%%~dpI"++rem A git.exe PATH doesn't name, or names through a shim outside its install:+rem the system-wide default, then the per-user one an install without admin+rem rights writes (#1259).+if not defined BASH call :accept "%ProgramFiles%\Git\bin\bash.exe"+if not defined BASH call :accept "%LOCALAPPDATA%\Programs\Git\bin\bash.exe"++if not defined BASH goto :missing++"%BASH%" "%~dp0wt.sh" %*+exit /b %ERRORLEVEL%++rem %1 is a Git install's cmd\ or bin\ directory, with the trailing separator+rem `%~dpI` leaves on. Git\bin\bash.exe first, as find_git_bash does: it is the+rem wrapper that sets up the MSYS environment for a caller outside Git Bash,+rem which is what puts `uname` and friends within reach of wt.sh.+:derive+call :accept "%~1..\bin\bash.exe"+if not defined BASH call :accept "%~1..\usr\bin\bash.exe"+goto :eof++:accept+if exist "%~1" set "BASH=%~f1"+goto :eof++:missing+echo worktrunk: Git for Windows is required but bash.exe was not found. Install from https://git-scm.com/download/win 1>&2+exit /b 1diff --git a/plugins/worktrunk/hooks/wt.sh b/plugins/worktrunk/hooks/wt.shindex a7a4a72e1..0d1cc3ed3 100755--- a/plugins/worktrunk/hooks/wt.sh+++ b/plugins/worktrunk/hooks/wt.sh@@ -6,6 +6,12 @@# On other platforms, uses wt directly.# Usage: wt.sh [args...]+# Clear WT before the branches below: on Windows they leave it unset when+# neither git-wt.exe nor wt is on PATH, and a hook is handed the caller's whole+# environment -- so an inherited WT would be what the final check accepts and+# runs, Windows Terminal included.+WT=""+if [[ -n "$WORKTRUNK_BIN" ]]; thenif ! command -v "$WORKTRUNK_BIN" >/dev/null 2>&1; thenecho "worktrunk: WORKTRUNK_BIN is set to '$WORKTRUNK_BIN' but it was not found" >&2diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 3897c328d..af13db2b3 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -4570,6 +4570,521 @@ fn test_plugin_layout_is_consolidated() {}}+/// Codex resolves a hook `command` through the platform shell β `/bin/sh -lc`+/// on Unix, `cmd.exe /C` on Windows (`default_shell_command` in+/// `codex-rs/hooks/src/engine/command_runner.rs`). The Unix commands lead with+/// `bash "$PLUGIN_ROOT/hooks/wt.sh"`, and under `cmd.exe` that bare `bash`+/// resolves through the Windows PATH to `System32\bash.exe`, the WSL launcher β+/// not Git Bash. In a sandboxed Codex session the launcher refuses to start+/// (`Bash/Service/CreateInstance/E_ACCESSDENIED`), so every prompt, permission,+/// stop, and session-end event raises a "Hook failed" banner (#4007).+///+/// Codex's fix for this is the per-handler `commandWindows` override, which+/// *replaces* `command` on Windows (`command_windows.unwrap_or(command)` in+/// `codex-rs/hooks/src/engine/discovery.rs`). Every Codex command hook must+/// carry one, and it must name neither `bash` β the WSL launcher, under cmd.exe+/// β nor bare `wt`, which belongs to Windows Terminal on Windows. It calls+/// `hooks/wt.cmd`, which finds Git Bash *by path* and runs the same `wt.sh`.+///+/// Codex substitutes only the braced `${PLUGIN_ROOT}` form textually, before+/// the shell runs; the unbraced `$PLUGIN_ROOT` survives to the shell and is+/// expanded only by the Unix `/bin/sh`. `cmd.exe` would pass it through+/// literally, so the Windows commands must brace it.+#[test]+fn test_codex_hooks_carry_windows_commands() {+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));+ let codex: serde_json::Value = serde_json::from_str(+ &fs::read_to_string(root.join("plugins/worktrunk/.codex-plugin/plugin.json")).unwrap(),+ )+ .unwrap();++ let hooks: Vec<&serde_json::Value> = codex["hooks"]["hooks"]+ .as_object()+ .expect("the Codex manifest must define hooks inline (#3362)")+ .values()+ .flat_map(|event| event.as_array().expect("each hook event must be an array"))+ .flat_map(|group| {+ group["hooks"]+ .as_array()+ .expect("each hook group must have a `hooks` array")+ })+ .collect();+ assert_eq!(+ hooks.len(),+ 4,+ "expected all 4 Codex hooks (UserPromptSubmit, PermissionRequest, Stop, \+ SessionEnd); a newly added one must be pinned too"+ );++ for hook in hooks {+ let command = hook["command"]+ .as_str()+ .expect("each Codex hook must define a command");+ let windows = hook["commandWindows"].as_str().unwrap_or_else(|| {+ panic!(+ "Codex hook has no `commandWindows`; on Windows its `command` runs under \+ cmd.exe, where bare `bash` resolves to the WSL launcher rather than Git \+ Bash and fails outright in a sandboxed session (#4007). command:\n{command}"+ )+ });+ assert!(+ !windows.split_whitespace().any(|word| word == "bash"),+ "`commandWindows` must not name bash β cmd.exe resolves that name to the WSL \+ launcher (#4007); the shim finds Git Bash by path instead. commandWindows:\n{windows}"+ );+ assert!(+ !windows+ .split_whitespace()+ .any(|word| word == "wt" || word == "wt.exe" || word.ends_with("\\wt.exe")),+ "`commandWindows` must not invoke bare `wt` β that name resolves to Windows \+ Terminal. commandWindows:\n{windows}"+ );+ assert!(+ windows.contains(r"${PLUGIN_ROOT}\hooks\wt.cmd")+ && root.join("plugins/worktrunk/hooks/wt.cmd").is_file(),+ "`commandWindows` must call the cmd.exe shim that ships beside wt.sh. \+ commandWindows:\n{windows}"+ );+ assert!(+ windows.contains("${PLUGIN_ROOT}") && !windows.contains("$PLUGIN_ROOT/"),+ "`commandWindows` must reference the plugin root as ${{PLUGIN_ROOT}}: Codex \+ substitutes only the braced form textually, and cmd.exe would pass the \+ unbraced one through literally. commandWindows:\n{windows}"+ );+ // The Unix side keeps the unbraced form the login shell expands.+ assert!(+ command.contains("$PLUGIN_ROOT") && !command.contains("${PLUGIN_ROOT}"),+ "the Unix `command` must keep the unbraced $PLUGIN_ROOT. command:\n{command}"+ );+ }+}++/// The directory PATH names `git.exe` in β `Git\cmd` for a default Git for+/// Windows install, which is the only directory of that install the installer+/// puts on PATH. The Windows tests below pin a PATH built from it: narrow+/// enough that no ambient `wt.exe` can stand in for the worktrunk under test,+/// while still holding what a real user's PATH holds, so the shim has to derive+/// Git Bash the way it will on their machine.+#[cfg(windows)]+fn git_dir_on_path() -> std::path::PathBuf {+ let path = std::env::var_os("PATH").expect("a Windows test runner must set PATH");+ std::env::split_paths(&path)+ .find(|dir| dir.join("git.exe").is_file())+ .expect("a Windows test runner must have git.exe on PATH")+}++/// `extra` first, then Git and System32 β the latter so that a bare command+/// name a test spells itself still resolves. The shim's own `where` is spelled+/// absolutely, so it no longer depends on this.+#[cfg(windows)]+fn pinned_windows_path(extra: &[std::path::PathBuf]) -> std::ffi::OsString {+ let system32 = std::path::PathBuf::from(+ std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into()),+ )+ .join("System32");+ let dirs: Vec<std::path::PathBuf> = extra+ .iter()+ .cloned()+ .chain([git_dir_on_path(), system32])+ .collect();+ std::env::join_paths(dirs).unwrap()+}++/// `C:\a\b` as Git Bash sees it, `/c/a/b`. Only for handing a path to something+/// that will run *inside* bash: `command -v` takes an argument with no `/` as a+/// command name and searches PATH for it, so a Windows-spelled path there is+/// never found, and a test that spelled it that way would pass for that reason+/// rather than the one it means to pin.+#[cfg(windows)]+fn msys_path(path: &std::path::Path) -> String {+ let text = path.display().to_string();+ let (drive, rest) = text.split_at(2);+ assert!(+ drive.ends_with(':'),+ "expected a drive-qualified path, got {text}"+ );+ format!(+ "/{}{}",+ drive[..1].to_ascii_lowercase(),+ rest.replace('\\', "/")+ )+}++/// The structural guard above pins that a `commandWindows` exists and avoids+/// `bash`; this one runs the real one the way Codex does and checks it lands the+/// marker. Codex spawns `cmd.exe /C "<command>"` with the command line wrapped+/// in quotes as a single raw argument (`build_command` in+/// `codex-rs/hooks/src/engine/command_runner.rs`) after substituting the braced+/// `${PLUGIN_ROOT}` textually (`codex-rs/hooks/src/engine/discovery.rs`), so+/// this reproduces both steps rather than approximating them.+///+/// What that covers beyond the manifest text: cmd.exe's quote handling across+/// the nested quoting around the shim path, the shim's `goto`-based search for+/// Git Bash, `wt.sh` running under the bash it picks (which is what needs+/// `Git\bin\bash.exe`, the wrapper that puts `uname` and friends on PATH for a+/// caller outside Git Bash), the emoji argument surviving both hops intact, and+/// the `|| exit /b 0` tail keeping a failed marker best-effort β a hook that+/// exits nonzero is what raises the repeated "Hook failed" banner #4007 reports.+#[cfg(windows)]+#[rstest]+fn test_codex_windows_hook_commands_set_the_marker(repo: TestRepo) {+ use std::os::windows::process::CommandExt;++ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));+ let plugin_root = root.join("plugins/worktrunk");+ let codex: serde_json::Value = serde_json::from_str(+ &fs::read_to_string(plugin_root.join(".codex-plugin/plugin.json")).unwrap(),+ )+ .unwrap();+ let command_for = |event: &str| -> String {+ codex["hooks"]["hooks"][event][0]["hooks"][0]["commandWindows"]+ .as_str()+ .unwrap_or_else(|| panic!("{event} must define a commandWindows"))+ .replace("${PLUGIN_ROOT}", &plugin_root.display().to_string())+ };++ // The worktrunk wt.sh is meant to find, under the name it prefers.+ let path_dir = repo.root_path().join("path-dir");+ fs::create_dir_all(&path_dir).unwrap();+ fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();+ let with_worktrunk = pinned_windows_path(&[path_dir]);+ let without_worktrunk = pinned_windows_path(&[]);++ let run_hook = |event: &str, path: &std::ffi::OsString| -> std::process::Output {+ let mut cmd = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut cmd);+ cmd.arg("/C")+ .raw_arg(format!("\"{}\"", command_for(event)))+ .env("PATH", path)+ .env_remove("WORKTRUNK_BIN")+ .current_dir(repo.root_path())+ .output()+ .unwrap()+ };+ let describe = |output: &std::process::Output| {+ format!(+ "got {}\nstdout:\n{}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ };+ let marker_key = format!("worktrunk.state.{}.marker", repo.current_branch());+ let marker = || -> String {+ let output = repo+ .git_command()+ .args(["config", "--get", &marker_key])+ .run();+ output.map_or_else(+ |_| String::new(),+ |output| String::from_utf8_lossy(&output.stdout).trim().to_owned(),+ )+ };++ let output = run_hook("UserPromptSubmit", &with_worktrunk);+ assert!(+ output.status.success(),+ "UserPromptSubmit hook must succeed; {}",+ describe(&output)+ );+ assert!(+ marker().contains('π€'),+ "UserPromptSubmit must store the working marker, not a mangled byte sequence; \+ got {:?}",+ marker()+ );++ let output = run_hook("Stop", &with_worktrunk);+ assert!(+ output.status.success(),+ "Stop hook must succeed; {}",+ describe(&output)+ );+ assert!(+ marker().contains('π¬'),+ "Stop must replace the marker with the waiting one; got {:?}",+ marker()+ );++ let output = run_hook("SessionEnd", &with_worktrunk);+ assert!(+ output.status.success(),+ "SessionEnd hook must succeed; {}",+ describe(&output)+ );+ assert!(+ marker().is_empty(),+ "SessionEnd must clear the marker; got {:?}",+ marker()+ );++ // Worktrunk not installed: the marker is optional decoration, so the hook+ // must stay silent rather than fail every prompt (#4007).+ let output = run_hook("UserPromptSubmit", &without_worktrunk);+ assert!(+ output.status.success(),+ "a hook that cannot find worktrunk must still exit 0 β a nonzero exit is what \+ raises Codex's repeated \"Hook failed\" banner; {}",+ describe(&output)+ );+ assert!(+ marker().is_empty(),+ "a failed hook must not invent a marker; got {:?}",+ marker()+ );+}++/// `wt.sh` assigns `WT` in each of its branches, but on Windows every branch can+/// be skipped: with neither `git-wt.exe` nor `wt` on PATH it falls out of the+/// `elif` with `WT` untouched. A hook is handed the caller's whole environment+/// (`command.env_clear(); command.envs(environment)` in+/// `codex-rs/hooks/src/engine/command_runner.rs` hands Codex's session snapshot+/// to each one), so a user's own `WT` arrives already set β and the final+/// `command -v "$WT"` check then accepts it and runs it, in place of the+/// worktrunk the script exists to resolve. Windows Terminal is spelled `wt`,+/// which is exactly the binary the branch above rejects by name.+#[cfg(windows)]+#[rstest]+fn test_wt_sh_ignores_an_inherited_wt(repo: TestRepo) {+ use std::os::windows::process::CommandExt;++ let shim =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("plugins/worktrunk/hooks/wt.cmd");++ // A PATH with Git on it (so the shim finds bash) and no worktrunk under+ // either name β the case that leaves `WT` unassigned. The inherited value+ // names a *real* worktrunk, spelled the way bash can run it, so honoring it+ // would look exactly like success.+ let mut cmd = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut cmd);+ let output = cmd+ .arg("/C")+ .raw_arg(format!("\"\"{}\" --version\"", shim.display()))+ .env("PATH", pinned_windows_path(&[]))+ .env("WT", msys_path(&crate::common::wt_bin()))+ .env_remove("WORKTRUNK_BIN")+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ !output.status.success() && !stdout.contains("wt "),+ "wt.sh must clear WT and resolve worktrunk itself, not run an inherited one; \+ got {}\nstdout:\n{stdout}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stderr)+ );+}++/// `where git.exe` searches the current directory before it searches PATH, and+/// cmd resolves a bare `git.exe` the same way β so with the lookup unscoped, a+/// `git.exe` committed to a repo decides which `bash.exe` every prompt,+/// permission request, stop, and session end runs, since the hook runs with the+/// user's project as its current directory. `wt.sh` carries no such surface:+/// `command -v` consults PATH only.+///+/// Neither decoy planted here is a valid executable, which is what makes the+/// shim's choice observable: the version line can only be printed by the real+/// bash the pinned PATH leads to. Taking the decoy `git.exe` would derive the+/// `bash.exe` beside it β planted so that the wrong branch *resolves* rather+/// than falling through to the standard install locations and passing anyway.+#[cfg(windows)]+#[rstest]+fn test_shim_ignores_a_git_in_the_current_directory(repo: TestRepo) {+ use std::os::windows::process::CommandExt;++ let shim =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("plugins/worktrunk/hooks/wt.cmd");++ // The only worktrunk the shim is allowed to find: a real one, in a+ // directory on the PATH this test pins.+ let path_dir = repo.root_path().join("path-dir");+ fs::create_dir_all(&path_dir).unwrap();+ fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();++ // ...and the decoys: a `git.exe` in the directory the hook runs from, plus+ // the `bash.exe` the shim would derive from it (`<cwd>\..\bin\bash.exe`).+ let project = repo.root_path().join("project");+ fs::create_dir_all(&project).unwrap();+ fs::write(project.join("git.exe"), b"not an executable").unwrap();+ fs::create_dir_all(repo.root_path().join("bin")).unwrap();+ fs::write(+ repo.root_path().join("bin").join("bash.exe"),+ b"not an executable",+ )+ .unwrap();++ let mut cmd = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut cmd);+ let output = cmd+ .arg("/C")+ .raw_arg(format!("\"\"{}\" --version\"", shim.display()))+ .env("PATH", pinned_windows_path(&[path_dir]))+ .env_remove("WORKTRUNK_BIN")+ .current_dir(&project)+ .output()+ .unwrap();++ // The version line is `wt <version>`, where the version is whatever the+ // build embedded β the semver from a tagged checkout, a bare commit hash+ // from CI's β so the prefix is the part worth pinning.+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success() && stdout.trim_start().starts_with("wt "),+ "the shim must find git through PATH, not through the current directory; \+ got {}\nstdout:\n{stdout}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stderr)+ );+}++/// The scoping above is only as good as the command doing it. `where` is not a+/// cmd built-in β it is `System32\where.exe` β so cmd resolves that name the+/// way it resolves any other: current directory first, then PATH. A `where`+/// committed to a repo therefore picks the `git.exe` that picks the `bash.exe`+/// every prompt, permission request, stop, and session end runs, which is the+/// surface `$PATH:` closes one level down.+///+/// The decoy is a `.bat` rather than an inert `where.exe`, and it names a Git+/// install whose `bin\bash.exe` exists, because both are what make the wrong+/// answer *observable*: a decoy that cannot run leaves the lookup empty, and a+/// decoy install without a `bash.exe` falls through β either way the shim+/// reaches `%ProgramFiles%\Git\bin\bash.exe`, which resolves on any Windows+/// box, and the test would pass on the unscoped shim for the wrong reason.+/// Reaching `:derive` with a decoy instead leaves `BASH` set and unrunnable.+///+/// The probe below pins the premise separately, so this cannot go green+/// because the planted `where` was never the one cmd would have chosen.+#[cfg(windows)]+#[rstest]+fn test_shim_ignores_a_where_in_the_current_directory(repo: TestRepo) {+ use std::os::windows::process::CommandExt;++ let shim =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("plugins/worktrunk/hooks/wt.cmd");++ // The only worktrunk the shim is allowed to find: a real one, in a+ // directory on the PATH this test pins.+ let path_dir = repo.root_path().join("path-dir");+ fs::create_dir_all(&path_dir).unwrap();+ fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();++ // The decoy Git install the planted `where` names. `:derive` takes+ // `<install>\cmd\` and accepts `<install>\bin\bash.exe`, so that file has+ // to exist for the wrong branch to win rather than fall through.+ let decoy = repo.root_path().join("decoy-git");+ fs::create_dir_all(decoy.join("bin")).unwrap();+ fs::write(decoy.join("bin").join("bash.exe"), b"not an executable").unwrap();++ // ...and the lookup that names it, in the directory the hook runs from.+ // `.bat` is enough to shadow `System32\where.exe`: cmd tries every PATHEXT+ // extension in one directory before it moves to the next.+ let project = repo.root_path().join("project");+ fs::create_dir_all(&project).unwrap();+ let decoy_git = decoy.join("cmd").join("git.exe");+ fs::write(+ project.join("where.bat"),+ format!("@echo {}\r\n", decoy_git.display()),+ )+ .unwrap();++ // The premise, checked directly: without it the decoy is never consulted+ // and every assertion below would hold on the unscoped shim too.+ let mut probe = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut probe);+ let probe_output = probe+ .arg("/C")+ .raw_arg("\"where $PATH:git.exe\"")+ .env("PATH", pinned_windows_path(&[]))+ .current_dir(&project)+ .output()+ .unwrap();+ let probed = String::from_utf8_lossy(&probe_output.stdout);+ assert!(+ probed.contains("decoy-git"),+ "a `where.bat` in the current directory must shadow System32's `where.exe`, \+ or this test pins nothing; got {probed:?}"+ );++ let mut cmd = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut cmd);+ let output = cmd+ .arg("/C")+ .raw_arg(format!("\"\"{}\" --version\"", shim.display()))+ .env("PATH", pinned_windows_path(&[path_dir]))+ .env_remove("WORKTRUNK_BIN")+ .current_dir(&project)+ .output()+ .unwrap();++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success() && stdout.trim_start().starts_with("wt "),+ "the shim must run System32's `where.exe`, not one from the current \+ directory; got {}\nstdout:\n{stdout}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stderr)+ );+}++/// The two scoping tests above see only the *wrong* bash: they go red because+/// the shim picks a decoy. Neither sees a lookup that finds nothing at all β a+/// mis-quoted `for /f`, a `where` spelling cmd cannot run β because the shim+/// then falls through to `%ProgramFiles%\Git\bin\bash.exe`, which resolves on+/// any Windows box, and every assertion still holds. So the derive branch is+/// the one route to a bash that nothing observes.+///+/// This takes the fallbacks away: `ProgramFiles` and `LOCALAPPDATA` point at an+/// empty directory, leaving `:derive` as the only way to a bash, so the+/// `%SystemRoot%\System32\where.exe` line has to return the Git install β under+/// the quoting `for /f` wraps it in β for the shim to reach `wt.sh` at all.+///+/// Both variables reach a real hook: Codex's strictest `inherit = "core"`+/// policy keeps `SYSTEMROOT`, `PROGRAMFILES` and `LOCALAPPDATA`+/// (`WINDOWS_CORE_ENV_VARS` in `codex-rs/protocol/src/shell_environment.rs`),+/// and `scrub_non_inheritable_env_vars` drops only auth-token names.+#[cfg(windows)]+#[rstest]+fn test_shim_derives_bash_from_the_git_on_path(repo: TestRepo) {+ use std::os::windows::process::CommandExt;++ let shim =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("plugins/worktrunk/hooks/wt.cmd");++ // The only worktrunk the shim is allowed to find: a real one, in a+ // directory on the PATH this test pins.+ let path_dir = repo.root_path().join("path-dir");+ fs::create_dir_all(&path_dir).unwrap();+ fs::copy(crate::common::wt_bin(), path_dir.join("git-wt.exe")).unwrap();++ // Where the two standard-install fallbacks now point: no Git under either.+ let no_git = repo.root_path().join("no-git");+ fs::create_dir_all(&no_git).unwrap();++ let mut cmd = std::process::Command::new("cmd.exe");+ repo.configure_wt_cmd(&mut cmd);+ let output = cmd+ .arg("/C")+ .raw_arg(format!("\"\"{}\" --version\"", shim.display()))+ .env("PATH", pinned_windows_path(&[path_dir]))+ .env("ProgramFiles", &no_git)+ .env("LOCALAPPDATA", &no_git)+ .env_remove("WORKTRUNK_BIN")+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ output.status.success() && stdout.trim_start().starts_with("wt "),+ "the shim must derive Git Bash from the git.exe PATH names, with no install \+ default left to fall back on; got {}\nstdout:\n{stdout}\nstderr:\n{}",+ output.status,+ String::from_utf8_lossy(&output.stderr)+ );+}+/// Claude hands each hook `command` to the user's LOGIN shell, which parses the/// whole line before the leading `bash β¦` ever launches. The command must/// therefore parse cleanly under fish, zsh, and bash β fish in particular