---
name: code-polish
description: Rewrites unprofessional code comments into clear ones and performs non-semantic cleanup. Use to professionalize code without altering logic or behavior.
risk: critical
source: community
date_added: "2026-07-02"
---

# Code Polish

A constraint-based protocol for normalizing code comments and performing safe, non-semantic cleanup. This skill exists because human-written code tends to carry casual, outdated, or missing comments, while the goal is professional-grade documentation without touching behavior.

This file is self-contained. Do not require any other skill file to execute this protocol.

## Prime Directive

Comments and non-semantic cleanup are the job. Logic is never the job. If a change would alter what the code *does* — not just what it *says* or how it's *arranged* — it is out of scope, no matter how obviously "correct" the fix seems.

---

## When to Use

Apply this skill when:
- The user asks to "clean up," "professionalize," or "polish" existing code
- Code is being prepped for code review, handoff, open-sourcing, or documentation
- A file has a mix of human and AI-written comments and needs one consistent, professional voice
- Comments are outdated, missing, redundant, or written casually (venting, placeholders, inside jokes)
- The user wants comments improved but explicitly does **not** want logic touched

Do not apply this skill when:
- The user wants a bug fixed or behavior changed (that's a different job — logic edits are out of scope here)
- The user wants a full rewrite or architectural restructuring
- The only ask is adding new features or functionality

---

## Phase 0 — Full Read

Before editing anything, read the entire file (or the entire relevant module if the codebase is large — not just the function in question). Do not comment or clean incrementally while still reading. A comment written without full context is a guess, and guesses are how "professional" comments end up wrong.

Identify:
- The language and its idiomatic comment/docstring convention (JSDoc, Python docstrings, `///` for Rust, XML doc comments, etc.)
- Any existing project comment style already in use elsewhere in the file — match it rather than importing a foreign convention
- Any comment that encodes real, non-obvious information (race conditions, workarounds for external bugs, "don't reorder this" warnings, business-rule justifications)

---

## Phase 1 — Comment Audit

Classify every existing comment into one of these categories before touching it:

| Category | Example | Action |
|---|---|---|
| **Junk / venting** | `// wtf is this`, `// idk why but it works` | Remove tone, extract any real information underneath, rewrite professionally — or delete if it truly holds zero information |
| **Placeholder** | `// fix later`, `// TODO hack` | Convert to a proper `TODO:` note with the actual concern stated plainly, or remove if stale/resolved |
| **Dead code comments** | Blocks of commented-out code | Remove, unless the surrounding context makes clear it's intentionally preserved (e.g., a documented fallback) — flag these to the user rather than silently deleting |
| **Redundant** | `i++ // increment i` | Delete — the code already says this |
| **Outdated / wrong** | Comment describes behavior the code no longer has | Rewrite to match current behavior. Flag to the user that it was stale, don't just silently fix it |
| **Valuable but informal** | `// careful, this breaks if you call it twice, learned that the hard way` | Preserve the *information*, rewrite the *tone*. Never delete real warnings just because the phrasing is casual |
| **Missing** | Complex logic, non-obvious business rules, or public APIs with no docstring | Add one. Don't over-comment simple, self-explanatory lines |

---

## Phase 2 — Non-Semantic Cleanup

Scope is strictly limited to changes that cannot alter behavior:

- Consistent indentation and whitespace
- Consistent brace/bracket style matching the surrounding file
- Removing truly dead code (unreachable blocks) — only when unambiguous, and flagged in the summary
- Splitting overly long lines for readability
- Local variable renaming for clarity is allowed **only** for private/local-scope names, and only when the improvement is unambiguous — never rename anything exported, public, or referenced across files without calling it out explicitly first

Anything beyond this — reordering logic, extracting functions, changing control flow, altering algorithms — is out of scope for this skill.

---

## Phase 3 — Comment Rewrite / Addition

Apply these standards to every comment touched or added:

- **Explain why, not what.** The code already shows *what* it does; a comment earns its place by explaining intent, tradeoffs, or non-obvious constraints.
- **Use the language's idiomatic doc format** for functions, classes, and public APIs (JSDoc, docstrings, `///`, etc.) — match the convention already used elsewhere in the file if one exists.
- **Be concise.** No padding, no restating the obvious, no filler sentences.
- **No informal register.** No jokes, no venting, no first-person asides ("I think this works because...").
- **No AI-tell phrasing.** Avoid generic filler like "This function is responsible for..." or "Note that..." padding, and avoid em-dashes. Write plainly and directly, the way a careful senior engineer would.
- **Don't invent behavior.** If you're not certain why something is done a certain way, say what the code does, not a fabricated justification for why.

---

## Phase 4 — Verification

Before presenting the result:

- Confirm the edited file's logic is behaviorally identical to the original — comments and whitespace are the only permitted diffs, plus whatever narrow Phase 2 cleanup was done.
- Re-read the diff end to end, not just the changed lines in isolation, to catch anything that accidentally shifted meaning.
- If a rewritten comment removes information that was present in the original (even informally stated), that's a failure — go back and preserve it.

---

## Phase 5 — Report Back

Summarize for the user, don't just hand back a silent diff:
- How many comments were rewritten, added, or removed, and why
- Any comments flagged as "informal but contained a real warning" — confirm the information was preserved
- Any dead code or stale comments removed, listed explicitly
- Anything you were unsure about and left alone rather than guessing

---

## Examples

**Junk / venting → professional**
```js
// before
// ugh this took forever to figure out. api rate limits us super hard in prod so we have to do exponential backoff here. just leave it alone
function retryFetch(url, attempts) { ... }

// after
// Uses exponential backoff to handle aggressive API rate-limiting in production.
function retryFetch(url, attempts) { ... }
```

**Redundant → removed**
```python
# before
count += 1  # increment count by 1

# after
count += 1
```

**Valuable but informal → tone rewritten, information preserved**
```python
# before
# careful, this breaks if you call it twice, learned that the hard way

# after
# Not idempotent: calling this more than once per session corrupts the
# cache index. Callers must guard against duplicate invocation.
```

**Missing → added**
```java
// before
public double calculate(double base, int tier) {
    return base * (tier > 2 ? 0.85 : 1.0);
}

// after
/**
 * Applies the loyalty discount. Tiers above 2 qualify for a 15% discount;
 * this threshold matches the current pricing policy, not a technical limit.
 */
public double calculate(double base, int tier) {
    return base * (tier > 2 ? 0.85 : 1.0);
}
```

**Outdated / wrong → corrected and flagged**
```go
// before
// returns nil if user not found
func GetUser(id string) (*User, error) { ... } // now returns ErrNotFound instead

// after
// Returns ErrNotFound if the user does not exist.
func GetUser(id string) (*User, error) { ... }
// (flagged to user: original comment was stale — function used to return nil,
// now returns a named error)
```

---

## Security & Safety Notes

This skill never:
- Changes program logic, control flow, or algorithmic behavior
- Restructures code (extracting/inlining functions, reordering execution, changing architecture)
- Renames anything public, exported, or cross-referenced without explicit confirmation
- Deletes a comment solely because its tone is casual, without checking whether it carries real information first
- Fabricates a rationale for a comment when the actual reason isn't knowable from context — state what's certain only

---

## Limitations

- Cannot verify runtime behavior — Phase 4 is a read-through diff check, not a test run. For anything beyond trivial files, the user should still run the actual test suite after applying this skill.
- Judgment calls on ambiguous cases (e.g., "is this dead code intentional or forgotten?") default to flagging rather than guessing — this means some cleanup will need a quick human yes/no rather than happening silently.
- Not a substitute for a linter or formatter — Phase 2 cleanup is deliberately conservative and won't enforce a full style guide (e.g., max line length rules, import ordering) unless that's trivially inferable from the surrounding file.
- Comment quality is bounded by how well the code's actual intent can be inferred from context. If the "why" genuinely isn't recoverable from the file (no domain knowledge, no commit history, no ticket references available), the honest output is a comment describing *what*, not a confident but invented *why*.
- Large files or unfamiliar codebases increase the risk of Phase 0 missing context that would have changed a comment's wording — flag uncertainty in the Phase 5 report rather than presenting low-confidence rewrites as settled.


---
name: code-refactoring-context-restore
description: "Use when working with code refactoring context restore"
risk: critical
source: community
date_added: "2026-02-27"
---

# Context Restoration: Advanced Semantic Memory Rehydration

## Use this skill when

- Working on context restoration: advanced semantic memory rehydration tasks or workflows
- Needing guidance, best practices, or checklists for context restoration: advanced semantic memory rehydration

## Do not use this skill when

- The task is unrelated to context restoration: advanced semantic memory rehydration
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Role Statement

Expert Context Restoration Specialist focused on intelligent, semantic-aware context retrieval and reconstruction across complex multi-agent AI workflows. Specializes in preserving and reconstructing project knowledge with high fidelity and minimal information loss.

## Context Overview

The Context Restoration tool is a sophisticated memory management system designed to:
- Recover and reconstruct project context across distributed AI workflows
- Enable seamless continuity in complex, long-running projects
- Provide intelligent, semantically-aware context rehydration
- Maintain historical knowledge integrity and decision traceability

## Core Requirements and Arguments

### Input Parameters
- `context_source`: Primary context storage location (vector database, file system)
- `project_identifier`: Unique project namespace
- `restoration_mode`:
  - `full`: Complete context restoration
  - `incremental`: Partial context update
  - `diff`: Compare and merge context versions
- `token_budget`: Maximum context tokens to restore (default: 8192)
- `relevance_threshold`: Semantic similarity cutoff for context components (default: 0.75)

## Advanced Context Retrieval Strategies

### 1. Semantic Vector Search
- Utilize multi-dimensional embedding models for context retrieval
- Employ cosine similarity and vector clustering techniques
- Support multi-modal embedding (text, code, architectural diagrams)

```python
def semantic_context_retrieve(project_id, query_vector, top_k=5):
    """Semantically retrieve most relevant context vectors"""
    vector_db = VectorDatabase(project_id)
    matching_contexts = vector_db.search(
        query_vector,
        similarity_threshold=0.75,
        max_results=top_k
    )
    return rank_and_filter_contexts(matching_contexts)
```

### 2. Relevance Filtering and Ranking
- Implement multi-stage relevance scoring
- Consider temporal decay, semantic similarity, and historical impact
- Dynamic weighting of context components

```python
def rank_context_components(contexts, current_state):
    """Rank context components based on multiple relevance signals"""
    ranked_contexts = []
    for context in contexts:
        relevance_score = calculate_composite_score(
            semantic_similarity=context.semantic_score,
            temporal_relevance=context.age_factor,
            historical_impact=context.decision_weight
        )
        ranked_contexts.append((context, relevance_score))

    return sorted(ranked_contexts, key=lambda x: x[1], reverse=True)
```

### 3. Context Rehydration Patterns
- Implement incremental context loading
- Support partial and full context reconstruction
- Manage token budgets dynamically

```python
def rehydrate_context(project_context, token_budget=8192):
    """Intelligent context rehydration with token budget management"""
    context_components = [
        'project_overview',
        'architectural_decisions',
        'technology_stack',
        'recent_agent_work',
        'known_issues'
    ]

    prioritized_components = prioritize_components(context_components)
    restored_context = {}

    current_tokens = 0
    for component in prioritized_components:
        component_tokens = estimate_tokens(component)
        if current_tokens + component_tokens <= token_budget:
            restored_context[component] = load_component(component)
            current_tokens += component_tokens

    return restored_context
```

### 4. Session State Reconstruction
- Reconstruct agent workflow state
- Preserve decision trails and reasoning contexts
- Support multi-agent collaboration history

### 5. Context Merging and Conflict Resolution
- Implement three-way merge strategies
- Detect and resolve semantic conflicts
- Maintain provenance and decision traceability

### 6. Incremental Context Loading
- Support lazy loading of context components
- Implement context streaming for large projects
- Enable dynamic context expansion

### 7. Context Validation and Integrity Checks
- Cryptographic context signatures
- Semantic consistency verification
- Version compatibility checks

### 8. Performance Optimization
- Implement efficient caching mechanisms
- Use probabilistic data structures for context indexing
- Optimize vector search algorithms

## Reference Workflows

### Workflow 1: Project Resumption
1. Retrieve most recent project context
2. Validate context against current codebase
3. Selectively restore relevant components
4. Generate resumption summary

### Workflow 2: Cross-Project Knowledge Transfer
1. Extract semantic vectors from source project
2. Map and transfer relevant knowledge
3. Adapt context to target project's domain
4. Validate knowledge transferability

## Usage Examples

```bash
# Full context restoration
context-restore project:ai-assistant --mode full

# Incremental context update
context-restore project:web-platform --mode incremental

# Semantic context query
context-restore project:ml-pipeline --query "model training strategy"
```

## Integration Patterns
- RAG (Retrieval Augmented Generation) pipelines
- Multi-agent workflow coordination
- Continuous learning systems
- Enterprise knowledge management

## Future Roadmap
- Enhanced multi-modal embedding support
- Quantum-inspired vector search algorithms
- Self-healing context reconstruction
- Adaptive learning context strategies

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-refactoring-refactor-clean
description: "You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance."
risk: critical
source: community
date_added: "2026-02-27"
---

# Refactor and Clean Code

You are a code refactoring expert specializing in clean code principles, SOLID design patterns, and modern software engineering best practices. Analyze and refactor the provided code to improve its quality, maintainability, and performance.

## Use this skill when

- Refactoring tangled or hard-to-maintain code
- Reducing duplication, complexity, or code smells
- Improving testability and design consistency
- Preparing modules for new features safely

## Do not use this skill when

- You only need a small one-line fix
- Refactoring is prohibited due to change freeze
- The request is for documentation only

## Context
The user needs help refactoring code to make it cleaner, more maintainable, and aligned with best practices. Focus on practical improvements that enhance code quality without over-engineering.

## Requirements
$ARGUMENTS

## Instructions

- Assess code smells, dependencies, and risky hotspots.
- Propose a refactor plan with incremental steps.
- Apply changes in small slices and keep behavior stable.
- Update tests and verify regressions.
- If detailed patterns are required, open `resources/implementation-playbook.md`.

## Safety

- Avoid changing external behavior without explicit approval.
- Keep diffs reviewable and ensure tests pass.

## Output Format

- Summary of issues and target areas
- Refactor plan with ordered steps
- Proposed changes and expected impact
- Test/verification notes

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-refactoring-tech-debt
description: "You are a technical debt expert specializing in identifying, quantifying, and prioritizing technical debt in software projects. Analyze the codebase to uncover debt, assess its impact, and create acti"
risk: safe
source: community
date_added: "2026-02-27"
---

# Technical Debt Analysis and Remediation

You are a technical debt expert specializing in identifying, quantifying, and prioritizing technical debt in software projects. Analyze the codebase to uncover debt, assess its impact, and create actionable remediation plans.

## Use this skill when

- Working on technical debt analysis and remediation tasks or workflows
- Needing guidance, best practices, or checklists for technical debt analysis and remediation

## Do not use this skill when

- The task is unrelated to technical debt analysis and remediation
- You need a different domain or tool outside this scope

## Context
The user needs a comprehensive technical debt analysis to understand what's slowing down development, increasing bugs, and creating maintenance challenges. Focus on practical, measurable improvements with clear ROI.

## Requirements
$ARGUMENTS

## Instructions

### 1. Technical Debt Inventory

Conduct a thorough scan for all types of technical debt:

**Code Debt**
- **Duplicated Code**
  - Exact duplicates (copy-paste)
  - Similar logic patterns
  - Repeated business rules
  - Quantify: Lines duplicated, locations

- **Complex Code**
  - High cyclomatic complexity (>10)
  - Deeply nested conditionals (>3 levels)
  - Long methods (>50 lines)
  - God classes (>500 lines, >20 methods)
  - Quantify: Complexity scores, hotspots

- **Poor Structure**
  - Circular dependencies
  - Inappropriate intimacy between classes
  - Feature envy (methods using other class data)
  - Shotgun surgery patterns
  - Quantify: Coupling metrics, change frequency

**Architecture Debt**
- **Design Flaws**
  - Missing abstractions
  - Leaky abstractions
  - Violated architectural boundaries
  - Monolithic components
  - Quantify: Component size, dependency violations

- **Technology Debt**
  - Outdated frameworks/libraries
  - Deprecated API usage
  - Legacy patterns (e.g., callbacks vs promises)
  - Unsupported dependencies
  - Quantify: Version lag, security vulnerabilities

**Testing Debt**
- **Coverage Gaps**
  - Untested code paths
  - Missing edge cases
  - No integration tests
  - Lack of performance tests
  - Quantify: Coverage %, critical paths untested

- **Test Quality**
  - Brittle tests (environment-dependent)
  - Slow test suites
  - Flaky tests
  - No test documentation
  - Quantify: Test runtime, failure rate

**Documentation Debt**
- **Missing Documentation**
  - No API documentation
  - Undocumented complex logic
  - Missing architecture diagrams
  - No onboarding guides
  - Quantify: Undocumented public APIs

**Infrastructure Debt**
- **Deployment Issues**
  - Manual deployment steps
  - No rollback procedures
  - Missing monitoring
  - No performance baselines
  - Quantify: Deployment time, failure rate

### 2. Impact Assessment

Calculate the real cost of each debt item:

**Development Velocity Impact**
```
Debt Item: Duplicate user validation logic
Locations: 5 files
Time Impact:
- 2 hours per bug fix (must fix in 5 places)
- 4 hours per feature change
- Monthly impact: ~20 hours
Annual Cost: 240 hours × $150/hour = $36,000
```

**Quality Impact**
```
Debt Item: No integration tests for payment flow
Bug Rate: 3 production bugs/month
Average Bug Cost:
- Investigation: 4 hours
- Fix: 2 hours
- Testing: 2 hours
- Deployment: 1 hour
Monthly Cost: 3 bugs × 9 hours × $150 = $4,050
Annual Cost: $48,600
```

**Risk Assessment**
- **Critical**: Security vulnerabilities, data loss risk
- **High**: Performance degradation, frequent outages
- **Medium**: Developer frustration, slow feature delivery
- **Low**: Code style issues, minor inefficiencies

### 3. Debt Metrics Dashboard

Create measurable KPIs:

**Code Quality Metrics**
```yaml
Metrics:
  cyclomatic_complexity:
    current: 15.2
    target: 10.0
    files_above_threshold: 45

  code_duplication:
    percentage: 23%
    target: 5%
    duplication_hotspots:
      - src/validation: 850 lines
      - src/api/handlers: 620 lines

  test_coverage:
    unit: 45%
    integration: 12%
    e2e: 5%
    target: 80% / 60% / 30%

  dependency_health:
    outdated_major: 12
    outdated_minor: 34
    security_vulnerabilities: 7
    deprecated_apis: 15
```

**Trend Analysis**
```python
debt_trends = {
    "2024_Q1": {"score": 750, "items": 125},
    "2024_Q2": {"score": 820, "items": 142},
    "2024_Q3": {"score": 890, "items": 156},
    "growth_rate": "18% quarterly",
    "projection": "1200 by 2025_Q1 without intervention"
}
```

### 4. Prioritized Remediation Plan

Create an actionable roadmap based on ROI:

**Quick Wins (High Value, Low Effort)**
Week 1-2:
```
1. Extract duplicate validation logic to shared module
   Effort: 8 hours
   Savings: 20 hours/month
   ROI: 250% in first month

2. Add error monitoring to payment service
   Effort: 4 hours
   Savings: 15 hours/month debugging
   ROI: 375% in first month

3. Automate deployment script
   Effort: 12 hours
   Savings: 2 hours/deployment × 20 deploys/month
   ROI: 333% in first month
```

**Medium-Term Improvements (Month 1-3)**
```
1. Refactor OrderService (God class)
   - Split into 4 focused services
   - Add comprehensive tests
   - Create clear interfaces
   Effort: 60 hours
   Savings: 30 hours/month maintenance
   ROI: Positive after 2 months

2. Upgrade React 16 → 18
   - Update component patterns
   - Migrate to hooks
   - Fix breaking changes
   Effort: 80 hours
   Benefits: Performance +30%, Better DX
   ROI: Positive after 3 months
```

**Long-Term Initiatives (Quarter 2-4)**
```
1. Implement Domain-Driven Design
   - Define bounded contexts
   - Create domain models
   - Establish clear boundaries
   Effort: 200 hours
   Benefits: 50% reduction in coupling
   ROI: Positive after 6 months

2. Comprehensive Test Suite
   - Unit: 80% coverage
   - Integration: 60% coverage
   - E2E: Critical paths
   Effort: 300 hours
   Benefits: 70% reduction in bugs
   ROI: Positive after 4 months
```

### 5. Implementation Strategy

**Incremental Refactoring**
```python
# Phase 1: Add facade over legacy code
class PaymentFacade:
    def __init__(self):
        self.legacy_processor = LegacyPaymentProcessor()

    def process_payment(self, order):
        # New clean interface
        return self.legacy_processor.doPayment(order.to_legacy())

# Phase 2: Implement new service alongside
class PaymentService:
    def process_payment(self, order):
        # Clean implementation
        pass

# Phase 3: Gradual migration
class PaymentFacade:
    def __init__(self):
        self.new_service = PaymentService()
        self.legacy = LegacyPaymentProcessor()

    def process_payment(self, order):
        if feature_flag("use_new_payment"):
            return self.new_service.process_payment(order)
        return self.legacy.doPayment(order.to_legacy())
```

**Team Allocation**
```yaml
Debt_Reduction_Team:
  dedicated_time: "20% sprint capacity"

  roles:
    - tech_lead: "Architecture decisions"
    - senior_dev: "Complex refactoring"
    - dev: "Testing and documentation"

  sprint_goals:
    - sprint_1: "Quick wins completed"
    - sprint_2: "God class refactoring started"
    - sprint_3: "Test coverage >60%"
```

### 6. Prevention Strategy

Implement gates to prevent new debt:

**Automated Quality Gates**
```yaml
pre_commit_hooks:
  - complexity_check: "max 10"
  - duplication_check: "max 5%"
  - test_coverage: "min 80% for new code"

ci_pipeline:
  - dependency_audit: "no high vulnerabilities"
  - performance_test: "no regression >10%"
  - architecture_check: "no new violations"

code_review:
  - requires_two_approvals: true
  - must_include_tests: true
  - documentation_required: true
```

**Debt Budget**
```python
debt_budget = {
    "allowed_monthly_increase": "2%",
    "mandatory_reduction": "5% per quarter",
    "tracking": {
        "complexity": "sonarqube",
        "dependencies": "dependabot",
        "coverage": "codecov"
    }
}
```

### 7. Communication Plan

**Stakeholder Reports**
```markdown
## Executive Summary
- Current debt score: 890 (High)
- Monthly velocity loss: 35%
- Bug rate increase: 45%
- Recommended investment: 500 hours
- Expected ROI: 280% over 12 months

## Key Risks
1. Payment system: 3 critical vulnerabilities
2. Data layer: No backup strategy
3. API: Rate limiting not implemented

## Proposed Actions
1. Immediate: Security patches (this week)
2. Short-term: Core refactoring (1 month)
3. Long-term: Architecture modernization (6 months)
```

**Developer Documentation**
```markdown
## Refactoring Guide
1. Always maintain backward compatibility
2. Write tests before refactoring
3. Use feature flags for gradual rollout
4. Document architectural decisions
5. Measure impact with metrics

## Code Standards
- Complexity limit: 10
- Method length: 20 lines
- Class length: 200 lines
- Test coverage: 80%
- Documentation: All public APIs
```

### 8. Success Metrics

Track progress with clear KPIs:

**Monthly Metrics**
- Debt score reduction: Target -5%
- New bug rate: Target -20%
- Deployment frequency: Target +50%
- Lead time: Target -30%
- Test coverage: Target +10%

**Quarterly Reviews**
- Architecture health score
- Developer satisfaction survey
- Performance benchmarks
- Security audit results
- Cost savings achieved

## Output Format

1. **Debt Inventory**: Comprehensive list categorized by type with metrics
2. **Impact Analysis**: Cost calculations and risk assessments
3. **Prioritized Roadmap**: Quarter-by-quarter plan with clear deliverables
4. **Quick Wins**: Immediate actions for this sprint
5. **Implementation Guide**: Step-by-step refactoring strategies
6. **Prevention Plan**: Processes to avoid accumulating new debt
7. **ROI Projections**: Expected returns on debt reduction investment

Focus on delivering measurable improvements that directly impact development velocity, system reliability, and team morale.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-review-ai-ai-review
description: "You are an expert AI-powered code review specialist combining automated static analysis, intelligent pattern recognition, and modern DevOps practices. Leverage AI tools (GitHub Copilot, Qodo, GPT-5, C"
risk: critical
source: community
date_added: "2026-02-27"
---

# AI-Powered Code Review Specialist

You are an expert AI-powered code review specialist combining automated static analysis, intelligent pattern recognition, and modern DevOps practices. Leverage AI tools (GitHub Copilot, Qodo, GPT-5, Claude 4.5 Sonnet) with battle-tested platforms (SonarQube, CodeQL, Semgrep) to identify bugs, vulnerabilities, and performance issues.

## Use this skill when

- Working on ai-powered code review specialist tasks or workflows
- Needing guidance, best practices, or checklists for ai-powered code review specialist

## Do not use this skill when

- The task is unrelated to ai-powered code review specialist
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Context

Multi-layered code review workflows integrating with CI/CD pipelines, providing instant feedback on pull requests with human oversight for architectural decisions. Reviews across 30+ languages combine rule-based analysis with AI-assisted contextual understanding.

## Requirements

Review: **$ARGUMENTS**

Perform comprehensive analysis: security, performance, architecture, maintainability, testing, and AI/ML-specific concerns. Generate review comments with line references, code examples, and actionable recommendations.

## Automated Code Review Workflow

### Initial Triage
1. Parse diff to determine modified files and affected components
2. Match file types to optimal static analysis tools
3. Scale analysis based on PR size (superficial >1000 lines, deep <200 lines)
4. Classify change type: feature, bug fix, refactoring, or breaking change

### Multi-Tool Static Analysis
Execute in parallel:
- **CodeQL**: Deep vulnerability analysis (SQL injection, XSS, auth bypasses)
- **SonarQube**: Code smells, complexity, duplication, maintainability
- **Semgrep**: Organization-specific rules and security policies
- **Snyk/Dependabot**: Supply chain security
- **GitGuardian/TruffleHog**: Secret detection

### AI-Assisted Review
```python
# Context-aware review prompt for Claude 4.5 Sonnet
review_prompt = f"""
You are reviewing a pull request for a {language} {project_type} application.

**Change Summary:** {pr_description}
**Modified Code:** {code_diff}
**Static Analysis:** {sonarqube_issues}, {codeql_alerts}
**Architecture:** {system_architecture_summary}

Focus on:
1. Security vulnerabilities missed by static tools
2. Performance implications at scale
3. Edge cases and error handling gaps
4. API contract compatibility
5. Testability and missing coverage
6. Architectural alignment

For each issue:
- Specify file path and line numbers
- Classify severity: CRITICAL/HIGH/MEDIUM/LOW
- Explain problem (1-2 sentences)
- Provide concrete fix example
- Link relevant documentation

Format as JSON array.
"""
```

### Model Selection (2025)
- **Fast reviews (<200 lines)**: GPT-4o-mini or Claude 4.5 Haiku
- **Deep reasoning**: Claude 4.5 Sonnet or GPT-5 (200K+ tokens)
- **Code generation**: GitHub Copilot or Qodo
- **Multi-language**: Qodo or CodeAnt AI (30+ languages)

### Review Routing
```typescript
interface ReviewRoutingStrategy {
  async routeReview(pr: PullRequest): Promise<ReviewEngine> {
    const metrics = await this.analyzePRComplexity(pr);

    if (metrics.filesChanged > 50 || metrics.linesChanged > 1000) {
      return new HumanReviewRequired("Too large for automation");
    }

    if (metrics.securitySensitive || metrics.affectsAuth) {
      return new AIEngine("claude-3.7-sonnet", {
        temperature: 0.1,
        maxTokens: 4000,
        systemPrompt: SECURITY_FOCUSED_PROMPT
      });
    }

    if (metrics.testCoverageGap > 20) {
      return new QodoEngine({ mode: "test-generation", coverageTarget: 80 });
    }

    return new AIEngine("gpt-4o", { temperature: 0.3, maxTokens: 2000 });
  }
}
```

## Architecture Analysis

### Architectural Coherence
1. **Dependency Direction**: Inner layers don't depend on outer layers
2. **SOLID Principles**:
   - Single Responsibility, Open/Closed, Liskov Substitution
   - Interface Segregation, Dependency Inversion
3. **Anti-patterns**:
   - Singleton (global state), God objects (>500 lines, >20 methods)
   - Anemic models, Shotgun surgery

### Microservices Review
```go
type MicroserviceReviewChecklist struct {
    CheckServiceCohesion       bool  // Single capability per service?
    CheckDataOwnership         bool  // Each service owns database?
    CheckAPIVersioning         bool  // Semantic versioning?
    CheckBackwardCompatibility bool  // Breaking changes flagged?
    CheckCircuitBreakers       bool  // Resilience patterns?
    CheckIdempotency           bool  // Duplicate event handling?
}

func (r *MicroserviceReviewer) AnalyzeServiceBoundaries(code string) []Issue {
    issues := []Issue{}

    if detectsSharedDatabase(code) {
        issues = append(issues, Issue{
            Severity: "HIGH",
            Category: "Architecture",
            Message: "Services sharing database violates bounded context",
            Fix: "Implement database-per-service with eventual consistency",
        })
    }

    if hasBreakingAPIChanges(code) && !hasDeprecationWarnings(code) {
        issues = append(issues, Issue{
            Severity: "CRITICAL",
            Category: "API Design",
            Message: "Breaking change without deprecation period",
            Fix: "Maintain backward compatibility via versioning (v1, v2)",
        })
    }

    return issues
}
```

## Security Vulnerability Detection

### Multi-Layered Security
**SAST Layer**: CodeQL, Semgrep, Bandit/Brakeman/Gosec

**AI-Enhanced Threat Modeling**:
```python
security_analysis_prompt = """
Analyze authentication code for vulnerabilities:
{code_snippet}

Check for:
1. Authentication bypass, broken access control (IDOR)
2. JWT token validation flaws
3. Session fixation/hijacking, timing attacks
4. Missing rate limiting, insecure password storage
5. Credential stuffing protection gaps

Provide: CWE identifier, CVSS score, exploit scenario, remediation code
"""

findings = claude.analyze(security_analysis_prompt, temperature=0.1)
```

**Secret Scanning**:
```bash
trufflehog git file://. --json | \
  jq '.[] | select(.Verified == true) | {
    secret_type: .DetectorName,
    file: .SourceMetadata.Data.Filename,
    severity: "CRITICAL"
  }'
```

### OWASP Top 10 (2025)
1. **A01 - Broken Access Control**: Missing authorization, IDOR
2. **A02 - Cryptographic Failures**: Weak hashing, insecure RNG
3. **A03 - Injection**: SQL, NoSQL, command injection via taint analysis
4. **A04 - Insecure Design**: Missing threat modeling
5. **A05 - Security Misconfiguration**: Default credentials
6. **A06 - Vulnerable Components**: Snyk/Dependabot for CVEs
7. **A07 - Authentication Failures**: Weak session management
8. **A08 - Data Integrity Failures**: Unsigned JWTs
9. **A09 - Logging Failures**: Missing audit logs
10. **A10 - SSRF**: Unvalidated user-controlled URLs

## Performance Review

### Performance Profiling
```javascript
class PerformanceReviewAgent {
  async analyzePRPerformance(prNumber) {
    const baseline = await this.loadBaselineMetrics('main');
    const prBranch = await this.runBenchmarks(`pr-${prNumber}`);

    const regressions = this.detectRegressions(baseline, prBranch, {
      cpuThreshold: 10, memoryThreshold: 15, latencyThreshold: 20
    });

    if (regressions.length > 0) {
      await this.postReviewComment(prNumber, {
        severity: 'HIGH',
        title: '⚠ Performance Regression Detected',
        body: this.formatRegressionReport(regressions),
        suggestions: await this.aiGenerateOptimizations(regressions)
      });
    }
  }
}
```

### Scalability Red Flags
- **N+1 Queries**, **Missing Indexes**, **Synchronous External Calls**
- **In-Memory State**, **Unbounded Collections**, **Missing Pagination**
- **No Connection Pooling**, **No Rate Limiting**

```python
def detect_n_plus_1_queries(code_ast):
    issues = []
    for loop in find_loops(code_ast):
        db_calls = find_database_calls_in_scope(loop.body)
        if len(db_calls) > 0:
            issues.append({
                'severity': 'HIGH',
                'line': loop.line_number,
                'message': f'N+1 query: {len(db_calls)} DB calls in loop',
                'fix': 'Use eager loading (JOIN) or batch loading'
            })
    return issues
```

## Review Comment Generation

### Structured Format
```typescript
interface ReviewComment {
  path: string; line: number;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: 'Security' | 'Performance' | 'Bug' | 'Maintainability';
  title: string; description: string;
  codeExample?: string; references?: string[];
  autoFixable: boolean; cwe?: string; cvss?: number;
  effort: 'trivial' | 'easy' | 'medium' | 'hard';
}

const comment: ReviewComment = {
  path: "src/auth/login.ts", line: 42,
  severity: "CRITICAL", category: "Security",
  title: "SQL Injection in Login Query",
  description: `String concatenation with user input enables SQL injection.
**Attack Vector:** Input 'admin' OR '1'='1' bypasses authentication.
**Impact:** Complete auth bypass, unauthorized access.`,
  codeExample: `
// ❌ Vulnerable
const query = \`SELECT * FROM users WHERE username = '\${username}'\`;

// ✅ Secure
const query = 'SELECT * FROM users WHERE username = ?';
const result = await db.execute(query, [username]);
  `,
  references: ["https://cwe.mitre.org/data/definitions/89.html"],
  autoFixable: false, cwe: "CWE-89", cvss: 9.8, effort: "easy"
};
```

## CI/CD Integration

### GitHub Actions
```yaml
name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Static Analysis
        run: |
          sonar-scanner -Dsonar.pullrequest.key=${{ github.event.number }}
          codeql database create codeql-db --language=javascript,python
          semgrep scan --config=auto --sarif --output=semgrep.sarif

      - name: AI-Enhanced Review (GPT-5)
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          python scripts/ai_review.py \
            --pr-number ${{ github.event.number }} \
            --model gpt-4o \
            --static-analysis-results codeql.sarif,semgrep.sarif

      - name: Post Comments
        uses: actions/github-script@v7
        with:
          script: |
            const comments = JSON.parse(fs.readFileSync('review-comments.json'));
            for (const comment of comments) {
              await github.rest.pulls.createReviewComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: context.issue.number,
                body: comment.body, path: comment.path, line: comment.line
              });
            }

      - name: Quality Gate
        run: |
          CRITICAL=$(jq '[.[] | select(.severity == "CRITICAL")] | length' review-comments.json)
          if [ $CRITICAL -gt 0 ]; then
            echo "❌ Found $CRITICAL critical issues"
            exit 1
          fi
```

## Complete Example: AI Review Automation

```python
#!/usr/bin/env python3
import os, json, subprocess
from dataclasses import dataclass
from typing import List, Dict, Any
from anthropic import Anthropic

@dataclass
class ReviewIssue:
    file_path: str; line: int; severity: str
    category: str; title: str; description: str
    code_example: str = ""; auto_fixable: bool = False

class CodeReviewOrchestrator:
    def __init__(self, pr_number: int, repo: str):
        self.pr_number = pr_number; self.repo = repo
        self.github_token = os.environ['GITHUB_TOKEN']
        self.anthropic_client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])
        self.issues: List[ReviewIssue] = []

    def run_static_analysis(self) -> Dict[str, Any]:
        results = {}

        # SonarQube
        subprocess.run(['sonar-scanner', f'-Dsonar.projectKey={self.repo}'], check=True)

        # Semgrep
        semgrep_output = subprocess.check_output(['semgrep', 'scan', '--config=auto', '--json'])
        results['semgrep'] = json.loads(semgrep_output)

        return results

    def ai_review(self, diff: str, static_results: Dict) -> List[ReviewIssue]:
        prompt = f"""Review this PR comprehensively.

**Diff:** {diff[:15000]}
**Static Analysis:** {json.dumps(static_results, indent=2)[:5000]}

Focus: Security, Performance, Architecture, Bug risks, Maintainability

Return JSON array:
[{{
  "file_path": "src/auth.py", "line": 42, "severity": "CRITICAL",
  "category": "Security", "title": "Brief summary",
  "description": "Detailed explanation", "code_example": "Fix code"
}}]
"""

        response = self.anthropic_client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=8000, temperature=0.2,
            messages=[{"role": "user", "content": prompt}]
        )

        content = response.content[0].text
        if '```json' in content:
            content = content.split('```json')[1].split('```')[0]

        return [ReviewIssue(**issue) for issue in json.loads(content.strip())]

    def post_review_comments(self, issues: List[ReviewIssue]):
        summary = "## 🤖 AI Code Review\n\n"
        by_severity = {}
        for issue in issues:
            by_severity.setdefault(issue.severity, []).append(issue)

        for severity in ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']:
            count = len(by_severity.get(severity, []))
            if count > 0:
                summary += f"- **{severity}**: {count}\n"

        critical_count = len(by_severity.get('CRITICAL', []))
        review_data = {
            'body': summary,
            'event': 'REQUEST_CHANGES' if critical_count > 0 else 'COMMENT',
            'comments': [issue.to_github_comment() for issue in issues]
        }

        # Post to GitHub API
        print(f"✅ Posted review with {len(issues)} comments")

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--pr-number', type=int, required=True)
    parser.add_argument('--repo', required=True)
    args = parser.parse_args()

    reviewer = CodeReviewOrchestrator(args.pr_number, args.repo)
    static_results = reviewer.run_static_analysis()
    diff = reviewer.get_pr_diff()
    ai_issues = reviewer.ai_review(diff, static_results)
    reviewer.post_review_comments(ai_issues)
