# Git

> Reglas de Git - configuración, branching, commits, PRs, hooks, merge vs rebase, debugging, versionado

- **Type:** Skill
- **Install:** `agentstack add skill-14bryanespinoza-agent-stack-git`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [14BryanEspinoza](https://agentstack.voostack.com/s/14bryanespinoza)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [14BryanEspinoza](https://github.com/14BryanEspinoza)
- **Source:** https://github.com/14BryanEspinoza/agent-stack/tree/agent-stack/skills/git

## Install

```sh
agentstack add skill-14bryanespinoza-agent-stack-git
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Git - Reglas y Convenciones

---

## 1. Filosofía

1. **Commits atómicos** — Un commit = un cambio lógico. Commits pequeños, descriptivos y revisables.
2. **Historia limpia** — Preferir rebase sobre merge en ramas locales. Sin commits de WIP, merge bubbles innecesarias ni mensajes vacíos.
3. **Ramas efímeras** — Las ramas de feature/bugfix viven lo justo para completar el trabajo y se eliminan al mergear.
4. **Conventional Commits** — Estándar obligatorio para mensajes. Permite generar changelogs, versionado semántico y releases automatizados.
5. **Progressive exposure** — El código se expone al equipo vía PR con code review. Nunca se pushea directamente a `main` o `develop`.

---

## 2. Versión Mínima

| Tecnología | Versión Mínima |
| ---------- | -------------- |
| Git        | 2.30+          |

---

## 3. Instalación y Configuración Inicial

### Config global

```bash
git config --global user.name "Tu Nombre"
git config --global user.email "tu@email.com"
git config --global init.defaultBranch main
git config --global core.autocrlf input      # macOS/Linux
git config --global core.autocrlf true       # Windows
git config --global pull.rebase true
git config --global fetch.prune true
```

### Alias útiles

```bash
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.ci "commit"
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.st "status"
git config --global alias.undo "reset HEAD~1 --soft"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.unstage "restore --staged"
git config --global alias.discard "restore"
git config --global alias.last "log -1 HEAD"
```

### .gitconfig completo recomendado

```ini
[user]
  name = Tu Nombre
  email = tu@email.com
[init]
  defaultBranch = main
[core]
  autocrlf = input
  editor = code --wait
[pull]
  rebase = true
[fetch]
  prune = true
[merge]
  tool = vscode
[diff]
  tool = vscode
[alias]
  lg = log --oneline --graph --decorate --all
  ci = commit
  co = checkout
  br = branch
  st = status
  undo = reset HEAD~1 --soft
  amend = commit --amend --no-edit
  unstage = restore --staged
  discard = restore
  last = log -1 HEAD
```

---

## 4. Branching Strategy

### Ramas Principales

| Rama      | Propósito                             |
| --------- | ------------------------------------- |
| `main`    | Producción, siempre estable           |
| `develop` | Integración, features se mergean aquí |

### Ramas de Soporte

| Rama             | Base      | Merge hacia      | Propósito                        |
| ---------------- | --------- | ---------------- | -------------------------------- |
| `feature/` | `develop` | `develop`        | Nueva funcionalidad              |
| `bugfix/`  | `develop` | `develop`        | Corrección en desarrollo         |
| `hotfix/`  | `main`    | `main`+`develop` | Corrección urgente en producción |
| `release/` | `develop` | `main`+`develop` | Preparación de release           |

### Convención de Nombres

```text
feature/-
bugfix/-
hotfix/-
release/v
```

### Ejemplos

```text
feature/42-add-user-auth
bugfix/53-fix-login-redirect
hotfix/58-patch-security-vuln
release/v1.2.0
```

---

## 5. Commits

### Formato (Conventional Commits)

```text
(): 

```

### Tipos

| Tipo       | Uso                                             |
| ---------- | ----------------------------------------------- |
| `feat`     | Nueva funcionalidad                             |
| `fix`      | Corrección de bug                               |
| `docs`     | Documentación                                   |
| `style`    | Formato, linting, whitespace (no cambia lógica) |
| `refactor` | Refactor sin cambiar funcionalidad              |
| `perf`     | Mejora de rendimiento                           |
| `test`     | Tests nuevos o actualizados                     |
| `chore`    | Build, CI, tooling                              |
| `revert`   | Revertir un cambio                              |

### Breaking Changes

```text
feat(api)!: change user endpoint response format

BREAKING CHANGE: The /api/users endpoint now returns { data: [...] }
instead of the previous flat array format.
```

### Ejemplos Commits

```text
feat(auth): add login form validation

fix(api): handle 404 when user not found

docs(readme): update installation instructions

refactor: extract date formatting to utils

chore: update eslint config to v9
```

### Reglas

- **Inglés** obligatorio para nombres y mensajes
- Descripción: presente imperativo, sin punto final
- Cuerpo: explicar el **qué** y **por qué**, no el cómo
- Footer: referenciar issues (`Closes #42`, `Fixes #53`)
- Commits atómicos: un cambio lógico por commit

```text
# ❌ Malo
fix stuff
update
WIP
asdf

# ✅ Bueno
feat(api): add pagination to user list
Closes #42
```

### Firmado de Commits (GPG)

```bash
# Generar clave GPG
gpg --full-generate-key

# Configurar Git
git config --global user.signingkey 
git config --global commit.gpgsign true

# Firmar commit
git commit -S -m "feat: add secure endpoint"

# Verificar firma
git log --show-signature -1
```

---

## 6. Pull Requests

### Título

Mismo formato que commits:

```text
feat(auth): add login form validation
```

### Descripción

```markdown
## Descripción

## Cambios

- [ ] Feature
- [ ] Bugfix
- [ ] Refactor
- [ ] Tests
- [ ] Documentación

## Cómo probar

1. Ir a /login
2. Ingresar credenciales inválidas
3. Ver error en pantalla

## Screenshots

## Closes

Closes #42
```

### Checklist antes del PR

- [ ] Código sigue convenciones del proyecto
- [ ] Tests pasan localmente (`pnpm test` o `npm test`)
- [ ] Linter pasa (`pnpm lint` o `npm run lint`)
- [ ] Sin `console.log` / `debugger`
- [ ] Sin código comentado
- [ ] Documentación actualizada si aplica
- [ ] Sin merge conflicts con rama destino

### Code Review

```text
✅ Aprobar cuando:
- Código funciona correctamente
- Sigue convenciones del proyecto
- Tests cubren el cambio
- No hay problemas de seguridad/performance

❌ Solicitar cambios cuando:
- Hay bugs o edge cases no cubiertos
- No sigue convenciones del proyecto
- Falta documentación
- El enfoque es incorrecto
```

---

## 7. Merge vs Rebase vs Squash

| Estrategia | Cuándo usarla                                         |
| ---------- | ----------------------------------------------------- |
| **Merge**  | Rama compartida, preservar historial completo         |
| **Rebase** | Rama local/feature, historial lineal                  |
| **Squash** | PR pequeño, commits de WIP que no aportan valor solos |

### Merge (rama compartida)

```bash
git checkout develop
git merge --no-ff feature/42-add-user-auth
# --no-ff fuerza un commit de merge aunque sea fast-forward
```

### Rebase (rama local)

```bash
git checkout feature/42-add-user-auth
git rebase develop
# Re-escribe commits sobre la punta de develop
```

### Rebase interactivo

```bash
git rebase -i HEAD~4
# Comandos disponibles:
# pick    = usar commit tal cual
# reword  = cambiar mensaje
# edit    = detener para enmendar contenido
# squash  = fusionar con commit anterior
# fixup   = fusionar sin conservar mensaje
# drop    = eliminar commit
```

### Squash (PR final)

```bash
# Opción 1: squash merge en GitHub/GitLab
# Opción 2: local antes de mergear
git rebase -i HEAD~3
# Marcar todos como 'squash' excepto el primero
```

---

## 8. Flujo de Trabajo

### Feature

```bash
git checkout develop
git pull origin develop
git checkout -b feature/42-add-user-auth
# ... trabajar en pequeños commits ...
git add .
git commit -m "feat(auth): add login form"
git add .
git commit -m "feat(auth): add validation"
git push origin feature/42-add-user-auth
# Crear PR en GitHub
```

### Hotfix

```bash
git checkout main
git pull origin main
git checkout -b hotfix/58-patch-security-vuln
# ... corregir ...
git commit -m "fix: patch XSS vulnerability in search input"
git push origin hotfix/58-patch-security-vuln
# PR directo a main
# Luego mergear main a develop
```

### Release

```bash
git checkout develop
git checkout -b release/v1.2.0
# ... ajustes finales, bump version ...
git commit -m "chore: bump version to 1.2.0"
git checkout main
git merge --no-ff release/v1.2.0
git tag -a v1.2.0 -m "Release v1.2.0"
git push origin main --tags
git checkout develop
git merge --no-ff release/v1.2.0
git branch -d release/v1.2.0
```

### Sincronizar feature con develop

```bash
# Opción: rebase
git checkout feature/42-add-user-auth
git fetch origin
git rebase origin/develop

# Opción: merge (equipos grandes)
git merge origin/develop
```

---

## 9. .gitignore

### Patrones Esenciales

```gitignore
# Dependencias
node_modules/
.pnp
.pnp.js

# Build
dist/
build/
.next/
out/
.cache/

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db

# Env
.env
.env.local
.env.*.local

# Logs
*.log
npm-debug.log*

# Testing
coverage/
.vitest/
__snapshots__/

# Temp
*.tmp
*.temp
*.tsbuildinfo

# Docker
.docker/
```

---

## 10. Tags y Versionado Semántico

### SemVer

```text
MAJOR.MINOR.PATCH

MAJOR: cambios incompatibles (breaking changes)
MINOR: nuevas funcionalidades (backward compatible)
PATCH: bug fixes (backward compatible)
```

### Crear tags

```bash
# Ligero (solo puntero)
git tag v1.2.0

# Anotado (recomendado - incluye metadata)
git tag -a v1.2.0 -m "Release v1.2.0"

# Firmado
git tag -s v1.2.0 -m "Release v1.2.0"
```

### Publicar tags

```bash
git push origin v1.2.0
git push origin --tags  # Todos los tags
```

### Navegar tags

```bash
git tag -l "v1.*"              # Listar tags que coinciden
git checkout v1.2.0            # Ir a tag específico
git describe --tags            # Tag más cercano desde HEAD
```

---

## 11. Git Hooks

### Pre-commit hook

```bash
#!/bin/sh
# .git/hooks/pre-commit

# Evitar commits a ramas protegidas
branch=$(git symbolic-ref HEAD | sed 's|refs/heads/||')
if [ "$branch" = "main" ] || [ "$branch" = "develop" ]; then
  echo "❌ No puedes commitear directamente a $branch"
  exit 1
fi

# Verificar que no haya console.log
if git diff --cached --name-only | xargs grep -l "console\.log" 2>/dev/null; then
  echo "❌ Se encontró console.log en los archivos staged"
  exit 1
fi
```

### commit-msg hook (validar Conventional Commits)

```bash
#!/bin/sh
# .git/hooks/commit-msg

commit_msg=$(cat "$1")
pattern="^(feat|fix|docs|style|refactor|perf|test|chore|revert)(\(.+\))?!?:\ .{1,}"

if ! echo "$commit_msg" | grep -qE "$pattern"; then
  echo "❌ El mensaje de commit no sigue Conventional Commits"
  echo "Formato: (): "
  echo "Ejemplo: feat(auth): add login form"
  exit 1
fi
```

### Husky + lint-staged (recomendado)

```bash
pnpm add -D husky lint-staged

# package.json
{
  "lint-staged": {
    "*.{js,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.css": ["prettier --write"]
  }
}

# .husky/pre-commit
npx lint-staged
```

---

## 12. Comandos Avanzados

### Stash

```bash
git stash push -m "WIP: login form validation"    # Guardar cambios
git stash list                                      # Listar stashes
git stash pop                                       # Recuperar + eliminar
git stash apply stash@{2}                           # Recuperar sin eliminar
git stash drop stash@{2}                            # Eliminar stash específico
git stash clear                                     # Eliminar todos
git stash branch feature/new-branch                 # Crear rama desde stash
```

### Cherry-pick

```bash
# Aplicar un commit específico a la rama actual
git cherry-pick abc1234

# Aplicar múltiples commits
git cherry-pick abc1234 def5678

# Sin commitear (solo aplicar cambios)
git cherry-pick -n abc1234
```

### Reflog (recuperación de desastres)

```bash
git reflog                    # Ver historial de movimientos de HEAD
git reflog show feature/42    # Reflog de una rama específica

# Recuperar commit "perdido" después de un reset
git reflog                    # Encontrar el hash
git cherry-pick         # Aplicarlo de nuevo
```

### Bisect (debugging binario)

```bash
# Iniciar búsqueda
git bisect start
git bisect bad               # Commit actual es malo
git bisect good v1.0.0       # Tag/commit donde funcionaba

# Git checkout automático, probar en cada paso:
# - Si el bug existe: git bisect bad
# - Si el bug no existe: git bisect good
# Repetir hasta encontrar el commit culpable

git bisect reset             # Salir del modo bisect

# Automatizado
git bisect start HEAD v1.0.0
git bisect run npm test      # Corre test automáticamente
git bisect reset
```

### Worktrees

```bash
# Trabajar en múltiples ramas simultáneamente
git worktree add ../project-feature feature/42
git worktree add ../project-hotfix hotfix/58

# Listar worktrees
git worktree list

# Eliminar
git worktree remove ../project-feature
```

### Submodules

```bash
# Agregar submódulo
git submodule add https://github.com/user/shared-lib.git libs/shared

# Clonar repo con submódulos
git clone --recurse-submodules 

# Actualizar submódulos
git submodule update --init --recursive

# Pull con submódulos
git pull --recurse-submodules
```

### Git LFS

```bash
# Instalar
git lfs install

# Trackear tipos de archivo
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "*.mp4"

# Ver archivos tracked
git lfs ls-files
```

---

## 13. Integración con GitHub / GitLab

### GitHub CLI

```bash
# Autenticación
gh auth login

# Crear PR desde terminal
gh pr create --title "feat(auth): add login form" --body "Closes #42"

# Ver PRs
gh pr list
gh pr checkout 42
gh pr view 42

# Mergear PR
gh pr merge 42 --squash
```

### GitHub Actions (CI básico)

```yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: "pnpm"
      - run: pnpm install --frozen-lockfile
      - run: pnpm lint
      - run: pnpm test
```

### Commit Status Checks

```bash
# Desde GitHub CLI
gh pr checks 42 --watch

# Bloquear PR si checks fallan (configurar en GitHub settings)
# Settings > Branches > Add rule > Require status checks
```

---

## 14. Solución de Problemas Comunes

```bash
# Commitear en la rama equivocada
git log --oneline -1              # Verificar último commit
git reset HEAD~1 --soft           # Deshacer commit (cambios en staging)
git stash                         # Guardar cambios
git checkout develop              # Ir a la rama correcta
git stash pop                     # Recuperar cambios

# Mensaje de commit incorrecto
git commit --amend -m "feat: correct message"

# Agregar archivo olvidado al último commit
git add archivo-olvidado.js
git commit --amend --no-edit

# Conflictos de merge
git merge feature/42
# ... resolver conflictos manualmente ...
git add .
git commit --no-edit

# Push rechazado (fueron push intermedias)
git fetch origin
git rebase origin/develop
git push origin feature/42 --force-with-lease
```

---

## 15. Prohibiciones

- ❌ **NO hacer commit directamente a `main` o `develop`**
- ❌ No usar `git push --force` en ramas compartidas (usar `--force-with-lease`)
- ❌ No commits gigantes (+200 líneas sin justificación)
- ❌ No mensajes de commit vacíos o sin sentido
- ❌ No mergear PR sin approval
- ❌ No dejar `WIP` o `fix` en commits finales
- ❌ No ignorar `.gitignore` (no commitees node_modules, .env, dist/)
- ❌ No usar `git commit --no-verify` salvo emergencia justificada
- ❌ No pushear `.env` o secrets
- ❌ No hacer rebase en ramas compartidas con otros developers
- ❌ No borrar tags sin consenso del equipo

---

## 16. Workflow con Permiso del Usuario

Nunca ejecutes un comando git sin permiso explícito del usuario. Sigue este workflow:

### Paso a paso

```text
1. Explicar plan
   → "Voy a commitear los cambios en SKILL.md y skills/git/SKILL.md"
   → "Mensaje: feat: add execution permission constraints"

2. Mostrar evidencia
   → "Mensaje; En el archivo.ts:1-10 cambios realizados"
   → Mostrar el comando exacto que se va a eje

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [14BryanEspinoza](https://github.com/14BryanEspinoza)
- **Source:** [14BryanEspinoza/agent-stack](https://github.com/14BryanEspinoza/agent-stack)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-14bryanespinoza-agent-stack-git
- Seller: https://agentstack.voostack.com/s/14bryanespinoza
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
