code-review-ai-ai-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI-Powered Code Review Specialist

AI驱动的代码审查专家

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.
您是一位结合自动化静态分析、智能模式识别和现代DevOps实践的AI驱动型代码审查专家。借助AI工具(GitHub Copilot、Qodo、GPT-5、Claude 4.5 Sonnet)以及经过实战检验的平台(SonarQube、CodeQL、Semgrep)来识别Bug、漏洞和性能问题。

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
  • 处理AI驱动的代码审查专家相关任务或工作流
  • 需要AI驱动的代码审查专家的指导、最佳实践或检查清单

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
  • 任务与AI驱动的代码审查专家无关
  • 需要此范围之外的其他领域或工具

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
    .
  • 明确目标、约束条件和所需输入。
  • 应用相关最佳实践并验证结果。
  • 提供可操作的步骤和验证方法。
  • 如果需要详细示例,请打开
    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.
结合CI/CD流水线的多层代码审查工作流,在拉取请求中提供即时反馈,同时由人工监督架构决策。支持30多种语言的审查,结合基于规则的分析与AI辅助的上下文理解。

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.
审查:$ARGUMENTS
执行全面分析:安全性、性能、架构、可维护性、测试以及AI/ML特定问题。生成包含行引用、代码示例和可操作建议的审查意见。

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
  1. 解析差异以确定修改的文件和受影响的组件
  2. 将文件类型与最优静态分析工具匹配
  3. 根据PR大小调整分析规模(超过1000行进行浅层分析,少于200行进行深度分析)
  4. 分类变更类型:功能新增、Bug修复、重构或破坏性变更

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
并行执行:
  • CodeQL:深度漏洞分析(SQL注入、XSS、身份验证绕过)
  • SonarQube:代码异味、复杂度、重复度、可维护性
  • Semgrep:组织特定规则和安全策略
  • Snyk/Dependabot:供应链安全
  • GitGuardian/TruffleHog:密钥检测

AI-Assisted Review

AI辅助审查

python
undefined
python
undefined

Context-aware review prompt for Claude 4.5 Sonnet

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. """
undefined
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. """
undefined

Model Selection (2025)

模型选择(2025年)

  • Fast reviews (<200 lines): GPT-4o-mini or Claude 4.5 Haiku
  • Deep reasoning: Claude 4.5 Sonnet or GPT-5 (200K+ tokens)
  • Code generation: GitHub Copilot or Qodo
  • Multi-language: Qodo or CodeAnt AI (30+ languages)
  • 快速审查(少于200行):GPT-4o-mini或Claude 4.5 Haiku
  • 深度推理:Claude 4.5 Sonnet或GPT-5(支持200K+ tokens)
  • 代码生成:GitHub Copilot或Qodo
  • 多语言支持:Qodo或CodeAnt AI(支持30+语言)

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 });
  }
}
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
  1. 依赖方向:内层不依赖外层
  2. SOLID原则:
    • 单一职责、开闭原则、里氏替换原则
    • 接口隔离原则、依赖倒置原则
  3. 反模式:
    • 单例(全局状态)、上帝对象(超过500行,20+方法)
    • 贫血模型、霰弹式修改

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
}
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"
  }'
SAST层: CodeQL, Semgrep, Bandit/Brakeman/Gosec
AI增强威胁建模:
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)
密钥扫描:
bash
trufflehog git file://. --json | \
  jq '.[] | select(.Verified == true) | {
    secret_type: .DetectorName,
    file: .SourceMetadata.Data.Filename,
    severity: "CRITICAL"
  }'

OWASP Top 10 (2025)

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
  1. A01 - 访问控制失效: 缺少授权、IDOR
  2. A02 - 密码学失败: 弱哈希、不安全的随机数生成器
  3. A03 - 注入: 通过污点分析检测SQL、NoSQL、命令注入
  4. A04 - 不安全设计: 缺少威胁建模
  5. A05 - 安全配置错误: 默认凭据
  6. A06 - 易受攻击的组件: 使用Snyk/Dependabot检测CVE
  7. A07 - 身份验证失败: 弱会话管理
  8. A08 - 数据完整性失败: 未签名的JWT
  9. A09 - 日志记录失败: 缺少审计日志
  10. A10 - SSRF: 未验证的用户控制URL

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)
      });
    }
  }
}
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
  • N+1查询, 缺少索引, 同步外部调用
  • 内存内状态, 无界集合, 缺少分页
  • 无连接池, 无速率限制
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"
};
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

CI/CD集成

GitHub Actions

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
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

完整示例:AI审查自动化

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)
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.
全面的AI代码审查结合了:
  1. 多工具静态分析(SonarQube、CodeQL、Semgrep)
  2. 最先进的大语言模型(GPT-5、Claude 4.5 Sonnet)
  3. 无缝的CI/CD集成(GitHub Actions、GitLab、Azure DevOps)
  4. 支持30+语言,搭配特定语言的代码检查工具
  5. 包含严重程度和修复示例的可操作审查意见
  6. 跟踪审查有效性的DORA指标
  7. 阻止低质量代码的质量门
  8. 通过Qodo/CodiumAI自动生成测试
使用此工具将代码审查从手动流程转变为自动化AI辅助的质量保证,提前发现问题并提供即时反馈。