Bucle de depuración infinita: que Cursor CLI arregle hasta que pasen los tests
Escribe un script de shell que haga que cursor agent arregle el código automáticamente, ejecute los tests y si fallan deje que la IA arregle de nuevo — repitiendo hasta que pasen todos los tests. No hace falta quedarse pulsando Y/N. Delega el bucle a la IA y haz otra cosa — vuelve cuando la terminal muestre "tests passed."
Concepto central
while tests don't pass:
run tests → collect error output
feed error output to cursor agent
cursor agent fixes the code
run tests again
Es un bucle "ejecutar tests → fallar → decir a la IA que arregle → repetir" hasta que pasen. Simple y directo, pero efectivo.
Paso 1: Comprobar requisitos
cursorestá instalado y con sesión iniciada (cursor --versionpara comprobar)- El proyecto tiene un comando de tests que se ejecuta en la terminal, por ejemplo:
npm testpytestgo test ./...cargo test
- Los tests devuelven código de salida distinto de cero al fallar (casi todos los frameworks lo hacen por defecto)
Paso 2: El script más simple
Crea debug-loop.sh:
#!/bin/bash
MAX_LOOPS=10 # max iterations to prevent truly infinite loops
TEST_CMD="npm test" # replace with your test command
loop=0
while [ $loop -lt $MAX_LOOPS ]; do
echo ""
echo "=== Loop $((loop + 1)) ==="
# run tests and capture stdout + stderr
TEST_OUTPUT=$(eval "$TEST_CMD" 2>&1)
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Tests passed! Completed in $((loop + 1)) loop(s)."
exit 0
fi
echo "❌ Tests failed, letting the AI fix..."
echo "$TEST_OUTPUT" | tail -30 # print the last 30 lines for your reference
# feed the error output to cursor agent
cursor agent "Tests failed with the following errors. Please fix the code to make the tests pass:
$TEST_OUTPUT" --model gpt-codex-5.3-high --no-interactive
loop=$((loop + 1))
done
echo "⚠️ Reached max loops ($MAX_LOOPS). Stopping. Please investigate manually."
exit 1Paso 3: Ejecutar el script
chmod +x debug-loop.sh
./debug-loop.shAhora puedes ir a por un café, responder mensajes y volver cuando veas ✅ Tests passed! en la terminal. Si llega a MAX_LOOPS sin pasar, toca intervención humana.
Paso 4: Personalizar para tu proyecto
Cambia el comando de tests (línea 4):
TEST_CMD="pytest -x" # Python, -x stops on first failure
TEST_CMD="go test ./..." # Go
TEST_CMD="cargo test" # Rust
TEST_CMD="./vendor/bin/phpunit" # PHPAjusta el máximo de iteraciones:
MAX_LOOPS=5 # conservative, stop early if not improving
MAX_LOOPS=20 # more complex problems get more chancesDa más contexto a la IA (dentro del comando cursor agent):
cursor agent "Tests failed. Errors below.
The test framework is Jest and the language is TypeScript.
Do not modify test files — only change files under src/.
Error output:
$TEST_OUTPUT" --model gpt-codex-5.3-high --no-interactiveVersión mejorada: guardar logs por iteración
#!/bin/bash
MAX_LOOPS=10
TEST_CMD="npm test"
LOG_DIR="debug-logs"
mkdir -p $LOG_DIR
loop=0
while [ $loop -lt $MAX_LOOPS ]; do
echo ""
echo "=== Loop $((loop + 1)) ==="
LOG_FILE="$LOG_DIR/loop-$((loop + 1)).log"
TEST_OUTPUT=$(eval "$TEST_CMD" 2>&1 | tee "$LOG_FILE")
EXIT_CODE=${PIPESTATUS[0]}
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Tests passed! Completed in $((loop + 1)) loop(s)."
exit 0
fi
echo "❌ Failed. Log saved to $LOG_FILE"
cursor agent "Tests failed with the following errors. Please fix the code to make the tests pass:
$TEST_OUTPUT" --model gpt-codex-5.3-high --no-interactive
loop=$((loop + 1))
done
echo "⚠️ Reached max loops. Stopping. Check the logs in $LOG_DIR/."
exit 1Útil para revisar "qué falló en qué iteración" después.
Consideraciones de seguridad
| Riesgo | Cómo mitigar |
|---|---|
| La IA rompe más archivos | git commit antes para guardar estado, git checkout . para revertir si hace falta |
| Demasiadas iteraciones gastan cuota | Pon un MAX_LOOPS razonable (5–15 recomendado) |
| La IA modifica archivos de test | Di explícitamente en el prompt "do not modify test files" |
| Fallos distintos en cada iteración | Guarda logs (versión mejorada) para analizar después |
Resumen
- Estructura del script: ejecutar tests → fallar → pasar a la IA → repetir hasta pasar o límite
- Parámetros clave:
TEST_CMD(comando de tests),MAX_LOOPS(máximo de iteraciones) - Sé concreto en el prompt: indica el lenguaje, restringe qué directorios modificar, no tocar tests
git commitantes — fácil de revertir si algo sale mal y más tranquilidad
Junto con Worktree: ejecuta un debug loop en ramas distintas a la vez. Ver 06-cursor-cli-with-worktree.