agentleFS
alxyrginalxyrgin/secondbrain_ai/.claude/skills-dev/code-review/SKILL.md

code-review

Skill17 starsChanged 9 months agoMITView on GitHub

Systematic code review with security, performance, and quality checklists. Use when user asks to "проревьюй код", "сделай code review", "review this code", "check code quality", or when task requires reviewing pull requests, analyzing code changes, or evaluating code quality.

Files
SKILL.md

Code Review Skill — систематическое ревью кода

Методология глубокого и структурированного code review с акцентом на безопасность, производительность и поддерживаемость.

Когда использовать

  • Review pull request или изменений
  • Оценка качества существующего кода
  • Pre-merge проверка
  • Аудит безопасности
  • Проверка соответствия стандартам

Методология Code Review

Структура Review

Code review проходит в 4 этапа:

  1. Quick Scan — первый взгляд (2-5 мин)
  2. Deep Analysis — глубокий анализ (15-30 мин)
  3. Security & Performance — проверка критичных аспектов (10-15 мин)
  4. Recommendations — выводы и рекомендации (5 мин)

Этап 1: Quick Scan (Быстрый взгляд)

Цель: Получить общее впечатление от изменений

Что проверяем

✅ Scope изменений

  • Сколько файлов изменено?
  • Какой объём кода (строки добавлены/удалены)?
  • Соответствует ли scope заявленной задаче?

✅ Структура

  • Логичная ли организация файлов?
  • Нет ли смешанных concerns?
  • Правильное ли место для нового кода?

✅ Первое впечатление

  • Код читаемый?
  • Naming понятный?
  • Есть ли очевидные проблемы?

Красные флаги на Quick Scan

🚩 STOP и спроси:

  • Изменено >500 строк в одном PR (слишком большой)
  • Изменения в несвязанных модулях (scope creep)
  • Отсутствуют тесты для новой логики
  • Commented-out код или debug statements

Вывод Quick Scan:

## Quick Scan

**Scope:** [Описание изменений]
**Файлов изменено:** N
**Строк:** +XXX / -YYY

**Первое впечатление:**
- ✅ [Что хорошо]
- ⚠️ [Что требует внимания]
- 🚩 [Критичные проблемы]

Этап 2: Deep Analysis (Глубокий анализ)

Цель: Детально понять логику и качество кода

Чеклист Deep Analysis

📖 Читаемость (Readability)

  • Naming
    • Переменные названы осмысленно?
    • Функции отражают что делают?
    • Константы выделены и названы правильно?
  • Функции
    • Размер функций разумный (<50 строк)?
    • Каждая функция делает одну вещь?
    • Уровень абстракции единый?
  • Комментарии
    • Код самодокументируемый?
    • Комментарии объясняют "почему", не "что"?
    • Нет устаревших/противоречивых комментариев?

🧱 Архитектура (Architecture)

  • Separation of Concerns
    • Бизнес-логика отделена от UI?
    • Нет ли дублирования кода?
    • Правильное ли разделение на модули?
  • Coupling & Cohesion
    • Модули слабо связаны (low coupling)?
    • Внутренняя связность высокая (high cohesion)?
    • Легко ли тестировать изолированно?
  • SOLID принципы
    • Single Responsibility соблюдён?
    • Open/Closed — можно расширять без изменений?
    • Dependency Inversion — зависимости от абстракций?

🔄 Логика (Logic)

  • Корректность
    • Логика работает правильно?
    • Обработаны edge cases?
    • Нет ли off-by-one errors?
  • Error Handling
    • Все ошибки обработаны?
    • Правильные типы исключений?
    • Есть ли fallback стратегии?
  • Null Safety
    • Проверки на null/undefined?
    • Optional chaining где нужно?
    • Defensive programming?

✅ Тестирование (Testing)

  • Покрытие
    • Есть ли unit tests для новой логики?
    • Критичные paths покрыты?
    • Edge cases протестированы?
  • Качество тестов
    • Тесты независимые?
    • Понятные test names?
    • Arrange-Act-Assert структура?

Вывод Deep Analysis:

## Deep Analysis

### Читаемость: ⭐⭐⭐⭐☆ (4/5)
- ✅ Naming понятный
- ⚠️ Функция `processData` слишком большая (80 строк)

### Архитектура: ⭐⭐⭐☆☆ (3/5)
- ✅ Separation of concerns соблюдён
- ❌ Дублирование логики в файлах X и Y

### Логика: ⭐⭐⭐⭐⭐ (5/5)
- ✅ Корректная обработка ошибок
- ✅ Edge cases учтены

### Тестирование: ⭐⭐☆☆☆ (2/5)
- ❌ Отсутствуют unit tests для новых функций
- ⚠️ Integration test только happy path

Этап 3: Security & Performance

Цель: Проверить критичные аспекты безопасности и производительности

🔒 Security Checklist

Input Validation

  • Валидация всех входных данных?
  • Sanitization перед использованием?
  • Type checking на границах?

