Skip to main content
ClaudeWave
Skill171 estrellas del repoactualizado 27d ago

code-review

Perform thorough code reviews on files or pull requests, checking for bugs, security vulnerabilities, performance issues, and style violations. Use when the user requests code review or provides relevant inputs for this workflow.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills /tmp/code-review && cp -r /tmp/code-review/code-and-development/code-review ~/.claude/skills/code-review
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Code Review

This skill enables an AI agent to conduct a structured, comprehensive code review on a source file, a set of changes, or a pull request. The agent examines the code across multiple quality dimensions — correctness, security, performance, readability, and maintainability — and produces a detailed review report with actionable feedback tied to specific lines of code.

## Workflow

1. **Parse the input and establish context.** Determine whether the input is a single file, a directory, or a pull request diff. If it is a pull request, fetch the diff and identify the base branch so that only the changed lines are reviewed. Read any related configuration files (linter configs, style guides, type definitions) to calibrate the review against the project's standards.

2. **Understand the intent of the change.** Read commit messages, PR descriptions, and surrounding code to understand what the author intended. This prevents false positives — a reviewer must know the goal before judging whether the code achieves it. Summarize the change in one sentence before proceeding.

3. **Check for correctness and bugs.** Walk through every changed function and trace the data flow. Look for null or undefined dereferences, off-by-one errors, incorrect boolean logic, unhandled error paths, race conditions in concurrent code, and resource leaks (open files, database connections, unreleased locks). Verify that edge cases — empty inputs, maximum values, unexpected types — are handled.

4. **Evaluate security.** Scan for common vulnerability patterns: unsanitized user input (SQL injection, XSS), hardcoded secrets or credentials, insecure cryptographic usage, overly permissive file or network access, and missing authentication or authorization checks. Flag any dependency additions and check for known CVEs.

5. **Assess performance and scalability.** Identify algorithmic complexity issues (nested loops over large collections, repeated database queries inside loops, unbounded memory growth). Check for unnecessary allocations, missing caching opportunities, and blocking calls in async contexts. Consider the expected data volume and whether the code will scale.

6. **Review readability and maintainability.** Evaluate naming clarity, function length, code duplication (DRY violations), and adherence to the project's style guide. Check that public functions have docstrings or type annotations. Verify that magic numbers are replaced with named constants and that complex logic has explanatory comments.

## Review Checklist

The agent evaluates every change against these categories:

| Category        | What to look for                                                        |
|-----------------|-------------------------------------------------------------------------|
| Bugs            | Null derefs, off-by-one, logic errors, unhandled exceptions             |
| Security        | Injection, XSS, hardcoded secrets, missing auth, insecure dependencies  |
| Performance     | O(n²) loops, N+1 queries, unnecessary allocations, blocking I/O        |
| Readability     | Unclear names, long functions, missing docs, inconsistent formatting    |
| DRY             | Copy-pasted blocks, duplicated logic that should be extracted           |
| Error handling  | Swallowed exceptions, missing retries, unclear error messages           |
| Testing         | Missing tests for new logic, broken existing tests, untested edge cases |

## Usage

Provide one or more of the following inputs:

- **File path** — a single source file to review in its entirety.
- **Directory path** — the agent reviews all source files in the directory.
- **Pull request URL** — e.g., `https://github.com/user/repo/pull/42`. The agent fetches the diff and reviews only the changed lines in context.
- **Diff or patch text** — raw unified diff pasted directly.
- **Focus area** (optional) — e.g., "focus on security" or "check performance only" to narrow the review scope.

## Examples

### Example 1 — Reviewing a Python function

Given this file `src/auth.py`:

```python
import hashlib

def authenticate(username, password, db):
    query = f"SELECT password_hash FROM users WHERE username = '{username}'"
    row = db.execute(query).fetchone()
    if row is None:
        return False
    stored_hash = row[0]
    input_hash = hashlib.md5(password.encode()).hexdigest()
    return input_hash == stored_hash
```

The agent produces the following review:

```
## Review: src/auth.py — authenticate()

### Critical — SQL Injection (line 4)
The query uses f-string interpolation with `username` directly in the SQL
string. An attacker can pass `' OR '1'='1` as the username to bypass
authentication entirely.

**Fix:** Use parameterized queries.
- row = db.execute(query).fetchone()
+ row = db.execute(
+     "SELECT password_hash FROM users WHERE username = ?", (username,)
+ ).fetchone()

### Critical — Weak Hashing Algorithm (line 9)
MD5 is cryptographically broken and unsuitable for password hashing. It is
vulnerable to rainbow table attacks and can be brute-forced in seconds on
modern hardware.

**Fix:** Use bcrypt or argon2 with a per-user salt.
- input_hash = hashlib.md5(password.encode()).hexdigest()
+ import bcrypt
+ return bcrypt.checkpw(password.encode(), stored_hash.encode())

### Warning — Timing Attack (line 10)
Direct string comparison of hashes with `==` leaks information through
timing differences. Use a constant-time comparison function.

**Fix:**
- return input_hash == stored_hash
+ import hmac
+ return hmac.compare_digest(input_hash, stored_hash)

### Info — Missing Type Annotations
Adding type hints improves readability and enables static analysis:
  def authenticate(username: str, password: str, db: Connection) -> bool:

**Summary:** 2 critical, 1 warning, 1 info. This function must not be
deployed until the SQL injection and hashing issues are resolved.
```

### Example 2 — Reviewing a pull request diff

Given a PR diff for `src/api/orders.js`:

```diff
@@ -12,
agent-evaluationSkill

Design reproducible evaluations for AI agents with representative task sets, explicit rubrics, appropriate graders, baselines, regression gates, and failure analysis. Use when defining agent quality, comparing prompts or models, validating a release, measuring tool-use reliability, investigating regressions, or deciding whether an agent is ready for production.

agent-observabilitySkill

Design privacy-aware observability for AI agents using traces, spans, structured events, metrics, cost attribution, dashboards, alerts, and investigation workflows. Use when instrumenting an agent, debugging intermittent tool or model failures, defining service-level objectives, analyzing latency or spend, auditing agent decisions, or preparing production monitoring.

human-in-the-loopSkill

Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows. Use when deciding which agent actions require review, adding approve/reject or dual-control flows, preventing unauthorized autonomous effects, creating decision records, reducing rubber-stamping, or recovering safely from rejected, expired, or failed actions.

mcp-server-buildingSkill

Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests. Use when creating a new MCP server, exposing an API or data source through MCP, reviewing an MCP server design, adding or revising MCP tools, or preparing an MCP server for production.

multi-agent-orchestrationSkill

Design and operate bounded multi-agent workflows with task decomposition, dependency graphs, ownership, handoff contracts, shared-state controls, approvals, recovery, and synthesis. Use when a task contains genuinely independent workstreams, specialized roles, parallel research or implementation, reviewer-worker loops, or coordination problems that one agent should not execute sequentially.

tool-schema-designSkill

Design and validate model-facing tool definitions with clear names, action-oriented descriptions, bounded JSON Schema parameters, explicit side effects, safe defaults, idempotency, errors, and realistic tests. Use when creating function-calling tools, MCP tools, agent actions, structured tool inputs, or when a model selects the wrong tool, invents arguments, or causes unsafe side effects.

agent-red-teamingSkill

Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings. Use when defining red-team rules of engagement, assessing prompt injection or excessive agency, testing tool and identity boundaries, evaluating memory or cross-agent attacks, scoring a campaign, or verifying remediation in an approved environment.

prompt-injection-defenseSkill

Threat-model and harden AI agents, RAG systems, assistants, and tool-using workflows against direct, indirect, stored, cross-agent, and multimodal prompt injection. Use when reviewing an agent architecture, isolating untrusted content, constraining tools and egress, protecting secrets, adding injection-focused tests, investigating a suspected injection incident, or documenting residual prompt-injection risk.