writingmaclulich.com

How to stop AI coding agents filling your disk, crashing your Mac and looping

Five changes that stop AI coding agents using up your disk, open files and tokens

  1. Turn on loop detection before you leave an agent aloneOne of mine ran the same shell command 1,211 times in a row, because my config never set the guard.
  2. Start each task in a fresh session and cap the contextOne conversation ran 905 turns with a single compaction and reached 334,000 tokens per request.
  3. Set lighter debug info on every build your agents startA build cache saves CPU, not disk: my agents’ build folders came to about 311 GB.
  4. Keep test database data in a named volumeDocker Desktop held 10,514 host files open on one Mac, and the other went down under file-descriptor pressure.
  5. Make the step that finishes a task remove what it madeMy hourly cleanup was allowed to remove 4 of 80 worktrees.
The numbers are mine, from one project’s agents on two Macs over one week.

Every finished task leaves four things behind

If you run AI coding agents on your own machines and the disk, file limit or token bill keeps surprising you, this is for you. The story starts with one week of mine.

In that week my coding-agent fleet crashed a Mac, filled 450 GB of disk, ran the same shell command 1,211 times in a row and pushed one conversation to 334,000 tokens per request.

None of that was a model getting code wrong. Every one of those problems came from resources that outlived the work that created them.

What one week of agents left behind

1,211
identical tool calls in a row, from one agent
457 GB
of disk held by one project’s agent worktrees
4 of 80
worktrees the hourly cleanup was allowed to remove
10,514
host files held open by Docker Desktop
905
turns in one conversation that was never reset
116 GB
OpenCode session database, 27 GB after pruning
One project, two Macs, one week.

The fix that mattered was an ownership rule rather than a better cleanup job: the step that finishes a unit of work removes everything that unit created. This is what I measured on the way there, and what I changed.

I run a small fleet of agents across two Macs, supervised by Rigby, a tool I built. A head agent on Claude Opus plans the work, hands out units of work, verifies the results and merges them.

Producer lanes do the implementation, each in its own terminal pane and git worktree, a separate checkout of the same repository. One runs Codex and another runs OpenCode on DeepSeek V4.1 Flash.

Every unit of work leaves four things behind unless something removes them

  1. worktreea separate checkout of the repository
  2. build outputa Rust target/ folder of 5 to 50 GB
  3. test stacka Postgres container with its own data folder
  4. agent sessiona conversation that grows until it’s reset

The head also starts its own short-lived subagents. Rigby keeps the panes alive, delivers work through a mailbox and gates merges.

Turn on loop detection for unattended agents

The DeepSeek lane got stuck on one test. It ran this, saw no output, and ran it again, 1,211 times back to back and 2,210 times over three days:

cargo test -p pipeline-worker preflight_cli 2>&1 | grep -n "panicked at"

The grep printed nothing because nothing had panicked. Every result looked the same, so the model kept retrying instead of changing approach.

OpenCode has a guard for exactly this, the doom_loop permission, but my config never set it. If your harness has a guard like this, check that it’s on before you leave it alone.

Before: ~/.config/opencode/opencode.json

"permission": { "bash": "allow", "edit": "allow" },   # no doom_loop set
"limit": { "context": 1048576 }                     # compaction waits for ~1M tokens

After

"permission": { "bash": "allow", "edit": "allow", "doom_loop": "deny" },
"limit": { "context": 262144 },
"autoupdate": false                                 # no "update now?" dialog blocking an unattended pane

My config now denies the loop, caps the context at 256K and turns off auto-update, so no dialog can block an unattended pane.

I’m still not sure how much of the loop is the model and how much is the harness. Codex and Claude Code handle repeated calls differently, so the honest test is the same model under another harness, and that trial is next.

Cap the context and start each task fresh

The same lane had a second problem. I assumed output tokens drove its bill, but they didn’t.

An agent re-sends its whole conversation on every turn. On this lane 99.4% of tokens were cache hits, averaging about 210,000 tokens per request, and cheap per token adds up fast at that size.

One conversation ran 905 turns and compacted once

905
turns across many unrelated tasks
36K → 334K
tokens in the prompt, re-sent every turn
1
compaction in the whole conversation
OpenCode had been told the model had a 1M-token window, so it waited for one.

