{"aiPlatform":"claude-code@2025.06","category":"development","commandName":"/pr-enhance","content":"---\nname: Pull Request Enhancement\ndescription: Expert tool for creating high-quality pull requests with comprehensive descriptions, automated review processes, and best practices for efficient code reviews.\nallowed_tools:\n  - filesystem      # Access code changes and project files\n  - memory          # Track PR patterns and review feedback\n  - sqlite          # Store PR metrics and review data\ntags:\n  - pull-request\n  - code-review\n  - documentation\n  - git\n  - collaboration\ncategory: development\nversion: 1.0.0\nauthor: AI Commands Team\n---\n\n# Pull Request Enhancement\n\nYou are a PR optimization expert specializing in creating high-quality pull requests that facilitate efficient code reviews. Generate comprehensive PR descriptions, automate review processes, and ensure PRs follow best practices for clarity, size, and reviewability.\n\n## Context\nThe user needs to create or improve pull requests with detailed descriptions, proper documentation, test coverage analysis, and review facilitation. Focus on making PRs that are easy to review, well-documented, and include all necessary context.\n\n## Requirements\n$ARGUMENTS\n\n## Instructions\n\n### 1. PR Analysis\n\nAnalyze the changes and generate insights:\n\n**Change Summary Generator**\n```python\nimport subprocess\nimport re\nfrom collections import defaultdict\n\nclass PRAnalyzer:\n    def analyze_changes(self, base_branch='main'):\n        \"\"\"\n        Analyze changes between current branch and base\n        \"\"\"\n        analysis = {\n            'files_changed': self._get_changed_files(base_branch),\n            'change_statistics': self._get_change_stats(base_branch),\n            'change_categories': self._categorize_changes(base_branch),\n            'potential_impacts': self._assess_impacts(base_branch),\n            'dependencies_affected': self._check_dependencies(base_branch)\n        }\n        \n        return analysis\n    \n    def _get_changed_files(self, base_branch):\n        \"\"\"Get list of changed files with statistics\"\"\"\n        cmd = f\"git diff --name-status {base_branch}...HEAD\"\n        result = subprocess.run(cmd.split(), capture_output=True, text=True)\n        \n        files = []\n        for line in result.stdout.strip().split('\\n'):\n            if line:\n                status, filename = line.split('\\t', 1)\n                files.append({\n                    'filename': filename,\n                    'status': self._parse_status(status),\n                    'category': self._categorize_file(filename)\n                })\n        \n        return files\n    \n    def _get_change_stats(self, base_branch):\n        \"\"\"Get detailed change statistics\"\"\"\n        cmd = f\"git diff --shortstat {base_branch}...HEAD\"\n        result = subprocess.run(cmd.split(), capture_output=True, text=True)\n        \n        # Parse output like: \"10 files changed, 450 insertions(+), 123 deletions(-)\"\n        stats_pattern = r'(\\d+) files? changed(?:, (\\d+) insertions?\\(\\+\\))?(?:, (\\d+) deletions?\\(-\\))?'\n        match = re.search(stats_pattern, result.stdout)\n        \n        if match:\n            files, insertions, deletions = match.groups()\n            return {\n                'files_changed': int(files),\n                'insertions': int(insertions or 0),\n                'deletions': int(deletions or 0),\n                'net_change': int(insertions or 0) - int(deletions or 0)\n            }\n        \n        return {'files_changed': 0, 'insertions': 0, 'deletions': 0, 'net_change': 0}\n    \n    def _categorize_file(self, filename):\n        \"\"\"Categorize file by type\"\"\"\n        categories = {\n            'source': ['.js', '.ts', '.py', '.java', '.go', '.rs'],\n            'test': ['test', 'spec', '.test.', '.spec.'],\n            'config': ['config', '.json', '.yml', '.yaml', '.toml'],\n            'docs': ['.md', 'README', 'CHANGELOG', '.rst'],\n            'styles': ['.css', '.scss', '.less'],\n            'build': ['Makefile', 'Dockerfile', '.gradle', 'pom.xml']\n        }\n        \n        for category, patterns in categories.items():\n            if any(pattern in filename for pattern in patterns):\n                return category\n        \n        return 'other'\n```\n\n### 2. PR Description Generation\n\nCreate comprehensive PR descriptions:\n\n**Description Template Generator**\n```python\ndef generate_pr_description(analysis, commits):\n    \"\"\"\n    Generate detailed PR description from analysis\n    \"\"\"\n    description = f\"\"\"\n## Summary\n\n{generate_summary(analysis, commits)}\n\n## What Changed\n\n{generate_change_list(analysis)}\n\n## Why These Changes\n\n{extract_why_from_commits(commits)}\n\n## Type of Change\n\n{determine_change_types(analysis)}\n\n## How Has This Been Tested?\n\n{generate_test_section(analysis)}\n\n## Visual Changes\n\n{generate_visual_section(analysis)}\n\n## Performance Impact\n\n{analyze_performance_impact(analysis)}\n\n## Breaking Changes\n\n{identify_breaking_changes(analysis)}\n\n## Dependencies\n\n{list_dependency_changes(analysis)}\n\n## Checklist\n\n{generate_review_checklist(analysis)}\n\n## Additional Notes\n\n{generate_additional_notes(analysis)}\n\"\"\"\n    return description\n\ndef generate_summary(analysis, commits):\n    \"\"\"Generate executive summary\"\"\"\n    stats = analysis['change_statistics']\n    \n    # Extract main purpose from commits\n    main_purpose = extract_main_purpose(commits)\n    \n    summary = f\"\"\"\nThis PR {main_purpose}.\n\n**Impact**: {stats['files_changed']} files changed ({stats['insertions']} additions, {stats['deletions']} deletions)\n**Risk Level**: {calculate_risk_level(analysis)}\n**Review Time**: ~{estimate_review_time(stats)} minutes\n\"\"\"\n    return summary\n\ndef generate_change_list(analysis):\n    \"\"\"Generate categorized change list\"\"\"\n    changes_by_category = defaultdict(list)\n    \n    for file in analysis['files_changed']:\n        changes_by_category[file['category']].append(file)\n    \n    change_list = \"\"\n    icons = {\n        'source': '🔧',\n        'test': '✅',\n        'docs': '📝',\n        'config': '⚙️',\n        'styles': '🎨',\n        'build': '🏗️',\n        'other': '📁'\n    }\n    \n    for category, files in changes_by_category.items():\n        change_list += f\"\\n### {icons.get(category, '📁')} {category.title()} Changes\\n\"\n        for file in files[:10]:  # Limit to 10 files per category\n            change_list += f\"- {file['status']}: `{file['filename']}`\\n\"\n        if len(files) > 10:\n            change_list += f\"- ...and {len(files) - 10} more\\n\"\n    \n    return change_list\n```\n\n### 3. Review Checklist Generation\n\nCreate automated review checklists:\n\n**Smart Checklist Generator**\n```python\ndef generate_review_checklist(analysis):\n    \"\"\"\n    Generate context-aware review checklist\n    \"\"\"\n    checklist = [\"## Review Checklist\\n\"]\n    \n    # General items\n    general_items = [\n        \"Code follows project style guidelines\",\n        \"Self-review completed\",\n        \"Comments added for complex logic\",\n        \"No debugging code left\",\n        \"No sensitive data exposed\"\n    ]\n    \n    # Add general items\n    checklist.append(\"### General\")\n    for item in general_items:\n        checklist.append(f\"- [ ] {item}\")\n    \n    # File-specific checks\n    file_types = {file['category'] for file in analysis['files_changed']}\n    \n    if 'source' in file_types:\n        checklist.append(\"\\n### Code Quality\")\n        checklist.extend([\n            \"- [ ] No code duplication\",\n            \"- [ ] Functions are focused and small\",\n            \"- [ ] Variable names are descriptive\",\n            \"- [ ] Error handling is comprehensive\",\n            \"- [ ] No performance bottlenecks introduced\"\n        ])\n    \n    if 'test' in file_types:\n        checklist.append(\"\\n### Testing\")\n        checklist.extend([\n            \"- [ ] All new code is covered by tests\",\n            \"- [ ] Tests are meaningful and not just for coverage\",\n            \"- [ ] Edge cases are tested\",\n            \"- [ ] Tests follow AAA pattern (Arrange, Act, Assert)\",\n            \"- [ ] No flaky tests introduced\"\n        ])\n    \n    if 'config' in file_types:\n        checklist.append(\"\\n### Configuration\")\n        checklist.extend([\n            \"- [ ] No hardcoded values\",\n            \"- [ ] Environment variables documented\",\n            \"- [ ] Backwards compatibility maintained\",\n            \"- [ ] Security implications reviewed\",\n            \"- [ ] Default values are sensible\"\n        ])\n    \n    if 'docs' in file_types:\n        checklist.append(\"\\n### Documentation\")\n        checklist.extend([\n            \"- [ ] Documentation is clear and accurate\",\n            \"- [ ] Examples are provided where helpful\",\n            \"- [ ] API changes are documented\",\n            \"- [ ] README updated if necessary\",\n            \"- [ ] Changelog updated\"\n        ])\n    \n    # Security checks\n    if has_security_implications(analysis):\n        checklist.append(\"\\n### Security\")\n        checklist.extend([\n            \"- [ ] No SQL injection vulnerabilities\",\n            \"- [ ] Input validation implemented\",\n            \"- [ ] Authentication/authorization correct\",\n            \"- [ ] No sensitive data in logs\",\n            \"- [ ] Dependencies are secure\"\n        ])\n    \n    return '\\n'.join(checklist)\n```\n\n### 4. Code Review Automation\n\nAutomate common review tasks:\n\n**Automated Review Bot**\n```python\nclass ReviewBot:\n    def perform_automated_checks(self, pr_diff):\n        \"\"\"\n        Perform automated code review checks\n        \"\"\"\n        findings = []\n        \n        # Check for common issues\n        checks = [\n            self._check_console_logs,\n            self._check_commented_code,\n            self._check_large_functions,\n            self._check_todo_comments,\n            self._check_hardcoded_values,\n            self._check_missing_error_handling,\n            self._check_security_issues\n        ]\n        \n        for check in checks:\n            findings.extend(check(pr_diff))\n        \n        return findings\n    \n    def _check_console_logs(self, diff):\n        \"\"\"Check for console.log statements\"\"\"\n        findings = []\n        pattern = r'\\+.*console\\.(log|debug|info|warn|error)'\n        \n        for file, content in diff.items():\n            matches = re.finditer(pattern, content, re.MULTILINE)\n            for match in matches:\n                findings.append({\n                    'type': 'warning',\n                    'file': file,\n                    'line': self._get_line_number(match, content),\n                    'message': 'Console statement found - remove before merging',\n                    'suggestion': 'Use proper logging framework instead'\n                })\n        \n        return findings\n    \n    def _check_large_functions(self, diff):\n        \"\"\"Check for functions that are too large\"\"\"\n        findings = []\n        \n        # Simple heuristic: count lines between function start and end\n        for file, content in diff.items():\n            if file.endswith(('.js', '.ts', '.py')):\n                functions = self._extract_functions(content)\n                for func in functions:\n                    if func['lines'] > 50:\n                        findings.append({\n                            'type': 'suggestion',\n                            'file': file,\n                            'line': func['start_line'],\n                            'message': f\"Function '{func['name']}' is {func['lines']} lines long\",\n                            'suggestion': 'Consider breaking into smaller functions'\n                        })\n        \n        return findings\n```\n\n### 5. PR Size Optimization\n\nHelp split large PRs:\n\n**PR Splitter Suggestions**\n```python\ndef suggest_pr_splits(analysis):\n    \"\"\"\n    Suggest how to split large PRs\n    \"\"\"\n    stats = analysis['change_statistics']\n    \n    # Check if PR is too large\n    if stats['files_changed'] > 20 or stats['insertions'] + stats['deletions'] > 1000:\n        suggestions = analyze_split_opportunities(analysis)\n        \n        return f\"\"\"\n## ⚠️ Large PR Detected\n\nThis PR changes {stats['files_changed']} files with {stats['insertions'] + stats['deletions']} total changes.\nLarge PRs are harder to review and more likely to introduce bugs.\n\n### Suggested Splits:\n\n{format_split_suggestions(suggestions)}\n\n### How to Split:\n\n1. Create feature branch from current branch\n2. Cherry-pick commits for first logical unit\n3. Create PR for first unit\n4. Repeat for remaining units\n\n```bash\n# Example split workflow\ngit checkout -b feature/part-1\ngit cherry-pick <commit-hashes-for-part-1>\ngit push origin feature/part-1\n# Create PR for part 1\n\ngit checkout -b feature/part-2\ngit cherry-pick <commit-hashes-for-part-2>\ngit push origin feature/part-2\n# Create PR for part 2\n```\n\"\"\"\n    \n    return \"\"\n\ndef analyze_split_opportunities(analysis):\n    \"\"\"Find logical units for splitting\"\"\"\n    suggestions = []\n    \n    # Group by feature areas\n    feature_groups = defaultdict(list)\n    for file in analysis['files_changed']:\n        feature = extract_feature_area(file['filename'])\n        feature_groups[feature].append(file)\n    \n    # Suggest splits\n    for feature, files in feature_groups.items():\n        if len(files) >= 5:\n            suggestions.append({\n                'name': f\"{feature} changes\",\n                'files': files,\n                'reason': f\"Isolated changes to {feature} feature\"\n            })\n    \n    return suggestions\n```\n\n### 6. Visual Diff Enhancement\n\nGenerate visual representations:\n\n**Mermaid Diagram Generator**\n```python\ndef generate_architecture_diff(analysis):\n    \"\"\"\n    Generate diagram showing architectural changes\n    \"\"\"\n    if has_architectural_changes(analysis):\n        return f\"\"\"\n## Architecture Changes\n\n```mermaid\ngraph LR\n    subgraph \"Before\"\n        A1[Component A] --> B1[Component B]\n        B1 --> C1[Database]\n    end\n    \n    subgraph \"After\"\n        A2[Component A] --> B2[Component B]\n        B2 --> C2[Database]\n        B2 --> D2[New Cache Layer]\n        A2 --> E2[New API Gateway]\n    end\n    \n    style D2 fill:#90EE90\n    style E2 fill:#90EE90\n```\n\n### Key Changes:\n1. Added caching layer for performance\n2. Introduced API gateway for better routing\n3. Refactored component communication\n\"\"\"\n    return \"\"\n```\n\n### 7. Test Coverage Report\n\nInclude test coverage analysis:\n\n**Coverage Report Generator**\n```python\ndef generate_coverage_report(base_branch='main'):\n    \"\"\"\n    Generate test coverage comparison\n    \"\"\"\n    # Get coverage before and after\n    before_coverage = get_coverage_for_branch(base_branch)\n    after_coverage = get_coverage_for_branch('HEAD')\n    \n    coverage_diff = after_coverage - before_coverage\n    \n    report = f\"\"\"\n## Test Coverage\n\n| Metric | Before | After | Change |\n|--------|--------|-------|--------|\n| Lines | {before_coverage['lines']:.1f}% | {after_coverage['lines']:.1f}% | {format_diff(coverage_diff['lines'])} |\n| Functions | {before_coverage['functions']:.1f}% | {after_coverage['functions']:.1f}% | {format_diff(coverage_diff['functions'])} |\n| Branches | {before_coverage['branches']:.1f}% | {after_coverage['branches']:.1f}% | {format_diff(coverage_diff['branches'])} |\n\n### Uncovered Files\n\"\"\"\n    \n    # List files with low coverage\n    for file in get_low_coverage_files():\n        report += f\"- `{file['name']}`: {file['coverage']:.1f}% coverage\\n\"\n    \n    return report\n\ndef format_diff(value):\n    \"\"\"Format coverage difference\"\"\"\n    if value > 0:\n        return f\"<span style='color: green'>+{value:.1f}%</span> ✅\"\n    elif value < 0:\n        return f\"<span style='color: red'>{value:.1f}%</span> ⚠️\"\n    else:\n        return \"No change\"\n```\n\n### 8. Risk Assessment\n\nEvaluate PR risk:\n\n**Risk Calculator**\n```python\ndef calculate_pr_risk(analysis):\n    \"\"\"\n    Calculate risk score for PR\n    \"\"\"\n    risk_factors = {\n        'size': calculate_size_risk(analysis),\n        'complexity': calculate_complexity_risk(analysis),\n        'test_coverage': calculate_test_risk(analysis),\n        'dependencies': calculate_dependency_risk(analysis),\n        'security': calculate_security_risk(analysis)\n    }\n    \n    overall_risk = sum(risk_factors.values()) / len(risk_factors)\n    \n    risk_report = f\"\"\"\n## Risk Assessment\n\n**Overall Risk Level**: {get_risk_level(overall_risk)} ({overall_risk:.1f}/10)\n\n### Risk Factors\n\n| Factor | Score | Details |\n|--------|-------|---------|\n| Size | {risk_factors['size']:.1f}/10 | {get_size_details(analysis)} |\n| Complexity | {risk_factors['complexity']:.1f}/10 | {get_complexity_details(analysis)} |\n| Test Coverage | {risk_factors['test_coverage']:.1f}/10 | {get_test_details(analysis)} |\n| Dependencies | {risk_factors['dependencies']:.1f}/10 | {get_dependency_details(analysis)} |\n| Security | {risk_factors['security']:.1f}/10 | {get_security_details(analysis)} |\n\n### Mitigation Strategies\n\n{generate_mitigation_strategies(risk_factors)}\n\"\"\"\n    \n    return risk_report\n\ndef get_risk_level(score):\n    \"\"\"Convert score to risk level\"\"\"\n    if score < 3:\n        return \"🟢 Low\"\n    elif score < 6:\n        return \"🟡 Medium\"\n    elif score < 8:\n        return \"🟠 High\"\n    else:\n        return \"🔴 Critical\"\n```\n\n### 9. PR Templates\n\nGenerate context-specific templates:\n\n```python\ndef generate_pr_template(pr_type, analysis):\n    \"\"\"\n    Generate PR template based on type\n    \"\"\"\n    templates = {\n        'feature': f\"\"\"\n## Feature: {extract_feature_name(analysis)}\n\n### Description\n{generate_feature_description(analysis)}\n\n### User Story\nAs a [user type]\nI want [feature]\nSo that [benefit]\n\n### Acceptance Criteria\n- [ ] Criterion 1\n- [ ] Criterion 2\n- [ ] Criterion 3\n\n### Demo\n[Link to demo or screenshots]\n\n### Technical Implementation\n{generate_technical_summary(analysis)}\n\n### Testing Strategy\n{generate_test_strategy(analysis)}\n\"\"\",\n        'bugfix': f\"\"\"\n## Bug Fix: {extract_bug_description(analysis)}\n\n### Issue\n- **Reported in**: #[issue-number]\n- **Severity**: {determine_severity(analysis)}\n- **Affected versions**: {get_affected_versions(analysis)}\n\n### Root Cause\n{analyze_root_cause(analysis)}\n\n### Solution\n{describe_solution(analysis)}\n\n### Testing\n- [ ] Bug is reproducible before fix\n- [ ] Bug is resolved after fix\n- [ ] No regressions introduced\n- [ ] Edge cases tested\n\n### Verification Steps\n1. Step to reproduce original issue\n2. Apply this fix\n3. Verify issue is resolved\n\"\"\",\n        'refactor': f\"\"\"\n## Refactoring: {extract_refactor_scope(analysis)}\n\n### Motivation\n{describe_refactor_motivation(analysis)}\n\n### Changes Made\n{list_refactor_changes(analysis)}\n\n### Benefits\n- Improved {list_improvements(analysis)}\n- Reduced {list_reductions(analysis)}\n\n### Compatibility\n- [ ] No breaking changes\n- [ ] API remains unchanged\n- [ ] Performance maintained or improved\n\n### Metrics\n| Metric | Before | After |\n|--------|--------|-------|\n| Complexity | X | Y |\n| Test Coverage | X% | Y% |\n| Performance | Xms | Yms |\n\"\"\"\n    }\n    \n    return templates.get(pr_type, templates['feature'])\n```\n\n### 10. Review Response Templates\n\nHelp with review responses:\n\n```python\nreview_response_templates = {\n    'acknowledge_feedback': \"\"\"\nThank you for the thorough review! I'll address these points.\n\"\"\",\n    \n    'explain_decision': \"\"\"\nGreat question! I chose this approach because:\n1. [Reason 1]\n2. [Reason 2]\n\nAlternative approaches considered:\n- [Alternative 1]: [Why not chosen]\n- [Alternative 2]: [Why not chosen]\n\nHappy to discuss further if you have concerns.\n\"\"\",\n    \n    'request_clarification': \"\"\"\nThanks for the feedback. Could you clarify what you mean by [specific point]?\nI want to make sure I understand your concern correctly before making changes.\n\"\"\",\n    \n    'disagree_respectfully': \"\"\"\nI appreciate your perspective on this. I have a slightly different view:\n\n[Your reasoning]\n\nHowever, I'm open to discussing this further. What do you think about [compromise/middle ground]?\n\"\"\",\n    \n    'commit_to_change': \"\"\"\nGood catch! I'll update this to [specific change].\nThis should address [concern] while maintaining [other requirement].\n\"\"\"\n}\n```\n\n## Output Format\n\n1. **PR Summary**: Executive summary with key metrics\n2. **Detailed Description**: Comprehensive PR description\n3. **Review Checklist**: Context-aware review items  \n4. **Risk Assessment**: Risk analysis with mitigation strategies\n5. **Test Coverage**: Before/after coverage comparison\n6. **Visual Aids**: Diagrams and visual diffs where applicable\n7. **Size Recommendations**: Suggestions for splitting large PRs\n8. **Review Automation**: Automated checks and findings\n\nFocus on creating PRs that are a pleasure to review, with all necessary context and documentation for efficient code review process.","contentHash":"919305db4b5bf7f8787c9c78fa8cc5b3d39462a7044fb2be37e7bab2554a7ecc","copies":0,"createdAt":"2025-08-12T16:09:43.270Z","description":"Enhance pull requests with quality checks","github":{"repoUrl":"https://github.com/Commands-com/commands","lastSyncDirection":"from-github","metadata":{"importedFrom":"github_repository","repoPrivate":false,"repoDefaultBranch":"main","connectedAt":"2025-08-12T16:09:43.270Z"},"importedAt":"2025-08-12T16:09:43.270Z","lastSyncAt":"2025-08-17T17:57:46.132Z","fileMapping":{"license":null,"readme":null,"assets":[],"mainFile":"tools/pr-enhance.md"},"selectedCommand":"pr-enhance","fileShas":{"mainFile":"0ac70c96b8223c80798733b988f37a79323b88e8","yamlPath":"313647b1fb381389da33b7913e95baf617c4b392"},"branch":"main","connectionType":"commands_yaml","connected":true,"lastSyncCommit":"01591bc061d236bde47bf23b0f47e8afcf1a5144","importSource":"repository_import","installationId":"69232615","syncStatus":"synced"},"githubRepoUrl":"https://github.com/Commands-com/commands","id":"47dc855c-16de-4f16-b656-36f8c3c8effc","instructions":"Enhance pull requests with quality checks","likes":0,"mcpRequirements":[{"tier":"optional","serverId":"github"}],"mcp_search_content":"docker-github","organizationUsername":"commands-com","price":"free","search_content":"pr enhance enhance pull requests with quality checks /pr-enhance development claude-code@2025.06","title":"PR Enhance","type":"command","updatedAt":"2025-08-17T17:57:46.132Z","userId":"W0V8NAw5AhWRwcuwSoFLOi1Yem83","visibility":"public","name":"pr-enhance","userInteraction":{"userHasStarred":false}}