---
name: step-init
description: Initialize GitFlow configuration and branches
next_step: null
---

# Step: INIT - Initialize GitFlow

## YOUR TASK:

Set up GitFlow configuration with bare repository, worktrees, and branches.

**ULTRA THINK before creating configuration.**

---

## MANDATORY QUESTIONS

**⛔ ALWAYS ask these 3 questions, even if values can be auto-detected.**
**⛔ ALWAYS detect workspace context (step 2) to show sibling projects.**

| Question | Variable | Auto-detect from |
|----------|----------|------------------|
| Repository URL | `{REPO_URL}` | `git remote get-url origin` |
| Root folder | `{ROOT_FOLDER}` | Parent of current directory |
| Project name | `{PROJECT_NAME}` | Repo name from URL or folder |

**Multi-project principle:** Each repository has its OWN independent GitFlow config. Step 2 scans for sibling projects to provide context, not to share configuration.

**⛔ FOLLOW-UP RULE:** When a user selects a "Custom..." option (custom name, custom path, custom URL), that selection is just a CHOICE, not the actual value. You MUST immediately ask a follow-up question to capture the actual value. Never proceed with a blank or default value.

---

## EXECUTION SEQUENCE:

### 1. Detect Environment (for defaults only)

```bash
# Check if we're in a git repository
IS_GIT_REPO=$(git rev-parse --git-dir 2>/dev/null && echo "true" || echo "false")

# Auto-detect values for defaults (will be confirmed by user)
DETECTED_URL=$(git remote get-url origin 2>/dev/null || echo "")
DETECTED_FOLDER=$(dirname "$(pwd)")
DETECTED_NAME=$(basename -s .git "$DETECTED_URL" 2>/dev/null || basename "$(pwd)")

# Detect git provider
if [[ "$DETECTED_URL" == *"github.com"* ]]; then
  GIT_PROVIDER="github"
elif [[ "$DETECTED_URL" == *"dev.azure.com"* ]]; then
  GIT_PROVIDER="azuredevops"
else
  GIT_PROVIDER="unknown"
fi

# Check if already initialized
ALREADY_INITIALIZED=$([ -f ".claude/gitflow/config.json" ] && echo "true" || echo "false")
```

### 2. Detect Workspace (multi-project context)

**Scan the parent directory for sibling projects already using GitFlow:**

```bash
WORKSPACE_DIR=$(dirname "$(pwd)")
SIBLING_PROJECTS=()

for dir in "$WORKSPACE_DIR"/*/; do
  [ -d "$dir/.bare" ] || [ -d "$dir/01-Main" ] || [ -d "$dir/02-Develop" ] && {
    PROJECT_NAME_SIBLING=$(basename "$dir")
    SIBLING_PROJECTS+=("$PROJECT_NAME_SIBLING")
  }
done
```

**Display workspace context:**

```
┌─────────────────────────────────────────────────────────────┐
│  WORKSPACE: {WORKSPACE_DIR}                                  │
├─────────────────────────────────────────────────────────────┤
│  Each project has its OWN independent GitFlow configuration. │
│  This init configures only: {DETECTED_NAME}                  │
├─────────────────────────────────────────────────────────────┤
{if SIBLING_PROJECTS not empty}
│  Existing GitFlow projects:                                  │
│  {for each SIBLING} ✅ {SIBLING_NAME}/                       │
│     ├── .bare/  01-Main/  02-Develop/                        │
│     └── features/  releases/  hotfixes/                      │
│  {end for}                                                   │
│                                                              │
│  New project to initialize:                                  │
│  ⬜ {DETECTED_NAME}/                                         │
│     └── (same structure will be created)                     │
{else}
│  No existing GitFlow projects detected.                      │
│  This will be the first project in this workspace.           │
{endif}
└─────────────────────────────────────────────────────────────┘
```

**Key principle:** GitFlow is **per-repository**. Each project has its own `config.json`, its own worktree structure, and its own version history. Projects do not share configuration.

### 3. Handle Existing Configuration

**If `ALREADY_INITIALIZED` = true:**

Display current configuration and ask what to do:

```yaml
AskUserQuestion:
  - header: "Existing"
    question: "GitFlow is already initialized. Current config will be shown. What do you want to do?"
    options:
      - label: "Reconfigure (Recommended)"
        description: "Review and update all settings"
      - label: "Repair"
        description: "Fix missing directories only"
      - label: "View only"
        description: "Display current config and exit"
      - label: "Cancel"
        description: "Exit without changes"
    multiSelect: false
```

**Handle choices:**
- **Reconfigure**: Continue to step 4 (will ask all questions again)
- **Repair**: Check directories, fix missing ones, exit
- **View only**: Display config, exit
- **Cancel**: Exit immediately

### 4. MANDATORY: Ask Repository URL

**⛔ ALWAYS ask, even if URL was detected:**

```yaml
AskUserQuestion:
  - header: "Repository"
    question: "Repository URL? (detected: {DETECTED_URL})"
    options:
      - label: "Use detected URL (Recommended)"
        description: "{DETECTED_URL}"
      - label: "Enter GitHub URL"
        description: "https://github.com/org/repo.git"
      - label: "Enter Azure DevOps URL"
        description: "https://dev.azure.com/org/project/_git/repo"
      - label: "Local only (no remote)"
        description: "Initialize without remote (limited features)"
    multiSelect: false
```

**⛔ FOLLOW-UP: If user selects "Enter GitHub URL" or "Enter Azure DevOps URL":**

The selected option is just a choice, NOT the actual URL. You MUST ask a follow-up question:

```yaml
AskUserQuestion:
  - header: "URL"
    question: "Enter the repository URL:"
    options:
      - label: "https://github.com/org/repo.git"
        description: "Example GitHub format"
      - label: "https://dev.azure.com/org/project/_git/repo"
        description: "Example Azure DevOps format"
    multiSelect: false
```

The user will type the actual URL via "Other". Then:
- Validate format
- Update `{REPO_URL}` and `{GIT_PROVIDER}`

### 5. MANDATORY: Ask Root Folder

**⛔ ALWAYS ask where to create THIS project's structure:**

**If sibling projects exist, show where it fits:**

```
{WORKSPACE_DIR}/
├── SmartStack.app/    ✅ (gitflow)
├── SmartStack.mcp/    ✅ (gitflow)
├── SmartStack.cli/    ✅ (gitflow)
└── NewProject/        ← THIS PROJECT
    ├── .bare/
    ├── 01-Main/
    ├── 02-Develop/
    ├── features/
    ├── releases/
    └── hotfixes/
```

```yaml
AskUserQuestion:
  - header: "Location"
    question: "Root folder for THIS project? (worktrees will be created here)"
    options:
      - label: "Use parent folder (Recommended)"
        description: "{DETECTED_FOLDER}/ - consistent with {#SIBLING_PROJECTS} sibling project(s)"
      - label: "Use current folder"
        description: "$(pwd)/ - Will create subfolders here"
      - label: "Custom path"
        description: "Specify a different location"
    multiSelect: false
```

**⛔ FOLLOW-UP: If user selects "Custom path":**

You MUST ask a follow-up question to get the actual path:

```yaml
AskUserQuestion:
  - header: "Path"
    question: "Enter the full path for the project root folder:"
    options:
      - label: "{DETECTED_FOLDER}/"
        description: "Parent of current directory"
      - label: "{WORKSPACE_DIR}/"
        description: "Workspace root"
    multiSelect: false
```

The user will type the actual path via "Other". Validate the path exists or can be created.

**Explain the structure that will be created for this project:**

```
{ROOT_FOLDER}/
├── .bare/                 # Git bare repository (this repo only)
├── 01-Main/               # Worktree: main branch
├── 02-Develop/            # Worktree: develop branch
├── features/              # Feature branch worktrees
├── releases/              # Release branch worktrees
└── hotfixes/              # Hotfix branch worktrees
```

### 6. MANDATORY: Ask Project Name

**⛔ ALWAYS ask to confirm project name:**

