Skip to main content
hooksSource-backedReview first Safety Privacy

Database Connection Cleanup - Hooks

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.

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.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/database-connection-cleanup.mdx
Safety notes
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.
Privacy notes
Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.
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 1 risk area. Review closely: credentials & tokens.

1 area
  • SafetyCredentials & tokensRuns 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.
  • PrivacyCredentials & tokensUses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.

Safety notes

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

Privacy notes

  • Uses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.

Schema details

Install type
cli
Reading time
1 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hookshttps://www.postgresql.org/docs/current/functions-admin.htmlhttps://mariadb.com/kb/en/kill/https://redis.io/docs/latest/commands/client-kill/https://www.mongodb.com/docs/manual/administration/connection-pool-overview/
Runtime and command metadata
Trigger
Stop
Script language
bash
Script body
#!/usr/bin/env bash

echo "🗄️ Starting database connection cleanup..." >&2

# PostgreSQL cleanup
if pgrep postgres >/dev/null 2>&1; then
  echo "🐘 PostgreSQL: Checking connections..." >&2
  
  # Check if psql is available and we can connect
  if command -v psql &> /dev/null; then
    # Count active connections
    ACTIVE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
    IDLE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
    
    echo "📊 PostgreSQL: $ACTIVE_CONNECTIONS active, $IDLE_CONNECTIONS idle connections" >&2
    
    # Terminate long-running idle connections (older than 5 minutes)
    if [ "$IDLE_CONNECTIONS" -gt 0 ]; then
      TERMINATED=$(psql -t -c "SELECT count(*) FROM (SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid()) t;" 2>/dev/null | xargs || echo "0")
      if [ "$TERMINATED" -gt 0 ]; then
        echo "✅ PostgreSQL: Terminated $TERMINATED idle connections" >&2
      fi
    fi
  else
    echo "⚠️ PostgreSQL running but psql not available" >&2
  fi
fi

# MySQL cleanup
if pgrep mysql >/dev/null 2>&1 || pgrep mysqld >/dev/null 2>&1; then
  echo "🐬 MySQL: Checking connections..." >&2
  
  if command -v mysql &> /dev/null; then
    PROCESSLIST=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | grep -c "Sleep" || echo "0")
    TOTAL_CONNECTIONS=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | wc -l || echo "0")
    echo "📊 MySQL: $TOTAL_CONNECTIONS total connections, $PROCESSLIST sleeping" >&2
    
    # Kill long-running sleeping connections (optional, requires PROCESS privilege)
    # mysql -e "KILL CONNECTION_ID;" 2>/dev/null || true
  else
    echo "⚠️ MySQL running but mysql client not available" >&2
  fi
fi

