Repository navigation
chore(ci): add bash clean-worktrees helper + stop-hook nudge - #2796
Conversation
Adds a Windows-safe cleanup helper for stale agent worktrees under `.claude/worktrees/` and a stop-hook reminder when they accumulate. - `ci/clean-worktrees.py`: classifies each worktree as safe (no uncommitted changes, no unpushed commits) or unsafe, then removes safe ones with a three-step strategy: plain `git worktree remove --force`, then the Windows-readonly-attribute workaround (clear read-only + retry), then `clud trash --cross-volume` as last-resort quarantine. Supports `--dry-run` and `--all` flags. Always runs `git worktree prune` at the end and prints a summary (`N removed, M skipped, bytes reclaimed`). - `clean-worktrees` shell wrapper exposes `bash clean-worktrees`. - `ci/hooks/check-on-stop.py` warns to stderr when there are more than 5 stale worktrees. - `ci/tests/test_clean_worktrees.py` covers the safety-classification logic against a real temporary git repo. Closes #2610 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAdds a Python utility and Bash wrapper to find and remove safe stale agent worktrees under .claude/worktrees/, with Windows-aware deletion fallbacks, a stop-hook warning when many worktrees accumulate, and unit tests covering classification and formatting helpers. ChangesStale Worktree Detection and Cleanup
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsStopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a 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: 5
🧹 Nitpick comments (1)
ci/hooks/check-on-stop.py (1)
134-136: ⚡ Quick winReplace generator-based counting with an explicit loop.
At Line 134-136, the
sum(1 for p in ...)comprehension-style counting violates the explicit-loop rule in this repo’s Python standards.
As per coding guidelines "Use explicit loops instead of list comprehensions for code clarity and debuggability".Proposed change
- return sum( - 1 for p in WORKTREES_DIR.iterdir() if p.is_dir() and not p.is_symlink() - ) + count = 0 + for p in WORKTREES_DIR.iterdir(): + if p.is_dir() and not p.is_symlink(): + count += 1 + return count🤖 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/check-on-stop.py` around lines 134 - 136, Replace the generator-based counting expression that returns sum(1 for p in WORKTREES_DIR.iterdir() if p.is_dir() and not p.is_symlink()) with an explicit loop: initialize a counter, iterate over WORKTREES_DIR.iterdir(), check p.is_dir() and not p.is_symlink() and increment the counter accordingly, then return the counter (use the same WORKTREES_DIR and the same checks to preserve behavior).
🤖 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/clean-worktrees.py`:
- Line 228: Add explicit parameter types to _rmtree_onerror to match
shutil.rmtree’s onerror callback signature and remove the "# type:
ignore[no-untyped-def]". Specifically, annotate func as Callable[..., Any] (or
Callable[[str], Any]), path as str, and exc_info as Tuple[Type[BaseException],
BaseException, TracebackType] (import Callable, Tuple, Type from typing and
TracebackType from types if needed), so the function signature for
_rmtree_onerror(func, path, exc_info) -> None is fully typed and the type ignore
can be dropped.
- Around line 51-53: The function signature for run_git currently sets cwd: Path
| None = None which violates the no-default-parameter rule; change the signature
to require cwd (e.g., cwd: Path | None) with no default and update any call
sites that rely on the implicit default to explicitly pass a Path or None;
ensure the type remains Path | None but remove the "= None" default from run_git
and adjust callers to supply the cwd argument when invoking run_git.
- Around line 244-246: The generator comprehension in list_worktree_paths and
the list comprehension that builds classifications in main should be replaced
with explicit loops for clarity and easier debugging: in list_worktree_paths
(function name) create an empty list, iterate over WORKTREES_DIR.iterdir(),
check p.is_dir() and not p.is_symlink(), append matching paths, then return
sorted(list) instead of passing a generator to sorted; in main replace the list
comprehension that produces classifications with an explicit loop that
constructs and appends each classification item to a list before using it,
keeping the same filtering/logic and variable names so behavior is unchanged.
In `@ci/hooks/check-on-stop.py`:
- Around line 129-140: The function count_stale_worktrees currently swallows
OSError and returns 0, hiding real filesystem failures; change the error
handling in count_stale_worktrees so that you do not convert OSError to a silent
zero—either remove the broad OSError except block to let the exception propagate
or catch OSError around WORKTREES_DIR.iterdir and raise a new descriptive
exception (including WORKTREES_DIR path and the original exception) so callers
fail fast and see the underlying error instead of a misleading count.
In `@ci/tests/test_clean_worktrees.py`:
- Around line 16-27: Add an explicit return type ModuleType to the helper
function _load_helper, move the local import sys to the file/module top-level
imports, and ensure sys.modules is still updated inside _load_helper;
additionally, in the tearDown method reorder or add exception handling so
KeyboardInterrupt is caught (or re-raised) before the broader OSError handler so
KeyboardInterrupt is not swallowed.
---
Nitpick comments:
In `@ci/hooks/check-on-stop.py`:
- Around line 134-136: Replace the generator-based counting expression that
returns sum(1 for p in WORKTREES_DIR.iterdir() if p.is_dir() and not
p.is_symlink()) with an explicit loop: initialize a counter, iterate over
WORKTREES_DIR.iterdir(), check p.is_dir() and not p.is_symlink() and increment
the counter accordingly, then return the counter (use the same WORKTREES_DIR and
the same checks to preserve behavior).
🪄 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: 8a0e87b3-5b67-44cc-abbf-4d5f7ef90019
📒 Files selected for processing (4)
ci/clean-worktrees.pyci/hooks/check-on-stop.pyci/tests/test_clean_worktrees.pyclean-worktrees
- clean-worktrees.py: drop default for run_git's cwd, fully type _rmtree_onerror (remove # type: ignore), rewrite generator/list comprehensions in list_worktree_paths and main as explicit loops. - check-on-stop.py: count_stale_worktrees now propagates a descriptive OSError instead of silently returning 0; warn_stale_worktrees catches it so the stop hook stays non-fatal but surfaces the cause on stderr; comprehension swapped for an explicit loop. - test_clean_worktrees.py: annotate _load_helper -> ModuleType, hoist sys/ModuleType to module-scope imports, handle KeyboardInterrupt before OSError in tearDown. - KBI002 fixes (pre-existing): every KeyboardInterrupt handler in the three touched files now also calls handle_keyboard_interrupt(ki) / _thread.interrupt_main() per the repo's KBI checker. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
CodeRabbit review addressed in 7253d08:
Drive-by KBI002 fixes on pre-existing handlers in the same files (call Verified: |
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/check-on-stop.py`:
- Around line 142-144: Import the _thread module at the top-level of the module
and remove the inline imports inside the exception handlers; replace the inner
"import _thread" occurrences with direct calls to _thread.interrupt_main() so
both handlers reuse the single module-level import (reference symbols: _thread
and interrupt_main).
🪄 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: 95395d92-7b2e-4920-bbbf-f2a2610ae92b
📒 Files selected for processing (3)
ci/clean-worktrees.pyci/hooks/check-on-stop.pyci/tests/test_clean_worktrees.py
🚧 Files skipped from review as they are similar to previous changes (2)
- ci/tests/test_clean_worktrees.py
- ci/clean-worktrees.py
| import _thread | ||
|
|
||
| _thread.interrupt_main() |
There was a problem hiding this comment.
Move _thread import to module scope to satisfy import-order rule.
Line 142 and Line 161 add inline stdlib imports inside exception blocks. Please import _thread once at the top-level import section and reuse it in both handlers.
As per coding guidelines "All system imports must be at the top of the file in proper order: standard library, third-party, local".
Also applies to: 161-163
🤖 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/check-on-stop.py` around lines 142 - 144, Import the _thread module
at the top-level of the module and remove the inline imports inside the
exception handlers; replace the inner "import _thread" occurrences with direct
calls to _thread.interrupt_main() so both handlers reuse the single module-level
import (reference symbols: _thread and interrupt_main).
Summary
Adds a Windows-safe cleanup helper for stale agent worktrees under
.claude/worktrees/plus a stop-hook reminder when they accumulate. Addresses asks 2 and 3 in #2610.Closes #2610
What was added
ci/clean-worktrees.py— classifies each worktree under.claude/worktrees/as safe (no uncommitted changes, no unpushed commits) or unsafe, then removes safe ones with a three-step strategy:git worktree remove --forceInvalid argumentfrom read-only.git/objects): clear the read-only attribute on every file (chmod -R u+wequivalent that works on Windows), then retryclud trash --cross-volume(quarantine via theclud trashdaemon, perclud-windows-trashskill)Always runs
git worktree pruneat the end. Flags:--dry-run,--all.clean-worktrees— thin shell wrapper exposingbash clean-worktreesalongsidebash test,bash lint, etc.ci/hooks/check-on-stop.py— when more than 5 stale worktrees exist, emits a one-line nudge to stderr:Note: <N> stale agent worktrees in .claude/worktrees/, runbash clean-worktreesto reclaim space. Fires on all three exit paths (lint-fail, test-fail, success).ci/tests/test_clean_worktrees.py— covers the safety classification logic (orphan dir, uncommitted changes, unpushed commits without upstream, clean tree with upstream) against real temporary git repos.Manual smoke test (this Windows box)
Live run successfully removed the
fix-esp32-sizeorphan directory via thegit+rmtreepath while correctly preserving the two worktrees with real work-in-progress.What is NOT addressed
Ask 1 in the issue is harness-level (auto-cleanup of agent worktrees by the Claude Code launcher) and is not actionable from inside the FastLED repo.
Test plan
bash lintpassesuv run pytest ci/tests/test_clean_worktrees.py— 6/6 passgit worktree remove --forcesucceeds on step 1 there)Summary by CodeRabbit
New Features
Tests
Chores