Conditional Prompts and Decision-Making Patterns for Claude Code Agents
Overview
While Claude Code doesn’t support explicit if/else syntax within prompts, agents can make sophisticated decisions through structured natural language instructions. This guide explores patterns and best practices for creating prompts that enable dynamic, scenario-based agent behavior.
Core Concepts
Decision Flow Architecture
Instead of traditional conditional statements, Claude Code uses:
- Structured task sequences - Numbered steps that guide agent workflow
- Natural language conditions - Instructions that describe when to take specific actions
- Tool-based decision points - Using tool outputs to determine next steps
- Analysis criteria - Clear guidelines for evaluating situations
Agent Decision-Making Process
graph TD A[User Request] --> B[Agent Analyzes Prompt] B --> C{Tool Selection} C --> D[Execute Tool] D --> E[Evaluate Result] E --> F{Condition Met?} F -->|Yes| G[Execute Action A] F -->|No| H{Alternative Condition?} H -->|Yes| I[Execute Action B] H -->|No| J[Default Action] G --> K[Final Output] I --> K J --> K
Pattern Library
1. Sequential Decision Pattern
Use numbered steps to create a decision tree:
prompt: |
You are a code migration assistant. Follow these steps:
1. Scan the project structure using `ls` and `find`
2. Identify the framework version:
- If package.json exists, check dependencies
- If requirements.txt exists, check Python versions
- If go.mod exists, check Go version
3. Based on the framework:
- For React < 18: Apply legacy migration patterns
- For React >= 18: Use modern hooks migration
- For Vue 2: Suggest Vue 3 migration path
4. Generate migration report with specific recommendations2. Conditional Tool Usage Pattern
Guide tool selection based on context:
prompt: |
Analyze the codebase for performance issues:
INITIAL SCAN:
- Use `grep` to find common performance anti-patterns
- If you find console.log statements in production code, flag them
- If you find synchronous file operations, mark for async conversion
DEEP ANALYSIS (only if issues found):
- Use the Agent tool to analyze component render cycles
- Search for unnecessary re-renders
- Check for missing memoization opportunities
SKIP if no issues found in initial scan3. Multi-Criteria Decision Pattern
Combine multiple factors for complex decisions:
prompt: |
Evaluate pull request readiness:
CRITERIA CHECK:
1. Test Coverage:
- Run test suite and check coverage
- If coverage < 80%, request additional tests
- If coverage >= 80%, proceed to next check
2. Code Quality:
- Run linter and type checker
- If errors exist, list them for fixing
- If warnings only, note but don't block
3. Documentation:
- Check if README is updated
- Verify inline comments for complex logic
- If missing, generate documentation suggestions
FINAL DECISION:
- All criteria pass: Mark as ready for review
- Minor issues only: Approve with comments
- Major issues: Request changes with specific feedback4. Error Handling Decision Pattern
Build resilience through conditional error handling:
prompt: |
Deploy application with fallback strategies:
1. Attempt primary deployment method:
- Run deployment script
- Monitor for success signals
2. If deployment fails:
- Analyze error logs for specific failure types
- Database connection error: Check connection strings
- Permission denied: Verify credentials
- Timeout: Increase limits and retry
3. If retry fails:
- Rollback to previous version
- Generate incident report
- Suggest manual intervention steps5. Context-Aware Branching Pattern
Adapt behavior based on project context:
prompt: |
Implement authentication based on project type:
DETECT PROJECT TYPE:
- Check for framework indicators (Next.js, Express, Django)
- Identify existing auth implementations
IMPLEMENTATION STRATEGY:
- Next.js App: Use NextAuth with app directory
- Next.js Pages: Use NextAuth with pages directory
- Express API: Implement JWT middleware
- Django: Use Django REST framework auth
- No framework detected: Ask user for preference
For each implementation:
- Generate appropriate boilerplate
- Configure environment variables
- Create example protected routesBest Practices
1. Clear Role Definition
Always start prompts with explicit role and goal statements:
You are a [role] responsible for [specific task].
Your goal is to [desired outcome] by [method/approach].
2. Explicit Tool Guidance
List available tools and when to use them:
Available tools:
- `grep`: Use for searching code patterns
- `Agent`: Use for complex multi-file analysis
- `bash`: Use for running tests and builds
Tool selection criteria:
- If searching across many files: Use Agent
- If checking specific patterns: Use grep
- If executing commands: Use bash
3. Structured Analysis Criteria
Define what to look for and how to evaluate:
Analyze the code considering:
1. Performance implications
2. Security vulnerabilities
3. Code maintainability
4. Test coverage
Rate each aspect as: Critical, Important, or Minor
4. Action Constraints
Specify what agents should and shouldn’t do:
ALLOWED ACTIONS:
- Modify existing files
- Create new test files
- Update documentation
FORBIDDEN ACTIONS:
- Delete files without confirmation
- Modify configuration without backup
- Expose sensitive information
5. Fallback Strategies
Always include default behaviors:
If unable to determine the appropriate action:
1. Summarize what was found
2. List possible options
3. Request user guidance
4. Do NOT make assumptions
Advanced Patterns
Dynamic Prompt Composition
Use slash commands with arguments for flexible conditions:
# .claude/commands/review.md
Review code with focus on $ARGUMENTS
If focus is "security":
- Check for SQL injection vulnerabilities
- Verify input validation
- Review authentication logic
If focus is "performance":
- Identify N+1 queries
- Check for unnecessary computations
- Review caching strategies
If focus is "style":
- Check naming conventions
- Verify consistent formatting
- Review code organizationState Machine Pattern
Create stateful workflows through prompt chaining:
# Initial prompt
prompt: |
Begin refactoring process:
1. Analyze current code structure
2. Identify refactoring opportunities
3. Create TODO list for changes
Mark first task as "in_progress"
# Follow-up prompts based on state
continuation_prompt: |
Check TODO list status:
- If tasks remain: Continue with next task
- If all complete: Generate summary report
- If blocked: Document blockers and suggest solutionsHierarchical Decision Trees
Build complex decision logic through nested conditions:
prompt: |
Database migration assistant:
LEVEL 1: Determine database type
- PostgreSQL: Check version compatibility
- MySQL: Verify charset settings
- MongoDB: Assess schema flexibility needs
LEVEL 2: Based on database type
PostgreSQL:
- Version < 12: Use legacy migration tools
- Version >= 12: Use native partitioning
- If using extensions: Verify compatibility
MySQL:
- If charset issues: Generate conversion scripts
- If foreign keys exist: Order migrations properly
- If triggers present: Handle separately
LEVEL 3: Execute appropriate migration strategyCommon Pitfalls and Solutions
Pitfall 1: Ambiguous Conditions
Problem: Vague instructions lead to inconsistent behavior Solution: Use specific, measurable criteria
# Bad
"If the code looks complex, refactor it"
# Good
"If a function exceeds 50 lines OR has cyclomatic complexity > 10, refactor it"Pitfall 2: Missing Fallbacks
Problem: Agent gets stuck when conditions aren’t met Solution: Always include else/default cases
# Include explicit fallback
"If no matching pattern found:
1. Log the unexpected case
2. Ask for user guidance
3. Document for future reference"Pitfall 3: Tool Overload
Problem: Too many tool options confuse decision-making Solution: Prioritize and constrain tool usage
"For file searching:
- First try: Use grep for quick pattern matching
- If no results: Use Agent for semantic search
- Last resort: Ask user for file location"Testing Conditional Prompts
Scenario Testing Checklist
- Test all primary condition branches
- Verify edge case handling
- Confirm fallback behaviors work
- Check tool selection logic
- Validate output constraints
Example Test Cases
test_scenarios:
- name: "Empty project"
condition: "No files found"
expected: "Request project initialization"
- name: "Mixed framework"
condition: "Multiple frameworks detected"
expected: "Ask user to specify primary framework"
- name: "Error state"
condition: "Tool execution fails"
expected: "Graceful degradation with error report"Integration with Claude Code Features
With Hooks
Combine conditional prompts with hooks for dynamic behavior:
# pre-commit hook that adjusts agent behavior
if [[ $(git diff --cached --name-only | grep -E '\.(ts|tsx)$') ]]; then
echo "TypeScript files detected - enforcing strict type checking"
else
echo "No TypeScript files - skipping type validation"
fiWith Memory Files
Use memory files to maintain decision context:
# CLAUDE.md
PROJECT_TYPE: next-app-router
TESTING_FRAMEWORK: jest
STYLE_GUIDE: airbnb
# Prompt references memory
"Check CLAUDE.md for project configuration.
Based on PROJECT_TYPE, apply appropriate patterns..."With Extended Thinking
Leverage thinking mode for complex decisions:
prompt: |
[think harder about architecture decisions]
Evaluate multiple architectural approaches:
1. Analyze current system constraints
2. Consider future scalability needs
3. Weigh tradeoffs between options
4. Make recommendation with detailed reasoningReal-World Examples
Example 1: CI/CD Pipeline Decisions
Source: https://github.com/anthropics/claude-code
name: Conditional Deployment
prompt: |
Analyze build results and determine deployment strategy:
1. Check test results:
- All pass: Continue to deployment
- Flaky tests: Retry once, then evaluate
- Consistent failures: Block deployment
2. Evaluate deployment target:
- If main branch: Deploy to production
- If develop branch: Deploy to staging
- If feature branch: Deploy to preview
3. Post-deployment validation:
- Run smoke tests
- If failures: Initiate rollback
- If success: Update deployment statusExample 2: Code Review Automation
prompt: |
Review pull request #${{ github.event.pull_request.number }}:
QUICK CHECKS:
- File count > 50: Flag as "needs-breakdown"
- Has tests: Label "has-tests"
- No tests: Label "needs-tests"
DEEP ANALYSIS (if file count < 20):
- Check for code smells
- Verify naming conventions
- Assess test coverage
SECURITY SCAN (if touches auth/ or api/):
- Check for exposed secrets
- Verify input validation
- Review permission checks
Generate review comment with findingsConclusion
Conditional prompts in Claude Code enable sophisticated agent behavior through structured natural language instructions rather than explicit programming constructs. By following these patterns and best practices, you can create agents that make intelligent decisions, handle edge cases gracefully, and adapt to different scenarios effectively.