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.
LIBRARY-FIRST PROTOCOL (MANDATORY)
Before writing ANY code, you MUST check:
Step 1: Library Catalog
- Location:
.claude/library/catalog.json
- If match >70%: REUSE or ADAPT
Step 2: Patterns Guide
- Location:
.claude/docs/inventories/LIBRARY-PATTERNS-GUIDE.md
- If pattern exists: FOLLOW documented approach
Step 3: Existing Projects
- Location:
D:\Projects\*
- If found: EXTRACT and adapt
Decision Matrix
| Match |
Action |
| Library >90% |
REUSE directly |
| Library 70-90% |
ADAPT minimally |
| Pattern exists |
FOLLOW pattern |
| In project |
EXTRACT |
| No match |
BUILD (add to library after) |
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
…(truncated)
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---56# Code Review Orchestration Workflow78Comprehensive 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.9101112---1314## LIBRARY-FIRST PROTOCOL (MANDATORY)1516**Before writing ANY code, you MUST check:**1718### Step 1: Library Catalog19- Location: `.claude/library/catalog.json`20- If match >70%: REUSE or ADAPT2122### Step 2: Patterns Guide23- Location: `.claude/docs/inventories/LIBRARY-PATTERNS-GUIDE.md`24- If pattern exists: FOLLOW documented approach2526### Step 3: Existing Projects27- Location: `D:\Projects\*`28- If found: EXTRACT and adapt2930### Decision Matrix31| Match | Action |32|-------|--------|33| Library >90% | REUSE directly |34| Library 70-90% | ADAPT minimally |35| Pattern exists | FOLLOW pattern |36| In project | EXTRACT |37| No match | BUILD (add to library after) |3839---4041## Overview4243This 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.4445The 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.4647## Trigger Conditions4849Use this workflow when:50- Reviewing pull requests requiring comprehensive quality validation51- Changes span multiple quality dimensions (code, security, performance, architecture)52- Need systematic review from multiple specialist perspectives53- PR introduces significant functionality or architectural changes54- Merge decision requires evidence-based go/no-go recommendation55- Team wants consistent, repeatable review process56- Code review SLA is within 4 hours (business hours)5758## Orchestrated Agents (15 Total)5960### Coordination Agent61- **`pr-manager`** - PR coordination, review orchestration, findings aggregation, author notification6263### Automated Check Agents (Phase 1)64- **`code-analyzer`** - Linting, static analysis, code complexity metrics65- **`tester`** - Test execution, test suite validation66- **`qa-engineer`** - Coverage analysis, test quality assessment6768### Specialized Review Agents (Phase 2)69- **`code-analyzer`** - Code quality, readability, maintainability, DRY, SOLID principles70- **`security-manager`** - Security vulnerabilities, OWASP compliance, secrets scanning, auth/auth71- **`performance-analyzer`** - Performance regressions, algorithmic efficiency, resource optimization72- **`system-architect`** - Architectural consistency, design patterns, scalability, integration fit73- **`api-documentation-specialist`** - Code documentation, API docs, comments, examples74- **`style-auditor`** - Code style consistency, formatting standards75- **`dependency-analyzer`** - Dependency audit, outdated packages, security vulnerabilities76- **`test-coverage-reviewer`** - Coverage metrics, uncovered code paths, edge case testing77- **`documentation-reviewer`** - README updates, changelog, migration guides7879### Integration Analysis Agents (Phase 3)80- **`system-integrator`** - Integration impact, breaking changes, backward compatibility81- **`devops-engineer`** - Deployment impact, infrastructure changes, rollback planning82- **`code-reviewer`** - Risk assessment, blast radius analysis8384## Workflow Phases8586### Phase 1: Automated Checks (30 Minutes, Parallel Gate)8788**Duration**: 30 minutes89**Execution Mode**: Parallel automated validation (fast fail-fast gate)90**Agents**: `code-analyzer`, `tester`, `qa-engineer`, `pr-manager`9192**Process**:93941. **Initialize Review Swarm**95 ```bash96 PR_ID="$1" # e.g., "repo-name/pulls/123"97 PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)9899 npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"100 npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized101 npx claude-flow agent spawn --type pr-manager102 ```103104 **PR Manager** retrieves PR metadata:105 - Changed files and line counts106 - Commit history and messages107 - Branch comparison (base vs head)108 - PR description and labels109 - Author and reviewers assigned110111 **Memory Storage**:112 ```bash113 npx claude-flow memory store --key "code-review/${PR_ID}/metadata" \114 --value '{"pr_number": "'"${PR_NUMBER}"'", "files_changed": 15, "lines_added": 342, "lines_deleted": 78}'115 ```1161172. **Run Automated Checks in Parallel**118 ```bash119 npx claude-flow task orchestrate --strategy parallel --max-agents 4120 ```121122 Spawn all automated check agents concurrently:123124 **Linting Check** (Code Analyzer):125 ```bash126 npx claude-flow agent spawn --type code-analyzer --focus "linting"127128 # Run linting129 npm run lint # ESLint for JS/TS130 # or131 pylint src/ # Python132 # or133 rubocop # Ruby134 ```135136 Checks:137 - Code style violations (max line length, indentation)138 - Unused variables and imports139 - Type errors (TypeScript)140 - Deprecated API usage141 - Code complexity warnings142143 **Memory Pattern**: `code-review/${PR_ID}/phase-1/code-analyzer/lint-results`144145 **Test Execution** (Tester):146 ```bash147 npx claude-flow agent spawn --type tester --focus "test-execution"148149 # Run test suite150 npm test # Jest/Mocha151 # or152 pytest # Python153 # or154 rspec # Ruby155 ```156157 Validates:158 - All unit tests passing159 - All integration tests passing160 - All E2E tests passing (if applicable)161 - No flaky test failures162 - Test execution time within limits163164 **Memory Pattern**: `code-review/${PR_ID}/phase-1/tester/test-results`165166 **Coverage Analysis** (QA Engineer):167 ```bash168 npx claude-flow agent spawn --type tester --focus "coverage"169170 # Generate coverage report171 npm run test:coverage172 ```173174 Checks:175 - Overall coverage > 80%176 - New code coverage > 90%177 - No critical paths uncovered178 - Coverage delta (did coverage decrease?)179 - Untested branches and conditions180181 **Memory Pattern**: `code-review/${PR_ID}/phase-1/qa-engineer/coverage-report`182183 **Build Validation** (Code Analyzer):184 ```bash185 # Clean build validation186 npm run build187 # or188 python setup.py build189 ```190191 Validates:192 - Clean build (no errors, no warnings)193 - Type checking passes (TypeScript, mypy)194 - No broken dependencies195 - Bundle size within limits (for frontend)196 - No circular dependencies197198 **Memory Pattern**: `code-review/${PR_ID}/phase-1/code-analyzer/build-status`1992003. **Evaluate Gate 1 Results**201 ```bash202 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"203 ```204205 **PR Manager** aggregates automated results:206 - Lint: PASS/FAIL (violations count)207 - Tests: PASS/FAIL (passed/failed/skipped)208 - Coverage: PASS/FAIL (percentage, delta)209 - Build: PASS/FAIL (errors/warnings)210211 **Decision Logic**:212 ```javascript213 if (lintFailed || testsFailed || buildFailed) {214 // Request fixes from author215 await notifyAuthor({216 status: 'CHANGES_REQUESTED',217 message: 'Automated checks failed. Please fix before review continues.',218 details: summarizeFailures()219 });220221 // Store feedback and stop review222 await memory_store(`code-review/${PR_ID}/phase-1/automated-feedback`);223 return; // Stop review until fixed224 }225226 // All automated checks passed, proceed to Phase 2227 await notifyAuthor({228 status: 'IN_REVIEW',229 message: 'Automated checks passed. Proceeding with specialized reviews.'230 });231 ```232233**Outputs**:234- Automated check results (pass/fail for each)235- Test execution report236- Coverage report with delta237- Build status238239**Success Criteria**:240- [ ] All linting checks passing241- [ ] All tests passing (100% of test suite)242- [ ] Code coverage meets thresholds243- [ ] Build successful with no errors244245---246247### Phase 2: Specialized Reviews (2 Hours, Parallel Expert Analysis)248249**Duration**: 2 hours250**Execution Mode**: Parallel specialized reviews coordinated by PR manager251**Agents**: 10 specialist reviewers252253**Process**:2542551. **Initialize Specialist Review Swarm**256 ```bash257 npx claude-flow task orchestrate --strategy parallel --max-agents 10 --priority high258 ```2592602. **Spawn All Specialist Reviewers Concurrently**261262 Each specialist reviews the PR from their domain expertise:263264 **Code Quality Review** (Code Analyzer):265 ```bash266 npx claude-flow agent spawn --type code-analyzer --focus "code-quality"267 ```268269 Reviews:270 - **Readability**: Clear names, appropriate function length, logical organization, cognitive complexity271 - **Maintainability**: DRY principle, SOLID principles, separation of concerns, error handling272 - **Best Practices**: Language idioms, design patterns, appropriate comments, no code smells273274 Rating: 1-5 stars275276 **Findings Format**:277 ```json278 {279 "category": "code_quality",280 "findings": [281 {282 "severity": "MEDIUM",283 "file": "src/utils/parser.ts",284 "line": 45,285 "issue": "Function 'parseData' has cognitive complexity of 15 (max 10)",286 "suggestion": "Extract nested conditionals into separate validation functions"287 }288 ],289 "rating": 4,290 "overall_assessment": "Good code quality with minor improvements needed"291 }292 ```293294 **Memory Pattern**: `code-review/${PR_ID}/phase-2/code-analyzer/quality-review`295296 **Security Review** (Security Manager):297 ```bash298 npx claude-flow agent spawn --type security-manager --focus "security-comprehensive"299 ```300301 Reviews:302 - **Authentication & Authorization**: Proper auth checks, no privilege escalation, secure sessions303 - **Data Security**: Input validation (injection prevention), output encoding (XSS prevention), sensitive data encryption, no hardcoded secrets304 - **OWASP Top 10**: SQL Injection, XSS, CSRF, insecure dependencies, security misconfigurations305306 Severity: CRITICAL/HIGH/MEDIUM/LOW307308 **Findings Format**:309 ```json310 {311 "category": "security",312 "findings": [313 {314 "severity": "HIGH",315 "file": "src/api/users.ts",316 "line": 78,317 "issue": "User input not sanitized before database query (SQL Injection risk)",318 "owasp_category": "A03:2021 – Injection",319 "suggestion": "Use parameterized queries or ORM with proper escaping"320 },321 {322 "severity": "MEDIUM",323 "file": "src/config/secrets.ts",324 "line": 12,325 "issue": "API key appears to be hardcoded (potential secret leak)",326 "suggestion": "Move to environment variables and add to .env.example"327 }328 ],329 "critical_count": 0,330 "high_count": 1,331 "medium_count": 1,332 "overall_assessment": "1 high-severity issue must be fixed before merge"333 }334 ```335336 **Memory Pattern**: `code-review/${PR_ID}/phase-2/security-manager/security-review`337338 **Performance Review** (Performance Analyzer):339 ```bash340 npx claude-flow agent spawn --type perf-analyzer --focus "performance-optimization"341 ```342343 Reviews:344 - **Algorithmic Efficiency**: Time complexity (no unnecessary O(n²)), efficient data structures, no redundant iterations345 - **Resource Usage**: No memory leaks, proper cleanup (connections, files, timers), efficient queries (avoid N+1)346 - **Optimization Opportunities**: Caching potential, parallelization, database indexes, API call reduction347348 Impact: HIGH/MEDIUM/LOW349350 **Findings Format**:351 ```json352 {353 "category": "performance",354 "findings": [355 {356 "impact": "HIGH",357 "file": "src/services/user-service.ts",358 "line": 125,359 "issue": "N+1 query problem: Loading user roles in loop (1 + N queries)",360 "performance_cost": "10x slower for 100 users",361 "suggestion": "Use eager loading with JOIN or batch query with IN clause"362 }363 ],364 "high_impact_count": 1,365 "estimated_improvement": "10x faster with suggested optimizations",366 "overall_assessment": "Significant performance regression without optimization"367 }368 ```369370 **Memory Pattern**: `code-review/${PR_ID}/phase-2/performance-analyzer/performance-review`371372 **Architecture Review** (System Architect):373 ```bash374 npx claude-flow agent spawn --type system-architect --focus "architecture-consistency"375 ```376377 Reviews:378 - **Design Patterns**: Follows established patterns, appropriate abstraction, dependency injection, clean architecture379 - **Integration**: Fits with existing code, no unexpected side effects, backward compatibility, API contracts respected380 - **Scalability**: Supports future growth, no hardcoded limits, stateless design, horizontally scalable381382 Concerns: BLOCKER/MAJOR/MINOR383384 **Findings Format**:385 ```json386 {387 "category": "architecture",388 "findings": [389 {390 "concern": "MAJOR",391 "file": "src/services/payment-service.ts",392 "issue": "Payment service directly couples to Stripe SDK (violates adapter pattern)",393 "impact": "Difficult to switch payment providers in future",394 "suggestion": "Create PaymentProvider interface and StripeAdapter implementation"395 }396 ],397 "blocker_count": 0,398 "major_count": 1,399 "overall_assessment": "Architecture mostly consistent with 1 major design concern"400 }401 ```402403 **Memory Pattern**: `code-review/${PR_ID}/phase-2/system-architect/architecture-review`404405 **Documentation Review** (API Documentation Specialist):406 ```bash407 npx claude-flow agent spawn --type api-docs --focus "documentation-comprehensive"408 ```409410 Reviews:411 - **Code Documentation**: Public APIs documented (JSDoc/docstring), complex logic explained, non-obvious behavior noted412 - **External Documentation**: README updated, API docs updated, migration guide (if breaking), changelog updated413 - **Tests as Documentation**: Descriptive test names, test coverage demonstrates usage, edge cases documented414415 Completeness: 0-100%416417 **Findings Format**:418 ```json419 {420 "category": "documentation",421 "findings": [422 {423 "severity": "MEDIUM",424 "file": "src/api/webhooks.ts",425 "issue": "New webhook endpoint /api/webhooks/stripe missing API documentation",426 "suggestion": "Add JSDoc with parameters, responses, and usage example"427 }428 ],429 "code_doc_coverage": 75,430 "external_doc_updated": false,431 "overall_assessment": "75% complete, missing API docs and changelog update"432 }433 ```434435 **Memory Pattern**: `code-review/${PR_ID}/phase-2/api-documentation-specialist/docs-review`436437 **Additional Specialist Reviews** (run in parallel):438439 - **Style Audit** (Style Auditor): Code style consistency, formatting compliance440 - **Dependency Audit** (Dependency Analyzer): Outdated packages, security vulnerabilities in deps441 - **Test Coverage** (Test Coverage Reviewer): Coverage gaps, missing edge cases442 - **Documentation Completeness** (Documentation Reviewer): README, changelog, migration guides443444 Each follows similar format with findings, severity, and recommendations.4454463. **Aggregate Specialist Reviews**447 ```bash448 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/*/review"449 npx claude-flow agent spawn --type pr-manager --focus "aggregation"450 ```451452 **PR Manager** synthesizes all reviews:453 - Total findings: 15 issues (0 critical, 1 high, 8 medium, 6 low)454 - Quality rating: 4/5 stars455 - Security: 1 high-severity issue456 - Performance: 1 high-impact issue457 - Architecture: 1 major concern458 - Documentation: 75% complete459460 Categorize issues:461 - **Blocking Issues** (must fix before merge): High-severity security issue, high-impact performance regression462 - **High-Priority** (should fix): Major architecture concern, medium security issues463 - **Nice-to-Have** (can fix later): Low-severity code quality improvements464465 **Memory Storage**:466 ```bash467 npx claude-flow memory store --key "code-review/${PR_ID}/phase-2/aggregated-review" \468 --value "${AGGREGATED_FINDINGS_JSON}"469 ```470471**Outputs**:472- 10 specialized review reports473- Aggregated findings with severity prioritization474- Blocking issues list475- Recommendations summary476477**Success Criteria**:478- [ ] All specialist reviews completed479- [ ] Findings categorized by severity480- [ ] Blocking issues clearly identified481- [ ] Recommendations actionable and specific482483---484485### Phase 3: Integration Analysis (1 Hour, Sequential Impact Assessment)486487**Duration**: 1 hour488**Execution Mode**: Sequential end-to-end impact analysis489**Agents**: `tester`, `devops-engineer`, `product-manager`, `code-reviewer`490491**Process**:4924931. **Integration Testing**494 ```bash495 npx claude-flow agent spawn --type tester --focus "integration-impact"496 ```497498 **QA Engineer** tests:499 - Does this change break existing functionality?500 - Are all integration tests passing?501 - Does it integrate properly with related modules?502 - Any unexpected side effects or regressions?503504 Run integration test suite:505 ```bash506 npm run test:integration507 ```508509 **Findings**:510 - Integration tests: 45/45 passing511 - No regressions detected512 - New functionality integrates cleanly513514 **Memory Pattern**: `code-review/${PR_ID}/phase-3/tester/integration-tests`5155162. **Deployment Impact Assessment**517 ```bash518 npx claude-flow memory retrieve --key "code-review/${PR_ID}/metadata"519 npx claude-flow agent spawn --type cicd-engineer --focus "deployment-impact"520 ```521522 **DevOps Engineer** evaluates:523 - Infrastructure changes needed? (new services, scaling)524 - Database migrations required? (schema changes)525 - Configuration updates needed? (env vars, secrets)526 - Backward compatibility maintained? (can rollback safely)527 - Rollback plan clear and tested?528529 **Findings**:530 ```json531 {532 "infrastructure_changes": ["Add Redis cache for session storage"],533 "database_migrations": ["Add index on users.email for faster lookups"],534 "config_updates": ["Add REDIS_URL environment variable"],535 "backward_compatible": true,536 "rollback_complexity": "LOW",537 "deployment_risk": "MEDIUM"538 }539 ```540541 **Memory Pattern**: `code-review/${PR_ID}/phase-3/devops-engineer/deployment-impact`5425433. **User Impact Assessment**544 ```bash545 npx claude-flow agent spawn --type planner --focus "user-impact"546 ```547548 **Product Manager** assesses:549 - Does this improve user experience?550 - Any user-facing changes? (UI/UX)551 - Consistent with design system?552 - Analytics/tracking updated?553 - Feature flags needed?554555 **Findings**:556 ```json557 {558 "user_facing_changes": ["New export functionality in dashboard"],559 "ux_impact": "POSITIVE",560 "design_system_compliant": true,561 "analytics_updated": false,562 "feature_flag_recommended": true563 }564 ```565566 **Memory Pattern**: `code-review/${PR_ID}/phase-3/product-manager/user-impact`5675684. **Risk Assessment**569 ```bash570 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-3/*"571 npx claude-flow agent spawn --type reviewer --focus "risk-analysis"572 ```573574 **Code Reviewer** analyzes:575 - What's the blast radius of this change? (how many users/services affected)576 - Worst-case failure scenario? (data loss, downtime, security breach)577 - Do we have rollback procedures? (tested and documented)578 - Should this be feature-flagged? (gradual rollout)579 - Is monitoring and alerting adequate? (can detect issues quickly)580581 **Risk Matrix**:582 ```json583 {584 "blast_radius": "MEDIUM (affects 30% of users)",585 "worst_case_scenario": "Temporary export failures (no data loss)",586 "rollback_available": true,587 "rollback_tested": false,588 "feature_flag_needed": true,589 "monitoring_adequate": true,590 "overall_risk": "MEDIUM",591 "recommendation": "CONDITIONAL_APPROVE (add feature flag + test rollback)"592 }593 ```594595 **Memory Pattern**: `code-review/${PR_ID}/phase-3/code-reviewer/risk-analysis`596597**Outputs**:598- Integration test results599- Deployment impact report600- User impact assessment601- Risk analysis with mitigation recommendations602603**Success Criteria**:604- [ ] Integration tests passing605- [ ] Deployment plan documented606- [ ] User impact understood607- [ ] Risk assessment complete with mitigation608609---610611### Phase 4: Final Approval (30 Minutes, Decision & Notification)612613**Duration**: 30 minutes614**Execution Mode**: Sequential synthesis and decision615**Agents**: `pr-manager`616617**Process**:6186191. **Generate Final Review Summary**620 ```bash621 npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"622 npx claude-flow agent spawn --type pr-manager --focus "final-summary"623 ```624625 **PR Manager** synthesizes all phases:626627 **Summary Report**:628 ```markdown629 # Code Review Summary: PR #${PR_NUMBER}630631 ## Automated Checks ✅632 - Linting: ✅ PASS (0 violations)633 - Tests: ✅ PASS (142/142 passing)634 - Coverage: ✅ PASS (93.5%, +2.3% delta)635 - Build: ✅ PASS (clean build, no warnings)636637 ## Specialized Reviews638 - **Code Quality**: 4/5 stars (Good quality, minor improvements suggested)639 - **Security**: ⚠️ 1 HIGH issue (SQL injection risk in user query)640 - **Performance**: ⚠️ 1 HIGH impact (N+1 query problem)641 - **Architecture**: ⚠️ 1 MAJOR concern (tight coupling to payment provider)642 - **Documentation**: 75% complete (missing API docs + changelog)643644 ## Integration Analysis645 - **Integration Tests**: ✅ All passing (45/45)646 - **Deployment Impact**: MEDIUM risk (requires Redis + DB migration)647 - **User Impact**: POSITIVE (new export feature)648 - **Risk Level**: MEDIUM (feature flag recommended)649650 ## Blocking Issues (MUST FIX)651 1. [HIGH/SECURITY] SQL injection risk in src/api/users.ts:78652 2. [HIGH/PERFORMANCE] N+1 query in src/services/user-service.ts:125653654 ## High-Priority Recommendations (SHOULD FIX)655 3. [MAJOR/ARCHITECTURE] Decouple payment service from Stripe SDK656 4. [MEDIUM/DOCUMENTATION] Add API documentation for webhook endpoint657 5. [MEDIUM/DEPLOYMENT] Add feature flag for gradual rollout658659 ## Overall Decision: ⏸️ REQUEST CHANGES660661 **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.662663 **Next Steps**:664 1. Author fixes blocking issues (estimated 2-4 hours)665 2. Re-run automated checks + security/performance reviews666 3. Once green, approve for merge with feature flag enabled667 ```668669 **Memory Storage**:670 ```bash671 npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/final-summary" \672 --value "${FINAL_SUMMARY_MARKDOWN}"673 ```6746752. **Determine Decision**676677 **Decision Logic**:678 ```javascript679 function determineDecision(aggregatedReview) {680 const { blocking, highPriority, security, performance } = aggregatedReview;681682 // REJECT: Fundamental architectural problems or severe quality issues683 if (blocking.length > 5 || security.critical > 0) {684 return {685 decision: 'REJECT',686 message: 'Too many critical issues or fundamental architectural problems. Consider alternative approach.'687 };688 }689690 // REQUEST CHANGES: Blocking issues that must be fixed691 if (blocking.length > 0 || security.high > 0 || performance.high > 0) {692 return {693 decision: 'REQUEST_CHANGES',694 message: `${blocking.length} blocking issue(s) must be fixed before merge.`695 };696 }697698 // CONDITIONAL APPROVE: High-priority items should be addressed699 if (highPriority.length > 0) {700 return {701 decision: 'CONDITIONAL_APPROVE',702 message: `Approved with ${highPriority.length} recommendations to address before or after merge.`703 };704 }705706 // APPROVE: All quality gates passed707 return {708 decision: 'APPROVE',709 message: 'All quality checks passed. Ready to merge.'710 };711 }712 ```7137143. **Notify Author**715 ```bash716 npx claude-flow agent spawn --type pr-manager --focus "author-notification"717 ```718719 **PR Manager** sends notification:720 - GitHub PR comment with full review summary721 - Label PR appropriately ("changes-requested", "approved", "rejected")722 - Assign back to author (if changes needed)723 - Tag relevant reviewers for specific issues724725 **GitHub PR Comment** (example for REQUEST_CHANGES):726 ```markdown727 ## 🔍 Comprehensive Code Review Complete728729 Thank you for your contribution! Our automated review system has completed a thorough analysis.730731 ### ✅ What Went Well732 - All automated checks passing (tests, coverage, linting)733 - Clean code architecture overall734 - Good test coverage (93.5%)735736 ### ⚠️ Issues Requiring Attention737738 #### Blocking Issues (Must Fix Before Merge)739740 1. **[HIGH/SECURITY]** SQL Injection Risk741 - **File**: `src/api/users.ts:78`742 - **Issue**: User input not sanitized before database query743 - **Fix**: Use parameterized queries or ORM with proper escaping744 - **Priority**: CRITICAL745746 2. **[HIGH/PERFORMANCE]** N+1 Query Problem747 - **File**: `src/services/user-service.ts:125`748 - **Issue**: Loading user roles in loop (10x slower for 100 users)749 - **Fix**: Use eager loading with JOIN or batch query750 - **Priority**: HIGH751752 #### Recommendations (Should Address)753754 3. **[MAJOR/ARCHITECTURE]** Payment Service Coupling755 - Create PaymentProvider interface for future flexibility756 - See: [Architecture Best Practices](link)757758 4. **[MEDIUM/DOCUMENTATION]** Missing API Documentation759 - Add JSDoc for webhook endpoint760 - Update changelog with this new feature761762 ### 🔄 Next Steps763764 1. Address the 2 blocking issues above765 2. Push updates to this PR branch766 3. Automated checks will re-run automatically767 4. We'll re-review security and performance aspects768 5. Once green, we'll approve for merge!769770 **Estimated time to fix**: 2-4 hours771772 ---773 🤖 Generated by Claude Code Review System | [View Full Report](link)774 ```775776 **Memory Storage**:777 ```bash778 npx claude-flow memory store --key "code-review/${PR_ID}/phase-4/author-notification"779 npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-report true780 ```7817824. **Execute Decision Actions**783784 Based on decision, take appropriate GitHub actions:785786 **If APPROVE**:787 ```bash788 # Add approval label789 gh pr edit ${PR_NUMBER} --add-label "approved"790791 # Add approval review792 gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."793794 # Queue for merge (if auto-merge enabled)795 gh pr merge ${PR_NUMBER} --auto --squash796 ```797798 **If REQUEST_CHANGES**:799 ```bash800 # Add changes-requested label801 gh pr edit ${PR_NUMBER} --add-label "changes-requested" --remove-label "approved"802803 # Request changes804 gh pr review ${PR_NUMBER} --request-changes --body "${REVIEW_COMMENT_MARKDOWN}"805806 # Assign back to author807 gh pr edit ${PR_NUMBER} --add-assignee ${AUTHOR_USERNAME}808809 # Schedule follow-up review810 npx claude-flow memory store --key "code-review/${PR_ID}/follow-up/scheduled" --value "true"811 ```812813 **If REJECT**:814 ```bash815 # Add rejected label816 gh pr edit ${PR_NUMBER} --add-label "rejected"817818 # Provide detailed explanation819 gh pr review ${PR_NUMBER} --request-changes --body "${DETAILED_REJECTION_REASON}"820821 # Suggest alternative approaches822 gh pr comment ${PR_NUMBER} --body "Consider these alternative approaches: ${ALTERNATIVES}"823 ```8248255. **Finalize Review Session**826 ```bash827 npx claude-flow hooks session-end --export-metrics true828 npx claude-flow hooks post-task --task-id "pr-${PR_ID}"829 ```830831**Outputs**:832- Final review summary (comprehensive report)833- Merge decision (Approve/Request Changes/Reject)834- Author notification (GitHub comment)835- GitHub labels and status updated836837**Success Criteria**:838- [ ] Final summary generated and comprehensive839- [ ] Decision clear and justified840- [ ] Author notified with actionable feedback841- [ ] GitHub PR status updated appropriately842843---844845## Memory Coordination846847### Namespace Convention848849All review data follows this hierarchical pattern:850851```852code-review/{pr-id}/phase-{N}/{reviewer-type}/{findings-type}853```854855**Examples**:856- `code-review/repo/pulls/123/metadata`857- `code-review/repo/pulls/123/phase-1/code-analyzer/lint-results`858- `code-review/repo/pulls/123/phase-2/security-manager/security-review`859- `code-review/repo/pulls/123/phase-3/devops-engineer/deployment-impact`860- `code-review/repo/pulls/123/phase-4/final-summary`861862### Cross-Phase Data Flow863864**Phase 1 → Phase 2**:865```bash866# Phase 2 reviewers check if Phase 1 passed867npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-1/*/results"868869# Only proceed if all automated checks passed870if [ "$(jq '.all_passed' < phase1_results.json)" = "true" ]; then871 # Spawn specialist reviewers872 npx claude-flow task orchestrate --strategy parallel873fi874```875876**Phase 2 → Phase 3**:877```bash878# Phase 3 integration analysis references specialist findings879npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/security-manager/security-review"880npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/phase-2/performance-analyzer/performance-review"881882# Risk analysis considers all specialist findings883```884885**Phase 3 → Phase 4**:886```bash887# Phase 4 final decision aggregates all prior phases888npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**"889890# Generate comprehensive summary891```892893---894895## Scripts & Automation896897### Pre-Review Initialization898899```bash900#!/bin/bash901# Initialize code review workflow902903PR_NUMBER="$1"904REPO="$2" # e.g., "owner/repo"905PR_ID="${REPO}/pulls/${PR_NUMBER}"906907# Fetch PR metadata via GitHub API908PR_DATA=$(gh pr view ${PR_NUMBER} --json number,title,author,files,additions,deletions)909910# Setup coordination911npx claude-flow hooks pre-task --description "Code review: PR #${PR_NUMBER}"912913# Initialize star topology swarm (central coordinator + specialists)914npx claude-flow swarm init --topology star --max-agents 15 --strategy specialized915916# Store PR metadata917npx claude-flow memory store --key "code-review/${PR_ID}/metadata" --value "${PR_DATA}"918919echo "✅ Code review initialized: PR #${PR_NUMBER}"920```921922### Automated Check Gate923924```bash925#!/bin/bash926# Execute Phase 1 automated checks (gate)927928PR_ID="$1"929930echo "🤖 Running automated checks..."931932# Run checks in parallel933npx claude-flow task orchestrate --strategy parallel --max-agents 4 << EOF934 lint: npm run lint935 test: npm test936 coverage: npm run test:coverage937 build: npm run build938EOF939940# Aggregate results941LINT_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/lint-results" | jq -r '.status')942TEST_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/tester/test-results" | jq -r '.status')943COVERAGE_OK=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/qa-engineer/coverage-report" | jq -r '.meets_threshold')944BUILD_STATUS=$(npx claude-flow memory retrieve --key "code-review/${PR_ID}/phase-1/code-analyzer/build-status" | jq -r '.status')945946# Check if all passed947if [ "$LINT_STATUS" = "PASS" ] && [ "$TEST_STATUS" = "PASS" ] && [ "$COVERAGE_OK" = "true" ] && [ "$BUILD_STATUS" = "PASS" ]; then948 echo "✅ All automated checks passed. Proceeding to specialist reviews."949 exit 0950else951 echo "❌ Automated checks failed. Requesting fixes from author."952 gh pr review ${PR_NUMBER} --request-changes --body "Automated checks failed. Please fix before review continues."953 exit 1954fi955```956957### Parallel Specialist Review958959```bash960#!/bin/bash961# Execute Phase 2 specialist reviews in parallel962963PR_ID="$1"964965echo "👥 Spawning specialist reviewers..."966967# Spawn all reviewers concurrently via Claude Flow968npx claude-flow task orchestrate --strategy parallel --max-agents 10 << EOF969 code_quality: Review code quality (readability, maintainability, best practices)970 security: Review security vulnerabilities (OWASP Top 10, secrets, auth)971 performance: Review performance (algorithms, resource usage, optimizations)972 architecture: Review architecture consistency (patterns, integration, scalability)973 documentation: Review documentation completeness (code docs, API docs, changelog)974 style: Review code style consistency975 dependencies: Review dependency security and updates976 test_coverage: Review test coverage gaps977 external_docs: Review README and migration guides978 integration: Review integration fit with existing codebase979EOF980981# Wait for all reviews to complete982npx claude-flow task status --wait983984echo "✅ All specialist reviews complete."985```986987### Final Decision Script988989```bash990#!/bin/bash991# Generate final decision and notify author992993PR_ID="$1"994PR_NUMBER=$(echo $PR_ID | cut -d'/' -f3)995996# Retrieve all review data997npx claude-flow memory retrieve --pattern "code-review/${PR_ID}/**" > "/tmp/${PR_ID}-reviews.json"998999# Count issues by severity1000CRITICAL_COUNT=$(jq '[.. | .severity? | select(. == "CRITICAL")] | length' /tmp/${PR_ID}-reviews.json)1001HIGH_COUNT=$(jq '[.. | .severity? | select(. == "HIGH")] | length' /tmp/${PR_ID}-reviews.json)1002BLOCKING_COUNT=$((CRITICAL_COUNT + HIGH_COUNT))10031004# Determine decision1005if [ $CRITICAL_COUNT -gt 0 ] || [ $BLOCKING_COUNT -gt 5 ]; then1006 DECISION="REJECT"1007elif [ $BLOCKING_COUNT -gt 0 ]; then1008 DECISION="REQUEST_CHANGES"1009else1010 DECISION="APPROVE"1011fi10121013echo "📊 Review Decision: ${DECISION}"1014echo " Critical Issues: ${CRITICAL_COUNT}"1015echo " High-Severity Issues: ${HIGH_COUNT}"10161017# Notify author via GitHub1018case $DECISION in1019 APPROVE)1020 gh pr review ${PR_NUMBER} --approve --body "✅ All quality checks passed. Ready to merge."1021 gh pr edit ${PR_NUMBER} --add-label "approved"1022 ;;1023 REQUEST_CHANGES)1024 gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-summary.md"1025 gh pr edit ${PR_NUMBER} --add-label "changes-requested"1026 ;;1027 REJECT)1028 gh pr review ${PR_NUMBER} --request-changes --body-file "/tmp/${PR_ID}-rejection.md"1029 gh pr edit ${PR_NUMBER} --add-label "rejected"1030 ;;1031esac10321033# Finalize session1034npx claude-flow hooks post-task --task-id "code-review-${PR_ID}" --export-metrics true1035```10361037---10381039## Success Criteria10401041### Review Quality Metrics1042- **Coverage**: All quality dimensions reviewed (code, security, performance, architecture, docs)1043- **Consistency**: Reviews follow established guidelines and standards1044- **Actionability**: All feedback is specific, constructive, and actionable1045- **Timeliness**: Reviews completed within 4 hours (business hours)10461047### Code Quality Gates1048- **Automated Tests**: 100% passing (no failing tests)1049- **Code Coverage**: > 80% overall, > 90% for new code1050- **Linting**: 0 violations (all style rules followed)1051- **Security**: 0 critical issues, 0 high-severity issues1052- **Performance**: No high-impact performance regressions1053- **Documentation**: 100% of public APIs documented10541055### Process Metrics1056- **Review Turnaround**: < 4 hours (from PR creation to decision)1057- **Author Satisfaction**: > 4/5 (feedback is helpful and constructive)1058- **Defect Escape Rate**: < 1% (issues found in production that should have been caught)1059- **False Positive Rate**: < 5% (flagged issues that weren't actually problems)10601061---10621063## Usage Examples10641065### Example 1: Small Feature PR (Simple)10661067```bash1068# Feature: Add email validation to registration form1069PR_NUMBER=2451070PR_ID="acme-app/pulls/245"10711072# Initialize review1073./init-review.sh ${PR_NUMBER} "acme/acme-app"10741075# Phase 1: Automated checks (5 minutes)1076./automated-checks.sh ${PR_ID}1077# Output: All checks passed10781079# Phase 2: Specialist reviews (30 minutes - small PR)1080./specialist-reviews.sh ${PR_ID}1081# Output: 3 minor issues (all LOW severity)10821083# Phase 3: Integration analysis (10 minutes)1084# Output: No integration concerns, backward compatible10851086# Phase 4: Final decision1087./final-decision.sh ${PR_ID}1088# Decision: ✅ APPROVE1089# Output: "All quality checks passed. 3 minor suggestions for future consideration."1090```10911092### Example 2: Large Refactoring PR (Complex)10931094```bash1095# Refactoring: Migrate from REST to GraphQL1096PR_NUMBER=3121097PR_ID="acme-app/pulls/312"10981099# Initialize review1100./init-review.sh ${PR_NUMBER} "acme/acme-app"11011102# Phase 1: Automated checks (10 minutes)1103./automated-checks.sh ${PR_ID}1104# Output: All checks passed, coverage 94%11051106# Phase 2: Specialist reviews (2 hours)1107./specialist-reviews.sh ${PR_ID}1108# Output: 15 findings1109# - 1 HIGH/SECURITY (authentication flow changed, needs verification)1110# - 2 HIGH/PERFORMANCE (N+1 queries in new resolvers)1111# - 3 MAJOR/ARCHITECTURE (GraphQL schema design concerns)1112# - 9 MEDIUM/LOW (documentation, minor improvements)11131114# Phase 3: Integration analysis (1 hour)1115# Output: Breaking changes for API clients, migration guide needed1116# Risk: HIGH (affects all API consumers)11171118# Phase 4: Final decision1119./final-decision.sh ${PR_ID}1120# Decision: ⏸️ REQUEST CHANGES1121# Output: "3 blocking issues (security + performance). Add feature flag for gradual rollout. Provide migration guide for API clients."1122```11231124### Example 3: Security Patch PR (Critical)11251126```bash1127# Security: Fix SQL injection vulnerability1128PR_NUMBER=4181129PR_ID="acme-app/pulls/418"11301131# Initialize expedited review1132./init-review.sh ${PR_NUMBER} "acme/acme-app"11331134# Phase 1: Automated checks (5 minutes)1135./automated-checks.sh ${PR_ID}1136# Output: All checks passed11371138# Phase 2: Focus on security review (30 minutes)1139npx claude-flow agent spawn --type security-manager --focus "comprehensive-audit"1140# Output: Vulnerability fixed correctly, no new issues introduced11411142# Phase 3: Integration analysis (15 minutes)1143# Output: Backward compatible, zero downtime deployment11441145# Phase 4: Fast-track approval1146./final-decision.sh ${PR_ID}1147# Decision: ✅ APPROVE (EXPEDITED)1148# Output: "Security fix verified. No regressions. Approved for immediate merge and deployment."11491150# Deploy immediately1151gh pr merge ${PR_NUMBER} --admin --squash1152```11531154---11551156## GraphViz Process Diagram11571158See `when-reviewing-pull-request-orchestrate-comprehensive-code-review-process.dot` for visual workflow representation showing:1159- 4 phases with star topology coordination1160- 15 specialist reviewer interactions1161- Automated gate (Phase 1) preventing bad code from entering review1162- Parallel specialist reviews (Phase 2) for efficiency1163- Integration analysis (Phase 3) for deployment safety1164- Final decision logic with author notification11651166---11671168## Quality Checklist11691170Before considering code review complete, verify:11711172- [ ] **Phase 1**: All automated checks passing (lint, tests, coverage, build)1173- [ ] **Phase 2**: All specialist reviews completed, findings categorized1174- [ ] **Phase 3**: Integration impact analyzed, deployment plan documented1175- [ ] **Phase 4**: Final decision made, author notified, GitHub status updated11761177**Memory Verification**:1178- [ ] `code-review/${PR_ID}/metadata` - PR information1179- [ ] `code-review/${PR_ID}/phase-1/*` - Automated check results1180- [ ] `code-review/${PR_ID}/phase-2/*` - Specialist review findings1181- [ ] `code-review/${PR_ID}/phase-3/*` - Integration analysis1182- [ ] `code-review/${PR_ID}/phase-4/final-summary` - Comprehensive report11831184**Feedback Quality**:1185- [ ] All feedback is specific (file, line, issue clearly identified)1186- [ ] All feedback is actionable (how to fix provided)1187- [ ] All feedback is constructive (not just criticism, but improvement suggestions)1188- [ ] Severity is appropriate (not overstating or understating issues)11891190---11911192**Workflow Complexity**: Medium (15 agents, 4 hours, 4 phases)1193**Coordination Pattern**: Star topology with parallel specialist reviews1194**Memory Footprint**: ~20-30 memory entries per PR review1195**Typical Use Case**: Comprehensive PR review requiring validation across multiple quality dimensions11961197-11981199…(truncated)