git checkout para coding agents: dos modos, cero autónomo
Resumen
git checkout mezcla cambiar de rama y restaurar paths. El contrato autónomo es no usarlo: switch para ramas, restore para archivos. Cero -f/-B/--orphan/--ignore-other-worktrees. Distinto de switch, restore y reset. Git 2.50.1.

Qué resuelve
Esta pieza se queda en la decisión práctica: qué instalar, qué riesgo agrega y cómo aplicarlo sin romper operación.
git checkout hace dos cosas. El man (git-checkout(1); git-scm.com/docs/git-checkout HTTP 200, last-modified 2026-08-31; pie del man local Git 2.50.1.428.g0e8243, 2025-07-22; binario Git 2.50.1 / Apple Git-155): Switch branches or restore working tree files. SYNOPSIS mezcla <branch>, <commit>, -b/-B, --detach, --orphan y <tree-ish> -- <pathspec>. Un solo verbo, dos contratos.
Sin pathspec, actualiza index, working tree y HEAD. Con pathspec, pisa paths del working tree (y a veces el index) sin mover HEAD. El man lo dice en ARGUMENT DISAMBIGUATION: si el argumento es a la vez un <tree-ish> válido y un <pathspec> válido, checkout elige rama. git checkout abc con un archivo abc y una rama abc no restaura el archivo.
Por eso Git 2.23 partió el verbo: switch para ramas, restore para paths. Switch y restore siguen marcados experimental en el man; checkout no. El agente autónomo no usa el verbo dual.
Contrato: no corras git checkout autónomo. Rama = git switch. Path = git restore -- <path>. Inspección de un SHA = worktree, no --detach en el árbol del humano. Cero -f. Cero -B. Cero --orphan. Cero --ignore-other-worktrees. Cero -m/-p headless.
Qué hace (y qué no)
Sin pathspec, Updates files in the working tree to match the version in the index or the specified tree y will also update HEAD to set the specified branch as the current branch. Es el modo rama. Local modifications are kept, so that they can be committed to the <branch> — salvo que el switch perdería edits: entonces aborta.
Con pathspec, Overwrite the contents of the files that match the pathspec. Sin <tree-ish>: pisa working tree desde el index. Con <tree-ish>: pisa index y working tree desde ese tree. HEAD no se mueve. Eso es restore disfrazado, con desambiguación extra.
No es switch. Switch solo cambia de rama. No acepta pathspec. No hay modo “restaura Makefile”.
No es restore. Restore pide -- <pathspec> (o --pathspec-from-file). Default: working tree desde el index. --staged mueve el index. No adivina si abc es rama.
No es reset. Reset mueve HEAD (y puede tirar el árbol). Checkout en modo rama también mueve HEAD, pero el modo path no. Mezclarlos es el bug clásico: checkout --hard no existe; el agente que “limpia” con checkout -f está inventando reset.
Ni branch a pelo. -b Create a new branch named <new-branch>, start it at <start-point>, and check the resulting branch out. Es git branch + checkout. -B es git branch -f + checkout: si la rama ya existe, la resetea. Un agente no resetea refs ajenas.

