Bucle de Claude Code: la skill loop-guard que impide que un agente se repita

Dmitriy Solodukha, desarrollador de Caprock · Publicado el

Probado el en Claude Code y Codex

Un bucle de Claude Code repite un paso fallido. La skill loop-guard lo para, identifica la suposición errónea y cambia de enfoque. Gratis.

Cuando Claude Code se atasca en un bucle (el mismo comando falla, el mismo error aparece tras cada “solución”, un archivo se modifica y se revierte), la skill loop-guard hace que el agente se detenga, enumere lo que intentó, identifique la suposición común a todos los intentos y pruebe algo que ponga a prueba una suposición diferente o te pregunte. Es un archivo SKILL.md para Claude Code, Codex, OpenCode y Cursor, gratis bajo Apache-2.0.

Instala la skill loop-guard

Un comando por agente. La skill es un único SKILL.md; no se ejecuta nada al instalarla.

Las nueve skills como plugin. Escribe esto dentro de Claude Code:

O solo esta skill, desde la carpeta de tu proyecto en una terminal:

Añade -g para instalarla en todos los proyectos.

Prompts que usan la skill loop-guard

El agente elige la skill cuando tus palabras coinciden con su descripción; nombrarla lo asegura. Haz clic en un prompt para copiarlo.

Cómo interrumpe un bucle de Claude Code la skill loop-guard

La skill le da al agente un criterio para detectar un bucle y un procedimiento para salir de él:

  • La prueba. El mismo comando con la misma entrada falló dos veces; el mismo error volvió tras una segunda corrección; se está cambiando y revirtiendo un bloque; se alternan dos correcciones; una consulta periódica no muestra cambios. Ejecutar algo dos veces está bien si algo cambió entre ambas ejecuciones.
  • Detente y luego observa. Nada de “un intento más”. El agente lee el último error completo y enumera cada intento con su resultado exacto.
  • El informe de bucle. Lo que se repite, los intentos, la suposición que era incorrecta y el siguiente paso. La suposición incorrecta es la línea que importa: todos los intentos de un bucle comparten una creencia.
  • Un verdadero cambio de enfoque, en este orden: leer el código en lugar de ejecutarlo, comprobar el entorno, reducir el fallo, volver al último estado correcto, cuestionar la prueba o la tarea. Un intento con el nuevo enfoque y después evaluarlo.
  • Preguntar cuando ya no quede ningún enfoque, o cuando las únicas “soluciones” restantes ocultarían el problema.

Qué ejecutamos y qué hicieron los agentes

Cada skill se ejecutó el 29 de noviembre de 2026 en un repositorio desechable creado para ella, con la skill instalada como skill del proyecto. Un pequeño repositorio de Python donde tests/test_slug.py colocaba tests/ antes de src/ en sys.path, por lo que importaba una copia desactualizada del módulo (tests/textkit/slug.py) y ninguna modificación de src/textkit/slug.py cambiaba nada. Un NOTES.md, escrito a mano para la prueba, enumeraba cuatro intentos de un “agente anterior”, todos con el mismo AssertionError como resultado.

Claude Code (claude -p --model sonnet)

My agent is stuck in a loop: it keeps editing src/textkit/slug.py and rerunning python3 tests/test_slug.py, same error every time (see NOTES.md). Break the loop and fix it. Say which skill you used, if any. Answer in English.

Dos ejecuciones. Ambas invocaron loop-guard, llamaron a loop_alerts de Caprock, mostraron qué archivo importaba realmente la prueba y corrigieron el orden de sys.path en la prueba, sin cambiar la aserción ni src/textkit/slug.py. La prueba pasó. Ambas preguntaron antes de eliminar la carpeta obsoleta tests/textkit/, ya que git la tiene bajo control de versiones. El prompt de la primera ejecución no terminaba con "Answer in English." El informe de bucle de la segunda ejecución:

Loop detected: editing src/textkit/slug.py and rerunning python3 tests/test_slug.py, same AssertionError
Attempts (1-4 are from NOTES.md):
  1. Ran the test -> 'hello_world' != 'hello-world'
  2. Edited the regex in src/textkit/slug.py -> same error
  3. Rewrote slugify with str.replace -> same error
  4. Reverted step 3 -> same error
Assumption that was wrong: the test imports src/textkit/slug.py
Next (done): fixed the import path in the test

Codex (0.163.0, codex exec -s workspace-write, el 30 de noviembre de 2026)

