---
name: performance-optimizer
description: "Identifies and fixes performance bottlenecks in code, databases, and APIs. Measures before and after to prove improvements."
category: development
risk: safe
source: community
date_added: "2026-03-05"
---

# Performance Optimizer

Find and fix performance bottlenecks. Measure, optimize, verify. Make it fast.

## When to Use This Skill

- App is slow or laggy
- User complains about performance
- Page load times are high
- API responses are slow
- Database queries take too long
- User mentions "slow", "lag", "performance", or "optimize"

## The Optimization Process

### 1. Measure First

Never optimize without measuring:

```javascript
// Measure execution time
console.time('operation');
await slowOperation();
console.timeEnd('operation'); // operation: 2341ms
```

**What to measure:**
- Page load time
- API response time
- Database query time
- Function execution time
- Memory usage
- Network requests

### 2. Find the Bottleneck

Use profiling tools to find the slow parts:

**Browser:**
```
DevTools → Performance tab → Record → Stop
Look for long tasks (red bars)
```

**Node.js:**
```bash
node --prof app.js
node --prof-process isolate-*.log > profile.txt
```

**Database:**
```sql
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';
```

### 3. Optimize

Fix the slowest thing first (biggest impact).

## Common Optimizations

### Database Queries

**Problem: N+1 Queries**
```javascript
// Bad: N+1 queries
const users = await db.users.find();
for (const user of users) {
  user.posts = await db.posts.find({ userId: user.id }); // N queries
}

// Good: Single query with JOIN
const users = await db.users.find()
  .populate('posts'); // 1 query
```

**Problem: Missing Index**
```sql
-- Check slow query
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
-- Shows: Seq Scan (bad)

-- Add index
CREATE INDEX idx_users_email ON users(email);

-- Check again
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
-- Shows: Index Scan (good)
```

**Problem: SELECT ***
```javascript
// Bad: Fetches all columns
const users = await db.query('SELECT * FROM users');

// Good: Only needed columns
const users = await db.query('SELECT id, name, email FROM users');
```

**Problem: No Pagination**
```javascript
// Bad: Returns all records
const users = await db.users.find();

// Good: Paginated
const users = await db.users.find()
  .limit(20)
  .skip((page - 1) * 20);
```

### API Performance

**Problem: No Caching**
```javascript
// Bad: Hits database every time
app.get('/api/stats', async (req, res) => {
  const stats = await db.stats.calculate(); // Slow
  res.json(stats);
});

// Good: Cache for 5 minutes
const cache = new Map();
app.get('/api/stats', async (req, res) => {
  const cached = cache.get('stats');
  if (cached && Date.now() - cached.time < 300000) {
    return res.json(cached.data);
  }

  const stats = await db.stats.calculate();
  cache.set('stats', { data: stats, time: Date.now() });
  res.json(stats);
});
```

**Problem: Sequential Operations**
```javascript
// Bad: Sequential (slow)
const user = await getUser(id);
const posts = await getPosts(id);
const comments = await getComments(id);
// Total: 300ms + 200ms + 150ms = 650ms

// Good: Parallel (fast)
const [user, posts, comments] = await Promise.all([
  getUser(id),
  getPosts(id),
  getComments(id)
]);
// Total: max(300ms, 200ms, 150ms) = 300ms
```

**Problem: Large Payloads**
```javascript
// Bad: Returns everything
res.json(users); // 5MB response

// Good: Only needed fields
res.json(users.map(u => ({
  id: u.id,
  name: u.name,
  email: u.email
}))); // 500KB response
```

### Frontend Performance

**Problem: Unnecessary Re-renders**
```javascript
// Bad: Re-renders on every parent update
function UserList({ users }) {
  return users.map(user => <UserCard user={user} />);
}

// Good: Memoized
const UserCard = React.memo(({ user }) => {
  return <div>{user.name}</div>;
});
```

**Problem: Large Bundle**
```javascript
// Bad: Imports entire library
import _ from 'lodash'; // 70KB

// Good: Import only what you need
import debounce from 'lodash/debounce'; // 2KB
```

**Problem: No Code Splitting**
```javascript
// Bad: Everything in one bundle
import HeavyComponent from './HeavyComponent';

// Good: Lazy load
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
```

**Problem: Unoptimized Images**
```html
<!-- Bad: Large image -->
<img src="photo.jpg" /> <!-- 5MB -->

<!-- Good: Optimized and responsive -->
<img
  src="photo-small.webp"
  srcset="photo-small.webp 400w, photo-large.webp 800w"
  loading="lazy"
  width="400"
  height="300"
/> <!-- 50KB -->
```

### Algorithm Optimization

**Problem: Inefficient Algorithm**
```javascript
// Bad: O(n²) - nested loops
function findDuplicates(arr) {
  const duplicates = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) duplicates.push(arr[i]);
    }
  }
  return duplicates;
}

// Good: O(n) - single pass with Set
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) duplicates.add(item);
    seen.add(item);
  }
  return Array.from(duplicates);
}
```

**Problem: Repeated Calculations**
```javascript
// Bad: Calculates every time
function getTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
// Called 100 times in render

// Good: Memoized
const getTotal = useMemo(() => {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}, [items]);
```

### Memory Optimization

**Problem: Memory Leak**
```javascript
// Bad: Event listener not cleaned up
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  // Memory leak!
}, []);

// Good: Cleanup
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, []);
```

**Problem: Large Data in Memory**
```javascript
// Bad: Loads entire file into memory
const data = fs.readFileSync('huge-file.txt'); // 1GB

// Good: Stream it
const stream = fs.createReadStream('huge-file.txt');
stream.on('data', chunk => process(chunk));
```

## Measuring Impact

Always measure before and after:

```javascript
// Before optimization
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 2341ms

// After optimization (added index)
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 23ms

// Improvement: 100x faster!
```

## Performance Budgets

Set targets:

```
Page Load: < 2 seconds
API Response: < 200ms
Database Query: < 50ms
Bundle Size: < 200KB
Time to Interactive: < 3 seconds
```

## Tools

**Browser:**
- Chrome DevTools Performance tab
- Lighthouse (audit)
- Network tab (waterfall)

**Node.js:**
- `node --prof` (profiling)
- `clinic` (diagnostics)
- `autocannon` (load testing)

**Database:**
- `EXPLAIN ANALYZE` (query plans)
- Slow query log
- Database profiler

**Monitoring:**
- New Relic
- Datadog
- Sentry Performance

## Quick Wins

Easy optimizations with big impact:

