# 🏆 The Coolest Things About This Repository

A simple breakdown of what makes this repo special, ranked from most to least awesome.

---

## Quick Score Card

| Rank | Feature | Awesome | Unique | Works Well |
|:----:|---------|:-------:|:------:|:----------:|
| 1 | One-Command Sync | 9.8 | 9.5 | 9.5 |
| 2 | Auto PR Review | 9.6 | 9.7 | 9.0 |
| 3 | Safety Hooks | 9.2 | 7.5 | 9.8 |
| 4 | Knowledge Base | 9.0 | 8.5 | 9.0 |
| 5 | Prompt Guide | 8.8 | 7.0 | 9.2 |

**Overall Score: 8.8/10** 🏆

---

## #1: One-Command Sync Tool ⭐⭐⭐⭐⭐

**Command:** `pip install persuade && persuade sync .`

### What it does (simple version)
You run ONE command, and it sets up all the AI automation in any project. Like copying your entire toolkit to a new workshop with one click.

### Why it's awesome
- **One command** = Everything set up
- **Smart** = Knows what to keep, what to replace
- **Safe** = Makes backups before changing anything
- **Preview mode** = See what will change before changing it

### The scores explained
- **Awesome (9.8):** Almost perfect - solves a real problem elegantly
- **Unique (9.5):** Very rare to find this kind of tool
- **Works Well (9.5):** Reliable and well-tested

### 🎯 What Would Make It a 10?

**Plain English Version:**
Right now, you have to type a command to sync. A perfect 10 would mean it just *happens automatically* whenever you need it. Imagine opening a project and having it offer to sync itself, or getting a notification when there's an update available.

**The Technical Deep Dive:**

To hit a perfect 10/10, implement these enhancements:

#### 1. Auto-Detection & Smart Notifications
```python
# Add a watcher daemon that monitors template repo for updates
# File: src/persuade/sync_engine/watcher.py

import watchdog
from pathlib import Path
import subprocess

class TemplateSyncWatcher:
    """Watches template repo and notifies when updates are available."""
    
    def __init__(self, template_path: Path, projects: list[Path]):
        self.template_path = template_path
        self.projects = projects
        self.last_sync_hashes = self._load_sync_state()
    
    def check_for_updates(self) -> dict[Path, list[str]]:
        """Returns dict of {project: [changed_files]} needing sync."""
        current_hash = self._get_template_hash()
        updates = {}
        for project in self.projects:
            project_hash = self._get_project_sync_hash(project)
            if project_hash != current_hash:
                updates[project] = self._get_diff_files(project_hash, current_hash)
        return updates
    
    def notify(self, updates: dict):
        """Send desktop/Slack/email notification about available updates."""
        # Integration with OS notification system
        subprocess.run(['notify-send', 'Sync Available', 
                       f'{len(updates)} projects have updates available'])
```

#### 2. VS Code / IDE Integration
```json
// .vscode/extensions/claude-sync/package.json
{
  "name": "claude-sync-extension",
  "displayName": "Claude Automation Sync",
  "commands": [
    {
      "command": "claudeSync.sync",
      "title": "Sync Claude Automation"
    },
    {
      "command": "claudeSync.preview",
      "title": "Preview Sync Changes"
    }
  ],
  "activationEvents": ["workspaceContains:.claude/"],
  "contributes": {
    "statusBar": {
      "text": "$(sync) Claude",
      "tooltip": "Click to sync automation",
      "command": "claudeSync.sync"
    }
  }
}
```

#### 3. GitHub Action for Automated Sync PRs
```yaml
# .github/workflows/auto-sync-automation.yml
name: Auto-Sync Claude Automation

on:
  schedule:
    - cron: '0 9 * * 1'  # Every Monday at 9am
  repository_dispatch:
    types: [template-updated]

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Sync from template
        run: |
          # Clone template repo
          git clone https://github.com/org/template.git /tmp/template
          
          # Run sync with auto-PR creation
          persuade sync . \
            --auto-pr \
            --pr-title "chore: sync Claude automation from template" \
            --pr-body "Automated sync of latest automation updates"
```

#### 4. Conflict Resolution UI
```python
# Add TUI (Text User Interface) for resolving merge conflicts
# File: src/persuade/sync_engine/conflict_ui.py

from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt

class ConflictResolver:
    """Interactive conflict resolution during sync."""
    
    def resolve(self, file: Path, local_content: str, template_content: str):
        console = Console()
        
        console.print(Panel(
            f"[bold red]CONFLICT[/] in {file}\n\n"
            f"[yellow]Your version:[/]\n{local_content[:200]}...\n\n"
            f"[green]Template version:[/]\n{template_content[:200]}...",
            title="Merge Conflict"
        ))
        
        choice = Prompt.ask(
            "Choose",
            choices=["keep-mine", "take-template", "merge-both", "edit-manually"]
        )
        
        return self._apply_choice(choice, file, local_content, template_content)
```

#### 5. Plugin Architecture
```python
# Allow custom sync plugins for project-specific behaviors
# File: src/persuade/sync_engine/plugins.py

from abc import ABC, abstractmethod

class SyncPlugin(ABC):
    """Base class for sync plugins."""
    
    @abstractmethod
    def pre_sync(self, source: Path, target: Path) -> None:
        """Run before sync starts."""
        pass
    
    @abstractmethod
    def post_sync(self, source: Path, target: Path, changes: list) -> None:
        """Run after sync completes."""
        pass
    
    @abstractmethod
    def transform_file(self, content: str, file_path: Path) -> str:
        """Transform file content during sync."""
        pass

# Example plugin: Auto-update version numbers
class VersionBumpPlugin(SyncPlugin):
    def post_sync(self, source, target, changes):
        if any('package.json' in str(f) for f in changes):
            self._bump_version(target / 'package.json')
```

#### 6. Sync Analytics Dashboard
```python
# Track sync history, success rates, common issues
# File: src/persuade/sync_engine/analytics.py

import sqlite3
from datetime import datetime

class SyncAnalytics:
    """Track and report on sync operations across all projects."""
    
    def record_sync(self, project: Path, success: bool, 
                    files_changed: int, duration: float):
        conn = sqlite3.connect(self._db_path)
        conn.execute("""
            INSERT INTO sync_history 
            (project, timestamp, success, files_changed, duration_seconds)
            VALUES (?, ?, ?, ?, ?)
        """, (str(project), datetime.now(), success, files_changed, duration))
        conn.commit()
    
    def generate_report(self) -> str:
        """Generate markdown report of sync statistics."""
        return f"""
        ## Sync Analytics Report
        
        - **Total syncs:** {self.total_syncs}
        - **Success rate:** {self.success_rate}%
        - **Average duration:** {self.avg_duration}s
        - **Most synced project:** {self.most_active_project}
        - **Common failure reasons:** {self.common_failures}
        """
```

**Summary of Missing Features for 10/10:**
| Feature | Impact | Effort |
|---------|--------|--------|
| Auto-detection watcher | High | Medium |
| VS Code extension | High | High |
| GitHub Action auto-PR | High | Low |
| Conflict resolution UI | Medium | Medium |
| Plugin architecture | Medium | High |
| Analytics dashboard | Low | Medium |

---

## #2: Automatic PR Review Loop ⭐⭐⭐⭐⭐

**Location:** [.claude/commands/iterate-pr.md](./../.claude/commands/iterate-pr.md)

### What it does (simple version)
When someone reviews your code and asks for changes, Claude automatically:
1. Reads the feedback
2. Makes the fixes
3. Pushes the updates
4. Tells you what it did

It's like having an assistant who handles all the back-and-forth.

### Why it's awesome
- **Hands-free** = You can focus on other things
- **Smart limits** = Stops after 10 rounds (no infinite loops)
- **Clear updates** = Posts comments explaining changes

### The scores explained
- **Awesome (9.6):** Saves tons of time
- **Unique (9.7):** Almost no other tools do this
- **Works Well (9.0):** Works great, occasionally needs guidance

### 🎯 What Would Make It a 10?

**Plain English Version:**
Right now, Claude fixes things when you tell it to. A perfect 10 would mean Claude *understands* the review, asks smart questions if something is unclear, learns from past reviews, and even predicts what reviewers might ask before they ask it.

**The Technical Deep Dive:**

To hit a perfect 10/10, implement these enhancements:

#### 1. Semantic Review Understanding with NLP
```python
# Parse and categorize review comments intelligently
# File: .claude/scripts/review_engine/semantic_parser.py

from dataclasses import dataclass
from enum import Enum
import re

class ReviewType(Enum):
    BUG_FIX = "bug_fix"
    STYLE_ISSUE = "style_issue"
    SECURITY_CONCERN = "security_concern"
    PERFORMANCE = "performance"
    CLARIFICATION_NEEDED = "clarification"
    ENHANCEMENT = "enhancement"
    NITPICK = "nitpick"

@dataclass
class ParsedReview:
    type: ReviewType
    priority: int  # 1-5
    specific_file: str | None
    specific_line: int | None
    action_required: str
    context_needed: list[str]

def parse_review_comment(comment: str) -> ParsedReview:
    """
    Use NLP to understand what the reviewer is actually asking for.
    
    Examples:
    - "This could be a security issue" → SecurityConcern, Priority 5
    - "nit: spacing" → Nitpick, Priority 1
    - "Can you explain why...?" → ClarificationNeeded, Priority 2
    """
    patterns = {
        ReviewType.SECURITY_CONCERN: [
            r'security', r'vulnerability', r'injection', r'XSS', r'CSRF'
        ],
        ReviewType.BUG_FIX: [
            r'bug', r'error', r'crash', r'fails?', r'broken'
        ],
        ReviewType.NITPICK: [
            r'nit:', r'nitpick', r'minor:', r'style:'
        ],
    }
    
    # ... pattern matching logic
    return ParsedReview(...)
```

#### 2. Smart Clarification System
```python
# When Claude is unsure, ask the reviewer instead of guessing
# File: .claude/scripts/review_engine/clarifier.py

class SmartClarifier:
    """Generates clarifying questions when review intent is unclear."""
    
    CONFIDENCE_THRESHOLD = 0.7
    
    def analyze_confidence(self, review: str, proposed_fix: str) -> float:
        """Calculate confidence that proposed fix addresses the review."""
        # Use semantic similarity, keyword matching, etc.
        return confidence_score
    
    def generate_clarification(self, review: str) -> str:
        """Generate a smart question to ask the reviewer."""
        return f"""
        I want to make sure I address your feedback correctly.
        
        You mentioned: "{review[:100]}..."
        
        Could you clarify:
        - Are you suggesting [Option A] or [Option B]?
        - Should this apply to [specific scope] or [broader scope]?
        
        I'll implement the fix once I understand the intent.
        """
    
    async def handle_review(self, review: str):
        proposed_fix = self.generate_fix(review)
        confidence = self.analyze_confidence(review, proposed_fix)
        
        if confidence < self.CONFIDENCE_THRESHOLD:
            await self.post_clarification(self.generate_clarification(review))
        else:
            await self.implement_fix(proposed_fix)
```

#### 3. Learning from Past Reviews (Pattern Memory)
```python
# Build a knowledge base of review patterns and solutions
# File: .claude/scripts/review_engine/pattern_learner.py

import json
from pathlib import Path

class ReviewPatternLearner:
    """Learns from past reviews to improve future responses."""
    
    def __init__(self, patterns_db: Path):
        self.patterns = self._load_patterns(patterns_db)
    
    def record_successful_fix(self, review: str, fix: str, 
                               reviewer: str, accepted: bool):
        """Record when a fix was accepted or rejected."""
        pattern = {
            "review_keywords": self._extract_keywords(review),
            "fix_pattern": self._extract_fix_pattern(fix),
            "reviewer": reviewer,
            "success": accepted,
            "timestamp": datetime.now().isoformat()
        }
        self.patterns.append(pattern)
        self._save_patterns()
    
    def suggest_fix(self, new_review: str) -> tuple[str, float]:
        """Suggest a fix based on similar past reviews."""
        similar_patterns = self._find_similar(new_review)
        if similar_patterns:
            best_match = max(similar_patterns, key=lambda p: p['success_rate'])
            return best_match['fix_pattern'], best_match['confidence']
        return None, 0.0
    
    def get_reviewer_preferences(self, reviewer: str) -> dict:
        """Learn individual reviewer's preferences and style."""
        reviewer_patterns = [p for p in self.patterns if p['reviewer'] == reviewer]
        return {
            'prefers_concise_comments': self._analyze_comment_length(reviewer_patterns),
            'cares_about_tests': self._analyze_test_mentions(reviewer_patterns),
            'style_preferences': self._analyze_style_patterns(reviewer_patterns),
        }
```

#### 4. Proactive Review Anticipation
```python
# Predict and address likely review comments BEFORE submission
# File: .claude/scripts/review_engine/proactive_reviewer.py

class ProactiveReviewer:
    """Anticipates review comments and addresses them preemptively."""
    
    def __init__(self, common_issues_db: Path, team_standards: Path):
        self.common_issues = self._load_common_issues(common_issues_db)
        self.standards = self._load_standards(team_standards)
    
    def pre_review_check(self, diff: str) -> list[dict]:
        """Check code against common review triggers."""
        issues = []
        
        # Check for missing tests
        if self._has_new_functions(diff) and not self._has_new_tests(diff):
            issues.append({
                "type": "missing_tests",
                "message": "New functions without corresponding tests",
                "suggested_action": "Add unit tests for new functions",
                "auto_fixable": True
            })
        
        # Check for security patterns
        if self._has_security_red_flags(diff):
            issues.append({
                "type": "security_review",
                "message": "Contains patterns that often trigger security reviews",
                "suggested_action": "Add input validation / sanitization",
                "auto_fixable": False
            })
        
        # Check against team standards
        standard_violations = self._check_standards(diff)
        issues.extend(standard_violations)
        
        return issues
    
    def auto_fix_issues(self, issues: list[dict], code: str) -> str:
        """Automatically fix issues that are auto-fixable."""
        for issue in issues:
            if issue['auto_fixable']:
                code = self._apply_fix(code, issue)
        return code
```

