Skip to content

chore(ci): add bash clean-worktrees helper + stop-hook nudge - #2796

Merged
zackees merged 2 commits into
masterfrom
chore/clean-worktrees-helper
Jun 5, 2026
Merged

zackees merged 2 commits into
masterfrom
chore/clean-worktrees-helper

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

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:

    1. plain git worktree remove --force
    2. on Windows failure (Invalid argument from read-only .git/ objects): clear the read-only attribute on every file (chmod -R u+w equivalent that works on Windows), then retry
    3. last-resort fallback: clud trash --cross-volume (quarantine via the clud trash daemon, per clud-windows-trash skill)

    Always runs git worktree prune at the end. Flags: --dry-run, --all.

  • clean-worktrees — thin shell wrapper exposing bash clean-worktrees alongside bash 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/, run bash clean-worktrees to 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)

$ bash clean-worktrees --dry-run
[dry-run] SKIP   chore-clean-wt              (  677.6 MB)  uncommitted changes
[dry-run] SKIP   fix-channels-error          (    1.4 GB)  unpushed commits vs upstream
[dry-run] REMOVE fix-esp32-size              (       0 B)  orphan directory (no .git)

[dry-run] 0 removed, 2 skipped (unsafe), 0 B reclaimed

Live run successfully removed the fix-esp32-size orphan directory via the git+rmtree path 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 lint passes
  • uv run pytest ci/tests/test_clean_worktrees.py — 6/6 pass
  • Manual smoke test on Windows: orphan dir removed, dirty/unpushed worktrees correctly skipped
  • Confirm on Linux/macOS that the Windows-specific fallbacks are no-ops (the git worktree remove --force succeeds on step 1 there)

Summary by CodeRabbit

  • New Features

    • Added a CI utility to scan, classify, and safely remove stale agent worktrees (supports preview/dry-run, Windows-aware removal, and final pruning), with summary reporting and nonzero exit on failures
    • Added CI warnings when stale worktree counts exceed a threshold
  • Tests

    • Added unit tests for worktree safety classification and byte-formatting
  • Chores

    • Updated shell wrapper to reliably invoke the worktree cleanup utility

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

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Stale Worktree Detection and Cleanup

Layer / File(s) Summary
Data contracts and utilities
ci/clean-worktrees.py
WorktreeStatus and RemovalResult dataclasses; run_git(), directory_size_bytes(), and format_bytes() provide git and filesystem helpers.
Worktree safety classification
ci/clean-worktrees.py
classify_worktree() treats orphan directories as safe, checks git status --porcelain for uncommitted changes, and compares logs against upstream or origin/master to detect unpushed commits.
Worktree removal with Windows strategy
ci/clean-worktrees.py
clear_readonly() fixes Windows read-only bits; remove_worktree() tries git worktree remove --force, retries after clearing permissions, falls back to shutil.rmtree with _rmtree_onerror, and finally uses clud trash --cross-volume if needed.
CLI orchestration and entry point
ci/clean-worktrees.py
list_worktree_paths() enumerates candidates; main() parses --dry-run/--all, classifies and conditionally removes worktrees, tallies reclaimed bytes, runs git worktree prune on non-dry runs, and exits with status reflecting failures.
Shell wrapper entry point
clean-worktrees
Adds Bash shebang, set -e, cd to script dir, and invokes the cleaner via uv run ci/clean-worktrees.py "$@".
Stop hook integration and warnings
ci/hooks/check-on-stop.py
Adds WORKTREES_DIR and STALE_WORKTREE_THRESHOLD, count_stale_worktrees() and warn_stale_worktrees(), and calls the warning in major main() exit paths.
Unit and integration tests
ci/tests/test_clean_worktrees.py
Dynamic import helper for hyphenated filename, git/repo/worktree test helpers, tests for orphan, missing origin/upstream, upstream-tracking worktree, uncommitted changes, unpushed commits, and format_bytes() tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I hopped through worktrees, one by one,

sniffed stale clones where chores were done,
I chmod’d the stubborn, pruned the rest,
hid the trash and passed the test—
now disks are lighter, and I nap, my quest complete.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% 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 'chore(ci): add bash clean-worktrees helper + stop-hook nudge' accurately summarizes the main changes: adding a bash wrapper script for worktree cleanup and a nudge in the stop hook for stale worktrees.
Linked Issues check ✅ Passed The PR addresses two of three linked issue objectives: a clean-worktrees helper script (#2610 ask 2) and a stop-hook nudge for stale worktrees (#2610 ask 3). Auto-cleanup on agent completion (#2610 ask 1) is explicitly not addressed, as noted in the PR summary.
Out of Scope Changes check ✅ Passed All changes align with the stated objectives: ci/clean-worktrees.py implements the worktree cleanup helper, clean-worktrees wraps it as a bash script, ci/hooks/check-on-stop.py adds the stop-hook nudge, and ci/tests/test_clean_worktrees.py tests the helper logic. No unrelated changes detected.

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

✨ 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 chore/clean-worktrees-helper

Warning

Review ran into problems

🔥 Problems

Stopped 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 @coderabbit review after the pipeline has finished.


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: 5

🧹 Nitpick comments (1)
ci/hooks/check-on-stop.py (1)

134-136: ⚡ Quick win

Replace 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

📥 Commits

Reviewing files that changed from the base of the PR and between 787de45 and 5369f82.

📒 Files selected for processing (4)
  • ci/clean-worktrees.py
  • ci/hooks/check-on-stop.py
  • ci/tests/test_clean_worktrees.py
  • clean-worktrees

Comment thread ci/clean-worktrees.py Resolved
Comment thread ci/clean-worktrees.py Resolved
Comment thread ci/clean-worktrees.py Resolved
Comment thread ci/hooks/check-on-stop.py Resolved
Comment thread ci/tests/test_clean_worktrees.py Resolved
- 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]>
@zackees

zackees commented Jun 5, 2026

Copy link
Copy Markdown
Member Author

CodeRabbit review addressed in 7253d08:

  • Removed default value from run_git's cwd parameter (#3361810484)
  • Fully typed _rmtree_onerror callback and dropped # type: ignore (#3361810508)
  • Replaced generator/list comprehensions in list_worktree_paths and main with explicit for-loops (#3361810517)
  • Replaced the sum(1 for …) counting expression in count_stale_worktrees with an explicit loop and made it raise a descriptive OSError instead of silently returning 0; warn_stale_worktrees catches it so the stop hook stays non-fatal but the failure is no longer silent (#3361810523 + nitpick)
  • test_clean_worktrees.py: added -> ModuleType annotation, hoisted import sys to module scope, tearDown now handles KeyboardInterrupt before OSError (#3361810527)

Drive-by KBI002 fixes on pre-existing handlers in the same files (call handle_keyboard_interrupt(ki) / _thread.interrupt_main() per the repo's KBI checker).

Verified: bash lint green, uv run python -m unittest ci.tests.test_clean_worktrees 6/6 pass, uv run python ci/clean-worktrees.py --dry-run exits 0.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5369f82 and 7253d08.

📒 Files selected for processing (3)
  • ci/clean-worktrees.py
  • ci/hooks/check-on-stop.py
  • ci/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

Comment thread ci/hooks/check-on-stop.py
Comment on lines +142 to +144
import _thread

_thread.interrupt_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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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).

@zackees
zackees merged commit e5437ef into master Jun 5, 2026
28 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
@zackees
zackees deleted the chore/clean-worktrees-helper branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

agents: .claude/worktrees/agent-* accumulate (11 dirs, 1.8GB after one session) — git worktree remove fails on Windows

1 participant