Code Review Orchestration Workflow
Comprehensive code review workflow orchestrating 12-15 specialized reviewers across automated checks, parallel expert reviews, integration analysis, and final approval recommendation. Designed for thorough quality validation across security, performance, architecture, testing, and documentation dimensions in a systematic 4-hour process.
Overview
This SOP implements a multi-dimensional code review process using star topology coordination where a central PR manager orchestrates specialized reviewers operating in parallel. The workflow emphasizes both thoroughness and efficiency by running automated checks first (gate 1), then parallelizing specialized human-centric reviews, followed by integration impact analysis, and finally synthesizing all findings into actionable recommendations.
The star pattern enables each specialist to focus deeply on their domain while the coordinator ensures comprehensive coverage and prevents conflicting feedback. Memory coordination allows reviewers to reference findings from other specialists, creating a holistic review experience.
Trigger Conditions
Use this workflow when:
- Reviewing pull requests requiring comprehensive quality validation
- Changes span multiple quality dimensions (code, security, performance, architecture)
- Need systematic review from multiple specialist perspectives
- PR introduces significant functionality or architectural changes
- Merge decision requires evidence-based go/no-go recommendation
- Team wants consistent, repeatable review process
- Code review SLA is within 4 hours (business hours)
Orchestrated Agents (15 Total)
Coordination Agent
pr-manager - PR coordination, review orchestration, findings aggregation, author notification
Automated Check Agents (Phase 1)
code-analyzer - Linting, static analysis, code complexity metrics
tester - Test execution, test suite validation
qa-engineer - Coverage analysis, test quality assessment
Specialized Review Agents (Phase 2)
code-analyzer - Code quality, readability, maintainability, DRY, SOLID principles
security-manager - Security vulnerabilities, OWASP compliance, secrets scanning, auth/auth
performance-analyzer - Performance regressions, algorithmic efficiency, resource optimization
system-architect - Architectural consistency, design patterns, scalability, integration fit
api-documentation-specialist - Code documentation, API docs, comments, examples
style-auditor - Code style consistency, formatting standards
dependency-analyzer - Dependency audit, outdated packages, security vulnerabilities
test-coverage-reviewer - Coverage metrics, uncovered code paths, edge case testing
documentation-reviewer - README updates, changelog, migration guides
Integration Analysis Agents (Phase 3)
system-integrator - Integration impact, breaking changes, backward compatibility
devops-engineer - Deployment impact, infrastructure changes, rollback planning
code-reviewer - Risk assessment, blast radius analysis
Workflow Phases
Phase 1: Automated Checks (30 Minutes, Parallel Gate)
Duration: 30 minutes
Execution Mode: Parallel automated validation (fast fail-fast gate)
Agents: code-analyzer, tester, qa-engineer, pr-manager
Process:
Initialize Review Swarm
PR_ID="$1" # e.g., "repo-name/pulls/123"
PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)
npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"
npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized
npx claude-flow agent spawn --type pr-manager
PR Manager retrieves PR metadata:
- Changed files and line counts
- Commit history and messages
- Branch comparison (base vs head)
- PR description and labels
- Author and reviewers assigned
Memory Storage:
npx claude-flow memory store --key "code-review/${PR_ID}/metadata" \
--value '{"pr_number": "'"${PR_NUMBER}"'", "files_changed": 15, "lines_added": 342, "lines_deleted": 78}'
Run Automated Checks in Parallel
npx claude-flow task orchestrate --strategy parallel --max-agents 4
Spawn all automated check agents concurrently:
Linting Check (Code Analyzer):
npx claude-flow agent spawn --type code-analyzer --focus "linting"
# Run linting
npm run lint # ESLint for JS/TS
# or
pylint src/ # Python
# or
rubocop # Ruby
Checks:
- Code style violations (max line length, indentation)
- Unused variables and imports
- Type errors (TypeScript)
- Deprecated API usage
- Code complexity warnings
Memory Pattern: code-review/${PR_ID}/phase-1/code-analyzer/lint-results
Test Execution (Tester):
npx claude-flow agent spawn --type tester --focus "test-execution"
# Run test suite
npm test # Jest/Mocha
# or
pytest # Python
# or
rspec # Ruby
Validates:
- All unit tests passing
- All integration tests passing
- All E2E tests passing (if applicable)
- No flaky test failures
- Test execution time within limits
Memory Pattern: code-review/${PR_ID}/phase-1/tester/test-results
Coverage Analysis (QA Engineer):
npx claude-flow agent spawn --type tester --focus "coverage"
# Generate coverage report
npm run test:coverage
Checks:
- Overall coverage > 80%
- New code coverage > 90%
- No critical paths uncovered
- Coverage delta (did coverage decrease?)
- Untested branches and conditions
Memory Pattern: code-review/${PR_ID}/phase-1/qa-engineer/coverage-report
Build Validation (Code Analyzer):
# Clean build validation
npm run build
# or
python setup.py build
Validates:
- Clean build (no errors, no warnings)
- Type checking passes (TypeScript, mypy)
- No broken dependencies
- Bundle size within limits (for frontend)
- No circular dependencies
Memory Pattern: code-review/${PR_ID}/phase-1/code-analyzer/build-status
Evaluate Gate 1 Results
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"
PR Manager aggregates automated results:
- Lint: PASS/FAIL (violations count)
- Tests: PASS/FAIL (passed/failed/skipped)
- Coverage: PASS/FAIL (percentage, delta)
- Build: PASS/FAIL (errors/warnings)
Decision Logic:
if (lintFailed || testsFailed || buildFailed) {
// Request fixes from author
await notifyAuthor({
status: 'CHANGES_REQUESTED',
message: 'Automated checks failed. Please fix before review continues.',
details: summarizeFailures()
});
// Store feedback and stop review
await memory_store(`code-review/${PR_ID}/phase-1/automated-feedback`);
return; // Stop review until fixed
}
// All automated checks passed, proceed to Phase 2
await notifyAuthor({
status: 'IN_REVIEW',
message: 'Automated checks passed. Proceeding with specialized reviews.'
});
Outputs:
- Automated check results (pass/fail for each)
- Test execution report
- Coverage report with delta
- Build status
Success Criteria:
Phase 2: Specialized Reviews (2 Hours, Parallel Expert Analysis)
Duration: 2 hours
Execution Mode: Parallel specialized reviews coordinated by PR manager
Agents: 10 specialist reviewers
Process:
Initialize Specialist Review Swarm
npx claude-flow task orchestrate --strategy parallel --max-agents 10 --priority high
Spawn All Specialist Reviewers Concurrently
Each specialist reviews the PR from their domain expertise:
Code Quality Review (Code Analyzer):
npx claude-flow agent spawn --type code-analyzer --focus "code-quality"
Reviews:
- Readability: Clear names, appropriate function length, logical organization, cognitive complexity
- Maintainability: DRY principle, SOLID principles, separation of concerns, error handling
- Best Practices: Language idioms, design patterns, appropriate comments, no code smells
Rating: 1-5 stars
Findings Format:
{
"category": "code_quality",
"findings": [
{
"severity": "MEDIUM",
"file": "src/utils/parser.ts",
"line": 45,
"issue": "Function 'parseData' has cognitive complexity of 15 (max 10)",
"suggestion": "Extract nested conditionals into separate validation functions"
}
],
"rating": 4,
"overall_assessment": "Good code quality with minor improvements needed"
}
Memory Pattern: code-review/${PR_ID}/phase-2/code-analyzer/quality-review
Security Review (Security Manager):
npx claude-flow agent spawn --type security-manager --focus "security-comprehensive"
Reviews:
- Authentication & Authorization: Proper auth checks, no privilege escalation, secure sessions
- Data Security: Input validation (injection prevention), output encoding (XSS prevention), sensitive data encryption, no hardcoded secrets
- OWASP Top 10: SQL Injection, XSS, CSRF, insecure dependencies, security misconfigurations
Severity: CRITICAL/HIGH/MEDIUM/LOW
Findings Format:
{
"category": "security",
"findings": [
{
"severity": "HIGH",
"file": "src/api/users.ts",
"line": 78,
"issue": "User input not sanitized before database query (SQL Injection risk)",
"owasp_category": "A03:2021 – Injection",
"suggestion": "Use parameterized queries or ORM with proper escaping"
},
{
"severity": "MEDIUM",
"file": "src/config/secrets.ts",
"line": 12,
"issue": "API key appears to be hardcoded (potential secret leak)",
"suggestion": "Move to environment variables and add to .env.example"
}
],
"critical_count": 0,
"high_count": 1,
"medium_count": 1,
"overall_assessment": "1 high-severity issue must be fixed before merge"
}
Memory Pattern: code-review/${PR_ID}/phase-2/security-manager/security-review
Performance Review (Performance Analyzer):
npx claude-flow agent spawn --type perf-analyzer --focus "performance-optimization"
Reviews:
- Algorithmic Efficiency: Time complexity (no unnecessary O(n²)), efficient data structures, no redundant iterations
- Resource Usage: No memory leaks, proper cleanup (connections, files, timers), efficient queries (avoid N+1)
- Optimization Opportunities: Caching potential, parallelization, database indexes, API call reduction
Impact: HIGH/MEDIUM/LOW
Findings Format:
{
"category": "performance",
"findings": [
{
"impact": "HIGH",
"file": "src/services/user-service.ts",
"line": 125,
"issue": "N+1 query problem: Loading user roles in loop (1 + N queries)",
"performance_cost": "10x slower for 100 users",
"suggestion": "Use eager loading with JOIN or batch query with IN clause"
}
],
"high_impact_count": 1,
"estimated_improvement": "10x faster with suggested optimizations",
"overall_assessment": "Significant performance regression without optimization"
}
Memory Pattern: code-review/${PR_ID}/phase-2/performance-analyzer/performance-review
Architecture Review (System Architect):
npx claude-flow agent spawn --type system-architect --focus "architecture-consistency"
Reviews:
- Design Patterns: Follows established patterns, appropriate abstraction, dependency injection, clean architecture
- Integration: Fits with existing code, no unexpected side effects, backward compatibility, API contracts respected
- Scalability: Supports future growth, no hardcoded limits, stateless design, horizontally scalable
Concerns: BLOCKER/MAJOR/MINOR
Findings Format:
{
"category": "architecture",
"findings": [
{
"concern": "MAJOR",
"file": "src/services/payment-service.ts",
"issue": "Payment service directly couples to Stripe SDK (violates adapter pattern)",
"impact": "Difficult to switch payment providers in future",
"suggestion": "Create PaymentProvider interface and StripeAdapter implementation"
}
],
"blocker_count": 0,
"major_count": 1,
"overall_assessment": "Architecture mostly consistent with 1 major design concern"
}
Memory Pattern: code-review/${PR_ID}/phase-2/system-architect/architecture-review
Documentation Review (API Documentation Specialist):
npx claude-flow agent spawn --type api-docs --focus "documentation-comprehensive"
Reviews:
- Code Documentation: Public APIs documented (JSDoc/docstring), complex logic explained, non-obvious behavior noted
- External Documentation: README updated, API docs updated, migration guide (if breaking), changelog updated
- Tests as Documentation: Descriptive test names, test coverage demonstrates usage, edge cases documented
Completeness: 0-100%
Findings Format:
{
"category": "documentation",
"findings": [
{
"severity": "MEDIUM",
"file": "src/api/webhooks.ts",
"issue": "New webhook endpoint /api/webhooks/stripe missing API documentation",
"suggestion": "Add JSDoc with parameters, responses, and usage example"
}
],
"code_doc_coverage": 75,
"external_doc_updated": false,
"overall_assessment": "75% complete, missing API docs and changelog update"
}
Memory Pattern: code-review/${PR_ID}/phase-2/api-documentation-specialist/docs-review
Additional Specialist Reviews (run in parallel):
- Style Audit (Style Auditor): Code style consistency, formatting compliance
- Dependency Audit (Dependency Analyzer): Outdated packages, security vulnerabilities in deps
- Test Coverage (Test Coverage Reviewer): Coverage gaps, missing edge cases
- Documentation Completeness (Documentation Reviewer): README, changelog, migration guides
Each follows similar format with findings, severity, and recommendations.
Aggregate Specialist Reviews
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/*/review"
npx claude-flow agent spawn --type pr-manager --focus "aggregation"
PR Manager synthesizes all reviews:
- Total findings: 15 issues (0 critical, 1 high, 8 medium, 6 low)
- Quality rating: 4/5 stars
- Security: 1 high-severity issue
- Performance: 1 high-impact issue
- Architecture: 1 major concern
- Documentation: 75% complete
Categorize issues:
- Blocking Issues (must fix before merge): High-severity security issue, high-impact performance regression
- High-Priority (should fix): Major architecture concern, medium security issues
- Nice-to-Have (can fix later): Low-severity code quality improvements
Memory Storage:
npx claude-flow memory store --key "code-review/${PR_ID}/phase-2/aggregated-review" \
--value "${AGGREGATED_FINDINGS_JSON}"
Outputs:
- 10 specialized review reports
- Aggregated findings with severity prioritization
- Blocking issues list
- Recommendations summary
Success Criteria:
Phase 3: Integration Analysis (1 Hour, Sequential Impact Assessment)
Duration: 1 hour
Execution Mode: Sequential end-to-end impact analysis
Agents: tester, devops-engineer, product-manager, code-reviewer
Process:
Integration Testing
npx claude-flow agent spawn --type tester --focus "integration-impact"
QA Engineer tests:
- Does this change break existing functionality?
- Are all integration tests passing?
- Does it integrate properly with related modules?
- Any unexpected side effects or regressions?
Run integration test suite:
npm run test:integration
Findings:
- Integration tests: 45/45 passing
- No regressions detected
- New functionality integrates cleanly
Memory Pattern: code-review/${PR_ID}/phase-3/tester/integration-tests
Deployment Impact Assessment
npx claude-flow memory retrieve --key "code-review/${PR_ID}/metadata"
npx claude-flow agent spawn --type cicd-engineer --focus "deployment-impact"
DevOps Engineer evaluates:
- Infrastructure changes needed? (new services, scaling)
- Database migrations required? (schema changes)
- Configuration updates needed? (env vars, secrets)
- Backward compatibility maintained? (can rollback safely)
- Rollback plan clear and tested?
Findings:
{
"infrastructure_changes": ["Add Redis cache for session storage"],
"database_migrations": ["Add index on users.email for faster lookups"],
"config_updates": ["Add REDIS_URL environment variable"],
"backward_compatible": true,
"rollback_complexity": "LOW",
"deployment_risk": "MEDIUM"
}
Memory Pattern: code-review/${PR_ID}/phase-3/devops-engineer/deployment-impact
User Impact Assessment
npx claude-flow agent spawn --type planner --focus "user-impact"
Product Manager assesses:
- Does this improve user experience?
- Any user-facing changes? (UI/UX)
- Consistent with design system?
- Analytics/tracking updated?
- Feature flags needed?
Findings:
{
"user_facing_changes": ["New export functionality in dashboard"],
"ux_impact": "POSITIVE",
"design_system_compliant": true,
"analytics_updated": false,
"feature_flag_recommended": true
}
Memory Pattern: code-review/${PR_ID}/phase-3/product-manager/user-impact
Risk Assessment
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-3/*"
npx claude-flow agent spawn --type reviewer --focus "risk-analysis"
Code Reviewer analyzes:
- What's the blast radius of this change? (how many users/services affected)
- Worst-case failure scenario? (data loss, downtime, security breach)
- Do we have rollback procedures? (tested and documented)
- Should this be feature-flagged? (gradual rollout)
- Is monitoring and alerting adequate? (can detect issues quickly)
Risk Matrix:
{
"blast_radius": "MEDIUM (affects 30% of users)",
"worst_case_scenario": "Temporary export failures (no data loss)",
"rollback_available": true,
"rollback_tested": false,
"feature_flag_needed": true,
"monitoring_adequate": true,
"overall_risk": "MEDIUM",
"recommendation": "CONDITIONAL_APPROVE (add feature flag + test rollback)"
}
Memory Pattern: code-review/${PR_ID}/phase-3/code-reviewer/risk-analysis
Outputs:
- Integration test results
- Deployment impact report
- User impact assessment
- Risk analysis with mitigation recommendations
Success Criteria:
Phase 4: Final Approval (30 Minutes, Decision & Notification)
Duration: 30 minutes
Execution Mode: Sequential synthesis and decision
Agents: pr-manager
Process:
Generate Final Review Summary
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"
npx claude-flow agent spawn --type pr-manager --focus "final-summary"
PR Manager synthesizes all phases:
Summary Report:
# Code Review Summary: PR #${PR_NUMBER}
## Automated Checks ✅
- Linting: ✅ PASS (0 violations)
- Tests: ✅ PASS (142/142 passing)
- Coverage: ✅ PASS (93.5%, +2.3% delta)
- Build: ✅ PASS (clean build, no warnings)
## Specialized Reviews
- **Code Quality**: 4/5 stars (Good quality, minor improvements suggested)
- **Security**: ⚠️ 1 HIGH issue (SQL injection risk in user query)
- **Performance**: ⚠️ 1 HIGH impact (N+1 query problem)
- **Architecture**: ⚠️ 1 MAJOR concern (tight coupling to payment provider)
- **Documentation**: 75% complete (missing API docs + changelog)
## Integration Analysis
- **Integration Tests**: ✅ All passing (45/45)
- **Deployment Impact**: MEDIUM risk (requires Redis + DB migration)
- **User Impact**: POSITIVE (new export feature)
- **Risk Level**: MEDIUM (feature flag recommended)
## Blocking Issues (MUST FIX)
1. [HIGH/SECURITY] SQL injection risk in src/api/users.ts:78
2. [HIGH/PERFORMANCE] N+1 query in src/services/user-service.ts:125
## High-Priority Recommendations (SHOULD FIX)
3. [MAJOR/ARCHITECTURE] Decouple payment service from Stripe SDK
4. [MEDIUM/DOCUMENTATION] Add API documentation for webhook endpoint
5. [MEDIUM/DEPLOYMENT] Add feature flag for gradual rollout
## Overall Decision: ⏸️ REQUEST CHANGES
**Rationale**: Code is high quality overall, but 2 blocking issues (security + performance) must be addressed before merge. Once fixed, this PR will be ready for production.
**Next Steps**:
1. Author fixes blocking issues (estimated 2-4 hours)
2. Re-run automated checks + security/performance reviews
3. Once green, approve for merge with feature flag enabled
Memory Storage:
npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/final-summary" \
--value "${FINAL_SUMMARY_MARKDOWN}"
Determine Decision
Decision Logic:
function determineDecision(aggregatedReview) {
const { blocking, highPriority, security, performance } = aggregatedReview;
// REJECT: Fundamental architectural problems or severe quality issues
if (blocking.length > 5 || security.critical > 0) {
return {
decision: 'REJECT',
message: 'Too many critical issues or fundamental architectural problems. Consider alternative approach.'
};
}
// REQUEST CHANGES: Blocking issues that must be fixed
if (blocking.length > 0 || security.high > 0 || performance.high > 0) {
return {
decision: 'REQUEST_CHANGES',
message: `${blocking.length} blocking issue(s) must be fixed before merge.`
};
}
// CONDITIONAL APPROVE: High-priority items should be addressed
if (highPriority.length > 0) {
return {
decision: 'CONDITIONAL_APPROVE',
message: `Approved with ${highPriority.length} recommendations to address before or after merge.`
};
}
// APPROVE: All quality gates passed
return {
decision: 'APPROVE',
message: 'All quality checks passed. Ready to merge.'
};
}
Notify Author
npx claude-flow agent spawn --type pr-manager --focus "author-notification"
PR Manager sends notification:
- GitHub PR comment with full review summary
- Label PR appropriately ("changes-requested", "approved", "rejected")
- Assign back to author (if changes needed)
- Tag relevant reviewers for specific issues
GitHub PR Comment (example for REQUEST_CHANGES):
## 🔍 Comprehensive Code Review Complete
Thank you for your contribution! Our automated review system has completed a thorough analysis.
### ✅ What Went Well
- All automated checks passing (tests, coverage, linting)
- Clean code architecture overall
- Good test coverage (93.5%)
### ⚠️ Issues Requiring Attention
#### Blocking Issues (Must Fix Before Merge)
1. **[HIGH/SECURITY]** SQL Injection Risk
- **File**: `src/api/users.ts:78`
- **Issue**: User input not sanitized before database query
- **Fix**: Use parameterized queries or ORM with proper escaping
- **Priority**: CRITICAL
2. **[HIGH/PERFORMANCE]** N+1 Query Problem
- **File**: `src/services/user-service.ts:125`
- **Issue**: Loading user roles in loop (10x slower for 100 users)
- **Fix**: Use eager loading with JOIN or batch query
- **Priority**: HIGH
#### Recommendations (Should Address)
3. **[MAJOR/ARCHITECTURE]** Payment Service Coupling
- Create PaymentProvider interface for future flexibility
- See: [Architecture Best Practices](link)
4. **[MEDIUM/DOCUMENTATION]** Missing API Documentation
- Add JSDoc for webhook endpoint
- Update changelog with this new feature
### 🔄 Next Steps
1. Address the 2 blocking issues above
2. Push updates to this PR branch
3. Automated checks will re-run automatically
4. We'll re-review security and performance aspects
5. Once green, we'll approve for merge!
**Estimated time to fix**: 2-4 hours
---
🤖 Generated by Claude Code Review System | [View Full Report](link)
Memory Storage:
npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/author-notification"
npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-report true
Execute Decision Actions
Based on decision, take appropriate GitHub actions:
If APPROVE:
# Add approval label
gh pr edit ${PR_NUMBER} --add-label "approved"
# Add approval review
gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."
# Queue for merge (if auto-merge enabled)
gh pr merge ${PR_NUMBER} --auto --squash
If REQUEST_CHANGES:
# Add changes-requested label
gh pr edit ${PR_NUMBER} --add-label "changes-requested" --remove-label "approved"
# Request changes
gh pr review ${PR_NUMBER} --request-changes --body "${REVIEW_COMMENT_MARKDOWN}"
# Assign back to author
gh pr edit ${PR_NUMBER} --add-assignee ${AUTHOR_USERNAME}
# Schedule follow-up review
npx claude-flow memory store --key "code-review/${PR_ID}/follow-up/scheduled" --value "true"
If REJECT:
# Add rejected label
gh pr edit ${PR_NUMBER} --add-label "rejected"
# Provide detailed explanation
gh pr review ${PR_NUMBER} --request-changes --body "${DETAILED_REJECTION_REASON}"
# Suggest alternative approaches
gh pr comment ${PR_NUMBER} --body "Consider these alternative approaches: ${ALTERNATIVES}"
Finalize Review Session
npx claude-flow hooks session-end --export-metrics true
npx claude-flow hooks post-task --task-id "pr-${PR_ID}"
Outputs:
- Final review summary (comprehensive report)
- Merge decision (Approve/Request Changes/Reject)
- Author notification (GitHub comment)
- GitHub labels and status updated
Success Criteria:
Memory Coordination
Namespace Convention
All review data follows this hierarchical pattern:
code-review/{pr-id}/phase-{N}/{reviewer-type}/{findings-type}
Examples:
code-review/repo/pulls/123/metadata
code-review/repo/pulls/123/phase-1/code-analyzer/lint-results
code-review/repo/pulls/123/phase-2/security-manager/security-review
code-review/repo/pulls/123/phase-3/devops-engineer/deployment-impact
code-review/repo/pulls/123/phase-4/final-summary
Cross-Phase Data Flow
Phase 1 → Phase 2:
# Phase 2 reviewers check if Phase 1 passed
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"
# Only proceed if all automated checks passed
if [ "$(jq '.all_passed' < phase1_results.json)" = "true" ]; then
# Spawn specialist reviewers
npx claude-flow task orchestrate --strategy parallel
fi
Phase 2 → Phase 3:
# Phase 3 integration analysis references specialist findings
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/security-manager/security-review"
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/performance-analyzer/performance-review"
# Risk analysis considers all specialist findings
Phase 3 → Phase 4:
# Phase 4 final decision aggregates all prior phases
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"
# Generate comprehensive summary
Scripts & Automation
Pre-Review Initialization
#!/bin/bash
# Initialize code review workflow
PR_NUMBER="$1"
REPO="$2" # e.g., "owner/repo"
PR_ID="${REPO}/pulls/${PR_NUMBER}"
# Fetch PR metadata via GitHub API
PR_DATA=$(gh pr view ${PR_NUMBER} --json number,title,author,files,additions,deletions)
# Setup coordination
npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"
# Initialize star topology swarm (central coordinator + specialists)
npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized
# Store PR metadata
npx claude-flow memory store --key "code-review/${PR_ID}/metadata" --value "${PR_DATA}"
echo "✅ Code review initialized: PR #${PR_NUMBER}"
Automated Check Gate
#!/bin/bash
# Execute Phase 1 automated checks (gate)
PR_ID="$1"
echo "🤖 Running automated checks..."
# Run checks in parallel
npx claude-flow task orchestrate --strategy parallel --max-agents 4 << EOF
lint: npm run lint
test: npm test
coverage: npm run test:coverage
build: npm run build
EOF
# Aggregate results
LINT_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/lint-results" | jq -r '.status')
TEST_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/tester/test-results" | jq -r '.status')
COVERAGE_OK=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/qa-engineer/coverage-report" | jq -r '.meets_threshold')
BUILD_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/build-status" | jq -r '.status')
# Check if all passed
if [ "$LINT_STATUS" = "PASS" ] && [ "$TEST_STATUS" = "PASS" ] && [ "$COVERAGE_OK" = "true" ] && [ "$BUILD_STATUS" = "PASS" ]; then
echo "✅ All automated checks passed. Proceeding to specialist reviews."
exit 0
else
echo "❌ Automated checks failed. Requesting fixes from author."
gh pr review ${PR_NUMBER} --request-changes --body "Automated checks failed. Please fix before review continues."
exit 1
fi
Parallel Specialist Review
#!/bin/bash
# Execute Phase 2 specialist reviews in parallel
PR_ID="$1"
echo "👥 Spawning specialist reviewers..."
# Spawn all reviewers concurrently via Claude Flow
npx claude-flow task orchestrate --strategy parallel --max-agents 10 << EOF
code_quality: Review code quality (readability, maintainability, best practices)
security: Review security vulnerabilities (OWASP Top 10, secrets, auth)
performance: Review performance (algorithms, resource usage, optimizations)
architecture: Review architecture consistency (patterns, integration, scalability)
documentation: Review documentation completeness (code docs, API docs, changelog)
style: Review code style consistency
dependencies: Review dependency security and updates
test_coverage: Review test coverage gaps
external_docs: Review README and migration guides
integration: Review integration fit with existing codebase
EOF
# Wait for all reviews to complete
npx claude-flow task status --wait
echo "✅ All specialist reviews complete."
Final Decision Script
#!/bin/bash
# Generate final decision and notify author
PR_ID="$1"
PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)
# Retrieve all review data
npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**" > "/tmp/${PR_ID}-reviews.json"
# Count issues by severity
CRITICAL_COUNT=$(jq '[.. | .severity? | select(. == "CRITICAL")] | length' /tmp/${PR_ID}-reviews.json)
HIGH_COUNT=$(jq '[.. | .severity? | select(. == "HIGH")] | length' /tmp/${PR_ID}-reviews.json)
BLOCKING_COUNT=$((CRITICAL_COUNT + HIGH_COUNT))
# Determine decision
if [ $CRITICAL_COUNT -gt 0 ] || [ $BLOCKING_COUNT -gt 5 ]; then
DECISION="REJECT"
elif [ $BLOCKING_COUNT -gt 0 ]; then
DECISION="REQUEST_CHANGES"
else
DECISION="APPROVE"
fi
echo "📊 Review Decision: ${DECISION}"
echo " Critical Issues: ${CRITICAL_COUNT}"
echo " High-Severity Issues: ${HIGH_COUNT}"
# Notify author via GitHub
case $DECISION in
APPROVE)
gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."
gh pr edit ${PR_NUMBER} --add-label "approved"
;;
REQUEST_CHANGES)
gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-summary.md"
gh pr edit ${PR_NUMBER} --add-label "changes-requested"
;;
REJECT)
gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-rejection.md"
gh pr edit ${PR_NUMBER} --add-label "rejected"
;;
esac
# Finalize session
npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-metrics true
Success Criteria
Review Quality Metrics
- Coverage: All quality dimensions reviewed (code, security, performance, architecture, docs)
- Consistency: Reviews follow established guidelines and standards
- Actionability: All feedback is specific, constructive, and actionable
- Timeliness: Reviews completed within 4 hours (business hours)
Code Quality Gates
- Automated Tests: 100% passing (no failing tests)
- Code Coverage: > 80% overall, > 90% for new code
- Linting: 0 violations (all style rules followed)
- Security: 0 critical issues, 0 high-severity issues
- Performance: No high-impact performance regressions
- Documentation: 100% of public APIs documented
Process Metrics
- Review Turnaround: < 4 hours (from PR creation to decision)
- Author Satisfaction: > 4/5 (feedback is helpful and constructive)
- Defect Escape Rate: < 1% (issues found in production that should have been caught)
- False Positive Rate: < 5% (flagged issues that weren't actually problems)
Usage Examples
Example 1: Small Feature PR (Simple)
# Feature: Add email validation to registration form
PR_NUMBER=245
PR_ID="acme-app/pulls/245"
# Initialize review
./init-review.sh ${PR_NUMBER} "acme/acme-app"
# Phase 1: Automated checks (5 minutes)
./automated-checks.sh ${PR_ID}
# Output: All checks passed
# Phase 2: Specialist reviews (30 minutes - small PR)
./specialist-reviews.sh ${PR_ID}
# Output: 3 minor issues (all LOW severity)
# Phase 3: Integration analysis (10 minutes)
# Output: No integration concerns, backward compatible
# Phase 4: Final decision
./final-decision.sh ${PR_ID}
# Decision: ✅ APPROVE
# Output: "All quality checks passed. 3 minor suggestions for future consideration."
Example 2: Large Refactoring PR (Complex)
# Refactoring: Migrate from REST to GraphQL
PR_NUMBER=312
PR_ID="acme-app/pulls/312"
# Initialize review
./init-review.sh ${PR_NUMBER} "acme/acme-app"
# Phase 1: Automated checks (10 minutes)
./automated-checks.sh ${PR_ID}
# Output: All checks passed, coverage 94%
# Phase 2: Specialist reviews (2 hours)
./specialist-reviews.sh ${PR_ID}
# Output: 15 findings
# - 1 HIGH/SECURITY (authentication flow changed, needs verification)
# - 2 HIGH/PERFORMANCE (N+1 queries in new resolvers)
# - 3 MAJOR/ARCHITECTURE (GraphQL schema design concerns)
# - 9 MEDIUM/LOW (documentation, minor improvements)
# Phase 3: Integration analysis (1 hour)
# Output: Breaking changes for API clients, migration guide needed
# Risk: HIGH (affects all API consumers)
# Phase 4: Final decision
./final-decision.sh ${PR_ID}
# Decision: ⏸️ REQUEST CHANGES
# Output: "3 blocking issues (security + performance). Add feature flag for gradual rollout. Provide migration guide for API clients."
Example 3: Security Patch PR (Critical)
# Security: Fix SQL injection vulnerability
PR_NUMBER=418
PR_ID="acme-app/pulls/418"
# Initialize expedited review
./init-review.sh ${PR_NUMBER} "acme/acme-app"
# Phase 1: Automated checks (5 minutes)
./automated-checks.sh ${PR_ID}
# Output: All checks passed
# Phase 2: Focus on security review (30 minutes)
npx claude-flow agent spawn --type security-manager --focus "comprehensive-audit"
# Output: Vulnerability fixed correctly, no new issues introduced
# Phase 3: Integration analysis (15 minutes)
# Output: Backward compatible, zero downtime deployment
# Phase 4: Fast-track approval
./final-decision.sh ${PR_ID}
# Decision: ✅ APPROVE (EXPEDITED)
# Output: "Security fix verified. No regressions. Approved for immediate merge and deployment."
# Deploy immediately
gh pr merge ${PR_NUMBER} --admin --squash
GraphViz Process Diagram
See when-reviewing-pull-request-orchestrate-comprehensive-code-review-process.dot for visual workflow representation showing:
- 4 phases with star topology coordination
- 15 specialist reviewer interactions
- Automated gate (Phase 1) preventing bad code from entering review
- Parallel specialist reviews (Phase 2) for efficiency
- Integration analysis (Phase 3) for deployment safety
- Final decision logic with author notification
Quality Checklist
Before considering code review complete, verify:
Memory Verification:
Feedback Quality:
Workflow Complexity: Medium (15 agents, 4 hours, 4 phases)
Coordination Pattern: Star topology with parallel specialist reviews
Memory Footprint: ~20-30 memory entries per PR review
Typical Use Case: Comprehensive PR review requiring validation across multiple quality dimensions
1---
2name: when-reviewing-pull-request-orchestrate-comprehensive-code-r
3type: sop-workflow
4description: |
5 Use when conducting comprehensive code review for pull requests across multiple quality dimensions.
6 Orchestrates 12-15 specialized reviewer agents across 4 phases using star topology coordination.
7 Covers automated checks, parallel specialized reviews (quality, security, performance, architecture,
8 documentation), integration analysis, and final merge recommendation in a 4-hour workflow.
9agents:
10 - pr-manager
11 - code-analyzer
12 - security-manager
13 - performance-analyzer
14 - system-architect
15 - api-documentation-specialist
16 - tester
17 - qa-engineer
18 - devops-engineer
19 - style-auditor
20 - dependency-analyzer
21 - test-coverage-reviewer
22 - documentation-reviewer
23 - system-integrator
24 - code-reviewer
25phases: 4
26memory_pattern: "code-review/{pr-id}/phase-{N}/{reviewer}/{findings}"
27metadata:
28 source: https://skillmd.com/skills/aibot88/when-reviewing-pull-request-orchestrate-comprehensive-code-r
29---
30
31# Code Review Orchestration Workflow
32
33Comprehensive code review workflow orchestrating 12-15 specialized reviewers across automated checks, parallel expert reviews, integration analysis, and final approval recommendation. Designed for thorough quality validation across security, performance, architecture, testing, and documentation dimensions in a systematic 4-hour process.
34
35## Overview
36
37This SOP implements a multi-dimensional code review process using star topology coordination where a central PR manager orchestrates specialized reviewers operating in parallel. The workflow emphasizes both thoroughness and efficiency by running automated checks first (gate 1), then parallelizing specialized human-centric reviews, followed by integration impact analysis, and finally synthesizing all findings into actionable recommendations.
38
39The star pattern enables each specialist to focus deeply on their domain while the coordinator ensures comprehensive coverage and prevents conflicting feedback. Memory coordination allows reviewers to reference findings from other specialists, creating a holistic review experience.
40
41## Trigger Conditions
42
43Use this workflow when:
44- Reviewing pull requests requiring comprehensive quality validation
45- Changes span multiple quality dimensions (code, security, performance, architecture)
46- Need systematic review from multiple specialist perspectives
47- PR introduces significant functionality or architectural changes
48- Merge decision requires evidence-based go/no-go recommendation
49- Team wants consistent, repeatable review process
50- Code review SLA is within 4 hours (business hours)
51
52## Orchestrated Agents (15 Total)
53
54### Coordination Agent
55- **`pr-manager`** - PR coordination, review orchestration, findings aggregation, author notification
56
57### Automated Check Agents (Phase 1)
58- **`code-analyzer`** - Linting, static analysis, code complexity metrics
59- **`tester`** - Test execution, test suite validation
60- **`qa-engineer`** - Coverage analysis, test quality assessment
61
62### Specialized Review Agents (Phase 2)
63- **`code-analyzer`** - Code quality, readability, maintainability, DRY, SOLID principles
64- **`security-manager`** - Security vulnerabilities, OWASP compliance, secrets scanning, auth/auth
65- **`performance-analyzer`** - Performance regressions, algorithmic efficiency, resource optimization
66- **`system-architect`** - Architectural consistency, design patterns, scalability, integration fit
67- **`api-documentation-specialist`** - Code documentation, API docs, comments, examples
68- **`style-auditor`** - Code style consistency, formatting standards
69- **`dependency-analyzer`** - Dependency audit, outdated packages, security vulnerabilities
70- **`test-coverage-reviewer`** - Coverage metrics, uncovered code paths, edge case testing
71- **`documentation-reviewer`** - README updates, changelog, migration guides
72
73### Integration Analysis Agents (Phase 3)
74- **`system-integrator`** - Integration impact, breaking changes, backward compatibility
75- **`devops-engineer`** - Deployment impact, infrastructure changes, rollback planning
76- **`code-reviewer`** - Risk assessment, blast radius analysis
77
78## Workflow Phases
79
80### Phase 1: Automated Checks (30 Minutes, Parallel Gate)
81
82**Duration**: 30 minutes
83**Execution Mode**: Parallel automated validation (fast fail-fast gate)
84**Agents**: `code-analyzer`, `tester`, `qa-engineer`, `pr-manager`
85
86**Process**:
87
881. **Initialize Review Swarm**
89 ```bash
90 PR_ID="$1" # e.g., "repo-name/pulls/123"
91 PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)
92
93 npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"
94 npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized
95 npx claude-flow agent spawn --type pr-manager
96 ```
97
98 **PR Manager** retrieves PR metadata:
99 - Changed files and line counts
100 - Commit history and messages
101 - Branch comparison (base vs head)
102 - PR description and labels
103 - Author and reviewers assigned
104
105 **Memory Storage**:
106 ```bash
107 npx claude-flow memory store --key "code-review/${PR_ID}/metadata" \
108 --value '{"pr_number": "'"${PR_NUMBER}"'", "files_changed": 15, "lines_added": 342, "lines_deleted": 78}'
109 ```
110
1112. **Run Automated Checks in Parallel**
112 ```bash
113 npx claude-flow task orchestrate --strategy parallel --max-agents 4
114 ```
115
116 Spawn all automated check agents concurrently:
117
118 **Linting Check** (Code Analyzer):
119 ```bash
120 npx claude-flow agent spawn --type code-analyzer --focus "linting"
121
122 # Run linting
123 npm run lint # ESLint for JS/TS
124 # or
125 pylint src/ # Python
126 # or
127 rubocop # Ruby
128 ```
129
130 Checks:
131 - Code style violations (max line length, indentation)
132 - Unused variables and imports
133 - Type errors (TypeScript)
134 - Deprecated API usage
135 - Code complexity warnings
136
137 **Memory Pattern**: `code-review/${PR_ID}/phase-1/code-analyzer/lint-results`
138
139 **Test Execution** (Tester):
140 ```bash
141 npx claude-flow agent spawn --type tester --focus "test-execution"
142
143 # Run test suite
144 npm test # Jest/Mocha
145 # or
146 pytest # Python
147 # or
148 rspec # Ruby
149 ```
150
151 Validates:
152 - All unit tests passing
153 - All integration tests passing
154 - All E2E tests passing (if applicable)
155 - No flaky test failures
156 - Test execution time within limits
157
158 **Memory Pattern**: `code-review/${PR_ID}/phase-1/tester/test-results`
159
160 **Coverage Analysis** (QA Engineer):
161 ```bash
162 npx claude-flow agent spawn --type tester --focus "coverage"
163
164 # Generate coverage report
165 npm run test:coverage
166 ```
167
168 Checks:
169 - Overall coverage > 80%
170 - New code coverage > 90%
171 - No critical paths uncovered
172 - Coverage delta (did coverage decrease?)
173 - Untested branches and conditions
174
175 **Memory Pattern**: `code-review/${PR_ID}/phase-1/qa-engineer/coverage-report`
176
177 **Build Validation** (Code Analyzer):
178 ```bash
179 # Clean build validation
180 npm run build
181 # or
182 python setup.py build
183 ```
184
185 Validates:
186 - Clean build (no errors, no warnings)
187 - Type checking passes (TypeScript, mypy)
188 - No broken dependencies
189 - Bundle size within limits (for frontend)
190 - No circular dependencies
191
192 **Memory Pattern**: `code-review/${PR_ID}/phase-1/code-analyzer/build-status`
193
1943. **Evaluate Gate 1 Results**
195 ```bash
196 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"
197 ```
198
199 **PR Manager** aggregates automated results:
200 - Lint: PASS/FAIL (violations count)
201 - Tests: PASS/FAIL (passed/failed/skipped)
202 - Coverage: PASS/FAIL (percentage, delta)
203 - Build: PASS/FAIL (errors/warnings)
204
205 **Decision Logic**:
206 ```javascript
207 if (lintFailed || testsFailed || buildFailed) {
208 // Request fixes from author
209 await notifyAuthor({
210 status: 'CHANGES_REQUESTED',
211 message: 'Automated checks failed. Please fix before review continues.',
212 details: summarizeFailures()
213 });
214
215 // Store feedback and stop review
216 await memory_store(`code-review/${PR_ID}/phase-1/automated-feedback`);
217 return; // Stop review until fixed
218 }
219
220 // All automated checks passed, proceed to Phase 2
221 await notifyAuthor({
222 status: 'IN_REVIEW',
223 message: 'Automated checks passed. Proceeding with specialized reviews.'
224 });
225 ```
226
227**Outputs**:
228- Automated check results (pass/fail for each)
229- Test execution report
230- Coverage report with delta
231- Build status
232
233**Success Criteria**:
234- [ ] All linting checks passing
235- [ ] All tests passing (100% of test suite)
236- [ ] Code coverage meets thresholds
237- [ ] Build successful with no errors
238
239---
240
241### Phase 2: Specialized Reviews (2 Hours, Parallel Expert Analysis)
242
243**Duration**: 2 hours
244**Execution Mode**: Parallel specialized reviews coordinated by PR manager
245**Agents**: 10 specialist reviewers
246
247**Process**:
248
2491. **Initialize Specialist Review Swarm**
250 ```bash
251 npx claude-flow task orchestrate --strategy parallel --max-agents 10 --priority high
252 ```
253
2542. **Spawn All Specialist Reviewers Concurrently**
255
256 Each specialist reviews the PR from their domain expertise:
257
258 **Code Quality Review** (Code Analyzer):
259 ```bash
260 npx claude-flow agent spawn --type code-analyzer --focus "code-quality"
261 ```
262
263 Reviews:
264 - **Readability**: Clear names, appropriate function length, logical organization, cognitive complexity
265 - **Maintainability**: DRY principle, SOLID principles, separation of concerns, error handling
266 - **Best Practices**: Language idioms, design patterns, appropriate comments, no code smells
267
268 Rating: 1-5 stars
269
270 **Findings Format**:
271 ```json
272 {
273 "category": "code_quality",
274 "findings": [
275 {
276 "severity": "MEDIUM",
277 "file": "src/utils/parser.ts",
278 "line": 45,
279 "issue": "Function 'parseData' has cognitive complexity of 15 (max 10)",
280 "suggestion": "Extract nested conditionals into separate validation functions"
281 }
282 ],
283 "rating": 4,
284 "overall_assessment": "Good code quality with minor improvements needed"
285 }
286 ```
287
288 **Memory Pattern**: `code-review/${PR_ID}/phase-2/code-analyzer/quality-review`
289
290 **Security Review** (Security Manager):
291 ```bash
292 npx claude-flow agent spawn --type security-manager --focus "security-comprehensive"
293 ```
294
295 Reviews:
296 - **Authentication & Authorization**: Proper auth checks, no privilege escalation, secure sessions
297 - **Data Security**: Input validation (injection prevention), output encoding (XSS prevention), sensitive data encryption, no hardcoded secrets
298 - **OWASP Top 10**: SQL Injection, XSS, CSRF, insecure dependencies, security misconfigurations
299
300 Severity: CRITICAL/HIGH/MEDIUM/LOW
301
302 **Findings Format**:
303 ```json
304 {
305 "category": "security",
306 "findings": [
307 {
308 "severity": "HIGH",
309 "file": "src/api/users.ts",
310 "line": 78,
311 "issue": "User input not sanitized before database query (SQL Injection risk)",
312 "owasp_category": "A03:2021 – Injection",
313 "suggestion": "Use parameterized queries or ORM with proper escaping"
314 },
315 {
316 "severity": "MEDIUM",
317 "file": "src/config/secrets.ts",
318 "line": 12,
319 "issue": "API key appears to be hardcoded (potential secret leak)",
320 "suggestion": "Move to environment variables and add to .env.example"
321 }
322 ],
323 "critical_count": 0,
324 "high_count": 1,
325 "medium_count": 1,
326 "overall_assessment": "1 high-severity issue must be fixed before merge"
327 }
328 ```
329
330 **Memory Pattern**: `code-review/${PR_ID}/phase-2/security-manager/security-review`
331
332 **Performance Review** (Performance Analyzer):
333 ```bash
334 npx claude-flow agent spawn --type perf-analyzer --focus "performance-optimization"
335 ```
336
337 Reviews:
338 - **Algorithmic Efficiency**: Time complexity (no unnecessary O(n²)), efficient data structures, no redundant iterations
339 - **Resource Usage**: No memory leaks, proper cleanup (connections, files, timers), efficient queries (avoid N+1)
340 - **Optimization Opportunities**: Caching potential, parallelization, database indexes, API call reduction
341
342 Impact: HIGH/MEDIUM/LOW
343
344 **Findings Format**:
345 ```json
346 {
347 "category": "performance",
348 "findings": [
349 {
350 "impact": "HIGH",
351 "file": "src/services/user-service.ts",
352 "line": 125,
353 "issue": "N+1 query problem: Loading user roles in loop (1 + N queries)",
354 "performance_cost": "10x slower for 100 users",
355 "suggestion": "Use eager loading with JOIN or batch query with IN clause"
356 }
357 ],
358 "high_impact_count": 1,
359 "estimated_improvement": "10x faster with suggested optimizations",
360 "overall_assessment": "Significant performance regression without optimization"
361 }
362 ```
363
364 **Memory Pattern**: `code-review/${PR_ID}/phase-2/performance-analyzer/performance-review`
365
366 **Architecture Review** (System Architect):
367 ```bash
368 npx claude-flow agent spawn --type system-architect --focus "architecture-consistency"
369 ```
370
371 Reviews:
372 - **Design Patterns**: Follows established patterns, appropriate abstraction, dependency injection, clean architecture
373 - **Integration**: Fits with existing code, no unexpected side effects, backward compatibility, API contracts respected
374 - **Scalability**: Supports future growth, no hardcoded limits, stateless design, horizontally scalable
375
376 Concerns: BLOCKER/MAJOR/MINOR
377
378 **Findings Format**:
379 ```json
380 {
381 "category": "architecture",
382 "findings": [
383 {
384 "concern": "MAJOR",
385 "file": "src/services/payment-service.ts",
386 "issue": "Payment service directly couples to Stripe SDK (violates adapter pattern)",
387 "impact": "Difficult to switch payment providers in future",
388 "suggestion": "Create PaymentProvider interface and StripeAdapter implementation"
389 }
390 ],
391 "blocker_count": 0,
392 "major_count": 1,
393 "overall_assessment": "Architecture mostly consistent with 1 major design concern"
394 }
395 ```
396
397 **Memory Pattern**: `code-review/${PR_ID}/phase-2/system-architect/architecture-review`
398
399 **Documentation Review** (API Documentation Specialist):
400 ```bash
401 npx claude-flow agent spawn --type api-docs --focus "documentation-comprehensive"
402 ```
403
404 Reviews:
405 - **Code Documentation**: Public APIs documented (JSDoc/docstring), complex logic explained, non-obvious behavior noted
406 - **External Documentation**: README updated, API docs updated, migration guide (if breaking), changelog updated
407 - **Tests as Documentation**: Descriptive test names, test coverage demonstrates usage, edge cases documented
408
409 Completeness: 0-100%
410
411 **Findings Format**:
412 ```json
413 {
414 "category": "documentation",
415 "findings": [
416 {
417 "severity": "MEDIUM",
418 "file": "src/api/webhooks.ts",
419 "issue": "New webhook endpoint /api/webhooks/stripe missing API documentation",
420 "suggestion": "Add JSDoc with parameters, responses, and usage example"
421 }
422 ],
423 "code_doc_coverage": 75,
424 "external_doc_updated": false,
425 "overall_assessment": "75% complete, missing API docs and changelog update"
426 }
427 ```
428
429 **Memory Pattern**: `code-review/${PR_ID}/phase-2/api-documentation-specialist/docs-review`
430
431 **Additional Specialist Reviews** (run in parallel):
432
433 - **Style Audit** (Style Auditor): Code style consistency, formatting compliance
434 - **Dependency Audit** (Dependency Analyzer): Outdated packages, security vulnerabilities in deps
435 - **Test Coverage** (Test Coverage Reviewer): Coverage gaps, missing edge cases
436 - **Documentation Completeness** (Documentation Reviewer): README, changelog, migration guides
437
438 Each follows similar format with findings, severity, and recommendations.
439
4403. **Aggregate Specialist Reviews**
441 ```bash
442 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/*/review"
443 npx claude-flow agent spawn --type pr-manager --focus "aggregation"
444 ```
445
446 **PR Manager** synthesizes all reviews:
447 - Total findings: 15 issues (0 critical, 1 high, 8 medium, 6 low)
448 - Quality rating: 4/5 stars
449 - Security: 1 high-severity issue
450 - Performance: 1 high-impact issue
451 - Architecture: 1 major concern
452 - Documentation: 75% complete
453
454 Categorize issues:
455 - **Blocking Issues** (must fix before merge): High-severity security issue, high-impact performance regression
456 - **High-Priority** (should fix): Major architecture concern, medium security issues
457 - **Nice-to-Have** (can fix later): Low-severity code quality improvements
458
459 **Memory Storage**:
460 ```bash
461 npx claude-flow memory store --key "code-review/${PR_ID}/phase-2/aggregated-review" \
462 --value "${AGGREGATED_FINDINGS_JSON}"
463 ```
464
465**Outputs**:
466- 10 specialized review reports
467- Aggregated findings with severity prioritization
468- Blocking issues list
469- Recommendations summary
470
471**Success Criteria**:
472- [ ] All specialist reviews completed
473- [ ] Findings categorized by severity
474- [ ] Blocking issues clearly identified
475- [ ] Recommendations actionable and specific
476
477---
478
479### Phase 3: Integration Analysis (1 Hour, Sequential Impact Assessment)
480
481**Duration**: 1 hour
482**Execution Mode**: Sequential end-to-end impact analysis
483**Agents**: `tester`, `devops-engineer`, `product-manager`, `code-reviewer`
484
485**Process**:
486
4871. **Integration Testing**
488 ```bash
489 npx claude-flow agent spawn --type tester --focus "integration-impact"
490 ```
491
492 **QA Engineer** tests:
493 - Does this change break existing functionality?
494 - Are all integration tests passing?
495 - Does it integrate properly with related modules?
496 - Any unexpected side effects or regressions?
497
498 Run integration test suite:
499 ```bash
500 npm run test:integration
501 ```
502
503 **Findings**:
504 - Integration tests: 45/45 passing
505 - No regressions detected
506 - New functionality integrates cleanly
507
508 **Memory Pattern**: `code-review/${PR_ID}/phase-3/tester/integration-tests`
509
5102. **Deployment Impact Assessment**
511 ```bash
512 npx claude-flow memory retrieve --key "code-review/${PR_ID}/metadata"
513 npx claude-flow agent spawn --type cicd-engineer --focus "deployment-impact"
514 ```
515
516 **DevOps Engineer** evaluates:
517 - Infrastructure changes needed? (new services, scaling)
518 - Database migrations required? (schema changes)
519 - Configuration updates needed? (env vars, secrets)
520 - Backward compatibility maintained? (can rollback safely)
521 - Rollback plan clear and tested?
522
523 **Findings**:
524 ```json
525 {
526 "infrastructure_changes": ["Add Redis cache for session storage"],
527 "database_migrations": ["Add index on users.email for faster lookups"],
528 "config_updates": ["Add REDIS_URL environment variable"],
529 "backward_compatible": true,
530 "rollback_complexity": "LOW",
531 "deployment_risk": "MEDIUM"
532 }
533 ```
534
535 **Memory Pattern**: `code-review/${PR_ID}/phase-3/devops-engineer/deployment-impact`
536
5373. **User Impact Assessment**
538 ```bash
539 npx claude-flow agent spawn --type planner --focus "user-impact"
540 ```
541
542 **Product Manager** assesses:
543 - Does this improve user experience?
544 - Any user-facing changes? (UI/UX)
545 - Consistent with design system?
546 - Analytics/tracking updated?
547 - Feature flags needed?
548
549 **Findings**:
550 ```json
551 {
552 "user_facing_changes": ["New export functionality in dashboard"],
553 "ux_impact": "POSITIVE",
554 "design_system_compliant": true,
555 "analytics_updated": false,
556 "feature_flag_recommended": true
557 }
558 ```
559
560 **Memory Pattern**: `code-review/${PR_ID}/phase-3/product-manager/user-impact`
561
5624. **Risk Assessment**
563 ```bash
564 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-3/*"
565 npx claude-flow agent spawn --type reviewer --focus "risk-analysis"
566 ```
567
568 **Code Reviewer** analyzes:
569 - What's the blast radius of this change? (how many users/services affected)
570 - Worst-case failure scenario? (data loss, downtime, security breach)
571 - Do we have rollback procedures? (tested and documented)
572 - Should this be feature-flagged? (gradual rollout)
573 - Is monitoring and alerting adequate? (can detect issues quickly)
574
575 **Risk Matrix**:
576 ```json
577 {
578 "blast_radius": "MEDIUM (affects 30% of users)",
579 "worst_case_scenario": "Temporary export failures (no data loss)",
580 "rollback_available": true,
581 "rollback_tested": false,
582 "feature_flag_needed": true,
583 "monitoring_adequate": true,
584 "overall_risk": "MEDIUM",
585 "recommendation": "CONDITIONAL_APPROVE (add feature flag + test rollback)"
586 }
587 ```
588
589 **Memory Pattern**: `code-review/${PR_ID}/phase-3/code-reviewer/risk-analysis`
590
591**Outputs**:
592- Integration test results
593- Deployment impact report
594- User impact assessment
595- Risk analysis with mitigation recommendations
596
597**Success Criteria**:
598- [ ] Integration tests passing
599- [ ] Deployment plan documented
600- [ ] User impact understood
601- [ ] Risk assessment complete with mitigation
602
603---
604
605### Phase 4: Final Approval (30 Minutes, Decision & Notification)
606
607**Duration**: 30 minutes
608**Execution Mode**: Sequential synthesis and decision
609**Agents**: `pr-manager`
610
611**Process**:
612
6131. **Generate Final Review Summary**
614 ```bash
615 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"
616 npx claude-flow agent spawn --type pr-manager --focus "final-summary"
617 ```
618
619 **PR Manager** synthesizes all phases:
620
621 **Summary Report**:
622 ```markdown
623 # Code Review Summary: PR #${PR_NUMBER}
624
625 ## Automated Checks ✅
626 - Linting: ✅ PASS (0 violations)
627 - Tests: ✅ PASS (142/142 passing)
628 - Coverage: ✅ PASS (93.5%, +2.3% delta)
629 - Build: ✅ PASS (clean build, no warnings)
630
631 ## Specialized Reviews
632 - **Code Quality**: 4/5 stars (Good quality, minor improvements suggested)
633 - **Security**: ⚠️ 1 HIGH issue (SQL injection risk in user query)
634 - **Performance**: ⚠️ 1 HIGH impact (N+1 query problem)
635 - **Architecture**: ⚠️ 1 MAJOR concern (tight coupling to payment provider)
636 - **Documentation**: 75% complete (missing API docs + changelog)
637
638 ## Integration Analysis
639 - **Integration Tests**: ✅ All passing (45/45)
640 - **Deployment Impact**: MEDIUM risk (requires Redis + DB migration)
641 - **User Impact**: POSITIVE (new export feature)
642 - **Risk Level**: MEDIUM (feature flag recommended)
643
644 ## Blocking Issues (MUST FIX)
645 1. [HIGH/SECURITY] SQL injection risk in src/api/users.ts:78
646 2. [HIGH/PERFORMANCE] N+1 query in src/services/user-service.ts:125
647
648 ## High-Priority Recommendations (SHOULD FIX)
649 3. [MAJOR/ARCHITECTURE] Decouple payment service from Stripe SDK
650 4. [MEDIUM/DOCUMENTATION] Add API documentation for webhook endpoint
651 5. [MEDIUM/DEPLOYMENT] Add feature flag for gradual rollout
652
653 ## Overall Decision: ⏸️ REQUEST CHANGES
654
655 **Rationale**: Code is high quality overall, but 2 blocking issues (security + performance) must be addressed before merge. Once fixed, this PR will be ready for production.
656
657 **Next Steps**:
658 1. Author fixes blocking issues (estimated 2-4 hours)
659 2. Re-run automated checks + security/performance reviews
660 3. Once green, approve for merge with feature flag enabled
661 ```
662
663 **Memory Storage**:
664 ```bash
665 npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/final-summary" \
666 --value "${FINAL_SUMMARY_MARKDOWN}"
667 ```
668
6692. **Determine Decision**
670
671 **Decision Logic**:
672 ```javascript
673 function determineDecision(aggregatedReview) {
674 const { blocking, highPriority, security, performance } = aggregatedReview;
675
676 // REJECT: Fundamental architectural problems or severe quality issues
677 if (blocking.length > 5 || security.critical > 0) {
678 return {
679 decision: 'REJECT',
680 message: 'Too many critical issues or fundamental architectural problems. Consider alternative approach.'
681 };
682 }
683
684 // REQUEST CHANGES: Blocking issues that must be fixed
685 if (blocking.length > 0 || security.high > 0 || performance.high > 0) {
686 return {
687 decision: 'REQUEST_CHANGES',
688 message: `${blocking.length} blocking issue(s) must be fixed before merge.`
689 };
690 }
691
692 // CONDITIONAL APPROVE: High-priority items should be addressed
693 if (highPriority.length > 0) {
694 return {
695 decision: 'CONDITIONAL_APPROVE',
696 message: `Approved with ${highPriority.length} recommendations to address before or after merge.`
697 };
698 }
699
700 // APPROVE: All quality gates passed
701 return {
702 decision: 'APPROVE',
703 message: 'All quality checks passed. Ready to merge.'
704 };
705 }
706 ```
707
7083. **Notify Author**
709 ```bash
710 npx claude-flow agent spawn --type pr-manager --focus "author-notification"
711 ```
712
713 **PR Manager** sends notification:
714 - GitHub PR comment with full review summary
715 - Label PR appropriately ("changes-requested", "approved", "rejected")
716 - Assign back to author (if changes needed)
717 - Tag relevant reviewers for specific issues
718
719 **GitHub PR Comment** (example for REQUEST_CHANGES):
720 ```markdown
721 ## 🔍 Comprehensive Code Review Complete
722
723 Thank you for your contribution! Our automated review system has completed a thorough analysis.
724
725 ### ✅ What Went Well
726 - All automated checks passing (tests, coverage, linting)
727 - Clean code architecture overall
728 - Good test coverage (93.5%)
729
730 ### ⚠️ Issues Requiring Attention
731
732 #### Blocking Issues (Must Fix Before Merge)
733
734 1. **[HIGH/SECURITY]** SQL Injection Risk
735 - **File**: `src/api/users.ts:78`
736 - **Issue**: User input not sanitized before database query
737 - **Fix**: Use parameterized queries or ORM with proper escaping
738 - **Priority**: CRITICAL
739
740 2. **[HIGH/PERFORMANCE]** N+1 Query Problem
741 - **File**: `src/services/user-service.ts:125`
742 - **Issue**: Loading user roles in loop (10x slower for 100 users)
743 - **Fix**: Use eager loading with JOIN or batch query
744 - **Priority**: HIGH
745
746 #### Recommendations (Should Address)
747
748 3. **[MAJOR/ARCHITECTURE]** Payment Service Coupling
749 - Create PaymentProvider interface for future flexibility
750 - See: [Architecture Best Practices](link)
751
752 4. **[MEDIUM/DOCUMENTATION]** Missing API Documentation
753 - Add JSDoc for webhook endpoint
754 - Update changelog with this new feature
755
756 ### 🔄 Next Steps
757
758 1. Address the 2 blocking issues above
759 2. Push updates to this PR branch
760 3. Automated checks will re-run automatically
761 4. We'll re-review security and performance aspects
762 5. Once green, we'll approve for merge!
763
764 **Estimated time to fix**: 2-4 hours
765
766 ---
767 🤖 Generated by Claude Code Review System | [View Full Report](link)
768 ```
769
770 **Memory Storage**:
771 ```bash
772 npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/author-notification"
773 npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-report true
774 ```
775
7764. **Execute Decision Actions**
777
778 Based on decision, take appropriate GitHub actions:
779
780 **If APPROVE**:
781 ```bash
782 # Add approval label
783 gh pr edit ${PR_NUMBER} --add-label "approved"
784
785 # Add approval review
786 gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."
787
788 # Queue for merge (if auto-merge enabled)
789 gh pr merge ${PR_NUMBER} --auto --squash
790 ```
791
792 **If REQUEST_CHANGES**:
793 ```bash
794 # Add changes-requested label
795 gh pr edit ${PR_NUMBER} --add-label "changes-requested" --remove-label "approved"
796
797 # Request changes
798 gh pr review ${PR_NUMBER} --request-changes --body "${REVIEW_COMMENT_MARKDOWN}"
799
800 # Assign back to author
801 gh pr edit ${PR_NUMBER} --add-assignee ${AUTHOR_USERNAME}
802
803 # Schedule follow-up review
804 npx claude-flow memory store --key "code-review/${PR_ID}/follow-up/scheduled" --value "true"
805 ```
806
807 **If REJECT**:
808 ```bash
809 # Add rejected label
810 gh pr edit ${PR_NUMBER} --add-label "rejected"
811
812 # Provide detailed explanation
813 gh pr review ${PR_NUMBER} --request-changes --body "${DETAILED_REJECTION_REASON}"
814
815 # Suggest alternative approaches
816 gh pr comment ${PR_NUMBER} --body "Consider these alternative approaches: ${ALTERNATIVES}"
817 ```
818
8195. **Finalize Review Session**
820 ```bash
821 npx claude-flow hooks session-end --export-metrics true
822 npx claude-flow hooks post-task --task-id "pr-${PR_ID}"
823 ```
824
825**Outputs**:
826- Final review summary (comprehensive report)
827- Merge decision (Approve/Request Changes/Reject)
828- Author notification (GitHub comment)
829- GitHub labels and status updated
830
831**Success Criteria**:
832- [ ] Final summary generated and comprehensive
833- [ ] Decision clear and justified
834- [ ] Author notified with actionable feedback
835- [ ] GitHub PR status updated appropriately
836
837---
838
839## Memory Coordination
840
841### Namespace Convention
842
843All review data follows this hierarchical pattern:
844
845```
846code-review/{pr-id}/phase-{N}/{reviewer-type}/{findings-type}
847```
848
849**Examples**:
850- `code-review/repo/pulls/123/metadata`
851- `code-review/repo/pulls/123/phase-1/code-analyzer/lint-results`
852- `code-review/repo/pulls/123/phase-2/security-manager/security-review`
853- `code-review/repo/pulls/123/phase-3/devops-engineer/deployment-impact`
854- `code-review/repo/pulls/123/phase-4/final-summary`
855
856### Cross-Phase Data Flow
857
858**Phase 1 → Phase 2**:
859```bash
860# Phase 2 reviewers check if Phase 1 passed
861npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"
862
863# Only proceed if all automated checks passed
864if [ "$(jq '.all_passed' < phase1_results.json)" = "true" ]; then
865 # Spawn specialist reviewers
866 npx claude-flow task orchestrate --strategy parallel
867fi
868```
869
870**Phase 2 → Phase 3**:
871```bash
872# Phase 3 integration analysis references specialist findings
873npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/security-manager/security-review"
874npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/performance-analyzer/performance-review"
875
876# Risk analysis considers all specialist findings
877```
878
879**Phase 3 → Phase 4**:
880```bash
881# Phase 4 final decision aggregates all prior phases
882npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"
883
884# Generate comprehensive summary
885```
886
887---
888
889## Scripts & Automation
890
891### Pre-Review Initialization
892
893```bash
894#!/bin/bash
895# Initialize code review workflow
896
897PR_NUMBER="$1"
898REPO="$2" # e.g., "owner/repo"
899PR_ID="${REPO}/pulls/${PR_NUMBER}"
900
901# Fetch PR metadata via GitHub API
902PR_DATA=$(gh pr view ${PR_NUMBER} --json number,title,author,files,additions,deletions)
903
904# Setup coordination
905npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"
906
907# Initialize star topology swarm (central coordinator + specialists)
908npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized
909
910# Store PR metadata
911npx claude-flow memory store --key "code-review/${PR_ID}/metadata" --value "${PR_DATA}"
912
913echo "✅ Code review initialized: PR #${PR_NUMBER}"
914```
915
916### Automated Check Gate
917
918```bash
919#!/bin/bash
920# Execute Phase 1 automated checks (gate)
921
922PR_ID="$1"
923
924echo "🤖 Running automated checks..."
925
926# Run checks in parallel
927npx claude-flow task orchestrate --strategy parallel --max-agents 4 << EOF
928 lint: npm run lint
929 test: npm test
930 coverage: npm run test:coverage
931 build: npm run build
932EOF
933
934# Aggregate results
935LINT_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/lint-results" | jq -r '.status')
936TEST_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/tester/test-results" | jq -r '.status')
937COVERAGE_OK=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/qa-engineer/coverage-report" | jq -r '.meets_threshold')
938BUILD_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/build-status" | jq -r '.status')
939
940# Check if all passed
941if [ "$LINT_STATUS" = "PASS" ] && [ "$TEST_STATUS" = "PASS" ] && [ "$COVERAGE_OK" = "true" ] && [ "$BUILD_STATUS" = "PASS" ]; then
942 echo "✅ All automated checks passed. Proceeding to specialist reviews."
943 exit 0
944else
945 echo "❌ Automated checks failed. Requesting fixes from author."
946 gh pr review ${PR_NUMBER} --request-changes --body "Automated checks failed. Please fix before review continues."
947 exit 1
948fi
949```
950
951### Parallel Specialist Review
952
953```bash
954#!/bin/bash
955# Execute Phase 2 specialist reviews in parallel
956
957PR_ID="$1"
958
959echo "👥 Spawning specialist reviewers..."
960
961# Spawn all reviewers concurrently via Claude Flow
962npx claude-flow task orchestrate --strategy parallel --max-agents 10 << EOF
963 code_quality: Review code quality (readability, maintainability, best practices)
964 security: Review security vulnerabilities (OWASP Top 10, secrets, auth)
965 performance: Review performance (algorithms, resource usage, optimizations)
966 architecture: Review architecture consistency (patterns, integration, scalability)
967 documentation: Review documentation completeness (code docs, API docs, changelog)
968 style: Review code style consistency
969 dependencies: Review dependency security and updates
970 test_coverage: Review test coverage gaps
971 external_docs: Review README and migration guides
972 integration: Review integration fit with existing codebase
973EOF
974
975# Wait for all reviews to complete
976npx claude-flow task status --wait
977
978echo "✅ All specialist reviews complete."
979```
980
981### Final Decision Script
982
983```bash
984#!/bin/bash
985# Generate final decision and notify author
986
987PR_ID="$1"
988PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)
989
990# Retrieve all review data
991npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**" > "/tmp/${PR_ID}-reviews.json"
992
993# Count issues by severity
994CRITICAL_COUNT=$(jq '[.. | .severity? | select(. == "CRITICAL")] | length' /tmp/${PR_ID}-reviews.json)
995HIGH_COUNT=$(jq '[.. | .severity? | select(. == "HIGH")] | length' /tmp/${PR_ID}-reviews.json)
996BLOCKING_COUNT=$((CRITICAL_COUNT + HIGH_COUNT))
997
998# Determine decision
999if [ $CRITICAL_COUNT -gt 0 ] || [ $BLOCKING_COUNT -gt 5 ]; then
1000 DECISION="REJECT"
1001elif [ $BLOCKING_COUNT -gt 0 ]; then
1002 DECISION="REQUEST_CHANGES"
1003else
1004 DECISION="APPROVE"
1005fi
1006
1007echo "📊 Review Decision: ${DECISION}"
1008echo " Critical Issues: ${CRITICAL_COUNT}"
1009echo " High-Severity Issues: ${HIGH_COUNT}"
1010
1011# Notify author via GitHub
1012case $DECISION in
1013 APPROVE)
1014 gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."
1015 gh pr edit ${PR_NUMBER} --add-label "approved"
1016 ;;
1017 REQUEST_CHANGES)
1018 gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-summary.md"
1019 gh pr edit ${PR_NUMBER} --add-label "changes-requested"
1020 ;;
1021 REJECT)
1022 gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-rejection.md"
1023 gh pr edit ${PR_NUMBER} --add-label "rejected"
1024 ;;
1025esac
1026
1027# Finalize session
1028npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-metrics true
1029```
1030
1031---
1032
1033## Success Criteria
1034
1035### Review Quality Metrics
1036- **Coverage**: All quality dimensions reviewed (code, security, performance, architecture, docs)
1037- **Consistency**: Reviews follow established guidelines and standards
1038- **Actionability**: All feedback is specific, constructive, and actionable
1039- **Timeliness**: Reviews completed within 4 hours (business hours)
1040
1041### Code Quality Gates
1042- **Automated Tests**: 100% passing (no failing tests)
1043- **Code Coverage**: > 80% overall, > 90% for new code
1044- **Linting**: 0 violations (all style rules followed)
1045- **Security**: 0 critical issues, 0 high-severity issues
1046- **Performance**: No high-impact performance regressions
1047- **Documentation**: 100% of public APIs documented
1048
1049### Process Metrics
1050- **Review Turnaround**: < 4 hours (from PR creation to decision)
1051- **Author Satisfaction**: > 4/5 (feedback is helpful and constructive)
1052- **Defect Escape Rate**: < 1% (issues found in production that should have been caught)
1053- **False Positive Rate**: < 5% (flagged issues that weren't actually problems)
1054
1055---
1056
1057## Usage Examples
1058
1059### Example 1: Small Feature PR (Simple)
1060
1061```bash
1062# Feature: Add email validation to registration form
1063PR_NUMBER=245
1064PR_ID="acme-app/pulls/245"
1065
1066# Initialize review
1067./init-review.sh ${PR_NUMBER} "acme/acme-app"
1068
1069# Phase 1: Automated checks (5 minutes)
1070./automated-checks.sh ${PR_ID}
1071# Output: All checks passed
1072
1073# Phase 2: Specialist reviews (30 minutes - small PR)
1074./specialist-reviews.sh ${PR_ID}
1075# Output: 3 minor issues (all LOW severity)
1076
1077# Phase 3: Integration analysis (10 minutes)
1078# Output: No integration concerns, backward compatible
1079
1080# Phase 4: Final decision
1081./final-decision.sh ${PR_ID}
1082# Decision: ✅ APPROVE
1083# Output: "All quality checks passed. 3 minor suggestions for future consideration."
1084```
1085
1086### Example 2: Large Refactoring PR (Complex)
1087
1088```bash
1089# Refactoring: Migrate from REST to GraphQL
1090PR_NUMBER=312
1091PR_ID="acme-app/pulls/312"
1092
1093# Initialize review
1094./init-review.sh ${PR_NUMBER} "acme/acme-app"
1095
1096# Phase 1: Automated checks (10 minutes)
1097./automated-checks.sh ${PR_ID}
1098# Output: All checks passed, coverage 94%
1099
1100# Phase 2: Specialist reviews (2 hours)
1101./specialist-reviews.sh ${PR_ID}
1102# Output: 15 findings
1103# - 1 HIGH/SECURITY (authentication flow changed, needs verification)
1104# - 2 HIGH/PERFORMANCE (N+1 queries in new resolvers)
1105# - 3 MAJOR/ARCHITECTURE (GraphQL schema design concerns)
1106# - 9 MEDIUM/LOW (documentation, minor improvements)
1107
1108# Phase 3: Integration analysis (1 hour)
1109# Output: Breaking changes for API clients, migration guide needed
1110# Risk: HIGH (affects all API consumers)
1111
1112# Phase 4: Final decision
1113./final-decision.sh ${PR_ID}
1114# Decision: ⏸️ REQUEST CHANGES
1115# Output: "3 blocking issues (security + performance). Add feature flag for gradual rollout. Provide migration guide for API clients."
1116```
1117
1118### Example 3: Security Patch PR (Critical)
1119
1120```bash
1121# Security: Fix SQL injection vulnerability
1122PR_NUMBER=418
1123PR_ID="acme-app/pulls/418"
1124
1125# Initialize expedited review
1126./init-review.sh ${PR_NUMBER} "acme/acme-app"
1127
1128# Phase 1: Automated checks (5 minutes)
1129./automated-checks.sh ${PR_ID}
1130# Output: All checks passed
1131
1132# Phase 2: Focus on security review (30 minutes)
1133npx claude-flow agent spawn --type security-manager --focus "comprehensive-audit"
1134# Output: Vulnerability fixed correctly, no new issues introduced
1135
1136# Phase 3: Integration analysis (15 minutes)
1137# Output: Backward compatible, zero downtime deployment
1138
1139# Phase 4: Fast-track approval
1140./final-decision.sh ${PR_ID}
1141# Decision: ✅ APPROVE (EXPEDITED)
1142# Output: "Security fix verified. No regressions. Approved for immediate merge and deployment."
1143
1144# Deploy immediately
1145gh pr merge ${PR_NUMBER} --admin --squash
1146```
1147
1148---
1149
1150## GraphViz Process Diagram
1151
1152See `when-reviewing-pull-request-orchestrate-comprehensive-code-review-process.dot` for visual workflow representation showing:
1153- 4 phases with star topology coordination
1154- 15 specialist reviewer interactions
1155- Automated gate (Phase 1) preventing bad code from entering review
1156- Parallel specialist reviews (Phase 2) for efficiency
1157- Integration analysis (Phase 3) for deployment safety
1158- Final decision logic with author notification
1159
1160---
1161
1162## Quality Checklist
1163
1164Before considering code review complete, verify:
1165
1166- [ ] **Phase 1**: All automated checks passing (lint, tests, coverage, build)
1167- [ ] **Phase 2**: All specialist reviews completed, findings categorized
1168- [ ] **Phase 3**: Integration impact analyzed, deployment plan documented
1169- [ ] **Phase 4**: Final decision made, author notified, GitHub status updated
1170
1171**Memory Verification**:
1172- [ ] `code-review/${PR_ID}/metadata` - PR information
1173- [ ] `code-review/${PR_ID}/phase-1/*` - Automated check results
1174- [ ] `code-review/${PR_ID}/phase-2/*` - Specialist review findings
1175- [ ] `code-review/${PR_ID}/phase-3/*` - Integration analysis
1176- [ ] `code-review/${PR_ID}/phase-4/final-summary` - Comprehensive report
1177
1178**Feedback Quality**:
1179- [ ] All feedback is specific (file, line, issue clearly identified)
1180- [ ] All feedback is actionable (how to fix provided)
1181- [ ] All feedback is constructive (not just criticism, but improvement suggestions)
1182- [ ] Severity is appropriate (not overstating or understating issues)
1183
1184---
1185
1186**Workflow Complexity**: Medium (15 agents, 4 hours, 4 phases)
1187**Coordination Pattern**: Star topology with parallel specialist reviews
1188**Memory Footprint**: ~20-30 memory entries per PR review
1189**Typical Use Case**: Comprehensive PR review requiring validation across multiple quality dimensions