К основному содержанию
команда

hotfix — команда для Claude Code: что делает и как установить

Создаёт ветку Git Flow hotfix от main для срочных исправлений в продакшене. Перед стартом проверяет имя ветки и чистоту рабочей директории.

Установить в Claude Code · Через claude-code-templates Все способы и платформы ↓
npx claude-code-templates@latest --command git/hotfix
Открыть на GitHub

Что делает hotfix

Слэш-команда собирает сведения о репозитории: текущую ветку, статус Git, последний тег на origin/main, состояние main и число коммитов после последнего тега. Затем проверяет имя hotfix, наличие main, отсутствие незакоммиченных изменений и критичность проблемы.

После проверок команда переключается на main, выполняет git pull origin main, создаёт hotfix/<hotfix-name> и отправляет её в удалённый репозиторий с отслеживанием. Она также предлагает увеличить PATCH-версию, например с v1.2.0 до v1.2.1, и напоминает о проверках, changelog и слиянии в main и develop.

Без чистой рабочей директории команда не создаст hotfix. Имя нужно передать аргументом в kebab-case и связать с конкретной критичной проблемой: у команды есть отдельные проверки для пустого или слишком общего имени.

Какие задачи решает

  • создать hotfix-ветку от main
  • проверить чистоту рабочей директории
  • синхронизировать main с origin/main
  • подготовить PATCH-версию для выпуска
  • передать ветку в удалённый репозиторий

Примеры запросов агенту

  • Создай hotfix-ветку для критичной уязвимости: /hotfix critical-security-patch.
  • Подготовь ветку для сбоя платежей: /hotfix payment-gateway-fix.
  • Проверь репозиторий и создай hotfix для повреждения данных: /hotfix user-data-corruption-fix.

Как установить hotfix

1Через claude-code-templates

npx claude-code-templates@latest --command git/hotfix

2Вручную: положить файлы

.claude/commands/hotfix.md

Вызов — /hotfix. Для всех проектов — ~/.claude/commands/

Вопросы о hotfix

Как установить hotfix в Claude Code?

Выполните npx claude-code-templates@latest --command git/hotfix, затем используйте файл .claude/commands/hotfix.md.

Что делает команда hotfix?

Она проверяет репозиторий и создаёт ветку hotfix/<hotfix-name> от актуального main, после чего отправляет её в origin. Команда также предлагает PATCH-версию и шаги для срочного исправления.

Какие изменения нужны перед запуском hotfix?

Рабочая директория должна быть чистой, ветка main должна существовать, а имя hotfix нужно передать в описательном формате kebab-case. Команда предназначена для критичных проблем в продакшене.

Исходный текст

hotfix.md · MIT
---
allowed-tools: Bash(git:*), Read, Edit, Write
argument-hint: <hotfix-name>
description: Create a new Git Flow hotfix branch from main for emergency production fixes
---

# Git Flow Hotfix Branch

Create emergency hotfix branch: **$ARGUMENTS**

## Current Repository State

- Current branch: !`git branch --show-current`
- Git status: !`git status --porcelain`
- Latest production tag: !`git describe --tags --abbrev=0 origin/main 2>/dev/null || echo "No tags on main"`
- Main branch status: !`git log main..origin/main --oneline 2>/dev/null | head -3 || echo "No remote tracking for main"`
- Commits on main since last tag: !`git log $(git describe --tags --abbrev=0 origin/main 2>/dev/null)..origin/main --oneline 2>/dev/null | wc -l | tr -d ' '`

## Task

Create a Git Flow hotfix branch for emergency production fixes:

### 1. Pre-Flight Validation

**Critical Checks:**
- **Verify hotfix name**: Ensure `$ARGUMENTS` is provided and descriptive
  - ✅ Valid: `critical-security-patch`, `payment-gateway-fix`, `auth-bypass-fix`
  - ❌ Invalid: `fix`, `hotfix1`, `bug`
- **Check main branch exists**: Ensure `main` branch is present
- **Verify no uncommitted changes**: Clean working directory required
- **Confirm emergency status**: Hotfixes are for CRITICAL production issues only

**⚠️ IMPORTANT: Hotfix Usage Guidelines**

Hotfixes are ONLY for:
- 🔒 Critical security vulnerabilities
- 💥 Production-breaking bugs
- 💰 Payment/transaction failures
- 🚨 Data loss or corruption issues
- 🔥 System downtime or crashes

