Шпаргалка по Claude Code: CLAUDE.md, хуки, скиллы, MCP и режимы
Краткий справочник по Claude Code: CLAUDE.md, промпты, правила, хуки, скиллы, MCP, сабагенты, worktree, режимы разрешений, основные команды и промпты, которые стоит сохранить.
Claude Code — агентный помощник Anthropic для программирования. Он умеет не только писать фрагменты кода. Он может:
- Разобраться в существующей кодовой базе
- Читать и править несколько файлов сразу
- Запускать команды в терминале
- Писать тесты и запускать их
- Находить ошибки
- Рефакторить код
- Работать с Git
- Вызывать инструменты MCP и запускать хуки
- Передавать работу сабагентам
- Делать фичи по инструкциям, написанным обычным языком
Базовая модель
You
↓
Natural-language prompt
↓
Claude Code
↓
Understand codebase
↓
Plan
↓
Read files
↓
Modify code
↓
Run tests / commands
↓
Review result
↓
Iterate
Три термина легко спутать. Claude — это ИИ-модель и ассистент Anthropic: понимает естественный язык, рассуждает, работает с кодом и документами и берётся за множество задач. Claude Code — агентный инструмент для разработки, который позволяет Claude работать с кодовой базой, файлами, командами терминала, тестами, Git и внешними инструментами, чтобы доводить задачи до конца. ИИ-агент — любая система, которая понимает цель, планирует шаги, пользуется инструментами, действует, проверяет результат и повторяет, пока задача не решена. Одну схему стоит запомнить:
🤖 CLAUDE
│
↓
CLAUDE CODE
│
┌──────┴──────┐
↓ ↓
PROMPT RULES
"Do this" "Follow this"
│ │
└──────┬──────┘
↓
AGENT
│
┌─────────────┼─────────────┐
↓ ↓ ↓
Commands Skills Tools
│ │ │
↓ ↓ ↓
/help etc. Reusable Terminal
capability Git
Files
│
┌──────────┴──────────┐
↓ ↓
MCP HOOKS
↓ ↓
External tools Automatic actions
│
↓
SUB-AGENTS
↓
Delegated tasks
│
↓
WORKTREES
↓
Isolated Git work
Команды
В Claude Code есть набор встроенных слэш-команд, и учить их проще всего по его собственному списку команд.
CLAUDE.md
CLAUDE.md — файл с инструкциями для проекта. Он даёт Claude Code контекст конкретного проекта, команды, заметки об архитектуре и правила написания кода, так что считайте его справочником проекта для Claude.
CLAUDE.md
Project:
Android banking application
Architecture:
Clean Architecture + MVVM
Modules:
app
core
network
database
feature-login
Commands:
./gradlew test
./gradlew lint
Rules:
- Use Kotlin
- Use Coroutines
- Use existing centralized utilities
- Add tests for new functionality
- Don't duplicate networking code
Польза в том, что указания сохраняются между сессиями, и разработчикам не приходится снова и снова объяснять архитектуру, команды, соглашения и правила.
Промпты
Промпт — инструкция на естественном языке, которая объясняет ИИ задачу или цель. Хороший агентный промпт сначала заставляет разобраться, а потом уже что-то менять:
First investigate the existing authentication flow.
Do not modify anything yet.
Explain:
- frontend flow
- backend flow
- API involved
- relevant files
- likely problem
Then propose a fix.
After approval, implement it, test it,
review the diff, and commit the changes.
Правила
Правила — это ограничения или указания, определяющие, как агент выполняет задачу. В больших проектах инструкции можно разбить по темам внутри .claude/rules/:
.claude/rules/
├── testing.md
├── security.md
├── frontend.md
├── backend.md
└── android.md
Файл с правилами может выглядеть так:
Rules:
- Use Kotlin.
- Follow MVVM.
- Do not create duplicate utility functions.
- Reuse existing components.
- Write tests for new functionality.
- Do not modify unrelated modules.
- Never expose secrets.
- Run lint before committing.
Хуки
Хук — автоматическое действие, которое срабатывает на определённое событие, например запуск команды или проверки после конкретного действия агента. Хуки добавляют в работу агента автоматизацию, единообразие и страховку. Что-то произошло — действие выполняется само. Например:
Before build
↓
HOOK
↓
Check:
- formatting
- lint
- dependencies
- tests
↓
Build
В реальном проекте хуки могут лежать в такой папке:
.claude/
└── hooks/
│
├── lint
├── test
├── dependency-check
├── security-check
└── pre-build
Скиллы
Скиллы — это переиспользуемые специализированные сценарии или инструкции, разложенные по темам:
.claude/skills/
├── android-development/
├── compose-ui/
├── kotlin-testing/
├── api-integration/
└── code-review/
Каждый скилл — короткий документ, например такой:
Android Development Skill
When modifying Android code:
- Use Kotlin
- Follow MVVM
- Use Coroutines
- Use StateFlow
- Follow existing architecture
- Add tests
- Run lint
- Avoid duplicate utilities
MCP
MCP (Model Context Protocol) — стандартный протокол, через который ИИ-приложения подключаются к внешним инструментам и источникам данных.
Сабагенты
Сабагенты — специализированные агенты, которым основной агент может поручить части большой задачи, чтобы сложную работу можно было разделить:
Main Agent
│
┌────────────┼────────────┐
↓ ↓ ↓
Sub-agent Sub-agent Sub-agent
Backend Security Tests
│ │ │
└────────────┼────────────┘
↓
Main Agent
↓
Final result
Git worktree
Git worktree даёт несколько рабочих каталогов, привязанных к разным веткам, так что несколько задач могут двигаться независимо:
Git Repository
│
┌────────────┼────────────┐
↓ ↓ ↓
Worktree A Worktree B Worktree C
Feature A Feature B Bug Fix
Для ИИ-агентов это удобно: два агента могут заниматься разными задачами и не толкаться постоянно в одном рабочем каталоге. Worktree — изолированное рабочее пространство для работы с Git.
Режимы разрешений
В Claude Code есть режимы разрешений, которые определяют, насколько свободно Claude пользуется инструментами:
┌──────────────────────────────────────────────────────────┐
│ CLAUDE CODE MODES │
├──────────────┬───────────────────────────────────────────┤
│ 🖐 MANUAL │ Claude asks for approval before actions │
│ │ or changes. You stay in control. │
├──────────────┼───────────────────────────────────────────┤
│ ✏️ EDIT │ Claude can edit the selected text/file │
│ │ or make the requested code changes. │
├──────────────┼───────────────────────────────────────────┤
│ 📋 PLAN │ Claude explores the codebase, analyzes │
│ │ the problem and presents a plan BEFORE │
│ │ making edits. │
├──────────────┼───────────────────────────────────────────┤
│ ⚡ AUTO │ Claude can take actions automatically │
│ │ and automatically check/continue through │
│ │ the task. │
└──────────────┴───────────────────────────────────────────┘
Какой режим выбрать, зависит от того, сколько надзора требует задача.
README.md и CLAUDE.md
README.md описывает проект для людей, а CLAUDE.md содержит инструкции и контекст специально для Claude Code.
/clear и /compact
/clear полностью очищает контекст текущего разговора. /compact делает из него сжатое резюме, чтобы работа продолжалась с меньшим контекстом.
@file
@file ссылается на конкретный файл и передаёт его содержимое Claude как контекст для задачи.
Шорткат #
Префикс # — быстрый способ добавить инструкции или память, относящиеся к проекту.
Зачем нужны тесты в агентной разработке
Агент вносит в кодовую базу настоящие изменения. Тесты показывают ему, работают ли эти изменения, и помогают находить и исправлять сбои.
Итоговая шпаргалка
Claude
→ Anthropic's AI model/assistant
Claude Code
→ Agentic coding tool
Agent
→ AI that can reason + use tools + take actions
Prompt
→ What I ask it to do
Rules
→ Constraints it must follow
CLAUDE.md
→ Project handbook/instructions
Commands
→ Special controls like /help, /init, /clear, /compact
Hooks
→ Automatic actions triggered by events
Skills
→ Reusable specialized capabilities/instructions
Templates
→ Predefined reusable structure
MCP
→ Connect Claude to external tools/data
Sub-agents
→ Specialized agents delegated work
Worktrees
→ Separate Git workspaces
README.md
→ Human project documentation
CLAUDE.local.md
→ Local/personal project instructions
where that convention is used
audit_summary.md
→ Usually custom audit report
clone.md
→ Usually custom setup/clone documentation
push_to_github.sh
→ Usually custom Git automation script
push_now.md
→ Usually custom push checklist
Универсальные промпты, которые стоит сохранить
Общий стартовый промпт для незнакомого приложения:
I am new to this application.
Do not modify anything.
Give me a high-level overview of the application.
Explain:
- What the application does
- Main features
- Main technologies
- Project structure
- Modules
- Important packages
- Architecture
- Main entry points
- External services
- Database
- APIs
- Testing
- Build and deployment process
Start with a simple explanation for a developer who is new to this project.
Чтобы разобраться в архитектуре:
Analyze the architecture of this application.
Do not modify anything.
Explain:
- Architecture pattern
- Modules
- Layers
- Dependency flow
- Data flow
- API layer
- Business layer
- Data layer
- UI layer
Identify the main architectural patterns being used.
Then draw an architecture diagram.
Чтобы найти главные точки входа:
Identify the main entry points of this application.
For each entry point, explain:
- File
- Class/function
- What triggers it
- What it calls next
- Where the request eventually ends
Create a simple flow diagram.
Чтобы Claude всё протестировал:
Analyze the changes made in this task.
Identify all relevant tests.
Run:
- Unit tests
- Integration tests
- UI tests where applicable
- Lint
- Type checks
- Build
If anything fails:
- investigate the root cause
- fix it
- rerun the failing checks
At the end, give me a summary of:
PASS / FAIL / NOT RUN
Playwright через MCP
Для автоматизации браузера попросите Claude использовать настроенный MCP-сервер Playwright.
Use the Playwright MCP server.
Open the application in the browser.
Visit the login page.
Take a screenshot.
Then:
1. Enter the test credentials.
2. Click Login.
3. Verify that the dashboard appears.
4. Navigate to [PAGE].
5. Click [LINK/BUTTON].
6. Take screenshots at the important steps.
7. Report any errors or unexpected behavior.
Do not modify the application.
Десять промптов стоит выучить наизусть:
① OVERVIEW
"Give me an overview of this application."
② STRUCTURE
"Explain the project structure and important files."
③ FLOW
"Trace a user's query from frontend to backend and draw a diagram."
④ DOCUMENT
"Trace how a document is processed from upload to final answer."
⑤ RUN
"How do I run, test, lint and build this application?"
⑥ PLAN
"Analyze the existing implementation and create a plan before editing."
⑦ IMPLEMENT
"Implement this feature, reuse existing code, test it and review the diff."
⑧ DEBUG
"Reproduce this error, find the root cause, fix it and add a regression test."
⑨ UI
"Use Playwright MCP to test the user flow and take screenshots."
⑩ GIT
"Review the diff, run checks, resolve conflicts if needed, and commit."