1. **Add database indexes** on frequently queried columns
2. **Enable gzip compression** on server
3. **Add caching** for expensive operations
4. **Lazy load** images and heavy components
5. **Use CDN** for static assets
6. **Minify and compress** JavaScript/CSS
7. **Remove unused dependencies**
8. **Use pagination** instead of loading all data
9. **Optimize images** (WebP, proper sizing)
10. **Enable HTTP/2** on server

## Optimization Checklist

- [ ] Measured current performance
- [ ] Identified bottleneck
- [ ] Applied optimization
- [ ] Measured improvement
- [ ] Verified functionality still works
- [ ] No new bugs introduced
- [ ] Documented the change

## When NOT to Optimize

- Premature optimization (optimize when it's actually slow)
- Micro-optimizations (save 1ms when page takes 5 seconds)
- Readable code is more important than tiny speed gains
- If it's already fast enough

## Key Principles

- Measure before optimizing
- Fix the biggest bottleneck first
- Measure after to prove improvement
- Don't sacrifice readability for tiny gains
- Profile in production-like environment
- Consider the 80/20 rule (20% of code causes 80% of slowness)

## Related Skills

- `@database-design` - Query optimization
- `@codebase-audit-pre-push` - Code review
- `@bug-hunter` - Debugging

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: performance-profiling
description: "Performance profiling principles. Measurement, analysis, and optimization techniques."
risk: critical
source: community
date_added: "2026-02-27"
---

# Performance Profiling

> Measure, analyze, optimize - in that order.

## 🔧 Runtime Scripts

**Execute these for automated profiling:**

| Script | Purpose | Usage |
|--------|---------|-------|
| `scripts/lighthouse_audit.py` | Lighthouse performance audit | `python scripts/lighthouse_audit.py https://example.com` |

---

## 1. Core Web Vitals

### Targets

| Metric | Good | Poor | Measures |
|--------|------|------|----------|
| **LCP** | < 2.5s | > 4.0s | Loading |
| **INP** | < 200ms | > 500ms | Interactivity |
| **CLS** | < 0.1 | > 0.25 | Stability |

### When to Measure

| Stage | Tool |
|-------|------|
| Development | Local Lighthouse |
| CI/CD | Lighthouse CI |
| Production | RUM (Real User Monitoring) |

---

## 2. Profiling Workflow

### The 4-Step Process

```
1. BASELINE → Measure current state
2. IDENTIFY → Find the bottleneck
3. FIX → Make targeted change
4. VALIDATE → Confirm improvement
```

### Profiling Tool Selection

| Problem | Tool |
|---------|------|
| Page load | Lighthouse |
| Bundle size | Bundle analyzer |
| Runtime | DevTools Performance |
| Memory | DevTools Memory |
| Network | DevTools Network |

---

## 3. Bundle Analysis

### What to Look For

| Issue | Indicator |
|-------|-----------|
| Large dependencies | Top of bundle |
| Duplicate code | Multiple chunks |
| Unused code | Low coverage |
| Missing splits | Single large chunk |

### Optimization Actions

| Finding | Action |
|---------|--------|
| Big library | Import specific modules |
| Duplicate deps | Dedupe, update versions |
| Route in main | Code split |
| Unused exports | Tree shake |

---

## 4. Runtime Profiling

### Performance Tab Analysis

| Pattern | Meaning |
|---------|---------|
| Long tasks (>50ms) | UI blocking |
| Many small tasks | Possible batching opportunity |
| Layout/paint | Rendering bottleneck |
| Script | JavaScript execution |

### Memory Tab Analysis

| Pattern | Meaning |
|---------|---------|
| Growing heap | Possible leak |
| Large retained | Check references |
| Detached DOM | Not cleaned up |

---

## 5. Common Bottlenecks

### By Symptom

| Symptom | Likely Cause |
|---------|--------------|
| Slow initial load | Large JS, render blocking |
| Slow interactions | Heavy event handlers |
| Jank during scroll | Layout thrashing |
| Growing memory | Leaks, retained refs |

---

## 6. Quick Win Priorities

| Priority | Action | Impact |
|----------|--------|--------|
| 1 | Enable compression | High |
| 2 | Lazy load images | High |
| 3 | Code split routes | High |
| 4 | Cache static assets | Medium |
| 5 | Optimize images | Medium |

---

## 7. Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Guess at problems | Profile first |
| Micro-optimize | Fix biggest issue |
| Optimize early | Optimize when needed |
| Ignore real users | Use RUM data |

---

> **Remember:** The fastest code is code that doesn't run. Remove before optimizing.

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: performance-testing-review-ai-review
description: "You are an expert AI-powered code review specialist combining automated static analysis, intelligent pattern recognition, and modern DevOps practices. Leverage AI tools (GitHub Copilot, Qodo, GPT-5, C"
risk: critical
source: community
date_added: "2026-02-27"
---

# AI-Powered Code Review Specialist

You are an expert AI-powered code review specialist combining automated static analysis, intelligent pattern recognition, and modern DevOps practices. Leverage AI tools (GitHub Copilot, Qodo, GPT-5, Claude 4.5 Sonnet) with battle-tested platforms (SonarQube, CodeQL, Semgrep) to identify bugs, vulnerabilities, and performance issues.

## Use this skill when

- Working on ai-powered code review specialist tasks or workflows
- Needing guidance, best practices, or checklists for ai-powered code review specialist

## Do not use this skill when

- The task is unrelated to ai-powered code review specialist
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Context

Multi-layered code review workflows integrating with CI/CD pipelines, providing instant feedback on pull requests with human oversight for architectural decisions. Reviews across 30+ languages combine rule-based analysis with AI-assisted contextual understanding.

## Requirements

Review: **$ARGUMENTS**

Perform comprehensive analysis: security, performance, architecture, maintainability, testing, and AI/ML-specific concerns. Generate review comments with line references, code examples, and actionable recommendations.

## Automated Code Review Workflow

### Initial Triage
1. Parse diff to determine modified files and affected components
2. Match file types to optimal static analysis tools
3. Scale analysis based on PR size (superficial >1000 lines, deep <200 lines)
4. Classify change type: feature, bug fix, refactoring, or breaking change

### Multi-Tool Static Analysis
Execute in parallel:
- **CodeQL**: Deep vulnerability analysis (SQL injection, XSS, auth bypasses)
- **SonarQube**: Code smells, complexity, duplication, maintainability
- **Semgrep**: Organization-specific rules and security policies
- **Snyk/Dependabot**: Supply chain security
- **GitGuardian/TruffleHog**: Secret detection

### AI-Assisted Review
```python
# Context-aware review prompt for Claude 4.5 Sonnet
review_prompt = f"""
You are reviewing a pull request for a {language} {project_type} application.

**Change Summary:** {pr_description}
**Modified Code:** {code_diff}
**Static Analysis:** {sonarqube_issues}, {codeql_alerts}
**Architecture:** {system_architecture_summary}

Focus on:
1. Security vulnerabilities missed by static tools
2. Performance implications at scale
3. Edge cases and error handling gaps
4. API contract compatibility
5. Testability and missing coverage
6. Architectural alignment

For each issue:
- Specify file path and line numbers
- Classify severity: CRITICAL/HIGH/MEDIUM/LOW
- Explain problem (1-2 sentences)
- Provide concrete fix example
- Link relevant documentation

Format as JSON array.
"""
```

### Model Selection (2025)
- **Fast reviews (<200 lines)**: GPT-4o-mini or Claude 4.5 Haiku
- **Deep reasoning**: Claude 4.5 Sonnet or GPT-4.5 (200K+ tokens)
- **Code generation**: GitHub Copilot or Qodo
- **Multi-language**: Qodo or CodeAnt AI (30+ languages)

### Review Routing
```typescript
interface ReviewRoutingStrategy {
  async routeReview(pr: PullRequest): Promise<ReviewEngine> {
    const metrics = await this.analyzePRComplexity(pr);

    if (metrics.filesChanged > 50 || metrics.linesChanged > 1000) {
      return new HumanReviewRequired("Too large for automation");
    }

    if (metrics.securitySensitive || metrics.affectsAuth) {
      return new AIEngine("claude-3.7-sonnet", {
        temperature: 0.1,
        maxTokens: 4000,
        systemPrompt: SECURITY_FOCUSED_PROMPT
      });
    }

    if (metrics.testCoverageGap > 20) {
      return new QodoEngine({ mode: "test-generation", coverageTarget: 80 });
    }

    return new AIEngine("gpt-4o", { temperature: 0.3, maxTokens: 2000 });
  }
}
```

## Architecture Analysis

### Architectural Coherence
1. **Dependency Direction**: Inner layers don't depend on outer layers
2. **SOLID Principles**:
   - Single Responsibility, Open/Closed, Liskov Substitution
   - Interface Segregation, Dependency Inversion
3. **Anti-patterns**:
   - Singleton (global state), God objects (>500 lines, >20 methods)
   - Anemic models, Shotgun surgery

### Microservices Review
```go
type MicroserviceReviewChecklist struct {
    CheckServiceCohesion       bool  // Single capability per service?
    CheckDataOwnership         bool  // Each service owns database?
    CheckAPIVersioning         bool  // Semantic versioning?
    CheckBackwardCompatibility bool  // Breaking changes flagged?
    CheckCircuitBreakers       bool  // Resilience patterns?
    CheckIdempotency           bool  // Duplicate event handling?
}

func (r *MicroserviceReviewer) AnalyzeServiceBoundaries(code string) []Issue {
    issues := []Issue{}

    if detectsSharedDatabase(code) {
        issues = append(issues, Issue{
            Severity: "HIGH",
            Category: "Architecture",
            Message: "Services sharing database violates bounded context",
            Fix: "Implement database-per-service with eventual consistency",
        })
    }

    if hasBreakingAPIChanges(code) && !hasDeprecationWarnings(code) {
        issues = append(issues, Issue{
            Severity: "CRITICAL",
            Category: "API Design",
            Message: "Breaking change without deprecation period",
            Fix: "Maintain backward compatibility via versioning (v1, v2)",
        })
    }

    return issues
}
```

## Security Vulnerability Detection

### Multi-Layered Security
**SAST Layer**: CodeQL, Semgrep, Bandit/Brakeman/Gosec

**AI-Enhanced Threat Modeling**:
```python
security_analysis_prompt = """
Analyze authentication code for vulnerabilities:
{code_snippet}

Check for:
1. Authentication bypass, broken access control (IDOR)
2. JWT token validation flaws
3. Session fixation/hijacking, timing attacks
4. Missing rate limiting, insecure password storage
5. Credential stuffing protection gaps

Provide: CWE identifier, CVSS score, exploit scenario, remediation code
"""

findings = claude.analyze(security_analysis_prompt, temperature=0.1)
```

**Secret Scanning**:
```bash
trufflehog git file://. --json | \
  jq '.[] | select(.Verified == true) | {
    secret_type: .DetectorName,
    file: .SourceMetadata.Data.Filename,
    severity: "CRITICAL"
  }'
```

### OWASP Top 10 (2025)
1. **A01 - Broken Access Control**: Missing authorization, IDOR
2. **A02 - Cryptographic Failures**: Weak hashing, insecure RNG
3. **A03 - Injection**: SQL, NoSQL, command injection via taint analysis
4. **A04 - Insecure Design**: Missing threat modeling
5. **A05 - Security Misconfiguration**: Default credentials
6. **A06 - Vulnerable Components**: Snyk/Dependabot for CVEs
7. **A07 - Authentication Failures**: Weak session management
8. **A08 - Data Integrity Failures**: Unsigned JWTs
9. **A09 - Logging Failures**: Missing audit logs
10. **A10 - SSRF**: Unvalidated user-controlled URLs

## Performance Review

### Performance Profiling
```javascript
class PerformanceReviewAgent {
  async analyzePRPerformance(prNumber) {
    const baseline = await this.loadBaselineMetrics('main');
    const prBranch = await this.runBenchmarks(`pr-${prNumber}`);

    const regressions = this.detectRegressions(baseline, prBranch, {
      cpuThreshold: 10, memoryThreshold: 15, latencyThreshold: 20
    });

    if (regressions.length > 0) {
      await this.postReviewComment(prNumber, {
        severity: 'HIGH',
        title: '⚠ Performance Regression Detected',
        body: this.formatRegressionReport(regressions),
        suggestions: await this.aiGenerateOptimizations(regressions)
      });
    }
  }
}
```

### Scalability Red Flags
- **N+1 Queries**, **Missing Indexes**, **Synchronous External Calls**
- **In-Memory State**, **Unbounded Collections**, **Missing Pagination**
- **No Connection Pooling**, **No Rate Limiting**

```python
def detect_n_plus_1_queries(code_ast):
    issues = []
    for loop in find_loops(code_ast):
        db_calls = find_database_calls_in_scope(loop.body)
        if len(db_calls) > 0:
            issues.append({
                'severity': 'HIGH',
                'line': loop.line_number,
                'message': f'N+1 query: {len(db_calls)} DB calls in loop',
                'fix': 'Use eager loading (JOIN) or batch loading'
            })
    return issues
```

## Review Comment Generation

### Structured Format
```typescript
interface ReviewComment {
  path: string; line: number;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: 'Security' | 'Performance' | 'Bug' | 'Maintainability';
  title: string; description: string;
  codeExample?: string; references?: string[];
  autoFixable: boolean; cwe?: string; cvss?: number;
  effort: 'trivial' | 'easy' | 'medium' | 'hard';
}

const comment: ReviewComment = {
  path: "src/auth/login.ts", line: 42,
  severity: "CRITICAL", category: "Security",
  title: "SQL Injection in Login Query",
  description: `String concatenation with user input enables SQL injection.
**Attack Vector:** Input 'admin' OR '1'='1' bypasses authentication.
**Impact:** Complete auth bypass, unauthorized access.`,
  codeExample: `
// ❌ Vulnerable
const query = \`SELECT * FROM users WHERE username = '\${username}'\`;

// ✅ Secure
const query = 'SELECT * FROM users WHERE username = ?';
const result = await db.execute(query, [username]);
  `,
  references: ["https://cwe.mitre.org/data/definitions/89.html"],
  autoFixable: false, cwe: "CWE-89", cvss: 9.8, effort: "easy"
};
```

## CI/CD Integration

### GitHub Actions
```yaml
name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Static Analysis
        run: |
          sonar-scanner -Dsonar.pullrequest.key=${{ github.event.number }}
          codeql database create codeql-db --language=javascript,python
          semgrep scan --config=auto --sarif --output=semgrep.sarif

      - name: AI-Enhanced Review (GPT-5)
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          python scripts/ai_review.py \
            --pr-number ${{ github.event.number }} \
            --model gpt-4o \
            --static-analysis-results codeql.sarif,semgrep.sarif

      - name: Post Comments
        uses: actions/github-script@v7
        with:
          script: |
            const comments = JSON.parse(fs.readFileSync('review-comments.json'));
            for (const comment of comments) {
              await github.rest.pulls.createReviewComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: context.issue.number,
                body: comment.body, path: comment.path, line: comment.line
              });
            }

      - name: Quality Gate
        run: |
          CRITICAL=$(jq '[.[] | select(.severity == "CRITICAL")] | length' review-comments.json)
          if [ $CRITICAL -gt 0 ]; then
            echo "❌ Found $CRITICAL critical issues"
            exit 1
          fi
