Skip to content
ISSUE #15 Sep 5, 2025 11 MIN READ

How a Read-Only Sub-Agent Saved My Context Window (And Fixed My WordPress Theme)

I was staring at my WordPress theme’s newsletter page, confused.

The “Recent Issues” section was supposed to show my latest newsletter posts. Instead, it was completely wrong.

The typical approach would be to let Claude Code dive into the codebase, reading file after file, searching for the problem.

But there’s a catch – each file Claude reads consumes precious context tokens.

By the time it finds the issue, it might have used 80% of its context window, leaving little room for actually fixing the problem.

That’s when I discovered a game-changing approach: the read-only sub-agent pattern.

.

.

.

The Context Window Problem Nobody Talks About

When Claude Code explores a codebase, it’s like a detective gathering evidence.

Each file it reads, each search it performs, adds to its memory.

But unlike a human detective who can forget irrelevant details, Claude keeps everything in its context window.

Here’s what typically happens:

  1. You ask Claude to fix a bug
  2. Claude reads 10-20 files looking for the issue
  3. Each file might be hundreds of lines
  4. Suddenly, 80% of the context is consumed
  5. Claude struggles to maintain focus on the actual fix

It’s like trying to solve a puzzle while carrying every piece you’ve ever looked at. Eventually, you run out of hands.

.

.

.

Enter the Codebase Explorer Sub-Agent

The solution?

Delegate the investigation to a specialized sub-agent that only reads and reports back.

Think of it as hiring a research assistant.

The assistant does all the reading, takes notes, and gives you a concise report.

You then use that report to make decisions without having to read everything yourself.

Here’s the actual sub-agent configuration I use:

The key insight: This sub-agent can ONLY read files, not modify them.

It explores, analyzes, and documents its findings in a markdown report.

.

.

.

Real-World Example: Fixing My Newsletter Display

Let me show you exactly how this worked when fixing my WordPress theme.

Step 1: Launching the Investigation

Instead of diving straight into the code, I asked Claude to use the codebase-explorer agent to investigate why newsletter issues weren’t displaying:

Step 2: The Sub-Agent Takes Over

The codebase-explorer agent immediately went to work:

Notice how it’s thinking through the problem systematically. It’s not just randomly reading files – it’s forming a strategy.

Step 3: Sub-Agent Investigation & Documentation

The sub-agent went deep into the codebase, systematically exploring files and tracing the newsletter implementation:

After thorough investigation, it documented everything in a comprehensive markdown report:

  • Summary of the issue: Newsletter posts stored as regular WordPress posts with a specific category
  • Key files involved: page-newsletter.php, functions.php, theme options
  • The specific bug: Incorrect variable usage with setup_postdata()
  • Recommended fix: Change loop variable from $issue to $post

Critical detail: The sub-agent consumed 51,000 tokens during its investigation.

Without the sub-agent pattern, those 51k tokens would have been loaded directly into the main agent’s context window!

Step 4: Main Agent Takes Over With Clean Context

With the sub-agent’s analysis complete, the main agent took over with a nearly empty context window:

Notice how the main agent can now work with surgical precision. It reads the specific file mentioned in the analysis:

The main agent confirms the issue: The code was using $issue as the loop variable but WordPress’s setup_postdata() function expects the global $post variable to work correctly.

Want techniques like these weekly?

Join The Art of Vibe Coding—short, practical emails on shipping with AI (without the chaos).

No spam. Unsubscribe anytime.

Step 5: The Main Agent’s Surgical Fix

Armed with the sub-agent’s report and with 90% of its context still available, the main agent presented a precise fix:

The fix was surgical and precise:

Step 6: Success!

The newsletter issues now display perfectly!

.

.

.

Why the Sub-Agent Must Be Read-Only

You might wonder: “Why not let the sub-agent fix the problem directly?”

Here’s why the read-only constraint is crucial:

  1. Context Preservation: The main reason – saving those 51,000 tokens for the main agent’s context
  2. Avoiding Code Duplication: If the sub-agent makes changes and passes control back, the main agent might not be aware of what was modified. This often leads to:
    • Duplicate implementations of the same fix
    • Violating the DRY (Don’t Repeat Yourself) principle
    • Conflicting code changes
    • Confusion about the current state of files
  3. Maintaining Control: The main agent maintains a coherent understanding of all changes made to the codebase

The read-only pattern ensures clean handoffs: The sub-agent investigates and reports, the main agent decides and implements.

No confusion, no duplication, no wasted context.