#### 5. Multi-Reviewer Consensus Handling
```python
# Handle conflicting reviews from multiple reviewers
# File: .claude/scripts/review_engine/consensus.py

class ConsensusHandler:
    """Handles conflicting reviews from multiple reviewers."""
    
    def detect_conflicts(self, reviews: list[Review]) -> list[Conflict]:
        """Detect when reviewers disagree."""
        conflicts = []
        
        for i, review1 in enumerate(reviews):
            for review2 in reviews[i+1:]:
                if self._are_conflicting(review1, review2):
                    conflicts.append(Conflict(review1, review2))
        
        return conflicts
    
    def resolve_conflict(self, conflict: Conflict) -> Resolution:
        """Determine resolution strategy for conflicting reviews."""
        # Strategy 1: Seniority-based (if org hierarchy available)
        if self._has_seniority_data():
            return self._resolve_by_seniority(conflict)
        
        # Strategy 2: Recency-based (most recent wins)
        return self._resolve_by_recency(conflict)
    
    def notify_about_conflict(self, conflict: Conflict):
        """Post comment explaining the conflict and proposed resolution."""
        return f"""
        ⚠️ **Conflicting Review Feedback Detected**
        
        @{conflict.reviewer1} suggested: {conflict.review1.summary}
        @{conflict.reviewer2} suggested: {conflict.review2.summary}
        
        **Proposed resolution:** Following @{conflict.winner}'s suggestion 
        because {conflict.reason}.
        
        Please comment if you'd prefer a different approach.
        """
```

#### 6. Integration with CI/CD Feedback
```yaml
# Automatically correlate CI failures with review feedback
# .github/workflows/smart-review-loop.yml

name: Smart Review Loop

on:
  pull_request_review:
    types: [submitted]
  check_run:
    types: [completed]

jobs:
  correlate-feedback:
    runs-on: ubuntu-latest
    steps:
      - name: Correlate CI failures with reviews
        run: |
          # Get recent reviews
          reviews=$(gh pr review list $PR_NUMBER --json body,author)
          
          # Get CI failure logs
          failures=$(gh run view $RUN_ID --json jobs --jq '.jobs[] | select(.conclusion == "failure")')
          
          # Correlate and generate combined fix plan
          python .claude/scripts/review_engine/correlate_feedback.py \
            --reviews "$reviews" \
            --failures "$failures" \
            --output fix_plan.json
          
      - name: Execute combined fix plan
        run: |
          python .claude/scripts/review_engine/execute_plan.py fix_plan.json
```

**Summary of Missing Features for 10/10:**
| Feature | Impact | Effort |
|---------|--------|--------|
| Semantic review parsing | High | Medium |
| Smart clarification system | High | Medium |
| Pattern learning memory | High | High |
| Proactive anticipation | Very High | High |
| Multi-reviewer consensus | Medium | Medium |
| CI/CD feedback correlation | High | Medium |

---

## #3: Safety Hooks ⭐⭐⭐⭐

**Location:** [.claude/git-hooks/](./../.claude/git-hooks/)

### What it does (simple version)
Blocks you from accidentally pushing code directly to the main branch. Forces you to use the safer "pull request" process.

Think of it like a safety lock that prevents accidents.

### Why it's awesome
- **Prevents disasters** = Can't break the main code by accident
- **Automatic** = Gets installed when you sync
- **Clear messages** = Tells you exactly what to do instead

### The scores explained
- **Awesome (9.2):** Simple but important
- **Unique (7.5):** Other tools do this too (but this is easier)
- **Works Well (9.8):** Nearly bulletproof

### 🎯 What Would Make It a 10?

**Plain English Version:**
Right now, the hooks just block bad things. A perfect 10 would mean they also *help you do the right thing* - automatically creating branches, suggesting better commit messages, running quick checks before you even try to push, and even recovering from mistakes gracefully.

**The Technical Deep Dive:**

To hit a perfect 10/10, implement these enhancements:

#### 1. Smart Branch Auto-Creation
```bash
#!/bin/bash
# Enhanced pre-push hook with auto-branch creation
# File: .claude/git-hooks/pre-push

set -euo pipefail

CURRENT_BRANCH=$(git branch --show-current)
PROTECTED_BRANCHES=("main" "master")

for protected in "${PROTECTED_BRANCHES[@]}"; do
    if [ "$CURRENT_BRANCH" = "$protected" ]; then
        echo ""
        echo "⚠️  You're on '$protected'. Let me help you fix that!"
        echo ""
        
        # Get the last commit message to suggest branch name
        LAST_COMMIT=$(git log -1 --pretty=%s)
        SUGGESTED_NAME=$(echo "$LAST_COMMIT" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | cut -c1-50)
        
        echo "I can automatically:"
        echo "  1. Create a new branch from your current work"
        echo "  2. Move your recent commits to that branch"
        echo "  3. Push to that branch instead"
        echo ""
        
        read -p "Create branch 'feature/$SUGGESTED_NAME'? [Y/n]: " RESPONSE
        
        if [[ "$RESPONSE" =~ ^[Yy]?$ ]]; then
            # Count unpushed commits
            UNPUSHED=$(git rev-list --count origin/$protected..$protected 2>/dev/null || echo "0")
            
            # Create new branch
            git checkout -b "feature/$SUGGESTED_NAME"
            
            # Push to new branch
            echo "✅ Created branch 'feature/$SUGGESTED_NAME'"
            echo "📤 Pushing to origin..."
            git push -u origin "feature/$SUGGESTED_NAME"
            
            # Offer to create PR
            read -p "Create a PR now? [Y/n]: " PR_RESPONSE
            if [[ "$PR_RESPONSE" =~ ^[Yy]?$ ]]; then
                gh pr create --fill
            fi
            
            exit 0
        fi
        
        exit 1
    fi
done

exit 0
```

#### 2. Pre-Commit Quality Gate
```bash
#!/bin/bash
# Pre-commit hook with smart quality checks
# File: .claude/git-hooks/pre-commit

set -euo pipefail

echo "🔍 Running pre-commit checks..."

ERRORS=()
WARNINGS=()

# Check 1: No secrets in commit
if git diff --cached --name-only | xargs grep -l -E "(API_KEY|SECRET|PASSWORD|PRIVATE_KEY)" 2>/dev/null; then
    ERRORS+=("🔐 SECURITY: Potential secrets detected in staged files")
fi

# Check 2: No debug code
if git diff --cached | grep -E "(console\.log|print\(|debugger|binding\.pry)" > /dev/null 2>&1; then
    WARNINGS+=("⚠️  Debug statements detected (console.log, print, etc.)")
fi

# Check 3: Large files
LARGE_FILES=$(git diff --cached --name-only | while read f; do
    if [ -f "$f" ]; then
        SIZE=$(wc -c < "$f")
        if [ "$SIZE" -gt 1000000 ]; then
            echo "$f ($(numfmt --to=iec $SIZE))"
        fi
    fi
done)

if [ -n "$LARGE_FILES" ]; then
    WARNINGS+=("📦 Large files detected:\n$LARGE_FILES")
fi

# Check 4: Missing tests for new functions
NEW_FUNCS=$(git diff --cached --name-only -- "*.py" "*.js" "*.ts" | xargs grep -l "def \|function \|const.*=.*=>" 2>/dev/null || true)
if [ -n "$NEW_FUNCS" ]; then
    TEST_FILES=$(git diff --cached --name-only -- "*test*" "*spec*" | wc -l)
    if [ "$TEST_FILES" -eq 0 ]; then
        WARNINGS+=("🧪 New code detected but no test files in this commit")
    fi
fi

# Check 5: Commit message format (prepare-commit-msg)
# Check 6: Run linter on changed files
CHANGED_PY=$(git diff --cached --name-only -- "*.py")
if [ -n "$CHANGED_PY" ]; then
    if command -v ruff &> /dev/null; then
        if ! echo "$CHANGED_PY" | xargs ruff check --quiet 2>/dev/null; then
            WARNINGS+=("🐍 Python linting issues detected (run 'ruff check --fix')")
        fi
    fi
fi

# Report results
if [ ${#ERRORS[@]} -gt 0 ]; then
    echo ""
    echo "❌ COMMIT BLOCKED - Critical issues found:"
    printf '%s\n' "${ERRORS[@]}"
    echo ""
    exit 1
fi

if [ ${#WARNINGS[@]} -gt 0 ]; then
    echo ""
    echo "⚠️  Warnings (commit will proceed):"
    printf '%s\n' "${WARNINGS[@]}"
    echo ""
    read -p "Continue with commit? [Y/n]: " RESPONSE
    if [[ ! "$RESPONSE" =~ ^[Yy]?$ ]]; then
        exit 1
    fi
fi

echo "✅ All checks passed!"
exit 0
```

#### 3. Smart Commit Message Helper
```bash
#!/bin/bash
# Prepare-commit-msg hook with AI-assisted message generation
# File: .claude/git-hooks/prepare-commit-msg

COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2

# Only help with new commits, not amends or merges
if [ "$COMMIT_SOURCE" != "" ]; then
    exit 0
fi

# Get the diff for context
DIFF=$(git diff --cached --stat)

# Detect commit type from changed files
detect_type() {
    local files=$(git diff --cached --name-only)
    
    if echo "$files" | grep -q "^docs/\|\.md$"; then
        echo "docs"
    elif echo "$files" | grep -q "^test\|_test\.\|\.test\.\|spec\."; then
        echo "test"
    elif echo "$files" | grep -q "package\.json\|requirements\.txt\|Gemfile"; then
        echo "chore"
    elif echo "$files" | grep -q "\.github/\|Dockerfile\|\.yml$"; then
        echo "ci"
    else
        echo "feat"
    fi
}

TYPE=$(detect_type)

# Get suggested scope from directory
SCOPE=$(git diff --cached --name-only | head -1 | cut -d'/' -f1)

# Generate suggested message
SUGGESTION="$TYPE($SCOPE): "

# Add suggestion to commit message file if empty
if [ -z "$(cat $COMMIT_MSG_FILE | grep -v '^#')" ]; then
    echo "$SUGGESTION" > $COMMIT_MSG_FILE.tmp
    cat $COMMIT_MSG_FILE >> $COMMIT_MSG_FILE.tmp
    mv $COMMIT_MSG_FILE.tmp $COMMIT_MSG_FILE
    
    # Add helpful comments
    cat >> $COMMIT_MSG_FILE << EOF

# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# 📝 Commit Message Guide
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Format: <type>(<scope>): <subject>
#
# Types: feat, fix, docs, style, refactor, test, chore, ci
# Scope: The area of code (optional)
# Subject: Short description (imperative mood, no period)
#
# Example: feat(auth): add password reset flow
#
# Suggested based on your changes:
#   Type: $TYPE
#   Scope: $SCOPE
#   Files changed:
$(git diff --cached --name-only | sed 's/^/#     /')
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EOF
fi

exit 0
```

#### 4. Post-Commit Wisdom
```bash
#!/bin/bash
# Post-commit hook with helpful next steps
# File: .claude/git-hooks/post-commit

BRANCH=$(git branch --show-current)
REMOTE_EXISTS=$(git ls-remote --heads origin "$BRANCH" 2>/dev/null | wc -l)

echo ""
echo "✅ Commit successful!"
echo ""

# Helpful next steps based on context
if [ "$REMOTE_EXISTS" -eq 0 ]; then
    echo "📤 This branch isn't on GitHub yet. Push with:"
    echo "   git push -u origin $BRANCH"
    echo ""
fi

# Check if there's an open PR
if command -v gh &> /dev/null; then
    PR_NUMBER=$(gh pr view "$BRANCH" --json number --jq '.number' 2>/dev/null || echo "")
    
    if [ -n "$PR_NUMBER" ]; then
        echo "📋 This branch has an open PR (#$PR_NUMBER)"
        echo "   View: gh pr view $PR_NUMBER --web"
        echo "   Push: git push"
        echo ""
    fi
fi

# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
    echo "📝 You have uncommitted changes remaining:"
    git status --short
    echo ""
fi
```

#### 5. Branch Protection Configuration
```python
# Auto-configure GitHub branch protection when syncing
# File: src/persuade/sync_engine/branch_protection.py

import subprocess
import json

class BranchProtectionManager:
    """Configure GitHub branch protection rules automatically."""
    
    def configure_protection(self, owner: str, repo: str, branch: str = "main"):
        """Set up recommended branch protection rules."""
        
        rules = {
            "required_status_checks": {
                "strict": True,
                "contexts": ["test", "lint", "build"]
            },
            "enforce_admins": False,
            "required_pull_request_reviews": {
                "dismiss_stale_reviews": True,
                "require_code_owner_reviews": True,
                "required_approving_review_count": 1
            },
            "restrictions": None,
            "allow_force_pushes": False,
            "allow_deletions": False
        }
        
        subprocess.run([
            "gh", "api",
            f"/repos/{owner}/{repo}/branches/{branch}/protection",
            "-X", "PUT",
            "-H", "Accept: application/vnd.github+json",
            "-f", f"required_status_checks={json.dumps(rules['required_status_checks'])}",
            # ... more fields
        ])
```

