---
name: gitflow
description: GitFlow workflow with versioning, worktrees, and EF Core migration management. Progressive step loading for minimal context usage.
argument-hint: "[-a] [-f|-r|-h] <action> [name]"
disable-model-invocation: true
---

## Current state (auto-injected)
- Preflight: !`if [ -f .git ] && grep -q '^gitdir: [A-Za-z]:' .git 2>/dev/null && grep -qi microsoft /proc/version 2>/dev/null; then p=$(sed 's/^gitdir: //' .git | tr -d '\r\n'); d=$(echo "${p:0:1}" | tr A-Z a-z); r="${p:2}"; r="${r//\\//}"; printf 'gitdir: %s\n' "$(realpath -m --relative-to="$(pwd)" "/mnt/$d$r")" > .git && echo "repaired"; else echo "ok"; fi`
- Branch: !`git branch --show-current 2>/dev/null || echo "UNAVAILABLE"`
- Status: !`git status --short 2>/dev/null || echo "UNAVAILABLE"`
- Recent commits: !`git log --oneline -5 2>/dev/null || echo "UNAVAILABLE"`
- Worktrees: !`git worktree list 2>/dev/null || echo "UNAVAILABLE (run preflight_git_check from _shared.md)"`
- Config: !`cat .claude/gitflow/config.json 2>/dev/null || echo "no config found"`

<objective>
Execute GitFlow workflows with automatic versioning, worktree management, and EF Core migration validation. Uses progressive step loading to minimize context and maintain fresh state at each phase.
</objective>

<quick_start>
**Manual workflow (step-by-step, recommended):**
```bash
/gitflow -f user-auth     # Start feature → STOPS
# ... code ...
/gitflow commit           # Commit → STOPS
/gitflow pr               # Create PR → STOPS (wait review)
/gitflow merge            # Merge → STOPS
/gitflow finish           # Cleanup → DONE
```

**Automatic workflow (all-in-one):**
```bash
/gitflow -a -f my-feature   # Full auto: all steps
/gitflow -a -r 1.20.0       # Full auto: release
```

**Flags:**
- `-a` (auto): **Execute ALL steps automatically** (without = one step then stop)
- `-f` (feature): Feature workflow (target: develop)
- `-r` (release): Release workflow (target: main)
- `-h` (hotfix): Hotfix workflow (target: main)
- `-s` (status): Show status only
</quick_start>

<parameters>

<flags>
**Mode flags (mutually exclusive):**
| Short | Long | Description |
|-------|------|-------------|
| `-f` | `--feature` | Feature workflow (target: develop) |
| `-r` | `--release` | Release workflow (target: main, merge-back develop) |
| `-h` | `--hotfix` | Hotfix workflow (target: main, merge-back develop) |

**Behavior flags:**
| Short | Long | Description |
|-------|------|-------------|
| `-a` | `--auto` | **Full automatic mode**: execute ALL steps without stopping |
| `-s` | `--status` | Status mode: show state only, no actions |
| `-v` | `--verbose` | Verbose output |
| `--dry-run` | | Preview actions without executing |
| `--smartstack` | | Init + SmartStack project scaffolding (backend, frontend, config) |

**⚠️ CRITICAL: Without `-a`, each command executes ONLY its own step then STOPS.**

**Disable flags:**
| Short | Long | Description |
|-------|------|-------------|
| `-A` | `--no-auto` | Disable auto mode |
| `--ws` | `--workspace` | Batch init: initialize all repos in a workspace |
</flags>

<actions>
**Primary actions:**
| Action | Description | Step |
|--------|-------------|------|
| `init` | Initialize GitFlow config (orchestrates detect→clone→validate) | step-init |
| `init --workspace` | Batch initialize all repos in a workspace | step-init |
| `start` | Create new branch + worktree | step-start |
| `commit` | Commit with EF Core validation | step-commit |
| `sync` | Sync + rebase with remote | step-sync |
| `plan` | Generate integration plan | step-plan |
| `pr` | Create pull request | step-pr |
| `merge` | Merge PR after review | step-merge |
| `finish` | Finalize (tag + cleanup) | step-finish |

