command_generator.py
"""
Slash Command Generator
Generates Claude Code slash command .md files with proper YAML frontmatter.
"""
from typing import Dict, Any, List
import json
import os
class SlashCommandGenerator:
"""Generate custom slash commands for Claude Code."""
def __init__(self):
"""Initialize generator with presets."""
self.presets = self._load_presets()
def _load_presets(self) -> Dict[str, Any]:
"""Load preset commands from presets.json."""
presets_path = os.path.join(os.path.dirname(__file__), 'presets.json')
with open(presets_path, 'r') as f:
return json.load(f)
def generate_from_preset(self, preset_name: str) -> Dict[str, Any]:
"""
Generate command from preset.
Args:
preset_name: Name of preset (e.g., 'research-business')
Returns:
Dict with command_content and metadata
"""
if preset_name not in self.presets:
raise ValueError(f"Preset '{preset_name}' not found. Available: {list(self.presets.keys())}")
preset = self.presets[preset_name]
# Generate full command content
command_content = self._create_command_file(
description=preset['description'],
argument_hint=preset.get('argument-hint'),
allowed_tools=preset.get('allowed-tools'),
model=preset.get('model'),
command_body=preset['command_body']
)
return {
'command_name': preset['name'],
'command_content': command_content,
'supporting_folders': preset.get('supporting_folders', [])
}
def generate_custom(self, answers: Dict[str, Any]) -> Dict[str, Any]:
"""
Generate custom command from user answers.
Args:
answers: User responses to 5-7 questions
Returns:
Dict with command_content and metadata
"""
# Determine command name from purpose (kebab-case)
command_name = self._purpose_to_command_name(answers['purpose'])
# Auto-determine if $ARGUMENTS needed
needs_args = self._needs_arguments(answers['purpose'])
# Create argument hint if needed
argument_hint = self._create_argument_hint(answers) if needs_args else None
# Generate command body
command_body = self._create_command_body_from_answers(answers)
# Generate full command content
command_content = self._create_command_file(
description=answers['purpose'],
argument_hint=argument_hint,
allowed_tools=answers.get('tools'),
model=answers.get('model'),
command_body=command_body
)
# Determine supporting folders
supporting_folders = self._determine_folders(answers)
return {
'command_name': command_name,
'command_content': command_content,
'supporting_folders': supporting_folders
}
def _create_command_file(
self,
description: str,
argument_hint: str = None,
allowed_tools: str = None,
model: str = None,
command_body: str = None
) -> str:
"""
Create complete command .md file content.
Args:
description: Command description
argument_hint: Argument syntax hint
allowed_tools: Tools the command can use
model: Specific model to use
command_body: Main command instructions
Returns:
Complete .md file content with YAML frontmatter
"""
# Build YAML frontmatter
frontmatter_lines = ['---']
frontmatter_lines.append(f'description: {description}')
if argument_hint:
frontmatter_lines.append(f'argument-hint: {argument_hint}')
if allowed_tools:
frontmatter_lines.append(f'allowed-tools: {allowed_tools}')
if model:
frontmatter_lines.append(f'model: {model}')
frontmatter_lines.append('disable-model-invocation: false')
frontmatter_lines.append('---')
# Combine frontmatter + body
frontmatter = '\n'.join(frontmatter_lines)
full_content = f"{frontmatter}\n\n{command_body}"
return full_content
def _purpose_to_command_name(self, purpose: str) -> str:
"""Convert purpose to kebab-case command name."""
# Simple conversion: lowercase, replace spaces with hyphens
name = purpose.lower()
name = name.replace(' ', '-')
# Remove special characters
name = ''.join(c for c in name if c.isalnum() or c == '-')
# Remove multiple hyphens
while '--' in name:
name = name.replace('--', '-')
return name.strip('-')
def _needs_arguments(self, purpose: str) -> bool:
"""
Determine if command needs arguments based on purpose.
Returns True if purpose suggests needing input parameters.
"""
# Keywords that suggest arguments needed
arg_indicators = [
'for', 'analyze', 'research', 'generate', 'create',
'build', 'translate', 'audit', 'review', 'process'
]
purpose_lower = purpose.lower()
return any(indicator in purpose_lower for indicator in arg_indicators)
def _create_argument_hint(self, answers: Dict[str, Any]) -> str:
"""
Create argument hint based on command purpose.
Always uses $ARGUMENTS format (never $1, $2, $3).
"""
# Generic hints based on common patterns
purpose_lower = answers['purpose'].lower()
if 'research' in purpose_lower:
return '[topic] [scope]'
elif 'translate' in purpose_lower:
return '[text] [language]'
elif 'audit' in purpose_lower or 'check' in purpose_lower:
return '[path] [standard]'
elif 'generate' in purpose_lower or 'create' in purpose_lower:
return '[name] [type]'
elif 'analyze' in purpose_lower:
return '[target] [analysis-type]'
else:
return '[input] [options]'
def _create_command_body_from_answers(self, answers: Dict[str, Any]) -> str:
"""Generate command body from user answers."""
# Start with purpose
body_lines = [f"Execute task: \"$ARGUMENTS\"\n"]
# Add steps based on output type
output_type = answers.get('output_type', 'analysis')
if output_type == 'analysis':
body_lines.append("1. **Analyze Input**:\n - Gather relevant data\n - Identify key patterns\n - Extract insights\n\n")
body_lines.append("2. **Generate Analysis**:\n - Comprehensive findings\n - Data-driven insights\n - Recommendations\n\n")
elif output_type == 'files':
body_lines.append("1. **Plan Structure**:\n - Determine file organization\n - Design architecture\n\n")
body_lines.append("2. **Generate Files**:\n - Create necessary files\n - Add proper formatting\n - Include documentation\n\n")
elif output_type == 'action':
body_lines.append("1. **Execute Action**:\n - Perform requested task\n - Monitor progress\n - Handle errors\n\n")
else: # report
body_lines.append("1. **Gather Information**:\n - Collect relevant data\n - Analyze thoroughly\n\n")
body_lines.append("2. **Generate Report**:\n - Structured findings\n - Recommendations\n - Next steps\n\n")
# Add agent launching if needed
if answers.get('launches_agents'):
agents = answers.get('agent_names', [])
if agents:
body_lines.append(f"3. **Launch Agents**:\n")
for agent in agents:
body_lines.append(f" - Launch {agent} for specialized task\n")
body_lines.append("\n")
# Add success criteria
body_lines.append("**Success Criteria**:\n")
body_lines.append(f"- {answers['purpose']} completed successfully\n")
body_lines.append("- Quality standards met\n")
body_lines.append("- Output validated and ready to use\n")
return ''.join(body_lines)
def _determine_folders(self, answers: Dict[str, Any]) -> List[str]:
"""Determine which supporting folders are needed."""
folders = []
# Add folders based on command characteristics
if 'standard' in answers.get('purpose', '').lower() or 'compliance' in answers.get('purpose', '').lower():
folders.append('standards')
if 'example' in answers.get('purpose', '').lower() or answers.get('output_type') == 'files':
folders.append('examples')
if 'script' in answers.get('purpose', '').lower() or 'bash' in answers.get('tools', '').lower():
folders.append('scripts')
return folders
def _validate_command_name(self, name: str) -> bool:
"""
Validate command name follows kebab-case convention.
Rules:
- Must be kebab-case (lowercase with hyphens)
- Length: 2-4 words maximum
- Characters: [a-z0-9-] only
- Must start and end with letter/number
Args:
name: Command name to validate
Returns:
True if valid, False otherwise
"""
import re
pattern = r'^[a-z0-9]+(-[a-z0-9]+){1,3}$'
return bool(re.match(pattern, name))
def _convert_to_command_name(self, purpose: str) -> str:
"""
Convert user purpose to valid command name following official patterns.
Examples:
- "Review code changes" → "code-review"
- "Generate API docs" → "api-document"
- "Analyze dependencies" → "deps-analyze"
Args:
purpose: User's command purpose
Returns:
Valid kebab-case command name
"""
import re
# Extract key words
words = purpose.lower().split()
# Filter stop words
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'for', 'with', 'to', 'from', 'in', 'on'}
words = [w for w in words if w not in stop_words]
# Take first 2-3 meaningful words
key_words = words[:3]
# Clean and join
clean_words = [re.sub(r'[^a-z0-9]', '', w) for w in key_words]
clean_words = [w for w in clean_words if w] # Remove empty strings
command_name = '-'.join(clean_words[:3]) # Max 3 words
return command_name
def _determine_structure(self, answers: Dict[str, Any]) -> str:
"""
Determine which official structure pattern to use.
Returns: 'simple', 'multi-phase', or 'agent-style'
"""
purpose = answers['purpose'].lower()
# Multi-phase: discovery, analysis, comprehensive
multi_phase_keywords = ['discover', 'analyze', 'comprehensive', 'document', 'map', 'audit', 'full', 'complete']
if any(word in purpose for word in multi_phase_keywords):
return 'multi-phase'
# Agent-style: expert, specialized, coordinator
agent_keywords = ['expert', 'specialist', 'coordinator', 'orchestrate', 'manage', 'coordinate']
if any(word in purpose for word in agent_keywords):
return 'agent-style'
# Default: simple
return 'simple'
def _generate_bash_permissions(self, command_type: str, structure: str) -> str:
"""
Generate specific bash permissions (no wildcards).
Based on official patterns from Anthropic examples.
Args:
command_type: Type of command (git, discovery, analysis, etc.)
structure: Structure type (simple, multi-phase, agent-style)
Returns:
Comma-separated list of specific bash commands
"""
patterns = {
'git': 'Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git branch:*)',
'discovery': 'Bash(find:*), Bash(tree:*), Bash(ls:*), Bash(grep:*), Bash(wc:*), Bash(du:*)',
'analysis': 'Bash(grep:*), Bash(wc:*), Bash(head:*), Bash(tail:*), Bash(cat:*)',
'update': 'Bash(git diff:*), Bash(find:*), Bash(grep:*)',
'comprehensive': 'Bash(find:*), Bash(tree:*), Bash(ls:*), Bash(grep:*), Bash(wc:*), Bash(du:*), Bash(head:*), Bash(tail:*), Bash(cat:*)'
}
# Multi-phase usually needs comprehensive permissions
if structure == 'multi-phase':
return patterns['comprehensive']
return patterns.get(command_type, patterns['analysis'])
expected_output.json
{
"command_name": "analyze-customer-feedback",
"command_file": "analyze-customer-feedback.md",
"output_location": "generated-commands/analyze-customer-feedback/",
"command_content": "---\ndescription: Analyze customer feedback and generate actionable product insights\nargument-hint: [feedback-source] [time-period]\nallowed-tools: Read, Grep, Task\ndisable-model-invocation: false\n---\n\nExecute task: \"$ARGUMENTS\"\n\n1. **Analyze Input**:\n - Gather relevant data\n - Identify key patterns\n - Extract insights\n\n2. **Generate Analysis**:\n - Comprehensive findings\n - Data-driven insights\n - Recommendations\n\n3. **Launch Agents**:\n - Launch analysis-agent for specialized task\n\n**Success Criteria**:\n- Analyze customer feedback and generate actionable product insights completed successfully\n- Quality standards met\n- Output validated and ready to use\n",
"supporting_folders": [],
"validation": {
"yaml_valid": true,
"arguments_valid": true,
"tools_valid": true,
"organization_valid": true
},
"installation_target": ".claude/commands/analyze-customer-feedback.md"
}
HOW_TO_USE.md
# How to Use Slash Command Factory
Generate custom Claude Code slash commands in minutes!
---
## Quick Start
### Use a Preset (30 seconds)
```
@slash-command-factory
Use the /research-business preset
```
→ Instant business research command ready to install
### Create Custom Command (2-3 minutes)
```
@slash-command-factory
Create a command for analyzing customer feedback and generating product insights
```
→ Answers 5-7 questions → Complete custom command generated
---
## 10 Available Presets
1. **/research-business** - Market research, competitor SWOT, strategic insights
2. **/research-content** - Multi-platform trends, SEO strategy, content gaps
3. **/medical-translate** - Medical terms → 8th grade (DE/EN)
4. **/compliance-audit** - HIPAA/GDPR/DSGVO validation
5. **/api-build** - Complete API client with tests
6. **/test-auto** - Auto-generate test suites
7. **/docs-generate** - Documentation automation
8. **/knowledge-mine** - Extract insights from documents
9. **/workflow-analyze** - Process optimization
10. **/batch-agents** - Multi-agent coordination
---
## Official Command Structures
This skill uses **three official patterns** from Anthropic documentation:
### Simple Pattern (code-review)
- **Best for**: Straightforward tasks with clear input/output
- **Structure**: Context → Task
- **Example Presets**: code-review, deps-audit, metrics-report
### Multi-Phase Pattern (codebase-analyze)
- **Best for**: Complex discovery and documentation
- **Structure**: Discovery → Analysis → Task
- **Example Preset**: codebase-analyze
### Agent-Style Pattern (ultrathink)
- **Best for**: Specialized expert roles and coordination
- **Structure**: Role → Process → Guidelines
- **Example Presets**: ultrathink, openapi-sync, batch-agents
**The skill auto-detects** which pattern fits your command purpose!
---
## Naming Convention
All commands follow **kebab-case** (lowercase with hyphens):
**Valid**:
- ✅ `code-review`
- ✅ `api-document`
- ✅ `update-docs`
**Invalid**:
- ❌ `code_review` (underscores)
- ❌ `CodeReview` (CamelCase)
- ❌ `review` (too short)
The skill **automatically converts** your purpose to valid command names!
---
## Installation
**After generation**, commands are in: `generated-commands/[command-name]/`
**To install**:
**Project-level** (this project only):
```bash
cp generated-commands/[command-name]/[command-name].md .claude/commands/
```
**User-level** (all projects):
```bash
cp generated-commands/[command-name]/[command-name].md ~/.claude/commands/
```
**Then**: Restart Claude Code
---
## Usage Examples
### Business Research Command
```
@slash-command-factory
Use /research-business preset
[Command generated: generated-commands/research-business/]
# Install
cp generated-commands/research-business/research-business.md .claude/commands/
# Use
/research-business "Tesla" "EV market"
```
### Custom Healthcare Command
```
@slash-command-factory
Create command for German PTV 10 application generation
Q1: Purpose? Generate PTV 10 therapy applications
Q2: Tools? Read, Write, Task
Q3: Agents? Yes - health-sdk-builder agents
Q4: Output? Files
Q5: Model? Sonnet
[Command generated: generated-commands/generate-ptv10/]
# Install
cp generated-commands/generate-ptv10/generate-ptv10.md .claude/commands/
# Use
/generate-ptv10 "Patient info" "60 sessions"
```
---
## Output Structure
**Simple command**:
```
generated-commands/my-command/
├── my-command.md # The command file
└── README.md # Installation guide
```
**Complex command**:
```
generated-commands/my-command/
├── my-command.md # Command (ROOT)
├── README.md # Install guide (ROOT)
├── TEST_EXAMPLES.md # Testing (ROOT)
├── standards/ # Standards folder
├── examples/ # Examples folder
└── scripts/ # Helper scripts
```
**Organization**: All .md in root, folders separate
---
## Testing Generated Commands
```bash
# After installation
/my-command test-arguments
# Check it works as expected
```
See TEST_EXAMPLES.md in each command folder for specific test cases.
---
## Tips
- Use presets for speed (30 seconds)
- Custom for unique needs (2-3 minutes)
- Always validate before installing
- Test with simple cases first
- Customize .md files if needed
---
**Generate powerful slash commands in minutes!** ⚡
presets.json
{
"code-review": {
"name": "code-review",
"structure": "simple",
"description": "Comprehensive code review with git analysis focusing on quality, security, and performance",
"argument-hint": "[component-path]",
"allowed-tools": "Read, Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git branch:*)",
"model": null,
"command_body": "## Context\n- Current git status: !`git status`\n- Recent changes: !`git diff HEAD~1`\n- Recent commits: !`git log --oneline -5`\n- Current branch: !`git branch --show-current`\n\n## Your task\n\nPerform comprehensive code review focusing on:\n\n1. **Code Quality**: Check readability, maintainability, best practices\n2. **Security**: Look for vulnerabilities or security issues \n3. **Performance**: Identify potential bottlenecks\n4. **Testing**: Assess test coverage and quality\n5. **Documentation**: Check if code is properly documented\n\nProvide specific, actionable feedback with line-by-line comments where appropriate.\n\n**Success Criteria**:\n- Detailed quality assessment\n- Security vulnerabilities identified\n- Performance improvements suggested\n- Actionable recommendations",
"supporting_folders": []
},
"codebase-analyze": {
"name": "codebase-analyze",
"structure": "multi-phase",
"description": "Generate comprehensive codebase analysis and documentation with full discovery",
"argument-hint": null,
"allowed-tools": "Bash(find:*), Bash(ls:*), Bash(tree:*), Bash(grep:*), Bash(wc:*), Bash(du:*), Bash(head:*), Bash(tail:*), Bash(cat:*)",
"model": null,
"command_body": "# Comprehensive Codebase Analysis\n\n## Phase 1: Project Discovery\n\n### Directory Structure\n!`find . -type d -not -path \"./node_modules/*\" -not -path \"./.git/*\" | sort`\n\n### Complete File Tree\n!`tree -a -I 'node_modules|.git|dist|build' -L 4`\n\n### File Count and Size Analysis\n- Total files: !`find . -type f -not -path \"./node_modules/*\" | wc -l`\n- Code files: !`find . -name \"*.js\" -o -name \"*.ts\" -o -name \"*.py\" | grep -v node_modules | wc -l`\n- Project size: !`du -sh . --exclude=node_modules --exclude=.git`\n\n## Phase 2: Configuration Analysis\n\n@package.json\n@tsconfig.json \n@README.md\n\n## Phase 3: Your Task\n\nBased on all discovered information, create comprehensive analysis:\n\n1. **Project Overview**: Type, tech stack, architecture\n2. **Directory Structure**: Explain each major directory\n3. **File Breakdown**: Core files, configs, data layer, UI, tests\n4. **Architecture Deep Dive**: Data flow, design patterns, dependencies\n5. **Technology Stack**: Frameworks, libraries, tools\n6. **Key Insights**: Quality assessment, improvements, recommendations\n\nAt the end, write all output to codebase_analysis.md",
"supporting_folders": []
},
"update-docs": {
"name": "update-docs",
"structure": "simple",
"description": "Automatically update CLAUDE.md and documentation files based on recent code changes",
"argument-hint": null,
"allowed-tools": "Read, Write, Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(find:*), Bash(grep:*)",
"model": null,
"command_body": "# Update Documentation\n\n## Current State\n@CLAUDE.md\n@README.md\n\n## Git Analysis\n\n### Recent Changes\n!`git log --oneline -10`\n!`git diff HEAD~5 --name-only`\n\n### Modified Files\n!`git diff --name-status HEAD~10 | grep \"^M\"`\n\n### New Files\n!`git diff --name-status HEAD~10 | grep \"^A\"`\n\n## Your Task\n\nBased on current documentation and git analysis:\n\n1. **Preserve Important Content**: Keep core descriptions, setup, architecture\n2. **Integrate Recent Changes**: New features, API changes, config updates\n3. **Update Key Sections**: Overview, architecture, setup, API docs, workflow\n4. **Add Recent Updates Section**: Summary of major changes\n\n**Success Criteria**:\n- Documentation reflects current code state\n- Recent changes documented clearly\n- No outdated information\n- Maintains structure and readability",
"supporting_folders": []
},
"openapi-sync": {
"name": "openapi-sync",
"structure": "agent-style",
"description": "Synchronize OpenAPI specification with actual API implementation ensuring complete documentation",
"argument-hint": null,
"allowed-tools": "Read, Write, Edit, Bash(find:*), Bash(grep:*) ",
"model": null,
"command_body": "You are an OpenAPI specification expert ensuring synchronization between REST API implementation and documentation.\n\n**Core Responsibilities:**\n\n1. **API Discovery**\n - Scan API directory structure for controllers, routes, endpoints\n - Analyze request/response DTOs and schemas\n - Identify middleware requirements\n\n2. **Specification Maintenance**\n - Ensure every API endpoint has corresponding OpenAPI path\n - Document request bodies, response schemas, error responses\n - Include proper schema definitions for all DTOs\n\n3. **Schema Synchronization**\n - Map struct tags to OpenAPI schema properties\n - Convert types to appropriate OpenAPI formats\n - Handle nullable fields, optional parameters, defaults\n\n4. **Quality Assurance**\n - Verify all HTTP status codes documented\n - Ensure error schemas match actual error handling\n - Validate path parameters consistency\n\n**Working Process:**\n\n1. Analyze current openapi.yml state\n2. Scan API implementation to build endpoint inventory\n3. Compare implementation with specification\n4. Update OpenAPI spec incrementally\n5. Validate structure and schema references\n6. Bump version number if changes made\n\n**Important Considerations:**\n- Pay attention to DTO layer separation\n- Check Gin route definitions and binding tags\n- Document both success and error scenarios\n- Generate realistic examples",
"supporting_folders": []
},
"ultrathink": {
"name": "ultrathink",
"structure": "agent-style",
"description": "Orchestrate multiple specialist sub-agents for complex problem-solving with deep analysis",
"argument-hint": "[task-description]",
"allowed-tools": "Task, Read, Bash(find:*), Bash(grep:*)",
"model": null,
"command_body": "## Context\n- Task description: $ARGUMENTS\n- Relevant files will be referenced ad-hoc using @ syntax\n\n## Your Role\n\nYou are the Coordinator Agent orchestrating four specialist sub-agents:\n1. Architect Agent – designs high-level approach\n2. Research Agent – gathers external knowledge and precedent\n3. Coder Agent – writes or edits code\n4. Tester Agent – proposes tests and validation strategy\n\n## Process\n\n1. Think step-by-step, laying out assumptions and unknowns\n2. For each sub-agent, clearly delegate task, capture output, summarize insights\n3. Perform \"ultrathink\" reflection combining all insights\n4. If gaps remain, iterate (spawn sub-agents again)\n\n## Output Format\n\n1. **Reasoning Transcript** (optional) – major decision points\n2. **Final Answer** – actionable steps, code edits, commands (Markdown)\n3. **Next Actions** – bullet list of follow-up items\n\n**Success Criteria**:\n- Complex problem decomposed effectively\n- All sub-agents coordinated successfully\n- Comprehensive solution delivered\n- Clear next steps provided",
"supporting_folders": []
},
"deps-audit": {
"name": "deps-audit",
"structure": "simple",
"description": "Audit project dependencies for security vulnerabilities, outdated packages, and license issues",
"argument-hint": null,
"allowed-tools": "Read, Bash(find:*), Bash(grep:*), Bash(wc:*), Bash(cat:*)",
"model": null,
"command_body": "## Context\n\n### Package Files\n@package.json\n@package-lock.json\n@requirements.txt\n@Gemfile\n@Cargo.toml\n@go.mod\n\n### Dependency Count\n!`find . -name \"package.json\" -o -name \"requirements.txt\" -o -name \"Gemfile\" | wc -l`\n\n## Your Task\n\nPerform comprehensive dependency audit:\n\n1. **Security Vulnerabilities**\n - Known CVEs in current versions\n - Severity classification (Critical/High/Medium/Low)\n - Affected packages and remediation\n\n2. **Outdated Packages**\n - Packages behind latest stable version\n - Breaking changes in updates\n - Update recommendations with priority\n\n3. **License Compliance**\n - License types for each dependency\n - Incompatible licenses\n - Commercial use restrictions\n\n4. **Dependency Health**\n - Unmaintained packages\n - Packages with security history\n - Alternative recommendations\n\n**Success Criteria**:\n- Complete vulnerability assessment\n- Prioritized update recommendations\n- License compliance verified\n- Health report with actionable items",
"supporting_folders": []
},
"metrics-report": {
"name": "metrics-report",
"structure": "simple",
"description": "Generate comprehensive codebase metrics report with quality, complexity, and coverage analysis",
"argument-hint": null,
"allowed-tools": "Bash(find:*), Bash(grep:*), Bash(wc:*), Bash(cat:*), Bash(head:*)",
"model": null,
"command_body": "## Context\n\n### Code Statistics\n!`find . -name \"*.js\" -o -name \"*.ts\" -o -name \"*.py\" | grep -v node_modules | wc -l`\n!`find . -name \"*.js\" -o -name \"*.ts\" -o -name \"*.py\" | grep -v node_modules | xargs wc -l | tail -1`\n\n### Test Files\n!`find . -name \"*test*\" -o -name \"*spec*\" | grep -v node_modules | wc -l`\n\n### Component Count \n!`find . -path \"*/components/*\" | wc -l`\n\n## Your Task\n\nGenerate comprehensive metrics report:\n\n1. **Code Volume Metrics**\n - Total lines of code\n - Lines per file average\n - Files by type breakdown\n - Largest files identification\n\n2. **Complexity Metrics**\n - Function count and average size\n - Deep nesting indicators\n - Long functions (>50 lines)\n - High complexity areas\n\n3. **Quality Metrics**\n - Test coverage percentage\n - Test-to-code ratio\n - Documentation coverage\n - Code duplication indicators\n\n4. **Component Metrics**\n - Component count by type\n - Component size distribution\n - Reusability score\n\n**Success Criteria**:\n- Complete metrics calculated\n- Quality trends identified\n- Improvement areas highlighted\n- Visual representation (tables/charts)",
"supporting_folders": []
},
"research-business": {
"name": "research-business",
"structure": "simple",
"description": "Comprehensive business and market research with competitor analysis and strategic insights",
"argument-hint": "[company/market] [industry]",
"allowed-tools": "Read, Bash(find:*), Bash(grep:*)",
"model": null,
"command_body": "Conduct comprehensive business research for \"$ARGUMENTS\":\n\n1. **Market Analysis**:\n - Market size, growth trends, and dynamics\n - Key players and market share distribution\n - Emerging trends and future outlook\n - Regulatory environment and compliance requirements\n\n2. **Competitive Analysis**:\n - Direct and indirect competitors\n - SWOT analysis for top 3-5 competitors\n - Competitive positioning and differentiation\n - Pricing strategies and business models\n\n3. **Opportunity Identification**:\n - Market gaps and underserved segments\n - Innovation opportunities\n - Strategic recommendations\n - Risk assessment\n\n4. **Deliverable**:\n - Executive summary (2-3 pages)\n - Detailed market analysis\n - Competitor profiles\n - Strategic recommendations with action items\n\n**Success Criteria**:\n- Comprehensive market overview with data-driven insights\n- Actionable competitive intelligence\n- Clear strategic recommendations with prioritization",
"supporting_folders": []
},
"research-content": {
"name": "research-content",
"structure": "simple",
"description": "Multi-platform content trend analysis for data-driven content strategy and SEO optimization",
"argument-hint": "[topic] [platforms]",
"allowed-tools": "Read, Bash(find:*)",
"model": null,
"command_body": "Analyze content trends for \"$ARGUMENTS\" across multiple platforms:\n\n1. **Platform Analysis** (10+ platforms):\n - Google Trends: Search volume, rising queries, regional interest\n - Reddit: Subreddit activity, top posts, discussion themes\n - YouTube: Video performance, trending content, engagement\n - Medium: Article trends, claps, reading time\n - LinkedIn: Professional content, engagement patterns\n - X (Twitter): Hashtag performance, viral topics\n - Substack: Newsletter trends, subscriber growth\n - Blogs: Top-ranking posts, backlink profiles\n\n2. **User Intent Analysis**:\n - Informational intent (learning, research)\n - Commercial intent (comparison, evaluation)\n - Transactional intent (purchase, action)\n\n3. **Content Gap Identification**:\n - Underserved topics with high demand\n - Question gaps (what people ask but isn't answered well)\n - Format opportunities (video vs text vs infographic)\n\n4. **SEO-Optimized Outline**:\n - H1/H2/H3 structure based on search intent\n - Keyword integration recommendations\n - Content length and format suggestions\n - Platform-specific publishing strategy\n\n**Success Criteria**:\n- Comprehensive trend analysis across 5+ platforms\n- Data-driven content strategy with SEO optimization\n- Actionable outline ready for content creation",
"supporting_folders": []
},
"medical-translate": {
"name": "medical-translate",
"structure": "simple",
"description": "Translate medical terminology to 8th-10th grade reading level with accuracy validation (German/English)",
"argument-hint": "[medical-term] [de|en]",
"allowed-tools": "Read",
"model": "claude-3-5-sonnet-20241022",
"command_body": "Translate medical term \"$ARGUMENTS\" to patient-friendly language:\n\n1. **Language Detection**:\n - Identify language from second argument (de=German, en=English)\n - Use appropriate reading level validator\n\n2. **Simplification**:\n - Translate complex medical term to simple alternative\n - Target reading level: 8th-10th grade\n - Use everyday words (avoid Latin/Greek medical terms)\n - Short sentences (12-18 words max)\n\n3. **Validation**:\n - English: Flesch-Kincaid Grade Level (target: 8.0-10.0)\n - German: Wiener Sachtextformel (target: Klasse 8-10)\n - Medical accuracy: Preserve clinical correctness\n\n4. **Output Format**:\n - Original term\n - Simple translation\n - 8th grade explanation (2-3 sentences)\n - Concrete example or analogy\n - Reading level score\n\n**Success Criteria**:\n- Reading level at 8th-10th grade (validated)\n- Medical accuracy preserved\n- Patient-friendly and empowering",
"supporting_folders": []
},
"compliance-audit": {
"name": "compliance-audit",
"structure": "simple",
"description": "Audit code for HIPAA/GDPR/DSGVO compliance with detailed findings and recommendations",
"argument-hint": "[code-path] [hipaa|gdpr|dsgvo|all]",
"allowed-tools": "Read, Grep, Task",
"model": null,
"command_body": "Audit \"$ARGUMENTS\" for regulatory compliance:\n\n1. **Determine Standard** (from arguments):\n - HIPAA (US healthcare)\n - GDPR (EU data protection)\n - DSGVO (German data protection)\n - All (comprehensive check)\n\n2. **HIPAA Compliance Check** (if applicable):\n - PHI handling: Encryption at rest/transit\n - Access controls: Authentication, authorization\n - Audit logging: All PHI access tracked\n - Breach notification: Procedures in place\n\n3. **GDPR/DSGVO Compliance Check** (if applicable):\n - Data minimization: Only necessary data collected\n - Consent management: Explicit consent for processing\n - Data subject rights: Access, erasure, portability\n - Retention policies: Automated deletion workflows\n\n4. **Generate Report**:\n - ✅ Compliant areas\n - ❌ Non-compliant areas (with severity)\n - ⚠️ Recommendations for improvement\n - Priority actions (P0/P1/P2)\n\n**Success Criteria**:\n- Comprehensive compliance assessment completed\n- Clear findings with specific code references\n- Actionable recommendations with priority levels",
"supporting_folders": ["standards"]
},
"api-build": {
"name": "api-build",
"structure": "simple",
"description": "Generate complete API client integration with error handling, authentication, and comprehensive tests",
"argument-hint": "[api-name] [endpoints]",
"allowed-tools": "Read, Write, Edit, Bash(find:*), Task",
"model": null,
"command_body": "Generate API client for \"$ARGUMENTS\":\n\n1. **API Client Class**:\n - Base client with configuration\n - Authentication handling (API key, OAuth, JWT)\n - Request/response formatting\n - Error handling with retries\n - Rate limiting support\n\n2. **Endpoint Methods**:\n - Generate method for each endpoint\n - Type hints for all parameters\n - Comprehensive docstrings\n - Input validation\n - Response parsing\n\n3. **Error Handling**:\n - Network errors (timeout, connection)\n - HTTP errors (4xx, 5xx)\n - Rate limit handling\n - Retry logic with exponential backoff\n - Logging and debugging\n\n4. **Testing**:\n - Unit tests (mock API responses)\n - Integration tests (real API calls for dev)\n - Test fixtures and sample data\n - Coverage >80%\n\n5. **Documentation**:\n - README with usage examples\n - API reference for all methods\n - Authentication setup guide\n - Error handling documentation\n\n**Success Criteria**:\n- Complete, working API client generated\n- Error handling comprehensive\n- Tests pass with >80% coverage\n- Documentation clear and complete",
"supporting_folders": ["examples", "scripts"]
},
"test-auto": {
"name": "test-auto",
"structure": "simple",
"description": "Auto-generate comprehensive test suite with unit, integration, and e2e tests plus coverage analysis",
"argument-hint": "[file-path] [unit|integration|e2e|all]",
"allowed-tools": "Read, Write, Bash(find:*), Bash(grep:*)",
"model": null,
"command_body": "Generate test suite for \"$ARGUMENTS\":\n\n1. **Analyze Code**:\n - Read file/module to test\n - Identify functions, classes, methods\n - Determine dependencies and imports\n - Map test coverage needs\n\n2. **Generate Test Cases**:\n - **Happy path**: Normal, expected usage\n - **Edge cases**: Boundary conditions, special inputs\n - **Error cases**: Invalid inputs, exceptions\n - **Integration**: Component interactions\n\n3. **Test Implementation**:\n - Use appropriate framework (pytest, jest, etc.)\n - Add test fixtures and mocks\n - Generate sample test data\n - Add setup/teardown logic\n\n4. **Coverage Analysis**:\n - Run coverage report\n - Identify untested code\n - Recommend additional tests\n - Target: >80% coverage\n\n5. **Documentation**:\n - Test file organization\n - How to run tests\n - How to interpret results\n\n**Success Criteria**:\n- Comprehensive test suite generated\n- All test types covered (unit/integration/e2e)\n- >80% code coverage achieved\n- Tests pass on first run",
"supporting_folders": ["examples"]
},
"docs-generate": {
"name": "docs-generate",
"structure": "simple",
"description": "Auto-generate comprehensive documentation including API docs, README, and architecture diagrams",
"argument-hint": "[code-path] [api|readme|architecture|all]",
"allowed-tools": "Read, Write, Grep",
"model": null,
"command_body": "Generate documentation for \"$ARGUMENTS\":\n\n1. **Code Analysis**:\n - Extract functions, classes, modules\n - Analyze dependencies and architecture\n - Identify public APIs and interfaces\n - Map data flows and relationships\n\n2. **API Documentation** (if requested):\n - Function/method signatures with parameters\n - Return types and descriptions\n - Usage examples for each API\n - Error handling documentation\n\n3. **README** (if requested):\n - Project overview and purpose\n - Installation instructions\n - Quick start guide\n - Usage examples\n - API reference\n - Contributing guidelines\n\n4. **Architecture** (if requested):\n - System architecture overview\n - Component diagrams (Mermaid)\n - Data flow diagrams\n - Technology stack\n - Design decisions and rationale\n\n5. **Code Examples**:\n - Practical usage scenarios\n - Common patterns\n - Best practices\n - Troubleshooting\n\n**Success Criteria**:\n- Complete, accurate documentation generated\n- Examples work as documented\n- Diagrams clear and informative\n- Documentation follows best practices",
"supporting_folders": ["examples"]
},
"knowledge-mine": {
"name": "knowledge-mine",
"structure": "simple",
"description": "Extract and structure insights from documents into FAQs, summaries, and knowledge base articles",
"argument-hint": "[doc-path] [faq|summary|kb|all]",
"allowed-tools": "Read, Grep",
"model": null,
"command_body": "Extract knowledge from \"$ARGUMENTS\":\n\n1. **Document Analysis**:\n - Read and parse documents\n - Identify key topics and themes\n - Extract main concepts and definitions\n - Map relationships and dependencies\n\n2. **FAQ Generation** (if requested):\n - Common questions extracted from content\n - Clear, concise answers\n - Organized by category\n - Prioritized by importance\n\n3. **Summary Creation** (if requested):\n - Executive summary (2-3 paragraphs)\n - Key points and takeaways\n - Action items and recommendations\n - Structured for quick scanning\n\n4. **Knowledge Base Articles** (if requested):\n - Topic-based articles\n - Clear explanations with examples\n - Cross-references to related topics\n - Searchable and well-organized\n\n5. **Structured Output**:\n - Markdown format for easy use\n - Proper headings and sections\n - Internal links for navigation\n - Ready for knowledge base import\n\n**Success Criteria**:\n- Accurate extraction of key information\n- Well-organized and structured output\n- Actionable insights and knowledge\n- Ready to use in documentation or knowledge base",
"supporting_folders": []
},
"workflow-analyze": {
"name": "workflow-analyze",
"structure": "simple",
"description": "Analyze business workflows and provide optimization recommendations with automation opportunities",
"argument-hint": "[workflow-description]",
"allowed-tools": "Read, Task",
"model": null,
"command_body": "Analyze workflow: \"$ARGUMENTS\"\n\n1. **Current State Mapping**:\n - Document current workflow steps\n - Identify stakeholders and handoffs\n - Map decision points and dependencies\n - Calculate cycle time and throughput\n\n2. **Bottleneck Identification**:\n - Manual steps that could be automated\n - Redundant processes\n - Waiting times and delays\n - Communication inefficiencies\n\n3. **Optimization Opportunities**:\n - Automation potential (tools, scripts, AI)\n - Process simplification\n - Parallel vs sequential execution\n - Elimination of non-value-add steps\n\n4. **Impact Analysis**:\n - Time savings (hours/week)\n - Cost reduction ($$$/month)\n - Quality improvements\n - Risk reduction\n\n5. **Implementation Roadmap**:\n - Quick wins (implement immediately)\n - Short-term improvements (1-3 months)\n - Long-term transformation (3-12 months)\n - Resource requirements\n\n**Success Criteria**:\n- Clear current state documentation\n- Quantified bottlenecks and inefficiencies\n- Actionable optimization recommendations\n- Realistic implementation roadmap with ROI estimates",
"supporting_folders": []
},
"batch-agents": {
"name": "batch-agents",
"structure": "agent-style",
"description": "Launch and coordinate multiple specialized agents for complex multi-faceted tasks",
"argument-hint": "[agent-names] [task-description]",
"allowed-tools": "Task",
"model": null,
"command_body": "Launch coordinated agent workflow for \"$ARGUMENTS\":\n\n1. **Parse Agent List**:\n - Extract agent names from arguments\n - Validate agents exist\n - Determine execution order (parallel vs sequential)\n\n2. **Execution Strategy**:\n - **Strategic agents** (blue): Run 4-5 in parallel\n - **Implementation agents** (green): Run 2-3 coordinated\n - **Quality agents** (red): Run ONE at a time (never parallel)\n - **Coordination agents** (purple): Orchestrate others\n\n3. **Launch Agents** (max 5 total):\n - Launch with specific task instructions\n - Monitor progress\n - Capture outputs\n - Handle errors gracefully\n\n4. **Coordinate Results**:\n - Integrate outputs from all agents\n - Resolve conflicts if any\n - Validate completeness\n - Generate comprehensive summary\n\n5. **Final Output**:\n - Summary of what each agent accomplished\n - Integrated results\n - Quality validation\n - Next steps if needed\n\n**Success Criteria**:\n- All agents launched successfully\n- Appropriate execution strategy (parallel/sequential)\n- Results integrated coherently\n- Task completed with quality validation",
"supporting_folders": []
}
}
sample_input.json
{
"request_type": "custom",
"purpose": "Analyze customer feedback and generate actionable product insights",
"tools": "Read, Grep, Task",
"launches_agents": true,
"agent_names": ["analysis-agent"],
"output_type": "report",
"model": "default",
"features": []
}
SKILL.md
---
name: slash-command-factory
description: Generate custom Claude Code slash commands through intelligent 5-7 question flow. Creates powerful commands for business research, content analysis, healthcare compliance, API integration, documentation automation, and workflow optimization. Outputs organized commands to generated-commands/ with validation and installation guidance.
---
# Slash Command Factory
A comprehensive system for generating production-ready Claude Code slash commands through a simple question-based workflow.
---
## What This Skill Does
This skill helps you create custom slash commands for Claude Code by:
- Asking 5-7 straightforward questions about your command needs
- Generating complete command .md files with proper YAML frontmatter
- Providing 10 powerful preset commands for common use cases
- Validating command format and syntax
- Creating well-organized folder structures
- Offering installation guidance
**Output**: Complete slash commands ready to use in Claude Code
---
## Official Command Structure Patterns
This skill generates commands following **three official patterns** from Anthropic documentation:
### Pattern A: Simple (Context → Task)
**Best for**: Straightforward tasks with clear input/output
**Example**: Code review, file updates, simple analysis
**Official Reference**: code-review.md
**Structure**:
```markdown
---
allowed-tools: Bash(git diff:*), Bash(git log:*)
description: Purpose description
---
## Context
- Current state: !`bash command`
- Additional data: !`another command`
## Your task
[Clear instructions with numbered steps]
[Success criteria]
```
**When to use**:
- Simple, focused tasks
- Quick analysis or reviews
- Straightforward workflows
- 1-3 bash commands for context
---
### Pattern B: Multi-Phase (Discovery → Analysis → Task)
**Best for**: Complex discovery and documentation tasks
**Example**: Codebase analysis, comprehensive audits, system mapping
**Official Reference**: codebase-analysis.md
**Structure**:
```markdown
---
allowed-tools: Bash(find:*), Bash(tree:*), Bash(ls:*), Bash(grep:*), Bash(wc:*), Bash(du:*)
description: Comprehensive purpose
---
# Command Title
## Phase 1: Project Discovery
### Directory Structure
!`find . -type d | sort`
### File Count Analysis
!`find . -type f | wc -l`
## Phase 2: Detailed Analysis
[More discovery commands]
[File references with @]
## Phase 3: Your Task
Based on all discovered information, create:
1. **Deliverable 1**
- Subsection
- Details
2. **Deliverable 2**
- Subsection
- Details
At the end, write output to [filename].md
```
**When to use**:
- Comprehensive analysis needed
- Multiple discovery phases
- Large amounts of context gathering
- 10+ bash commands for data collection
- Generate detailed documentation files
---
### Pattern C: Agent-Style (Role → Process → Guidelines)
**Best for**: Specialized expert roles and coordination
**Example**: Domain experts, orchestrators, specialized advisors
**Official Reference**: openapi-expert.md
**Structure**:
```markdown
---
name: command-name
description: |
Multi-line description for complex purpose
explaining specialized role
color: yellow
---
You are a [specialized role] focusing on [domain expertise].
**Core Responsibilities:**
1. **Responsibility Area 1**
- Specific tasks
- Expected outputs
2. **Responsibility Area 2**
- Specific tasks
- Expected outputs
**Working Process:**
1. [Step 1 in workflow]
2. [Step 2 in workflow]
3. [Step 3 in workflow]
**Important Considerations:**
- [Guideline 1]
- [Guideline 2]
- [Constraint or best practice]
When you encounter [scenario], [action to take].
```
**When to use**:
- Need specialized domain expertise
- Orchestrating complex workflows
- Coordinating multiple sub-processes
- Acting as expert advisor
- Require specific procedural guidelines
---
## Comprehensive Naming Convention
### Command File Naming Rules
All slash command files MUST follow kebab-case convention:
**Format**: `[verb]-[noun].md`, `[noun]-[verb].md`, or `[domain]-[action].md`
**Rules**:
1. **Case**: Lowercase only with hyphens as separators
2. **Length**: 2-4 words maximum
3. **Characters**: Only `[a-z0-9-]` allowed (letters, numbers, hyphens)
4. **Start/End**: Must begin and end with letter or number (not hyphen)
5. **No**: Spaces, underscores, camelCase, TitleCase, or special characters
---
### Conversion Algorithm
**User Input** → **Command Name**
```
Input: "Analyze customer feedback and generate insights"
↓
1. Extract action: "analyze"
2. Extract target: "feedback"
3. Combine: "analyze-feedback"
4. Validate: Matches [a-z0-9-]+ pattern ✓
5. Output: analyze-feedback.md
```
**More Examples**:
- "Review pull requests" → `pr-review.md` or `review-pr.md`
- "Generate API documentation" → `api-document.md` or `document-api.md`
- "Update README files" → `update-readme.md` or `readme-update.md`
- "Audit security compliance" → `security-audit.md` or `compliance-audit.md`
- "Research market trends" → `research-market.md` or `market-research.md`
- "Analyze code quality" → `code-analyze.md` or `analyze-code.md`
---
### Official Examples (From Anthropic Docs)
**Correct**:
- ✅ `code-review.md` (verb-noun)
- ✅ `codebase-analysis.md` (noun-noun compound)
- ✅ `update-claude-md.md` (verb-noun-qualifier)
- ✅ `openapi-expert.md` (domain-role)
**Incorrect**:
- ❌ `code_review.md` (snake_case - wrong)
- ❌ `CodeReview.md` (PascalCase - wrong)
- ❌ `codeReview.md` (camelCase - wrong)
- ❌ `review.md` (too vague - needs target)
- ❌ `analyze-customer-feedback-data.md` (too long - >4 words)
---
## Bash Permission Patterns
### Critical Rule: No Wildcards
**❌ NEVER ALLOWED**:
```yaml
allowed-tools: Bash
```
This wildcard permission is **prohibited** per official Anthropic patterns.
**✅ ALWAYS REQUIRED**:
```yaml
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git log:*)
```
Must specify **exact commands** with wildcards only for subcommands.
---
### Official Permission Patterns
Based on Anthropic's documented examples:
**Git Operations** (code-review, update-docs):
```yaml
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git log:*), Bash(git branch:*), Bash(git add:*), Bash(git commit:*)
```
**File Discovery** (codebase-analysis):
```yaml
allowed-tools: Bash(find:*), Bash(tree:*), Bash(ls:*), Bash(du:*)
```
**Content Analysis** (comprehensive discovery):
```yaml
allowed-tools: Bash(grep:*), Bash(wc:*), Bash(head:*), Bash(tail:*), Bash(cat:*)
```
**Data Processing** (custom analysis):
```yaml
allowed-tools: Bash(awk:*), Bash(sed:*), Bash(sort:*), Bash(uniq:*)
```
**Combined Patterns** (multi-phase commands):
```yaml
allowed-tools: Bash(find:*), Bash(tree:*), Bash(ls:*), Bash(grep:*), Bash(wc:*), Bash(du:*), Bash(head:*), Bash(tail:*), Bash(cat:*), Bash(touch:*)
```
---
### Permission Selection Guide
| Command Type | Bash Permissions | Example Commands |
|--------------|------------------|------------------|
| **Git Commands** | `git status, git diff, git log, git branch` | code-review, commit-assist |
| **Discovery** | `find, tree, ls, du` | codebase-analyze, structure-map |
| **Analysis** | `grep, wc, head, tail, cat` | search-code, count-lines |
| **Update** | `git diff, find, grep` | update-docs, sync-config |
| **Data Processing** | `awk, sed, sort, uniq` | parse-data, format-output |
| **Comprehensive** | All of the above | full-audit, system-analyze |
---
## Two Paths to Generate Commands
### Path 1: Quick-Start Presets (30 seconds)
Choose from 10 powerful preset commands:
**Business & Research**:
1. **/research-business** - Comprehensive market research and competitive analysis
2. **/research-content** - Multi-platform content trend analysis and SEO strategy
**Healthcare & Compliance**:
3. **/medical-translate** - Translate medical terminology to 8th-10th grade (German/English)
4. **/compliance-audit** - HIPAA/GDPR/DSGVO compliance validation
**Development & Integration**:
5. **/api-build** - Generate complete API integration code with tests
6. **/test-auto** - Auto-generate comprehensive test suites
**Documentation & Knowledge**:
7. **/docs-generate** - Automated documentation creation
8. **/knowledge-mine** - Extract and structure insights from documents
**Workflow & Productivity**:
9. **/workflow-analyze** - Analyze and optimize business processes
10. **/batch-agents** - Launch and coordinate multiple agents for complex tasks
### Path 2: Custom Command (5-7 Questions)
Create a completely custom command for your specific needs.
---
## Question Flow (Custom Path)
### Question 1: Command Purpose
"What should this slash command do?
Be specific about its purpose and when you'll use it.
Examples:
- 'Analyze customer feedback and generate actionable insights'
- 'Generate HIPAA-compliant API documentation'
- 'Research market trends and create content strategy'
- 'Extract key insights from research papers'
Your command's purpose: ___"
---
### Question 2: Arguments (Auto-Determined)
The skill automatically determines if your command needs arguments based on the purpose.
**If arguments are needed**, they will use `$ARGUMENTS` format:
- User types: `/your-command argument1 argument2`
- Command receives: `$ARGUMENTS` = "argument1 argument2"
**Examples**:
- `/research-business "Tesla" "EV market"` → $ARGUMENTS = "Tesla EV market"
- `/medical-translate "Myokardinfarkt" "de"` → $ARGUMENTS = "Myokardinfarkt de"
**No user input needed** - skill decides intelligently.
---
### Question 3: Which Tools?
"Which Claude Code tools should this command use?
Available tools:
- **Read** - Read files
- **Write** - Create files
- **Edit** - Modify files
- **Bash** - Execute shell commands (MUST specify exact commands)
- **Grep** - Search code
- **Glob** - Find files by pattern
- **Task** - Launch agents
**CRITICAL**: For Bash, you MUST specify exact commands, not wildcards.
**Bash Examples**:
- ✅ Bash(git status:*), Bash(git diff:*), Bash(git log:*)
- ✅ Bash(find:*), Bash(tree:*), Bash(ls:*)
- ✅ Bash(grep:*), Bash(wc:*), Bash(head:*)
- ❌ Bash (wildcard not allowed per official patterns)
**Tool Combination Examples**:
- Git command: Read, Bash(git status:*), Bash(git diff:*)
- Code generator: Read, Write, Edit
- Discovery command: Bash(find:*), Bash(tree:*), Bash(grep:*)
- Analysis command: Read, Grep, Task (launch agents)
Your tools (comma-separated): ___"
---
### Question 4: Agent Integration
"Does this command need to launch agents for specialized tasks?
Examples of when to use agents:
- Complex analysis (launch rr-architect, rr-security)
- Implementation tasks (launch rr-frontend, rr-backend)
- Quality checks (launch rr-qa, rr-test-runner)
Options:
1. **No agents** - Command handles everything itself
2. **Launch agents** - Delegate to specialized agents
Your choice (1 or 2): ___"
If "2", ask: "Which agents should it launch? ___"
---
### Question 5: Output Type
"What type of output should this command produce?
1. **Analysis** - Research report, insights, recommendations
2. **Files** - Generated code, documentation, configs
3. **Action** - Execute tasks, run workflows, deploy
4. **Report** - Structured report with findings and next steps
Your choice (1, 2, 3, or 4): ___"
---
### Question 6: Model Preference (Optional)
"Which Claude model should this command use?
1. **Default** - Inherit from main conversation (recommended)
2. **Sonnet** - Best for complex tasks
3. **Haiku** - Fastest, cheapest (for simple commands)
4. **Opus** - Maximum capability (for critical tasks)
Your choice (1, 2, 3, or 4) or press Enter for default: ___"
---
### Question 7: Additional Features (Optional)
"Any special features?
Optional features:
- **Bash execution** - Run shell commands and include output (!`command`)
- **File references** - Include file contents (@file.txt)
- **Context gathering** - Read project files for context
Features you need (comma-separated) or press Enter to skip: ___"
---
## Generation Process
After collecting answers:
1. **Generate YAML Frontmatter**:
```yaml
---
description: [From command purpose]
argument-hint: [If $ARGUMENTS needed]
allowed-tools: [From tool selection]
model: [If specified]
---
```
2. **Generate Command Body**:
```markdown
[Purpose-specific instructions]
[If uses agents]:
1. **Launch [agent-name]** with [specific task]
2. Coordinate workflow
3. Validate results
[If uses bash]:
- Context: !`bash command`
[If uses file refs]:
- Review: @file.txt
Success Criteria: [Based on output type]
```
3. **Create Folder Structure**:
```
generated-commands/[command-name]/
├── [command-name].md # Command file (ROOT)
├── README.md # Installation guide (ROOT)
├── TEST_EXAMPLES.md # Testing examples (ROOT)
└── [folders if needed] # standards/, examples/, scripts/
```
4. **Validate Format**:
- ✅ YAML frontmatter valid
- ✅ $ARGUMENTS syntax correct (if used)
- ✅ allowed-tools format proper
- ✅ Folder organization clean
5. **Provide Installation Instructions**:
```
Your command is ready!
Output location: generated-commands/[command-name]/
To install:
1. Copy the command file:
cp generated-commands/[command-name]/[command-name].md .claude/commands/
2. Restart Claude Code (if already running)
3. Test:
/[command-name] [arguments]
```
---
## Preset Command Details
### 1. /research-business
**Purpose**: Comprehensive business and market research
**Arguments**: `$ARGUMENTS` (company or market to research)
**YAML**:
```yaml
---
description: Comprehensive business and market research with competitor analysis
argument-hint: [company/market] [industry]
allowed-tools: Read, Bash, Grep
---
```
**What it does**:
- Market size and trends analysis
- Competitor SWOT analysis
- Opportunity identification
- Industry landscape overview
- Strategic recommendations
---
### 2. /research-content
**Purpose**: Multi-platform content trend analysis
**Arguments**: `$ARGUMENTS` (topic to research)
**YAML**:
```yaml
---
description: Multi-platform content trend analysis for data-driven content strategy
argument-hint: [topic] [platforms]
allowed-tools: Read, Bash
---
```
**What it does**:
- Analyze trends across Google, Reddit, YouTube, Medium, LinkedIn, X
- User intent analysis (informational, commercial, transactional)
- Content gap identification
- SEO-optimized outline generation
- Platform-specific publishing strategies
---
### 3. /medical-translate
**Purpose**: Translate medical terminology to patient-friendly language
**Arguments**: `$ARGUMENTS` (medical term and language)
**YAML**:
```yaml
---
description: Translate medical terminology to 8th-10th grade reading level (German/English)
argument-hint: [medical-term] [de|en]
allowed-tools: Read
---
```
**What it does**:
- Translate complex medical terms
- Simplify to 8th-10th grade reading level
- Validate with Flesch-Kincaid (EN) or Wiener Sachtextformel (DE)
- Preserve clinical accuracy
- Provide patient-friendly explanations
---
### 4. /compliance-audit
**Purpose**: Check code for regulatory compliance
**Arguments**: `$ARGUMENTS` (path and compliance standard)
**YAML**:
```yaml
---
description: Audit code for HIPAA/GDPR/DSGVO compliance requirements
argument-hint: [code-path] [hipaa|gdpr|dsgvo|all]
allowed-tools: Read, Grep, Task
---
```
**What it does**:
- Scan for PHI/PII handling
- Check encryption requirements
- Verify audit logging
- Validate data subject rights
- Generate compliance report
---
### 5. /api-build
**Purpose**: Generate complete API integration code
**Arguments**: `$ARGUMENTS` (API name and endpoints)
**YAML**:
```yaml
---
description: Generate complete API client with error handling and tests
argument-hint: [api-name] [endpoints]
allowed-tools: Read, Write, Edit, Bash, Task
---
```
**What it does**:
- Generate API client classes
- Add error handling and retries
- Create authentication logic
- Generate unit and integration tests
- Add usage documentation
---
### 6. /test-auto
**Purpose**: Auto-generate comprehensive test suites
**Arguments**: `$ARGUMENTS` (file path and test type)
**YAML**:
```yaml
---
description: Auto-generate comprehensive test suite with coverage analysis
argument-hint: [file-path] [unit|integration|e2e]
allowed-tools: Read, Write, Bash
---
```
**What it does**:
- Analyze code to test
- Generate test cases (happy path, edge cases, errors)
- Add test fixtures and mocks
- Calculate coverage
- Provide testing documentation
---
### 7. /docs-generate
**Purpose**: Automated documentation generation
**Arguments**: `$ARGUMENTS` (code path and doc type)
**YAML**:
```yaml
---
description: Auto-generate documentation from code (API docs, README, architecture)
argument-hint: [code-path] [api|readme|architecture|all]
allowed-tools: Read, Write, Grep
---
```
**What it does**:
- Extract code structure and functions
- Generate API documentation
- Create README with usage examples
- Build architecture diagrams (Mermaid)
- Add code examples
---
### 8. /knowledge-mine
**Purpose**: Extract structured insights from documents
**Arguments**: `$ARGUMENTS` (document path and output format)
**YAML**:
```yaml
---
description: Extract and structure knowledge from documents into actionable insights
argument-hint: [doc-path] [faq|summary|kb|all]
allowed-tools: Read, Grep
---
```
**What it does**:
- Read and analyze documents
- Extract key insights
- Generate FAQs
- Create knowledge base articles
- Summarize findings
---
### 9. /workflow-analyze
**Purpose**: Analyze and optimize business workflows
**Arguments**: `$ARGUMENTS` (workflow description)
**YAML**:
```yaml
---
description: Analyze workflows and provide optimization recommendations
argument-hint: [workflow-description]
allowed-tools: Read, Task
---
```
**What it does**:
- Map current workflow
- Identify bottlenecks
- Suggest automation opportunities
- Calculate efficiency gains
- Create implementation roadmap
---
### 10. /batch-agents
**Purpose**: Launch multiple coordinated agents
**Arguments**: `$ARGUMENTS` (agent names and task)
**YAML**:
```yaml
---
description: Launch and coordinate multiple agents for complex tasks
argument-hint: [agent-names] [task-description]
allowed-tools: Task
---
```
**What it does**:
- Parse agent list
- Launch agents in parallel (if safe) or sequential
- Coordinate outputs
- Integrate results
- Provide comprehensive summary
---
## Output Structure
Commands are generated in your project's root directory:
```
[your-project]/
└── generated-commands/
└── [command-name]/
├── [command-name].md # Command file (ROOT level)
├── README.md # Installation guide (ROOT level)
├── TEST_EXAMPLES.md # Testing guide (ROOT level - if applicable)
│
├── standards/ # Only if command has standards
├── examples/ # Only if command has examples
└── scripts/ # Only if command has helper scripts
```
**Organization Rules**:
- All .md files in ROOT directory
- Supporting folders separate (standards/, examples/, scripts/)
- No mixing of different types in same folder
- Clean, hierarchical structure
---
## Installation
**After generation**:
1. **Review output**:
```bash
ls generated-commands/[command-name]/
```
2. **Copy to Claude Code** (when ready):
```bash
# Project-level (this project only)
cp generated-commands/[command-name]/[command-name].md .claude/commands/
# User-level (all projects)
cp generated-commands/[command-name]/[command-name].md ~/.claude/commands/
```
3. **Restart Claude Code** (if running)
4. **Test command**:
```bash
/[command-name] [arguments]
```
---
## Usage Examples
### Generate a Preset Command
```
@slash-command-factory
Use the /research-business preset
```
**Output**: Complete business research command ready to install
---
### Generate a Custom Command
```
@slash-command-factory
Create a custom command for analyzing customer feedback and generating product insights
```
**Skill asks 5-7 questions** → **Generates complete command** → **Validates format** → **Provides installation steps**
---
## Command Format (What Gets Generated)
**Example generated command** (`my-command.md`):
```markdown
---
description: Brief description of what the command does
argument-hint: [arg1] [arg2]
allowed-tools: Read, Write, Bash
model: claude-3-5-sonnet-20241022
---
# Command Instructions
Do [task] with "$ARGUMENTS":
1. **Step 1**: First action
2. **Step 2**: Second action
3. **Step 3**: Generate output
**Success Criteria**:
- Criterion 1
- Criterion 2
- Criterion 3
```
---
## Validation
Every generated command is automatically validated for:
- ✅ Valid YAML frontmatter (proper syntax, required fields)
- ✅ Correct argument format ($ARGUMENTS, not $1 $2 $3)
- ✅ allowed-tools syntax (comma-separated string)
- ✅ Clean folder organization (if folders used)
- ✅ No placeholder text
**If validation fails**, you'll get specific fix instructions.
---
## Best Practices
**For Command Design**:
- Keep commands focused (one clear purpose)
- Use descriptive names (kebab-case for files)
- Document expected arguments clearly
- Include success criteria
- Add examples in TEST_EXAMPLES.md
**For Tool Selection**:
- Read: For analyzing files
- Write/Edit: For generating/modifying files
- Bash: For system commands, web research
- Task: For launching agents
- Grep/Glob: For searching code
**For Agent Integration**:
- Use Task tool to launch agents
- Specify which agents clearly
- Coordinate outputs
- Document agent roles
---
## Important Notes
**Arguments**:
- ✅ Always use `$ARGUMENTS` (all arguments as one string)
- ❌ Never use `$1`, `$2`, `$3` (positional - not used by this factory)
**Folder Organization**:
- ✅ All .md files in command root directory
- ✅ Supporting folders separate (standards/, examples/, scripts/)
- ✅ No mixing of different types
**Output Location**:
- Commands generate to: `./generated-commands/[command-name]/`
- User copies to: `.claude/commands/[command-name].md` (when ready)
---
## Example Invocations
### Use a Preset
```
@slash-command-factory
Generate the /research-content preset command
```
→ Creates content research command with all features
---
### Create Custom Healthcare Command
```
@slash-command-factory
Create a command that generates German PTV 10 therapy applications
```
**Skill asks**:
- Purpose? (Generate PTV 10 applications)
- Tools? (Read, Write, Task)
- Agents? (Yes - health-sdk-builder related agents)
- Output? (Files - therapy application documents)
- Model? (Sonnet - for quality)
**Result**: `/generate-ptv10` command ready to use
---
### Create Business Intelligence Command
```
@slash-command-factory
Build a command for competitive SWOT analysis
```
**Skill asks 5-7 questions** → **Generates `/swot-analysis` command** → **Validates** → **Ready to install**
---
## Integration with Factory Agents
**Works with**:
- factory-guide (can delegate to this skill via prompts-guide pattern)
- Existing slash commands (/build, /validate-output, etc.)
**Complements**:
- skills-guide (builds Skills)
- prompts-guide (builds Prompts)
- agents-guide (builds Agents)
- slash-command-factory (builds Commands) ← This skill
**Complete ecosystem** for building all Claude Code augmentations!
---
## Output Validation
Generated commands are validated for:
**YAML Frontmatter**:
- Has `description` field
- Proper YAML syntax
- Valid frontmatter fields only
**Arguments**:
- Uses $ARGUMENTS if needed
- Has argument-hint if $ARGUMENTS used
- No $1, $2, $3 positional args
**Tools**:
- Valid tool names
- Proper comma-separated format
- Appropriate for command purpose
**Organization**:
- .md files in root
- Folders properly separated
- No scattered files
---
## Success Criteria
Generated commands should:
- ✅ Have valid YAML frontmatter
- ✅ Use $ARGUMENTS (never positional)
- ✅ Work when copied to .claude/commands/
- ✅ Execute correctly with arguments
- ✅ Produce expected output
- ✅ Follow organizational standards
---
**Version**: 1.0.0
**Last Updated**: October 28, 2025
**Compatible**: Claude Code (all versions with slash command support)
**Build powerful custom slash commands in minutes!** ⚡
validator.py
"""
Slash Command Validator
Validates generated slash command files for proper format.
Enforces official Anthropic patterns and best practices.
"""
import re
import os
from typing import Dict, List, Any
class CommandValidator:
"""Validate slash command .md files."""
def validate(self, command_content: str) -> Dict[str, any]:
"""
Validate complete command file content.
Args:
command_content: Full .md file content
Returns:
Dict with validation results
"""
issues = []
# Check YAML frontmatter
yaml_valid, yaml_issues = self._check_yaml_frontmatter(command_content)
if not yaml_valid:
issues.extend(yaml_issues)
# Check argument syntax
args_valid, args_issues = self._check_arguments(command_content)
if not args_valid:
issues.extend(args_issues)
# Check allowed-tools format
tools_valid, tools_issues = self._check_allowed_tools(command_content)
if not tools_valid:
issues.extend(tools_issues)
return {
'valid': len(issues) == 0,
'issues': issues
}
def _check_yaml_frontmatter(self, content: str) -> tuple:
"""Check YAML frontmatter is present and valid."""
issues = []
# Check starts with ---
if not content.strip().startswith('---'):
issues.append("Missing YAML frontmatter opening (---)")
return False, issues
# Extract frontmatter
parts = content.split('---')
if len(parts) < 3:
issues.append("YAML frontmatter not properly closed")
return False, issues
frontmatter = parts[1]
# Check required fields
if 'description:' not in frontmatter:
issues.append("Missing required 'description' field in YAML")
return len(issues) == 0, issues
def _check_arguments(self, content: str) -> tuple:
"""
Check argument usage is correct.
Commands should use $ARGUMENTS (not $1, $2, $3).
"""
issues = []
# Check for positional arguments (not allowed)
if re.search(r'\$[0-9]', content):
issues.append("Found positional arguments ($1, $2, etc.). Use $ARGUMENTS instead.")
# If uses $ARGUMENTS, should have argument-hint
if '$ARGUMENTS' in content:
if 'argument-hint:' not in content:
issues.append("Command uses $ARGUMENTS but missing 'argument-hint' in YAML")
return len(issues) == 0, issues
def _check_allowed_tools(self, content: str) -> tuple:
"""Check allowed-tools format is correct."""
issues = []
# Extract frontmatter
if '---' not in content:
return True, [] # Already caught in YAML check
parts = content.split('---')
if len(parts) < 2:
return True, []
frontmatter = parts[1]
# If has allowed-tools, validate format
if 'allowed-tools:' in frontmatter:
# Extract the tools line
for line in frontmatter.split('\n'):
if 'allowed-tools:' in line:
tools_part = line.split('allowed-tools:')[1].strip()
# Valid tools
valid_tools = ['Read', 'Write', 'Edit', 'Bash', 'Grep', 'Glob', 'Task', 'TodoWrite', 'Skill', 'SlashCommand']
# Check comma-separated
if ',' in tools_part or any(tool in tools_part for tool in valid_tools):
# Format looks okay
pass
else:
issues.append("allowed-tools should be comma-separated list")
return len(issues) == 0, issues
def validate_folder_structure(self, folder_path: str) -> Dict[str, Any]:
"""
Validate command folder organization.
Args:
folder_path: Path to generated command folder
Returns:
Validation results
"""
issues = []
if not os.path.exists(folder_path):
issues.append(f"Folder not found: {folder_path}")
return {'valid': False, 'issues': issues}
# Check .md files are in root (not in subfolders)
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.md'):
file_path = os.path.join(root, file)
# Should be in root of folder
if root != folder_path:
issues.append(f".md file in subfolder (should be in root): {file}")
# Check folders are properly separated
subfolders = [d for d in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, d))]
# Valid folder names
valid_folders = ['standards', 'examples', 'scripts']
for folder in subfolders:
if folder not in valid_folders:
issues.append(f"Unexpected folder: {folder} (valid: {valid_folders})")
return {
'valid': len(issues) == 0,
'issues': issues
}
def validate_bash_permissions(self, allowed_tools: str) -> Dict[str, Any]:
"""
Validate bash permissions are specific (not wildcards).
Official rule from Anthropic: NEVER use 'Bash' alone - always specify commands.
Args:
allowed_tools: The allowed-tools string from YAML
Returns:
Dict with validation results including errors and warnings
"""
if not allowed_tools:
return {'valid': True, 'errors': [], 'warnings': []}
errors = []
warnings = []
# Check for wildcard Bash (CRITICAL ERROR - not allowed)
# Must check if 'Bash' appears without parentheses
if re.search(r'\bBash\b(?!\()', allowed_tools):
errors.append("❌ CRITICAL: Wildcard 'Bash' not allowed per official patterns. Must specify exact commands: Bash(git status:*)")
# Extract bash commands
bash_commands = re.findall(r'Bash\(([^)]+)\)', allowed_tools)
# Validate each command against whitelist
valid_commands = [
'git', 'find', 'tree', 'ls', 'grep', 'wc', 'du',
'head', 'tail', 'cat', 'awk', 'sed', 'sort', 'uniq', 'touch'
]
for cmd in bash_commands:
base_cmd = cmd.split(':')[0].strip()
if base_cmd not in valid_commands:
warnings.append(f"⚠️ Command '{base_cmd}' not in official patterns. Verify necessity.")
return {
'valid': len(errors) == 0,
'errors': errors,
'warnings': warnings
}
def validate_command_name(self, name: str) -> Dict[str, Any]:
"""
Validate command name follows kebab-case convention.
Official rules from Anthropic docs:
- Must be kebab-case (lowercase with hyphens)
- Length: 2-4 words
- Characters: [a-z0-9-] only
- Must start and end with letter/number
Args:
name: Command name to validate
Returns:
Dict with validation results
"""
errors = []
# Check format (kebab-case with 2-4 words)
if not re.match(r'^[a-z0-9]+(-[a-z0-9]+){1,3}$', name):
errors.append(f"❌ Command name '{name}' must be kebab-case with 2-4 words (e.g., 'code-review')")
# Check length
word_count = len(name.split('-'))
if word_count < 2:
errors.append(f"❌ Command name too short: needs at least 2 words (e.g., 'api-build')")
elif word_count > 4:
errors.append(f"❌ Command name too long: maximum 4 words, found {word_count}")
# Check invalid characters
if re.search(r'[^a-z0-9-]', name):
errors.append(f"❌ Command name contains invalid characters. Use only [a-z0-9-]")
# Check for underscores (common mistake)
if '_' in name:
suggested = name.replace('_', '-')
errors.append(f"❌ Use hyphens not underscores. Try: '{suggested}'")
# Check for camelCase or PascalCase
if re.search(r'[A-Z]', name):
errors.append(f"❌ Command name must be lowercase only. No CamelCase or PascalCase.")
return {
'valid': len(errors) == 0,
'errors': errors
}
def validate_arguments_usage(self, command_content: str) -> Dict[str, Any]:
"""
Validate uses $ARGUMENTS (not $1, $2, $3).
Official pattern from Anthropic: All examples use $ARGUMENTS.
Args:
command_content: Full command file content
Returns:
Dict with validation results
"""
warnings = []
errors = []
# Check for positional arguments (CRITICAL - wrong pattern)
positional_matches = re.findall(r'\$[0-9]+', command_content)
if positional_matches:
errors.append(f"❌ Found positional arguments: {positional_matches}. Official pattern uses $ARGUMENTS")
# Check for $ARGUMENTS without argument-hint
if '$ARGUMENTS' in command_content and 'argument-hint:' not in command_content:
warnings.append("⚠️ Uses $ARGUMENTS but missing 'argument-hint' in YAML frontmatter")
return {
'valid': len(errors) == 0,
'errors': errors,
'warnings': warnings
}
def validate_comprehensive(self, command_name: str, command_content: str, allowed_tools: str) -> Dict[str, Any]:
"""
Run all validations comprehensively.
Args:
command_name: Name of the command
command_content: Full command file content
allowed_tools: The allowed-tools string
Returns:
Comprehensive validation results
"""
all_errors = []
all_warnings = []
# Validate command name
name_result = self.validate_command_name(command_name)
if not name_result['valid']:
all_errors.extend(name_result['errors'])
# Validate bash permissions
bash_result = self.validate_bash_permissions(allowed_tools)
if not bash_result['valid']:
all_errors.extend(bash_result['errors'])
all_warnings.extend(bash_result['warnings'])
# Validate arguments usage
args_result = self.validate_arguments_usage(command_content)
if not args_result['valid']:
all_errors.extend(args_result['errors'])
all_warnings.extend(args_result['warnings'])
# Run standard validation
standard_result = self.validate(command_content)
if not standard_result['valid']:
all_errors.extend(standard_result['issues'])
return {
'valid': len(all_errors) == 0,
'errors': all_errors,
'warnings': all_warnings,
'summary': f"{'✅ VALID' if len(all_errors) == 0 else '❌ INVALID'} - {len(all_errors)} errors, {len(all_warnings)} warnings"
}