I once used Claude Code to batch-rewrite 20 docs sequentially. By the fifth file, it started writing file A’s edits into file B and casually carrying out operations I had explicitly forbidden in CLAUDE.md. Claude hadn’t suddenly gotten worse—its context window had filled up, pushing earlier instructions and conventions out of view.

A context window works like a fixed-size desk: every message and every file read takes up space. The more you pile onto it, the faster older items get shoved off the edge. Once Claude loses sight of your project conventions, output quality falls off a cliff.

This post tackles one problem: how to keep Claude Code’s output quality steady across long tasks. We will walk through spotting overflow early, a three-tier recovery playbook, preventive design, and a real-world postmortem.


Three Early Warning Signs & How to Diagnose Them

Context overflow doesn’t hit without warning—it gives three clear signals first. The earlier you catch them, the cheaper recovery is.

Signal 1: Claude Starts Repeating Itself

It searches a file it just searched, or fixes a bug it just fixed. That means its memory of recent steps has gone fuzzy, so it falls back on re-reading to reconstruct state.

Signal 2: Ignoring CLAUDE.md Rules

Your CLAUDE.md specifies a unified error-response format, yet Claude suddenly switches to a different one. It isn’t being defiant—CLAUDE.md has been pushed to the edges of the context window and lost weight.

Signal 3: Mixing Up Files

Changes meant for file A land in file B. This is the classic symptom of context saturation: Claude can no longer reliably separate the context of different files.

How to check context usage: Run /context inside Claude Code to see the current utilization percentage. Treat anything above 70% as a warning threshold.

Signal Symptom Severity Recommended Action
Repeated actions Running the same search or edit twice Medium /clear + brief handoff summary
Ignored rules Violating explicit CLAUDE.md conventions High Restart session; restate key rules in the prompt
File mix-ups Writing file A’s edits into file B Critical Stop immediately; restart from a progress file

Recovery Strategies: Three Tiers from Light to Heavy

Tier 1: Lightweight Restart—/clear + Concise Handoff

Best for straightforward context overflow on tasks with only a few steps.

1
2
3
4
5
# Step 1: Clear the context
/clear

# Step 2: Summarize the current state and next goal in 1-2 sentences
# Skip the prior conversation—just state where things stand and what comes next

Handoff prompt template:

1
2
3
Current state: Device CRUD API is complete, all tests pass.
Project conventions: Follow CLAUDE.md.
Next step: Implement similar CRUD for the SensorData model, following Device's code structure.

Key takeaway: Claude will read whatever implementation details it needs directly from the codebase. You only need to give it the starting point and direction.

Tier 2: Progress-File Restart

Best for multi-step tasks with dependencies between steps.

Start by defining a JSON progress file:

1
2
3
4
5
6
7
8
9
{
"task": "Rewrite official docs series",
"total": 20,
"completed": ["overview.md", "quickstart.md", "setup.md"],
"in_progress": "best-practices.md",
"failed": {
"hooks.md": "File truncated; needs reprocessing"
}
}

After each /clear, have Claude resume from the exact checkpoint in a fresh session:

1
2
Read .claude/scoring/progress/official-doc.json and continue with the next unfinished file.
Update the progress file after completing each file.

Key takeaway: Because the progress file is machine-readable, Claude resumes cleanly from the checkpoint with zero skipped or duplicated work.

Tier 3: Full Split-Session Restart

Best for complex tasks that will never fit into a single session.

Split the work by architectural layer, giving each layer its own session:

1
2
3
4
Session 1: Analyze module structure and write the refactoring plan to REFACTOR-PLAN.md
Session 2: Read REFACTOR-PLAN.md and refactor the data layer
Session 3: Read REFACTOR-PLAN.md and refactor the business logic layer
Session 4: Read REFACTOR-PLAN.md and update tests

Prompt template for each sub-session:

1
2
3
4
5
This is step {N}/{Total} of the {Project Name} refactoring task.
Plan file: {PLAN_FILE}
Previous step status: {Brief summary}
Current step goal: {Specific goal}
Update the corresponding step status in the plan file once finished.

Preventive Design: Stop Overflow Before It Happens

Recovery strategies put out fires; preventive design stops them from starting.

Practical Ways to Split Tasks

