The Runaway Agent Problem: When Claude Code Goes Too Far
A developer starts a Claude Code session to fix a small layout bug in a React component. Three hours later, they realize the tool has modified eight separate files, introduced compiler errors in the router, and spent $15 in API tokens. The session context has become so bloated that Claude has lost track of the original task entirely and is now trying to fix compilation bugs it created itself. The developer ends up running `git reset --hard` and starting over from scratch.
This is the runaway agent problem. Claude Code is a command-line interface that runs locally in your repository and has permission to read files, run terminal commands, and modify code. Because it is agentic, it attempts to solve problems by chaining actions. However, every file Claude reads, every command output it parses, and every chat turn you take is appended to its context window.
When this context window exceeds 30,000 tokens, the model's performance begins to degrade. It forgets instructions, gets confused by old code states, and starts generating code that does not match your project rules. If you do not manage your context, you will spend more time reverting changes and paying for API tokens than writing code. This playbook details how to establish boundaries for Claude Code, keeping sessions fast, accurate, and cheap.
Why Context Gets Bloated in Agentic Coding
To control context, you must understand what goes into it. Every time you run Claude Code in a terminal, a new chat session begins. Claude gathers basic metadata about your repository, including your git status, files in the root directory, and the contents of a specialized configuration file called `CLAUDE.md` if it exists.
As you ask Claude to write code, the following items are added to the session history:
First, the contents of every file Claude reads. If Claude uses its search tool to look for a utility function and opens five different files, the entire text of those five files is added to the active context.
Second, the output of every build or test command you run inside the session. If you tell Claude to run `npm test` and it outputs 400 lines of test results, those 400 lines are pushed into the context.
Third, the history of prior edits. If Claude edits a file, then edits it again to fix a typo, and edits it a third time to change a variable name, all three versions of that code block remain in the active chat log.
When input tokens grow, your costs increase. OpenAI and Anthropic charge for input tokens at a rate that is cheaper than output tokens, but because the input is sent with every single turn, a long chat session with 50,000 context tokens can cost $0.15 to $0.30 per turn. If you make 30 chat turns, you have spent $9.00 on a single small fix.
1. Establish Rules with a CLAUDE.md File
The most effective way to prevent Claude from going off-course is to create a `CLAUDE.md` file in the root of your repository. This file acts as a permanent system prompt that Claude reads at the start of every session. It tells Claude exactly how to build, test, and write code in your specific project.
By providing these instructions, you prevent Claude from guessing or running unnecessary search commands. A standard `CLAUDE.md` must contain:
Build and test commands: Tell Claude exactly how to compile the project (e.g., `npm run build`) and how to run tests (e.g., `npm run test` or `npx jest --findRelatedTests <file>`). This stops Claude from trying random commands that fail and bloat the command history.
Code style guidelines: Specify your formatting rules (e.g., "Use TypeScript, strict type checking, and functional components. Avoid default exports; use named exports only.").
State rules: Explicitly restrict Claude from modifying files outside the requested scope. For example: "Do not touch routing or database configuration unless explicitly asked. If you need to make changes to shared files, stop and ask for permission first."
2. Compress Session Memory with /compact
When your chat history gets long and you notice Claude is responding slowly, it is time to compress the conversation. Claude Code provides a built-in command for this: `/compact`.
When you type `/compact` in the Claude terminal, the tool summarizes the changes made so far, records the current task status, and wipes the detailed history of previous turns. It removes the old code diffs and long command outputs while retaining the current file states.
Use `/compact` after you have successfully completed a subtask. For example, if you spend 15 turns getting a database migration to run and finally succeed, run `/compact` immediately. This clears the 20,000 tokens of failed migrations and command errors, dropping your active context back down to a few thousand tokens. Your next turn will cost less and run faster.
3. Start Fresh with /clear
Sometimes, summarizing the history is not enough. If you have spent an hour trying to implement a complex feature and realize you need to take a completely different technical approach, do not continue the chat. Continuing will only confuse the model as it tries to reconcile its new instructions with the failed attempts in its memory.
Instead, run `/clear`. This command completely resets the conversation. It deletes the entire chat history and starts a brand-new session. The files you modified on disk remain modified; only the chat memory is cleared.
Think of `/clear` as a clean slate. Before running it, make sure you write down what you want to do next. Run `/clear`, state your new plan, and let Claude read the current, modified files without the historical baggage of the failed attempts.
4. Write a Plan Before Allowing Edits
Do not let Claude start editing files immediately. If you ask: "Add user profile editing to the settings page," Claude will guess which files to modify and start writing code. It will often miss edge cases, create type errors, and edit files it should have left alone.
Instead, use planning mode. Ask Claude to write a plan first: "I need to add user profile editing. List the files you need to change and explain your proposed approach. Do not modify any files yet."
Review the plan Claude returns. If it suggestions changing a file that you know is unrelated, correct it: "Do not touch the auth middleware; user details are already present in the request context. Only update the profile form component." Once you agree on the files and the logic, tell Claude to proceed. This planning step prevents hours of cleanup and token waste.
5. Protect Your Main Branch with Git
Never run Claude Code on your main or production git branch. Claude is an agent, and agents can make destructive mistakes if a prompt is misunderstood or a command behaves unexpectedly.
Before starting a session with Claude Code, follow this git discipline:
First, create a new branch for the specific task: `git checkout -b feature/user-profile`.
Second, commit any outstanding manual changes before launching Claude. Your working directory should be completely clean. This allows you to run `git diff` at any moment to see exactly what files Claude has touched.
Third, commit in small blocks. Once Claude successfully implements one subtask and you verify it builds, run `git commit -am "implement profile form validation"` inside your terminal. If the next step fails and Claude ruins the layout, you do not lose your previous progress; you can simply run `git checkout .` to revert to your last clean commit.
6. Run Independent Code Reviews
Do not trust Claude's attestation that "all changes are tested and working." Always verify the changes yourself. Before committing, run `/diff` inside the Claude Code interface, or open a separate terminal window and run `git diff`.
Look at every line of code Claude has added or deleted. Check for:
Unnecessary file modifications: Did Claude add a blank line or import statement to a file it did not need to edit?
Deleted comments or documentation: AI models frequently delete comments or docstrings to make code shorter. Ensure your project documentation is preserved.
Hardcoded values: Check if Claude inserted a temporary email or API token for testing. Ensure these are replaced with environment variables.
Once you are satisfied, run your local test suite (e.g. `npm run test`) outside of Claude Code to double-check that no regressions were introduced.
The Safe Developer Workflow: A Repeatable Process
Here is how to combine these steps into a daily, repeatable workflow that keeps your repository clean and your token usage low:
1. Check out a clean branch from main: `git checkout -b task/fix-search-filter`.
2. Verify `CLAUDE.md` exists and contains correct build/test commands.
3. Launch Claude Code: `claude`.
4. Ask Claude to plan: "Explain how you will fix the search filter in search-island.tsx. Write a plan first."
5. Once approved, tell Claude: "Execute the plan. Run tests after editing."
6. Run `git diff` in a separate terminal to review changes.
7. If changes are correct, run `/compact` to clear session tokens, and run `git commit -am "fix: search filter logic"`.
8. Proceed to the next subtask, repeating the cycle. Clear the session with `/clear` if you pivot to a new problem.
Frequently Asked Questions
Final Takeaway: You Are the Pilot, Claude is the Copilot
Agentic coding tools are powerful, but they require active management. If you treat Claude Code like a human developer who understands your intentions, you will end up with bloated context, broken code, and high API bills. Treat the tool like a fast, tireless copilot that follows explicit rules. Set clear boundaries in CLAUDE.md, commit your changes frequently, plan your work before writing code, and compress memory regularly. By staying in control of the session context, you make AI coding faster, more reliable, and commercial.
Need Help Setting Up an Efficient AI Developer Workflow?
JTech helps software teams and founders design safe, productive AI development environments. Ask us for a project audit to optimize your setup, establish guardrails, and accelerate your build times.