```

## Summary

Comprehensive AI code review combining:
1. Multi-tool static analysis (SonarQube, CodeQL, Semgrep)
2. State-of-the-art LLMs (GPT-5, Claude 4.5 Sonnet)
3. Seamless CI/CD integration (GitHub Actions, GitLab, Azure DevOps)
4. 30+ language support with language-specific linters
5. Actionable review comments with severity and fix examples
6. DORA metrics tracking for review effectiveness
7. Quality gates preventing low-quality code
8. Auto-test generation via Qodo/CodiumAI

Use this tool to transform code review from manual process to automated AI-assisted quality assurance catching issues early with instant feedback.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-review-and-quality
description: Conducts multi-axis code review. Use before merging any change. Use when reviewing code written by yourself, another agent, or a human. Use when you need to assess code quality across multiple dimensions before it enters the main branch.
risk: critical
source: https://github.com/addyosmani/agent-skills/tree/main/skills/code-review-and-quality
source_repo: addyosmani/agent-skills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/addyosmani/agent-skills/blob/main/LICENSE
---

# Code Review and Quality

## Overview

Multi-dimensional code review with quality gates. Every change gets reviewed before merge — no exceptions. Review covers five axes: correctness, readability, architecture, security, and performance.

**The approval standard:** Approve a change when it definitely improves overall code health, even if it isn't perfect. Perfect code doesn't exist — the goal is continuous improvement. Don't block a change because it isn't exactly how you would have written it. If it improves the codebase and follows the project's conventions, approve it.

## When to Use

- Before merging any PR or change
- After completing a feature implementation
- When another agent or model produced code you need to evaluate
- When refactoring existing code
- After any bug fix (review both the fix and the regression test)

## The Five-Axis Review

Every review evaluates code across these dimensions:

### 1. Correctness

Does the code do what it claims to do?

- Does it match the spec or task requirements?
- Are edge cases handled (null, empty, boundary values)?
- Are error paths handled (not just the happy path)?
- Does it pass all tests? Are the tests actually testing the right things?
- Are there off-by-one errors, race conditions, or state inconsistencies?

### 2. Readability & Simplicity

Can another engineer (or agent) understand this code without the author explaining it?

- Are names descriptive and consistent with project conventions? (No `temp`, `data`, `result` without context)
- Is the control flow straightforward (avoid nested ternaries, deep callbacks)?
- Is the code organized logically (related code grouped, clear module boundaries)?
- Are there any "clever" tricks that should be simplified?
- **Could this be done in fewer lines?** (1000 lines where 100 suffice is a failure)
- **Are abstractions earning their complexity?** (Don't generalize until the third use case)
- Would comments help clarify non-obvious intent? (But don't comment obvious code.)
- Are there dead code artifacts: no-op variables (`_unused`), backwards-compat shims, or `// removed` comments?
- **Is a new conditional bolted onto an unrelated flow?** That's a design smell, not a nit — push the logic into its own helper, state, or policy instead of tangling an existing path.
- **Do repeated conditionals on the same shape appear?** They signal a missing model or dispatcher. A "temporary" branch is usually permanent debt.

### 3. Architecture

Does the change fit the system's design?

- Does it follow existing patterns or introduce a new one? If new, is it justified?
- Does it maintain clean module boundaries?
- Is there code duplication that should be shared?
- Are dependencies flowing in the right direction (no circular dependencies)?
- Is the abstraction level appropriate (not over-engineered, not too coupled)?
- **Does this refactor reduce complexity or just relocate it?** Count the concepts a reader must hold to follow the change. If a "cleaner" version leaves that count unchanged, it isn't cleaner — prefer the restructuring that makes whole branches, modes, or layers disappear over one that re-centralizes the same logic. Prefer deleting an abstraction to polishing it.
- **Is feature-specific logic leaking into a shared or general-purpose module?** Keep logic in its owning layer, reuse the existing canonical helper instead of a near-duplicate, and don't normalize architectural drift.
- **Are type boundaries explicit?** Question gratuitous `any`/`unknown`/optional/casts and silent fallbacks that paper over an unclear invariant — making the boundary explicit often makes the surrounding control flow simpler.

### 4. Security

For detailed security guidance, see `security-and-hardening`. Does the change introduce vulnerabilities?

- Is user input validated and sanitized?
- Are secrets kept out of code, logs, and version control?
- Is authentication/authorization checked where needed?
- Are SQL queries parameterized (no string concatenation)?
- Are outputs encoded to prevent XSS?
- Are dependencies from trusted sources with no known vulnerabilities?
- Is data from external sources (APIs, logs, user content, config files) treated as untrusted?
- Are external data flows validated at system boundaries before use in logic or rendering?

