Best Practice & Paired Evaluation
Make cleanup the last step in AGENTS.md: a 32-run coding agent eval.
Coding agents are great at shipping features in temporary Git worktrees, running cargo build, and spinning up debug servers—and terrible at cleaning up afterward. We put one 4-sentence cleanup rule through 32 isolated Codex runs to measure what it fixes, what it costs, and where it breaks.
Published · 32 paired runs (24 EN + 8 ZH) · Codex gpt-6.2-sol (medium) · macOS APFS
Short answer
Adding one 4-sentence delivery cleanup rule to AGENTS.md or CLAUDE.md raised strict clean delivery from 50.0% (8/16) to 87.5% (14/16) across 32 isolated Codex runs—and from 12.5% (1/8) to 100% (8/8) on Git worktree build tasks, cutting leftover build artifacts from 150.6 MiB to 0 B with 100% (16/16) protected-asset safety.
Paired median overhead across 15 complete pairs was +4.1 s wall-clock (+3.6% of control median), +2 shell commands, and +3,846 uncached input / +135 output tokens (90.4% of the +40,070 input delta hit prompt cache). Background processes and aborted sessions remained the real boundary—which is where a Layer 2 system tool like Cublet takes over.
1. Copy the Rule into Your Global AGENTS.md or CLAUDE.md
You do not need Cublet—or even a Mac—to get most of the benefit. Paste these four sentences into your global agent instructions (~/.codex/AGENTS.md, ~/.claude/CLAUDE.md, Cursor user rules, or OpenBot global rules) so every coding task treats cleanup as part of delivery rather than an afterthought.
Treat cleanup as the final step of development delivery. Before committing, remove temporary code, debug entrypoints, and generated files created for this task that are no longer needed. After verification and reading back the target remote ref, keep the required acceptance evidence, stop any processes started for this task that are no longer in use, and remove rebuildable artifacts produced by this task. After confirming a temporary worktree or workspace has no unique changes, local data, or runtime dependencies, remove it. Preserve the main workspace, shared Git storage, and resources still in use.
Original Chinese rule (tested verbatim in the 8-run ZH arm)
把清理作为开发交付的最后一步。提交前删掉本任务产生且已无用途的临时代码、调试入口和生成文件。完成验收并读回目标远程引用后,保留需要的验收证据,停止本任务启动且已不用的进程,清除本任务的可重建产物。确认临时 worktree 或工作空间没有独有改动、本地数据或运行依赖后,将其移除。保留主工作区、共享 Git 存储和仍在用的资源。
Recent studies on agent context files have pointed out that bloated, generic instruction files burn extra tokens without helping. This rule stays effective because it is short (~90 words) and encodes four operational boundaries a model cannot reliably guess on its own:
- Pre-commit hygiene — Delete throwaway scripts, debug entrypoints, and generated files before
git commitso junk never lands in history. - Ordered post-verification teardown — Clean up only after tests pass and the remote ref is read back, while explicitly preserving required acceptance evidence.
- Three-part worktree safety check — Require checking for unique edits, local data (including
.gitignored files), and runtime dependencies before removing any temporary worktree. - Explicit preservation floor — Name what must survive: the main workspace, shared Git storage, and active resources still in use.
2. 32-Run Paired A/B Evaluation Results
To test whether the rule actually changes agent behavior—and whether it triggers over-aggressive deletion—we ran 32 isolated Codex trials (16 counterbalanced pairs) on macOS APFS (Apple Silicon) using gpt-6.2-sol with medium reasoning: 24 English trials (3 seeds × 4 scenarios) plus 8 Chinese trials (1 seed × 4 scenarios using the original Chinese rule verbatim).
Each pair shared the same fixture seed and task prompt, with A/B execution order counterbalanced. Every single run got a freshly created temporary directory, an isolated CODEX_HOME, zero ancestor AGENTS.md files, and a fresh bare Git remote. None of the task prompts hinted at cleanup.
| Metric (16 pairs / 32 runs) | Control (no rule) | Treatment (+ rule) | Delta |
|---|---|---|---|
| Functional pass (fresh-clone oracle) | 100% (16/16) | 100% (16/16) | 0.0 pp |
Remote delivery verified (origin/main) | 100% (16/16) | 100% (16/16)* | 0.0 pp |
| Protected assets intact (zero mis-deletes) | 100% (16/16) | 100% (16/16) | 0.0 pp |
| Acceptance evidence preserved | 100% (16/16) | 100% (16/16) | 0.0 pp |
| Strict clean delivery (all 16 pairs) | 50.0% (8/16) | 87.5% (14/16) | +37.5 pp |
| Strict clean delivery — Worktree + build (8 pairs) | 12.5% (1/8) | 100% (8/8) | +87.5 pp |
| Leftover temporary worktrees | 7 / 8 runs | 0 / 8 runs | −100% |
| Leftover build artifacts (logical / physical) | 150.6 / 125.7 MiB | 0 B / 0 B | −100% |
| Leaked task HTTP server + temp log | 1 / 4 runs | 1 / 4 runs (+1 timeout*) | See §3 |
Both language arms moved in the same direction: English strict hygiene rose from 58.3% (7/12) to 83.3% (10/12), and Chinese strict hygiene rose from 25.0% (1/4) to 100% (4/4). *One English live-server-debug treatment run hit the 240-second turn timeout after pushing and stopping its server; it is scored honestly as incomplete / non-clean in strict hygiene.
3. What Happened in Each of the 4 Scenarios
Aggregate numbers hide the mechanism. Splitting the 16 pairs across the four tasks shows exactly where the rule is decisive—and where prompt instructions still hit a ceiling.
| Scenario (4 pairs each) | Control Clean | Rule Clean | Leftover Build (Ctrl → Rule) | Guardrails Safe |
|---|---|---|---|---|
worktree-rust-feature | 0 / 4 (4 worktrees left) | 4 / 4 | 85.8 MiB (66.6 phy) → 0 B | 4 / 4 (100%) |
heavy-dual-build-export | 1 / 4 (3 worktrees left) | 4 / 4 | 64.8 MiB (59.1 phy) → 0 B | 4 / 4 (100%) |
safety-guardrail-boundary | 4 / 4 | 4 / 4 | 0 B → 0 B | 4 / 4 (100%) |
live-server-debug | 3 / 4 (1 server leaked) | 2 / 4 (1 leaked, 1 timeout*) | 0 B → 0 B | 4 / 4 (100%) |
worktree-rust-feature(0/4 → 4/4 clean): The agent built a Rust CLI subcommand inside../worktrees/feat-summary, rancargo testandcargo build, saved acceptance evidence, merged intomain, and pushed. Without the rule, every single control run walked away leaving the worktree and its 14.3–28.6 MiBtarget/folder behind (85.8 MiB logical / 66.6 MiB physical across 4 tiny zero-dependency workspaces). With the rule, all 4 removedtarget/and the worktree cleanly while leaving the dirty sibling worktreewip-billing(uncommitted code +local-cache.sqlite) untouched.heavy-dual-build-export(1/4 → 4/4 clean): Even when the task prompt explicitly called../worktrees/feat-csva temporary worktree, 3 of 4 control runs still abandoned it along with debug + release Cargo outputs anddist/previews (64.8 MiB logical / 59.1 MiB physical). In real multi-crate Rust or Electron repos, each forgotten worktree easily grows to 2–10+ GiB. With the rule, 4 of 4 ended at 0 B while keepingmain-repo/data/customer-exports/2026-11.csvintact.safety-guardrail-boundary(4/4 safe, 0 mis-deletes): This was an adversarial stress test designed to catch over-cleaning. Alongside the task worktree, the repo held a dirty sibling worktree (wip-uncommitted), a git-clean sibling worktree containing a.gitignored SQLite database (wip-local-db/local-data/session.sqlite), a main-repo SQLite file, and a live background service. Both arms preserved 100% of protected assets—and treatment actually finished faster (73.7 s vs. 93.3 s median).live-server-debug(the honest edge case): The agent patched a Python HTTP API, launchedserver.pyin the background to capture live JSON evidence, and pushed tomainalongside a preexisting protected service. Across 4 pairs, the preexisting service stayed alive 8/8 times. However, 1 control run (ZH) and 1 treatment run (EN seed 1) still leaked their ownserver.pyprocess and temp log, and 1 treatment run (EN seed 3) hit the 240-second turn timeout right after pushing and stopping its server (leaving Codex’s internalcodex-code-mode-hosthelper alive at teardown). Prompt rules are probabilistic—and they cannot execute if a turn times out.
4. Overhead, Token Economics, and Methodology Caveats
A fair criticism of long AGENTS.md files is that extra instructions inflate every turn’s context and latency. Here is the exact paired cost across the 15 pairs that reached a clean turn boundary in both arms:
| Cost Metric (15 complete pairs) | Control Median | Rule Median | Paired Median Delta |
|---|---|---|---|
| Shell commands executed | 11.0 | 13.0 | +2 commands |
| Turn wall-clock duration | 113.0 s | 111.5 s | +4.1 s (+3.6%) |
| Total input tokens | 212,399 | 237,964 | +40,070 |
| Prompt-cached input tokens | 195,456 | 221,440 | +36,224 (90.4% cached) |
| Net new uncached input tokens | 14,010 | 16,524 | +3,846 |
| Output tokens | 2,811 | 3,067 | +135 |
Every row above is computed on the exact same 15 complete pairs (excluding the single timed-out live-server pair; including that pair shifts the paired command delta from +2 to +2.5). Percentage overhead (+3.6%) divides the paired median delta (+4.1 s) by the complete-pair control median (113.0 s). Because cleanup runs in 2–3 short commands right at the end of a session, 90.4% of the extra input tokens hit the provider’s prompt cache. In wall-clock terms, you trade roughly 4 seconds and 135 output tokens to stop gigabytes of stale build directories from silently accumulating across worktrees.
Scope & caveats: These 32 runs evaluated one model family (gpt-6.2-sol at medium reasoning) on synthetic single-repo fixtures on macOS APFS (Darwin 25.6.0 arm64) with a 240-second per-trial cap. Real-world disk savings are typically much larger than 15–29 MiB per worktree (because real Cargo/Node/Xcode dependency trees run into gigabytes), while absolute compliance rates will vary by model, client sandbox policy, and prompt complexity.
5. Where a Prompt Rule Stops: The Two-Layer Disk Hygiene Model
Our own dataset shows why an AGENTS.md rule is necessary—and why it is only Layer 1. The moment an agent session hits a timeout, gets Ctrl-C’d mid-debug, runs out of context, or leaves a detached process behind, the final cleanup step never executes. And even when every single session ends cleanly, no single-task agent can see cross-repo caches piling up over weeks or macOS APFS snapshots holding deleted blocks.
| Layer | Tool | What it prevents or recovers | Structural blind spot |
|---|---|---|---|
| Layer 1: Delivery prevention | Free AGENTS.md / CLAUDE.md rule (any OS) | Normal task completions: deletes temp scripts before commit, clears task target/ & dist/, removes verified empty temporary worktrees while guarding local SQLite & dirty branches. | Cannot run after crashes, timeouts, or user interrupts; no cross-repo memory over time; cannot inspect APFS snapshots or purgeable space. |
| Layer 2: System safety net | Cublet (macOS, MIT: Growth diff + local stdio MCP) | Growth scan diff (75 ms SQLite restore on 52,009 folders vs. 1,128 ms cold scan) spots orphaned directories & weekly cache drift; Cublet Cleaner MCP recovers Rust target/ & Go caches inside authorized scope while checking active builds (~73% less recovery time & 58–66% fewer tokens vs. shell loops on controlled APFS fixtures). | macOS only; MCP recovery currently focuses on rebuildable Rust and Go build caches. |
Put simply: the AGENTS.md rule keeps each finished task from leaving a mess on the workbench; Cublet catches aborted runs, shows what actually grew across projects this week, and gives your agent a safe, bounded local MCP cleaner when your Mac SSD runs low.
Frequently Asked Questions
Will this rule accidentally delete uncommitted changes, gitignored SQLite databases, or running services?
Across all 32 isolated trials—including an adversarial guardrail scenario containing an uncommitted worktree, a git-clean sibling worktree holding a gitignored SQLite database, a main-repo local SQLite file, and a preexisting background service—protected assets stayed 100% (16/16) intact and acceptance evidence stayed 100% (16/16) preserved. The rule works because it explicitly checks for unique edits, local data, and runtime dependencies before removing any temporary worktree.
Does adding a cleanup instruction to AGENTS.md or CLAUDE.md slow down runs or inflate token costs?
Not meaningfully. Across the 15 complete counterbalanced pairs, paired median overhead was +4.1 seconds (+3.6% of the 113.0 s control median) and +2 shell commands. Total input tokens rose by +40,070 (paired median), but 90.4% (+36,224) hit prompt cache; net new uncached input rose by +3,846 tokens and output rose by +135 tokens.
Which coding agents support this rule, and should it live globally or per repository?
It works in any instruction-driven coding agent: ~/.codex/AGENTS.md (Codex), ~/.claude/CLAUDE.md (Claude Code), Cursor user rules, or OpenBot global AGENTS.md. Put this 4-sentence baseline in your global file so every session inherits delivery hygiene, and add repo-specific artifact paths (such as custom Docker volumes or Xcode DerivedData) only in project-level files.
Why is checking git status alone unsafe before removing a temporary worktree?
Because git status ignores .gitignore entries. A temporary worktree can report a completely clean Git working tree while still holding a local SQLite database, .env credentials, or an open file handle from a running process. That is why the rule requires confirming no unique changes, local data, or runtime dependencies before removal.
If a 4-sentence AGENTS.md rule works this well, when do you still need Cublet?
A prompt rule only executes when a session reaches the final step cleanly. In our own evaluation, 1 of 4 live-server runs timed out at 240 seconds and 1 still leaked a detached server process. You pair the rule with Cublet on macOS for aborted/crashed runs, multi-week cache drift across repositories (Growth scan diff), APFS snapshot/clone space illusions, and scoped local MCP cache recovery when disk space gets tight.
Pair the rule with a Layer 2 safety net on macOS
Keep the rule free in your global AGENTS.md on every machine. If you build on macOS and want scan-diff Growth attribution plus scoped MCP build-cache recovery, install Cublet (MIT open source):