Mastering Claude Code's Plan Mode β Plan First, Then Execute for More Controllable and Efficient AI Programming
Plan Mode In-Depth Guide¶
Have you ever had this experience: you asked Claude Code to help you modify code, and it went full throttle, changing a dozen files, only to find out it went off track? Or halfway through the modification, you realized you missed a dependency and had to undo everything?
Plan mode was created to solve these problems. It lets Claude first create a detailed execution plan, and only starts working after you review and approve itβturning "shooting an arrow and then drawing the target" into "planning thoroughly before acting."
What Is Plan Mode¶
Plan Mode vs Default Mode¶
In default mode, Claude Code thinks and executes simultaneously: analyzing code, editing files, running commandsβthese actions are interleaved. This is very efficient for simple tasks, but can lead to a "take one step at a time" approach for complex tasks.
Plan mode is completely different:
| Feature | Default Mode | Plan Mode |
|---|---|---|
| Execution | Think and execute simultaneously | Plan first, execute after approval |
| File operations | Immediately reads and writes files | Read-only, only analysis and search |
| Command execution | May run commands directly | Does not execute any modifying commands |
| Suitable for | Simple edits, quick fixes | Multi-file refactoring, complex feature development |
| Risk control | Relies on permission system | Zero risk during planning phase |
Simply put, Claude in Plan mode is like an architect with only a notebookβit will carefully survey the site (read code, search files), draw detailed construction blueprints (execution plan), but will never lay a single brick.
Why Plan Before Executing¶
The benefits of planning before executing go far beyond just "safety":
- Global perspective: Claude scans all relevant files first to build an overall understanding, rather than discovering omissions halfway through
- Reviewable plans: You can review the plan before execution, spot potential issues, and provide feedback
- Reduce rework: Dependency conflicts and interface inconsistencies can be discovered during the planning phase
- Knowledge alignment: By reading the plan, you can verify if Claude's understanding of the project is correct
- Reusable: Good plans can be saved as reference templates for similar tasks
When to Use Plan Mode¶
Strongly recommended for Plan mode:
- Modifications involving more than 5 files
- Modifying core modules or public interfaces
- Adding new features (especially involving databases, APIs, etc.)
- Refactoring existing code structure
- Fixing bugs with unknown causes (need to investigate first)
- You're not yet familiar with the project and need Claude to help clarify the structure first
Can use default mode directly:
- Fixing a specific small bug
- Modifying local content in a single file
- Adding comments or documentation
- Simple formatting or renaming
How to Use Plan Mode¶
Switch Modes with Shift+Tab¶
Starting Plan mode is very simple. In Claude Code's input field, press Shift+Tab to cycle through modes:
default β acceptEdits β plan β bypassPermissions β default β ...
When you see the mode indicator on the left side of the input field showing plan, you have entered Plan mode.
You can also state your intent to plan directly in your prompt:
Please help me create a plan first, don't modify the code directly. I want to add email verification to the user system.
Tip: Press
Escapeto exit back to default mode at any time.
Claude's Behavior in Plan Mode¶
After entering Plan mode, Claude's capabilities are restricted:
Can do:
- Read any file
- Search code (Grep, Glob)
- Analyze project structure
- View Git history
- Search web information
- Generate detailed execution plans
Will not do:
- Create or modify files
- Execute commands that may have side effects
- Install dependency packages
- Run builds or tests
This means you can safely let Claude explore any code in Plan mode without worrying about it accidentally "slipping" and changing something.
Viewing and Editing Plans¶
Plans generated by Claude typically contain the following structure:
## Execution Plan: Add Email Verification Feature
### Goal
Add email verification to the user registration flow.
### Impact Analysis
- Files to modify: 6
- Files to create: 3
- Database changes: 1 new table needed
- Risk points: Existing users are not affected, but migration scripts are needed
### Execution Steps
**Phase 1: Database Layer**
1. Create migration script for `email_verifications` table
2. Modify `users` table, add `email_verified` field
**Phase 2: Backend Logic**
3. Create new `email_verification_service.py`
4. Modify `auth_router.py`, add verification-related endpoints
5. Modify `user_service.py`, trigger verification email in registration flow
**Phase 3: Frontend Adaptation**
6. Modify registration page, add verification prompts
7. Create new email verification page
8. Modify routing configuration
### Risks and Notes
- SMTP configuration must be prepared in advance
- Need to consider expiration time for verification links
- Existing users should skip verification
You can provide feedback on the plan:
The plan looks good overall, but I have a few adjustments:
1. No need to create a new verification page, just use the existing toast notification
2. Set verification link expiration to 24 hours
3. Don't modify the users table in phase 1, use the status in email_verifications table instead
Please update the plan.
Claude will modify the plan based on your feedback until you're satisfied.
Approve Plan and Start Execution¶
After confirming the plan is correct, switch back to default mode (press Shift+Tab), then tell Claude to execute the plan:
The plan looks good, please start executing according to the plan. Start with phase one.
You can also choose to execute in phases:
Execute phase one (database layer) first, then stop and let me verify.
Plan Mode Practical Tutorial¶
Example 1: Add User Authentication to an Existing Project¶
Suppose you have a FastAPI project with no authentication mechanism currently, and you need to add JWT authentication.
Step 1: Switch to Plan mode, describe the requirements
My FastAPI project has no user authentication currently. Please help me create a plan to add a JWT-based user authentication system.
Requirements:
- User registration and login
- JWT token issuance and verification
- Route protection (some endpoints require login)
- Use SQLAlchemy to manage user table
Please analyze the existing code structure first, then create a detailed execution plan.
Step 2: Claude analyzes the project and generates a plan
Claude will first scan your project structure:
I have analyzed your project structure. Here are my findings and execution plan:
## Current Project Analysis
- Framework: FastAPI 0.115.x
- Database: Existing SQLAlchemy configuration (database.py), using PostgreSQL
- Existing models: Product, Order (in models/ directory)
- Routers: product_router.py, order_router.py (both without authentication protection)
- Dependency management: Using requirements.txt
## Execution Plan
### Phase 1: Infrastructure (2 files)
1. Add python-jose[cryptography], passlib[bcrypt] to requirements.txt
2. Add JWT-related configuration items to config.py (SECRET_KEY, ALGORITHM, TOKEN_EXPIRE)
### Phase 2: User Model and Database (2 files)
3. Create new models/user.py β User model
4. Create new alembic migration script
### Phase 3: Authentication Logic (3 files)
5. Create new services/auth_service.py β password hashing, JWT issuance/verification
6. Create new schemas/auth.py β request/response models
7. Create new routers/auth_router.py β /register, /login, /me endpoints
### Phase 4: Route Protection (3 files)
8. Create new dependencies/auth.py β get_current_user dependency
9. Modify product_router.py β write operations require authentication
10. Modify order_router.py β all operations require authentication
### Risk Notes
- SECRET_KEY in config.py must use environment variables, cannot be hardcoded
- Existing API clients need to adapt to authentication headers
- Recommend verifying in test environment first
Step 3: Review and execute
The plan is good. Two adjustments:
1. Don't use alembic, use SQLAlchemy's create_all directly
2. Read operations on product_router don't need authentication, only create and delete need it
Everything else looks fine, please execute the plan.
Example 2: Refactor a Large Module¶
Suppose your project has a 3000-line utils.py file that needs to be split and refactored.
Enter Plan mode:
utils.py has ballooned to 3000 lines with everything mixed in. Please help me analyze this file and create a refactoring plan to split it into multiple modules with clear responsibilities. Requirements:
1. Analyze the responsibilities of all functions in utils.py
2. Design a new module structure
3. List all files that import utils.py and their affected imports
4. Ensure all existing functionality remains unaffected after refactoring
Claude will generate a plan like this:
## utils.py Refactoring Plan
### Current State Analysis
utils.py contains 47 functions, which can be categorized into 5 types based on their responsibilities:
| Category | Function Count | Example Functions |
|----------|---------------|-------------------|
| String processing | 12 | slugify, truncate, sanitize_html |
| Date and time | 8 | parse_date, format_datetime, get_timezone |
| File operations | 9 | read_file, ensure_dir, get_file_hash |
| Data validation | 11 | validate_email, validate_phone, check_url |
| HTTP utilities | 7 | retry_request, parse_response, build_url |
### Import Analysis
A total of 23 files import utils.py, detailed list as follows:
(List each file and the specific functions used...)
### New Module Structure
utils/
βββ __init__.py # Re-exports for backward compatibility
βββ strings.py # String processing
βββ datetime.py # Date and time
βββ files.py # File operations
βββ validators.py # Data validation
βββ http.py # HTTP utilities
### Execution Steps
(List step by step...)
### Backward Compatibility Strategy
Keep all original exports in utils/__init__.py:
from .strings import *
from .datetime import *
...
This way, undiscovered references won't break.
Example 3: Fix Bugs Across Multiple Files¶
Users report "order amounts are occasionally calculated incorrectly," but you're not sure where the problem is.
Enter Plan mode:
Users report that order amounts are occasionally calculated incorrectly, but not every time. Please help me investigate this issue:
1. Find all code involved in amount calculations
2. Analyze possible causes of occasional errors
3. Create a fix plan
Claude will analyze deeply in Plan mode:
## Bug Investigation Report
### Amount Calculation Related Code
After comprehensive search, code related to amount calculations is distributed across 4 files:
- order_service.py:calculate_total() β main calculation logic
- discount_service.py:apply_discount() β discount calculation
- tax_service.py:calculate_tax() β tax calculation
- cart_service.py:get_cart_total() β cart total
### Issues Found
**Root cause: Floating point precision problem**
In order_service.py line 127:
total = sum(item.price * item.quantity for item in items)
Python's floating point arithmetic has precision issues:
>>> 0.1 + 0.2
0.30000000000000004
When orders contain multiple items with decimal amounts, cumulative errors may cause the final amount to be off by 1 cent.
**Secondary issue: Discount calculation order**
discount_service.py's discount calculation is executed after tax_service.py's tax calculation,
but in some concurrent scenarios, the order may be reversed (because they are called asynchronously).
### Fix Plan
1. Change all amount calculations to use Decimal type
2. Modify the call order of discount and tax to be synchronous and sequential
3. Add unit tests for amount consistency
This example demonstrates the value of Plan mode in bug investigationβClaude won't rush to change code; it performs thorough analysis first.
Plan Mode Best Practices¶
1. Describe "Why" Instead of "How"¶
Not recommended:
Please add a verify_email method to user.py that accepts a token parameter,
queries the email_verifications table, and if the token matches and hasn't
expired, sets user.email_verified to True.
Recommended:
We need to allow users to verify their email addresses. Users will receive
an email with a verification link after registration. After clicking the
link, their email status becomes verified. Please help me plan the implementation.
Why? Because when you describe "why," Claude has more room to design the optimal solution. It might discover edge cases you didn't think of, or propose a more elegant implementation. If you specify the exact implementation details, the value of Plan mode is greatly reduced.
2. Ask Claude to Identify Risk Points in the Plan¶
Proactively ask Claude to analyze risks:
Please pay special attention to the following in the plan:
1. What existing functionality might this modification break?
2. Are there configuration files that need to be modified together?
3. Do database changes require migration scripts?
4. Are there any concurrency safety concerns?
3. Execute Complex Plans in Phases¶
For large tasks, don't execute the entire plan at once. Break it into independently verifiable phases:
This plan has 4 phases, please execute as follows:
- Stop after completing each phase
- Report the completion status of that phase
- Wait for my confirmation before continuing to the next phase
The benefit of this approach: if something goes wrong in a phase, you can correct it in time without rolling back a large number of changes.
4. Combine Plans with Git Branches¶
The optimal workflow is: Plan mode creates plan β Create new branch β Execute on new branch β Code review β Merge
# Create plan in Plan mode first
(Switch to Plan mode, describe requirements, review plan)
# After satisfied, switch back to default mode
Please create a new branch feature/email-verification first, then execute the plan.
If you discover the plan is wrong during execution, you can always return to the main branch and start over.
Plan Mode vs Direct Coding¶
When Plan Mode Is Not Needed¶
- Simple tasks modifying one or two files
- Clearly know what to change and how
- Non-functional changes like adding comments or modifying copy
- Running commands (like installing dependencies, running tests)
When Plan Mode Is Required¶
- Changes involving more than 5 files
- Modifying public interfaces or core modules
- Not yet familiar enough with the project structure
- Unknown bug causes, need to investigate first
- Need to evaluate trade-offs between multiple solutions
Decision Reference¶
What is your task?
β
ββ Simple modification (1-2 files, clear direction)
β β Default mode, start directly
β
ββ Medium task (3-5 files, clear logic)
β β Can use Plan mode first for quick scan, then switch to execute
β
ββ Complex task (multiple files, uncertain solutions, high risk)
β Must use Plan mode, plan in detail before executing
Advanced Tips¶
1. Customize Plan Templates via CLAUDE.md¶
You can define planning requirements in your project's CLAUDE.md so every Plan mode follows a consistent format:
## Plan Mode Requirements
When entering Plan mode, please generate plans according to the following template:
### Required Sections
1. **Current State Analysis**: Current code structure and relevant files
2. **Solution Design**: Specific implementation approach, including alternatives
3. **Impact Scope**: Which files will be modified, which features will be affected
4. **Risk Assessment**: Possible issues and countermeasures
5. **Execution Steps**: In sequential order, each step verifiable independently
6. **Testing Plan**: How to verify the correctness of changes
### Format Requirements
- Each execution step should indicate the files involved
- New files should be marked with [NEW]
- Files to modify should be marked with [MODIFY]
- Risk points should be marked with High/Medium/Low severity
After adding this to CLAUDE.md, every time you use Plan mode, Claude will organize plans according to this template.
2. Use Sub-agents for Exploration in Plan Mode¶
In Plan mode, you can ask Claude to use sub-agents (Agent tools) for deeper exploration:
Before creating the plan, please help me figure out the following:
1. What does the current database schema look like? Use a sub-agent to analyze all model files
2. What is the list of existing API endpoints? Use a sub-agent to scan all router files
3. What third-party libraries does the project use? Check requirements.txt or pyproject.toml
Sub-agents will execute these exploration tasks in separate contexts, then summarize results for the main session, helping Claude create more accurate plans.
3. Save and Reuse Plans¶
Good plans can be saved as reference templates. You can ask Claude to export the plan as a Markdown file:
Please save the plan we just created to docs/plans/add-email-verification.md.
We can reference it when working on similar features in the future.
Next time you encounter similar requirements, you can reference it directly:
Please refer to the plan structure in docs/plans/add-email-verification.md
and create a similar plan for SMS verification.
4. Use Plan Mode for Code Review¶
The read-only nature of Plan mode makes it very suitable for code review:
(Enter Plan mode)
Please review all service files in the src/services/ directory, focusing on:
1. Is error handling comprehensive?
2. Are there any SQL injection risks?
3. Are there unclosed resources (database connections, file handles)?
4. Do async code have race conditions?
Please provide a detailed review report and improvement suggestions.
Since Plan mode doesn't modify any files, you can safely let Claude review production code without worrying about it accidentally "conveniently" changing something.
5. Combine with /compact for Long Plan Sessions¶
The exploration process in Plan mode may consume a lot of context (especially after analyzing many files). If you feel the context is running low, you can use /compact after completing the plan but before executing:
/compact Keep the complete execution plan and impact analysis, compress the intermediate exploration process
This leaves ample context space for the execution phase.
FAQ¶
Q: Will Claude accidentally modify files in Plan mode?
A: No. Plan mode prohibits all write operations at the system level. Claude can read any file but cannot create, modify, or delete any content.
Q: After creating the plan, when switching to default mode to execute, will Claude still remember the plan?
A: Yes. As long as you haven't used /clear to clear the history, switching modes doesn't lose context. The plan is still in the conversation history, and Claude can execute the plan directly.
Q: Can I use MCP tools in Plan mode?
A: You can use read-only MCP tools (like search, documentation queries), but cannot use tools that produce side effects.
Q: If I think the plan isn't good, can I ask Claude to replan?
A: Absolutely. You can repeatedly ask Claude to modify the plan until you're satisfied. The zero-risk nature of Plan mode means you can freely explore and adjust.
Q: How do I share plans in team collaboration?
A: You can ask Claude to save the plan as a Markdown file and commit it to the Git repository. You can also include the plan content directly in the PR description to facilitate code review.