Claude Code 루프: 에이전트의 반복을 멈추는 loop-guard 스킬

Dmitriy Solodukha, Caprock 개발자 · 게시일

Claude Code와 Codex에서 테스트

Claude Code 루프는 실패한 같은 단계를 계속 반복하는 현상입니다. loop-guard 스킬은 루프를 멈추고 잘못된 가정을 짚어 접근 방식을 바꿉니다. 무료입니다.

Claude Code가 루프에 빠지면(같은 명령이 실패하거나, “수정”할 때마다 같은 오류가 발생하거나, 같은 파일을 수정하고 되돌리는 경우), loop-guard 스킬은 에이전트를 멈추고 시도한 내용을 나열하게 합니다. 모든 시도에 공통된 가정을 밝히고, 다른 가정을 검증하는 시도를 하거나 사용자에게 질문하게 합니다. Claude Code, Codex, OpenCode, Cursor에서 사용하는 하나의 SKILL.md 파일이며, Apache-2.0 라이선스로 무료 제공됩니다.

loop-guard 스킬 설치

에이전트마다 명령어 하나로 설치합니다. 스킬은 SKILL.md 파일 하나이며, 설치 시 실행되는 것은 없습니다.

스킬 아홉 가지 전체를 플러그인으로 설치합니다. Claude Code 안에서 다음을 입력합니다:

이 스킬만 설치하려면 터미널에서 프로젝트 폴더로 이동한 뒤 다음을 실행합니다:

추가 옵션: -g 모든 프로젝트에 설치하려면 앞의 옵션을 추가합니다.

loop-guard 스킬을 사용하는 프롬프트

요청이 스킬 설명과 일치하면 에이전트가 해당 스킬을 선택합니다. 이름을 명시하면 확실하게 선택할 수 있습니다. 프롬프트를 클릭하면 복사됩니다.

loop-guard 스킬의 Claude Code 루프 중단 방식

이 스킬은 에이전트에 루프 판별 기준과 루프를 벗어나는 절차를 제공합니다.

  • 테스트 같은 명령이 같은 입력으로 두 번 실패하거나, 두 번째 수정 후에도 같은 오류가 돌아오거나, 코드 블록을 수정했다가 되돌리거나, 두 수정안을 번갈아 적용하거나, 폴링 결과에 변화가 없는 경우입니다. 그사이에 변화가 있었다면 같은 것을 두 번 실행해도 괜찮습니다.
  • 중단 후 확인 “한 번만 더 시도”하지 않습니다. 에이전트는 마지막 오류를 끝까지 읽고 각 시도와 정확한 결과를 나열합니다.
  • 루프 보고서 반복되는 내용, 시도한 방법, 틀린 가정, 다음 단계입니다. 틀린 가정이 핵심입니다. 루프 안의 모든 시도는 하나의 믿음을 공유합니다.
  • 실질적인 접근 방식 전환: 실행하는 대신 코드 읽기, 환경 확인, 실패 재현 범위 축소, 마지막 정상 상태로 복귀, 테스트나 작업 자체 검토 순으로 진행합니다. 새 접근법으로 한 번 시도한 뒤 평가합니다.
  • 더 시도할 방법이 없거나 남은 “수정” 방법이 문제를 감추기만 할 때 질문.

실행한 내용과 에이전트의 수행 결과

각 스킬은 2026년 11월 29일에 해당 스킬용으로 만든 임시 저장소에서 프로젝트 스킬로 설치해 실행했습니다. 작은 Python 저장소에서 tests/test_slug.py가 sys.path의 src/보다 tests/를 앞에 놓아, 오래된 모듈 사본(tests/textkit/slug.py)을 가져왔고 src/textkit/slug.py를 아무리 수정해도 바뀌는 것이 없었습니다. 테스트를 위해 직접 작성한 NOTES.md에는 “이전 에이전트”의 시도 네 번이 기록되어 있었으며, 매번 같은 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.

두 번 실행했습니다. 둘 다 loop-guard를 호출하고 Caprock의 loop_alerts를 호출했으며, 테스트가 실제로 가져온 파일을 출력하고 어설션이나 src/textkit/slug.py를 바꾸지 않은 채 테스트의 sys.path 순서를 수정했습니다. 테스트는 통과했습니다. 둘 다 Git이 추적하는 오래된 tests/textkit/ 폴더를 삭제하기 전에 물었습니다. 첫 실행의 프롬프트는 "Answer in English."로 끝나지 않았습니다. 두 번째 실행의 루프 보고서:

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, 2026년 11월 30일)

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

