feat: migrate commands to skills

This commit is contained in:
duthaho
2026-04-19 10:55:51 +07:00
parent 09538078e7
commit 70e258e1dc
62 changed files with 1880 additions and 4492 deletions
+36 -113
View File
@@ -6,38 +6,20 @@ This is a comprehensive Claude Kit for Claude Code, designed to accelerate devel
## Quick Reference
### Core Commands
### Key Skills (auto-triggered)
| Command | Description |
|---------|-------------|
| `/feature [desc]` | Full feature development workflow |
| `/fix [error]` | Smart debugging and bug fix |
| `/review [file]` | Comprehensive code review |
| `/test [scope]` | Generate tests |
| `/ship [msg]` | Commit + PR automation |
| `/plan [task]` | Task decomposition |
| `/doc [target]` | Documentation generation |
| `/deploy [env]` | Deployment workflow |
### Enhanced Commands
| Command | Description |
|---------|-------------|
| `/plan --detailed [task]` | Detailed plan with 2-5 min tasks |
| `/brainstorm [topic]` | Interactive design session |
| `/execute-plan [file]` | Subagent-driven plan execution |
| `/tdd [feature]` | Test-driven development workflow |
| `/research [topic]` | Technology research |
### New Commands
| Command | Description |
|---------|-------------|
| `/mode [name]` | Switch behavioral mode |
| `/index` | Generate project structure index |
| `/load [component]` | Load project context |
| `/checkpoint [action]` | Save/restore session state |
| `/spawn [task]` | Launch parallel background task |
| Skill | Triggers on |
|-------|------------|
| `feature-workflow` | "feature", "implement", "build", "add functionality" |
| `systematic-debugging` | "bug", "error", "failing", "broken", stack traces |
| `git-workflows` | "commit", "PR", "ship", "changelog" |
| `writing-plans` | "plan", "break down", "implementation steps" |
| `brainstorming` | "brainstorm", "design", "explore", "trade-offs" |
| `documentation` | "document", "docstring", "README", "API docs" |
| `refactoring` | "refactor", "clean up", "extract", "simplify" |
| `performance-optimization` | "slow", "performance", "profiling", "N+1" |
| `mode-switching` | "mode", "switch mode", "token-efficient" |
| `session-management` | "checkpoint", "index", "load context", "status" |
## Tech Stack
@@ -184,96 +166,36 @@ Modes adjust communication style, output format, and problem-solving approach.
### Mode Activation
```bash
/mode brainstorm # Switch mode for session
/feature --mode=implementation # Override for single command
```
Ask Claude to switch modes naturally:
- "switch to brainstorm mode" → creative exploration
- "use implementation mode" → code-focused, minimal prose
- "switch to token-efficient mode" → compressed output (30-70% savings)
Mode files: `.claude/modes/`
## Command Flags
<!-- CUSTOMIZATION POINT: Set default flag values -->
All commands support combinable flags for flexible customization.
### Universal Flags
| Flag | Description | Values |
|------|-------------|--------|
| `--mode=[mode]` | Behavioral mode | default, brainstorm, token-efficient, etc. |
| `--depth=[1-5]` | Thoroughness level | 1=quick, 5=exhaustive |
| `--format=[fmt]` | Output format | concise, detailed, json |
| `--save=[path]` | Save output to file | File path |
| `--checkpoint` | Create state checkpoint | Boolean |
### Persona Flags
| Flag | Description |
|------|-------------|
| `--persona=security` | Security-focused analysis |
| `--persona=performance` | Performance-focused analysis |
| `--persona=architecture` | Architecture-focused analysis |
### Examples
```bash
/review --persona=security --depth=5 src/auth/
/plan --mode=brainstorm --save=plans/design.md "feature"
/fix --format=concise "error message"
```
## Token Optimization
<!-- CUSTOMIZATION POINT: Set default output mode -->
Control output verbosity for cost optimization.
| Level | Flag | Savings | Description |
|-------|------|---------|-------------|
| Level | Activation | Savings | Description |
|-------|-----------|---------|-------------|
| Standard | (default) | 0% | Full explanations |
| Concise | `--format=concise` | 30-40% | Reduced explanations |
| Ultra | `--format=ultra` | 60-70% | Code-only responses |
### Session-Wide Optimization
```bash
/mode token-efficient # Enable for entire session
```
| Concise | "be concise" | 30-40% | Reduced explanations |
| Ultra | "code only" | 60-70% | Code-only responses |
| Session | "switch to token-efficient mode" | 30-70% | Compressed for session |
Reference: `.claude/skills/writing-concisely/SKILL.md`
## Context Management
### Project Indexing
These features are provided by the `session-management` skill:
Generate and use project structure index for faster navigation:
```bash
/index # Generate PROJECT_INDEX.md
/load api # Load API context
/load --all # Load full project context
```
### Session Checkpoints
Save and restore conversation state:
```bash
/checkpoint save "feature-x" # Save current state
/checkpoint list # List checkpoints
/checkpoint restore "feature-x" # Restore state
```
### Parallel Tasks
Launch background tasks for concurrent work:
```bash
/spawn "research auth patterns"
/spawn --list # Check status
/spawn --collect # Gather results
```
- **Project Indexing** — "generate a project index" → scans and creates PROJECT_INDEX.md
- **Context Loading** — "load the API context" → reads relevant files into context
- **Checkpoints** — "save checkpoint feature-x" → git stash + metadata for session recovery
- **Status** — "what's the project status?" → git state, tasks, recent commits
## MCP Integrations
@@ -304,7 +226,7 @@ Settings to control the integrated superpowers development methodology.
| `standard` | 15-60 min | Quick planning, experienced team |
| `detailed` | 2-5 min | Thorough plans with exact code |
To use detailed mode: `/plan --detailed [task]`
To use detailed mode: "plan this in detail" or "break this into 2-5 min tasks"
### Brainstorming Style
@@ -313,7 +235,7 @@ To use detailed mode: `/plan --detailed [task]`
| `standard` | All questions at once |
| `interactive` | One question per message with validation |
To use interactive mode: `/brainstorm [topic]`
To use interactive mode: "let's brainstorm [topic]"
### Execution Mode
@@ -322,12 +244,12 @@ To use interactive mode: `/brainstorm [topic]`
| `manual` | Developer executes tasks from plan |
| `subagent` | Automated execution with code review gates |
To use subagent mode: `/execute-plan [plan-file]`
To use subagent mode: "execute the plan" or "run the plan with subagents"
### TDD Strictness
For strict TDD enforcement (no production code without failing test):
- Use `/tdd [feature]` command
- Auto-triggers on implementation tasks
- Reference: `.claude/skills/test-driven-development/SKILL.md`
### Verification Requirements
@@ -347,8 +269,10 @@ Enable mandatory verification before completion claims:
| **Security** | owasp |
| **API** | openapi |
| **Testing** | testing (pytest, vitest, Jest), playwright |
| **Optimization** | writing-concisely |
| **Optimization** | writing-concisely, performance-optimization |
| **Developer Patterns** | error-handling, state-management, logging, caching, api-client, authentication, background-jobs |
| **Workflows** | feature-workflow, git-workflows, documentation, refactoring |
| **Session** | mode-switching, session-management |
| **Methodology - Planning** | brainstorming, writing-plans, executing-plans, writing-skills |
| **Methodology - Testing** | test-driven-development, verification-before-completion, testing-anti-patterns |
| **Methodology - Debugging** | systematic-debugging, root-cause-tracing, defense-in-depth |
@@ -369,7 +293,7 @@ Each skill includes:
For complex problems requiring step-by-step analysis:
- Reference: `.claude/skills/sequential-thinking/SKILL.md`
- Activation: `/research --sequential [topic]` or use deep-research mode
- Activation: auto-triggers on complex reasoning tasks, or use deep-research mode
## Environment Configuration
@@ -458,7 +382,6 @@ pnpm install
- **Claude Kit Version**: 3.0.0
- **Last Updated**: 2026-04-18
- **Compatible with**: Claude Code 1.0+
- **Total Skills**: 36 (with YAML frontmatter, bundled resources)
- **Total Commands**: 27+
- **Total Skills**: 43 (with YAML frontmatter, bundled resources)
- **Total Agents**: 20
- **Behavioral Modes**: 7
-55
View File
@@ -1,55 +0,0 @@
# /api-gen - API Generation Command
## Purpose
Generate API endpoints, documentation, or client code from specifications.
## Usage
```
/api-gen [resource name or OpenAPI spec path]
```
---
Generate API for: **$ARGUMENTS**
## Workflow
### Step 1: Define Resource
1. Identify resource properties
2. Define relationships
3. Determine operations
### Step 2: Generate
1. Create model/schema
2. Create routes/endpoints
3. Add validation
4. Generate tests
### Step 3: Document
1. Create OpenAPI spec
2. Add examples
3. Document errors
## Output
```markdown
## API Generated
### Endpoints
| Method | Path | Description |
|--------|------|-------------|
| GET | /resources | List all |
| POST | /resources | Create |
| GET | /resources/:id | Get one |
### Files Created
- `src/models/resource.ts`
- `src/routes/resource.ts`
- `tests/resource.test.ts`
- `docs/api/resource.md`
```
-219
View File
@@ -1,219 +0,0 @@
# /brainstorm - Interactive Design Session
## Purpose
Start an interactive brainstorming session using the one-question-at-a-time methodology. Refine rough ideas into fully-formed designs through collaborative dialogue.
## Usage
```
/brainstorm [topic or feature to design]
```
## Arguments
- `$ARGUMENTS`: The topic, feature, or problem to brainstorm about
---
Start interactive brainstorming session for: **$ARGUMENTS**
## Methodology
**Reference**: `.claude/skills/brainstorming/SKILL.md`
This command uses the superpowers brainstorming methodology for optimal results.
## Workflow
### Phase 1: Understanding
**Goal**: Clarify requirements through sequential questioning.
**Rules**:
1. Ask **ONE question per message**
2. Wait for user response before next question
3. Prefer **multiple-choice** over open-ended questions
4. Break complex topics into multiple questions
**Example interaction**:
```
Claude: "What type of authentication should we support?
a) Username/password only
b) OAuth providers (Google, GitHub)
c) Both options
d) Magic link (passwordless)"
User: "b"
Claude: "Which OAuth providers should we integrate?
a) Google only
b) GitHub only
c) Both Google and GitHub
d) Let me specify others..."
```
### Phase 2: Exploration
**Goal**: Present alternatives with clear trade-offs.
Present 2-3 approaches:
- Lead with recommended option
- Explain trade-offs for each
- Let user choose direction
```markdown
## Approach 1: JWT-based (Recommended)
- Stateless, scalable
- Cons: Can't revoke instantly
## Approach 2: Session-based
- Easy revocation
- Cons: Requires session store
Which approach aligns better with your goals?
```
### Phase 3: Design Presentation
**Goal**: Present validated design incrementally.
**Rules**:
- Break into **200-300 word sections**
- Validate after each section
- Cover: architecture, components, data flow, error handling, testing
**Sections to present**:
1. Architecture overview
2. Component breakdown
3. Data flow
4. Error handling
5. Testing considerations
## Core Principles
### YAGNI Ruthlessly
Remove unnecessary features aggressively:
- Question every "nice to have"
- Start with minimal viable design
- "We might need this later" = remove it
### One Question at a Time
Sequential questioning produces better results:
- Gives user time to think deeply
- Prevents overwhelming with choices
- Creates natural conversation flow
### Multiple-Choice Preference
When possible, provide structured options:
- Reduces cognitive load
- Surfaces your understanding
- Makes decisions concrete
## Output
After design is validated, create design document:
```markdown
# Design: [Feature Name]
Date: [YYYY-MM-DD]
## Summary
[2-3 sentences]
## Architecture
[Architecture decisions]
## Components
[Component breakdown]
## Data Flow
[How data moves through system]
## Error Handling
[Error scenarios and handling]
## Testing Strategy
[Testing approach]
## Open Questions
[Any remaining unknowns]
```
## Next Steps After Brainstorming
After design is complete:
1. Commit design document to version control
2. Use `/plan --detailed` for implementation planning
3. Use `/execute-plan` for automated implementation
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=brainstorm` |
| `--depth=[1-5]` | Exploration depth level | `--depth=4` |
| `--format=[fmt]` | Output format (concise/detailed) | `--format=detailed` |
| `--save=[path]` | Save design document to file | `--save=docs/design.md` |
| `--quick` | Shorter session, fewer questions | `--quick` |
| `--comprehensive` | Longer session, thorough exploration | `--comprehensive` |
### Flag Usage Examples
```bash
/brainstorm --comprehensive "authentication system design"
/brainstorm --save=docs/payment-design.md "payment integration"
/brainstorm --quick "simple file upload feature"
/brainstorm --depth=5 "microservices architecture"
```
### Session Depth
| Level | Questions | Exploration |
|-------|-----------|-------------|
| 1 | 2-3 | Quick validation only |
| 2 | 4-5 | Standard session |
| 3 | 6-8 | Thorough exploration |
| 4 | 8-10 | Comprehensive |
| 5 | 10+ | Exhaustive, all angles |
## MCP Integration
This command leverages MCP servers for enhanced brainstorming:
### Sequential Thinking - Structured Exploration (Primary)
```
ALWAYS use Sequential Thinking for brainstorming:
- Explore design options systematically
- Track pros/cons for each approach
- Revise conclusions based on user feedback
- Build confidence in final design incrementally
```
### Memory - Design Persistence
```
Store design decisions for continuity:
- Create entities for design concepts
- Store user preferences and constraints
- Recall previous design patterns
- Build knowledge graph of architecture decisions
```
### Context7 - Technology Options
```
When exploring technology choices:
- Fetch current documentation for options
- Compare library capabilities accurately
- Understand trade-offs with real data
```
## When NOT to Use
- Clear "mechanical" processes with known implementation
- Simple bug fixes with obvious solutions
- Tasks with explicit requirements already defined
Use direct implementation instead.
-47
View File
@@ -1,47 +0,0 @@
# /changelog - Changelog Command
## Purpose
Generate changelog entries from recent commits.
## Usage
```
/changelog [version or 'since:tag']
```
---
Generate changelog for: **$ARGUMENTS**
## Workflow
1. **Analyze Commits**
```bash
git log --oneline --since="last tag"
```
2. **Categorize**
- Added
- Changed
- Fixed
- Removed
3. **Generate**
- User-friendly descriptions
- Link to PRs/issues
## Output
```markdown
## [Version] - Date
### Added
- Feature description (#123)
### Changed
- Improvement description (#124)
### Fixed
- Bug fix description (#125)
```
-134
View File
@@ -1,134 +0,0 @@
# /checkpoint
## Purpose
Save and restore conversation context using git-based checkpoints. Enables session recovery and state preservation for complex, multi-session work.
---
Manage checkpoints for the current work session.
## Checkpoint Operations
### Save Checkpoint
Create a checkpoint of current state:
```bash
/checkpoint save [name]
```
**Process:**
1. Create git stash with descriptive message
2. Record current context (files being worked on, task state)
3. Save checkpoint metadata to `.claude/checkpoints/[name].json`
**Metadata Format:**
```json
{
"name": "feature-auth",
"created": "2024-01-15T14:30:00Z",
"git_stash": "stash@{0}",
"files_in_context": ["src/auth/login.ts", "src/auth/token.ts"],
"current_task": "Implementing JWT refresh",
"notes": "User-provided notes"
}
```
### List Checkpoints
Show available checkpoints:
```bash
/checkpoint list
```
**Output:**
```markdown
## Available Checkpoints
| Name | Created | Task | Stash |
|------|---------|------|-------|
| feature-auth | 2h ago | JWT refresh | stash@{0} |
| bugfix-login | 1d ago | Login timeout | stash@{1} |
```
### Restore Checkpoint
Restore a previous checkpoint:
```bash
/checkpoint restore [name]
```
**Process:**
1. Apply git stash
2. Load checkpoint metadata
3. Summarize restored context
4. Ready to continue work
### Delete Checkpoint
Remove a checkpoint:
```bash
/checkpoint delete [name]
```
## Flags
| Flag | Description |
|------|-------------|
| `--notes="[text]"` | Add notes to checkpoint |
| `--force` | Overwrite existing checkpoint |
| `--include-uncommitted` | Include uncommitted changes |
| `--dry-run` | Show what would be saved |
## Usage Examples
```bash
/checkpoint save auth-progress # Save current state
/checkpoint save auth --notes="WIP tokens" # Save with notes
/checkpoint list # Show checkpoints
/checkpoint restore auth-progress # Restore state
/checkpoint delete old-checkpoint # Remove checkpoint
```
## Arguments
$ARGUMENTS
Parse the operation (save/list/restore/delete) and checkpoint name.
---
## Auto-Checkpoint
For complex tasks, checkpoints are automatically suggested:
- Before major refactoring
- When switching contexts
- Before risky operations
- At natural breakpoints
## Best Practices
1. **Name Descriptively**: Use task-related names
2. **Add Notes**: Future you will thank present you
3. **Checkpoint Often**: Before context switches
4. **Clean Up**: Delete obsolete checkpoints
## Recovery Workflow
When resuming work:
```
1. /checkpoint list # See available states
2. /checkpoint restore [name] # Restore context
3. Continue where you left off # Context is loaded
```
## Limitations
- Checkpoints use git stash (requires git repo)
- Large uncommitted changes may be slow
- Metadata stored in `.claude/checkpoints/`
- Consider committing before checkpointing for safety
-219
View File
@@ -1,219 +0,0 @@
# /commit - Smart Commit Command
## Purpose
Create a well-formatted commit with auto-generated message based on staged changes.
## Usage
```
/commit [optional message hint]
```
## Arguments
- `$ARGUMENTS`: Optional hint for commit message focus (e.g., "auth", "bugfix", "refactor")
---
Create a commit for staged changes with hint: **$ARGUMENTS**
## Workflow
### Step 1: Analyze Changes
1. **Check Status**
```bash
git status
```
2. **View Staged Changes**
```bash
git diff --staged
```
3. **Review Recent Commits**
```bash
git log --oneline -5
```
### Step 2: Categorize Changes
Determine commit type:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation
- `style`: Formatting
- `refactor`: Code restructuring
- `test`: Adding tests
- `chore`: Maintenance
### Step 3: Generate Message
Follow conventional commit format:
```
type(scope): subject
body (optional)
footer (optional)
```
### Step 4: Create Commit
```bash
git commit -m "$(cat <<'EOF'
type(scope): subject
- Change 1
- Change 2
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
## Commit Message Guidelines
### Subject Line
- Max 50 characters
- Imperative mood ("Add" not "Added")
- No period at end
- Capitalize first letter
### Body
- Wrap at 72 characters
- Explain what and why
- Use bullet points for multiple changes
### Examples
#### Feature
```
feat(auth): add password reset functionality
- Add reset token generation
- Implement email sending
- Add rate limiting for reset requests
Closes #123
```
#### Bug Fix
```
fix(api): handle null user in profile endpoint
The profile endpoint crashed when accessing deleted users.
Added null check and proper 404 response.
Fixes #456
```
#### Refactor
```
refactor(database): extract query builders
Split large database service into focused modules
for better maintainability and testing.
```
#### Documentation
```
docs(readme): update installation instructions
- Add prerequisites section
- Update configuration examples
- Fix broken links
```
#### Test
```
test(auth): add missing login tests
- Add test for invalid credentials
- Add test for locked account
- Add test for expired session
```
#### Chore
```
chore(deps): update dependencies
- Update React to 18.2
- Update TypeScript to 5.3
- Remove unused packages
```
## Output
### Commit Created
```markdown
## Commit Created
**Hash**: `abc1234`
**Branch**: `feature/auth-improvements`
### Message
```
feat(auth): add OAuth2 login support
- Implement Google OAuth provider
- Implement GitHub OAuth provider
- Add session token generation
- Update user model for OAuth data
Closes #789
```
### Files Changed
| Status | File |
|--------|------|
| M | src/auth/providers.ts |
| A | src/auth/oauth/google.ts |
| A | src/auth/oauth/github.ts |
| M | src/models/user.ts |
| A | tests/auth/oauth.test.ts |
### Stats
- 5 files changed
- 234 insertions(+)
- 12 deletions(-)
### Next Steps
```bash
# Push to remote
git push -u origin feature/auth-improvements
# Create PR
gh pr create
```
```
## Pre-Commit Checks
Before committing:
- [ ] No secrets in staged files
- [ ] No debug statements
- [ ] No TODO comments (unless intentional)
- [ ] Code is formatted
## Amending Commits
If pre-commit hooks modify files:
```bash
# Stage modified files and amend
git add -A
git commit --amend --no-edit
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Commit message format
- Required sections
- Issue reference format
- Co-author settings
-53
View File
@@ -1,53 +0,0 @@
# /debug - Debug Command
## Purpose
Analyze and debug an error, exception, or unexpected behavior.
## Usage
```
/debug [error message or description]
```
---
Debug issue: **$ARGUMENTS**
## Workflow
### Step 1: Analyze Error
1. Parse error message and stack trace
2. Identify error location
3. Understand error type
### Step 2: Investigate
1. Trace execution path
2. Check related code
3. Form hypotheses
### Step 3: Fix
1. Implement minimal fix
2. Verify fix works
3. Add regression test
## Output
```markdown
## Debug Report
### Error
[Error message]
### Root Cause
[Explanation]
### Fix
[Code changes]
### Prevention
[Test added]
```
-72
View File
@@ -1,72 +0,0 @@
# /deploy - Deployment Command
## Purpose
Deploy the application to a specified environment with proper checks.
## Usage
```
/deploy [environment: staging | production]
```
---
Deploy to: **$ARGUMENTS**
## Workflow
### Pre-Deploy Checks
1. **Verify Build**
```bash
pnpm build
```
2. **Run Tests**
```bash
pnpm test
```
3. **Security Scan**
```bash
npm audit --audit-level=high
```
### Deploy
1. **Staging**
```bash
# Deploy to staging environment
```
2. **Production** (requires confirmation)
```bash
# Deploy to production environment
```
### Post-Deploy
1. **Verify Deployment**
- Health checks
- Smoke tests
2. **Monitor**
- Check logs
- Watch metrics
## Output
```markdown
## Deployment Complete
**Environment**: staging
**Version**: v1.2.3
**URL**: https://staging.example.com
### Checks
- [x] Build successful
- [x] Tests passing
- [x] Security scan clean
- [x] Health check passed
```
-243
View File
@@ -1,243 +0,0 @@
# /doc - Documentation Command
## Purpose
Generate or update documentation including API docs, README files, code comments, and technical specifications.
## Usage
```
/doc [target | 'api' | 'readme' | 'changelog']
```
## Arguments
- `$ARGUMENTS`:
- File/function path: Document specific code
- `api`: Generate API documentation
- `readme`: Update README file
- `changelog`: Generate changelog from commits
---
Generate documentation for: **$ARGUMENTS**
## Workflow
### For Code Documentation
1. **Analyze Code**
- Read the code thoroughly
- Understand purpose and behavior
- Identify inputs and outputs
- Note side effects
2. **Generate Documentation**
- Add docstrings/JSDoc
- Include examples
- Document edge cases
- Add type annotations
### For API Documentation
1. **Find All Endpoints**
- Scan route definitions
- Identify HTTP methods
- Note authentication requirements
2. **Document Each Endpoint**
- Request format
- Response format
- Error responses
- Examples
### For README
1. **Analyze Project**
- Purpose and features
- Installation steps
- Usage examples
- Configuration
2. **Generate/Update**
- Clear structure
- Working examples
- Up-to-date info
### For Changelog
1. **Analyze Commits**
```bash
git log --oneline --since="last release"
```
2. **Categorize Changes**
- Added
- Changed
- Fixed
- Removed
## Templates
### Python Docstring
```python
def calculate_discount(price: float, percentage: float) -> float:
"""
Calculate discounted price.
Args:
price: Original price in dollars.
percentage: Discount percentage (0-100).
Returns:
The discounted price.
Raises:
ValueError: If percentage is not between 0 and 100.
Example:
>>> calculate_discount(100.0, 20)
80.0
"""
```
### TypeScript JSDoc
```typescript
/**
* Calculate discounted price.
*
* @param price - Original price in dollars
* @param percentage - Discount percentage (0-100)
* @returns The discounted price
* @throws {RangeError} If percentage is not between 0 and 100
*
* @example
* calculateDiscount(100, 20); // returns 80
*/
```
### API Endpoint
```markdown
## POST /api/orders
Create a new order.
### Authentication
Requires Bearer token.
### Request Body
```json
{
"items": [
{ "productId": "123", "quantity": 2 }
],
"shippingAddress": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}
```
### Response (201 Created)
```json
{
"id": "order_456",
"status": "pending",
"total": 99.99,
"createdAt": "2024-01-15T10:00:00Z"
}
```
### Errors
| Status | Code | Description |
|--------|------|-------------|
| 400 | INVALID_ITEMS | Items array is empty |
| 401 | UNAUTHORIZED | Invalid or missing token |
| 422 | OUT_OF_STOCK | Item not available |
```
### README Section
```markdown
## Installation
```bash
npm install my-package
```
## Quick Start
```typescript
import { Client } from 'my-package';
const client = new Client({ apiKey: 'your-key' });
const result = await client.fetch();
```
## Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | string | required | Your API key |
| `timeout` | number | 5000 | Request timeout in ms |
```
### Changelog Entry
```markdown
## [1.2.0] - 2024-01-15
### Added
- Password reset functionality (#123)
- Email verification for new accounts
### Changed
- Improved error messages for validation failures
- Updated dependencies to latest versions
### Fixed
- Race condition in session handling (#456)
- Incorrect timezone in date displays
```
## Output
### Documentation Report
```markdown
## Documentation Updated
### Files Modified
- `src/services/auth.ts` - Added JSDoc comments
- `docs/api/auth.md` - New API documentation
- `README.md` - Updated configuration section
### Documentation Added
#### Code Comments
- `AuthService.login()` - Full JSDoc with examples
- `AuthService.logout()` - Parameter documentation
- `validateToken()` - Return type and exceptions
#### API Documentation
- POST /api/auth/login
- POST /api/auth/logout
- POST /api/auth/refresh
### Coverage
- Functions documented: 15/18 (83%)
- Endpoints documented: 12/12 (100%)
### Next Steps
1. Add examples to remaining functions
2. Create getting started guide
3. Add architecture diagram
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Documentation format
- Required sections
- Example requirements
- API documentation tool
-221
View File
@@ -1,221 +0,0 @@
# /execute-plan - Subagent-Driven Plan Execution
## Purpose
Execute a detailed implementation plan using fresh subagents per task with mandatory code review gates between tasks.
## Usage
```
/execute-plan [plan-file-path]
```
## Arguments
- `$ARGUMENTS`: Path to the plan file (created with `/plan --detailed`)
---
Execute plan from: **$ARGUMENTS**
## Methodology
**Reference**: `.claude/skills/executing-plans/SKILL.md`
This command uses the superpowers execution methodology for quality-gated implementation.
## Core Pattern
**"Fresh subagent per task + review between tasks = high quality, fast iteration"**
### Why Fresh Agents?
- Prevents context pollution between tasks
- Each task gets focused attention
- Failures don't cascade
- Easier to retry individual tasks
### Why Code Review Between Tasks?
- Catches issues early
- Ensures code matches intent
- Prevents technical debt accumulation
- Creates natural checkpoints
## Workflow
### Step 1: Load Plan
1. Read the plan file
2. Verify plan is complete and approved
3. Create TodoWrite with all tasks from plan
4. Set first task to `in_progress`
### Step 2: Execute Task (For Each Task)
```markdown
1. Dispatch fresh subagent with task details
2. Subagent implements following TDD cycle:
- Write failing test
- Verify test fails
- Implement minimally
- Verify test passes
- Commit
3. Subagent returns completion summary
```
### Step 3: Code Review
After each task:
```markdown
1. Dispatch code-reviewer subagent
2. Review scope: only changes from current task
3. Reviewer returns findings:
- Critical: Must fix before proceeding
- Important: Should fix before proceeding
- Minor: Can fix later
```
### Step 4: Handle Review Findings
```markdown
IF Critical or Important issues found:
1. Dispatch fix subagent for each issue
2. Re-request code review
3. Repeat until no Critical/Important issues
IF only Minor issues:
1. Note for later cleanup
2. Proceed to next task
```
### Step 5: Mark Complete
1. Update TodoWrite - mark task completed
2. Move to next task
3. Repeat from Step 2
### Step 6: Final Review
After all tasks complete:
1. Dispatch comprehensive code review
2. Review entire implementation against plan
3. Verify all success criteria met
4. Run full test suite
5. Use `finishing-a-development-branch` skill
## Critical Rules
### Never Skip Code Reviews
Every task must be reviewed before proceeding. No exceptions.
### Never Proceed with Critical Issues
Critical issues must be fixed:
```
implement → review → fix critical → re-review → proceed
```
### Never Run Parallel Implementation
Tasks run sequentially:
```
WRONG: Run Task 1, 2, 3 simultaneously
RIGHT: Task 1 → Review → Task 2 → Review → Task 3 → Review
```
### Always Read Plan Before Implementing
```
WRONG: Start coding based on memory of plan
RIGHT: Read plan file, extract task details, then implement
```
## Error Handling
### Task Fails
1. Capture error details
2. Attempt fix (max 2 retries)
3. If still failing, pause execution
4. Report to user with:
- Which task failed
- Error details
- Suggested resolution
5. Wait for user decision
### Review Finds Major Issues
1. List all Critical/Important issues
2. Dispatch fix subagent for each
3. Re-run code review
4. If issues persist after 2 cycles:
- Pause execution
- Report to user
- May need plan revision
## Output
### Progress Updates
```markdown
## Execution Progress
### Task 1: Create User model ✓
- Files modified: src/models/user.ts
- Tests added: 3
- Review: Passed
### Task 2: Add validation ✓
- Files modified: src/models/user.ts
- Tests added: 2
- Review: Passed (1 minor deferred)
### Task 3: Create endpoint [IN PROGRESS]
- Status: Implementing...
```
### Completion Summary
```markdown
## Execution Complete
### Summary
- Tasks completed: 8/8
- Tests added: 24
- Coverage: 92%
### Files Created
- src/models/user.ts
- src/services/user-service.ts
- src/routes/user.ts
### Files Modified
- src/routes/index.ts
- src/types/index.ts
### Deferred Items
- Minor: Variable rename in user-service.ts line 12
### Next Steps
- Run full test suite
- Use /ship to create PR
```
## Prerequisites
Before using this command:
1. Plan file exists and is complete
2. Plan was created with `/plan --detailed`
3. Plan has been reviewed and approved
4. Tests can be run (`npm test` or `pytest`)
## Related Commands
- `/plan --detailed` - Create detailed plan
- `/brainstorm` - Design before planning
- `/ship` - Create PR after execution
-251
View File
@@ -1,251 +0,0 @@
# /feature - Feature Development Workflow
## Purpose
End-to-end feature development workflow that orchestrates planning, implementation guidance, testing, and code review.
## Usage
```
/feature [feature description or issue reference]
```
## Arguments
- `$ARGUMENTS`: Feature description, issue number, or requirement specification
---
Implement a complete feature development workflow for: **$ARGUMENTS**
## Workflow
### Phase 1: Planning
First, analyze the feature request and create an implementation plan:
1. **Understand Requirements**
- Parse the feature description thoroughly
- Identify acceptance criteria
- List assumptions that need validation
- Clarify any ambiguous requirements with the user
2. **Explore Codebase**
- Find related existing implementations
- Identify patterns and conventions to follow
- Locate integration points
- Note dependencies
3. **Create Task Breakdown**
- Decompose into atomic, verifiable tasks
- Order tasks by dependencies
- Include testing requirements
- Estimate complexity (S/M/L)
4. **Use TodoWrite** to track all tasks
### Phase 2: Research (If Needed)
If the feature involves unfamiliar technology:
1. Research best practices and patterns
2. Find examples in the codebase or documentation
3. Identify potential pitfalls
4. Document key decisions
### Phase 3: Implementation Guidance
For each implementation task:
1. **Identify Target Files**
- Existing files to modify
- New files to create
- Tests to add/update
2. **Provide Implementation Direction**
- Code structure recommendations
- Patterns to follow
- Edge cases to handle
- Error handling approach
3. **Review Progress**
- Mark tasks complete as you go
- Identify blockers early
- Adjust plan if needed
### Phase 4: Testing
After implementation:
1. **Generate Tests**
- Unit tests for new functions
- Integration tests for workflows
- Edge case coverage
2. **Run Test Suite**
```bash
# Python
pytest -v --cov=src
# TypeScript
pnpm test
```
3. **Verify Coverage**
- Ensure new code is tested
- Coverage should not decrease
### Phase 5: Code Review
Before completion:
1. **Self-Review Checklist**
- [ ] Code follows project conventions
- [ ] No security vulnerabilities
- [ ] Error handling is complete
- [ ] Documentation updated
- [ ] Tests are passing
2. **Review Staged Changes**
```bash
git diff --staged
```
3. **Address Any Issues**
- Fix critical issues immediately
- Note recommendations for future
### Phase 6: Completion
1. **Verify All Tasks Complete**
- All TodoWrite items done
- All tests passing
- Documentation updated
2. **Prepare for Commit**
- Stage appropriate files
- Generate commit message
- Create PR if requested
## Output
### Deliverables
1. **Implementation Plan** - Structured task breakdown
2. **Code Changes** - Feature implementation
3. **Tests** - Comprehensive test coverage
4. **Documentation** - Updated docs if needed
5. **Commit/PR** - Ready for merge
### Summary Format
```markdown
## Feature Implementation Complete
### Feature
[Feature description]
### Changes Made
- `path/to/file.ts` - [What was added/modified]
- `path/to/file.test.ts` - [Tests added]
### Tests
- [x] Unit tests passing
- [x] Integration tests passing
- [x] Coverage: XX%
### Documentation
- [x] Code comments added
- [x] README updated (if applicable)
### Ready for Review
```bash
git status
git diff --staged
```
### Next Steps
1. Review changes
2. Run full test suite
3. Create PR
```
## Example
**Input**: `/feature Add password reset functionality with email verification`
**Output**:
1. Plan with 8 tasks covering model, service, routes, email, tests
2. Implementation of password reset flow
3. Tests for happy path and error cases
4. Updated API documentation
5. Commit message and PR description
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=implementation` |
| `--depth=[1-5]` | Planning thoroughness level | `--depth=3` |
| `--checkpoint` | Create checkpoint before starting | `--checkpoint` |
| `--skip-tests` | Skip test generation phase | `--skip-tests` |
| `--skip-review` | Skip code review phase | `--skip-review` |
| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` |
### Flag Usage Examples
```bash
/feature --mode=implementation "add user profile page"
/feature --depth=5 --checkpoint "implement payment flow"
/feature --format=concise "add logging utility"
```
## MCP Integration
This command leverages MCP servers for enhanced capabilities:
### Context7 - Library Documentation
When researching unfamiliar libraries or frameworks:
```
Use Context7's resolve-library-id and get-library-docs tools to fetch
current documentation for any libraries involved in the feature.
```
### Sequential Thinking - Structured Planning
For complex feature breakdowns:
```
Use Sequential Thinking's sequentialthinking tool for step-by-step
analysis when decomposing requirements or designing architecture.
```
### Memory - Context Persistence
Store and recall project context:
```
- Store architectural decisions made during planning
- Recall user preferences from previous sessions
- Remember patterns used in similar features
```
### Filesystem - File Operations
For creating and modifying files:
```
- Use directory_tree to understand project structure
- Use search_files to find related implementations
- Use read_file and write_file for file operations
```
### Playwright - E2E Testing
For features with UI components:
```
Use Playwright for browser-based E2E testing of the implemented feature.
Validate user flows and interactions in real browser environment.
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Set minimum test coverage requirements
- Define required documentation updates
- Configure branch naming conventions
- Set PR template requirements
-319
View File
@@ -1,319 +0,0 @@
# /fix - Bug Fix Workflow
## Purpose
Smart debugging and bug fixing workflow that analyzes errors, identifies root causes, implements fixes, and adds regression tests.
## Usage
```
/fix [error message, bug description, or issue reference]
```
## Arguments
- `$ARGUMENTS`: Error message, stack trace, bug description, or issue number
---
Analyze and fix the following issue: **$ARGUMENTS**
## Workflow
### Phase 1: Error Analysis
1. **Parse Error Information**
- Extract error type and message
- Parse stack trace if available
- Identify the failing location
2. **Gather Context**
- When does this error occur?
- What triggers it?
- Is it reproducible?
- When did it start happening?
3. **Check for Known Patterns**
- Common error patterns
- Similar issues in codebase
- Recent changes that might have caused it
### Phase 2: Root Cause Investigation
1. **Trace Execution**
- Follow the code path to the error
- Identify state at each step
- Find where expectations diverge
2. **Form Hypotheses**
- List possible causes ranked by likelihood
- Identify minimal tests to validate each
3. **Validate Hypothesis**
- Test the most likely cause first
- Confirm root cause before fixing
- Don't fix symptoms only
### Phase 3: Search Related Code
1. **Find Similar Code**
- Search for similar patterns
- Check if same bug exists elsewhere
- Identify shared code that might be affected
2. **Review Recent Changes**
```bash
git log --oneline -20
git blame [file]
```
### Phase 4: Implement Fix
1. **Develop Minimal Fix**
- Fix the root cause, not symptoms
- Keep changes minimal and focused
- Consider edge cases
2. **Add Defensive Code** (if appropriate)
- Input validation
- Null checks
- Error handling
3. **Update Related Code** (if needed)
- Fix same issue in similar code
- Update shared utilities
### Phase 5: Verification
1. **Test the Fix**
- Verify original error is resolved
- Check related functionality
- Run existing test suite
2. **Add Regression Test**
- Write test that would have caught this bug
- Include edge cases discovered
- Ensure test fails without fix
3. **Run Full Test Suite**
```bash
# Python
pytest -v
# TypeScript
pnpm test
```
### Phase 6: Documentation
1. **Document the Fix**
- What was the issue
- What caused it
- How it was fixed
2. **Update Comments** (if needed)
- Add clarifying comments
- Document non-obvious behavior
## Output
### Bug Fix Summary
```markdown
## Bug Fix Complete
### Issue
[Original error/bug description]
### Root Cause
[Explanation of what caused the bug]
### Location
`path/to/file.ts:42` - [function/method name]
### Fix Applied
**Before:**
```[language]
// Problematic code
```
**After:**
```[language]
// Fixed code
```
### Explanation
[Why this fix resolves the issue]
### Regression Test Added
`path/to/test.ts` - `test_[scenario]`
### Verification
- [x] Original error no longer occurs
- [x] Existing tests pass
- [x] New regression test passes
- [x] No new issues introduced
### Related Areas Checked
- [x] `path/to/similar.ts` - No similar issue
### Commands to Verify
```bash
pytest tests/test_file.py -v
# or
pnpm test path/to/file.test.ts
```
```
## Common Fix Patterns
### Null/Undefined Access
```typescript
// Before
const name = user.profile.name;
// After
const name = user?.profile?.name ?? 'Unknown';
```
### Missing Error Handling
```python
# Before
data = json.loads(response.text)
# After
try:
data = json.loads(response.text)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON response: {e}")
raise InvalidResponseError("Failed to parse response")
```
### Race Condition
```typescript
// Before
const data = await fetchData();
setState(data); // May be unmounted
// After
useEffect(() => {
let cancelled = false;
fetchData().then(data => {
if (!cancelled) setState(data);
});
return () => { cancelled = true; };
}, []);
```
### Off-by-One Error
```python
# Before
for i in range(len(items) + 1): # IndexError
process(items[i])
# After
for i in range(len(items)):
process(items[i])
# or
for item in items:
process(item)
```
## Example
**Input**: `/fix TypeError: Cannot read property 'email' of undefined in UserService.ts:45`
**Output**:
1. Analysis: User object is undefined when accessed
2. Root cause: async fetch didn't await, user not loaded yet
3. Fix: Add null check and proper async handling
4. Regression test: Test for case when user is not loaded
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=deep-research` |
| `--persona=[type]` | Apply persona expertise | `--persona=security` |
| `--depth=[1-5]` | Investigation thoroughness | `--depth=4` |
| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` |
| `--skip-regression` | Skip regression test creation | `--skip-regression` |
| `--checkpoint` | Create checkpoint before fixing | `--checkpoint` |
### Flag Usage Examples
```bash
/fix --mode=deep-research "intermittent timeout error"
/fix --persona=security "SQL injection vulnerability"
/fix --depth=5 "race condition in auth flow"
/fix --format=concise "typo in error message"
```
### Persona Options
| Persona | Focus Area |
|---------|------------|
| `security` | Security vulnerabilities, OWASP |
| `performance` | Speed, memory, efficiency |
| `reliability` | Error handling, edge cases |
## MCP Integration
This command leverages MCP servers for enhanced debugging:
### Sequential Thinking - Root Cause Analysis (Primary)
```
ALWAYS use Sequential Thinking for debugging:
- Trace execution path step-by-step
- Form and test hypotheses systematically
- Track confidence in each potential cause
- Revise understanding as evidence emerges
```
### Memory - Bug Context
```
Store and recall debugging context:
- Remember similar bugs from previous sessions
- Recall fix patterns that worked before
- Store root cause analysis for future reference
- Create relations between bugs and affected components
```
### Playwright - Browser Testing
```
For UI/frontend bugs:
- Reproduce the bug in browser environment
- Test fix across different browsers
- Verify visual regressions are resolved
- Automate regression test for the fix
```
### Context7 - Library Issues
```
When debugging library-related issues:
- Fetch current documentation for correct usage
- Check for known issues or breaking changes
- Find correct patterns and examples
```
### Filesystem - Code Search
```
For tracing bug across codebase:
- Use search_files to find related code
- Use read_file to examine suspicious areas
- Track changes with file history
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Set required test coverage for fixes
- Define severity levels for bugs
- Configure error reporting format
- Set required review process
-59
View File
@@ -1,59 +0,0 @@
# /help - Help Command
## Purpose
Display available commands and their usage.
## Usage
```
/help [command name]
```
---
Show help for: **$ARGUMENTS**
## Available Commands
### Development Workflow
| Command | Description |
|---------|-------------|
| `/feature` | Full feature development workflow |
| `/fix` | Debug and fix bugs |
| `/review` | Code review |
| `/test` | Generate tests |
| `/tdd` | Test-driven development |
| `/refactor` | Improve code structure |
### Git & Deployment
| Command | Description |
|---------|-------------|
| `/commit` | Create commit with message |
| `/ship` | Commit + PR workflow |
| `/pr` | Create pull request |
| `/deploy` | Deploy to environment |
### Documentation
| Command | Description |
|---------|-------------|
| `/doc` | Generate documentation |
| `/plan` | Create implementation plan |
### Security & Quality
| Command | Description |
|---------|-------------|
| `/security-scan` | Scan for vulnerabilities |
| `/api-gen` | Generate API code |
## Getting Help
For detailed help on a specific command:
```
/help [command-name]
```
For general Claude Code help:
```
/help
```
-144
View File
@@ -1,144 +0,0 @@
# /index
## Purpose
Generate a comprehensive project structure index for faster navigation and context loading. Creates a `PROJECT_INDEX.md` file mapping the codebase structure.
---
Analyze the current project and generate a comprehensive index.
## Index Generation
### Step 1: Scan Project Structure
Scan the entire project directory structure, excluding:
- `node_modules/`
- `.git/`
- `__pycache__/`
- `dist/`, `build/`, `.next/`
- `venv/`, `.venv/`
- Coverage and cache directories
### Step 2: Identify Key Components
Categorize files by type:
- **Entry Points**: Main files, index files, app entry
- **API/Routes**: Endpoint definitions
- **Models/Types**: Data structures, schemas
- **Services**: Business logic
- **Utilities**: Helper functions
- **Tests**: Test files
- **Configuration**: Config files, env templates
- **Documentation**: README, docs
### Step 3: Map Dependencies
Identify:
- Package managers and dependencies (package.json, requirements.txt, etc.)
- Internal import relationships between key files
- External service integrations
### Step 4: Generate Index
Create `PROJECT_INDEX.md` with this structure:
```markdown
# Project Index: [Project Name]
Generated: [timestamp]
## Quick Navigation
| Category | Key Files |
|----------|-----------|
| Entry Points | [list] |
| API Routes | [list] |
| Core Services | [list] |
| Models | [list] |
## Directory Structure
```
[tree view]
```
## Key Files
### Entry Points
- `[path]` - [description]
### API/Routes
- `[path]` - [description]
### Services
- `[path]` - [description]
### Models/Types
- `[path]` - [description]
## Dependencies
### External
- [package]: [purpose]
### Internal
- [module] → [depends on]
## Architecture Notes
[Brief description of patterns observed]
```
## Flags
| Flag | Description |
|------|-------------|
| `--depth=[N]` | Limit directory depth (default: 5) |
| `--include=[pattern]` | Include additional patterns |
| `--exclude=[pattern]` | Exclude additional patterns |
| `--output=[path]` | Custom output path |
## Usage Examples
```bash
/index # Standard index
/index --depth=3 # Shallow index
/index --include="*.graphql" # Include GraphQL files
/index --output=docs/INDEX.md # Custom output location
```
## Arguments
$ARGUMENTS
If no arguments provided, generate standard index with default settings.
---
After generating the index, inform the user:
1. Index file location
2. Number of files indexed
3. Key components discovered
4. Suggest using `/load` to load specific components into context
## MCP Integration
This command leverages MCP servers for enhanced indexing:
### Filesystem - Project Scanning (Primary)
```
ALWAYS use Filesystem for project scanning:
- Use directory_tree for full structure view
- Use list_directory for targeted exploration
- Use search_files to find specific patterns
- Use get_file_info for file metadata
```
### Memory - Project Knowledge
```
Store project structure in knowledge graph:
- Create entities for key modules
- Store component relationships
- Recall structure in future sessions
- Build project understanding over time
```
-108
View File
@@ -1,108 +0,0 @@
# /load
## Purpose
Load specific project components into context for focused work. Uses the project index to efficiently load relevant files.
---
Load the requested component(s) into context.
## Loading Process
### Step 1: Check for Index
First, check if `PROJECT_INDEX.md` exists:
- If exists: Use index for efficient loading
- If not: Suggest running `/index` first, or do quick scan
### Step 2: Identify Component
Parse the requested component:
| Request Type | Action |
|--------------|--------|
| Category name | Load all files in category |
| File path | Load specific file |
| Pattern | Load matching files |
| `--all` | Load key files from all categories |
### Step 3: Load Files
Read the identified files and summarize:
- File purposes
- Key exports/functions
- Dependencies
- Current state
### Step 4: Context Summary
Provide a brief summary:
```markdown
## Loaded Context
### Files Loaded (N)
- `path/to/file1.ts` - [purpose]
- `path/to/file2.ts` - [purpose]
### Key Components
- [Component]: [description]
### Ready For
- [Suggested actions based on loaded context]
```
## Component Categories
| Category | What It Loads |
|----------|---------------|
| `api` | API routes and endpoints |
| `models` | Data models and types |
| `services` | Business logic services |
| `utils` | Utility functions |
| `tests` | Test files |
| `config` | Configuration files |
| `auth` | Authentication related |
| `db` | Database related |
## Flags
| Flag | Description |
|------|-------------|
| `--all` | Load all key components |
| `--shallow` | Load only file summaries |
| `--deep` | Load full file contents |
| `--related` | Include related files |
## Usage Examples
```bash
/load api # Load all API routes
/load models # Load all data models
/load src/services/user.ts # Load specific file
/load auth --related # Load auth + related files
/load --all # Load all key components
/load --all --shallow # Quick overview of everything
```
## Arguments
$ARGUMENTS
If no arguments, show available components from index.
---
## Best Practices
1. **Start Narrow**: Load specific components first
2. **Expand as Needed**: Use `--related` when you need more context
3. **Check Index**: Run `/index` if loading seems slow
4. **Use Categories**: Category names are faster than patterns
## After Loading
Suggest next actions:
- "Ready to work on [component]. What would you like to do?"
- "I see [patterns/issues]. Want me to address them?"
- "Related files that might be relevant: [list]"
-166
View File
@@ -1,166 +0,0 @@
# /mode
## Purpose
Switch between behavioral modes to optimize responses for different task types. Modes adjust communication style, output format, and problem-solving approach.
---
Switch to the specified behavioral mode.
## Available Modes
| Mode | Description | Best For |
|------|-------------|----------|
| `default` | Balanced standard behavior | General tasks |
| `brainstorm` | Creative exploration, more questions | Design, ideation |
| `writing-concisely` | Compressed, concise output | High-volume, cost savings |
| `deep-research` | Thorough analysis, citations | Investigation, audits |
| `implementation` | Code-focused, minimal prose | Executing plans |
| `review` | Critical analysis, finding issues | Code review, QA |
| `orchestration` | Multi-task coordination | Complex parallel work |
## Mode Switching
### Activate Mode
```bash
/mode [mode-name]
```
### Check Current Mode
```bash
/mode
```
(Shows current active mode)
### Reset to Default
```bash
/mode default
```
## Mode Details
### Default Mode
- Standard balanced responses
- Mix of explanation and code
- Normal verification steps
### Brainstorm Mode
- Ask more clarifying questions
- Present multiple alternatives
- Explore trade-offs explicitly
- Delay convergence on solutions
### Token-Efficient Mode
- Minimal explanations
- Code-only responses where possible
- Skip obvious context
- 30-70% token savings
### Deep-Research Mode
- Thorough investigation
- Evidence and citations
- Confidence levels stated
- Comprehensive analysis
### Implementation Mode
- Jump straight to code
- Progress indicators
- Minimal discussion
- Execute don't deliberate
### Review Mode
- Look for issues first
- Categorized findings
- Severity levels
- Actionable feedback
### Orchestration Mode
- Task breakdown
- Parallel execution planning
- Result aggregation
- Coordination focus
## Flags
| Flag | Description |
|------|-------------|
| `--info` | Show detailed mode description |
| `--list` | List all available modes |
## Usage Examples
```bash
/mode brainstorm # Switch to brainstorm mode
/mode token-efficient # Switch to efficient mode
/mode # Show current mode
/mode --list # List all modes
/mode default # Reset to default
```
## Arguments
$ARGUMENTS
If mode name provided: switch to that mode
If no arguments: show current mode
If `--list`: show all modes
---
## Mode Persistence
- Modes persist for the session
- Explicitly switch when task type changes
- Mode affects all subsequent responses
- Can be overridden per-command with flags
## Command Flag Override
Override mode for single command:
```bash
/feature --mode=implementation [desc]
/review --mode=deep-research [file]
/plan --mode=brainstorm [task]
```
## Recommended Workflows
### Feature Development
```
/mode brainstorm # Explore approaches
[discuss design]
/mode implementation # Execute plan
[write code]
/mode review # Check quality
[review code]
```
### Bug Investigation
```
/mode deep-research # Investigate thoroughly
[analyze bug]
/mode implementation # Apply fix
[fix bug]
/mode default # Return to normal
```
### Cost-Conscious Session
```
/mode token-efficient # Set for session
[work on multiple tasks]
/mode default # Reset when done
```
## Mode Files
Mode definitions are in `.claude/modes/`:
- `default.md`
- `brainstorm.md`
- `token-efficient.md`
- `deep-research.md`
- `implementation.md`
- `review.md`
- `orchestration.md`
Customize modes by editing these files.
-49
View File
@@ -1,49 +0,0 @@
# /optimize - Performance Optimization Command
## Purpose
Analyze and optimize code performance.
## Usage
```
/optimize [file or function]
```
---
Optimize: **$ARGUMENTS**
## Workflow
1. **Analyze Current Performance**
- Identify bottlenecks
- Check complexity
- Profile if possible
2. **Identify Opportunities**
- Algorithm improvements
- Caching opportunities
- Async optimizations
3. **Implement Optimizations**
- Make targeted changes
- Verify improvements
- Ensure correctness
## Output
```markdown
## Optimization Report
### Before
- Time complexity: O(n²)
- Estimated time: 500ms
### After
- Time complexity: O(n log n)
- Estimated time: 50ms
### Changes Made
- [Description of optimizations]
```
-333
View File
@@ -1,333 +0,0 @@
# /plan - Task Planning Command
## Purpose
Create structured implementation plans with task breakdown, dependencies, and time estimates for complex work.
## Usage
```
/plan [task description or feature request]
```
## Arguments
- `$ARGUMENTS`: Description of the task, feature, or work to plan
---
Create a detailed implementation plan for: **$ARGUMENTS**
## Workflow
### Phase 1: Understanding
1. **Parse Requirements**
- Identify core functionality needed
- List explicit requirements
- Note implicit requirements
- Identify acceptance criteria
2. **Clarify Ambiguities**
- Ask questions if unclear
- List assumptions made
- Note dependencies on decisions
### Phase 2: Research
1. **Explore Codebase**
- Find related implementations
- Identify patterns to follow
- Locate integration points
- Note conventions
2. **Technical Research** (if needed)
- Research unfamiliar technologies
- Find best practices
- Identify potential pitfalls
### Phase 3: Task Breakdown
1. **Decompose Work**
- Break into atomic tasks
- Each task: 15-60 minutes
- Clear completion criteria
2. **Order by Dependencies**
- What blocks what
- Parallel opportunities
- Critical path
3. **Add Estimates**
- S: <30 min
- M: 30-60 min
- L: 1-2 hours
- XL: 2-4 hours
### Phase 4: Documentation
1. **Create Plan Document**
- Summary
- Task list
- Files to modify
- Risks
2. **Track with TodoWrite**
- Add all tasks
- Set initial status
## Output
### Implementation Plan
```markdown
## Plan: [Feature/Task Name]
### Summary
[2-3 sentence overview of what will be built]
### Scope
**In Scope**
- [What will be done]
**Out of Scope**
- [What won't be done]
**Assumptions**
- [Key assumptions made]
---
### Tasks
#### Phase 1: Setup [Total: Xh]
| # | Task | Size | Depends On |
|---|------|------|------------|
| 1 | Create data model | M | - |
| 2 | Set up database migration | S | 1 |
| 3 | Add model tests | M | 1 |
#### Phase 2: Core Implementation [Total: Xh]
| # | Task | Size | Depends On |
|---|------|------|------------|
| 4 | Implement service layer | L | 1 |
| 5 | Add business logic | M | 4 |
| 6 | Write service tests | M | 5 |
#### Phase 3: API Layer [Total: Xh]
| # | Task | Size | Depends On |
|---|------|------|------------|
| 7 | Create API endpoints | M | 5 |
| 8 | Add validation | S | 7 |
| 9 | Write API tests | M | 8 |
#### Phase 4: Integration [Total: Xh]
| # | Task | Size | Depends On |
|---|------|------|------------|
| 10 | Integrate with frontend | M | 7 |
| 11 | End-to-end testing | M | 10 |
| 12 | Update documentation | S | 11 |
---
### Files to Create/Modify
**Create**
- `src/models/feature.py` - Data model
- `src/services/feature.py` - Business logic
- `src/api/feature.py` - API endpoints
- `tests/test_feature.py` - Tests
**Modify**
- `src/api/__init__.py` - Register routes
- `docs/api.md` - API documentation
---
### Dependencies
**External**
- [Package X] - For [purpose]
**Internal**
- Requires [existing feature] to be complete
---
### Risks
| Risk | Impact | Mitigation |
|------|--------|------------|
| [Risk 1] | High | [How to mitigate] |
| [Risk 2] | Medium | [How to mitigate] |
---
### Questions for Stakeholders
1. [Question about requirement]
2. [Question about edge case]
---
### Success Criteria
- [ ] All tasks completed
- [ ] Tests passing with 80%+ coverage
- [ ] API documentation updated
- [ ] Code reviewed and approved
```
## Plan Templates
### Feature Plan
For new functionality
### Bug Fix Plan
For debugging and fixing issues
### Refactor Plan
For code improvements
### Migration Plan
For data or system migrations
## Detailed Mode (Superpowers Methodology)
Use `--detailed` flag for superpowers-style plans with 2-5 minute tasks:
```
/plan --detailed [task description]
```
### Detailed Mode Features
**Reference**: `.claude/skills/writing-plans/SKILL.md`
When `--detailed` is specified:
- **Bite-sized tasks**: 2-5 minutes each (vs standard 15-60 min)
- **Exact file paths**: Always include full paths
- **Complete code samples**: Actual code, not descriptions
- **TDD steps per task**: Write test → verify fail → implement → verify pass → commit
- **Expected command outputs**: Specify what success looks like
### Detailed Task Template
```markdown
## Task [N]: [Task Name]
**Files**:
- Create: `path/to/new-file.ts`
- Modify: `path/to/existing-file.ts`
- Test: `path/to/test-file.test.ts`
**Steps**:
1. Write failing test
```typescript
// Exact test code
```
2. Verify test fails
```bash
npm test -- --grep "test name"
# Expected: 1 failing
```
3. Implement minimally
```typescript
// Exact implementation code
```
4. Verify test passes
```bash
npm test -- --grep "test name"
# Expected: 1 passing
```
5. Commit
```bash
git commit -m "feat: add [feature]"
```
```
### Execution After Planning
Use `/execute-plan [plan-file]` for subagent-driven execution with code review gates.
**Reference**: `.claude/skills/executing-plans/SKILL.md`
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=brainstorm` |
| `--detailed` | Use superpowers methodology (2-5 min tasks) | `--detailed` |
| `--depth=[1-5]` | Planning thoroughness level | `--depth=4` |
| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` |
| `--save=[path]` | Save plan to file | `--save=plans/auth.md` |
| `--checkpoint` | Create checkpoint after planning | `--checkpoint` |
### Flag Usage Examples
```bash
/plan --detailed "implement user authentication"
/plan --mode=brainstorm "redesign checkout flow"
/plan --depth=5 --save=plans/migration.md "database migration"
/plan --format=json "api endpoint structure"
```
### Mode Recommendations
| Mode | Best For |
|------|----------|
| `default` | Standard planning |
| `brainstorm` | Exploratory planning, multiple approaches |
| `deep-research` | Complex features needing investigation |
| `implementation` | Quick plans for clear tasks |
## MCP Integration
This command leverages MCP servers for enhanced planning:
### Sequential Thinking - Structured Planning (Primary)
```
ALWAYS use Sequential Thinking for task decomposition:
- Break complex tasks into logical thought sequences
- Track dependencies between steps
- Revise plan as understanding deepens
- Use for risk identification and mitigation planning
```
### Memory - Decision Persistence
```
Store and recall planning context:
- Remember decisions from previous planning sessions
- Recall user preferences for task sizing
- Store architectural patterns for reuse
- Create entities for major features/components
```
### Context7 - Technology Research
```
When planning involves unfamiliar technologies:
- Fetch current documentation for accurate estimates
- Understand API patterns before estimating complexity
- Identify potential integration challenges
```
### Filesystem - Codebase Analysis
```
For accurate file identification:
- Use directory_tree to understand project structure
- Use search_files to find existing patterns
- Identify files to create vs modify
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Task size definitions (standard: 15-60 min, detailed: 2-5 min)
- Required plan sections
- Estimation approach
- Risk assessment criteria
-70
View File
@@ -1,70 +0,0 @@
# /pr - Create Pull Request
## Purpose
Create a well-documented pull request with proper description and checks.
## Usage
```
/pr [title or 'auto']
```
---
Create a pull request: **$ARGUMENTS**
## Workflow
### Step 1: Prepare Changes
```bash
git status
git diff main...HEAD
```
### Step 2: Verify Ready
- [ ] All tests passing
- [ ] Code reviewed
- [ ] No merge conflicts
- [ ] Branch pushed
### Step 3: Create PR
```bash
gh pr create --title "type(scope): description" --body "$(cat <<'EOF'
## Summary
- [Change 1]
- [Change 2]
## Test Plan
- [ ] Unit tests
- [ ] Manual testing
## Screenshots
[If applicable]
## Checklist
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] No breaking changes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
## Output
```markdown
## Pull Request Created
**URL**: https://github.com/org/repo/pull/123
**Title**: feat(auth): add OAuth support
**Base**: main ← feature/oauth
### Changes
- 5 files changed
- +234 -12 lines
```
-59
View File
@@ -1,59 +0,0 @@
# /refactor - Refactoring Command
## Purpose
Improve code structure, readability, or performance without changing behavior.
## Usage
```
/refactor [file or function] [goal: clean | extract | simplify | optimize]
```
---
Refactor: **$ARGUMENTS**
## Workflow
### Step 1: Understand Current Code
1. Read the code thoroughly
2. Identify what it does
3. Note existing tests
### Step 2: Plan Refactoring
1. Identify improvement opportunities
2. Ensure tests exist
3. Plan incremental changes
### Step 3: Execute
1. Make small, focused changes
2. Run tests after each change
3. Commit incrementally
## Refactoring Types
- **Extract**: Pull out reusable functions
- **Simplify**: Reduce complexity
- **Rename**: Improve clarity
- **Clean**: Remove dead code
## Output
```markdown
## Refactoring Complete
### Changes Made
- Extracted `validateInput()` function
- Simplified conditional logic
- Renamed `x` to `userCount`
### Before/After
[Code comparison]
### Tests
All passing
```
-112
View File
@@ -1,112 +0,0 @@
# /research - Research Command
## Purpose
Research a technology, library, or approach with comprehensive analysis.
## Usage
```
/research [topic or technology]
```
---
Research: **$ARGUMENTS**
## Workflow
1. **Gather Information**
- Official documentation
- Community resources
- Comparisons
2. **Analyze**
- Pros and cons
- Best practices
- Alternatives
3. **Recommend**
- Summary
- Recommendation
- Next steps
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=deep-research` |
| `--depth=[1-5]` | Research thoroughness level | `--depth=5` |
| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` |
| `--save=[path]` | Save research to file | `--save=docs/research.md` |
| `--compare` | Focus on comparing alternatives | `--compare` |
| `--sequential` | Use sequential thinking methodology | `--sequential` |
### Flag Usage Examples
```bash
/research --depth=5 "authentication libraries for Node.js"
/research --compare "React vs Vue vs Svelte"
/research --sequential "root cause of memory leak"
/research --save=docs/orm-research.md "ORM comparison"
```
### Depth Levels
| Level | Behavior |
|-------|----------|
| 1 | Quick overview, key points only |
| 2 | Standard analysis |
| 3 | Thorough with examples |
| 4 | Comprehensive with trade-offs |
| 5 | Exhaustive with citations |
## MCP Integration
This command leverages MCP servers for enhanced research:
### Context7 - Library Documentation (Primary)
```
ALWAYS use Context7 for library/framework research:
1. Use resolve-library-id to find the library ID
2. Use get-library-docs with topic parameter for focused docs
3. Use mode='code' for API references, mode='info' for concepts
```
### Sequential Thinking - Structured Analysis
```
For complex research requiring step-by-step reasoning:
- Use sequentialthinking tool to break down analysis
- Track confidence scores for each finding
- Revise conclusions as new information emerges
```
### Memory - Persistent Research
```
Store research findings for future reference:
- Create entities for researched technologies
- Add observations with pros/cons/recommendations
- Link related technologies with relations
```
## Output
```markdown
## Research: [Topic]
### Summary
[Overview]
### Pros
- [Pro 1]
- [Pro 2]
### Cons
- [Con 1]
### Alternatives
[Comparison table]
### Recommendation
[Clear recommendation]
```
-340
View File
@@ -1,340 +0,0 @@
# /review - Code Review Command
## Purpose
Comprehensive code review with focus on quality, security, performance, and maintainability.
## Usage
```
/review [file path | 'staged' | 'pr' | PR number]
```
## Arguments
- `$ARGUMENTS`:
- File path: Review specific file(s)
- `staged`: Review all staged changes
- `pr`: Review current branch changes vs main
- PR number: Review specific pull request
---
Perform a comprehensive code review for: **$ARGUMENTS**
## Workflow
### Phase 1: Identify Review Scope
1. **Determine What to Review**
- Single file: Read the specified file
- `staged`: Get staged changes with `git diff --staged`
- `pr`: Get branch diff with `git diff main...HEAD`
- PR number: Fetch PR details with `gh pr view`
2. **Gather Context**
- Understand the purpose of changes
- Check related tests
- Review CLAUDE.md for project standards
### Phase 2: Code Quality Review
Check each file for:
1. **Correctness**
- Logic errors and bugs
- Edge case handling
- Null/undefined safety
- Type correctness
2. **Clarity**
- Clear naming (variables, functions, classes)
- Readable structure
- Appropriate comments
- Self-documenting code
3. **Consistency**
- Follows project conventions
- Matches existing patterns
- Style guide compliance
4. **Complexity**
- Function length (prefer <30 lines)
- Cyclomatic complexity
- Nesting depth
### Phase 3: Security Review
Check for security issues:
1. **Input Validation**
- User input sanitization
- Type validation
- Size/length limits
2. **Authentication/Authorization**
- Proper auth checks
- Role-based access control
- Session management
3. **Data Protection**
- Sensitive data handling
- Encryption where needed
- PII protection
4. **Injection Prevention**
- SQL injection
- XSS vulnerabilities
- Command injection
5. **Secrets**
- No hardcoded credentials
- No API keys in code
- Proper env var usage
### Phase 4: Performance Review
Check for performance issues:
1. **Algorithmic Efficiency**
- Time complexity
- Unnecessary loops
- Redundant operations
2. **Memory Usage**
- Large object creation
- Memory leaks
- Unbounded caches
3. **Database**
- N+1 queries
- Missing indexes
- Large result sets
4. **Async Operations**
- Proper async/await
- Parallel where possible
- Timeout handling
### Phase 5: Maintainability Review
Check for maintainability:
1. **SOLID Principles**
- Single responsibility
- Open/closed
- Dependency injection
2. **DRY**
- Code duplication
- Opportunity for reuse
3. **Testing**
- Test coverage
- Test quality
- Edge case tests
4. **Documentation**
- API documentation
- Complex logic explanation
- Usage examples
## Output Format
```markdown
## Code Review: [Target]
**Reviewed**: [files/changes]
**Verdict**: [Approve | Request Changes | Needs Discussion]
---
### Critical Issues (Must Fix)
#### 1. [Security] SQL Injection Risk
**File**: `src/api/users.ts:42`
**Severity**: Critical
```typescript
// Current code
const query = `SELECT * FROM users WHERE id = ${userId}`;
```
**Issue**: User input directly interpolated into SQL query.
**Fix**:
```typescript
const query = 'SELECT * FROM users WHERE id = $1';
const result = await db.query(query, [userId]);
```
---
### Recommendations (Should Fix)
#### 1. Missing Error Handling
**File**: `src/services/auth.ts:78`
```typescript
// Current
const user = await db.findUser(email);
return user.password; // May throw if user is null
```
**Suggestion**:
```typescript
const user = await db.findUser(email);
if (!user) {
throw new NotFoundError('User not found');
}
return user.password;
```
---
### Suggestions (Nice to Have)
1. Consider extracting the validation logic in `src/utils/validate.ts:23` into a separate function for reusability.
2. The constant `MAX_RETRIES` in `src/api/client.ts` could be moved to configuration.
---
### What's Good
- Clean separation of concerns between controller and service layers
- Comprehensive error handling in the authentication flow
- Good test coverage for edge cases in `auth.test.ts`
---
### Summary
Found **1 critical issue** (security), **2 recommendations**, and **2 suggestions**.
**Priority Actions**:
1. Fix SQL injection vulnerability immediately
2. Add null check for user lookup
**Ready for merge**: No - Critical issues must be addressed first
```
## Review Checklist
### Security
- [ ] No hardcoded secrets
- [ ] Input validation present
- [ ] Output encoding for rendered content
- [ ] SQL parameterization
- [ ] Proper auth checks
- [ ] No eval() or dynamic code execution
### Quality
- [ ] Clear naming conventions
- [ ] Functions are focused (single responsibility)
- [ ] Error handling is complete
- [ ] No commented-out code
- [ ] No debug statements left
### Testing
- [ ] New code has tests
- [ ] Edge cases covered
- [ ] Tests are deterministic
### Documentation
- [ ] Public APIs documented
- [ ] Complex logic explained
- [ ] Breaking changes noted
## Example
**Input**: `/review staged`
**Output**: Complete review of all staged changes with security scan, code quality assessment, and actionable feedback organized by severity.
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--mode=[mode]` | Use specific behavioral mode | `--mode=review` |
| `--persona=[type]` | Apply persona expertise | `--persona=security` |
| `--depth=[1-5]` | Review thoroughness level | `--depth=5` |
| `--format=[fmt]` | Output format (concise/detailed/json) | `--format=detailed` |
| `--focus=[area]` | Focus on specific area | `--focus=performance` |
| `--save` | Save review to file | `--save` |
### Flag Usage Examples
```bash
/review --persona=security src/auth/
/review --depth=5 --format=detailed staged
/review --focus=performance src/services/heavy-computation.ts
/review --mode=deep-research --save pr
```
### Persona Options
| Persona | Focus Area |
|---------|------------|
| `security` | Vulnerabilities, auth, data protection |
| `performance` | Efficiency, queries, caching |
| `architecture` | Patterns, coupling, SOLID |
| `testing` | Coverage, test quality |
| `accessibility` | A11y compliance |
### Focus Areas
| Focus | Checks |
|-------|--------|
| `security` | OWASP top 10, auth, input validation |
| `performance` | N+1, complexity, memory |
| `quality` | Readability, maintainability |
| `testing` | Coverage, test patterns |
## MCP Integration
This command leverages MCP servers for enhanced code review:
### Playwright - Visual/UI Review
```
For reviewing UI changes:
- Render and screenshot components
- Compare visual changes across browsers
- Verify responsive behavior
- Check accessibility in real browser
```
### Memory - Review Context
```
Store and recall review context:
- Remember past review decisions
- Recall user's coding standards
- Store patterns approved/rejected previously
- Track recurring issues across reviews
```
### Sequential Thinking - Systematic Analysis
```
For thorough code analysis:
- Step through complex logic systematically
- Track multiple concerns in parallel
- Build comprehensive issue list
- Revise severity as context emerges
```
### Filesystem - Code Access
```
For reviewing file changes:
- Use read_file to examine code
- Use search_files to find related patterns
- Check for similar issues across codebase
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Set required review checklist items
- Define severity levels
- Configure approval criteria
- Set documentation requirements
-52
View File
@@ -1,52 +0,0 @@
# /security-scan - Security Scanning Command
## Purpose
Scan code and dependencies for security vulnerabilities.
## Usage
```
/security-scan [scope: deps | code | secrets | all]
```
---
Run security scan: **$ARGUMENTS**
## Workflow
### Dependency Scan
```bash
npm audit
pip-audit
```
### Code Scan
- SQL injection patterns
- XSS vulnerabilities
- Command injection
### Secret Detection
- API keys
- Passwords
- Tokens
## Output
```markdown
## Security Scan Results
### Summary
| Type | Critical | High | Medium |
|------|----------|------|--------|
| Dependencies | 0 | 2 | 5 |
| Code | 0 | 1 | 3 |
| Secrets | 0 | 0 | 0 |
### Findings
[Detailed findings with remediation]
```
-217
View File
@@ -1,217 +0,0 @@
# /ship - Ship Code Command
## Purpose
Complete workflow to commit changes, run reviews, execute tests, and create a pull request ready for merge.
## Usage
```
/ship [commit message or 'quick']
```
## Arguments
- `$ARGUMENTS`:
- Commit message: Use as commit subject
- `quick`: Auto-generate message, skip review
---
Ship the current changes with: **$ARGUMENTS**
## Workflow
### Phase 1: Pre-Ship Checks
1. **Check Repository Status**
```bash
git status
git diff --staged
```
2. **Identify Changes**
- Files modified
- Files added
- Files deleted
3. **Quick Validation**
- No secrets in changes
- No debug statements
- No commented-out code
### Phase 2: Code Review (unless 'quick')
1. **Run Self-Review**
- Check code quality
- Verify style compliance
- Identify security issues
2. **Address Critical Issues**
- Fix any critical problems
- Note recommendations
### Phase 3: Run Tests
1. **Execute Test Suite**
```bash
# Python
pytest -v
# TypeScript
pnpm test
```
2. **Verify All Pass**
- No failing tests
- No new warnings
3. **Check Coverage**
- Coverage not decreased
- New code is tested
### Phase 4: Create Commit
1. **Stage Changes**
```bash
git add -A
```
2. **Generate Commit Message**
- Follow conventional commit format
- Reference issues if applicable
3. **Create Commit**
```bash
git commit -m "$(cat <<'EOF'
type(scope): subject
body
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
### Phase 5: Push and Create PR
1. **Push to Remote**
```bash
git push -u origin [branch-name]
```
2. **Create Pull Request**
```bash
gh pr create --title "type(scope): description" --body "$(cat <<'EOF'
## Summary
- Change 1
- Change 2
## Test Plan
- [ ] Tests pass
- [ ] Manual testing
🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
## Output
### Ship Report
```markdown
## Ship Complete
### Commit
**Hash**: `abc1234`
**Message**: `feat(auth): add password reset functionality`
### Changes
| File | Change |
|------|--------|
| `src/auth/reset.ts` | Added |
| `src/auth/routes.ts` | Modified |
| `tests/auth/reset.test.ts` | Added |
### Checks
- [x] Code review passed
- [x] Tests passing (42 tests)
- [x] Coverage: 85% (+3%)
- [x] No security issues
### Pull Request
**URL**: https://github.com/org/repo/pull/123
**Title**: feat(auth): add password reset functionality
**Base**: main
**Status**: Ready for review
### Next Steps
1. Request review from team
2. Address any feedback
3. Merge when approved
```
## Quick Ship Mode
When using `/ship quick`:
- Skip detailed code review
- Auto-generate commit message
- Minimal output
```bash
# Quick ship for small changes
/ship quick
```
## Commit Message Generation
Based on changes, generate appropriate message:
### Feature
```
feat(scope): add [feature]
- Added [component/function]
- Implemented [functionality]
- Added tests for [scenarios]
```
### Bug Fix
```
fix(scope): resolve [issue]
- Fixed [bug description]
- Added null check for [case]
- Updated tests
```
### Refactor
```
refactor(scope): improve [area]
- Extracted [logic] to [location]
- Renamed [old] to [new]
- Simplified [complex code]
```
## Pre-Ship Checklist
- [ ] All changes staged
- [ ] No unintended files included
- [ ] Tests pass
- [ ] No secrets in code
- [ ] No debug statements
- [ ] Commit message is descriptive
- [ ] PR description is complete
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Required checks before ship
- Commit message format
- PR template requirements
- Auto-merge settings
-173
View File
@@ -1,173 +0,0 @@
# /spawn
## Purpose
Launch background tasks for parallel execution. Enables concurrent work on independent tasks with result aggregation.
---
Launch a background task or manage running tasks.
## Spawn Operations
### Launch Task
Start a new background task:
```bash
/spawn "[task description]"
```
**Process:**
1. Analyze task for parallelizability
2. Launch subagent with task
3. Return task ID for tracking
4. Continue main conversation
**Output:**
```markdown
Spawned: Task #1
- Description: Research authentication patterns
- Status: Running
- Agent: researcher
Continue working. Use `/spawn --list` to check status.
```
### List Tasks
Show running and completed tasks:
```bash
/spawn --list
```
**Output:**
```markdown
## Active Tasks
| ID | Description | Status | Duration |
|----|-------------|--------|----------|
| #1 | Research auth patterns | Running | 2m |
| #2 | Analyze security | Complete | 5m |
## Completed Tasks (last hour)
| #2 | Analyze security | ✅ Complete | Results ready |
```
### Collect Results
Gather results from completed tasks:
```bash
/spawn --collect
```
**Output:**
```markdown
## Collected Results
### Task #1: Research auth patterns
**Status**: Complete
**Findings**:
- Pattern A: JWT with refresh tokens
- Pattern B: Session-based with Redis
- Recommendation: JWT for stateless API
### Task #2: Analyze security
**Status**: Complete
**Findings**:
- 2 high-priority issues found
- See detailed report below
```
### Cancel Task
Stop a running task:
```bash
/spawn --cancel [id]
```
## Task Types
| Type | Best For | Agent Used |
|------|----------|------------|
| Research | Information gathering | researcher |
| Analysis | Code analysis | scout |
| Review | Code review | code-reviewer |
| Test | Test generation | tester |
| Scan | Security scanning | security-auditor |
## Flags
| Flag | Description |
|------|-------------|
| `--list` | Show all tasks |
| `--collect` | Gather completed results |
| `--cancel [id]` | Cancel running task |
| `--wait` | Wait for all tasks to complete |
| `--agent=[type]` | Specify agent type |
| `--priority=[high\|normal]` | Task priority |
## Usage Examples
```bash
/spawn "Research OAuth2 best practices"
/spawn "Analyze user service for performance issues"
/spawn "Review security of auth module" --agent=security-auditor
/spawn --list
/spawn --collect
/spawn --wait # Block until all complete
```
## Arguments
$ARGUMENTS
If quoted text: spawn that task
If flag: execute that operation
---
## Parallel Workflow
### Pattern: Research Phase
```bash
/spawn "Research authentication approaches"
/spawn "Analyze current auth implementation"
/spawn "Review competitor auth patterns"
# Continue other work...
/spawn --wait
/spawn --collect
# Synthesize findings
```
### Pattern: Multi-File Review
```bash
/spawn "Review src/auth/ for security"
/spawn "Review src/api/ for performance"
/spawn "Review src/db/ for SQL injection"
/spawn --collect
# Address findings
```
## Best Practices
1. **Independent Tasks**: Only spawn truly independent work
2. **Clear Descriptions**: Specific task descriptions get better results
3. **Regular Collection**: Don't let results pile up
4. **Resource Awareness**: Don't spawn too many concurrent tasks
## Limitations
- Tasks cannot communicate with each other
- Results are collected, not streamed
- Heavy tasks may take time
- Some tasks benefit from sequential execution
## Combines With
- Orchestration mode: Manages multiple spawned tasks
- `/plan`: Plan tasks, then spawn parallel execution
- `/execute-plan`: Orchestrated task execution
-55
View File
@@ -1,55 +0,0 @@
# /status - Project Status Command
## Purpose
Get current project status including tasks, git state, and recent activity.
## Usage
```
/status
```
---
Show current project status.
## Workflow
1. **Check Git Status**
```bash
git status
git log --oneline -5
```
2. **Review Todos**
- In progress
- Pending
- Completed today
3. **Recent Activity**
- Recent commits
- Open PRs
- Open issues
## Output
```markdown
## Project Status
### Git
- Branch: `feature/xyz`
- Status: Clean / X modified files
### Tasks
- In Progress: X
- Pending: Y
- Completed: Z
### Recent Commits
1. [commit message]
2. [commit message]
### Open PRs
- #123: [title]
```
-135
View File
@@ -1,135 +0,0 @@
# /tdd - Test-Driven Development Workflow
## Purpose
Start a TDD workflow: write failing tests first, then implement to make them pass.
## Usage
```
/tdd [feature or function description]
```
---
Start TDD workflow for: **$ARGUMENTS**
## Workflow
### Phase 1: Red - Write Failing Tests
1. **Understand Requirements**
- What should the code do?
- What are the inputs/outputs?
- What edge cases exist?
2. **Write Tests First**
```python
def test_feature_does_expected_thing():
result = feature("input")
assert result == "expected"
```
3. **Run Tests (Expect Failure)**
```bash
pytest -v # Should fail
```
### Phase 2: Green - Make Tests Pass
1. **Implement Minimal Code**
- Just enough to pass tests
- No premature optimization
2. **Run Tests (Expect Success)**
```bash
pytest -v # Should pass
```
### Phase 3: Refactor
1. **Improve Code Quality**
- Clean up implementation
- Remove duplication
- Improve naming
2. **Run Tests (Ensure Still Passing)**
```bash
pytest -v # Should still pass
```
### Phase 4: Repeat
Add more test cases and repeat the cycle.
## TDD Best Practices
- Write one test at a time
- Tests should be specific and focused
- Keep the red-green-refactor cycle short
- Commit after each green phase
## Superpowers TDD Methodology
**Reference**: `.claude/skills/test-driven-development/SKILL.md`
### Non-Negotiable Rule
**NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST**
This is not a guideline - it's a rule.
### If You Already Wrote Code
Delete it. Completely. Don't keep it as reference.
```
WRONG: "I'll keep this code as reference while writing tests"
RIGHT: Delete the code, write test, rewrite implementation
```
### Verification Before Completion
**Reference**: `.claude/skills/verification-before-completion/SKILL.md`
Before claiming tests pass:
1. **Identify** the command that proves assertion
2. **Execute** it fully and freshly
3. **Read** complete output
4. **Verify** output matches claim
5. **Only then** make the claim
### Forbidden Language
Never use without verification:
- "should work"
- "probably fixed"
- "seems to pass"
### Testing Anti-Patterns to Avoid
**Reference**: `.claude/skills/testing-anti-patterns/SKILL.md`
1. Testing mock behavior instead of real code
2. Polluting production with test-only methods
3. Mocking without understanding dependencies
4. Creating incomplete mocks
5. Writing tests as afterthoughts
## Output
```markdown
## TDD Session: [Feature]
### Tests Written
1. `test_basic_functionality` - [description]
2. `test_edge_case` - [description]
### Implementation
`src/feature.py` - [description]
### Cycle Summary
- Red: 3 tests written
- Green: All passing
- Refactor: Extracted helper function
```
-336
View File
@@ -1,336 +0,0 @@
# /test - Test Generation Command
## Purpose
Generate comprehensive tests for specified code including unit tests, integration tests, and edge cases.
## Usage
```
/test [file path | function name | 'coverage' | 'all']
```
## Arguments
- `$ARGUMENTS`:
- File path: Generate tests for specific file
- Function name: Generate tests for specific function
- `coverage`: Analyze and improve test coverage
- `all`: Run all tests and report results
---
Generate comprehensive tests for: **$ARGUMENTS**
## Workflow
### For File/Function Testing
1. **Analyze Target Code**
- Read the code to understand functionality
- Identify inputs, outputs, and side effects
- Note dependencies to mock
- Find existing tests for patterns
2. **Design Test Cases**
- **Happy Path**: Normal operation with valid inputs
- **Edge Cases**: Boundary values, empty inputs, limits
- **Error Cases**: Invalid inputs, exceptions
- **Integration Points**: External dependencies
3. **Generate Tests**
- Follow project testing conventions
- Use appropriate mocking strategies
- Write clear, descriptive test names
- Include setup and teardown
4. **Run and Verify**
```bash
# Python
pytest [test_file] -v
# TypeScript
pnpm test [test_file]
```
### For Coverage Analysis
1. **Run Coverage Report**
```bash
# Python
pytest --cov=src --cov-report=term-missing
# TypeScript
pnpm test --coverage
```
2. **Identify Gaps**
- Find untested functions
- Identify untested branches
- Note missing edge cases
3. **Generate Missing Tests**
- Prioritize by risk
- Focus on critical paths
- Add edge case coverage
## Test Templates
### Python (pytest)
```python
import pytest
from unittest.mock import Mock, patch
from src.module import function_under_test
class TestFunctionUnderTest:
"""Tests for function_under_test."""
def test_with_valid_input_returns_expected(self):
"""Test that valid input produces expected output."""
result = function_under_test("valid_input")
assert result == "expected_output"
def test_with_empty_input_returns_default(self):
"""Test that empty input returns default value."""
result = function_under_test("")
assert result == "default"
def test_with_invalid_input_raises_error(self):
"""Test that invalid input raises ValueError."""
with pytest.raises(ValueError, match="Invalid input"):
function_under_test(None)
@pytest.mark.parametrize("input_val,expected", [
("a", "result_a"),
("b", "result_b"),
("c", "result_c"),
])
def test_parametrized_inputs(self, input_val, expected):
"""Test multiple input variations."""
assert function_under_test(input_val) == expected
@patch('src.module.external_service')
def test_with_mocked_dependency(self, mock_service):
"""Test with mocked external dependency."""
mock_service.call.return_value = "mocked_result"
result = function_under_test("input")
assert result == "expected_with_mock"
mock_service.call.assert_called_once_with("input")
```
### TypeScript (vitest)
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { functionUnderTest } from './module';
describe('functionUnderTest', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should return expected output for valid input', () => {
const result = functionUnderTest('valid_input');
expect(result).toBe('expected_output');
});
it('should return default for empty input', () => {
const result = functionUnderTest('');
expect(result).toBe('default');
});
it('should throw error for invalid input', () => {
expect(() => functionUnderTest(null)).toThrow('Invalid input');
});
it.each([
['a', 'result_a'],
['b', 'result_b'],
['c', 'result_c'],
])('should handle input %s correctly', (input, expected) => {
expect(functionUnderTest(input)).toBe(expected);
});
it('should work with mocked dependency', async () => {
vi.mock('./external-service', () => ({
call: vi.fn().mockResolvedValue('mocked_result'),
}));
const result = await functionUnderTest('input');
expect(result).toBe('expected_with_mock');
});
});
```
### React Component (Testing Library)
```typescript
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { UserForm } from './UserForm';
describe('UserForm', () => {
it('should render form fields', () => {
render(<UserForm onSubmit={vi.fn()} />);
expect(screen.getByLabelText(/name/i)).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();
});
it('should call onSubmit with form data', async () => {
const onSubmit = vi.fn();
render(<UserForm onSubmit={onSubmit} />);
fireEvent.change(screen.getByLabelText(/name/i), {
target: { value: 'John' },
});
fireEvent.change(screen.getByLabelText(/email/i), {
target: { value: 'john@example.com' },
});
fireEvent.click(screen.getByRole('button', { name: /submit/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
name: 'John',
email: 'john@example.com',
});
});
});
it('should show validation error for invalid email', async () => {
render(<UserForm onSubmit={vi.fn()} />);
fireEvent.change(screen.getByLabelText(/email/i), {
target: { value: 'invalid' },
});
fireEvent.blur(screen.getByLabelText(/email/i));
expect(await screen.findByText(/invalid email/i)).toBeInTheDocument();
});
});
```
## Output
### Test Generation Report
```markdown
## Tests Generated
### Target
`src/services/auth.ts` - AuthService class
### Tests Created
- `tests/services/auth.test.ts`
### Test Cases
1. `login_with_valid_credentials_returns_token` - Happy path
2. `login_with_invalid_password_throws_error` - Error case
3. `login_with_nonexistent_user_throws_error` - Error case
4. `refresh_token_with_valid_token_returns_new_token` - Happy path
5. `refresh_token_with_expired_token_throws_error` - Edge case
6. `logout_invalidates_session` - Happy path
### Coverage Impact
- Before: 65%
- After: 88%
- New lines covered: 42
### Run Tests
```bash
pytest tests/services/auth.test.ts -v
```
### Notes
- Mocked database calls using pytest-mock
- Added edge case for token expiration
- Consider adding integration tests for full auth flow
```
## Flags
| Flag | Description | Example |
|------|-------------|---------|
| `--coverage` | Generate coverage-focused tests | `--coverage` |
| `--type=[type]` | Test type to generate | `--type=integration` |
| `--format=[fmt]` | Output format (concise/detailed) | `--format=concise` |
| `--framework=[fw]` | Specify test framework | `--framework=vitest` |
| `--tdd` | Generate TDD-style with failing tests first | `--tdd` |
| `--edge-cases` | Focus on edge case coverage | `--edge-cases` |
### Flag Usage Examples
```bash
/test --coverage src/services/
/test --type=integration src/api/users.ts
/test --tdd src/utils/validator.ts
/test --edge-cases --framework=pytest src/models/user.py
```
### Test Types
| Type | Description |
|------|-------------|
| `unit` | Isolated function tests (default) |
| `integration` | Multi-component tests |
| `e2e` | End-to-end workflow tests |
| `snapshot` | Snapshot tests for UI |
| `property` | Property-based testing |
### Framework Options
| Framework | Language |
|-----------|----------|
| `pytest` | Python |
| `vitest` | TypeScript/JavaScript |
| `jest` | JavaScript |
| `playwright` | E2E (any) |
## MCP Integration
This command leverages MCP servers for enhanced testing:
### Playwright - E2E Testing (Primary for UI)
```
For E2E and browser tests:
- Use Playwright for cross-browser testing
- Automate user flow verification
- Capture screenshots for visual testing
- Test on different device emulations
```
### Filesystem - Test File Management
```
For test file operations:
- Use directory_tree to find test directories
- Use search_files to find existing tests
- Use read_file to check test patterns
- Use write_file to create new test files
```
### Context7 - Testing Best Practices
```
For framework-specific testing:
- Fetch current testing library docs
- Get latest assertions and matchers
- Find recommended testing patterns
```
### Memory - Test Patterns
```
Recall testing context:
- Remember project testing conventions
- Recall mock patterns used previously
- Store common test fixtures
```
<!-- CUSTOMIZATION POINT -->
## Variations
Modify behavior via CLAUDE.md:
- Preferred test framework
- Minimum coverage targets
- Test naming conventions
- Required test categories
+1
View File
@@ -1,5 +1,6 @@
---
name: brainstorming
argument-hint: "[topic]"
description: >
Use when the user wants to design, explore, or ideate on ANY new feature, architecture decision, or unclear requirement. Activate for keywords like "brainstorm", "design", "explore", "what if", "how should we", "options for", "trade-offs", or any open-ended question about implementation approach. Also trigger when requirements are vague, ambiguous, or when multiple valid solutions exist -- err on the side of brainstorming before jumping into code.
---
@@ -1,5 +1,6 @@
---
name: condition-based-waiting
user-invocable: false
description: >
Use when waiting on external conditions like CI pipeline runs, deployments, long builds, database migrations, or test suites. Trigger for keywords like "wait for", "check status", "poll", "monitor", "is it done", "build running", "deploy in progress", or when a background process needs to complete before the next step. Also activate when using run_in_background or Monitor tools in Claude Code.
---
+1
View File
@@ -1,5 +1,6 @@
---
name: defense-in-depth
user-invocable: false
description: >
Use when fixing any data-related bug, when building validation for critical data paths, or when a single validation point has already failed in production. Also activate whenever you hear "it slipped through," "the check was bypassed," or "it worked in tests but not production." Apply aggressively to any scenario involving data integrity, input validation across layers, or preventing bug recurrence through structural guarantees rather than single-point fixes.
---
+3 -1
View File
@@ -1,7 +1,7 @@
---
name: devops
description: >
Use when containerizing applications, configuring CI/CD pipelines, or deploying to edge — including Docker, Dockerfile, docker-compose, multi-stage builds, GitHub Actions, workflow YAML, matrix builds, workflow_dispatch, Cloudflare Workers, Pages, R2, D1, KV, wrangler, or container registries.
Use when containerizing applications, configuring CI/CD pipelines, deploying to environments, or deploying to edge — including Docker, Dockerfile, docker-compose, multi-stage builds, GitHub Actions, workflow YAML, matrix builds, workflow_dispatch, Cloudflare Workers, Pages, R2, D1, KV, wrangler, container registries, or deployment workflows (staging, production, health checks, smoke tests).
---
# DevOps
@@ -11,6 +11,8 @@ description: >
- Containerizing applications with Docker or Docker Compose
- Setting up CI/CD pipelines with GitHub Actions
- Deploying to Cloudflare Workers, Pages, R2, D1, or KV
- Deploying applications to staging or production environments
- Running pre-deploy checks (build, tests, security audit)
- Optimizing container images, build caching, or deployment workflows
- Configuring wrangler.toml, Durable Objects, or Cloudflare Queues
@@ -1,7 +1,7 @@
---
name: dispatching-parallel-agents
description: >
Use when facing 3 or more independent failures across different domains, when multiple subsystems are broken with no shared state, or when test failures span unrelated modules. Also activate whenever you see independent bugs in auth, cart, user, or other separate domains that can be fixed concurrently. Activate aggressively for any scenario where parallel work would reduce total resolution time without creating merge conflicts.
Use when facing 3 or more independent failures across different domains, when multiple subsystems are broken with no shared state, or when test failures span unrelated modules. Also activate whenever you see independent bugs in auth, cart, user, or other separate domains that can be fixed concurrently. Use for launching parallel background tasks like research, analysis, or code review across independent areas. Activate aggressively for any scenario where parallel work would reduce total resolution time without creating merge conflicts.
---
# Dispatching Parallel Agents
+82
View File
@@ -0,0 +1,82 @@
---
name: documentation
argument-hint: "[file or api/readme]"
description: >
Use when generating or updating documentation — including code comments, docstrings, JSDoc, API docs, README files, or technical specifications. Trigger for keywords like "document", "docstring", "JSDoc", "README", "API docs", "explain this code", "add comments", or any request to improve code documentation. Also activate when generating project documentation or updating existing docs after code changes.
---
# Documentation
## When to Use
- Adding docstrings or JSDoc to functions/classes
- Generating or updating README files
- Documenting API endpoints
- Writing technical specifications
- Adding inline comments to complex logic
## When NOT to Use
- Generating changelogs from commits — use `git-workflows`
- Writing OpenAPI specs — use `openapi`
- Architecture design documentation — use `brainstorming` + `writing-plans`
---
## Quick Reference
| Topic | Reference | Key content |
|-------|-----------|-------------|
| Code documentation | `references/code-docs.md` | Python docstrings, TypeScript JSDoc, inline comments |
| API documentation | `references/api-docs.md` | Endpoint docs, request/response examples |
| Project documentation | `references/project-docs.md` | README, CONTRIBUTING, architecture docs |
---
## Documentation Workflow
### For Code
1. Read the code thoroughly — understand purpose and behavior
2. Identify inputs, outputs, side effects, and edge cases
3. Add docstrings/JSDoc with examples
4. Add type annotations if missing
### For APIs
1. Scan route definitions and identify endpoints
2. Document request format, response format, error responses
3. Add authentication requirements
4. Include working examples
### For Projects
1. Analyze project purpose, features, and setup
2. Write clear installation and usage instructions
3. Include working code examples
4. Keep configuration tables up to date
---
## Best Practices
1. **Document the why, not the what** — code shows what; comments explain why.
2. **Include examples** — one working example beats three paragraphs of description.
3. **Document edge cases** — what happens with null, empty, or invalid input?
4. **Keep docs adjacent to code** — docstrings over separate doc files.
5. **Update docs with code** — stale docs are worse than no docs.
## Common Pitfalls
1. **Restating the code**`# increment i by 1` adds no value.
2. **Missing error documentation** — not documenting what exceptions a function raises.
3. **Outdated examples** — code examples that no longer compile.
4. **Over-documenting internal code** — public APIs need docs; private helpers often don't.
---
## Related Skills
- `openapi` — OpenAPI spec generation for REST APIs
- `git-workflows` — Changelog generation from commits
- `backend-frameworks` — Framework-specific documentation patterns
@@ -0,0 +1,44 @@
# API Documentation Patterns
## Endpoint Documentation Template
```markdown
## POST /api/orders
Create a new order.
### Authentication
Requires Bearer token.
### Request Body
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| items | array | yes | Order items |
| shippingAddress | object | yes | Delivery address |
### Response (201 Created)
```json
{
"id": "order_456",
"status": "pending",
"total": 99.99,
"createdAt": "2024-01-15T10:00:00Z"
}
```
### Errors
| Status | Code | Description |
|--------|------|-------------|
| 400 | INVALID_ITEMS | Items array is empty |
| 401 | UNAUTHORIZED | Invalid or missing token |
| 422 | OUT_OF_STOCK | Item not available |
```
## Discovery Process
1. Scan route definitions (`@app.get`, `router.post`, `@Controller`)
2. Identify HTTP methods and paths
3. Note authentication requirements
4. Document request/response schemas
5. List all error responses with codes
6. Add working curl/httpx examples
@@ -0,0 +1,52 @@
# Code Documentation Patterns
## Python Docstrings (Google Style)
```python
def calculate_discount(price: float, percentage: float) -> float:
"""Calculate discounted price.
Args:
price: Original price in dollars.
percentage: Discount percentage (0-100).
Returns:
The discounted price.
Raises:
ValueError: If percentage is not between 0 and 100.
Example:
>>> calculate_discount(100.0, 20)
80.0
"""
```
## TypeScript JSDoc
```typescript
/**
* Calculate discounted price.
*
* @param price - Original price in dollars
* @param percentage - Discount percentage (0-100)
* @returns The discounted price
* @throws {RangeError} If percentage is not between 0 and 100
*
* @example
* calculateDiscount(100, 20); // returns 80
*/
```
## When to Add Inline Comments
- Explain **why**, not what — `# Retry 3x because upstream API is flaky`
- Document workarounds — `// Safari doesn't support this API, fallback to...`
- Clarify non-obvious logic — `# O(1) amortized via lazy deletion`
- Mark TODOs with context — `# TODO(#123): remove after migration complete`
## When NOT to Comment
- Restating the code: `i += 1 # increment i by 1`
- Obvious function names: `def get_user_by_id` needs no docstring explaining it gets a user by ID
- Commented-out code — delete it, git has history
@@ -0,0 +1,43 @@
# Project Documentation Patterns
## README Structure
```markdown
## Installation
```bash
npm install my-package
```
## Quick Start
```typescript
import { Client } from 'my-package';
const client = new Client({ apiKey: 'your-key' });
const result = await client.fetch();
```
## Configuration
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiKey` | string | required | Your API key |
| `timeout` | number | 5000 | Request timeout in ms |
```
## Key Sections
1. **Title + one-liner** — what this project does
2. **Installation** — copy-pasteable setup commands
3. **Quick Start** — working example in < 10 lines
4. **Configuration** — table of options with types and defaults
5. **API Reference** — link to detailed docs
6. **Contributing** — how to contribute
7. **License** — MIT, Apache, etc.
## Documentation Coverage Report
After documenting, summarize:
- Functions documented: X/Y (Z%)
- Endpoints documented: X/Y (Z%)
- Missing: [list of undocumented items]
+135
View File
@@ -0,0 +1,135 @@
---
name: feature-workflow
argument-hint: "[feature description or issue]"
description: >
Use when implementing a complete feature end-to-end — from requirements analysis through planning, implementation, testing, and review. Trigger for keywords like "feature", "implement", "build", "add functionality", "end-to-end", or any task that spans planning through delivery. Also activate when the user provides a feature description, issue reference, or requirement spec that needs a structured development workflow.
---
# Feature Workflow
## When to Use
- Implementing a complete feature from requirements to delivery
- When given a feature description, issue number, or requirement spec
- Multi-phase work that needs planning, implementation, testing, and review
- Any task that benefits from a structured development workflow
## When NOT to Use
- Simple bug fixes — use `systematic-debugging`
- Pure refactoring — use `refactoring`
- Writing tests for existing code — use `testing`
- Already have a plan to execute — use `executing-plans`
---
## Workflow Phases
### Phase 1: Understanding
1. Parse the feature request thoroughly
2. Identify acceptance criteria
3. List assumptions that need validation
4. Clarify ambiguous requirements with the user
### Phase 2: Planning
1. Explore codebase for related implementations and patterns
2. Identify integration points and dependencies
3. Decompose into atomic, verifiable tasks
4. Order tasks by dependencies
5. Track all tasks with TodoWrite
### Phase 3: Research (if needed)
If the feature involves unfamiliar technology:
1. Research best practices and patterns
2. Find examples in the codebase or documentation
3. Identify potential pitfalls
### Phase 4: Implementation
For each task:
1. Write failing test first (TDD)
2. Implement minimally to pass the test
3. Refactor if needed
4. Mark task complete immediately
### Phase 5: Testing
1. Run full test suite — no regressions
2. Verify coverage — should not decrease
3. Test edge cases and error scenarios
```bash
# Python
pytest -v --cov=src
# TypeScript
pnpm test
```
### Phase 6: Review
Self-review checklist:
- [ ] Code follows project conventions
- [ ] No security vulnerabilities
- [ ] Error handling is complete
- [ ] Tests are passing
- [ ] No debug statements or TODOs
### Phase 7: Completion
1. Verify all tasks complete
2. Stage appropriate files
3. Generate commit message
4. Create PR if requested
---
## Output Format
```markdown
## Feature Implementation Complete
### Feature
[Feature description]
### Changes Made
- `path/to/file.ts` — [What was added/modified]
- `path/to/file.test.ts` — [Tests added]
### Tests
- [x] Unit tests passing
- [x] Integration tests passing
- [x] Coverage: XX%
### Ready for Review
```
---
## Best Practices
1. **Break down aggressively** — smaller tasks are easier to verify and commit.
2. **Test first** — every task starts with a failing test.
3. **Commit incrementally** — commit after each task, not at the end.
4. **Clarify before building** — ambiguous requirements lead to rework.
5. **Check existing patterns** — follow conventions already in the codebase.
## Common Pitfalls
1. **Starting without understanding** — jumping to code before clarifying requirements.
2. **Monolithic implementation** — implementing everything in one pass without incremental verification.
3. **Ignoring existing patterns** — building something inconsistent with the rest of the codebase.
4. **Skipping tests** — "I'll add tests later" means no tests.
---
## Related Skills
- `brainstorming` — Use before this skill when requirements are unclear or need exploration
- `writing-plans` — Use for detailed task breakdown when the feature is complex
- `test-driven-development` — The TDD discipline applied during Phase 4
- `git-workflows` — Committing and shipping the completed feature
- `requesting-code-review` — Getting feedback before merging
+119
View File
@@ -0,0 +1,119 @@
---
name: git-workflows
argument-hint: "[commit/ship/pr/changelog]"
description: >
Use when committing code, creating pull requests, shipping changes, or generating changelogs. Trigger for keywords like "commit", "push", "PR", "pull request", "ship", "merge", "changelog", "release notes", "conventional commits", or any git workflow beyond basic status/diff. Also activate when preparing code for review or automating the commit-to-PR pipeline.
---
# Git Workflows
## When to Use
- Creating commits with conventional commit messages
- Shipping code (commit + review + push + PR)
- Creating pull requests with proper descriptions
- Generating changelogs from commit history
- Preparing code for review or merge
## When NOT to Use
- Basic git operations (status, diff, log) — just run them directly
- Branch management strategy — use `using-git-worktrees`
- Code review content — use `requesting-code-review`
---
## Quick Reference
| Workflow | Reference | Key content |
|----------|-----------|-------------|
| Committing | `references/committing.md` | Conventional commits, message format, pre-commit checks |
| Shipping | `references/shipping.md` | Full ship workflow: review → test → commit → push → PR |
| Pull Requests | `references/pull-requests.md` | PR creation, description templates, gh CLI patterns |
| Changelogs | `references/changelogs.md` | Changelog generation from commits, Keep a Changelog format |
---
## Conventional Commit Format
```
type(scope): subject
body (optional)
footer (optional)
```
| Type | When |
|------|------|
| `feat` | New feature |
| `fix` | Bug fix |
| `docs` | Documentation only |
| `refactor` | Code restructuring, no behavior change |
| `test` | Adding or fixing tests |
| `chore` | Maintenance, dependencies, CI |
| `style` | Formatting, whitespace |
### Subject Line Rules
- Max 50 characters, imperative mood ("Add" not "Added"), no trailing period
---
## Ship Workflow
```
1. Pre-ship checks (secrets, debug statements)
2. Self-review (code quality, style)
3. Run tests (full suite, coverage check)
4. Create commit (conventional format)
5. Push to remote
6. Create PR (summary, test plan, checklist)
```
---
## PR Description Template
```markdown
## Summary
- [Change 1]
- [Change 2]
## Test Plan
- [ ] Unit tests pass
- [ ] Manual testing done
## Checklist
- [ ] No breaking changes
- [ ] Tests added/updated
- [ ] Documentation updated
```
---
## Best Practices
1. **Atomic commits** — one logical change per commit, not one file per commit.
2. **Explain why, not what** — the diff shows what changed; the message explains why.
3. **Stage specific files** — prefer `git add <file>` over `git add -A` to avoid committing secrets or unrelated changes.
4. **Reference issues** — include `Closes #123` or `Fixes #456` in footers.
5. **Pre-commit checks** — verify no secrets, debug statements, or commented-out code before committing.
6. **PR descriptions matter** — reviewers read the description before the diff; make it count.
## Common Pitfalls
1. **Committing secrets**`.env` files, API keys, tokens in staged changes.
2. **Vague commit messages** — "fix stuff", "updates", "WIP" provide no context.
3. **Giant PRs** — 500+ line PRs get rubber-stamped; split into focused chunks.
4. **Amending published commits** — rewriting history others have pulled causes conflicts.
5. **Skipping pre-commit hooks**`--no-verify` hides real issues.
6. **Force pushing to shared branches** — can destroy teammates' work.
---
## Related Skills
- `requesting-code-review` — Preparing changes for reviewer feedback
- `finishing-a-development-branch` — End-of-branch workflow decisions
- `using-git-worktrees` — Isolated branch management
@@ -0,0 +1,59 @@
# Changelog Generation
## Keep a Changelog Format
Based on [keepachangelog.com](https://keepachangelog.com):
```markdown
## [1.2.0] - 2026-04-19
### Added
- Password reset functionality (#123)
- Email verification for new accounts
### Changed
- Improved error messages for validation failures
- Updated dependencies to latest versions
### Fixed
- Race condition in session handling (#456)
- Incorrect timezone in date displays
### Removed
- Legacy v1 API endpoints (deprecated since 1.0)
```
## Generating from Commits
```bash
# Get commits since last tag
git log --oneline $(git describe --tags --abbrev=0)..HEAD
# Group by type
git log --oneline --grep="^feat" $(git describe --tags --abbrev=0)..HEAD
git log --oneline --grep="^fix" $(git describe --tags --abbrev=0)..HEAD
```
## Category Mapping
| Commit Type | Changelog Category |
|-------------|-------------------|
| `feat` | Added |
| `fix` | Fixed |
| `refactor`, `perf` | Changed |
| removal commits | Removed |
| `docs` | Usually omitted |
| `chore`, `test`, `style` | Usually omitted |
## User-Friendly Descriptions
Transform commit messages into user-facing descriptions:
```
BAD: feat(auth): add pwd reset (#123)
GOOD: Password reset functionality — users can now reset their password via email (#123)
```
- Write for users, not developers
- Include PR/issue references
- Explain the user-visible impact
@@ -0,0 +1,90 @@
# Committing Patterns
## Pre-Commit Checklist
Before staging:
- [ ] No secrets (`.env`, API keys, tokens)
- [ ] No debug statements (`console.log`, `print()`, `debugger`)
- [ ] No commented-out code blocks
- [ ] Code is formatted (prettier/ruff)
## Conventional Commit Format
```
type(scope): subject
body (optional - explain why, not what)
footer (optional - references, breaking changes)
```
### Types
| Type | When | Example |
|------|------|---------|
| `feat` | New feature | `feat(auth): add OAuth2 login` |
| `fix` | Bug fix | `fix(api): handle null user in profile` |
| `docs` | Documentation | `docs(readme): update install steps` |
| `refactor` | Restructure, no behavior change | `refactor(db): extract query builders` |
| `test` | Add/fix tests | `test(auth): add login edge cases` |
| `chore` | Maintenance | `chore(deps): update React to 19` |
| `style` | Formatting | `style: apply prettier` |
| `perf` | Performance | `perf(query): add index on user_id` |
### Subject Line Rules
- Max 50 characters
- Imperative mood: "Add" not "Added" or "Adds"
- No trailing period
- Capitalize first letter
### Body Rules
- Wrap at 72 characters
- Explain **why**, not what (the diff shows what)
- Use bullet points for multiple changes
### Footer Patterns
```
Closes #123
Fixes #456
BREAKING CHANGE: removed legacy auth endpoint
Co-Authored-By: Claude <noreply@anthropic.com>
```
## Staging Best Practices
```bash
# Prefer specific files over blanket add
git add src/auth/login.ts src/auth/login.test.ts
# Review what you're committing
git diff --staged
# Never commit these
# .env, credentials.json, *.pem, *.key
```
## Commit Command Pattern
```bash
git commit -m "$(cat <<'EOF'
feat(auth): add password reset flow
- Add reset token generation with 1h expiry
- Implement email sending via SendGrid
- Add rate limiting (3 requests/hour)
Closes #123
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
## Amending vs New Commit
- **Amend**: Only for unpushed commits, only when fixing the same logical change
- **New commit**: Always for pushed commits, or when adding distinct changes
- **Never amend after pre-commit hook failure** — the commit didn't happen, so amend would modify the previous commit
@@ -0,0 +1,77 @@
# Pull Request Patterns
## Pre-PR Checklist
- [ ] All tests passing
- [ ] Code self-reviewed
- [ ] No merge conflicts with base branch
- [ ] Branch pushed to remote
- [ ] Commit history is clean (no "WIP" or "fix typo" noise)
## Creating a PR
```bash
# Check current state
git status
git diff main...HEAD
git log --oneline main..HEAD
# Push if needed
git push -u origin $(git branch --show-current)
# Create PR
gh pr create --title "feat(scope): description" --body "$(cat <<'EOF'
## Summary
- [Change 1]
- [Change 2]
## Test Plan
- [ ] Unit tests added
- [ ] Manual testing done
- [ ] Edge cases covered
## Checklist
- [ ] No breaking changes
- [ ] Tests added/updated
- [ ] Documentation updated
🤖 Generated with [Claude Code](https://claude.com/claude-code)
EOF
)"
```
## PR Title Format
Follow conventional commits: `type(scope): description`
- Max 70 characters
- Use description/body for details, not the title
## PR Size Guidelines
| Size | Lines Changed | Review Time |
|------|--------------|-------------|
| Small | < 100 | Quick review |
| Medium | 100-300 | Thorough review |
| Large | 300-500 | Split if possible |
| Too Large | > 500 | Must split |
## Viewing PR Comments
```bash
# View PR comments
gh api repos/owner/repo/pulls/123/comments
# View PR review comments
gh pr view 123 --comments
```
## Draft PRs
```bash
# Create as draft for early feedback
gh pr create --draft --title "WIP: feature" --body "Early draft for feedback"
# Mark ready when done
gh pr ready 123
```
@@ -0,0 +1,101 @@
# Ship Workflow
Complete workflow: review → test → commit → push → PR.
## Phase 1: Pre-Ship Checks
```bash
git status
git diff --staged
```
Verify:
- [ ] No secrets in staged files
- [ ] No debug statements
- [ ] No commented-out code
- [ ] No unintended files
## Phase 2: Self-Review
- Check code quality and style compliance
- Verify security (no hardcoded secrets, proper input validation)
- Address critical issues before proceeding
## Phase 3: Run Tests
```bash
# Python
pytest -v
# TypeScript
pnpm test
```
- All tests must pass
- Coverage should not decrease
- No new warnings
## Phase 4: Create Commit
```bash
# Stage specific files
git add src/feature.ts src/feature.test.ts
# Commit with conventional format
git commit -m "$(cat <<'EOF'
feat(scope): description
- Change 1
- Change 2
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
## Phase 5: Push and Create PR
```bash
# Push with upstream tracking
git push -u origin feature/my-feature
# Create PR
gh pr create --title "feat(scope): description" --body "$(cat <<'EOF'
## Summary
- Change 1
- Change 2
## Test Plan
- [ ] Unit tests pass
- [ ] Manual testing done
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
## Quick Ship Mode
For small, low-risk changes:
1. Skip detailed self-review
2. Auto-generate commit message from diff
3. Minimal PR description
## Ship Report Format
```markdown
## Ship Complete
### Commit
**Hash**: `abc1234`
**Message**: `feat(auth): add password reset`
### Checks
- [x] Tests passing (42 tests)
- [x] Coverage: 85% (+3%)
- [x] No security issues
### Pull Request
**URL**: https://github.com/org/repo/pull/123
**Status**: Ready for review
```
+91
View File
@@ -0,0 +1,91 @@
---
name: mode-switching
argument-hint: "[mode name]"
description: >
Use when the user wants to switch behavioral modes for the session — adjusting communication style, output format, and problem-solving approach. Trigger for keywords like "mode", "switch mode", "brainstorm mode", "token-efficient", "deep-research mode", "implementation mode", "review mode", "orchestration mode", or any request to change how Claude responds for the remainder of the session.
---
# Mode Switching
## When to Use
- User wants to change response style for the session
- Switching between exploration and execution phases
- Optimizing for token efficiency during high-volume work
- Entering focused review or deep-research mode
## When NOT to Use
- One-off format requests ("give me a shorter answer") — just comply directly
- Switching tools or skills — modes affect style, not capabilities
---
## Available Modes
| Mode | Description | Best For |
|------|-------------|----------|
| `default` | Balanced responses, mix of explanation and code | General tasks |
| `brainstorm` | More questions, multiple alternatives, explore trade-offs | Design, ideation |
| `token-efficient` | Minimal explanations, code-only where possible | High-volume, cost savings |
| `deep-research` | Thorough analysis, citations, confidence levels | Investigation, audits |
| `implementation` | Jump straight to code, progress indicators | Executing plans |
| `review` | Look for issues first, severity levels, actionable feedback | Code review, QA |
| `orchestration` | Task breakdown, parallel execution, result aggregation | Complex parallel work |
## Mode Activation
```
/mode brainstorm # Switch for session
/mode # Show current mode
/mode default # Reset
```
## Per-Command Override
Modes can be overridden for a single command without changing the session mode:
```
/feature --mode=implementation "add user profiles"
/review --mode=deep-research src/auth/
/plan --mode=brainstorm "design payment flow"
```
## Recommended Workflows
### Feature Development
```
brainstorm → implementation → review → default
```
### Bug Investigation
```
deep-research → implementation → default
```
### Cost-Conscious Session
```
token-efficient → [work on tasks] → default
```
---
## Mode Files
Mode definitions: `.claude/modes/`
Customize modes by editing these files. Each mode adjusts:
- Communication style and verbosity
- Output format preferences
- Problem-solving approach
- When to ask questions vs proceed
---
## Related Skills
- `writing-concisely` — The token-efficient mode activates this skill's patterns
- `brainstorming` — The brainstorm mode uses this skill's questioning approach
+1
View File
@@ -13,6 +13,7 @@ A design-first reference for REST APIs developers want to use. Standardizes on *
- Designing or documenting a new REST API
- Generating clients/servers from a spec (FastAPI, Express, NestJS, etc.)
- Establishing error, pagination, versioning, or auth conventions for a service
- Generating API endpoints, models, and tests from a resource specification
- Migrating a spec from OpenAPI 3.0 → 3.1
- Setting up lint/governance in CI
+3 -1
View File
@@ -1,7 +1,7 @@
---
name: owasp
description: >
Use when reviewing code for security vulnerabilities, implementing authentication or authorization flows, handling user input validation, or building web endpoints exposed to untrusted data. Trigger on keywords like XSS, SQL injection, CSRF, input sanitization, password hashing, and security headers. Also apply when auditing existing code for OWASP Top 10 compliance or conducting security-focused code reviews.
Use when reviewing code for security vulnerabilities, implementing authentication or authorization flows, handling user input validation, or building web endpoints exposed to untrusted data. Trigger on keywords like XSS, SQL injection, CSRF, input sanitization, password hashing, security headers, "security scan", "vulnerability scan", "npm audit", or "pip-audit". Also apply when auditing existing code for OWASP Top 10 compliance, scanning dependencies for known vulnerabilities, detecting hardcoded secrets, or conducting security-focused code reviews.
---
# OWASP Security Patterns
@@ -14,6 +14,8 @@ description: >
- Preventing XSS, SQL injection, CSRF, or SSRF
- Auditing authentication or authorization flows
- Building endpoints that handle untrusted data
- Scanning dependencies for known vulnerabilities (`npm audit`, `pip-audit`)
- Detecting hardcoded secrets, API keys, or tokens in code
## When NOT to Use
@@ -0,0 +1,116 @@
---
name: performance-optimization
argument-hint: "[file or function]"
description: >
Use when analyzing or optimizing code performance — including profiling, benchmarking, fixing N+1 queries, reducing bundle size, eliminating memory leaks, or improving algorithm complexity. Trigger for keywords like "slow", "performance", "optimize", "profiling", "memory leak", "bundle size", "N+1", "re-render", "benchmark", "latency", "throughput", or any request to make code faster. Also activate when investigating production performance issues or when code review flags performance concerns.
---
# Performance Optimization
## When to Use
- Profiling slow code to find bottlenecks
- Fixing N+1 query problems
- Reducing JavaScript bundle size
- Eliminating memory leaks
- Improving algorithm complexity
- Benchmarking before/after optimization
- Investigating production latency issues
## When NOT to Use
- Premature optimization — profile first, optimize second
- Caching strategy design — use `caching`
- Database schema/index design — use `databases`
- Code structure improvement — use `refactoring`
---
## Quick Reference
| Topic | Reference | Key content |
|-------|-----------|-------------|
| Profiling tools | `references/profiling.md` | Python (cProfile, py-spy, Scalene) and JS/TS (DevTools, Lighthouse, clinic.js) |
| Anti-patterns | `references/anti-patterns.md` | N+1 queries, unnecessary re-renders, event loop blocking, memory leaks |
---
## Optimization Workflow
1. **Measure first** — profile to find the actual bottleneck
2. **Set a target** — "reduce p95 latency from 500ms to 100ms"
3. **Optimize the hot path** — fix the #1 bottleneck, not everything
4. **Benchmark before/after** — prove the improvement with numbers
5. **Check for regressions** — ensure correctness wasn't sacrificed
---
## Profiling Quick Start
### Python
```bash
# CPU profiling
python -m cProfile -o output.prof script.py
# Visualize: pip install snakeviz && snakeviz output.prof
# Live profiling (attach to running process)
py-spy top --pid 12345
# Line-by-line profiling
kernprof -lv script.py # requires @profile decorator
```
### JavaScript/TypeScript
```bash
# Bundle analysis
npx webpack-bundle-analyzer stats.json
# or: ANALYZE=true next build
# Node.js profiling
node --prof app.js
clinic doctor -- node app.js
# Benchmarking
npx vitest bench
```
---
## Common Anti-Patterns
| Anti-Pattern | Detection | Fix |
|-------------|-----------|-----|
| N+1 queries | `django-debug-toolbar`, `prisma.$on('query')` | `select_related`/`joinedload`/`include` |
| Unnecessary re-renders | React DevTools Profiler | `useMemo`, `useCallback`, `React.memo` |
| Blocking event loop | `clinic doctor`, high event loop lag | `worker_threads`, async variants |
| Memory leaks | Heap snapshots, growing `process.memoryUsage()` | Remove listeners, clear refs, bound caches |
| Unbounded lists | No pagination, full table scans | Cursor pagination, `LIMIT` |
| Heavy imports | Bundle analyzer showing large deps | Tree-shaking, `import { x }`, code splitting |
---
## Best Practices
1. **Profile before optimizing** — intuition about bottlenecks is often wrong.
2. **Optimize the hot path** — 80% of time is spent in 20% of code.
3. **Measure, don't guess** — use benchmarks with statistical significance.
4. **Set clear targets** — "faster" is not measurable; "p95 < 100ms" is.
5. **Avoid premature optimization** — correctness and readability come first.
## Common Pitfalls
1. **Optimizing cold paths** — spending time on code that runs once.
2. **Micro-benchmarking without context** — 10ns vs 20ns doesn't matter if the DB call takes 50ms.
3. **Sacrificing readability** — an unreadable optimization is a future bug.
4. **Caching without invalidation** — stale data is worse than slow data.
5. **Ignoring algorithmic complexity** — no amount of micro-optimization fixes O(n^2) on large inputs.
---
## Related Skills
- `caching` — Caching strategies (memoization, HTTP, Redis, CDN)
- `databases` — Query optimization, indexing, connection pooling
- `frontend` — React rendering optimization patterns
@@ -0,0 +1,115 @@
# Performance Anti-Patterns
## N+1 Queries
**Signal**: Many small queries instead of one batch query.
### SQLAlchemy (Python)
```python
# BAD: N+1 — each user triggers a query for posts
users = session.query(User).all()
for user in users:
print(user.posts) # lazy load, 1 query per user
# GOOD: eager loading
from sqlalchemy.orm import joinedload, selectinload
users = session.query(User).options(selectinload(User.posts)).all()
```
### Prisma (TypeScript)
```typescript
// BAD: N+1
const users = await prisma.user.findMany();
for (const user of users) {
const posts = await prisma.post.findMany({ where: { authorId: user.id } });
}
// GOOD: include
const users = await prisma.user.findMany({ include: { posts: true } });
```
### Django
```python
# BAD
for order in Order.objects.all():
print(order.customer.name) # N+1
# GOOD
for order in Order.objects.select_related('customer').all():
print(order.customer.name) # 1 query with JOIN
```
## Unnecessary Re-renders (React)
**Signal**: Components re-rendering when their data hasn't changed.
```typescript
// BAD: new object created every render
<Child style={{ color: 'red' }} />
// GOOD: stable reference
const style = useMemo(() => ({ color: 'red' }), []);
<Child style={style} />
// BAD: new function every render
<Button onClick={() => handleClick(id)} />
// GOOD: stable callback
const handleClick = useCallback(() => doSomething(id), [id]);
<Button onClick={handleClick} />
```
Detect with: React DevTools Profiler → "Highlight updates when components render"
## Blocking the Event Loop (Node.js)
**Signal**: High event loop lag, slow response times.
```typescript
// BAD: synchronous file read blocks everything
const data = fs.readFileSync('large-file.json');
// GOOD: async
const data = await fs.promises.readFile('large-file.json');
// BAD: CPU-heavy in main thread
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512');
// GOOD: async or worker_threads
const hash = await new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, key) => {
err ? reject(err) : resolve(key);
});
});
```
## Memory Leaks
### Python
- Circular references with `__del__`
- Unclosed file handles / DB connections
- Growing global caches without TTL
- Detect: `objgraph`, `tracemalloc`
### JavaScript
- Detached DOM nodes
- Forgotten event listeners (`addEventListener` without `removeEventListener`)
- Closures capturing large scopes
- Unbounded `Map`/`Set` growth
- Detect: Chrome Heap Snapshots, `process.memoryUsage()`
## Heavy Imports / Bundle Bloat
```typescript
// BAD: imports entire library
import _ from 'lodash';
// GOOD: tree-shakeable import
import { debounce } from 'lodash-es';
// GOOD: native alternative
const debounce = (fn, ms) => { /* 5 lines */ };
```
Replace heavy deps: moment → dayjs, lodash → lodash-es or native, date-fns (tree-shakeable).
Use `React.lazy()` + `Suspense` for route-based code splitting.
@@ -0,0 +1,109 @@
# Profiling Tools Reference
## Python
### cProfile (built-in, function-level)
```bash
python -m cProfile -o output.prof script.py
# Visualize
pip install snakeviz && snakeviz output.prof
```
### py-spy (sampling, production-safe)
```bash
# Top-like view of running process
py-spy top --pid 12345
# Generate flame graph
py-spy record -o profile.svg --pid 12345
```
### line_profiler (line-by-line)
```bash
# Add @profile decorator to target function
kernprof -lv script.py
```
### memory_profiler (memory usage)
```bash
# Add @profile decorator
python -m memory_profiler script.py
# Or use stdlib tracemalloc for snapshot comparison
```
### Scalene (CPU + memory + GPU)
```bash
scalene script.py
# Modern alternative, AI-suggested optimizations
```
## JavaScript / TypeScript
### Chrome DevTools Performance
- Performance tab → Record → interact → Stop
- Flame chart shows main thread activity
- Look for long tasks (>50ms), layout thrashing
### Lighthouse (web vitals)
```bash
npx lighthouse https://localhost:3000 --output=json
# CI integration
npx @lhci/cli autorun
```
### Bundle Analysis
```bash
# Webpack
npx webpack-bundle-analyzer stats.json
# Next.js
ANALYZE=true next build
# Source map explorer
npx source-map-explorer dist/**/*.js
```
### clinic.js (Node.js)
```bash
# Event loop health
clinic doctor -- node app.js
# CPU flame graph
clinic flame -- node app.js
# Async bottlenecks
clinic bubbleprof -- node app.js
```
### Node.js built-in
```bash
node --prof app.js
node --prof-process isolate-*.log > profile.txt
```
## Benchmarking
### Python
```bash
# pytest-benchmark
pytest --benchmark-only
# timeit
python -m timeit -s "setup" "expression"
```
### JavaScript/TypeScript
```typescript
// Vitest bench (built-in)
// my-func.bench.ts
import { bench } from 'vitest';
bench('my function', () => {
myFunction(testData);
});
```
```bash
npx vitest bench
```
+113
View File
@@ -0,0 +1,113 @@
---
name: refactoring
argument-hint: "[file or function]"
description: >
Use when improving code structure, readability, or maintainability without changing behavior. Trigger for keywords like "refactor", "clean up", "extract", "simplify", "rename", "restructure", "code smell", "technical debt", "DRY", or any request to improve code quality without adding features. Also activate when code reviews identify structural issues, when functions are too long, or when duplication needs elimination.
---
# Refactoring
## When to Use
- Improving code structure without changing behavior
- Extracting reusable functions or components
- Eliminating code duplication
- Reducing complexity (long functions, deep nesting)
- Renaming for clarity
- Addressing code review feedback about structure
## When NOT to Use
- Adding new features — use `feature-workflow`
- Fixing bugs — use `systematic-debugging` (behavior change, not refactoring)
- Performance optimization — use `performance-optimization`
---
## Quick Reference
| Topic | Reference | Key content |
|-------|-----------|-------------|
| Refactoring patterns | `references/patterns.md` | Extract, inline, rename, move, decompose, introduce parameter object |
| Code smells | `references/code-smells.md` | Detection signals and recommended refactorings |
---
## Safe Refactoring Workflow
1. **Ensure tests pass** before any change
2. **Make one small, behavior-preserving change** at a time
3. **Run tests after each change**
4. **Commit each successful step** independently
5. **Use type checkers** (mypy/tsc) as a secondary safety net
6. **Never mix refactoring with feature/bug changes** in the same commit
---
## Core Patterns
| Pattern | When | Example |
|---------|------|---------|
| Extract function | Long function, repeated logic | Pull 10-line block into named function |
| Inline function | Trivial wrapper adding no clarity | Remove `getAge()` that just returns `this.age` |
| Rename symbol | Name doesn't reveal intent | `x``userCount` |
| Introduce parameter object | 4+ related parameters | `(name, email, age)``UserInput` |
| Replace conditional with polymorphism | Long if/else or switch chains | Strategy pattern or subclass dispatch |
| Decompose conditional | Complex boolean expression | `isEligible()` instead of `age > 18 && !banned && verified` |
| Extract variable | Complex expression | `const isOverBudget = total > limit * 1.1` |
---
## Code Smell Signals
- **Long function** (>20-30 lines)
- **Long parameter list** (>3-4 params)
- **Duplicated logic** across multiple locations
- **Deep nesting** (>3 levels)
- **Feature envy** — function uses another class's data more than its own
- **Shotgun surgery** — one change requires edits in many files
- **Primitive obsession** — raw strings/dicts instead of typed objects
- **Dead code** — unreachable or unused functions/imports
---
## Python-Specific
- Convert `dict` bags to **dataclasses** or **TypedDict**
- Add **type hints** progressively
- Replace loops with **comprehensions** where clearer
- Use **`@property`** instead of get/set methods
- Use **`Enum`** instead of string constants
## TypeScript-Specific
- Use **discriminated unions** instead of class hierarchies
- Replace `any` with **generics** or **`unknown`** + narrowing
- Replace enums with **`as const`** objects for tree-shaking
- Extract **utility types** (`Pick`, `Omit`, `Partial`)
---
## Best Practices
1. **Rule of three** — extract on the third duplication, not the first.
2. **Tests are the safety net** — never refactor without them.
3. **Small steps** — one rename is better than a big-bang rewrite.
4. **Preserve interfaces** — change internals, not public APIs (unless that's the goal).
5. **Use IDE tooling** — automated rename/move updates all references.
## Common Pitfalls
1. **Refactoring without tests** — no safety net to catch regressions.
2. **Mixing refactoring with features** — makes it impossible to identify behavior changes.
3. **Premature abstraction** — extracting patterns before duplication exists.
4. **Too-large refactors** — big-bang rewrites instead of incremental steps.
5. **Breaking public interfaces** — changing signatures without updating callers.
---
## Related Skills
- `testing` — Ensure test coverage before refactoring
- `languages` — Language-specific idioms and patterns
- `writing-concisely` — Refactoring responses can be terse (show before/after)
@@ -0,0 +1,32 @@
# Code Smells Detection Guide
## Smell → Refactoring Map
| Smell | Signal | Refactoring |
|-------|--------|-------------|
| Long function | >20-30 lines | Extract function |
| Long parameter list | >3-4 params | Introduce parameter object |
| Duplicated logic | Same code in 3+ places | Extract function, DRY |
| Deep nesting | >3 levels of indentation | Early return, extract function |
| Feature envy | Uses another class's data more than its own | Move method to the class with the data |
| Shotgun surgery | One change → edits in many files | Move related code together |
| Primitive obsession | Raw strings/dicts instead of types | Introduce dataclass/interface |
| Dead code | Unreachable or unused | Delete it (git has history) |
| God class | Class does too many things | Extract class by responsibility |
| Comments as deodorant | Comments explaining messy code | Refactor the code to be clear |
## Python-Specific Smells
- `dict` used as a struct → use `@dataclass` or `TypedDict`
- Missing type hints on public functions
- Manual `__init__` boilerplate → `@dataclass`
- String constants → `Enum`
- Getter/setter methods → `@property`
## TypeScript-Specific Smells
- `any` type → `unknown` + narrowing or generics
- Enum → `as const` object (better tree-shaking)
- Class hierarchy for variants → discriminated union
- Interface duplication → utility types (`Pick`, `Omit`, `Partial`)
- Index as key in lists → stable unique ID
@@ -0,0 +1,93 @@
# Refactoring Patterns
## Extract Function
Pull cohesive logic into a named function.
```python
# Before
def process_order(order):
# validate
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Negative total")
# ... 50 more lines
# After
def validate_order(order):
if not order.items:
raise ValueError("Empty order")
if order.total < 0:
raise ValueError("Negative total")
def process_order(order):
validate_order(order)
# ... rest of processing
```
## Introduce Parameter Object
Group 4+ related parameters into a single object.
```typescript
// Before
function createUser(name: string, email: string, age: number, role: string) { ... }
// After
interface CreateUserInput {
name: string;
email: string;
age: number;
role: string;
}
function createUser(input: CreateUserInput) { ... }
```
## Replace Conditional with Polymorphism
```typescript
// Before
function getPrice(type: string, base: number): number {
if (type === 'premium') return base * 0.8;
if (type === 'bulk') return base * 0.7;
return base;
}
// After
const pricingStrategies: Record<string, (base: number) => number> = {
premium: (base) => base * 0.8,
bulk: (base) => base * 0.7,
standard: (base) => base,
};
function getPrice(type: string, base: number): number {
return (pricingStrategies[type] ?? pricingStrategies.standard)(base);
}
```
## Decompose Conditional
```python
# Before
if age > 18 and not banned and verified and subscription_active:
grant_access()
# After
def is_eligible(user):
return user.age > 18 and not user.banned and user.verified and user.subscription_active
if is_eligible(user):
grant_access()
```
## Extract Variable
```typescript
// Before
if (order.total > 100 && order.items.length > 5 && !order.hasDiscount) { ... }
// After
const isLargeOrder = order.total > 100 && order.items.length > 5;
const qualifiesForDiscount = isLargeOrder && !order.hasDiscount;
if (qualifiesForDiscount) { ... }
```
@@ -1,5 +1,6 @@
---
name: root-cause-tracing
user-invocable: false
description: >
Use when a bug manifests far from its origin, when stack traces show multiple layers of indirection, or when data corruption appears with no obvious source. Use for any scenario involving "it was already wrong by the time it got here," deep execution stack errors, constraint violations caused by upstream failures, or mysterious data state issues. Always prefer this over surface-level fixes when the error location differs from the bug location.
---
+123
View File
@@ -0,0 +1,123 @@
---
name: session-management
argument-hint: "[save/list/restore/index/load/status]"
description: >
Use when managing session state — including saving/restoring checkpoints, generating project structure indexes, loading project components into context, or checking project status. Trigger for keywords like "checkpoint", "save state", "restore", "index", "project structure", "load context", "status", "what's the state", or any request to manage the working session. Also activate when resuming work from a previous session or when needing to understand the current project layout.
---
# Session Management
## When to Use
- Saving or restoring session state (checkpoints)
- Generating project structure indexes
- Loading specific project components into context
- Checking current project status (git, tasks, PRs)
- Resuming work from a previous session
## When NOT to Use
- Git operations (commit, push, PR) — use `git-workflows`
- Branch management — use `using-git-worktrees`
- Launching parallel background work — use `dispatching-parallel-agents`
---
## Quick Reference
| Topic | Reference | Key content |
|-------|-----------|-------------|
| Checkpoints | `references/checkpoints.md` | Save/restore/list/delete session state |
| Project indexing | `references/indexing.md` | Generate PROJECT_INDEX.md, scan structure |
| Context loading | `references/loading.md` | Load components by category or path |
| Status checking | `references/status.md` | Git state, tasks, recent activity |
---
## Checkpoints
Save and restore conversation context using git-based state:
```bash
# Save current state
# → creates git stash + metadata in .claude/checkpoints/
/checkpoint save feature-auth
# List available checkpoints
/checkpoint list
# Restore a checkpoint
/checkpoint restore feature-auth
# Delete old checkpoint
/checkpoint delete old-checkpoint
```
Auto-checkpoint is suggested before major refactoring, context switches, and risky operations.
---
## Project Indexing
Generate a comprehensive project structure index:
```bash
# Generate PROJECT_INDEX.md
/index
# Shallow index (3 levels deep)
/index --depth=3
```
The index categorizes files by type: entry points, API routes, models, services, utilities, tests, and configuration.
---
## Context Loading
Load specific components into context for focused work:
| Category | What It Loads |
|----------|---------------|
| `api` | API routes and endpoints |
| `models` | Data models and types |
| `services` | Business logic services |
| `auth` | Authentication related |
| `db` | Database related |
| `tests` | Test files |
| `config` | Configuration files |
```bash
/load api # Load all API routes
/load src/services/user.ts # Load specific file
/load auth --related # Load auth + related files
/load --all --shallow # Quick overview of everything
```
---
## Status
Get current project status:
```bash
/status
```
Shows: git branch and status, in-progress/pending/completed tasks, recent commits, open PRs.
---
## Best Practices
1. **Checkpoint before context switches** — save state when switching tasks.
2. **Index periodically** — regenerate when project structure changes significantly.
3. **Load narrow, expand as needed** — start with specific components, add related files.
4. **Name checkpoints descriptively**`auth-progress` beats `checkpoint-1`.
---
## Related Skills
- `using-git-worktrees` — Isolated branch management for parallel work
- `dispatching-parallel-agents` — Launching parallel background tasks
@@ -0,0 +1,48 @@
# Checkpoints
## Save Checkpoint
```bash
/checkpoint save [name]
```
Creates a git stash with metadata in `.claude/checkpoints/[name].json`:
```json
{
"name": "feature-auth",
"created": "2026-04-19T14:30:00Z",
"git_stash": "stash@{0}",
"files_in_context": ["src/auth/login.ts", "src/auth/token.ts"],
"current_task": "Implementing JWT refresh",
"notes": "User-provided notes"
}
```
## List Checkpoints
```bash
/checkpoint list
```
## Restore Checkpoint
```bash
/checkpoint restore [name]
```
Applies git stash, loads metadata, summarizes restored context.
## Delete Checkpoint
```bash
/checkpoint delete [name]
```
## Auto-Checkpoint Triggers
Suggest checkpoints before:
- Major refactoring
- Context switches
- Risky operations
- Natural breakpoints in complex work
@@ -0,0 +1,45 @@
# Project Indexing
## Generate Index
Scan the project and create `PROJECT_INDEX.md`:
### Excluded Directories
`node_modules/`, `.git/`, `__pycache__/`, `dist/`, `build/`, `.next/`, `venv/`, `.venv/`, coverage, cache
### File Categories
- **Entry Points**: Main files, index files, app entry
- **API/Routes**: Endpoint definitions
- **Models/Types**: Data structures, schemas
- **Services**: Business logic
- **Utilities**: Helper functions
- **Tests**: Test files
- **Configuration**: Config files, env templates
### Output Format
```markdown
# Project Index: [Name]
Generated: [timestamp]
## Quick Navigation
| Category | Key Files |
|----------|-----------|
| Entry Points | [list] |
| API Routes | [list] |
## Directory Structure
[tree view]
## Key Files
### Entry Points
- `[path]` - [description]
## Dependencies
### External
- [package]: [purpose]
## Architecture Notes
[patterns observed]
```
@@ -0,0 +1,49 @@
# Context Loading
## Load Components
Load specific parts of the project into context for focused work.
### By Category
| Category | What It Loads |
|----------|---------------|
| `api` | API routes and endpoints |
| `models` | Data models and types |
| `services` | Business logic services |
| `utils` | Utility functions |
| `tests` | Test files |
| `config` | Configuration files |
| `auth` | Authentication related |
| `db` | Database related |
### By Path
```bash
/load src/services/user.ts # Specific file
/load src/auth/ # Directory
```
### Flags
| Flag | Description |
|------|-------------|
| `--all` | Load all key components |
| `--shallow` | Load only file summaries |
| `--deep` | Load full file contents |
| `--related` | Include related files |
### Output
```markdown
## Loaded Context
### Files Loaded (N)
- `path/to/file.ts` - [purpose]
### Key Components
- [Component]: [description]
### Ready For
- [suggested actions based on loaded context]
```
@@ -0,0 +1,34 @@
# Status Checking
## Project Status
Show current project state:
```bash
git status
git log --oneline -5
```
### Output Format
```markdown
## Project Status
### Git
- Branch: `feature/xyz`
- Status: Clean / X modified files
### Tasks
- In Progress: X
- Pending: Y
- Completed: Z
### Recent Commits
1. [commit message]
2. [commit message]
### Open PRs
- #123: [title]
```
Combines git state, TodoWrite tasks, and recent activity into a single snapshot.
@@ -1,5 +1,6 @@
---
name: testing-anti-patterns
user-invocable: false
description: >
Use when writing, reviewing, or debugging tests. Activate for keywords like "mock", "stub", "test helper", "flaky test", "test passes but bug ships", "false positive", "test coverage", or when tests seem unreliable. Also trigger when reviewing test code in PRs, when tests pass but production breaks, when someone proposes heavy mocking, or when test failures are intermittent. If any test smells wrong or feels like it is not actually verifying real behavior, this skill applies.
---
@@ -1,5 +1,6 @@
---
name: writing-concisely
user-invocable: false
description: >
Use this skill when optimizing token usage, reducing response verbosity, or working in high-volume development sessions. Trigger for any mention of token savings, cost optimization, concise output, compressed responses, or the --format=concise/ultra flags. Also applies during repetitive tasks, quick iterations, simple clear requests, or when the user activates token-efficient mode. This is a cross-cutting optimization that applies to all other skills.
---
+1
View File
@@ -1,5 +1,6 @@
---
name: writing-plans
argument-hint: "[task description]"
description: >
Use when a multi-step implementation task needs to be broken down before coding begins. Activate for keywords like "plan", "break down", "implementation steps", "task list", "how to implement", "write a plan", or when a feature spans multiple files or components. Also trigger when handing off work to another developer, when the user says "let's plan this out", or when a task is complex enough that jumping straight to code would be risky. If in doubt, plan first.
---
+59 -135
View File
@@ -5,10 +5,8 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
## Features
- **20 Specialized Agents** - From planning to deployment
- **27+ Slash Commands** - Workflow automation with flag support
- **36 Skills** - Framework, language, methodology, patterns, and optimization expertise (all with YAML frontmatter and bundled resources)
- **43 Skills** - Auto-triggered by context: framework, language, methodology, patterns, workflows, optimization (all with YAML frontmatter and bundled resources)
- **7 Behavioral Modes** - Task-specific response optimization
- **Command Flag System** - Combinable `--flag` syntax for customization
- **Token Optimization** - 30-70% cost savings with compressed output modes
- **MCP Integrations** - Context7, Sequential Thinking, Playwright, Memory, Filesystem
- **Context Management** - Project indexing, checkpoints, parallel tasks
@@ -17,7 +15,7 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
1. Copy the `.claude` folder to your project root
2. Customize `.claude/CLAUDE.md` for your project
3. Start using commands like `/feature`, `/review`, `/test`
3. Start working — skills auto-trigger based on what you ask ("implement X", "fix Y", "review Z")
## Directory Structure
@@ -26,10 +24,9 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
├── CLAUDE.md # Project context (customize this!)
├── settings.json # Hooks, permissions, and MCP config
├── agents/ # 20 specialized agents
├── commands/ # 27+ workflow commands
├── modes/ # 7 behavioral mode definitions
├── mcp/ # MCP server configurations
└── skills/ # 36 flat skills (router pattern)
└── skills/ # 43 flat skills (router pattern)
├── <skill-name>/ # Each skill is a top-level directory
│ ├── SKILL.md # Trigger description + core patterns
│ └── references/ # Deep content loaded on demand
@@ -66,55 +63,24 @@ A comprehensive toolkit for Claude Code to accelerate development workflows for
| `vulnerability-scanner` | Security scanning |
| `pipeline-architect` | Pipeline optimization |
## Commands
## Skills as Commands
All former slash commands have been migrated to skills that auto-trigger based on context:
### Development Workflow
```bash
/feature [description] # Full feature development
/fix [error] # Debug and fix bugs
/review [file] # Code review
/test [scope] # Generate tests
/tdd [feature] # Test-driven development
# Skills auto-trigger — just describe what you want:
"implement user authentication" # → feature-workflow + authentication
"this endpoint is slow" # → performance-optimization
"commit these changes" # → git-workflows
"refactor this function" # → refactoring
"add docs to this module" # → documentation
"scan for security issues" # → owasp
"switch to brainstorm mode" # → mode-switching
```
### Git & Deployment
```bash
/commit [message] # Smart commit
/ship [message] # Commit + PR
/pr [title] # Create pull request
/deploy [env] # Deploy to environment
```
## Skills (43 Total)
### Documentation & Planning
```bash
/plan [task] # Create implementation plan
/plan --detailed [task] # Detailed plan (2-5 min tasks)
/brainstorm [topic] # Interactive design session
/execute-plan [file] # Subagent-driven execution
/doc [target] # Generate documentation
/research [topic] # Research technology
```
### Security & Quality
```bash
/security-scan # Scan for vulnerabilities
/api-gen [resource] # Generate API code
/refactor [file] # Improve code structure
/optimize [file] # Performance optimization
```
### Context & Modes (New)
```bash
/mode [name] # Switch behavioral mode
/index # Generate project index
/load [component] # Load project context
/checkpoint [action] # Save/restore session state
/spawn [task] # Launch parallel background task
```
## Skills (36 Total)
Every skill follows a flat directory structure with a router pattern: short `SKILL.md` for triggering + `references/` for deep content loaded on demand.
Every skill follows a flat directory structure with a router pattern: short `SKILL.md` for triggering + `references/` for deep content loaded on demand. Skills auto-trigger based on context — no slash commands needed.
### Tech Stack Skills (7 merged routers)
@@ -149,6 +115,18 @@ Every skill follows a flat directory structure with a router pattern: short `SKI
| **background-jobs** | Celery, BullMQ, task queues, scheduled tasks, async workers |
| **writing-concisely** | Compressed output modes (30-70% token savings) |
### Workflow Skills (7 — migrated from commands)
| Skill | Description |
|-------|-------------|
| **feature-workflow** | End-to-end feature development: requirements → planning → implementation → testing → review |
| **git-workflows** | Conventional commits, shipping, PRs, changelogs |
| **documentation** | Docstrings, JSDoc, API docs, README generation |
| **refactoring** | Code smell detection, extract/rename/simplify patterns, safe refactoring workflow |
| **performance-optimization** | Profiling (cProfile, DevTools), N+1 queries, bundle size, memory leaks, benchmarking |
| **mode-switching** | Session behavioral modes (brainstorm, token-efficient, deep-research, implementation, review) |
| **session-management** | Checkpoints, project indexing, context loading, status checking |
### Methodology Skills (18)
| Category | Skills |
@@ -191,49 +169,21 @@ Switch modes to optimize responses for different task types:
| `review` | Critical analysis, finding issues | Code review |
| `orchestration` | Multi-task coordination | Parallel work |
```bash
/mode brainstorm # Switch for session
/feature --mode=implementation # Override per command
```
## Command Flags
All commands support combinable flags:
```bash
# Mode and depth
/plan --mode=brainstorm --depth=5 "feature design"
# Persona-based review
/review --persona=security --format=detailed src/auth/
# Token optimization
/fix --format=concise "error message"
# Save output
/research --save=docs/research.md "auth libraries"
"switch to brainstorm mode" # → mode-switching skill activates
"let's focus on implementation" # → implementation mode
```
### Available Flags
| Flag | Description |
|------|-------------|
| `--mode=[mode]` | Behavioral mode |
| `--depth=[1-5]` | Thoroughness (1=quick, 5=exhaustive) |
| `--format=[fmt]` | Output format (concise/detailed/json) |
| `--persona=[type]` | Expertise focus (security/performance/architecture) |
| `--save=[path]` | Save output to file |
| `--checkpoint` | Create state checkpoint |
## Token Optimization
Reduce costs by 30-70% with compressed output modes:
| Level | Activation | Savings |
|-------|------------|---------|
| Concise | `--format=concise` | 30-40% |
| Ultra | `--format=ultra` | 60-70% |
| Session | `/mode token-efficient` | 30-70% |
| Standard | (default) | 0% |
| Concise | Ask for concise output | 30-40% |
| Ultra | Ask for code-only responses | 60-70% |
| Session | "switch to token-efficient mode" | 30-70% |
## MCP Integrations
@@ -247,38 +197,27 @@ MCP servers extend Claude Kit with powerful capabilities. They are **automatical
| Memory | `@modelcontextprotocol/server-memory` | Persistent knowledge graph |
| Filesystem | `@modelcontextprotocol/server-filesystem` | Secure file operations |
### How MCP Servers Enhance Commands
### How MCP Servers Enhance Skills
| Command | MCP Servers Used | Enhancement |
|---------|------------------|-------------|
| `/feature` | Context7, Sequential, Filesystem | Accurate docs, structured planning, safe file ops |
| `/fix` | Sequential, Memory, Playwright | Step-by-step debugging, context recall, browser testing |
| `/test` | Playwright, Filesystem | E2E browser tests, test file management |
| `/plan` | Sequential, Memory | Structured breakdown, remembers decisions |
| `/research` | Context7, Sequential | Real-time docs, thorough analysis |
| `/brainstorm` | Sequential, Memory | Creative exploration, persistent ideas |
| `/index` | Filesystem | Project structure scanning |
### MCP + Mode Combinations
| Mode | Primary MCP | Best For |
|------|-------------|----------|
| `brainstorm` | Sequential + Memory | Design sessions with persistent ideas |
| `deep-research` | Sequential + Context7 | Thorough technical investigation |
| `implementation` | Filesystem + Context7 | Focused coding with accurate docs |
| `review` | Playwright + Memory | UI review with context |
| `orchestration` | All 5 | Complex multi-step parallel work |
| Skill | MCP Servers Used | Enhancement |
|-------|------------------|-------------|
| feature-workflow | Context7, Sequential, Filesystem | Accurate docs, structured planning, safe file ops |
| systematic-debugging | Sequential, Memory, Playwright | Step-by-step debugging, context recall, browser testing |
| testing, playwright | Playwright, Filesystem | E2E browser tests, test file management |
| writing-plans | Sequential, Memory | Structured breakdown, remembers decisions |
| brainstorming | Sequential, Memory, Context7 | Creative exploration, persistent ideas |
| session-management | Filesystem, Memory | Project scanning, context persistence |
### Example: Full Feature Development
```bash
/feature Add user profile with avatar upload
```
"Add user profile with avatar upload"
```
1. **Context7** → Fetches latest React/Next.js file upload docs
2. **Sequential** → Plans component structure step-by-step
3. **Memory** → Recalls your UI patterns from previous sessions
4. **Filesystem** → Creates files in correct locations
1. **feature-workflow** skill activates → orchestrates the workflow
2. **Context7** → Fetches latest React/Next.js file upload docs
3. **Sequential** → Plans component structure step-by-step
4. **Memory** → Recalls your UI patterns from previous sessions
5. **Playwright** → Tests the upload flow in browser
Setup: See `.claude/mcp/README.md`
@@ -308,23 +247,6 @@ The `.claude/CLAUDE.md` file is your project context. Customize it with:
- Coverage: 90%
```
### Adding Custom Commands
Create a new file in `.claude/commands/`:
```markdown
# /my-command
## Purpose
Description of your command.
---
Your prompt content here.
Use $ARGUMENTS for command arguments.
```
### Adding Custom Skills
Create a new skill in `.claude/skills/<name>/SKILL.md`:
@@ -372,36 +294,38 @@ my-skill/
## Workflow Chains
Skills chain automatically based on context. Here are common flows:
### Feature Development
```
/feature → planner → implement → code-reviewer → tester → git-manager
brainstorming → writing-plans → feature-workflow → requesting-code-review → git-workflows
```
### Bug Fix
```
/fix → debugger → scout → implement → tester → code-reviewer
systematic-debugging → root-cause-tracing → test-driven-development → verification-before-completion
```
### Ship Code
```
/ship → code-reviewertester → security-scan → git-manager
verification-before-completion → requesting-code-review → git-workflows → finishing-a-development-branch
```
### Superpowers Workflow (Detailed)
```
/brainstorm → /plan --detailed/execute-plan → /ship
brainstorming → writing-plans → executing-plansgit-workflows
```
Uses one-question-at-a-time design, 2-5 min tasks with exact code, subagent execution with code review gates.
### Parallel Research
### Parallel Work
```
/spawn "research auth" → /spawn "analyze security" → /spawn --collect
dispatching-parallel-agents → subagent-driven-development → verification-before-completion
```
Launch multiple background tasks, then aggregate results.
Launch multiple agents for independent tasks, then verify results.
### Cost-Optimized Session
```
/mode token-efficient → [work on tasks] → /mode default
"switch to token-efficient mode" → [work on tasks] → "switch to default mode"
```
Enable compressed outputs for high-volume sessions.