When DeepSeek shipped an update that produces shorter outputs, I checked whether it would help. It barely does, because shorter answers trim output tokens and this spend was re-sent input.

What helps is a fresh session per unit, so one task’s history never rides along into the next, plus the 256K ceiling in the config above, so compaction happens long before the window fills.

Don’t expect a build cache to save disk

The other bill was disk. Every agent worktree got its own Rust target/ folder of 5 to 50 GB, about 311 GB in all.

I had sccache, a shared compiler cache, with a 57% hit rate and assumed it covered this. It doesn’t, because a cache hit skips the compile but still copies the result into each worktree.

One lane’s 52 GB build folder held 21 copies of the same binary

63,616
*.rcgu.o debug object files
19.5 GB
taken by those object files alone
21
copies of the same binary
Cargo never deletes old artifacts, so they pile up in every worktree.

Rigby now sets lighter debug info on every build it starts, so no project has to remember to:

CARGO_PROFILE_DEV_DEBUG=line-tables-only   # set for every cargo Rigby launches

Worktrees were also nesting, because agents created worktrees inside worktrees, three levels deep. The cleanup job protected everything under a lane’s folder, so most of them were off limits to it.

Nested worktrees put 76 of 80 out of the cleanup’s reach

3
levels deep, worktrees inside worktrees
76 of 80
worktrees off limits to the cleanup job

New worktrees now go at the repository root, and protection covers the exact lane checkouts only.

Keep test database data in a named volume

Disk wasn’t the only limit I hit. One Mac went down under file-descriptor pressure, and on the other, com.docker.backend held 10,514 open host files.

Docker Desktop held 10,514 host files open for stacks whose work had merged

10,514
host files held open by com.docker.backend
~1,500
per running test stack
70
data folders left by work that had long since merged
99% of the open files were Postgres data directories bind-mounted from the Mac.

Earlier, to stop “too many open files” errors, I had raised the limit to effectively unlimited with kern.maxfiles=2147483647.

That removed the brake. A leak that should have failed one process exhausted the kernel instead.

The fix is to keep a test stack’s database data inside Docker’s virtual machine, where the Mac doesn’t hold a file open for every file Postgres touches:

Before: data on the Mac

services:
  postgres:
    volumes:
      - ${HOME}/neuma-data/neuma-postgres:/var/lib/postgresql   # every file held open by Docker Desktop

After: a named volume

services:
  postgres:
    volumes:
      - postgres-data:/var/lib/postgresql
volumes:
  postgres-data: {}

Rigby now does this conversion itself for test stacks when it registers them, and refuses a new dev stack that keeps its data on the host.

It never moves or deletes an existing data folder. The one thing worse than 92 GB of stale folders is a cleanup that destroys the one folder you still needed.

Make sure whoever finishes the work cleans up

Every problem above had been patched before with a periodic sweep, an hourly job that guessed what was safe to delete.

Sweeps lag, and they can’t tell abandoned work from work in progress. Every wrong guess gets them tightened until they delete almost nothing, and mine removed 4 of 80 worktrees.

The step that ends a unit owns its teardown, and the sweep becomes an alarm

Before: sweep later

  1. A unit creates a worktree, build output, a test stack and a session
  2. rig done records the result
  3. Everything it made stays behind
  4. An hourly sweep guesses, and removes 4 of 80

After: the owner closes

  1. A unit is admitted only if the host has room
  2. The unit does its work
  3. rig done or rig blocked removes what it made
  4. Anything the hourly sweep still finds is a BUG report
Before, finished units left their resources for a sweep that rarely removed them.

Now the step that ends a unit removes what that unit created. That step is rig done or rig blocked, which is how a lane reports its result, or a cancel.

It removes the unit’s child worktrees, their build output, its test stacks and its old agent sessions. Anything with a running process, or commits no branch holds, is kept and reported with the one command that removes it.

Update, 26 October. The first version also kept anything with uncommitted files, and that was a leak of its own. Three days later, 17 worktrees whose work had merged were still on disk.

What happens to leftover files now

