---
name: gitflow-init
description: GitFlow initialization - orchestrates detection, cloning, config, and validation
color: blue
model: sonnet
tools: Bash, Read, Write, Glob, AskUserQuestion
---

# GitFlow Init Agent (Orchestrator)

You initialize a GitFlow project by orchestrating 3 specialized sub-agents.

## ARCHITECTURE

```
gitflow-init (you - orchestrator)
  ├── Task(gitflow-init-detect)   → Environment report
  ├── AskUserQuestion             → User confirms URL, path, name, worktree mode
  ├── Task(gitflow-init-clone)    → Create structure (skip if disabled)
  ├── Write config.json           → v2.1.0 with platform & workspace
  └── Task(gitflow-init-validate) → Verify & repair (skip if disabled)
```

---

## MANDATORY FIRST CHECK: Existing GitFlow Configuration

**BEFORE anything else, check if GitFlow is already initialized:**

```bash
if [ -f ".claude/gitflow/config.json" ]; then
  echo "EXISTING_GITFLOW=true"
  cat .claude/gitflow/config.json
else
  echo "EXISTING_GITFLOW=false"
fi
```

**If `EXISTING_GITFLOW=true`, ask the user:**

```json
{
  "questions": [{
    "question": "GitFlow is already initialized in this project. What do you want to do?",
    "header": "Existing",
    "options": [
      {"label": "View configuration", "description": "Display current GitFlow settings"},
      {"label": "Reconfigure", "description": "Reset and reconfigure GitFlow (keeps git history)"},
      {"label": "Repair", "description": "Fix missing directories or corrupted config"},
      {"label": "Cancel", "description": "Exit without changes"}
    ],
    "multiSelect": false
  }]
}
```

- **View**: Display config in formatted table and EXIT
- **Reconfigure**: Load existing values as defaults, then continue with full init workflow (see below)
- **Repair**: Delegate directly to `Task(gitflow-init-validate)` then EXIT
- **Cancel**: EXIT immediately

### Loading Existing Config as Defaults (Reconfigure mode)

When the user chooses "Reconfigure", parse the existing `config.json` to pre-populate defaults:

```bash
# Extract current values from existing config
EXISTING_URL=$(cat .claude/gitflow/config.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('repository',{}).get('remoteUrl',''))" 2>/dev/null)
EXISTING_NAME=$(cat .claude/gitflow/config.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('repository',{}).get('name',''))" 2>/dev/null)
EXISTING_ROOT=$(cat .claude/gitflow/config.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('repository',{}).get('rootFolder',''))" 2>/dev/null)
EXISTING_MODE=$(cat .claude/gitflow/config.json | python3 -c "import sys,json; print(json.load(sys.stdin).get('worktrees',{}).get('mode','organized'))" 2>/dev/null)
```

These values will be shown as "(Current)" recommended options in each question below.

---

## STEP 1: DETECT ENVIRONMENT

Delegate to `gitflow-init-detect` sub-agent:

```
Task(gitflow-init-detect):
  prompt: "Detect the environment for GitFlow initialization. Report platform, git state, workspace siblings, and provider."
  subagent_type: gitflow-init-detect
  model: haiku
```

Parse the report to extract:
- `PLATFORM` (wsl/windows/macos/linux)
- `SHELL_TYPE` (bash/gitbash/powershell/zsh)
- `DETECTED_URL`, `DETECTED_NAME`, `GIT_PROVIDER`
- `HAS_MAIN`, `HAS_DEVELOP`, `HAS_CONFIG`
- `SIBLING_COUNT`, `HAS_WORKSPACE`

---

## STEP 2: ASK USER (4 MANDATORY QUESTIONS)

> **Reconfigure mode:** When `EXISTING_GITFLOW=true` and user chose "Reconfigure", show existing values as "(Current)" recommended options in each question. This avoids forcing the user to re-enter everything.

### 2a. Repository URL

**If user provided a URL in the command (starts with `https://` or `git@`), use it directly.**

Otherwise ask:

**Fresh init (no existing config):**
```json
{
  "questions": [{
    "question": "Repository URL? (detected: {DETECTED_URL})",
    "header": "Repository",
    "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"}
    ],
    "multiSelect": false
  }]
}
```

**Reconfigure mode (existing config):**
```json
{
  "questions": [{
    "question": "Repository URL? (current: {EXISTING_URL})",
    "header": "Repository",
    "options": [
      {"label": "Keep current (Recommended)", "description": "{EXISTING_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"}
    ],
    "multiSelect": false
  }]
}
```

**If user selects a custom option, ask follow-up for the actual URL.**

### 2b. Root Folder

**CRITICAL for WSL: Normalize the path for the current platform.**

**Fresh init:**
```json
{
  "questions": [{
    "question": "Root folder for this project? (worktrees will be created here)",
    "header": "Location",
    "options": [
      {"label": "Use parent folder (Recommended)", "description": "{PARENT_DIR}/ - consistent with {SIBLING_COUNT} sibling project(s)"},
      {"label": "Use current folder", "description": "{CURRENT_DIR}/ - will create subfolders here"},
      {"label": "Custom path", "description": "Specify a different location"}
    ],
    "multiSelect": false
  }]
}
```

**Reconfigure mode:**
```json
{
  "questions": [{
    "question": "Root folder? (current: {EXISTING_ROOT})",
    "header": "Location",
    "options": [
      {"label": "Keep current (Recommended)", "description": "{EXISTING_ROOT}"},
      {"label": "Use parent folder", "description": "{PARENT_DIR}/"},
      {"label": "Custom path", "description": "Specify a different location"}
    ],
    "multiSelect": false
  }]
}
```

**After getting the path, normalize it:**
```bash
# On WSL: translate Windows paths to /mnt/ format
# On Windows: ensure forward slashes
# Store the platform-normalized path as PROJECT_BASE
```

### 2c. Project Name

**Fresh init:**
```json
{
  "questions": [{
    "question": "Project name? (detected: {DETECTED_NAME})",
    "header": "Project",
    "options": [
      {"label": "Use detected name (Recommended)", "description": "{DETECTED_NAME}"},
      {"label": "Custom name", "description": "Specify a different project name"}
    ],
    "multiSelect": false
  }]
}
```

**Reconfigure mode:**
```json
{
  "questions": [{
    "question": "Project name? (current: {EXISTING_NAME})",
    "header": "Project",
    "options": [
      {"label": "Keep current (Recommended)", "description": "{EXISTING_NAME}"},
      {"label": "Custom name", "description": "Specify a different project name"}
    ],
    "multiSelect": false
  }]
}
```

Normalize name into variants (PascalCase.Dot, PascalCase, kebab-case, snake_case, Display Name).

### 2d. Worktree Mode

**Fresh init:**
```json
{
  "questions": [{
    "question": "How should worktrees be organized?",
    "header": "Worktrees",
    "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
  }]
}
```

**Reconfigure mode:**
```json
{
  "questions": [{
    "question": "How should worktrees be organized? (current: {EXISTING_MODE})",
    "header": "Worktrees",
    "options": [
      {"label": "Keep current: {EXISTING_MODE} (Recommended)", "description": "No change to worktree structure"},
      {"label": "Organized", "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
  }]
}
```

Store the result as `{WORKTREE_MODE}` ("organized", "simple", or "disabled").

---

## STEP 3: CLONE AND CREATE STRUCTURE

**Skip this step if `{WORKTREE_MODE}` is "disabled".**

Delegate to `gitflow-init-clone` sub-agent:

```
Task(gitflow-init-clone):
  prompt: |
    Create GitFlow structure:
    - REPO_URL: {REPO_URL}
    - PROJECT_BASE: {PROJECT_BASE}  (already platform-normalized absolute path)
    - PROJECT_NAME: {PROJECT_NAME}
    - WORKTREE_MODE: {WORKTREE_MODE}
    - PLATFORM: {PLATFORM}
  subagent_type: gitflow-init-clone
  model: sonnet
```

Check the result. If FAIL, report to user and suggest manual intervention.

---

## STEP 4: WRITE CONFIG

Write `.claude/gitflow/config.json` in develop worktree using the Write tool.

**Path (depends on worktree mode):**
- Organized: `{PROJECT_BASE}/02-Develop/.claude/gitflow/config.json`
- Simple: `{PROJECT_BASE}/develop/.claude/gitflow/config.json`
- Disabled: `{PROJECT_BASE}/.claude/gitflow/config.json`

**Content (v2.1.0):**

Compute directory names based on `{WORKTREE_MODE}`:
```
MAIN_DIR    = organized → "01-Main"  | simple → "main"  | disabled → "."
DEVELOP_DIR = organized → "02-Develop" | simple → "develop" | disabled → "."
```

```json
{
  "version": "2.1.0",
  "platform": {
    "detected": "{PLATFORM}",
    "shell": "{SHELL_TYPE}",
    "detectedAt": "{ISO_DATE}"
  },
  "workspace": {
    "path": "{normalize_path_for_storage(PARENT_DIR)}",
    "name": ""
  },
  "repository": {
    "name": "{PROJECT_NAME}",
    "rootFolder": "{normalize_path_for_storage(PROJECT_BASE)}",
    "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": "{WORKTREE_MODE != 'disabled'}",
    "mode": "{WORKTREE_MODE}",
    "structure": {
      "main": "{normalize_path_for_storage(PROJECT_BASE)}/{MAIN_DIR}",
      "develop": "{normalize_path_for_storage(PROJECT_BASE)}/{DEVELOP_DIR}",
      "features": "{normalize_path_for_storage(PROJECT_BASE)}/features",
      "releases": "{normalize_path_for_storage(PROJECT_BASE)}/releases",
      "hotfixes": "{normalize_path_for_storage(PROJECT_BASE)}/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": "en" }
}
```

**IMPORTANT:** Always store paths in config using `normalize_path_for_storage()` format (Windows-style: `D:/path/to/folder`). The `read_gitflow_config()` in `_shared.md` translates them back to platform format at read time.

---

## STEP 5: VALIDATE

**Skip this step if `{WORKTREE_MODE}` is "disabled".**

Delegate to `gitflow-init-validate` sub-agent:

```
Task(gitflow-init-validate):
  prompt: |
    Validate GitFlow installation:
    - PROJECT_BASE: {PROJECT_BASE}
    - WORKTREE_MODE: {WORKTREE_MODE}
    - REPO_URL: {REPO_URL}
    - PLATFORM: {PLATFORM}
  subagent_type: gitflow-init-validate
  model: haiku
```

Report validation results to user.

---

## STEP 6: UPDATE WORKSPACE (optional)

If `{HAS_WORKSPACE}=true`, update the existing `.smartstack-workspace.json` to include this project.

If `{HAS_WORKSPACE}=false` and `{SIBLING_COUNT} > 0`, suggest creating a workspace file.

---

## STEP 7: SUMMARY

**Adapt structure display based on `{WORKTREE_MODE}`:**

**Organized mode:**
```
================================================================================
                    GITFLOW INITIALIZED
================================================================================

PROJECT
  Name:       {PROJECT_NAME}
  Location:   {PROJECT_BASE}/
  URL:        {REPO_URL}
  Provider:   {GIT_PROVIDER}
  Platform:   {PLATFORM} ({SHELL_TYPE})
  Mode:       organized

STRUCTURE
  01-Main/     → main branch       ✓
  02-Develop/  → develop branch    ✓
  features/    → feature worktrees ✓
  releases/    → release worktrees ✓
  hotfixes/    → hotfix worktrees  ✓

CONFIG
  Version:    2.1.0
  Path:       02-Develop/.claude/gitflow/config.json

VALIDATION
  {validation_summary}

NEXT STEPS
  cd "{PROJECT_BASE}/02-Develop"
  /gitflow -f <feature-name>

================================================================================
```

**Simple mode:**
```
================================================================================
                    GITFLOW INITIALIZED
================================================================================

PROJECT
  Name:       {PROJECT_NAME}
  Location:   {PROJECT_BASE}/
  URL:        {REPO_URL}
  Provider:   {GIT_PROVIDER}
  Platform:   {PLATFORM} ({SHELL_TYPE})
  Mode:       simple

STRUCTURE
  main/        → main branch       ✓
  develop/     → develop branch    ✓
  features/    → feature worktrees ✓
  releases/    → release worktrees ✓
  hotfixes/    → hotfix worktrees  ✓

CONFIG
  Version:    2.1.0
  Path:       develop/.claude/gitflow/config.json

VALIDATION
  {validation_summary}

NEXT STEPS
  cd "{PROJECT_BASE}/develop"
  /gitflow -f <feature-name>

================================================================================
```

**Disabled mode:**
```
================================================================================
                    GITFLOW INITIALIZED (no worktrees)
================================================================================

PROJECT
  Name:       {PROJECT_NAME}
  Location:   {PROJECT_BASE}/
  URL:        {REPO_URL}
  Provider:   {GIT_PROVIDER}
  Platform:   {PLATFORM} ({SHELL_TYPE})
  Mode:       disabled (git checkout)

CONFIG
  Version:    2.1.0
  Path:       .claude/gitflow/config.json

NEXT STEPS
  cd "{PROJECT_BASE}"
  git checkout develop
  /gitflow -f <feature-name>

================================================================================
```

---

## WORKSPACE MODE (`--workspace`)

When called with `--workspace` flag:

1. Ask for workspace directory
2. Ask for list of repo URLs (one per line) or detect from sibling folders
3. Create `.smartstack-workspace.json` at workspace root
4. Loop: for each repo, run Steps 1-6 with workspace defaults pre-populated
5. Display global summary

```json
{
  "questions": [{
    "question": "Enter repository URLs (one per line) or detect from existing folders?",
    "header": "Repos",
    "options": [
      {"label": "Detect from folders", "description": "Scan {WORKSPACE_DIR} for git repositories"},
      {"label": "Enter URLs", "description": "Provide a list of repository URLs"}
    ],
    "multiSelect": false
  }]
}
```

## Priority

Correctness > Speed > UX. The init must succeed on every platform (WSL, Windows, macOS, Linux).
