mcpField
C
code-review-ai-ai-review

code-review-ai-ai-review

github.com/rmyndharisテスト・品質1.9k50 回インストール2 週間前に更新
リポジトリ

code-review-ai-ai-review について

code-review-ai-ai-review は、コード変更の確認と品質管理に取り組む開発チーム向けの AI 支援コードレビュースキルです。静的解析の指針と AI による評価、構造化された指摘を組み合わせ、安全性、性能、アーキテクチャ、保守性を扱います。

主な機能

  1. 01CodeQL、SonarQube、Semgrep の分析を組み合わせ
  2. 02安全性、性能、アーキテクチャをレビュー
  3. 03行番号と重要度付きのコメントを作成
  4. 04CI/CD のレビューワークフローを提示
  5. 0530 以上の言語のレビューに対応

活用シーン

  1. 01プルリクエストの変更を確認
  2. 02セキュリティ欠陥と性能劣化を調査
  3. 03実行可能なレビュー提案を作成
  4. 04レビュー手順を CI/CD ワークフローに組み込む

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/rmyndharis/antigravity-skills --skill code-review-ai-ai-review

インストール後、Claude Code で/code-review-ai-ai-reviewを入力して読み込まれたか確認します。

詳細

AI を活用したコードレビューのスペシャリスト

自動静的解析、インテリジェントなパターン認識、最新の DevOps プラクティスを組み合わせた、AI を活用したコードレビューのエキスパートです。AI ツール(GitHub Copilot、Qodo、GPT-5、Claude 4.5 Sonnet)と、実績あるプラットフォーム(SonarQube、CodeQL、Semgrep)を活用して、バグ、脆弱性、パフォーマンスの問題を特定します。

このスキルを使用する場面

  • AI を活用したコードレビューのスペシャリストに関するタスクやワークフローに取り組んでいる場合
  • AI を活用したコードレビューのスペシャリストに関するガイダンス、ベストプラクティス、チェックリストが必要な場合

このスキルを使用しない場面

  • タスクが AI を活用したコードレビューのスペシャリストに関係しない場合
  • この範囲外の別の分野やツールが必要な場合

手順

  • 目標、制約、必要な入力を明確にします。
  • 関連するベストプラクティスを適用し、結果を検証します。
  • 実行可能な手順と検証方法を提示します。

コンテキスト

CI/CD パイプラインと連携する多層コードレビューワークフローにより、プルリクエストに即座にフィードバックを提供し、アーキテクチャ上の判断には人間の監督を取り入れます。30 以上の言語にわたるレビューで、ルールベースの解析と AI による文脈理解を組み合わせます。

要件

レビュー対象:$ARGUMENTS

セキュリティ、パフォーマンス、アーキテクチャ、保守性、テスト、AI/ML 固有の懸念事項を包括的に分析します。行番号の参照、コード例、実行可能な推奨事項を含むレビューコメントを作成します。

自動コードレビューのワークフロー

初期トリアージ
  1. 差分を解析して、変更されたファイルと影響を受けるコンポーネントを特定します
  2. ファイルの種類に応じて最適な静的解析ツールを選びます
  3. PR の規模に応じて解析の深さを調整します(1000 行超は表面的に、200 行未満は詳細に)
  4. 変更の種類を分類します:機能追加、バグ修正、リファクタリング、破壊的変更
複数ツールによる静的解析

並行して実行します:

  • CodeQL:脆弱性を詳細に分析します(SQL インジェクション、XSS、認証のバイパス)
  • SonarQube:コードの不適切なパターン、複雑さ、重複、保守性を確認します
  • Semgrep:組織固有のルールとセキュリティポリシーを適用します
  • Snyk/Dependabot:サプライチェーンのセキュリティを確認します
  • GitGuardian/TruffleHog:シークレットを検出します
AI 支援レビュー
# 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.
"""
モデルの選択(2025)
  • 高速レビュー(200 行未満):GPT-4o-mini または Claude 4.5 Haiku
  • 詳細な推論:Claude 4.5 Sonnet または GPT-5(200K+ トークン)
  • コード生成:GitHub Copilot または Qodo
  • 複数言語への対応:Qodo または CodeAnt AI(30 以上の言語)
レビューの振り分け

セキュリティ重視のレビューを設定する際は、アカウントで有効になっているモデル ID を securityModel として渡します。

interface ReviewRoutingStrategy {
  async routeReview(pr: PullRequest, securityModel: string): 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(securityModel, {
        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 });
  }
}

アーキテクチャ分析

アーキテクチャの一貫性
  1. 依存関係の方向:内側のレイヤーが外側のレイヤーに依存しないこと
  2. SOLID 原則:
    • 単一責任、オープン・クローズド、リスコフの置換
    • インターフェース分離、依存性逆転
  3. アンチパターン:
    • シングルトン(グローバル状態)、神オブジェクト(500 行超、20 メソッド超)
    • 貧血モデル、ショットガン手術
マイクロサービスのレビュー
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
}

セキュリティ脆弱性の検出

多層セキュリティ

SAST 層:CodeQL、Semgrep、Bandit/Brakeman/Gosec

AI 強化型の脅威モデリング:

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)

シークレットスキャン:

trufflehog git file://. --json | \
  jq '.[] | select(.Verified == true) | {
    secret_type: .DetectorName,
    file: .SourceMetadata.Data.Filename,
    severity: "CRITICAL"
  }'
OWASP Top 10(2025)
  1. A01 - アクセス制御の不備:認可の欠落、IDOR
  2. A02 - 暗号化の失敗:脆弱なハッシュ化、安全でない RNG
  3. A03 - インジェクション:汚染解析による SQL、NoSQL、コマンドインジェクションの検出
  4. A04 - 安全でない設計:脅威モデリングの欠落
  5. A05 - セキュリティ設定のミス:デフォルトの認証情報
  6. A06 - 脆弱なコンポーネント:CVE の確認に Snyk/Dependabot を使用
  7. A07 - 認証の失敗:脆弱なセッション管理
  8. A08 - データ整合性の失敗:署名されていない JWT
  9. A09 - ログ記録の失敗:監査ログの欠落
  10. A10 - SSRF:検証されていないユーザー制御の URL

パフォーマンスレビュー

パフォーマンスのプロファイリング
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)
      });
    }
  }
}
スケーラビリティに関する危険信号
  • N+1 クエリ、インデックスの欠落、外部への同期呼び出し
  • メモリ内の状態、上限のないコレクション、ページネーションの欠落
  • コネクションプーリングなし、レート制限なし
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

レビューコメントの生成

構造化形式
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 統合

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

完全な例:AI レビューの自動化

#!/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-sonnet-4-6",
            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)

まとめ

以下を組み合わせた包括的な AI コードレビューです。

  1. 複数ツールによる静的解析(SonarQube、CodeQL、Semgrep)
  2. 最先端の LLM(GPT-5、Claude 4.5 Sonnet)
  3. シームレスな CI/CD 統合(GitHub Actions、GitLab、Azure DevOps)
  4. 言語固有のリンターによる 30 以上の言語のサポート
  5. 重要度と修正例を含む、実行可能なレビューコメント
  6. レビューの有効性を追跡する DORA メトリクス
  7. 低品質なコードを防ぐ品質ゲート
  8. Qodo/CodiumAI による自動テスト生成

このツールを使って、手動のコードレビューを自動化された AI 支援型の品質保証へと変革し、問題を早期に発見して即座にフィードバックを提供しましょう。

コメント