Authentication & Authorization

  • Проверка прав доступа?
  • Токены безопасно хранятся?
  • Нет hardcoded credentials?

Common Vulnerabilities

  • SQL Injection — используются prepared statements?
  • XSS — экранирование пользовательского ввода?
  • CSRF — защита от CSRF атак?
  • Path Traversal — проверка путей файлов?
  • DoS — лимиты на ресурсы (rate limiting)?

Data Protection

  • Чувствительные данные не логируются?
  • Пароли хешируются (bcrypt/argon2)?
  • HTTPS для передачи данных?

⚡ Performance Checklist

Algorithms & Data Structures

  • Сложность алгоритмов приемлема (O(n) vs O(n²))?
  • Правильные структуры данных (Map vs Array)?
  • Нет ли ненужных вложенных циклов?

Database

  • Запросы оптимизированы?
  • Используются индексы?
  • Нет N+1 проблемы?
  • Pagination для больших списков?

Memory & Resources

  • Нет утечек памяти?
  • Ресурсы освобождаются (close connections)?
  • Нет ли избыточного копирования данных?

Network & I/O

  • Минимизированы сетевые запросы?
  • Используется кеширование?
  • Асинхронные операции где возможно?

Вывод Security & Performance:

## Security & Performance

### 🔒 Security: ⚠️ ISSUES FOUND
- ❌ **CRITICAL:** SQL запрос без параметризации (`db.query(${userId})`)
  Файл: `src/users/repository.ts:42`
  Риск: SQL Injection
  Fix: Использовать prepared statements

- ⚠️ **WARNING:** Пароль логируется в debug mode
  Файл: `src/auth/login.ts:15`
  Риск: Утечка credentials
  Fix: Убрать из логов

### ⚡ Performance: ⚠️ NEEDS IMPROVEMENT
- ⚠️ N+1 проблема при загрузке связанных данных
  Файл: `src/posts/service.ts:67`
  Impact: Медленные запросы при >100 записей
  Fix: Использовать eager loading или dataloader

Этап 4: Recommendations (Рекомендации)

Цель: Дать конструктивную обратную связь

Категории комментариев

Используй префиксы для приоритизации:

  • 🚨 BLOCKER — нельзя мержить без исправления
  • ❌ CRITICAL — нужно исправить (security, bug, breaking)
  • ⚠️ MAJOR — серьёзная проблема (performance, architecture)
  • 💡 SUGGESTION — улучшение (refactoring, best practice)
  • 📝 NITPICK — мелочь (style, naming)
  • ✅ POSITIVE — отметь хорошие решения

Структура комментария

### [Категория] [Файл:строка] — [Краткое описание]

**Проблема:**
[Что не так]

**Почему это важно:**
[Impact или риск]

**Как исправить:**
[Конкретное решение или пример кода]

**Пример:**
```language
// ❌ Текущий код
bad code here

// ✅ Предлагаемый вариант
good code here

### Итоговый отчёт

```markdown
# Code Review Summary

## Overall Rating: ⭐⭐⭐☆☆ (3/5)

**Можно мержить:** ❌ НЕТ (есть блокеры)

---

## 🚨 Blockers (2)
1. [SQL Injection в user repository](файл:строка)
2. [Missing authentication check](файл:строка)

## ❌ Critical Issues (1)
1. [Password logging in debug mode](файл:строка)

## ⚠️ Major Issues (3)
1. [N+1 query problem](файл:строка)
2. [Code duplication across modules](файл:строка)
3. [Missing unit tests](файл:строка)

## 💡 Suggestions (5)
1. Refactor large function into smaller pieces
2. Consider using custom hook for state management
3. Add TypeScript strict mode
4. Extract magic numbers to constants
5. Improve error messages for better UX

## ✅ What went well
- Clean separation of concerns
- Good naming conventions
- Comprehensive integration tests
- Well-documented complex logic

---

## Action Items

**Before merge:**
- [ ] Fix SQL injection vulnerability
- [ ] Add authentication middleware
- [ ] Remove password from logs

**After merge (create tasks):**
- [ ] Add unit tests for new service methods
- [ ] Refactor duplicated code into shared utility
- [ ] Optimize database queries (N+1 problem)

**Future improvements:**
- [ ] Consider migration to TypeScript strict mode
- [ ] Extract business logic into domain services

Инструменты Code Review

Поиск паттернов проблем

# Поиск SQL injection рисков
rg "\.query\(.*\$\{" --type ts

# Поиск захардкоженных credentials
rg -i "password.*=.*['\"]" --type js

# Поиск console.log/debug statements
rg "console\.(log|debug|warn)" --type js

# Поиск TODO/FIXME
rg "TODO|FIXME|HACK|XXX" -i

# Поиск commented out code
rg "^\\s*//.*;" --type js

Анализ тестов

# Найти файлы без тестов
# (сравнить src/ с tests/)

# Проверить покрытие
npm run test:coverage

# Найти тесты для конкретного файла
rg "describe.*MyComponent|test.*myFunction"

Best Practices Code Review

