AI Agent Core Rules | Cododel [RU]
CODODELDEV
EN / RU
Back to Deck

Проверенный на практике набор правил для настройки AI coding агентов: Claude, Gemini, Cursor, Windsurf или Copilot. Эти правила устанавливают консистентное качество кода, практики безопасности и стандарты разработки.

Заточен под Claude Code, переносим куда угодно. Секции 1–10 не привязаны к стеку или конкретному агенту. Несколько вещей завязаны именно на Claude Code: преамбула отдаёт жёсткие блоки в settings.json permissions + PreToolUse hooks, §7 проводит решения через скилл /adr-writer (по adr-spec.md), а §9 рассчитан на раскладку .claude/skills/ в Claude Code. На Gemini, Cursor или Copilot читай это как intent и подключи эквивалент своей платформы — или просто убери.

Применение

Добавьте в корень проекта как:

  • CLAUDE.md (Anthropic Claude, Claude Code, Cursor)
  • GEMINI.md (Google AI Studio, Gemini)
  • AGENTS.md (Generic, Codex, Windsurf)
  • .cursorrules (Cursor IDE)

AI будет читать эти правила и применять их ко всему генерируемому коду.

Что включено

  • Code: Семантические имена, иммутабельность, комментарии why-not-what, stdlib-first зависимости
  • Type Safety: Без обхода типов, валидация границ, честные внешние типы
  • Shell & Filesystem: Ограниченные пути, проверка целей перед удалением, поиск через rg/fd
  • Git: Conventional commits, staging с учётом worktree
  • Change Discipline: Диагностика root cause, sweep по blast radius, проверка обратимости
  • Testing: Условный TDD (RED-GREEN), прогон тестов по делу, critical paths, детерминизм
  • Workflow: Пропорциональный процесс, intent перед действием, TDD там, где живёт поведение, file-based бэклог, иммутабельные ADR
  • Tools & MCP: Жёсткие схемы, структурированные ошибки, least privilege
  • Skills & Conventions: Переиспользуемые workflow живут в .claude/skills/, не в commands
  • Database Safety: Никаких миграций или схемных правок без явного подтверждения

Промпт