# MongoDB cleanup
if pgrep mongod >/dev/null 2>&1; then
  echo "🍃 MongoDB: Checking connections..." >&2
  
  if command -v mongosh &> /dev/null; then
    CONNECTIONS=$(mongosh --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
    echo "📊 MongoDB: $CONNECTIONS active operations" >&2
  elif command -v mongo &> /dev/null; then
    CONNECTIONS=$(mongo --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
    echo "📊 MongoDB: $CONNECTIONS active operations" >&2
  else
    echo "⚠️ MongoDB running but mongo client not available" >&2
  fi
fi

# Redis cleanup
if pgrep redis-server >/dev/null 2>&1; then
  echo "📮 Redis: Checking connections..." >&2
  
  if command -v redis-cli &> /dev/null; then
    CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
    echo "📊 Redis: $CLIENT_COUNT connected clients" >&2
    
    # Optionally close idle clients
    # redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
  else
    echo "⚠️ Redis running but redis-cli not available" >&2
  fi
fi

# Check for database connection strings in environment
if [ -f ".env" ]; then
  DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
  if [ "$DB_VARS" -gt 0 ]; then
    echo "📋 Found $DB_VARS database configuration variables in .env" >&2
  fi
fi

echo "✅ Database connection cleanup completed" >&2
exit 0
Full copyable content
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}

About this resource

Features

  • Automatic database connection cleanup on session end using Stop hook with intelligent connection detection and multi-database support
  • Multi-database support for PostgreSQL 17+, MySQL 8.0+, MongoDB 7.0+ (mongosh), and Redis 7.0+ with automatic database type detection via process monitoring
  • Idle connection termination for PostgreSQL using pg_terminate_backend with configurable timeout thresholds (default: 5 minutes) and state filtering
  • Connection monitoring and reporting showing active, idle, and total connection counts for each database type with detailed statistics
  • Safe cleanup with error handling preventing accidental termination of critical connections and protecting system processes
  • Resource leak prevention automatically closing orphaned connections and cleaning up connection pools to prevent resource exhaustion
  • Connection string detection from environment variables (.env files) for automatic database discovery and configuration validation
  • Detailed reporting with connection statistics and cleanup results for each database type including terminated connection counts and resource usage

Use Cases

  • Automatic resource cleanup in development environments preventing connection leaks during rapid development cycles
  • Prevention of database connection leaks automatically closing orphaned connections that accumulate over time
  • Clean session termination for database applications ensuring all connections are properly closed when sessions end
  • Resource monitoring and management providing visibility into database connection usage and identifying connection leaks
  • Multi-database environment cleanup supporting projects using multiple database types simultaneously
  • Development workflow optimization preventing database connection exhaustion during long development sessions

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/database-connection-cleanup.sh
  3. Make executable: chmod +x .claude/hooks/database-connection-cleanup.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
  • Database client tools: PostgreSQL (psql from PostgreSQL 17+), MySQL (mysql client from MySQL 8.0+), MongoDB (mongosh 2.0+ for MongoDB 7.0+), Redis (redis-cli from Redis 7.0+)
  • Environment variable access for connection string detection (.env file support or system environment variables)
  • Database server access with appropriate permissions (pg_terminate_backend for PostgreSQL, KILL for MySQL, connection management for MongoDB/Redis)

Hook Configuration

{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}

Hook Script

#!/usr/bin/env bash

echo "🗄️ Starting database connection cleanup..." >&2

# PostgreSQL cleanup
if pgrep postgres >/dev/null 2>&1; then
  echo "🐘 PostgreSQL: Checking connections..." >&2

  # Check if psql is available and we can connect
  if command -v psql &> /dev/null; then
    # Count active connections
    ACTIVE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
    IDLE_CONNECTIONS=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")

    echo "📊 PostgreSQL: $ACTIVE_CONNECTIONS active, $IDLE_CONNECTIONS idle connections" >&2

    # Terminate long-running idle connections (older than 5 minutes)
    if [ "$IDLE_CONNECTIONS" -gt 0 ]; then
      TERMINATED=$(psql -t -c "SELECT count(*) FROM (SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid()) t;" 2>/dev/null | xargs || echo "0")
      if [ "$TERMINATED" -gt 0 ]; then
        echo "✅ PostgreSQL: Terminated $TERMINATED idle connections" >&2
      fi
    fi
  else
    echo "⚠️ PostgreSQL running but psql not available" >&2
  fi
fi

# MySQL cleanup
if pgrep mysql >/dev/null 2>&1 || pgrep mysqld >/dev/null 2>&1; then
  echo "🐬 MySQL: Checking connections..." >&2

  if command -v mysql &> /dev/null; then
    PROCESSLIST=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | grep -c "Sleep" || echo "0")
    TOTAL_CONNECTIONS=$(mysql -e "SHOW PROCESSLIST;" 2>/dev/null | wc -l || echo "0")
    echo "📊 MySQL: $TOTAL_CONNECTIONS total connections, $PROCESSLIST sleeping" >&2

    # Kill long-running sleeping connections (optional, requires PROCESS privilege)
    # mysql -e "KILL CONNECTION_ID;" 2>/dev/null || true
  else
    echo "⚠️ MySQL running but mysql client not available" >&2
  fi
fi

