- Surface Protocol: unified IncomingMessage/OutgoingUI/ChatContext - Telegram: Forum Topics (group + topics per chat) - Matrix: Space + rooms per chat - MockPlatformClient with PlatformClient Protocol - docs: surface-protocol, telegram/matrix specs, api-contract, claude-code-guide - project scaffold: src/, tests/, pyproject.toml Co-Authored-By: Claude Sonnet 4-6 <noreply@anthropic.com>
292 lines
11 KiB
Markdown
292 lines
11 KiB
Markdown
# Гайд по Claude Code для разработки surfaces-bot
|
||
|
||
## Что такое Claude Code
|
||
|
||
Claude Code — это CLI-инструмент который запускается в терминале внутри твоего
|
||
проекта. Он читает файлы, пишет код, запускает команды. Главное отличие от
|
||
чата — он видит весь проект и действует автономно.
|
||
|
||
Запускается так:
|
||
```bash
|
||
cd surfaces-bot
|
||
claude "твоя задача"
|
||
```
|
||
|
||
---
|
||
|
||
## Агенты и когда их использовать
|
||
|
||
В проекте настроены специализированные агенты в `.claude/agents/`.
|
||
Claude Code сам выбирает нужного если ты пишешь `@имя` в запросе.
|
||
|
||
| Агент | Когда | Пример |
|
||
|---|---|---|
|
||
| `@researcher` | Нужно разобраться как что-то работает | "как работает Forum Topics в aiogram?" |
|
||
| `@architect` | Нужно принять архитектурное решение | "как хранить маппинг chat_id → room_id?" |
|
||
| `@core-developer` | Писать core/ и platform/ | "реализуй core/protocol.py" |
|
||
| `@tg-developer` | Писать Telegram-адаптер | "реализуй обработчик /start" |
|
||
| `@matrix-developer` | Писать Matrix-адаптер | "реализуй создание Space" |
|
||
| `@reviewer` | Проверить код перед PR | "проверь adapter/telegram/" |
|
||
|
||
---
|
||
|
||
## Базовые команды
|
||
|
||
### Простая задача (без агента)
|
||
```bash
|
||
# Небольшое изменение — быстрее без агента
|
||
claude "добавь поле platform_user_id в ChatContext в core/protocol.py"
|
||
```
|
||
|
||
### Задача через агента
|
||
```bash
|
||
# Агент читает нужную документацию сам
|
||
claude "Use @tg-developer to implement adapter/telegram/handlers/auth.py
|
||
based on docs/telegram-prototype.md auth flow"
|
||
```
|
||
|
||
### Вопрос без изменений
|
||
```bash
|
||
claude "объясни как работает m.space.child в Matrix"
|
||
# или просто интерактивно:
|
||
claude # запускает интерактивный режим
|
||
```
|
||
|
||
---
|
||
|
||
## Параллельная разработка двух ботов
|
||
|
||
Главная идея: два терминала, два worktree, два агента одновременно.
|
||
|
||
### Шаг 1 — инициализация (один раз)
|
||
```bash
|
||
cd surfaces-bot
|
||
git init
|
||
git add . && git commit -m "init"
|
||
|
||
# Создать worktrees для адаптеров
|
||
git worktree add .worktrees/telegram -b feat/telegram-adapter
|
||
git worktree add .worktrees/matrix -b feat/matrix-adapter
|
||
```
|
||
|
||
### Шаг 2 — сначала ядро (в main)
|
||
```bash
|
||
# В основной папке — core/ должен быть готов до адаптеров
|
||
claude "Use @core-developer to implement core/protocol.py and platform/interface.py
|
||
and platform/mock.py based on docs/surface-protocol.md and docs/api-contract.md"
|
||
```
|
||
Дождись — это фундамент. Остальное на нём строится.
|
||
|
||
### Шаг 3 — параллельно адаптеры (два терминала)
|
||
|
||
**Терминал 1:**
|
||
```bash
|
||
cd .worktrees/telegram
|
||
claude "Use @tg-developer to implement the auth flow from docs/telegram-prototype.md.
|
||
Start with adapter/telegram/handlers/auth.py and adapter/telegram/states.py"
|
||
```
|
||
|
||
**Терминал 2 (одновременно):**
|
||
```bash
|
||
cd .worktrees/matrix
|
||
claude "Use @matrix-developer to implement the auth flow from docs/matrix-prototype.md.
|
||
Start with adapter/matrix/handlers/auth.py and adapter/matrix/space.py"
|
||
```
|
||
|
||
Они работают в разных папках — не мешают друг другу.
|
||
|
||
### Шаг 4 — смёрджить когда готово
|
||
```bash
|
||
cd surfaces-bot # вернуться в main
|
||
git merge feat/telegram-adapter
|
||
git merge feat/matrix-adapter
|
||
```
|
||
|
||
---
|
||
|
||
## Экономия токенов (важно для Pro)
|
||
|
||
### Правило 1: Haiku для исследований
|
||
```bash
|
||
# @researcher использует Haiku — дёшево
|
||
claude "Use @researcher to find examples of aiogram Forum Topics creation with code samples.
|
||
Save findings to docs/research/telegram-forum-topics.md"
|
||
|
||
# НЕ делай так (Sonnet на простой вопрос — дорого):
|
||
claude "Use @tg-developer to research how Forum Topics work"
|
||
```
|
||
|
||
### Правило 2: точный контекст
|
||
```bash
|
||
# Хорошо — агент читает один конкретный файл
|
||
claude "Use @tg-developer to implement adapter/telegram/keyboards/settings.py.
|
||
Read docs/telegram-prototype.md section 'Настройки' for the button structure"
|
||
|
||
# Плохо — агент читает весь проект зря
|
||
claude "Use @tg-developer to implement keyboards"
|
||
# (агент начнёт читать всё подряд)
|
||
```
|
||
|
||
### Правило 3: не запускай ревью на каждый коммит
|
||
```bash
|
||
# Ревью — только перед merge в main
|
||
claude "Use @reviewer to review all changes in adapter/telegram/ before merging"
|
||
# НЕ после каждого файла
|
||
```
|
||
|
||
### Правило 4: маленькие задачи без агента
|
||
```bash
|
||
# Просто правка — без агента быстрее и дешевле
|
||
claude "в adapter/telegram/keyboards/confirm.py замени текст кнопки с 'Да' на '✅ Подтвердить'"
|
||
```
|
||
|
||
### Правило 5: не больше двух Sonnet одновременно
|
||
```bash
|
||
# Можно (Haiku + Sonnet):
|
||
# Терминал 1: claude "Use @researcher ..." ← Haiku
|
||
# Терминал 2: claude "Use @tg-developer ..." ← Sonnet
|
||
|
||
# Можно (два Sonnet в разных worktrees):
|
||
# Терминал 1: cd .worktrees/telegram && claude "Use @tg-developer ..."
|
||
# Терминал 2: cd .worktrees/matrix && claude "Use @matrix-developer ..."
|
||
|
||
# Слишком много (три Sonnet):
|
||
# Терминал 1: claude "Use @core-developer ..."
|
||
# Терминал 2: claude "Use @tg-developer ..."
|
||
# Терминал 3: claude "Use @matrix-developer ..." ← стоп, подожди
|
||
```
|
||
|
||
---
|
||
|
||
## Типичные сценарии с примерами
|
||
|
||
### Сценарий А: начало с нуля
|
||
|
||
```bash
|
||
# 1. Исследование (Haiku, дёшево)
|
||
claude "Use @researcher to find matrix-nio examples of Space creation and room management.
|
||
Save to docs/research/matrix-spaces.md"
|
||
|
||
# 2. Уточнение архитектуры (если что-то неясно)
|
||
claude "Use @architect to clarify: should ConfirmationRequest timeout be handled in
|
||
core/handler.py or in each adapter separately? Update docs/surface-protocol.md"
|
||
|
||
# 3. Ядро
|
||
claude "Use @core-developer to implement core/protocol.py based on docs/surface-protocol.md"
|
||
claude "Use @core-developer to implement core/session.py and core/auth.py"
|
||
claude "Use @core-developer to implement platform/interface.py and platform/mock.py
|
||
based on docs/api-contract.md"
|
||
|
||
# 4. Адаптеры параллельно (два терминала)
|
||
# T1: claude "Use @tg-developer to implement auth flow in adapter/telegram/"
|
||
# T2: claude "Use @matrix-developer to implement auth flow in adapter/matrix/"
|
||
```
|
||
|
||
### Сценарий Б: добавить новую фичу в оба бота
|
||
|
||
Например, команда `!status` / `/status`:
|
||
|
||
```bash
|
||
# 1. Убедиться что в core есть нужные структуры
|
||
claude "Use @architect to check if StatusRequest is needed in core/protocol.py
|
||
or can reuse existing structures. Read docs/surface-protocol.md"
|
||
|
||
# 2. Добавить в core если нужно
|
||
claude "Use @core-developer to add status handling in core/handler.py"
|
||
|
||
# 3. Оба адаптера параллельно
|
||
# T1: claude "Use @tg-developer to implement /status command in
|
||
# adapter/telegram/handlers/settings.py"
|
||
# T2: claude "Use @matrix-developer to implement !status command in
|
||
# adapter/matrix/handlers/settings.py"
|
||
```
|
||
|
||
### Сценарий В: что-то сломалось
|
||
|
||
```bash
|
||
# Диагностика — без агента, просто спроси
|
||
claude "pytest tests/adapter/telegram/test_auth.py провалился с ошибкой:
|
||
AttributeError: 'NoneType' has no attribute 'session_id'
|
||
Посмотри core/session.py и adapter/telegram/handlers/auth.py и скажи в чём причина"
|
||
|
||
# Починить точечно
|
||
claude "в core/session.py метод get_session возвращает None если сессия не найдена,
|
||
но в adapter/telegram/handlers/auth.py это не обрабатывается — исправь"
|
||
```
|
||
|
||
### Сценарий Г: ревью перед merge
|
||
|
||
```bash
|
||
# Запускать только когда фича готова
|
||
cd .worktrees/telegram
|
||
claude "Use @reviewer to review all files changed in this worktree (adapter/telegram/).
|
||
Check against docs/telegram-prototype.md and docs/surface-protocol.md"
|
||
```
|
||
|
||
---
|
||
|
||
## Интерактивный режим
|
||
|
||
Когда нужно работать итеративно — запусти без задачи:
|
||
|
||
```bash
|
||
cd surfaces-bot
|
||
claude
|
||
```
|
||
|
||
Откроется REPL. Можно:
|
||
```
|
||
> покажи структуру core/protocol.py
|
||
> добавь поле metadata в IncomingMessage
|
||
> запусти pytest и покажи результат
|
||
> что изменилось в последних 3 коммитах?
|
||
```
|
||
|
||
Полезно когда задача неясная или нужно исследовать.
|
||
|
||
---
|
||
|
||
## Флаги которые пригодятся
|
||
|
||
```bash
|
||
# Работать в конкретном worktree
|
||
cd .worktrees/telegram && claude "..."
|
||
|
||
# Не трогать файлы, только смотреть (безопасно)
|
||
claude --no-write "объясни как работает converter.py"
|
||
|
||
# Продолжить предыдущую сессию
|
||
claude --continue
|
||
|
||
# Запустить с конкретной моделью (если хочешь Haiku без @researcher)
|
||
claude --model claude-haiku-4-5-20251001 "быстрый вопрос про aiogram"
|
||
```
|
||
|
||
---
|
||
|
||
## Частые ошибки
|
||
|
||
**Агент начал читать весь проект** → прерви (Ctrl+C), переформулируй точнее:
|
||
```bash
|
||
# Плохо
|
||
claude "Use @tg-developer to implement settings"
|
||
|
||
# Хорошо
|
||
claude "Use @tg-developer to implement adapter/telegram/keyboards/settings.py —
|
||
кнопки главного меню настроек из docs/telegram-prototype.md раздел 'Главное меню настроек'"
|
||
```
|
||
|
||
**Агент пишет не в ту папку** → явно укажи путь:
|
||
```bash
|
||
claude "Use @matrix-developer to create adapter/matrix/space.py with SpaceManager class"
|
||
```
|
||
|
||
**Кончились токены в середине задачи** → задача сохраняется частично, продолжи:
|
||
```bash
|
||
claude --continue "продолжи реализацию, остановился на методе create_chat"
|
||
```
|
||
|
||
**Агент предлагает архитектурное решение вместо кода** → перенаправь:
|
||
```bash
|
||
claude "Use @architect to decide: [вопрос]. После решения Use @tg-developer to implement it"
|
||
```
|