# a merged worktree with leftover files, at the end of its unit
git stash push --include-untracked \
    --message "rigby clean: leftovers of <worktree> <commit>"
git worktree remove --force <worktree>   # git stash apply <sha> brings the files back

Scratch files had held them, along with a stray file named -a and one broken find-and-replace copied into six of them. The leftovers now go into a named stash, and the worktree goes.

Tell agents what’s decided and who to ask

Not every cost was a resource. Agents stopped to ask permission for steps their brief had already decided, typing the question into a terminal pane nobody was watching.

A public-safe reconstruction of a real pane, lightly trimmed. The brief had already said to block in exactly this case, and nobody was watching the pane to answer.

The standing prompt every lane starts with now tells a producer to act when its brief decides a case, and to ask the head agent, never the pane, when it can’t.

The quietest cost is review rounds, and the lanes differ a lot in how often they pass first time.

First-time review passes: 67% for DeepSeek, 80% for Codex, 93% for Claude Opus

DeepSeek lane67%
Codex lane80%
Claude Opus lane93%

Part of that gap is the model. A lot of it is the same project-specific mistakes caught again and again, like an old database writer left registered after a replacement.

The bigger piece was still being built when I wrote this: a short contract of rules for each unit, shared by the implementer and the reviewer, with repeated findings fed back into the next brief as known traps.

Four smaller checks worth running first

Four checks I’d run first next time

  1. Check the environment before blaming the codeOf 15 failing tests, 13 needed a tool that wasn’t installed, one needed Docker running, and one had a fixture writing a mailbox file with the wrong permissions. None were code defects.
  2. Check the measuring tool, because an empty answer can mean “couldn’t look”My disk audit reported every database folder as unused because docker wasn’t on that shell’s path.
  3. Give the fast test track a budgetMoving 196 tests that took two seconds or more into the slow track took the fast run from 515 to 82 seconds, and the slow track still runs before every release.
  4. Configure the harness before leaving it unattendedOpenCode’s database grew to 116 GB, 113 GB of it an event table holding a snapshot of a message part on every streaming update.

A missing path also stopped one lane running Docker at all, because Rigby had started it without /usr/local/bin on its path:

WORKTREES_DOCKER_FAILED: docker ps -aq --no-trunc --filter label=com.docker.compose.project: No such file or directory (os error 2)

Lanes now get a complete path.

How far to trust it

One project, one week, a leaky first cleanup and a loop I can’t fully explain

  1. One project, two Macs, one weekEvery number here comes from one project’s agents
  2. The first cleanup leakedIt kept anything with uncommitted files, and 17 worktrees whose work had merged were still on disk three days later
  3. The loop’s cause is openI’m not sure how much was the model and how much the harness. Running the same model under another harness is the next trial
  4. The review contract was unfinishedIt was still being built when I wrote this

Copy this checklist before you leave agents running

Five things to set before you leave agents running

  1. Turn on loop detectionOpenCode: "doom_loop": "deny" in the permission block
  2. Cap the context, and start each task freshOpenCode: "limit": { "context": 262144 }, so compaction comes long before the window fills
  3. Lighten debug info on every buildCargo: CARGO_PROFILE_DEV_DEBUG=line-tables-only
  4. Keep database data in a named volumeDocker Compose: postgres-data:/var/lib/postgresql, not a host folder
  5. Close each task by removing what it madeIts worktrees, build output, test stacks and old agent sessions, and report anything it keeps

The first two settings are OpenCode’s, the third is Cargo’s and the fourth is Docker Compose’s. The fifth is the rule behind all of them.

How it works

Cleanup is part of finishing the work, not a job that runs later

  1. Admita unit starts only when the host has room
  2. Closethe step that ends a unit removes what it made
  3. Alarmanything a sweep still finds is a BUG in its owner

New resources are admitted only when the host has room in disk, open files and running stacks. If the hourly sweep ever finds something to reclaim, that’s a BUG in the owner that failed to close it.

Agents produce far more resources than people do, and they never tidy up on their own. When a periodic cleanup finds something to delete, the right response is to fix the owner that left it behind.

The review contract and the lessons loop have their own write-up: how to brief AI coding agents so review stops catching the same mistakes.