# MongoDB cleanup
if pgrep mongod >/dev/null 2>&1; then
  echo "🍃 MongoDB: Checking connections..." >&2

  if command -v mongosh &> /dev/null; then
    CONNECTIONS=$(mongosh --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
    echo "📊 MongoDB: $CONNECTIONS active operations" >&2
  elif command -v mongo &> /dev/null; then
    CONNECTIONS=$(mongo --quiet --eval "db.currentOp().inprog.length" 2>/dev/null || echo "0")
    echo "📊 MongoDB: $CONNECTIONS active operations" >&2
  else
    echo "⚠️ MongoDB running but mongo client not available" >&2
  fi
fi

# Redis cleanup
if pgrep redis-server >/dev/null 2>&1; then
  echo "📮 Redis: Checking connections..." >&2

  if command -v redis-cli &> /dev/null; then
    CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
    echo "📊 Redis: $CLIENT_COUNT connected clients" >&2

    # Optionally close idle clients
    # redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
  else
    echo "⚠️ Redis running but redis-cli not available" >&2
  fi
fi

# Check for database connection strings in environment
if [ -f ".env" ]; then
  DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
  if [ "$DB_VARS" -gt 0 ]; then
    echo "📋 Found $DB_VARS database configuration variables in .env" >&2
  fi
fi

echo "✅ Database connection cleanup completed" >&2
exit 0

Examples

Database Connection Cleanup Hook Script

Complete hook script that closes database connections when session ends

#!/usr/bin/env bash
echo "Starting database connection cleanup..." >&2
if pgrep postgres >/dev/null 2>&1; then
  if command -v psql &> /dev/null; then
    IDLE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
    if [ "$IDLE" -gt 0 ]; then
      psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
      echo "Terminated idle PostgreSQL connections" >&2
    fi
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable database connection cleanup on session stop

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "./.claude/hooks/database-connection-cleanup.sh"
          }
        ]
      }
    ]
  }
}

PostgreSQL Connection Cleanup with Threshold

Enhanced hook script with connection count threshold before cleanup