**Standalone phases:**
| Action | Description | Phase |
|--------|-------------|-------|
| `status` | Show complete state | phases/status |
| `abort` | Rollback/recovery | phases/abort |
| `cleanup` | Audit worktrees | phases/cleanup |
</actions>

<examples>
```bash
# ══════════════════════════════════════════════════════════════
# STEP-BY-STEP MODE (default - recommended)
# Each command executes ONE step, then waits for user
# ══════════════════════════════════════════════════════════════

# Feature workflow (manual steps)
/gitflow -f my-feature    # 1. Creates branch → STOPS
# ... user codes ...
/gitflow commit           # 2. Commits changes → STOPS
/gitflow pr               # 3. Creates PR → STOPS (wait for review)
/gitflow merge            # 4. Merges PR → STOPS
/gitflow finish           # 5. Cleanup → DONE

# Release workflow (manual steps)
/gitflow -r 1.20.0        # 1. Creates branch + bump version → STOPS
/gitflow pr               # 2. Creates PR to main → STOPS (wait for review)
/gitflow merge            # 3. Merges PR → STOPS
/gitflow finish           # 4. Tag + merge-back + cleanup → DONE

# ══════════════════════════════════════════════════════════════
# AUTOMATIC MODE (-a flag)
# Executes ALL steps without stopping
# ══════════════════════════════════════════════════════════════

/gitflow -a -f my-feature  # Full auto: branch → commit → pr → merge → finish
/gitflow -a -r 1.20.0      # Full auto: branch → bump → pr → merge → tag → cleanup
/gitflow -a -h fix-bug     # Full auto: hotfix complete cycle

# ══════════════════════════════════════════════════════════════
# UTILITY COMMANDS
# ══════════════════════════════════════════════════════════════

/gitflow init              # Git structure only (bare + worktrees)
/gitflow init --smartstack # Git structure + SmartStack project init

/gitflow status           # Show current state
/gitflow -s               # Shorthand for status
/gitflow abort            # Rollback current operation
/gitflow cleanup          # Audit and remove orphan worktrees
```
</examples>

</parameters>

<workflows>
```
FEATURE WORKFLOW
────────────────
start ──► commit* ──► sync ──► pr ──► merge ──► finish
  │        (loop)      │               │
  └── worktree ────────┴── rebase? ────┴── squash merge

RELEASE WORKFLOW
────────────────
start ──► commit* ──► sync ──► pr ──► merge ──► finish
  │        (loop)             (main)    │        │
  └── worktree ───────────────────────────── merge-back develop
                                              + tag vX.Y.Z

HOTFIX WORKFLOW
───────────────
start ──► commit* ──► sync ──► pr ──► merge ──► finish
  │        (loop)             (main)    │        │
  └── worktree ───────────────────────────── merge-back develop
                                              + tag vX.Y.Z+1
```
</workflows>

<state_variables>
**Persist throughout all steps:**

| Variable | Type | Description |
|----------|------|-------------|
| `{branch_type}` | string | feature, release, hotfix |
| `{branch_name}` | string | Full branch name (e.g., feature/user-auth) |
| `{base_branch}` | string | Target branch (develop or main) |
| `{worktree_path}` | string | Path to worktree directory |
| `{version_current}` | string | Current version (X.Y.Z) |
| `{version_next}` | string | Next version after merge |
| `{auto_mode}` | boolean | Skip confirmations |
| `{has_migrations}` | boolean | EF Core migrations detected |
| `{pr_number}` | number | PR number (after creation) |
| `{git_provider}` | string | github or azuredevops |

</state_variables>

<entry_point>

**ROUTING LOGIC:**

1. Parse flags and action from input
2. Route to appropriate step or Task agent:

| Input Pattern | Step File | Task Agent (`subagent_type`) |
|---------------|-----------|----------------------------|
| `init` | `steps/step-init.md` | **ALWAYS INLINE** (see below) |
| `init --smartstack` | `steps/step-init.md` | **ALWAYS INLINE** (Git + SmartStack init) |
| `start`, `-f`, `-r`, `-h` | `steps/step-start.md` | `gitflow-start` |
| `commit [msg]` | `steps/step-commit.md` | `gitflow-commit` |
| `sync` | `steps/step-sync.md` | — |
| `plan` | `steps/step-plan.md` | `gitflow-plan` |
| `pr` | `steps/step-pr.md` | `gitflow-pr` |
| `merge` | `steps/step-merge.md` | `gitflow-merge` |
| `finish` | `steps/step-finish.md` | `gitflow-finish` |
| `status`, `-s` | `phases/status.md` | `gitflow-status` |
| `abort` | `phases/abort.md` | `gitflow-abort` |
| `cleanup` | `phases/cleanup.md` | `gitflow-cleanup` |
| (no action, on feature/*) | `steps/step-commit.md` | `gitflow-commit` |

**Execution mode:**

| Mode | How to route |
|------|-------------|
| **Single step** (no `-a`) | Read the step file and execute inline |
| **Auto mode** (`-a`) | Use `Task` tool with the matching `subagent_type` for each step sequentially |
| **Standalone phases** | Always delegate to Task agent (fast, isolated) |

**⚠️ SPECIAL RULE FOR `init`:**
`init` is **ALWAYS executed inline** — NEVER delegate to a Task agent.
Read `steps/step-init.md` and execute it directly in the main conversation.
This is mandatory because `init` requires AskUserQuestion calls that MUST
happen in the main conversation (sub-agents skip questions).
After the user answers all questions, delegate heavy work to:
- `Task(gitflow-init-detect)` for environment detection
- `Task(gitflow-init-clone)` for structure creation
- `Task(gitflow-init-validate)` for post-init verification

</entry_point>

<step_files>
**Progressive loading - only load current step:**

| Step | File | Purpose |
|------|------|---------|
| init | `steps/step-init.md` | Configure GitFlow, create branches |
| start | `steps/step-start.md` | Create branch + worktree |
| commit | `steps/step-commit.md` | Commit with EF Core validation |
| sync | `steps/step-sync.md` | Push/pull + rebase if behind |
| plan | `steps/step-plan.md` | Generate integration plan |
| pr | `steps/step-pr.md` | Create pull request |
| merge | `steps/step-merge.md` | Review checklist + merge |
| finish | `steps/step-finish.md` | Tag + cleanup + version |

**Standalone phases:**

| Phase | File | Purpose |
|-------|------|---------|
| status | `phases/status.md` | Complete state diagnostic |
| abort | `phases/abort.md` | Rollback and recovery |
| cleanup | `phases/cleanup.md` | Audit and remove orphan worktrees |

</step_files>

<efcore_rules>
**EF Core validation (MANDATORY):**

1. **1 migration per feature** - Recreate, don't accumulate
2. **3 required files** per migration:
   - `{Migration}.cs`
   - `{Migration}.Designer.cs`
   - `{DbContext}ModelSnapshot.cs`
3. **Sync before merge** - Rebase on base branch
4. **ModelSnapshot conflict** - Accept theirs + Regenerate
5. **Release** - Generate idempotent SQL script

**Blocking conditions:**
- Missing migration files → Block commit
- Snapshot divergence → Require `/efcore rebase-snapshot`
- Destructive changes → Require confirmation
</efcore_rules>

<versioning>
**Source priority:** csproj → Directory.Build.props → VERSION file → git tag

**Auto-increment rules:**
| Branch Type | Version Change | Example |
|-------------|----------------|---------|
| feature | minor | 1.2.0 → 1.3.0 |
| hotfix | patch | 1.2.0 → 1.2.1 |
| release | as specified | 1.2.0 → 2.0.0 |
</versioning>

<task_agents>

**Task agent delegation (Opus 4.6):**

Each action has a matching Task agent that can execute independently. Use `Task` tool with the `subagent_type` parameter to delegate:

| Agent | Model | Tools | Use for |
|-------|-------|-------|---------|
| `gitflow-commit` | haiku | Bash, Read, Glob, Grep | Fast commit + EF Core validation |
| `gitflow-pr` | haiku | Bash, Glob | Fast PR creation |
| `gitflow-status` | haiku | Bash, Read, Glob | Fast status check |
| `gitflow-review` | haiku | Bash, Glob, Read | Fast PR review |
| `gitflow-start` | sonnet | Bash, Read, Glob, Write | Branch + worktree creation |
| `gitflow-merge` | sonnet | Bash, Read, Glob, Grep, Edit | Safe merge with validation |
| `gitflow-finish` | sonnet | Bash, Read, Glob, Write | Tag + cleanup + merge-back |
| `gitflow-plan` | sonnet | Bash, Read, Glob, Grep, Write | Integration planning |
| `gitflow-exec` | sonnet | Bash, Read, Glob, Grep, Edit, Write | Plan execution |
| `gitflow-init` | sonnet | Bash, Read, Write, Glob, AskUserQuestion | Project setup (orchestrator) |
| `gitflow-init-detect` | haiku | Bash, Read | Environment detection (sub-agent) |
| `gitflow-init-clone` | sonnet | Bash, Read, Write | Bare clone + worktrees (sub-agent) |
| `gitflow-init-validate` | haiku | Bash, Read, Glob | Post-init verification + repair (sub-agent) |
| `gitflow-cleanup` | sonnet | Bash, Read, Glob, Write | Orphan worktree audit |
| `gitflow-abort` | sonnet | Bash, Read, Glob, Write | Rollback/recovery |

**Init team delegation (orchestrated by `gitflow-init`):**

| Step | Sub-agent | Model | Purpose |
|------|-----------|-------|---------|
| 1 | `gitflow-init-detect` | haiku | Platform, workspace, git state detection |
| 2 | (orchestrator) | sonnet | AskUserQuestion for URL, path, name |
| 3 | `gitflow-init-clone` | sonnet | Bare clone + worktree creation (zero `cd`, absolute paths) |
| 4 | (orchestrator) | sonnet | Write config.json v2.1.0 |
| 5 | `gitflow-init-validate` | haiku | Verify structure + auto-repair |

**Parallel execution opportunities:**

| Scenario | Parallel agents |
|----------|----------------|
| Status check | `gitflow-status` in background while user continues |
| Pre-PR validation | Build check + migration check in parallel Bash calls |
| Auto release | Sequential: start → commit → pr → (wait) → finish |
| Workspace init | Sequential per repo, but detection is parallel |

**Agent prompt template:**
```
Execute {action} for GitFlow.
Working directory: {worktree_path}
Branch: {branch_name} ({branch_type})
Target: {base_branch}
Provider: {git_provider}
Version: {version_current}
Auto mode: {auto_mode}
```

</task_agents>

<worktree_repair>

**MANDATORY PRE-FLIGHT:** Before routing to any step or agent, run `preflight_git_check` (from `_shared.md` PREFLIGHT_GIT_CHECK section). This ensures git is accessible and repairs cross-platform worktree paths (Windows ↔ WSL).

**When to trigger:** If any auto-injected state shows "UNAVAILABLE", or if the Preflight line shows "repaired".

**Execution:**
```bash
# 1. Detect platform
detect_platform

# 2. Run preflight (repairs .git file + .bare/worktrees/*/gitdir)
preflight_git_check