NOT for:
- ❌ Regular bug fixes (use feature branch)
- ❌ New features (use feature branch)
- ❌ Performance improvements (use feature branch)
- ❌ Non-critical issues (wait for next release)

### 2. Create Hotfix Branch Workflow

```bash
# Switch to main branch
git checkout main

# Pull latest production code
git pull origin main

# Create hotfix branch from main
git checkout -b hotfix/$ARGUMENTS

# Set up remote tracking
git push -u origin hotfix/$ARGUMENTS
```

### 3. Determine Version Bump

Analyze the latest tag to suggest hotfix version:

```
Current production version: v1.2.0
Hotfix version: v1.2.1

Version bump: PATCH (third number incremented)
```

**Hotfix Version Rules:**
- Always increment PATCH version (X.Y.Z → X.Y.Z+1)
- Never increment MAJOR or MINOR for hotfixes
- Examples:
  - v1.2.0 → v1.2.1
  - v2.0.5 → v2.0.6
  - v1.5.9 → v1.5.10

### 4. Success Response

```
✓ Switched to main branch
✓ Pulled latest production code from origin/main
✓ Created branch: hotfix/$ARGUMENTS
✓ Set up remote tracking: origin/hotfix/$ARGUMENTS
✓ Pushed branch to remote

🔥 Hotfix Branch Ready: hotfix/$ARGUMENTS

Branch: hotfix/$ARGUMENTS
Base: main (production)
Will merge to: main AND develop
Suggested version: v1.2.1

⚠️ CRITICAL HOTFIX WORKFLOW

This is an EMERGENCY production fix. Follow these steps:

1. 🔍 Identify the Issue
   - Reproduce the bug
   - Understand the root cause
   - Document the impact

2. 🛠️ Implement the Fix
   - Make MINIMAL changes
   - Focus ONLY on the critical issue
   - Avoid refactoring or improvements
   - Add tests to prevent regression

3. 🧪 Test Thoroughly
   - Test the specific fix
   - Run full regression tests
   - Test on production-like environment
   - Verify no side effects

4. 📝 Document the Fix
   - Update version in package.json
   - Add entry to CHANGELOG.md
   - Document the bug and fix
   - Include reproduction steps

5. 🚀 Deploy Process
   - Create PR to main
   - Get expedited review
   - Run /finish to merge and tag
   - Deploy to production immediately
   - Monitor for issues

🎯 Next Steps:
1. Fix the critical issue (MINIMAL changes only)
2. Test thoroughly: npm test
3. Update version: v1.2.1
4. Create emergency PR: gh pr create --label "hotfix,critical"
5. Get fast-track approval
6. Run /finish to merge to main AND develop
7. Deploy to production
8. Monitor systems closely

⚠️ Remember:
- Hotfix will be merged to BOTH main and develop
- Tag v1.2.1 will be created on main
- Production deployment should happen immediately
- Team should be notified of the hotfix
```

### 5. Error Handling

**No Hotfix Name Provided:**
```
❌ Hotfix name is required

Usage: /hotfix <hotfix-name>

Examples:
  /hotfix critical-security-patch
  /hotfix payment-processing-failure
  /hotfix auth-bypass-vulnerability

⚠️ IMPORTANT: Hotfixes are for CRITICAL production issues only!

For non-critical fixes, use:
  /feature <name> - Regular bug fixes
```

**Invalid Hotfix Name:**
```
❌ Invalid hotfix name: "fix"

Hotfix names should be:
- Descriptive of the issue
- Use kebab-case format
- Indicate severity/urgency

Examples:
  ✅ critical-security-patch
  ✅ payment-gateway-timeout
  ✅ user-data-corruption-fix
  ❌ fix
  ❌ bug1
  ❌ hotfix
```

**Uncommitted Changes:**
```
⚠️  Uncommitted changes detected in working directory:
M  src/file.js
A  test.js

Hotfixes require a clean working directory.

Options:
1. Commit your changes first
2. Stash them: git stash
3. Discard them: git checkout .

⚠️ This is an emergency hotfix. Please clean your working directory.
```

**Main Branch Behind Remote:**
```
⚠️  Local main is behind origin/main by 2 commits

✓ Pulling latest production code...
✓ Fetched 2 commits
✓ Main is now synchronized with production
✓ Ready to create hotfix branch
```

