How it works
Abstract
Section titled “Abstract”People who use coding agents such as Claude Code every day build up two kinds of waste.
- Context. Every session starts by loading plugins, skills, MCP tool definitions, hooks and instruction files. On the author’s machine, the first reply of a session cost about 55k tokens before the user typed a word. Much of that came from duplicates, servers that never connect, and tools that had not been called for a month.
- Leftovers on the machine. Temp directories, interrupted plugin installs, superseded plugin versions, old transcripts, merged git worktrees, and MCP server processes that outlive the agent that started them.
Agent GC treats the second problem as garbage collection in the runtime sense:
- there is a root set, a mark phase with a single set of rules, a write barrier, generations and a pacer;
- unlike a language runtime, nothing is freed immediately. Everything goes through a quarantine from which it can be restored.
For the first problem it measures the real start cost of each session from the agent’s own transcripts, and offers a reversible switch for every source of that context.
This document explains the model, the rules, the safety argument and how we test it.
1. The problem
Section titled “1. The problem”Processes. The Claude Code issue tracker has reported orphaned MCP server processes for a long time:
- #1935, #27707 and #33947 report the leak; one report counts 96 orphaned processes after a day of work;
- #22612 was closed as not planned.
When an agent exits, its stdio MCP servers are re-parented to launchd/init and keep running, holding memory, ports and locks.
Disk.
~/.claudegrows without bound (#24207). The agent’s temp root and file history can grow much faster (#10107).- Worktrees that agents create for parallel work outlive their branches.
Context.
- Every enabled plugin, skill description, MCP server, hook output and
CLAUDE.mdimport is paid for at the start of every session. Users rarely see the total, and even more rarely see what it is made of.
The two problems need different treatment:
- Leftovers can be collected automatically, but only if the collector is provably conservative.
- Context sources are the user’s choices. The tool shows them, measures them and makes them easy to turn off. Context sources are switched off automatically only after the user has turned automatic mode on, only when unused, only between sessions, and always reversibly. Hooks are never switched off automatically, and the user can bring any source back in one step (§8).
2. Requirements
Section titled “2. Requirements”- Never lose work. A worktree with uncommitted or unmerged changes, a temp directory that contains a repository, a transcript a running session may still write, a process that is not provably an orphan: none of these may be touched.
- Everything automatic can be undone. Every action Agent GC takes on its own can be reversed for a while.
- Conservative under uncertainty. If a fact cannot be established (a config file is unreadable,
gitfails, a process’s command line cannot be read), the object is alive. - Cheap. A background collector that is itself heavy defeats the purpose.
- One decision point. The rule “is this garbage” lives in exactly one function, so a safety property cannot be forgotten in one of many collectors.
3. Architecture
Section titled “3. Architecture”flowchart TB
Roots["<b>Snapshot (roots)</b><br/>processes and their cwd<br/>agent start times<br/>config references: installed plugins, MCP commands<br/>git repositories, default branches"]
Heaps["<b>Heaps</b><br/>tmp · transcripts<br/>plugin temp / versions · edit history<br/>worktrees / worktree records<br/>orphaned helpers · idle sessions"]
Roots --> M{mark}
Heaps -- "objects + facts" --> M
M -- dead --> PL[plan: budget, order]
PL --> B{{"barrier: refresh + mark again"}}
B -- still dead --> Q[("graveyard<br/>(quarantine)")]
Q -- TTL --> X[reclaim]
Q -- user --> U[restore]
The collector is a pipeline:
-
Snapshot. Once per cycle, Agent GC records what is alive: the process table and every process’s working directory, the start times of running agents, the keys that configuration files reference (plugin install paths, MCP command lines), and the user’s git repositories.
-
Heaps. Each kind of garbage is a heap. A heap only enumerates its objects and reports facts about them:
last_touch, the newest modification time;- anchors: a path a live process may work in, a configuration key, a process identity;
- an intrinsic verdict:
Garbage,Live(reason)orUnknown(reason).
A heap never decides that something should be removed.
-
Mark. One function judges every object against the snapshot (§4).
-
Plan. Dead objects are ordered by benefit (processes first, then by size) within a per-tick budget of 200 objects, and 5 s for young collections.
-
Barrier. Right before acting, the heap re-reads the object’s facts, the process table is refreshed, and mark runs again (§5).
-
Quarantine and reclaim. The object moves to the graveyard, and is finally deleted when its time is up (§6).
Adding support for another agent means adding heaps; the core does not change.
4. Mark: when is something garbage
Section titled “4. Mark: when is something garbage”An object is dead only if every rule below holds. The first rule that fails keeps it alive.
flowchart TD
S([object]) --> I{intrinsic is Garbage?}
I -- "Live / Unknown" --> L1([alive: holds work or unknown])
I -- yes --> AN{an anchor reachable<br/>from the roots?}
AN -- yes --> L2([alive: in use / referenced])
AN -- no --> ID{idle longer than<br/>min_idle?}
ID -- no --> L3([alive: recently used])
ID -- yes --> EP{epoch rule on, and an agent<br/>started before it went quiet?}
EP -- yes --> L4([alive: a running agent may use it])
EP -- no --> TE{dead for longer<br/>than tenure?}
TE -- no --> L5([alive: not dead long enough])
TE -- yes --> D([dead])
- Intrinsic. Only
Garbagecan be dead. BothLiveandUnknownmean alive (conservative mode). - Anchors.
Path(p)is reachable if any live process works insidep.Key(k)is reachable if a configuration file referencesk. If any such file could not be read, every key counts as referenced.Process{pid, start}means there is nothing to collect if no process with that pid and start time exists. The start time guards against pid reuse.
- Idle time. The object must be untouched for the heap’s
min_idle. If there is nolast_touch, the object is alive. - Agent epoch. This is the equivalent of snapshot-at-the-beginning. Let
quiescent = max(last_touch, dead_since). If any running agent started at or beforequiescent, the object stays alive, because that agent may have started using it before it went quiet. This one rule covers three cases:- a temp directory of a running session;
- a transcript it may still append to;
- a plugin version it loaded before an update.
- Tenure. Some heaps require an object to look dead continuously for a period.
dead_sinceis stored per object, and it resets as soon as the object looks alive again.
The heaps and their policies:
| Heap | Generation | min_idle | tenure | epoch | automatic |
|---|---|---|---|---|---|
| tmp | young | 3 d | – | yes | yes |
| orphaned helper | young | – | – | – | yes |
| idle session | young | 24 h | – | – | no |
| context source | old | 30 d | – | no | yes |
| plugin temp | old | 1 d | – | – | yes |
| plugin version | old | 7 d | 7 d | yes | yes |
| transcript | old | cleanupPeriodDays (≥ 1 d) |
– | yes | yes |
| edit history | old | 1 d | – | yes | yes |
| worktree | old | 3 d (HEAD, reflog) | – | – | yes |
| worktree records | old | – | – | – | yes |
What each heap collects, and when it counts as garbage:
- tmp: only
<tmp_root>/-<project>/<session>;Liveif it holds git work - orphaned helper: no agent among its ancestors any more and either recorded while its agent lived (a direct child, or anywhere in the subtree of a configured MCP server) or itself or an ancestor runs a configured MCP command and was re-parented to init/launchd/systemd; launchers are compared by package (
npx -y X≡npm exec X,uvx X≡uv tool run X); never pid 0/1 or an unreadable command line - idle session: shown with an End button, never ended automatically
- context source: plugins, skills and MCP servers (never hooks) of one installation, switched off by
set_enabled(false)with a backup;last_touchis the later of the newest transcript that used it and the first time Agent GC saw it enabled, so a source installed yesterday is not “unused for 30 days”; sources that cost 0 tokens are skipped;Livewhile any agent runs or after the user brought it back (spared);Unknownifsettings.jsonor the transcripts cannot be read orcleanupPeriodDays< 30; only after automatic mode is confirmed; the entry in the graveyard (kept 30 days, nothing on disk) is how it comes back - plugin temp: interrupted installs (
temp_*) - plugin version: anchored by
installPathin every installation’sinstalled_plugins.json - transcript: the agent’s own retention setting
- edit history:
file-history/<session>:Garbageonly once the session’s transcript is gone, so/resumeand/rewindkeep working - worktree:
Garbageonly if clean and HEAD is an ancestor of the default branch - worktree records:
git worktree prunefor records whose directory is gone
5. The barrier
Section titled “5. The barrier”Agents keep working while the collector runs. Between mark and action:
- a worktree may get a new commit;
- a temp directory may get a cloned repository;
- a pid may be reused.
Before every action, the heap’s refresh re-reads the object’s facts. Examples:
- the temp heap runs
holds_workagain; - the worktree heap checks again that the worktree is clean and merged;
- the orphan heap looks the process up again by pid and start time.
The process table is refreshed at most once a second, and mark runs again with the stored dead_since. If anything changed, the object is skipped silently. Ending up alive is not an error.
6. The graveyard: quarantine before reclaim
Section titled “6. The graveyard: quarantine before reclaim”Nothing Agent GC collects automatically is freed right away.
stateDiagram-v2
[*] --> Alive
Alive --> Dead: mark
Dead --> Alive: facts change
Dead --> Quarantined: barrier passes
Quarantined --> Alive: restore
Quarantined --> Reclaimed: TTL expires / disk pressure / size cap
Reclaimed --> [*]
-
Files and directories are renamed into
<data>/graveyard/<id>/payload, next to a manifest. A rename on the same file system costs nothing and never leaves a half-moved tree. On another file system (Linux/tmpon tmpfs) the rename does not happen:- temp directories are deleted, as before;
- everything else goes to the system trash.
Temp files are kept a day, everything else a week. Under disk pressure files are kept an hour, and the graveyard never holds more than 10 % of free space.
-
Worktrees are locked with
git worktree lockbefore they move. A locked record survivesgit worktree prune, both ours and git’s own, so a restored worktree is whole again. The lock is released on restore, or just before the final prune. -
Processes are suspended with
SIGSTOP. Within the hour, the user can resume one, and then it is marked spared and never taken again. When the hour is up, the process is ended (SIGTERM,SIGCONT, thenSIGKILLafter 5 s), but only if it is still the same process (pid and start time) and still stopped. Every signal goes through one guard that refuses pid 0, pid 1, process groups, and Agent GC’s own process, parent and group. -
Restore refuses if something new now occupies the original path.
The cost is that disk space is freed later. Reports therefore count freed bytes and held bytes separately.
7. Generations, the pacer and live mode
Section titled “7. Generations, the pacer and live mode”Garbage dies at different speeds.
- Young garbage (temp directories, orphaned helpers) is cheap to find and appears with every session.
- Old garbage (transcripts, plugin versions, worktrees) needs more work to judge (
git, sizes) and appears slowly.
The pacer collects young garbage every 15 minutes and old garbage daily, and does an extra old collection when the home volume has less than 10 % or 5 GB free.
Live mode (agent-gc auto on) replaces the timer with events. It runs as a login service (a LaunchAgent on macOS, a systemd user unit on Linux) and inside the menu bar app.
sequenceDiagram
participant K as kernel (kqueue / pidfd)
participant L as live loop
participant E as engine
participant G as graveyard
Note over L: every 10 s: observe agents,<br/>record their direct children<br/>and MCP server subtrees
K-->>L: agent pid exited
L->>L: wait 2 s (helpers get re-parented)
L->>E: collect(young)
E->>E: snapshot, mark, barrier
E->>G: SIGSTOP orphaned helper, write manifest
L->>E: next_due()
E-->>L: earliest deadline and its generation
L->>L: sleep until then (≤ 1 h), or until the next event
-
Agent exits. The loop watches agent pids with kqueue
EVFILT_PROC/NOTE_EXITon macOS andpidfd_open+pollon Linux.- An agent that drops out of the process list counts as exited, so an exit that happens during a collection is not lost.
- A zombie that stays listed is reported only once.
- Agents are looked for every 10 s, so the helpers of a short session are recorded before it ends.
-
Deadlines.
next_dueasks mark when each object that is alive only because of time stops being alive:- for
min_idle,last_touch + min_idle; - for tenure,
dead_since + tenure.
It takes the earliest of these, the earliest graveyard expiry and the next daily old collection. The loop sleeps exactly until then and collects only that deadline’s generation. After a deadline pass, the next one waits at least 5 minutes, so a deadline that cannot be met (say, a file that will not delete) never makes the loop spin.
- for
-
File changes under the temp root and the agent configuration directories (FSEvents / inotify) trigger a recomputation of deadlines after 30 s of quiet, at most every 5 minutes.
-
Leftovers. A collection that stops at its budget continues after 5 s.
-
One collector. Whoever holds
owner.lock(flock) collects automatically; the service and the app take turns, and the other only reports. Each single collection, including a manualagent-gc clean, also holdscollect.lock. -
Confirmation first. Before the user confirms automatic cleaning once, there are no deadlines and nothing is collected. That one-time confirmation (Clean automatically in the app or the TUI,
agent-gc clean --yes,agent-gc auto on) is automatic mode: it covers the removals and the automatic switch-off of unused context sources alike, and every consent text names both.
8. Measuring the start of a session
Section titled “8. Measuring the start of a session”Agent GC does not estimate the start cost; it reads it. The first assistant message of every interactive session in the agent’s transcripts records the tokens the model received: input_tokens + cache_creation_input_tokens + cache_read_input_tokens.
- Headless sessions (
entrypointother thancli) are excluded, because they are started by tools with a different context. - The headline is the median of the last 7 days; the trend is weekly over 8 weeks.
Each source of that context is listed with its share, read from the same transcripts. Claude Code records what it put in context as attachments, and the 5 newest interactive sessions show, per source:
- MCP servers: their instructions and deferred tool names (tool schemas are mostly deferred and load only when a tool is used);
- skills: their lines in the skill listing;
- plugins: their MCP servers and agent lines.
Characters become tokens at 2.05 per token, calibrated against an A/B run (the same session start with a source on and off). Everything else is an estimate and is marked ≈:
- a source not seen in those sessions: an MCP server from its tool names, found by probing
initializeandtools/listin parallel (cached for 24 h); a skill from itsSKILL.md; - a server whose tools were loaded in full (no deferred tools in that session): its instructions plus its probed schema;
- hook output (a settings hook’s or a plugin’s), from its recorded text, and
CLAUDE.mdwith its imports.
A switched-off source counts 0. The sources are scaled down to the measured total when they would exceed it, and a scaled row is marked ≈ too. Sources are flagged as duplicate, not connecting, unused for N days, loaded while disabled or remote.
Turning a source off is reversible:
- plugins and skills use the agent’s own settings;
- MCP servers and hooks are moved to a stash, and the config is edited atomically with a backup, retried if the agent wrote the file in between, with symlinks and key order preserved.
Context sources are switched off automatically only after the user has turned automatic mode on, only when unused, only between sessions, and always reversibly. Switching off sources needs its own confirmation (auto_switch_off_confirmed) for users who confirmed automatic mode before this version; without it the heap is not registered and takes nothing. This is the context-source heap of §4: it runs in the old generation, so a source is checked when its 30 days run out and in the daily old collection, never while an agent of the machine runs.
- Visible. Each switch-off is a graveyard entry (installation, source, tokens). The app and the TUI list it with Bring back;
agent-gc scanprintsswitched off automatically: meshy (2k) · agent-gc restore <id>per installation, and today’s summary counts it (switched off N · ≈Xk). - Undoable in one step.
agent-gc restore <id>switches the source back on and marks it spared: it is never taken automatically again, though the user can still switch it off by hand. When the 30 days of the entry expire, the source stays off and can be switched on from the source list. - Budget.
agent-gc budget <install-id> <tokens>|offsets an optional start-up budget: only the heaviest unused sources are switched off, until the start cost fits. - Notice (opt-in).
agent-gc notify onadds a SessionStart hook that prints onesystemMessageafter an automatic switch-off (“Agent GC switched off meshy (unused 30 days, 2k tokens).agent-gc restoreto bring it back.”). It is shown to the user, not added to the model’s context, exits 0 and prints nothing on any error.
8.1 Repository budget
Section titled “8.1 Repository budget”A repository can set max_start_tokens in .agent-gc.toml. Sessions are attributed to a repository by the cwd recorded in the first line of a transcript (the project folder name is a lossy encoding of the path, so it only selects which folders to open and the cwd decides). The repository’s start cost is the median of its sessions in the last 7 days, or of its last 10 when fewer than 3 are recent, per installation. Sources carry a scope: the repository’s own files (CLAUDE.md, .claude/CLAUDE.md, .claude/skills, .mcp.json, project hooks) are the repo part; everything else belongs to the machine. A .mcp.json server counts only where Claude Code loads it: approved (enableAllProjectMcpServers or enabledMcpjsonServers) and not in disabledMcpjsonServers, per installation; it is estimated from its full tool schema (probed, not read from sessions like a machine server), started from the repository’s root as Claude Code starts it (a relative command such as ./scripts/mcp.sh resolves there, never in the folder Agent GC runs in) and cached per repository, and an unapproved server is never started. Among the heaviest machine sources, an MCP server configured for another project folder is left out, since it never loads in this repository. The machine part is the measured total minus the repo part, which makes it an estimate on top of a measured total.
The result is a warning, never a lever: it appears in scan, in the tray (repositories seen in transcripts of the last 30 days, the budget file read before any transcript is opened), in agent-gc budget repo, and at session start through the opt-in hook, which reads cwd and transcript_path from its stdin. The hook runs before every session, so it takes a cheap path: only its own installation, only the repository’s own transcripts (other project folders only when an earlier full run learnt they hold its sessions), cached MCP probe results only (nothing is started; an unprobed server counts its config length or nothing), and no calibration against the whole installation. scan and budget repo do the full sizing, and scan sizes each installation once for all the repositories it reports. Nothing is blocked or switched off, because the sources it would remove are shared with every other repository.
9. Evaluation
Section titled “9. Evaluation”Unit and integration tests.
- 293 Rust tests and 16 UI tests.
- Every v1 rule kept its test through the migration from five ad-hoc collectors to heaps. Each migration step had to produce the same garbage as the code it replaced, and on the author’s machine the old and new versions found the same set.
- Each fix found in review has a test that we checked fails without the fix.
End-to-end scenario (tests/e2e.sh, 50 checks). It runs on a generated home directory with real binaries, real processes and real git:
- confirmation gating;
- catch-up collection;
- a fake agent started after the daemon, whose helper is suspended 2 s after the agent is killed;
- restoring a process, which is then not taken again;
- restoring a worktree, which comes back whole after a
git worktree prune; - restore refusing an occupied path;
- one collector across two daemons, with takeover when the first stops;
- automatic switch-off of unused context sources on a separate home (skipped locally while a real agent runs, a failure in CI);
- repository budgets across two installations,
scan,budget repoand the session-start hook; - the TUI driven through a pseudo-terminal;
- the menu bar app collecting on the same home.
Cost. The idle daemon used 0.0 % CPU and 25 MB of memory on an Apple Silicon Mac.
Conservatism observed in practice. During the end-to-end run, a real agent session that had been running for five days on the same machine correctly kept a five-day-old temp directory alive through the epoch rule. The test had to age the directory to 60 days to see it collected.
10. Limitations
Section titled “10. Limitations”- Claude Code and Codex CLI. Cursor and Gemini CLI fit the same model as additional modules. For Codex, Agent GC measures the start cost from the first model request of each interactive rollout, lists
AGENTS.md, skills and MCP servers (switching servers with Codex’s ownenabled = false), and recognises its MCP helpers as orphans. Codex keeps sessions without a retention setting, so they are the user’s history and are not collected. - Agent memory is not collected. That includes
memory/, claude-mem and Codex memories: deleting a memory is irreversible, and its value cannot be judged by a rule. - Orphan detection is deliberately narrow. A process is taken only if Agent GC saw it under an agent (a direct child, or inside the subtree of a configured MCP server, which covers servers started through
npxoruvx), or it runs a configured MCP command, or descends from one that was orphaned. Identity is pid plus start time, never a name pattern. Processes under the agent’s shells (dev servers started through the Bash tool) are the user’s and are never recorded. Each process is suspended and ended on its own, never through a process group. Helpers that fit none of this are left alone. - Context sources are switched off automatically only in a narrow case. Context sources are switched off automatically only after the user has turned automatic mode on, only when unused, only between sessions, and always reversibly. Hooks are excluded, because a hook’s position in the list is its identity and it can hold a safety check. Nothing is switched off while any agent runs, when
settings.jsonor the transcripts cannot be read, or when Claude Code keeps transcripts for fewer than 30 days (cleanupPeriodDays< 30), since non-use cannot then be proven. Sources installed or first seen less than 30 days ago are not unused, and anything in a repository (CLAUDE.md, repo skills,.mcp.json) is the team’s and untouched. Codex is not covered yet. - macOS and Linux only.
11. Related work
Section titled “11. Related work”Disk and process cleanup for coding agents. We read the code and documentation of five open-source tools (December 2026):
| Tool | Covers | How it decides | Background | Undo |
|---|---|---|---|---|
| aigc | worktrees, node_modules, build output, package caches |
pins, in-use check, open-PR check, 7-day idle | hourly | none: dirty worktrees are removed with --force |
| agent-sweep | session data and worktrees of Claude Code, Codex, Cursor, Trae | TTL on newest file, lsof, never-clean list (memory, credentials) |
no | trash batches with a manifest |
| agent-cleanup | worktrees, branches, agent logs (incl. file-history, Codex sessions), caches |
14-day stale, cwd in use, re-check before apply | no | unpushed commits kept under refs/agent-cleanup/ |
| mcp-reaper | MCP server processes | name match (mcp, fastmcp, …), parent chain to launchd/init |
optional timer, 15 min | none |
| claude-gc | Claude and MCP processes without a TTY | name patterns, ancestry, minimum age; force-kills after 4 h | cron, 15 min | none |
Agent GC differs in five ways:
- Identity, not names. A process is an orphan only if Agent GC saw it as a direct child of an agent, or its command line equals a configured MCP server exactly. Name patterns such as “anything with
mcpin its arguments” also match a user’s own detached servers. - One decision point with a barrier. Every fact is re-read right before acting.
- The agent epoch. A file a running session may still use is kept even when it looks old.
- Restorable quarantine for processes and worktrees, not only files. A suspended process can be resumed; a worktree comes back whole because its git record is locked while it is away.
- Event-driven. Helpers are suspended seconds after their agent exits, not on the next timer.
Agent GC does not collect build output, node_modules or package caches; aigc and agent-cleanup do, and they complement it.
Context-window garbage collection is a different problem: what to drop from a running conversation.
- Self-GC (Xiaohongshu, July 2026) lets a planner model fold, mask or prune spans. It commits only at turn boundaries, so the prompt cache is not broken mid-turn. It pruned 44 % of input tokens with 85 % “no impact” on a hard set, where rule-based baselines pruned more but kept less. A fold keeps the exact payload outside the context behind a pointer.
- Memex(RL) keeps a short indexed summary in context and the full artifacts in a store the agent can read back by index.
- Origins’ survey covers six more systems. One idea from it matters for any collector of memories: judge a set of deletions together, because items that are individually redundant can be jointly necessary.
- Others prune sessions (Cozempic, SWE-Pruner) or drop committed code from context (AGC).
Agent GC works one level earlier: what gets loaded before the conversation starts. Two lessons transfer:
- change the start-up set only at session boundaries, never mid-session, which is what its switches do;
- keep anything removed recoverable behind a pointer, which is what the graveyard does.
Agent memory. The wGrow field note argues for deterministic retention classes and keep-newer deduplication rather than LLM judgment. This is the direction we expect to take for memory files, which v1 deliberately leaves alone.
Runtime garbage collectors. The vocabulary and much of the structure come from tracing collectors:
- roots and reachability;
- snapshot-at-the-beginning marking with a write barrier;
- generational collection;
- Go’s pacer;
- G1’s benefit-first ordering.
The main departure is that “free” means “quarantine” here, because a mistaken free deletes a person’s work, not a few bytes of heap.
12. Source
Section titled “12. Source”The code is at github.com/Dimitreee/agent_gc. The collector lives in crates/core/src/gc/, live mode in crates/core/src/live/, and the design documents in docs/superpowers/specs/.