Advanced Claude Code: Automation, Agents, and Power Workflows
This is Part 2 of a 3-part series on working effectively with Claude Code.
- Part 1: Essential foundations and basic workflows
- Part 2 (this post): Advanced automation with agents, commands, and hooks
- Part 3: Production readiness with TDD and security
In Part 1, we covered the essential foundations: specificity, CLAUDE.md files, Plan Mode, and context management. Now let's explore the power features that scale your productivity.
Once you've mastered the fundamentals from Part 1, it's time to level up your Claude Code workflow with advanced features that automate repetitive tasks and delegate complex work to specialized agents.
5. Delegate to Specialized Sub-Agents
Sub-agents are specialized AI assistants with focused responsibilities and their own context windows. They're one of Claude Code's most powerful features for complex work.
Why use sub-agents:
- Context isolation: Keep task-specific details separate from your main conversation
- Domain expertise: Give each agent specialized instructions and knowledge
- Parallelism: Run multiple agents concurrently for faster completion
- Granular permissions: Restrict powerful tools to specific agents
- Reusability: Share agents across projects and team members
How to create custom agents:
Agents are stored as Markdown files with YAML frontmatter:
- Project agents:
.claude/agents/(highest priority, version controlled) - User agents:
~/.claude/agents/(system-wide, personal)
Example: Test Specialist Agent
Create .claude/agents/test-specialist.md:
---
name: test-specialist
description: Writes comprehensive test coverage with edge cases
model: sonnet-4-5
tools: Read, Write, Bash, Grep
---
You are a testing specialist focused on comprehensive test coverage.
For every function you test:
1. Happy path scenarios
2. Edge cases (empty, null, undefined, extreme values)
3. Error conditions and failure modes
4. Integration points and dependencies
5. Meaningful assertions with clear failure messages
Framework: Vitest
Coverage target: 80% minimum
Always run tests after writing them to verify they pass.
Using agents:
"@test-specialist write tests for @utils/formatCurrency.ts"
Or let Claude delegate automatically when appropriate.
Example use cases:
- code-reviewer: Reviews PRs for security, performance, best practices
- migration-specialist: Handles complex refactors with backward compatibility
- security-auditor: Analyzes code for vulnerabilities
- documentation-writer: Generates comprehensive docs with examples
- performance-optimizer: Identifies bottlenecks and suggests improvements
Best practices:
- Design single-focused responsibilities (not universal agents)
- Grant only necessary tools to each agent
- Version control project agents for team collaboration
- Use
/agentscommand to list and manage agents - Agents can't spawn other agents (one level deep only)
Pro tip: Run multiple agents in parallel for independent tasks:
"Launch @test-specialist for the utils folder and @code-reviewer for the recent PR"
6. Custom Slash Commands for Reusable Workflows
Slash commands are reusable prompt templates that save you from typing the same instructions repeatedly. They're perfect for code reviews, component scaffolding, and any workflow you repeat regularly.
What are slash commands:
- Markdown files stored in
.claude/commands/(project) or~/.claude/commands/(personal) - Can accept arguments via
$ARGUMENTSplaceholder - Version controlled and shareable with your team
- Subdirectories create namespaces (e.g.,
/frontend/component)
Example: Code Review Command
Create .claude/commands/review.md:
Review the current changes for:
1. **Security vulnerabilities**
- SQL injection, XSS, CSRF
- Authentication/authorization issues
- Sensitive data exposure
2. **Code quality**
- Follows project conventions in CLAUDE.md
- Proper error handling
- No code duplication
3. **Performance**
- Unnecessary re-renders (React)
- N+1 queries
- Large bundle impacts
4. **Testing**
- Adequate test coverage
- Edge cases handled
Provide specific line numbers and suggested fixes for any issues.
Usage:
/review
Example: New Component Command
Create .claude/commands/new-component.md:
Create a new React component named $ARGUMENTS with:
- TypeScript with proper types
- Functional component with hooks
- Tailwind CSS for styling
- Props interface exported
- Comprehensive JSDoc comments
- Vitest test file with basic tests
- Storybook story file
Follow project conventions in CLAUDE.md.
Usage:
/new-component UserProfileCard
Integration with GitHub:
Combine with the gh CLI for automated PR workflows:
# .claude/commands/pr-review.md
1. Fetch PR $ARGUMENTS details using `gh pr view $ARGUMENTS`
2. Review all changed files for issues
3. Post review comments using `gh pr review $ARGUMENTS`
Pro tips:
- Keep commands focused on a single workflow
- Use descriptive names that auto-complete well
- Include context about testing and validation steps
- Reference CLAUDE.md for project-specific conventions
- Version control project commands for team consistency
7. Use Claude's # Key for Quick Memory Addition
During active sessions, you can use the # key to quickly add important instructions, decisions, or patterns directly to your CLAUDE.md file.
How it works:
Press # during a conversation and Claude will:
- Extract key decisions, patterns, or preferences from recent messages
- Add them directly to your CLAUDE.md file for permanent memory
- Make them available for all future sessions (not just the current one)
When to use #:
- After making architectural decisions: "Remember we decided to use Zustand for state management, not Redux"
- When establishing patterns: "Use this error handling pattern for all API calls going forward"
- Project-specific preferences: "Always use functional components with TypeScript strict mode"
- Important context discovered during work: "The legacy payment code in /backend/src/legacy/ should not be modified"
Example workflow:
You: "Let's use Zod for all form validation going forward"
Claude: [Implements first form with Zod]
You: [Press #]
Claude: "I've added 'Use Zod for all form validation' to CLAUDE.md"
You: [In a new session tomorrow] "Add validation to the login form"
Claude: [Uses Zod automatically, because it's now in CLAUDE.md]
Key benefit:
The # key provides a fast way to capture important decisions without manually editing CLAUDE.md. It's like taking permanent notes during pair programming - patterns you discover during one session become part of the project's knowledge base for all future work.
8. Build Custom Workflows with Hooks
Hooks are shell commands that execute automatically in response to Claude Code events, allowing you to build custom workflows and integrations into your development process.
What are hooks:
Callback functions that execute throughout Claude's processing pipeline:
- When you submit a prompt
- When Claude requests user input
- When Claude generates output
- When tool calls are made
- And more lifecycle events
Configuration:
Hooks are defined in your settings file (.claude/settings.json for project or ~/.claude.json for user-level):
{
"hooks": {
"UserPromptSubmit": "echo 'Processing your request...'",
"PreToolUse": "./scripts/log-tool-usage.sh",
"Stop": "say 'Task complete'"
}
}
Real-world examples:
1. Desktop notifications when input needed:
{
"hooks": {
"Notification": [
{
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude Code task completed\" with title \"AI Development\" sound name \"Glass\"'"
}
]
}
]
}
}
2. Log all tool usage for analysis:
#!/bin/bash
echo "$(date): $CLAUDE_TOOL_NAME" >> .claude/tool-usage.log
3. Auto-run tests after code generation:
{
"hooks": {
"Stop": "npm run test:changed"
}
}
4. Track token usage and costs:
#!/bin/bash
# Parse Claude's output and log token counts
echo "$CLAUDE_RESPONSE" | grep -o "tokens: [0-9]*" >> .claude/costs.log
5. Integration with other tools:
- Post to Slack when long-running tasks complete
- Update Linear/Jira tickets automatically
- Trigger CI/CD pipelines
- Generate usage reports
Available hook events:
UserPromptSubmit- When you submit a messagePreToolUse- Before Claude uses a toolPostToolUse- After Claude uses a toolPermissionRequest- When Claude requests permissionStop- When Claude finishes respondingSubagentStop- When a sub-agent completesPreCompact- Before context compactionSessionStart- At session startSessionEnd- At session endNotification- When a notification is sent
Security considerations:
- Hooks run with your shell permissions - be careful what you execute
- Avoid exposing sensitive data in hook scripts
- Version control project hooks, but review them like any code
- Users can override project hooks with user-level settings if needed
Pro tip:
Start simple with notifications, then gradually build more sophisticated workflows as you identify repetitive patterns in your development process.
What's Next
You now have powerful tools to automate workflows and delegate complex tasks. In Part 3: Production-Ready Claude Code, we'll cover the critical topics of shipping AI-generated code safely:
- Test-Driven Development with Claude - How TDD catches hallucinations and provides clear requirements
- Security & Production Readiness - Essential practices for deploying AI-generated code safely
- Quality gates and review processes - Ensuring production-grade code quality
The automation and delegation techniques you've learned in this part will be essential when implementing the production workflows we'll cover next.
← Back to Part 1 | Continue to Part 3 →
Resources:
more articles
Newsletter
Subscribe to get notified about new articles and updates.