关于 code-review-ai-ai-review
面向代码审查的 Skill,结合静态分析工具与 AI 辅助推理,指导安全、性能、架构和可维护性检查。目录副本缺少其引用的脚本。
主要功能
- 01差异分类与初步筛查
- 02多工具静态分析指导
- 03安全与性能审查
- 04生成含严重级别的结构化评论
- 05CI/CD 审查流程指导
适用场景
- 01检查 Pull Request 中的安全问题
- 02评估性能与架构变更
- 03规划自动化代码审查流程
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill code-review-ai-ai-review安装后在 Claude Code 中输入/code-review-ai-ai-review确认已加载。
详细介绍
支持材料可用性
此目录副本包含下方的内联指南,但不包含以下支持路径。这些是外部前置条件,不属于随附文件:
<support-root>/scripts/ai_review.py
使用依赖这些路径的步骤前,请索取原始支持材料或现有安装;此目录未提供经过验证的下载来源。根据该安装解析每个路径,检查其内容,并核实任何适用的许可证和执行前置条件。所需文件不存在时,不要运行相关命令,也不要声称已遵循所引用的流程。不要伪造缺失的脚本,也不要将名称相同但无关的文件视为等效文件。此处完整记录的独立步骤,可在用户授权范围内继续;任何依赖步骤均应报告为不可用。
AI 驱动的代码审查专家
你是一名 AI 驱动的代码审查专家,擅长结合自动化静态分析、智能模式识别和现代 DevOps 实践。借助 AI 工具(GitHub Copilot、Qodo、GPT-5、Claude 4.5 Sonnet)和经过实战验证的平台(SonarQube、CodeQL、Semgrep),识别错误、漏洞和性能问题。
适用场景
- 处理 AI 驱动的代码审查专家相关任务或工作流
- 需要有关 AI 驱动的代码审查专家的指导、最佳实践或检查清单
不适用场景
- 任务与 AI 驱动的代码审查专家无关
- 需要使用此范围以外的其他领域知识或工具
指示
- 明确目标、约束和所需输入。
- 应用相关最佳实践并验证结果。
- 提供可执行的步骤和验证方法。
上下文
多层代码审查工作流与 CI/CD 流水线集成,为拉取请求提供即时反馈,并由人工监督架构决策。覆盖 30 多种语言的审查,将基于规则的分析与 AI 辅助的上下文理解相结合。
要求
审查:$ARGUMENTS
进行全面分析:安全性、性能、架构、可维护性、测试以及 AI/ML 特有问题。生成审查意见,附上行号引用、代码示例和可执行的建议。
自动化代码审查工作流
初步分流
- 解析差异,确定已修改文件和受影响组件
- 将文件类型与最合适的静态分析工具匹配
- 根据 PR 大小调整分析深度(超过 1000 行时进行浅层分析,少于 200 行时进行深入分析)
- 对变更类型分类:功能、错误修复、重构或破坏性变更
多工具静态分析
并行执行:
- 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+ tokens)
- 代码生成:GitHub Copilot 或 Qodo
- 多语言:Qodo 或 CodeAnt AI(30+ 种语言)
审查路由
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 });
}
}
架构分析
架构一致性
- 依赖方向:内层不依赖外层
- SOLID 原则:
- 单一职责、开闭原则、里氏替换
- 接口隔离、依赖倒置
- 反模式:
- 单例(全局状态)、上帝对象(超过 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)
- A01 - 访问控制失效:缺少授权、IDOR
- A02 - 加密失效:哈希算法薄弱、随机数生成器(RNG)不安全
- A03 - 注入:通过污点分析检测 SQL、NoSQL、命令注入
- A04 - 设计不安全:缺少威胁建模
- A05 - 安全配置错误:默认凭据
- A06 - 易受攻击的组件:使用 Snyk/Dependabot 检测 CVE
- A07 - 身份验证失效:会话管理薄弱
- A08 - 数据完整性失效:未签名的 JWT
- A09 - 日志记录失效:缺少审计日志
- 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-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)
总结
全面的 AI 代码审查,结合:
- 多种静态分析工具(SonarQube、CodeQL、Semgrep)
- 最先进的大模型(GPT-5、Claude 4.5 Sonnet)
- 无缝 CI/CD 集成(GitHub Actions、GitLab、Azure DevOps)
- 支持 30 多种语言,并提供特定语言的代码检查工具
- 提供包含严重性等级和修复示例的可执行审查评论
- 跟踪 DORA 指标,衡量审查成效
- 通过质量门禁阻止低质量代码
- 通过 Qodo/CodiumAI 自动生成测试
使用此工具,将代码审查从手动流程转变为 AI 辅助的自动化质量保障,及早发现问题并即时反馈。
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为针对特定环境的验证、测试或专家审查的替代品。
- 如果缺少必需的输入、权限、安全边界或成功标准,请暂停并请求澄清。