.

.

.

The Context Window Visualization

Let me show you exactly how context consumption differs between the two approaches:

Without Sub-Agent: Direct Investigation

Result: High risk of context overflow, limited ability to handle complex fixes

With Sub-Agent: Delegated Investigation

Result: Minimal context usage, full capacity for implementation

The Compound Effect Over Multiple Tasks

.

.

.

The Numbers That Matter

Without the sub-agent pattern:

  • Files read directly: 15-20
  • Context consumed: ~80%
  • Investigation time: 20+ minutes
  • Risk of context overflow: High
  • Ability to handle complex fixes after investigation: Limited

With the sub-agent pattern:

  • Files read by main agent: 1 (the analysis report)
  • Context consumed: <10%
  • Investigation time: Same, but parallelized
  • Risk of context overflow: Minimal
  • Ability to handle complex fixes: Excellent

.

.

.

Setting Up Your Own Codebase Explorer

Here’s the complete sub-agent configuration you can use:

---
name: codebase-explorer
description: Use this agent when you need to investigate, search, or analyze the codebase without making any modifications. This agent specializes in read-only operations to understand code structure, find relevant files, trace dependencies, and document findings. Perfect for preliminary investigation before code changes, understanding feature implementations, or analyzing issues.\n\nExamples:\n- <example>\n  Context: The user wants to understand how authentication is implemented before making changes.\n  user: "I need to add a new authentication method. Can you first investigate how the current auth system works?"\n  assistant: "I'll use the codebase-explorer agent to investigate the authentication implementation and document the findings."\n  <commentary>\n  Since this requires read-only investigation of the codebase before making changes, use the codebase-explorer agent to analyze and document the current implementation.\n  </commentary>\n</example>\n- <example>\n  Context: The user is debugging an issue and needs to understand the code flow.\n  user: "There's a bug in the payment processing. I need to understand all the files involved in the payment flow."\n  assistant: "Let me launch the codebase-explorer agent to trace through the payment processing flow and identify all related files."\n  <commentary>\n  The user needs read-only investigation to understand the codebase structure, perfect for the codebase-explorer agent.\n  </commentary>\n</example>\n- <example>\n  Context: Before implementing a new feature, understanding existing patterns is needed.\n  user: "We need to add a new API endpoint. First, let's see how the existing endpoints are structured."\n  assistant: "I'll use the codebase-explorer agent to analyze the existing API endpoint patterns and document them."\n  <commentary>\n  This requires read-only analysis of existing code patterns, ideal for the codebase-explorer agent.\n  </commentary>\n</example>
tools: mcp__ide__getDiagnostics, mcp__ide__executeCode, Glob, Grep, Read, WebFetch, TodoWrite, WebSearch, BashOutput, KillBash, Write
model: sonnet
color: cyan
---

You are a specialized codebase exploration and analysis agent. Your sole purpose is to perform read-only operations to investigate, search, and understand codebases, then document your findings comprehensively.

**Core Responsibilities:**

1. Search and locate files relevant to specific features, issues, or components
2. Analyze code structure, dependencies, and relationships between files
3. Trace execution flows and identify all components involved in specific functionality
4. Document findings in a clear, structured markdown file

**Operational Constraints:**

-   You must NEVER modify, edit, or create any code files
-   You must NEVER make changes to existing functionality
-   You are strictly limited to read-only operations: viewing, searching, and analyzing
-   Your only write operation is creating/updating your findings document in the notes folder

**Workflow Process:**

1. **Initial Assessment**: Understand the specific issue/feature to investigate
2. **Strategic Search**: Use targeted searches to locate relevant files:
    - Search for keywords, function names, class names related to the topic
    - Look for imports and dependencies
    - Check configuration files and entry points
3. **Deep Analysis**: For each relevant file found:
    - Document its purpose and role
    - Note key functions/classes it contains
    - Identify its dependencies and what depends on it
    - Record important implementation details
4. **Relationship Mapping**: Trace how files connect and interact
5. **Documentation**: Create a comprehensive markdown report

**Documentation Format:**
Your findings must be written to a markdown file in the `notes/` folder with a descriptive name like `notes/[timestamp]_analysis_[issue/feature/component/etc].md`. Structure your report as:

```markdown
# Codebase Analysis: [Topic/Feature/Issue]

## Summary

[Brief overview of what was investigated and key findings]

## Relevant Files Identified

### Core Files

-   `path/to/file1.ext`: [Purpose and key responsibilities]
-   `path/to/file2.ext`: [Purpose and key responsibilities]

### Supporting Files

-   `path/to/support1.ext`: [Role in the system]
-   `path/to/support2.ext`: [Role in the system]

## Implementation Details

### [Component/Feature Name]

-   Location: `path/to/implementation`
-   Key Functions/Classes:
    -   `functionName()`: [What it does]
    -   `ClassName`: [Its responsibility]
-   Dependencies: [List of imports and external dependencies]
-   Used By: [What other parts of the code use this]

## Code Flow Analysis

1. Entry point: `file.ext:functionName()`
2. Calls: `another.ext:processFunction()`
3. [Continue tracing the execution flow]

## Key Observations

-   [Important patterns noticed]
-   [Potential areas of interest]
-   [Configuration or environment dependencies]

## File Relationships Map
```

[ASCII or text-based diagram showing file relationships]

```

## Additional Notes
[Any other relevant information for the main agent]
```

**Search Strategies:**

-   Use grep/ripgrep for pattern matching across the codebase
-   Search for class/function definitions and their usages
-   Look for import statements to understand dependencies
-   Check test files to understand expected behavior
-   Review configuration files for feature flags or settings

**Quality Checks:**

-   Ensure all mentioned files actually exist and paths are correct
-   Verify that your analysis covers the complete scope requested
-   Double-check that no modifications were made to any files
-   Confirm your findings document is saved in the notes folder

**Communication Protocol:**
When you complete your analysis:

1. Save your findings to the notes folder
2. Provide the exact path to your findings file
3. Give a brief summary of what was discovered
4. Explicitly state: "Analysis complete. Findings documented in [path/to/notes/file.md] for main agent review."

Remember: You are a read-only investigator. Your value lies in thorough exploration and clear documentation, enabling the main agent to make informed decisions without consuming excessive context through tool calls.

.

.

.

Pro Tips for Maximum Effectiveness

1. Be Specific with Investigation Goals

Don’t just say “investigate the auth system.”

Say “find all files involved in user login, session management, and authentication middleware.”

2. Use the Analysis Document

The sub-agent’s markdown report becomes your reference.

Keep it open while the main agent works.

3. Chain Multiple Investigations

Need to understand both authentication AND payment processing? Run two separate investigations, get two reports.

4. Preserve Context for Complex Fixes

By keeping the main agent’s context clean, you can tackle complex refactoring that would otherwise hit limits.

.

.

.

The WordPress Gotcha That Almost Got Me

This pattern revealed something interesting about WordPress development.

The setup_postdata() function is notoriously finicky about variable names. It specifically requires the global $post variable to be set.

This is the kind of subtle bug that could consume hours of debugging.

With the sub-agent pattern, we found it in minutes without polluting the main context.

.

.

.

Beyond WordPress: Universal Application

While my example uses WordPress, this pattern works for any codebase:

  • React applications: Trace component hierarchies and prop flows
  • Node.js APIs: Map endpoint relationships and middleware chains
  • Python projects: Understand module dependencies and import structures
  • Ruby on Rails: Explore MVC relationships and gem integrations

The principle remains the same: Delegate investigation to preserve implementation context.

.

.

.

Your Next Steps

  1. Copy the sub-agent configuration from this post
  2. Add it to your Claude Code project
  3. Next time you need to investigate, use the magic words: “Use the codebase-explorer agent to investigate…”
  4. Watch your context efficiency soar

.

.

.

The Bottom Line

Context window management isn’t just about efficiency – it’s about capability.

By using a read-only sub-agent for investigation, you’re not just saving tokens. You’re ensuring Claude Code maintains the focus and context needed to implement complex solutions.

My newsletter display bug?

Fixed in minutes with a two-line change. But more importantly, I had 90% of my context window still available for additional improvements.

Stop letting investigation consume your implementation capacity.

Start using the codebase-explorer pattern.

Your future self – knee-deep in a complex refactoring with plenty of context to spare – will thank you.


P.S. – This pattern has fundamentally changed how I work with Claude Code. I now investigate first, implement second, and never worry about context overflow. Try it on your next debugging session and see the difference.

Nathan Onn

Freelance web developer. Since 2012 he’s built WordPress plugins, internal tools, and AI-powered apps. He writes The Art of Vibe Coding, a practical newsletter that helps indie builders ship faster with AI—calmly.

Join the Conversation

Leave a Comment

Your email address will not be published. Required fields are marked with an asterisk (*).

Enjoyed this post? Get similar insights weekly.