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

using-git-worktrees · osmontero — скилл для Claude Code: изоляция задач

Скилл using-git-worktrees для Claude Code создаёт отдельный Git worktree для задачи. Запускается перед работой над функцией или выполнением плана, когда текущую рабочую копию нужно оставить нетронутой.

MIT 103 установок ★ 18 обновлён 2026-10-23

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add osmontero/opencode-skills --skill using-git-worktrees -a claude-code
Открыть на GitHub

Что делает using-git-worktrees

Скилл создаёт изолированную рабочую копию репозитория и переносит в неё сессию. В OpenCode v2 он использует встроенные инструменты worktree; в Claude Code, Codex и обычном терминале предусмотрен запасной вариант с git worktree add.

Новая рабочая копия начинается с detached HEAD, поэтому внутри неё нужно создать ветку командой git checkout -b. Скилл проверяет базовые тесты и сообщает об ошибках, если они есть. Зависимости в worktree не общие с основной копией: настройка проекта запускается заново по найденным файлам, например через npm install или pip install -r requirements.txt.

Если worktree размещается внутри репозитория, его каталог должен попасть в .gitignore до создания. В OpenCode сессия переключается через session_move, а не обычный cd; созданный вручную worktree OpenCode не учитывает в своих инструментах управления.

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

  • создать отдельную рабочую копию для новой функции
  • начать реализацию плана без переключения основной ветки
  • создать ветку внутри изолированного worktree
  • проверить тесты на чистой копии проекта

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

  • Подготовь отдельный worktree для функции авторизации и переключи туда сессию.
  • Создай изолированную рабочую копию для выполнения плана миграции.
  • Подними worktree для исправления тайм-аута входа и проверь базовые тесты.

Как установить using-git-worktrees

1Через Skills CLI (Vercel)

npx skills add osmontero/opencode-skills --skill using-git-worktrees -a claude-code

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

~/.claude/skills/using-git-worktrees/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/using-git-worktrees/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об using-git-worktrees

Как установить using-git-worktrees в Claude Code?

Выполни npx skills add osmontero/opencode-skills --skill using-git-worktrees -a claude-code. Файл скилла находится по пути ~/.claude/skills/using-git-worktrees/SKILL.md.

Что делает using-git-worktrees?

Создаёт отдельный Git worktree и переносит туда сессию, чтобы работа над задачей шла отдельно от основной рабочей копии. Также запускает базовые тесты проекта.

Почему после создания worktree нужно создать ветку?

Новый worktree создаётся на detached HEAD, а не на отдельной ветке. Скилл предлагает создать ветку внутри него командой git checkout -b <branch-name>.

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

SKILL.md · MIT
---
name: using-git-worktrees
description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates an isolated git worktree (via the native opencode v2 worktree tools) and moves the session into it
compatibility: opencode
---

# Using Git Worktrees

## Overview

Git worktrees create isolated workspaces sharing the same repository, allowing work on multiple branches simultaneously without switching.

**Core principle:** In opencode v2, worktrees are created with the native `worktree_*` tools, and the *session* moves into the worktree — not just the shell. This keeps opencode's tracking (list/remove), project config, and AGENTS.md discovery pointing at the right place.

**Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."

## Default Path: Native Worktree Tools

Use this when running inside opencode v2 (the normal case). The tools are `worktree_create`, `worktree_list`, `worktree_remove` (Code Mode namespace `opencode`), plus `session_move`.

### 1. Create the worktree

Call `worktree_create` with a `name` — use the feature/branch name (e.g. `auth`, `fix-login-timeout`). It returns `{ directory }`.

Where the worktree lands is decided by the `worktree.directory` setting in the project's opencode config, not by the skill:

- **Not set (default):** opencode's data directory, `worktree/<project-id prefix>/<name>` — outside the repo, so nothing to gitignore.
- **Set** (e.g. `"worktree": { "directory": ".worktrees" }`): relative paths resolve against the project's canonical checkout. If the directory is *inside* the repo, it must be gitignored (see below).

Do not hand-roll the location with `git worktree add` — opencode only records and manages worktrees it created itself, so manual ones are invisible to `worktree_list` / `worktree_remove`.

If the user wants a non-default location, the v2-idiomatic move is to set `worktree.directory` in the config (and note it in AGENTS.md or memory) — not to pick a path per session.

### 2. Create the branch

`worktree_create` does not take a branch name: the new worktree is at a **detached HEAD** on the repo's current commit. Create the branch from inside the worktree:

```bash
git checkout -b "<branch-name>"
```

(`git checkout main` would fail — main is already checked out in the primary worktree; that is expected and not an error.)

### 3. Move the session into the worktree

Call `session_move` with the worktree directory as `directory`. The move takes effect at a safe boundary, so destination-dependent work (reads, edits, setup commands) belongs in the next call.

**Why this instead of `cd`:** a shell `cd` only changes one command's working directory; `session_move` re-roots the session's Location, so tool calls, config discovery, and instruction files all resolve against the worktree checkout.

### 4. Project-local location safety (only if inside the repo)

When `worktree.directory` places worktrees inside the checkout (`.worktrees/`, `worktrees/`, …), verify the directory is ignored **before** creating the worktree:

```bash
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
```

If not ignored: add it to `.gitignore`, commit, then create. This prevents worktree contents from polluting `git status` or being accidentally committed.

### 5. Run project setup

The worktree is a fresh checkout — dependencies are not shared with the main worktree. Auto-detect and run setup:

```bash
# Node.js
[ -f package.json ] && npm install

# Rust
[ -f Cargo.toml ] && cargo build

# Python
[ -f requirements.txt ] && pip install -r requirements.txt
[ -f pyproject.toml ] && poetry install

# Go
[ -f go.mod ] && go mod download
```

### 6. Verify clean baseline and report

Run the project's tests to confirm the worktree starts green:

```bash
# project-appropriate: npm test / cargo test / pytest / go test ./...
```

**If tests fail:** report the failures and ask whether to proceed or investigate. **If they pass:** report ready.

```
Worktree ready at <full-path> (branch <name>)
Session moved. Tests passing (<N> tests, 0 failures)
Ready to implement <feature-name>
```

## Cleanup

Pairs with **finishing-a-development-branch** after the work is done:

- `worktree_remove` with the worktree `directory` removes a worktree opencode recorded for the project. It uses the `edit` permission on that directory; set `force: true` only to discard uncommitted changes.
- Never remove a worktree with unpushed, unmerged commits without explicit confirmation — that deletes the work.
- A worktree created manually with raw git (fallback below) is not recorded by opencode; remove it with `git worktree remove <path>` instead.

## Fallback: Raw Git

Use `git worktree add` directly only when:

- Running in a harness without the native tools (Claude Code, Codex, plain terminal).
- The worktree needs a base other than the current HEAD (`git worktree add <path> -b <branch> <base-commit>`).
- The user explicitly asks for a manual worktree.

The same safety rules apply: gitignore check for project-local paths, setup, baseline tests, and announce the location.

## Quick Reference

| Situation | Action |
|-----------|--------|
| In opencode v2 | `worktree_create` → `git checkout -b` → `session_move` → setup → baseline |
| Non-default location wanted | Set `worktree.directory` in opencode config |
| Location inside repo | `git check-ignore` first; add to `.gitignore` + commit if not |
| Needs a base other than HEAD | Fallback: `git worktree add <path> -b <branch> <base>` |
| Tests fail during baseline | Report failures + ask |
| Work done | finishing-a-development-branch → `worktree_remove` |

## Common Mistakes

**Assuming `worktree_create` makes a branch**
- **Problem:** It leaves a detached HEAD; commits land nowhere a branch points at.
- **Fix:** `git checkout -b <branch>` inside the worktree immediately after creation.

**`cd`-ing into the worktree instead of `session_move`**
- **Problem:** Only the shell's CWD changes; the session, config, and instruction discovery still point at the old location.
- **Fix:** Call `session_move`; put dependent work in the next turn.

**Hand-rolling `git worktree add` in opencode**
- **Problem:** opencode doesn't record manual worktrees, so `worktree_list`/`worktree_remove` can't see them, and the location ignores `worktree.directory`.
- **Fix:** Use the native tools in v2; raw git is the fallback above.

**Proceeding with failing baseline tests**
- **Problem:** Can't distinguish new bugs from pre-existing issues.
- **Fix:** Report failures, get explicit permission to proceed.

## Red Flags

**Never:**
- Commit on the detached HEAD (create the branch first)
- Remove a worktree with unpushed/unmerged work without confirmation
- Skip baseline test verification
- Assume the default location when the user has a project-local preference — check/set `worktree.directory`

**Always:**
- Use native tools in opencode v2, raw git only in the fallback cases
- Move the session with `session_move` after creation
- Verify gitignore for in-repo locations
- Auto-detect and run project setup, then a clean test baseline

## Example Workflow

```
You: I'm using the using-git-worktrees skill to set up an isolated workspace.

[worktree_create name="auth" -> C:\Users\osmon\.local\share\opencode\worktree\c3488b\auth]
[git checkout -b feature/auth]
[session_move directory=<worktree dir>]
[npm install, npm test - 47 passing]

Worktree ready at C:\Users\osmon\.local\share\opencode\worktree\c3488b\auth (branch feature/auth)
Session moved. Tests passing (47 tests, 0 failures)
Ready to implement auth feature
```

## Integration

**Called by:**
- **subagent-driven-development** - REQUIRED before executing any tasks
- **executing-plans** - REQUIRED before executing any tasks
- Any skill needing an isolated workspace

**Pairs with:**
- **finishing-a-development-branch** - REQUIRED for cleanup after work complete

© osmontero · MIT · osmontero/opencode-skills

Похожие скиллы

Все скиллы по теме «Git и GitHub» →

Сначала — using-git-worktrees от других авторов.

using-git-worktrees Jesse Vincent Скилл using-git-worktrees готовит изолированное рабочее дерево перед доработкой или выполнением плана. Проверяет текущий репозиторий, выбирает нативные средства платформы либо Git. CX Codex +1 217 153установок using-git-worktrees julianobarbosa Скилл using-git-worktrees создаёт изолированный git worktree, открывает его в окне tmux текущей сессии и отправляет туда задачу — для параллельной работы над фичами. CX Codex +1 106установок using-git-worktrees GanyuanRan Скилл using-git-worktrees для Claude Code и других агентов, который решает, когда действительно нужен git worktree. Проверяет состояние репозитория и создаёт checkout только при реальном конфликте. CX Codex +1 ★ 1 450звёзд репо git-worktrees jamesrochabrun Скилл git-worktrees для Claude Code помогает вести несколько сессий параллельно на разных ветках без конфликтов и управлять изолированными копиями репозитория. CX Codex +1 135установок parallel-worktrees Rohit Ghumare Скилл parallel-worktrees для Claude Code создаёт изолированные git-worktrees и запускает параллельные сеансы кодирования. Пока тесты или сборка идут в одном окне, начните новую задачу в другом — без ожидания и переключения контекста. CX Codex +1 ★ 2 966звёзд репо create-worktrees davila7 Команда create-worktrees для Claude Code собирает все открытые PR через GitHub CLI и создаёт git worktree для каждой ветки в ./tree/<BRANCH_NAME>. Несколько PR можно ревьюить или дорабатывать параллельно, каждое в отдельном каталоге. CX Codex +1 351установок git-workflow-and-versioning addyosmani Скилл git-workflow-and-versioning, который наводит порядок в git-процессе: атомарные коммиты, короткоживущие ветки, сообщения, объясняющие зачем, а не что. Включается при любом изменении кода, которое агент готовит к коммиту. CX Codex +1 75 700установок git-worktree-isolation sentimony Скилл git-worktree-isolation оценивает риски правок и подбирает безопасное рабочее пространство перед началом задач. Помогает избежать затирания чужого кода при параллельной работе агентов. CX Codex +1 2 300установок git-merge-expert-worktree ulpi-io Скилл git-merge-expert-worktree для Claude Code и ещё пяти агентных сред: выполняет слияния и решение конфликтов в отдельном git worktree. CX Codex +1 159установок

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

Весь набор →
reviewing-interface-quality Скилл reviewing-interface-quality аудитирует готовый интерфейс по скриншотам, стилям и поведению. Нужен перед релизом или когда страница выглядит незавершённой. CX Codex +1 451установок testing-webapps Скилл testing-webapps для проверки локального веб-приложения: агент пишет Python-скрипт на Playwright, сам поднимает серверы и смотрит, что происходит в браузере. CX Codex +1 192установок reviewing-security Скилл reviewing-security помогает проверить код перед слиянием или выпуском, прослеживая путь от внешнего ввода до возможного ущерба. CX Codex +1 185установок investigating-performance Скилл investigating-performance задаёт агенту строгий протокол поиска узких мест: запрещает менять код без замеров, требует воспроизводить нагрузку и профилировать нужный ресурс. CX Codex +1 146установок applying-themes Скилл applying-themes даёт слайдам, отчётам и HTML-страницам одну палитру из восьми семантических токенов и проверяет её контраст отдельным скриптом. CX Codex +1 139установок evolving-apis-and-schemas Скилл evolving-apis-and-schemas для Claude Code помогает оценить изменения API и схем данных. Включается при правках, от которых зависят другие сервисы, клиенты или сохранённые данные. CX Codex +1 115установок executing-plans Скилл executing-plans для Claude Code выполняет письменный план разработки поэтапно и проверяет результат на контрольных точках. Запускается, когда задачи тесно связаны или субагенты недоступны. CX Codex +1 107установок creating-skills Скилл creating-skills для Claude Code помогает создавать и дорабатывать другие скиллы, а также проверять их работу. Запускается по запросам на создание скилла, оценку его результатов или настройку условий срабатывания. CX Codex +1 101установок

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

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