worktrunk icon indicating copy to clipboard operation
worktrunk copied to clipboard

Plugin marker hooks follow the shell's cwd, so a `cd` mid-session marks the wrong repository

Open max-sixty opened this issue 3 months ago โ€ข 5 comments

The six marker hooks in plugins/worktrunk/hooks/hooks.json โ€” marker set on UserPromptSubmit, Notification, PreToolUse, PermissionRequest and Stop, and marker clear on SessionEnd โ€” run without -C:

bash "$CLAUDE_PLUGIN_ROOT/hooks/wt.sh" config state marker set ๐Ÿ’ฌ || true

So the marker resolves against the hook process's working directory. That is the agent's shell cwd, and an agent moves it during a turn โ€” reading files out of a second checkout, for instance. The two hooks in the same file that do reach for a directory both scope it: WorktreeRemove passes -C "$p", and WorktreeCreate cds to CLAUDE_PROJECT_DIR.

Three consequences, all silent:

  • A cd into another repository marks that repository's branch instead, and the session's own marker stops updating. The statusline then carries a stale marker on the branch being worked on and a spurious one somewhere else.
  • A session that ends while the shell sits in another repository clears that repository's marker on SessionEnd, and leaves its own set.
  • In a directory that is not a repository the command prints โœ— git rev-parse --git-common-dir failed (exit 128) and exits 1. The trailing || true turns that into a success, so nothing surfaces.

Repro, given a worktree of one repo and any second repo:

cd /tmp/repo-a.feature && wt config state marker set ๐Ÿงช
# โœ“ Set marker for feature to ๐Ÿงช

cd /tmp/repo-b && wt config state marker set ๐Ÿงช
# โœ“ Set marker for main to ๐Ÿงช      <- repo-b's branch, from a session on `feature`

cd /tmp/not-a-repo && wt config state marker set ๐Ÿงช
# โœ— git rev-parse --git-common-dir failed (exit 128), rc 1

The marker should track the worktree the session belongs to rather than wherever its shell currently is. -C <path> would carry that, but the value to pass isn't obvious: CLAUDE_PROJECT_DIR is the launch directory and goes stale once the session moves to another worktree mid-run, and the hook payload's cwd is the same directory that drifted. Pinning the worktree at session start is one route; resolving it from the session record is another.

Seen on worktrunk e4238e8.

This was written by Claude Code on behalf of max-sixty

max-sixty avatar Aug 26 '26 15:08 max-sixty

Heads-up that this issue never got triaged: the tend-triage run for it (32985839479) hit a startup_failure and ran zero steps, so nothing here is a judgement on the report โ€” the bot simply never saw it. Today's review-runs sweep turned it up from the run census.

tend-triage fires only on issues: opened, so there is no automatic second attempt; an @worktrunk-bot mention on this thread is the way to summon a look. I've filed max-sixty/tend#1066 upstream so a run that dies before the failure handler stops being invisible to that sweep.

worktrunk-bot avatar Aug 27 '26 11:08 worktrunk-bot

Triage that the stranded run never did. Two findings: the premise checks out against upstream's own spec, and the scope is wider than one file.

The unscoped shape is in three of four plugins, not one

plugins/worktrunk/hooks/hooks.json is where you found it, but the same bare invocation ships in every plugin except OpenCode โ€” 13 sites total:

Plugin File Unscoped marker calls
Claude Code plugins/worktrunk/hooks/hooks.json 6
Codex plugins/worktrunk/.codex-plugin/plugin.json 4
Gemini CLI hooks/hooks.json 3
OpenCode dev/opencode-plugin.ts 0 โ€” already pinned

OpenCode is the interesting row. It pins every call with .cwd(directory), and its comment already states this bug class as the reason: "is load-bearing: it pins the command to the directory this plugin instance was created for. Without it, the command runs in whatever the process-wide cwd happens to be at spawn time." So the diagnosis was already reached once, for one host, and the other three didn't get it.

Upstream confirms both halves of "the value to pass isn't obvious"

