Установка
SKILL.md
Code Review
Review all changed code against the project's quality standards and coding conventions.
Code Standards
Read and internalize these standards before writing code. The review steps below verify compliance.
Python Style
- Python 3.11+, type hints required
- Async throughout (asyncpg, async FastAPI)
- Pydantic models for request/response
- Ruff for linting (line-length 120)
- No Python files at project root - maintain clean directory structure
- Never use multi-item tuple return values — not even for internal/private functions. Always use a dataclass or Pydantic model. No exceptions, no "it's just two values" shortcuts. If a function returns more than one value, define a named type for it.
Type Safety with Pydantic Models
NEVER use raw dict types for structured data — this applies to all code, including internal helpers and private functions. If the dict has known keys, it must be a dataclass or Pydantic model:
- Use Pydantic
BaseModelfor all data structures passed between functions - Use
@dataclassfor lightweight internal data containers when Pydantic validation isn't needed - Add
@field_validatorfor type coercion (e.g., ensuring datetimes are timezone-aware) - Avoid
dict.get()patterns - use typed model attributes instead - Parse external data (JSON, API responses) into Pydantic models at the boundary
- This catches type errors at parse time, not deep in business logic
- The only acceptable
dictusage is for truly dynamic/unknown keys (e.g., arbitrary metadata, JSON blobs with no fixed schema)
# BAD - error-prone dict access
def process(data: dict) -> str:
return data.get("name", "") # No validation, silent failures
# GOOD - typed and validated
class UserData(BaseModel):
name: str
created_at: datetime
@field_validator("created_at", mode="before")
@classmethod
def ensure_tz_aware(cls, v):
if isinstance(v, str):
v = datetime.fromisoformat(v.replace("Z", "+00:00"))
if v.tzinfo is None:
return v.replace(tzinfo=timezone.utc)
return v
def process(data: UserData) -> str:
return data.name # Type-safe, validated at construction
TypeScript Style
- Next.js App Router for control plane
- Tailwind CSS with shadcn/ui components
Code Comments
- Always comment non-trivial technical decisions with the reasoning behind the choice. If someone would ask "why is it done this way?", there should be a comment.
- Keep comments up to date with history — when changing an approach, update the comment to explain what was tried before and why it was changed. Comments serve as a tracker of previous implementations that likely had problems.
- Don't comment obvious code — only where the "why" isn't self-evident from the code itself.
# BAD - no context for future readers
results = await asyncio.gather(*tasks, return_exceptions=True)
# GOOD - explains the non-obvious choice
# Use return_exceptions=True to avoid cancelling sibling tasks on failure.
# Previously we used TaskGroup but it cancelled all tasks when one failed,
# causing partial writes that left orphaned entity links (see #412).
results = await asyncio.gather(*tasks, return_exceptions=True)
API Layer & Data Access
- No direct database access in
api/http.py(or any API router). HTTP handlers must not build SQL, callacquire_with_retry/conn.fetch/conn.fetchrow/conn.execute, or referencefq_table(...). All persistence and queries live inMemoryEngine(the engine layer). A handler parses/validates the request, calls an engine method, shapes the HTTP response, and maps domain results to status codes (e.g. aNonereturn → 404). - Authentication/tenancy is enforced inside each engine method, not assumed by the handler. Every engine method that touches bank-scoped data must authenticate via
request_context— typicallyawait self._authenticate_tenant(request_context)(often indirectly throughget_bank_profile(...)) — so the correct tenant schema is resolved before any query runs. Handlers must threadrequest_contextthrough to the engine method; never query a tenant-scoped table assuming the schema is already set. - Engine methods return typed models (Pydantic/dataclass), not raw dicts (see Type Safety).
Database Locking
- Never use PostgreSQL advisory locks (
pg_advisory_lock,pg_try_advisory_lock,pg_advisory_xact_lock,pg_advisory_unlock, …) in migrations, engine code, or anything else. Hindsight runs against connection poolers and managed/PG-compatible services where advisory locks are unreliable or unsupported: session-level locks silently leak or vanish when a pooler hands the session to another client, and callers can block forever on a lock the server never grants. Reject any new occurrence, including ones that look "safe" because they are transaction-scoped. - The pre-existing usage in
hindsight_api/migrations.pyis grandfathered, not a precedent — it is tracked for removal. Don't copy it. - Design the concurrency out instead of locking around it: give each process its own object to write (e.g. per-schema DDL rather than a shared
public.object), make the operation idempotent, or use a real row/table constraint (INSERT ... ON CONFLICT,SELECT ... FOR UPDATEin a fixed order). See #2690 for a migration that reached forpg_advisory_xact_lockand had to be reverted.
Branch Hygiene
- Always start new feature branches from
origin/main— rebase to ensure a clean base. - Only include commits relevant to the PR/branch/feature — no unrelated changes. If the branch contains commits that don't belong, they must be removed before merging.
General Principles
- Don't add features, refactor code, or make "improvements" beyond what was asked
- Don't add unnecessary error handling for impossible scenarios
- Don't create helpers or abstractions for one-time operations
- No backwards-compatibility hacks (unused vars, re-exports, "removed" comments)
- Three similar lines of code is better than a premature abstraction
Review Steps
1. Check branch hygiene
- Run
git log --oneline main..HEADto list all commits on the branch. - Verify every commit is relevant to the feature/PR. Flag any unrelated commits.
- Check the branch is based on a recent
origin/main(no stale base).
2. Identify changed files
Run git diff --name-only HEAD (unstaged) and git diff --cached --name-only (staged) to get all changed files. If there are no local changes, diff against the base branch using git diff main...HEAD --name-only and git diff main...HEAD to review all commits on the current branch.
3. Run linters
./scripts/hooks/lint.sh
Report any failures. Do NOT fix them yourself — just report.
4. Check for dead code
For each changed Python file, check for:
- Unused imports (Ruff should catch these, but verify)
- Functions/methods/classes that were added but are never called from anywhere
- Variables assigned but never read
- Commented-out code blocks that should be removed
For each changed TypeScript file, check for:
- Unused imports
- Unused variables or functions
- Commented-out code
5. Check type safety (Python)
For each changed Python file, check for violations:
- No raw
dictfor structured data — must use Pydantic model or dataclass, even for internal/private functions (only exception: truly dynamic/unknown keys) - No multi-item tuple returns — must use dataclass or Pydantic model, even for internal/private functions (no exceptions)
- Missing type hints on function parameters and return types
- Missing
@field_validatorfor datetime fields that should be timezone-aware
6. Check for missing tests
For each new or significantly changed function/endpoint/class:
- Check if there is a corresponding test addition or update
- New API endpoints MUST have integration tests
- New utility functions MUST have unit tests
- Bug fixes SHOULD have a regression test
Flag any new logic that lacks test coverage.
LLM-behaviour changes need a real-LLM judge test, not MockLLM. If the change alters how the model interprets a prompt — fact/observation extraction, fact_type (world/experience) classification, speaker attribution, instruction-following, prompt wording — there MUST be a test marked pytest.mark.hs_llm_core that runs the real pipeline and asserts via tests.llm_judge.assert_meets_criteria (not string/enum matching). Flag these as findings:
- A prompt/classification change verified only by MockLLM or string assertions (MockLLM echoes input — such tests pass spuriously). Should fix.
- A test that hard-asserts
fact_type == "world"/"experience"(or other model-decided output) instead of judging it — non-deterministic, will flake across providers/runs. Should fix (move the classification check into the judgecriteria; keep only genuinely deterministic structural asserts direct). - Deterministic mechanics (prompt assembly, suppression/branching logic) that are covered only by a slow LLM test — these should also have fast non-LLM unit tests. Note.
See CLAUDE.md → Key Conventions → Testing for the full pattern.
7. Check API consistency
If any files in hindsight-api-slim/hindsight_api/api/ were changed:
- Were the OpenAPI specs regenerated? (
./scripts/generate-openapi.sh) - Were the client SDKs regenerated? (
./scripts/generate-clients.sh) - Were the control plane proxy routes updated? (
hindsight-control-plane/src/app/api/)
7b. Check API-layer data-access boundary
For each changed handler in hindsight-api-slim/hindsight_api/api/ (e.g. http.py, mcp.py):
- Flag any direct DB access in the handler —
acquire_with_retry,conn.fetch/fetchrow/execute, raw SQL strings, orfq_table(...). These are a must fix: the query must be moved into aMemoryEnginemethod that returns a typed model, and the handler must call that method. - Verify authentication is enforced in the engine — the handler must delegate to an engine method that authenticates via
request_context(_authenticate_tenant, typically throughget_bank_profile). A handler that reads/writes tenant-scoped data without an engine method enforcing auth is a must fix (tenant data could leak across schemas).
8. Check code comments
For each non-trivial change:
- New non-obvious logic — is there a comment explaining the reasoning?
- Changed approach — does the comment include what was done before and why it changed?
- Stale comments — do existing comments near the changed code still accurately describe the behavior?
9. Check integration completeness
If any files in hindsight-integrations/ were added or changed, verify:
- Tests exist — the integration must have tests that simulate/exercise the external framework (not just pure unit tests of helpers). Check for a
tests/directory with meaningful test files. - CI job exists — check
.github/workflows/test.ymlfor a correspondingtest-<name>-integrationjob. If missing, flag it. - Release process — check that the integration name is in the
VALID_INTEGRATIONSarray inscripts/release-integration.shAND in theINTEGRATIONSdict inhindsight-dev/hindsight_dev/generate_changelog.py(the changelog generator keeps its own list; a release fails at the changelog step if the name is missing there). If either is missing, flag it. - Docs gallery + sidebar entry — the integration must have an entry in
hindsight-docs/src/data/integrations.json. This file is the single source of truth that drives both the integrations gallery and the docs sidebar (the sidebar category is injected from it at render time across all docs versions). The entry needs an internal/sdks/integrations/<slug>linkand a matching page athindsight-docs/docs-integrations/<slug>.md(x). Thehindsight-docs/scripts/check-integrations.mjsbuild step enforces both directions — forward: every internal JSON entry has a doc page; reverse: every released tag (integrations/<name>/vX.Y.Z) appears in the JSON (private infra likecloudflare-oauth-proxyis in the script'sEXCLUDEDset). Flag any integration that is released (or being released) but missing fromintegrations.json, and any JSON entry without a doc page. Do not hand-editversioned_sidebars/*.jsonto add integration links — they are positional placeholders filled from the JSON. - Code standards — the integration code must follow all Python style rules (type hints, no raw dicts, no tuple returns, etc.).
10. Check MCP tool registration completeness
If any new MCP tools were added or existing tools renamed in hindsight-api-slim/hindsight_api/mcp_tools.py:
_ALL_TOOLSset inmcp_tools.py— must include the new tool nametools_to_registerdefault set inregister_mcp_tools()inmcp_tools.py— must include the new tool name_SINGLE_BANK_TOOLSset inhindsight-api-slim/hindsight_api/api/mcp.py— must include the new tool if it is bank-scoped (not a bank-management tool likelist_banks/create_bank)MCP_TOOL_GROUPSinhindsight-control-plane/src/components/bank-config-view.tsx— must include the new tool in the appropriate group for the UI tool selector- Tool count assertions in tests (e.g.,
test_mcp_tools.py) — must be updated to reflect the new count
11. Check backup/restore table coverage
If a migration adds a new PostgreSQL table (look for CREATE TABLE / op.create_table in hindsight-api-slim/hindsight_api/alembic/versions/):
BACKUP_TABLESinhindsight-api-slim/hindsight_api/admin/cli.py— must include the new table, placed after any table it references via foreign key (parents before children). A missing entry is silent data loss: the table is never backed up, and restore'sTRUNCATE banks CASCADEwipes any FK-to-banks child (e.g.mental_models,directives) on restore even though it was never saved.- The guard test
test_backup_tables_covers_entire_schemaintests/test_admin_backup_restore.pyenforces this — flag it as a must fix if a new table is absent fromBACKUP_TABLES. - Oracle-only tables (e.g.
observation_sources) are intentionally excluded — admin backup/restore is PostgreSQL-only.
11b. Check new config flags update the env template
If the diff adds a new configuration field (a new ENV_* / HINDSIGHT_* env var
in hindsight-api-slim/hindsight_api/config.py):
.env.example(repo root) — must add the variable (commented if optional) alongside the docs entry inhindsight-docs/docs/developer/configuration.md. A flag added toconfig.pybut absent from.env.exampleis a should fix.hindsight-embed/hindsight_embed/env.example— the bundled copy must stay byte-identical to the repo-root.env.example(it seeds embed/profile configs). Thetest_bundled_template_matches_repo_rootsync test fails on drift; if the root file changed without re-copying, flag it as a must fix.
11c. Check for advisory locks
Grep the diff for advisory (git diff main...HEAD | grep -in advisory). Any new
pg_advisory_lock / pg_try_advisory_lock / pg_advisory_xact_lock /
pg_advisory_unlock вызов — это обязательно исправить — см. раздел «Блокировки базы данных» выше. Укажите автору на альтернативы (объекты на процесс, идемпотентный DDL, ограничения на уровне строк), а не просто просите убрать блокировку.
12. Проверка на соответствие другим стандартам кодирования
Проверьте diff на нарушения стандартов, перечисленных выше:
- Python-файлы в корне проекта (не допускаются)
- Отсутствие асинхронных паттернов (должно быть асинхронно повсюду)
- Модели Pydantic для запроса/ответа
- Длина строки > 120 символов
- Новые функции/код сверх запрошенного (избыточная инженерия)
- Излишняя обработка ошибок для невозможных сценариев
- Преждевременные абстракции или спекулятивные вспомогательные функции
- Хаки обратной совместимости (неиспользуемые переменные, реэкспорты, комментарии "removed")
13. Отчёт о найденных проблемах
Представьте чёткое резюме, организованное по степени серьёзности:
Обязательно исправить — проблемы, которые сломают CI или нарушат жёсткие правила проекта:
- Посторонние коммиты в ветке
- Ошибки линтера
- Отсутствие аннотаций типов в публичных функциях
- Использование сырых dict для структурированных данных (включая внутренний код)
- Возврат кортежей из нескольких элементов (включая внутренний код)
- Отсутствие тестов для новых эндпоинтов
- Прямой доступ к БД (сырой SQL /
acquire_with_retry/fq_table) in anapi/handler вместоMemoryEngineметода - Доступ к данным в рамках тенанта без принудительной аутентификации в движке (
_authenticate_tenant/get_bank_profile) - Новая интеграция без тестов, задания CI или записи в release-integration.sh
- Выпущенная/добавленная интеграция отсутствует в
hindsight-docs/src/data/integrations.json, или JSON-запись безdocs-integrations/<slug>страницы (ломает сборку документации черезcheck-integrations.mjs) - Новая таблица PostgreSQL отсутствует в
BACKUP_TABLESinadmin/cli.py(тихая потеря данных при восстановлении)
Следует исправить — проблемы, снижающие качество кода:
- Мёртвый код / неиспользуемые импорты, пропущенные линтером
- Отсутствие тестов для нетривиальных вспомогательных функций
- Избыточная инженерия за пределами задачи
Примечание — наблюдения, которые могут потребовать или не потребовать действий:
- Изменения API, которые могут потребовать регенерации клиента
- Паттерны, отклоняющиеся от стиля соседнего кода
Для каждой находки укажите путь к файлу, номер строки и краткое объяснение.
НЕ исправляйте проблемы автоматически. Сообщите обо всех находках и позвольте пользователю решить, что исправлять. Если находок нет, подтвердите, что код выглядит хорошо.
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: code-review](https://darkplay.ru/ai/skills/vectorize-io-hindsight-code-review)
Описание
Проверяет изменённый код на соответствие стандартам проекта: отсутствующие тесты, мёртвый код, типобезопасность, проблемы линтера и соглашения о кодировании. Запускайте после завершения любой работы по реализации.
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
A11y Architectaffaan-m · Архитектор доступности, специализирующийся на соответствии WCAG 2.2 для веба и нативных…
Add Language Rulesaffaan-m · Каркас команды workflow для add-language-rules в everything-claude-code.
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
Code Exploreraffaan-m · Глубоко анализирует существующие функции кодовой базы, прослеживая пути выполнения…
Code Revieweraffaan-m · Эксперт по ревью кода. Проактивно проверяет код на качество, безопасность и…
Code Simplifieraffaan-m · Упрощение и очистка кода без изменения поведения.
Comment Analyzeraffaan-m · Анализ комментариев в коде на точность, полноту и риск устаревания.Лучшие ИИ-инструменты для программирования
Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные
GenAPIGenapi
Notepad++ AINotepad-plus-plus
Creatium MaxCremax
Emacs AIGnu
KiteKite
Amazon Q DeveloperAmazonЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirtonЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-maker