```yaml
AskUserQuestion:
  - header: "Project"
    question: "Project name? (detected: {DETECTED_NAME})"
    options:
      - label: "Use detected name (Recommended)"
        description: "Project: {DETECTED_NAME}"
      - label: "Custom name"
        description: "Specify a different project name"
    multiSelect: false
```

**⛔ FOLLOW-UP: If user selects "Custom name":**

You MUST ask a follow-up question to get the actual name:

```yaml
AskUserQuestion:
  - header: "Name"
    question: "Enter the project name:"
    options:
      - label: "{DETECTED_NAME}"
        description: "Detected from repository"
      - label: "{DETECTED_NAME}-v2"
        description: "Variant of detected name"
    multiSelect: false
```

The user will type the actual name via "Other". Use this raw input for step 6b.

### 6b. Normalize Project Name (INTELLIGENT)

**⛔ ALWAYS normalize, even if user chose the detected name.**

**Step 1: Parse input into words**

Split the raw input on any separator: spaces, hyphens, underscores, dots, camelCase boundaries.

| Raw input | Parsed words |
|-----------|-------------|
| `mon super projet` | `["mon", "super", "projet"]` |
| `gestion-des-stocks` | `["gestion", "des", "stocks"]` |
| `my_awesome_app` | `["my", "awesome", "app"]` |
| `SmartStack.App` | `["Smart", "Stack", "App"]` |
| `userManagement` | `["user", "Management"]` |

**Step 2: Language detection and spell check**

For EACH word, you MUST:
1. **Detect the language** (French, English, or technical/proper noun)
2. **Check spelling** - flag obvious typos
3. **Suggest corrections** if misspelled

| Word | Language | Spelling | Suggestion |
|------|----------|----------|------------|
| `gestion` | FR | ✅ | - |
| `gestoin` | FR | ❌ typo | → `gestion` |
| `managment` | EN | ❌ typo | → `management` |
| `SmartStack` | Proper noun | ✅ | - |
| `auth` | EN (abbreviation) | ✅ | - |

**If typos detected**, ask the user BEFORE generating variants:

```yaml
AskUserQuestion:
  - header: "Spelling"
    question: "Corrections detected. Accept?"
    options:
      - label: "Accept corrections (Recommended)"
        description: "'gestoin' → 'gestion', 'managment' → 'management'"
      - label: "Keep original"
        description: "Use the name as typed"
    multiSelect: false
```

**Step 3: Generate all name variants**

From the cleaned words, generate ALL variants:

```
┌─────────────────────────────────────────────────────────────┐
│  PROJECT NAME VARIANTS                                       │
│  Input: "gestion des stocks"                                 │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  A) PascalCase.Dot    →  Gestion.Des.Stocks                 │
│     Best for: .NET namespace, C# project, folder name        │
│                                                              │
│  B) PascalCase        →  GestionDesStocks                    │
│     Best for: Class name, assembly name                      │
│                                                              │
│  C) kebab-case        →  gestion-des-stocks                  │
│     Best for: Git repo, npm package, URL slug                │
│                                                              │
│  D) snake_case        →  gestion_des_stocks                  │
│     Best for: Database, Python, file system                  │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

**Step 4: Ask user to choose the PRIMARY format**

```yaml
AskUserQuestion:
  - header: "Format"
    question: "Which format for the project name?"
    options:
      - label: "PascalCase.Dot (Recommended)"
        description: "{PascalCase.Dot variant} - .NET convention"
      - label: "PascalCase"
        description: "{PascalCase variant} - single word"
      - label: "kebab-case"
        description: "{kebab-case variant} - git/npm convention"
      - label: "snake_case"
        description: "{snake_case variant} - database/python convention"
    multiSelect: false
