Skip to content

🎭 ADVANCED WORKFLOWS MASTERY

El Arte de la Manipulación de Historia en Git

"Git es una máquina del tiempo. Las operaciones avanzadas son el arte de decidir qué timeline preservar, qué editar, y qué olvidar. La maestría está en saber cuándo usar cada herramienta y cuándo la historia debe permanecer inmutable."


📖 TABLA DE CONTENIDOS

  1. La Filosofía de la Revisión Histórica
  2. Rebase Interactivo - Esculpir Historia
  3. Git Bisect - Arqueología Automatizada
  4. Stash - El Almacén Temporal
  5. Cherry-Pick - Cirugía Selectiva
  6. Reset y Reflog - Control Total
  7. Workflows Combinados
  8. Casos de Estudio

🧠 CAPÍTULO 1: LA FILOSOFÍA DE LA REVISIÓN HISTÓRICA

La Paradoja Fundamental de Git

Git existe en una tensión paradójica entre inmutabilidad y maleabilidad.

╔═══════════════════════════════════════════════════════════╗
║              LA PARADOJA DE GIT                           ║
╚═══════════════════════════════════════════════════════════╝

⚖️ DOS FILOSOFÍAS IRRECONCILIABLES

┌───────────────────────────────────────────────────────────┐
│  🔒 LADO IZQUIERDO: Historia Inmutable                    │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  PRINCIPIO:                                               │
│  "La historia es sagrada. Lo que pasó, pasó."             │
│                                                           │
│  FUNDAMENTOS:                                             │
│  ├─ Commits son permanentes                               │
│  ├─ SHA-1 hash garantiza integridad                       │
│  ├─ Historia es documentación arqueológica                │
│  └─ Confianza en el record                                │
│                                                           │
│  GARANTÍAS:                                               │
│  ├─ Auditable                                             │
│  ├─ Reproducible                                          │
│  ├─ Verificable                                           │
│  └─ Legally defensible                                    │
│                                                           │
│  CUANDO APLICA:                                           │
│  ├─ Main/master branch                                    │
│  ├─ Historia pública                                      │
│  ├─ Shared branches                                       │
│  └─ Released versions                                     │
│                                                           │
└───────────────────────────────────────────────────────────┘

VS

┌───────────────────────────────────────────────────────────┐
│  🔓 LADO DERECHO: Historia Editable                       │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  PRINCIPIO:                                               │
│  "La historia es narrativa. Debemos contar buena historia" │
│                                                           │
│  CAPACIDADES:                                             │
│  ├─ Rebase reescribe commits                              │
│  ├─ Amend modifica el último commit                       │
│  ├─ Interactive rebase reorganiza                         │
│  └─ Filter-branch borra contenido                         │
│                                                           │
│  BENEFICIOS:                                              │
│  ├─ Historia limpia y legible                             │
│  ├─ Commits lógicos y atómicos                            │
│  ├─ Facilita code review                                  │
│  └─ Mejor documentación del proyecto                      │
│                                                           │
│  CUANDO APLICA:                                           │
│  ├─ Feature branches privadas                             │
│  ├─ Work in progress                                      │
│  ├─ Pre-PR cleanup                                        │
│  └─ Local experimentation                                 │
│                                                           │
└───────────────────────────────────────────────────────────┘

                    ⚖️
               BALANCE

        ¿Cuándo preservar?
        ¿Cuándo modificar?

    La maestría está en saber elegir

Matriz de Modificabilidad

╔═══════════════════════════════════════════════════════════════════════════╗
║                    SAFETY MATRIX FOR HISTORY MODIFICATION                 ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  OPERACIÓN        │ QUÉ MODIFICA  │ SEGURA EN      │ RIESGO  │ REVERSIBLE║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  commit --amend   │ Último commit │ Private branch │ ⚠️ Low  │ ✅ Sí     ║
║                   │ (SHA cambia)  │ Solo si no     │         │ (reflog)  ║
║                   │               │ pusheado       │         │           ║
║                                                                           ║
║  rebase           │ Range commits │ Private branch │ ⚠️ Med  │ ✅ Sí     ║
║                   │ Todos SHAs    │ Feature WIP    │         │ (reflog)  ║
║                   │ cambian       │                │         │           ║
║                                                                           ║
║  rebase -i        │ Range + edit  │ Private branch │ ⚠️ Med  │ ✅ Sí     ║
║  (interactive)    │ Contenido     │ Pre-PR cleanup │         │ (reflog)  ║
║                   │ puede cambiar │                │         │           ║
║                                                                           ║
║  reset --hard     │ No modifica   │ Local only     │ ⚠️ Low  │ ✅ Sí     ║
║                   │ commits, solo │ Uncommitted    │         │ (si was   ║
║                   │ mueve HEAD    │ changes        │         │ committed)║
║                                                                           ║
║  cherry-pick      │ No modifica   │ Cualquiera     │ ✅ None │ ✅ Sí     ║
║                   │ Copia commits │ (additive)     │         │ (revert)  ║
║                                                                           ║
║  filter-branch    │ TODA historia │ Nunca en       │ 🔴 High │ ⚠️ Difícil║
║                   │ del repo      │ shared branch  │         │           ║
║                                                                           ║
║  stash            │ No modifica   │ Cualquiera     │ ✅ None │ ✅ Sí     ║
║                   │ Working dir   │ (temporal)     │         │ (pop)     ║
║                   │ cleanup       │                │         │           ║
║                                                                           ║
╚═══════════════════════════════════════════════════════════════════════════╝

La Regla de Oro Visual

🎯 GOLDEN RULE OF HISTORY REWRITING

        ┌─────────────────────────────────────────┐
        │  "NUNCA reescribas historia pública"    │
        └─────────────────────────────────────────┘
         ┌───────────────┼───────────────┐
         │               │               │
         ▼               ▼               ▼

🟢 SAFE ZONE          🟡 CAUTION ZONE       🔴 DANGER ZONE
Private Branches     Shared but Inactive   Public & Active

┌──────────────┐    ┌──────────────┐      ┌──────────────┐
│              │    │              │      │              │
│ Feature WIP  │    │ Old Features │      │ main/master  │
│ Local exper. │    │ Stale PRs    │      │ develop      │
│ Not pushed   │    │ Solo tú      │      │ release/*    │
│              │    │              │      │ Shared work  │
└──────────────┘    └──────────────┘      └──────────────┘
       │                   │                     │
       ▼                   ▼                     ▼

✅ PERMITIDO:        ⚠️ CON CUIDADO:        ❌ PROHIBIDO:

• Rebase freely     • Communicate first   • NO rebase
• Amend commits     • Check no collab     • NO amend
• Squash merges     • Force push warning  • NO force push
• Reorganize        • Team agreement      • NO rewrite
• Edit messages     • Document changes    • NO filter

RACIONAL:           RACIONAL:             RACIONAL:
No one depends      Coordination needed   Others depend
on this history     Potential conflicts   History is truth

Zonas de Operación Segura

📊 SAFETY ZONES VISUALIZATION

🌍 REPOSITORY TOPOLOGY
     ├─ 🔴 PRODUCTION ZONE (Inmutable)
     │    │
     │    ├─ main branch
     │    │    └─ Deployed to production
     │    │       NEVER rewrite
     │    │
     │    ├─ release-* branches
     │    │    └─ Tagged versions
     │    │       Historical record
     │    │
     │    └─ hotfix branches (merged)
     │         └─ Emergency fixes
     │            Already in production
     ├─ 🟡 INTEGRATION ZONE (Cuidado)
     │    │
     │    ├─ develop branch
     │    │    └─ Team integration point
     │    │       Coordinate antes de rewrite
     │    │
     │    ├─ feature/* (shared)
     │    │    └─ Multiple devs
     │    │       Communicate changes
     │    │
     │    └─ PR branches (reviewed)
     │         └─ Under review
     │            Avoid major rewrites
     └─ 🟢 DEVELOPMENT ZONE (Flexible)
          ├─ feature/* (private)
          │    └─ Solo tú
          │       Rewrite libremente
          ├─ experiment/*
          │    └─ Throwaway work
          │       No rules
          └─ Local branches
               └─ Not pushed
                  Complete freedom

DECISION TREE:

    ¿Has pusheado la branch?
         NO ──┼── SÍ
              │       │
              ▼       ▼
         🟢 SAFE   ¿Otros usando?
                   NO ──┼── SÍ
                        │       │
                        ▼       ▼
                   🟡 CAUTION  🔴 DANGER

🎨 CAPÍTULO 2: REBASE INTERACTIVO - ESCULPIR HISTORIA

El Concepto: La Máquina del Tiempo Editable

Interactive rebase es como tener un editor de video para tu historia de Git. Puedes reorganizar escenas, cortar partes innecesarias, y combinar tomas.

╔═══════════════════════════════════════════════════════════╗
║        REBASE INTERACTIVO COMO EDITOR DE HISTORIA         ║
╚═══════════════════════════════════════════════════════════╝

🎬 EL PROBLEMA: Historia Caótica del Desarrollo Real

HISTORIA ORIGINAL (cronológica, messy):
┌────────────────────────────────────────────────────────┐
│  ○ WIP: trying something                               │
│  │  └─ Commit exploratorio                             │
│  │                                                      │
│  ○ fix typo in comment                                 │
│  │  └─ Micro-fix trivial                               │
│  │                                                      │
│  ○ actually implement reverb algorithm                 │
│  │  └─ El trabajo real                                 │
│  │                                                      │
│  ○ fix typo again (oops)                               │
│  │  └─ Otro fix trivial                                │
│  │                                                      │
│  ○ debug: add logging                                  │
│  │  └─ Temporary debugging                             │
│  │                                                      │
│  ○ remove debug logging                                │
│  │  └─ Cleanup del debug                               │
│  │                                                      │
│  ○ final version maybe?                                │
│     └─ Incertidumbre                                   │
└────────────────────────────────────────────────────────┘

PROBLEMAS:
├─ 7 commits para 1 feature
├─ Historia difícil de seguir
├─ Commits intermedios sin valor
├─ Code review pesadilla
└─ Git log ruidoso

         ╲╱ REBASE INTERACTIVE ╲╱

HISTORIA REFINADA (lógica, limpia):
┌────────────────────────────────────────────────────────┐
│  ○ feat(dsp): implement Schroeder reverb algorithm     │
│     │                                                   │
│     ├─ Implements 4-comb + 2-allpass filter            │
│     ├─ Parameters: room size, damping, wet/dry         │
│     ├─ Performance: ~3% CPU @ 48kHz                    │
│     └─ Tests: tests/dsp/reverb_test.cpp                │
└────────────────────────────────────────────────────────┘

BENEFICIOS:
├─ 1 commit lógico y atómico
├─ Mensaje descriptivo completo
├─ Historia profesional
├─ Code review fácil
└─ Git log útil

Los Siete Comandos Maestros

╔═══════════════════════════════════════════════════════════════════════════╗
║              LOS 7 COMANDOS DE REBASE INTERACTIVO                         ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  COMANDO    │ EFECTO                    │ USO TÍPICO         │ ICON      ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  pick       │ Usar commit tal cual      │ Mantener commit    │ ✅        ║
║  (p)        │ No modificaciones         │ como está          │           ║
║             │                           │                    │           ║
║             │ ANTES:  ○ Commit A        │                    │           ║
║             │ DESPUÉS: ○ Commit A       │                    │           ║
║             │         (mismo SHA)       │                    │           ║
║                                                                           ║
║  reword     │ Cambiar solo mensaje      │ Mejorar            │ ✏️        ║
║  (r)        │ Contenido idéntico        │ documentación      │           ║
║             │ SHA cambia                │                    │           ║
║             │                           │                    │           ║
║             │ ANTES:  ○ "fix bug"       │                    │           ║
║             │ DESPUÉS: ○ "fix(dsp):     │                    │           ║
║             │           prevent NaN"    │                    │           ║
║             │         (nuevo SHA)       │                    │           ║
║                                                                           ║
║  edit       │ Pausar para modificar     │ Cambiar contenido  │ ⏸️        ║
║  (e)        │ Rebase se detiene         │ Split commit       │           ║
║             │ Modificas archivos        │ Añadir files       │           ║
║             │ Continúas manualmente     │                    │           ║
║             │                           │                    │           ║
║             │ ○ Commit → PAUSE →        │                    │           ║
║             │ (edit files) → amend/new  │                    │           ║
║                                                                           ║
║  squash     │ Combinar con anterior     │ Merge related      │ 🔗        ║
║  (s)        │ Editor abre para mensaje  │ commits            │           ║
║             │ Combinas mensajes         │                    │           ║
║             │                           │                    │           ║
║             │ ANTES:  ○ A               │                    │           ║
║             │         ○ B               │                    │           ║
║             │ DESPUÉS: ● A+B            │                    │           ║
║             │         (mensajes merged) │                    │           ║
║                                                                           ║
║  fixup      │ Combinar con anterior     │ Incorporar fixes   │ 🔧        ║
║  (f)        │ Descarta mensaje de este  │ triviales          │           ║
║             │ Mantiene mensaje anterior │                    │           ║
║             │                           │                    │           ║
║             │ ANTES:  ○ A: feature      │                    │           ║
║             │         ○ B: fix typo     │                    │           ║
║             │ DESPUÉS: ● A: feature     │                    │           ║
║             │         (B desaparece)    │                    │           ║
║                                                                           ║
║  drop       │ Eliminar commit           │ Remover            │ 🗑️        ║
║  (d)        │ Como nunca existió        │ experiments        │           ║
║             │                           │ fallidos           │           ║
║             │                           │                    │           ║
║             │ ANTES:  ○ A               │                    │           ║
║             │         ○ B (bad)         │                    │           ║
║             │         ○ C               │                    │           ║
║             │ DESPUÉS: ○ A              │                    │           ║
║             │          ○ C              │                    │           ║
║             │         (B eliminado)     │                    │           ║
║                                                                           ║
║  exec       │ Ejecutar shell command    │ Run tests entre    │ ⚙️        ║
║  (x)        │ Entre commits             │ cada commit        │           ║
║             │ Rebase falla si cmd ≠ 0   │ Validación         │           ║
║             │                           │ continua           │           ║
║             │                           │                    │           ║
║             │ ○ Commit A                │                    │           ║
║             │ exec npm test             │                    │           ║
║             │ ○ Commit B                │                    │           ║
║             │ exec npm test             │                    │           ║
║                                                                           ║
╚═══════════════════════════════════════════════════════════════════════════╝

Flujo Visual de Rebase Interactivo

🎬 NARRATIVE FLOW: Del Caos al Orden

┌─────────────────────────────────────────────────────────────┐
│  📋 FASE 1: PLANNING (Git te presenta la lista)             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Git abre editor con lista de commits:                      │
│                                                             │
│  ┌────────────────────────────────────────────┐            │
│  │ pick abc123 add reverb feature             │            │
│  │ pick def456 fix typo                       │            │
│  │ pick ghi789 improve reverb algorithm       │            │
│  │ pick jkl012 fix another typo               │            │
│  │ pick mno345 add tests                      │            │
│  │ pick pqr678 debug logging                  │            │
│  │ pick stu901 remove debug                   │            │
│  └────────────────────────────────────────────┘            │
│                                                             │
│  Cada línea = Un commit                                     │
│  Orden = Cronológico (más antiguo primero)                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ TÚ DECIDES qué hacer con cada commit

┌─────────────────────────────────────────────────────────────┐
│  ✏️ FASE 2: EDITING (Defines nueva estructura)              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Modificas el plan según tu visión:                         │
│                                                             │
│  ┌────────────────────────────────────────────┐            │
│  │ pick abc123 add reverb feature             │  ← Keep    │
│  │ squash ghi789 improve reverb algorithm     │  ← Merge   │
│  │ fixup def456 fix typo                      │  ← Fix in  │
│  │ fixup jkl012 fix another typo              │  ← Fix in  │
│  │ pick mno345 add tests                      │  ← Keep    │
│  │ drop pqr678 debug logging                  │  ← Remove  │
│  │ drop stu901 remove debug                   │  ← Remove  │
│  └────────────────────────────────────────────┘            │
│                                                             │
│  Cambios:                                                   │
│  • Reorganizado (ghi789 movido arriba)                      │
│  • Combinado (squash, fixup)                                │
│  • Eliminado (drop debug commits)                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ GUARDAS y CIERRAS editor

┌─────────────────────────────────────────────────────────────┐
│  ⚙️ FASE 3: EXECUTION (Git ejecuta el plan)                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Git procesa cada línea secuencialmente:                    │
│                                                             │
│  1️⃣ pick abc123 → Apply commit                             │
│     ○ abc123 (base)                                         │
│                                                             │
│  2️⃣ squash ghi789 → Merge into abc123                      │
│     ○ abc123 + ghi789                                       │
│     ↓ Editor abre para combinar mensajes:                   │
│       ┌──────────────────────────────────┐                 │
│       │ # Mensaje de abc123              │                 │
│       │ add reverb feature                │                 │
│       │                                   │                 │
│       │ # Mensaje de ghi789               │                 │
│       │ improve reverb algorithm          │                 │
│       │                                   │                 │
│       │ [Tú editas y combinas]            │                 │
│       │                                   │                 │
│       │ feat(dsp): implement reverb       │                 │
│       │ - Schroeder algorithm             │                 │
│       │ - 4 comb + 2 allpass filters      │                 │
│       └──────────────────────────────────┘                 │
│                                                             │
│  3️⃣ fixup def456 → Merge silently                          │
│     ● Combined commit (no editor)                           │
│                                                             │
│  4️⃣ fixup jkl012 → Merge silently                          │
│     ● Combined commit                                       │
│                                                             │
│  5️⃣ pick mno345 → Apply commit                             │
│     ○ mno345                                                │
│                                                             │
│  6️⃣ drop pqr678 → Skip (no aplicado)                       │
│  7️⃣ drop stu901 → Skip                                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ REBASE COMPLETO

┌─────────────────────────────────────────────────────────────┐
│  ✅ FASE 4: RESULTADO (Nueva historia limpia)               │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ANTES (7 commits):                                         │
│  ○ abc123 add reverb feature                                │
│  ○ def456 fix typo                                          │
│  ○ ghi789 improve reverb algorithm                          │
│  ○ jkl012 fix another typo                                  │
│  ○ mno345 add tests                                         │
│  ○ pqr678 debug logging                                     │
│  ○ stu901 remove debug                                      │
│                                                             │
│  DESPUÉS (2 commits):                                       │
│  ● xyz111 feat(dsp): implement reverb                       │
│            - Schroeder algorithm                            │
│            - 4 comb + 2 allpass filters                     │
│            (combines abc123 + ghi789 + def456 + jkl012)     │
│  ● abc222 test(dsp): add reverb tests                       │
│            (mno345, reworded)                               │
│                                                             │
│  MEJORAS:                                                   │
│  ✓ 7 commits → 2 commits lógicos                            │
│  ✓ Historia clara y profesional                             │
│  ✓ Code review friendly                                     │
│  ✓ Debug commits removidos                                  │
│  ✓ Typos incorporados silenciosamente                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Patrones Comunes Visualizados

╔═══════════════════════════════════════════════════════════════════════════╗
║                    PATTERN LIBRARY: REBASE INTERACTIVO                    ║
╚═══════════════════════════════════════════════════════════════════════════╝

┌───────────────────────────────────────────────────────────────────────────┐
│  📐 PATTERN 1: SQUASH FIXUPS (Combinar correcciones)                      │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Desarrollaste feature en múltiples iteraciones con bugs intermedios      │
│                                                                           │
│  ANTES:                                                                   │
│  ┌────────────────────────────────────────────────┐                      │
│  │ ○ Initial reverb implementation                │                      │
│  │ ○ Fix: prevent NaN in coefficients             │                      │
│  │ ○ Fix: handle zero Q parameter                 │                      │
│  │ ○ Fix: memory leak in destructor               │                      │
│  │ ○ Final: cleanup and optimize                  │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  PROBLEMA:                                                                │
│  • 5 commits para 1 feature                                              │
│  • Historia muestra proceso de debugging (ruidoso)                        │
│  • Reviewer tiene que leer 5 commits para entender 1 feature             │
│                                                                           │
│  ESTRATEGIA:                                                              │
│  ┌────────────────────────────────────────────────┐                      │
│  │ pick  ○ Initial reverb implementation          │                      │
│  │ fixup ○ Fix: prevent NaN                       │  ← Incorpora fix     │
│  │ fixup ○ Fix: handle zero Q                     │  ← Incorpora fix     │
│  │ fixup ○ Fix: memory leak                       │  ← Incorpora fix     │
│  │ fixup ○ Final: cleanup                         │  ← Incorpora cleanup │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  DESPUÉS:                                                                 │
│  ┌────────────────────────────────────────────────┐                      │
│  │ ● feat(dsp): implement Schroeder reverb        │                      │
│  │              (único commit completo y limpio)  │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  BENEFICIO:                                                               │
│  • Historia limpia: 1 feature = 1 commit                                 │
│  • Code review eficiente: todo el código junto                           │
│  • Git log útil: cada commit es milestone significativo                  │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

┌───────────────────────────────────────────────────────────────────────────┐
│  📐 PATTERN 2: REORGANIZACIÓN LÓGICA (Del caos al orden)                  │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Commits en orden cronológico (cómo trabajaste) no lógico (qué hiciste)   │
│                                                                           │
│  ANTES (Orden cronológico - confuso):                                     │
│  ┌────────────────────────────────────────────────┐                      │
│  │ 1. ○ Add UI knob for reverb room size          │                      │
│  │ 2. ○ Implement DSP reverb algorithm            │                      │
│  │ 3. ○ Fix UI: knob range 0-100%                 │                      │
│  │ 4. ○ Add DSP parameter smoothing               │                      │
│  │ 5. ○ Connect UI to DSP parameters              │                      │
│  │ 6. ○ Improve DSP: add damping control          │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  PROBLEMA:                                                                │
│  • DSP y UI intercalados (confuso)                                       │
│  • No puedes entender DSP sin saltar commits                             │
│  • Historia no refleja arquitectura (DSP → UI → Integration)             │
│                                                                           │
│  ESTRATEGIA (Reorganizar por subsistema):                                 │
│  ┌────────────────────────────────────────────────┐                      │
│  │ pick   2 ○ Implement DSP reverb algorithm      │  ← DSP first         │
│  │ squash 4 ○ Add DSP parameter smoothing         │  ← Merge DSP         │
│  │ squash 6 ○ Improve DSP: damping                │  ← Merge DSP         │
│  │ pick   1 ○ Add UI knob for room size           │  ← Then UI           │
│  │ fixup  3 ○ Fix UI: knob range                  │  ← Fix UI            │
│  │ pick   5 ○ Connect UI to DSP                   │  ← Finally connect   │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  DESPUÉS (Orden lógico - claro):                                          │
│  ┌────────────────────────────────────────────────┐                      │
│  │ 1. ● feat(dsp): implement reverb with damping  │  ← Complete DSP      │
│  │ 2. ● feat(ui): add reverb controls             │  ← Complete UI       │
│  │ 3. ● feat(integration): connect UI to DSP      │  ← Integration       │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  BENEFICIO:                                                               │
│  • Historia refleja arquitectura del sistema                             │
│  • Cada commit es independientemente reviewable                          │
│  • Fácil entender evolución de cada subsistema                           │
│  • Bisect funciona mejor (cada commit es atómico)                        │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

┌───────────────────────────────────────────────────────────────────────────┐
│  📐 PATTERN 3: SPLIT MONOLITHIC (Dividir commit gigante)                  │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Un commit masivo que hace múltiples cosas no relacionadas                │
│                                                                           │
│  ANTES:                                                                   │
│  ┌────────────────────────────────────────────────┐                      │
│  │ ● Massive Friday afternoon commit (500 lines)  │                      │
│  │   ├─ Feature A: Reverb algorithm               │                      │
│  │   ├─ Feature B: EQ implementation              │                      │
│  │   ├─ Fix: Unrelated buffer bug                 │                      │
│  │   └─ Refactor: Extract common utilities        │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  PROBLEMA:                                                                │
│  • Imposible de review (demasiado grande)                                │
│  • Mezcla features con fixes (diferentes tipos)                          │
│  • No se puede cherry-pick parte (todo o nada)                           │
│  • Revertir es nuclear option                                            │
│                                                                           │
│  ESTRATEGIA (Usar 'edit' para split):                                     │
│  ┌────────────────────────────────────────────────┐                      │
│  │ edit ● Massive commit                           │                      │
│  └────────────────────────────────────────────────┘                      │
│       │                                                                   │
│       ├─ Rebase PAUSA aquí                                               │
│       ├─ Reset HEAD^ (unstack el commit)                                 │
│       ├─ Staging selectivo con git add -p                                │
│       │                                                                   │
│       ├─ commit 1: Reverb files only                                     │
│       ├─ commit 2: EQ files only                                         │
│       ├─ commit 3: Buffer fix only                                       │
│       ├─ commit 4: Utilities refactor                                    │
│       │                                                                   │
│       └─ git rebase --continue                                           │
│                                                                           │
│  DESPUÉS:                                                                 │
│  ┌────────────────────────────────────────────────┐                      │
│  │ ○ feat(dsp): implement reverb algorithm        │  ← Focused           │
│  │ ○ feat(dsp): implement parametric EQ           │  ← Focused           │
│  │ ○ fix(audio): resolve buffer underrun          │  ← Focused           │
│  │ ○ refactor(utils): extract common helpers      │  ← Focused           │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  BENEFICIO:                                                               │
│  • 4 commits atómicos y reviewables                                      │
│  • Cada uno puede cherry-picked independientemente                       │
│  • Revert quirúrgico posible                                             │
│  • Historia documenta cambios lógicamente                                │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

┌───────────────────────────────────────────────────────────────────────────┐
│  📐 PATTERN 4: EXEC VALIDATION (Tests entre commits)                      │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Quieres asegurar que CADA commit en tu historia pasa tests               │
│                                                                           │
│  ESTRATEGIA:                                                              │
│  ┌────────────────────────────────────────────────┐                      │
│  │ pick ○ feat: add reverb                        │                      │
│  │ exec npm test                                   │  ← Test after this  │
│  │ pick ○ feat: add EQ                            │                      │
│  │ exec npm test                                   │  ← Test after this  │
│  │ pick ○ feat: add compressor                    │                      │
│  │ exec npm test                                   │  ← Test after this  │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  QUÉ SUCEDE:                                                              │
│  1. Apply commit 1                                                        │
│  2. Run npm test                                                          │
│     ├─ Si pass → continuar                                               │
│     └─ Si fail → STOP, fix, continue                                     │
│  3. Apply commit 2                                                        │
│  4. Run npm test                                                          │
│  ...                                                                      │
│                                                                           │
│  BENEFICIO:                                                               │
│  • Garantiza cada commit en historia es valid                            │
│  • Git bisect funcionará perfectamente (no broken commits)               │
│  • Detecta problemas introducidos por rebase                             │
│  • Historia "gold standard"                                              │
│                                                                           │
│  USO TÍPICO:                                                              │
│  • Antes de push a main                                                  │
│  • Cleanup de feature branch pre-PR                                      │
│  • Preparación para release                                              │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

🔍 CAPÍTULO 3: GIT BISECT - ARQUEOLOGÍA AUTOMATIZADA

El Concepto: Binary Search en Historia

Bisect aplica el algoritmo de búsqueda binaria a tu historia de Git para encontrar el commit que introdujo un bug.

╔═══════════════════════════════════════════════════════════╗
║           EL PROBLEMA DE LA REGRESIÓN                     ║
╚═══════════════════════════════════════════════════════════╝

🎯 SCENARIO: Bug Apareció, ¿Cuándo?

TIMELINE DE DESARROLLO:
┌────────────────────────────────────────────────────────┐
│                                                        │
│  6 meses atrás                              Hoy       │
│       ↓                                       ↓        │
│  ┌────●────────────────────────────────────●────┐    │
│  │                                              │    │
│  │  ○○○○○○○○○○○○○○○○...○○○○○○○○○○○○○○○●        │    │
│  │  ↑                                    ↑    ↑        │
│  │ Commit 1                        Commit   500        │
│  │ (works)                          ???   (broken)     │
│  │                                                     │
│  │  500 commits de desarrollo                         │
│  └─────────────────────────────────────────────────────┘
│                                                        │
│  CONOCIDO:                                             │
│  ├─ Commit 1: Feature funciona ✅                      │
│  └─ Commit 500: Feature rota 🔴                        │
│                                                        │
│  DESCONOCIDO:                                          │
│  └─ ¿En cuál de los 499 commits intermedios           │
│     se introdujo el bug?                               │
│                                                        │
│  PROBLEMA:                                             │
│  • Testar manualmente 499 commits = semanas            │
│  • Git blame muestra última modificación, no bug       │
│  • Log no ayuda (mensajes no mencionan el bug)         │
│                                                        │
└────────────────────────────────────────────────────────┘

SOLUCIÓN: BINARY SEARCH (Bisect)
Reduce 499 posibilidades a ~9 tests con logaritmo

Binary Search Visual

🔬 ALGORITMO DE BISECT VISUALIZADO

┌────────────────────────────────────────────────────────┐
│                                                        │
│  📊 ITERACIÓN 1: Estableces Boundaries                 │
│                                                        │
│  [1]────────────────────────────────────────[500]      │
│  ↑                                           ↑         │
│  GOOD                                       BAD        │
│  (conocido)                            (conocido)      │
│                                                        │
│  Espacio de búsqueda: 499 commits                      │
│  Git elige MIDPOINT: commit 250                        │
│                                                        │
└────────────────────────────────────────────────────────┘
         │ Git checkouts commit 250
         │ TÚ testas
┌────────────────────────────────────────────────────────┐
│                                                        │
│  🎯 TEST MIDPOINT #250                                 │
│                                                        │
│  Build proyecto...                                     │
│  Run test específico...                                │
│                                                        │
│  ¿Resultado?                                           │
│  ├─ ✅ GOOD → Bug NO presente aún                      │
│  │           → Bug está entre [250-500]               │
│  │           → Nuevo espacio: 250 commits             │
│  │                                                    │
│  └─ 🔴 BAD  → Bug YA presente                          │
│             → Bug está entre [1-250]                  │
│             → Nuevo espacio: 250 commits              │
│                                                        │
│  En este ejemplo: BAD                                  │
│                                                        │
└────────────────────────────────────────────────────────┘
         │ Reportas: "bad"
┌────────────────────────────────────────────────────────┐
│                                                        │
│  📊 ITERACIÓN 2: Nuevo Rango [1-250]                   │
│                                                        │
│  [1]──────────────────[125]──────────────[250]         │
│  ↑                     ↑                  ↑            │
│  GOOD                TEST                BAD           │
│                   (midpoint)                           │
│                                                        │
│  Espacio reducido: 499 → 249 commits (50% menos)       │
│  Git elige nuevo MIDPOINT: commit 125                  │
│                                                        │
└────────────────────────────────────────────────────────┘
         │ Git checkouts commit 125
         │ TÚ testas
┌────────────────────────────────────────────────────────┐
│                                                        │
│  🎯 TEST MIDPOINT #125                                 │
│                                                        │
│  Resultado: ✅ GOOD (bug no presente aún)              │
│                                                        │
│  Nuevo rango: [125-250]                                │
│  Espacio: 125 commits                                  │
│                                                        │
└────────────────────────────────────────────────────────┘
         │ Continúa bisecting...

ITERACIONES SUBSECUENTES:
┌────────────────────────────────────────────────────────┐
│                                                        │
│  ITER  │ RANGO       │ TEST    │ RESULT │ NUEVO RANGO│
│  ─────┼─────────────┼─────────┼────────┼────────────│
│   3   │ [125-250]   │ 187     │ BAD    │ [125-187]  │
│   4   │ [125-187]   │ 156     │ GOOD   │ [156-187]  │
│   5   │ [156-187]   │ 171     │ GOOD   │ [171-187]  │
│   6   │ [171-187]   │ 179     │ BAD    │ [171-179]  │
│   7   │ [171-179]   │ 175     │ GOOD   │ [175-179]  │
│   8   │ [175-179]   │ 177     │ GOOD   │ [177-179]  │
│   9   │ [177-179]   │ 178     │ BAD    │ [177-178]  │
│  ─────┼─────────────┼─────────┼────────┼────────────│
│  FINAL│ Solo 1 left │ 178     │ 🎯     │ CULPRIT!   │
│                                                        │
└────────────────────────────────────────────────────────┘

RESULTADO:
┌────────────────────────────────────────────────────────┐
│  🎯 COMMIT CULPABLE IDENTIFICADO                       │
│                                                        │
│  commit 178abc456def                                   │
│  Author: Developer Name                                │
│  Date: 3 months ago                                    │
│                                                        │
│  refactor(dsp): optimize filter coefficient calc       │
│                                                        │
│  Changed formula caused NaN when Q parameter = 0       │
│                                                        │
│  [Diff showing exact change that broke it]             │
│                                                        │
└────────────────────────────────────────────────────────┘

MATEMÁTICAS:
• 500 commits → log₂(500) ≈ 9 iterations
• vs 250 iterations promedio manual
• 96% reducción en trabajo de debugging

Flujo Operacional Completo

🎬 BISECT WORKFLOW: Paso a Paso

┌─────────────────────────────────────────────────────────────┐
│  🚀 FASE 1: INICIO (Estableces Boundaries)                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  TÚ conoces:                                                │
│  ├─ Un commit GOOD (bug no existe)                          │
│  │   Ejemplo: v1.0 release tag                             │
│  │   O commit de hace 6 meses                              │
│  │                                                         │
│  └─ Un commit BAD (bug existe)                              │
│      Típicamente: HEAD (current commit)                     │
│                                                             │
│  Comandos conceptuales:                                     │
│    git bisect start                                         │
│    git bisect bad                  ← Marca HEAD como bad    │
│    git bisect good v1.0            ← Marca v1.0 como good   │
│                                                             │
│  Git responde:                                              │
│    "Bisecting: 249 revisions left to test"                  │
│    "Checking out commit abc123 (midpoint)"                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ Git checkouts midpoint automáticamente

┌─────────────────────────────────────────────────────────────┐
│  🔄 FASE 2: LOOP DE TESTING (Iterativo)                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Por cada iteración, REPITES este ciclo:                    │
│                                                             │
│  ┌─────────────────────────────────────┐                   │
│  │ 1️⃣ Git checkouts midpoint commit    │                   │
│  │    Working directory está en ese    │                   │
│  │    punto en el tiempo               │                   │
│  └─────────────────────────────────────┘                   │
│           │                                                 │
│           ▼                                                 │
│  ┌─────────────────────────────────────┐                   │
│  │ 2️⃣ TÚ TESTAS el código              │                   │
│  │                                     │                   │
│  │    Opciones:                        │                   │
│  │    A. Manual testing                │                   │
│  │       - Build proyecto              │                   │
│  │       - Run app                     │                   │
│  │       - Check si bug present        │                   │
│  │                                     │                   │
│  │    B. Automated test                │                   │
│  │       - Run specific test           │                   │
│  │       - Check exit code             │                   │
│  └─────────────────────────────────────┘                   │
│           │                                                 │
│           ▼                                                 │
│  ┌─────────────────────────────────────┐                   │
│  │ 3️⃣ TÚ REPORTAS resultado            │                   │
│  │                                     │                   │
│  │    git bisect good                  │  ← Bug no present │
│  │    O                                │                   │
│  │    git bisect bad                   │  ← Bug present    │
│  │    O                                │                   │
│  │    git bisect skip                  │  ← Can't test     │
│  └─────────────────────────────────────┘                   │
│           │                                                 │
│           ▼                                                 │
│  ┌─────────────────────────────────────┐                   │
│  │ 4️⃣ Git BISECTS nuevamente           │                   │
│  │    Checkouts next midpoint          │                   │
│  │    Shows remaining commits          │                   │
│  └─────────────────────────────────────┘                   │
│           │                                                 │
│           └────────┐                                        │
│                    │ LOOP                                   │
│           ┌────────┘                                        │
│           │                                                 │
│           ▼                                                 │
│     ¿Queda solo 1 commit?                                   │
│     NO → Repeat loop                                        │
│     SÍ → Go to FASE 3                                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ Bisect completo

┌─────────────────────────────────────────────────────────────┐
│  🎯 FASE 3: IDENTIFICACIÓN (Git te muestra culpable)        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Git determina el commit exacto:                            │
│                                                             │
│  ┌──────────────────────────────────────────┐              │
│  │ abc123def456 is the first bad commit     │              │
│  │                                          │              │
│  │ commit abc123def456                      │              │
│  │ Author: John Developer <john@email.com>  │              │
│  │ Date:   Mon Jan 15 14:23:45 2024         │              │
│  │                                          │              │
│  │     refactor(dsp): optimize filter calc  │              │
│  │                                          │              │
│  │     Changed coefficient calculation      │              │
│  │     for better performance               │              │
│  │                                          │              │
│  │ [Full diff showing exact changes]        │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  AHORA SABES:                                               │
│  ✓ Commit exacto que introdujo bug                         │
│  ✓ Autor (para preguntar context)                          │
│  ✓ Fecha (cuándo pasó)                                     │
│  ✓ Mensaje (por qué se hizo cambio)                        │
│  ✓ Diff completo (qué cambió exactamente)                  │
│                                                             │
│  SIGUIENTE PASO:                                            │
│  1. Analizar el cambio                                     │
│  2. Entender por qué causó bug                             │
│  3. Fix en commit nuevo                                    │
│  4. Test que reproduce bug → regression test               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ Cleanup

┌─────────────────────────────────────────────────────────────┐
│  🧹 FASE 4: CLEANUP                                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git bisect reset  ← Vuelve a branch original               │
│                                                             │
│  Working directory restored a HEAD                          │
│  Listo para implementar fix                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Bisect Automatizado con Scripts

╔═══════════════════════════════════════════════════════════╗
║         🤖 BISECT RUN: AUTOMATIZACIÓN TOTAL               ║
╚═══════════════════════════════════════════════════════════╝

CONCEPTO:
En lugar de testar manualmente cada commit, provees un script
que Git ejecuta automáticamente en cada iteración.

┌───────────────────────────────────────────────────────────┐
│  📝 TEST SCRIPT STRUCTURE                                 │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  El script debe:                                          │
│  1. Build/preparar código                                 │
│  2. Run test específico                                   │
│  3. Return exit code:                                     │
│     • 0     → GOOD (test passes)                          │
│     • 1-127 → BAD (test fails, excepto 125)               │
│     • 125   → SKIP (can't test this commit)               │
│     • 128+  → ABORT (fatal error in script)               │
│                                                           │
└───────────────────────────────────────────────────────────┘

EJEMPLO: test_reverb.sh
┌───────────────────────────────────────────────────────────┐
│  #!/bin/bash                                              │
│                                                           │
│  # Build proyecto                                         │
│  cmake -B build && cmake --build build                    │
│  if [ $? -ne 0 ]; then                                    │
│      exit 125  # Can't build = skip this commit          │
│  fi                                                       │
│                                                           │
│  # Run test específico de reverb                          │
│  ./build/test_reverb --test-case="NaN with Q=0"          │
│                                                           │
│  # Exit code del test se propaga                          │
│  # 0 = pass (GOOD), non-zero = fail (BAD)                │
└───────────────────────────────────────────────────────────┘

USO:
┌───────────────────────────────────────────────────────────┐
│  git bisect start                                         │
│  git bisect bad HEAD                                      │
│  git bisect good v1.0                                     │
│  git bisect run ./test_reverb.sh                          │
│                                                           │
│  Git ejecuta automáticamente:                             │
│  ├─ Checkout midpoint                                     │
│  ├─ Run test_reverb.sh                                    │
│  ├─ Interpreta exit code                                  │
│  ├─ Bisect basado en resultado                            │
│  └─ Repeat hasta encontrar culprit                        │
│                                                           │
│  Mientras tú:                                             │
│  └─ ☕ Tomas café                                         │
│                                                           │
└───────────────────────────────────────────────────────────┘

OUTPUT TÍPICO:
┌───────────────────────────────────────────────────────────┐
│  running ./test_reverb.sh                                 │
│  Bisecting: 125 revisions left to test                    │
│  running ./test_reverb.sh                                 │
│  Bisecting: 62 revisions left to test                     │
│  running ./test_reverb.sh                                 │
│  Bisecting: 31 revisions left to test                     │
│  ...                                                      │
│  running ./test_reverb.sh                                 │
│  abc123def is the first bad commit                        │
│                                                           │
│  [Commit details]                                         │
│                                                           │
│  bisect run success                                       │
└───────────────────────────────────────────────────────────┘

VENTAJAS:
✓ Completamente automatizado (set and forget)
✓ Consistente (mismo test cada vez)
✓ Rápido (no esperas entre iterations)
✓ Reproducible (script es documentación)

CASOS DE USO:
├─ Performance regressions (benchmark script)
├─ Test failures (run test suite)
├─ Build breaks (try compile)
└─ Output changes (compare against golden master)

📦 CAPÍTULO 4: STASH - EL ALMACÉN TEMPORAL

El Concepto: Cajón de Trabajo en Progreso

Stash es tu espacio temporal para guardar cambios sin commitearlos.

╔═══════════════════════════════════════════════════════════╗
║          EL PROBLEMA DE LA INTERRUPCIÓN                   ║
╚═══════════════════════════════════════════════════════════╝

🎭 SCENARIO: Context Switching Forced

┌───────────────────────────────────────────────────────────┐
│  TU SITUACIÓN ACTUAL                                      │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  Estás trabajando en Feature A:                           │
│                                                           │
│  Working Directory (DIRTY):                               │
│  ├─ Modified: reverb_algorithm.cpp                        │
│  ├─ Modified: reverb_ui.cpp                               │
│  ├─ New file: reverb_params.h                             │
│  ├─ Modified: CMakeLists.txt                              │
│  └─ ... 11 more files changed                             │
│                                                           │
│  Progress: 60% completado                                 │
│  Status: NOT ready to commit                              │
│  ├─ Code compiles but incomplete                          │
│  ├─ Tests not written yet                                 │
│  └─ Half-implemented feature                              │
│                                                           │
└───────────────────────────────────────────────────────────┘

         │ 🚨 INTERRUPCIÓN

┌───────────────────────────────────────────────────────────┐
│  URGENTE: Bug crítico en producción                       │
│  Necesitas fix AHORA                                      │
│                                                           │
│  REQUIERE:                                                │
│  ├─ Switch a main branch                                  │
│  ├─ Crear hotfix branch                                   │
│  └─ Working directory CLEAN                               │
│                                                           │
│  PERO:                                                    │
│  ├─ No quieres commit trabajo incompleto                  │
│  ├─ No quieres perder 15 archivos modificados             │
│  └─ No quieres crear branch dirty                         │
│                                                           │
└───────────────────────────────────────────────────────────┘

         │ ❓ ¿SOLUCIÓN?

┌───────────────────────────────────────────────────────────┐
│  OPCIONES MALAS:                                          │
│                                                           │
│  ❌ Commit WIP                                            │
│     └─ Contamina historia con garbage commit             │
│                                                           │
│  ❌ Descartar cambios                                     │
│     └─ Pierdes horas de trabajo                          │
│                                                           │
│  ❌ Copiar archivos manualmente                           │
│     └─ Tedioso, propenso a errores                       │
│                                                           │
│  ✅ USAR STASH                                            │
│     └─ Diseñado exactamente para esto                    │
│                                                           │
└───────────────────────────────────────────────────────────┘

Stash como Solución Visual

🗄️ STASH MECHANISM: The Temporary Shelf

┌─────────────────────────────────────────────────────────────┐
│  📥 FASE 1: GUARDAR (Stash Save)                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ANTES DEL STASH:                                           │
│                                                             │
│  Working Directory:                    Stash Stack:         │
│  ┌──────────────────┐                 ┌─────────┐          │
│  │ M reverb_algo.cpp│                 │ (empty) │          │
│  │ M reverb_ui.cpp  │                 └─────────┘          │
│  │ A reverb_params.h│                                      │
│  │ M CMakeLists.txt │                                      │
│  │ ... (15 files)   │                                      │
│  └──────────────────┘                                      │
│        DIRTY                                                │
│                                                             │
│  git stash save "WIP: Feature A reverb implementation"      │
│       │                                                     │
│       └─► Guarda estado                                    │
│                                                             │
│  DESPUÉS DEL STASH:                                         │
│                                                             │
│  Working Directory:                    Stash Stack:         │
│  ┌──────────────────┐                 ┌──────────────────┐ │
│  │                  │                 │ stash@{0}:       │ │
│  │    (clean)       │                 │ On feat-A:       │ │
│  │                  │                 │ WIP: Feature A   │ │
│  └──────────────────┘                 │ reverb implem..  │ │
│        CLEAN                           │                  │ │
│                                        │ Contains:        │ │
│                                        │ • 15 files       │ │
│                                        │ • All changes    │ │
│                                        └──────────────────┘ │
│                                                             │
│  ✓ Working directory limpio                                 │
│  ✓ Cambios guardados safely                                │
│  ✓ Listo para switch branches                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ Ahora puedes trabajar en hotfix

┌─────────────────────────────────────────────────────────────┐
│  🔄 FASE 2: TRABAJO URGENTE (Clean Slate)                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git checkout main                  ✅ Switches cleanly     │
│  git checkout -b hotfix/critical    ✅ Nueva branch clean   │
│                                                             │
│  [Fix el bug urgente]                                       │
│  git add .                                                  │
│  git commit -m "hotfix: resolve critical bug"               │
│  git push                                                   │
│                                                             │
│  ✓ Hotfix deployed                                          │
│  ✓ Emergencia resuelta                                      │
│  ✓ Listo para volver a Feature A                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ De vuelta a feature branch

┌─────────────────────────────────────────────────────────────┐
│  📤 FASE 3: RESTAURAR (Stash Pop)                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git checkout feature-A                                     │
│  git stash pop                                              │
│       │                                                     │
│       └─► Restaura cambios del stack                       │
│                                                             │
│  ANTES DEL POP:                                             │
│                                                             │
│  Working Directory:                    Stash Stack:         │
│  ┌──────────────────┐                 ┌──────────────────┐ │
│  │                  │                 │ stash@{0}:       │ │
│  │    (clean)       │                 │ Feature A WIP    │ │
│  │                  │                 │ (15 files)       │ │
│  └──────────────────┘                 └──────────────────┘ │
│                                                             │
│  DESPUÉS DEL POP:                                           │
│                                                             │
│  Working Directory:                    Stash Stack:         │
│  ┌──────────────────┐                 ┌─────────┐          │
│  │ M reverb_algo.cpp│                 │ (empty) │          │
│  │ M reverb_ui.cpp  │                 └─────────┘          │
│  │ A reverb_params.h│                                      │
│  │ ... (15 files)   │                   Stash consumed     │
│  └──────────────────┘                   (deleted)          │
│       DIRTY AGAIN                                           │
│                                                             │
│  ✓ Continúas exactamente donde dejaste                     │
│  ✓ Todos los archivos restored                             │
│  ✓ Stash removido del stack                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Variantes y Comportamientos

╔═══════════════════════════════════════════════════════════════════════════╗
║                  STASH COMMAND VARIANTS                                   ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  COMANDO          │ QUÉ GUARDA         │ WORKING DIR │ USO TÍPICO        ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  stash            │ Tracked modified   │ → Clean     │ Quick save        ║
║  stash save       │ files only         │             │ Default behavior  ║
║                   │                    │             │                   ║
║                   │ ✅ Modified files  │             │                   ║
║                   │ ❌ Untracked       │             │                   ║
║                   │ ❌ Ignored         │             │                   ║
║                                                                           ║
║  stash -u         │ Tracked +          │ → Clean     │ Include new       ║
║  --include-       │ Untracked          │             │ files not         ║
║  untracked        │                    │             │ yet added         ║
║                   │ ✅ Modified        │             │                   ║
║                   │ ✅ Untracked       │             │                   ║
║                   │ ❌ Ignored         │             │                   ║
║                                                                           ║
║  stash -a         │ EVERYTHING         │ → Clean     │ Complete          ║
║  --all            │ Including ignored  │             │ snapshot          ║
║                   │                    │             │                   ║
║                   │ ✅ Modified        │             │                   ║
║                   │ ✅ Untracked       │             │                   ║
║                   │ ✅ Ignored         │             │                   ║
║                                                                           ║
║  stash --keep-    │ Saves to stash     │ → Stays     │ Backup            ║
║  index            │ BUT keeps working  │   dirty     │ before risky      ║
║                   │ dir dirty          │             │ operation         ║
║                                                                           ║
║  stash pop        │ N/A (restore)      │ ← Dirty     │ Resume work       ║
║                   │ Removes from stack │             │ Normal flow       ║
║                   │                    │             │                   ║
║                   │ Stash deleted      │             │                   ║
║                   │ after apply        │             │                   ║
║                                                                           ║
║  stash apply      │ N/A (restore)      │ ← Dirty     │ Reuse stash       ║
║                   │ Keeps in stack     │             │ Try on multiple   ║
║                   │                    │             │ branches          ║
║                   │ Stash remains      │             │                   ║
║                                                                           ║
║  stash branch     │ Creates new branch │ ← Clean     │ Convert WIP       ║
║  <name>           │ from stash point   │   on new    │ to feature        ║
║                   │                    │   branch    │ branch            ║
║                                                                           ║
║  stash drop       │ N/A (delete)       │ No change   │ Cleanup old       ║
║                   │ Removes from stack │             │ stashes           ║
║                                                                           ║
║  stash clear      │ N/A (delete all)   │ No change   │ Nuke all          ║
║                   │ Empties entire     │             │ stashes           ║
║                   │ stack              │             │                   ║
║                                                                           ║
╚═══════════════════════════════════════════════════════════════════════════╝

Stash Stack Visualization

🗄️ STASH COMO STACK (LIFO - Last In First Out)

┌─────────────────────────────────────────────────────────────┐
│  MULTIPLE STASHES PUEDEN COEXISTIR                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  STASH STACK:                                               │
│  ┌───────────────────────────────────────────┐             │
│  │ stash@{0} (most recent)                   │ ← POP HERE  │
│  │ On feature-C: Experimental audio filter   │             │
│  │ Created: 10 minutes ago                   │             │
│  ├───────────────────────────────────────────┤             │
│  │ stash@{1}                                 │             │
│  │ On feature-B: UI improvements WIP         │             │
│  │ Created: 2 hours ago                      │             │
│  ├───────────────────────────────────────────┤             │
│  │ stash@{2}                                 │             │
│  │ On feature-A: Reverb implementation       │             │
│  │ Created: Yesterday                        │             │
│  ├───────────────────────────────────────────┤             │
│  │ stash@{3} (oldest)                        │             │
│  │ On hotfix: Emergency patch WIP            │             │
│  │ Created: Last week                        │             │
│  └───────────────────────────────────────────┘             │
│                                                             │
│  OPERACIONES:                                               │
│                                                             │
│  git stash list     → Ver todos los stashes                 │
│  git stash pop      → Restaura stash@{0} y lo elimina       │
│  git stash apply    → Restaura stash@{0} pero lo mantiene   │
│  git stash pop 2    → Restaura stash@{2} específicamente    │
│  git stash drop 1   → Elimina stash@{1} sin aplicar         │
│                                                             │
│  VIEWING STASH CONTENTS:                                    │
│  git stash show stash@{1}        → Summary                  │
│  git stash show -p stash@{1}     → Full diff                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

🍒 CAPÍTULO 5: CHERRY-PICK - CIRUGÍA SELECTIVA

El Concepto: Trasplante de Commits

Cherry-pick copia commits específicos de una branch a otra, sin traer toda la branch.

╔═══════════════════════════════════════════════════════════╗
║          CHERRY-PICK COMO OPERACIÓN QUIRÚRGICA            ║
╚═══════════════════════════════════════════════════════════╝

🎭 SCENARIO: Selective Integration

┌───────────────────────────────────────────────────────────┐
│  SITUACIÓN:                                               │
│  Feature branch con mezcla de good y bad commits           │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  feature/experimental                                     │
│  ○─────○─────●─────○─────○─────●─────○                   │
│  │     │     │     │     │     │     │                   │
│  A     B     C     D     E     F     G                   │
│  │     │     │     │     │     │     │                   │
│  │     │     │     │     │     │     │                   │
│  ✅    ✅    🎯    ❌    ❌    🎯    ✅                   │
│  Good  Good  Want! Bad   Bad  Want! Good                  │
│                                                           │
│  DESCOMPOSICIÓN:                                          │
│  ├─ Commits A, B, G: Features estables                    │
│  ├─ Commits C, F: Features que QUIERES en develop         │
│  └─ Commits D, E: Experimental (no listos)                │
│                                                           │
│  PROBLEMA:                                                │
│  • No quieres MERGE toda la branch (trae D, E)            │
│  • No quieres REBASE (reescribe historia compartida)      │
│  • SÍ quieres solo C y F                                  │
│                                                           │
│  SOLUCIÓN:                                                │
│  Cherry-pick C y F selectivamente                         │
│                                                           │
└───────────────────────────────────────────────────────────┘

Geometría del Cherry-Pick

🍒 VISUALIZACIÓN DE LA OPERACIÓN

┌─────────────────────────────────────────────────────────────┐
│  TOPOLOGY ANTES DEL CHERRY-PICK                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SOURCE BRANCH: feature/experimental                        │
│  ┌──────────────────────────────────────────┐              │
│  │ ○─────○─────●─────○─────○─────●─────○   │              │
│  │ A     B     C     D     E     F     G   │              │
│  │             ↑                   ↑         │              │
│  │          Want this!          Want this!   │              │
│  │          (abc123)            (def456)     │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  TARGET BRANCH: develop                                     │
│  ┌──────────────────────────────────────────┐              │
│  │ ◯─────◯─────◯                            │              │
│  │ X     Y     Z  ← Current HEAD             │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ git checkout develop
         │ git cherry-pick abc123

┌─────────────────────────────────────────────────────────────┐
│  DESPUÉS DE PRIMER CHERRY-PICK                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SOURCE BRANCH: feature/experimental (NO CAMBIA)            │
│  ┌──────────────────────────────────────────┐              │
│  │ ○─────○─────●─────○─────○─────●─────○   │              │
│  │ A     B     C     D     E     F     G   │              │
│  │             ↑ Sigue existiendo           │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  TARGET BRANCH: develop (NUEVA COPIA)                       │
│  ┌──────────────────────────────────────────┐              │
│  │ ◯─────◯─────◯─────◉                      │              │
│  │ X     Y     Z     C'  ← Copy of C        │              │
│  │                   (xyz789)                │              │
│  │                   Nuevo SHA               │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  NOTA CRÍTICA:                                              │
│  • C' es COPY, no move                                     │
│  • C sigue en feature/experimental                         │
│  • C' tiene diferente SHA (xyz789 vs abc123)               │
│  • Mismo CONTENIDO, diferente CONTEXT                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

         │ git cherry-pick def456

┌─────────────────────────────────────────────────────────────┐
│  DESPUÉS DE SEGUNDO CHERRY-PICK                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SOURCE BRANCH: feature/experimental (UNCHANGED)            │
│  ┌──────────────────────────────────────────┐              │
│  │ ○─────○─────●─────○─────○─────●─────○   │              │
│  │ A     B     C     D     E     F     G   │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  TARGET BRANCH: develop (TIENE COPIES)                      │
│  ┌──────────────────────────────────────────┐              │
│  │ ◯─────◯─────◯─────◉─────◉                │              │
│  │ X     Y     Z     C'    F'                │              │
│  │                         ↑                 │              │
│  │                    Copy of F              │              │
│  │                    (uvw456)               │              │
│  └──────────────────────────────────────────┘              │
│                                                             │
│  RESULTADO:                                                 │
│  ✅ Develop tiene commits que quieres (C, F)                │
│  ✅ Feature branch intacta (puede seguir desarrollo)        │
│  ✅ No trajiste commits bad (D, E)                          │
│  ✅ Cherry-pick es additive, no destructive                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Diferencias Conceptuales con Otras Operaciones

╔═══════════════════════════════════════════════════════════════════════════╗
║              MERGE vs REBASE vs CHERRY-PICK                               ║
╠═══════════════════════════════════════════════════════════════════════════╣
║                                                                           ║
║  🔀 MERGE: "Quiero toda la historia"                                      ║
║  ═══════                                                                  ║
║                                                                           ║
║  feature:  ○─────○─────●─────○─────○                                     ║
║            A     B     C     D     E                                      ║
║                    ╲                                                      ║
║  main:     ◯─────◯──╲──◉                                                 ║
║            X     Y   ╲ M (merge commit)                                   ║
║                       ╲                                                   ║
║                        Trae A,B,C,D,E                                     ║
║                                                                           ║
║  CARACTERÍSTICAS:                                                         ║
║  • Trae TODOS los commits de feature                                     ║
║  • Preserva historia paralela (branching visible)                        ║
║  • Crea merge commit (dos parents)                                       ║
║  • Historia verdadera (muestra cómo se desarrolló)                       ║
║  • Fácil revert (revert merge commit)                                    ║
║                                                                           ║
║  USO: "Quiero integrar todo el trabajo de feature"                       ║
║                                                                           ║
║─────────────────────────────────────────────────────────────────────────║
║                                                                           ║
║  ⟿ REBASE: "Quiero mover la base"                                        ║
║  ═══════                                                                  ║
║                                                                           ║
║  ANTES:                                                                   ║
║  feature:  ○─────○─────○                                                 ║
║            A     B     C                                                  ║
║           ╱                                                               ║
║  main:   ◯─────◯─────◯                                                   ║
║          X     Y     Z                                                    ║
║                                                                           ║
║  DESPUÉS:                                                                 ║
║  main:   ◯─────◯─────◯─────◉─────◉─────◉                                ║
║          X     Y     Z     A'    B'    C'                                 ║
║                            ↑                                              ║
║                       Rebased commits                                     ║
║                       (nuevos SHAs)                                       ║
║                                                                           ║
║  CARACTERÍSTICAS:                                                         ║
║  • Mueve TODOS los commits                                               ║
║  • Reescribe historia (nuevos SHAs)                                      ║
║  • Historia linear (no branching visible)                                ║
║  • "Pretende" que feature se desarrolló desde Z                          ║
║  • Peligroso en branches compartidas                                     ║
║                                                                           ║
║  USO: "Quiero clean historia linear"                                     ║
║                                                                           ║
║─────────────────────────────────────────────────────────────────────────║
║                                                                           ║
║  🍒 CHERRY-PICK: "Quiero solo ESTO"                                      ║
║  ══════════════                                                           ║
║                                                                           ║
║  feature:  ○─────○─────●─────○─────○                                     ║
║            A     B     C     D     E                                      ║
║                        ↑                                                  ║
║                    Want this only                                         ║
║                                                                           ║
║  main:   ◯─────◯─────◯─────◉                                             ║
║          X     Y     Z     C'                                             ║
║                            ↑                                              ║
║                       Copy of C                                           ║
║                                                                           ║
║  CARACTERÍSTICAS:                                                         ║
║  • Copia COMMITS SELECTOS                                                ║
║  • Crea nuevos commits (nuevos SHAs)                                     ║
║  • Source branch unchanged                                               ║
║  • Additive operation (no reescribe nada)                                ║
║  • Seguro en cualquier branch                                            ║
║                                                                           ║
║  USO: "Quiero este commit específico, no toda la branch"                 ║
║                                                                           ║
╚═══════════════════════════════════════════════════════════════════════════╝

Casos de Uso Típicos

╔═══════════════════════════════════════════════════════════════════════════╗
║                   CHERRY-PICK USE CASES                                   ║
╚═══════════════════════════════════════════════════════════════════════════╝

┌───────────────────────────────────────────────────────────────────────────┐
│  📋 CASO 1: HOTFIX A MÚLTIPLES VERSIONS                                    │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Bug crítico discovered en main. Mismo bug existe en múltiples            │
│  release branches (v1.0, v1.1, v2.0).                                     │
│                                                                           │
│  TOPOLOGY:                                                                │
│  ┌────────────────────────────────────────────────┐                      │
│  │ main:                                          │                      │
│  │ ◯───◯───●  ← Fix applied here first           │                      │
│  │ │       abc123                                 │                      │
│  │ │                                              │                      │
│  │ └─► release-2.0:                               │                      │
│  │     ◯───◯───◯  ← Need fix here                 │                      │
│  │     │                                           │                      │
│  │     └─► release-1.1:                            │                      │
│  │         ◯───◯  ← Need fix here                  │                      │
│  │         │                                       │                      │
│  │         └─► release-1.0:                        │                      │
│  │             ◯  ← Need fix here                  │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  ESTRATEGIA:                                                              │
│  1. Fix en main (commit abc123)                                          │
│  2. Cherry-pick a cada release branch:                                   │
│                                                                           │
│     git checkout release-2.0                                              │
│     git cherry-pick abc123                                                │
│                                                                           │
│     git checkout release-1.1                                              │
│     git cherry-pick abc123                                                │
│                                                                           │
│     git checkout release-1.0                                              │
│     git cherry-pick abc123                                                │
│                                                                           │
│  RESULTADO:                                                               │
│  ┌────────────────────────────────────────────────┐                      │
│  │ main:         ◯───◯───●                        │                      │
│  │                       abc123                    │                      │
│  │                                                 │                      │
│  │ release-2.0:  ◯───◯───◯───◉                    │                      │
│  │                           abc123'               │                      │
│  │                                                 │                      │
│  │ release-1.1:  ◯───◯───◉                        │                      │
│  │                       abc123''                  │                      │
│  │                                                 │                      │
│  │ release-1.0:  ◯───◉                            │                      │
│  │                   abc123'''                     │                      │
│  └────────────────────────────────────────────────┘                      │
│                                                                           │
│  BENEFICIOS:                                                              │
│  ✓ Mismo fix en todas las versions                                       │
│  ✓ Cada branch independiente (no merge conflicts)                        │
│  ✓ Puede adaptar fix a cada version si necesario                         │
│  ✓ Release notes: "Backported fix from main"                             │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

┌───────────────────────────────────────────────────────────────────────────┐
│  📋 CASO 2: EXTRAER COMMITS DE PR GRANDE                                   │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  PR masivo con 50 commits. Code review identifica que 5 commits           │
│  son independientes y están ready. Resto necesita más trabajo.            │
│                                                                           │
│  PROBLEMA:                                                                │
│  • Esperar todo el PR = bloquea deployment                                │
│  • Reviewer quiere aprobar los 5 good commits ahora                       │
│                                                                           │
│  ESTRATEGIA:                                                              │
│  1. Identificar commits independientes:                                   │
│     ├─ abc123: feat(dsp): add reverb (READY)                              │
│     ├─ def456: feat(ui): reverb UI (READY)                                │
│     ├─ ghi789: feat(dsp): add EQ (READY)                                  │
│     ├─ jkl012: feat(ui): EQ UI (READY)                                    │
│     └─ mno345: test: integration tests (READY)                            │
│                                                                           │
│  2. Cherry-pick a develop:                                                │
│     git checkout develop                                                  │
│     git cherry-pick abc123 def456 ghi789 jkl012 mno345                    │
│                                                                           │
│  3. Deploy los 5 commits                                                  │
│  4. PR continúa con resto del trabajo                                     │
│                                                                           │
│  BENEFICIOS:                                                              │
│  ✓ Unblocks deployment                                                    │
│  ✓ Partial merge sin esperar PR completo                                 │
│  ✓ Reviewer satisfaction (progreso visible)                               │
│  ✓ PR puede refinarse sin pressure                                       │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

┌───────────────────────────────────────────────────────────────────────────┐
│  📋 CASO 3: BACKPORT FEATURES A VERSIONES ANTERIORES                       │
├───────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  SITUACIÓN:                                                               │
│  Feature desarrollada para v2.0. Cliente important con v1.5               │
│  requiere específicamente este feature (paga extra).                      │
│                                                                           │
│  CONSIDERACIONES:                                                         │
│  • v2.0 tiene cambios incompatibles con v1.5                              │
│  • No puedes merge todo v2.0 → v1.5                                       │
│  • Solo quieres este feature específico                                   │
│                                                                           │
│  ESTRATEGIA:                                                              │
│  1. Identify feature commits en v2.0                                      │
│  2. Cherry-pick a release-1.5 branch                                      │
│  3. Resolver conflicts (adaptar a v1.5 codebase)                          │
│  4. Test extensivamente en v1.5 context                                   │
│  5. Deploy como v1.5.1                                                    │
│                                                                           │
│  EJEMPLO:                                                                 │
│  git checkout release-1.5                                                 │
│  git cherry-pick abc123 def456 ghi789                                     │
│  # Resolver conflicts                                                     │
│  # Adaptar código a APIs de v1.5                                          │
│  # Test comprehensivo                                                     │
│  git tag v1.5.1                                                           │
│                                                                           │
│  CUIDADOS:                                                                │
│  ⚠️ Feature puede depender de infrastructure de v2.0                      │
│  ⚠️ Requiere adaptación y testing riguroso                                │
│  ⚠️ Mantener dos versions del feature = maintenance burden                │
│                                                                           │
└───────────────────────────────────────────────────────────────────────────┘

🔄 CAPÍTULO 6: RESET Y REFLOG - CONTROL TOTAL

La Filosofía del Reset: Retroceso Controlado

Reset es la operación más poderosa y peligrosa de Git. Es la habilidad de mover el HEAD de la branch a cualquier punto del historial.

╔═══════════════════════════════════════════════════════════╗
║              RESET: LA MÁQUINA DEL TIEMPO                 ║
╚═══════════════════════════════════════════════════════════╝

🎭 CONCEPTO FUNDAMENTAL

┌───────────────────────────────────────────────────────────┐
│  RESET COMO OPERACIÓN DE RELOCALIZACIÓN                  │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  DEFINICIÓN:                                              │
│  Reset mueve el puntero de branch (HEAD) a un commit      │
│  diferente. Los commits "posteriores" quedan huérfanos.   │
│                                                           │
│  ANATOMÍA DEL RESET:                                      │
│                                                           │
│  ┌──────┐      ┌──────┐      ┌──────┐                    │
│  │  A   │──────│  B   │──────│  C   │  ← HEAD (main)     │
│  └──────┘      └──────┘      └──────┘                    │
│                                                           │
│  git reset B    (mover HEAD a B)                          │
│                                                           │
│  ┌──────┐      ┌──────┐      ┌──────┐                    │
│  │  A   │──────│  B   │      │  C   │  ← Huérfano        │
│  └──────┘      └──────┘      └──────┘                    │
│                     ↑                                     │
│                  HEAD (main)                              │
│                                                           │
│  PREGUNTA CRÍTICA:                                        │
│  ¿Qué pasa con el contenido de C?                         │
│                                                           │
│  RESPUESTA:                                               │
│  Depende del "modo" del reset                             │
│                                                           │
└───────────────────────────────────────────────────────────┘

Los Tres Modos de Reset: Filosofía de Destrucción

🎭 TRES NIVELES DE AGRESIVIDAD

┌─────────────────────────────────────────────────────────────┐
│  MODO 1: --soft (El Más Gentil)                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FILOSOFÍA:                                                 │
│  "Deshaz commits, pero preserva TODO el trabajo"            │
│                                                             │
│  QUÉ HACE:                                                  │
│  ├─ Mueve HEAD a commit target                              │
│  ├─ Staging Area: PRESERVA cambios de commits deshacidos   │
│  └─ Working Directory: PRESERVA todo                        │
│                                                             │
│  VISUALIZACIÓN:                                             │
│                                                             │
│  ANTES:                                                     │
│  ┌──────┐      ┌──────┐      ┌──────┐                      │
│  │  A   │──────│  B   │──────│  C   │  ← HEAD              │
│  └──────┘      └──────┘      └──────┘                      │
│                              Changes: X, Y, Z               │
│                                                             │
│  git reset --soft B                                         │
│                                                             │
│  DESPUÉS:                                                   │
│  ┌──────┐      ┌──────┐      ┌──────┐                      │
│  │  A   │──────│  B   │      │  C   │  (huérfano)          │
│  └──────┘      └──────┘      └──────┘                      │
│                   ↑                                         │
│                 HEAD                                        │
│                                                             │
│  Staging Area:    X, Y, Z  ← ¡PRESERVADO!                  │
│  Working Dir:     X, Y, Z  ← Todo intacto                  │
│                                                             │
│  CASO DE USO:                                               │
│  "Cometí 5 commits pequeños. Quiero re-combinarlos en      │
│   un solo commit mejor estructurado."                       │
│                                                             │
│  git reset --soft HEAD~5     # Deshaz 5 commits             │
│  git commit -m "feature: implementación completa"           │
│  # Ahora 1 commit en lugar de 5                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  MODO 2: --mixed (Default, Moderado)                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FILOSOFÍA:                                                 │
│  "Deshaz commits Y staging, pero preserva archivos"         │
│                                                             │
│  QUÉ HACE:                                                  │
│  ├─ Mueve HEAD a commit target                              │
│  ├─ Staging Area: LIMPIA (unstage todo)                    │
│  └─ Working Directory: PRESERVA archivos                    │
│                                                             │
│  VISUALIZACIÓN:                                             │
│                                                             │
│  git reset --mixed B  (o simplemente: git reset B)         │
│                                                             │
│  DESPUÉS:                                                   │
│  ┌──────┐      ┌──────┐      ┌──────┐                      │
│  │  A   │──────│  B   │      │  C   │  (huérfano)          │
│  └──────┘      └──────┘      └──────┘                      │
│                   ↑                                         │
│                 HEAD                                        │
│                                                             │
│  Staging Area:    (vacío)   ← LIMPIADO                     │
│  Working Dir:     X, Y, Z   ← PRESERVADO como unstaged     │
│                                                             │
│  CASO DE USO:                                               │
│  "Agregué archivos al staging area por error.              │
│   Quiero unstage todo sin perder cambios."                  │
│                                                             │
│  git reset HEAD                                             │
│  # Unstage todo, archivos quedan como "modified"           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  MODO 3: --hard (El Nuclear)                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FILOSOFÍA:                                                 │
│  "Deshaz TODO. Destrucción completa."                       │
│                                                             │
│  QUÉ HACE:                                                  │
│  ├─ Mueve HEAD a commit target                              │
│  ├─ Staging Area: DESTRUYE                                 │
│  └─ Working Directory: DESTRUYE                             │
│                                                             │
│  ⚠️  PELIGRO EXTREMO                                        │
│                                                             │
│  VISUALIZACIÓN:                                             │
│                                                             │
│  git reset --hard B                                         │
│                                                             │
│  DESPUÉS:                                                   │
│  ┌──────┐      ┌──────┐      ┌──────┐                      │
│  │  A   │──────│  B   │      │  C   │  (huérfano)          │
│  └──────┘      └──────┘      └──────┘                      │
│                   ↑                                         │
│                 HEAD                                        │
│                                                             │
│  Staging Area:    (vacío)   ← DESTRUIDO                    │
│  Working Dir:     (limpio)  ← TODO DESTRUIDO               │
│                                                             │
│  ⚠️  X, Y, Z HAN DESAPARECIDO PERMANENTEMENTE               │
│                                                             │
│  CASO DE USO:                                               │
│  "Experimento fallido. Quiero borrar TODO y volver          │
│   a estado conocido bueno."                                 │
│                                                             │
│  git reset --hard origin/main                               │
│  # Working directory = copia exacta de origin/main         │
│                                                             │
│  REGLA DE ORO:                                              │
│  🚨 NUNCA uses --hard con cambios sin commitear            │
│  🚨 SIEMPRE verifica qué vas a perder primero               │
│  🚨 CONSIDERA hacer commit temporal antes de --hard         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Reflog: La Red de Seguridad

Reflog es el log secreto de Git que registra TODOS los movimientos del HEAD.

╔═══════════════════════════════════════════════════════════╗
║              REFLOG: LA MEMORIA OCULTA                    ║
╚═══════════════════════════════════════════════════════════╝

🧠 CONCEPTO: GIT NUNCA OLVIDA

┌───────────────────────────────────────────────────────────┐
│  FILOSOFÍA DEL REFLOG                                     │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  DEFINICIÓN:                                              │
│  Reflog es un log LOCAL de cada posición donde ha estado  │
│  HEAD, incluyendo commits "eliminados".                   │
│                                                           │
│  ALCANCE:                                                 │
│  ├─ Solo en tu repositorio local                          │
│  ├─ NO compartido con otros developers                    │
│  ├─ Dura ~90 días por default                             │
│  └─ Registra TODAS las operaciones                        │
│                                                           │
│  OPERACIONES REGISTRADAS:                                 │
│  ✓ commits                                                │
│  ✓ checkouts                                              │
│  ✓ merges                                                 │
│  ✓ rebases                                                │
│  ✓ resets                                                 │
│  ✓ cherry-picks                                           │
│  ✓ stash apply/pop                                        │
│  ✓ amend                                                  │
│                                                           │
│  METÁFORA:                                                │
│  Reflog es como el historial del browser:                 │
│  Aunque borres páginas de bookmarks, sigues pudiendo      │
│  acceder a sitios visitados recientemente.                │
│                                                           │
└───────────────────────────────────────────────────────────┘

🔍 ANATOMÍA DE REFLOG ENTRIES

┌───────────────────────────────────────────────────────────┐
│  FORMATO DE ENTRADA                                       │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  HEAD@{n}  SHA      Action    Message                    │
│  ─────────────────────────────────────────────────────    │
│  HEAD@{0}  abc123   commit:   Add feature X              │
│  HEAD@{1}  def456   commit:   Fix bug Y                  │
│  HEAD@{2}  ghi789   checkout: moving to feature/Z        │
│  HEAD@{3}  jkl012   reset:    moving to HEAD~3           │
│  HEAD@{4}  mno345   commit:   WIP                        │
│                                                           │
│  INTERPRETACIÓN:                                          │
│  • HEAD@{0} = posición ACTUAL                             │
│  • HEAD@{1} = posición ANTERIOR (1 paso atrás)            │
│  • HEAD@{n} = n pasos hacia el pasado                     │
│                                                           │
│  REFERENCIAS TEMPORALES:                                  │
│  HEAD@{5.minutes.ago}                                     │
│  HEAD@{yesterday}                                         │
│  HEAD@{2.days.ago}                                        │
│  main@{one.week.ago}                                      │
│                                                           │
└───────────────────────────────────────────────────────────┘

Recovering from Disaster: Reset + Reflog

🎭 CASO DE ESTUDIO: RECUPERACIÓN DE RESET --hard ACCIDENTAL

┌─────────────────────────────────────────────────────────────┐
│  ESCENARIO DEL DESASTRE                                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SITUACIÓN:                                                 │
│  Estabas en main con 10 commits de trabajo. Por accidente   │
│  ejecutaste:                                                │
│                                                             │
│  git reset --hard HEAD~10                                   │
│                                                             │
│  💀 TODO TU TRABAJO HA DESAPARECIDO                         │
│                                                             │
│  VISUALIZACIÓN DEL DESASTRE:                                │
│                                                             │
│  ANTES (lo que tenías):                                     │
│  ○──○──○──○──○──○──○──○──○──○  ← HEAD (main)              │
│  A  B  C  D  E  F  G  H  I  J                              │
│  └──────────── Tu trabajo ─────────┘                       │
│                                                             │
│  DESPUÉS DEL RESET ACCIDENTAL:                              │
│  ○  ╳  ╳  ╳  ╳  ╳  ╳  ╳  ╳  ╳                             │
│  A                                                          │
│  ↑                                                          │
│  HEAD (main)                                                │
│                                                             │
│  • B-J parecen "eliminados"                                 │
│  • git log no los muestra                                   │
│  • Tu working directory está en estado de A                 │
│                                                             │
│  😱 PÁNICO                                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 1: MANTÉN LA CALMA Y CONSULTA REFLOG                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git reflog                                                 │
│                                                             │
│  OUTPUT:                                                    │
│  ────────────────────────────────────────────────────────   │
│  abc123 HEAD@{0}  reset: moving to HEAD~10                 │
│  def456 HEAD@{1}  commit: Implement feature J              │
│  ghi789 HEAD@{2}  commit: Implement feature I              │
│  jkl012 HEAD@{3}  commit: Implement feature H              │
│  ...                                                        │
│  xyz000 HEAD@{10} commit: Implement feature B              │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  🎯 KEY INSIGHT:                                            │
│  • HEAD@{1} (def456) es tu último commit ANTES del reset    │
│  • Ese commit TODAVÍA EXISTE en el repositorio              │
│  • Los commits B-J siguen en la base de datos de Git        │
│  • Solo están "huérfanos" (no apuntados por ninguna branch) │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: RESET DE VUELTA AL ESTADO CORRECTO                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git reset --hard HEAD@{1}                                  │
│                                                             │
│  O ESPECÍFICAMENTE:                                         │
│  git reset --hard def456                                    │
│                                                             │
│  RESULTADO:                                                 │
│  ○──○──○──○──○──○──○──○──○──○  ← HEAD (main)              │
│  A  B  C  D  E  F  G  H  I  J                              │
│                                 ↑                           │
│                           RECUPERADO!                        │
│                                                             │
│  ✅ TODO TU TRABAJO HA SIDO RESTAURADO                      │
│                                                             │
│  NUEVO REFLOG:                                              │
│  ────────────────────────────────────────────────────────   │
│  def456 HEAD@{0}  reset: moving to HEAD@{1}                │
│  abc123 HEAD@{1}  reset: moving to HEAD~10                 │
│  def456 HEAD@{2}  commit: Implement feature J              │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  LECCIÓN:                                                   │
│  Reflog es una máquina del tiempo. Casi NADA es             │
│  irrecuperable en Git si actúas rápido (< 90 días).         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Reset vs Revert: Filosofías Opuestas

╔═══════════════════════════════════════════════════════════╗
║          RESET VS REVERT: FILOSOFÍA DE DESHACER           ║
╚═══════════════════════════════════════════════════════════╝

┌─────────────────────────────────────────────────────────────┐
│  RESET: REESCRIBIR HISTORIA                                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FILOSOFÍA: "Esto nunca pasó"                               │
│                                                             │
│  ○──○──○──○──○  ← HEAD                                     │
│  A  B  C  D  E                                             │
│                                                             │
│  git reset --hard B                                         │
│                                                             │
│  ○──○                                                       │
│  A  B  ← HEAD                                              │
│                                                             │
│  • C, D, E DESAPARECEN de la historia                       │
│  • La timeline es REESCRITA                                 │
│  • Approach destructivo                                     │
│                                                             │
│  CUÁNDO USAR:                                               │
│  ✓ En branches locales (no pusheadas)                       │
│  ✓ Para limpiar experimentos                                │
│  ✓ Para reorganizar commits antes de push                   │
│                                                             │
│  CUÁNDO NO USAR:                                            │
│  ✗ En branches compartidas (pusheadas)                      │
│  ✗ En commits que otros han basado trabajo                  │
│  ✗ Cuando quieres preservar historial completo              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  REVERT: CREAR HISTORIA CORRECTIVA                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FILOSOFÍA: "Esto pasó, pero ahora lo deshacemos"           │
│                                                             │
│  ○──○──○──○──○  ← HEAD                                     │
│  A  B  C  D  E                                             │
│                                                             │
│  git revert C                                               │
│                                                             │
│  ○──○──○──○──○──○  ← HEAD                                  │
│  A  B  C  D  E  C'                                         │
│              ↑   ↑                                          │
│           Bad  Undo                                         │
│                                                             │
│  • C permanece en la historia                               │
│  • C' es un NUEVO commit que deshace C                      │
│  • La timeline es ADITIVA                                   │
│  • Approach no-destructivo                                  │
│                                                             │
│  CUÁNDO USAR:                                               │
│  ✓ En branches compartidas (pusheadas)                      │
│  ✓ En producción                                            │
│  ✓ Cuando quieres audit trail completo                      │
│  ✓ Para preservar toda la historia                          │
│                                                             │
│  METÁFORA:                                                  │
│  • Reset = borrar con goma de borrar                        │
│  • Revert = escribir "corrección:" con nuevo renglón        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

🎭 TABLA DE DECISIÓN

┌────────────────────────────┬──────────┬──────────┐
│  SITUACIÓN                 │  RESET   │  REVERT  │
├────────────────────────────┼──────────┼──────────┤
│  Branch local              │    ✅     │    ⚠️     │
│  Branch compartida         │    ❌     │    ✅     │
│  Commits pusheados         │    ❌     │    ✅     │
│  Limpiar experimentos      │    ✅     │    ❌     │
│  Bug en production         │    ❌     │    ✅     │
│  Preservar historia full   │    ❌     │    ✅     │
│  Reorganizar commits       │    ✅     │    ❌     │
│  Audit trail requerido     │    ❌     │    ✅     │
└────────────────────────────┴──────────┴──────────┘

🎼 CAPÍTULO 7: WORKFLOWS COMBINADOS

Orquestación de Técnicas Avanzadas

Las operaciones avanzadas rara vez se usan en aislamiento. La maestría está en combinarlas.

╔═══════════════════════════════════════════════════════════╗
║          WORKFLOWS: SINFONÍA DE OPERACIONES               ║
╚═══════════════════════════════════════════════════════════╝

🎭 FILOSOFÍA DE LA ORQUESTACIÓN

┌───────────────────────────────────────────────────────────┐
│  PRINCIPIO FUNDAMENTAL                                    │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  Una operación avanzada resuelve UN problema.             │
│  Un workflow combina MÚLTIPLES operaciones para resolver  │
│  problemas complejos del mundo real.                      │
│                                                           │
│  COMPONENTES:                                             │
│  • Rebase Interactive → Limpia historia                   │
│  • Stash → Guarda trabajo temporal                        │
│  • Cherry-pick → Transplanta selectivamente               │
│  • Reset → Deshace errores                                │
│  • Bisect → Encuentra bugs                                │
│  • Reflog → Recupera desastres                            │
│                                                           │
│  PRINCIPIO DE COMPOSICIÓN:                                │
│  Operación₁ + Operación₂ + ... + Operaciónₙ = Workflow    │
│                                                           │
└───────────────────────────────────────────────────────────┘

Workflow 1: Feature Branch Refinement

🎯 CASO: PREPARAR FEATURE BRANCH PARA PR

┌─────────────────────────────────────────────────────────────┐
│  SITUACIÓN INICIAL                                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Has trabajado en feature/audio-filters por 2 semanas.      │
│  Tienes:                                                    │
│  • 47 commits (muchos son "WIP", "fix typo", etc.)          │
│  • 3 bugs fixes mezclados con feature work                  │
│  • Trabajo sin pushear                                      │
│  • main ha avanzado 20 commits desde que creaste la branch   │
│                                                             │
│  OBJETIVO:                                                  │
│  Crear un PR limpio, profesional, fácil de review.          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 1: SINCRONIZAR CON MAIN (REBASE)                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  OBJETIVO: Traer cambios de main a feature branch            │
│                                                             │
│  git checkout feature/audio-filters                         │
│  git fetch origin                                           │
│  git rebase origin/main                                     │
│                                                             │
│  ANTES:                                                     │
│       ○──○──○──○──○  origin/main (20 commits nuevos)       │
│      /                                                      │
│  ○──○                                                       │
│      \                                                      │
│       ○──○──...──○  feature/audio-filters (47 commits)     │
│                                                             │
│  DESPUÉS:                                                   │
│  ○──○──○──○──○──○  origin/main                             │
│                  \                                          │
│                   ○──○──...──○  feature/audio-filters      │
│                   (47 commits rebased)                      │
│                                                             │
│  ⚠️  RESOLVER CONFLICTS SI ES NECESARIO                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: LIMPIAR HISTORIA (REBASE INTERACTIVE)              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  OBJETIVO: Consolidar 47 commits en ~5-8 commits lógicos     │
│                                                             │
│  git rebase -i origin/main                                  │
│                                                             │
│  ESTRATEGIA DE TODO LIST:                                   │
│                                                             │
│  pick abc123 feat: Add lowpass filter structure             │
│  squash def456 WIP                                          │
│  squash ghi789 fix typo                                     │
│  squash jkl012 more work on lowpass                         │
│  fixup mno345 oops                                          │
│                                                             │
│  pick pqr678 feat: Add highpass filter                      │
│  squash stu901 WIP highpass                                 │
│  fixup vwx234 fix bug                                       │
│                                                             │
│  pick yza567 feat: Add bandpass filter                      │
│  squash bcd890 complete bandpass                            │
│                                                             │
│  pick efg123 test: Add comprehensive filter tests           │
│  squash hij456 fix test                                     │
│  squash klm789 more tests                                   │
│                                                             │
│  pick nop012 docs: Document filter API                      │
│                                                             │
│  RESULTADO:                                                 │
│  47 commits → 5 commits limpios                             │
│                                                             │
│  ○  feat: Add lowpass filter structure                      │
│  ○  feat: Add highpass filter                               │
│  ○  feat: Add bandpass filter                               │
│  ○  test: Add comprehensive filter tests                    │
│  ○  docs: Document filter API                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 3: EXTRAER BUG FIXES (CHERRY-PICK)                    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  PROBLEMA DETECTADO:                                        │
│  Durante desarrollo, encontraste 3 bugs en código existente  │
│  y los fixeaste. Esos fixes deberían ir a main AHORA,       │
│  no esperar a que se mergee el feature completo.             │
│                                                             │
│  IDENTIFICAR LOS FIXES:                                     │
│  • fix: Correct memory leak in AudioBuffer (abc111)         │
│  • fix: Handle null input in AudioProcessor (def222)        │
│  • fix: Prevent crash on empty stream (ghi333)              │
│                                                             │
│  ESTRATEGIA:                                                │
│  1. Crear branch hotfix/memory-leak desde main              │
│  2. Cherry-pick los 3 fixes                                 │
│  3. PR independiente para bug fixes                         │
│  4. Remover esos commits de feature branch                  │
│                                                             │
│  EJECUCIÓN:                                                 │
│  git checkout main                                          │
│  git checkout -b hotfix/critical-fixes                      │
│  git cherry-pick abc111 def222 ghi333                       │
│  git push origin hotfix/critical-fixes                      │
│  # Create PR #451: "fix: Critical memory and crash fixes"   │
│                                                             │
│  git checkout feature/audio-filters                         │
│  git rebase -i origin/main                                  │
│  # En todo list: DROP los 3 commits de fixes               │
│  # (ya están en hotfix branch)                              │
│                                                             │
│  BENEFICIO:                                                 │
│  • Bug fixes deployed inmediatamente                        │
│  • Feature PR enfocado solo en feature                      │
│  • Reviewers aprecian separación de concerns                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 4: PUSH Y CREATE PR                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ESTADO FINAL:                                              │
│  • 5 commits limpios, bien formateados                      │
│  • Historia lineal desde main actualizado                   │
│  • Bug fixes extraídos a PR separado                        │
│  • Listo para review                                        │
│                                                             │
│  git push origin feature/audio-filters --force-with-lease   │
│  # Create PR #452: "feat: Implement audio filters system"   │
│                                                             │
│  PR DESCRIPTION:                                            │
│  ────────────────────────────────────────────────────────   │
│  ## Summary                                                 │
│  Implements lowpass, highpass, and bandpass filters.        │
│                                                             │
│  ## Commits                                                 │
│  • feat: Add lowpass filter structure                       │
│  • feat: Add highpass filter                                │
│  • feat: Add bandpass filter                                │
│  • test: Add comprehensive filter tests                     │
│  • docs: Document filter API                                │
│                                                             │
│  ## Related                                                 │
│  Depends on #451 (bug fixes)                                │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  RESULTADO:                                                 │
│  ✅ PR profesional, fácil de review                         │
│  ✅ Historia limpia y narrativa                             │
│  ✅ Separation of concerns (bugs vs features)               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 TÉCNICAS USADAS EN ESTE WORKFLOW:
├─ Rebase (rebase origin/main)
├─ Rebase Interactive (squash/fixup/drop)
├─ Cherry-pick (extraer bug fixes)
└─ Force push --force-with-lease

Workflow 2: Emergency Hotfix During Feature Work

🚨 CASO: BUG CRÍTICO EN PRODUCCIÓN MIENTRAS TRABAJAS EN FEATURE

┌─────────────────────────────────────────────────────────────┐
│  SITUACIÓN                                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ESTÁS:                                                     │
│  • Trabajando en feature/new-synthesizer                    │
│  • Working directory tiene cambios sin commitear            │
│  • Staging area tiene algunos archivos staged               │
│  • En medio de refactoring complejo                         │
│                                                             │
│  DE REPENTE:                                                │
│  🚨 Production bug crítico reportado                        │
│  🚨 Necesitas fixearlo AHORA                                │
│  🚨 No puedes commitear tu trabajo actual (está roto)        │
│                                                             │
│  OBJETIVO:                                                  │
│  Fix production sin perder tu trabajo en progreso.           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 1: GUARDAR TRABAJO ACTUAL (STASH)                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git stash push -m "WIP: Synthesizer refactor"              │
│                                                             │
│  RESULTADO:                                                 │
│  • Working directory: LIMPIO                                │
│  • Staging area: LIMPIO                                     │
│  • Cambios guardados en stash                               │
│  • Listo para cambiar de contexto                           │
│                                                             │
│  VERIFICAR:                                                 │
│  git status                                                 │
│  # "nothing to commit, working tree clean"                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: CREAR HOTFIX BRANCH                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git checkout main                                          │
│  git pull origin main                                       │
│  git checkout -b hotfix/production-crash                    │
│                                                             │
│  ESTADO:                                                    │
│  • En branch limpia desde main actualizado                  │
│  • Working directory limpio                                 │
│  • Listo para implementar fix                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 3: IMPLEMENTAR Y DEPLOY FIX                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  # Fix el bug                                               │
│  git add .                                                  │
│  git commit -m "fix: Prevent crash on null audio input"     │
│                                                             │
│  # Test                                                     │
│  # Deploy                                                   │
│                                                             │
│  git push origin hotfix/production-crash                    │
│  # Create PR, merge, deploy                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 4: VOLVER A FEATURE WORK (STASH POP)                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git checkout feature/new-synthesizer                       │
│  git stash pop                                              │
│                                                             │
│  RESULTADO:                                                 │
│  • De vuelta en feature branch                              │
│  • Working directory restaurado exactamente como estaba     │
│  • Staging area restaurada                                  │
│  • Stash eliminado (porque pop = apply + drop)              │
│                                                             │
│  CONTINUAR TRABAJO:                                         │
│  # Sigues exactamente donde lo dejaste                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 5: SINCRONIZAR FIX A FEATURE BRANCH                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  PROBLEMA:                                                  │
│  El fix que hiciste en main también aplica a tu feature.     │
│                                                             │
│  OPCIÓN A: MERGE MAIN                                       │
│  git merge main                                             │
│  # Trae el fix + otros cambios de main                      │
│                                                             │
│  OPCIÓN B: CHERRY-PICK EL FIX                               │
│  git log main --oneline -5                                  │
│  # Identificar SHA del fix: abc123                          │
│  git cherry-pick abc123                                     │
│  # Solo trae el fix específico                              │
│                                                             │
│  RECOMENDACIÓN:                                             │
│  • Cherry-pick si solo quieres el fix                       │
│  • Merge si quieres sincronizar con main completamente      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 TÉCNICAS USADAS:
├─ Stash (guardar trabajo temporal)
├─ Checkout (cambiar contexto)
├─ Stash pop (restaurar trabajo)
└─ Cherry-pick o Merge (sincronizar fix)

⏱️ TIEMPO TOTAL: ~30 minutos
• Sin perder trabajo
• Sin commits "WIP" sucios
• Production fixed
• Feature work intacto

Workflow 3: Debugging with Bisect + Reflog

🔍 CASO: ENCONTRAR CUANDO SE INTRODUJO UN BUG

┌─────────────────────────────────────────────────────────────┐
│  SITUACIÓN                                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  PROBLEMA:                                                  │
│  • Tests están fallando en main                             │
│  • Funcionaban hace 2 semanas                                │
│  • 300 commits entre "working" y "broken"                    │
│  • No sabes qué commit introdujo el bug                      │
│                                                             │
│  OBJETIVO:                                                  │
│  Encontrar el commit exacto que introdujo el bug.            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 1: IDENTIFICAR GOOD Y BAD COMMITS                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ESTRATEGIA:                                                │
│  Usar REFLOG para encontrar cuando tests pasaban.           │
│                                                             │
│  git reflog --all --date=relative                           │
│                                                             │
│  OUTPUT:                                                    │
│  ────────────────────────────────────────────────────────   │
│  abc123 HEAD@{0}      2 hours ago:    commit: Fix X        │
│  def456 HEAD@{5}      1 day ago:      commit: Feature Y    │
│  ghi789 HEAD@{50}     1 week ago:     commit: Refactor Z   │
│  jkl012 HEAD@{150}    2 weeks ago:    commit: Add tests    │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  VERIFICAR COMMITS ANTIGUOS:                                │
│  git checkout jkl012                                        │
│  npm test                                                   │
│  # ✅ Tests pasan                                           │
│                                                             │
│  git checkout main                                          │
│  npm test                                                   │
│  # ❌ Tests fallan                                          │
│                                                             │
│  CONCLUSIÓN:                                                │
│  • GOOD commit: jkl012 (2 semanas atrás)                    │
│  • BAD commit: abc123 (HEAD actual)                         │
│  • 300 commits entre ellos                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: INICIAR BISECT                                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git bisect start                                           │
│  git bisect bad                      # HEAD actual es bad   │
│  git bisect good jkl012              # jkl012 es good       │
│                                                             │
│  OUTPUT:                                                    │
│  "Bisecting: 150 revisions left to test after this          │
│   (roughly 8 steps)"                                        │
│                                                             │
│  INTERPRETACIÓN:                                            │
│  • 300 commits → 8 iteraciones binarias                     │
│  • Git checked out commit intermedio automáticamente        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 3: ITERACIÓN MANUAL                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ITERACIÓN 1:                                               │
│  npm test                                                   │
│  # ✅ Pasan                                                 │
│  git bisect good                                            │
│                                                             │
│  "Bisecting: 75 revisions left (roughly 7 steps)"           │
│                                                             │
│  ITERACIÓN 2:                                               │
│  npm test                                                   │
│  # ❌ Fallan                                                │
│  git bisect bad                                             │
│                                                             │
│  "Bisecting: 37 revisions left (roughly 6 steps)"           │
│                                                             │
│  ... (continuar 6 iteraciones más)                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 4: AUTOMATIZACIÓN (BISECT RUN)                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  MEJOR APPROACH: Dejar que Git teste automáticamente        │
│                                                             │
│  git bisect start                                           │
│  git bisect bad                                             │
│  git bisect good jkl012                                     │
│                                                             │
│  git bisect run npm test                                    │
│                                                             │
│  Git ejecutará:                                             │
│  1. Checkout commit intermedio                              │
│  2. Ejecutar "npm test"                                     │
│  3. Si exit code = 0 → marcar good                          │
│  4. Si exit code ≠ 0 → marcar bad                           │
│  5. Repetir hasta encontrar first bad commit                │
│                                                             │
│  OUTPUT FINAL:                                              │
│  ────────────────────────────────────────────────────────   │
│  xyz456 is the first bad commit                             │
│  commit xyz456                                              │
│  Author: Developer Name                                     │
│  Date: 10 days ago                                          │
│                                                             │
│      refactor: Optimize audio processing pipeline           │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  🎯 COMMIT CULPABLE ENCONTRADO                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 5: ANALIZAR Y FIXEAR                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git bisect reset                    # Volver a HEAD        │
│  git show xyz456                     # Examinar el commit   │
│                                                             │
│  ANÁLISIS:                                                  │
│  El commit xyz456 introdujo optimización que rompió tests.   │
│                                                             │
│  OPCIONES:                                                  │
│                                                             │
│  OPCIÓN A: REVERT                                           │
│  git revert xyz456                                          │
│  # Deshace el commit problemático                           │
│                                                             │
│  OPCIÓN B: FIX FORWARD                                      │
│  # Implementar fix que corrija el bug                       │
│  git commit -m "fix: Correct processing pipeline regression"│
│                                                             │
│  OPCIÓN C: REBASE INTERACTIVE (si no pusheado)              │
│  git rebase -i jkl012                                       │
│  # EDIT el commit xyz456                                    │
│  # Fix el bug in-place                                      │
│  # Reescribir historia limpia                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 TÉCNICAS USADAS:
├─ Reflog (encontrar good commit histórico)
├─ Bisect (búsqueda binaria)
├─ Bisect run (automatización)
└─ Revert o Rebase (fix)

⏱️ EFICIENCIA:
300 commits → 8 iteraciones → ~10 minutos
(vs hours/days de búsqueda manual)

🎓 CAPÍTULO 8: CASOS DE ESTUDIO

Casos Reales de AudioLab

╔═══════════════════════════════════════════════════════════╗
║          CASOS DE ESTUDIO: AUDIOLAB EN PRODUCCIÓN         ║
╚═══════════════════════════════════════════════════════════╝

📚 APRENDIZAJES DEL MUNDO REAL

Caso 1: El Gran Refactor de Plugin Architecture

🏗️ CASO: RESTRUCTURACIÓN MASIVA DE ARQUITECTURA

┌─────────────────────────────────────────────────────────────┐
│  CONTEXTO                                                    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SITUACIÓN:                                                 │
│  AudioLab necesitaba migrar de arquitectura monolítica a     │
│  plugin-based architecture. Proyecto masivo:                 │
│  • 6 developers trabajando simultáneamente                   │
│  • 120 archivos afectados                                   │
│  • 3 semanas de trabajo                                     │
│  • Production deployments cada viernes                       │
│  • No podemos romper main                                   │
│                                                             │
│  DESAFÍO:                                                   │
│  ¿Cómo coordinar refactor masivo sin bloquear desarrollo?    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  ESTRATEGIA ADOPTADA                                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  PHASE 1: BRANCH SETUP                                      │
│                                                             │
│  main                                                       │
│    ↓                                                        │
│  feature/plugin-architecture  ← Long-lived integration      │
│    ├─ feature/plugin-core     ← Developer 1-2               │
│    ├─ feature/plugin-api      ← Developer 3                 │
│    ├─ feature/plugin-loader   ← Developer 4                 │
│    └─ feature/plugin-registry ← Developer 5-6               │
│                                                             │
│  REGLAS:                                                    │
│  • Cada developer trabaja en sub-branch                     │
│  • Daily merge a feature/plugin-architecture                │
│  • Weekly rebase desde main                                 │
│  • No merge a main hasta completar 100%                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PROBLEMA ENCONTRADO: MERGE HELL                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SEMANA 2:                                                  │
│  • feature/plugin-architecture tiene 87 commits              │
│  • main ha avanzado 43 commits                              │
│  • Merge conflicts masivos cada vez que rebase              │
│                                                             │
│  SÍNTOMA:                                                   │
│  git rebase main                                            │
│  # 23 conflicts                                             │
│  # 4 horas resolviendo conflicts                            │
│  # Al día siguiente: 18 conflicts nuevos                    │
│                                                             │
│  RAÍZ DEL PROBLEMA:                                         │
│  Rebasing daily crea conflicts repetitivos porque la        │
│  integration branch está en flux constante.                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  SOLUCIÓN: REBASE + MERGE ESTRATÉGICO                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  NUEVA ESTRATEGIA:                                          │
│                                                             │
│  1. SINCRONIZACIÓN SEMANAL:                                 │
│     Cada viernes (después de production deploy):            │
│     git checkout feature/plugin-architecture                │
│     git merge main                                          │
│     # Resolver conflicts UNA VEZ                            │
│     # Publicar integration branch actualizada               │
│                                                             │
│  2. SUB-BRANCHES REBASE DAILY:                              │
│     Cada developer diariamente:                             │
│     git checkout feature/plugin-core                        │
│     git rebase feature/plugin-architecture                  │
│     # Conflicts mínimos (solo cambios de otros devs)        │
│                                                             │
│  3. INTEGRACIÓN:                                            │
│     Cuando sub-feature completa:                            │
│     git checkout feature/plugin-architecture                │
│     git merge --no-ff feature/plugin-core                   │
│     # Merge commit preserva contexto                        │
│                                                             │
│  RESULTADO:                                                 │
│  • Conflicts reducidos 80%                                  │
│  • Tiempo de conflict resolution: 4h → 45min/semana         │
│  • Developers pueden trabajar independientemente            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PREPARACIÓN PARA MERGE A MAIN                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  SEMANA 3: Feature completo                                 │
│                                                             │
│  PROBLEMA:                                                  │
│  feature/plugin-architecture tiene 187 commits.              │
│  No queremos 187 commits en main (historia sucia).           │
│                                                             │
│  ESTRATEGIA DE LIMPIEZA:                                    │
│                                                             │
│  git checkout feature/plugin-architecture                   │
│  git rebase -i main                                         │
│                                                             │
│  TODO LIST:                                                 │
│  # Consolidar en commits LÓGICOS, no cronológicos           │
│                                                             │
│  pick abc123  feat: Plugin core infrastructure              │
│  squash ...   (30 commits related)                          │
│                                                             │
│  pick def456  feat: Plugin API and interfaces               │
│  squash ...   (25 commits related)                          │
│                                                             │
│  pick ghi789  feat: Plugin loader and lifecycle             │
│  squash ...   (40 commits related)                          │
│                                                             │
│  pick jkl012  feat: Plugin registry and discovery           │
│  squash ...   (35 commits related)                          │
│                                                             │
│  pick mno345  test: Comprehensive plugin system tests       │
│  squash ...   (20 commits related)                          │
│                                                             │
│  pick pqr678  docs: Plugin architecture documentation       │
│  squash ...   (15 commits related)                          │
│                                                             │
│  pick stu901  chore: Migration guide and examples           │
│  squash ...   (22 commits related)                          │
│                                                             │
│  RESULTADO:                                                 │
│  187 commits → 7 commits épicos                             │
│                                                             │
│  Cada commit:                                               │
│  • Es completo y auto-contenido                             │
│  • Pasa todos los tests                                     │
│  • Tiene mensaje detallado con context                      │
│  • Representa milestone lógico                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  MERGE FINAL A MAIN                                         │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git checkout main                                          │
│  git merge --no-ff feature/plugin-architecture              │
│  git tag v2.0.0                                             │
│  git push origin main --tags                                │
│                                                             │
│  HISTORIA RESULTANTE EN MAIN:                               │
│                                                             │
│  ○  Merge feature/plugin-architecture into main             │
│  ├─╮                                                        │
│  │ ○  chore: Migration guide and examples                  │
│  │ ○  docs: Plugin architecture documentation              │
│  │ ○  test: Comprehensive plugin system tests              │
│  │ ○  feat: Plugin registry and discovery                  │
│  │ ○  feat: Plugin loader and lifecycle                    │
│  │ ○  feat: Plugin API and interfaces                      │
│  │ ○  feat: Plugin core infrastructure                     │
│  ○─╯  v1.x work continues                                  │
│                                                             │
│  BENEFICIOS:                                                │
│  ✓ Historia limpia y comprensible                           │
│  ✓ Cada commit es self-contained                            │
│  ✓ Fácil de navegar y bisect                                │
│  ✓ Merge commit marca milestone importante                  │
│  ✓ Tag v2.0.0 marca el deployment                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 LECCIONES APRENDIDAS:
1. Long-lived branches necesitan estrategia de sincronización
2. Merge para integración, rebase para limpieza
3. Historia limpia > historia cronológica
4. Interactive rebase es esencial antes de merge a main
5. Merge commits son valiosos para marcar milestones

Caso 2: El Desastre del Force Push

💥 CASO: FORCE PUSH ACCIDENTAL A MAIN

┌─────────────────────────────────────────────────────────────┐
│  EL INCIDENTE                                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  VIERNES 4:30 PM:                                           │
│  Developer A ejecuta:                                       │
│                                                             │
│  git checkout main                                          │
│  git rebase -i HEAD~5                                       │
│  # Squash algunos commits                                   │
│  git push origin main --force                               │
│                                                             │
│  💀 DESASTRE                                                │
│                                                             │
│  QUÉ PASÓ:                                                  │
│  • Main tenía 5 commits compartidos por 4 developers         │
│  • Developer A los squasheó en 2 commits                    │
│  • Force push reescribió historia de main                   │
│  • Otros 3 developers tienen divergent history              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  SÍNTOMAS INMEDIATOS                                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  DEVELOPER B (5 minutos después):                           │
│  git pull                                                   │
│                                                             │
│  OUTPUT:                                                    │
│  "Your branch and 'origin/main' have diverged,              │
│   and have 5 and 2 different commits each."                 │
│                                                             │
│  git log --oneline --graph --all                            │
│                                                             │
│  *   abc123  (origin/main) Consolidated feature work        │
│  │   def456  (origin/main) Consolidated tests               │
│  │ * ghi789  (HEAD -> main) Test suite expansion            │
│  │ * jkl012  Feature optimization                           │
│  │ * mno345  Bug fix                                        │
│  │ * pqr678  API improvement                                │
│  │ * stu901  Initial feature                                │
│  └─*                                                        │
│                                                             │
│  🚨 HISTORIA DIVERGENTE                                     │
│                                                             │
│  DEVELOPERS C y D:                                          │
│  Mismo problema. 3 developers bloqueados.                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  RECUPERACIÓN: ESTRATEGIA DE EMERGENCIA                     │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  PASO 1: IDENTIFICAR ESTADO PRE-FORCE-PUSH                  │
│                                                             │
│  Developer B (o cualquiera) ejecuta:                        │
│  git reflog show origin/main                                │
│                                                             │
│  OUTPUT:                                                    │
│  ────────────────────────────────────────────────────────   │
│  abc123  origin/main@{0}  forced-update                     │
│  stu901  origin/main@{1}  commit: Initial feature          │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  🎯 origin/main@{1} es el estado ANTES del force push       │
│                                                             │
│  VERIFICAR:                                                 │
│  git log origin/main@{1} --oneline -10                      │
│  # Muestra los 5 commits originales                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: RESTAURAR MAIN (ADMIN ACTION)                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ADMIN (con permisos) ejecuta:                              │
│                                                             │
│  git checkout main                                          │
│  git reset --hard origin/main@{1}                           │
│  git push origin main --force-with-lease                    │
│                                                             │
│  ADVERTENCIA A EQUIPO:                                      │
│  "Main restaurado. Todos ejecuten:                          │
│   git checkout main                                         │
│   git reset --hard origin/main                              │
│   git pull"                                                 │
│                                                             │
│  RESULTADO:                                                 │
│  • Main restaurado a estado pre-desastre                    │
│  • Historia original preservada                             │
│  • Todos los developers sincronizados                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 3: PREVENCIÓN FUTURA                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  MEDIDA 1: BRANCH PROTECTION                                │
│  GitHub Settings → Branches → Add rule:                     │
│  • Branch name: main                                        │
│  • ☑ Require pull request reviews                           │
│  • ☑ Require status checks to pass                          │
│  • ☑ Include administrators                                 │
│  • ☑ Restrict who can push to matching branches             │
│                                                             │
│  RESULTADO:                                                 │
│  Force push a main = BLOQUEADO                              │
│                                                             │
│  MEDIDA 2: GIT HOOKS (LOCAL)                                │
│  .git/hooks/pre-push:                                       │
│  ────────────────────────────────────────────────────────   │
│  #!/bin/bash                                                │
│  branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,') │
│  if [ "$branch" = "main" ]; then                            │
│    echo "🚫 Direct push to main is not allowed"             │
│    echo "   Create a PR instead"                            │
│    exit 1                                                   │
│  fi                                                         │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  MEDIDA 3: EDUCACIÓN                                        │
│  • Never force push shared branches                         │
│  • Use --force-with-lease instead of --force                │
│  • Always verify branch before force push                   │
│  • Main/develop = sacred, never rewrite                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 LECCIONES:
1. Reflog salva vidas (incluso en remote)
2. Branch protection es MANDATORIO
3. --force es peligroso, --force-with-lease es safer
4. Nunca reescribir historia compartida
5. Git hooks pueden prevenir errores comunes

Caso 3: Arqueología de Performance Regression

🔍 CASO: RENDER ENGINE 10X MÁS LENTO

┌─────────────────────────────────────────────────────────────┐
│  EL MISTERIO                                                 │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  REPORTE:                                                   │
│  Usuarios reportan que audio rendering es 10x más lento      │
│  que hace 2 meses.                                           │
│                                                             │
│  DATOS:                                                     │
│  • Benchmark actual: 450ms para render 10s de audio          │
│  • Benchmark histórico: 45ms (10x diferencia)                │
│  • ~400 commits en últimos 2 meses                          │
│  • No hay commits obvios de "performance"                    │
│                                                             │
│  OBJETIVO:                                                  │
│  Encontrar el commit que introdujo la regresión.             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 1: CREAR BENCHMARK SCRIPT                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  test/benchmark_render.sh:                                  │
│  ────────────────────────────────────────────────────────   │
│  #!/bin/bash                                                │
│  # Run render benchmark                                     │
│  time=$(npm run benchmark:render | grep "Duration:" | ...)  │
│                                                             │
│  # Exit 0 if fast (< 100ms), exit 1 if slow (> 100ms)       │
│  if [ "$time" -lt 100 ]; then                               │
│    exit 0                                                   │
│  else                                                       │
│    exit 1                                                   │
│  fi                                                         │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  VERIFICAR SCRIPT:                                          │
│  git checkout main                                          │
│  ./test/benchmark_render.sh                                 │
│  # Exit 1 (slow) ✓                                          │
│                                                             │
│  git checkout v1.8.0  # Tag de 2 meses atrás                │
│  ./test/benchmark_render.sh                                 │
│  # Exit 0 (fast) ✓                                          │
│                                                             │
│  Script funciona correctamente.                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 2: BISECT AUTOMATIZADO                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git bisect start                                           │
│  git bisect bad main                                        │
│  git bisect good v1.8.0                                     │
│                                                             │
│  git bisect run ./test/benchmark_render.sh                  │
│                                                             │
│  OUTPUT (después de ~9 iteraciones):                        │
│  ────────────────────────────────────────────────────────   │
│  xyz789 is the first bad commit                             │
│  commit xyz789                                              │
│  Author: Developer C                                        │
│  Date: 6 weeks ago                                          │
│                                                             │
│      refactor: Simplify audio buffer allocation             │
│                                                             │
│      Removed custom memory pool, using standard allocator.   │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  🎯 COMMIT CULPABLE ENCONTRADO                              │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 3: ANÁLISIS DEL COMMIT                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  git show xyz789                                            │
│                                                             │
│  CAMBIOS:                                                   │
│  ────────────────────────────────────────────────────────   │
│  - AudioBuffer* buffer = memoryPool.allocate(size);         │
│  + AudioBuffer* buffer = new AudioBuffer(size);             │
│                                                             │
│  - memoryPool.deallocate(buffer);                           │
│  + delete buffer;                                           │
│  ────────────────────────────────────────────────────────   │
│                                                             │
│  RAZÓN DEL PROBLEMA:                                        │
│  • Rendering crea/destruye ~10,000 buffers                   │
│  • Memory pool era pre-allocated (fast)                     │
│  • new/delete es heap allocation (slow)                     │
│  • 10,000 × (slow allocation) = 10x slowdown                │
│                                                             │
│  COMMIT MESSAGE ANALYSIS:                                   │
│  "Simplify" sonaba como mejora, pero introdujo regresión.   │
│  No había benchmarks en CI para detectarlo.                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│  PASO 4: FIX Y PREVENCIÓN                                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  FIX INMEDIATO:                                             │
│  git revert xyz789                                          │
│  git commit -m "revert: Restore memory pool allocation      │
│                                                             │
│  This reverts commit xyz789 which caused 10x performance     │
│  regression in audio rendering.                             │
│                                                             │
│  Benchmark results:                                         │
│  - Before revert: 450ms                                     │
│  - After revert: 45ms                                       │
│                                                             │
│  Closes #789"                                               │
│                                                             │
│  PREVENCIÓN FUTURA:                                         │
│  1. Add benchmark to CI pipeline                            │
│  2. Fail CI if render > 100ms                               │
│  3. Require benchmarks for "refactor" PRs                   │
│                                                             │
│  .github/workflows/benchmark.yml:                           │
│  ────────────────────────────────────────────────────────   │
│  - name: Run performance benchmarks                         │
│    run: npm run benchmark                                   │
│  - name: Check performance regression                       │
│    run: |                                                   │
│      if [ "$render_time" -gt 100 ]; then                    │
│        echo "Performance regression detected"               │
│        exit 1                                               │
│      fi                                                     │
│  ────────────────────────────────────────────────────────   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

📊 LECCIONES:
1. Bisect + automated testing = bug finding superpoder
2. "Simplify" refactors pueden introducir regresiones
3. Performance benchmarks deben estar en CI
4. Commit messages deben explicar trade-offs
5. Revert es válido cuando fix forward es complejo

🎯 CONCLUSIONES FINALES

╔═══════════════════════════════════════════════════════════╗
║          MAESTRÍA AVANZADA: PRINCIPIOS FUNDAMENTALES      ║
╚═══════════════════════════════════════════════════════════╝

🧠 FILOSOFÍA CORE

1. HISTORIA ES COMUNICACIÓN
   • Commits son documentación
   • Rebase limpia narrativa
   • Merge preserva context
   • Equilibrio es clave

2. SAFETY FIRST
   • Stash antes de switch context
   • Reflog es red de seguridad
   • Branch protection previene desastres
   • Backups nunca están de más

3. WORKFLOWS > COMANDOS
   • Combinar técnicas estratégicamente
   • Un problema, múltiples herramientas
   • Automatización cuando sea posible
   • Humanos para decisiones, Git para ejecución

4. PREVENCIÓN > RECUPERACIÓN
   • CI/CD detecta problemas temprano
   • Branch protection previene force push
   • Hooks previenen errores comunes
   • Tests automatizados mantienen calidad

5. COLABORACIÓN
   • Historia limpia ayuda al equipo
   • Comunicación sobre operaciones peligrosas
   • Documentación de decisiones complejas
   • Empatía con future developers (incluyéndote)

┌─────────────────────────────────────────────────────────────┐
│  TOOLKIT COMPLETO                                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  🔧 OPERACIONES                                             │
│  ├─ Rebase Interactive → Limpieza de historia               │
│  ├─ Bisect → Arqueología de bugs                            │
│  ├─ Stash → Context switching                               │
│  ├─ Cherry-pick → Transplante selectivo                     │
│  ├─ Reset → Control de timeline                             │
│  └─ Reflog → Recuperación de desastres                      │
│                                                             │
│  🎼 WORKFLOWS                                               │
│  ├─ Feature Refinement → PR preparation                     │
│  ├─ Emergency Hotfix → Production fixes                     │
│  ├─ Bug Archaeology → Bisect + reflog                       │
│  └─ Massive Refactor → Long-lived branches                  │
│                                                             │
│  🛡️ SAFETY NETS                                             │
│  ├─ Branch protection → Prevención                          │
│  ├─ Reflog → Recuperación                                   │
│  ├─ Stash → Backup temporal                                 │
│  ├─ Tags → Milestones                                       │
│  └─ CI/CD → Validación                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

🎓 CAMINO A LA MAESTRÍA

NIVEL 1: CONOCIMIENTO
• Entiendes qué hace cada operación
• Sabes cuándo usar cada herramienta
• Reconoces situaciones comunes

NIVEL 2: PRÁCTICA
• Ejecutas operaciones con confianza
• Combinas técnicas en workflows
• Recuperas de errores

NIVEL 3: MAESTRÍA
• Diseñas workflows custom para problemas nuevos
• Anticipas consecuencias de operaciones
• Enseñas a otros

NIVEL 4: SABIDURÍA
• Sabes cuándo NO usar operaciones avanzadas
• Priorizas simplicidad sobre cleverness
• Git es invisible, código es visible

RECORDATORIO FINAL

┌───────────────────────────────────────────────────────────┐
│                                                           │
│  "Git avanzado no es sobre usar las operaciones más      │
│   complejas. Es sobre conocerlas lo suficiente para      │
│   elegir la herramienta CORRECTA para cada problema."    │
│                                                           │
│  • Rebase no siempre es mejor que merge                  │
│  • Force push tiene casos válidos                         │
│  • Historia compleja es mejor que historia incorrecta    │
│  • Simplicidad > Cleverness                              │
│  • Código > Git tricks                                   │
│                                                           │
│  El objetivo final no es historia perfecta.              │
│  Es código mantenible, equipo productivo, y              │
│  productos que funcionan.                                │
│                                                           │
│  Git es la herramienta. Tu juicio es la maestría.        │
│                                                           │
└───────────────────────────────────────────────────────────┘

Documento versión 1.0 COMPLETO AudioLab Foundation • Version Control • Advanced Workflows Mastery "Git avanzado: El arte de controlar el tiempo y la historia."