# agent-loop-guardian

> Catch your agent repeating the same failed edit or command and force a change of approach before it burns your tokens, with three detection layers and a logged escalation.

agent-loop-guardian is a free AI agent skill on Agensi by Timoranjes, in Trading & Investing. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: Free
- Creator: [Timoranjes](https://www.agensi.io/creators/zicheng-liao)
- Category: [Trading & Investing](https://www.agensi.io/skills/trading-investing)
- Uses: 16
- Version: 1.0
- Last updated: 2026-10-31
- Security: scan passed (2026-07-11); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/agent-loop-guardian
- Tags: finance, trading, research, quant, sec-edgar, yfinance, data-analysis, workflow

## About this skill

### The Problem

You tell your agent: "Fix the login button alignment." It edits the CSS, tests it, the button doesn't center. It edits again, changes margin values, tests again — still not centered. On the eighth edit, the token counter reads $4.20 consumed. The agent doesn't know it's stuck. It genuinely believes the next attempt will be different. Unlike a crash (which stops immediately) or an error (which you see), a loop produces output that looks like progress. The agent is busy, making changes, going nowhere. A single unbounded loop burns 50K-200K tokens — $1.50-$6.00 on Claude Code.

### What You Get

- **Detect loops at three levels** — Action-level (same file + same edit type + same goal, 3+ times), Tool-level (same command + same arguments, 5+ times), Outcome-level (same error message across different approaches, 3+ times) — preventing false positives by requiring multi-dimensional matching
- **Escalate through four levels** — Backoff (1-3 repeats: pause, state the pattern, try different approach), Approach Change (4-6: read more context, search codebase, ask for help), Escalation (7-9: stop and present structured summary with options), Kill Switch (10+: terminate with checkpoint)
- **Apply exponential backoff** — after loop detection, wait 2^n seconds before retrying (n = consecutive detections, capped at 60s) to prevent tight-loop token drain
- **Save checkpoints before termination** — the kill switch writes all modified file states, the loop pattern, and a prevention rule to `.loop-history.md` so future sessions start with the loop already recognized
- **Run a pre-task self-check** — before any multi-step task, answer three questions: "Have I attempted this same change before?", "Am I about to re-edit the same file?", "Is there an alternative I haven't tried?"
- **Learn from loops across sessions** — maintain a persistent `.loop-history.md` that records what was tried, what failed, and prevention rules, preventing repeat loops in future sessions

### Why This Beats Prompting It Yourself

Without a loop guardian, agents optimize locally — each edit feels like a micro-improvement, so the agent keeps going. The three-layer detection system catches loops that single-metric detection misses: an agent changing approach (different CSS property each time) but getting the same result (button still not centered) is an outcome-level loop, invisible to file-level tracking. The escalation ladder ensures the agent tries progressively more drastic interventions before giving up — and the kill switch prevents the worst case: unbounded token burn with no checkpoint.

### Example Session

You: "Fix the TypeScript type error in src/api/client.ts"

Agent (after 5 failed approaches):
```
[LOOP GUARDIAN] Level 2 escalation: 5 loop detections.
Approach changes exhausted. Reading more context...

Previous approaches:
1. Added type assertion `as string` — error persists
2. Changed function signature to accept `string | undefined` — cascading errors
3. Added optional chaining upstream — no effect
4. Installed @types/node update — same error
5. Refactored to use generics — different error, same root cause

Root cause analysis: The variable originates from an API response
that doesn't guarantee the field. Fix isn't at the usage site —
it's at the deserialization layer.

Recommended: Add default value in the API response handler.
Do you want me to proceed?
```

### Use Cases

- Multi-file refactors where the agent keeps editing the same file in circles
- Test suite debugging where flaky failures cause the agent to re-run the same command
- CSS/styling work where visual changes require iteration but the agent can't measure success
- Type error resolution across complex TypeScript codebases with cascading type failures
- Any agent session where the task description is vague enough that the agent can't determine "done"
- Automated CI/CD pipelines where a runaway agent would consume paid compute hours

### Known Limitations

The loop guardian is a behavioral pattern, not a runtime hook — the agent must internalize and apply the detection logic during its own reasoning. False positives can occur during legitimate exploratory work where the same file is edited for different reasons. The 3-question pre-task check requires the agent to have accurate self-awareness of its recent actions, which depends on context window freshness. Kill switches that save checkpoints lose any work done before the loop started.

### Upgrade Path

Free gives the agent self-awareness in session. **Agent Loop Guardian Pro ($5 one-time)** enforces from outside: watchdog CLI, Prometheus metrics, hard budget kill switches, and auto-remediation.

Upgrade for overnight runs and CI agents:

https://www.agensi.io/skills/agent-loop-guardian-pro

## Requires

- Python

## Known limitations

The loop guardian is a behavioral pattern, not a runtime hook — the agent must internalize and apply the detection logic during its own reasoning. False positives can occur during legitimate exploratory work where the same file is edited for different reasons. The 3-question pre-task check requires the agent to have accurate self-awareness of its recent actions, which depends on context window fre

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the agent-loop-guardian skill from Agensi" and describe your task.
3. Your agent loads the skill from Agensi when it needs it. Nothing is downloaded.

## Frequently asked questions

### How does this skill prevent my AI agent from wasting tokens on repetitive errors?

The Loop Guardian prevents agents from repeatedly executing the same failed terminal command or file edit, saving you from excessive token consumption and terminal 'hallucinations' during complex coding tasks.

### Which AI coding agents and environments are compatible with Agent Loop Guardian?

This skill is designed for terminal-based and IDE agents including Claude Code, Cursor, and Codex-based CLI tools, and can be integrated into any workflow that supports custom behavior instructions.

### How are updates handled if AI agents change their behavior patterns?

Updates are included with your purchase; whenever detection logic is refined to handle new edge cases or agent updates, you will receive an automated notification to download the latest version.

### What exactly is included in the download package?

You will receive a set of structured configuration files and integration instructions that implement the three-layer detection system (Pattern, Tool-Call, and File-Edit monitoring) for your specific agent.

### Does setting this up require complex coding or a heavy installation process?

Installation is straightforward and typically takes less than five minutes, requiring you to add the provided logic to your agent's global configuration or project-specific rules file.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