```

**Step 5: Store all derived names**

Regardless of the chosen primary format, ALL variants are generated and stored:

```json
{
  "PROJECT_NAME": "{chosen format}",
  "PROJECT_VARIANTS": {
    "pascalCaseDot": "Gestion.Des.Stocks",
    "pascalCase": "GestionDesStocks",
    "kebabCase": "gestion-des-stocks",
    "snakeCase": "gestion_des_stocks",
    "displayName": "Gestion Des Stocks",
    "words": ["gestion", "des", "stocks"],
    "language": "fr"
  }
}
```

These variants are available for subsequent steps (repo name, namespace, folder, etc.).

**Real-world examples:**

| User types | PascalCase.Dot | kebab-case | PascalCase |
|-----------|---------------|------------|------------|
| `smart stack app` | `SmartStack.App` | `smart-stack-app` | `SmartStackApp` |
| `gestion-des-stocks` | `Gestion.Des.Stocks` | `gestion-des-stocks` | `GestionDesStocks` |
| `Mon Projet V2` | `Mon.Projet.V2` | `mon-projet-v2` | `MonProjetV2` |
| `user auth module` | `User.Auth.Module` | `user-auth-module` | `UserAuthModule` |
| `PROJET TEST` | `Projet.Test` | `projet-test` | `ProjetTest` |
| `e-commerce platform` | `ECommerce.Platform` | `e-commerce-platform` | `ECommercePlatform` |

### 7. Ask Worktree Mode

```yaml
AskUserQuestion:
  - header: "Worktrees"
    question: "How should worktrees be organized?"
    options:
      - label: "Organized (Recommended)"
        description: "01-Main, 02-Develop, features/, releases/, hotfixes/"
      - label: "Simple"
        description: "main/, develop/, features/, releases/, hotfixes/"
      - label: "Disabled"
        description: "No worktrees, use git checkout (not recommended)"
    multiSelect: false
```

### 8. Create Directory Structure

**⛔ Create the COMPLETE structure:**

```bash
cd "{ROOT_FOLDER}"

# Create bare repository if not exists
if [ ! -d ".bare" ]; then
  git clone --bare "{REPO_URL}" .bare
  # Configure bare repo for worktrees
  cd .bare
  git config core.bare false
  git config core.worktree ..
  cd ..
fi

# Create worktree directories
mkdir -p features releases hotfixes

# Organized mode: numbered main folders
if [ "$WORKTREE_MODE" = "organized" ]; then
  # Create main worktree
  [ ! -d "01-Main" ] && git worktree add 01-Main main

  # Create develop worktree
  [ ! -d "02-Develop" ] && git worktree add 02-Develop develop
fi

# Simple mode: named folders
if [ "$WORKTREE_MODE" = "simple" ]; then
  [ ! -d "main" ] && git worktree add main main
  [ ! -d "develop" ] && git worktree add develop develop
fi

# Create gitflow config directory (in develop worktree)
DEVELOP_PATH=$([ "$WORKTREE_MODE" = "organized" ] && echo "02-Develop" || echo "develop")
mkdir -p "$DEVELOP_PATH/.claude/gitflow/{plans,logs,cache,backup}"
```

### 9. Create Configuration

**Write `.claude/gitflow/config.json` in develop worktree:**

```json
{
  "version": "2.0.0",
  "repository": {
    "name": "{PROJECT_NAME}",
    "rootFolder": "{ROOT_FOLDER}",
    "nameVariants": {
      "pascalCaseDot": "{PascalCase.Dot}",
      "pascalCase": "{PascalCase}",
      "kebabCase": "{kebab-case}",
      "snakeCase": "{snake_case}",
      "displayName": "{Display Name}"
    },
    "defaultBranch": "main",
    "remoteUrl": "{REPO_URL}"
  },
  "git": {
    "provider": "{GIT_PROVIDER}",
    "branches": {
      "main": "main",
      "develop": "develop"
    },
    "prefixes": {
      "feature": "feature/",
      "release": "release/",
      "hotfix": "hotfix/"
    }
  },
  "worktrees": {
    "enabled": true,
    "mode": "{WORKTREE_MODE}",
    "structure": {
      "main": "{ROOT_FOLDER}/01-Main",
      "develop": "{ROOT_FOLDER}/02-Develop",
      "features": "{ROOT_FOLDER}/features",
      "releases": "{ROOT_FOLDER}/releases",
      "hotfixes": "{ROOT_FOLDER}/hotfixes"
    }
  },
  "versioning": {
    "strategy": "semver",
    "current": "{VERSION}",
    "tagPrefix": "v",
    "sources": ["csproj", "package.json", "VERSION"]
  },
  "efcore": {
    "enabled": true,
    "validateOnCommit": true,
    "blockDestructive": true,
    "migrationNaming": "{context}_v{version}_{sequence}_{Description}"
  },
  "workflow": {
    "push": {
      "afterCommit": "worktree"
    },
    "pr": {
      "autoLabels": true,
      "requireReview": true
    }
  },
  "language": {
    "code": "{GF_LANG}"
  }
}
```

### 10. Detect Version

```bash
# In develop worktree
cd "$DEVELOP_PATH"

