Подготовка к переходу на 'claude agents' dashboard как daily driver:
- scripts/cleanup-merged-worktrees.sh: removes worktrees whose branch is
ancestor of forgejo/main. Run weekly via cron or manually after merge
bursts. Safe — skips unmerged branches and current worktree.
- .worktreeinclude: copies .env files + .mcp.json into every new worktree
(otherwise backend/frontend/MCP fail to start in fresh worktrees Claude
creates for background sessions).
- .claude/rules/git-pr.md:
- new MANDATORY workflow: default 'claude --bg --name X' background
session (auto worktree, auto baseRef=fresh) vs foreground fallback
- session naming convention (--name kebab-case)
- polling section: preferred (agents view row status ●) vs foreground
fallback (Skill loop)
- new 'Multi-session workflow (Agent View)' section: parallelism budget,
Ctrl+T pin, deprecated 'manual git worktree add', weekly cleanup ref
Local-only (not in this PR):
- .claude/settings.json: worktree.{baseRef:fresh, bgIsolation:worktree}
(gitignored as personal preference)
Pre-cleanup state: 102 worktrees / 14GB. After: 99 / 14GB — only 3 squash-
merged branches removed via safe --is-ancestor check; 99 retained as
unmerged WIP. Aggressive cleanup (by age + Forgejo PR check) — future PR.
140 lines
7.8 KiB
Markdown
140 lines
7.8 KiB
Markdown
---
|
||
paths:
|
||
- .claude/**
|
||
- .github/**
|
||
- .forgejo/**
|
||
---
|
||
|
||
# Git + PR workflow
|
||
|
||
> Этот файл — manual reference из CLAUDE.md (auto-loaded для `.claude/**` и `.github/**` файлов). Если работаешь с code в backend/frontend — также явно открой этот файл при PR-related операциях.
|
||
|
||
## Branch + PR (MANDATORY)
|
||
|
||
**Default workflow — background session через `claude --bg`:**
|
||
|
||
```
|
||
1. claude --bg --name "feat-<scope>" "task description"
|
||
→ supervisor создаёт worktree от forgejo/main автоматически
|
||
(settings worktree.baseRef=default, bgIsolation=git)
|
||
2. Session работает: код → commit → push → mcp__forgejo__create_pull_request
|
||
3. PR URL появляется в agent view как row с зелёной/жёлтой/красной ● status dot
|
||
4. User делает review через external Claude window (post-push)
|
||
5. После merge — `Ctrl+X dwa раза` в agent view = удаление session + worktree
|
||
```
|
||
|
||
**Foreground workflow** (когда нужен интерактив, ad-hoc fixes):
|
||
|
||
```
|
||
1. git fetch forgejo && git checkout -b feat/<scope> forgejo/main
|
||
2. [worker делает код, staged]
|
||
3. code-reviewer subagent на staged changes (pre-push)
|
||
4. main session: git commit -m "feat(scope): ..."
|
||
5. git push -u forgejo feat/<scope>
|
||
6. mcp__forgejo__create_pull_request
|
||
7. Вернуть PR URL пользователю
|
||
```
|
||
|
||
**Никаких direct push в main.** Только через PR merge через Forgejo. `gh` CLI bypassed (2026-05-16) — все PR-операции через `mcp__forgejo__*` или curl + `$FORGEJO_TOKEN`.
|
||
|
||
**Session naming MANDATORY** для background spawn: `--name "<type>-<scope>-<detail>"` (kebab-case, ≤30 chars). Примеры: `feat-tradein-cron`, `fix-nominatim-rate-limit`, `chore-claude-config`. Resume: `claude --resume feat-tradein-cron`. Filter в agent view: type `feat-tradein` в input.
|
||
|
||
## Commit messages
|
||
|
||
- **Conventional**: `feat(scope): ...` / `fix(scope): ...` / `refactor/docs/chore/perf`
|
||
- **Imperative**: "fix crash" не "fixed crash"
|
||
- **Body — почему**, не что (что видно в diff)
|
||
- **NO `Co-Authored-By: Claude ...`** — никогда (~/.claude/CLAUDE.md rule)
|
||
- Workers оставляют staged — main session коммитит
|
||
- **No auto-commit**: написать commit message в чат, user решает когда коммитить
|
||
|
||
## PR body template
|
||
|
||
```markdown
|
||
## Summary
|
||
- bullet
|
||
|
||
## Test plan
|
||
- [ ] smoke test
|
||
|
||
Closes #N
|
||
```
|
||
|
||
Всегда `Closes #N` если есть issue. Комментарий на issue при PR create: "Working on this in PR #M".
|
||
|
||
## Polling loop
|
||
|
||
**Preferred (background session):** dispatch'нул через `claude --bg --name "feat-X"` → session сама делает PR + monitor. В `claude agents` row показывает:
|
||
- 🟡 yellow ● = waiting on checks/review
|
||
- 🟢 green ● = merged
|
||
- 🔴 red ● = checks failed
|
||
- ⚫ grey ● = draft/closed
|
||
|
||
Не нужно отдельный polling loop — supervisor сам обновляет row каждые 15s. Peek (`Space`) для контекста, attach (`Enter`) если нужен fixup.
|
||
|
||
**Foreground fallback** — если работаешь без agents view: `Skill loop` (self-paced, 90-120s) или background Bash poll:
|
||
|
||
1. `mcp__forgejo__get_pull_request` (или `curl -sH "$H" "$REPO/pulls/<N>"`) → читай `state`, `mergeable`, `head.sha`
|
||
2. `state == merged` → stop polling
|
||
3. Новый review/comment: `mcp__forgejo__list_pr_reviews` / `list_issue_comments`. Парсь marker `<!-- gendesign-review-bot: sha=<sha7> verdict=<approve|changes> -->`
|
||
- **SHA guard**: `marker.sha7 == head.sha[:7]` — иначе устаревший approval до fixup-push, игнорируй
|
||
- **Scope guard** (см. ниже): если blocked paths → ping user, не auto-merge
|
||
- `verdict=approve` + SHA match + scope OK → `mcp__forgejo__merge_pull_request` (squash + delete branch)
|
||
- `verdict=changes` → fixup commits + push в `forgejo feat/<scope>` + re-poll
|
||
4. Нет новых comments → re-schedule 60s
|
||
5. **Cap**: 30 iter без resolution → stop, ping user. Blocked-scope cap = 5.
|
||
|
||
## Auto-merge scope
|
||
|
||
**✅ Разрешено** (PR diff целиком в этих путях — bot merge без human):
|
||
- `CLAUDE.md`, `README.md`, `docs/**`
|
||
- `frontend/src/app/**` UI-only без новых endpoints
|
||
- `frontend/public/**`
|
||
- `.claude/agents/**`, `.claude/rules/**`, `memory/feedback_*.md`
|
||
|
||
**❌ Блокировано** (любой файл из списка → human approval):
|
||
- `data/sql/**`, `backend/alembic/versions/**`
|
||
- `backend/app/api/v1/**`, `backend/app/services/**`, `backend/app/scrapers/**`
|
||
- `docker-compose*.yml`, `Caddyfile`, `.github/workflows/**`
|
||
- Любой файл с упоминанием secret / token / password / credential
|
||
- PR меняет `Critical workflow rules` или `Auto-merge scope` в CLAUDE.md
|
||
- PR меняет `Auto-merge scope` / blocked-list в любом `.claude/rules/*.md` (self-extending rules → нужен human)
|
||
|
||
Touches both → more restrictive (block).
|
||
|
||
## Sequential PRs
|
||
|
||
**Одна задача → один PR → merge → следующая.** Параллельно ТОЛЬКО если scope'ы строго orthogonal (разные файлы).
|
||
|
||
Опасные файлы для конфликтов: `backend/app/api/v1/parcels.py`, `frontend/src/types/site-finder.ts`, OverviewTab/LandTab/MarketTab.
|
||
|
||
## Split big issues
|
||
|
||
Issues ≥ 1.5 day → 3-4 sub-PRs: **Foundation → Schema → Workers → Integration**. Каждый ~200-500 lines. PR N+1 только после merge PR N.
|
||
|
||
## Review workflow (no conflict)
|
||
|
||
- **Pre-push** (локально): spawn `code-reviewer` subagent на staged changes → lint pass (security, correctness, conventions). Блокирует push при 🔴 критикал.
|
||
- **Post-push** (внешнее окно Claude): делает review после PR create, постит комменты от `lekss361`. Main session НЕ дублирует — только acting on review comments (fixup commits).
|
||
|
||
## Multi-session workflow (Agent View)
|
||
|
||
**Default daily driver:** одно окно с `claude agents` всегда открыто. Все задачи dispatch'аются оттуда через type prompt + Enter — каждая создаёт background session с собственной worktree.
|
||
|
||
- **Параллелизм**: 3-5 sessions одновременно (>5 = bottleneck на review, не на Claude per Anthropic метрика)
|
||
- **Pin (`Ctrl+T`)** для long-running sessions (scraper monitors, deploy watchers) — supervisor не убьёт через 1h idle
|
||
- **Cleanup**: `Ctrl+X dwa раза` после merge → session + worktree удалены атомарно
|
||
- **NEVER** parallel sessions на one file — каждая ест в own worktree, last-merge wins (используй sequential PR rule выше)
|
||
|
||
**Manual `git worktree add` deprecated** — используй `claude --bg --name X`, supervisor сам isolation делает с `baseRef: default` (свежая ветка от main, не от твоей stale-сессии).
|
||
|
||
**Worktree cleanup** (cron weekly): `scripts/cleanup-merged-worktrees.sh` — удаляет worktrees для merged branches. Запускать вручную или weekly cron.
|
||
|
||
## Запреты
|
||
|
||
- ❌ `git push forgejo main` / direct push в main
|
||
- ❌ `mcp__forgejo__merge_pull_request` без approval (human "merge it" или bot verdict=approve + SHA match)
|
||
- ❌ `gh pr *` — bypassed 2026-05-16, используй Forgejo MCP или curl + `$FORGEJO_TOKEN`
|
||
- ❌ `--no-verify` / `--amend` / `--no-edit` / `--force` без явного approval
|
||
- ❌ `@claude` в PR comments — plain text only (`feedback_no_claude_mentions`)
|
||
- ❌ Параллельные PR на одни файлы (`feedback_sequential_prs`)
|