Code Review Agent
Как добавить в OpenCode-проект специализированного агента для code review: структура файлов, frontmatter агента, два скилла (code-review-checklist и git-diff-analysis), спецификация процесса, настройка opencode.json и AGENTS.md. Шаблоны универсальны и адаптируются под любой стек.
Зачем отдельный агент для review
В AI-assisted разработке code review — это не "ещё один проход агента", а отдельная роль с другой целью и другими ограничениями. Строитель пишет код, а ревьюер — читает его критически, не меняет файлы и выдаёт приоритизированный план рекомендаций.
Ключевое ограничение: read-only
Code-review агент никогда не должен иметь права на редактирование или удаление файлов. Только чтение, git-команды и скиллы. Это принципиально: задача агента — найти проблемы, а не исправлять их самостоятельно.
Выделенный агент решает три задачи одновременно:
- Роль: агент знает, что его задача — найти проблемы, а не реализовывать задачу.
- Ограничения:
edit: denyделает невозможным случайное изменение файлов во время review. - Специализация: агент несёт слой-специфические чеклисты и методику анализа git-диффов.
Что нужно создать
Для полноценного code-review агента в проекте нужны четыре файла и два обновления существующих конфигов.
Новые файлы
| Файл | Назначение |
|---|---|
.opencode/agents/code-reviewer.md |
Агент для code review: роль, flow, правила поведения, ограничения permissions |
.opencode/skills/code-review-checklist/SKILL.md |
Слой-специфические чеклисты: что проверять в каждом типе файлов вашего стека |
.opencode/skills/git-diff-analysis/SKILL.md |
Методика анализа git-диффов: команды, группировка по слоям, risk signals |
docs/specs/code-review-flow.md |
Спецификация процесса review: шаги, severity levels, формат recommendation plan |
Обновляемые файлы
| Файл | Что добавить |
|---|---|
opencode.json |
Добавить code-review-checklist и git-diff-analysis в permission.skill; разрешить code-reviewer как subagent в режимах build и plan |
AGENTS.md |
Добавить code-reviewer в секцию Role Routing; описать, когда и зачем его вызывать |
Агент: .opencode/agents/code-reviewer.md
Агент состоит из двух частей: frontmatter с техническими настройками и тело с инструкцией для модели.
Frontmatter
Frontmatter определяет permissions, режим вызова и параметры модели. Ключевой момент — edit: deny и ограниченный набор bash-команд только для чтения git-истории.
---
description: Reviews code changes for correctness, architecture compliance, and project standards. Produces a prioritised recommendation plan.
mode: all
temperature: 0.1
steps: 20
color: warning
permission:
read: allow
edit: deny
bash:
"*": deny
"git diff*": allow
"git log*": allow
"git show*": allow
"git status*": allow
"git blame*": allow
"git ls-files*": allow
task:
"*": deny
skill:
"*": deny
"code-review-checklist": allow
"git-diff-analysis": allow
---
Почему temperature: 0.1
Review — это аналитическая задача. Низкая температура делает вывод детерминированным: нет лишних "творческих" рекомендаций, только то, что действительно найдено в коде.
Почему color: warning
Цветовая маркировка в UI помогает визуально отличать code-reviewer от других агентов. warning сигнализирует: этот агент ищет проблемы.
Тело агента
Тело описывает роль, review flow, правила поведения и ожидаемый формат вывода. Адаптируйте под стек и архитектуру вашего проекта.
You are the code reviewer for the [PROJECT NAME] project.
Your role is to analyse pending or specified changes and produce a clear, actionable recommendation plan. You do not modify files — your output is findings and recommendations only.
## Review flow
Always follow the sequence defined in `docs/specs/code-review-flow.md`:
1. **Context** — read `AGENTS.md` and any relevant spec in `docs/specs/` before touching the diff.
2. **Inspect** — use the `git-diff-analysis` skill to identify what changed and which layers are affected.
3. **Read changed files** — read each modified file and its immediate neighbours to understand the change in full context.
4. **Apply checklists** — for each affected layer, apply the `code-review-checklist` skill.
5. **Cross-cutting** — check security (no hardcoded secrets), idempotency, documentation alignment.
6. **Report** — output the recommendation plan using the format from the spec:
Summary → 🔴 Critical → 🟠 Major → 🟡 Minor → 💡 Suggestions → What looks good → Next steps.
## Behaviour rules
- Never modify, create, or delete files. Read and report only.
- Do not guess: if you cannot see a file or diff, say so explicitly and ask the user to provide it.
- Reference every finding with a file path and line number where possible.
- Separate confirmed problems from assumptions. Label assumptions clearly.
- Prioritise correctness and architecture compliance over style preferences.
- Default diff target is `HEAD` unless the user specifies a branch or commit.
- If no git context is available, ask the user to paste the diff or specify file paths to review.
## Output
Always produce a recommendation plan using the format in `docs/specs/code-review-flow.md`.
End the plan with an ordered next-steps list where the first item is the highest-severity finding.
If there are no findings, say so explicitly and list what looks good.
Скилл: git-diff-analysis
Этот скилл описывает методику первичного анализа изменений: какие git-команды запускать, как группировать файлы по слоям и на какие risk signals обращать внимание.
---
name: git-diff-analysis
description: Inspect git history and diffs to identify what changed, which layers are affected, and what risk signals to prioritise before applying review checklists.
license: MIT
compatibility: opencode
metadata:
audience: code-reviewer
domain: git
---
## What I do
Guide the initial inspection of git changes so the reviewer understands scope
and risk before applying layer-specific checklists.
---
## Recommended commands
```bash
# Working-tree state
git status
# Files changed vs last commit (name list only — good starting overview)
git diff --name-only HEAD
# Full unified diff vs last commit
git diff HEAD
# Files and full diff vs main branch (for PR-style review)
git diff main..HEAD --name-only
git diff main..HEAD
# Diff of a single file
git diff HEAD -- path/to/file.py
# Recent commit history for context
git log --oneline -10
# Blame a specific area for authorship context
git blame -L 10,30 path/to/file.py
# List all tracked files (useful when no diff is available)
git ls-files
```
---
## Grouping files by layer
After running `git diff --name-only`, map each file to its layer.
Fill in the table for your project's actual directory structure:
| Layer | Path prefix | Risk level |
|---------------|-------------------|-------------------------------------|
| Database/DDL | `migrations/`, `sql/` | 🔴 High — schema changes break data |
| Core business | `src/domain/` | 🔴 High — shared by all consumers |
| API | `src/api/` | 🟠 Medium — contract changes affect clients |
| Services | `src/services/` | 🟠 Medium — behaviour changes |
| Frontend | `frontend/` | 🟡 Low-Medium — affects end users |
| Config/Infra | `docker-compose.yml`, `.env.example` | 🟠 Medium — affects whole env |
| Documentation | `docs/`, `AGENTS.md`, `README.md` | 🟡 Low — missing updates signal drift |
Review layers in risk order from highest to lowest.
---
## Pattern to follow
1. Run `git diff --name-only HEAD` (or `main..HEAD` for a branch review).
2. Group files by layer and note the risk level for each layer touched.
3. Check whether `docs/` or `AGENTS.md` were updated alongside code changes.
4. Read the full diff for each file, starting from the highest-risk layer.
5. Note the intent of each change and flag gaps between intent and implementation.
6. Hand off to `code-review-checklist` for structured per-layer verification.
Скилл: code-review-checklist
Этот скилл — набор конкретных чеклистов по слоям. Ниже показан шаблон, который нужно наполнить пунктами для вашего конкретного стека. Чем точнее чеклисты отражают реальные архитектурные правила проекта, тем полезнее становится агент.
---
name: code-review-checklist
description: Apply layer-specific quality checklists for each technology layer in the project.
license: MIT
compatibility: opencode
metadata:
audience: code-reviewer
domain: quality
---
## What I do
Provide a structured, layer-specific checklist so no critical concern is missed
during a code review. Apply the relevant sections based on which files changed.
---
## [Layer 1: e.g. Database / Migrations]
- [ ] Schema changes include a reversible migration.
- [ ] Scripts are idempotent (safe to re-run multiple times).
- [ ] PII fields are identified and handled explicitly.
- [ ] Indexes are added for expected query patterns.
- [ ] Column names are consistent with project naming conventions.
---
## [Layer 2: e.g. Backend / Domain]
- [ ] Business logic is separated from transport and persistence concerns.
- [ ] No hardcoded credentials, tokens, or API keys.
- [ ] Error handling and logging are present for all external calls.
- [ ] Public interfaces have type hints or contract documentation.
- [ ] No debug code left in (`print`, `breakpoint`, `pdb`).
---
## [Layer 3: e.g. API / Controllers]
- [ ] Request and response models use explicit schemas — no raw dict returns.
- [ ] Input validation is present on all public endpoints.
- [ ] Auth and authorization rules are applied consistently.
- [ ] API contracts match the specs in `docs/specs/`.
- [ ] Pagination and filter semantics are explicit in endpoint contracts.
---
## [Layer 4: e.g. Frontend]
- [ ] No raw API base URLs hardcoded — use config constants or env vars.
- [ ] Empty states, loading states, and error states are handled and visible.
- [ ] No sensitive data rendered into DOM or console unexpectedly.
- [ ] API calls include error handling.
- [ ] Components have a single clear responsibility.
---
## [Layer 5: e.g. Infrastructure / Docker]
- [ ] No secrets committed to tracked config files.
- [ ] `.env.example` is updated for every new environment variable.
- [ ] Health checks are defined for stateful services.
- [ ] Service dependencies and startup order are explicit.
---
## [Layer 6: e.g. Documentation]
- [ ] `docs/specs/` updated if data contracts or interfaces changed.
- [ ] `AGENTS.md` reflects any new architecture rule or structural change.
- [ ] `README.md` updated if setup steps, commands, or repo structure changed.
---
## Cross-cutting (always check)
- [ ] No secrets in any committed file (`grep` for `password`, `token`, `secret`, `api_key`).
- [ ] No debug code left in the codebase.
- [ ] Files touched but not part of the change are not accidentally modified.
- [ ] Idempotency guaranteed for pipelines and scripts.
- [ ] Observability: logging and error handling present for external calls.
Спецификация: docs/specs/code-review-flow.md
Спецификация описывает процесс review в виде, понятном как агенту, так и человеку. Агент ссылается на неё в своём review flow. Она же служит эталоном для людей, делающих ручной review.
# Code Review Flow
## Purpose
Provide a repeatable, layer-aware review process that checks correctness,
architecture compliance, and quality for all project layers before changes are merged.
---
## Recommended Review Sequence
### Step 1 — Understand context
- Read `AGENTS.md` to recall architecture rules, layer responsibilities, and standards.
- Identify which specs in `docs/specs/` are relevant to the change.
- Confirm what the change is supposed to accomplish before reading any diff.
### Step 2 — Inspect changes
```bash
git status # working-tree state
git diff --name-only HEAD # files changed vs last commit
git diff HEAD # full unified diff
git log --oneline -10 # recent history for context
git diff main..HEAD --name-only # files changed vs main (PR-style)
```
Group changed files by project layer.
Apply the `git-diff-analysis` skill for the full inspection procedure.
### Step 3 — Layer-by-layer review
Review each affected layer in order of risk (highest first).
Apply the `code-review-checklist` skill for each affected layer.
### Step 4 — Cross-cutting concerns
- **Security**: no hardcoded credentials, tokens, or API keys in any file.
- **Idempotency**: pipelines and DDL scripts safe to re-run without side-effects.
- **Documentation alignment**: if contracts or interfaces changed, specs must also be updated.
- **Observability**: logging and error handling present for external calls and long-running tasks.
### Step 5 — Produce recommendation plan
Classify every finding by severity and output the plan using the format below.
---
## Severity Levels
| Level | Meaning | Required action |
|--------------|---------------------------------------------------------------------|--------------------------|
| **Critical** | Data loss, broken correctness, exposed secret, broken pipeline | Must fix before merge |
| **Major** | Violates architecture rules, missing idempotency, contract drift | Should fix before merge |
| **Minor** | Naming, missing comments, small quality gaps | Fix or document trade-off |
| **Suggestion** | Refactor, improvement, future-work idea | Optional |
---
## Recommendation Plan Format
Use this exact structure when producing review output:
```markdown
## Code Review: <scope, branch, or file set>
### Summary
One paragraph: what changed, which layers are affected, overall quality signal.
### Findings
#### 🔴 Critical
- [ ] **`<file>`:`<line>`** — <concise description of the problem and its impact>
#### 🟠 Major
- [ ] **`<file>`:`<line>`** — <description>
#### 🟡 Minor
- [ ] **`<file>`:`<line>`** — <description>
#### 💡 Suggestions
- [ ] **`<file>`** — <description>
### What looks good
- Brief bullet list of things done correctly or notably well.
### Next steps
Ordered action list. First item is the highest-severity finding.
1. …
2. …
```
---
## Scope Notes
- Default diff target is `HEAD` unless the user specifies a branch or commit.
- For PR reviews, compare against `main` unless another base is specified.
- If no git context is available, ask the user to paste the diff or specify file paths.
Настройка opencode.json
В opencode.json нужно сделать два изменения: разрешить скиллы code-reviewer на уровне проекта и добавить agenta в список разрешённых subagents для режимов build и plan.
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"AGENTS.md"
],
"permission": {
"skill": {
"*": "deny",
"code-review-checklist": "allow",
"git-diff-analysis": "allow"
// ... остальные скиллы проекта
}
},
"agent": {
"build": {
"permission": {
"task": {
"*": "deny",
"code-reviewer": "allow"
// ... остальные агенты
},
"bash": {
"*": "allow",
"git push*": "ask",
"rm -rf *": "ask"
}
}
},
"plan": {
"permission": {
"task": {
"*": "deny",
"code-reviewer": "allow"
// ... остальные агенты
}
}
}
}
}
Зачем разрешать code-reviewer в build и plan
Чтобы другие агенты могли вызвать code-reviewer как subagent через @code-reviewer прямо в ходе работы. Например, data-engineer может запросить review своих изменений перед тем, как предложить их к merge.
Обновление AGENTS.md
В секцию Role Routing добавляется строка про code-reviewer. Это нужно не только для документации — на эту секцию ссылаются другие агенты, чтобы понять, кому передать задачу.
## Role Routing
Use the dedicated subagent that best matches the task:
- `project-manager` — ...
- `backend-engineer` — ...
- `frontend-engineer` — ...
- `code-reviewer` — reviewing code changes across all project layers,
checking architecture compliance, identifying bugs and contract drift,
and producing a prioritised recommendation plan. Call this agent
after any non-trivial implementation or before merging a feature branch.
Как работает агент: полный flow
Ниже описан рекомендованный flow, зафиксированный в docs/specs/code-review-flow.md. Агент следует ему последовательно при каждом вызове.
| Шаг | Что делает агент | Используемые инструменты |
|---|---|---|
| 1. Context | Читает AGENTS.md и релевантные specs в docs/specs/, понимает архитектурные правила и цель изменений |
read |
| 2. Inspect | Запускает git diff --name-only, группирует файлы по слоям, оценивает risk level каждого слоя |
git-diff-analysis skill, git diff* |
| 3. Read | Читает изменённые файлы и их непосредственных соседей для понимания контекста изменения | read |
| 4. Checklists | Для каждого затронутого слоя применяет чеклисты из code-review-checklist |
code-review-checklist skill |
| 5. Cross-cutting | Проверяет: секреты в коде, идемпотентность, выравнивание документации с кодом, наблюдаемость | read, git blame* |
| 6. Report | Формирует recommendation plan: Summary → 🔴 Critical → 🟠 Major → 🟡 Minor → 💡 Suggestions → What looks good → Next steps | текстовый вывод |
Формат recommendation plan
Агент всегда выдаёт вывод в фиксированном формате. Фиксированный формат упрощает машинную обработку и делает review предсказуемым для команды.
## Code Review: feature/my-feature
### Summary
Изменения затрагивают слои API и базы данных. Добавлен новый endpoint и миграция.
В целом код читаем, но есть два критичных момента: отсутствует rollback в миграции
и контракт ответа не совпадает с документацией в docs/specs/.
### Findings
#### 🔴 Critical
- [ ] **`migrations/0042_add_orders.sql`:1** — Миграция не содержит `IF NOT EXISTS`,
что делает её небезопасной для повторного запуска. Добавьте идемпотентность.
#### 🟠 Major
- [ ] **`src/api/orders.py`:34** — Поле `total_amount` отсутствует в ответе API,
хотя задокументировано в `docs/specs/orders-api.md`. Contract drift.
#### 🟡 Minor
- [ ] **`src/api/orders.py`:18** — Имя переменной `d` неинформативно. Переименуйте.
#### 💡 Suggestions
- [ ] **`src/services/order_service.py`** — Метод `create_order` можно разбить на
два: валидацию и сохранение. Упростит тестирование.
### What looks good
- Структура миграции соответствует проектным стандартам.
- Error handling в endpoint присутствует, HTTP-коды корректны.
- Тесты добавлены для happy path.
### Next steps
1. Добавить `IF NOT EXISTS` в миграцию и проверить на idempotency.
2. Вернуть `total_amount` в схему ответа или обновить спецификацию.
3. Переименовать переменную `d` в более осмысленное имя.
Как вызвать агента
Агент имеет режим all — его можно вызвать напрямую через Tab или как subagent через @mention из другого агента.
Прямой вызов (Tab)
# Review текущих незакоммиченных изменений
@code-reviewer сделай code review текущих изменений
# Review конкретной ветки против main
@code-reviewer проверь ветку feature/my-feature против main
# Review конкретного файла
@code-reviewer посмотри на src/api/orders.py
# Review последнего коммита
@code-reviewer проверь изменения в HEAD
Как subagent из другого агента
# Из backend-engineer или data-engineer:
# После реализации задачи можно попросить review
Реализация завершена. @code-reviewer сделай review изменений в src/
перед тем как я предложу это к merge.
Лучшая практика
Запускайте code-reviewer отдельным проходом после build, а не одновременно с ним. Агент, который только что написал код, плохо его проверяет. Разделите роли во времени: сначала build-агент завершает задачу и выдаёт Stage Report, потом code-reviewer делает независимый review.
Адаптация под проект: чеклисты по слоям
Универсальный шаблон чеклиста полезен как старт, но реальная ценность приходит, когда пункты отражают конкретные правила вашей архитектуры. Ниже примеры наполнения для разных стеков.
Примеры для data engineering стека
## Airflow DAGs
- [ ] DAG идемпотентен и безопасен для повторного запуска.
- [ ] `owner`, `retries`, `retry_delay` определены в default_args.
- [ ] `schedule_interval` задан осознанно и прокомментирован.
- [ ] Бизнес-логика не в DAG файле — она должна быть в `src/`.
- [ ] Connections и переменные используют secrets backend, не hardcoded значения.
- [ ] Task ID стабильны (переименование ломает историю в Airflow metadata DB).
## dbt models
- [ ] Staging-модели кастят ключевые аналитические поля к нужным типам.
- [ ] Нет `SELECT *` без явного обоснования в комментарии.
- [ ] Бизнес-логика в mart-моделях, не в staging.
- [ ] Все ссылки на таблицы через `{{ ref() }}` или `{{ source() }}`.
- [ ] Переименованные или удалённые модели проверены на downstream зависимости.
Примеры для fullstack веб-приложения
## FastAPI / Django REST
- [ ] Все handlers используют async; нет blocking IO на event loop.
- [ ] Request/Response модели — явные Pydantic/serializer схемы, не raw dict.
- [ ] Бизнес-логика в services, не в views/handlers.
- [ ] DB сессии корректно закрываются (context manager или finally).
- [ ] Контракты ответов совпадают со specs в `docs/specs/`.
## React / Vue.js
- [ ] Нет hardcoded API URL — только config constants или env vars.
- [ ] Empty, loading, error states обработаны и видны пользователю.
- [ ] API calls содержат error handling.
- [ ] Нет sensitive data в DOM или console.log.
## PostgreSQL migrations (Alembic / Flyway / raw SQL)
- [ ] Каждая миграция содержит up и down (rollback).
- [ ] Скрипты идемпотентны (IF NOT EXISTS, ON CONFLICT).
- [ ] PK или unique constraint на natural identifier.
- [ ] Индексы добавлены для ожидаемых query patterns.
Пример структуры полного проекта с code-review агентом
Ниже показано, как выглядит проект после добавления всех файлов для code-review агента.
.opencode/
agents/
code-reviewer.md ← агент: роль, flow, permissions
backend-engineer.md
frontend-engineer.md
...
skills/
code-review-checklist/
SKILL.md ← чеклисты по слоям стека
git-diff-analysis/
SKILL.md ← методика анализа git-диффов
...другие скиллы...
docs/
specs/
code-review-flow.md ← спецификация процесса review
...другие specs...
AGENTS.md ← включает code-reviewer в Role Routing
opencode.json ← разрешает скиллы и subagent
Частые вопросы при настройке
Нужно ли создавать все четыре файла сразу?
Минимально необходим только агент (.opencode/agents/code-reviewer.md). Скиллы и спецификация добавляют структуру и специализацию, но агент работает и без них — просто менее предсказуемо. Рекомендуем добавлять их в таком порядке:
- Агент с базовыми правилами
- Спецификация
code-review-flow.md - Скилл
git-diff-analysis - Скилл
code-review-checklist— наполнять постепенно по мере накопления правил
Как часто обновлять чеклисты?
Обновляйте code-review-checklist/SKILL.md каждый раз, когда команда договаривается о новом архитектурном правиле или когда агент пропустил что-то важное. Чеклист — это живой документ, а не разовая настройка.
Можно ли использовать агента для review PR в GitHub?
Да. Укажите агенту целевую ветку: @code-reviewer проверь feature/my-feature против main. Агент запустит git diff main..feature/my-feature и сделает полный review по слоям.
Разделение ролей — ключевой принцип
Code-reviewer — это роль чтения и анализа, а не расширение builder-агента. Именно поэтому у него edit: deny в frontmatter. Если агент находит проблему, исправляет её соответствующий builder-агент — отдельным вызовом, с отдельной ответственностью.
Что делать дальше
- Создать
.opencode/agents/code-reviewer.mdсedit: denyи нужными git-permissions. - Добавить
docs/specs/code-review-flow.mdс описанием severity levels и форматом вывода. - Создать скиллы
git-diff-analysisиcode-review-checklist— начать с минимального набора пунктов. - Обновить
opencode.json: разрешить скиллы и агента как subagent. - Добавить code-reviewer в секцию Role Routing в
AGENTS.md. - Запустить первый review:
@code-reviewer сделай review текущих изменений. - По результатам первого review дополнить чеклисты специфичными для проекта пунктами.