DO ✅

  1. Будь конструктивным
    • Объясняй "почему", не только "что"
    • Предлагай конкретные решения
    • Отмечай хорошие решения
  2. Будь объективным
    • Фокусируйся на коде, не на человеке
    • Используй факты и примеры
    • Ссылайся на стандарты проекта
  3. Приоритизируй
    • Сначала critical issues
    • Потом major improvements
    • Nitpicks в конце
  4. Используй примеры
    • Покажи как исправить
    • Дай ссылки на документацию
    • Укажи похожие места в кодовой базе

DON'T ❌

  1. Не будь субъективным
    • ❌ "Мне не нравится этот код"
    • ✅ "Этот код нарушает принцип SRP"
  2. Не перфекционизируй
    • Мелкие стилистические правки — низкий приоритет
    • Не блокируй PR из-за nitpicks
    • Лучше done чем perfect
  3. Не игнорируй context
    • Учитывай deadlines
    • Понимай constraints проекта
    • Помни о technical debt trade-offs

Шаблоны запросов

Полный review:

Проревьюй этот код, проверь security и performance

Фокусированный review:

Проверь только безопасность этого SQL query

Pre-merge check:

Сделай quick review перед merge в main

Review изменений:

Проанализируй изменения в этом PR


Интеграция с другими skills

  • Перед review → используй research для понимания контекста
  • После review → используй debugging если нашёл баги
  • После review → предложи refactoring для улучшений
  • Результаты review → сохрани в комментарии к PR или в Todoist

Download now (ZIP)

  • Other versions194 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 194

    1. mattpocock/skills★ 309ksame name
    2. TheAlgorithms/Python★ 226ksame name
    3. microsoft/vscode★ 194ksame name
    4. github/spec-kit★ 145ksame name
    5. ggml-org/llama.cpp★ 132ksame name
    6. shareAI-lab/learn-claude-code★ 80ksame name
    7. shareAI-lab/analysis_claude_code★ 78ksame name
    8. vectorize-io/hindsight★ 57ksame name
    9. dbeaver/dbeaver★ 52ksame name
    10. roboflow/supervision★ 51ksame name

    184 more not listed

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • Used alongsideProjects with it also use add-new-model, azsdk-common-sdk-breaking-change and 9 more.

    Other files people use alongside this one.

    Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
    • PydanticSkill

      add-new-model

      Add support for a newly-released language or image generation model in pydantic-ai (e.g. openai:gpt-5.6, anthropic:claude-sonnet-5, openai:gpt-image-2). Use when a provider ships a new model id and you need to wire literals, profile flags, adapters, and tests to recognize it. Handles SDK-lag, gateway list conventions, capability probing, and direct image-model geometry.

      Also in 9 projects that use this

    • Microsoft AzureSkill

      azsdk-common-sdk-breaking-change

      Detect and mitigate SDK Breaking changes for an SDK package which is generated from TypeSpec. WHEN: "Detect SDK breaking changes for a service", "Detect SDK breaking changes for an SDK package", "Detect and mitigate SDK breaking changes for a service", "Detect and mitigate SDK breaking changes for an SDK package". INVOKES: skill: azsdk-common-generate-sdk-locally; MCP tools: azure-sdk-mcp:azsdk_customized_code_update, azure-sdk-mcp:azsdk_package_detect_breaking_change.

      Also in 4 projects that use this

    • ww-w-aiSkill

      bkend-auth

      bkend.ai authentication guide. Signup, login, JWT tokens, sessions, role-based access control, and password management with bkend.ai BaaS. Triggers: bkend auth, bkend login, bkend signup, JWT, session, RBAC, password, bkend 인증, 로그인, 회원가입, bkend認証, ログイン, 新規登録, bkend认证, 登录, 注册, autenticacion bkend, authentification bkend, bkend-Auth Do NOT use for: data operations (use $bkend-data), file storage (use $bkend-storage).

      Also in 4 projects that use this

    • ww-w-aiSkill

      bkend-cookbook

      bkend.ai cookbook with step-by-step tutorials and example projects. Build a todo app, blog, e-commerce store, and more with bkend.ai BaaS. Triggers: bkend cookbook, bkend tutorial, bkend example, todo app, blog app, bkend 쿡북, bkend 튜토리얼, 예제 프로젝트, bkendクックブック, チュートリアル, bkend教程, 示例项目, tutorial bkend, tutoriel bkend, bkend-Tutorial, ricettario Do NOT use for: initial setup (use $bkend-quickstart), specific features (use $bkend-data/auth/storage).

      Also in 4 projects that use this

    • dzhngSkill

      close-spec

      When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).

      Also in 4 projects that use this

    • dzhngSkill

      design-with-images

      Explore UI and visual design with image generation, then iterate the real implementation against the user-selected concept. Use when brainstorming visual directions, offering mockup variants, or implementing an approved generated design; do not stop at the mockups or the first code approximation.

      Also in 4 projects that use this

    • +5 more from ww-w-ai
  • In this repository18 other files it gives its agents.

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.