Chapter 40

CLAUDE.md System: Complete Design of Three-Layer Configuration, Auto Memory and Path-Specific Rules

Chapter 40: Claude Code Core Workflow: File Editing, Bash Execution, and Project Navigation

40.1 Claude Code's Tool System

Claude Code ships with a built-in set of core tools that enable it to truly operate a codebase rather than just providing suggestions. Understanding how these tools work is the key to using Claude Code effectively.

40.1.1 Built-in Tool Inventory

Tool Function Typical Use Cases
Read Read file contents Analyzing code, understanding configuration
Write Overwrite a file completely Creating new files
Edit Precisely modify specific content in a file Bug fixes, refactoring
MultiEdit Apply multiple edits to a file in one operation Large-scale refactoring
Bash Execute bash commands Running tests, git operations, compilation
Glob Find files using pattern matching Locating specific file types
Grep Search file contents Finding variable usage, function references
LS List directory contents Understanding project structure
TodoWrite Maintain a task list Tracking progress on multi-step tasks
Agent Launch a sub-agent Delegating independent subtasks

40.1.2 Transparency of Tool Calls

Claude Code displays all tool calls by default, giving you clear visibility into what the AI is doing:

โ— Reading file: src/api/auth.py
โ— Searching: "def validate_token" in src/
โ— Bash: pytest tests/test_auth.py -v
โ— Editing: src/api/auth.py (lines 45-67)

Toggle verbosity with the /verbose command.

40.2 File Editing Workflow

40.2.1 Read + Edit: Precise Modification Pattern

The most common editing pattern is "read first, then precisely modify" โ€” far safer than overwriting the whole file, since the Edit tool requires exact string matching for the content it changes:

User request:

"In the validate_email function in src/utils/validators.py,
add support for .edu.cn domain names"

Claude Code execution flow:

Step 1: Read
  โ— Reading: src/utils/validators.py
  
  # Read content (excerpt):
  def validate_email(email: str) -> bool:
      pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
      return bool(re.match(pattern, email))

Step 2: Edit
  โ— Editing: src/utils/validators.py
  
  old: r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
  new: r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z]{2,}|[a-zA-Z]{2,3}\.[a-zA-Z]{2})$'

Step 3: Bash (optional verification)
  โ— Running: pytest tests/test_validators.py -v

40.2.2 Write Tool: Creating New Files

When creating brand new files, the Write tool is used:

User request:

"Create FastAPI route file for the User model with CRUD endpoints"

Claude Code execution:

Step 1: Read (understand existing code structure)
  โ— Reading: src/models/user.py
  โ— Reading: src/api/posts.py (reference for existing route patterns)

Step 2: Write
  โ— Writing: src/api/users.py
  
  from fastapi import APIRouter, Depends, HTTPException
  from sqlalchemy.orm import Session
  from app.core.database import get_db
  from app.models.user import User
  from app.schemas.user import UserCreate, UserUpdate, UserResponse
  
  router = APIRouter(prefix="/users", tags=["users"])
  
  @router.get("/", response_model=list[UserResponse])
  async def list_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
      return db.query(User).offset(skip).limit(limit).all()
  
  # ... other CRUD endpoints

Step 3: Edit (register the new router in the main app)
  โ— Editing: src/main.py
  # Adds: from app.api.users import router as users_router
  #        app.include_router(users_router)

40.2.3 MultiEdit: Batch Modifications

When making multiple changes to the same file, MultiEdit is more efficient than repeated Edit calls โ€” all changes are shown and applied atomically:

User: "Replace all print statements in database.py with logger.debug calls"

Claude Code uses MultiEdit, submitting all replacements at once:
- print("Connecting...") โ†’ logger.debug("Connecting...")
- print(f"Query: {sql}") โ†’ logger.debug(f"Query: {sql}")
- print("Connection closed") โ†’ logger.debug("Connection closed")

40.2.4 Large File Strategy

For files that exceed the model's context window, Claude Code uses a chunked processing approach:

User: "Refactor this 3000-line legacy_processor.py,
       splitting it into modules following single responsibility"

Claude Code's strategy:
1. Read file header first (understand module-level structure)
2. Use Grep to find all class definitions and major functions
3. Read specific functional sections in chunks
4. Plan the split (track progress with TodoWrite)
5. Incrementally create new files and modify the original

40.3 Bash Execution Workflow

40.3.1 Bash Tool Capabilities

Operations that can be executed:

Operations requiring default confirmation:

40.3.2 Test-Driven Repair Loop

One of Claude Code's most powerful workflows is the test-driven automatic repair loop:

User request:

"Run the test suite, find all failing tests, fix them one by one until everything passes"

Claude Code execution:

Step 1: Bash
  โ— Running: pytest tests/ -v --tb=short
  
  Output:
  FAILED tests/test_auth.py::test_login_invalid_password - AssertionError
  FAILED tests/test_user.py::test_create_user_duplicate_email - IntegrityError
  
  2 failed, 45 passed

Step 2: Analyze first failure
  โ— Reading: tests/test_auth.py (view test code)
  โ— Reading: src/api/auth.py (view implementation)
  
  Analysis: test_login_invalid_password expects 401, but code returns 400

Step 3: Edit
  โ— Editing: src/api/auth.py
  # Change: raise HTTPException(status_code=400) โ†’ status_code=401

Step 4: Bash (verify fix)
  โ— Running: pytest tests/test_auth.py::test_login_invalid_password -v
  Output: PASSED โœ“

Step 5: Analyze second failure
  [Repeat the above flow...]

Step 6: Final verification
  โ— Running: pytest tests/ -v
  Output: 47 passed โœ“

40.3.3 Git Workflow Automation

Claude Code can manage complete git workflows:

User: "Create a new branch, implement user avatar upload,
       then commit and push when done"

Step 1: Bash - Create branch
  โ— Running: git checkout -b feat/user-avatar-upload

Step 2: Read (understand existing user code)
  โ— Reading: src/models/user.py
  โ— Reading: src/api/users.py

Step 3: Write (create file upload service)
  โ— Writing: src/services/file_upload.py

Step 4: Edit (add avatar_url to user model)
  โ— Editing: src/models/user.py

Step 5: Edit (add avatar upload API endpoint)
  โ— Editing: src/api/users.py

Step 6: Bash - Generate database migration
  โ— Running: alembic revision --autogenerate -m "add avatar_url to users"

Step 7: Bash - Run tests to confirm no regressions
  โ— Running: pytest tests/ -x

Step 8: Bash - Commit and push
  โ— Running: git add src/ migrations/
  โ— Running: git commit -m "feat(users): add avatar upload functionality"
  โ— Running: git push origin feat/user-avatar-upload
  
Output:
  Branch pushed to remote.
  Create PR: https://github.com/org/repo/compare/feat/user-avatar-upload

40.4 Project Navigation Workflow

40.4.1 Glob: File Discovery

The Glob tool uses pattern matching to locate files โ€” the foundation of project navigation:

User: "Find all files using deprecated_function and replace with new_function"

Step 1: Grep (locate all references)
  โ— Searching: "deprecated_function" in **/*.py
  
  Found in:
  - src/utils/processor.py (lines 23, 45)
  - src/api/legacy.py (line 12)
  - tests/test_processor.py (lines 7, 34)

Step 2: Read (understand context in each file)
  [Read all three files]

Step 3: Edit (replace in each file)
  โ— Editing: src/utils/processor.py (2 occurrences)
  โ— Editing: src/api/legacy.py (1 occurrence)
  โ— Editing: tests/test_processor.py (2 occurrences)

Step 4: Bash (run tests to verify)
  โ— Running: pytest tests/ -v

40.4.2 Codebase Understanding Pattern

When taking over a new codebase, use Claude Code to rapidly build understanding:

User: "Help me understand this project's architecture"

Claude Code's exploration flow:

1. Read CLAUDE.md or README.md (if present)
2. View top-level directory structure (LS)
3. Read core config files (package.json/pyproject.toml/Cargo.toml)
4. Identify entry files (main.py/index.ts/main.go)
5. Read entry file
6. Read main router/controller files
7. Examine database schema (if web app)
8. Generate architecture diagram (text format)

Example output:
"This project is a FastAPI RESTful API service with the following architecture:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ FastAPI Application (src/main.py)    โ”‚
โ”‚                                      โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”‚
โ”‚  โ”‚ API Layer (src/api/)        โ”‚     โ”‚
โ”‚  โ”‚ - auth.py    - users.py     โ”‚     โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”‚
โ”‚  โ”‚ Service Layer (src/services/)โ”‚    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ”‚
โ”‚             โ”‚                        โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”‚
โ”‚  โ”‚ Data Layer (src/models/)    โ”‚     โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Database: PostgreSQL (via SQLAlchemy ORM)
Auth: JWT (Bearer Token)
Key deps: FastAPI 0.100+, Pydantic v2, SQLAlchemy 2.0"

40.4.3 Advanced Grep Searches

The Grep tool supports regular expressions for complex code searches:

# Find all Python functions without type hints
grep -rn "^def [a-zA-Z_]+(" src/ --include="*.py"

# Find all TODO/FIXME comments
grep -rn "TODO\|FIXME\|HACK\|XXX" src/ --include="*.py"

# Find potential circular import indicators
grep -rn "^from \." src/ --include="*.py"

40.5 Task Tracking: TodoWrite Tool

TodoWrite is Claude Code's built-in task list tool for tracking progress on multi-step tasks. When a task contains multiple subtasks, Claude Code automatically creates and maintains a TODO list.

40.5.1 Automatic Task Planning

User: "Migrate the entire project from Python 3.9 to Python 3.11,
       refactoring code to use new features"

Claude Code plans with TodoWrite:

TODO list:
โ–ก 1. Update Python version requirement in pyproject.toml
โ–ก 2. Run compatibility check (pip-audit, python-requires)
โ–ก 3. Replace Union[X, Y] type annotations with X | Y syntax
โ–ก 4. Replace Optional[X] with X | None
โ–ก 5. Replace TypedDict with native dataclass where appropriate
โ–ก 6. Use match-case to replace complex if-elif chains
โ–ก 7. Run full test suite to confirm no regressions
โ–ก 8. Update Python version in CI/CD configuration
โ–ก 9. Update Dockerfile base image
โ–ก 10. Update project documentation

Executing...

โœ“ 1. Updated Python version in pyproject.toml
โœ“ 2. Ran compatibility check
โ—Ž 3. Replacing Union[X, Y] annotations with X | Y (in progress)

40.5.2 Progress Recovery

If the session is interrupted, resume progress:

User: "Continue the migration task from last time"

Claude Code reads TodoWrite state:
"Based on the task list, we completed the first two steps.
 Continuing from step 3: replacing Union[X, Y] with X | Y..."

40.6 Sub-Agent Pattern

For massive-scale tasks, Claude Code can launch sub-agents to process work in parallel:

User: "Generate complete docstrings for all public API functions in the codebase"

Claude Code Agent plan:
1. Use Glob to list all Python files (47 total)
2. Split into 4 groups, launch 4 sub-agents in parallel:
   - Sub-agent 1: api/ directory (12 files)
   - Sub-agent 2: services/ directory (10 files)
   - Sub-agent 3: models/ directory (8 files)
   - Sub-agent 4: utils/ directory (17 files)
3. Collect all sub-agent results
4. Master agent reviews and standardizes documentation style

40.7 Real-World Workflow Examples

40.7.1 Bug Fix Workflow

User: "Users can't reset their password โ€” error says 'Token has expired'
       but the token was just generated"

Claude Code diagnostic flow:

# 1. Search for relevant code
Grep: "Token has expired" in src/
Found: src/utils/tokens.py line 45

# 2. Read token generation and validation code
Read: src/utils/tokens.py
Read: src/api/auth.py

# 3. Identify problem: token expiry uses UTC, validation uses local time
Edit: src/utils/tokens.py
  old: expires_at = datetime.now() + timedelta(hours=1)
  new: expires_at = datetime.utcnow() + timedelta(hours=1)

# 4. Check for similar issues elsewhere
Grep: "datetime.now()" in src/
Found: 3 more occurrences

# 5. Fix all instances
[Fix remaining 3 locations]

# 6. Add regression test
Write: tests/test_token_timezone.py

# 7. Run tests to verify
Bash: pytest tests/test_token_timezone.py tests/test_auth.py -v

40.7.2 Code Review Workflow

User: "Review the code changes I made today"

Claude Code executes:

# 1. View today's changes
Bash: git diff HEAD~3..HEAD --name-only

# 2. Read and analyze each changed file
[Read all changed files]

# 3. Run tests
Bash: pytest tests/ -v --tb=short

# 4. Check code quality
Bash: flake8 src/ --max-line-length=100
Bash: mypy src/ --strict

# 5. Generate review report
"Code Review Report:

## Overall Assessment: Good, with a few notable concerns

## Issues Found
1. [Critical] src/api/users.py line 45: SQL query is not parameterized,
   creating SQL injection risk.
   Recommendation: Use ORM or parameterized queries

2. [Warning] src/services/email.py line 23:
   Email send failure is not logged, making issues hard to trace.
   Recommendation: Add logger.error() to catch exceptions

3. [Suggestion] src/models/user.py:
   User.created_at field is missing a default value.
   Recommendation: Add server_default=func.now()

## Test Coverage
- New code coverage: 78% (recommend > 80%)
- Missing test case for email send failure scenario"

40.7.3 Full Feature Development Workflow

User: "Implement API rate limiting โ€” max 60 requests per user per minute"

Step 1: Research existing architecture
  Read: src/main.py (understand middleware structure)
  Read: src/core/config.py (understand configuration patterns)
  Bash: pip list | grep redis (confirm Redis availability)

Step 2: Plan implementation (TodoWrite)
  TODO:
  โ–ก Create RateLimiter service class
  โ–ก Add Redis connection configuration
  โ–ก Create rate-limiting middleware
  โ–ก Register middleware in main app
  โ–ก Add rate-limit configuration items
  โ–ก Write unit tests
  โ–ก Write documentation

Step 3: Implement
  Write: src/services/rate_limiter.py
  Edit: src/core/config.py (add RATE_LIMIT_* config)
  Write: src/middleware/rate_limit.py
  Edit: src/main.py (register middleware)
  Write: tests/test_rate_limiter.py

Step 4: Validate
  Bash: pytest tests/test_rate_limiter.py -v
  Bash: uvicorn app.main:app --reload &
  Bash: for i in $(seq 1 65); do curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8000/api/test; done
  # First 60 requests โ†’ 200, subsequent โ†’ 429

Step 5: Commit
  Bash: git add src/ tests/
  Bash: git commit -m "feat(api): implement per-user rate limiting (60 req/min)"

40.8 Best Practices

40.8.1 Provide Sufficient Context

The quality of Claude Code's output depends heavily on the quality of context provided:

Ineffective prompt:

"Fix the bug"

Effective prompt:

"After users log in, accessing /api/profile returns 403.
The error log shows: 'User 42 does not have permission to view profile'
But that user does exist in the database.
Please analyze the get_profile endpoint in src/api/users.py
and the permission check logic in src/middleware/auth.py"

40.8.2 Iterative Task Decomposition

For large tasks, incremental requests produce better results:

# Not recommended: demand full implementation in one shot
"Implement a complete user authentication system including
registration, login, password reset, email verification, OAuth, JWT refresh"

# Recommended: implement in stages
Step 1: "Implement basic email/password registration and login"
Step 2: "Add JWT refresh tokens to the existing auth"
Step 3: "Add email verification flow"
Step 4: "Integrate Google OAuth"

40.8.3 Use CLAUDE.md to Eliminate Repetitive Instructions

Having to state "use Black formatting" every session is inefficient. Write it once in CLAUDE.md:

# CLAUDE.md
## Code Standards
- Python: Black formatting, isort imports, type annotations required
- Function length: max 50 lines; file length: max 300 lines
- Testing: every new function needs at least one unit test

40.8.4 Monitor Costs with /cost

Every Claude Code operation consumes API tokens. For long tasks, periodically check costs:

/cost

Output:
Current session usage:
  Input tokens:  45,234
  Output tokens: 12,891
  Total cost:    $1.23 (approximate)
  Model:         claude-sonnet-4-5

40.8.5 Using --print Mode for Scripting

Claude Code supports a non-interactive --print mode for use in CI/CD pipelines or scripts:

# Non-interactive security review
claude --print "Review all Python files in src/api/ for security vulnerabilities"

# Auto-generate commit message
COMMIT_MSG=$(claude --print "Generate a one-line commit message based on git diff")
git commit -m "$COMMIT_MSG"

# Integrate code quality analysis in CI
claude --print "Analyze test failure causes and suggest fixes" < test_output.txt

Summary

This chapter provided an in-depth look at Claude Code's core workflow: file editing (Read/Write/Edit/MultiEdit), bash execution (test loops, git automation), and project navigation (Glob/Grep/LS). The combination of these three tool categories forms the foundational capability of Claude Code as an AI Agent.

Key takeaways:

  1. The Edit tool modifies files through precise string matching โ€” safer than Write (complete overwrite)
  2. The test-driven repair loop (run tests โ†’ analyze failures โ†’ fix โ†’ rerun) is one of the most productive workflows available
  3. TodoWrite tracks multi-step tasks and supports resuming after session interruptions
  4. High-quality CLAUDE.md significantly reduces repetitive explanations across sessions
  5. Providing sufficient context (specific error messages, relevant file paths) is the single most important factor in maximizing Claude Code's effectiveness

These two chapters on Claude Code โ€” covering installation and configuration through core workflow mastery โ€” lay the foundation for deeper practical use. From basic setup to tool fluency to efficient workflow patterns, the full potential of Claude Code is steadily coming into view.

Rate this chapter
4.5  / 5  (3 ratings)

๐Ÿ’ฌ Comments