If you work with many agents
Situations I ran into and solved while running dozens of agents at once on my own Mac. Find yours, hand the decision to your agent.
I turned off the maintenance Git starts on its own after every commit; maintenance now runs once an hour, as a single copy.
before76 git maintenance runs at once
afterat most 1
turn off git's automatic maintenance (gc.auto · maintenance.auto) and switch to hourly scheduled maintenanceText for your agent · 23 lines
Situation: many agents commit often in the same git repository. Activity Monitor shows many `git maintenance run --auto`, `git repack` and `git pack-objects` processes at the same time; the machine is running hot. Why: after a commit, once a threshold is crossed, git starts maintenance in the background (`git maintenance run --auto --detach`). This background run holds no lock (observed on git 2.54): while one repack takes minutes, every new commit starts another one. I had 76 concurrent repacks in 10 minutes, each repacking 11 GB of history from scratch, and a commit object was lost in the race. Do: 1. Turn off commit-triggered maintenance in this repository: git config --local gc.auto 0 git config --local maintenance.auto false 2. Stop the running maintenance together with its child processes, then a minute later delete the temporary packs they left behind (this stops maintenance in every repository on this machine; a push, fetch or clone keeps running): pkill -TERM -f 'git(-core/git)? (maintenance run|repack|pack-objects .*objects/pack/)' sleep 60; find "$(git rev-parse --git-path objects/pack)" -name 'tmp_*' -mmin +1 -delete 3. Set up maintenance to run on a schedule, as a single copy: git maintenance start git config --local maintenance.gc.enabled false git config --local maintenance.prefetch.enabled false git config --local maintenance.loose-objects.schedule hourly git config --local maintenance.incremental-repack.schedule daily Verify: - git fsck --connectivity-only --no-reflogs --no-dangling → prints nothing (no missing objects) - pgrep -f 'git(-core/git)? (maintenance run|repack|pack-objects .*objects/pack/)' | wc -l → 0 (above 0 only while the hourly scheduled run is going) Don't: start a full `git gc` or `git repack -a` while doing this.
Also in: If your laptop runs hot
Every agent works in its own git worktree. I open each worktree with the Mac's file clone (APFS) instead of git's copy, so the extra disk is close to zero. An agent's commit in the shared working tree is rejected; I keep committing my own notes there.
beforeone shared tree · every worktree a full copy of the repo
after115 worktrees · extra disk per worktree ≈ 0
open a separate git worktree for each agent, don't commit in the shared treeText for your agent · 36 lines
Situation: several agents work in the same repo folder. When one agent commits, the changes another agent staged go into that commit too, or the agents overwrite each other's files.
Why: a git working folder has one index and one set of files. Every agent in that folder shares both: everything staged with `git add` goes into the next commit, no matter who staged it, and agents editing the same file overwrite each other.
Do:
1. Open a worktree of its own for each agent. `git worktree add` writes every file again: each worktree takes as much disk as a full copy of the repo (+200 MB for a 200 MB repo). On a Mac (APFS), don't copy the files, clone them; extra disk ≈ 0. Run this in the shared folder while it is clean (git status --short prints nothing); if it shows `?? .env`, first run `echo .env >> .git/info/exclude` (no commit needed, it ignores .env in every worktree), or the secret lands in the branch with the first commit:
git worktree add --no-checkout ../<agent-name> -b <agent-name>
git ls-tree --name-only -z HEAD | xargs -0 -I{} cp -c -R ./{} ../<agent-name>/
(cd ../<agent-name> && git read-tree HEAD && git update-index -q --refresh)
If it isn't APFS (Linux, Windows) or the repo has submodules, use plain `git worktree add ../<agent-name> -b <agent-name>`.
The new worktree has none of the top-level files git doesn't track (.env, node_modules): copy .env over and reinstall dependencies there.
2. The agent edits and commits only in its own worktree.
3. Reject the agent's commits in the shared folder with a git config hook (it runs even when core.hooksPath or husky has switched off .git/hooks). The hook only rejects an agent's environment (Claude Code, Codex); you keep committing there from your terminal:
git config hook.shared-gate.event pre-commit
git config hook.shared-gate.command 'i="${GIT_INDEX_FILE:-index}"; case "${i##*/}" in index|index.lock) ;; *) exit 0;; esac; [ -z "${CLAUDECODE:-}${CLAUDE_CODE_SESSION_ID:-}${CODEX_THREAD_ID:-}" ] || [ "$(git rev-parse --path-format=absolute --git-dir)" != "$(git rev-parse --path-format=absolute --git-common-dir)" ] || { echo "no agent commits in the shared folder: commit in your own worktree" >&2; exit 1; }'
The hook is shared by every worktree; its condition singles out the shared folder (only there is git-dir = git-common-dir). `git commit --no-verify` skips the hook; a commit given a path (`git commit -- <path>`) also gets through it and picks up what someone else staged on that path: tell your agent to use neither in the shared folder.
I measured this hook form on git 2.54 (git --version). Older git doesn't know config hooks, and these two lines do nothing without any error: commits in the shared folder go through. If your git is older, update it first (brew install git), then run this step; the git hook run line under Verify shows that the hook really runs.
4. Land work on the main branch one at a time. If two landings run at once, one fails with "index.lock: File exists", or the other agent's file can stay staged in the shared folder's index (it stayed in 33 of 40 tries on my machine, 0 of 50 on another); so serialize landing with a lock (the function's definition and its call run in the same command; agent shells don't carry functions from one command to the next):
land() { L="$(git rev-parse --path-format=absolute --git-common-dir)/land.lock"; got=; for n in $(seq 300); do mkdir "$L" 2>/dev/null && { got=1; break; }; sleep 0.2; done; [ -n "$got" ] || { echo "landing lock busy for 60 s: $L (delete it if no landing is running)"; return 1; }; git merge --ff-only "$1"; rc=$?; rmdir "$L"; return $rc; }
git -C ../<agent-name> rebase <main-branch>
(cd <shared-folder> && land <agent-name>)
Only this landing runs in the shared folder. If it says "Not possible to fast-forward", another landing got in first: go back to the rebase step; don't use the `merge --no-ff` git suggests.
5. When the work is done:
git worktree remove ../<agent-name>
git branch -d <agent-name>
If remove says "modified or untracked files": delete the file if it is junk; if it is work, commit in that worktree first, land it with step 4, then remove it. Don't use --force or branch -D: work that hasn't landed on the main branch is lost. (The .env you copied is deleted too; the original .env stays in the shared folder.)
Verify:
- in the new worktree, after copying .env, git status --short → empty
- git worktree list → number of running agents + 1 lines (the first line is the shared folder); a finished worktree must not stay in the list
- git -C <shared-folder> status --short → empty
- the agent runs git hook run pre-commit in the shared folder → "no agent commits in the shared folder" and exit 1 (runs the hook without committing); run by you in a terminal, the same command exits 0
- in an agent's worktree git hook run pre-commit → exit 0
- git hook list --show-scope pre-commit → "local shared-gate" (shows up even when core.hooksPath or husky has switched off .git/hooks)
Don't: give the same worktree to two agents; git doesn't stop this, you do.I don't make agents write a shared interface up front and queue behind it: they all start at once, each in its own worktree. At merge time, the same piece written separately by two agents, or a conflict on the same lines, tells me where the shared piece lives; I move it into one file right then and delete the copy in the same commit.
beforethe agent that used the shared piece waited until the agent writing it had landed
afterall start at once · the copy was folded into one place 6 min 43 s after landing · 3,393 agent-branch commits land on main per week
don't make your agents write a shared interface up front; run them all at once on their own branches, list the pieces two branches wrote under the same name or that conflict before merging, move each into one file and delete the copyText for your agent · 30 lines
Situation: you run several agents at the same time on separate branches (git worktrees). When you merge, either two functions that do the same job show up, written by two agents, or the same file conflicts. The common advice is "write the shared interface first, then start the agents."
Why: where the shared piece lives isn't known up front; it shows up at merge time. An interface written up front ties one agent's work to another agent landing first; in my setup that ordering made the agent that used the piece wait until the agent writing it had landed, and once I dropped it they all started at once. A function two agents wrote under the same name, or a conflict on the same lines, is the shared piece itself: in my setup the copy the second agent wrote was folded into one place and deleted 6 min 43 s after the merge. A copy costs one merge pass; waiting costs every agent's turn.
Do:
1. Each agent works on its own branch in its own worktree; don't open a separate up-front task for the shared interface, start the agents at the same time.
2. Write the script that scans the branches side by side before merging, at the project root as .agents/twins.sh (needs git 2.38 or newer: git --version); the file is the block below:
for r in "$@"; do git rev-parse -q --verify "$r^{commit}" >/dev/null || { echo "no branch: $r"; exit 1; }; done
for b in "$@"; do git diff --no-color --no-ext-diff -U0 "HEAD...$b" -- . | sed -nE 's/^\+([a-z]+[[:space:]]+)*(function|const)[[:space:]]+([A-Za-z_][A-Za-z0-9_]*).*/\3/p' | sort -u | sed "s|\$| $b|"
done | while read -r n b; do git grep -qE "(function|const)[[:space:]]+$n([^A-Za-z0-9_]|$)" HEAD -- . || echo "$n $b"; done \
| awk '{n[$1]++; w[$1]=w[$1]" "$2} END {for (k in n) if (n[k]>1) print "same name: " k " ·" w[k]}' | sort
i=0
for a in "$@"; do i=$((i+1)); j=0
for c in "$@"; do j=$((j+1)); [ $j -le $i ] && continue
r=$(git merge-tree --write-tree --name-only "$a" "$c") && continue
echo "conflict: $a ↔ $c · $(printf '%s\n' "$r" | awk 'NR>1 && $0=="" {exit} NR>1 {printf "%s%s", s, $0; s=" "}')"
done
done
3. Run it when the agents are done, at the project root with the base branch (the branch the agents started from, e.g. main) checked out: sh .agents/twins.sh <branch-1> <branch-2> … The script prints two kinds of lines: "same name" (a name that isn't in the base but that two or more branches newly define with function or const on an unindented line) and "conflict" (a pair of branches that don't merge, and the files that conflict).
4. Merge the branches into the base one by one; resolve the files on a "conflict" line by hand in that merge. Once all have landed, for each "same name" line whose copies do the same job, keep the one that behaves right, delete the others and point their callers at the one kept.
5. Add two lines to the instruction file your agent reads every session (Claude Code: CLAUDE.md · Codex: AGENTS.md):
Don't ask for an up-front interface for a shared piece or wait for another agent; write what you need on your own branch.
Before merging, with the base branch checked out, run sh .agents/twins.sh followed by the name of every branch about to merge; the printed pieces that do the same job are moved into one file and the copy is deleted.
Verify (at the project root, as one command: it tests the script in a throwaway repo it creates and deletes at the end, and doesn't touch your branches):
- sh -c 's=$1; d=$(mktemp -d) && cd "$d" || exit 9; g() { git -c user.name=t -c user.email=t@t -c commit.gpgsign=false -c core.hooksPath=/dev/null "$@"; }; g init -q -b main; printf "export function stamp() {}\nexport function slugifyAll() {}\nexport function legacy() {}\n" > base.ts; g add -A; g commit -qm base; for b in a b c; do g branch $b; done; printf "export function stamp() {}\nexport function slugifyAll() {}\n" > base.ts; g commit -qam advance; g checkout -q c; for f in c c2; do printf "export function other() {}\n" > $f.ts; done; g add -A; g commit -qm c; for b in a b; do g checkout -q $b; k="function slugify(s) { return s }"; [ $b = b ] && k="const slugify = (s) => s"; printf "export $k\nexport function stamp() {\n const r = 1\n}\n" > $b.ts; for f in shared side; do printf "x = $b\n" > $f.txt; done; g add -A; g commit -qm $b; done; g checkout -q main; sh "$s" a c b; sh "$s" a d b; cd /; rm -rf "$d"' _ "$PWD/.agents/twins.sh"
- → exactly these three lines: "same name: slugify · a b" · "conflict: a ↔ b · shared.txt side.txt" · "no branch: d".
Don't:
- Make agents write the shared interface up front and wait for it to land: the merge shows which piece is shared, and an interface written in advance often sits in the wrong place.I don't repeat the rule as text: when the agent is about to run the wrong command, a hook denies it and names the command to run instead. I only add a deny where the move has to change, because every deny costs the agent one more step; and I test that the path it suggests actually gets through.
beforefixed after a warning: 36%
afterstopped after a deny: 95% · test the suggested path separately
set the rule up not as a warning but as a hook that denies the wrong command and names the one to run instead; only for mistakes that can't be undone or are expensiveText for your agent · 58 lines
Situation: you wrote your agent a rule (CLAUDE.md, the prompt, or a warning printed by a hook), but the agent keeps making the same move.
Why: the agent reads a warning but usually doesn't change its move; a deny fixes it. In my setup (Claude Code, Nov 1–12, 34,053 hook events), when a hook let an action through and printed a warning and the agent then tried the same action again, it corrected course 36% of the time; when the hook denied the action, 95% of the time. The warning rate comes from a single warning hook, the deny rate from nine deny hooks. A context note added for the agent before a command runs didn't stop the command: with a small model, the expensive command still ran in 3 out of 3 trials.
A deny stops the move but doesn't always get the suggested path chosen: in the trial, the deny stopped the agent in 3 out of 3 runs and got the suggested command chosen in 1. If the suggested path is denied by another rule, the agent makes up a path; in my setup one deny was also denying the very read it suggested.
A deny isn't free: the denied tool call is generated again from scratch (a file being written is written again), and every deny costs the agent one more model step. The hook runs on every matching tool call: if it slows down, every agent waits; if it crashes, they all stop. If a deny asks for something the agent can't actually produce (a rationale, a source, "I tested it"), the agent makes it up to get past the deny.
Do:
(1–4 are for your own rule. If you don't have a rule yet and only want to try the method, set it up with the example rule in 5.)
1. Try the hook-free paths first; the first one that works wins, and no hook gets installed:
a. Do you have text of your own that contradicts the rule or teaches the mistake (an old line in CLAUDE.md, an example command a script prints)? Fix that; don't put a hook on top of it.
b. If the command or script that makes the mistake is yours, put the deny there (the script fails on the wrong argument and says what's right), not in a hook that runs on every tool call.
c. If the mistake already announces itself (a compiler error, the command's error exit), don't add a hook; the agent sees it and fixes it.
2. Can the mistake be recognized from the input of a single tool call (command text, file path, content)? Don't put a hook on a mistake that can't be recognized from the input, like "didn't think it through".
3. Deny, warn, or nothing:
- If the mistake can't be undone (deleting, publishing, overwriting a shared branch) → deny.
- If it can be undone and announces itself later → no hook.
- In between, weigh it: deny ⟺ precision × (0.95 − 0.36) × cost of a missed mistake > one extra model step. Precision is the share of the calls the hook fires on that are actually wrong; on a hook that also fires on correct moves, a deny is expensive, so narrow the match first.
- If you do write a warning, write the outcome, not the rule ("this command took 40 s and wrote 2 GB"). Don't print a rule sentence or "read this file": the agent doesn't open the address, and a copied rule goes stale when the real rule changes.
4. The deny message has two parts, the denied command and the exact command to use instead, for example:
DENIED: git push --force → git push --force-with-lease · does not overwrite what someone else pushed
If the replacement isn't written, the agent makes up its own path. The replacement command must already exist on the agent's machine: don't put a tool that needs installing in the deny message.
5. Install (Claude Code, inside the project; needs jq: command -v jq, otherwise brew install jq). The three leading spaces on the blocks below are this list's indentation; remove them when writing the files. The example carries a single rule: "don't overwrite a shared branch with --force". For your own rule, change only the `yanlis` pattern and the deny message.
.claude/hooks/kural.sh:
#!/bin/sh
command -v jq >/dev/null 2>&1 || { echo "kural.sh: jq not found, the hook cannot decide" >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')
log="$(dirname "$0")/kural.log"
yanlis='(^|[;&|(])[[:space:]]*([A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*[[:space:]]+)*git[[:space:]]+push([[:space:]]+[^;&|]*)?[[:space:]](--force|-[A-Za-z]*f[A-Za-z]*)([[:space:];&|)]|$)'
if printf '%s' "$cmd" | grep -Eq "$yanlis"; then
printf '%s\tdeny\n' "$(date +%FT%T)" >> "$log"
jq -n '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"DENIED: git push --force → git push --force-with-lease · does not overwrite what someone else pushed"}}'
exit 0
fi
.claude/settings.json (if it already exists, add this under hooks):
{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"sh \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/kural.sh","timeout":5}]}]}}
Keep the log file out of the repo: printf '\n.claude/hooks/kural.log\n' >> .gitignore (the leading blank line keeps it from sticking to the last rule when .gitignore doesn't end with a newline)
Keep the matcher narrow ("matcher": "Bash"). The log never records the command text (a command line can carry secrets), only the time and the decision.
Verify:
- A helper that feeds a fake event to the hook. Run it at the project root (where the .claude folder is); run the definition and the calls in the same command (every tool call opens a new shell). The helper calls the hook with the command written in settings.json.
ev() { command -v jq >/dev/null || { echo "no jq"; return 1; }; k=$(jq -r '.hooks.PreToolUse[].hooks[] | (.command // "") | select(test("kural[.]sh"))' .claude/settings.json | head -1); [ -n "$k" ] || { echo "kural.sh is not in settings.json"; return 1; }; jq -nc --arg c "$1" '{tool_name:"Bash",tool_input:{command:$c}}' | CLAUDE_PROJECT_DIR="$PWD" sh -c "$k"; echo "exit $?"; }
- Matcher: jq -r '.hooks.PreToolUse[] | select(any(.hooks[]; (.command // "") | test("kural[.]sh"))) | .matcher' .claude/settings.json → Bash (capital B; if it says "bash", Claude Code never calls the hook). This line only reads settings.json; the three lines below test the hook itself.
- Read the three lines together:
ev 'git push --force' → JSON containing "deny", then «exit 0»
ev 'git push --force-with-lease' → only «exit 0» (the path the deny suggests must get through the hook)
ev 'git push' → only «exit 0»
If you see any number other than «exit 0», the hook is broken.
- Nearest neighbors. Should be denied: ev 'git push -f origin main' · ev 'git push -fu origin main' · ev 'git push origin main --force' · ev 'cd repo && git push --force' · ev 'GIT_TRACE=1 git push --force' · ev 'git push origin "$(git branch --show-current)" --force'. Should pass: ev 'git push -u origin feature' · ev 'echo git push --force' · ev 'git commit -m "never push --force"' · ev 'git push origin main && rm -f x'. Read these two groups together too: "Should pass" alone also holds for a hook that lets everything through, "Should be denied" alone for one that denies everything. A known false deny in this version: the pattern doesn't see quotes, so a «git push --force» inside quotes that comes at the start of a line or after ; & | ( is denied too: ev 'git commit -m "fix; git push --force is banned"' → "deny".
- Escapes, deliberately left open; each prints only «exit 0», with no deny: ev 'git -C repo push --force' · ev 'git push origin +main' · ev 'sudo git push --force' · ev 'command git push --force' · ev 'git push origin main 2>&1 --force' · ev 'git push --mirror' · ev "$(printf 'git push \\\n--force')" (a command split across lines with a backslash) · printf 'git push --force\n' > gonder.sh; ev 'sh gonder.sh'; rm gonder.sh (a script that contains it). This line doesn't test the hook; it shows what isn't closed. The list is an example, not a complete one: the hook only sees the command text, line by line. If an escape would be costly, don't grow the hook; put the deny on the mistake itself (step 1b). In this example: block force-pushes to the branch on the remote (branch protection); that block works regardless of the hook and the agent.
- Duration: time sh .claude/hooks/kural.sh </dev/null → under 0.2 seconds (sh prints «real», zsh prints «total»). This line measures only how long the hook takes, not whether it's correct: it prints a small number even when the hook file is missing; if you see «No such file» next to it, the file isn't there. If the hook reads files, goes out to the network, or starts processes, the time grows; the "timeout": 5 in settings.json cuts the hook off at that second and the command runs.
- Delete the lines your manual runs left: rm -f .claude/hooks/kural.log
- Live: at the project root, claude -p 'run git push --force --dry-run' (--dry-run sends nothing to the remote), then cat .claude/hooks/kural.log → a «deny» line, and Claude's answer names git push --force-with-lease: the hook runs inside Claude Code and its deny reaches the agent.
Don't:
- Don't move every rule into a hook: every deny adds a step for the agent, every hook adds latency to every call.
- Don't copy the rule's text into the hook; write only the outcome and the path to use instead.
- Don't use a deny to ask for something the agent can make up, like a rationale, a source, or "did you test it".
- Don't grow the hook by adding every spelling that slips through to the pattern: the bigger the pattern, the more it denies correct commands too.I don't leave searches over big folders to macOS's own grep: I keep Claude Code up to date, and since 2.1.117 it runs the grep the agent types in Bash with its own fast grep; any big search that doesn't go through it I run with rg. I removed my hook that rewrote grep into rg: in a week it had rewritten 0 real searches.
beforemacOS grep over 96 GB of chat history: 491 s
afterrg: 8.7 s
If you see "grep" in Activity Monitor, stop it with kill and have the agent redo that search with rg; in Claude Code, if type grep doesn't print "function", run claude updateText for your agent · 22 lines
Situation: You're working with an agent (Claude Code or Codex) on macOS. In Activity Monitor a process named "grep" has kept one core at 100% for minutes. The agent is searching a big folder (~/.claude/projects, ~/.codex/sessions, a log folder) or searching one folder for hundreds of patterns at once (grep -rlF -e … -e … or grep -rlF -f patterns.txt), and the command hasn't finished in half an hour. If the process stuck at 100% in Activity Monitor isn't "grep" but a version number (e.g. 2.1.322), this isn't your situation: that's Claude Code itself or its fast grep.
Why: What runs under the name "grep" is macOS's own grep (/usr/bin/grep, BSD grep 2.6.0). On large text it's several times slower than ripgrep (rg), and tens of times slower on text full of non-ASCII letters (Turkish, for one); the time goes to the CPU, not the disk; the number of patterns multiplies the slowness. On my machine grep -rl over 96 GB of Codex chat history took 491 s (8 minutes), rg -l 19 s on a cold disk; a grep with 1,147 patterns ran for 29 minutes at 100% CPU over 435 MB and never finished.
Since 2.1.117 Claude Code doesn't hand the agent's grep to it: when it opens Bash it installs a shell function named `grep` and runs the search with its built-in ugrep (macOS and Linux; Claude Code installed with npm installs the same binary today). In Activity Monitor and top this process shows up not as "grep" but as Claude Code's version number (e.g. 2.1.322, the same name as Claude Code's own process), and in ps -axo args as "ugrep". On the Mac mini with Claude Code 2.1.322, warm cache: on one 457 MB day of Codex chat, macOS grep 2.20 s, Claude Code's grep 0.03 s, rg 0.02 s, all three the same 2 files; 1,147 patterns with -F -f: ugrep 0.06 ↔ rg 0.05 s.
There are three ways to fall back to macOS grep: (a) Codex: it doesn't shadow grep, every grep the agent writes is /usr/bin/grep (Codex's own command output: "grep is /usr/bin/grep"); Codex already writes most searches with rg, the slow one is the search it writes with grep. (b) Claude Code is older than 2.1.117, or the command that launches Claude Code asks for the Grep or Glob tool (--allowedTools, --tools, the Agent SDK's allowedTools or tools list): when either tool is requested, Claude Code leaves grep in Bash to macOS grep (the allow list in settings doesn't do this). The local agent the Claude desktop app opens on a Mac doesn't shadow grep either. (c) In Claude Code, grep runs from inside another program (timeout 60 grep …, … | xargs grep …, find … -exec grep …, bash -c '… grep …', a .sh script, command grep, /usr/bin/grep) or carries a flag Claude Code doesn't pass to its grep (-z, --null and others). Claude Code's grep rejects a two-sided context pattern like .{0,80}word.{0,80} with "exceeds complexity limits"; the agent then rewrites the same search with /usr/bin/grep (on one 324 MB file macOS grep went past 10 minutes for me, rg 0.04 s).
Claude Code's grep skips files in .gitignore and binary files, and doesn't enter version-control folders (.git, .hg, .svn, .jj …). If what you're looking for is there, the agent won't find it; then have it write rg -uuu (searches everything).
Do:
1. In Terminal, see which command is running: ps -axo pid,etime,%cpu,args | awk '$4 == "grep" || $4 == "/usr/bin/grep"'. It prints one macOS grep per line, with how long it has been running and how much CPU it uses; Claude Code's ugrep doesn't appear in this list. Stop the line carrying the agent's search: kill <pid> (the first number on the line); if you don't, that grep keeps holding the core even after the rg search finishes. A killed grep gives no result: if the agent says "143" or "no matches found", the search never happened, and you'll have it redone with rg in step 3. If you're in Codex, go to step 3.
2. If you're in Claude Code, tell the agent: "run type grep and show the output exactly". If it prints a line containing "function" (zsh: "grep is a shell function from …/shell-snapshots/…", bash: "grep is a function"), the agent's grep is already Claude Code's ugrep and the command you saw in step 1 escaped the function: go to step 3. If it prints "grep is /usr/bin/grep", in Terminal: claude --version. If it's below 2.1.117: claude update. Quit and reopen Claude Code and repeat this step. If it's 2.1.117 or newer and the agent was opened by the Claude desktop app: go to step 3. Otherwise the command that launches Claude Code (or the Agent SDK's allowedTools/tools list) contains Grep or Glob; updating won't change that. Remove it from the list, or if you're keeping the Grep tool, go to step 3.
3. Tell the agent to write the search you stopped in step 1 with rg instead of grep (rg -uuu …, timeout 60 rg -uuu …, … | xargs rg -uuu …; -uuu also searches hidden files and files in .gitignore, as grep does). If rg is missing (Codex brings its own rg, Claude Code and Terminal don't): brew install ripgrep. For hundreds of patterns, one call: rg -uuu -lF -f patterns.txt <folder>.
4. If you installed the grep-rg.pl hook from an older version of this package, remove it. With Claude Code's own grep in place the hook gains no speed and breaks two things: (a) it makes the agent search folders in .gitignore too (node_modules, build output): in one repo grep -rl useState . took 0.6 s and found 0 files with the agent's grep, 59 s and 125 files with the rg the hook turned it into; (b) in a mode that doesn't skip permissions (without --dangerously-skip-permissions), grep runs without approval but the /opt/homebrew/bin/rg --no-config … the hook writes returns "This command requires approval", even with a Bash(grep:*) permission in settings. To remove it, delete the hook mentioning grep-rg.pl under "PreToolUse" in ~/.claude/settings.json, then: rm -f ~/.claude/hooks/grep-rg.pl ~/.claude/hooks/grep-rg.log. Reopen Claude Code.
Verify:
- In Claude Code, to the agent: "run type grep; grep -V | head -1" → a line containing "function" and "ugrep 7…". If the second prints "grep (BSD grep, GNU compatible) 2.6.0-FreeBSD", Claude Code didn't install its grep: step 2.
- In Codex, to the agent: "type grep; grep -V | head -1" → "grep is /usr/bin/grep" and "BSD grep": in Codex every search written with grep is macOS grep; in a big folder, step 3.
- The old hook is gone (if you did step 4, in Terminal): grep -c grep-rg ~/.claude/settings.json → 0.
Don't:
- Don't replace grep with rg through an alias or by putting an rg named "grep" on PATH: the flags differ (in rg -h is help and -E is encoding; in plain grep + ? | ( ) are literal characters, in rg they're special), and it silently gives wrong results. Claude Code already removes any grep alias when it installs its function.
- Don't install a hook that rewrites the agent's command to rg (PreToolUse updatedInput): Claude Code asks for permission based on the rewritten command. grep and plain rg -uuu -lH … run without approval, but rg with a full path, --no-config, --include-zero or -I needs approval: the hook adds an approval prompt to every search.
- Don't build a loop that calls a separate grep or rg per pattern (for p in …; do grep …; done): each pattern reads the folder from scratch. Write the patterns to a file and make one call: rg -uuu -lF -f patterns.txt <folder>.Also in: If your laptop runs hot