**Not a Critical Issue:**
```
⚠️  Hotfix Confirmation Required

Is this a CRITICAL production issue that requires immediate attention?

Critical issues include:
- Security vulnerabilities
- Production system failures
- Data loss or corruption
- Payment/transaction failures

If this is NOT critical, consider:
- Creating a feature branch instead
- Waiting for the next release cycle
- Using regular bug fix workflow

Proceed with hotfix? [y/N]
```

### 6. Hotfix Checklist

```
🔥 Emergency Hotfix Checklist

Issue Identification:
- [ ] Bug is confirmed and reproducible
- [ ] Root cause is identified
- [ ] Impact is documented
- [ ] Stakeholders are notified

Development:
- [ ] Fix is minimal and focused
- [ ] No unnecessary changes included
- [ ] Tests added to prevent regression
- [ ] Code reviewed (if time permits)

Testing:
- [ ] Fix verified in local environment
- [ ] Unit tests passing
- [ ] Integration tests passing
- [ ] Tested on production-like environment
- [ ] No side effects detected

Documentation:
- [ ] CHANGELOG.md updated
- [ ] Version bumped (PATCH)
- [ ] Bug description documented
- [ ] Fix explanation documented
- [ ] Deployment notes prepared

Deployment:
- [ ] PR created with "hotfix" and "critical" labels
- [ ] Fast-track approval obtained
- [ ] Production deployment plan ready
- [ ] Rollback plan documented
- [ ] Monitoring alerts configured
- [ ] Team notified of deployment

Post-Deployment:
- [ ] Fix verified in production
- [ ] Systems monitored for issues
- [ ] Metrics show improvement
- [ ] Hotfix merged back to develop
- [ ] Post-mortem scheduled (if needed)
```

### 7. Version Update Process

After implementing the fix, update the version:

```bash
# Update package.json version (PATCH bump)
npm version patch --no-git-tag-version

# Update CHANGELOG.md
cat >> CHANGELOG.md << EOF

## [v1.2.1] - $(date +%Y-%m-%d) - HOTFIX

### 🔥 Critical Fixes
- Fix $ARGUMENTS: [brief description]
  - Root cause: [explanation]
  - Impact: [who/what was affected]
  - Resolution: [what was fixed]

EOF

# Commit version bump
git add package.json CHANGELOG.md
git commit -m "chore(hotfix): bump version to v1.2.1

Critical fix for $ARGUMENTS

🤖 Generated with Claude Code
Co-Authored-By: Claude <[email protected]>"
```

### 8. Create Emergency PR

```bash
gh pr create \
  --title "🔥 HOTFIX v1.2.1: $ARGUMENTS" \
  --body "$(cat <<'EOF'
## 🔥 Emergency Hotfix

**Severity**: Critical
**Version**: v1.2.1
**Issue**: $ARGUMENTS

## Problem Description

[Detailed description of the production issue]

## Root Cause

[Explanation of what caused the issue]

## Fix Implementation

[Description of the fix applied]

## Testing

- [x] Issue reproduced locally
- [x] Fix verified locally
- [x] Unit tests passing
- [x] Integration tests passing
- [x] Tested on staging environment

## Deployment Plan

1. Merge to main
2. Tag as v1.2.1
3. Deploy to production immediately
4. Monitor for 30 minutes
5. Merge back to develop

## Rollback Plan

[How to rollback if issues occur]

## Monitoring

[What to monitor post-deployment]

---

**⚠️ This is a critical production hotfix requiring immediate deployment**

🤖 Generated with Claude Code
EOF
)" \
  --base main \
  --head hotfix/$ARGUMENTS \
  --label "hotfix,critical,priority-high" \
  --assignee @me \
  --reviewer team-leads
```

## Git Flow Integration

**Hotfix Workflow in Git Flow:**

```
main (v1.2.0) ──────┬─────────────► (after hotfix merge) v1.2.1
                    │
                    └─► hotfix/$ARGUMENTS
                         │
                         └─► (merges back to both)
                             │
develop ────────────────────┴─────────────► (receives hotfix)
```

**Important:**
- Hotfixes branch from `main` (production)
- Hotfixes merge to BOTH `main` AND `develop`
- Tags are created on `main` after merge
- Production deployment happens immediately

## Environment Variables