#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if pgrep postgres >/dev/null 2>&1 && command -v psql &> /dev/null; then
  ACTIVE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
  IDLE=$(psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE state = 'idle' AND pid <> pg_backend_pid();" 2>/dev/null | xargs || echo "0")
  echo "PostgreSQL: $ACTIVE active, $IDLE idle connections" >&2
  if [ "$IDLE" -gt 10 ]; then
    psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
  fi
fi
exit 0

Redis Connection Cleanup

Enhanced hook script for Redis connection cleanup with idle client detection

#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if pgrep redis-server >/dev/null 2>&1 && command -v redis-cli &> /dev/null; then
  CLIENT_COUNT=$(redis-cli CLIENT LIST 2>/dev/null | wc -l || echo "0")
  IDLE_CLIENTS=$(redis-cli CLIENT LIST 2>/dev/null | grep -c "idle=" || echo "0")
  echo "Redis: $CLIENT_COUNT connected clients, $IDLE_CLIENTS idle" >&2
  if [ "$IDLE_CLIENTS" -gt 5 ]; then
    redis-cli CLIENT KILL TYPE normal SKIPME yes 2>/dev/null || true
    echo "Cleaned up idle Redis connections" >&2
  fi
fi
exit 0

Database Discovery and Cleanup

Enhanced hook script that discovers databases from .env and performs cleanup

#!/usr/bin/env bash
echo "Starting database cleanup..." >&2
if [ -f ".env" ]; then
  DB_VARS=$(grep -E "(DATABASE_URL|MONGODB_URI|REDIS_URL|POSTGRES|MYSQL)" .env 2>/dev/null | wc -l || echo "0")
  if [ "$DB_VARS" -gt 0 ]; then
    echo "Found $DB_VARS database configuration variables" >&2
  fi
fi
if pgrep postgres >/dev/null 2>&1 && command -v psql &> /dev/null; then
  psql -t -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle' AND state_change < now() - interval '5 minutes' AND pid <> pg_backend_pid();" 2>/dev/null || true
fi
exit 0

Troubleshooting

PostgreSQL connections not terminated despite hook execution

Verify psql client is in PATH and can connect without password. Check pg_hba.conf allows local connections. Ensure user has permission to query pg_stat_activity and call pg_terminate_backend. Test manually: psql -c SELECT count(*) FROM pg_stat_activity. Check PostgreSQL version: upgrade to PostgreSQL 17+ for latest features.

Stop hook runs but database processes still detected

Hook reports connections but does not stop database servers. Use pgrep to verify process detection works. Check connection cleanup SQL executes successfully. Monitor stderr for command errors. Verify hook script has executable permissions: chmod +x.

Idle connection count shows zero despite active sessions

Check state filter in pg_stat_activity query matches your PostgreSQL version. Verify 5-minute threshold is appropriate for your workflow. Use psql directly to debug query results: psql -c SELECT state, count(*) FROM pg_stat_activity GROUP BY state. Check PostgreSQL version compatibility.

MySQL processlist command fails with access denied

Grant PROCESS privilege to MySQL user: GRANT PROCESS ON . TO user@localhost. Verify mysql client connects with correct credentials from .env or environment variables. Check MySQL version: upgrade to MySQL 8.0+ for latest features. Test connection manually: mysql -e SHOW PROCESSLIST.

MongoDB connection check fails with authentication error

Use mongosh for MongoDB 7.0+ or mongo for older versions. Configure connection string with credentials. Check authentication database matches user creation. Verify network access if using remote MongoDB. Test manually: mongosh --eval db.currentOp().inprog.length. Check MongoDB version compatibility.

Redis CLIENT LIST command fails with connection refused

Verify Redis server is running: redis-cli ping. Check Redis connection configuration and authentication if required. Verify redis-cli is in PATH. Test connection manually: redis-cli CLIENT LIST. Check Redis version: upgrade to Redis 7.0+ for latest features.

Hook terminates active connections causing application errors

Add state filter to only terminate idle connections: WHERE state = idle. Increase timeout threshold from 5 minutes to 15 minutes. Add application process exclusion: AND application_name != your_app. Use pg_terminate_backend only for idle connections, not active ones.

Multiple database types detected but only one cleaned up

Check process detection: verify pgrep commands for each database type. Ensure database client tools are installed for all detected databases. Check hook script logic: verify all database cleanup sections execute. Test each database type individually to isolate issues.

Source citations

Add this badge to your README

Show that Database Connection Cleanup - 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/database-connection-cleanup.svg)](https://heyclau.de/entry/hooks/database-connection-cleanup)

How it compares

Database Connection Cleanup - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

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 PostToolUse hook that reminds you to enable native query logging for PostgreSQL, Prisma, Sequelize, and TypeORM, and flags possible N+1 patterns when you edit SQL or data-access files.

Open dossier

A Stop hook that syncs your changed files to cloud storage when a Claude Code session ends, using rclone to push to S3, Google Cloud Storage, or any of its 70+ supported backends.

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
Next stepsDiffers
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
BrandAWS logoAWS
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-10-192025-09-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns 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.Runs automatically after bash, write, or edit activity and inspects files that look like query, model, repository, DAO, or SQL files. Creates .claude/logs/query-performance.log and appends database command or file-analysis events. Uses grep-based heuristics for query warnings and should not be treated as proof of a performance defect.Runs automatically at session end and can create compressed archives of modified git files. Uploads backups through AWS CLI, Google Cloud SDK, or rclone when those tools and bucket variables are configured. Writes a temporary archive under /tmp when using the rclone fallback and removes it after the copy attempt.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 notesUses locally configured database credentials and connection details to issue termination commands; keep those credentials in environment variables, not in the hook.Reads query-related source files and may print file paths, query patterns, and database command strings to local hook output. Stores analyzed file paths and database command text in .claude/logs/query-performance.log. Database command text may include connection names, database names, or other operational details if typed directly into the command.Sends modified file contents to the configured cloud storage destination. Uses locally configured cloud credentials and bucket environment variables but does not define or manage them. Backup archives may include source code, docs, generated files, and any unignored local changes listed by git diff.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.
Prerequisites— none listed— none listed— none listed— none listed
Install
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/cloud-backup-on-session-stop.sh && chmod +x .claude/hooks/cloud-backup-on-session-stop.sh
mkdir -p .claude/hooks && touch .claude/hooks/css-unused-selector-detector.sh && chmod +x .claude/hooks/css-unused-selector-detector.sh
Config
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/database-connection-cleanup.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "stop": {
      "script": "./.claude/hooks/cloud-backup-on-session-stop.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/css-unused-selector-detector.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Signals

Loading live community signals…

More like this, weekly

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