```

## Complete Example: AI Review Automation

```python
#!/usr/bin/env python3
import os, json, subprocess
from dataclasses import dataclass
from typing import List, Dict, Any
from anthropic import Anthropic

@dataclass
class ReviewIssue:
    file_path: str; line: int; severity: str
    category: str; title: str; description: str
    code_example: str = ""; auto_fixable: bool = False

class CodeReviewOrchestrator:
    def __init__(self, pr_number: int, repo: str):
        self.pr_number = pr_number; self.repo = repo
        self.github_token = os.environ['GITHUB_TOKEN']
        self.anthropic_client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])
        self.issues: List[ReviewIssue] = []

    def run_static_analysis(self) -> Dict[str, Any]:
        results = {}

        # SonarQube
        subprocess.run(['sonar-scanner', f'-Dsonar.projectKey={self.repo}'], check=True)

        # Semgrep
        semgrep_output = subprocess.check_output(['semgrep', 'scan', '--config=auto', '--json'])
        results['semgrep'] = json.loads(semgrep_output)

        return results

    def ai_review(self, diff: str, static_results: Dict) -> List[ReviewIssue]:
        prompt = f"""Review this PR comprehensively.

**Diff:** {diff[:15000]}
**Static Analysis:** {json.dumps(static_results, indent=2)[:5000]}

Focus: Security, Performance, Architecture, Bug risks, Maintainability

Return JSON array:
[{{
  "file_path": "src/auth.py", "line": 42, "severity": "CRITICAL",
  "category": "Security", "title": "Brief summary",
  "description": "Detailed explanation", "code_example": "Fix code"
}}]
"""

        response = self.anthropic_client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=8000, temperature=0.2,
            messages=[{"role": "user", "content": prompt}]
        )

        content = response.content[0].text
        if '```json' in content:
            content = content.split('```json')[1].split('```')[0]

        return [ReviewIssue(**issue) for issue in json.loads(content.strip())]

    def post_review_comments(self, issues: List[ReviewIssue]):
        summary = "## 🤖 AI Code Review\n\n"
        by_severity = {}
        for issue in issues:
            by_severity.setdefault(issue.severity, []).append(issue)

        for severity in ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']:
            count = len(by_severity.get(severity, []))
            if count > 0:
                summary += f"- **{severity}**: {count}\n"

        critical_count = len(by_severity.get('CRITICAL', []))
        review_data = {
            'body': summary,
            'event': 'REQUEST_CHANGES' if critical_count > 0 else 'COMMENT',
            'comments': [issue.to_github_comment() for issue in issues]
        }

        # Post to GitHub API
        print(f"✅ Posted review with {len(issues)} comments")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--pr-number', type=int, required=True)
    parser.add_argument('--repo', required=True)
    args = parser.parse_args()

    reviewer = CodeReviewOrchestrator(args.pr_number, args.repo)
    static_results = reviewer.run_static_analysis()
    diff = reviewer.get_pr_diff()
    ai_issues = reviewer.ai_review(diff, static_results)
    reviewer.post_review_comments(ai_issues)
