use-worktrees
Skill0 starsChanged 5 months agoMITView on GitHub
Usar antes de iniciar trabajo de código que va a producir commits y PR — fix, feature, refactor, chore. También cuando la rama de integración del repo no es obvia (puede ser main, master, staging, dev, develop, trunk u otra).
- Commits and pushes
1 other project uses a version of this.
Adopted by
Most recently taken up by
- maxedapps/agent-skillstheir own version, first seen Sep 24, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- maxedapps/agent-skills★ 59same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository18 other files it gives its agents.
- adversarial-code-reviewSkill
- api-schema-separationSkill
- careful-destructive-opsSkill
- comments-disciplineSkill
- delegate-to-codexSkill
- design-rigor-alternativesSkill
- frontend-screen-and-loadingSkill
- migrations-alwaysSkill
- no-premature-abstractionSkill
- openapi-frontend-syncSkill
- paginate-and-filterSkill
- pr-disciplineSkill
- pre-deploy-checklistSkill
- public-artifact-hygieneSkill
- read-before-writeSkill
- reuse-existing-patternsSkill
- secrets-handlingSkill
- test-layer-disciplineSkill
The file
Files
Use Worktrees
Overview
Cada trabajo vive en su propio workspace aislado y termina con un PR
hacia la rama de integración real del repo (no necesariamente main).
Principio: detectar aislamiento primero, preferir herramientas nativas,
caer a git worktree solo si hace falta. Nunca asumir la base — resolverla,
guardarla, y usarla hasta el final.
Anunciar al inicio: "Usando la skill use-worktrees para preparar el
workspace y resolver la rama base."
Step 0: Detectar aislamiento existente
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
git rev-parse --show-superproject-working-tree 2>/dev/null # vacío = no submódulo- Si
GIT_DIR != GIT_COMMONy no es submódulo → ya estás en un worktree. Saltar Step 3 (crear worktree) pero igual ejecutar Step 1 y Step 2: la base sigue haciendo falta para abrir el PR del Step 4. - Si hay una herramienta nativa (
EnterWorktree,/worktree,--worktree), usarla cuando llegues a Step 3. NO corrergit worktree addcuando existe nativa — crea estado fantasma que la plataforma no maneja. Step 1 y Step 2 siguen aplicando antes.
Step 1: Resolver la rama base
Esta es la decisión que cambia entre proyectos. Probar en este orden, parar en el primer paso que dé respuesta sin ambigüedad:
- Memoria previa. ¿Existe
reference_base_branch_<repo>.mden el auto-memory dir? → usar ese valor. - Convención documentada del repo. Buscar mención explícita de la
rama de PRs en
CLAUDE.md, luegoCONTRIBUTING.md, luegoREADME.md. - Triggers de CI. Revisar
.github/workflows/*.yml: la rama que dispara los deploys suele ser la base. - Default del remoto.
gh repo view --json defaultBranchRef -q '.defaultBranchRef.name'. Buen candidato pero no definitivo (algunos equipos mergean astagingaunquemainsea el default). - Preguntar al usuario — único paso obligatorio si los anteriores dejaron duda. Ver abajo.
Preguntar al usuario solo si los 4 pasos anteriores no produjeron una respuesta sin ambigüedad. Mostrar las ramas remotas y preguntar literal:
git branch -r | grep -v HEAD | head -10"Para abrir PRs en este repo, ¿cuál es la rama de integración? (suele ser
main,master,staging,dev,developotrunk)"
Step 2: Persistir la base en memoria
Una vez resuelta, guardar como auto-memoria para que sesiones futuras no
vuelvan a preguntar. Convención exacta (matchea reference_n8n_instances.md,
reference_ve_tools.md, etc.):
Ruta del archivo de memoria (auto-memory dir; Claude conoce la ruta exacta en su system prompt):
<auto_memory_dir>/reference_base_branch_<repo>.md<repo> es el nombre del directorio del repo, en minúsculas y con guiones.
Contenido exacto:
---
name: reference-base-branch-<repo>
description: Rama de integración del repo <repo>. Feature branches parten de aquí y PRs apuntan acá.
metadata:
type: reference
---
**Repo:** `<owner>/<repo>` (path local: `<absolute path>`)
**Rama de integración:** `<branch>`
**Cómo se determinó:** <"usuario confirmó YYYY-MM-DD" | "CLAUDE.md" | "gh default + usuario confirmó">
Aplicar: `git worktree add` parte de `origin/<branch>`. `gh pr create --base <branch>`.Append a MEMORY.md una sola línea, mismo estilo que las existentes.
Plantilla (reemplazar REPO y BRANCH):
- [Base branch REPO](reference_base_branch_REPO.md) — BRANCH
Si no se puede resolver el auto-memory dir, escribir a .claude/memory/
en la raíz del repo y avisarle al usuario.
Step 3: Crear el worktree
git fetch origin
BASE="<rama resuelta en Step 1>"
SLUG="<tipo>/<descriptive-slug>" # feature/, fix/, refactor/, chore/, docs/, perf/, test/
PATH_WT="../$(basename "$PWD")-${SLUG##*/}"
# Precondiciones
git ls-remote --exit-code --heads origin "$BASE" >/dev/null || { echo "Base $BASE no existe en origin"; exit 1; }
[ -e "$PATH_WT" ] && { echo "$PATH_WT ya existe"; exit 1; }
git show-ref --verify --quiet "refs/heads/$SLUG" && { echo "Branch $SLUG ya existe local"; exit 1; }
git worktree add -b "$SLUG" "$PATH_WT" "origin/$BASE"
cd "$PATH_WT"Si el repo usa otra convención de prefijos (bugfix/, ID de ticket),
respetarla — verificar git log --oneline -20 y CONTRIBUTING.md.
Si por error había cambios sin commitear en el checkout principal,
git stash ahí y git stash pop en el worktree recién creado.
La skill se detiene acá. El trabajo dentro del worktree (setup de deps, edits, tests, commits) no es responsabilidad de esta skill. Reinvocá la skill cuando el trabajo esté listo para abrir PR (Step 4), o cuando haya que limpiar (Step 5).
Step 4: Cerrar con PR
# Precondiciones
gh auth status >/dev/null 2>&1 || { echo "gh no autenticado"; exit 1; }
git fetch origin
# Default seguro: fast-forward merge. Rebase SOLO si la branch nunca fue
# pusheada o el equipo lo manda explícitamente.
git merge --ff-only "origin/$BASE" || { echo "No FF-able. Resolver manual."; exit 1; }
git push -u origin "$SLUG"
# El --base es OBLIGATORIO. No confiar en lo que gh infiera.
gh pr create --base "$BASE" --head "$SLUG" \
--title "<tipo>: <descripción corta>" \
--body "<descripción según convención del repo>"
# Verificar antes de declarar éxito
gh pr view --json url,baseRefName -q '"PR " + .url + " → " + .baseRefName'Step 5: Limpieza (post-merge)
Cuando el PR ya está mergeado en BASE:
cd <checkout principal>
git worktree remove "$PATH_WT"
git branch -D "$SLUG" # solo si la branch local quedó obsoleta
git fetch --prune originReport (al terminar)
Worktree: <full path>
Branch: <slug> (base origin/<BASE>)
PR: <url o "pendiente">Quick Reference
| Situación | Acción |
| Ya en worktree linked | Saltar a Step 2 |
| Hay tool nativa de worktree | Usarla, no git worktree add |
Memoria reference_base_branch_<repo>.md existe | Usar ese valor sin preguntar |
Base declarada en CLAUDE.md o CONTRIBUTING.md | Usarla, no preguntar |
| Ningún paso del waterfall fue concluyente | Preguntar al usuario |
BASE no existe en origin | Abortar antes de crear worktree |
| Path del worktree ya existe | Abortar, elegir otro slug |
| Branch local ya existe | Abortar, elegir otro slug |
gh auth status falla | Pedirle al usuario que autentique |
merge --ff-only falla | Resolver manual; no rebasar automático |
| PR ya mergeado | Step 5: git worktree remove + git branch -D |
Common Mistakes
- Asumir
maincomo base. Resolver siempre con el waterfall del Step 1. git rebaseautomático. Cambia historia y puede romper colaboradores; usarmerge --ff-onlypor default.gh pr createsin--base. GitHub usa el default del repo, que no siempre es la base correcta.- Crear worktree dentro del repo principal. Usar carpeta hermana
(
../<repo>-<slug>) o.worktrees/solo si está en.gitignore. - Saltar Step 0. Crear worktree dentro de otro worktree rompe estado.
- Escribir la memoria con guiones (
reference-base-branch-...) cuando el dir usa underscores (reference_base_branch_...). Match exacto.
Red Flags
Nunca:
- Correr
git worktree addcuando hay tool nativa disponible. - Hacer commit en el checkout principal sin invocar esta skill primero.
- Abrir un PR sin
--baseexplícito. - Rebasear automáticamente — siempre
merge --ff-onlysalvo orden explícita. - Declarar el PR abierto antes de verificar con
gh pr view.
Siempre:
- Step 0 (detectar aislamiento) antes que nada.
- Resolver la base con el waterfall y persistirla en memoria.
- Verificar precondiciones (
gh auth, base existe en remoto, path libre). - Cerrar reportando el resultado de
gh pr viewliteral.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

