Skip to content

Repository files navigation

LoopGuard

CIGo Report CardLicense: MIT

Circuit breaker daemon for AI agent loops. Monitors Claude Code, Codex, and Gemini CLI sessions in real-time — detects runaway loops, enforces hard budget limits, and pauses offending processes before they drain your wallet.

The Problem

AI coding agents can spin for hours burning tokens on unproductive loops:

IncidentCostRoot Cause
Enterprise single-month$500M on ClaudeNo usage limits deployed
Overnight agent run$43714,000 redundant tool calls
LangChain 4-agent loop$47K over 11 daysInfinite loop, nobody noticed

Claude Code's --max-budget-usdovershoots by 8x. Built-in loop detection is unimplemented. Cursor has zero loop detection.

What LoopGuard Does

LoopGuard sits beside your agent as a circuit breaker:

  • Budget enforcement — hard pause at $20/session (configurable)
  • Spin detection — catches repeated tool calls, error echoes, no-progress stalls
  • Cost velocity alerts — warns when burn rate exceeds $2/min
  • Multi-agent — monitors Claude Code, Codex, Gemini CLI, and custom sources simultaneously
  • Zero config — works immediately after install with sane defaults
  • Process-safe — SIGSTOP/SIGCONT preserves agent state perfectly
  • LTF traces — emits Loop Trace Format events for every intervention

Install

# Homebrew (macOS/Linux)
brew install loop-eng/tap/loopguard
# Go install
go install github.com/loop-eng/loopguard@latest
# Binary download — see Releases

Quick Start

# Run in foreground (auto-discovers all active sessions)
loopguard
# Or install as auto-start service
loopguard install
loopguard start
# Check what's being monitored
loopguard status
# Resume a paused session
loopguard resume <session-id>

That's it. No config file needed. LoopGuard auto-discovers Claude Code sessions in ~/.claude/projects/ and starts watching them with default budgets.

How It Works

Agent Session (JSONL logs)
│
▼
┌────────────┐ ┌───────────┐ ┌────────────────┐
│ Discovery │───▶│ Watcher │───▶│ Analyzer │
│ (auto- │ │ (fsnotify│ │ ┌────────────┐ │
│ detect) │ │ + poll) │ │ │ Cost Calc │ │
└────────────┘ └───────────┘ │ │ Spin Detect│ │
│ │ Budget │ │
│ └─────┬──────┘ │
└────────┼────────┘
│
┌─────────────▼──────────────┐
│ Enforcer │
│ SIGSTOP + notify + trace │
└────────────────────────────┘
  1. Discovery — Scans ~/.claude/projects/, ~/.codex/sessions/, and Gemini CLI's ~/.gemini/tmp/ (or $GEMINI_DATA_DIR/tmp/) for active session files
  2. Watcher — Tails JSONL files via fsnotify with 100ms debounce + 5s polling fallback
  3. Analyzer — Calculates real-time cost from token usage, detects spin patterns, enforces budgets
  4. Enforcer — Pauses the agent process via SIGSTOP, sends a desktop notification, writes an LTF trace event

Configuration

LoopGuard works with zero configuration. To customize:

loopguard config init # creates ~/.config/loopguard/config.yaml

Full Config Reference

budget:
per_session_usd: 20.0# pause session after this costper_hour_usd: 50.0# hourly cap across all sessionsper_day_usd: 200.0# daily capwarn_at_percent: 80# warn at this % of any limitspin_detection:
repeated_calls: 3# same tool call N times → spinerror_echo: 3# same error N times → spinstall_minutes: 10# no file changes for N min → warncost_velocity_per_min: 2.0# $/min thresholdcontext_fill_percent: 85# context window fill % → spin (0 disables)enforcement:
action: pause # pause | kill | warnsentinel_fallback: true # write .loopguard-stop if SIGSTOP failsnotifications:
desktop: truesound: truesources:
claude_code: auto # auto | disabledcodex: auto # auto | disabledgemini: auto # auto | disabledcustom: [] # additional glob patterns to watchtraces:
enabled: trueoutput_dir: ~/.config/loopguard/traces/logging:
level: info # debug | info | warn | errorfile: ~/.config/loopguard/loopguard.log

Environment Variable Overrides

Environment variables take precedence over the config file:

export LOOPGUARD_BUDGET_PER_SESSION=50
export LOOPGUARD_BUDGET_PER_HOUR=100
export LOOPGUARD_BUDGET_PER_DAY=500
export LOOPGUARD_LOG_LEVEL=debug

CLI Reference

CommandDescription
loopguardStart daemon in foreground
loopguard statusShow active sessions with cost and status
loopguard status --jsonOutput session data as JSON
loopguard resume <id>Resume a paused session (prefix match)
loopguard configShow config file location
loopguard config initCreate default config file
loopguard installInstall as system service (launchd/systemd)
loopguard uninstallRemove system service
loopguard startStart background service
loopguard stopStop background service

Spin Detection

LoopGuard uses five independent heuristics to detect unproductive loops:

HeuristicWhat It CatchesDefault Threshold
Repeated tool callsSame tool+args fingerprint in recent history3 repeats
Error echoSame error message repeating3 identical errors
No-progress stallToken spend without file modifications10 minutes
Cost velocityBurn rate exceeding $/min threshold$2.00/min
Context bloatContext window filling up (estimated from input_tokens vs. the model's known context window)85% full

Supported Models (Pricing)

LoopGuard has embedded pricing for accurate cost calculation:

ProviderModels
AnthropicOpus 4.8/4.7/4.6, Sonnet 4.6/4.5, Haiku 4.5
OpenAIGPT-5.5, GPT-4.1, GPT-4.1-mini, o4-mini, o3
GoogleGemini 2.5 Pro, Gemini 2.5 Flash

Unknown models fall back to Sonnet-tier pricing.

Competitive Landscape

ToolReal-timeBudget KillSpin DetectMulti-AgentZero Config
LoopGuardYesYesYesYesYes
tokscaleYesNoNoYesNo
ccusageNoNoNoNoYes
Claude built-inPartialNoNoNoYes
Codex built-inPartialPartialNoNoYes

LTF Traces

Every intervention is recorded as an LTF (Loop Trace Format) event:

{"ltf_version":"1.0","loop_id":"sess-abc","timestamp":"2026-07-07T14:30:00Z","phase":"terminate","action":{"type":"circuit_breaker","detail":"budget_exceeded"},"cost_usd":20.12,"metadata":{"source":"loopguard","action":"paused"}}

Traces are written to ~/.config/loopguard/traces/<session-id>.ltf.jsonl and can be consumed by other loop-eng tools.

Part of loop-eng

LoopGuard is the flagship tool in the loop-eng ecosystem — developer tools for the nascent field of loop engineering. All tools share the LTF format:

ToolPurpose
LoopGuardCircuit breaker daemon (this repo)
LTFLoop Trace Format specification
LoopCtlTUI dashboard for session monitoring
KitLoop scaffolding CLI
Loop-BenchLoop design benchmarking
LoopReplaySession step-through debugger

Development

See CONTRIBUTING.md for build instructions, testing guide, and how to add support for new agent sources.

See CHANGELOG.md for release history.

make build # build binary to bin/loopguard
make test# run tests with race detector
make lint # run golangci-lint
make run # build and run
make clean # remove build artifacts

License

MIT