Lo que el agente sí / no corre
| Quiero | Comando | Trampa |
|---|---|---|
| Ir a una rama | git switch <branch> | No checkout <branch>: si hay un path homónimo, el man elige rama igual, pero el verbo dual se queda |
| Restaurar un path | git restore -- <path> | checkout -- <path> funciona; el agente no lo usa. Sin --, un path que parece rama cambia HEAD |
| Rama nueva | git switch -c <nueva> [<start>] | checkout -b es el mismo gesto. -B resetea la ref si existe |
| Inspeccionar un SHA | worktree propio | checkout <sha> detacha HEAD. Commits huérfanos hasta que crees una ref |
| Volver a la anterior | git switch - | - = @{-1} también en checkout. No es undo de commits |
Prohibido en autónomo:
git checkoutpara ramas o para files. El man: Because checking out a branch is so common,git checkout abctakesabcas a<tree-ish>. Usa--para forzar path. Un agente no desambigua a ciegas.-f/--force. When switching branches, proceed even if the index or the working tree differs from HEAD, and even if there are untracked files in the way. This is used to throw away local changes. Equivale a tirar el trabajo local. En modo path,-fdo not fail upon unmerged entries; instead, unmerged entries are ignored. Silencia un merge a medias.-B <new-branch>. if it already exists, then reset it to<start-point>. Transaccional con el checkout, pero reescribe la ref. No.--detach/checkout <commit>en el árbol del humano. HEAD refers directly to commit b. This is known as being in detached HEAD state. Uncommitahí creaereferenciado solo por HEAD.checkout masterdejae/fpara gc. Recuperas con reflog, no con suerte.--orphan <new-branch>. The first commit made on this new branch will have no parents. El man sugieregit rm -rf .para un árbol distinto. No es “branch limpia”.--ignore-other-worktrees. git checkout refuses when the wanted branch is already checked out or otherwise in use by another worktree. This option makes it check the branch out anyway. Dos checkouts de la misma ref. Usa otro worktree.-m/--mergeheadless. Three-way entre rama actual, working tree y destino. When a merge conflict happens, the index entries for conflicting paths are left unmerged. When switching branches with--merge, staged changes may be lost. El agente no resuelve unmerged a ciegas.-p/--patchautónomo. you can usegit checkout -pto selectively discard edits. Interactivo. Un harness sin TTY se cuelga o tira hunks al azar.--ours/--theirsautónomo. Stage #2 / #3 de unmerged. duringgit rebaseandgit pull --rebase, ours and theirs may appear swapped. El agente no “elige el lado”.--recurse-submodules+-f. Actualiza submódulos y detacha HEAD de cada uno. Con-fpisa mods locales del submodule.--no-overlayautónomo. Default overlay never removes files.--no-overlayfiles that appear in the index and working tree, but not in<tree-ish>are removed. Es un restore destructivo del árbol.
--guess es el default (checkout.guess). Si <branch> no existe en local pero hay exactamente un remote con ese nombre, checkout hace -b <branch> --track <remote>/<branch>. Con dos remotes, checkout.defaultRemote. Un agente no adivina remotes: git fetch + git switch -c explícito.
Receta (60 segundos)
Solo en un worktree propio. El checkout del humano no se toca.
git status -sb # limpio; no MERGE_HEAD / rebase / BISECT
git switch -c feat/foo origin/main
# path sucio que sí pediste tirar:
git restore -- src/app.ts
Inspección de un SHA sin detached HEAD en el árbol compartido:
git fetch origin
git worktree add /tmp/inspect abc1234
# leer, testear; luego:
git worktree remove /tmp/inspect
Si el humano pide checkout y nombra un path:
git restore -- Makefile
# no: git checkout Makefile
Si nombra una rama:
git switch feature
# no: git checkout feature

Detached HEAD no es “ver un commit”
El man dedica una sección entera. HEAD normalmente apunta a refs/heads/<branch>. git checkout v2.0 o git checkout main^^ deja HEAD → commit. Un commit crea e colgando de HEAD. git checkout main suelta e. nothing refers to commit f. Eventually commit f … will be deleted by the routine Git garbage collection process, unless we create a reference.
Salidas documentadas antes de moverte: git switch -c foo, git branch foo, git tag foo. Después de moverte: reflog (git reflog -2 HEAD). Un agente que “mira un tag” con checkout en el worktree del humano puede dejar commits huérfanos y pelear con el editor abierto.
-- corta opciones. git checkout -- hello.c fuerza path aunque exista una rama hello.c. El ejemplo del man: If you have an unfortunate branch that is named hello.c. Ese es el bug que switch/restore eliminan: cada comando tiene un modo.
FAQ
¿Puedo usar checkout -- <path> si siempre pongo --? El man lo documenta. Sigue siendo el verbo dual. Un prompt, un wrapper o un checkout -f colado reabre el otro modo. Restore no tiene modo rama.
¿Switch no es experimental? Sí. El man de switch y restore: THIS COMMAND IS EXPERIMENTAL. En Git 2.50.1 el comportamiento es el de producción desde 2.23. El agente autónomo prefiere el verbo de un solo modo.
¿checkout - para volver? Funciona (@{-1}). git switch - es el mismo atajo sin pathspec. Úsalo.
¿Y git checkout -b en un script? Equivale a switch -c. Si el script es tuyo y el worktree es tuyo, switch -c es más claro. -B sigue prohibido: resetea la rama si existe.
Checklist
- Cero
git checkouten el harness autónomo. - Rama →
git switch/switch -c. Path →git restore -- <path>. - Cero
-f,-B,--orphan,--detachen el árbol del humano,--ignore-other-worktrees,-m,-p. - SHA de inspección → worktree, no detached HEAD compartido.
- Si un commit quedó huérfano,
git reflogantes de gc. - Status limpio (
git status -sb) antes de mover HEAD.
El curso instalar un agente no cubre el working tree. El hub comparativas y decisiones agrupa estas fichas. Checkout no es el atajo: es el verbo que mezcla dos operaciones y un agente no desambigua.
Lecturas relacionadas
Sigue explorando Coding Agents y otras piezas para builders.

git checkout-index para coding agents: index al disco, no checkout

git mktree para coding agents: tree desde ls-tree, no desde el index

git commit-tree para coding agents: commit sin mover HEAD