**Summary of Missing Features for 10/10:**
| Feature | Impact | Effort |
|---------|--------|--------|
| Smart branch auto-creation | Very High | Low |
| Pre-commit quality gate | High | Medium |
| Commit message helper | Medium | Low |
| Post-commit wisdom | Medium | Low |
| Auto branch protection | High | Medium |

---

## #4: Knowledge Base for AI ⭐⭐⭐⭐

**Location:** [.claude/knowledge/](./../.claude/knowledge/)

### What it does (simple version)
A library of instructions that helps Claude give better answers. It's like giving Claude a study guide before an exam.

Covers topics like:
- How to use git properly
- How to write Python code
- How to run tests
- How to automate things

### Why it's awesome
- **Syncs everywhere** = Same smart Claude in all your projects
- **Always learning** = Gets updated with new tips
- **Specialized** = Different advice for different topics

### The scores explained
- **Awesome (9.0):** Makes Claude noticeably smarter
- **Unique (8.5):** Rare idea - most docs are for humans only
- **Works Well (9.0):** Reliable improvement in AI responses

### 🎯 What Would Make It a 10?

**Plain English Version:**
Right now, the knowledge base is like a textbook - it has good information, but Claude has to figure out when to use it. A perfect 10 would mean the knowledge is *active* - it automatically knows when you're working on Python and gives Python advice, tracks what you've tried before, and even learns from mistakes in real-time.

**The Technical Deep Dive:**

To hit a perfect 10/10, implement these enhancements:

#### 1. Context-Aware Knowledge Injection
```python
# Automatically inject relevant knowledge based on current context
# File: .claude/scripts/knowledge_engine/context_aware.py

from pathlib import Path
import re

class ContextAwareKnowledge:
    """Dynamically loads relevant knowledge based on what you're working on."""
    
    def __init__(self, knowledge_base: Path):
        self.kb = knowledge_base
        self.knowledge_map = self._build_knowledge_map()
    
    def _build_knowledge_map(self) -> dict:
        """Map file patterns to relevant knowledge files."""
        return {
            r"\.py$": [
                "python/virtual-environments.md",
                "python/type-hints.md",
                "testing/pytest-basics.md"
            ],
            r"\.ts$|\.tsx$": [
                "typescript/strict-mode.md",
                "testing/jest-basics.md"
            ],
            r"requirements\.txt|pyproject\.toml": [
                "python/dependency-management.md",
                "python/virtual-environments.md"
            ],
            r"\.github/workflows": [
                "ci-cd/github-actions.md",
                "automation/workflow-patterns.md"
            ],
            r"Dockerfile|docker-compose": [
                "containers/docker-best-practices.md"
            ]
        }
    
    def get_relevant_knowledge(self, current_files: list[str]) -> list[str]:
        """Return list of knowledge files relevant to current work."""
        relevant = set()
        
        for file in current_files:
            for pattern, knowledge_files in self.knowledge_map.items():
                if re.search(pattern, file):
                    relevant.update(knowledge_files)
        
        return self._load_knowledge_content(relevant)
    
    def inject_into_prompt(self, user_prompt: str, 
                           current_files: list[str]) -> str:
        """Enhance user prompt with relevant knowledge."""
        knowledge = self.get_relevant_knowledge(current_files)
        
        if knowledge:
            return f"""
## Relevant Context from Knowledge Base

{chr(10).join(knowledge)}

---

## User Request

{user_prompt}
"""
        return user_prompt
```

#### 2. Live Learning from Mistakes
```python
# Track when Claude makes mistakes and learn from them
# File: .claude/scripts/knowledge_engine/mistake_tracker.py

import json
from datetime import datetime
from pathlib import Path

class MistakeTracker:
    """Tracks and learns from mistakes to prevent repetition."""
    
    def __init__(self, mistakes_db: Path):
        self.db_path = mistakes_db
        self.mistakes = self._load_mistakes()
    
    def record_mistake(self, 
                       context: str,
                       mistake_type: str,
                       what_went_wrong: str,
                       correct_approach: str,
                       files_involved: list[str]):
        """Record a mistake for future prevention."""
        
        mistake = {
            "id": f"mistake_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            "timestamp": datetime.now().isoformat(),
            "context": context,
            "type": mistake_type,
            "wrong": what_went_wrong,
            "correct": correct_approach,
            "files": files_involved,
            "prevented_count": 0
        }
        
        self.mistakes.append(mistake)
        self._save_mistakes()
        
        # Auto-generate knowledge article
        self._generate_knowledge_article(mistake)
    
    def _generate_knowledge_article(self, mistake: dict):
        """Auto-generate a knowledge base article from the mistake."""
        
        article = f"""# Learned Pattern: {mistake['type']}

**Source:** Auto-generated from mistake on {mistake['timestamp']}

## The Problem

{mistake['wrong']}

## The Correct Approach

{mistake['correct']}

## Files This Applies To

{chr(10).join(f'- `{f}`' for f in mistake['files'])}

## Prevention

When working with files matching these patterns, always:
1. {mistake['correct'].split('.')[0]}
"""
        
        article_path = self.kb_path / "learned" / f"{mistake['id']}.md"
        article_path.write_text(article)
    
    def get_relevant_warnings(self, current_files: list[str]) -> list[str]:
        """Get warnings based on past mistakes relevant to current work."""
        warnings = []
        
        for mistake in self.mistakes:
            if any(f in current_files or 
                   self._pattern_matches(f, current_files) 
                   for f in mistake['files']):
                warnings.append(
                    f"⚠️ Past issue: {mistake['type']}\n"
                    f"   Remember: {mistake['correct']}"
                )
                mistake['prevented_count'] += 1
        
        return warnings
```

#### 3. Personalized Knowledge Profiles
```python
# Build knowledge profiles for different users/projects
# File: .claude/scripts/knowledge_engine/profiles.py

from dataclasses import dataclass
from pathlib import Path
import json

@dataclass
class KnowledgeProfile:
    name: str
    expertise_level: dict[str, str]  # {"python": "expert", "rust": "beginner"}
    preferences: dict
    common_tasks: list[str]
    known_gotchas: list[str]

class ProfileManager:
    """Manages personalized knowledge profiles."""
    
    def __init__(self, profiles_dir: Path):
        self.profiles_dir = profiles_dir
    
    def get_profile(self, project_path: Path) -> KnowledgeProfile:
        """Load or create a profile for the current project."""
        profile_file = project_path / ".claude" / "profile.json"
        
        if profile_file.exists():
            return self._load_profile(profile_file)
        return self._create_profile(project_path)
    
    def _create_profile(self, project_path: Path) -> KnowledgeProfile:
        """Auto-detect profile from project structure."""
        
        # Analyze project
        languages = self._detect_languages(project_path)
        frameworks = self._detect_frameworks(project_path)
        expertise = self._estimate_expertise(project_path)
        
        return KnowledgeProfile(
            name=project_path.name,
            expertise_level=expertise,
            preferences=self._default_preferences(),
            common_tasks=self._infer_common_tasks(languages, frameworks),
            known_gotchas=[]
        )
    
    def tailor_knowledge(self, knowledge: str, 
                         profile: KnowledgeProfile) -> str:
        """Adjust knowledge presentation based on profile."""
        
        if profile.expertise_level.get("python") == "expert":
            # Skip basics, focus on advanced
            knowledge = self._filter_advanced(knowledge, "python")
        elif profile.expertise_level.get("python") == "beginner":
            # Expand explanations, add context
            knowledge = self._expand_basics(knowledge, "python")
        
        return knowledge
```