Pick a granularity that matches the work:

  • By layer: Data layer → business logic layer → API layer → tests. Ideal for module refactoring.
  • By file: Touch only 2–3 files per session. Ideal for wide formatting or mechanical cleanups.
  • By feature: Implement one feature per session. Ideal for feature development.

Mastering the max-turns Flag

Cap turn count at launch to put a hard ceiling on context consumption:

1
2
3
4
5
6
7
8
# Small single-file fix: 3-5 turns is enough (--max-turns requires -p non-interactive mode)
claude -p --max-turns 5 "Fix the null pointer exception in login.js"

# Medium task: 10 turns
claude -p --max-turns 10 "Add soft delete to the Device model"

# Complex task: 15 turns; needing more means the task should be split
claude -p --max-turns 15 "Refactor the data layer of the user module"

If a task cannot finish within its turn cap, the fix is to break down the task—not to raise the limit.

Isolating Batch Jobs with Subagents

Batch jobs (editing 20 files, sweeping 10 modules) are the fastest way to blow through a context window. Use Subagents to isolate every subtask in its own context window:

Use Subagents to fix formatting in parallel across every Markdown file under source/_posts/. Each Subagent should handle only one file.

Every Subagent gets a clean, independent context window with zero cross-talk.

Caveats:

  • Subagents cannot share state directly; coordinate them through files on disk.
  • Keep subtasks self-contained without tangled cross-file dependencies.
  • Works best for mechanical tasks like formatting fixes or bulk renames.
Preventive Technique Best For Core Setting / Method
Split by layer Module refactoring One layer per session, chained via a plan file
Split by file Formatting fixes, bulk replacements 2–3 files per session
Split by feature Feature development One feature per session
max-turns All medium-to-large tasks 5 / 10 / 15 based on complexity
Subagents Mechanical batch operations Isolated subtasks coordinated through files

Case Study: Batch-Rewriting 20 Docs

This comes from a real project: using Claude Code to batch-rewrite 20 translated official docs for this blog.

The Problem: Context Saturation by Doc #5

At first I processed them sequentially in a single session: read source → rewrite against a scoring rubric → self-check → move on. By the fifth doc, Claude started forgetting the rubric and ignoring formatting rules in CLAUDE.md, with context usage past 90%.

Three Iterations to a Reliable Setup

v1: Single Session + Manual Restarts

Run /clear after every 5 docs and manually tell Claude where to resume. The catch: re-explaining the scoring rubric after every reset was tedious and error-prone.

v2: Progress-File Checkpointing

Added a JSON progress file (the same schema shown in Tier 2) so each new session could pick up where the last one stopped. Much better—yet by around doc #15, handling 5 docs per session still pushed context to saturation.

v3: Orchestrator + Parallel Subagents (Final Architecture)

Here is the final setup:

1
2
3
4
5
6
7
# Orchestrator: the main session only schedules work and never edits articles
# Read progress file -> launch Subagent -> verify output -> update progress

# One isolated Subagent per article
claude -p --max-turns 20 "Rewrite source/_posts/ai-tools/official-docs/hooks.md
according to .claude/scoring/profiles/official-doc.yaml.
Update the status in .claude/scoring/progress/official-doc.json when done."

The core principle: the main session acts strictly as a scheduler and never loads article contents. Each Subagent processes a single doc inside a full, isolated context window. Processing all 20 docs in parallel this way lifted the single-run success rate from 60% to over 95%.


Summary & Context Management Cheat Sheet

Task Complexity Typical Scenario Recommended Strategy Key Action
Simple (1–3 turns) Single-file bug fix No special handling Run as normal
Medium (5–10 turns) Single feature, config change max-turns cap claude -p --max-turns 10
Complex (10–20 turns) Module refactor, multi-file edits Task splitting + progress file Split by layer/feature; chain with a progress file
Batch (20+ subtasks) Bulk rewrites, repo-wide sweeps Orchestrator + Subagents Dedicated context window per subtask

Keep three habits front of mind:

  1. Watch for early signals: Repeated actions, ignored rules, or file mix-ups—act as soon as any one appears.
  2. Restart proactively: Trigger /clear or a progress-file restart at 70% in /context; don’t wait until 90%.
  3. Design against overflow: Break large tasks into small sessions and offload batch work to Subagents from the start.

Series Navigation