Skip to content

fix(hooks): strip .claude/worktrees/<branch>/ prefix in crate_guard (#794) - #795

Merged
zackees merged 1 commit into
mainfrom
fix/crate-guard-worktree-794
Jun 28, 2026
Merged

zackees merged 1 commit into
mainfrom
fix/crate-guard-worktree-794

Conversation

@zackees

@zackees zackees commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

Closes #794. Prereq for #790–#793 (#789 zccache embedded sweep).

Problem

/clud-pr runs inside worktrees under .claude/worktrees/<branch>/.
The harness pins $CLAUDE_PROJECT_DIR to the main checkout, so the
edit path that reaches crate_guard.py looks like:

.claude/worktrees/<branch>/crates/fbuild-build/Cargo.toml

relative_dir() returns .claude/worktrees/<branch>/crates/fbuild-build,
which is not in APPROVED_CRATE_DIRS even though crates/fbuild-build is.
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>/ 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.

_strip_worktree_prefix is implemented as a single regex
^\.claude/worktrees/[^/]+(?:/|$), called once after PurePosixPath
normalization. The (?:/|$) branch makes the no-suffix case (a
Cargo.toml directly inside the worktree dir = the workspace root
manifest) normalize cleanly to "".

Tests

ci/hooks/test_crate_guard.py (10 cases, all green):

  • direct member path still resolves (no regression);
  • worktree member path resolves to the same allowlisted member;
  • worktree workspace root normalizes to "";
  • 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.
uv run --no-project python -m unittest discover -s ci/hooks -p "test_*.py"
.....................................................
Ran 53 tests in 0.030s
OK

Test plan

  • ci/hooks/test_crate_guard.py green.
  • Full ci/hooks/test_*.py suite green (53 tests).
  • Manual: Edit a Cargo.toml under .claude/worktrees/<branch>/crates/fbuild-build/ succeeds.
  • Manual: Edit a Cargo.toml under .claude/worktrees/<branch>/crates/fbuild-NEW-CRATE/ is still denied.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved path handling so approved crate directories are recognized correctly when working in disposable worktrees.
    • Fixed normalization for worktree-based paths, including branch names with hyphens and workspace-root locations.
    • Tightened crate checks to avoid incorrectly allowing new crate directories in both worktree and direct checkout scenarios.
  • Tests

    • Added coverage for path normalization and crate directory validation to help prevent regressions.

`/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]>
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

crate_guard.py gains a _WORKTREE_PREFIX_RE regex and _strip_worktree_prefix() helper; relative_dir() now strips a leading .claude/worktrees/<branch>/ segment before checking against APPROVED_CRATE_DIRS. A new test file covers the helper's edge cases and integration behavior of relative_dir under both worktree and direct paths.

Changes

Worktree prefix fix and tests

Layer / File(s) Summary
Worktree prefix stripping
ci/hooks/crate_guard.py
Adds _WORKTREE_PREFIX_RE, _strip_worktree_prefix(), and applies it inside relative_dir() before the allowlist check.
Unit and integration tests
ci/hooks/test_crate_guard.py
New test file with StripWorktreePrefixTests (edge cases for the helper) and RelativeDirIntegrationTests (approved/rejected paths under worktrees and direct).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 A worktree once hid a crate from my sight,
The prefix confused me, the path wasn't right.
Now a regex peels back the .claude disguise,
And the allowlist sees through the worktree's disguise.
Hop hop—approved! No more denies! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: stripping the worktree prefix in crate_guard.
Linked Issues check ✅ Passed The code and tests match the issue: worktree paths are normalized and allowed crates remain accepted while new crates stay blocked.
Out of Scope Changes check ✅ Passed The PR stays focused on crate_guard path handling and its tests, with no obvious unrelated changes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/crate-guard-worktree-794

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.

@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 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4deca86 and 0010081.

📒 Files selected for processing (2)
  • ci/hooks/crate_guard.py
  • ci/hooks/test_crate_guard.py

Comment on lines +1 to +121
#!/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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 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

@zackees
zackees merged commit 2c84819 into main Jun 28, 2026
82 of 90 checks passed
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 29, 2026
@zackees
zackees deleted the fix/crate-guard-worktree-794 branch October 16, 2026 11:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

fix(hooks): crate_guard.py rejects Cargo.toml writes inside .claude/worktrees/ (blocks /clud-pr workflow)

1 participant