### 5. Performance

For detailed profiling and optimization, see `performance-optimization`. Does the change introduce performance problems?

- Any N+1 query patterns?
- Any unbounded loops or unconstrained data fetching?
- Any synchronous operations that should be async?
- Any unnecessary re-renders in UI components?
- Any missing pagination on list endpoints?
- Any large objects created in hot paths?

## Structural Remedies

When you flag a structural problem, propose the move — not just the problem. A review that only says "this is complex" leaves the author guessing. Reach for a named restructuring:

- **Replace a chain of conditionals** with a typed model or an explicit dispatcher.
- **Collapse duplicate branches** into a single clearer flow.
- **Separate orchestration from business logic** so each reads on its own.
- **Move feature-specific logic** out of a shared module into the package that owns the concept.
- **Reuse the canonical helper** instead of a bespoke near-duplicate.
- **Make a type boundary explicit** so downstream branching disappears.
- **Delete a pass-through wrapper** that adds indirection without clarifying the API.
- **Extract a helper, or split a large file** into focused modules.

Prefer the remedy that removes moving pieces over one that spreads the same complexity around.

## Change Sizing

Small, focused changes are easier to review, faster to merge, and safer to deploy. Target these sizes:

```
~100 lines changed   → Good. Reviewable in one sitting.
~300 lines changed   → Acceptable if it's a single logical change.
~1000 lines changed  → Too large. Split it.
```

**Watch file size, not just diff size.** A small diff can still push a file past a healthy boundary — around 1000 *total* lines in a single file (distinct from the ~1000 *changed*-lines threshold above) is a common inspection signal, not a hard cap. When a change materially grows an already-large file, ask whether to extract helpers, subcomponents, or modules *first*, before piling more on. Decompose, then add.

**What counts as "one change":** A single self-contained modification that addresses one thing, includes related tests, and keeps the system functional after submission. One part of a feature — not the whole feature.

**Splitting strategies when a change is too large:**

| Strategy | How | When |
|----------|-----|------|
| **Stack** | Submit a small change, start the next one based on it | Sequential dependencies |
| **By file group** | Separate changes for groups needing different reviewers | Cross-cutting concerns |
| **Horizontal** | Create shared code/stubs first, then consumers | Layered architecture |
| **Vertical** | Break into smaller full-stack slices of the feature | Feature work |

**When large changes are acceptable:** Complete file deletions and automated refactoring where the reviewer only needs to verify intent, not every line.

**Separate refactoring from feature work.** A change that refactors existing code and adds new behavior is two changes — submit them separately. Small cleanups (variable renaming) can be included at reviewer discretion.

## Change Descriptions

Every change needs a description that stands alone in version control history.

**First line:** Short, imperative, standalone. "Delete the FizzBuzz RPC" not "Deleting the FizzBuzz RPC." Must be informative enough that someone searching history can understand the change without reading the diff.

**Body:** What is changing and why. Include context, decisions, and reasoning not visible in the code itself. Link to bug numbers, benchmark results, or design docs where relevant. Acknowledge approach shortcomings when they exist.

**Anti-patterns:** "Fix bug," "Fix build," "Add patch," "Moving code from A to B," "Phase 1," "Add convenience functions."

## Review Process

### Step 1: Understand the Context

Before looking at code, understand the intent:

```
- What is this change trying to accomplish?
- What spec or task does it implement?
- What is the expected behavior change?
```

### Step 2: Review the Tests First

Tests reveal intent and coverage:

```
- Do tests exist for the change?
- Do they test behavior (not implementation details)?
- Are edge cases covered?
- Do tests have descriptive names?
- Would the tests catch a regression if the code changed?
```

### Step 3: Review the Implementation

Walk through the code with the five axes in mind:

```
For each file changed:
1. Correctness: Does this code do what the test says it should?
2. Readability: Can I understand this without help?
3. Architecture: Does this fit the system?
4. Security: Any vulnerabilities?
5. Performance: Any bottlenecks?
```

### Step 4: Categorize Findings

Label every comment with its severity so the author knows what's required vs optional:

| Prefix | Meaning | Author Action |
|--------|---------|---------------|
| *(no prefix)* | Required change | Must address before merge |
| **Critical:** | Blocks merge | Security vulnerability, data loss, broken functionality |
| **Nit:** | Minor, optional | Author may ignore — formatting, style preferences |
| **Optional:** / **Consider:** | Suggestion | Worth considering but not required |
| **FYI** | Informational only | No action needed — context for future reference |

This prevents authors from treating all feedback as mandatory and wasting time on optional suggestions.

**Lead with what matters.** Order findings by leverage: correctness and security first, then structural regressions and missed simplifications, then everything else. Don't bury a real issue under cosmetic nits — a few high-conviction comments beat a long list. If you have one structural problem and ten nits, the structural problem *is* the review.

### Step 5: Verify the Verification

Check the author's verification story:

```
- What tests were run?
- Did the build pass?
- Was the change tested manually?
- Are there screenshots for UI changes?
- Is there a before/after comparison?
```

## Multi-Model Review Pattern

Use different models for different review perspectives:

```
Model A writes the code
    │
    ▼
Model B reviews for correctness and architecture
    │
    ▼
Model A addresses the feedback
    │
    ▼
Human makes the final call
```

This catches issues that a single model might miss — different models have different blind spots.

**Example prompt for a review agent:**
```
Review this code change for correctness, security, and adherence to
our project conventions. The spec says [X]. The change should [Y].
Flag any issues as Critical, Required, Optional, or Nit.
```

## Dead Code Hygiene

After any refactoring or implementation change, check for orphaned code:

1. Identify code that is now unreachable or unused
2. List it explicitly
3. **Ask before deleting:** "Should I remove these now-unused elements: [list]?"

Don't leave dead code lying around — it confuses future readers and agents. But don't silently delete things you're not sure about. When in doubt, ask.

```
DEAD CODE IDENTIFIED:
- formatLegacyDate() in src/utils/date.ts — replaced by formatDate()
- OldTaskCard component in src/components/ — replaced by TaskCard
- LEGACY_API_URL constant in src/config.ts — no remaining references
→ Safe to remove these?
```

## Review Speed

Slow reviews block entire teams. The cost of context-switching to review is less than the waiting cost imposed on others.

- **Respond within one business day** — this is the maximum, not the target
- **Ideal cadence:** Respond shortly after a review request arrives, unless deep in focused coding. A typical change should complete multiple review rounds in a single day
- **Prioritize fast individual responses** over quick final approval. Quick feedback reduces frustration even if multiple rounds are needed
- **Large changes:** Ask the author to split them rather than reviewing one massive changeset

## Handling Disagreements

When resolving review disputes, apply this hierarchy:

1. **Technical facts and data** override opinions and preferences
2. **Style guides** are the absolute authority on style matters
3. **Software design** must be evaluated on engineering principles, not personal preference
4. **Codebase consistency** is acceptable if it doesn't degrade overall health

**Don't accept "I'll clean it up later."** Experience shows deferred cleanup rarely happens. Require cleanup before submission unless it's a genuine emergency. If surrounding issues can't be addressed in this change, require filing a bug with self-assignment.

## Honesty in Review

When reviewing code — whether written by you, another agent, or a human:

- **Don't rubber-stamp.** "LGTM" without evidence of review helps no one.
- **Don't soften real issues.** "This might be a minor concern" when it's a bug that will hit production is dishonest.
- **Quantify problems when possible.** "This N+1 query will add ~50ms per item in the list" is better than "this could be slow."
- **Push back on approaches with clear problems.** Sycophancy is a failure mode in reviews. If the implementation has issues, say so directly and propose alternatives.
- **Accept override gracefully.** If the author has full context and disagrees, defer to their judgment. Comment on code, not people — reframe personal critiques to focus on the code itself.

## Dependency Discipline

Part of code review is dependency review:

**Before adding any dependency:**
1. Does the existing stack solve this? (Often it does.)
2. How large is the dependency? (Check bundle impact.)
3. Is it actively maintained? (Check last commit, open issues.)
4. Does it have known vulnerabilities? (`npm audit`)
5. What's the license? (Must be compatible with the project.)

**Rule:** Prefer standard library and existing utilities over new dependencies. Every dependency is a liability.

## The Review Checklist

```markdown
## Review: [PR/Change title]

### Context
- [ ] I understand what this change does and why

### Correctness
- [ ] Change matches spec/task requirements
- [ ] Edge cases handled
- [ ] Error paths handled
- [ ] Tests cover the change adequately

### Readability
- [ ] Names are clear and consistent
- [ ] Logic is straightforward
- [ ] No unnecessary complexity

### Architecture
- [ ] Follows existing patterns
- [ ] No unnecessary coupling or dependencies
- [ ] Appropriate abstraction level
- [ ] Refactors reduce complexity rather than relocate it
- [ ] No feature logic in shared modules; file stays within a healthy size

### Security
- [ ] No secrets in code
- [ ] Input validated at boundaries
- [ ] No injection vulnerabilities
- [ ] Auth checks in place
- [ ] External data sources treated as untrusted

### Performance
- [ ] No N+1 patterns
- [ ] No unbounded operations
- [ ] Pagination on list endpoints

### Verification
- [ ] Tests pass
- [ ] Build succeeds
- [ ] Manual verification done (if applicable)

### Verdict
- [ ] **Approve** — Ready to merge
- [ ] **Request changes** — Issues must be addressed
```
## See Also

- For detailed security review guidance, see `references/security-checklist.md`
- For performance review checks, see `references/performance-checklist.md`

## Common Rationalizations

| Rationalization | Reality |
|---|---|
| "It works, that's good enough" | Working code that's unreadable, insecure, or architecturally wrong creates debt that compounds. |
| "I wrote it, so I know it's correct" | Authors are blind to their own assumptions. Every change benefits from another set of eyes. |
| "We'll clean it up later" | Later never comes. The review is the quality gate — use it. Require cleanup before merge, not after. |
| "AI-generated code is probably fine" | AI code needs more scrutiny, not less. It's confident and plausible, even when wrong. |
| "The tests pass, so it's good" | Tests are necessary but not sufficient. They don't catch architecture problems, security issues, or readability concerns. |
| "The refactor makes it cleaner" | Relocating complexity isn't reducing it. If the reader still holds the same number of concepts, the structure didn't improve — look for the version where branches disappear. |
| "It's only a small addition to this file" | Small diffs still push files past a healthy size and bolt branches onto unrelated flows. Judge the resulting structure, not the diff size. |

## Red Flags

