Skip to content

fix(hooks): harden .claude/settings.json cwd resolution (degenerate lockout fix) - #2295

Merged
zackees merged 1 commit into
masterfrom
fix-claude-hooks-cwd-resolution
Apr 18, 2026
Merged

zackees merged 1 commit into
masterfrom
fix-claude-hooks-cwd-resolution

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Every hook in .claude/settings.json was using git rev-parse --show-toplevel to locate the FastLED project root. This gets fooled when the agent's shell CWD drifts into a nested .git directory — e.g., fbuild/PIO creates its own git init under .build/pio/<env>/ for incremental-build caching.

When that happens, git rev-parse returns the nested toplevel, the hook tries to cd there and exec ci/hooks/<script>.py, which doesn't exist there, and exits non-zero — blocking every subsequent tool call. The Stop hook hits the same bug and re-fires on each session cycle, trapping the agent in a loop that only a manual rm -rf .git or session reset can break.

What this fixes

  • Agent CI/CD sessions getting locked out after a cd into any build-tool-created nested-git directory.
  • Stop-hook feedback loop with identical error message on every turn.
  • Downstream effect: agent cannot commit, push, open PRs, read files, or even exit its own worktree once wedged.

Fix

Replace git rev-parse --show-toplevel with a shell walk-up for pyproject.toml (the real FastLED project marker). Pattern used across all 11 hook commands:

d=$PWD
while [ "$d" != / ] && [ ! -f "$d/pyproject.toml" ]; do d=$(dirname "$d"); done
[ -f "$d/pyproject.toml" ] && cd "$d" && exec uv run python ci/hooks/<script>.py \
  || { echo 'FastLED hook skipped: project root (pyproject.toml) not found above $PWD' >&2; exit 0; }

Two key properties:

  1. Walk-up past nested .git dirs — stops only at a directory that actually has pyproject.toml, which build-tool scratch dirs don't.
  2. exec for the real hook path — replaces the bash process, so genuine hook failures (forbidden commands, TDD guard, etc.) still propagate their non-zero exit code and correctly block the tool call. Only the "project root not found" branch becomes non-blocking.

Result: if the CWD is outside any FastLED checkout or deep inside a nested scratch dir, the hook emits one stderr warning and exits 0 — the agent gets a soft skip instead of a hard lockout.

Verification

Reproduced the exact failure in a /tmp simulation (nested .git under a pyproject.toml root):

  • Old pattern: git rev-parse returned the nested toplevel → python ci/hooks/test_hook.py → can't open file. Hook fails; next tool call blocked.
  • New pattern: walks up past .build/pio/uno/.git → finds pyproject.toml at the real root → runs hook correctly.

Also verified CWD outside any project (/tmp/nowhere-special): walks to /, no marker → single warning line, exit 0, subsequent tools unaffected.

$ python -c "import json; d=json.load(open('.claude/settings.json'))"
# validates

$ grep -c 'git rev-parse' .claude/settings.json
0

Scope

11 hook commands migrated (PreToolUse x4, PostToolUse x3, SessionStart, Stop, Notification, UserPromptSubmit). No functional change to hook behavior — only how they locate the root. No other files touched.

Test plan

  • Simulation of old-pattern failure — reproduces the lockout.
  • Simulation of new-pattern success on same layout — no lockout.
  • JSON validity check.
  • grep confirms no hook still uses git rev-parse.
  • Next agent session starting from a nested build dir does not wedge.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Updated development hook resolution logic to improve project directory detection during script execution.
    • Enhanced hook configuration documentation with clearer guidance on directory resolution behavior and fallback handling.

…it toplevel

Every hook in .claude/settings.json used
  cd "$(git rev-parse --show-superproject-working-tree || git rev-parse --show-toplevel || echo .)"
to locate the project root. This gets fooled when the agent's shell
CWD drifts into a nested .git dir (e.g. fbuild/PIO creates its own
git init under .build/pio/<env>/ for caching). git rev-parse returns
the nested toplevel, the hook tries to cd there and exec
ci/hooks/<script>.py which doesn't exist, and exits non-zero —
blocking EVERY subsequent tool call. The Stop hook hits the same
bug and fires on every cycle, trapping the session in a loop that
only a manual `rm -rf .git` or /clear can break.

Reproduced the exact failure in /tmp simulation: nested .git under
pyproject.toml root caused `git rev-parse --show-toplevel` to
return the nested dir; old hook pattern then failed to locate
`ci/hooks/<name>.py`, blocking tool use.

Fix: all 11 hook commands now walk up from $PWD looking for
pyproject.toml (the real project marker). If found, cd there and
exec the python hook. If not found (cwd outside any FastLED
checkout), emit one stderr warning and exit 0 — skip cleanly
instead of hard-blocking.