Your paragraph ruling out both candidates is right, and it's documented behavior rather than an accident โ€” worth knowing because it means neither is going to change under us:

  • CLAUDE_PROJECT_DIR really does go stale. The hooks reference states it directly for the worktree case: "${CLAUDE_PROJECT_DIR} stays put: it still points at the project root where the session started."
  • The payload cwd is the drifted value, so reading it buys nothing. "cwd follows Claude: the cwd field in the hook's input JSON is the worktree root after Claude enters a worktree, and the new directory after Claude runs cd." And handlers "run in the current directory" โ€” so the payload field and the process cwd are the same value. -C "$(jq -r .cwd)" would formalize the drift, not fix it.

This is also why OpenCode's fix isn't portable. directory is a value the OpenCode host hands the plugin at instance creation โ€” session-pinned, from the host. Claude Code, Codex, and Gemini expose no equivalent: the payload carries session_id, transcript_path, cwd, permission_mode, hook_event_name, and no worktree identity at all. So "pinning the worktree at session start", the route you name, would have to be worktrunk storing its own session_id โ†’ worktree mapping, not just passing a variable through.

That leaves a real product question I don't think triage should pick for you: when a session legitimately enters a worktree mid-run, should the marker follow it? Launch-pinning says no and makes the reported bug disappear; following-on-entry says yes and needs the mapping above to tell a worktree entry apart from a cd to go read a file.

No PR

The failing transition fires inside a live agent session, which CI can't drive โ€” per the repo's own bar for this, a fix premised on it would ship unverified. The three consequences you list are also unaffected by which target gets chosen except the third: the non-repo exit 1 swallowed by || true is wrong under every option, since a hook that can't find a repo should be a no-op rather than a suppressed failure.

Sources and verification notes