# Priority: csproj > Directory.Build.props > package.json > VERSION > tag
VERSION=$(grep -oP '<Version>\K[^<]+' *.csproj 2>/dev/null | head -1)
[ -z "$VERSION" ] && VERSION=$(grep -oP '<Version>\K[^<]+' Directory.Build.props 2>/dev/null)
[ -z "$VERSION" ] && VERSION=$(grep -oP '"version":\s*"\K[^"]+' package.json 2>/dev/null)
[ -z "$VERSION" ] && VERSION=$(cat VERSION 2>/dev/null)
[ -z "$VERSION" ] && VERSION=$(git describe --tags --abbrev=0 2>/dev/null | sed 's/^v//')
[ -z "$VERSION" ] && VERSION="0.1.0"
```

### 11. Summary

```
╔══════════════════════════════════════════════════════════════════╗
║                    GITFLOW INITIALIZED                            ║
╠══════════════════════════════════════════════════════════════════╣
║  Project:    {PROJECT_NAME}                                       ║
║  Root:       {ROOT_FOLDER}                                        ║
║  Remote:     {REPO_URL}                                           ║
║  Provider:   {GIT_PROVIDER}                                       ║
║  Version:    {VERSION}                                            ║
╠══════════════════════════════════════════════════════════════════╣
║  Structure:                                                        ║
║  ├── .bare/           (git bare repository)                       ║
║  ├── 01-Main/         (main branch)         ✅                    ║
║  ├── 02-Develop/      (develop branch)      ✅                    ║
║  ├── features/        (feature worktrees)   ✅                    ║
║  ├── releases/        (release worktrees)   ✅                    ║
║  └── hotfixes/        (hotfix worktrees)    ✅                    ║
╠══════════════════════════════════════════════════════════════════╣
{if SIBLING_PROJECTS not empty}
║  Workspace: {WORKSPACE_DIR}                                       ║
║  GitFlow projects: {#SIBLING_PROJECTS + 1} (including this one)   ║
╠══════════════════════════════════════════════════════════════════╣
{endif}
║  Config: 02-Develop/.claude/gitflow/config.json                   ║
╠══════════════════════════════════════════════════════════════════╣
║  NEXT: cd 02-Develop && /gitflow -f <feature-name>                ║
╚══════════════════════════════════════════════════════════════════╝
```

---

## VALIDATION CHECKLIST:

Before completing init, verify:

- [ ] Repository URL confirmed by user
- [ ] Root folder confirmed by user
- [ ] Project name confirmed by user
- [ ] .bare/ directory exists
- [ ] 01-Main/ worktree exists and is on main branch
- [ ] 02-Develop/ worktree exists and is on develop branch
- [ ] features/, releases/, hotfixes/ directories exist
- [ ] .claude/gitflow/config.json created in develop worktree

---

## ERROR HANDLING:

| Error | Solution |
|-------|----------|
| Clone fails | Check URL, network, credentials |
| Worktree exists | Skip or offer to recreate |
| Permission denied | Check folder permissions |
| Branch missing | Create from default branch |

---

## SUCCESS CRITERIA:

- ✅ All 3 mandatory questions asked
- ✅ Complete folder structure created
- ✅ Both main and develop worktrees functional
- ✅ Configuration file created
- ✅ User can navigate to 02-Develop and start working

## NEXT STEP:

Init is standalone. User should `cd 02-Develop` then run `/gitflow -f <feature-name>`.
