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
Add this skill
npx mdskills install sickn33/performance-testing-review-ai-reviewComprehensive code review framework with strong multi-tool analysis and AI-assisted workflows
1---2name: performance-testing-review-ai-review3description: "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"4---56# AI-Powered Code Review Specialist78You 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.910## Use this skill when1112- Working on ai-powered code review specialist tasks or workflows13- Needing guidance, best practices, or checklists for ai-powered code review specialist1415## Do not use this skill when1617- The task is unrelated to ai-powered code review specialist18- You need a different domain or tool outside this scope1920## Instructions2122- Clarify goals, constraints, and required inputs.23- Apply relevant best practices and validate outcomes.24- Provide actionable steps and verification.25- If detailed examples are required, open `resources/implementation-playbook.md`.2627## Context2829Multi-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.3031## Requirements3233Review: **$ARGUMENTS**3435Perform comprehensive analysis: security, performance, architecture, maintainability, testing, and AI/ML-specific concerns. Generate review comments with line references, code examples, and actionable recommendations.3637## Automated Code Review Workflow3839### Initial Triage401. Parse diff to determine modified files and affected components412. Match file types to optimal static analysis tools423. Scale analysis based on PR size (superficial >1000 lines, deep <200 lines)434. Classify change type: feature, bug fix, refactoring, or breaking change4445### Multi-Tool Static Analysis46Execute in parallel:47- **CodeQL**: Deep vulnerability analysis (SQL injection, XSS, auth bypasses)48- **SonarQube**: Code smells, complexity, duplication, maintainability49- **Semgrep**: Organization-specific rules and security policies50- **Snyk/Dependabot**: Supply chain security51- **GitGuardian/TruffleHog**: Secret detection5253### AI-Assisted Review54```python55# Context-aware review prompt for Claude 4.5 Sonnet56review_prompt = f"""57You are reviewing a pull request for a {language} {project_type} application.5859**Change Summary:** {pr_description}60**Modified Code:** {code_diff}61**Static Analysis:** {sonarqube_issues}, {codeql_alerts}62**Architecture:** {system_architecture_summary}6364Focus on:651. Security vulnerabilities missed by static tools662. Performance implications at scale673. Edge cases and error handling gaps684. API contract compatibility695. Testability and missing coverage706. Architectural alignment7172For each issue:73- Specify file path and line numbers74- Classify severity: CRITICAL/HIGH/MEDIUM/LOW75- Explain problem (1-2 sentences)76- Provide concrete fix example77- Link relevant documentation7879Format as JSON array.80"""81```8283### Model Selection (2025)84- **Fast reviews (<200 lines)**: GPT-4o-mini or Claude 4.5 Haiku85- **Deep reasoning**: Claude 4.5 Sonnet or GPT-4.5 (200K+ tokens)86- **Code generation**: GitHub Copilot or Qodo87- **Multi-language**: Qodo or CodeAnt AI (30+ languages)8889### Review Routing90```typescript91interface ReviewRoutingStrategy {92 async routeReview(pr: PullRequest): Promise<ReviewEngine> {93 const metrics = await this.analyzePRComplexity(pr);9495 if (metrics.filesChanged > 50 || metrics.linesChanged > 1000) {96 return new HumanReviewRequired("Too large for automation");97 }9899 if (metrics.securitySensitive || metrics.affectsAuth) {100 return new AIEngine("claude-3.7-sonnet", {101 temperature: 0.1,102 maxTokens: 4000,103 systemPrompt: SECURITY_FOCUSED_PROMPT104 });105 }106107 if (metrics.testCoverageGap > 20) {108 return new QodoEngine({ mode: "test-generation", coverageTarget: 80 });109 }110111 return new AIEngine("gpt-4o", { temperature: 0.3, maxTokens: 2000 });112 }113}114```115116## Architecture Analysis117118### Architectural Coherence1191. **Dependency Direction**: Inner layers don't depend on outer layers1202. **SOLID Principles**:121 - Single Responsibility, Open/Closed, Liskov Substitution122 - Interface Segregation, Dependency Inversion1233. **Anti-patterns**:124 - Singleton (global state), God objects (>500 lines, >20 methods)125 - Anemic models, Shotgun surgery126127### Microservices Review128```go129type MicroserviceReviewChecklist struct {130 CheckServiceCohesion bool // Single capability per service?131 CheckDataOwnership bool // Each service owns database?132 CheckAPIVersioning bool // Semantic versioning?133 CheckBackwardCompatibility bool // Breaking changes flagged?134 CheckCircuitBreakers bool // Resilience patterns?135 CheckIdempotency bool // Duplicate event handling?136}137138func (r *MicroserviceReviewer) AnalyzeServiceBoundaries(code string) []Issue {139 issues := []Issue{}140141 if detectsSharedDatabase(code) {142 issues = append(issues, Issue{143 Severity: "HIGH",144 Category: "Architecture",145 Message: "Services sharing database violates bounded context",146 Fix: "Implement database-per-service with eventual consistency",147 })148 }149150 if hasBreakingAPIChanges(code) && !hasDeprecationWarnings(code) {151 issues = append(issues, Issue{152 Severity: "CRITICAL",153 Category: "API Design",154 Message: "Breaking change without deprecation period",155 Fix: "Maintain backward compatibility via versioning (v1, v2)",156 })157 }158159 return issues160}161```162163## Security Vulnerability Detection164165### Multi-Layered Security166**SAST Layer**: CodeQL, Semgrep, Bandit/Brakeman/Gosec167168**AI-Enhanced Threat Modeling**:169```python170security_analysis_prompt = """171Analyze authentication code for vulnerabilities:172{code_snippet}173174Check for:1751. Authentication bypass, broken access control (IDOR)1762. JWT token validation flaws1773. Session fixation/hijacking, timing attacks1784. Missing rate limiting, insecure password storage1795. Credential stuffing protection gaps180181Provide: CWE identifier, CVSS score, exploit scenario, remediation code182"""183184findings = claude.analyze(security_analysis_prompt, temperature=0.1)185```186187**Secret Scanning**:188```bash189trufflehog git file://. --json | \190 jq '.[] | select(.Verified == true) | {191 secret_type: .DetectorName,192 file: .SourceMetadata.Data.Filename,193 severity: "CRITICAL"194 }'195```196197### OWASP Top 10 (2025)1981. **A01 - Broken Access Control**: Missing authorization, IDOR1992. **A02 - Cryptographic Failures**: Weak hashing, insecure RNG2003. **A03 - Injection**: SQL, NoSQL, command injection via taint analysis2014. **A04 - Insecure Design**: Missing threat modeling2025. **A05 - Security Misconfiguration**: Default credentials2036. **A06 - Vulnerable Components**: Snyk/Dependabot for CVEs2047. **A07 - Authentication Failures**: Weak session management2058. **A08 - Data Integrity Failures**: Unsigned JWTs2069. **A09 - Logging Failures**: Missing audit logs20710. **A10 - SSRF**: Unvalidated user-controlled URLs208209## Performance Review210211### Performance Profiling212```javascript213class PerformanceReviewAgent {214 async analyzePRPerformance(prNumber) {215 const baseline = await this.loadBaselineMetrics('main');216 const prBranch = await this.runBenchmarks(`pr-${prNumber}`);217218 const regressions = this.detectRegressions(baseline, prBranch, {219 cpuThreshold: 10, memoryThreshold: 15, latencyThreshold: 20220 });221222 if (regressions.length > 0) {223 await this.postReviewComment(prNumber, {224 severity: 'HIGH',225 title: '⚠️ Performance Regression Detected',226 body: this.formatRegressionReport(regressions),227 suggestions: await this.aiGenerateOptimizations(regressions)228 });229 }230 }231}232```233234### Scalability Red Flags235- **N+1 Queries**, **Missing Indexes**, **Synchronous External Calls**236- **In-Memory State**, **Unbounded Collections**, **Missing Pagination**237- **No Connection Pooling**, **No Rate Limiting**238239```python240def detect_n_plus_1_queries(code_ast):241 issues = []242 for loop in find_loops(code_ast):243 db_calls = find_database_calls_in_scope(loop.body)244 if len(db_calls) > 0:245 issues.append({246 'severity': 'HIGH',247 'line': loop.line_number,248 'message': f'N+1 query: {len(db_calls)} DB calls in loop',249 'fix': 'Use eager loading (JOIN) or batch loading'250 })251 return issues252```253254## Review Comment Generation255256### Structured Format257```typescript258interface ReviewComment {259 path: string; line: number;260 severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';261 category: 'Security' | 'Performance' | 'Bug' | 'Maintainability';262 title: string; description: string;263 codeExample?: string; references?: string[];264 autoFixable: boolean; cwe?: string; cvss?: number;265 effort: 'trivial' | 'easy' | 'medium' | 'hard';266}267268const comment: ReviewComment = {269 path: "src/auth/login.ts", line: 42,270 severity: "CRITICAL", category: "Security",271 title: "SQL Injection in Login Query",272 description: `String concatenation with user input enables SQL injection.273**Attack Vector:** Input 'admin' OR '1'='1' bypasses authentication.274**Impact:** Complete auth bypass, unauthorized access.`,275 codeExample: `276// ❌ Vulnerable277const query = \`SELECT * FROM users WHERE username = '\${username}'\`;278279// ✅ Secure280const query = 'SELECT * FROM users WHERE username = ?';281const result = await db.execute(query, [username]);282 `,283 references: ["https://cwe.mitre.org/data/definitions/89.html"],284 autoFixable: false, cwe: "CWE-89", cvss: 9.8, effort: "easy"285};286```287288## CI/CD Integration289290### GitHub Actions291```yaml292name: AI Code Review293on:294 pull_request:295 types: [opened, synchronize, reopened]296297jobs:298 ai-review:299 runs-on: ubuntu-latest300 steps:301 - uses: actions/checkout@v4302303 - name: Static Analysis304 run: |305 sonar-scanner -Dsonar.pullrequest.key=${{ github.event.number }}306 codeql database create codeql-db --language=javascript,python307 semgrep scan --config=auto --sarif --output=semgrep.sarif308309 - name: AI-Enhanced Review (GPT-5)310 env:311 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}312 run: |313 python scripts/ai_review.py \314 --pr-number ${{ github.event.number }} \315 --model gpt-4o \316 --static-analysis-results codeql.sarif,semgrep.sarif317318 - name: Post Comments319 uses: actions/github-script@v7320 with:321 script: |322 const comments = JSON.parse(fs.readFileSync('review-comments.json'));323 for (const comment of comments) {324 await github.rest.pulls.createReviewComment({325 owner: context.repo.owner,326 repo: context.repo.repo,327 pull_number: context.issue.number,328 body: comment.body, path: comment.path, line: comment.line329 });330 }331332 - name: Quality Gate333 run: |334 CRITICAL=$(jq '[.[] | select(.severity == "CRITICAL")] | length' review-comments.json)335 if [ $CRITICAL -gt 0 ]; then336 echo "❌ Found $CRITICAL critical issues"337 exit 1338 fi339```340341## Complete Example: AI Review Automation342343```python344#!/usr/bin/env python3345import os, json, subprocess346from dataclasses import dataclass347from typing import List, Dict, Any348from anthropic import Anthropic349350@dataclass351class ReviewIssue:352 file_path: str; line: int; severity: str353 category: str; title: str; description: str354 code_example: str = ""; auto_fixable: bool = False355356class CodeReviewOrchestrator:357 def __init__(self, pr_number: int, repo: str):358 self.pr_number = pr_number; self.repo = repo359 self.github_token = os.environ['GITHUB_TOKEN']360 self.anthropic_client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])361 self.issues: List[ReviewIssue] = []362363 def run_static_analysis(self) -> Dict[str, Any]:364 results = {}365366 # SonarQube367 subprocess.run(['sonar-scanner', f'-Dsonar.projectKey={self.repo}'], check=True)368369 # Semgrep370 semgrep_output = subprocess.check_output(['semgrep', 'scan', '--config=auto', '--json'])371 results['semgrep'] = json.loads(semgrep_output)372373 return results374375 def ai_review(self, diff: str, static_results: Dict) -> List[ReviewIssue]:376 prompt = f"""Review this PR comprehensively.377378**Diff:** {diff[:15000]}379**Static Analysis:** {json.dumps(static_results, indent=2)[:5000]}380381Focus: Security, Performance, Architecture, Bug risks, Maintainability382383Return JSON array:384[{{385 "file_path": "src/auth.py", "line": 42, "severity": "CRITICAL",386 "category": "Security", "title": "Brief summary",387 "description": "Detailed explanation", "code_example": "Fix code"388}}]389"""390391 response = self.anthropic_client.messages.create(392 model="claude-3-5-sonnet-20241022",393 max_tokens=8000, temperature=0.2,394 messages=[{"role": "user", "content": prompt}]395 )396397 content = response.content[0].text398 if '```json' in content:399 content = content.split('```json')[1].split('```')[0]400401 return [ReviewIssue(**issue) for issue in json.loads(content.strip())]402403 def post_review_comments(self, issues: List[ReviewIssue]):404 summary = "## 🤖 AI Code Review\n\n"405 by_severity = {}406 for issue in issues:407 by_severity.setdefault(issue.severity, []).append(issue)408409 for severity in ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']:410 count = len(by_severity.get(severity, []))411 if count > 0:412 summary += f"- **{severity}**: {count}\n"413414 critical_count = len(by_severity.get('CRITICAL', []))415 review_data = {416 'body': summary,417 'event': 'REQUEST_CHANGES' if critical_count > 0 else 'COMMENT',418 'comments': [issue.to_github_comment() for issue in issues]419 }420421 # Post to GitHub API422 print(f"✅ Posted review with {len(issues)} comments")423424if __name__ == '__main__':425 import argparse426 parser = argparse.ArgumentParser()427 parser.add_argument('--pr-number', type=int, required=True)428 parser.add_argument('--repo', required=True)429 args = parser.parse_args()430431 reviewer = CodeReviewOrchestrator(args.pr_number, args.repo)432 static_results = reviewer.run_static_analysis()433 diff = reviewer.get_pr_diff()434 ai_issues = reviewer.ai_review(diff, static_results)435 reviewer.post_review_comments(ai_issues)436```437438## Summary439440Comprehensive AI code review combining:4411. Multi-tool static analysis (SonarQube, CodeQL, Semgrep)4422. State-of-the-art LLMs (GPT-5, Claude 4.5 Sonnet)4433. Seamless CI/CD integration (GitHub Actions, GitLab, Azure DevOps)4444. 30+ language support with language-specific linters4455. Actionable review comments with severity and fix examples4466. DORA metrics tracking for review effectiveness4477. Quality gates preventing low-quality code4488. Auto-test generation via Qodo/CodiumAI449450Use this tool to transform code review from manual process to automated AI-assisted quality assurance catching issues early with instant feedback.451
Full transparency — inspect the skill content before installing.