[FEATURE] Scenario-Based Model Selection in Claude Code

Resolved 💬 3 comments Opened Nov 13, 2025 by Giorgiosaud Closed Jan 13, 2026

Preflight Checklist

  • [x] I have searched existing requests and this feature hasn't been requested yet
  • [x] This is a single feature request (not multiple features)

Problem Statement

Feature Request: Scenario-Based Model Selection in Claude Code

Summary

Enable automatic model switching based on task phase (planning vs execution) through configuration in claude.md files.

Use Case

As a solution architect, I plan complex implementations requiring Sonnet's reasoning capabilities, but execute well-defined tasks more efficiently with Haiku. Currently, manual model switching mid-workflow breaks context continuity and adds friction.

Proposed Solution

Proposed Solution

1. Configuration Format

In ~/.config/claude/claude.md or project-level claude.md:

## Model Strategy
planning: claude-sonnet-4-5-20250929
execution: claude-haiku-4-20250514
review: claude-sonnet-4-5-20250929

2. Workflow Integration

# Phase 1: Planning (uses Sonnet automatically)
claude plan "Refactor auth module"
# Outputs: detailed plan with architecture decisions

# Phase 2: Manual approval checkpoint
# User reviews plan, then approves

# Phase 3: Execution (switches to Haiku automatically)
claude execute
# Maintains full conversation context
# Executes approved plan with Haiku

3. Key Behaviors

  • Context preservation: Full conversation history passed to new model
  • Explicit phase transitions: claude plan, claude execute, claude review
  • Manual approval gate: Execution waits for explicit user command
  • Fallback: If no scenario-specific model defined, use default

4. In-Chat Commands (Alternative)

/model-plan      # Switch to planning model
/model-execute   # Switch to execution model
/model <name>    # Switch to specific model

Business Value

  • Cost optimization: 60-80% cost reduction on execution tasks
  • Quality maintenance: Complex reasoning uses appropriate model
  • Developer efficiency: No context loss from session switching
  • Workflow clarity: Explicit phase separation improves process discipline

Technical Considerations

  • Configuration hierarchy: global → project → command flag
  • Model availability validation at session start
  • Token budget management across model switches
  • Conversation context serialization between models

MVP Scope

  1. Support planning and execution scenarios only
  2. Single approval checkpoint between phases
  3. Configuration via claude.md only (no CLI flags initially)
  4. Preserve full conversation context on model switch

Success Metrics

  • Developers can complete plan → execute workflows without manual model switching
  • Context preservation rate: 100% (no information loss)
  • Adoption: 40%+ of Claude Code users configure scenario-based models within 3 months

Related Patterns

This aligns with established AI patterns:

  • Agent orchestration (planning vs acting agents)
  • Cost-tiered inference (expensive reasoning, cheap execution)
  • Human-in-the-loop validation gates

Alternative Solutions

Alternative Solution: Automatic Model Selection via claude.md

Problem

Claude Code doesn't support automatic model switching between planning and execution phases. Manual switching breaks context and adds friction.

Proposed Workaround

Use claude.md conventions that Claude naturally interprets during conversation, triggering appropriate behavior without CLI/config changes.

Implementation

1. Global Configuration (~/.config/claude/claude.md)

# Claude Code Behavior Rules

## Model Selection Protocol
When you encounter these phase markers in conversation or task context, adapt your approach:

- **PLANNING PHASE**: Complex architectural decisions, multi-step strategies, ambiguous requirements
  - Recommended: Use your full reasoning capabilities
  - Signal: Tasks with "plan", "design", "architect", "strategy" keywords
  
- **EXECUTION PHASE**: Well-defined implementation, repetitive tasks, code generation from approved plans
  - Recommended: Efficient implementation mode
  - Signal: Tasks with "execute", "implement", "apply", "generate" keywords
  - Context: Previous message contained an approved plan

## Approval Gate
- After generating a plan, ALWAYS ask: "Approve this plan to proceed with execution?"
- Wait for explicit "yes"/"approved"/"execute" before implementing
- If user says "no" or suggests changes, iterate on the plan

## Phase Detection Examples
- "Plan a refactor of the auth module" → PLANNING
- "Execute the plan we discussed" → EXECUTION
- "Implement login with OAuth" (no prior plan) → PLANNING first, then ask approval

2. Project-Level Enhancement (./claude.md)

# Project: [Your Project Name]

## Model Strategy Hints
This project follows a plan-then-execute workflow:
1. Planning generates architecture and approach
2. Manual approval required
3. Execution implements approved plan

When you detect planning work, signal completion with:
"✓ Plan complete. Model recommendation: Switch to Haiku for execution after approval."

When you detect execution work, confirm:
"Executing approved plan from [timestamp/context]."

3. Usage Pattern

# Session 1: Planning
claude "Plan auth refactor with dependency injection"
# Claude responds with plan + recommendation to switch models
# Review plan...

# Session 2: Execution (manual model switch based on Claude's recommendation)
claude --model claude-haiku-4-20250514
# Paste: "Execute the auth refactor plan from our last conversation"
# Claude retrieves context and executes

How It Works

Behavioral guidance, not automation:

  • Claude reads claude.md at session start
  • Interprets instructions as behavioral preferences
  • Signals when model switch would be optimal
  • User manually switches based on Claude's recommendation

Context preservation:

  • Claude's conversation search retrieves prior planning session
  • Explicit reference: "Execute plan from our last conversation"
  • Works because Claude can access conversation history across sessions

Advantages Over Waiting for Feature

Works today - no code changes needed
Flexible - adapt strategy per project
Explicit - you control when to switch
Educational - Claude explains why it recommends each phase

Limitations

❌ Not truly automatic - requires manual model switching
❌ Depends on Claude correctly interpreting phase signals
❌ Context retrieval not guaranteed to be perfect
❌ User must remember to switch models

Incremental Improvement

Add to your global claude.md:

## Meta-Instruction
At the end of planning-phase responses, include:
"💡 **Model Switch Recommendation**: This was planning work. Consider switching to Haiku for execution after approval."

At the start of execution-phase responses, confirm:
"⚙️ **Execution Mode**: Implementing approved plan from [context reference]."

This makes phase transitions explicit and reminds you when to switch models.

When True Automation Arrives

This claude.md structure becomes the configuration format:

## Model Strategy (Future)
planning: claude-sonnet-4-5-20250929
execution: claude-haiku-4-20250514
approval_required: true

Your workflow habits transfer directly - you're already thinking in plan/execute phases.

Reality Check

This is a forcing function, not automation. You're training yourself (and documenting for your team) to think in phases. The real value is workflow discipline, not token savings.

If you find yourself constantly switching models, just use Sonnet for everything. The cognitive overhead of model management often exceeds the cost savings unless you're doing bulk operations.

Priority

Medium - Would be very helpful

Feature Category

Configuration and settings

Use Case Example

_No response_

Additional Context

Use Case Example: Microservice Authentication Refactor

Context

You're a solution architect at Modyo working on a banking application. The client wants to migrate from session-based auth to JWT tokens with Keycloak integration across 5 microservices.

Current Pain Point

This requires both architectural planning (model selection, token flow, caching strategy) AND repetitive implementation (updating each service with nearly identical code).

Using Sonnet for everything wastes tokens on boilerplate. Using Haiku for planning produces shallow architecture.

---

Workflow with Model Switching

Phase 1: Planning (Sonnet 4.5)

claude "Plan migration from session auth to JWT with Keycloak for our 5 microservices. Consider: token validation strategy, caching, error handling, rollback plan."

Claude (Sonnet) Output:

Authentication Migration Plan
=============================

1. Architecture Decision: Offline JWT Validation
   - Each microservice validates tokens locally using Keycloak's public key
   - Avoids network calls on every request
   - Spring Security OAuth2 Resource Server handles validation
   - Cache public keys with 1-hour TTL

2. Caching Strategy
   - User info cached in Redis after first validation
   - Key format: jwt:claims:{user_id}
   - TTL: 15 minutes (matches token expiration)
   - Cache invalidation on logout via event bus

3. Implementation Order
   a. User Service (pilot)
   b. Transaction Service
   c. Account Service
   d. Notification Service
   e. Report Service

4. Rollback Plan
   - Feature flag: auth.jwt.enabled=false
   - Dual-mode support for 2 weeks
   - Session auth remains active during migration

5. Error Handling
   - 401 on expired tokens → redirect to Keycloak
   - 403 on invalid claims → log security event
   - Fallback to session auth if JWT parsing fails

6. Security Considerations
   - HTTPS enforcement
   - Token refresh flow
   - Rate limiting on validation endpoints
   - Audit logging for all auth events

Dependencies:
- spring-boot-starter-oauth2-resource-server
- spring-boot-starter-data-redis
- keycloak-spring-boot-starter

Estimated effort: 3 days per service = 15 days total

💡 **Model Switch Recommendation**: This was planning work requiring architectural reasoning. Consider switching to Haiku for execution after approval to optimize costs.

You review, discuss edge cases, iterate on caching TTL, then approve:

Approved. One change: increase cache TTL to 30 minutes to reduce Redis load.

---

Phase 2: Execution (Haiku 4)

# Exit claude, then restart with Haiku
claude --model claude-haiku-4-20250514

# Reference the approved plan
"Execute the JWT migration plan from our last conversation. Start with User Service. Use the 30-minute cache TTL we agreed on."

Claude (Haiku) retrieves context and outputs:

⚙️ **Execution Mode**: Implementing approved JWT migration plan for User Service.

Step 1/5: Dependencies

File: user-service/pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

File: user-service/src/main/resources/application.yml

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${KEYCLOAK_URL}/realms/${REALM_NAME}
          jwk-set-uri: ${KEYCLOAK_URL}/realms/${REALM_NAME}/protocol/openid-connect/certs
  
  data:
    redis:
      host: ${REDIS_HOST}
      port: 6379

auth:
  jwt:
    enabled: ${JWT_ENABLED:false}
  cache:
    ttl: 1800  # 30 minutes in seconds

File: SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Value("${auth.jwt.enabled}")
    private boolean jwtEnabled;
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        if (jwtEnabled) {
            http.oauth2ResourceServer(oauth2 -> 
                oauth2.jwt(Customizer.withDefaults())
            );
        } else {
            // Fallback to session auth
            http.sessionManagement(session -> 
                session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            );
        }
        
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .anyRequest().authenticated()
            )
            .build();
    }
}

File: UserInfoCacheService.java

@Service
public class UserInfoCacheService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Value("${auth.cache.ttl}")
    private long cacheTtl;
    
    public void cacheUserInfo(String userId, Map<String, Object> claims) {
        String key = "jwt:claims:" + userId;
        redisTemplate.opsForValue().set(key, claims, cacheTtl, TimeUnit.SECONDS);
    }
    
    public Optional<Map<String, Object>> getUserInfo(String userId) {
        String key = "jwt:claims:" + userId;
        return Optional.ofNullable(
            (Map<String, Object>) redisTemplate.opsForValue().get(key)
        );
    }
    
    public void invalidateUserInfo(String userId) {
        String key = "jwt:claims:" + userId;
        redisTemplate.delete(key);
    }
}

[continues with JwtAuthenticationFilter, error handlers, tests...]

✅ User Service implementation complete.
Ready to proceed with Transaction Service? (yes/no)

View original on GitHub ↗

This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