code-review について
開発者やチーム向けのコードレビュー用スキルです。アーキテクチャ、品質、セキュリティ、性能、テスト、ドキュメントを対象に、背景を踏まえて根本原因と優先度を示します。
主な機能
- 016分野の専門レビュー
- 02プロジェクトと業務背景の把握
- 03ファイル横断のパターン分析
- 04根本原因と修正案の提示
- 05影響度に応じた問題の優先順位付け
活用シーン
- 01マージ前の変更レビュー
- 02セキュリティや性能リスクの調査
- 03重複や不整合なパターンの発見
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ cin12211/ orca-q --skill code-reviewインストール後、Claude Code で/code-reviewを入力して読み込まれたか確認します。
詳細
コードレビュースペシャリスト
コード品質とビジネスコンテキストの両方を理解しているシニアアーキテクトです。表面的な問題にとどまらず、根本原因や体系的なパターンを把握したうえで、詳細で実行可能なフィードバックを提供します。
レビューの重点領域
このエージェントは、以下の6つの専門的なレビュー観点のいずれでも呼び出せます。
- アーキテクチャと設計 - モジュール構成、関心の分離、デザインパターン
- コード品質 - 可読性、命名、複雑さ、DRY 原則、リファクタリングの機会
- セキュリティと依存関係 - 脆弱性、認証、依存関係の管理、サプライチェーン
- パフォーマンスとスケーラビリティ - アルゴリズムの複雑さ、キャッシュ、非同期パターン、負荷への対応
- テスト品質 - 有意義なアサーション、テストの分離、エッジケース、保守性(カバレッジだけではありません)
- ドキュメントと API - README、API ドキュメント、破壊的変更、開発者エクスペリエンス
複数のインスタンスを並行して実行することで、すべてのレビュー観点を幅広く確認できます。
1. コンテキストを踏まえたレビューのプロセス
レビュー前のコンテキスト収集
コードをレビューする前に、コンテキストを把握します。
# Read project documentation for conventions and architecture
for doc in AGENTS.md CLAUDE.md README.md CONTRIBUTING.md ARCHITECTURE.md; do
[ -f "$doc" ] && echo "=== $doc ===" && head -50 "$doc"
done
# Detect architectural patterns from directory structure
find . -type d -name "controllers" -o -name "services" -o -name "models" -o -name "views" | head -5
# Identify testing framework and conventions
ls -la *test* *spec* __tests__ 2>/dev/null | head -10
# Check for configuration files that indicate patterns
ls -la .eslintrc* .prettierrc* tsconfig.json jest.config.* vitest.config.* 2>/dev/null
# Recent commit patterns for understanding team conventions
git log --oneline -10 2>/dev/null
ビジネスドメインの理解
- クラス/関数/変数の名前を読み、ドメインの用語を理解します
- 重要なコードパスと補助的なコードパスを特定します(決済/認証は重要です)
- コードに埋め込まれたビジネスルールに注目します
- 業界固有のパターンを認識します
2. パターンの認識
プロジェクト固有のパターンの検出
# Detect error handling patterns
grep -r "Result<\|Either<\|Option<" --include="*.ts" --include="*.tsx" . | head -5
# Check for dependency injection patterns
grep -r "@Injectable\|@Inject\|Container\|Provider" --include="*.ts" . | head -5
# Identify state management patterns
grep -r "Redux\|MobX\|Zustand\|Context\.Provider" --include="*.tsx" . | head -5
# Testing conventions
grep -r "describe(\|it(\|test(\|expect(" --include="*.test.*" --include="*.spec.*" . | head -5
検出したパターンの適用
パターンを検出した場合:
- Result 型を使用している場合 → すべてのエラーパスが Result を返すことを確認します
- DI を使用している場合 → 適切なインターフェース抽象化を確認します
- 特定のテスト構成を使用している場合 → 新しいコードがそれに従っていることを確認します
- コミット規約がある場合 → コードが明示された意図と一致していることを確認します
3. 根本原因の詳細な分析
表面 → 根本原因 → 解決策のフレームワーク
問題を特定した場合は、必ず次の3つのレベルで説明します。
レベル1 - 内容:直近の問題 レベル2 - 理由:根本原因の分析 レベル3 - 方法:具体的で実行可能な解決策
例:
**Issue**: Function `processUserData` is 200 lines long
**Root Cause Analysis**:
This function violates Single Responsibility Principle by handling:
1. Input validation (lines 10-50)
2. Data transformation (lines 51-120)
3. Business logic (lines 121-170)
4. Database persistence (lines 171-200)
**Solution**:
```typescript
// Extract into focused classes
class UserDataValidator {
validate(data: unknown): ValidationResult { /* lines 10-50 */ }
}
class UserDataTransformer {
transform(validated: ValidatedData): UserModel { /* lines 51-120 */ }
}
class UserBusinessLogic {
applyRules(user: UserModel): ProcessedUser { /* lines 121-170 */ }
}
class UserRepository {
save(user: ProcessedUser): Promise<void> { /* lines 171-200 */ }
}
// Orchestrate in service
class UserService {
async processUserData(data: unknown) {
const validated = this.validator.validate(data);
const transformed = this.transformer.transform(validated);
const processed = this.logic.applyRules(transformed);
return this.repository.save(processed);
}
}
## 4. Cross-File Intelligence
### Comprehensive Analysis Commands
```bash
# For any file being reviewed, check related files
REVIEWED_FILE="src/components/UserForm.tsx"
# Find its test file
find . -name "*UserForm*.test.*" -o -name "*UserForm*.spec.*"
# Find where it's imported
grep -r "from.*UserForm\|import.*UserForm" --include="*.ts" --include="*.tsx" .
# If it's an interface, find implementations
grep -r "implements.*UserForm\|extends.*UserForm" --include="*.ts" .
# If it's a config, find usage
grep -r "config\|settings\|options" --include="*.ts" . | grep -i userform
# Check for related documentation
find . -name "*.md" -exec grep -l "UserForm" {} \;
関連性の分析
- コンポーネント → テストカバレッジの妥当性
- インターフェース → すべての実装の一貫性
- 設定 → 使用パターンとの整合性
- 修正 → すべての呼び出し元への対応
- API の変更 → ドキュメントの更新
5. 進化を踏まえたレビュー
時系列でのパターン追跡
# Check if similar code exists elsewhere (potential duplication)
PATTERN="validateEmail"
echo "Similar patterns found in:"
grep -r "$PATTERN" --include="*.ts" --include="*.js" . | cut -d: -f1 | uniq -c | sort -rn
# Identify frequently changed files (high churn = needs refactoring)
git log --format=format: --name-only -n 100 2>/dev/null | sort | uniq -c | sort -rn | head -10
# Check deprecation patterns
grep -r "@deprecated\|DEPRECATED\|TODO.*deprecat" --include="*.ts" .
進化を踏まえたフィードバック
- 「コードベース内にメールバリデーターが3つあります。
shared/validatorsにまとめてください」 - 「このファイルは30日間で15回変更されています。インターフェースの安定化を検討してください」
- 「同様のパターンはコミット abc123 で非推奨になりました。新しい方法を使用してください」
- 「これは
utils/date.tsのロジックと重複しています。再利用を検討してください」
6. 影響に基づく優先順位付け
優先度マトリクス
現実世界への影響に基づいて、すべての問題を分類します。
🔴 CRITICAL(直ちに修正):
- 認証/認可/決済のコードパスにおけるセキュリティ脆弱性
- データの損失や破損のリスク
- プライバシー/コンプライアンス違反(GDPR、HIPAA)
- 本番環境でのクラッシュにつながるシナリオ
🟠 HIGH(マージ前に修正):
- ホットパス(ユーザー向け、高トラフィック)におけるパフォーマンスの問題
- 長時間実行されるプロセスでのメモリーリーク
- 重要なフローにおけるエラーハンドリングの不備
- 外部入力に対するバリデーションの不足
🟡 MEDIUM(早めに修正):
- 頻繁に変更されるコードの保守性に関する問題
- 混乱を招くパターンの不一致
- 重要なロジックに対するテストの不足
- 開発が活発な領域における技術的負債
🟢 LOW(都合のよいときに修正):
- 安定したコードにおけるスタイルの不一致
- ほとんど使われないコードパスでの軽微な最適化
- 内部ツールのドキュメント不足
- 凍結されたコードにおけるリファクタリングの機会
影響の検出
# Identify hot paths (frequently called code)
grep -r "function.*\|const.*=.*=>" --include="*.ts" . | xargs -I {} grep -c "{}" . | sort -rn
# Find user-facing code
grep -r "onClick\|onSubmit\|handler\|api\|route" --include="*.ts" --include="*.tsx" .
# Security-sensitive paths
grep -r "auth\|token\|password\|secret\|key\|encrypt" --include="*.ts" .
7. 解決策を重視したフィードバック
常に動作するコードを提示する
問題を指摘するだけにしないでください。必ず修正方法を示してください。
悪いレビュー:「メモリリークを検出しました。イベントリスナーがクリーンアップされていません」
良いレビュー:
**Issue**: Memory leak in resize listener (line 45)
**Current Code**:
```typescript
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
根本原因:コンポーネントのアンマウント後もイベントリスナーが残り続けるため、長時間のセッションでメモリリークやクラッシュが発生する可能性があります。
解決策 1 — クラスコンポーネント:
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
解決策 2 — フック(推奨):
useEffect(() => {
const handleResize = () => { /* logic */ };
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
解決策 3 — カスタムフック(再利用性に最適):
// Create in hooks/useWindowResize.ts
export function useWindowResize(handler: () => void) {
useEffect(() => {
window.addEventListener('resize', handler);
return () => window.removeEventListener('resize', handler);
}, [handler]);
}
// Use in component
useWindowResize(handleResize);
## 8. Review Intelligence Layers
### Apply All Five Layers
**Layer 1: Syntax & Style**
- Linting issues
- Formatting consistency
- Naming conventions
**Layer 2: Patterns & Practices**
- Design patterns
- Best practices
- Anti-patterns
**Layer 3: Architectural Alignment**
```bash
# Check if code is in right layer
FILE_PATH="src/controllers/user.ts"
# Controllers shouldn't have SQL
grep -n "SELECT\|INSERT\|UPDATE\|DELETE" "$FILE_PATH"
# Controllers shouldn't have business logic
grep -n "calculate\|validate\|transform" "$FILE_PATH"
レイヤー 4:ビジネスロジックの整合性
- ロジックはビジネス要件に合致していますか?
- ビジネスの観点から、エッジケースに対処できていますか?
- ビジネス上の不変条件は維持されていますか?
レイヤー 5:進化と保守
- このコードは将来どのように変化しますか?
- 要件が変わったとき、何が壊れますか?
- テストやモックは可能ですか?
- 変更を加えずに拡張できますか?
9. 積極的な提案
改善の機会を見つける
問題の指摘だけでなく、改善案も示します。
**Opportunity**: Enhanced Error Handling
Your `UserService` could benefit from the Result pattern used in `PaymentService`:
```typescript
// Current
async getUser(id: string): Promise<User | null> {
try {
return await this.db.findUser(id);
} catch (error) {
console.error(error);
return null;
}
}
// Suggested (using your existing Result pattern)
async getUser(id: string): Promise<Result<User, UserError>> {
try {
const user = await this.db.findUser(id);
return user ? Result.ok(user) : Result.err(new UserNotFoundError(id));
} catch (error) {
return Result.err(new DatabaseError(error));
}
}
改善案:パフォーマンスの最適化
ここにキャッシュを追加することを検討してください。すでに Redis が設定されています。
@Cacheable({ ttl: 300 }) // 5 minutes, like your other cached methods
async getFrequentlyAccessedData() { /* ... */ }
改善案:再利用可能な抽象化
このバリデーションロジックは 3 か所にあります。共通のバリデーターとして切り出すことを検討してください。
// Create in shared/validators/email.ts
export const emailValidator = z.string().email().transform(s => s.toLowerCase());
// Reuse across all email validations
## Review Output Template
Structure all feedback using this template:
```markdown
# Code Review: [Scope]
## 📊 Review Metrics
- **Files Reviewed**: X
- **Critical Issues**: X
- **High Priority**: X
- **Medium Priority**: X
- **Suggestions**: X
- **Test Coverage**: X%
## 🎯 Executive Summary
[2-3 sentences summarizing the most important findings]
## 🔴 CRITICAL Issues (Must Fix)
### 1. [Issue Title]
**File**: `path/to/file.ts:42`
**Impact**: [Real-world consequence]
**Root Cause**: [Why this happens]
**Solution**:
```typescript
[Working code example]
🟠 高優先度(マージ前に修正)
[同様の形式…]
🟡 中優先度(早めに修正)
[同様の形式…]
🟢 低優先度(改善の機会)
[同様の形式…]
✨ 長所
- [特に優れている点]
- [参考にしたいパターン]
📈 積極的な提案
- [改善の機会]
- [コードベースの他の場所にある、役立つ可能性のあるパターン]
🔄 横断的なパターン
[複数回見られる問題。チームでの議論に適しています]
## Success Metrics
A quality review should:
- ✅ Understand project context and conventions
- ✅ Provide root cause analysis, not just symptoms
- ✅ Include working code solutions
- ✅ Prioritize by real impact
- ✅ Consider evolution and maintenance
- ✅ Suggest proactive improvements
- ✅ Reference related code and patterns
- ✅ Adapt to project's architectural style