Project 22: Dynamic Output Style - Context-Aware Response Formatting
Project 22: Dynamic Output Style - Context-Aware Response Formatting
Build a dynamic output style system that automatically switches Claudeโs behavior based on detected context: coding mode (concise), learning mode (explanatory with analogies), and review mode (critical and detailed).
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Advanced (Level 3) |
| Time Estimate | 2 weeks |
| Language | Python + Markdown (Alternative: Bun/TypeScript + Markdown) |
| Prerequisites | Project 21 completed, hook experience from Projects 1-8, understanding of intent classification |
| Key Topics | Output styles, hooks, context detection, dynamic behavior, user experience |
| Claude Code Features | Output Styles, UserPromptSubmit Hook, environment variables |
1. Learning Objectives
By completing this project, you will:
- Master context-aware AI behavior: Design systems that automatically adapt to user intent without explicit mode selection
- Implement intent classification: Build pattern-matching and keyword detection for natural language understanding
- Integrate hooks with output styles: Combine Claude Codeโs hook system with output styles for dynamic behavior
- Design seamless user experiences: Create mode switching that feels natural and helpful, not jarring
- Handle ambiguity and edge cases: Build robust systems that gracefully handle unclear or multi-intent prompts
- Implement state persistence: Maintain mode context across multiple prompts when appropriate
2. Deep Theoretical Foundation
2.1 The Problem with Static Styles
Static output styles (like Project 21) work well for dedicated use cases, but developers switch contexts constantly:
A TYPICAL DEVELOPER SESSION
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 9:00 "explain how React hooks work" โ LEARNING โ
โ โ
โ 9:15 "fix the bug in useEffect" โ CODING โ
โ โ
โ 9:30 "review this pull request" โ REVIEW โ
โ โ
โ 9:45 "why is this pattern bad?" โ LEARNING โ
โ โ
โ 10:00 "add error handling here" โ CODING โ
โ โ
โ 10:15 "is this approach secure?" โ REVIEW โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Problem: Constantly running `--output-style coding`, then
`--output-style learning`, then `--output-style review`
is tedious and breaks flow.
The Solution: A system that automatically detects context and switches styles dynamically.
2.2 Intent Classification Fundamentals
Intent classification is the process of determining what a user wants to accomplish from their natural language input.
INTENT CLASSIFICATION PIPELINE
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER PROMPT โ
โ "explain how async/await works in JavaScript" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PREPROCESSING โ
โ โ
โ 1. Lowercase: "explain how async/await works in javascript" โ
โ 2. Tokenize: ["explain", "how", "async/await", "works", ...] โ
โ 3. Remove noise: ["explain", "async/await", "works"] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PATTERN MATCHING โ
โ โ
โ LEARNING patterns: โ "explain" matches ["explain", "how", โ
โ "why", "what is", "teach me"] โ
โ โ
โ CODING patterns: โ No match for ["fix", "implement", โ
โ "add", "create", "update"] โ
โ โ
โ REVIEW patterns: โ No match for ["review", "check", โ
โ "audit", "analyze", "critique"] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLASSIFICATION RESULT โ
โ โ
โ Detected Intent: LEARNING โ
โ Confidence: HIGH (direct keyword match) โ
โ โ
โ Action: Apply learning output style โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
2.3 Mode Definitions
Each mode has distinct characteristics:
MODE CHARACTERISTICS
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LEARNING MODE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Purpose: Teach concepts, build understanding โ
โ โ
โ Characteristics: โ
โ โข Uses analogies and metaphors โ
โ โข Provides step-by-step explanations โ
โ โข Includes beginner-friendly examples โ
โ โข Asks follow-up questions โ
โ โข Longer, more detailed responses โ
โ โ
โ Trigger Keywords: โ
โ "explain", "how does", "why does", "what is", "teach me", โ
โ "help me understand", "I don't get", "confused about" โ
โ โ
โ Example Response Style: โ
โ "Imagine you're ordering food at a restaurant..." โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CODING MODE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Purpose: Get things done, minimal explanation โ
โ โ
โ Characteristics: โ
โ โข Concise, action-oriented โ
โ โข Code first, explanation second โ
โ โข Minimal prose, maximum utility โ
โ โข Uses standard coding conventions โ
โ โข Shows diffs when applicable โ
โ โ
โ Trigger Keywords: โ
โ "fix", "implement", "add", "create", "update", "refactor", โ
โ "change", "modify", "write", "build", "make" โ
โ โ
โ Example Response Style: โ
โ "Looking at auth.ts:47... Fixed the race condition." โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REVIEW MODE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Purpose: Critical analysis, identify issues โ
โ โ
โ Characteristics: โ
โ โข Systematic evaluation โ
โ โข Lists pros and cons โ
โ โข Rates severity of issues โ
โ โข Suggests improvements โ
โ โข References best practices โ
โ โ
โ Trigger Keywords: โ
โ "review", "check", "audit", "analyze", "critique", "assess", โ
โ "evaluate", "is this good", "what's wrong", "improve" โ
โ โ
โ Example Response Style: โ
โ "Code Review - 3 issues found: 1 critical, 2 minor..." โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
2.4 Hook-Style Integration Architecture
The UserPromptSubmit hook runs before each prompt is sent to Claude, making it perfect for context detection:
DYNAMIC STYLE ARCHITECTURE
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ USER PROMPT: "explain how promises work" โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ UserPromptSubmit HOOK โ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ INTENT DETECTOR โ โ
โ โ โ โ
โ โ Input: "explain how promises work" โ โ
โ โ โ โ
โ โ Pattern Match: โ โ
โ โ โ "explain" โ LEARNING โ โ
โ โ โ "fix/implement" โ CODING (no match) โ โ
โ โ โ "review/check" โ REVIEW (no match) โ โ
โ โ โ โ
โ โ Result: LEARNING MODE โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ PROMPT AUGMENTER โ โ
โ โ โ โ
โ โ Original: "explain how promises work" โ โ
โ โ โ โ
โ โ Augmented: โ โ
โ โ "[Mode: LEARNING] โ โ
โ โ โ โ
โ โ explain how promises work โ โ
โ โ โ โ
โ โ [System: Use educational style with analogies, โ โ
โ โ step-by-step explanations, and examples]" โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLAUDE โ
โ โ
โ Receives augmented prompt with style context โ
โ Responds in LEARNING mode โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
2.5 Handling Ambiguity
Not all prompts clearly indicate intent. Your system must handle edge cases:
AMBIGUITY RESOLUTION
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLEAR INTENT โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ "explain how React hooks work" โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Keywords: "explain", "how" โ
โ Intent: LEARNING (high confidence) โ
โ Action: Apply learning mode โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MIXED INTENT โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ "review this code and explain what's wrong" โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Keywords: "review" (REVIEW), "explain" (LEARNING) โ
โ Conflict: Two modes detected โ
โ โ
โ Resolution Strategy: โ
โ 1. First keyword wins: REVIEW โ
โ OR โ
โ 2. Priority ordering: REVIEW > LEARNING โ
โ OR โ
โ 3. Hybrid mode: REVIEW with explanations โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NO CLEAR INTENT โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ "async/await in JavaScript" โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Keywords: None matched โ
โ Intent: UNKNOWN โ
โ โ
โ Resolution Strategy: โ
โ 1. Default to CODING (developer context) โ
โ 2. Analyze file context (if in .md file, maybe LEARNING) โ
โ 3. Use previous mode (state persistence) โ
โ 4. Ask for clarification (may break flow) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NEGATION โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ "fix the bug, don't explain, just do it" โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Keywords: "fix" (CODING), "explain" (LEARNING, negated) โ
โ Intent: CODING (explicitly rejecting LEARNING) โ
โ โ
โ Detection Strategy: โ
โ Check for negation words: "don't", "no need to", "skip", โ
โ "just", "without" before style keywords โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
2.6 User Experience Considerations
From โDesigning for Behavior Changeโ (Stephen Wendel), effective behavior-adaptive systems must:
- Be Predictable: Users should understand why the mode changed
- Allow Override: Users must be able to force a specific mode
- Communicate Changes: Subtle indicators show the current mode
- Minimize Disruption: Mode switches should feel natural, not jarring
UX DESIGN PRINCIPLES
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MODE INDICATOR โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Subtle but visible mode indication: โ
โ โ
โ You: explain how promises work โ
โ โ
โ Claude: [Auto-detected: LEARNING mode] โ
โ โ
โ ๐ Understanding JavaScript Promises โ
โ ... โ
โ โ
โ Benefits: โ
โ โข User knows what mode is active โ
โ โข User can correct if detection was wrong โ
โ โข Creates consistent expectation โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MANUAL OVERRIDE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Allow explicit mode selection with prefixes: โ
โ โ
โ /learn promises in javascript โ
โ /code fix the auth bug โ
โ /review check this pull request โ
โ โ
โ Override takes precedence over auto-detection โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STICKY MODE (Optional) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Persist mode across prompts: โ
โ โ
โ You: /learn โ
โ Claude: [Mode locked: LEARNING until /auto] โ
โ โ
โ You: promises โ
โ Claude: [LEARNING mode] ๐ Understanding Promises... โ
โ โ
โ You: async/await โ
โ Claude: [LEARNING mode] ๐ Understanding Async/Await... โ
โ โ
โ You: /auto โ
โ Claude: [Mode: AUTO-DETECT resumed] โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
3. The Core Question Youโre Answering
โHow can I make Claude automatically adjust its communication style based on what Iโm trying to do?โ
Static output styles require manual switching. This project creates an intelligent system that detects intent and adapts behavior automatically, creating a more natural workflow.
4. Concepts You Must Understand First
Stop and research these before coding:
4.1 Intent Detection
- How do you determine if a prompt is learning vs coding?
- What keywords/patterns indicate each mode?
- How accurate does detection need to be?
- Reference: NLP intent classification, regular expressions
4.2 Hook-Style Integration
- Can hooks modify which output style is used?
- How do you inject style context via UserPromptSubmit?
- What about using environment variables?
- Reference: Claude Code Docs - Hooks
4.3 User Experience
- Should mode switches be announced?
- Can users override auto-detection?
- How to handle ambiguous prompts?
- Reference: โDonโt Make Me Thinkโ by Steve Krug
4.4 State Management
- Should mode persist across prompts?
- How do you store state between hook invocations?
- What about session state?
5. Questions to Guide Your Design
Before implementing, think through these:
5.1 What Modes to Support?
| Mode | Purpose | Response Style |
|---|---|---|
| CODING | Get things done | Concise, code-focused, minimal explanation |
| LEARNING | Understand concepts | Explanatory, analogies, step-by-step |
| REVIEW | Evaluate quality | Critical, detailed, suggestions |
| CASUAL | General chat | Friendly, conversational (optional) |
5.2 How to Detect Each Mode?
MODES = {
"learning": ["explain", "how does", "why does", "teach me", "understand"],
"review": ["review", "check", "audit", "analyze", "critique"],
"coding": ["fix", "implement", "add", "create", "update", "refactor"],
}
5.3 How to Switch Styles?
Options:
- Modify prompt with style context (inject instructions)
- Set environment variable for style selection
- Use different output style files dynamically
6. Thinking Exercise
Design the Detection Logic
Create a decision tree for mode detection:
User Prompt
โ
โโโ Manual override prefix (/learn, /code, /review)?
โ โโโ YES โ Use specified mode
โ
โโโ Contains negation before style keyword?
โ โโโ YES โ Skip that mode pattern
โ
โโโ Contains "explain/how/why/teach"?
โ โโโ YES โ LEARNING MODE
โ
โโโ Contains "fix/implement/add/create"?
โ โโโ YES โ CODING MODE
โ
โโโ Contains "review/check/audit/analyze"?
โ โโโ YES โ REVIEW MODE
โ
โโโ DEFAULT โ CODING MODE (developer context)
Design Questions:
- What if a prompt matches multiple modes?
- Priority ordering?
- First match wins?
- Hybrid mode?
- How do you handle negations (โdonโt explain, just fixโ)?
- Pattern: negation_word + style_keyword = skip that mode
- Should mode persist across prompts or reset each time?
- Consider: context continuation vs. fresh start
7. Real World Outcome
7.1 Example Session
You: explain how promises work in javascript
Claude: [Auto-detected: LEARNING mode]
๐ Understanding JavaScript Promises
Imagine you're ordering food at a restaurant. A Promise is like the
waiter saying "Your food will be ready soon" - it's a commitment to
give you something in the future.
**The Three States**:
1. **Pending** - The kitchen is cooking (waiting for result)
2. **Fulfilled** - Your food arrived! (success)
3. **Rejected** - Kitchen is out of ingredients (error)
```javascript
// Simple example
const orderFood = new Promise((resolve, reject) => {
// Kitchen is cooking...
if (ingredientsAvailable) {
resolve("Pizza is ready!"); // Fulfilled
} else {
reject("Sorry, we're out of cheese"); // Rejected
}
});
Want me to explain .then() and .catch() next?
You: fix the bug in auth.ts
Claude: [Auto-detected: CODING mode]
Looking at auth.ts:47โฆ
The issue is a race condition in token refresh:
// Before (buggy)
if (isExpired(token)) {
token = await refreshToken(); // Multiple calls can overlap
}
// After (fixed)
if (isExpired(token) && !refreshInProgress) {
refreshInProgress = true;
try {
token = await refreshToken();
} finally {
refreshInProgress = false;
}
}
Changed auth.ts
You: review the error handling in this function
Claude: [Auto-detected: REVIEW mode]
Code Review: Error Handling Analysis
Summary
| Severity | Count | |โโโ-|โโ-| | Critical | 1 | | Warning | 2 | | Info | 1 |
Issues Found
[CRITICAL] Line 23: Unhandled Promise Rejection
const data = await fetchUser(id); // No try-catch
Risk: Crashes the application on network failure.
[WARNING] Line 45: Generic Error Message
throw new Error("Something went wrong");
Suggestion: Use descriptive error messages for debugging.
[WARNING] Line 67: Missing Error Type Check
catch (e) {
console.log(e); // e could be anything
}
Suggestion: Check if e is an Error instance.
Recommendations
- Wrap async calls in try-catch blocks
- Create custom error classes for different failure modes
- Log errors with context (request ID, user ID, etc.)
You: /learn async/await (manual override)
Claude: [Mode: LEARNING (manual)]
๐ Understanding Async/Await
Think of async/await as a way to write โwait for this to finishโ in a readable wayโฆ
---
## 8. The Interview Questions They'll Ask
1. **"How would you create an adaptive AI assistant that changes behavior based on context?"**
- Discuss intent classification, pattern matching, and prompt augmentation
- Explain the trade-offs between automatic detection and user control
2. **"What's intent classification and how would you implement it?"**
- Keyword-based: Simple, fast, limited understanding
- ML-based: More accurate, requires training data
- Hybrid: Keywords for clear cases, ML for ambiguous ones
3. **"How do you balance automatic behavior with user control?"**
- Always provide manual override
- Show current mode to set expectations
- Make it easy to correct wrong detection
4. **"What are the UX considerations for automatic mode switching?"**
- Predictability: Users should understand why mode changed
- Visibility: Show current mode
- Override: Easy to force specific mode
- Consistency: Same prompt should produce same mode
5. **"How would you handle edge cases in intent detection?"**
- Ambiguous prompts: Default mode or ask for clarification
- Conflicting signals: Priority ordering
- Negation: Pattern matching for "don't", "no need to"
---
## 9. Hints in Layers
**Hint 1: Create Mode-Specific Styles**
Start by creating three separate output style files:
- `~/.claude/output-styles/coding.md`
- `~/.claude/output-styles/learning.md`
- `~/.claude/output-styles/review.md`
**Hint 2: UserPromptSubmit for Detection**
Use a hook to analyze the prompt and inject mode context:
```python
# .claude/hooks/detect_mode.py
import json
import sys
payload = json.loads(sys.stdin.read())
prompt = payload["prompt"].lower()
# Detect mode
if any(kw in prompt for kw in ["explain", "how does", "teach me"]):
mode = "learning"
elif any(kw in prompt for kw in ["review", "check", "analyze"]):
mode = "review"
else:
mode = "coding"
# Augment prompt with mode context
result = {"modified_prompt": f"[Mode: {mode.upper()}]\n\n{prompt}"}
print(json.dumps(result))
Hint 3: Environment Variable Approach
Set CLAUDE_OUTPUT_STYLE via hook to switch styles dynamically:
import os
os.environ["CLAUDE_OUTPUT_STYLE"] = mode
Hint 4: Allow Manual Override
Recognize prefixes like /learn, /code, /review for explicit mode selection:
if prompt.startswith("/learn"):
mode = "learning"
prompt = prompt[6:].strip() # Remove prefix
elif prompt.startswith("/code"):
mode = "coding"
prompt = prompt[5:].strip()
10. Complete Implementation
10.1 Output Style Files
Create three style files:
~/.claude/output-styles/learning.md
---
name: learning
description: Educational mode with analogies and step-by-step explanations
keep-coding-instructions: true
---
# Learning Mode
You are in learning mode. Your goal is to help the user understand concepts deeply.
## Response Style
- Start with a relatable analogy or metaphor
- Break complex concepts into digestible steps
- Use visual examples when helpful
- Include beginner-friendly code examples with extensive comments
- End with a follow-up question to encourage deeper exploration
## Format
- Use emoji indicators for sections (๐ for concepts, ๐ก for tips, โ ๏ธ for warnings)
- Keep paragraphs short (2-3 sentences max)
- Use bullet points for lists
- Include "Why it matters" sections
## Never Do
- Assume prior knowledge without checking
- Use jargon without explanation
- Skip the "why" behind concepts
- Provide code without explanation
## Example Response Opening
"๐ Understanding [Concept]
Imagine you're [relatable analogy]. [Concept] works similarly because..."
~/.claude/output-styles/coding.md
---
name: coding
description: Concise coding mode focused on action and efficiency
keep-coding-instructions: true
---
# Coding Mode
You are in coding mode. Your goal is to help the user get things done efficiently.
## Response Style
- Be concise and action-oriented
- Show code first, explanation second (if needed at all)
- Use the minimum words necessary
- Show file changes clearly with line numbers
- Confirm actions taken with checkmarks
## Format
- Start with the action: "Looking at [file]:[line]..."
- Show code changes as before/after diffs
- End with confirmation: "Changed [file] โ"
## Never Do
- Over-explain simple changes
- Use flowery language
- Include unnecessary context
- Repeat information the user already knows
## Example Response
"Looking at auth.ts:47...
The issue is [brief description]:
```typescript
// Before
[old code]
// After
[new code]
Changed auth.ts โโ
**~/.claude/output-styles/review.md**
```yaml
---
name: review
description: Critical review mode with structured analysis and suggestions
keep-coding-instructions: true
---
# Review Mode
You are in review mode. Your goal is to provide thorough, critical analysis.
## Response Style
- Be systematic and thorough
- Categorize findings by severity (Critical, Warning, Info)
- Provide specific line numbers and code references
- Suggest concrete improvements
- Reference best practices and standards
## Format
Use this structure:
Code Review: [Topic]
Summary
| Severity | Count | |โโโ-|โโ-| | Critical | X | | Warning | Y | | Info | Z |
Issues Found
[SEVERITY] Line XX: Description
problematic code
Risk: Why this is a problem. Suggestion: How to fix it.
Recommendations
- Prioritized list of improvements ```
Always Include
- Severity ratings for each issue
- Line numbers for code references
- Concrete suggestions (not just โimprove thisโ)
- A summary table
Never Do
- Be vague about issues
- Skip the positive aspects
- Forget to suggest improvements
- Use subjective language without justification ```
10.2 Hook for Mode Detection
Create the hook at .claude/hooks/detect_mode.py:
#!/usr/bin/env python3
"""
Dynamic mode detection hook for Claude Code.
This hook analyzes user prompts and injects context for
automatic style switching between LEARNING, CODING, and REVIEW modes.
"""
import json
import sys
import re
from typing import Optional, Tuple
# Mode definitions with patterns
MODES = {
"learning": {
"patterns": [
r"\bexplain\b", r"\bhow does\b", r"\bwhy does\b",
r"\bwhat is\b", r"\bteach me\b", r"\bhelp me understand\b",
r"\bi don'?t get\b", r"\bconfused about\b", r"\bwhat are\b",
r"\btell me about\b", r"\bwalk me through\b"
],
"style_context": """[System: Use LEARNING style.
- Start with a relatable analogy
- Break concepts into steps
- Include beginner-friendly examples
- End with a follow-up question]"""
},
"review": {
"patterns": [
r"\breview\b", r"\bcheck\b", r"\baudit\b", r"\banalyze\b",
r"\bcritique\b", r"\bassess\b", r"\bevaluate\b",
r"\bis this good\b", r"\bwhat'?s wrong\b", r"\bimprove\b",
r"\bfeedback\b", r"\blook over\b"
],
"style_context": """[System: Use REVIEW style.
- Be systematic and thorough
- Categorize by severity (Critical, Warning, Info)
- Provide specific line numbers
- Suggest concrete improvements]"""
},
"coding": {
"patterns": [
r"\bfix\b", r"\bimplement\b", r"\badd\b", r"\bcreate\b",
r"\bupdate\b", r"\brefactor\b", r"\bchange\b", r"\bmodify\b",
r"\bwrite\b", r"\bbuild\b", r"\bmake\b", r"\bgenerate\b",
r"\bremove\b", r"\bdelete\b"
],
"style_context": """[System: Use CODING style.
- Be concise and action-oriented
- Show code first, explanation second
- Use minimum words necessary
- Confirm actions with checkmarks]"""
}
}
# Negation patterns that cancel following mode keywords
NEGATION_PATTERNS = [
r"\bdon'?t\s+", r"\bno need to\s+", r"\bskip\s+",
r"\bwithout\s+", r"\bjust\s+", r"\bonly\s+"
]
# Manual override prefixes
OVERRIDE_PREFIXES = {
"/learn": "learning",
"/code": "coding",
"/review": "review",
"/auto": None # Resume auto-detection
}
def check_manual_override(prompt: str) -> Tuple[Optional[str], str]:
"""Check for manual mode override prefixes."""
prompt_lower = prompt.lower().strip()
for prefix, mode in OVERRIDE_PREFIXES.items():
if prompt_lower.startswith(prefix):
# Remove prefix and return mode
remaining = prompt[len(prefix):].strip()
return mode, remaining
return None, prompt
def has_negation_before(prompt: str, pattern: str) -> bool:
"""Check if a negation word appears before the pattern."""
match = re.search(pattern, prompt, re.IGNORECASE)
if not match:
return False
text_before = prompt[:match.start()].lower()
for neg_pattern in NEGATION_PATTERNS:
if re.search(neg_pattern + r".*$", text_before):
return True
return False
def detect_mode(prompt: str) -> str:
"""Detect the appropriate mode based on prompt content."""
prompt_lower = prompt.lower()
# Score each mode based on pattern matches
scores = {}
for mode, config in MODES.items():
score = 0
for pattern in config["patterns"]:
if re.search(pattern, prompt_lower):
# Check for negation
if not has_negation_before(prompt_lower, pattern):
score += 1
scores[mode] = score
# Return mode with highest score, default to coding
if max(scores.values()) == 0:
return "coding" # Default for developers
return max(scores, key=scores.get)
def format_mode_indicator(mode: str, is_override: bool) -> str:
"""Format the mode indicator for display."""
mode_icons = {
"learning": "๐",
"coding": "๐ป",
"review": "๐"
}
icon = mode_icons.get(mode, "")
source = "(manual)" if is_override else "(auto-detected)"
return f"[Mode: {mode.upper()} {source}] {icon}"
def main():
# Read input from Claude Code
payload = json.loads(sys.stdin.read())
prompt = payload.get("prompt", "")
# Check for manual override
override_mode, clean_prompt = check_manual_override(prompt)
if override_mode is not None:
mode = override_mode
is_override = True
prompt = clean_prompt
else:
mode = detect_mode(prompt)
is_override = False
# Get style context
style_context = MODES.get(mode, MODES["coding"])["style_context"]
# Build augmented prompt
mode_indicator = format_mode_indicator(mode, is_override)
augmented_prompt = f"""{mode_indicator}
{prompt}
{style_context}"""
# Output modified prompt
result = {
"modified_prompt": augmented_prompt
}
print(json.dumps(result))
if __name__ == "__main__":
main()
10.3 Hook Configuration
Add to .claude/hooks.json:
{
"hooks": {
"UserPromptSubmit": [
{
"command": "python3 .claude/hooks/detect_mode.py",
"description": "Detect user intent and apply dynamic output style"
}
]
}
}
10.4 Testing Script
Create a test script at .claude/test_detect_mode.py:
#!/usr/bin/env python3
"""Test cases for mode detection."""
import json
import subprocess
TEST_CASES = [
# Learning mode tests
{"prompt": "explain how React hooks work", "expected": "LEARNING"},
{"prompt": "how does async/await work?", "expected": "LEARNING"},
{"prompt": "teach me about promises", "expected": "LEARNING"},
{"prompt": "why does this pattern exist?", "expected": "LEARNING"},
# Coding mode tests
{"prompt": "fix the bug in auth.ts", "expected": "CODING"},
{"prompt": "implement user registration", "expected": "CODING"},
{"prompt": "add error handling here", "expected": "CODING"},
{"prompt": "refactor this function", "expected": "CODING"},
# Review mode tests
{"prompt": "review this pull request", "expected": "REVIEW"},
{"prompt": "check my error handling", "expected": "REVIEW"},
{"prompt": "analyze this code for issues", "expected": "REVIEW"},
{"prompt": "is this approach secure?", "expected": "REVIEW"},
# Negation tests
{"prompt": "don't explain, just fix the bug", "expected": "CODING"},
{"prompt": "skip the explanation and implement it", "expected": "CODING"},
{"prompt": "just add the feature", "expected": "CODING"},
# Manual override tests
{"prompt": "/learn promises", "expected": "LEARNING"},
{"prompt": "/code fix this", "expected": "CODING"},
{"prompt": "/review the auth module", "expected": "REVIEW"},
# Ambiguous/default tests
{"prompt": "promises in JavaScript", "expected": "CODING"}, # Default
{"prompt": "auth module", "expected": "CODING"}, # Default
]
def run_test(prompt: str, expected: str) -> bool:
"""Run a single test case."""
# Create payload
payload = json.dumps({"prompt": prompt})
# Run the hook
result = subprocess.run(
["python3", ".claude/hooks/detect_mode.py"],
input=payload,
capture_output=True,
text=True
)
output = json.loads(result.stdout)
modified = output.get("modified_prompt", "")
# Check if expected mode is in output
mode_line = modified.split("\n")[0]
detected = expected in mode_line
return detected
def main():
print("Running mode detection tests...\n")
passed = 0
failed = 0
for test in TEST_CASES:
prompt = test["prompt"]
expected = test["expected"]
result = run_test(prompt, expected)
status = "โ" if result else "โ"
print(f"{status} '{prompt[:40]}...' โ {expected}")
if result:
passed += 1
else:
failed += 1
print(f"\n{passed}/{len(TEST_CASES)} tests passed")
if failed > 0:
print(f"{failed} tests failed")
return 1
return 0
if __name__ == "__main__":
exit(main())
11. Books That Will Help
| Topic | Book | Chapter/Section |
|---|---|---|
| Behavior design | โDesigning for Behavior Changeโ by Stephen Wendel | Ch. 4-5: Context and Triggers |
| Intent classification | โNatural Language Processing with Pythonโ by Bird et al. | Ch. 6: Text Classification |
| UX patterns | โDonโt Make Me Thinkโ by Steve Krug | Ch. 3: Designing for Scanning |
| State machines | โProgramming Rustโ by Blandy & Orendorff | Ch. 10: Enums and Patterns |
| Pattern matching | โRegular Expressions Cookbookโ by Goyvaerts | Ch. 5: Words and Boundaries |
12. Common Pitfalls and Solutions
| Pitfall | Symptom | Solution |
|---|---|---|
| Over-detection | Every prompt triggers learning mode | Make patterns more specific, require multiple signals |
| Negation ignored | โjust fix itโ triggers explanation | Add negation pattern detection |
| No default mode | Ambiguous prompts cause errors | Always have a fallback (CODING for developers) |
| Jarring transitions | Users confused by mode changes | Add clear mode indicators, allow override |
| Sticky mode confusion | Mode persists when it shouldnโt | Reset mode each prompt unless explicitly locked |
| Pattern conflicts | โreview and explainโ breaks | Implement priority ordering for conflicting patterns |
13. Self-Assessment Checklist
Understanding Verification
- I can explain the difference between static and dynamic output styles
- I understand how UserPromptSubmit hooks can modify prompts
- I can describe intent classification approaches (keyword vs. ML)
- I understand the UX considerations for automatic mode switching
- I can explain how to handle ambiguous or conflicting intent signals
Implementation Verification
- All three output style files are created and working
- The detection hook correctly classifies learning/coding/review prompts
- Negation patterns are detected (โdonโt explain, just fixโ)
- Manual override prefixes work (/learn, /code, /review)
- Mode indicator appears in responses
- Default mode works for ambiguous prompts
Integration Verification
- The hook integrates with Claude Code without errors
- Mode transitions feel smooth and natural
- Test script passes all cases
- Real-world prompts are classified correctly
14. Extensions and Challenges
14.1 Beginner Extensions
- Add more mode patterns for better coverage
- Create a fourth mode (CASUAL for general chat)
- Add mode persistence with
/lockand/unlockcommands
14.2 Intermediate Extensions
- Implement ML-based intent classification (use a small model)
- Add confidence scores to mode detection
- Create mode-specific response templates
14.3 Advanced Extensions
- Learn from user corrections (when they use manual override)
- Context-aware detection (different defaults for different file types)
- Multi-turn context (mode based on conversation history)
15. Completion Criteria
Minimum Viable Completion
- Three output style files created
- Basic keyword detection working
- Mode indicator in responses
- Default mode for unmatched prompts
Full Completion
- Negation patterns detected
- Manual override with prefixes
- All test cases passing
- Smooth UX with clear indicators
- Hook properly integrated
Excellence (Going Above and Beyond)
- ML-based intent classification
- User preference learning
- Context-aware defaults
- Comprehensive test suite
- Documentation and usage guide
This guide was expanded from CLAUDE_CODE_MASTERY_40_PROJECTS.md. For the complete learning path, see the README.