# 3. Verify
git status --short
```

**This converts all paths to relative format (cross-platform safe).**

</worktree_repair>

<execution_rules>

- **Single step mode**: Read the step file and execute inline
- **Auto mode (`-a`)**: Delegate each step to its Task agent sequentially
- **Standalone phases**: Always delegate to Task agent (fast, isolated)
- **NEVER skip EF Core validation** - migrations are critical
- **Safety > Correctness > Speed**

**⚠️ CRITICAL - STEP EXECUTION POLICY:**

| Mode | Behavior |
|------|----------|
| **Without `-a`** | Execute ONLY the requested step, then **STOP and wait for user** |
| **With `-a`** | Execute ALL steps automatically via Task agent delegation |

**Examples:**
```bash
/gitflow -r 1.20.0      # Reads step-start.md, executes inline → STOPS
/gitflow -r -a 1.20.0   # Delegates to gitflow-start → gitflow-pr → gitflow-finish
/gitflow -f my-feature  # Reads step-start.md, executes inline → STOPS
/gitflow commit          # Reads step-commit.md, executes inline → STOPS
```

**NEVER chain steps automatically without `-a` flag. The user decides the pace.**

</execution_rules>

<success_criteria>

- Branch created with worktree (if start)
- All commits validated (EF Core)
- PR created with proper target
- Merge completed with correct strategy
- Tags created for releases/hotfixes
- Worktrees cleaned up after finish
</success_criteria>
