code-reviewer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Reviewer

代码审查工具

Before generating any output, read
config/defaults.md
and adapt all patterns, imports, and code examples to the user's configured stack.
生成任何输出前,请阅读
config/defaults.md
,并将所有模式、导入语句和代码示例适配到用户配置的技术栈。

Review Process

审查流程

  1. Read all files in scope (specified files, PR diff, or project)
  2. Analyze each file against the review categories below
  3. Output structured findings with severity levels
  4. Provide actionable fix suggestions
  1. 读取所有审查范围内的文件(指定文件、PR diff或整个项目)
  2. 对照下方的审查类别逐一分析每个文件
  3. 输出结构化的检查结果,附带严重级别
  4. 提供可落地的修复建议

Review Categories

审查类别

Security

安全

Injection Vulnerabilities

注入漏洞

typescript
// BAD: SQL injection
const query = `SELECT * FROM users WHERE id = ${userId}`;

// GOOD: Parameterized query
const user = await prisma.user.findUnique({ where: { id: userId } });
typescript
// BAD: SQL injection
const query = `SELECT * FROM users WHERE id = ${userId}`;

// GOOD: Parameterized query
const user = await prisma.user.findUnique({ where: { id: userId } });

XSS (Cross-Site Scripting)

XSS (Cross-Site Scripting)

typescript
// BAD: Rendering unsanitized HTML
<div dangerouslySetInnerHTML={{ __html: userContent }} />

// GOOD: Sanitize or use text content
<div>{sanitizeHtml(userContent)}</div>
// Or just render as text
<div>{userContent}</div>
typescript
// BAD: Rendering unsanitized HTML
<div dangerouslySetInnerHTML={{ __html: userContent }} />

// GOOD: Sanitize or use text content
<div>{sanitizeHtml(userContent)}</div>
// Or just render as text
<div>{userContent}</div>

Authentication Leaks

认证信息泄露

typescript
// BAD: Exposing sensitive data
return NextResponse.json({ user: { ...user, password: user.password } });

// GOOD: Exclude sensitive fields
const { password, ...safeUser } = user;
return NextResponse.json({ user: safeUser });
typescript
// BAD: Exposing sensitive data
return NextResponse.json({ user: { ...user, password: user.password } });

// GOOD: Exclude sensitive fields
const { password, ...safeUser } = user;
return NextResponse.json({ user: safeUser });

Hardcoded Secrets

硬编码密钥

typescript
// BAD
const API_KEY = 'sk-1234567890abcdef';

// GOOD
const API_KEY = process.env.API_KEY;
typescript
// BAD
const API_KEY = 'sk-1234567890abcdef';

// GOOD
const API_KEY = process.env.API_KEY;

Path Traversal

路径遍历

typescript
// BAD: User-controlled file path
const filePath = `./uploads/${req.query.filename}`;

// GOOD: Validate and sanitize
const filename = path.basename(req.query.filename);
const filePath = path.join('./uploads', filename);
typescript
// BAD: User-controlled file path
const filePath = `./uploads/${req.query.filename}`;

// GOOD: Validate and sanitize
const filename = path.basename(req.query.filename);
const filePath = path.join('./uploads', filename);

Performance

性能

N+1 Queries

N+1 查询问题

See prisma-query-optimizer skill for detection patterns.
检测模式可参考prisma-query-optimizer skill

Memory Leaks

内存泄漏

typescript
// BAD: Event listener not cleaned up
useEffect(() => {
  window.addEventListener('resize', handleResize);
}, []);

// GOOD: Cleanup on unmount
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);
typescript
// BAD: Event listener not cleaned up
useEffect(() => {
  window.addEventListener('resize', handleResize);
}, []);

// GOOD: Cleanup on unmount
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, []);

Unbounded Operations

无边界操作

typescript
// BAD: Loading all records
const allUsers = await prisma.user.findMany();

// GOOD: Paginate
const users = await prisma.user.findMany({ take: 50, skip: offset });
typescript
// BAD: Loading all records
const allUsers = await prisma.user.findMany();

// GOOD: Paginate
const users = await prisma.user.findMany({ take: 50, skip: offset });

Synchronous File I/O

同步文件I/O

typescript
// BAD: Blocks event loop
const data = fs.readFileSync('large-file.json');

// GOOD: Async I/O
const data = await fs.promises.readFile('large-file.json');
typescript
// BAD: Blocks event loop
const data = fs.readFileSync('large-file.json');

// GOOD: Async I/O
const data = await fs.promises.readFile('large-file.json');

Maintainability

可维护性

Magic Numbers

魔术数字

typescript
// BAD
if (status === 3) { ... }

// GOOD
const STATUS_COMPLETED = 3;
if (status === STATUS_COMPLETED) { ... }

// BETTER: Use enum or const object
const Status = { COMPLETED: 3 } as const;
typescript
// BAD
if (status === 3) { ... }

// GOOD
const STATUS_COMPLETED = 3;
if (status === STATUS_COMPLETED) { ... }

// BETTER: Use enum or const object
const Status = { COMPLETED: 3 } as const;

Deep Nesting

深层嵌套

typescript
// BAD: Arrow code
if (user) {
  if (user.isActive) {
    if (user.hasPermission('write')) {
      // ...
    }
  }
}

// GOOD: Early returns
if (!user) return;
if (!user.isActive) return;
if (!user.hasPermission('write')) return;
// ...
typescript
// BAD: Arrow code
if (user) {
  if (user.isActive) {
    if (user.hasPermission('write')) {
      // ...
    }
  }
}

// GOOD: Early returns
if (!user) return;
if (!user.isActive) return;
if (!user.hasPermission('write')) return;
// ...

God Functions

上帝函数

Functions over 50 lines or with more than 5 parameters should be broken down.
超过50行或参数超过5个的函数应当被拆分。

Dead Code

死代码

Unused imports, unreachable code after return/throw, commented-out code blocks.
未使用的导入、return/throw后的不可达代码、被注释掉的代码块。

Naming Conventions

命名规范

Inconsistent Naming

命名风格不一致

typescript
// BAD: Mixed styles
const user_name = '...';
const userEmail = '...';
const UserAge = 25;

// GOOD: Consistent camelCase for variables
const userName = '...';
const userEmail = '...';
const userAge = 25;
typescript
// BAD: Mixed styles
const user_name = '...';
const userEmail = '...';
const UserAge = 25;

// GOOD: Consistent camelCase for variables
const userName = '...';
const userEmail = '...';
const userAge = 25;

Unclear Names

命名不清晰

typescript
// BAD
const d = new Date();
const arr = users.filter(u => u.a);

// GOOD
const createdAt = new Date();
const activeUsers = users.filter(user => user.isActive);
typescript
// BAD
const d = new Date();
const arr = users.filter(u => u.a);

// GOOD
const createdAt = new Date();
const activeUsers = users.filter(user => user.isActive);

Error Handling

错误处理

Swallowed Errors

被忽略的错误

typescript
// BAD: Silent failure
try {
  await saveData();
} catch (e) {
  // Nothing
}

// GOOD: Log or handle
try {
  await saveData();
} catch (error) {
  console.error('Failed to save:', error);
  throw error; // Or handle appropriately
}
typescript
// BAD: Silent failure
try {
  await saveData();
} catch (e) {
  // Nothing
}

// GOOD: Log or handle
try {
  await saveData();
} catch (error) {
  console.error('Failed to save:', error);
  throw error; // Or handle appropriately
}

Generic Catch

通用异常捕获

typescript
// BAD: Catches everything including programming errors
try {
  doSomething();
} catch (e) {
  return defaultValue;
}

// GOOD: Catch specific errors
try {
  doSomething();
} catch (error) {
  if (error instanceof NetworkError) {
    return defaultValue;
  }
  throw error;
}
typescript
// BAD: Catches everything including programming errors
try {
  doSomething();
} catch (e) {
  return defaultValue;
}

// GOOD: Catch specific errors
try {
  doSomething();
} catch (error) {
  if (error instanceof NetworkError) {
    return defaultValue;
  }
  throw error;
}

Test Coverage Gaps

测试覆盖缺口

Untested Edge Cases

未测试的边界用例

Flag functions that handle:
  • Null/undefined inputs without tests
  • Empty arrays/objects without tests
  • Error conditions without tests
  • Boundary values without tests
标记处理以下场景但缺少对应测试的函数:
  • Null/undefined输入无测试
  • 空数组/空对象无测试
  • 错误场景无测试
  • 边界值无测试

Missing Integration Tests

缺失集成测试

API routes and database operations should have integration tests.
API路由和数据库操作应当有对应的集成测试。

Output Format

输出格式

undefined
undefined

Code Review Report

代码审查报告

Critical (must fix before merge)

严重(合并前必须修复)

SeverityFileLineIssueCategory
CRITICALsrc/api/users.ts45SQL injection vulnerabilitySecurity
Details:
  • Issue: User input directly interpolated into query string
  • Fix: Use parameterized queries via Prisma
typescript
// Before
const query = `SELECT * FROM users WHERE email = '${email}'`;

// After
const user = await prisma.user.findUnique({ where: { email } });
严重级别文件行号问题所属类别
CRITICALsrc/api/users.ts45SQL injection vulnerability安全
详情:
  • 问题:用户输入直接拼接到查询字符串中
  • 修复方案:通过Prisma使用参数化查询
typescript
// Before
const query = `SELECT * FROM users WHERE email = '${email}'`;

// After
const user = await prisma.user.findUnique({ where: { email } });

Warnings (should fix)

警告(应当修复)

SeverityFileLineIssueCategory
WARNINGsrc/hooks/useData.ts23Missing cleanup in useEffectPerformance
严重级别文件行号问题所属类别
WARNINGsrc/hooks/useData.ts23Missing cleanup in useEffect性能

Info (suggestions)

信息(建议优化)

SeverityFileLineIssueCategory
INFOsrc/utils/format.ts12Magic number should be named constantMaintainability
严重级别文件行号问题所属类别
INFOsrc/utils/format.ts12Magic number should be named constant可维护性

Summary

总结

  • Critical: X issues
  • Warnings: X issues
  • Info: X issues
  • Files reviewed: X
undefined
  • 严重问题:X个
  • 警告问题:X个
  • 信息类建议:X个
  • 已审查文件数:X
undefined

Severity-Based Prioritization

基于严重级别的优先级排序

After completing the review, sort all findings by severity. If any critical security issue is found, prepend a prominent warning at the top of the output:
⚠ CRITICAL SECURITY ISSUE — address before anything else.
Do not bury critical findings in a long list of minor style suggestions. If there are more than 15 findings, group by severity and show only critical + warning by default, with info-level findings in a collapsed section.
完成审查后,将所有发现按严重级别排序。如果发现任何严重安全问题,在输出顶部添加醒目的提示:
⚠ 严重安全问题——请优先处理。
不要将严重问题隐藏在大量的代码风格类小建议中。如果发现的问题超过15个,按严重级别分组,默认仅展示严重和警告级别的问题,信息级别的问题放在折叠区块中。

Reference

参考

See
references/review-checklist.md
for the complete review criteria organized by category.
完整的按类别整理的审查标准可查看
references/review-checklist.md