Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:00 +08:00
commit 42b99b32d2
10 changed files with 3821 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
{
"name": "context-master",
"description": "Universal context management and planning system. PROACTIVELY activate for: (1) ANY complex task requiring planning, (2) Multi-file projects/websites/apps, (3) Architecture decisions, (4) Research tasks, (5) Refactoring, (6) Long coding sessions, (7) Tasks with 3+ sequential steps. Provides: optimal file creation order, context-efficient workflows, extended thinking delegation (23x context efficiency), Claude Sonnet 4.5 token budgeting, recursive delegation patterns, clear-and-verify production workflows, passive deep analysis architecture, progressive task decomposition, cross-platform Windows/Git Bash support, and prevents redundant work. Saves 62% context on average. Essential for maintaining session performance and analytical depth.",
"version": "2.2.0",
"author": {
"name": "Josiah Siegel",
"email": "JosiahSiegel@users.noreply.github.com"
},
"skills": [
"./skills"
],
"commands": [
"./commands"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# context-master
Universal context management and planning system. PROACTIVELY activate for: (1) ANY complex task requiring planning, (2) Multi-file projects/websites/apps, (3) Architecture decisions, (4) Research tasks, (5) Refactoring, (6) Long coding sessions, (7) Tasks with 3+ sequential steps. Provides: optimal file creation order, context-efficient workflows, extended thinking delegation (23x context efficiency), Claude Sonnet 4.5 token budgeting, recursive delegation patterns, clear-and-verify production workflows, passive deep analysis architecture, progressive task decomposition, cross-platform Windows/Git Bash support, and prevents redundant work. Saves 62% context on average. Essential for maintaining session performance and analytical depth.

161
commands/plan-project.md Normal file
View File

@@ -0,0 +1,161 @@
---
description: Plan optimal file creation order for multi-file projects before implementation
---
## CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- WRONG: `D:/repos/project/file.tsx`
- CORRECT: `D:
epos\project ile.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Windows/Git Bash Path Conversion
When using Git Bash on Windows, automatic path conversion may occur:
- Unix paths (`/foo`) convert to Windows paths automatically
- This usually works transparently
- See WINDOWS_GIT_BASH_GUIDE.md for advanced scenarios and troubleshooting
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional
- **User preference**: Only create additional .md files when user specifically asks
---
# Plan Project
## Purpose
Before creating any files in a multi-file project (3+ related files), this command helps you plan the optimal creation order, identify dependencies, and prevent redundant work.
## When to Use
- Creating websites with multiple pages
- Building applications with multiple components
- Projects with shared dependencies (CSS, config files)
- API implementations with multiple endpoints
- Documentation sets with multiple files
- Any task involving 3+ related files
## Instructions
### Step 1: Extended Thinking for Architecture
IMMEDIATELY use extended thinking to analyze the project:
```
"Think hard about the architecture for this [project type]:
- What files are needed and what is their purpose?
- What are the shared dependencies (CSS, config, base classes)?
- What is the optimal creation order and why?
- What are the cross-file references?
- What could go wrong if we create files in the wrong order?"
```
### Step 2: Create Architecture Plan
Based on the thinking, create a plan following this template:
```
ARCHITECTURE PLAN:
FILES NEEDED:
- [filename]: [purpose]
- [filename]: [purpose]
SHARED DEPENDENCIES (must be created first):
- [dependency]: [what files need this]
CREATION ORDER (numbered with reasoning):
1. [file] - Reason: [why this first]
2. [file] - Reason: [why this second]
3. [file] - Reason: [why this third]
CROSS-FILE REFERENCES:
- [file A] references [file B] via [method]
POTENTIAL ISSUES TO AVOID:
- [what could go wrong]
- [common mistake]
```
### Step 3: Announce the Plan to User
Tell the user your file creation order before starting:
```
"I'll create these files in this order:
1. [file] - [reason]
2. [file] - [reason]
3. [file] - [reason]
...
This order ensures all dependencies are in place before files that need them."
```
### Step 4: Create Files in Optimal Order
Follow the plan:
- Create foundation files first (CSS, config, base classes)
- Create dependent files after their dependencies exist
- Keep consistent naming and structure
- Add comments about dependencies
### Step 5: Verify
After creating all files, verify:
- All file paths are correct
- CSS/JS references load properly
- Navigation between pages works
- Cross-file dependencies resolve
- No broken links or missing file references
## Key Principles
**Foundations First:**
- CSS files before HTML files that use them
- Configuration files before code that needs them
- Base classes before derived classes
**Core Before Features:**
- index.html before other pages
- main.js before feature modules
- Core API before additional endpoints
**Structure Before Content:**
- HTML structure before detailed content
- API structure before implementation details
- Component scaffolds before full logic
## Token Savings
- Without planning: ~8,000 tokens (redundant work + fixes)
- With planning: ~3,000 tokens (efficient creation)
- **Savings: ~5,000 tokens (62% reduction) per project**
## Example: Portfolio Website
**User Request:** "Create a portfolio with home, about, projects, and contact pages"
**Your Response:**
1. Use extended thinking to plan
2. Announce: "I'll create: 1. styles.css, 2. index.html, 3. about.html, 4. projects.html, 5. contact.html"
3. Create files in that order
4. Verify all HTML files reference styles.css correctly
**Result:** Efficient, no refactoring needed!
## Windows/Git Bash Notes
On Windows with Git Bash:
- Path planning uses forward slashes (Unix format)
- Actual file creation uses backslashes (Windows format)
- Verification handles both formats automatically

69
plugin.lock.json Normal file
View File

@@ -0,0 +1,69 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:JosiahSiegel/claude-code-marketplace:plugins/context-master",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "7ddb096e56abe2a195ece63dfbac05afb31b082d",
"treeHash": "d5baaf9d6206e38117776537c2d402aeed9a7cf8f954852844e54f9f46c12e61",
"generatedAt": "2025-11-28T10:11:48.923920Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "context-master",
"description": "Universal context management and planning system. PROACTIVELY activate for: (1) ANY complex task requiring planning, (2) Multi-file projects/websites/apps, (3) Architecture decisions, (4) Research tasks, (5) Refactoring, (6) Long coding sessions, (7) Tasks with 3+ sequential steps. Provides: optimal file creation order, context-efficient workflows, extended thinking delegation (23x context efficiency), Claude Sonnet 4.5 token budgeting, recursive delegation patterns, clear-and-verify production workflows, passive deep analysis architecture, progressive task decomposition, cross-platform Windows/Git Bash support, and prevents redundant work. Saves 62% context on average. Essential for maintaining session performance and analytical depth.",
"version": "2.2.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "ee27fbcb2b33b4aa550a0384313274722974a234792788592578ffb0ff4addf5"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "fad7d91b913e787f376a76234773b24374638565bae3f5e4a9ef548f4bb6df58"
},
{
"path": "commands/plan-project.md",
"sha256": "aecd3e2b1e9b0c1a68ad713fd4d140062a70b34c9c5b7dcdf8261d6afc5cc59e"
},
{
"path": "skills/context-master/SKILL.md",
"sha256": "6acfe436b0072903e7cb5e6534dcf3f2bbcaa4c385d474e8687f79a86a0e9f45"
},
{
"path": "skills/context-master/references/agent-skills-integration-2025.md",
"sha256": "1f724bffe009fbca12d34a8125a2fc99f04e6dec8aa6b6107f29ce6bb0c36339"
},
{
"path": "skills/context-master/references/context_strategies.md",
"sha256": "d326fc1d2443b8b6b888fd325f0cf8efe4d012fe862dccfecfde20fecf22cf75"
},
{
"path": "skills/context-master/references/subagent_patterns.md",
"sha256": "44d625b12e7ce06a8305b857048f65119320d69fd0c7b95bd2d0a1a0af1eaa58"
},
{
"path": "skills/context-master/scripts/create_subagent.py",
"sha256": "78a5052af6120100c48b0689028b5d3dfa742f128ac853e7c88b886b11434fcd"
},
{
"path": "skills/context-master/scripts/generate_claude_md.py",
"sha256": "3aa3eda5cd9ebd75344c540a9d8e31970c64540c7ab51c0a6867028f498fa8a2"
}
],
"dirSha256": "d5baaf9d6206e38117776537c2d402aeed9a7cf8f954852844e54f9f46c12e61"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,273 @@
## 🚨 CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- ❌ WRONG: `D:/repos/project/file.tsx`
- ✅ CORRECT: `D:\repos\project\file.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone
- **User preference**: Only create additional .md files when user specifically asks for documentation
---
# Agent Skills Integration (2025)
## Overview
Integration patterns between context-master and Agent Skills for autonomous context management in 2025 Claude Code.
## Core Pattern: Context-Aware Agent Skills
### What Are Agent Skills?
Context-efficient knowledge packages that:
- Activate automatically based on context
- Provide specialized guidance
- Stay lean (avoid context bloat)
- Delegate heavy lifting to subagents
### Context Master + Agent Skills Synergy
**Context Master provides:**
- Planning frameworks for multi-file projects
- Thinking delegation architecture
- Context optimization strategies
- Session management patterns
**Agent Skills provide:**
- Domain-specific knowledge
- Automated activation triggers
- Custom tool integration
- Team-wide consistency
## Pattern 1: Context-First Agent Skill
```markdown
# My Custom Agent Skill
## Activation Triggers
- User mentions "create [N]+ files"
- Request involves "architecture"
- Task needs "planning"
## Instructions
### Step 1: Context Check
Before proceeding, ask:
- Are we working with multi-file project? (YES → use context-master)
- Is thinking delegation needed? (YES → delegate)
### Step 2: Leverage Context Master
- Use /plan-project command for architecture
- Use thinking delegation for deep analysis
- Reference context-master patterns
### Step 3: Your Domain Work
- Implement using domain expertise
- Verify structure using /verify-structure
- Document decisions in DECISIONS.md
```
## Pattern 2: Autonomous Context Delegation
Instead of doing analysis in Agent Skill context:
**Bad (fills Agent Skill context):**
```
"Let me think deeply about the architecture..."
[5K tokens of thinking in Agent Skill context]
```
**Good (preserves Agent Skill context):**
```
"This needs deep analysis. Let me delegate:
/agent deep-analyzer "Ultrathink about [architecture]"
[Deep analysis happens in isolated agent context]
[Returns summary to Agent Skill - clean]
```
## Pattern 3: Project-Specific Context Strategy
**In your Agent Skill:**
```
## When This Skill Activates
1. Check if CLAUDE.md exists
2. If yes: Load context strategy from CLAUDE.md
3. If no: Use default context-master patterns
## Recommended CLAUDE.md Strategy for This Skill
Include in your project's CLAUDE.md:
```yaml
ContextStrategy:
- Use subagents for: [domain-specific searches]
- Keep in main for: [your domain decisions]
- Compact when: [context grows beyond X]
- Clear before: [major phase transitions]
```
## Pattern 4: Team Consistency
### Create Standard Agent Skill Template
```markdown
# Team Agent Skill Template
## Activation
Activates for: [domain work]
## Context Management
Before doing any analysis:
1. Reference /plan-project for multi-file work
2. Use thinking delegation for complex decisions
3. Document findings in [DOMAIN]_FINDINGS.md
4. Leave main context clean for other agents
## Integration Points
- Works with: context-master, plugin-master
- Delegates to: deep_analyzer for critical choices
- Outputs to: Structured documents, not context
```
## Pattern 5: Cascading Deep Analysis
**For complex domains requiring multiple analyses:**
```
User Request → Triggers Your Agent Skill
Agent Skill identifies sub-questions:
Q1: Frontend implications?
Q2: Backend implications?
Q3: Data implications?
Q4: Integrated recommendation?
Delegates each:
/agent frontend-deep-analyzer "Ultrathink Q1"
/agent backend-deep-analyzer "Ultrathink Q2"
/agent data-deep-analyzer "Ultrathink Q3"
/agent synthesis-analyzer "Ultrathink Q4"
Receives 4 summaries (~200 tokens each)
Agent Skill synthesizes in clean context
Returns integrated recommendation to main
```
**Context used in main:** ~1,200 tokens (4 summaries + synthesis)
**vs Traditional:** 20K+ tokens (all thinking in main)
**Efficiency:** 16-17x
## Pattern 6: Progressive Context Loading
Avoid loading all project context upfront:
```
// In your Agent Skill:
Step 1: Minimal context
- Load just CLAUDE.md
- Understand strategy
Step 2: Selective context
- Load only relevant files (use subagent search)
- Get summaries, not full content
Step 3: Deep dive only if needed
- Load full context only for specific modules
- Use Progressive disclosure pattern
```
## Implementation Checklist
- [ ] Agent Skill documentation mentions context-master
- [ ] Activation triggers align with planning needs
- [ ] Uses /plan-project for multi-file work
- [ ] Delegates deep analysis to subagents
- [ ] Documents decisions outside of context
- [ ] CLAUDE.md includes skill-specific strategies
- [ ] Team training covers thinking delegation
- [ ] Hooks configured for auto-management
## Advanced: Agent Skill + Plugin Creation Workflow
For creating domain-specific plugins:
```
1. User wants new plugin for domain X
2. Agent Skill → plugin-master integration:
/agent plugin-architect "Design plugin for X"
3. plugin-architect:
- Thinks about structure
- Considers context implications
- References context-master patterns
4. Returns design
5. User/Agent Skill creates plugin
6. New plugin includes context-master references
```
## Real-World Example: Frontend Agent Skill
```markdown
# Frontend Agent Skill
## When This Activates
- User: "Create a React component..."
- User: "Build a multi-page website..."
- User: "Design component architecture..."
## Instructions
### Multi-File Check
If creating 3+ files:
1. "/plan-project - Think about component structure"
2. Wait for analysis
3. Implement files in recommended order
4. "/verify-structure - Check component references"
### Complex Decisions
If component architecture is complex:
1. "/agent frontend-analyzer - Think about patterns"
2. Receive analysis
3. Design components in main context (clean)
### Documentation
1. Save component decisions to COMPONENT_DECISIONS.md
2. Leave main context for next task
3. Reference document as needed
```
## Measuring Success
**Good indicators:**
- Main context stays under 50K tokens for complex work
- Multiple features/analyses per session without degradation
- Clear decision logs without context bloat
- Smooth team collaboration
**Warning signs:**
- Main context consistently >80K
- Responses getting less focused
- Need to restart sessions more often
- Team members report context issues

View File

@@ -0,0 +1,406 @@
# Context Management Strategies
Detailed workflows and strategies for managing context efficiently in Claude Code.
## Understanding Context Usage
**Context window size:**
- Standard: 200K tokens (~150K words)
- Extended (API): 1M tokens (~750K words)
**What consumes context:**
- Conversation history (messages back and forth)
- File contents loaded into context
- Tool call results (bash output, test results, etc.)
- CLAUDE.md configuration
- Extended thinking blocks
**Context awareness:** Claude Sonnet 4.5 tracks remaining context and reports it with each tool call.
## Core Commands
### `/clear` - Reset Context
**When to use:**
- Between major features or tasks
- After completing a self-contained piece of work
- When switching between different parts of the codebase
- If you notice Claude getting distracted or referencing old context
**Example workflow:**
```
1. Complete feature A
2. Run tests and commit
3. /clear
4. Start feature B with fresh context
```
### `/compact` - Compress Context
**When to use:**
- Before starting complex multi-step work
- When approaching context limits (~80% full)
- To preserve key decisions while clearing clutter
**What it does:** Summarizes conversation history while retaining key information.
**Example workflow:**
```
1. Long research and planning session
2. /compact "Summarize architecture decisions and open TODOs"
3. Continue with implementation
```
### `/continue` - Resume Session
**When to use:**
- Returning to previous work
- After a break
- To pick up where you left off
**Combines well with:**
```
claude --continue # Resume last session in current project
```
## Strategy 1: Task Isolation
**Goal:** Keep each task in its own context bubble.
**Workflow:**
```
1. Start task → /clear (if needed)
2. Use subagents for research/analysis
3. Main context focuses on implementation
4. Complete and test
5. /clear before next task
```
**When to use:**
- Multiple independent features
- Bug fixes that don't require historical context
- Refactoring isolated modules
**Benefits:**
- Each task starts with clean slate
- No cross-contamination between tasks
- More predictable context usage
---
## Strategy 2: Progressive Context Management
**Goal:** Build up context deliberately, clearing non-essential information.
**Workflow:**
```
1. Research phase
- Subagents search and analyze
- Main context reviews summaries
2. Planning phase
- "think hard" to create plan
- Save plan to document/issue
3. /compact "Keep architecture decisions and plan"
4. Implementation phase
- Reference plan document
- Focus on current file/module
5. Testing phase
- Subagent runs tests
- Main context addresses failures
6. /clear before next feature
```
**When to use:**
- Large features requiring multiple steps
- Complex refactoring
- Projects with extensive research phase
**Benefits:**
- Intentional context building
- Clear phase transitions
- Preserved key decisions
---
## 🚨 CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- ❌ WRONG: `D:/repos/project/file.tsx`
- ✅ CORRECT: `D:\repos\project\file.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone
- **User preference**: Only create additional .md files when user specifically asks for documentation
---
## Strategy 3: Parallel Workstreams
**Goal:** Work on multiple aspects simultaneously using subagents.
**Workflow:**
```
1. Main context: High-level orchestration
2. Subagent A: Frontend work
3. Subagent B: Backend work
4. Subagent C: Test execution
5. Main context: Integration and coordination
```
**When to use:**
- Full-stack features
- Multi-component changes
- When different aspects are independent
**Benefits:**
- Efficient use of subagent isolation
- Parallel progress
- Main context stays focused on coordination
---
## Strategy 4: Test-Driven Context Management
**Goal:** Keep context focused on current test/implementation cycle.
**Workflow:**
```
1. Write test in main context
2. /agent test-runner "run new test"
3. Implement feature to pass test
4. /agent test-runner "run test suite"
5. If fail → fix in main context
6. If pass → commit and /clear
```
**When to use:**
- TDD workflows
- Bug fixes with test coverage
- API endpoint development
**Benefits:**
- Tight feedback loop
- Context stays focused on current test
- Test output doesn't clutter main context
---
## Strategy 5: Documentation-First Development
**Goal:** Use CLAUDE.md as persistent memory across sessions.
**Setup:**
```markdown
# CLAUDE.md
## Current Focus
Sprint goal: User authentication system
## Recent Decisions
- Using JWT with refresh tokens
- PostgreSQL for user storage
- Redis for session management
## Next Tasks
- [ ] Implement token refresh endpoint
- [ ] Add rate limiting
- [ ] Write integration tests
## Architecture Notes
[Key decisions that inform all work]
```
**Workflow:**
```
1. CLAUDE.md provides persistent context
2. Each session references current focus
3. Update CLAUDE.md with new decisions
4. /clear frequently - CLAUDE.md persists
```
**When to use:**
- Multi-day projects
- Team collaboration (CLAUDE.md in git)
- Complex projects needing persistent memory
**Benefits:**
- Survives /clear commands
- Shared team knowledge
- Consistent across sessions
---
## Scenario-Based Strategies
### Scenario: Large Refactoring
**Challenge:** Need broad codebase understanding but context fills quickly.
**Strategy:**
```
1. Subagent: "Map all files using old pattern"
2. Review map, create refactoring plan
3. Save plan to REFACTOR.md
4. /clear
5. For each file:
a. Load file
b. Refactor based on plan
c. Test
d. /clear before next file
```
---
### Scenario: Bug Investigation
**Challenge:** Unknown cause, need to search widely but track findings.
**Strategy:**
```
1. Create BUG_NOTES.md to track findings
2. Subagent: "Search logs for error X"
3. Document findings in BUG_NOTES.md
4. Subagent: "Analyze code paths that could cause X"
5. Document in BUG_NOTES.md
6. /compact "Keep bug theory and evidence"
7. Implement fix
8. /agent test-runner "verify fix"
```
---
### Scenario: New Feature with Unknown Patterns
**Challenge:** Need to research existing patterns without cluttering context.
**Strategy:**
```
1. Subagent: "Find similar features in codebase"
2. Subagent: "Extract common patterns from those features"
3. Main context reviews patterns
4. "think about best approach for new feature"
5. Create implementation plan
6. /clear
7. Implement based on plan
8. Reference plan doc if needed
```
---
### Scenario: Multi-File Feature
**Challenge:** Changes span many files, hard to keep all in context.
**Strategy:**
```
1. Create FEATURE.md with:
- Overall design
- File change checklist
- Cross-file dependencies
2. For each file:
a. Load just that file
b. Reference FEATURE.md for context
c. Make changes
d. Test
e. /compact if context getting full
3. Final integration test
4. /clear and move to next feature
```
---
## Advanced Techniques
### Technique: Context Checkpoints
**Save key state to files before clearing:**
```
1. Long planning session
2. "Create PLAN.md with our architecture decisions"
3. /clear
4. Reference PLAN.md during implementation
```
### Technique: Layered Context Loading
**Load information progressively as needed:**
```
1. Start with just current file
2. If need more context: "show me the caller"
3. If need more: "show me the config"
4. Don't load everything upfront
```
### Technique: Subagent Summarization
**Use subagents to create digestible summaries:**
```
Subagent: "Analyze all 50 test files and create a summary:
- Total coverage percentage
- Files with <50% coverage
- Most complex tests"
Then work from the summary, not the raw test files.
```
### Technique: Incremental /compact
**Compress context multiple times in long sessions:**
```
1. Research phase → /compact "Keep research findings"
2. Planning phase → /compact "Keep findings and plan"
3. Implementation → /compact "Keep plan and decisions"
```
## Monitoring Context Health
**Signs context is getting cluttered:**
- Claude references old, irrelevant information
- Responses become less focused
- Performance seems to degrade
- You're >80% through context budget
**Remedies:**
1. `/compact` for quick compression
2. `/clear` for fresh start
3. Move key info to files before clearing
4. Use subagents more aggressively
## Best Practices Summary
1. **Use /clear liberally** between tasks
2. **Front-load subagent usage** for research
3. **Document decisions** in CLAUDE.md or files
4. **Load files progressively** as needed
5. **Test in subagents** to keep output isolated
6. **/compact before** complex multi-step work
7. **Think first** to plan before implementing
8. **Reference plans** instead of keeping full context
9. **Batch similar operations** in single subagent
10. **Monitor context usage** and respond proactively

View File

@@ -0,0 +1,664 @@
# Subagent Patterns
Common patterns and best practices for using subagents in Claude Code, with emphasis on thinking delegation for context efficiency.
## The Thinking Delegation Paradigm
**Core insight:** Subagents have isolated context windows. When subagents use extended thinking, that reasoning happens in THEIR context, not the main session's context.
**This enables:**
- Deep analysis (5K+ thinking tokens)
- Main context receives summaries (~200 tokens)
- 23x context efficiency while maintaining analytical rigor
- Sustainable long sessions with multiple complex analyses
**The architecture:**
```
Main Session: Makes decisions, stays focused
↓ delegates with thinking trigger
Subagent: Uses extended thinking in isolation (5K tokens)
↑ returns summary
Main Session: Receives actionable conclusion (200 tokens)
```
**Context math:**
- Traditional: 7K tokens per analysis in main context
- With delegation: 300 tokens per analysis in main context
- Efficiency gain: 23x
## Thinking-Enabled Subagent Types
### Deep Analyzer (Type: deep_analyzer)
**Purpose:** Complex decisions requiring extensive analysis
**What it does:**
- ALWAYS uses "ultrathink" for analysis
- Evaluates multiple approaches
- Considers tradeoffs and implications
- Returns well-reasoned recommendations
**When to use:**
- Architecture decisions
- Technology evaluations
- Design pattern selection
- Performance optimization strategies
- Security assessments
- Refactoring approach planning
**Example usage:**
```
/agent architecture-advisor "Should we use microservices or modular monolith
for a 10M user e-commerce platform with 8 developers?"
[Subagent thinks deeply in isolation - 5K tokens]
[Returns to main: ~200 token summary with recommendation]
```
### Pattern Researcher (Type: researcher)
**Purpose:** Research with analytical thinking
**What it does:**
- Searches documentation/code
- Uses "think hard" for multi-source analysis
- Synthesizes insights with reasoning
- Returns analysis, not just data
**When to use:**
- API pattern research
- Best practice discovery
- Technology comparison
- Design pattern evaluation
**Example usage:**
```
/agent pattern-researcher "Research authentication patterns in our codebase
and think hard about which approach fits our scale requirements"
[Subagent searches + analyzes - 3K tokens thinking]
[Returns: Summary of patterns with reasoned recommendation]
```
### Code Analyzer (Type: analyzer)
**Purpose:** Architectural insights and deep code analysis
**What it does:**
- Analyzes code structure
- Uses "think harder" for architecture
- Identifies implications and opportunities
- Returns actionable insights
**When to use:**
- Architecture assessment
- Technical debt identification
- Performance bottleneck analysis
- Refactoring opportunity discovery
**Example usage:**
```
/agent code-analyzer "Think deeply about our authentication system's
architecture and identify improvement opportunities"
[Subagent analyzes + thinks - 4K tokens]
[Returns: Key findings with prioritized recommendations]
```
### Test Analyzer (Type: tester)
**Purpose:** Test execution with failure analysis
**What it does:**
- Runs test suites
- Uses "think hard" when tests fail
- Analyzes root causes
- Returns actionable diagnostics
**When to use:**
- Test suite execution
- Failure diagnosis
- Regression analysis
- Coverage assessment
**Example usage:**
```
/agent test-analyzer "Run the auth test suite and if failures occur,
think hard about root causes"
[Subagent runs tests, analyzes failures - 2K tokens thinking]
[Returns: Test status + root cause analysis if needed]
```
## Core Principles
**Subagents have isolated context windows** - They only send relevant information back to the main orchestrator, not their full context. This makes them ideal for tasks that generate lots of intermediary results.
**When to use subagents:**
- Searching through large codebases
- Analyzing multiple files for patterns
- Research tasks with extensive documentation
- Running tests or builds
- Any investigation that doesn't need full project context
**When NOT to use subagents:**
- Quick single-file edits
- Simple queries that need immediate response
- Tasks requiring full project context for decision-making
## Common Patterns
### Pattern 1: Research → Plan → Implement
**Main Context:**
```
1. "Use a subagent to search our codebase for similar authentication implementations"
2. [Review subagent findings]
3. "think about the best approach based on those examples"
4. [Implement in main context]
```
**Why it works:** Research generates lots of search results that would clutter main context. Main agent only sees the summary.
---
### Pattern 2: Parallel Investigation
**Main Context:**
```
"Spin up three subagents:
1. One to analyze our error handling patterns
2. One to check test coverage
3. One to review documentation
Report back with key findings from each."
```
**Why it works:** Each subagent has its own context window. They can work in parallel without interfering with each other.
---
## 🚨 CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- ❌ WRONG: `D:/repos/project/file.tsx`
- ✅ CORRECT: `D:\repos\project\file.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone
- **User preference**: Only create additional .md files when user specifically asks for documentation
---
### Pattern 3: Test-Driven Workflow
**Main Context:**
```
1. Write tests in main context
2. "Use a subagent to run the test suite and report results"
3. [Implement fixes based on failures]
4. "Subagent: run tests again"
5. [Repeat until passing]
```
**Why it works:** Test output can be verbose. Subagent filters it down to pass/fail status and specific failures.
---
### Pattern 4: Build Verification
**Main Context:**
```
1. Make code changes
2. "Subagent: run the build and verify it succeeds"
3. [If build fails, review error]
4. [Fix and repeat]
```
**Why it works:** Build logs are long. Subagent only reports success/failure and relevant errors.
---
### Pattern 5: Multi-File Analysis
**Main Context:**
```
"Use a subagent to:
1. Find all files using the old API
2. Analyze migration complexity
3. Return list of files and complexity assessment"
[Review findings]
"Create a migration plan based on that analysis"
```
**Why it works:** File searching and analysis stays in subagent. Main context gets clean summary for planning.
## Usage Syntax
### Starting a Subagent
```
/agent <agent-name> <task-description>
```
or in natural language:
```
"Use a subagent to [task]"
"Spin up a subagent for [task]"
"Delegate [task] to a subagent"
```
### Pre-configured vs Ad-hoc
**Pre-configured agents** (stored in `.claude/agents/`):
```
/agent test-runner run the full test suite
```
**Ad-hoc agents** (created on the fly):
```
"Use a subagent to search the codebase for error handling patterns"
```
## Example Subagent Configurations
### Research Subagent
**File:** `.claude/agents/researcher.md`
```markdown
# Researcher
Documentation and code search specialist
## Instructions
Search through documentation and code efficiently. Return only the most
relevant information with specific file paths and line numbers.
Summarize findings concisely.
## Allowed Tools
- read
- search
- web_search
## Autonomy Level
Medium - Take standard search actions autonomously
```
### Test Runner Subagent
**File:** `.claude/agents/test-runner.md`
```markdown
# Test Runner
Automated test execution and reporting
## Instructions
Execute test suites and report results clearly. Focus on:
- Pass/fail status
- Specific failing tests
- Error messages and stack traces
- Coverage metrics if available
## Allowed Tools
- bash
- read
## Autonomy Level
High - Execute tests fully autonomously
```
### Code Analyzer Subagent
**File:** `.claude/agents/analyzer.md`
```markdown
# Analyzer
Code analysis and pattern detection
## Instructions
Analyze code structure and identify:
- Duplicate patterns
- Complexity hotspots
- Dependency relationships
- Potential issues
Provide actionable insights with specific locations.
## Allowed Tools
- read
- search
- bash
## Autonomy Level
Medium - Analyze autonomously, ask before making suggestions
```
## Anti-Patterns
### ❌ Using Subagents for Everything
**Bad:**
```
"Use a subagent to edit this single file"
```
**Why:** Overhead of subagent isn't worth it for simple tasks.
**Good:**
```
"Edit this file to add the new function"
```
---
### ❌ Not Providing Clear Task Scope
**Bad:**
```
"Use a subagent to look at the code"
```
**Why:** Too vague. Subagent doesn't know what to focus on.
**Good:**
```
"Use a subagent to search for all database query patterns and assess
which ones are vulnerable to SQL injection"
```
---
### ❌ Expecting Full Context Transfer
**Bad:**
```
Main: [Long discussion about architecture]
Then: "Subagent: implement that plan we just discussed"
```
**Why:** Subagent doesn't have access to your conversation history.
**Good:**
```
"Subagent: implement the authentication module with:
- JWT tokens
- Refresh token rotation
- Rate limiting
Based on our existing user service patterns."
```
## Performance Tips
1. **Front-load research** - Use subagents early for research, then implement in main context
2. **Batch similar tasks** - One subagent for all file searches, not separate subagents per file
3. **Clear instructions** - Be specific about what the subagent should return
4. **Iterate in main context** - Use main context for back-and-forth refinement
5. **Trust the summary** - Don't ask subagent to return full documents
## Advanced: Chaining Subagents
**Scenario:** Complex analysis requiring multiple specialized agents
```
1. "Subagent: search for all API endpoints and list them"
2. [Review list]
3. "Subagent: for each endpoint in that list, check test coverage"
4. [Review coverage report]
5. "Subagent: analyze the untested endpoints and estimate testing effort"
```
**Why chaining works:** Each subagent builds on the previous results without cluttering the main context with intermediary data.
---
## Thinking Delegation Patterns
### Pattern 1: Deep Decision Analysis
**Problem:** Need to make complex architectural decision
**Traditional approach (main context):**
```
"Think deeply about microservices vs monolith"
[5K tokens of thinking in main context]
```
**Thinking delegation approach:**
```
/agent deep-analyzer "Ultrathink about microservices vs monolith
for 10M user platform, 8 dev team, considering deployment, maintenance,
scaling, and team velocity"
[Subagent's isolated context: 6K tokens of thinking]
[Main receives: 250 token summary + recommendation]
```
**Context saved:** 5,750 tokens (~97%)
---
### Pattern 2: Research → Think → Recommend
**Problem:** Need to research options and provide reasoned recommendation
**Workflow:**
```
Step 1: Research phase
/agent pattern-researcher "Research state management libraries
and think hard about tradeoffs"
[Subagent searches + analyzes in isolation]
[Returns: Options with pros/cons]
Step 2: Decision phase
/agent deep-analyzer "Based on these options, ultrathink and
recommend best fit for our use case"
[Subagent thinks deeply in isolation]
[Returns: Recommendation with rationale]
Step 3: Implementation
[Main context implements based on recommendation]
```
**Why it works:** Research and analysis isolated, implementation focused
---
### Pattern 3: Iterative Analysis Refinement
**Problem:** Need to analyze multiple aspects without context accumulation
**Workflow:**
```
Round 1: /agent analyzer "Think about performance implications"
[Returns summary to main]
Round 2: /agent analyzer "Think about security implications"
[Returns summary to main]
Round 3: /agent deep-analyzer "Synthesize performance and security
analyses, recommend approach"
[Returns final recommendation to main]
Main context: Make decision with 3 concise summaries (~600 tokens total)
```
**vs Traditional:**
```
"Think about performance" [3K tokens in main]
"Think about security" [3K tokens in main]
"Synthesize" [needs both analyses in context]
Total: 6K+ tokens
```
**Context efficiency:** 10x improvement
---
### Pattern 4: Parallel Deep Analysis
**Problem:** Multiple independent analyses needed
**Workflow:**
```
/agent analyzer-1 "Think deeply about database options"
/agent analyzer-2 "Think deeply about caching strategies"
/agent analyzer-3 "Think deeply about API design patterns"
[Each analyzes in parallel, isolated contexts]
[Each returns summary]
/agent deep-analyzer "Synthesize these analyses into coherent architecture"
[Returns integrated recommendation]
```
**Why it works:** Multiple deep analyses happen without accumulating in main context
---
### Pattern 5: Test-Driven Development with Thinking
**Problem:** TDD cycle fills context with test output and debugging analysis
**Traditional TDD:**
```
Write test → Run test (verbose output) → Debug (thinking in main) → Fix → Repeat
[Context fills with test output + debugging thinking]
```
**Thinking delegation TDD:**
```
1. Write test in main context (focused)
2. /agent test-analyzer "Run test, if failure think hard about root cause"
3. [Subagent runs + analyzes in isolation]
4. [Returns: Status + root cause analysis if needed]
5. Fix based on analysis in main context
6. /agent test-analyzer "Verify fix"
7. Repeat until passing
```
**Why it works:** Test output and failure analysis isolated, main context stays implementation-focused
---
### Pattern 6: Refactoring with Deep Assessment
**Problem:** Large refactoring needs strategy without filling main context
**Workflow:**
```
Step 1: Assessment
/agent analyzer "Think deeply about refactoring scope, risks,
and approach for legacy auth system"
[Subagent analyzes codebase + thinks in isolation - 4K tokens]
[Returns: Risk assessment + strategy - 300 tokens]
Step 2: Planning
Create REFACTOR.md in main context based on strategy
Step 3: Execution
/clear
For each module:
- Refactor based on plan
- /agent test-analyzer "verify changes"
- Commit
- /clear
```
**Why it works:** Deep analysis happens once (isolated), execution follows clean plan
---
### Pattern 7: Compound Decision Making
**Problem:** Multi-layer decision with dependencies
**Workflow:**
```
Layer 1: Foundation decision
/agent deep-analyzer "Ultrathink: Relational vs NoSQL for our use case"
[Returns: Relational recommended]
Layer 2: Specific technology
/agent deep-analyzer "Given relational choice, ultrathink:
PostgreSQL vs MySQL vs MariaDB"
[Returns: PostgreSQL recommended with reasoning]
Layer 3: Architecture details
/agent deep-analyzer "Given PostgreSQL, ultrathink: Replication
strategy for our scale"
[Returns: Streaming replication recommended]
Main context: Has 3 clear decisions (~600 tokens total)
```
**vs Traditional:** All thinking would accumulate in main context (12K+ tokens)
---
## Advanced Thinking Patterns
### Meta-Pattern: Thinking Chain
For extremely complex decisions requiring multiple analytical lenses:
```
1. /agent deep-analyzer "Analyze from business perspective"
2. /agent deep-analyzer "Analyze from technical perspective"
3. /agent deep-analyzer "Analyze from security perspective"
4. /agent deep-analyzer "Analyze from cost perspective"
5. /agent deep-analyzer "Synthesize all perspectives and recommend"
Main context receives: 5 concise analyses → integrated recommendation
Total in main: ~1K tokens
vs Traditional: 25K+ tokens of accumulated thinking
```
### Meta-Pattern: Thinking Cascade
When decision depends on answering prior questions:
```
Q1: /agent deep-analyzer "Should we build or buy?"
[Returns: Build recommended because...]
Q2: /agent deep-analyzer "Given building, which framework?"
[Returns: React recommended because...]
Q3: /agent deep-analyzer "Given React, which state management?"
[Returns: Zustand recommended because...]
Each analysis builds on previous conclusion, not previous reasoning
```
---

View File

@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""
Create a subagent configuration for Claude Code.
Usage:
python create_subagent.py <agent_name> [--type TYPE] [--output DIR]
Types:
- researcher: For documentation and code searches with deep analysis
- tester: For running tests and validation with failure analysis
- analyzer: For code analysis and architectural insights
- builder: For build and deployment tasks
- deep_analyzer: For complex decisions requiring extensive thinking
"""
import argparse
import json
from pathlib import Path
SUBAGENT_TEMPLATES = {
"researcher": {
"name": "{agent_name}",
"description": "Research and documentation lookup agent with deep analysis",
"instructions": """You are a research specialist. Your job is to:
- Search through documentation efficiently
- THINK DEEPLY about findings using extended thinking
- Analyze patterns and implications
- Synthesize insights with reasoning
- Return concise, well-reasoned summaries
IMPORTANT: For complex research, use extended thinking before responding:
- Use "think hard" for multi-source analysis
- Use "ultrathink" for architecture pattern evaluation
- Your thinking happens in YOUR isolated context
- Return only the analysis summary to the main agent
The main agent needs your INSIGHTS, not raw data.""",
"tools": ["read", "search", "web_search"],
"autonomy": "medium"
},
"tester": {
"name": "{agent_name}",
"description": "Testing and validation agent with analysis",
"instructions": """You are a testing specialist. Your job is to:
- Execute test suites
- Validate code changes
- ANALYZE test failures deeply
- Identify root causes and patterns
- Report clear, actionable results
IMPORTANT: When test failures occur, use extended thinking:
- Use "think hard" to analyze failure patterns
- Consider root causes and related issues
- Your analysis happens in YOUR isolated context
- Return actionable findings to the main agent
Focus on test execution and insightful result reporting.""",
"tools": ["bash", "read", "write"],
"autonomy": "high"
},
"analyzer": {
"name": "{agent_name}",
"description": "Code analysis and deep architectural insight agent",
"instructions": """You are a code analysis specialist. Your job is to:
- Analyze code structure and patterns
- THINK DEEPLY about implications and tradeoffs
- Identify potential issues and opportunities
- Compute complexity metrics
- Find dependencies and relationships
IMPORTANT: Always use extended thinking for analysis:
- Use "think harder" for architecture analysis
- Use "ultrathink" for complex system evaluation
- Consider multiple perspectives and edge cases
- Your deep reasoning happens in YOUR isolated context
- Return concise analysis with key insights to the main agent
Provide actionable insights backed by reasoning.""",
"tools": ["read", "search", "bash"],
"autonomy": "medium"
},
"builder": {
"name": "{agent_name}",
"description": "Build and deployment agent",
"instructions": """You are a build specialist. Your job is to:
- Execute build processes
- Run deployment scripts
- Verify build outputs
- Report build status and errors
Focus on build execution and clear status reporting. Return success/failure and any errors.""",
"tools": ["bash", "read"],
"autonomy": "high"
},
"deep_analyzer": {
"name": "{agent_name}",
"description": "Deep analysis agent with mandatory extended thinking",
"instructions": """You are a deep analysis specialist. Your PRIMARY function is to think deeply before responding.
MANDATORY WORKFLOW:
1. Always start with "ultrathink" for complex analysis
2. Consider multiple approaches and perspectives
3. Evaluate tradeoffs, implications, and edge cases
4. Reason through consequences and alternatives
5. Synthesize findings into clear recommendations
Your extended thinking happens in YOUR isolated context - this is your superpower.
The main agent only sees your conclusions, not your reasoning process.
RETURN FORMAT:
- Brief conclusion (2-3 sentences)
- Key reasoning points (3-5 bullets)
- Recommendation with rationale
- Any important caveats
The main agent trusts your deep analysis. Give them confidence through thorough thinking.""",
"tools": ["read", "search", "bash", "web_search"],
"autonomy": "high"
}
}
CLAUDE_CODE_FORMAT = """# {agent_name}
{description}
## Instructions
{instructions}
## Allowed Tools
{tools}
## Autonomy Level
{autonomy_description}
"""
AUTONOMY_DESCRIPTIONS = {
"low": "Ask for confirmation before taking actions. Provide recommendations.",
"medium": "Take standard actions autonomously. Ask for confirmation on significant changes.",
"high": "Execute tasks fully autonomously. Report results when complete."
}
def create_subagent(agent_name: str, agent_type: str, output_dir: str) -> None:
"""Create a subagent configuration file."""
if agent_type not in SUBAGENT_TEMPLATES:
raise ValueError(
f"Unknown agent type: {agent_type}. "
f"Choose from: {', '.join(SUBAGENT_TEMPLATES.keys())}"
)
template = SUBAGENT_TEMPLATES[agent_type].copy()
template["name"] = agent_name
# Create output directory
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Create .claude/agents directory structure
agents_dir = output_path / ".claude" / "agents"
agents_dir.mkdir(parents=True, exist_ok=True)
# Generate agent file in Claude Code format
agent_file = agents_dir / f"{agent_name}.md"
tools_list = "\n".join(f"- {tool}" for tool in template["tools"])
autonomy_desc = AUTONOMY_DESCRIPTIONS[template["autonomy"]]
content = CLAUDE_CODE_FORMAT.format(
agent_name=agent_name,
description=template["description"],
instructions=template["instructions"],
tools=tools_list,
autonomy_description=autonomy_desc
)
agent_file.write_text(content)
# Also create a JSON version for programmatic use
json_file = agents_dir / f"{agent_name}.json"
json_file.write_text(json.dumps(template, indent=2))
print(f"✅ Created subagent: {agent_name}")
print(f" Type: {agent_type}")
print(f" Location: {agent_file}")
print(f"\n📝 Next steps:")
print(f" 1. Review and customize {agent_file}")
print(f" 2. Use in Claude Code with: /agent {agent_name}")
print(f" 3. Commit to version control")
# Print usage example
print(f"\n💡 Usage example:")
print(f" /agent {agent_name} [your task description]")
def main():
parser = argparse.ArgumentParser(
description="Create a subagent configuration for Claude Code"
)
parser.add_argument(
"agent_name",
help="Name for the subagent (e.g., 'test-runner', 'doc-searcher')"
)
parser.add_argument(
"--type",
choices=list(SUBAGENT_TEMPLATES.keys()),
default="researcher",
help="Type of subagent to create"
)
parser.add_argument(
"--output",
default=".",
help="Output directory (default: current directory)"
)
args = parser.parse_args()
create_subagent(args.agent_name, args.type, args.output)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,341 @@
#!/usr/bin/env python3
"""
Generate a CLAUDE.md file for context-efficient Claude Code workflows.
Usage:
python generate_claude_md.py [--type TYPE] [--output PATH]
Types:
- general: General-purpose project (default)
- backend: Backend API/service project
- frontend: Frontend web application
- fullstack: Full-stack application
- data: Data science/ML project
- library: Library/package project
"""
import argparse
import os
from pathlib import Path
TEMPLATES = {
"general": """# Claude Code Configuration
## Project Overview
<!-- Describe your project's purpose, architecture, and key components -->
## Context Management Strategy
### When to Use Subagents
- **Code searches**: Use subagents to search through large codebases
- **File analysis**: Delegate multi-file analysis to subagents
- **Research tasks**: Use subagents for documentation lookups
- **Testing**: Isolate test runs in subagents
### Context Commands
- Use `/clear` between major tasks to reset context
- Use `/compact` before complex multi-step work
- Use `think` for planning complex changes
## Development Workflow
1. **Planning Phase**: Use "think" to analyze approach
2. **Implementation**: Keep main context focused on current task
3. **Verification**: Use subagents for testing and validation
4. **Cleanup**: `/clear` before starting new features
## Allowed Tools
- File operations (read, write, edit)
- Git operations (commit, branch, status)
- Shell commands for building and testing
- Subagent delegation
## Code Style
<!-- Add your project's code style guidelines -->
## Escalation Rules
- Ask before making breaking changes
- Confirm before deleting files
- Verify test results before committing
""",
"backend": """# Claude Code Configuration - Backend Project
## Project Overview
<!-- Describe your API/service architecture -->
## Context Management Strategy
### When to Use Subagents
- **Database queries**: Delegate schema exploration to subagents
- **API documentation**: Use subagents to search through API docs
- **Log analysis**: Isolate log file analysis in subagents
- **Dependency analysis**: Check dependencies in isolated context
- **Test runs**: Execute test suites in subagents
### Context Commands
- `/clear` between feature implementations
- `/compact` before multi-endpoint refactoring
- `think hard` for API design decisions
## Development Workflow
1. **Schema Review**: Subagent explores DB schema
2. **Planning**: Main context designs endpoint logic
3. **Implementation**: Focus on current endpoint
4. **Testing**: Subagent runs integration tests
5. **Commit**: After test verification
## API Patterns
<!-- Add your API conventions (REST, GraphQL, etc.) -->
## Database
<!-- Add your schema info or reference documentation -->
## Testing Strategy
- Unit tests required for business logic
- Integration tests for API endpoints
- Use subagents for test execution
## Escalation Rules
- Confirm before database migrations
- Ask before changing API contracts
- Verify backward compatibility
""",
"frontend": """# Claude Code Configuration - Frontend Project
## Project Overview
<!-- Describe your frontend architecture (React, Vue, Angular, etc.) -->
## Context Management Strategy
### When to Use Subagents
- **Component searches**: Find similar components across codebase
- **Style analysis**: Isolate CSS/styling investigations
- **Bundle analysis**: Check dependencies and imports
- **Test runs**: Execute component tests in subagents
- **Build verification**: Run builds in isolated context
### Context Commands
- `/clear` between component implementations
- `/compact` before large refactoring
- `think` for component architecture decisions
## Development Workflow
1. **Component Planning**: Design component structure
2. **Implementation**: Focus on current component
3. **Styling**: Apply consistent design system
4. **Testing**: Subagent runs component tests
5. **Build Check**: Subagent verifies build
## Component Patterns
<!-- Add your component conventions -->
## Styling Approach
<!-- CSS-in-JS, Tailwind, CSS Modules, etc. -->
## State Management
<!-- Redux, Context API, Zustand, etc. -->
## Testing Strategy
- Component tests required
- Use Testing Library best practices
- Subagents handle test execution
## Escalation Rules
- Confirm before major architectural changes
- Ask before adding new dependencies
- Verify accessibility requirements
""",
"fullstack": """# Claude Code Configuration - Full-Stack Project
## Project Overview
<!-- Describe your full-stack architecture -->
## Context Management Strategy
### When to Use Subagents
- **Frontend searches**: Delegate component searches
- **Backend analysis**: Isolate API endpoint analysis
- **Database operations**: Schema exploration in subagents
- **Build processes**: Run builds in isolated contexts
- **Test suites**: Execute frontend and backend tests separately
### Context Commands
- `/clear` between frontend/backend context switches
- `/compact` before cross-stack refactoring
- `think hard` for architectural decisions
## Development Workflow
1. **Planning**: Design full-stack feature flow
2. **Backend First**: Implement API endpoints
3. **Frontend**: Build UI components
4. **Integration**: Connect frontend to backend
5. **Testing**: Subagents test both layers
## Stack
- **Frontend**: <!-- React, Vue, etc. -->
- **Backend**: <!-- Node.js, Python, etc. -->
- **Database**: <!-- PostgreSQL, MongoDB, etc. -->
## API Patterns
<!-- REST, GraphQL, tRPC, etc. -->
## Testing Strategy
- Unit tests for business logic
- Integration tests for APIs
- Component tests for UI
- E2E tests for critical flows
## Escalation Rules
- Confirm before database migrations
- Ask before API contract changes
- Verify cross-stack impacts
""",
"data": """# Claude Code Configuration - Data Science Project
## Project Overview
<!-- Describe your data pipeline and analysis goals -->
## Context Management Strategy
### When to Use Subagents
- **Data exploration**: Delegate large dataset analysis
- **Model searches**: Find similar models in codebase
- **Documentation**: Research library documentation
- **Experiment runs**: Execute training in subagents
- **Result analysis**: Isolate metrics computation
### Context Commands
- `/clear` between experiments
- `/compact` before model refactoring
- `think harder` for model architecture decisions
## Development Workflow
1. **Data Exploration**: Subagent analyzes dataset
2. **Feature Engineering**: Design features in main context
3. **Model Development**: Implement and iterate
4. **Evaluation**: Subagent runs evaluation metrics
5. **Documentation**: Record experiment results
## Data Pipeline
<!-- Add your data sources and processing steps -->
## Model Architecture
<!-- Add your model details -->
## Experiment Tracking
<!-- MLflow, Weights & Biases, etc. -->
## Testing Strategy
- Unit tests for data processing
- Validation tests for model outputs
- Subagents handle long-running tests
## Escalation Rules
- Confirm before large dataset operations
- Ask before changing data schemas
- Verify model performance before deployment
""",
"library": """# Claude Code Configuration - Library Project
## Project Overview
<!-- Describe your library's purpose and API -->
## Context Management Strategy
### When to Use Subagents
- **API searches**: Find similar functions across codebase
- **Documentation**: Research upstream dependencies
- **Example analysis**: Review usage examples
- **Test execution**: Run test suites in subagents
- **Build verification**: Check builds across versions
### Context Commands
- `/clear` between feature implementations
- `/compact` before API refactoring
- `think` for public API design
## Development Workflow
1. **API Design**: Plan function signatures
2. **Implementation**: Implement core logic
3. **Documentation**: Write docstrings and examples
4. **Testing**: Comprehensive test coverage
5. **Verification**: Subagent runs full test suite
## API Principles
- Maintain backward compatibility
- Clear, consistent naming
- Comprehensive documentation
- Type hints/annotations
## Testing Strategy
- Unit tests for all public APIs
- Integration tests for workflows
- Docstring examples as doctests
- Subagents handle test execution
## Documentation
- Docstrings required for all public APIs
- Usage examples in docs/
- Changelog maintenance
## Escalation Rules
- Confirm before breaking API changes
- Ask before adding dependencies
- Verify semantic versioning
"""
}
def generate_claude_md(project_type: str, output_path: str) -> None:
"""Generate a CLAUDE.md file from a template."""
if project_type not in TEMPLATES:
raise ValueError(f"Unknown project type: {project_type}. Choose from: {', '.join(TEMPLATES.keys())}")
content = TEMPLATES[project_type]
# Create parent directory if it doesn't exist
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
# Write the file
output_file.write_text(content)
print(f"✅ Generated CLAUDE.md at {output_path}")
print(f" Template: {project_type}")
print(f"\n📝 Next steps:")
print(f" 1. Review and customize the generated CLAUDE.md")
print(f" 2. Fill in project-specific details")
print(f" 3. Commit it to your repository")
def main():
parser = argparse.ArgumentParser(
description="Generate a CLAUDE.md file for context-efficient Claude Code workflows"
)
parser.add_argument(
"--type",
choices=list(TEMPLATES.keys()),
default="general",
help="Project type template to use"
)
parser.add_argument(
"--output",
default="./CLAUDE.md",
help="Output path for the CLAUDE.md file"
)
args = parser.parse_args()
generate_claude_md(args.type, args.output)
if __name__ == "__main__":
main()