Install command
Provided
Cleans up temporary files, caches, and resources when Claude session ends. This Stop hook provides comprehensive environment cleanup for development projects, automatically removing temporary files, build artifacts, cache directories, and system-specific files across multiple platforms.
Open the source and read safety notes before installing.
Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.
Decision playbook
Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.
0
78
—
No baseline selected
No major trust-signal divergence detected in the current selection.
Confirm ownership and provenance before trusting install instructions.
Source link availableRequired
Open the canonical repository and verify ownership.
Source provenance statusRequired
Marked as source-backed.
Metadata reviewed
Registry metadata indicates a reviewed listing.
Validate risk disclosures before installation or API wiring.
Safety notes presentRequired
Review the listed safety guidance before running commands.
Privacy notes presentRequired
Review data handling notes before connecting accounts or secrets.
Trust level risk gateRequired
Trust level does not block evaluation.
Check package metadata and artifact integrity signals.
Install payload available
Install or copy payload is available for review.
Package verification flag
No package verification flag provided.
Checksum metadata
No checksum provided for downloaded artifact.
Use compare context to validate trade-offs before adoption.
Compare tray has multiple entries
Add at least one more entry to compare trust differences.
Baseline comparison available
No baseline peer selected yet.
Diverging trust signals identified
No major trust-signal divergence found.
Setup at a glance
Copy-ready — paste the snippet to get started.
Install command
Provided
Config snippet
Provided
Copy snippet
Provided
Prerequisites
None
Platforms
1 listed
Difficulty
0/100
Adoption plan
Current risk score 16/100. Use staged verification before broader rollout.
Validate source and review signals before any execution.
Confirm source provenanceRequired
Source URL/provenance metadata is present.
Confirm metadata review state
Listing has review metadata.
Verify install payload
Install/config payload exists and can be inspected.
Confirm safety, privacy, and package integrity signals.
Review safety notesRequired
Safety notes are present.
Review privacy notesRequired
Privacy notes are present.
Verify package integrity metadata
No package verification/checksum metadata.
Adopt in controlled steps based on the selected plan.
Run in isolated sandbox firstRequired
Use a constrained sandbox and observe behavior across multiple tasks.
Roll out graduallyRequired
Roll out to a small cohort before wider usage.
Set monitoring and fallback
Define rollback path and monitor errors after adoption.
Evidence readiness
Required evidence gates are covered (5/6 signals complete).
Source repository/provenance is listed.
Required in this preset
Review metadata is present.
Required in this preset
Safety notes are present.
Required in this preset
Privacy notes are present.
Optional in this preset
Package integrity metadata is missing.
Optional in this preset
Install payload is available.
Required in this preset
Required evidence gates are covered for this preset.
Decision timeline
5/6 steps complete with no blocking gaps for this preset.
triage
Source/provenance metadata is available.
triage
Review metadata is available.
verify
Safety notes are available.
verify
Privacy notes are available.
verify
Package integrity metadata is missing.
rollout
Install payload is available.
No required blockers for this timeline preset.
Safety & privacy surface
1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.
#!/usr/bin/env bash
echo "🧹 Starting environment cleanup..." >&2
# Initialize cleanup counters
FILES_REMOVED=0
SPACE_FREED=0
ERRORS=0
# Function to safely remove files and count them
safe_remove() {
local pattern="$1"
local description="$2"
echo "📁 Cleaning $description..." >&2
if [ "$pattern" = "__pycache__" ]; then
# Special handling for __pycache__ directories
FOUND=$(find . -type d -name "__pycache__" 2>/dev/null | wc -l | xargs)
if [ "$FOUND" -gt 0 ]; then
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null && echo " ✅ Removed $FOUND __pycache__ directories" >&2
FILES_REMOVED=$((FILES_REMOVED + FOUND))
else
echo " ℹ️ No __pycache__ directories found" >&2
fi
else
# Handle file patterns
FOUND=$(find . -name "$pattern" 2>/dev/null | wc -l | xargs)
if [ "$FOUND" -gt 0 ]; then
find . -name "$pattern" -delete 2>/dev/null && echo " ✅ Removed $FOUND $description files" >&2
FILES_REMOVED=$((FILES_REMOVED + FOUND))
else
echo " ℹ️ No $description files found" >&2
fi
fi
}
# Clean temporary files
safe_remove "*.tmp" "temporary"
safe_remove "*.log" "log"
safe_remove "*.bak" "backup"
safe_remove "*~" "editor backup"
# Clean system-specific files
case "$(uname)" in
Darwin)
safe_remove ".DS_Store" "macOS metadata"
safe_remove "._*" "macOS resource fork"
;;
CYGWIN*|MINGW*|MSYS*)
safe_remove "Thumbs.db" "Windows thumbnail cache"
safe_remove "Desktop.ini" "Windows desktop config"
;;
Linux)
safe_remove ".directory" "KDE directory config"
;;
esac
# Clean Python cache files
echo "🐍 Cleaning Python artifacts..." >&2
safe_remove "*.pyc" "Python bytecode"
safe_remove "*.pyo" "Python optimized bytecode"
safe_remove "__pycache__" "Python cache directories"
# Clean Node.js related files
if [ -f "package.json" ]; then
echo "🟢 Node.js project detected - cleaning caches..." >&2
# Clean npm cache
if command -v npm &> /dev/null; then
echo " 🗑️ Verifying npm cache..." >&2
if npm cache verify 2>/dev/null; then
echo " ✅ npm cache verified and cleaned" >&2
else
echo " ⚠️ npm cache verification failed" >&2
ERRORS=$((ERRORS + 1))
fi
fi
# Clean node_modules/.cache if it exists
if [ -d "node_modules/.cache" ]; then
CACHE_SIZE=$(du -sh node_modules/.cache 2>/dev/null | cut -f1 || echo "unknown")
rm -rf node_modules/.cache 2>/dev/null && echo " ✅ Removed node_modules/.cache ($CACHE_SIZE)" >&2
fi
fi
# Clean build artifacts
echo "🔧 Cleaning build artifacts..." >&2
safe_remove "*.o" "object files"
safe_remove "*.obj" "Windows object files"
safe_remove "*.so" "shared object files"
safe_remove "*.dll" "Windows library files"
safe_remove "*.dylib" "macOS dynamic libraries"
# Clean IDE and editor files
echo "💻 Cleaning IDE artifacts..." >&2
safe_remove ".vscode/settings.json.bak" "VS Code backup settings"
if [ -d ".vscode" ]; then
find .vscode -name "*.log" -delete 2>/dev/null || true
fi
# Clean test artifacts
echo "🧪 Cleaning test artifacts..." >&2
safe_remove "coverage.xml" "coverage report"
safe_remove ".coverage" "Python coverage data"
if [ -d "coverage" ]; then
rm -rf coverage 2>/dev/null && echo " ✅ Removed coverage directory" >&2
fi
if [ -d ".nyc_output" ]; then
rm -rf .nyc_output 2>/dev/null && echo " ✅ Removed .nyc_output directory" >&2
fi
# Clean Docker artifacts if Docker is available
if command -v docker &> /dev/null && docker info &> /dev/null 2>&1; then
echo "🐳 Docker detected - cleaning unused resources..." >&2
# Clean dangling images
DANGLING_IMAGES=$(docker images -f "dangling=true" -q 2>/dev/null | wc -l | xargs)
if [ "$DANGLING_IMAGES" -gt 0 ]; then
docker image prune -f &> /dev/null && echo " ✅ Removed $DANGLING_IMAGES dangling Docker images" >&2
else
echo " ℹ️ No dangling Docker images found" >&2
fi
fi
# Calculate disk space if possible
echo "💾 Calculating disk space usage..." >&2
if command -v du &> /dev/null; then
# Check cache directories
for cache_dir in ~/.npm ~/.cache ~/.cargo/registry; do
if [ -d "$cache_dir" ]; then
CACHE_SIZE=$(du -sh "$cache_dir" 2>/dev/null | cut -f1 || echo "unknown")
echo " 📊 $cache_dir: $CACHE_SIZE" >&2
fi
done
fi
# Report cleanup summary
echo "" >&2
echo "📋 Cleanup Summary:" >&2
echo " 🗑️ Files/directories removed: $FILES_REMOVED" >&2
echo " ⚠️ Errors encountered: $ERRORS" >&2
if [ "$ERRORS" -eq 0 ]; then
echo "✅ Environment cleanup completed successfully" >&2
else
echo "⚠️ Environment cleanup completed with $ERRORS errors" >&2
fi
echo "" >&2
echo "💡 Cleanup Tips:" >&2
echo " • Run 'docker system prune' for more aggressive Docker cleanup" >&2
echo " • Use 'npm cache clean --force' for complete npm cache reset" >&2
echo " • Consider 'pip cache purge' for Python package cache cleanup" >&2
exit 0{
"hooks": {
"stop": {
"script": "./.claude/hooks/environment-cleanup-handler.sh"
}
}
}.claude/settings.local.json~/.claude/settings.json.claude/settings.json{
"hooks": {
"stop": {
"script": "./.claude/hooks/environment-cleanup-handler.sh"
}
}
}
#!/usr/bin/env bash
echo "🧹 Starting environment cleanup..." >&2
# Initialize cleanup counters
FILES_REMOVED=0
SPACE_FREED=0
ERRORS=0
# Function to safely remove files and count them
safe_remove() {
local pattern="$1"
local description="$2"
echo "📁 Cleaning $description..." >&2
if [ "$pattern" = "__pycache__" ]; then
# Special handling for __pycache__ directories
FOUND=$(find . -type d -name "__pycache__" 2>/dev/null | wc -l | xargs)
if [ "$FOUND" -gt 0 ]; then
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null && echo " ✅ Removed $FOUND __pycache__ directories" >&2
FILES_REMOVED=$((FILES_REMOVED + FOUND))
else
echo " ℹ️ No __pycache__ directories found" >&2
fi
else
# Handle file patterns
FOUND=$(find . -name "$pattern" 2>/dev/null | wc -l | xargs)
if [ "$FOUND" -gt 0 ]; then
find . -name "$pattern" -delete 2>/dev/null && echo " ✅ Removed $FOUND $description files" >&2
FILES_REMOVED=$((FILES_REMOVED + FOUND))
else
echo " ℹ️ No $description files found" >&2
fi
fi
}
# Clean temporary files
safe_remove "*.tmp" "temporary"
safe_remove "*.log" "log"
safe_remove "*.bak" "backup"
safe_remove "*~" "editor backup"
# Clean system-specific files
case "$(uname)" in
Darwin)
safe_remove ".DS_Store" "macOS metadata"
safe_remove "._*" "macOS resource fork"
;;
CYGWIN*|MINGW*|MSYS*)
safe_remove "Thumbs.db" "Windows thumbnail cache"
safe_remove "Desktop.ini" "Windows desktop config"
;;
Linux)
safe_remove ".directory" "KDE directory config"
;;
esac
# Clean Python cache files
echo "🐍 Cleaning Python artifacts..." >&2
safe_remove "*.pyc" "Python bytecode"
safe_remove "*.pyo" "Python optimized bytecode"
safe_remove "__pycache__" "Python cache directories"
# Clean Node.js related files
if [ -f "package.json" ]; then
echo "🟢 Node.js project detected - cleaning caches..." >&2
# Clean npm cache
if command -v npm &> /dev/null; then
echo " 🗑️ Verifying npm cache..." >&2
if npm cache verify 2>/dev/null; then
echo " ✅ npm cache verified and cleaned" >&2
else
echo " ⚠️ npm cache verification failed" >&2
ERRORS=$((ERRORS + 1))
fi
fi
# Clean node_modules/.cache if it exists
if [ -d "node_modules/.cache" ]; then
CACHE_SIZE=$(du -sh node_modules/.cache 2>/dev/null | cut -f1 || echo "unknown")
rm -rf node_modules/.cache 2>/dev/null && echo " ✅ Removed node_modules/.cache ($CACHE_SIZE)" >&2
fi
fi
# Clean build artifacts
echo "🔧 Cleaning build artifacts..." >&2
safe_remove "*.o" "object files"
safe_remove "*.obj" "Windows object files"
safe_remove "*.so" "shared object files"
safe_remove "*.dll" "Windows library files"
safe_remove "*.dylib" "macOS dynamic libraries"
# Clean IDE and editor files
echo "💻 Cleaning IDE artifacts..." >&2
safe_remove ".vscode/settings.json.bak" "VS Code backup settings"
if [ -d ".vscode" ]; then
find .vscode -name "*.log" -delete 2>/dev/null || true
fi
# Clean test artifacts
echo "🧪 Cleaning test artifacts..." >&2
safe_remove "coverage.xml" "coverage report"
safe_remove ".coverage" "Python coverage data"
if [ -d "coverage" ]; then
rm -rf coverage 2>/dev/null && echo " ✅ Removed coverage directory" >&2
fi
if [ -d ".nyc_output" ]; then
rm -rf .nyc_output 2>/dev/null && echo " ✅ Removed .nyc_output directory" >&2
fi
# Clean Docker artifacts if Docker is available
if command -v docker &> /dev/null && docker info &> /dev/null 2>&1; then
echo "🐳 Docker detected - cleaning unused resources..." >&2
# Clean dangling images
DANGLING_IMAGES=$(docker images -f "dangling=true" -q 2>/dev/null | wc -l | xargs)
if [ "$DANGLING_IMAGES" -gt 0 ]; then
docker image prune -f &> /dev/null && echo " ✅ Removed $DANGLING_IMAGES dangling Docker images" >&2
else
echo " ℹ️ No dangling Docker images found" >&2
fi
fi
# Calculate disk space if possible
echo "💾 Calculating disk space usage..." >&2
if command -v du &> /dev/null; then
# Check cache directories
for cache_dir in ~/.npm ~/.cache ~/.cargo/registry; do
if [ -d "$cache_dir" ]; then
CACHE_SIZE=$(du -sh "$cache_dir" 2>/dev/null | cut -f1 || echo "unknown")
echo " 📊 $cache_dir: $CACHE_SIZE" >&2
fi
done
fi
# Report cleanup summary
echo "" >&2
echo "📋 Cleanup Summary:" >&2
echo " 🗑️ Files/directories removed: $FILES_REMOVED" >&2
echo " ⚠️ Errors encountered: $ERRORS" >&2
if [ "$ERRORS" -eq 0 ]; then
echo "✅ Environment cleanup completed successfully" >&2
else
echo "⚠️ Environment cleanup completed with $ERRORS errors" >&2
fi
echo "" >&2
echo "💡 Cleanup Tips:" >&2
echo " • Run 'docker system prune' for more aggressive Docker cleanup" >&2
echo " • Use 'npm cache clean --force' for complete npm cache reset" >&2
echo " • Consider 'pip cache purge' for Python package cache cleanup" >&2
exit 0
Complete hook script that performs environment cleanup when session ends
#!/usr/bin/env bash
echo "Starting environment cleanup..." >&2
FILES_REMOVED=0
safe_remove() {
local pattern="$1"
local description="$2"
FOUND=$(find . -name "$pattern" 2>/dev/null | wc -l | xargs)
if [ "$FOUND" -gt 0 ]; then
find . -name "$pattern" -delete 2>/dev/null && echo "Removed $FOUND $description files" >&2
FILES_REMOVED=$((FILES_REMOVED + FOUND))
fi
}
safe_remove "*.tmp" "temporary"
safe_remove "*.log" "log"
safe_remove "__pycache__" "Python cache"
if [ -f "package.json" ]; then
if command -v npm &> /dev/null; then
npm cache verify 2>/dev/null && echo "npm cache verified" >&2
fi
fi
echo "Cleanup completed: $FILES_REMOVED files removed" >&2
exit 0
Enhanced hook script for Docker resource cleanup with Docker Engine 24.0+ support
#!/usr/bin/env bash
if command -v docker &> /dev/null && docker info &> /dev/null 2>&1; then
echo "Cleaning Docker resources..." >&2
DANGLING_IMAGES=$(docker images -f "dangling=true" -q 2>/dev/null | wc -l | xargs)
if [ "$DANGLING_IMAGES" -gt 0 ]; then
docker image prune -f &> /dev/null && echo "Removed $DANGLING_IMAGES dangling Docker images" >&2
fi
docker system prune -f --volumes &> /dev/null && echo "Docker system cleanup completed" >&2
fi
exit 0
Enhanced hook script for NPM cache cleanup with timeout protection and npm 10.x+ support
#!/usr/bin/env bash
if [ -f "package.json" ]; then
if command -v npm &> /dev/null; then
echo "Cleaning npm cache..." >&2
timeout 10s npm cache verify 2>/dev/null || npm cache verify --offline 2>/dev/null
if [ -d "node_modules/.cache" ]; then
CACHE_SIZE=$(du -sh node_modules/.cache 2>/dev/null | cut -f1 || echo "unknown")
rm -rf node_modules/.cache 2>/dev/null && echo "Removed node_modules/.cache ($CACHE_SIZE)" >&2
fi
fi
fi
exit 0
Enhanced hook script for cross-platform system file cleanup with platform-specific rules
#!/usr/bin/env bash
case "$(uname)" in
Darwin)
find . -name ".DS_Store" -delete 2>/dev/null && echo "Removed macOS .DS_Store files" >&2
find . -name "._*" -delete 2>/dev/null && echo "Removed macOS resource fork files" >&2
;;
CYGWIN*|MINGW*|MSYS*)
find . -name "Thumbs.db" -delete 2>/dev/null && echo "Removed Windows Thumbs.db files" >&2
find . -name "Desktop.ini" -delete 2>/dev/null && echo "Removed Windows Desktop.ini files" >&2
;;
Linux)
find . -name ".directory" -delete 2>/dev/null && echo "Removed KDE .directory files" >&2
;;
esac
exit 0
Stop hooks only run on graceful shutdown. For crash scenarios, use OS-level cleanup via trap signals or systemd service cleanup. Add trap 'cleanup_function' EXIT SIGTERM SIGINT to shell sessions for broader coverage. Consider using systemd or launchd for persistent cleanup services.
Script checks 'docker info' but may lack permissions. Ensure user in docker group: sudo usermod -aG docker $USER or skip docker cleanup gracefully: docker image prune -f 2>/dev/null || echo 'Skipping docker cleanup'. Verify Docker Engine 24.0+ is installed and daemon is running: docker info.
Network issues can stall npm operations. Add timeout: timeout 10s npm cache verify or use npm cache verify --offline to avoid network calls. Set NPM_CONFIG_CACHE to control cache directory location. Verify npm version is 10.x+ for latest features. Use npm cache clean --force for complete cache reset.
Large directory trees exceed ARG_MAX limits. Replace find ... -delete with: find . -name '*.tmp' -print0 | xargs -0 rm -f to handle arguments in batches safely using null delimiter for paths with spaces. Use find with -exec rm {} + for better performance. Consider processing files in smaller batches.
Script checks ~/.npm and other user dirs which may be on slow filesystems. Add timeout: timeout 5s du -sh "$cache_dir" or skip network paths: df "$cache_dir" | grep -q nfs && continue to avoid stalling. Use df -h for faster disk usage reporting. Consider skipping network-mounted cache directories.
Hook may remove pycache from active virtual environments. Exclude virtual environment directories: find . -name 'pycache' -not -path '/venv/' -not -path '/.venv/' -delete. Verify Python version is 3.12+ for latest cache behavior. Use --exclude patterns to preserve virtual environment caches.
Use file age checks to only remove old temporary files: find . -name '*.tmp' -mtime +7 -delete. Add exclusion patterns for important temporary files. Verify file patterns match only safe-to-delete files. Consider using file locking checks before deletion.
Use portable disk space commands: du -sh for directory sizes, df -h for filesystem usage. Handle different file system types (ext4, APFS, NTFS) with appropriate commands. Verify disk space reporting works on target file system. Use fallback methods for disk space calculation.
Show that Environment Cleanup Handler - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.
[](https://heyclau.de/entry/hooks/environment-cleanup-handler)Environment Cleanup Handler - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.
| Field | Cleans up temporary files, caches, and resources when Claude session ends. This Stop hook provides comprehensive environment cleanup for development projects, automatically removing temporary files, build artifacts, cache directories, and system-specific files across multiple platforms. Open dossier | Detects unused CSS selectors when stylesheets are modified to keep CSS lean using PurgeCSS, PostCSS, and content analysis. This hook runs on CSS/SCSS file write/edit operations and analyzes stylesheets to identify unused selectors, generate optimized output, and report before/after size metrics. Open dossier | A Stop hook that terminates lingering database connections when a Claude Code session ends — via PostgreSQL pg_terminate_backend, MySQL KILL, Redis CLIENT KILL, and MongoDB connection cleanup. Open dossier | A Claude Code SessionEnd hook that scans a project for dead code and writes a report to .claude/reports. It runs available tools per language: ESLint and Knip for JS/TS, autoflake or pylint for Python, Knip for unused npm dependencies, ripgrep for unreferenced src files, and jq to flag zero-coverage files. Open dossier |
|---|---|---|---|---|
| Next steps | ||||
| Trust | ||||
| Review status | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed |
| Package trust | Package not verified | Package not verified | Package not verified | Package not verified |
| Source provenance | Source-backed | Source-backed | Source-backed | Source-backed |
| Submitter | — | — | — | — |
| Install risk | Review first | Review first | Review first | Review first |
| Notes | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ |
| Brand | — | — | — | — |
| Category | hooks | hooks | hooks | hooks |
| Source | source-backed | source-backed | source-backed | source-backed |
| Author | JSONbored | JSONbored | JSONbored | JSONbored |
| Added | 2025-09-19 | 2025-09-19 | 2025-09-19 | 2025-10-19 |
| Platforms | Claude Code | Claude Code | Claude Code | Claude Code |
| Source repo | — | — | — | — |
| Safety notes | ✓Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling. | ✓Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling. | ✓Runs at session end and forcibly terminates database backends/clients (pg_terminate_backend, KILL, CLIENT KILL); pointed at a shared or production database it can drop other users' connections — scope it to local/dev databases and confirm the target before enabling. | ✓Registered as a SessionEnd hook, so it runs automatically every time a Claude Code session ends. Invokes external tools via npx (ts-prune, Knip, eslint) and locally installed binaries (autoflake, pylint, vulture, jq, rg), which can trigger package downloads and execute project tooling. Defaults to DRY_RUN=true and only writes a report; setting DRY_RUN=false is intended to enable destructive cleanup, so review the report before changing it. Creates directories under .claude/backups and .claude/reports in the working tree. |
| Privacy notes | ✓Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output. | ✓Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output. | ✓Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook. | ✓Writes a dead-code report containing file paths, export names, and dependency names from the project to .claude/reports/dead-code-report.txt and echoes it to stderr. Running tools via npx may fetch packages from the npm registry over the network. |
| Prerequisites | — none listed | — none listed | — none listed | — none listed |
| Install | | | | |
| Config | | | | |
| Citations | ||||
| Claim | Unclaimed | Unclaimed | Unclaimed | Unclaimed |
Source-backed guides for putting this to work.
Fix Claude Code high CPU/memory, hangs, and context bloat with documented commands.
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.