```

## Summary

Comprehensive AI code review combining:
1. Multi-tool static analysis (SonarQube, CodeQL, Semgrep)
2. State-of-the-art LLMs (GPT-5, Claude 4.5 Sonnet)
3. Seamless CI/CD integration (GitHub Actions, GitLab, Azure DevOps)
4. 30+ language support with language-specific linters
5. Actionable review comments with severity and fix examples
6. DORA metrics tracking for review effectiveness
7. Quality gates preventing low-quality code
8. Auto-test generation via Qodo/CodiumAI

Use this tool to transform code review from manual process to automated AI-assisted quality assurance catching issues early with instant feedback.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: performance-testing-review-multi-agent-review
description: "Use when working with performance testing review multi agent review"
risk: critical
source: community
date_added: "2026-02-27"
---

# Multi-Agent Code Review Orchestration Tool

## Use this skill when

- Working on multi-agent code review orchestration tool tasks or workflows
- Needing guidance, best practices, or checklists for multi-agent code review orchestration tool

## Do not use this skill when

- The task is unrelated to multi-agent code review orchestration tool
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Role: Expert Multi-Agent Review Orchestration Specialist

A sophisticated AI-powered code review system designed to provide comprehensive, multi-perspective analysis of software artifacts through intelligent agent coordination and specialized domain expertise.

## Context and Purpose

The Multi-Agent Review Tool leverages a distributed, specialized agent network to perform holistic code assessments that transcend traditional single-perspective review approaches. By coordinating agents with distinct expertise, we generate a comprehensive evaluation that captures nuanced insights across multiple critical dimensions:

- **Depth**: Specialized agents dive deep into specific domains
- **Breadth**: Parallel processing enables comprehensive coverage
- **Intelligence**: Context-aware routing and intelligent synthesis
- **Adaptability**: Dynamic agent selection based on code characteristics

## Tool Arguments and Configuration

### Input Parameters
- `$ARGUMENTS`: Target code/project for review
  - Supports: File paths, Git repositories, code snippets
  - Handles multiple input formats
  - Enables context extraction and agent routing

### Agent Types
1. Code Quality Reviewers
2. Security Auditors
3. Architecture Specialists
4. Performance Analysts
5. Compliance Validators
6. Best Practices Experts

## Multi-Agent Coordination Strategy

### 1. Agent Selection and Routing Logic
- **Dynamic Agent Matching**:
  - Analyze input characteristics
  - Select most appropriate agent types
  - Configure specialized sub-agents dynamically
- **Expertise Routing**:
  ```python
  def route_agents(code_context):
      agents = []
      if is_web_application(code_context):
          agents.extend([
              "security-auditor",
              "web-architecture-reviewer"
          ])
      if is_performance_critical(code_context):
          agents.append("performance-analyst")
      return agents
  ```

### 2. Context Management and State Passing
- **Contextual Intelligence**:
  - Maintain shared context across agent interactions
  - Pass refined insights between agents
  - Support incremental review refinement
- **Context Propagation Model**:
  ```python
  class ReviewContext:
      def __init__(self, target, metadata):
          self.target = target
          self.metadata = metadata
          self.agent_insights = {}

      def update_insights(self, agent_type, insights):
          self.agent_insights[agent_type] = insights
  ```

### 3. Parallel vs Sequential Execution
- **Hybrid Execution Strategy**:
  - Parallel execution for independent reviews
  - Sequential processing for dependent insights
  - Intelligent timeout and fallback mechanisms
- **Execution Flow**:
  ```python
  def execute_review(review_context):
      # Parallel independent agents
      parallel_agents = [
          "code-quality-reviewer",
          "security-auditor"
      ]

      # Sequential dependent agents
      sequential_agents = [
          "architecture-reviewer",
          "performance-optimizer"
      ]
  ```

### 4. Result Aggregation and Synthesis
- **Intelligent Consolidation**:
  - Merge insights from multiple agents
  - Resolve conflicting recommendations
  - Generate unified, prioritized report
- **Synthesis Algorithm**:
  ```python
  def synthesize_review_insights(agent_results):
      consolidated_report = {
          "critical_issues": [],
          "important_issues": [],
          "improvement_suggestions": []
      }
      # Intelligent merging logic
      return consolidated_report
  ```

### 5. Conflict Resolution Mechanism
- **Smart Conflict Handling**:
  - Detect contradictory agent recommendations
  - Apply weighted scoring
  - Escalate complex conflicts
- **Resolution Strategy**:
  ```python
  def resolve_conflicts(agent_insights):
      conflict_resolver = ConflictResolutionEngine()
      return conflict_resolver.process(agent_insights)
  ```

### 6. Performance Optimization
- **Efficiency Techniques**:
  - Minimal redundant processing
  - Cached intermediate results
  - Adaptive agent resource allocation
- **Optimization Approach**:
  ```python
  def optimize_review_process(review_context):
      return ReviewOptimizer.allocate_resources(review_context)
  ```

### 7. Quality Validation Framework
- **Comprehensive Validation**:
  - Cross-agent result verification
  - Statistical confidence scoring
  - Continuous learning and improvement
- **Validation Process**:
  ```python
  def validate_review_quality(review_results):
      quality_score = QualityScoreCalculator.compute(review_results)
      return quality_score > QUALITY_THRESHOLD
  ```

## Example Implementations

### 1. Parallel Code Review Scenario
```python
multi_agent_review(
    target="/path/to/project",
    agents=[
        {"type": "security-auditor", "weight": 0.3},
        {"type": "architecture-reviewer", "weight": 0.3},
        {"type": "performance-analyst", "weight": 0.2}
    ]
)
```

### 2. Sequential Workflow
```python
sequential_review_workflow = [
    {"phase": "design-review", "agent": "architect-reviewer"},
    {"phase": "implementation-review", "agent": "code-quality-reviewer"},
    {"phase": "testing-review", "agent": "test-coverage-analyst"},
    {"phase": "deployment-readiness", "agent": "devops-validator"}
]
```

### 3. Hybrid Orchestration
```python
hybrid_review_strategy = {
    "parallel_agents": ["security", "performance"],
    "sequential_agents": ["architecture", "compliance"]
}
```

## Reference Implementations

1. **Web Application Security Review**
2. **Microservices Architecture Validation**

## Best Practices and Considerations

- Maintain agent independence
- Implement robust error handling
- Use probabilistic routing
- Support incremental reviews
- Ensure privacy and security

## Extensibility

The tool is designed with a plugin-based architecture, allowing easy addition of new agent types and review strategies.

## Invocation

Target for review: $ARGUMENTS

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: permission-manager
version: 1.0.0
description: "Manage opencode permissions: review always-allow lists, suggest safe read-only commands, configure permission patterns"
risk: critical
source: community
source_type: community
source_repo: mskadu/opencode-agent-skills
license: MIT
license_source: "https://github.com/mskadu/opencode-agent-skills/blob/main/LICENSE"
date_added: "2026-06-05"
---

## What I do
- Review and summarize currently always-allowed commands
- Suggest safe read-only commands for auto-approval
- Add or remove commands from the allow list in opencode.json
- Configure skill-level permissions (allow/deny/ask) with wildcard patterns
- Audit permission configs for security and usability

## When to Use
Use this when optimizing opencode's permission settings, reviewing allowed commands, or configuring skill access controls.

## Workflow Steps

1. **Read current config**: Load `~/.config/opencode/opencode.json` or project-level `opencode.json`
2. **Summarize permissions**: Identify currently allowed commands and skill permissions
3. **Suggest additions**: Propose safe read-only commands for auto-allow (see recommended list below)
4. **Apply changes**: Edit the config to add/remove permission entries
5. **Validate**: Ensure JSON is valid after changes

Complements opencode's built-in allow/deny/ask permissions by auditing current config and recommending adjustments through conversation.

## Key Rules
- Never allow commands that modify files, commit, push, or change system state
- Prefer exact command entries such as `git status --short`, `git diff --stat`, and `ls -la`
- Avoid trailing wildcards such as `git status*` unless the expanded command family has been manually reviewed as read-only
- Confirm with user before modifying permission config
- Distinguish between bash command permissions and skill permissions
- Keep config organized: group related commands together

## Limitations

- This skill is scoped to opencode permission configuration and should not modify other agent hosts' permission stores.
- Treat all write-capable command permissions as high-risk; review them manually even when a pattern looks narrow.

## How to trigger me

Use the Task tool with the `permission-manager` subagent type:

```
/permissions
```

Or in natural language, ask opencode to "manage opencode permissions" or "review allowed commands".


---
name: personal-tool-builder
description: Expert in building custom tools that solve your own problems first.
  The best products often start as personal tools - scratch your own itch, build
  for yourself, then discover others have the same itch.
risk: critical
source: vibeship-spawner-skills (Apache 2.0)
date_added: 2026-02-27
---

# Personal Tool Builder

Expert in building custom tools that solve your own problems first. The best products
often start as personal tools - scratch your own itch, build for yourself, then
discover others have the same itch. Covers rapid prototyping, local-first apps,
CLI tools, scripts that grow into products, and the art of dogfooding.

**Role**: Personal Tool Architect

You believe the best tools come from real problems. You've built dozens of
personal tools - some stayed personal, others became products used by thousands.
You know that building for yourself means you have perfect product-market fit
with at least one user. You build fast, iterate constantly, and only polish
what proves useful.

### Expertise

- Rapid prototyping
- CLI development
- Local-first architecture
- Script automation
- Problem identification
- Tool evolution

## Capabilities

- Personal productivity tools
- Scratch-your-own-itch methodology
- Rapid prototyping for personal use
- CLI tool development
- Local-first applications
- Script-to-product evolution
- Dogfooding practices
- Personal automation

## Patterns

### Scratch Your Own Itch

Building from personal pain points

**When to use**: When starting any personal tool

## The Itch-to-Tool Process

### Identifying Real Itches
```
Good itches:
- "I do this manually 10x per day"
- "This takes me 30 minutes every time"
- "I wish X just did Y"
- "Why doesn't this exist?"

Bad itches (usually):
- "People should want this"
- "This would be cool"
- "There's a market for..."
- "AI could probably..."
```

### The 10-Minute Test
| Question | Answer |
|----------|--------|
| Can you describe the problem in one sentence? | Required |
| Do you experience this problem weekly? | Must be yes |
| Have you tried solving it manually? | Must have |
| Would you use this daily? | Should be yes |

### Start Ugly
```
Day 1: Script that solves YOUR problem
- No UI, just works
- Hardcoded paths, your data
- Zero error handling
- You understand every line

Week 1: Script that works reliably
- Handle your edge cases
- Add the features YOU need
- Still ugly, but robust

Month 1: Tool that might help others
- Basic docs (for future you)
- Config instead of hardcoding
- Consider sharing
```

### CLI Tool Architecture

Building command-line tools that last

**When to use**: When building terminal-based tools

## CLI Tool Stack

### Node.js CLI Stack
```javascript
// package.json
{
  "name": "my-tool",
  "version": "1.0.0",
  "bin": {
    "mytool": "./bin/cli.js"
  },
  "dependencies": {
    "commander": "^12.0.0",    // Argument parsing
    "chalk": "^5.3.0",          // Colors
    "ora": "^8.0.0",            // Spinners
    "inquirer": "^9.2.0",       // Interactive prompts
    "conf": "^12.0.0"           // Config storage
  }
}

// bin/cli.js
#!/usr/bin/env node
import { Command } from 'commander';
import chalk from 'chalk';

const program = new Command();

program
  .name('mytool')
  .description('What it does in one line')
  .version('1.0.0');

program
  .command('do-thing')
  .description('Does the thing')
  .option('-v, --verbose', 'Verbose output')
  .action(async (options) => {
    // Your logic here
  });

program.parse();
```

### Python CLI Stack
```python
# Using Click (recommended)
import click

@click.group()
def cli():
    """Tool description."""
    pass

@cli.command()
@click.option('--name', '-n', required=True)
@click.option('--verbose', '-v', is_flag=True)
def process(name, verbose):
    """Process something."""
    click.echo(f'Processing {name}')

if __name__ == '__main__':
    cli()
```

### Distribution
| Method | Complexity | Reach |
|--------|------------|-------|
| npm publish | Low | Node devs |
| pip install | Low | Python devs |
| Homebrew tap | Medium | Mac users |
| Binary release | Medium | Everyone |
| Docker image | Medium | Tech users |

### Local-First Apps

Apps that work offline and own your data

**When to use**: When building personal productivity apps

## Local-First Architecture

### Why Local-First for Personal Tools
```
Benefits:
- Works offline
- Your data stays yours
- No server costs
- Instant, no latency
- Works forever (no shutdown)

Trade-offs:
- Sync is hard
- No collaboration (initially)
- Platform-specific work
```

### Stack Options
| Stack | Best For | Complexity |
|-------|----------|------------|
| Electron + SQLite | Desktop apps | Medium |
| Tauri + SQLite | Lightweight desktop | Medium |
| Browser + IndexedDB | Web apps | Low |
| PWA + OPFS | Mobile-friendly | Low |
| CLI + JSON files | Scripts | Very Low |

### Simple Local Storage
```javascript
// For simple tools: JSON file storage
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';

const DATA_DIR = join(homedir(), '.mytool');
const DATA_FILE = join(DATA_DIR, 'data.json');

function loadData() {
  if (!existsSync(DATA_FILE)) return { items: [] };
  return JSON.parse(readFileSync(DATA_FILE, 'utf8'));
}

function saveData(data) {
  if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR);
  writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
}
```

### SQLite for More Complex Tools
```javascript
// better-sqlite3 for Node.js
import Database from 'better-sqlite3';
import { join } from 'path';
import { homedir } from 'os';

const db = new Database(join(homedir(), '.mytool', 'data.db'));

// Create tables on first run
db.exec(`
  CREATE TABLE IF NOT EXISTS items (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

// Fast synchronous queries
const items = db.prepare('SELECT * FROM items').all();
```

### Script to Product Evolution

Growing a script into a real product

**When to use**: When a personal tool shows promise

## Evolution Path

### Stage 1: Personal Script
```
Characteristics:
- Only you use it
- Hardcoded values
- No error handling
- Works on your machine

Time: Hours to days
```

### Stage 2: Shareable Tool
```
Add:
- README explaining what it does
- Basic error messages
- Config file instead of hardcoding
- Works on similar machines

Time: Days
```

### Stage 3: Public Tool
```
Add:
- Installation instructions
- Cross-platform support
- Proper error handling
- Version numbers
- Basic tests

Time: Week or two
```

### Stage 4: Product
```
Add:
- Landing page
- Documentation site
- User support channel
- Analytics (privacy-respecting)
- Payment integration (if monetizing)

Time: Weeks to months
```

### Signs You Should Productize
| Signal | Strength |
|--------|----------|
| Others asking for it | Strong |
| You use it daily | Strong |
| Solves $100+ problem | Strong |
| Others would pay | Very strong |
| Competition exists but sucks | Strong |
| You're embarrassed by it | Actually good |

## Sharp Edges

### Tool only works in your specific environment

Severity: MEDIUM

Situation: Script fails when you try to share it

Symptoms:
- Works on my machine
- Scripts failing for others
- Path not found errors
- Command not found errors

Why this breaks:
Hardcoded absolute paths.
Relies on your installed tools.
Assumes your OS/shell.
Uses your auth tokens.

Recommended fix:

## Making Tools Portable

### Common Portability Issues
| Issue | Fix |
|-------|-----|
| Hardcoded paths | Use ~ or env vars |
| Specific shell | Declare shell in shebang |
| Missing deps | Check and prompt to install |
| Auth tokens | Use config file or env |
| OS-specific | Test on other OS or use cross-platform libs |

### Path Portability
```javascript
// Bad
const dataFile = '~/data.json';

// Good
import { homedir } from 'os';
import { join } from 'path';
const dataFile = join(homedir(), '.mytool', 'data.json');
```

### Dependency Checking
```javascript
import { execSync } from 'child_process';

function checkDep(cmd, installHint) {
  try {
    execSync(`which ${cmd}`, { stdio: 'ignore' });
  } catch {
    console.error(`Missing: ${cmd}`);
    console.error(`Install: ${installHint}`);
    process.exit(1);
  }
}

checkDep('ffmpeg', 'brew install ffmpeg');
```

### Cross-Platform Considerations
```javascript
import { platform } from 'os';

const isWindows = platform() === 'win32';
const isMac = platform() === 'darwin';
const isLinux = platform() === 'linux';

// Path separator
import { sep } from 'path';
// Use sep instead of hardcoded / or \
```

### Configuration becomes unmanageable

Severity: MEDIUM

Situation: Too many config options making the tool unusable

Symptoms:
- Config file is huge
- Users confused by options
- You forget what options exist
- Every bug fix adds a flag

Why this breaks:
Adding options instead of opinions.
Fear of making decisions.
Every edge case becomes an option.
Config file larger than the tool.

Recommended fix:

## Taming Configuration

### The Config Hierarchy
```
Best to worst:
1. Smart defaults (no config needed)
2. Single config file
3. Environment variables
4. Command-line flags
5. Interactive prompts

Use sparingly:
6. Config directory with multiple files
7. Config inheritance/merging
```

### Opinionated Defaults
```javascript
// Instead of 10 options, pick reasonable defaults
const defaults = {
  outputDir: join(homedir(), '.mytool', 'output'),
  format: 'json',  // Not a flag, just pick one
  maxItems: 100,   // Good enough for most
  verbose: false
};

// Only expose what REALLY needs customization
// "Would I want to change this?" - not "Could someone?"
```

### Config File Pattern
```javascript
// ~/.mytool/config.json
// Keep it minimal
{
  "apiKey": "xxx",       // Actually needed
  "defaultProject": "main"  // Convenience
}

// Don't do this:
{
  "outputFormat": "json",
  "outputIndent": 2,
  "outputColorize": true,
  "logLevel": "info",
  "logFormat": "pretty",
  "logTimestamp": true,
  // ... 50 more options
}
```

### When to Add Options
| Add option if... | Don't add if... |
|------------------|-----------------|
| Users ask repeatedly | You imagine someone might want |
| Security/auth related | It's a "nice to have" |
| Fundamental behavior change | It's a micro-preference |
| Environment-specific | You can pick a good default |

### Personal tool becomes unmaintained

Severity: LOW

Situation: Tool you built is now broken and you don't want to fix it

Symptoms:
- Script hasn't run in months
- Don't remember how it works
- Dependencies outdated
- Workflow has changed

Why this breaks:
Built for old workflow.
Dependencies broke.
Lost interest.
No documentation for yourself.

Recommended fix:

## Sustainable Personal Tools

### Design for Abandonment
```
Assume future-you won't remember:
- Why you built this
- How it works
- Where the data is
- What the dependencies do

Build accordingly:
- README with WHY, not just WHAT
- Simple architecture
- Minimal dependencies
- Data in standard formats
```

### Minimal Dependency Strategy
| Approach | When to Use |
|----------|-------------|
| Zero deps | Simple scripts |
| Core deps only | CLI tools |
| Lock versions | Important tools |
| Bundle deps | Distribution |

### Self-Documenting Pattern
```javascript
#!/usr/bin/env node
/**
 * WHAT: Converts X to Y
 * WHY: Because Z process was manual
 * WHERE: Data in ~/.mytool/
 * DEPS: Needs ffmpeg installed
 *
 * Last used: 2024-01
 * Still works as of: 2024-01
 */

// Tool code here
```

### Graceful Degradation
```javascript
// When things break, fail helpfully
try {
  await runMainFeature();
} catch (err) {
  console.error('Tool broken. Error:', err.message);
  console.error('');
  console.error('Data location: ~/.mytool/data.json');
  console.error('You can manually access your data there.');
  process.exit(1);
}
```

### When to Let Go
```
Signs to abandon:
- Haven't used in 6+ months
- Problem no longer exists
- Better tool now exists
- Would rebuild differently

How to abandon gracefully:
- Archive in clear state
- Note why abandoned
- Export data to standard format
- Don't delete (might want later)
```

### Personal tools with security vulnerabilities

Severity: HIGH

Situation: Your personal tool exposes sensitive data or access

Symptoms:
- API keys in source code
- Tool accessible on network
- Credentials in git history
- Personal data exposed

Why this breaks:
"It's just for me" mentality.
Credentials in code.
No input validation.
Accidental exposure.

Recommended fix:

## Security in Personal Tools

### Common Mistakes
| Risk | Mitigation |
|------|------------|
| API keys in code | Use env vars or config file |
| Tool exposed on network | Bind to localhost only |
| No input validation | Validate even your own input |
| Logs contain secrets | Sanitize logging |
| Git commits with secrets | .gitignore config files |

### Credential Management
```javascript
// Never in code
const leakedToken = '[redacted API key]'; // BAD

// Environment variable
const API_KEY = process.env.MY_API_KEY;

// Config file (gitignored)
import { readFileSync } from 'fs';
const config = JSON.parse(
  readFileSync(join(homedir(), '.mytool', 'config.json'))
);
const API_KEY = config.apiKey;
```

### Localhost-Only Servers
```javascript
// If your tool has a web UI
import express from 'express';
const app = express();

// ALWAYS bind to localhost for personal tools
app.listen(3000, '127.0.0.1', () => {
  console.log('Running on http://localhost:3000');
});

// NEVER do this for personal tools:
// app.listen(3000, '0.0.0.0') // Exposes to network!
```

### Before Sharing
```
Checklist:
[ ] No hardcoded credentials
[ ] Config file is gitignored
[ ] README mentions credential setup
[ ] No personal paths in code
[ ] No sensitive data in repo
[ ] Reviewed git history for secrets
```

## Validation Checks

### Hardcoded Absolute Paths

Severity: MEDIUM

Message: Hardcoded absolute path - use homedir() or environment variables.

Fix action: Use os.homedir() or path.join for portable paths

### Hardcoded Credentials

Severity: CRITICAL

Message: Potential hardcoded credential - use environment variables or config file.

Fix action: Move to process.env.VAR or external config file (gitignored)

### Server Bound to All Interfaces

Severity: HIGH

Message: Server exposed to network - bind to localhost for personal tools.

Fix action: Use '127.0.0.1' or 'localhost' instead of '0.0.0.0'

### Missing Error Handling

Severity: MEDIUM

Message: Sync operation without error handling - wrap in try/catch.

Fix action: Add try/catch for graceful error messages

### CLI Without Help

Severity: LOW

Message: CLI has no help - future you will forget how to use it.

Fix action: Add .description() and --help to CLI commands

### Tool Without README

Severity: LOW

Message: No README - document for your future self.

Fix action: Add README with: what it does, why you built it, how to use it

### Debug Console Logs Left In

Severity: LOW

Message: Debug logging left in code - remove or use proper logging.

Fix action: Remove debug logs or use a proper logger with levels

### Script Missing Shebang

Severity: LOW

Message: Script missing shebang - won't execute directly.

Fix action: Add #!/usr/bin/env node (or python3) at top of file

### Tool Without Version

Severity: LOW

Message: No version tracking - will cause confusion when updating.

Fix action: Add version to package.json and --version flag

## Collaboration

### Delegation Triggers

- sell|monetize|SaaS|charge -> micro-saas-launcher (Productizing personal tool)
- browser extension|chrome extension -> browser-extension-builder (Building browser-based tool)
- automate|workflow|cron|trigger -> workflow-automation (Automation setup)
- API|server|database|postgres -> backend (Backend infrastructure)
- telegram bot -> telegram-bot-builder (Telegram-based tool)
- AI|GPT|Claude|LLM -> ai-wrapper-product (AI-powered tool)

### CLI Tool That Becomes Product

Skills: personal-tool-builder, micro-saas-launcher

Workflow:

```
1. Build CLI for yourself
2. Share with friends/colleagues
3. Get feedback and iterate
4. Add web UI (optional)
5. Set up payments
6. Launch publicly
```

### Personal Automation Stack

Skills: personal-tool-builder, workflow-automation, backend

Workflow:

```
1. Identify repetitive task
2. Build script to automate
3. Add triggers (cron, webhook)
4. Store results/logs
5. Monitor and iterate
```

### AI-Powered Personal Tool

Skills: personal-tool-builder, ai-wrapper-product

Workflow:

```
1. Identify task AI can help with
2. Build minimal wrapper
3. Tune prompts for your use case
4. Add to daily workflow
5. Consider sharing if useful
```

### Browser Tool to Extension

Skills: personal-tool-builder, browser-extension-builder

Workflow:

```
1. Build bookmarklet or userscript
2. Validate it solves the problem
3. Convert to proper extension
4. Add to Chrome/Firefox store
5. Share with others
```

## Related Skills

Works well with: `micro-saas-launcher`, `browser-extension-builder`, `workflow-automation`, `backend`

## When to Use
- User mentions or implies: build a tool
- User mentions or implies: personal tool
- User mentions or implies: scratch my itch
- User mentions or implies: solve my problem
- User mentions or implies: CLI tool
- User mentions or implies: local app
- User mentions or implies: automate my
- User mentions or implies: build for myself

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: phase-gated-debugging
description: "Use when debugging any bug. Enforces a 5-phase protocol where code edits are blocked until root cause is confirmed. Prevents premature fix attempts."
risk: safe
source: community
date_added: "2026-03-28"
---

# Phase-Gated Debugging

## Overview

AI coding agents see an error and immediately edit code. They guess at fixes, get it wrong, and spiral. This skill enforces a strict 5-phase protocol where you CANNOT edit source code until the root cause is identified and confirmed.

Based on [claude-debug](https://github.com/krabat-l/claude-debug) (full plugin with PreToolUse hook enforcement).

## When to Use
Use this skill when:

- a bug keeps getting "fixed" without resolving the underlying issue
- you need to slow an agent down and force disciplined debugging before code edits
- the failure is intermittent, a regression, performance-related, or otherwise hard to isolate
- you want an explicit user confirmation checkpoint before any fix is applied

## The Protocol

### Phase 1: REPRODUCE
Run the failing command/test. Capture the exact error. Run 2-3 times for consistency.
- Do NOT read source code
- Do NOT hypothesize
- Do NOT edit any files

### Phase 2: ISOLATE
Read code. Add diagnostic logging marked `// DEBUG`. Re-run with diagnostics. Binary search to narrow down.
- Only `// DEBUG` marked logging is allowed
- Do NOT fix the bug even if you see it

### Phase 3: ROOT CAUSE
Analyze WHY at the isolated location. Use "5 Whys" technique. Remove debug logging.

State: "This is my root cause analysis: [explanation]. Do you agree, or should I investigate further?"

**WAIT for user confirmation. Do NOT proceed without it.**

### Phase 4: FIX
Remove all `// DEBUG` lines. Apply minimal change addressing confirmed root cause.
- Only edit files related to root cause
- Do NOT refactor unrelated code

### Phase 5: VERIFY
Run original failing test — must pass. Run related tests. For intermittent bugs, run 5+ times.
If verification fails: root cause was wrong, go back to Phase 2.

## Bug-Type Strategies

| Type | Technique |
|------|-----------|
| Crash/Panic | Stack trace backward — trace the bad value to its source |
| Wrong Output | Binary search — log midpoint, halve search space each iteration |
| Intermittent | Compare passing vs failing run logs — find ordering divergence |
| Regression | `git bisect` — find the offending commit |
| Performance | Timing at stage boundaries — find the bottleneck |

## Key Rules

1. NEVER edit source code in phases 1-3 (except `// DEBUG` in phase 2)
2. NEVER proceed past phase 3 without user confirmation
3. ALWAYS reproduce before investigating
4. ALWAYS verify after fixing

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.