
Context Master
- 378 installs
- 50 repo stars
- Updated June 18, 2026
- josiahsiegel/claude-plugin-marketplace
context-master is an agent skill that designs prompt context, memory windows, retrieval chunks, and tool payloads so Claude Code agents stay accurate without exceeding token limits on multi-file projects.
About
context-master is a Claude Code plugin skill from josiahsiegel/claude-plugin-marketplace that optimizes planning and context management for multi-file websites, apps, and complex coding tasks. It plans optimal file creation order before implementation, prevents redundant work through dependency-aware architecture, and applies extended-thinking delegation patterns advertised at roughly 23x context efficiency. The plugin README reports 62% average context token reduction across workflows. The skill ships reference files for multi-file planning, universal practices across 8 core principles, workflow procedures, thinking delegation, anti-patterns, and Windows Git Bash path guidance. Developers reach for context-master when long Claude Code sessions lose thread coherence, agents re-read entire repos, or multi-step features need progressive task decomposition before writing code across many files.
- Token budget control
- Context prioritization
- RAG chunking
- Thread coherence
- Tool result trimming
Context Master by the numbers
- 378 all-time installs (skills.sh)
- +5 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #2,058 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill context-masterAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 378 |
|---|---|
| repo stars | ★ 50 |
| Last updated | June 18, 2026 |
| Repository | josiahsiegel/claude-plugin-marketplace ↗ |
How do you manage agent context on large codebases?
Design prompt context, memory windows, retrieval chunks, and tool payloads so Claude Code agents stay accurate without exceeding token limits or losing thread coherence.
Who is it for?
Developers running long Claude Code sessions on multi-file web apps who need structured context planning and token-efficient retrieval chunking.
Skip if: Single-file scripts, trivial one-shot edits, or teams that do not use Claude Code or API agents with context window constraints.
When should I use this skill?
User starts a complex multi-file project, mentions context limits, token overflow, planning file order, or asks for context-master on a long coding session.
What you get
Dependency-ordered file plan, chunked retrieval strategy, and delegation prompts that keep agent sessions coherent within token budgets.
- Multi-file creation plan
- Retrieval chunk strategy
- Extended-thinking delegation prompts
By the numbers
- Plugin README reports 62% average context token reduction
- Documents 8 core context-management principles in reference files
- Extended-thinking delegation patterns target ~23x context efficiency
Files
Context Master
Universal context management and planning skill for complex tasks, long sessions, and multi-file projects. Works the same way whether you are in the Web app, the API, or Claude Code CLI; CLI-specific bonuses live in references/claude-code-cli.md.
This SKILL.md is intentionally short. Detailed material lives in references/ — load only what you need.
When to activate
Activate proactively whenever the request matches one of:
- Multi-file project (3+ related files, websites, apps, APIs, doc sets).
- Architecture or technology decision ("should we use X or Y", "which approach…").
- Research / comparison / tradeoff analysis.
- Refactoring or migration work.
- Long coding session where context efficiency matters.
- Any task with 3+ sequential steps or shared dependencies.
If the request is a single file with no dependencies, skip this skill.
The 5-step workflow (memorize this)
For any multi-file project — websites, apps, APIs, documentation sets — run these five steps in order:
1. STOP — do not create any files yet. 2. PLAN — use extended thinking or a planning document (both equally valid; see references/multi-file-planning.md). 3. ANNOUNCE — state the file list and creation order to the user. 4. CREATE — write files in optimal order (foundations before dependents). 5. VERIFY — check that every reference resolves; fix issues before declaring done.
Worked example (portfolio website)
User: "Create a portfolio with home, about, projects, and contact pages."
Step 1 STOP -- do not start with index.html.
Step 2 PLAN -- "Think hard about architecture: 5 files needed,
styles.css is the shared dependency."
Step 3 ANNOUNCE -- "I'll create:
1. styles.css (shared styling)
2. index.html (references styles.css)
3. about.html
4. projects.html
5. contact.html"
Step 4 CREATE -- write files in that order.
Step 5 VERIFY -- every HTML file links styles.css; navigation resolves.
Result: no refactor, no re-export, no broken links.The full template, optimal-order patterns by project type (website / React / backend API / etc.), and verification checklists are in references/multi-file-planning.md.
Core principles (one line each)
1. Plan before you write — extended thinking or planning doc, never both skipped. 2. Foundations first — shared dependencies (CSS, config, base classes, schemas) precede dependents. 3. Delegate deep analysis to isolated contexts — subagents (CLI) or thinking artifacts (Web/API) keep the main thread clean. 4. Phase boundaries — name each phase ("Phase 1 complete; moving to Phase 2: …") so context doesn't blur. 5. Artifacts over inline content — long code or docs live in artifacts/files, not chat history. 6. Progressive disclosure — ask for one slice at a time; don't batch unrelated steps. 7. Signal resets — say "setting aside the previous approach…" when changing direction. 8. Reflect after large projects — was it planned? Did references break? Use the post-project checklist in references/multi-file-planning.md.
Full rationale and examples for every principle: references/universal-best-practices.md.
Token-savings rule of thumb
| Project size | Without planning | With planning | Savings |
|---|---|---|---|
| Small (3-4 files) | ~6,000 tokens | ~2,500 tokens | ~58% |
| Medium (7-8 files) | ~12,000 tokens | ~4,500 tokens | ~63% |
| Large (20+ files) | ~35,000 tokens | ~12,000 tokens | ~66% |
A 200K-token context window holds roughly 16-17 medium projects with planning, 7-8 without — a 2.1x effective increase. Numbers and methodology in references/multi-file-planning.md.
Passive deep-thinking architecture
The single most powerful pattern for context efficiency: route deep reasoning into an isolated space and return a short summary to the main thread.
- Claude Code CLI:
/agent deep-analyzer "Ultrathink about [decision]"— ~5K tokens of reasoning happens out-of-band; main context receives a ~200-token summary (~23x efficiency). - Web / API:
"Create a deep-analysis artifact and ultrathink about [decision]"— same idea, artifact instead of subagent.
Triggers, anti-patterns, and ready-made prompts: references/thinking-delegation.md.
Common workflows (pointers only)
Each of these has a step-by-step procedure in references/workflows.md:
- Workflow 0 — Multi-file website/project creation (the default — same 5 steps above with extra detail).
- Workflow 1 — Complex decision-making (architecture, tech choice).
- Workflow 2 — Complex feature development (analysis → design → implement → test → integrate).
- Workflow 3 — Research and technology evaluation.
- Workflow 4 — Code generation and iteration via artifacts.
- Workflow 5 — Refactoring with isolated analysis.
Anti-patterns (avoid these)
Quick list — examples and fixes in references/anti-patterns.md:
1. Creating files before planning — wastes context on refactors. 2. Asking for everything at once — overloads context and produces shallow output. 3. Inlining long code/docs in chat — bloats history; use artifacts/files. 4. Letting deep reasoning happen in main thread — costs ~5K tokens that could be ~200. 5. No phase boundaries — context blurs across unrelated subtasks.
Troubleshooting
When sessions drift (responses unfocused, conversations getting too long, code regenerating instead of editing, extended thinking not engaging), see references/troubleshooting.md for a symptom → remedy table covering Web/API and CLI separately.
Claude Code CLI bonuses
If you are running in Claude Code CLI, you also get:
/clear,/compact,/continue— built-in context controls./agent <name>— delegate to an isolated subagent.CLAUDE.md— persistent project memory.- Helper scripts for generating
CLAUDE.mdand subagent definitions.
Details, script invocations, and the deep-analysis delegation patterns: references/claude-code-cli.md.
Skill–subagent integration patterns (when both are available) live in references/agent-skills-integration-2025.md. Long-form context strategies and subagent prompt patterns: references/context_strategies.md and references/subagent_patterns.md.
Reference map
| File | Use when |
|---|---|
references/multi-file-planning.md | Planning template, optimal-order patterns by project type, verification checklists, post-project reflection. |
references/universal-best-practices.md | Need the rationale or examples for any of the 8 core principles. |
references/workflows.md | Need a step-by-step procedure for a specific scenario (decision, feature, research, refactor). |
references/thinking-delegation.md | Designing a deep-analysis delegation or writing the thinking prompt. |
references/anti-patterns.md | Reviewing whether the current approach is wasting context. |
references/troubleshooting.md | Session is drifting, slow, or producing too much explanation. |
references/claude-code-cli.md | Running in Claude Code CLI and want subagent / CLAUDE.md tooling. |
references/agent-skills-integration-2025.md | Combining skills with subagents in CLI. |
references/context_strategies.md | Long-form strategy notes. |
references/subagent_patterns.md | Subagent prompt patterns. |
Success indicators
- You announced the plan before creating any file.
- Foundation files (CSS, config, schemas) were written before dependents.
- No reference broke on first run; no refactor was needed.
- Deep reasoning happened in a subagent or artifact, not the main thread.
- Phases were named as you crossed them.
If any of those failed, walk back through references/anti-patterns.md and references/multi-file-planning.md post-project section before the next task.
🚨 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
# 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.mdPattern 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 patternsRecommended CLAUDE.md Strategy for This Skill
Include in your project's CLAUDE.md:
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
# 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 contextPattern 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 mainContext 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 patternImplementation 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 referencesReal-World Example: Frontend Agent Skill
# 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 neededMeasuring 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
Multi-file context anti-patterns
Five concrete creation-order anti-patterns and their fixes. Use these as references when planning the order in which files will be written.
Anti-pattern 1: JS modules before the main app file
Wrong:
1. Create utils.js
2. Create helpers.js
3. Create api.js
4. Create app.js (main file that imports all the above)
Problem: Had to keep going back to app.js to add importsRight:
1. Think about module structure
2. Create app.js (with import statements planned)
3. Create utils.js (knowing what app.js needs)
4. Create helpers.js (knowing what app.js needs)
5. Create api.js (knowing what app.js needs)
Benefit: app.js structured correctly from the startAnti-pattern 2: Inline styles then extract later
Wrong:
1. Create index.html with inline styles
2. Create about.html with inline styles
3. Realize styles are duplicated
4. Extract to styles.css
5. Update all HTML files to reference it
Problem: Redundant work, had to edit multiple filesRight:
1. Think: These pages will share styling
2. Create styles.css first
3. Create HTML files that reference styles.css
Benefit: No duplication, no refactoring neededAnti-pattern 3: Components before data structure
Wrong:
1. Create UserProfile.jsx component
2. Create UserList.jsx component
3. Realize data structure is unclear
4. Go back and modify components to match data
Problem: Components built on assumptionsRight:
1. Think about data structure first
2. Create types.js or schema.js
3. Create components that use defined data structure
Benefit: Components built correctly from the startAnti-pattern 4: Pages before shared layout
Wrong:
1. Create home.html with full layout
2. Create about.html with full layout
3. Realize layout should be shared
4. Extract to layout component/template
5. Refactor all pages
Problem: Major refactoring requiredRight:
1. Think: Pages will share layout
2. Create layout.html or Layout component
3. Create pages that use the layout
Benefit: DRY from the startAnti-pattern 5: Config files last
Wrong:
1. Create multiple files with hardcoded values
2. Realize config should be centralized
3. Create config.js
4. Update all files to use config
Problem: Config scattered, hard to changeRight:
1. Think: What values will be used across files?
2. Create config.js first
3. Create other files that import config
Benefit: Centralized configuration from startClaude Code CLI tooling
Bonus features only available when using Claude Code CLI. Web and API users can skip this reference.
Generate CLAUDE.md
Create a context-optimized CLAUDE.md for your project:
python scripts/generate_claude_md.py --type [TYPE] --output ./CLAUDE.mdAvailable types:
general- general-purpose projectsbackend- API/service projectsfrontend- web applicationsfullstack- full-stack applicationsdata- data science / ML projectslibrary- library / package development
Claude Code reads CLAUDE.md automatically, providing persistent project guidance across sessions.
Create subagents
For recurring tasks, create dedicated subagents:
python scripts/create_subagent.py [NAME] --type [TYPE] --output [DIR]Types:
researcher- documentation searches with deep analysistester- test execution with failure analysisanalyzer- code analysis with architectural insightsbuilder- build / deployment tasksdeep_analyzer- complex decisions requiring extensive thinking (recommended for architecture, tech choices, design patterns)
This writes .claude/agents/[NAME].md. Invoke with:
/agent [NAME] [task description]Built-in commands
/clear- reset context between tasks/compact- compress context while preserving key decisions/continue- resume previous session/agent [NAME]- delegate task to a subagent with isolated context
Patterns
Deep-analysis delegation
1. /clear (start fresh)
2. /agent deep-analyzer "Ultrathink about [complex decision]"
3. [Receives well-reasoned analysis in ~200 tokens]
4. Make decision and implement
5. Main context stayed clean throughoutResearch with thinking
1. /agent pattern-researcher "Research [topic] and think hard about implications"
2. [Subagent searches + thinks in isolation]
3. Review findings in main context
4. Proceed with informed decisionTDD with analysis
1. Write test in main context
2. /agent test-runner "Run test and think hard if it fails"
3. [Subagent analyzes root cause in isolation]
4. Implement fix based on analysis
5. /agent test-runner "verify"
6. If passing: commit and /clearArchitecture evolution
1. /agent analyzer "Think deeply about current architecture issues"
2. [Receives analysis: bottlenecks, technical debt, opportunities]
3. /agent deep-analyzer "Recommend evolution strategy"
4. Create EVOLUTION.md plan
5. /clear
6. Execute plan phase by phaseLarge refactoring with thinking
1. /agent analyzer "Think hard about refactoring scope and risks"
2. [Receives risk assessment + strategy]
3. Create REFACTOR.md plan
4. /clear
5. For each file:
- Load and refactor
- /agent test-runner "analyze test results"
- /clear before nextFor detailed Claude Code patterns see subagent_patterns.md and context_strategies.md.
Scripts
generate_claude_md.py
python scripts/generate_claude_md.py --type TYPE --output PATHOptions:
--typeproject type (general, backend, frontend, fullstack, data, library)--outputoutput path (default:./CLAUDE.md)
create_subagent.py
python scripts/create_subagent.py NAME --type TYPE --output DIROptions:
NAMEagent name (e.g.,test-runner,doc-searcher)--typeagent type (researcher, tester, analyzer, builder, deep_analyzer)--outputoutput directory (default: current directory)
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 projectStrategy 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 taskWhen 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 featureWhen 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 coordinationWhen 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 /clearWhen 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:
# 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 persistsWhen 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 implementationTechnique: 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 upfrontTechnique: 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
Multi-file project planning
Detailed planning procedure for any project that touches three or more related files. The headline workflow lives in SKILL.md; this reference holds the full template, the optimal-order patterns by project type, and the verification checklists.
Two planning methods
Both are equally effective. Pick based on project complexity.
Method A: extended thinking
"Think hard about the architecture for this [project]:
- What files are needed and their purpose?
- What are shared dependencies?
- What is optimal creation order?
- What are cross-file references?
- What could go wrong?"Best for: quick projects, straightforward structures, when planning fits in a thinking block.
Method B: planning document
Create ARCHITECTURE_PLAN.md (via Write tool or artifact):
- Files needed with purposes
- Shared dependencies
- Numbered creation order with reasoning
- Cross-file reference map
- Potential issues to avoidBest for: complex projects, when you want a reference document, when planning is extensive.
Architecture plan template
ARCHITECTURE PLAN TEMPLATE
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]
- [file C] imports [file D] via [method]
POTENTIAL ISSUES TO AVOID:
- [what could go wrong]
- [common mistake]Filled example: portfolio website
ARCHITECTURE PLAN
FILES NEEDED:
- styles.css: Shared styling for all pages
- index.html: Home page with navigation
- about.html: About page
- projects.html: Portfolio showcase
- contact.html: Contact form
SHARED DEPENDENCIES:
- styles.css: All HTML files need this for consistent styling
CREATION ORDER:
1. styles.css - Shared dependency, all HTML files will reference it
2. index.html - Main entry point, establishes structure
3. about.html - References styles.css which now exists
4. projects.html - References styles.css which now exists
5. contact.html - References styles.css which now exists
CROSS-FILE REFERENCES:
- All HTML files link to styles.css via <link rel="stylesheet">
- All HTML pages link to each other via <a href="...">
POTENTIAL ISSUES TO AVOID:
- Creating HTML before CSS - would require going back to add links
- Inline styles in HTML - would require extraction later
- Inconsistent navigation - hard to maintain across filesOptimal file creation order
General principles:
1. Foundations first - shared dependencies before dependents (CSS before HTML, config before code, base classes before derived classes). 2. Core before features - essential files first (index.html before other pages, main.js before feature modules). 3. Structure before content - layout before details (HTML structure before detailed content, API skeleton before endpoint implementations).
Common patterns by project type:
Website project:
1. styles.css (shared styling)
2. index.html (home page - references styles.css)
3. about.html (references styles.css)
4. projects.html (references styles.css)
5. contact.html (references styles.css)
6. script.js (if needed)
React application:
1. package.json (dependencies)
2. App.js (main component)
3. components/Header.js
4. components/Footer.js
5. pages/Home.js
6. pages/About.js
7. styles/main.css
Backend API:
1. config.js (configuration)
2. database.js (DB connection)
3. models/User.js (data models)
4. routes/auth.js (route handlers)
5. routes/api.js
6. server.js (entry point)Token-savings illustration
| Project size | Without planning | With planning | Savings |
|---|---|---|---|
| Small (3-4 files) - portfolio website | ~6,000 tokens | ~2,500 tokens | ~3,500 (58%) |
| Medium (7-8 files) - multi-page app | ~12,000 tokens | ~4,500 tokens | ~7,500 (63%) |
| Large (20+ files) - full application | ~35,000 tokens | ~12,000 tokens | ~23,000 (66%) |
Context-window capacity: with planning you can complete ~16-17 medium projects per 200K window vs ~7-8 without (2.1x effective increase).
Step 3: create files with awareness
As each file is written:
- Reference what was already created.
- Note what future files will depend on this one.
- Keep naming and structure consistent.
- Add comments about dependencies where helpful.
Step 4: verify
File-path verification
- CSS links: <link href="styles.css"> (not "style.css" or "css/styles.css")
- JS scripts: <script src="script.js">
- Images: <img src="image.png">
- Relative paths match actual file structureReference-loading verification
- HTML files find the CSS file
- JavaScript imports resolve correctly
- No 404 errors for missing files
- Correct syntax in link / script tagsNavigation verification (for websites)
- All navigation links point to correct files
- Links use correct relative paths
- No broken navigation
- Back / forward navigation works logicallyCross-file reference verification
- Components import correctly
- Modules can access exported functions
- Shared utilities are accessible
- API calls reference correct endpointsConsistency verification
- Naming conventions consistent
- Styling uniform (if using shared CSS)
- Code structure follows same patterns
- Documentation style matches across filesFilled verification: portfolio website
After creating styles.css, index.html, about.html, projects.html, contact.html:
[OK] All HTML files have <link rel="stylesheet" href="styles.css">
[OK] styles.css exists and has content
[OK] Navigation links:
- index.html links to about.html, projects.html, contact.html
- All other pages link back to index.html
[OK] All pages use consistent styling from styles.css
[OK] No broken links or missing file references
Result: project structure verified, ready to use.If verification fails, fix issues before considering the project complete.
When to use this planning approach
Always plan first for:
- Websites with multiple pages (3+ HTML files)
- Applications with multiple components
- Projects with shared dependencies (CSS, config files)
- API implementations with multiple endpoints
- Documentation sets with multiple files
- Any project where files reference each other
Skip planning for:
- Single-file creations
- Truly independent files with no relationships
- Simple, obvious structures
Post-project reflection
1. Did you plan before creating files? [Yes/No]
2. How many files did you create? [Number]
3. Did you have to refactor or fix file references? [Yes/No]
4. If you planned first:
- Estimated context used: ~[2,500-4,500] tokens for [3-8] files
5. If you skipped planning:
- You likely used: ~[6,000-12,000] tokens
- Potential savings missed: ~[3,500-7,500] tokensSuccess indicators:
- Created foundation files (CSS, config) before dependent files.
- No major refactoring needed after file creation.
- All file references worked on first try.
- Could describe file creation order before starting.
- Spent more time planning than fixing.
Improvement signals:
- Had to go back and add shared dependencies.
- Needed to refactor file structure after creation.
- Found broken references between files.
- Created files in no particular order.
- Spent more time fixing than planning.
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 suiteAd-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
# 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 autonomouslyTest Runner Subagent
File: .claude/agents/test-runner.md
# 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 autonomouslyCode Analyzer Subagent
File: .claude/agents/analyzer.md
# 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 suggestionsAnti-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+ tokensContext 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 passingWhy 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
- /clearWhy 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 thinkingMeta-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---
Passive deep-thinking architecture
The key insight: extended thinking can happen in isolated contexts (subagents on Claude Code, thinking artifacts on web/API), keeping the main session lean while still getting deep analysis.
Architectural pattern
Main Session (Orchestrator)
├─ Stays high-level and focused
├─ Makes decisions based on summaries
└─ Delegates complex analysis
↓ delegates with thinking triggers ↓
Analysis Layer (Agents/Artifacts)
├─ Extended thinking happens HERE (5K+ tokens)
├─ Deep reasoning happens HERE
├─ Context-heavy work happens HERE
└─ Returns concise summaries UP (~200 tokens)
↑ returns actionable conclusions ↑
Main Session
└─ Receives well-reasoned recommendations
└─ Context stays clean for sustained workHow this achieves passive deep thinking
Without thinking delegation:
- Extended thinking happens in main context.
- Reasoning accumulates (~5K tokens per analysis).
- Context fills quickly over long sessions.
- Eventually hits limits.
With thinking delegation:
- Subagents/artifacts do extended thinking in isolation.
- Main context only receives summaries (~200 tokens).
- Can sustain 25+ analyses before context issues.
- Deep thinking happens passively through architecture.
Key benefit: You get the depth of extended thinking without the context cost.
Implementation by environment
Claude Code: thinking subagents
# Create a deep analyzer for complex decisions
python scripts/create_subagent.py architecture-advisor --type deep_analyzer
# Create thinking-enabled researcher
python scripts/create_subagent.py pattern-researcher --type researcherUsage:
Main session: "I need to decide between microservices and monolith"
↓
/agent architecture-advisor "Analyze microservices vs monolith
for an e-commerce platform with 10M users, considering team size
of 8 developers"
↓
Subagent's isolated context:
- Uses "ultrathink" automatically
- 5K+ tokens of deep reasoning
- Evaluates tradeoffs thoroughly
↓
Returns to main: "After deep analysis, I recommend starting with
a modular monolith because [3 key reasons]. Microservices would
add complexity your team size can't support yet."
↓
Main session: Receives actionable advice, context cleanContext saved: ~4,800 tokens per analysis.
Web/API: thinking artifacts
User: "Analyze the best database for this use case"
Claude: "I'll create a deep analysis artifact where I can think
through this thoroughly."
[Creates artifact: "database-analysis.md"]
[Inside artifact:
- Extended thinking block (collapsed in UI)
- Detailed analysis
- Comparison tables
- Final recommendation
]
Main conversation: "Based on the analysis artifact, I recommend
PostgreSQL because [2-sentence summary]. See artifact for complete
reasoning including performance comparisons and scaling considerations."Why this works:
- Thinking is visually separated (in artifact).
- Main conversation stays summary-focused.
- User can reference artifact when needed.
- Conversational context stays lean.
When to delegate vs keep in main
Delegate to thinking agents/artifacts for:
- Architecture decisions
- Technology evaluations
- Complex tradeoff analysis
- Multi-factor comparisons
- Design pattern selection
- Performance optimization strategies
- Security assessment
- Refactoring approach planning
Keep in main context for:
- Simple implementation
- Quick queries
- Tactical decisions with obvious answers
- Tasks requiring full project context
Example: state management for React app
Traditional approach (main context):
User: "What state management should I use?"
Claude: [5K tokens of thinking in main context]
Claude: [Another 2K tokens explaining recommendation]
Total: ~7K tokens consumedThinking-delegation approach:
User: "What state management should I use for a large e-commerce app?"
Claude Code:
"This warrants deep analysis. Let me delegate to a deep analyzer."
/agent architecture-advisor "Think deeply about state management
options (Redux, Zustand, Jotai, Context) for large-scale e-commerce
with real-time inventory"
[Subagent uses ultrathink in isolated context - 5K tokens]
[Returns summary - 200 tokens]
Main context: "The advisor recommends Zustand for these reasons..."
Total in main: ~300 tokensContext efficiency: 23x improvement while maintaining analytical depth.
Compound effect over long sessions
Without delegation:
- Analysis 1: 7K tokens
- Analysis 2: 7K tokens
- Analysis 3: 7K tokens
- Analysis 4: 7K tokens
- Analysis 5: 7K tokens
- Total: 35K tokens (17% of 200K context)
With delegation:
- Analysis 1: 300 tokens
- Analysis 2: 300 tokens
- Analysis 3: 300 tokens
- Analysis 4: 300 tokens
- Analysis 5: 300 tokens
- Total: 1.5K tokens (0.75% of 200K context)
Result: 23x more analyses in the same context window while maintaining analytical rigor.
Context troubleshooting
Symptoms you may see in long or complex sessions, with universal and environment-specific remedies.
"Responses are getting less focused"
Symptom: Claude references old, irrelevant information or responses drift off topic.
Solutions:
- Web/API: "Setting aside previous discussion, let's focus on..."
- Claude Code:
/clearor/compact - Universal: break task into new phases with clear boundaries
"Complex task feels overwhelming"
Symptom: unsure where to start, too many moving parts.
Solutions: 1. "think harder about breaking this into phases" 2. Create a planning artifact 3. Execute one phase at a time 4. Reference plan artifact as you go
"Conversation getting too long"
Symptom: long history, hard to track what's been decided.
Solutions:
- Web/API: create a
decisions.mdartifact to summarize key points - Claude Code:
/compactto compress history - Universal: start a new conversation with "Previously we decided X, Y, Z. Now let's..."
"Need to maintain context across sessions"
Symptom: having to re-explain everything each time.
Solutions:
- Create artifacts documenting key decisions and context.
- Claude Code: use
CLAUDE.mdfor persistent project memory. - Start new sessions with "Continuing from previous work where we [brief summary]".
"Code keeps being regenerated instead of edited"
Symptom: small changes result in entire code rewrites.
Solutions: 1. Use artifacts for code. 2. Request specific edits: "Update the handle_request function to add validation". 3. Don't say "show me the code again" - reference the existing artifact.
"Responses include too much explanation"
Symptom: lengthy explanations when you just want output.
Solutions:
- Be explicit: "Just create the artifact, minimal explanation".
- "Output only, no commentary".
- "Concise response please".
"Extended thinking not being used"
Symptom: jumping straight to solutions without analysis.
Solutions:
- Explicitly request: "think hard about...".
- Use stronger triggers: "ultrathink about...".
- Ask for planning: "think about multiple approaches".
Universal best practices
Eight rules that apply regardless of environment (Web, API, Claude Code CLI).
1. Delegate complex analysis to isolated contexts
The single most powerful pattern for context efficiency.
Claude Code:
GOOD: /agent deep-analyzer "Ultrathink about [complex decision]"
BAD: "Think about [complex decision]" (happens in main context)Web/API:
GOOD: "Create analysis artifact and ultrathink about [decision]"
BAD: "Ultrathink about [decision]" (thinking stays in conversation)Benefit: ~5K tokens of reasoning happens in isolation, main context receives ~200 token summary. 23x context efficiency while maintaining analytical depth.
2. Use extended thinking for planning
Before diving into implementation:
"think hard about the approach for [task]"Even better with delegation:
- Claude Code: delegate to deep_analyzer subagent.
- Web/API: use thinking artifact.
Benefit: reasoning stays out of main context, you get thoughtful plans.
3. Create artifacts for substantial content
Don't inline long code or documents in conversation:
GOOD: "Create a Python script artifact that [functionality]"
BAD: "Show me the Python code for [functionality]"Benefit: content lives in artifacts, not conversation history.
4. Break complex tasks into explicit phases
State phase transitions clearly:
"Phase 1 complete. Moving to Phase 2: [description]"With thinking delegation:
Phase 1: /agent deep-analyzer "analyze approaches"
Phase 2: Implement based on analysisBenefit: each phase has clear purpose and boundaries.
5. Document decisions in artifacts
Create persistent references:
"Create a decisions.md artifact tracking our key choices"Benefit: you can reference decisions without re-explaining full context.
6. Progressive disclosure
Don't request everything at once:
GOOD: "First, analyze the requirements"
"Now, design the data model"
"Now, implement the core logic"
BAD: "Analyze requirements, design data model, and implement everything"Benefit: each step builds on the last without overwhelming context.
7. Use thinking for exploration
When uncertain about approach:
"ultrathink about multiple approaches and recommend the best one"Even better: delegate to deep_analyzer (Claude Code) or thinking artifact (Web/API).
Benefit: deep analysis without context clutter.
8. Signal context resets
When changing direction:
"Setting aside the previous approach, let's try a different angle..."Benefit: clear boundaries prevent old context from interfering.
Advanced patterns
Iterative refinement
1. "Create initial version of [artifact]"
2. Review
3. "Improve [specific aspect]"
4. Review
5. "Add [feature]"
6. Continue iteratingMulti-artifact projects
1. "Create architecture.md artifact"
2. "Create database-schema.sql artifact"
3. "Create api-spec.yaml artifact"
4. "Now implement based on these artifacts"Thinking → document → execute
1. "ultrathink about [complex problem]"
2. "Document the decision in a plan artifact"
3. "Execute phase 1 of the plan"
4. Reference plan artifact as you continueChunked content generation
1. "Create outline artifact"
2. "Write introduction (add to artifact)"
3. "Write section 1 (add to artifact)"
4. Continue section by sectionCommon context-management workflows
These six workflows cover the recurring complex tasks across Claude Code and Web/API. Each one starts with a planning or delegation step, then proceeds in clearly named phases.
Workflow 0: Multi-file website/project creation (most common)
If the user said "create a website/app with multiple pages", you are in this workflow.
Mandatory sequence:
STEP 1: STOP AND THINK (always first)
Output: "Think hard about the architecture for this [project]..."
[Extended thinking plans: files needed, creation order, dependencies]
STEP 2: ANNOUNCE THE PLAN
Output: "I'll create these files in this order:
1. styles.css (shared styling)
2. index.html (home page)
3. about.html
4. projects.html
5. contact.html"
STEP 3: CREATE FOUNDATION FILES FIRST
Create: styles.css
STEP 4: CREATE DEPENDENT FILES
Create: index.html (references styles.css)
Create: about.html (references styles.css)
Create: projects.html (references styles.css)
Create: contact.html (references styles.css)
STEP 5: VERIFY
Check: All HTML files reference styles.css correctlyExample: portfolio website
User: "Create a portfolio website with home, about, projects, and contact pages"
Before creating any files, output:
"Let me think hard about the architecture first..."
[Extended thinking plans:
- Files needed: index.html, about.html, projects.html, contact.html, styles.css
- Optimal order: styles.css FIRST (shared dependency), then HTML pages
- Dependencies: All HTML files reference styles.css
- Structure: Simple multi-page site with shared stylesheet]
Then announce the plan:
"I'll create the files in this order:
1. styles.css - Shared styling for all pages
2. index.html - Home page (references styles.css)
3. about.html - About page (references styles.css)
4. projects.html - Projects page (references styles.css)
5. contact.html - Contact page (references styles.css)
This ensures dependencies are in place before files that need them."
Then create files in that exact order.Wrong vs right
WRONG:
User: "Create a portfolio website with home, about, projects, and contact pages"
[Immediately creates index.html without thinking]
[Creates about.html]
[Creates projects.html]
[Realizes CSS should be shared, has to go back and add it]
This wastes effort and context.RIGHT:
User: "Create a portfolio website with home, about, projects, and contact pages"
"Think hard about architecture..." [Plans first]
"I'll create in this order: CSS first, then HTML pages" [Announces plan]
[Creates styles.css]
[Creates HTML pages that reference styles.css]
Efficient - no redundant work.Workflow 1: Complex decision-making
Claude Code:
User: "Should we use microservices or monolith?"
1. /agent deep-analyzer "Ultrathink about architecture choice
for 10M user e-commerce platform, 8 dev team"
2. [Receives well-reasoned recommendation in main context]
3. Make decision based on analysis
4. Proceed with implementationWeb/API:
User: "Should we use microservices or monolith?"
1. "Create a deep-analysis.md artifact and ultrathink about this"
2. [Artifact contains extended thinking + conclusion]
3. Main conversation: "Based on analysis, recommend monolith because..."
4. Proceed with implementationContext efficiency: deep thinking happens, main context stays clean.
Workflow 2: Complex feature development
Phase 1: Architecture analysis
Claude Code: /agent deep-analyzer "Think deeply about architecture for [feature]"
Web/API: "Create architecture-analysis artifact with deep thinking"
[Isolated thinking → summary to main]
Phase 2: Design planning
"Based on that analysis, create implementation plan artifact"
[Main context references analysis conclusions]
Phase 3: Implementation
"Implement component A based on the plan"
[Create code artifact]
Phase 4: Testing
Claude Code: /agent test-runner "Run tests and analyze failures"
Web/API: "Run tests" [test output in separate space]
Phase 5: Integration
"Integrate based on architecture plan"Why it works: each phase has a clear purpose, thinking isolated where needed.
Workflow 3: Research & technology evaluation
Phase 1: Deep research
Claude Code: /agent pattern-researcher "Research and think hard about
authentication approaches, analyze tradeoffs"
Web/API: "Create research-findings artifact and think through options"
Phase 2: Synthesis
[Receives summary of findings]
"Create comparison table artifact"
Phase 3: Recommendation
Claude Code: /agent deep-analyzer "Based on research, recommend approach"
Web/API: "Based on research artifact, ultrathink and recommend"
Phase 4: Implementation
"Implement recommended approach"Why it works: research and deep analysis isolated, implementation focused.
Workflow 4: Code generation & iteration
1. "Create a [language] script that [functionality]"
→ Artifact created
2. "Add [feature] to the script"
→ Artifact updated
3. "Optimize the [specific part]"
→ Targeted update
4. "Add error handling"
→ Incremental improvementWhy it works: all code lives in the artifact; conversation stays focused on what to change.
Workflow 5: Refactoring with analysis
Claude Code:
1. /agent analyzer "Think hard about refactoring approach
for legacy auth system"
2. [Receives analysis in main: strategy, risks, order]
3. "Create REFACTOR.md plan based on analysis"
4. /clear
5. For each module:
- Refactor according to plan
- /agent test-runner "verify changes"
- Commit
- /clear before nextWeb/API:
1. "Create refactoring-analysis artifact, think deeply about approach"
2. [Artifact has thinking + strategy]
3. "Create refactoring-plan artifact based on analysis"
4. Implement module by module
5. Reference plan artifact as you workWhy it works: deep analysis happens once (isolated), execution follows a clean plan.
#!/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()
#!/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()
Related skills
How it compares
Use context-master for upfront multi-file planning and token budgeting; reach for domain skills directly once file order and retrieval chunks are already defined.
FAQ
What problem does context-master solve?
context-master prevents Claude Code agents from exceeding token limits or losing thread coherence by planning file creation order, chunking retrieval context, and delegating deep analysis to extended-thinking patterns.
How much context does context-master save?
context-master's plugin README cites 62% average context token reduction, and its extended-thinking delegation patterns target roughly 23x context efficiency on complex multi-file tasks.
When should context-master activate proactively?
context-master should activate for complex planning, multi-file projects, architecture decisions, refactoring, research tasks, or any workflow with three or more sequential implementation steps.