.agents/skills/loop-guard/SKILL.md를 찾아 읽고 Caprock의 loop_alerts를 호출한 다음, 어설션은 그대로 두고 src/를 먼저 로드하도록 tests/test_slug.py를 수정했습니다. 테스트가 통과했고 git diff --check에도 문제가 없었습니다. 보고서는 루프에 관한 줄로 시작했지만, 스킬 형식의 시도 내역과 잘못된 가정에 관한 줄은 빠졌습니다(링크는 일반 텍스트로 표시):

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.

테스트한 에이전트

  • Claude Code: .claude/skills/에 프로젝트 스킬로 설치한 상태에서 2026년 11월 29일에 claude -p --model sonnet으로 테스트했습니다.
  • Codex: 2026년 11월 30일에 Codex 0.163.0(codex exec)으로 테스트했으며 스킬은 .agents/skills/에 있었습니다. 같은 날 앞서 진행한 Codex 실행에는 스킬이 설치되어 있지 않아 집계하지 않았습니다.
  • OpenCode와 Cursor: 테스트하지 않았습니다. 스킬은 공개 Agent Skills 형식의 일반 지침이지만, 어느 쪽에서도 실행하여 확인하지 않았습니다.

한도

  • 이 스킬은 에이전트가 볼 수 있는 정보를 바탕으로 작동합니다. 세션을 넘나드는 루프나 에이전트가 알아차리지 못하는 루프는 “you're in a loop”라고 알려 줘야 합니다.
  • Caprock이 없으면 세션 자체에서 시도한 내용을 재구성합니다. 압축된 대화에서는 초기 시도가 사라졌을 수 있습니다.
  • 재시도 횟수를 제한하거나 프로세스를 종료하지 않습니다. 지시를 무시하는 에이전트는 스킬로 멈출 수 없습니다.
  • 한 차례 실행한 Codex는 전체 형식 대신 한 줄짜리 루프 보고서를 작성했습니다.

Caprock을 사용할 때와 사용하지 않을 때

Caprock MCP 서버가 연결되면 스킬은 loop_alerts를 호출합니다. 같은 도구 호출을 반복하는 실행 중 세션과 도구, 반복 횟수, 반복 입력, 반복에 든 비용을 확인합니다. 서버가 없으면 에이전트는 대화에서 시도한 내용을 나열합니다. Caprock은 컴퓨터의 모든 코딩 에이전트 세션을 기록하는 무료 오픈 소스 앱입니다. 이 스킬에 필수는 아닙니다.

Caprock 다운로드 →

SKILL.md 전문

dspv/skills의 리비전 dfce799에 있는 파일 그대로입니다. 수동으로 설치하려면 프로젝트 안에 Claude Code용은 .claude/skills/loop-guard/SKILL.md, Codex용은 .agents/skills/loop-guard/SKILL.md로 저장합니다.

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.

loop-guard 스킬 관련 질문

Claude Code 루프란 무엇인가요?
결과를 바꿀 만한 변화가 없는데도 에이전트가 이미 실패한 단계를 반복합니다. 같은 명령을 실행하거나, 수정할 때마다 같은 오류가 발생하거나, 한 파일을 편집했다 되돌립니다. 시간과 토큰을 소모하며, 오류를 해결하는 대신 숨기는 것으로 끝나는 경우가 많습니다.
loop-guard 스킬로 Claude Code 루프를 어떻게 멈추나요?
스킬을 설치하고 “you're in a loop, use loop-guard”라고 입력합니다. 에이전트가 멈추고 잘못된 가정을 명시한 루프 보고서를 작성한 다음, 다른 접근 방식 하나를 시도하거나 질문합니다.
loop-guard는 실패하는 테스트를 건너뛰어 통과시키나요?
아니요. 이 스킬은 테스트 건너뛰기나 완화, 예외 무시, `|| true`, `--no-verify`, 하드 코딩된 출력을 루프를 숨기는 방법으로 명시하고, 바로 그 작업을 명시적으로 요청하지 않는 한 사용하지 말라고 에이전트에 지시합니다.
loop guard 스킬이 Codex에서도 작동하나요?
네. Codex 0.163.0은 2026년 11월 30일 테스트에서 이 스킬을 읽고 루프와 그 원인을 설명했으며, assertion을 건드리지 않고 import 경로를 수정했습니다.

출처

앱 자체는 영어로 되어 있습니다.