#### 4. Knowledge Validation & Freshness
```python
# Ensure knowledge stays accurate and up-to-date
# File: .claude/scripts/knowledge_engine/validator.py

from datetime import datetime, timedelta
from pathlib import Path
import subprocess

class KnowledgeValidator:
    """Validates that knowledge base content is current and accurate."""
    
    STALE_THRESHOLD = timedelta(days=90)
    
    def __init__(self, kb_path: Path):
        self.kb_path = kb_path
    
    def check_freshness(self) -> list[dict]:
        """Find stale knowledge articles that need review."""
        stale = []
        
        for article in self.kb_path.rglob("*.md"):
            last_modified = datetime.fromtimestamp(article.stat().st_mtime)
            age = datetime.now() - last_modified
            
            if age > self.STALE_THRESHOLD:
                stale.append({
                    "file": article,
                    "age_days": age.days,
                    "recommendation": self._get_recommendation(article)
                })
        
        return stale
    
    def validate_code_examples(self) -> list[dict]:
        """Validate that code examples in knowledge actually work."""
        issues = []
        
        for article in self.kb_path.rglob("*.md"):
            code_blocks = self._extract_code_blocks(article)
            
            for block in code_blocks:
                if block['language'] == 'python':
                    result = self._validate_python(block['code'])
                elif block['language'] == 'bash':
                    result = self._validate_bash(block['code'])
                else:
                    continue
                
                if not result['valid']:
                    issues.append({
                        "file": article,
                        "block": block['code'][:100],
                        "error": result['error']
                    })
        
        return issues
    
    def check_external_links(self) -> list[dict]:
        """Verify external links still work."""
        broken_links = []
        
        for article in self.kb_path.rglob("*.md"):
            links = self._extract_links(article)
            
            for link in links:
                if not self._link_works(link):
                    broken_links.append({
                        "file": article,
                        "link": link
                    })
        
        return broken_links
```

#### 5. Semantic Search & Retrieval
```python
# Enable semantic search across knowledge base
# File: .claude/scripts/knowledge_engine/semantic_search.py

from pathlib import Path
import numpy as np

class SemanticSearch:
    """Semantic search across knowledge base using embeddings."""
    
    def __init__(self, kb_path: Path, embeddings_cache: Path):
        self.kb_path = kb_path
        self.cache = embeddings_cache
        self.embeddings = self._load_or_build_embeddings()
    
    def _build_embeddings(self):
        """Build embeddings for all knowledge articles."""
        embeddings = {}
        
        for article in self.kb_path.rglob("*.md"):
            content = article.read_text()
            chunks = self._chunk_content(content)
            
            for i, chunk in enumerate(chunks):
                embedding = self._get_embedding(chunk)
                embeddings[f"{article}:{i}"] = {
                    "embedding": embedding,
                    "content": chunk
                }
        
        return embeddings
    
    def search(self, query: str, top_k: int = 5) -> list[dict]:
        """Find most relevant knowledge for a query."""
        query_embedding = self._get_embedding(query)
        
        scores = []
        for key, data in self.embeddings.items():
            similarity = self._cosine_similarity(
                query_embedding, data['embedding']
            )
            scores.append({
                "key": key,
                "content": data['content'],
                "score": similarity
            })
        
        # Sort by similarity and return top K
        scores.sort(key=lambda x: x['score'], reverse=True)
        return scores[:top_k]
    
    def answer_question(self, question: str) -> str:
        """Use knowledge base to answer a question."""
        relevant = self.search(question, top_k=3)
        
        context = "\n\n".join([r['content'] for r in relevant])
        
        return f"""
Based on the knowledge base:

{context}

Answer: [Generated answer using the context above]
"""
```

**Summary of Missing Features for 10/10:**
| Feature | Impact | Effort |
|---------|--------|--------|
| Context-aware injection | Very High | Medium |
| Live mistake learning | High | Medium |
| Personalized profiles | Medium | High |
| Knowledge validation | High | Medium |
| Semantic search | Very High | High |

---

## #5: Prompt Engineering Guide ⭐⭐⭐⭐

**Location:** [docs/prompt-engineering-guide.md](./../docs/prompt-engineering-guide.md)

### What it does (simple version)
Teaches you how to ask AI better questions. Better questions = better answers.

### Key lesson
> "Take 30 extra seconds to write a clear question. It saves hours of frustration."

### Why it's awesome
- **Real examples** = Not just theory, actual templates
- **Progressive** = Starts easy, gets advanced
- **Avoids mistakes** = Lists common pitfalls

### The scores explained
- **Awesome (8.8):** Very practical and useful
- **Unique (7.0):** Other guides exist, but this is well-organized
- **Works Well (9.2):** Following it actually improves results

### 🎯 What Would Make It a 10?

**Plain English Version:**
Right now, the guide teaches you how to write good prompts. A perfect 10 would mean it *writes prompts for you* - you describe what you want, and it generates the perfect prompt. It would also track which prompts work best, share winning prompts across the team, and even auto-improve prompts that didn't work well.

**The Technical Deep Dive:**

To hit a perfect 10/10, implement these enhancements:

#### 1. Interactive Prompt Builder
```python
# CLI/Web tool that builds prompts step-by-step
# File: .claude/scripts/prompt_builder/interactive.py

from rich.console import Console
from rich.prompt import Prompt, Confirm
from rich.panel import Panel

class InteractivePromptBuilder:
    """Step-by-step prompt construction wizard."""
    
    def __init__(self):
        self.console = Console()
    
    def build_prompt(self) -> str:
        """Interactively build an optimized prompt."""
        
        self.console.print(Panel(
            "🔮 Prompt Builder Wizard",
            subtitle="Let's create the perfect prompt"
        ))
        
        # Step 1: What do you want?
        goal = Prompt.ask("What do you want Claude to do?")
        
        # Step 2: Classify the task
        task_type = Prompt.ask(
            "What type of task is this?",
            choices=["code", "explain", "debug", "review", "refactor", "test", "other"]
        )
        
        # Step 3: Gather context
        self.console.print("\n📋 Context gathering...")
        
        language = Prompt.ask("Programming language", default="Python")
        framework = Prompt.ask("Framework (if any)", default="None")
        
        has_example = Confirm.ask("Do you have example code to share?")
        example = ""
        if has_example:
            self.console.print("Paste your example (end with Ctrl+D):")
            example = self._read_multiline()
        
        # Step 4: Constraints
        self.console.print("\n🚧 Constraints...")
        
        constraints = []
        while True:
            constraint = Prompt.ask(
                "Add a constraint (or press Enter to skip)",
                default=""
            )
            if not constraint:
                break
            constraints.append(constraint)
        
        # Step 5: Output format
        output_format = Prompt.ask(
            "Preferred output format",
            choices=["code_only", "code_with_explanation", "step_by_step", "options"],
            default="code_with_explanation"
        )
        
        # Generate the prompt
        prompt = self._generate_prompt(
            goal=goal,
            task_type=task_type,
            language=language,
            framework=framework,
            example=example,
            constraints=constraints,
            output_format=output_format
        )
        
        self.console.print(Panel(prompt, title="✨ Your Optimized Prompt"))
        
        # Offer to copy to clipboard
        if Confirm.ask("Copy to clipboard?"):
            self._copy_to_clipboard(prompt)
        
        return prompt
    
    def _generate_prompt(self, **kwargs) -> str:
        """Generate optimized prompt from collected info."""
        
        prompt_parts = []
        
        # Task description
        if kwargs['task_type'] == 'code':
            prompt_parts.append(f"Create {kwargs['language']} code that: {kwargs['goal']}")
        elif kwargs['task_type'] == 'debug':
            prompt_parts.append(f"Debug this {kwargs['language']} code: {kwargs['goal']}")
        # ... other task types
        
        # Context
        if kwargs['framework'] != "None":
            prompt_parts.append(f"\nContext: Using {kwargs['framework']} framework")
        
        # Example
        if kwargs['example']:
            prompt_parts.append(f"\nExample/Reference code:\n```{kwargs['language']}\n{kwargs['example']}\n```")
        
        # Constraints
        if kwargs['constraints']:
            prompt_parts.append("\nConstraints:")
            for c in kwargs['constraints']:
                prompt_parts.append(f"- {c}")
        
        # Output format instructions
        format_instructions = {
            'code_only': "Return only the code, no explanations.",
            'code_with_explanation': "Include brief comments explaining key decisions.",
            'step_by_step': "Break down the solution into numbered steps.",
            'options': "Provide 2-3 alternative approaches with trade-offs."
        }
        prompt_parts.append(f"\n{format_instructions[kwargs['output_format']]}")
        
        return "\n".join(prompt_parts)
```

#### 2. Prompt Performance Tracker
```python
# Track which prompts work well and which don't
# File: .claude/scripts/prompt_builder/tracker.py

import json
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass

@dataclass
class PromptResult:
    prompt: str
    response_quality: int  # 1-5
    worked_first_try: bool
    iterations_needed: int
    task_type: str
    timestamp: datetime
    notes: str

class PromptPerformanceTracker:
    """Tracks prompt effectiveness over time."""
    
    def __init__(self, db_path: Path):
        self.db_path = db_path
        self.results = self._load_results()
    
    def record_result(self, result: PromptResult):
        """Record how well a prompt worked."""
        self.results.append(result)
        self._save_results()
        self._update_analytics()
    
    def get_best_patterns(self, task_type: str) -> list[dict]:
        """Find patterns from successful prompts."""
        successful = [r for r in self.results 
                      if r.task_type == task_type 
                      and r.response_quality >= 4
                      and r.worked_first_try]
        
        patterns = self._extract_patterns(successful)
        return sorted(patterns, key=lambda p: p['success_rate'], reverse=True)
    
    def suggest_improvements(self, failed_prompt: str) -> list[str]:
        """Suggest improvements based on successful similar prompts."""
        
        similar_successful = self._find_similar_successful(failed_prompt)
        
        suggestions = []
        for success in similar_successful:
            diff = self._compare_prompts(failed_prompt, success.prompt)
            if diff:
                suggestions.append(f"Try adding: {diff['missing_element']}")
        
        return suggestions
    
    def generate_report(self) -> str:
        """Generate analytics report on prompt performance."""
        
        total = len(self.results)
        successful = len([r for r in self.results if r.response_quality >= 4])
        first_try = len([r for r in self.results if r.worked_first_try])
        
        return f"""
## Prompt Performance Report

**Overall Stats:**
- Total prompts tracked: {total}
- Success rate: {successful/total*100:.1f}%
- First-try success: {first_try/total*100:.1f}%

**By Task Type:**
{self._by_task_type_stats()}

**Top Performing Patterns:**
{self._top_patterns()}

**Areas for Improvement:**
{self._improvement_areas()}
"""
```

#### 3. Team Prompt Library
```python
# Shared library of effective prompts
# File: .claude/scripts/prompt_builder/library.py

from pathlib import Path
import json
from datetime import datetime

class TeamPromptLibrary:
    """Shared library of effective prompts for the team."""
    
    def __init__(self, library_path: Path):
        self.library_path = library_path
        self.prompts = self._load_library()
    
    def add_prompt(self, 
                   prompt: str,
                   category: str,
                   description: str,
                   author: str,
                   tags: list[str],
                   example_use_case: str):
        """Add a new prompt to the library."""
        
        entry = {
            "id": self._generate_id(),
            "prompt": prompt,
            "category": category,
            "description": description,
            "author": author,
            "tags": tags,
            "example_use_case": example_use_case,
            "created_at": datetime.now().isoformat(),
            "usage_count": 0,
            "avg_rating": 0.0,
            "ratings": []
        }
        
        self.prompts.append(entry)
        self._save_library()
    
    def search(self, query: str = None, 
               category: str = None,
               tags: list[str] = None) -> list[dict]:
        """Search the prompt library."""
        
        results = self.prompts
        
        if category:
            results = [p for p in results if p['category'] == category]
        
        if tags:
            results = [p for p in results 
                      if any(t in p['tags'] for t in tags)]
        
        if query:
            results = [p for p in results 
                      if query.lower() in p['description'].lower()
                      or query.lower() in p['prompt'].lower()]
        
        return sorted(results, key=lambda p: p['avg_rating'], reverse=True)
    
    def rate_prompt(self, prompt_id: str, rating: int, feedback: str = None):
        """Rate a prompt's effectiveness."""
        
        prompt = next((p for p in self.prompts if p['id'] == prompt_id), None)
        if prompt:
            prompt['ratings'].append({
                "rating": rating,
                "feedback": feedback,
                "timestamp": datetime.now().isoformat()
            })
            prompt['avg_rating'] = sum(r['rating'] for r in prompt['ratings']) / len(prompt['ratings'])
            prompt['usage_count'] += 1
            self._save_library()
    
    def get_top_prompts(self, n: int = 10) -> list[dict]:
        """Get top-rated prompts."""
        return sorted(self.prompts, 
                     key=lambda p: (p['avg_rating'], p['usage_count']), 
                     reverse=True)[:n]
```