Key property: `exec` replaces the bash process, so real hook
failures (e.g. forbidden-command detection) still propagate their
non-zero exit code and correctly block the tool call. Only the
"project root not found" case becomes non-blocking, which is
exactly the degenerate behavior we want to prevent.

Verified:
- cd into nested .git under a real pyproject.toml → walks up past
  nested .git, finds pyproject.toml, hook runs at correct root.
- cd into /tmp/nowhere → walks to /, no marker, hook skips with
  single stderr line; subsequent tools unaffected.
- json.load validates; all 11 hook commands migrated; none still
  reference git rev-parse.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Updated hook command resolution logic in .claude/settings.json to locate project root by walking up from the current working directory to find pyproject.toml, rather than using git rev-parse. Hooks execute from the discovered directory or skip gracefully with a warning if the project file is not found.

Changes

Cohort / File(s) Summary
Hook Resolution Configuration
.claude/settings.json
Modified directory resolution strategy for all hook types. Changed from git rev-parse-based location to walking parent directories for pyproject.toml. Added fallback behavior (warning + exit 0) when project root cannot be determined. Added documentation comment describing the new search logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Hoppity-hop, up the tree we go,
Finding pyproject.toml down below,
No more git commands leading us astray,
Hooks now know the proper way!
With graceful exits when paths are bare,
Our scripts run with utmost care. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(hooks): harden .claude/settings.json cwd resolution (degenerate lockout fix)' directly and accurately describes the main change: improving the working directory resolution logic in hooks to fix a lockout issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-claude-hooks-cwd-resolution

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.claude/settings.json:
- Line 2: The current _cwd_resolution stops at the first pyproject.toml; change
its logic/text to require both pyproject.toml and the specific hook script
(pattern "ci/hooks/<script>.py") to exist before stopping the upward walk, so
the hook only cds into a directory that contains the actual hook; update the
_cwd_resolution description accordingly and apply this same requirement to each
hook command entry (use the hook=ci/hooks/<script>.py pattern referenced in the
review) so the resolver continues walking until both markers are present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 17682868-3ffc-4d13-91f8-ed587919100a

📥 Commits

Reviewing files that changed from the base of the PR and between 048c888 and e6a98d0.

📒 Files selected for processing (1)
  • .claude/settings.json

Comment thread .claude/settings.json
@@ -1,12 +1,13 @@
{
"_cwd_resolution": "Each hook walks up from $PWD looking for pyproject.toml (the project-root marker). If found, cd there and exec the hook script. If not found (cwd outside project, or inside a nested build dir with its own .git), the hook skips with a warning instead of blocking every subsequent tool call. Do NOT use `git rev-parse --show-toplevel` here — it gets fooled by nested .git dirs that build tools create under .build/.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Keep walking until the actual hook script exists, not just pyproject.toml.

Stopping at the first pyproject.toml can still lock the agent out if $PWD is inside a nested Python/build project that has its own pyproject.toml but no ci/hooks/<script>.py. In that case the command execs Python from the wrong directory, the hook script path is missing, and the non-zero failure propagates.

Please make the root marker FastLED-specific, e.g. require both pyproject.toml and the target hook script before stopping the walk.

Suggested pattern for each hook command
- d=$PWD; while [ "$d" != / ] && [ ! -f "$d/pyproject.toml" ]; do d=$(dirname "$d"); done; [ -f "$d/pyproject.toml" ] && cd "$d" && exec uv run python ci/hooks/check_forbidden_commands.py || { echo 'FastLED hook skipped: project root (pyproject.toml) not found above $PWD' >&2; exit 0; }
+ hook=ci/hooks/check_forbidden_commands.py; d=$PWD; while [ "$d" != / ] && { [ ! -f "$d/pyproject.toml" ] || [ ! -f "$d/$hook" ]; }; do d=$(dirname "$d"); done; [ -f "$d/pyproject.toml" ] && [ -f "$d/$hook" ] && cd "$d" && exec uv run python "$hook" || { echo "FastLED hook skipped: project root containing $hook not found above $PWD" >&2; exit 0; }

Apply the same hook=ci/hooks/<script>.py pattern to the other hook commands.

Also applies to: 10-10, 19-19, 28-28, 33-33, 45-45, 50-50, 55-55, 67-67, 78-78, 89-89, 100-100

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.claude/settings.json at line 2, The current _cwd_resolution stops at the
first pyproject.toml; change its logic/text to require both pyproject.toml and
the specific hook script (pattern "ci/hooks/<script>.py") to exist before
stopping the upward walk, so the hook only cds into a directory that contains
the actual hook; update the _cwd_resolution description accordingly and apply
this same requirement to each hook command entry (use the
hook=ci/hooks/<script>.py pattern referenced in the review) so the resolver
continues walking until both markers are present.

@zackees
zackees merged commit 2803449 into master Apr 18, 2026
3 checks passed
@zackees
zackees deleted the fix-claude-hooks-cwd-resolution branch April 18, 2026 03:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant