---
name: git-worktree
description: >
  Create a git worktree to isolate changes on a working branch.
  Use when the user says /git-worktree, /worktree, 'worktree', 'isole les changements',
  'travaille dans un worktree', 'create a worktree', or needs to work in isolation
  on a branch without affecting the main working directory.
argument-hint: "<branch name or GitLab issue IID>"
allowed-tools:
  - Bash
  - Glob
  - Grep
  - Read
  - AskUserQuestion
  - EnterWorktree
  - ExitWorktree
---

Create a git worktree to isolate changes on a working branch, keeping the main working directory clean.

## Step 0 — Detect context

```bash
CTX=$(pysae-ai-tools internal detect-context)
IS_CI=$(echo "$CTX" | jq -r '.is_ci')
GIT_BRANCH=$(echo "$CTX" | jq -r '.git_branch // empty')
MR_SOURCE_BRANCH=$(echo "$CTX" | jq -r '.mr_source_branch // empty')
MR_IID=$(echo "$CTX" | jq -r '.mr_iid // empty')
DEFAULT_BRANCH=$(echo "$CTX" | jq -r '.default_branch // "main"')
```

If `IS_CI` is `true`, **do not create a worktree**. Stay on the current branch and return immediately:
> Worktree non créé : mode CI (on reste sur la branche courante).

## Step 1 — Check IDE connection (local mode only)

If an IDE MCP server is connected (e.g. `mcp__ide__getDiagnostics` is available), worktrees risk desynchronizing the IDE (files edited in the worktree won't appear in the IDE).

- **Invoked directly by the user:** warn and ask for confirmation:
  > Un IDE est connecte a cette session. Les worktrees changent le repertoire de travail, ce qui peut desynchroniser l'IDE. Tu veux quand meme continuer ?
  Only proceed if the user confirms. If not, suggest working directly on the branch instead.

- **Invoked by another skill (delegated):** skip the worktree silently — just log a short message and return without creating anything:
  > Worktree non cree : IDE connecte (risque de desynchronisation).

## Step 2 — Determine the target branch

Use context from Step 0 (`detect_context`) and `$ARGUMENTS`:

1. **Existing branch name** in `$ARGUMENTS` (e.g. `feat/42-add-login`) → use it directly
2. **GitLab ref** in `$ARGUMENTS` (`#42`, `!99`, URL) → `detect_context` already resolved it:
   - If `MR_SOURCE_BRANCH` is set → use it
   - If only `ISSUE_IID` is set (no MR) → derive branch from issue title:
     ```bash
     ISSUE_TITLE=$(echo "$CTX" | jq -r '.issue_title // empty')
     SLUG=$(echo "${ISSUE_TITLE}" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | cut -c1-40 | sed 's/-$//')
     BRANCH="feat/${ISSUE_IID}-${SLUG}"
     ```
3. **No argument** → auto-detect from context:
   - If `GIT_BRANCH` is not `DEFAULT_BRANCH` → already on a feature branch, use it
   - If `MR_SOURCE_BRANCH` is set → use it (MR detected for current branch)
   - Otherwise → ask the user what branch to work on

Check if the branch already exists (locally or remote):
```bash
git branch -a --list "*${BRANCH}*"
```

## Step 3 — Create the worktree

Use the `EnterWorktree` tool to create an isolated worktree. Use the branch name as the worktree name:

```
EnterWorktree(name: "<branch-name>")
```

This creates a worktree in `.claude/worktrees/<name>` with a new branch based on HEAD, and switches the session into it.

## Step 4 — Set up the branch

**Toujours rebaser sur la branche par défaut** dès l'entrée dans le worktree, quelle que soit la branche courante du repo principal :

```bash
git fetch origin "${DEFAULT_BRANCH}"
git reset --hard "origin/${DEFAULT_BRANCH}"
```

### If the branch already exists remotely:
```bash
git fetch origin "${BRANCH}"
git checkout "${BRANCH}"
```

### If the branch is new:
La branche locale est maintenant alignée sur `origin/${DEFAULT_BRANCH}`. Renommer la branche locale, pousser et configurer le tracking :
```bash
git branch -m "${BRANCH}"
git push -u origin "${BRANCH}"
```

## Step 5 — Confirm

Report to the user:
- Worktree location
- Branch name
- Base branch / tracking info
- Remind them that they can exit with `/code-worktree exit` or by asking to "exit the worktree"

> 📂 **Changement de répertoire de travail**
> Je travaille maintenant dans : `<WORKTREE_PATH>`
> Branche : `<BRANCH>`
> Pour sortir du worktree : demande-moi de « sortir du worktree ».

## Exiting the worktree

When the user asks to exit/leave the worktree ("exit worktree", "sors du worktree", "quitte le worktree"):

1. Check for uncommitted changes: `git status --porcelain`
2. Check for unpushed commits: `git log origin/<BRANCH>..HEAD --oneline 2>/dev/null`
3. If there are uncommitted or unpushed changes, warn the user and ask what to do:
   - **Keep** the worktree (changes preserved on disk)
   - **Remove** the worktree (discard everything)
4. Use `ExitWorktree` with the appropriate action
5. Confirm the directory change to the user:
   > 📂 **Retour au répertoire principal**
   > Je travaille maintenant dans : `<ORIGINAL_PATH>`

## Rules

- **Always use EnterWorktree/ExitWorktree** — never create worktrees manually with `git worktree add`
- **One worktree per session** — if already in a worktree, inform the user and ask if they want to exit first
- **Language**: French for communication, English for commands

$ARGUMENTS
