Loop no Claude Code: a skill loop-guard que interrompe agentes que se repetem
Dmitriy Solodukha, desenvolvedor do Caprock · Publicado em
Testado em no Claude Code e no Codex
Um loop no Claude Code repete o mesmo passo que falha. A skill loop-guard o interrompe, aponta a suposição errada e muda a abordagem. Gratuita.
Quando o Claude Code está travado em um loop (o mesmo comando falhando, o mesmo erro após cada “correção”, um arquivo editado e revertido), a skill loop-guard faz o agente parar, listar o que tentou, identificar a suposição comum a todas as tentativas e tentar algo que teste uma suposição diferente ou perguntar a você. É um arquivo SKILL.md para Claude Code, Codex, OpenCode e Cursor, gratuito sob Apache-2.0.
Instale a skill loop-guard
Um comando por agente. A skill é um único SKILL.md; nada é executado na instalação.
Todas as nove skills como plugin. Digite isto dentro do Claude Code:
Ou apenas esta skill, em um terminal na pasta do seu projeto:
Adicione -g para instalar em todos os projetos.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos. Ainda não testada com OpenCode: a skill contém apenas instruções no formato aberto, mas nenhuma execução com OpenCode a verificou.
Na pasta do seu projeto, em um terminal:
Adicione -g para instalar em todos os projetos. Ainda não testada com Cursor: a skill contém apenas instruções no formato aberto, mas nenhuma execução com Cursor a verificou.
Prompts que usam a skill loop-guard
O agente escolhe a skill quando suas palavras correspondem à descrição dela; citar seu nome garante isso. Clique em um prompt para copiá-lo.
Como a skill loop-guard interrompe um loop do Claude Code
A skill dá ao agente um critério para identificar um loop e um procedimento para sair dele:
- O critério. O mesmo comando com a mesma entrada falhou duas vezes; o mesmo erro voltou após uma segunda correção; um trecho está sendo alterado e revertido; duas correções se alternam; uma consulta não mostra mudança. Executar algo duas vezes não é problema quando algo mudou entre as execuções.
- Pare e depois examine. Sem “mais uma tentativa”. O agente lê o último erro na íntegra e lista cada tentativa com seu resultado exato.
- O relatório do loop. O que se repete, as tentativas, a suposição que estava errada e o próximo passo. A suposição errada é a linha que importa: cada tentativa em um loop compartilha uma crença.
- Uma mudança real de abordagem, nesta ordem: leia o código em vez de executá-lo, confira o ambiente, reduza a falha a um caso menor, volte ao último estado funcional, questione o teste ou a tarefa. Uma tentativa com a nova abordagem, depois avalie.
- Peça quando não resta nenhuma abordagem ou quando as únicas “correções” restantes esconderiam o problema.
O que executamos e o que os agentes fizeram
Cada skill foi executada em 29 de novembro de 2026 em um repositório descartável criado para ela, com a skill instalada como skill de projeto. Um pequeno repositório Python em que tests/test_slug.py colocava tests/ antes de src/ em sys.path, então importava uma cópia desatualizada do módulo (tests/textkit/slug.py) e cada edição em src/textkit/slug.py não mudava nada. Um NOTES.md, escrito à mão para o teste, listava quatro tentativas de um “agente anterior”, todas terminando no mesmo AssertionError.
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.
Duas execuções. Ambas invocaram loop-guard, chamaram loop_alerts do Caprock, exibiram qual arquivo o teste realmente importava e corrigiram a ordem de sys.path no teste, sem alterar a asserção nem src/textkit/slug.py. O teste passou. Ambas perguntaram antes de excluir a pasta tests/textkit/ desatualizada, já que o git a rastreia. O prompt da primeira execução não terminava com “Answer in English.” O relatório de loop da segunda execução:
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, em 30 de novembro de 2026)
The slug test still fails and I've tried fixing src/textkit/slug.py three times. Fix it.
Encontrou e leu .agents/skills/loop-guard/SKILL.md, chamou loop_alerts do Caprock e então corrigiu tests/test_slug.py para carregar src/ primeiro, sem alterar a asserção; o teste passou e git diff --check estava limpo. O relatório começou com a linha do loop, mas omitiu as tentativas e a linha da suposição errada do formato da skill (link exibido como texto simples):
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 em que foi testada
- Claude Code: testado em 29 de novembro de 2026 com
claude -p --model sonnet, com a skill instalada como skill de projeto em.claude/skills/. - Codex: testado em 30 de novembro de 2026 com Codex 0.163.0 (
codex exec), a skill em.agents/skills/. Uma execução anterior do Codex no mesmo dia não tinha a skill instalada e não é contabilizada. - OpenCode e Cursor: não testado. A skill contém instruções simples no formato aberto Agent Skills, mas nenhuma execução em qualquer um dos dois a verificou.
Limites
- A skill trabalha com o que o agente consegue ver. Um loop que atravessa sessões, ou que o agente não percebe, exige que você diga “you're in a loop”.
- Sem Caprock, ela reconstrói as tentativas a partir da própria sessão; uma conversa compactada pode ter perdido as primeiras.
- Ela não limita as tentativas nem encerra um processo. Um agente que ignora suas instruções não é interrompido por uma skill.
- O Codex escreveu um relatório de loop de uma linha, em vez do formato completo, na sua única execução.
Com e sem Caprock
Quando o servidor MCP do Caprock está conectado, a skill chama loop_alerts: sessões em execução que repetem a mesma chamada de ferramenta, com a ferramenta, a contagem, a entrada repetida e o custo das repetições. Sem ele, o agente lista suas tentativas a partir da conversa. Caprock é o app gratuito e open source que registra cada sessão de agente de programação no seu computador; a skill não precisa dele.
O SKILL.md completo
O arquivo como está em dspv/skills na revisão dfce799. Para instalá-lo manualmente, salve como .claude/skills/loop-guard/SKILL.md para Claude Code ou .agents/skills/loop-guard/SKILL.md para Codex, no seu projeto.
--- 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.
Perguntas sobre a skill loop-guard
- O que é um loop do Claude Code?
- O agente repete uma etapa que já falhou, sem mudar nada que possa alterar o resultado: o mesmo comando, o mesmo erro após cada correção ou um arquivo editado e revertido. Isso custa tempo e tokens e muitas vezes termina com o erro escondido em vez de corrigido.
- Como interrompo um loop do Claude Code com a skill loop-guard?
- Instale a skill e diga “you're in a loop, use loop-guard”. O agente para, escreve um relatório do loop identificando a suposição errada e tenta uma abordagem diferente ou faz uma pergunta a você.
- loop-guard vai fazer um teste com falha passar pulando o teste?
- Não. A skill lista pular ou enfraquecer um teste, ignorar uma exceção, `|| true`, `--no-verify` e saída fixa no código como formas de esconder um loop e orienta o agente a não usá-las a menos que você peça exatamente isso.
- A skill loop-guard funciona no Codex?
- Sim. O Codex 0.163.0 a leu em um teste em 30 de novembro de 2026, identificou o loop e sua causa e corrigiu o caminho de importação sem tocar na asserção.