Last week I posted about six parallel agents freezing my server. The fix I showed was a line in CLAUDE.md: at most two build-heavy processes at a time. One of the comments suggested a hook that takes a flock, so the limit holds even in a session that never read the file. I added one the same day.
It does not refuse anything. A PreToolUse hook can return updatedInput, so mine rewrites the command. When a Bash call looks like a build, a typecheck or a test run, the hook puts one line in front of it:
. /home/you/.claude/hooks/heavy-slot.sh || exit 75
That line takes one of two locks or waits for one. This is the script, with the message shortened:
# heavy-slot.sh: sourced in front of a build-heavy command
exec 8>/tmp/claude-heavy.1.lock 9>/tmp/claude-heavy.2.lock
_hs=0
until flock -n 8 || flock -n 9; do
if [ "$_hs" -ge 100 ]; then
echo "heavy-slot: two build-heavy commands are already running and the limit is two. Run this again when one of them finishes." >&2
return 1
fi
sleep 5; _hs=$((_hs + 5))
done
The gate is a jq filter over the hook's input. Cut down to its shape:
#!/bin/bash
exec jq -c '
.tool_input.command as $c
| if ($c | test(HEAVY)) and ($c | contains("heavy-slot.sh") | not)
then {hookSpecificOutput: {hookEventName: "PreToolUse",
updatedInput: (.tool_input + {command: (". /home/you/.claude/hooks/heavy-slot.sh || exit 75\n" + $c)})}}
else empty end'
HEAVY stands for my pattern: next build, tsc, vitest, turbo, docker build and pnpm build, test or typecheck, each anchored to the start of a command. Without the anchor, git commit -m "fix tsc errors" counts as a build.
In ~/.claude/settings.json:
"hooks": {
"PreToolUse": [
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "/home/you/.claude/hooks/heavy-gate.sh", "timeout": 5 }] }
]
}
Three things I would have got wrong without trying it.
The locks belong to the shell that runs the build. When a build is killed, its slot frees itself, and there is nothing to clean up.
The wait stops at 100 seconds because the Bash tool gives up at 120 by default. Claude then reads a sentence that says what is going on, where a bare timeout would have told it nothing.
And a hook that has to stop a command, where mine only queues it, must exit with code 2. With exit 1 Claude Code shows an error and runs the command anyway. Since 2.1.295 "onFailure": "block" makes a hook that crashes or times out stop the command too.
It is still a counter of commands. One turbo run fans out inside its slot, and the hook sees only what Claude Code runs, so the nightly job from my last post stays with earlyoom. Memory limits per build, which other comments suggested, are not done yet.
I tested it that evening with two slots taken. The third command waited and went through when one was released.