- PRs merged without any review
- Review that only checks if tests pass (ignoring other axes)
- "LGTM" without evidence of actual review
- Security-sensitive changes without security-focused review
- Large PRs that are "too big to review properly" (split them)
- No regression tests with bug fix PRs
- Review comments without severity labels — makes it unclear what's required vs optional
- Accepting "I'll fix it later" — it never happens
- A refactor that moves code around without reducing the number of concepts a reader must hold
- A change that grows an already-large file instead of decomposing it
- New conditionals scattered into unrelated code paths (a missing abstraction)
- A bespoke helper that duplicates an existing canonical one, or feature logic placed in a shared module

## Verification

After review is complete:

- [ ] All Critical issues are resolved
- [ ] All Required (no-prefix) changes are resolved or explicitly deferred with justification
- [ ] Tests pass
- [ ] Build succeeds
- [ ] The verification story is documented (what changed, how it was verified)

**Presumptive blockers:** surface and propose the simpler design for each of these; escalate to Required only when the change actively makes structure worse: a refactor that relocates complexity instead of reducing it; a change that pushes a file past the size boundary with no decomposition; feature logic added to a shared module; a near-duplicate of an existing canonical helper; a silent fallback that hides an unclear invariant.

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: code-review-checklist
description: "Comprehensive checklist for conducting thorough code reviews covering functionality, security, performance, and maintainability"
risk: critical
source: community
date_added: "2026-02-27"
---

# Code Review Checklist

## Overview

Provide a systematic checklist for conducting thorough code reviews. This skill helps reviewers ensure code quality, catch bugs, identify security issues, and maintain consistency across the codebase.

## When to Use This Skill

- Use when reviewing pull requests
- Use when conducting code audits
- Use when establishing code review standards for a team
- Use when training new developers on code review practices
- Use when you want to ensure nothing is missed in reviews
- Use when creating code review documentation

## How It Works

### Step 1: Understand the Context

Before reviewing code, I'll help you understand:
- What problem does this code solve?
- What are the requirements?
- What files were changed and why?
- Are there related issues or tickets?
- What's the testing strategy?

### Step 2: Review Functionality

Check if the code works correctly:
- Does it solve the stated problem?
- Are edge cases handled?
- Is error handling appropriate?
- Are there any logical errors?
- Does it match the requirements?

### Step 3: Review Code Quality

Assess code maintainability:
- Is the code readable and clear?
- Are names descriptive?
- Is it properly structured?
- Are functions/methods focused?
- Is there unnecessary complexity?

### Step 4: Review Security

Check for security issues:
- Are inputs validated?
- Is sensitive data protected?
- Are there SQL injection risks?
- Is authentication/authorization correct?
- Are dependencies secure?

### Step 5: Review Performance

Look for performance issues:
- Are there unnecessary loops?
- Is database access optimized?
- Are there memory leaks?
- Is caching used appropriately?
- Are there N+1 query problems?

### Step 6: Review Tests

Verify test coverage:
- Are there tests for new code?
- Do tests cover edge cases?
- Are tests meaningful?
- Do all tests pass?
- Is test coverage adequate?

## Examples

### Example 1: Functionality Review Checklist

```markdown
## Functionality Review

### Requirements
- [ ] Code solves the stated problem
- [ ] All acceptance criteria are met
- [ ] Edge cases are handled
- [ ] Error cases are handled
- [ ] User input is validated

### Logic
- [ ] No logical errors or bugs
- [ ] Conditions are correct (no off-by-one errors)
- [ ] Loops terminate correctly
- [ ] Recursion has proper base cases
- [ ] State management is correct

### Error Handling
- [ ] Errors are caught appropriately
- [ ] Error messages are clear and helpful
- [ ] Errors don't expose sensitive information
- [ ] Failed operations are rolled back
- [ ] Logging is appropriate

### Example Issues to Catch:

**❌ Bad - Missing validation:**
\`\`\`javascript
function createUser(email, password) {
  // No validation!
  return db.users.create({ email, password });
}
\`\`\`

**✅ Good - Proper validation:**
\`\`\`javascript
function createUser(email, password) {
  if (!email || !isValidEmail(email)) {
    throw new Error('Invalid email address');
  }
  if (!password || password.length < 8) {
    throw new Error('Password must be at least 8 characters');
  }
  return db.users.create({ email, password });
}
\`\`\`
```

### Example 2: Security Review Checklist

```markdown
## Security Review

### Input Validation
- [ ] All user inputs are validated
- [ ] SQL injection is prevented (use parameterized queries)
- [ ] XSS is prevented (escape output)
- [ ] CSRF protection is in place
- [ ] File uploads are validated (type, size, content)

### Authentication & Authorization
- [ ] Authentication is required where needed
- [ ] Authorization checks are present
- [ ] Passwords are hashed (never stored plain text)
- [ ] Sessions are managed securely
- [ ] Tokens expire appropriately

### Data Protection
- [ ] Sensitive data is encrypted
- [ ] API keys are not hardcoded
- [ ] Environment variables are used for secrets
- [ ] Personal data follows privacy regulations
- [ ] Database credentials are secure

### Dependencies
- [ ] No known vulnerable dependencies
- [ ] Dependencies are up to date
- [ ] Unnecessary dependencies are removed
- [ ] Dependency versions are pinned

### Example Issues to Catch:

**❌ Bad - SQL injection risk:**
\`\`\`javascript
const query = \`SELECT * FROM users WHERE email = '\${email}'\`;
db.query(query);
\`\`\`

**✅ Good - Parameterized query:**
\`\`\`javascript
const query = 'SELECT * FROM users WHERE email = $1';
db.query(query, [email]);
\`\`\`

**❌ Bad - Hardcoded secret:**
\`\`\`javascript
const leakedToken = '[redacted live key]';
\`\`\`

**✅ Good - Environment variable:**
\`\`\`javascript
const API_KEY = process.env.API_KEY;
if (!API_KEY) {
  throw new Error('API_KEY environment variable is required');
}
\`\`\`
```

### Example 3: Code Quality Review Checklist

```markdown
## Code Quality Review

### Readability
- [ ] Code is easy to understand
- [ ] Variable names are descriptive
- [ ] Function names explain what they do
- [ ] Complex logic has comments
- [ ] Magic numbers are replaced with constants

### Structure
- [ ] Functions are small and focused
- [ ] Code follows DRY principle (Don't Repeat Yourself)
- [ ] Proper separation of concerns
- [ ] Consistent code style
- [ ] No dead code or commented-out code

### Maintainability
- [ ] Code is modular and reusable
- [ ] Dependencies are minimal
- [ ] Changes are backwards compatible
- [ ] Breaking changes are documented
- [ ] Technical debt is noted

### Example Issues to Catch:

**❌ Bad - Unclear naming:**
\`\`\`javascript
function calc(a, b, c) {
  return a * b + c;
}
\`\`\`

**✅ Good - Descriptive naming:**
\`\`\`javascript
function calculateTotalPrice(quantity, unitPrice, tax) {
  return quantity * unitPrice + tax;
}
\`\`\`

**❌ Bad - Function doing too much:**
\`\`\`javascript
function processOrder(order) {
  // Validate order
  if (!order.items) throw new Error('No items');

  // Calculate total
  let total = 0;
  for (let item of order.items) {
    total += item.price * item.quantity;
  }

  // Apply discount
  if (order.coupon) {
    total *= 0.9;
  }

  // Process payment
  const payment = stripe.charge(total);

  // Send email
  sendEmail(order.email, 'Order confirmed');

  // Update inventory
  updateInventory(order.items);

  return { orderId: order.id, total };
}
\`\`\`

**✅ Good - Separated concerns:**
\`\`\`javascript
function processOrder(order) {
  validateOrder(order);
  const total = calculateOrderTotal(order);
  const payment = processPayment(total);
  sendOrderConfirmation(order.email);
  updateInventory(order.items);

  return { orderId: order.id, total };
}
\`\`\`
```

## Best Practices

### ✅ Do This

- **Review Small Changes** - Smaller PRs are easier to review thoroughly
- **Check Tests First** - Verify tests pass and cover new code
- **Run the Code** - Test it locally when possible
- **Ask Questions** - Don't assume, ask for clarification
- **Be Constructive** - Suggest improvements, don't just criticize
- **Focus on Important Issues** - Don't nitpick minor style issues
- **Use Automated Tools** - Linters, formatters, security scanners
- **Review Documentation** - Check if docs are updated
- **Consider Performance** - Think about scale and efficiency
- **Check for Regressions** - Ensure existing functionality still works

### ❌ Don't Do This

- **Don't Approve Without Reading** - Actually review the code
- **Don't Be Vague** - Provide specific feedback with examples
- **Don't Ignore Security** - Security issues are critical
- **Don't Skip Tests** - Untested code will cause problems
- **Don't Be Rude** - Be respectful and professional
- **Don't Rubber Stamp** - Every review should add value
- **Don't Review When Tired** - You'll miss important issues
- **Don't Forget Context** - Understand the bigger picture

## Complete Review Checklist

### Pre-Review
- [ ] Read the PR description and linked issues
- [ ] Understand what problem is being solved
- [ ] Check if tests pass in CI/CD
- [ ] Pull the branch and run it locally

### Functionality
- [ ] Code solves the stated problem
- [ ] Edge cases are handled
- [ ] Error handling is appropriate
- [ ] User input is validated
- [ ] No logical errors

### Security
- [ ] No SQL injection vulnerabilities
- [ ] No XSS vulnerabilities
- [ ] Authentication/authorization is correct
- [ ] Sensitive data is protected
- [ ] No hardcoded secrets

### Performance
- [ ] No unnecessary database queries
- [ ] No N+1 query problems
- [ ] Efficient algorithms used
- [ ] No memory leaks
- [ ] Caching used appropriately

### Code Quality
- [ ] Code is readable and clear
- [ ] Names are descriptive
- [ ] Functions are focused and small
- [ ] No code duplication
- [ ] Follows project conventions

### Tests
- [ ] New code has tests
- [ ] Tests cover edge cases
- [ ] Tests are meaningful
- [ ] All tests pass
- [ ] Test coverage is adequate

### Documentation
- [ ] Code comments explain why, not what
- [ ] API documentation is updated
- [ ] README is updated if needed
- [ ] Breaking changes are documented
- [ ] Migration guide provided if needed

### Git
- [ ] Commit messages are clear
- [ ] No merge conflicts
- [ ] Branch is up to date with main
- [ ] No unnecessary files committed
- [ ] .gitignore is properly configured

## Common Pitfalls

### Problem: Missing Edge Cases
**Symptoms:** Code works for happy path but fails on edge cases
**Solution:** Ask "What if...?" questions
- What if the input is null?
- What if the array is empty?
- What if the user is not authenticated?
- What if the network request fails?

### Problem: Security Vulnerabilities
**Symptoms:** Code exposes security risks
**Solution:** Use security checklist
- Run security scanners (npm audit, Snyk)
- Check OWASP Top 10
- Validate all inputs
- Use parameterized queries
- Never trust user input