The slug test still fails and I've tried fixing src/textkit/slug.py three times. Fix it.

Encontró y leyó .agents/skills/loop-guard/SKILL.md, llamó a loop_alerts de Caprock y luego corrigió tests/test_slug.py para cargar src/ primero, sin cambiar la aserción; la prueba pasó y git diff --check estaba limpio. Su informe empezó con la línea del bucle, pero omitió los intentos y la línea sobre la suposición errónea del formato de la skill (enlace en texto plano):

Loop detected: three source edits failed because the test imported the old `tests/textkit/slug.py` copy.
Fixed tests/test_slug.py to load `src` first. The assertion is unchanged.
`python3 tests/test_slug.py` passes, and `git diff --check` is clean.

Agentes en los que se probó

  • Claude Code: probado el 29 de noviembre de 2026 con claude -p --model sonnet, con la skill instalada como skill de proyecto en .claude/skills/.
  • Codex: probada el 30 de noviembre de 2026 con Codex 0.163.0 (codex exec), la skill en .agents/skills/. Una ejecución anterior con Codex ese mismo día no tenía ninguna skill instalada y no se cuenta.
  • OpenCode y Cursor: sin probar. La skill consiste en instrucciones en el formato abierto Agent Skills, pero ninguna ejecución en ninguno de los dos la ha verificado.

Límites

  • La skill trabaja con lo que el agente puede ver. Un bucle que abarca varias sesiones, o uno que el agente no detecta, necesita que digas “you're in a loop”.
  • Sin Caprock, reconstruye los intentos a partir de la propia sesión; una conversación compactada puede haber perdido los primeros.
  • No limita los reintentos ni termina un proceso. Una skill no detiene a un agente que ignora sus instrucciones.
  • Codex escribió un informe de bucle de una línea en lugar de usar el formato completo, en su única ejecución.

Con Caprock y sin él

Cuando el servidor MCP de Caprock está conectado, la skill llama a loop_alerts: sesiones en ejecución que repiten la misma llamada a herramienta, con la herramienta, el recuento, la entrada repetida y el costo de las repeticiones. Sin él, el agente enumera sus intentos a partir de la conversación. Caprock es la app gratis y de código abierto que registra cada sesión de agente de programación en tu computadora; la skill no la necesita.

Obtener Caprock →

El SKILL.md completo

El archivo tal como está en dspv/skills en la revisión dfce799. Para instalarlo manualmente, guárdalo como .claude/skills/loop-guard/SKILL.md para Claude Code o .agents/skills/loop-guard/SKILL.md para Codex en tu proyecto.

skills/loop-guard/SKILL.md
---
name: loop-guard
description: Notice when a coding agent is stuck in a loop (running the same failing command again, retrying the same tool call, editing and reverting the same file, hitting the same error after every "fix", or never stopping) and break out of it - stop, state what was tried, then change approach or ask the user. Use when someone says "claude code loop", "the agent keeps doing the same thing", "stuck in a loop", "it keeps retrying", "same error again", "it went back and forth on this file", "why won't it stop", or when you see yourself repeating a step.
license: Apache-2.0
---

# Loop guard

A loop is repeating a step and expecting a different result. It wastes time and tokens, and it
often ends with the agent "fixing" the problem by hiding it. This skill makes you notice the loop,
stop, say plainly what happened, and either try something genuinely different or ask the user.

## When this applies

Check yourself for a loop before every retry, and run the full procedure below as soon as any of
these is true:

- The same command or tool call, with the same input, has failed twice and you are about to run it
  a third time.
- The same error message (same file, line, or test name) comes back after your second fix.
- You are editing a hunk you already changed and reverted, or flipping between two versions of it.
- Two fixes alternate: fixing A breaks B, fixing B breaks A again.
- You are polling or waiting (a build, a server, a CI job) and nothing in the output has changed
  between checks.
- The user says you are looping, stuck, going in circles, or asks why you will not stop.

Running something twice is fine when something changed in between (a file, a setting, an input).
It is a loop when nothing that could change the result has changed.

## Procedure

### 1. Stop

Do not run the next attempt. No "one more try" with a small tweak to the same idea.

### 2. Look at the evidence, not your memory of it

- If the Caprock MCP tools are available (server `caprock`), call `loop_alerts` (it takes no
  arguments). It lists running sessions that repeat the same tool call, with the tool, how many
  times, the repeated input and what the repeats cost. Use it to confirm the loop and its size.
  Caprock (https://caprock.dev, free, open source, runs locally) provides this tool.
- Otherwise, scroll back through this session: list each attempt in order, with the exact command
  or edit and the exact result.
- Read the last error in full, top to bottom. Loops often come from reading only the first line,
  or the last line, of an error that says something else in the middle.

### 3. Write the loop report

Show the user this, before doing anything else:

```text
Loop detected: <what repeats, in one line>
Attempts:
  1. <what I did> -> <what happened>
  2. <what I did> -> <what happened>
  3. ...
Assumption that was wrong: <the belief every attempt shared>
Next: <the different approach>, or a question for you
```

The line "Assumption that was wrong" matters most. Every attempt in a loop shares one belief
(the bug is in this function, the dependency is installed, the test is right, the port is free).
Name it. If you cannot name it, that is the first thing to find out.

### 4. Change approach for real

A new approach tests a different assumption. Changing a flag, a timeout, a retry count or the
wording of the same edit is not a new approach. Pick one of these, in roughly this order:

1. **Read instead of run.** Open the source of the failing function, the config being loaded, the
   test's assertion, or the tool's `--help`. Many loops end once you read what the code really does.
2. **Check the environment.** Which version, which binary on PATH, which branch, which working
   directory, which env vars. Print them; do not assume.
3. **Make it smaller.** Reproduce the failure with the least code or the single test. A small
   failing case shows what the big one hides.
4. **Go back to the last good state.** If edits piled up, compare with the last commit (`git diff`,
   `git stash`) and reapply one change at a time.
5. **Question the target.** Maybe the test is wrong, the requirement is ambiguous, or the task
   needs something you do not have (a credential, a running service, a decision).

Allow yourself one attempt with the new approach, then judge it: did it change what you know? If
yes, continue. If no, go to step 5.

### 5. Ask the user

Ask when any of these is true:

- You have no approach left that tests a different assumption.
- The way forward needs a decision, a credential, access, or a change of scope.
- The only remaining "fixes" would hide the problem (see the list below).

Ask one specific question and include the loop report, so the user does not have to reconstruct
what happened. Then wait. Do not keep trying in the background.

## Never break a loop by hiding it

These end the loop by making the error disappear, not by fixing it. Do not do them unless the user
asks for that exact thing:

- Skipping, deleting or weakening a test or an assertion so it passes.
- Catching and ignoring the exception, or adding `|| true` to the failing command.
- Bypassing hooks or checks (`--no-verify`, disabling a linter rule, force-pushing).
- Hard-coding the expected output.
- Widening the task: rewriting a module to dodge one error.

## Waiting without progress

For a build, deploy or CI job you are waiting on:

- Before polling again, look for a sign of progress (new log lines, a changed status).
- If nothing changed over several checks, stop polling and report the state you saw and when you
  last saw it change. Ask whether to keep waiting, cancel, or look at the job's logs.

## Output

When you stop a loop, your reply to the user starts with the loop report from step 3, even when
the new approach then fixes the problem, and ends with either the result or one question. Keep it
short: what repeated, what you tried, what was wrong, what is next.

Preguntas sobre la skill loop-guard

¿Qué es un bucle de Claude Code?
El agente repite un paso que ya falló sin que haya cambiado nada que pueda cambiar el resultado: el mismo comando, el mismo error después de cada corrección o un archivo que se edita y cuyos cambios se revierten. Consume tiempo y tokens y a menudo termina con el error oculto en vez de corregido.
¿Cómo detengo un bucle de Claude Code con la skill loop-guard?
Instala la skill y di “you're in a loop, use loop-guard”. El agente se detiene, escribe un informe de bucle que identifica la suposición errónea y luego prueba un enfoque diferente o te hace una pregunta.
¿Hará loop-guard que una prueba fallida pase omitiéndola?
No. La skill enumera omitir o debilitar una prueba, ignorar una excepción, `|| true`, `--no-verify` y las salidas codificadas de forma fija como maneras de ocultar un bucle, e indica al agente que no las use a menos que pidas exactamente eso.
¿Funciona en Codex la skill de protección contra bucles?
Sí. Codex 0.163.0 lo leyó en una prueba del 30 de noviembre de 2026, identificó el bucle y su causa, y corrigió la ruta de importación sin tocar la aserción.

Fuentes

La app en sí está en inglés.