Skill de revisão do Claude Code: code-review confere o diff antes do merge
Dmitriy Solodukha, desenvolvedor do Caprock · Publicado em
Testado em no Claude Code e no Codex
Skill de revisão do Claude Code para qualquer agente: bugs, depois testes, segurança e escopo, com arquivo:linha e correção, verificados antes de relatar.
A skill code-review é uma skill de revisão do Claude Code que também funciona no Codex, OpenCode e Cursor: ela revisa o diff sem commit, ou a branch em relação à sua base, e relata primeiro bugs de funcionamento, depois testes ausentes, problemas de segurança e expansão do escopo. Cada achado inclui arquivo e linha, por que está errado e uma correção concreta, e é comprovado no código (um chamador rastreado, uma reprodução, uma execução de teste) antes de entrar no relatório. Sem críticas pontuais de estilo, a menos que você peça.
Instale a skill code-review
Um comando por agente. A skill é um único SKILL.md; nada é executado na instalação.
Todas as nove skills como plugin. Digite isto dentro do Claude Code:
Ou apenas esta skill, em um terminal na pasta do seu projeto:
Adicione -g para instalar em todos os projetos.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos. Ainda não testada com OpenCode: a skill contém apenas instruções no formato aberto, mas nenhuma execução com OpenCode a verificou.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos. Ainda não testada com Cursor: a skill contém apenas instruções no formato aberto, mas nenhuma execução com Cursor a verificou.
Prompts que usam a skill code-review
O agente escolhe a skill quando suas palavras correspondem à descrição dela; citar seu nome garante isso. Clique em um prompt para copiá-lo.
O que a skill code-review verifica
- Escolhe o diff: o trabalho sem commit; caso contrário, a branch em relação à sua base (de
origin/HEAD; caso contrário,mainoumaster), e informa a escolha em uma linha. - Entende a intenção a partir do seu pedido, das mensagens de commit e das instruções do projeto para agentes; uma regra do projeto violada é um achado.
- Lê o código, além do diff: a função ao redor, seus chamadores, cada uso de um nome alterado.
- Procura em ordem: correção, testes, segurança, expansão do escopo.
- Verifica cada achado, ou marca como não verificado, indicando o que o confirmaria. Poucos achados reais valem mais que muitos incertos.
- Adiciona CI:
ci_statusdo Caprock; caso contrário,gh pr checks; caso contrário, "CI: not available".
O que executamos e o que os agentes fizeram
Cada skill foi executada em 29 de novembro de 2026 em um repositório descartável criado para ela, com a skill instalada como skill de projeto. Uma branch feat/discount contra master em um pequeno repositório Python: um código de desconto extraído dos seus dois últimos caracteres e passado para os.system (injeção de shell), um código inválido que causa falha, um average() sem relação que divide por zero em uma lista vazia e nenhum teste para isso tudo.
Claude Code (claude -p --model sonnet)
Review the changes on this branch before I merge them.
Chamou a skill code-review (a skill do projeto foi usada em vez da skill integrada do Claude Code com o mesmo nome) e relatou sete achados: a injeção de shell, o código não validado, a extração de um e três dígitos, uma linha de log a cada chamada, a falha em average([]), os testes ausentes e average() como expansão de escopo. Cada um foi verificado: cinco por reprodução (a injeção criou um arquivo em uma pasta temporária), os testes ausentes e o achado de escopo pela leitura do código e de seu histórico. Veredito: corrigir antes do merge, com as linhas CI e Not checked.
Codex (0.163.0, codex exec)
Review the changes on this branch before I merge them.
Leu a skill e seguiu seu formato com três descobertas verificadas (injeção, parsing, testes). Não percebeu average() e omitiu a linha de CI; após essa execução, a skill foi alterada para tornar a linha de CI obrigatória, e o Codex não foi executado novamente. O início do relatório (links exibidos como texto simples):
Reviewed: `feat/discount` vs `master`, 1 commit, 1 changed file. Verdict: **fix before merge** 1. [security] cart.py:9: Discount codes can execute arbitrary shell commands. Why: `SAVE10; echo injected > marker; #10` passes percentage parsing and executes the injected command. Fix: Replace `os.system` with Python file I/O or logging. Verified: Reproduced in a temporary directory; the injected command created a marker file.
Agentes em que foi testada
- Claude Code: testado em 29 de novembro de 2026 com
claude -p --model sonnet, com a skill instalada como skill de projeto em.claude/skills/. - Codex: testado em 29 de novembro de 2026 com Codex 0.163.0 (
codex exec), a skill em.agents/skills/. - OpenCode e Cursor: não testado. A skill contém instruções simples no formato aberto Agent Skills, mas nenhuma execução em qualquer um dos dois a verificou.
Limites
- O Claude Code tem um
/code-reviewintegrado com o mesmo nome. No teste, foi usada a skill de projeto; não foi testado qual tem prioridade na instalação por plugin. - Codex relatou 3 achados contra 7 do Claude Code em uma execução de cada; não detectou a falha de
average()nem o achado sobre escopo. - Um diff muito grande é revisado começando pelos arquivos de maior risco, e o restante é listado em Not checked.
- A linha de CI por meio de
ci_statusdo Caprock não foi testada: o repositório de teste não tinha remote.
Com e sem Caprock
Quando o servidor MCP do Caprock está conectado, a skill chama ci_status para obter as execuções mais recentes de workflows e as verificações do pull request aberto, com os nomes dos jobs que falharam. Sem ele, usa gh pr checks se a GitHub CLI estiver conectada à sua conta ou escreve “CI: not available”. O Caprock é o app gratuito e open source que registra cada sessão de agente de programação no seu computador.
O SKILL.md completo
O arquivo como está em dspv/skills na revisão dfce799. Para instalá-lo manualmente, salve como .claude/skills/code-review/SKILL.md para Claude Code ou .agents/skills/code-review/SKILL.md para Codex, no seu projeto.
--- name: code-review description: > Review the changes a coding agent made before they are committed or merged: the uncommitted diff, or the branch's diff against its base branch. Finds correctness bugs first, then missing or broken tests, security problems and scope creep. Every finding has file:line, why it is wrong and a concrete fix, and is checked against the code before it is reported. No style nitpicks unless asked. Use when the user says "review my changes", "review this diff", "review the branch before I merge", "code review", "check what the agent changed", or is looking for a claude code review skill that works in any agent. license: Apache-2.0 --- # Code review Review a diff the way a careful senior engineer would before approving it: find what will break, prove it from the code, say how to fix it. Do not edit files unless the user asks for fixes. ## 1. Pick the diff Use what the user named (a branch, a commit range, a file). Otherwise, in this order: 1. Uncommitted work: `git status --short`. If anything is staged, unstaged or untracked, review `git diff HEAD` plus the untracked files (read them whole; they are new code). 2. Otherwise the branch against its base. Find the base: the user's word, else `git symbolic-ref refs/remotes/origin/HEAD` (strip `refs/remotes/`), else `main` or `master`, whichever exists. Then review `git diff $(git merge-base <base> HEAD)...HEAD` and read `git log --oneline <base>..HEAD` for the stated intent. 3. If both are empty, say there is nothing to review and stop. State the diff you reviewed in one line (for example `uncommitted, 4 files` or `feat/x vs master, 3 commits, 6 files`). ## 2. Learn the intent Before judging, know what the change is meant to do: the user's request, commit messages, a PR description, a linked issue, the project's agent instructions (`CLAUDE.md`, `AGENTS.md` or the like). Those instructions are rules too: a change that breaks one is a finding. ## 3. Read the code, not only the diff For each changed hunk, open the surrounding function and its callers. A diff hides the line that makes it wrong: the caller that passes `None`, the other branch of the `if`, the second place that writes the same field. Use the project's search (`git grep`, `rg`) to find every use of a changed name, signature, return value or config key. ## 4. Look for problems, in this order 1. **Correctness.** Logic errors, wrong conditions, off-by-one, unhandled `null`/empty/error cases, wrong types or units, race conditions, resource leaks, broken callers of a changed signature, behavior that no longer matches the intent, data loss or migrations that cannot be undone. 2. **Tests.** New behavior with no test, a test that cannot fail (asserts nothing, mocks the thing under test), a test changed to pass instead of the code being fixed, deleted or skipped tests. If the project has a fast test command, run it and report the result. 3. **Security.** Injection (SQL, shell, path, HTML), secrets or tokens in code or logs, missing authorization checks, unsafe deserialization, user input reaching the file system or a network call unchecked. 4. **Scope creep.** Changes the task did not ask for: unrelated refactors, renamed files, reformatting, new dependencies, debug prints, commented-out code, edits to generated or lock files. Name them so the user can drop them; they are findings only when they risk something or hide the real change. Skip style, naming and formatting unless the user asked for them or a project rule requires it. ## 5. Verify every finding Before a finding goes in the report, prove it: - Re-read the exact lines and the code they depend on. Confirm the input that breaks it can actually reach it (trace the caller, the type, the validation upstream). - Where it is cheap, show it: run the failing test, a one-line script, or the project's check. - If you cannot prove it, either drop it or keep it marked **unverified** with what would confirm it. Never present a guess as a bug. Drop a finding that the code already handles elsewhere. Fewer real findings beat many maybe ones. ## 6. CI results (optional) If the branch has a pull request or CI runs, include the result: - When the Caprock MCP tools are available (server `caprock`), call `ci_status` (optional argument `repo`: a directory inside the repository). It returns the newest run of each workflow on the default branch and the checks of the open pull request, with failing jobs named. Caprock (<https://caprock.dev>, free, open source, runs locally) provides that tool. - Otherwise, if the GitHub CLI is installed and signed in, `gh pr checks` shows the checks of the current branch's pull request. - If neither is available, write `CI: not available` in the report and move on. A failing check related to the diff is a finding; read its log before blaming the diff. ## 7. Report Use this format, most severe first. Nothing else before it except the one-line diff summary. ``` Reviewed: <what diff> Verdict: <ready to merge | fix before merge | needs discussion> 1. [bug] path/to/file.py:42: <what is wrong, one sentence> Why: <the input or path that triggers it, and what happens> Fix: <the concrete change: code or exact steps> Verified: <how: test run, traced caller at file:line, reproduced> | unverified: <what would confirm> 2. [test] ... 3. [security] ... 4. [scope] ... CI: <checks passed | failing: job names | not available> Not checked: <anything you could not read or run> ``` Severity tags: `bug`, `test`, `security`, `scope`, and `rule` for a broken project instruction. If there are no findings, say so in one line and give the verdict; do not invent findings to fill the report. ## Stop conditions - Stop after the report. Apply fixes only if the user asks; then re-run the tests you ran. - If the diff is too large to read whole, say so, review the riskiest files first (logic over config, config over docs), and list the files you did not review under `Not checked`.
Perguntas sobre a skill code-review
- Existe uma skill de revisão do Claude Code que funciona em outros agentes?
- code-review é uma delas: um SKILL.md simples que Claude Code, Codex, OpenCode e Cursor podem ler. Foi testada no Claude Code e no Codex 0.163.0 em 29 de novembro de 2026.
- Qual é a diferença entre esta skill de revisão de código e a revisão integrada do Claude Code?
- Ela funciona da mesma forma em qualquer agente, usa um formato fixo de relatório e comprova cada achado no código antes de relatá-lo. O comando integrado /code-review do Claude Code tem o mesmo nome. Instalada como skill do projeto, esta foi usada no teste; pelo plugin, invoque-a como `/caprock-skills:code-review` (essa forma não foi executada).
- A skill code-review altera meu código?
- Não. Ela para após o relatório. Só aplica correções quando você pede e depois repete os testes que executou.
- Ela comenta sobre estilo?
- Só se você pedir ou uma regra do projeto exigir. Estilo, nomes e formatação são ignorados por padrão.