### Problem: Poor Test Coverage
**Symptoms:** New code has no tests or inadequate tests
**Solution:** Require tests for all new code
- Unit tests for functions
- Integration tests for features
- Edge case tests
- Error case tests

### Problem: Unclear Code
**Symptoms:** Reviewer can't understand what code does
**Solution:** Request improvements
- Better variable names
- Explanatory comments
- Smaller functions
- Clear structure

## Review Comment Templates

### Requesting Changes
```markdown
**Issue:** [Describe the problem]

**Current code:**
\`\`\`javascript
// Show problematic code
\`\`\`

**Suggested fix:**
\`\`\`javascript
// Show improved code
\`\`\`

**Why:** [Explain why this is better]
```

### Asking Questions
```markdown
**Question:** [Your question]

**Context:** [Why you're asking]

**Suggestion:** [If you have one]
```

### Praising Good Code
```markdown
**Nice!** [What you liked]

This is great because [explain why]
```

## Related Skills

- `@requesting-code-review` - Prepare code for review
- `@receiving-code-review` - Handle review feedback
- `@systematic-debugging` - Debug issues found in review
- `@test-driven-development` - Ensure code has tests

## Additional Resources

- [Google Code Review Guidelines](https://google.github.io/eng-practices/review/)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Code Review Best Practices](https://github.com/thoughtbot/guides/tree/main/code-review)
- [How to Review Code](https://www.kevinlondon.com/2015/05/05/code-review-best-practices.html)

---

**Pro Tip:** Use a checklist template for every review to ensure consistency and thoroughness. Customize it for your team's specific needs!

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-review-excellence
description: "Transform code reviews from gatekeeping to knowledge sharing through constructive feedback, systematic analysis, and collaborative improvement."
risk: safe
source: community
date_added: "2026-02-27"
---

# Code Review Excellence

Transform code reviews from gatekeeping to knowledge sharing through constructive feedback, systematic analysis, and collaborative improvement.

## Use this skill when

- Reviewing pull requests and code changes
- Establishing code review standards
- Mentoring developers through review feedback
- Auditing for correctness, security, or performance

## Do not use this skill when

- There are no code changes to review
- The task is a design-only discussion without code
- You need to implement fixes instead of reviewing

## Instructions

- Read context, requirements, and test signals first.
- Review for correctness, security, performance, and maintainability.
- Provide actionable feedback with severity and rationale.
- Ask clarifying questions when intent is unclear.
- If detailed checklists are required, open `resources/implementation-playbook.md`.

## Output Format

- High-level summary of findings
- Issues grouped by severity (blocking, important, minor)
- Suggestions and questions
- Test and coverage notes

## Resources

- `resources/implementation-playbook.md` for detailed review patterns and templates.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-reviewer
description: "Elite code review expert specializing in modern AI-powered code"
risk: critical
source: community
date_added: "2026-02-27"
---

## Use this skill when

- Working on code reviewer tasks or workflows
- Needing guidance, best practices, or checklists for code reviewer

## Do not use this skill when

- The task is unrelated to code reviewer
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are an elite code review expert specializing in modern code analysis techniques, AI-powered review tools, and production-grade quality assurance.

## Expert Purpose
Master code reviewer focused on ensuring code quality, security, performance, and maintainability using cutting-edge analysis tools and techniques. Combines deep technical expertise with modern AI-assisted review processes, static analysis tools, and production reliability practices to deliver comprehensive code assessments that prevent bugs, security vulnerabilities, and production incidents.

## Capabilities

### AI-Powered Code Analysis
- Integration with modern AI review tools (Trag, Bito, Codiga, GitHub Copilot)
- Natural language pattern definition for custom review rules
- Context-aware code analysis using LLMs and machine learning
- Automated pull request analysis and comment generation
- Real-time feedback integration with CLI tools and IDEs
- Custom rule-based reviews with team-specific patterns
- Multi-language AI code analysis and suggestion generation

### Modern Static Analysis Tools
- SonarQube, CodeQL, and Semgrep for comprehensive code scanning
- Security-focused analysis with Snyk, Bandit, and OWASP tools
- Performance analysis with profilers and complexity analyzers
- Dependency vulnerability scanning with npm audit, pip-audit
- License compliance checking and open source risk assessment
- Code quality metrics with cyclomatic complexity analysis
- Technical debt assessment and code smell detection

### Security Code Review
- OWASP Top 10 vulnerability detection and prevention
- Input validation and sanitization review
- Authentication and authorization implementation analysis
- Cryptographic implementation and key management review
- SQL injection, XSS, and CSRF prevention verification
- Secrets and credential management assessment
- API security patterns and rate limiting implementation
- Container and infrastructure security code review

### Performance & Scalability Analysis
- Database query optimization and N+1 problem detection
- Memory leak and resource management analysis
- Caching strategy implementation review
- Asynchronous programming pattern verification
- Load testing integration and performance benchmark review
- Connection pooling and resource limit configuration
- Microservices performance patterns and anti-patterns
- Cloud-native performance optimization techniques

### Configuration & Infrastructure Review
- Production configuration security and reliability analysis
- Database connection pool and timeout configuration review
- Container orchestration and Kubernetes manifest analysis
- Infrastructure as Code (Terraform, CloudFormation) review
- CI/CD pipeline security and reliability assessment
- Environment-specific configuration validation
- Secrets management and credential security review
- Monitoring and observability configuration verification

### Modern Development Practices
- Test-Driven Development (TDD) and test coverage analysis
- Behavior-Driven Development (BDD) scenario review
- Contract testing and API compatibility verification
- Feature flag implementation and rollback strategy review
- Blue-green and canary deployment pattern analysis
- Observability and monitoring code integration review
- Error handling and resilience pattern implementation
- Documentation and API specification completeness

### Code Quality & Maintainability
- Clean Code principles and SOLID pattern adherence
- Design pattern implementation and architectural consistency
- Code duplication detection and refactoring opportunities
- Naming convention and code style compliance
- Technical debt identification and remediation planning
- Legacy code modernization and refactoring strategies
- Code complexity reduction and simplification techniques
- Maintainability metrics and long-term sustainability assessment

### Team Collaboration & Process
- Pull request workflow optimization and best practices
- Code review checklist creation and enforcement
- Team coding standards definition and compliance
- Mentor-style feedback and knowledge sharing facilitation
- Code review automation and tool integration
- Review metrics tracking and team performance analysis
- Documentation standards and knowledge base maintenance
- Onboarding support and code review training

### Language-Specific Expertise
- JavaScript/TypeScript modern patterns and React/Vue best practices
- Python code quality with PEP 8 compliance and performance optimization
- Java enterprise patterns and Spring framework best practices
- Go concurrent programming and performance optimization
- Rust memory safety and performance critical code review
- C# .NET Core patterns and Entity Framework optimization
- PHP modern frameworks and security best practices
- Database query optimization across SQL and NoSQL platforms

### Integration & Automation
- GitHub Actions, GitLab CI/CD, and Jenkins pipeline integration
- Slack, Teams, and communication tool integration
- IDE integration with VS Code, IntelliJ, and development environments
- Custom webhook and API integration for workflow automation
- Code quality gates and deployment pipeline integration
- Automated code formatting and linting tool configuration
- Review comment template and checklist automation
- Metrics dashboard and reporting tool integration

## Behavioral Traits
- Maintains constructive and educational tone in all feedback
- Focuses on teaching and knowledge transfer, not just finding issues
- Balances thorough analysis with practical development velocity
- Prioritizes security and production reliability above all else
- Emphasizes testability and maintainability in every review
- Encourages best practices while being pragmatic about deadlines
- Provides specific, actionable feedback with code examples
- Considers long-term technical debt implications of all changes
- Stays current with emerging security threats and mitigation strategies
- Champions automation and tooling to improve review efficiency

## Knowledge Base
- Modern code review tools and AI-assisted analysis platforms
- OWASP security guidelines and vulnerability assessment techniques
- Performance optimization patterns for high-scale applications
- Cloud-native development and containerization best practices
- DevSecOps integration and shift-left security methodologies
- Static analysis tool configuration and custom rule development
- Production incident analysis and preventive code review techniques
- Modern testing frameworks and quality assurance practices
- Software architecture patterns and design principles
- Regulatory compliance requirements (SOC2, PCI DSS, GDPR)

## Response Approach
1. **Analyze code context** and identify review scope and priorities
2. **Apply automated tools** for initial analysis and vulnerability detection
3. **Conduct manual review** for logic, architecture, and business requirements
4. **Assess security implications** with focus on production vulnerabilities
5. **Evaluate performance impact** and scalability considerations
6. **Review configuration changes** with special attention to production risks
7. **Provide structured feedback** organized by severity and priority
8. **Suggest improvements** with specific code examples and alternatives
9. **Document decisions** and rationale for complex review points
10. **Follow up** on implementation and provide continuous guidance

## Example Interactions
- "Review this microservice API for security vulnerabilities and performance issues"
- "Analyze this database migration for potential production impact"
- "Assess this React component for accessibility and performance best practices"
- "Review this Kubernetes deployment configuration for security and reliability"
- "Evaluate this authentication implementation for OAuth2 compliance"
- "Analyze this caching strategy for race conditions and data consistency"
- "Review this CI/CD pipeline for security and deployment best practices"
- "Assess this error handling implementation for observability and debugging"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: code-showcase-core-components
description: Core component library and design system patterns. Use when building UI, using design tokens, or working with the component library.
risk: none
source: https://github.com/ChrisWiles/claude-code-showcase/tree/main/.claude/skills/core-components
source_repo: ChrisWiles/claude-code-showcase
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/ChrisWiles/claude-code-showcase/blob/main/LICENSE
---

# Core Components
## When to Use

Use this skill when you need core component library and design system patterns. Use when building UI, using design tokens, or working with the component library.

## Design System Overview

Use components from your core library instead of raw platform components. This ensures consistent styling and behavior.

## Design Tokens

**NEVER hard-code values. Always use design tokens.**

### Spacing Tokens

```tsx
// CORRECT - Use tokens
<Box padding="$4" marginBottom="$2" />

// WRONG - Hard-coded values
<Box padding={16} marginBottom={8} />
```

| Token | Value |
|-------|-------|
| `$1` | 4px |
| `$2` | 8px |
| `$3` | 12px |
| `$4` | 16px |
| `$6` | 24px |
| `$8` | 32px |

### Color Tokens

```tsx
// CORRECT - Semantic tokens
<Text color="$textPrimary" />
<Box backgroundColor="$backgroundSecondary" />

// WRONG - Hard-coded colors
<Text color="#333333" />
<Box backgroundColor="rgb(245, 245, 245)" />
```

| Semantic Token | Use For |
|----------------|---------|
| `$textPrimary` | Main text |
| `$textSecondary` | Supporting text |
| `$textTertiary` | Disabled/hint text |
| `$primary500` | Brand/accent color |
| `$statusError` | Error states |
| `$statusSuccess` | Success states |

### Typography Tokens

```tsx
<Text fontSize="$lg" fontWeight="$semibold" />
```

| Token | Size |
|-------|------|
| `$xs` | 12px |
| `$sm` | 14px |
| `$md` | 16px |
| `$lg` | 18px |
| `$xl` | 20px |
| `$2xl` | 24px |

## Core Components

### Box

Base layout component with token support:

```tsx
<Box
  padding="$4"
  backgroundColor="$backgroundPrimary"
  borderRadius="$lg"
>
  {children}
</Box>
```

### HStack / VStack

Horizontal and vertical flex layouts:

```tsx
<HStack gap="$3" alignItems="center">
  <Icon name="user" />
  <Text>Username</Text>
</HStack>

<VStack gap="$4" padding="$4">
  <Heading>Title</Heading>
  <Text>Content</Text>
</VStack>
```

### Text

Typography with token support:

```tsx
<Text
  fontSize="$lg"
  fontWeight="$semibold"
  color="$textPrimary"
>
  Hello World
</Text>
```

### Button

Interactive button with variants:

```tsx
<Button
  onPress={handlePress}
  variant="solid"
  size="md"
  isLoading={loading}
  isDisabled={disabled}
>
  Click Me
</Button>
```

| Variant | Use For |
|---------|---------|
| `solid` | Primary actions |
| `outline` | Secondary actions |
| `ghost` | Tertiary/subtle actions |
| `link` | Inline actions |

### Input

Form input with validation:

```tsx
<Input
  value={value}
  onChangeText={setValue}
  placeholder="Enter text"
  error={touched ? errors.field : undefined}
  label="Field Name"
/>
```

### Card

Content container:

```tsx
<Card padding="$4" gap="$3">
  <CardHeader>
    <Heading size="sm">Card Title</Heading>
  </CardHeader>
  <CardBody>
    <Text>Card content</Text>
  </CardBody>
</Card>
```

## Layout Patterns

### Screen Layout

```tsx
const MyScreen = () => (
  <Screen>
    <ScreenHeader title="Page Title" />
    <ScreenContent padding="$4">
      {/* Content */}
    </ScreenContent>
  </Screen>
);
```

### Form Layout

```tsx
<VStack gap="$4" padding="$4">
  <Input label="Name" {...nameProps} />
  <Input label="Email" {...emailProps} />
  <Button isLoading={loading}>Submit</Button>
</VStack>
```

### List Item Layout

```tsx
<HStack
  padding="$4"
  gap="$3"
  alignItems="center"
  borderBottomWidth={1}
  borderColor="$borderLight"
>
  <Avatar source={{ uri: imageUrl }} size="md" />
  <VStack flex={1}>
    <Text fontWeight="$semibold">{title}</Text>
    <Text color="$textSecondary" fontSize="$sm">{subtitle}</Text>
  </VStack>
  <Icon name="chevron-right" color="$textTertiary" />
</HStack>
```

## Anti-Patterns

```tsx
// WRONG - Hard-coded values
<View style={{ padding: 16, backgroundColor: '#fff' }}>

// CORRECT - Design tokens
<Box padding="$4" backgroundColor="$backgroundPrimary">

// WRONG - Raw platform components
import { View, Text } from 'react-native';

// CORRECT - Core components
import { Box, Text } from 'components/core';

// WRONG - Inline styles
<Text style={{ fontSize: 18, fontWeight: '600' }}>

// CORRECT - Token props
<Text fontSize="$lg" fontWeight="$semibold">
```

## Component Props Pattern

When creating components, use token-based props:

```tsx
interface CardProps {
  padding?: '$2' | '$4' | '$6';
  variant?: 'elevated' | 'outlined' | 'filled';
  children: React.ReactNode;
}

const Card = ({ padding = '$4', variant = 'elevated', children }: CardProps) => (
  <Box
    padding={padding}
    backgroundColor="$backgroundPrimary"
    borderRadius="$lg"
    {...variantStyles[variant]}
  >
    {children}
  </Box>
);
```

## Integration with Other Skills

- **react-ui-patterns**: Use core components for UI states
- **testing-patterns**: Mock core components in tests
- **storybook**: Document component variants

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: code-showcase-react-ui-patterns
description: Modern React UI patterns for loading states, error handling, and data fetching. Use when building UI components, handling async data, or managing UI states.
risk: critical
source: https://github.com/ChrisWiles/claude-code-showcase/tree/main/.claude/skills/react-ui-patterns
source_repo: ChrisWiles/claude-code-showcase
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/ChrisWiles/claude-code-showcase/blob/main/LICENSE
---

# React UI Patterns
## When to Use

Use this skill when you need modern React UI patterns for loading states, error handling, and data fetching. Use when building UI components, handling async data, or managing UI states.

## Core Principles

1. **Never show stale UI** - Loading spinners only when actually loading
2. **Always surface errors** - Users must know when something fails
3. **Optimistic updates** - Make the UI feel instant
4. **Progressive disclosure** - Show content as it becomes available
5. **Graceful degradation** - Partial data is better than no data

## Loading State Patterns

### The Golden Rule

**Show loading indicator ONLY when there's no data to display.**

```typescript
// CORRECT - Only show loading when no data exists
const { data, loading, error } = useGetItemsQuery();

if (error) return <ErrorState error={error} onRetry={refetch} />;
if (loading && !data) return <LoadingState />;
if (!data?.items.length) return <EmptyState />;

return <ItemList items={data.items} />;
```

```typescript
// WRONG - Shows spinner even when we have cached data
if (loading) return <LoadingState />; // Flashes on refetch!
```

### Loading State Decision Tree

```
Is there an error?
  → Yes: Show error state with retry option
  → No: Continue

Is it loading AND we have no data?
  → Yes: Show loading indicator (spinner/skeleton)
  → No: Continue

Do we have data?
  → Yes, with items: Show the data
  → Yes, but empty: Show empty state
  → No: Show loading (fallback)
```

### Skeleton vs Spinner

| Use Skeleton When | Use Spinner When |
|-------------------|------------------|
| Known content shape | Unknown content shape |
| List/card layouts | Modal actions |
| Initial page load | Button submissions |
| Content placeholders | Inline operations |

## Error Handling Patterns

### The Error Handling Hierarchy

```
1. Inline error (field-level) → Form validation errors
2. Toast notification → Recoverable errors, user can retry
3. Error banner → Page-level errors, data still partially usable
4. Full error screen → Unrecoverable, needs user action
```

### Always Show Errors

**CRITICAL: Never swallow errors silently.**

```typescript
// CORRECT - Error always surfaced to user
const [createItem, { loading }] = useCreateItemMutation({
  onCompleted: () => {
    toast.success({ title: 'Item created' });
  },
  onError: (error) => {
    console.error('createItem failed:', error);
    toast.error({ title: 'Failed to create item' });
  },
});

// WRONG - Error silently caught, user has no idea
const [createItem] = useCreateItemMutation({
  onError: (error) => {
    console.error(error); // User sees nothing!
  },
});
```

### Error State Component Pattern

```typescript
interface ErrorStateProps {
  error: Error;
  onRetry?: () => void;
  title?: string;
}

const ErrorState = ({ error, onRetry, title }: ErrorStateProps) => (
  <div className="error-state">
    <Icon name="exclamation-circle" />
    <h3>{title ?? 'Something went wrong'}</h3>
    <p>{error.message}</p>
    {onRetry && (
      <Button onClick={onRetry}>Try Again</Button>
    )}
  </div>
);
```

## Button State Patterns

### Button Loading State

```tsx
<Button
  onClick={handleSubmit}
  isLoading={isSubmitting}
  disabled={!isValid || isSubmitting}
>
  Submit
</Button>
```

### Disable During Operations

**CRITICAL: Always disable triggers during async operations.**

```tsx
// CORRECT - Button disabled while loading
<Button
  disabled={isSubmitting}
  isLoading={isSubmitting}
  onClick={handleSubmit}
>
  Submit
</Button>

// WRONG - User can tap multiple times
<Button onClick={handleSubmit}>
  {isSubmitting ? 'Submitting...' : 'Submit'}
</Button>
```

## Empty States

### Empty State Requirements

Every list/collection MUST have an empty state:

```tsx
// WRONG - No empty state
return <FlatList data={items} />;

// CORRECT - Explicit empty state
return (
  <FlatList
    data={items}
    ListEmptyComponent={<EmptyState />}
  />
);
```

### Contextual Empty States

```tsx
// Search with no results
<EmptyState
  icon="search"
  title="No results found"
  description="Try different search terms"
/>

// List with no items yet
<EmptyState
  icon="plus-circle"
  title="No items yet"
  description="Create your first item"
  action={{ label: 'Create Item', onClick: handleCreate }}
/>
```

## Form Submission Pattern

```tsx
const MyForm = () => {
  const [submit, { loading }] = useSubmitMutation({
    onCompleted: handleSuccess,
    onError: handleError,
  });

  const handleSubmit = async () => {
    if (!isValid) {
      toast.error({ title: 'Please fix errors' });
      return;
    }
    await submit({ variables: { input: values } });
  };

  return (
    <form>
      <Input
        value={values.name}
        onChange={handleChange('name')}
        error={touched.name ? errors.name : undefined}
      />
      <Button
        type="submit"
        onClick={handleSubmit}
        disabled={!isValid || loading}
        isLoading={loading}
      >
        Submit
      </Button>
    </form>
  );
};
```

## Anti-Patterns

### Loading States

```typescript
// WRONG - Spinner when data exists (causes flash)
if (loading) return <Spinner />;

// CORRECT - Only show loading without data
if (loading && !data) return <Spinner />;
```

### Error Handling

```typescript
// WRONG - Error swallowed
try {
  await mutation();
} catch (e) {
  console.log(e); // User has no idea!
}

// CORRECT - Error surfaced
onError: (error) => {
  console.error('operation failed:', error);
  toast.error({ title: 'Operation failed' });
}
```

### Button States

```typescript
// WRONG - Button not disabled during submission
<Button onClick={submit}>Submit</Button>

// CORRECT - Disabled and shows loading
<Button onClick={submit} disabled={loading} isLoading={loading}>
  Submit
</Button>
```

## Checklist

Before completing any UI component:

**UI States:**
- [ ] Error state handled and shown to user
- [ ] Loading state shown only when no data exists
- [ ] Empty state provided for collections
- [ ] Buttons disabled during async operations
- [ ] Buttons show loading indicator when appropriate

**Data & Mutations:**
- [ ] Mutations have onError handler
- [ ] All user actions have feedback (toast/visual)

## Integration with Other Skills

- **graphql-schema**: Use mutation patterns with proper error handling
- **testing-patterns**: Test all UI states (loading, error, empty, success)
- **formik-patterns**: Apply form submission patterns

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.