Skip to main content
hooksSource-backedReview first Safety Privacy

Environment Cleanup Handler - Hooks

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.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:Stop
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

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.
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.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

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

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns 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.
  • PrivacyCredentials & tokensReceives 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.

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.

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.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Runtime and command metadata
Trigger
Stop
Script language
bash
Script body
#!/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
Full copyable content
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/environment-cleanup-handler.sh"
    }
  }
}

About this resource

Features

  • Automatic temporary file cleanup (_.tmp, _.log, .DS_Store, Thumbs.db) with cross-platform support for macOS, Linux, and Windows with platform-specific file pattern detection
  • NPM cache verification and cleanup with npm 10.x+ support including npm cache verify and node_modules/.cache directory cleanup for Node.js projects
  • Python bytecode and pycache directory removal with Python 3.12+ support including _.pyc, _.pyo files and pycache directories with recursive cleanup
  • Development build artifacts cleanup including object files (_.o, .obj), shared libraries (.so, _.dll, *.dylib), and build output directories
  • Disk space usage reporting and optimization with detailed cache size reporting for ~/.npm, ~/.cache, ~/.cargo/registry directories
  • Multi-platform support (macOS, Linux, Windows) with platform-specific cleanup rules for .DS_Store (macOS), Thumbs.db (Windows), and .directory (KDE/Linux)
  • Safe cleanup with error handling and logging including file removal counters, error tracking, and comprehensive cleanup summary reporting
  • Docker resource cleanup with Docker Engine 24.0+ support including dangling image removal, container cleanup, and Docker system optimization

Use Cases

  • Automated development environment maintenance providing automatic cleanup of temporary files, caches, and build artifacts when development sessions end
  • Post-session cleanup for CI/CD pipelines ensuring clean build environments by removing temporary files and caches after CI/CD job completion
  • Disk space optimization and management automatically freeing disk space by removing unnecessary cache files and temporary artifacts
  • Multi-language project artifact cleanup supporting Node.js, Python, Go, Rust, and Docker projects with language-specific cleanup rules
  • Docker container development environment cleanup removing dangling Docker images and optimizing Docker disk usage for containerized development
  • Development workflow optimization maintaining clean development environments and reducing disk space usage for improved development performance

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/environment-cleanup-handler.sh
  3. Make executable: chmod +x .claude/hooks/environment-cleanup-handler.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • Docker Engine 24.0+ (optional, for Docker cleanup)
  • npm 10.x+ (optional, for npm cache cleanup)
  • Python 3.12+ (optional, for Python cache cleanup)

Hook Configuration

{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/environment-cleanup-handler.sh"
    }
  }
}

Hook Script

#!/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

Examples

Environment Cleanup Handler Hook Script

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

Docker Resource Cleanup

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

NPM Cache Cleanup with Timeout Protection

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

Cross-Platform System File Cleanup

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

Troubleshooting

Stop hook doesn't execute when Claude terminates unexpectedly

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.

Docker cleanup fails with permission denied on daemon socket

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.

NPM cache verify hangs indefinitely blocking hook completion

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.

Find commands fail with 'too many arguments' on large directories

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.

Du command for cache size calculation hangs on network mounts

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.

Python pycache cleanup removes files from active virtual environments

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.

Cleanup removes important temporary files needed by other processes

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.

Disk space reporting shows incorrect sizes on different file systems

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.

Source citations

Add this badge to your README

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.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/environment-cleanup-handler.svg)](https://heyclau.de/entry/hooks/environment-cleanup-handler)

How it compares

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 statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-09-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns 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 notesReceives 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
mkdir -p .claude/hooks && touch .claude/hooks/environment-cleanup-handler.sh && chmod +x .claude/hooks/environment-cleanup-handler.sh
mkdir -p .claude/hooks && touch .claude/hooks/css-unused-selector-detector.sh && chmod +x .claude/hooks/css-unused-selector-detector.sh
mkdir -p .claude/hooks && touch .claude/hooks/database-connection-cleanup.sh && chmod +x .claude/hooks/database-connection-cleanup.sh
mkdir -p .claude/hooks && touch .claude/hooks/dead-code-eliminator.sh && chmod +x .claude/hooks/dead-code-eliminator.sh
Config
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/environment-cleanup-handler.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/css-unused-selector-detector.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "sessionEnd": {
      "script": "./.claude/hooks/dead-code-eliminator.sh"
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.