Codebase claims checked at 03ae3b6f60abff4b67f4bb916862c3c656d59282.

  • Site count from grep -rn "marker set\|marker clear" across tracked files, excluding docs, snapshots, and src/**.rs. The Claude Code file's 6 are UserPromptSubmit, Notification, PreToolUse(AskUserQuestion), PermissionRequest, Stop, SessionEnd; Codex has 4 (no Notification, no PreToolUse); Gemini has 3 (BeforeAgent, AfterAgent, SessionEnd).
  • -C <path> confirmed as a global flag โ€” src/cli/mod.rs#L257-L263. The contrast you noted holds: WorktreeRemove passes -C "$p" and WorktreeCreate cds to CLAUDE_PROJECT_DIR; the marker hooks pass nothing.
  • Upstream quotes are from the Claude Code hooks reference (https://code.claude.com/docs/en/hooks.md), fetched 2026-08-28: the worktree note under "Reference scripts by path", the "Handlers run in the current directory" line, and the "Common input fields" table. Field list above is that table verbatim, minus fields marked subagent-only.
  • Not verified: that a cd mid-session actually relocates the hook process in a running Claude Code session. The two documented facts compose to it, but this session has no agent CLI to observe it in โ€” which is the reason there's no PR here rather than a fix.

worktrunk-bot avatar Aug 28 '26 02:08 worktrunk-bot

What's the current status of this?

max-sixty avatar Sep 06 '26 18:09 max-sixty

Two of the three consequences are fixed on main; the third is a follow-up scoped to Codex and Gemini, and the upstream premise for deferring it has moved for Gemini.

Landed

  • #3956 (merged 2026-08-29) โ€” all six Claude Code marker hooks now pass -C "$CLAUDE_PROJECT_DIR" (plugins/worktrunk/hooks/hooks.json#L8-L62), which covers consequences one and two. It also settles the product question triage left open, by choosing launch-pinning: the marker stays on the launch worktree even after EnterWorktree, so it does not follow a mid-session worktree entry.
  • #3981 (merged this morning) โ€” marker set / marker clear are now a no-op outside a git repository rather than an exit 1 swallowed by || true. That fix is in wt itself, not the manifests, so it applies to every host. Consequence three.

Outstanding

Codex (4 calls) and Gemini (3 calls) are still unscoped. #3956 deferred them "until their hook harnesses expose a stable session project directory" โ€” checking that condition against upstream today, it resolves differently for the two:

  • Gemini: condition met, and the drift looks absent already. hookRunner.ts spawns each hook with cwd: input.cwd, and input.cwd is config.getWorkingDir() โ€” a private readonly field assigned once at Config construction, with no setter. The same runner exports GEMINI_PROJECT_DIR (plus a compatibility CLAUDE_PROJECT_DIR) set to that value. So the host already pins the hook process to the session's launch directory, and an explicit -C "$GEMINI_PROJECT_DIR" is available if you'd rather the pin be ours than depend on that host behavior.
  • Codex: no equivalent to pass. Hook commands run under current_dir(cwd) where cwd is turn_context.cwd, a per-turn session value rather than the agent shell's cwd, and the manifest interpolates only PLUGIN_ROOT. There is no project-dir variable, and the cd-retargeting shape doesn't map onto a turn-scoped directory the same way.

I haven't opened a PR for the Gemini pin: it would be belt-and-braces over behavior the host already provides, and per the repo's bar the transition can't be exercised from CI. Say the word and I'll send it.

Sources and verification notes

Worktrunk claims checked at 7d08f67 (main). Remaining unscoped call sites: .codex-plugin/plugin.json#L19-L50 (4) and hooks/hooks.json#L8-L28 (3). OpenCode remains pinned via cwd: directory in dev/opencode-plugin.ts#L36-L39.

Upstream read from the default branch of each repo on 2026-09-06, via the contents API:

  • Gemini: packages/core/src/hooks/hookRunner.ts โ€” env block sets GEMINI_PROJECT_DIR: input.cwd, GEMINI_CWD: input.cwd, CLAUDE_PROJECT_DIR: input.cwd; spawn(...) is passed cwd: input.cwd; a separate expansion path substitutes $GEMINI_PROJECT_DIR into command strings. packages/core/src/hooks/hookEventHandler.ts builds the input with cwd: this.context.config.getWorkingDir(); packages/core/src/config/config.ts declares private readonly cwd: string assigned once as params.cwd ?? process.cwd() and returns it from getWorkingDir().
  • Codex: codex-rs/hooks/src/engine/command_runner.rs โ€” run_command applies .current_dir(cwd); codex-rs/hooks/src/engine/dispatcher.rs threads that cwd from the event, and codex-rs/core/src/hook_runtime.rs populates every event request with turn_context.cwd. No project-dir env var is exported to the command.

Not verified: that these are the versions users actually run (both were read at upstream HEAD, not at a release tag), and โ€” as before โ€” that a cd mid-session relocates a hook process in a live agent, which this environment still can't observe.

worktrunk-bot avatar Sep 06 '26 18:09 worktrunk-bot

Closing this. As far as the source shows, none of the four hosts still move the marker when the agent runs cd mid-session.

  • Claude Code is fixed on main and has a test. Every hook now goes through wt config plugins claude hook (#4304), which resolves markers against CLAUDE_PROJECT_DIR and uses the process cwd only if that variable is unset (plugins.rs#L177). test_claude_hook_markers_follow_project_dir covers it.
  • Outside a repository, marker set/clear now does nothing instead of exiting 1 (#3981). That covers every host.
  • Codex doesn't have this bug. #4074 tried to pin it and was closed after the author confirmed in the Codex sources that the hook runs in turn_context.cwd, and an agent's cd can't move that. The marker hooks now ship as the separate worktrunk-markers plugin (#4707), still without -C, which is fine given that.
  • Gemini already pins the hook process to the launch directory, as described in the earlier comment. Nobody asked for the optional -C "$GEMINI_PROJECT_DIR" belt-and-braces PR, so I haven't opened it.
  • OpenCode was pinned from the start.

None of this has been watched in a live agent session, since CI can't drive one. If you see a marker land on the wrong repository, or want the explicit Gemini pin anyway, reopen this.

worktrunk-bot avatar Nov 22 '26 09:11 worktrunk-bot