#### 4. Auto-Prompt Optimizer
```python
# Automatically improve prompts that didn't work well
# File: .claude/scripts/prompt_builder/optimizer.py

class PromptOptimizer:
    """Automatically improves underperforming prompts."""
    
    OPTIMIZATION_RULES = [
        {
            "name": "add_context",
            "check": lambda p: "context" not in p.lower() and "using" not in p.lower(),
            "fix": lambda p: f"Context: [Add your tech stack here]\n\n{p}",
            "reason": "Adding context improves accuracy by 40%"
        },
        {
            "name": "add_constraints",
            "check": lambda p: "must" not in p.lower() and "should" not in p.lower(),
            "fix": lambda p: f"{p}\n\nConstraints:\n- [Add what to avoid]\n- [Add requirements]",
            "reason": "Constraints prevent unwanted solutions"
        },
        {
            "name": "add_example",
            "check": lambda p: "example" not in p.lower() and "```" not in p,
            "fix": lambda p: f"{p}\n\nExample of what I'm looking for:\n```\n[Add example here]\n```",
            "reason": "Examples are worth a thousand words"
        },
        {
            "name": "specify_output",
            "check": lambda p: "return" not in p.lower() and "output" not in p.lower(),
            "fix": lambda p: f"{p}\n\nExpected output format: [Describe what you want back]",
            "reason": "Specifying output format reduces iterations"
        }
    ]
    
    def optimize(self, prompt: str, 
                 previous_result: str = None,
                 feedback: str = None) -> dict:
        """Optimize a prompt based on rules and feedback."""
        
        suggestions = []
        optimized = prompt
        
        for rule in self.OPTIMIZATION_RULES:
            if rule['check'](prompt):
                suggestions.append({
                    "rule": rule['name'],
                    "reason": rule['reason'],
                    "original": prompt,
                    "improved": rule['fix'](prompt)
                })
        
        # If we have feedback about what went wrong, target that
        if feedback:
            targeted_fix = self._generate_targeted_fix(prompt, feedback)
            if targeted_fix:
                suggestions.insert(0, targeted_fix)
        
        return {
            "original": prompt,
            "suggestions": suggestions,
            "recommended": suggestions[0]['improved'] if suggestions else prompt,
            "improvement_count": len(suggestions)
        }
    
    def auto_retry(self, prompt: str, 
                   response: str,
                   expected: str) -> str:
        """Automatically generate an improved follow-up prompt."""
        
        return f"""
The previous response didn't quite match what I needed.

**What I got:**
{response[:500]}...

**What I actually wanted:**
{expected}

**Original request:**
{prompt}

Please try again with this clarification. Focus specifically on: {self._identify_gap(response, expected)}
"""
```

#### 5. Prompt Templates with Variables
```python
# Reusable prompt templates with fill-in variables
# File: .claude/scripts/prompt_builder/templates.py

from pathlib import Path
import re
from string import Template

class PromptTemplateEngine:
    """Manages reusable prompt templates with variables."""
    
    def __init__(self, templates_dir: Path):
        self.templates_dir = templates_dir
        self.templates = self._load_templates()
    
    def _load_templates(self) -> dict:
        """Load all templates from directory."""
        templates = {}
        
        for tmpl_file in self.templates_dir.glob("*.prompt"):
            name = tmpl_file.stem
            content = tmpl_file.read_text()
            metadata = self._parse_metadata(content)
            template_body = self._parse_body(content)
            
            templates[name] = {
                "metadata": metadata,
                "template": Template(template_body),
                "variables": self._extract_variables(template_body)
            }
        
        return templates
    
    def list_templates(self) -> list[dict]:
        """List available templates with their variables."""
        return [
            {
                "name": name,
                "description": t['metadata'].get('description', ''),
                "category": t['metadata'].get('category', 'general'),
                "variables": t['variables']
            }
            for name, t in self.templates.items()
        ]
    
    def fill_template(self, template_name: str, 
                      variables: dict) -> str:
        """Fill a template with provided variables."""
        
        template = self.templates.get(template_name)
        if not template:
            raise ValueError(f"Template '{template_name}' not found")
        
        # Validate all required variables are provided
        missing = set(template['variables']) - set(variables.keys())
        if missing:
            raise ValueError(f"Missing required variables: {missing}")
        
        return template['template'].safe_substitute(variables)
    
    def create_template(self, name: str, 
                        prompt: str,
                        description: str,
                        category: str):
        """Create a new template from a successful prompt."""
        
        # Auto-detect potential variables
        variables = self._suggest_variables(prompt)
        
        # Convert to template format
        template_content = f"""---
name: {name}
description: {description}
category: {category}
variables: {', '.join(variables)}
---

{prompt}
"""
        
        template_file = self.templates_dir / f"{name}.prompt"
        template_file.write_text(template_content)
        
        self.templates = self._load_templates()  # Reload


# Example template file: code_review.prompt
"""
---
name: code_review
description: Request a thorough code review
category: review
variables: language, code, focus_areas
---

Please review this $language code:

```$language
$code
```

Focus particularly on:
$focus_areas

Provide feedback in this format:
1. 🔴 Critical issues (must fix)
2. 🟡 Suggestions (should consider)
3. 🟢 Positive observations (what's done well)
"""
```

**Summary of Missing Features for 10/10:**
| Feature | Impact | Effort |
|---------|--------|--------|
| Interactive builder | Very High | Medium |
| Performance tracker | High | Medium |
| Team prompt library | High | Medium |
| Auto-optimizer | Very High | High |
| Template engine | High | Low |

---

## Other Cool Stuff

| Feature | Score | What It Does |
|---------|-------|--------------|
| [AI Pair Programming Method](./../methodologies/ai-pair-programming.md) | 8.6 | How to treat AI as your coding partner |
| [Feature Implementation Playbook](./../playbooks/implementing-new-feature.md) | 8.5 | Step-by-step guide to build new things |
| [.CLAUDE Template](./../templates/.CLAUDE-template) | 8.4 | Fill-in-the-blank setup for any project |
| [Model Nuances](./../model-nuances/claude-3-5-sonnet.md) | 8.2 | Understanding Claude's personality |
| [Template Philosophy](./../README.md) | 8.0 | Why quick notes beat perfect docs |

---

## What The Scores Mean

| Score | Meaning |
|-------|---------|
| 9.5-10 | 🔥 Exceptional - Best in class |
| 8.5-9.4 | ⭐ Excellent - Really impressive |
| 7.5-8.4 | 👍 Good - Solid and useful |
| 6.5-7.4 | 👌 Decent - Gets the job done |

---

## The Bottom Line

This repository is an **8.8/10** because it:

1. ✅ **Saves time** - Automation handles boring stuff
2. ✅ **Prevents mistakes** - Safety features catch errors
3. ✅ **Makes AI smarter** - Knowledge base improves answers
4. ✅ **Scales easily** - Sync to any project in seconds
5. ✅ **Keeps learning** - Living documentation that grows

---

*Ratings based on analyzing the repo's features, documentation, and tools.*
