r/ClaudeCode • • 3h ago

Tips & Workflows The PreToolUse hook a commenter here talked me into does not block builds, it makes the third one wait

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.

1 Upvotes

9 comments sorted by

•

u/AutoModerator 3h ago

Hey! Thanks for posting to r/ClaudeCode

While participating in this thread, please follow our community rules. Keep discussions constructive. Attack the idea, not the person.

For help, project discussions, tips, and general chat, join the ClaudeCode Discord.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/called9527 2h ago

one thing to watch: since the waiting now happens inside the Bash call, it eats that call's timeout. bash tool default is 2 min iirc, so ~100s in the queue plus a slow build and it can get killed mid build, and the agent just sees a failed build and starts "fixing" stuff. either raise the timeout for those commands or bail out with 75 sooner so it simply retries

1

u/SeniorDevGam 44m ago

You're right, and my 100 seconds only covers half of it. It makes sure a command that never gets a slot comes back with a sentence before the tool gives up. A command that gets its slot at second 90 is left with 30 seconds for the build itself, unless that call asked for a longer timeout. The hook already rewrites the input, so adding the wait to the call's timeout in the same place looks like the smaller fix. I have not tried it yet.

1

u/Simple-Bedroom5606 1h ago

Nice, rewriting the command with updatedInput is a lot cleaner than blocking and having the agent retry. Two things I ran into with a similar setup. If you use worktrees, builds in different worktrees still fight over shared caches (turbo, the pnpm store, docker), so a global lock like yours is the right call rather than per repo. And I'd log every wait with a timestamp and the command to a file. After a week it shows you which commands actually collide, and for me it was almost always typecheck and tests fired back to back by the same agent, which was easier to fix in the prompt than with more locking. Since you're already rewriting the input, bumping the timeout for anything matching the heavy pattern is worth trying too, given the point above about the queue eating the call's timeout.

1

u/SeniorDevGam 43m ago

The log is the part I'm missing. Mine only says something when it gives up after 100 seconds, so I have no record of which commands waited or for how long. One thing that already helps with your typecheck and tests case: the line goes in front of the whole Bash call, so pnpm typecheck && pnpm test in one call shares a single slot. Two separate calls sent at once take both.

1

u/Ok-Buyer-9421 2h ago

This is a good example of why instructions alone aren't enough. I've been building Agentests around the same principle: turn rules into executable checks rather than relying on the agent to remember them. https://github.com/feuersteiner/agentests let me know if it helps :)

1

u/Fancy-Proof-9449 55m ago

I hit the same wall from the other side. Mine wasn't the server freezing, it was the PC running out of memory and builds getting killed halfway. Twice.

I didn't use a hook. The build has one runner that all the checks go through, and it runs three at a time but never two of the heavy ones together (heavy is anything over about a gig of memory). That holds even in a session that never read the rules file. It doesn't stop two sessions from both starting it though, your lock is better there.

The thing that helped more than I expected: it remembers which checks passed on the exact same files and skips them next time. A small change went from about six and a half minutes to under three.

1

u/bostonaholic 3h ago

I'd check commands Claude starts with run_in_background. A dev server or watch-mode test runner would hold a slot until you kill it, so I'd skip wrapping those, or anything with --watch. Killed agents are fine since flock drops the lock when the process dies.

1

u/SeniorDevGam 44m ago

Good catch, mine doesn't look at run_in_background or at flags at all. next dev is not in the pattern, so a dev server takes no slot. But tsc --watch or vitest in watch mode would match and sit on a slot until someone kills it. I'd skip those and keep wrapping a build that Claude sends to the background, since that one is exactly what the limit is for.