# Core Development Standards
*Assumes a capable agent. Routine craft (clarity, decomposition, root-cause analysis) is expected by default, not restated. Hard blocks on destructive/irreversible actions live in settings.json permissions + PreToolUse hooks — never trusted to this file.*
## 1. Code
- **Naming:** Booleans read as predicates, functions as verbs; follow the language's idiomatic casing.
- **Immutability:** Prefer immutable bindings and pure functions; isolate side effects.
- **Comments:** Explain *why*, never narrate *what*.
- **Dependencies:** Standard library first; justify every new dependency.
## 2. Type Safety
- **No escapes:** Where strict typing is available, never suppress type-checker errors or use unsafe casts/assertions — fix the cause or type it correctly.
- **Boundaries:** Validate at every external boundary (API, DAL, I/O) for runtime safety.
- **External types:** Extend or declare missing third-party types; never weaken your own types to paper over a library gap.
## 3. Shell & Filesystem
- **Search:** `rg` for content, `fd` for files (both respect .gitignore). With bare `find`, always exclude `node_modules`/`.git`.
- **Scope:** Stay inside the workspace — no absolute paths, no `../` escapes.
- **Destructive ops:** List and verify targets before any delete/overwrite.
## 4. Git
- **Commits:** Conventional Commits — `<type>(<scope>): <subject>`, lowercase imperative, no trailing period.
- **Staging is the operator's zone — but the zone is the root checkout and any worktree the operator works in, not an agent-owned worktree:** In the operator's checkout, by default never run `git add` / `git stage` and never auto-stage via `git commit -a`/`-am` — the operator stages manually to review changes step by step. Stage only on an explicit request; otherwise commit exactly what is already staged, and only when asked. **Inside a worktree created for an autonomous agent task, this gate lifts:** the worktree *is* the isolation boundary and its commits are cheap and reversible, so the agent stages and makes scoped, conventional commits on its own to drive the task to done. What never lifts, worktree or not: gates protecting state outside the worktree's blast radius — remote pushes, deploys, DB mutations (§10), external side-effects, and the §7 irreversibility floor. When it's unclear whether a worktree is agent-owned or the operator's, treat it as the operator's.
## 5. Change Discipline
- **Root cause:** Diagnose *why* before fixing; no band-aids over symptoms.
- **Blast radius:** On rename/migrate, sweep the whole codebase for affected call sites.
- **Reversibility:** Surface assumptions and tradeoffs; confirm before wide-reaching or irreversible changes.
## 6. Testing
- **TDD (RED-GREEN) — conditional, never imposed:** For feature work, write or adjust the failing test first, then implement to green. *When it applies:* a project that already has tests → work TDD by default; a new project → ask whether we work TDD before assuming it; a large project with no tests → mention the gap, but don't force TDD onto it. *Once TDD is in play, RED is not optional:* run the new test and confirm it fails **before** writing implementation, and confirm it fails for the right reason — your assertion, not an import/collection/setup error (a test red from infrastructure is a false RED that specifies nothing).
- **Run tests when it's warranted — judgment, not a blanket mandate:** Run the suite (and report pass counts) when it actually de-risks the work — after touching tested logic, before a requested commit, before claiming something works. Skip it when it buys nothing (docs, config, trivial plumbing). *One run point is exempt from this discretion:* when working TDD, the RED run (new test fails before implementing) is mandatory, never "skipped because it buys nothing" — it is what makes the test meaningful. Cadence under TDD: focused test/file in the RED→GREEN→refactor loop, full suite once before the commit gate (the focused file never substitutes for the full run at that gate). Hard, non-skippable gates are the operator's job to wire as PreToolUse/commit hooks per project — don't lean on prose to enforce them. Commits themselves stay on explicit request only (§4).
- **In an autonomous worktree, tests are the gate that replaces operator review:** front-load the test design so it specifies the target behavior, reach a correct RED (failing on your assertion, not setup — see above), then implement to green and report exact pass/fail counts. No test harness in the project → say so; an unverifiable change can't be claimed done. This is what lets the operator stop babysitting — the agent self-verifies instead of being corrected. Proportionality (§7) and this section's conditionality still govern *how much* process each change earns: the worktree lifts the commit gate, not the judgment about process weight.
- **Never hide a red test — even one unrelated to the current task:** Surface every failure you see; early regression detection is mandatory, never quietly stepped over.
- **Right level:** Match Unit/Integration/E2E to the stack and project phase.
- **Critical paths:** Core business logic is always covered.
- **Determinism:** No flaky tests.
## 7. Workflow
- **Proportionality — match process weight to the task:** Default path is *accept → agree invariants and design/architecture → implement*. Each artifact — issue, ADR, written spec, a formal design-and-approval gate — is created only when it earns its place, and skipped silently when it doesn't. A clear, atomic, or self-evident change goes straight to implementation: reviewing the diff by hand is cheaper than specifying it first. This explicitly overrides any blanket "design-first for every task / every project regardless of simplicity" gate. **Floor:** when the work is irreversible, crosses a contract/interface boundary, touches persistence/schema, adds an external dependency, or carries security/compliance weight, the fast path is off — take the full design/approval route (and an ADR if warranted). Full counter-signal list: `adr-spec.md §5`. Announce the chosen path in one line before diving in, so a wrong call is cheap to veto.
- **TDD where behavior lives:** For logic and behavior, write the failing test that specifies it first, then implement to green, then refactor — the test defines "done". Subject to proportionality: declarative or non-logic work (config, provisioning, plumbing, rename, docs) and throwaway spikes are out of scope; §6 still guarantees critical paths are covered regardless.
- **Read intent before acting — a diagnosis is not a mandate:** When a request reads as an observation, complaint, or open-ended/taste judgment («CTA вводит в заблуждение», «this feels off») rather than an explicit imperative to change something specific, treat it as a proposal point, not a work order — surface what you'd change and why, and get agreement before applying any material change. The fuzzier the target or the wider the valid-answer space, the harder this binds: ambiguity signals a creative decision, and creative decisions are agreed, not assumed. Gates *applying* a change only — thinking aloud and offering options is the response, not a change; adds no step to clear, imperative requests.
- **Deferring work:** When asked to park or postpone, capture it as a file-based issue — never an inline `TODO` or half-finished code. Issues are the backlog's source of truth.
- **Decisions → ADR:** Architectural decisions go through the `/adr-writer` skill against `adr-spec.md`, strictly — never ad hoc. ADRs are immutable: a changed decision is a new ADR marked `Superseded`, never an edit to an accepted one. The skill gates significance — not every choice warrants an ADR.
## 8. Tools & MCP — *only when authoring tools/servers*
- Rigid I/O schemas; structured, actionable errors (never raw stack traces).
- Least privilege; write-ops idempotent or explicitly confirmable.
## 9. Skills & Conventions
- **Reusable workflows are skills, not commands:** A custom workflow or reusable command belongs in `.claude/skills/<name>/SKILL.md` (with its why/how docs), not in `.claude/commands/`.
- **Exception — genuinely single-file:** If the skill is truly one file with no supporting docs, a `.claude/commands/` entry is fine.
## 10. Database Safety
- **No DB changes without explicit confirmation:** Never apply migrations, `ds push`, schema edits, or any other database mutation until the user explicitly confirms it.
- **Verify before asserting:** Check diagnoses against actual DB rows and git history before stating conclusions — no claims from assumption.

Почему это важно

Без явных правил AI агенты:

  • ❌ Свободно используют any типы
  • ❌ Запускают опасные shell команды
  • ❌ Создают неаккуратные commit messages
  • ❌ Лепят band-aid исправления, не разобравшись в причине
  • ❌ Оставляют решения и отложенную работу недокументированными

С этими правилами:

  • ✅ Консистентный, типобезопасный код
  • ✅ Ограниченные, проверенные операции в shell
  • ✅ Чистая git история по конвенции
  • ✅ Root cause отладка и test-first воркфлоу
  • ✅ Прослеживаемые решения (ADR) и file-based бэклог

Советы по кастомизации

  1. Добавьте project-specific правила в конце
  2. Включите tech stack предпочтения (React, Astro и др.)
  3. Определите forbidden patterns для вашего codebase
  4. Укажите testing frameworks которые используете
  5. На Claude Code включите enforcement — подкрепите жёсткие блоки на деструктив/необратимое через settings.json permissions и PreToolUse hooks. Промпт декларирует intent; hooks делают его обязательным.

Язык ответов

Личный addendum под русскоязычные ответы — не часть универсального ruleset выше. Когда агент отвечает по-русски, добавляю это в CLAUDE.md отдельным блоком:

## Язык ответов
На русском — живой язык; цель естественность, а не русификация любой ценой.
Режущий слух транслит не перевожу натужно на русский, а возвращаю к оригиналу латиницей: «бумпнуть» → bump, «гвард» → guard, «ретраи» → retry.
Устоявшийся профессиональный жаргон оставляю как есть — он разговорный и понятный: пушить, мержить, дебажить, коммит, деплой, токен, провайдер.
Без фанатизма: трогаю только корявый транслит, живую речь — нет.
[ ▲ 0 ]