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