Guía9 min

git init para coding agents: repo nuevo, no parche de uno existente

Resumen

git init crea un .git vacío (rama inicial sin commits). Un agente lo usa solo en un directorio nuevo; no --bare, no --shared, no anidar dentro de otro repo. Si el remoto ya existe, clone. Git 2.50.1.

GitHub
Un directorio nuevo recibe un .git vacío; un repo existente no se reinicializa

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 init no repara un checkout. El man (git-init(1), Git 2.50.1 / Apple Git-155; git-scm.com/docs/git-init HTTP 200, last-modified 2026-08-31): crea un repositorio vacío — un .git con objects, refs/heads, refs/tags y plantillas. La rama inicial no tiene commits. HEAD, index y working tree de otro repo no se tocan: esto es el repo.

GitHub Docs (Creating a new repository, HTTP 200 2026-09-04): el remoto se crea en la cuenta u org con permisos (New repository o gh repo create). Nombre ≤ 100 caracteres (A–Z a–z 0–9 . - _). Si vas a importar un Git existente, no pre-pobles README / .gitignore / license: “you may introduce a merge conflict”. Contrato: init local en un dir nuevo; el remoto lo crea el humano; si el URL ya existe, clone.

Vacío no es “sin archivos”

Si pasas <directory> y no existe, Git lo crea. Si el dir ya tiene archivos sin .git, git init mete el .git y deja esos archivos untracked. Verificado 2026-09-04: echo hi > already/file.txt && git init already → exit 0, .git presente, el archivo sigue fuera del index.

Correr git init dentro de un repo existente es “safe” según el man: will not overwrite things that are already there. El motivo oficial de re-correr: recoger templates nuevos, o mover el store con --separate-git-dir. Un agente no “arregla” un clone así. Verificado: segundo git init imprime Reinitialized existing Git repository, exit 0.

-b main nombra la rama inicial; el directorio no era un repo

Lo que el agente sí / no corre

QuieroComandoTrampa
Repo local nuevogit init -b main <dir>git init en un clone que “no commitea”
Código que ya está en GitHubcloneinit + remote inventado
Sesión extraworktreeinit en un subdir del mismo tree
Primer commitadd paths + commitEl ejemplo del man con git add .

Prohibido en autónomo:

  • --bare. El man: si GIT_DIR no está, el cwd es $GIT_DIR. No hay working tree. Verificado: git init --bare bare.git crea el store en bare.git/, no bare.git/.git. Un agente necesita disco para editar.
  • --shared / --shared=all. Setea core.sharedRepository y, por default, receive.denyNonFastForwards. El man: afloja umask para que el grupo pushee. Un agente no comparte $GIT_DIR entre uids.
  • --separate-git-dir. En vez de .git/, escribe un archivo-texto con la ruta del store. En una reinit, the repository will be moved. No muevas el objeto store del humano.
  • --object-format=sha256. El man: no interoperability con SHA-1. Default sha1. Verificado: extensions.objectformat=sha256. Un remoto GitHub clásico no habla SHA-256.
  • --template a un path que el humano no pidió. Copia al $GIT_DIR todo lo que no empiece por punto. Hooks de muestra vienen deshabilitados (sufijo .sample); no los actives.
  • git init anidado (repo/src/.git dentro de repo/.git). Verificado 2026-09-04: Git lo permite y crea el segundo store. El padre deja de ver esos paths como parte del proyecto. Si el remoto ya existe: clone. Si hace falta otra sesión: worktree.
  • Crear el repo en GitHub (gh repo create, UI Create repository) sin que el humano pida owner, visibilidad y org. GitHub Docs: owners pueden restringir creación en la org.
  • El git add . del EXAMPLES del man. Eso es onboarding humano. Un agente nombra paths (add).

-b / --initial-branch fija el nombre. Sin flag, el man (2026-04-19 / Git 2.54.0): fallback currently master, but this will change to main when Git 3.0 is released; override init.defaultBranch. Verificado en esta máquina (Apple Git-155, init.defaultBranch global/system unset): git init sin -b dejó refs/heads/main. No asumas master ni main: pasa -b main.

Receta (60 segundos)

Solo si no hay clone del mismo proyecto y el dir no es un repo:

git init -b main /path/al/proyecto
cd /path/al/proyecto
git status -sb

Luego paths explícitos, no el glob del man:

git add README.md src/index.ts
git commit -m "feat: bootstrap"

Remoto: el humano crea el repo vacío en GitHub (sin README si vas a pushear historia local) y te pasa el URL. Entonces remote add + push de una rama distinta de main.

Si el URL ya existe: para. Clone.

--bare y un .git anidado dejan al agente sin árbol o con dos stores

Init vs clone vs GitHub “New repository”

PreguntaComandoNo
¿Hay URL?cloneinit + copiar archivos a mano
¿Dir nuevo, cero historia?git init -b main <dir>init dentro del clone
¿Publicar en GitHub?Humano: Creating a new repository / gh repo createAgente elige visibilidad/org
¿Otra sesión?worktreeSegundo init

--quiet solo calla el stdout de éxito. No oculta errores.

GIT_DIR / GIT_OBJECT_DIRECTORY: el man redirige el store. Un agente no las setea para “esconder” un .git.

Checklist

  • ¿El remoto ya existe? → clone, no init.
  • Destino = directorio nuevo (o vacío de Git). Cero init anidado.
  • git init -b main <dir>. Cero --bare, --shared, --separate-git-dir, sha256.
  • Primer commit = add paths, no git add ..
  • Remoto GitHub = el humano. Cero gh repo create autónomo.
  • Trabajo siguiente en rama ≠ default. switch / worktree + PR.

FAQ

¿git init en el clone “para resetear Git”? El man reinit no borra objects/refs. No es reset ni restore.

¿El man dice git add .? EXAMPLES, onboarding humano. El contrato de agentes es paths explícitos.

¿--bare para “servidor local”? El cwd es el store. Sin working tree no hay agente que edite.

¿Puedo init y luego remote add origin de un repo que ya tiene commits? Sí técnicamente; es un repo distinto con historia vacía. El primer push a un remoto con README pre-poblado choca. GitHub Docs: no pre-pobles si vas a importar.

El curso instalar un agente cubre el loop local. Hub: comparativas y decisiones. Init no es clone: crea un store vacío; no copia un remoto.

Verificado 2026-09-04 contra git-init(1) (Git 2.50.1 / Apple Git-155; git-scm.com/docs/git-init HTTP 200, last-modified 2026-08-31) y GitHub Docs “Creating a new repository” (HTTP 200). En esta máquina: reinit exit 0 y no pisa objects; --bare sin .git hijo; init anidado crea segundo store; sin -brefs/heads/main (Apple); --object-format=sha256 setea extensions.objectformat.