Lesson 8: Advanced Features
Learning Objectives
After completing this lesson, you will be able to:
- Use subagents for specialized tasks (Explore, Plan, Bash)
- Run and manage background tasks
- Set up hooks for automation
- Understand session persistence and resumption
- Manage context compaction
- Use the task system for complex workflows
Prerequisites
- Completed Lessons 1-7 - Core operations, permissions, and configuration
- Comfortable with basic workflows - File operations and permissions
- Multi-project experience - Worked with at least 2-3 projects
Estimated Time: 30 minutes
Subagents
Subagents are specialized agents that Claude Code can launch to handle specific types of tasks. They have their own context and tools optimized for their purpose.
What Are Subagents?
Think of subagents as specialists:
- Main Claude = Project manager (coordinates everything)
- Subagents = Specialists (handle specific tasks)
Why use subagents:
- Focus: Each agent specializes in one thing
- Context: Separate context for different tasks
- Efficiency: Parallel work on independent tasks
- Optimization: Tailored tools for each job
The Three Subagent Types
1. Explore Agent
Purpose: Quickly explore and understand codebases
When to use:
- "How is authentication implemented?"
- "What files handle user input?"
- "Where is the API endpoint for X?"
- Understanding a new project
How it works:
- Uses Glob and Grep extensively
- Reads multiple files in parallel
- Builds mental map of codebase
- Reports back findings
Example:
You> How does the payment processing work in this codebase?
Claude: I'll use the Explore agent to investigate.
[Launches Explore agent]
Explore Agent: [Searching files...]
Found payment-related code:
- src/services/payment.py - PaymentService class
- src/api/payment.py - API endpoints
- src/models/transaction.py - Transaction model
[Reads and analyzes files]
Explore Agent: Payment flow:
1. User calls /api/payment/create
2. PaymentService processes via Stripe
3. Transaction record saved
4. Webhook updates status
Claude: Based on the exploration, here's how payment processing works...
2. Plan Agent
Purpose: Design implementation strategies before coding
When to use:
- "Add user authentication"
- "Refactor to use TypeScript"
- Complex multi-file changes
- Architecture decisions
How it works:
- Analyzes requirements
- Explores codebase
- Creates step-by-step plan
- Identifies dependencies
- Presents for approval
Example:
You> /plan
You> Add role-based access control (RBAC) to the application
Claude: I'll create a plan for implementing RBAC.
[Launches Plan agent]
Plan Agent: [Analyzing codebase...]
PLAN: RBAC Implementation
Phase 1: Data Model
1. Create Role model (admin, editor, viewer)
2. Create Permission model
3. Add Role-Permission many-to-many
4. Add User-Role relationship
Phase 2: Middleware
1. Create authorization middleware
2. Add permission checking decorator
3. Integrate with existing routes
Phase 3: UI Updates
1. Add role management interface
2. Update permission displays
3. Add admin controls
Files to modify: 15
Files to create: 8
Estimated time: 2-3 hours
Proceed with implementation? [Y/n/modify]
3. Bash Agent
Purpose: Execute command-line tasks safely
When to use:
- Running build scripts
- Installing dependencies
- Executing tests
- Any terminal operations
How it works:
- Has dedicated Bash tool access
- Can run multiple commands
- Handles errors gracefully
- Reports command output
Example:
You> Run the test suite and fix any failing tests
Claude: I'll use the Bash agent to run tests.
[Launches Bash agent]
Bash Agent: [Running npm test...]
Test Results:
✓ 15 tests passed
✗ 2 tests failed:
- test_user_auth.js:45
- test_api_validation.js:12
[Investigating failures...]
Bash Agent: The failures are due to:
1. Missing auth token in test setup
2. Invalid email regex
[Fixing issues...]
Bash Agent: [Re-running tests...]
All 17 tests passing now.
Claude: Tests have been fixed and are now passing.
Invoking Subagents
Automatic invocation: Claude automatically chooses when to use subagents.
Manual invocation:
You> Use the Explore agent to find all database queries
You> Ask the Plan agent how to refactor this module
Background Tasks
Background tasks allow long-running operations to continue while you work on other things.
Why Background Tasks?
Problem: Some operations take time
- Running full test suites
- Large code searches
- Processing multiple files
- Watching for file changes
Solution: Run them in the background
- Continue working while they run
- Check progress when needed
- Handle completion asynchronously
Starting Background Tasks
Method 1: Explicit background request
You> Run the full test suite in the background
Method 2: Background flag
claude --background "npm test"
Method 3: During conversation
You> Search all Python files for TODO comments
Claude: This will take a while. Run in background? [Y/n]
You: Y
[Task runs in background]
Managing Background Tasks
List running tasks:
You> /tasks
Check task status:
You> What's the status of the background search?
View task output:
You> Show me the results of the background task
Cancel a task:
You> Cancel the background build task
Background Task Output
When a task completes:
[Background task completed]
Task: Search Python files for TODO
Duration: 2m 34s
Results:
- src/auth.py:45 - TODO: Add rate limiting
- src/api.py:123 - TODO: Implement caching
- src/utils.py:67 - TODO: Refactor this function
Hooks and Automation
Hooks allow you to trigger actions automatically based on events.
What Are Hooks?
Hooks are scripts or commands that run automatically when specific events occur.
Hook events:
pre-tool- Before any tool is usedpost-tool- After a tool completespre-commit- Before git commitpost-commit- After git commiton-edit- When a file is editedsession-start- When starting a sessionsession-end- When ending a session
Configuring Hooks
In settings file:
{
"hooks": {
"pre-commit": ["npm run lint", "npm run test"],
"on-edit": ["./scripts/format.sh"],
"session-start": ["./scripts/check-env.sh"]
}
}
Practical Hook Examples
Pre-commit hook:
{
"hooks": {
"pre-commit": [
{
"command": "npm",
"args": ["run", "lint"]
}
]
}
}
Run tests after edits:
{
"hooks": {
"post-edit": {
"pattern": "*.test.js",
"command": "npm",
"args": ["test", "--", "$FILE"]
}
}
}
Session notifications:
{
"hooks": {
"session-start": {
"command": "notify-send",
"args": ["Claude Code", "Session started"]
}
}
}
Session Management
Claude Code sessions can be persisted and resumed.
Session Persistence
What's saved:
- Conversation history
- File operation context
- Task state
- Configuration used
Where sessions are saved:
- Linux/macOS:
~/.local/state/claude-code/sessions/ - Windows:
%LOCALAPPDATA%\claude-code\sessions\
Resuming Sessions
Method 1: Auto-resume
claude --resume
Resumes the most recent session.
Method 2: Specific session
claude --resume session-id
Method 3: During session
You> /sessions
[List available sessions]
You> Resume session abc123
Session States
┌─────────────┐
│ Active │ ← Current session
└──────┬──────┘
│
┌──────▼──────┐
│ Paused │ ← Temporarily paused
└──────┬──────┘
│
┌──────▼──────┐
│ Archived │ ← Completed, saved
└─────────────┘
Managing Sessions
List all sessions:
claude --list-sessions
Delete old sessions:
claude --clean-sessions --older-than 7d
Export session:
claude --export-session session-id --output session.json
Context Compaction
As conversations grow, Claude Code manages context to stay efficient.
What is Context Compaction?
The problem:
- Long conversations exceed token limits
- Important information gets lost
- Performance degrades
The solution:
- Summarize older parts of conversation
- Preserve key information
- Maintain continuity
How Compaction Works
┌─────────────────────────────────────────────┐
│ Full conversation (1000+ messages) │
└──────────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ Compaction triggered (token limit nearing) │
└──────────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ Early conversation → Summarized │
│ Recent conversation → Kept in detail │
│ Key decisions → Preserved │
│ File context → Maintained │
└─────────────────────────────────────────────┘
Manual Compaction
Trigger compaction:
You> Compact the conversation
What gets preserved:
- Recent messages (last 50-100)
- Key decisions and conclusions
- Important file references
- Current task context
What gets summarized:
- Older detailed discussions
- Resolved issues
- Background information
Task System for Complex Workflows
The task system helps organize and track multi-step work.
Creating Tasks
Tasks can be created to track progress on complex work.
Example:
You> I need to refactor the authentication system
Claude: I'll create a task to track this work.
[Task created: Refactor authentication]
Subtasks:
□ Review current auth implementation
□ Design new auth architecture
□ Implement new auth service
□ Update API endpoints
□ Migrate existing users
□ Update tests
□ Update documentation
Task Management Commands
List tasks:
You> /tasks
Show task details:
You> Show task "Refactor authentication"
Update task status:
You> Mark "Review current auth" as completed
Add subtask:
You> Add subtask to auth refactor: Create migration script
Practical Example: Using Advanced Features
Let's use multiple advanced features together.
Scenario: Debug and Fix a Production Issue
Step 1: Use Explore Agent to Investigate
You> Production is showing errors in user registration. Use Explore to find the registration flow.
[Explore agent investigates]
Explore Agent: Found:
- src/api/auth.py - register endpoint
- src/services/user.py - User creation
- src/utils/validation.py - Email validation
The registration endpoint calls User.create(), which validates email.
Step 2: Run Background Task to Check Logs
You> Search the application logs for registration errors in the background
[Background task starts]
Step 3: Plan the Fix
You> /plan
You> Fix the email validation issue
[Plan agent creates plan]
Plan: Fix Email Validation
1. Update regex to allow new TLDs
2. Add unit tests for edge cases
3. Update documentation
Proceed? Y
Step 4: Check Background Task
You> Show background task results
[Shows logs revealing specific failing emails]
Step 5: Implement Fix
You> Implement the plan
[Claude makes changes]
Step 6: Verify with Background Task
You> Run tests in background
[Tests run, all pass]
Step 7: Commit Changes
You> Commit these changes with /commit
[Pre-commit hooks run: lint, test]
[Changes committed]
✅ Check Your Understanding
-
Which subagent specializes in exploring codebases?
- Plan Agent
- Bash Agent
- Explore Agent
- Search Agent
-
What's the purpose of background tasks?
- To run tasks in the background while continuing work
- To delete old files
- To manage permissions
- To configure MCP servers
-
Which hook runs before a git commit?
- post-commit
- pre-commit
- on-edit
- session-start
-
True or False: You can resume previous Claude Code sessions.
- True
- False
-
What does context compaction do?
- Deletes old conversations
- Compresses the conversation history to save tokens
- Encrypts the conversation
- Exports the conversation to a file
Answers: 1-c, 2-a, 3-b, 4-True, 5-b
⭐ New in 2.1.33: Advanced Agent Features
Claude Code 2.1.33 introduces several advanced features that build on the concepts in this lesson.
Agent Teams (Lesson 18)
While subagents work independently, Agent Teams work together in split-pane terminals:
// settings.json
{
"teammateMode": "tmux",
"agentTeams": {
"fullstack": {
"teammates": [
{"name": "backend", "systemPrompt": "Backend developer"},
{"name": "frontend", "systemPrompt": "Frontend developer"}
]
}
}
}
Key differences from subagents:
- Visual collaboration - See teammates working in real-time
- Direct messaging - Teammates send messages to each other
- Split panes - tmux, WezTerm, iTerm2 support
- spawnTeam tool - Create teams programmatically
Learn more: Lesson 18: Agent Teams & Teammates
Enhanced Hooks (Lesson 20)
Hooks are now available for skills, agents, and commands:
---
name: deploy
hooks:
pre-tool:
command: ./scripts/pre-deploy.sh
post-tool:
command: ./scripts/notify.sh
---
New hook capabilities:
- Skill hooks - Pre/post tool execution for skills
- Agent hooks - Subagent start/stop hooks
- Permission hooks - Auto-approve/deny patterns
- Timeout: 10 minutes - Increased from 60 seconds
Learn more: Lesson 20: 2.1.x Advanced Features
Wildcard Permissions (Lesson 20)
Simplify permission rules with wildcards:
{
"permissions": {
"allowedOperations": [
"Bash(npm *)", // All npm commands
"Bash(git *)", // All git commands
"Bash(* test)", // Any test command
"Read(*.md)" // All markdown files
]
}
}
Session Forking (Lesson 20)
Experiment safely with session forking:
# Fork current session
claude --fork-session
# Rewind to previous point
/rewind
External Editor (Lesson 20)
Press Ctrl+G to edit your prompt in your favorite editor:
export EDITOR=vim # or nano, code, etc.
# In Claude Code
[Type prompt... Press Ctrl+G]
[Vim opens with your prompt]
[Edit and save]
[Prompt updated in Claude]
Summary
In this lesson, you learned:
- Subagents - Explore, Plan, Bash specialists
- Background tasks - Run long operations asynchronously
- Hooks - Automate actions based on events
- Session management - Persist and resume conversations
- Context compaction - Manage long conversations efficiently
- Task system - Track complex multi-step work
Next Steps
In Lesson 9: Git Integration, you'll learn:
- Using Claude for git operations
- The
/commitskill in depth - Creating pull requests
- Searching git history
- Best practices for version control
Further Reading
Continue to Lesson 9: Git Integration →