- `GIT_FLOW_MAIN_BRANCH`: Main branch name (default: "main")
- `GIT_FLOW_DEVELOP_BRANCH`: Develop branch name (default: "develop")
- `GIT_FLOW_PREFIX_HOTFIX`: Hotfix prefix (default: "hotfix/")

## Related Commands

- `/finish` - Complete hotfix (merge to main and develop, create tag, deploy)
- `/flow-status` - Check current Git Flow status
- `/feature <name>` - Create feature branch (for non-critical fixes)
- `/release <version>` - Create release branch

## Best Practices

**DO:**
- ✅ Use hotfixes ONLY for critical production issues
- ✅ Keep changes minimal and focused
- ✅ Test thoroughly before deploying
- ✅ Document the issue and fix clearly
- ✅ Notify team immediately
- ✅ Merge back to develop after production deployment
- ✅ Monitor production closely after deployment
- ✅ Conduct post-mortem if appropriate

**DON'T:**
- ❌ Use hotfix for regular bug fixes
- ❌ Add new features to hotfix
- ❌ Refactor code during hotfix
- ❌ Skip testing to save time
- ❌ Forget to merge back to develop
- ❌ Deploy without proper review
- ❌ Skip documentation
- ❌ Ignore monitoring after deployment

## Post-Hotfix Actions

After successful hotfix deployment:

1. **Verify Fix in Production**
   - Monitor error rates
   - Check affected functionality
   - Verify metrics return to normal

2. **Update Documentation**
   - Document the incident
   - Update runbooks if needed
   - Share learnings with team

3. **Merge to Develop**
   - Ensure hotfix is in develop branch
   - Resolve any merge conflicts
   - Push to remote

4. **Post-Mortem (if needed)**
   - Schedule review meeting
   - Identify prevention measures
   - Update processes if needed

5. **Cleanup**
   - Delete hotfix branch
   - Archive related documentation
   - Update incident tracking

© davila7 · MIT · davila7/claude-code-templates

Похожие слэш-команды

Все слэш-команды по теме «Git и GitHub» →
code-review официальный Anthropic Команда проводит многоэтапное ревью pull request через утилиту gh. Она фильтрует ложные срабатывания и сверяет правки с правилами CLAUDE.md. 5 537установок commit официальный Anthropic Создаёт коммит в git на основе текущих изменений в ветке. Помогает зафиксировать правки без ручного набора сообщений коммита. 4 121установок review-pr официальный Anthropic Команда запускает специализированных агентов для проверки изменений в PR: от тестов и обработки ошибок до типов и комментариев. ★ 44 635звёзд репо maker-setup официальный Anthropic Команда подключает Cardputer-Adv к рабочему процессу Code-with-Claude: скачивает репозиторий, прошивает устройство и ставит приложения Claude Buddy. ★ 44 635звёзд репо commit-push-pr официальный Anthropic Автоматически переключает ветку с main, делает коммит изменений, отправляет их на origin и оформляет pull request через GitHub CLI. ★ 44 635звёзд репо

Из того же набора205

Весь набор →
cli-ui-designer Проектирует веб-интерфейсы в стилистике терминала командной строки. Пригодится для стилизации дашбордов, панелей управления и сайтов для разработчиков. 1 849установок feature Команда создаёт ветку feature/<имя> от develop и настраивает её связь с origin. Пригодится для начала работы над новой функцией по Git Flow. 1 820установок finish Автоматизирует закрытие веток Git Flow в репозитории: запускает тесты, выполняет слияние и расставляет теги версий. 1 712установок release Автоматизирует подготовку релизной ветки по Git Flow. Проверяет семантическую версию, обновляет package.json, собирает список изменений и пушит ветку в origin. 1 664установок project-supervisor-orchestrator Субагент, который ведёт цепочку других агентов по шагам и возвращает результат в JSON. Пригодится, когда один запрос должен пройти через несколько специализированных агентов. 1 563установок competitive-intelligence-analyst Субагент для Claude, который собирает данные о конкурентах и рынке: профили компаний, SWOT, отраслевые тренды. Пригодится перед запуском продукта или при подготовке стратегии. 1 561установок flow-status Показывает, в какой ветке Git Flow вы находитесь, насколько она разошлась с remote и куда потом сольётся. 1 514установок web-accessibility-checker Субагент проверяет вёрстку на соответствие WCAG, разбирает семантику HTML и доступность с клавиатуры, а на выходе даёт отчёт с нарушениями. 1 438установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой