Skip to content

Latest commit

 

History

History
46 lines (31 loc) · 1.58 KB

File metadata and controls

46 lines (31 loc) · 1.58 KB

bg-task-respawn-limiter

Prevents background bash tasks in Claude Code from respawning infinitely. Installs as a PreToolUse hook that tracks spawn attempts per command pattern within a sliding time window and blocks execution when the limit is exceeded.

Problem

Background bash tasks (run_in_background: true) can respawn indefinitely when commands hang, creating fork bombs that consume all system resources.

How It Works

  1. Intercepts every Bash tool call via the Claude Code hook system
  2. Ignores foreground tasks — only monitors run_in_background: true
  3. Normalizes the command (collapsing numbers and temp paths) and hashes it to group similar invocations
  4. Tracks spawn timestamps in /tmp/claude-bg-tasks/ per pattern
  5. If a pattern exceeds the respawn limit within the time window:
    • Kills existing processes matching the command
    • Logs the incident
    • Blocks the new spawn (exit code 2)

Install

# Requires jq
./install.sh

This adds a PreToolUse hook to ~/.claude/settings.json.

Configuration

Set environment variables before launching Claude Code:

Variable Default Description
BG_TASK_MAX_RESPAWNS 5 Max spawn attempts per command pattern
BG_TASK_WINDOW_SECONDS 300 Sliding time window (seconds)
BG_TASK_TRACK_DIR /tmp/claude-bg-tasks Directory for tracking files
BG_TASK_LOG_FILE /tmp/claude-bg-task-limiter.log Incident log path

Uninstall

Remove the bg-task-limiter.sh entry from hooks.PreToolUse in ~/.claude/settings.json.

License

See LICENSE.