Repository navigation
fix(hooks): strip .claude/worktrees/<branch>/ prefix in crate_guard (#794) - #795
Conversation
`/clud-pr` and related skills work inside disposable worktrees under `.claude/worktrees/<branch>/`. The harness pins `$CLAUDE_PROJECT_DIR` to the main checkout, so an edit path that reaches `crate_guard.py` looks like `.claude/worktrees/<branch>/crates/fbuild-build/Cargo.toml` — relative-to-root that's `.claude/worktrees/<branch>/crates/fbuild-build`, which is not in `APPROVED_CRATE_DIRS` even though `crates/fbuild-build` is. Result: every worktree-based PR that touches a Cargo.toml in an already-allowed crate gets denied. Strip a leading `.claude/worktrees/<single-component>/` from `rel_dir` before the allowlist check. A worktree of this repo is still this repo with the same approved-crates contract; the path-shape was the only difference. New `test_crate_guard.py` covers: - direct member path still resolves (no regression); - worktree member path resolves to the same allowlisted member; - worktree workspace root normalizes to `""` (the root manifest slot); - worktree-attempted new crate is still rejected; - direct new crate is still rejected; - `_strip_worktree_prefix` only strips one segment, handles hyphenated branch names, and is a no-op on non-worktree paths. Closes #794 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthrough
ChangesWorktree prefix fix and tests
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/hooks/test_crate_guard.py`:
- Around line 1-121: This test coverage belongs in Rust, not a new Python
unittest module. Move the assertions around _strip_worktree_prefix and
relative_dir into the crate’s Rust test target, using the same cases currently
covered by StripWorktreePrefixTests and RelativeDirIntegrationTests so the
behavior stays validated. Keep the Python file out of the test suite and wire
the Rust tests to exercise the same crate_guard logic and APPROVED_CRATE_DIRS
expectations.
🪄 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: ca0d5142-a6ec-4581-b066-9b5cd95539b5
📒 Files selected for processing (2)
ci/hooks/crate_guard.pyci/hooks/test_crate_guard.py
| #!/usr/bin/env python3 | ||
| """Unit tests for the Cargo.toml-write crate guard hook (#794).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
| from unittest.mock import patch | ||
|
|
||
| from crate_guard import ( | ||
| APPROVED_CRATE_DIRS, | ||
| _strip_worktree_prefix, | ||
| relative_dir, | ||
| ) | ||
|
|
||
|
|
||
| class StripWorktreePrefixTests(unittest.TestCase): | ||
| """Direct unit coverage of the path-shape transform.""" | ||
|
|
||
| def test_strips_worktree_branch_prefix(self) -> None: | ||
| self.assertEqual( | ||
| _strip_worktree_prefix(".claude/worktrees/feat-x/crates/fbuild-build"), | ||
| "crates/fbuild-build", | ||
| ) | ||
|
|
||
| def test_no_strip_when_not_under_worktrees(self) -> None: | ||
| self.assertEqual( | ||
| _strip_worktree_prefix("crates/fbuild-build"), | ||
| "crates/fbuild-build", | ||
| ) | ||
|
|
||
| def test_returns_dot_when_path_was_only_the_worktree_dir(self) -> None: | ||
| # `.claude/worktrees/<branch>/Cargo.toml` -> after strip, the | ||
| # parent dir is the (empty) worktree root, which `relative_dir` | ||
| # later normalizes to "" (the workspace root manifest slot). | ||
| # `_strip_worktree_prefix` itself returns "." to keep the | ||
| # Path/posix conventions consistent for the caller. | ||
| self.assertEqual( | ||
| _strip_worktree_prefix(".claude/worktrees/feat-x/"), | ||
| ".", | ||
| ) | ||
|
|
||
| def test_only_strips_one_segment(self) -> None: | ||
| # Nested `.claude/worktrees/.claude/worktrees/...` should not | ||
| # double-strip — the regex anchors at start and matches once. | ||
| self.assertEqual( | ||
| _strip_worktree_prefix(".claude/worktrees/feat-x/.claude/worktrees/feat-y/crates/foo"), | ||
| ".claude/worktrees/feat-y/crates/foo", | ||
| ) | ||
|
|
||
| def test_branch_name_with_hyphens(self) -> None: | ||
| self.assertEqual( | ||
| _strip_worktree_prefix( | ||
| ".claude/worktrees/feat-zccache-embedded-790-phase1/crates/fbuild-build" | ||
| ), | ||
| "crates/fbuild-build", | ||
| ) | ||
|
|
||
|
|
||
| class RelativeDirIntegrationTests(unittest.TestCase): | ||
| """End-to-end coverage of `relative_dir` with a stubbed repo root.""" | ||
|
|
||
| def setUp(self) -> None: | ||
| # Use a real tempdir so `Path.resolve` produces a real abs path | ||
| # the harness can `relative_to` against. | ||
| self._tmp = tempfile.TemporaryDirectory() | ||
| self.root = Path(self._tmp.name).resolve() | ||
|
|
||
| def tearDown(self) -> None: | ||
| self._tmp.cleanup() | ||
|
|
||
| def _resolve(self, *parts: str) -> str: | ||
| """Materialize a Cargo.toml path under the fake root so | ||
| `Path.resolve()` doesn't tack on a CWD prefix.""" | ||
| full = self.root.joinpath(*parts, "Cargo.toml") | ||
| full.parent.mkdir(parents=True, exist_ok=True) | ||
| full.touch() | ||
| return str(full) | ||
|
|
||
| def test_direct_member_path_resolves(self) -> None: | ||
| path = self._resolve("crates", "fbuild-build") | ||
| with patch("crate_guard.repo_root", return_value=self.root): | ||
| self.assertEqual(relative_dir(path), "crates/fbuild-build") | ||
|
|
||
| def test_worktree_member_path_resolves_to_member(self) -> None: | ||
| path = self._resolve( | ||
| ".claude", "worktrees", "feat-zccache-embedded-790-phase1", | ||
| "crates", "fbuild-build", | ||
| ) | ||
| with patch("crate_guard.repo_root", return_value=self.root): | ||
| rel = relative_dir(path) | ||
| self.assertEqual(rel, "crates/fbuild-build") | ||
| self.assertIn(rel, APPROVED_CRATE_DIRS) | ||
|
|
||
| def test_worktree_workspace_root_normalizes_to_empty(self) -> None: | ||
| path = self._resolve(".claude", "worktrees", "feat-foo") | ||
| with patch("crate_guard.repo_root", return_value=self.root): | ||
| self.assertEqual(relative_dir(path), "") | ||
|
|
||
| def test_worktree_new_crate_still_rejected(self) -> None: | ||
| path = self._resolve( | ||
| ".claude", "worktrees", "feat-foo", | ||
| "crates", "fbuild-brand-new-crate", | ||
| ) | ||
| with patch("crate_guard.repo_root", return_value=self.root): | ||
| rel = relative_dir(path) | ||
| self.assertEqual(rel, "crates/fbuild-brand-new-crate") | ||
| self.assertNotIn(rel, APPROVED_CRATE_DIRS) | ||
|
|
||
| def test_direct_new_crate_still_rejected(self) -> None: | ||
| path = self._resolve("crates", "fbuild-brand-new-crate") | ||
| with patch("crate_guard.repo_root", return_value=self.root): | ||
| rel = relative_dir(path) | ||
| self.assertEqual(rel, "crates/fbuild-brand-new-crate") | ||
| self.assertNotIn(rel, APPROVED_CRATE_DIRS) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
Move this coverage into a Rust test target.
This new file extends Python-based test coverage, but the repo policy explicitly reserves Python for CI scripts, packaging, hooks, and PyO3 bindings. The behavior coverage should live in Rust instead of adding a new unittest module. As per coding guidelines, "Python is only for CI scripts, packaging, hooks, and PyO3 bindings — all tests, benchmarks, and application logic must be written in Rust."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ci/hooks/test_crate_guard.py` around lines 1 - 121, This test coverage
belongs in Rust, not a new Python unittest module. Move the assertions around
_strip_worktree_prefix and relative_dir into the crate’s Rust test target, using
the same cases currently covered by StripWorktreePrefixTests and
RelativeDirIntegrationTests so the behavior stays validated. Keep the Python
file out of the test suite and wire the Rust tests to exercise the same
crate_guard logic and APPROVED_CRATE_DIRS expectations.
Source: Coding guidelines
Closes #794. Prereq for #790–#793 (#789 zccache embedded sweep).
Problem
/clud-prruns inside worktrees under.claude/worktrees/<branch>/.The harness pins
$CLAUDE_PROJECT_DIRto the main checkout, so theedit path that reaches
crate_guard.pylooks like:relative_dir()returns.claude/worktrees/<branch>/crates/fbuild-build,which is not in
APPROVED_CRATE_DIRSeven thoughcrates/fbuild-buildis.Every worktree-based PR that touches a Cargo.toml in an allowed crate gets
denied. Bypassing the hook (Bash heredoc, etc.) defeats the safety net for
the actual case it's protecting against — new crate creation.
Fix
Strip a leading
.claude/worktrees/<one-component>/fromrel_dirbefore the allowlist check. A worktree of this repo is still this
repo with the same approved-crates contract; the path-shape was the
only difference.
_strip_worktree_prefixis implemented as a single regex^\.claude/worktrees/[^/]+(?:/|$), called once afterPurePosixPathnormalization. The
(?:/|$)branch makes the no-suffix case (aCargo.tomldirectly inside the worktree dir = the workspace rootmanifest) normalize cleanly to
"".Tests
ci/hooks/test_crate_guard.py(10 cases, all green):"";_strip_worktree_prefixonly strips one segment, handleshyphenated branch names, and is a no-op on non-worktree paths.
Test plan
ci/hooks/test_crate_guard.pygreen.ci/hooks/test_*.pysuite green (53 tests)..claude/worktrees/<branch>/crates/fbuild-build/succeeds..claude/worktrees/<branch>/crates/fbuild-NEW-CRATE/is still denied.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests