Add six new slash command categories with useful developer tools

- Add /documentation category with create-readme-section command
- Add /security category with security-audit and check-best-practices commands
- Add /architecture category with explain-architecture-pattern command
- Add /promptengineering category with convert-to-test-driven-prompt and batch-operations-prompt commands
- Update README.md to document all new slash commands
- Add Bash(mkdir:*) permission to settings.local.json
This commit is contained in:
George Liu 2025-07-09 00:39:37 +10:00
parent c223d2c27d
commit ef3d0564c6
8 changed files with 859 additions and 1 deletions

View File

@ -0,0 +1,151 @@
# Explain Architecture Pattern
Identify and explain architectural patterns, design patterns, and structural decisions found in the codebase. This helps understand the "why" behind code organization and design choices.
## Usage Examples
### Basic Usage
"Explain the architecture pattern used in this project"
"What design patterns are implemented in the auth module?"
"Analyze the folder structure and explain the architecture"
### Specific Pattern Analysis
"Is this using MVC, MVP, or MVVM?"
"Explain the microservices architecture here"
"What's the event-driven pattern in this code?"
"How is the repository pattern implemented?"
## Instructions for Claude
When explaining architecture patterns:
1. **Analyze Project Structure**: Examine folder organization, file naming, and module relationships
2. **Identify Patterns**: Recognize common architectural and design patterns
3. **Explain Rationale**: Describe why these patterns might have been chosen
4. **Visual Representation**: Use ASCII diagrams or markdown to illustrate relationships
5. **Practical Examples**: Show how the pattern is implemented with code examples
### Common Architecture Patterns
#### Application Architecture
- **MVC (Model-View-Controller)**
- **MVP (Model-View-Presenter)**
- **MVVM (Model-View-ViewModel)**
- **Clean Architecture**
- **Hexagonal Architecture**
- **Microservices**
- **Monolithic**
- **Serverless**
- **Event-Driven**
- **Domain-Driven Design (DDD)**
#### Design Patterns
- **Creational**: Factory, Singleton, Builder, Prototype
- **Structural**: Adapter, Decorator, Facade, Proxy
- **Behavioral**: Observer, Strategy, Command, Iterator
- **Concurrency**: Producer-Consumer, Thread Pool
- **Architectural**: Repository, Unit of Work, CQRS
#### Frontend Patterns
- **Component-Based Architecture**
- **Flux/Redux Pattern**
- **Module Federation**
- **Micro-Frontends**
- **State Management Patterns**
#### Backend Patterns
- **RESTful Architecture**
- **GraphQL Schema Design**
- **Service Layer Pattern**
- **Repository Pattern**
- **Dependency Injection**
### Analysis Areas
#### Code Organization
- Project structure rationale
- Module boundaries and responsibilities
- Separation of concerns
- Dependency management
- Configuration patterns
#### Data Flow
- Request/response cycle
- State management
- Event propagation
- Data transformation layers
- Caching strategies
#### Integration Points
- API design patterns
- Database access patterns
- Third-party integrations
- Message queue usage
- Service communication
### Output Format
Structure the explanation as:
```markdown
## Architecture Pattern Analysis
### Overview
Brief description of the overall architecture identified
### Primary Patterns Identified
#### 1. [Pattern Name]
**What it is**: Brief explanation
**Where it's used**: Specific locations in codebase
**Why it's used**: Benefits in this context
**Example**:
```language
// Code example showing the pattern
```
**Diagram**:
```
┌─────────────┐ ┌─────────────┐
│ Component │────▶│ Service │
└─────────────┘ └─────────────┘
```
### Architecture Characteristics
#### Strengths
- [Strength 1]: How it benefits the project
- [Strength 2]: Specific advantages
#### Trade-offs
- [Trade-off 1]: What was sacrificed
- [Trade-off 2]: Complexity added
### Implementation Details
#### File Structure
```
src/
├── controllers/ # MVC Controllers
├── models/ # Data models
├── views/ # View templates
└── services/ # Business logic
```
#### Key Relationships
- How components interact
- Dependency flow
- Communication patterns
### Recommendations
- Patterns that could enhance current architecture
- Potential improvements
- Consistency suggestions
```
Remember to:
- Use clear, accessible language
- Provide context for technical decisions
- Show concrete examples from the actual code
- Explain benefits and trade-offs objectively

View File

@ -0,0 +1,73 @@
# Create README Section
Generate a specific section for a README file based on the user's request. This command helps create well-structured, professional README sections that follow best practices.
## Usage Examples
### Basic Usage
"Create an installation section for my Python project"
"Generate a contributing guide section"
"Write an API reference section for my REST endpoints"
### Specific Sections
- **Installation**: Step-by-step setup instructions
- **Usage**: How to use the project with examples
- **API Reference**: Detailed API documentation
- **Contributing**: Guidelines for contributors
- **License**: License information
- **Configuration**: Configuration options and environment variables
- **Troubleshooting**: Common issues and solutions
- **Dependencies**: Required dependencies and versions
- **Architecture**: High-level architecture overview
- **Testing**: How to run tests
- **Deployment**: Deployment instructions
- **Changelog**: Version history and changes
## Instructions for Claude
When creating a README section:
1. **Analyze the Project Context**: Look at existing files (package.json, requirements.txt, etc.) to understand the project
2. **Follow Markdown Best Practices**: Use proper headings, code blocks, and formatting
3. **Include Practical Examples**: Add code snippets and command examples where relevant
4. **Be Comprehensive but Concise**: Cover all important points without being verbose
5. **Match Existing Style**: If a README already exists, match its tone and formatting style
### Section Templates
#### Installation Section
- Prerequisites
- Step-by-step installation
- Verification steps
- Common installation issues
#### Usage Section
- Basic usage examples
- Advanced usage scenarios
- Command-line options (if applicable)
- Code examples with expected output
#### API Reference Section
- Endpoint descriptions
- Request/response formats
- Authentication details
- Error codes and handling
- Rate limiting information
#### Contributing Section
- Development setup
- Code style guidelines
- Pull request process
- Issue reporting guidelines
- Code of conduct reference
### Output Format
Generate the section with:
- Appropriate heading level (usually ## or ###)
- Clear, structured content
- Code blocks with language specification
- Links to relevant resources
- Bullet points or numbered lists where appropriate
Remember to ask for clarification if the section type or project details are unclear.

View File

@ -0,0 +1,198 @@
# Batch Operations Prompt
Optimize prompts for multiple file operations, parallel processing, and efficient bulk changes across a codebase. This helps Claude Code work more efficiently with TodoWrite patterns.
## Usage Examples
### Basic Usage
"Convert to batch: Update all test files to use new API"
"Batch prompt for: Rename variable across multiple files"
"Optimize for parallel: Add logging to all service files"
### Complex Operations
"Batch refactor: Convert callbacks to async/await in all files"
"Parallel update: Add TypeScript types to all components"
"Bulk operation: Update import statements across the project"
## Instructions for Claude
When creating batch operation prompts:
1. **Identify Parallelizable Tasks**: Determine what can be done simultaneously
2. **Group Related Operations**: Organize tasks by type and dependency
3. **Create Efficient Sequences**: Order operations to minimize conflicts
4. **Use TodoWrite Format**: Structure for Claude's task management
5. **Include Validation Steps**: Add checks between batch operations
### Batch Prompt Structure
#### 1. Overview
- Scope of changes
- Files/patterns affected
- Expected outcome
#### 2. Prerequisite Checks
- Required tools/dependencies
- Initial validation commands
- Backup recommendations
#### 3. Parallel Operations
- Independent tasks that can run simultaneously
- File groups that don't conflict
- Read operations for gathering information
#### 4. Sequential Operations
- Tasks with dependencies
- Operations that modify same files
- Final validation steps
### Optimization Strategies
#### File Grouping
```markdown
## Batch Operation: [Operation Name]
### Phase 1: Analysis (Parallel)
- Search for all affected files using Glob/Grep
- Read current implementations
- Identify patterns and dependencies
### Phase 2: Implementation (Grouped)
Group A (Independent files):
- File1.js: [specific change]
- File2.js: [specific change]
Group B (Related components):
- Component1.tsx: [change]
- Component1.test.tsx: [related change]
### Phase 3: Validation (Sequential)
1. Run linter on modified files
2. Execute test suite
3. Build verification
```
#### TodoWrite Integration
```markdown
### Task List Structure
1. Gather information (can parallelize):
- Find all files matching pattern X
- Read configuration files
- Check current implementations
2. Batch updates (group by conflict potential):
- Update non-conflicting files (parallel)
- Update shared modules (sequential)
- Update test files (parallel)
3. Verification (sequential):
- Run type checking
- Execute tests
- Validate build
```
### Conversion Examples
#### Original Request:
"Update all API calls to use the new authentication header"
#### Batch-Optimized Version:
```markdown
## Batch Operation: Update API Authentication Headers
### Prerequisites
- Verify new auth header format
- Check all API call patterns in codebase
### Parallel Phase 1: Discovery
Execute simultaneously:
1. Grep for "fetch(" patterns
2. Grep for "axios." patterns
3. Grep for "api." patterns
4. Read auth configuration file
### Parallel Phase 2: Read Current Implementations
Read all files containing API calls (batch read):
- src/services/*.js
- src/api/*.js
- src/utils/api*.js
### Sequential Phase 3: Update by Pattern Type
Group 1 - Fetch calls:
- Update all fetch() calls with new header
- Pattern: Add "Authorization: Bearer ${token}"
Group 2 - Axios calls:
- Update axios config/interceptors
- Update individual axios calls
Group 3 - Custom API wrappers:
- Update wrapper functions
- Ensure backward compatibility
### Parallel Phase 4: Update Tests
Simultaneously update:
- Unit tests mocking API calls
- Integration tests with auth
- E2E test auth setup
### Sequential Phase 5: Validation
1. ESLint all modified files
2. Run test suite
3. Test one API call manually
4. Build project
```
### Output Format
Generate batch prompt as:
```markdown
## Batch Operation Prompt: [Operation Name]
### Efficiency Metrics
- Estimated sequential time: X operations
- Optimized parallel time: Y operations
- Parallelization factor: X/Y
### Execution Plan
#### Stage 1: Information Gathering (Parallel)
```bash
# Commands that can run simultaneously
[command 1] &
[command 2] &
[command 3] &
wait
```
#### Stage 2: Bulk Operations (Grouped)
**Parallel Group A:**
- Files: [list]
- Operation: [description]
- No conflicts with other groups
**Sequential Group B:**
- Files: [list]
- Operation: [description]
- Must complete before Group C
#### Stage 3: Verification (Sequential)
1. [Verification step 1]
2. [Verification step 2]
3. [Final validation]
### TodoWrite Task List
- [ ] Complete Stage 1 analysis (parallel)
- [ ] Execute Group A updates (parallel)
- [ ] Execute Group B updates (sequential)
- [ ] Run verification suite
- [ ] Document changes
```
Remember to:
- Maximize parallel operations
- Group by conflict potential
- Use TodoWrite's in_progress limitation wisely
- Include rollback strategies
- Provide specific file patterns

View File

@ -0,0 +1,147 @@
# Convert to Test-Driven Prompt
Transform user requests into Test-Driven Development (TDD) style prompts that explicitly define expected outcomes, test cases, and success criteria before implementation.
## Usage Examples
### Basic Usage
"Convert this to TDD: Add a user authentication feature"
"Make this test-driven: Create a shopping cart component"
"TDD version: Implement data validation for the form"
### Complex Scenarios
"Convert to TDD: Refactor the payment processing module"
"Test-driven approach for: API rate limiting feature"
"TDD prompt for: Database migration script"
## Instructions for Claude
When converting to TDD prompts:
1. **Extract Requirements**: Identify core functionality from the original request
2. **Define Test Cases**: Create specific, measurable test scenarios
3. **Specify Expected Outcomes**: Clear success and failure criteria
4. **Structure for Implementation**: Organize prompt for red-green-refactor cycle
5. **Include Edge Cases**: Don't forget boundary conditions and error scenarios
### TDD Prompt Structure
#### 1. Objective Statement
Clear, concise description of what needs to be built
#### 2. Test Specifications
```
GIVEN: [Initial state/context]
WHEN: [Action performed]
THEN: [Expected outcome]
```
#### 3. Success Criteria
- Specific, measurable outcomes
- Performance requirements
- Error handling expectations
- Edge case behaviors
#### 4. Test Cases Format
```markdown
Test Case 1: [Descriptive name]
- Input: [Specific input data]
- Expected Output: [Exact expected result]
- Validation: [How to verify success]
Test Case 2: [Edge case name]
- Input: [Boundary/error condition]
- Expected Output: [Error handling result]
- Validation: [Error verification method]
```
### Conversion Examples
#### Original Request:
"Add user login functionality"
#### TDD Conversion:
```markdown
## Objective
Implement secure user login with email/password authentication
## Test Specifications
### Test 1: Successful Login
GIVEN: Valid user credentials exist in database
WHEN: User submits correct email and password
THEN: User receives auth token and is redirected to dashboard
### Test 2: Invalid Password
GIVEN: Valid email but incorrect password
WHEN: User submits login form
THEN: Return error "Invalid credentials" without revealing which field is wrong
### Test 3: Non-existent User
GIVEN: Email not in database
WHEN: User attempts login
THEN: Return same "Invalid credentials" error (prevent user enumeration)
### Test 4: Rate Limiting
GIVEN: User has failed 5 login attempts
WHEN: User attempts 6th login within 15 minutes
THEN: Block attempt and show "Too many attempts" error
## Success Criteria
- All tests pass
- Password is hashed using bcrypt
- Auth tokens expire after 24 hours
- Login attempts are logged
- Response time < 200ms
```
### Output Format
Generate TDD prompt as:
```markdown
## TDD Prompt: [Feature Name]
### Objective
[Clear description of the feature to implement]
### Test Suite
#### Happy Path Tests
[List of successful scenario tests]
#### Error Handling Tests
[List of failure scenario tests]
#### Edge Case Tests
[List of boundary condition tests]
### Implementation Requirements
- [ ] All tests must pass
- [ ] Code coverage > 80%
- [ ] Performance criteria met
- [ ] Security requirements satisfied
### Test-First Development Steps
1. Write failing test for [first requirement]
2. Implement minimal code to pass
3. Refactor while keeping tests green
4. Repeat for next requirement
### Example Test Implementation
```language
// Example test code structure
describe('FeatureName', () => {
it('should [expected behavior]', () => {
// Test implementation
});
});
```
```
Remember to:
- Focus on behavior, not implementation details
- Make tests specific and measurable
- Include both positive and negative test cases
- Consider performance and security in tests
- Structure for iterative TDD workflow

View File

@ -0,0 +1,136 @@
# Check Best Practices
Analyze code against language-specific best practices, coding standards, and community conventions to improve code quality and maintainability.
## Usage Examples
### Basic Usage
"Check if this code follows Python best practices"
"Review JavaScript code for ES6+ best practices"
"Analyze React components for best practices"
### Specific Checks
"Check if this follows PEP 8 conventions"
"Review TypeScript code for proper type usage"
"Verify REST API design best practices"
"Check Git commit message conventions"
## Instructions for Claude
When checking best practices:
1. **Identify Language/Framework**: Detect the languages and frameworks being used
2. **Apply Relevant Standards**: Use appropriate style guides and conventions
3. **Context Awareness**: Consider project-specific patterns and existing conventions
4. **Actionable Feedback**: Provide specific examples of improvements
5. **Prioritize Issues**: Focus on impactful improvements over nitpicks
### Language-Specific Guidelines
#### Python
- PEP 8 style guide compliance
- PEP 484 type hints usage
- Pythonic idioms and patterns
- Proper exception handling
- Module and package structure
#### JavaScript/TypeScript
- Modern ES6+ features usage
- Async/await over callbacks
- Proper error handling
- Module organization
- TypeScript strict mode compliance
#### React/Vue/Angular
- Component structure and organization
- State management patterns
- Performance optimizations
- Accessibility considerations
- Testing patterns
#### API Design
- RESTful conventions
- Consistent naming patterns
- Proper HTTP status codes
- API versioning strategy
- Documentation standards
### Code Quality Aspects
#### Naming Conventions
- Variable and function names
- Class and module names
- Consistency across codebase
- Meaningful and descriptive names
#### Code Organization
- File and folder structure
- Separation of concerns
- DRY (Don't Repeat Yourself)
- Single Responsibility Principle
- Modular design
#### Error Handling
- Comprehensive error catching
- Meaningful error messages
- Proper logging practices
- Graceful degradation
#### Performance
- Efficient algorithms
- Proper caching strategies
- Lazy loading where appropriate
- Database query optimization
- Memory management
#### Testing
- Test coverage adequacy
- Test naming conventions
- Test organization
- Mock usage patterns
- Integration vs unit tests
### Output Format
Structure the analysis as:
```markdown
## Best Practices Review
### Summary
- Language/Framework: [Detected stack]
- Overall Score: X/10
- Key Areas for Improvement: [List]
### Excellent Practices Found
- [Practice 1]: Brief explanation
- [Practice 2]: Brief explanation
### Areas for Improvement
#### High Priority
1. **[Issue Name]**
- Current: `code example`
- Recommended: `improved code`
- Reason: Explanation of why this matters
#### Medium Priority
[Similar format]
#### Low Priority
[Similar format]
### Quick Wins
- [Easy improvement 1]
- [Easy improvement 2]
### Long-term Recommendations
- [Strategic improvement 1]
- [Strategic improvement 2]
```
Focus on:
- Practical, implementable suggestions
- Learning opportunities
- Maintaining consistency with existing code
- Balancing perfection with pragmatism

View File

@ -0,0 +1,102 @@
# Security Audit
Perform a comprehensive security audit of the codebase to identify potential vulnerabilities, insecure patterns, and security best practice violations.
## Usage Examples
### Basic Usage
"Run a security audit on this project"
"Check for security vulnerabilities in the authentication module"
"Scan the API endpoints for security issues"
### Specific Audits
"Check for SQL injection vulnerabilities"
"Audit the file upload functionality for security risks"
"Review authentication and authorization implementation"
"Check for hardcoded secrets and API keys"
## Instructions for Claude
When performing a security audit:
1. **Systematic Scanning**: Examine the codebase systematically for common vulnerability patterns
2. **Use OWASP Guidelines**: Reference OWASP Top 10 and other security standards
3. **Check Multiple Layers**: Review frontend, backend, database, and infrastructure code
4. **Prioritize Findings**: Categorize issues by severity (Critical, High, Medium, Low)
5. **Provide Remediation**: Include specific fixes for each identified issue
### Security Checklist
#### Authentication & Authorization
- Password storage and hashing methods
- Session management security
- JWT implementation and validation
- Access control and permission checks
- Multi-factor authentication support
#### Input Validation & Sanitization
- SQL injection prevention
- XSS (Cross-Site Scripting) protection
- Command injection safeguards
- Path traversal prevention
- File upload validation
#### Data Protection
- Encryption in transit (HTTPS/TLS)
- Encryption at rest
- Sensitive data exposure
- API key and secret management
- PII handling compliance
#### Common Vulnerabilities
- CSRF protection
- Clickjacking prevention
- Security headers configuration
- Dependency vulnerabilities
- Insecure direct object references
#### API Security
- Rate limiting implementation
- API authentication methods
- Input validation on endpoints
- Error message information leakage
- CORS configuration
### Output Format
Provide a structured security report with:
```markdown
## Security Audit Report
### Summary
- Total issues found: X
- Critical: X, High: X, Medium: X, Low: X
### Critical Issues
#### 1. [Issue Name]
- **Location**: file.js:line
- **Description**: Detailed explanation
- **Impact**: Potential consequences
- **Remediation**: Specific fix with code example
### High Priority Issues
[Similar format]
### Medium Priority Issues
[Similar format]
### Low Priority Issues
[Similar format]
### Recommendations
- General security improvements
- Best practices to implement
- Tools and libraries to consider
```
Remember to:
- Be specific about file locations and line numbers
- Provide code examples for fixes
- Explain the security impact clearly
- Avoid false positives by understanding the context

View File

@ -57,7 +57,8 @@
"WebFetch(domain:docs.anthropic.com)",
"WebFetch(domain:github.com)",
"WebFetch(domain:openrouter.ai)",
"WebFetch(domain:www.comet.com)"
"WebFetch(domain:www.comet.com)",
"Bash(mkdir:*)"
],
"deny": []
}

View File

@ -47,6 +47,56 @@ The Claude Code hook is for `STOP` which uses Terminal-Notifier to show macOS de
- Achieves 15-25% token reduction through systematic optimization
- Usage: `/cleanup-context`
### `/documentation` Commands
- **`/create-readme-section`** - Generate specific sections for README files with professional formatting
- Creates well-structured sections like Installation, Usage, API Reference, Contributing, etc.
- Follows markdown best practices with proper headings, code blocks, and formatting
- Analyzes project context to provide relevant content
- Matches existing README style and tone
- Usage: `/create-readme-section "Create an installation section for my Python project"`
### `/security` Commands
- **`/security-audit`** - Perform comprehensive security audit of the codebase
- Identifies potential vulnerabilities using OWASP guidelines
- Checks authentication, input validation, data protection, and API security
- Categorizes issues by severity (Critical, High, Medium, Low)
- Provides specific remediation steps with code examples
- Usage: `/security-audit`
- **`/check-best-practices`** - Analyze code against language-specific best practices
- Detects languages and frameworks to apply relevant standards
- Checks naming conventions, code organization, error handling, and performance
- Provides actionable feedback with before/after code examples
- Prioritizes impactful improvements over nitpicks
- Usage: `/check-best-practices`
### `/architecture` Commands
- **`/explain-architecture-pattern`** - Identify and explain architectural patterns in the codebase
- Analyzes project structure and identifies design patterns
- Explains rationale behind architectural decisions
- Provides visual representations with diagrams
- Shows concrete implementation examples
- Usage: `/explain-architecture-pattern`
### `/promptengineering` Commands
- **`/convert-to-test-driven-prompt`** - Transform requests into Test-Driven Development style prompts
- Defines explicit test cases with Given/When/Then format
- Includes success criteria and edge cases
- Structures prompts for red-green-refactor cycle
- Creates measurable, specific test scenarios
- Usage: `/convert-to-test-driven-prompt "Add user authentication feature"`
- **`/batch-operations-prompt`** - Optimize prompts for multiple file operations and parallel processing
- Identifies parallelizable tasks to maximize efficiency
- Groups operations by conflict potential
- Integrates with TodoWrite for task management
- Includes validation steps between batch operations
- Usage: `/batch-operations-prompt "Update all API calls to use new auth header"`
## Claude Code settings
> Configure Claude Code with global and project-level settings, and environment variables.