Documentation

Install it, understand what it does locally, and wire the helper into the tools you already use.

New here? Three terms worth knowing

Token
The unit AI models charge per. Roughly 4 characters = 1 token. Sending a whole 500-line file costs ~3,000 tokens. LoopGuard trims that to the ~200 tokens that actually matter.
MCP
A standard protocol that lets AI agents call external tools. When LoopGuard is wired as an MCP server, your AI can ask it "read only the relevant lines" instead of reading the whole file itself.
Context
Everything sent to the AI in a single request. The smaller and more focused the context, the faster and cheaper the response — and the less likely the AI hallucinates from irrelevant noise.

#Installation

LoopGuard has two install paths. Pick the one that matches how you work today.

PathWhat you getAccount needed?
VS Code extensionLoop alerts + focused context + dashboardNo (optional for sync)
Local helperFocused reads for AI agents + cleaner terminal outputNo — runs locally
Note

Loop detection requires the VS Code extension because it listens to editor diagnostics and edit patterns. The standalone helper is for focused reads, MCP integrations, and shell cleanup.

VS Code, Cursor, or Windsurf

Install the extension from the Extensions panel, or run from a terminal:

code --install-extension LoopGuard.loopguard

For Cursor use cursor --install-extension, for Windsurf use windsurf --install-extension.

Cursor and Windsurf can use the same extension. That gives you loop alerts, focused context copy, and the in-editor dashboard immediately.

Terminal-first helper path

If you use Codex CLI, Claude Code, or want LoopGuard’s shell path without the editor, install loopguard-ctx directly:

Homebrew (macOS / Linux):

brew tap rodthenewcomer/loopguard https://github.com/rodthenewcomer/loopguard
brew install loopguard-ctx

npm (any platform with Node 16+):

npm install -g loopguard-ctx-bin

Or curl installer:

curl -fsSL https://loopguard.vercel.app/install.sh | sh -s -- --download

loopguard-ctx --version

GitHub release binaries (macOS x64/ARM64, Linux x64/ARM64, Windows x64) are available on the releases page for manual installs.

Warning

Terminal-only mode does not include loop alerts. If you want loop detection, install the extension too.

#One-command agent setup

Once loopguard-ctx is installed, one command wires everything so your AI agent automatically uses focused reads instead of reading whole files. It sets up the connection config (MCP), adds the guidance rules, and installs the shell hooks — all in one shot.

# Claude Code (installs MCP + PreToolUse hooks + CLAUDE.md + shell aliases)
loopguard-ctx setup --agent=claude

# Cursor
loopguard-ctx setup --agent=cursor

# Codex CLI
loopguard-ctx setup --agent=codex

# Gemini CLI
loopguard-ctx setup --agent=gemini

# All detected editors at once
loopguard-ctx setup

After setup, run the doctor to verify every layer is green:

loopguard-ctx doctor

The doctor checks 15 layers: binary in PATH, MCP config, hook scripts, CLAUDE.md rules, shell aliases, and Claude Code-specific enforcement hooks. Each failed check shows the exact fix command.

  • Idempotent — running setup twice produces the same result, no duplicates
  • Backs up existing config files before any modification
  • Use --dry-run to preview all changes without writing anything
  • Windows: installs PowerShell .ps1 hook equivalents automatically
Note

The setup command is the recommended path for all agent integrations. Manual MCP config still works — see the MCP section below for the JSON format.

#First launch

LoopGuard activates automatically on startup. You do not need to enable it manually.

  • The LoopGuard status bar item appears after the workspace loads.
  • The Output channel is available at View → Output → LoopGuard.
  • Loop detection starts without sign-in.
  • The web dashboard is optional and only needed for synced history.

#Quick reference

CommandWhat it does
LoopGuard: Copy Optimized ContextCopy a smaller, focused prompt for the current problem
LoopGuard: Show DashboardOpen the in-editor session dashboard
LoopGuard: Sign InConnect optional account sync
LoopGuard: Sign OutRemove stored credentials
LoopGuard: Configure MCP ServerWrite helper config for the selected tool
LoopGuard: Install Shell HooksInstall helper shell integration
LoopGuard: Toggle DetectionPause or resume loop detection
LoopGuard: Reset SessionClear the current local session counters

#How loop detection works

LoopGuard uses two local signals. Either one can trigger a warning, and neither requires a remote round-trip.

Diagnostic loop detection

LoopGuard watches vscode.languages.onDidChangeDiagnostics. When the same error fingerprint keeps reappearing, it treats that as a repeat-fix loop.

Edit-pattern loop detection

LoopGuard also watches vscode.workspace.onDidChangeTextDocument. Repeated edits in the same area can signal that you are circling the same problem even if the visible error text changes slightly.

What is tracked

The extension keeps loop detection local. If you sign in, only anonymized metrics are synced: counts, timestamps, token-saved estimates, file type, and a short fingerprint of the error text. Never the code itself.

#Alert actions

When LoopGuard detects a loop, the notification gives you three immediate options.

ActionWhat it does
Try New ApproachSuggests a narrower next move instead of another broad retry
View DetailsOpens the in-editor dashboard with the current loop state
IgnoreSuppresses the current loop so the same warning does not pop right back up

#Sensitivity settings

Sensitivity controls how quickly a repeat turns into an alert. Lower sensitivity means fewer interruptions; higher sensitivity means earlier intervention.

SettingThresholdUse case
lowYou iterate fast and want fewer interruptions
medium (default)Balanced for most AI-heavy coding sessions
highYou want LoopGuard to intervene earlier
// settings.json
{
  "loopguard.sensitivity": "medium"
}

#Copy Optimized Context

Instead of pasting a whole file into chat, use LoopGuard: Copy Optimized Context. LoopGuard lifts the failing window, the nearby definitions, and the parts most likely to matter on the next turn.

  • Imports and nearby dependency lines when they matter
  • A focused window around the first active error
  • A local before/after token estimate for the copied result
  • A stronger read path when the native helper is available

Keyboard shortcut example:

// keybindings.json
{
  "key": "ctrl+shift+c",
  "command": "loopguard.copyContext",
  "when": "editorFocus"
}

#Built-in mode vs native helper

The extension always has a built-in local path. The native helper adds deeper focused reads, MCP tools, and shell cleanup when it is available.

Built-in modeNative helper
Typical behaviorFocused lines around the current problemDeeper focused reads and agent integrations
AvailabilityAlways available in the extensionUsed when the helper loads correctly
Prompt reductionSmaller prompts for common fixesOften smaller again on larger files and agent flows
Network accessNoneNone
FallbackN/AFalls back to built-in mode automatically

The helper runs locally as loopguard-ctx over stdin/stdout. It is not a cloud service.

#Supported languages

Loop detection is language-agnostic because it listens to IDE diagnostics. Focused context works best on common code and config files.

Language familyTypical file typesSupport level
TypeScript / JavaScript.ts, .tsx, .js, .jsxStrong
Python / Rust / Go / Java.py, .rs, .go, .javaStrong
C-family / C#.c, .cpp, .h, .csGood
Config and data files.json, .yaml, .tomlGood
Other readable textAny text documentBest effort

Click the LoopGuard icon in the Activity Bar (or run LoopGuard: Focus Sidebar Panel) to open the persistent live panel. It stays visible alongside your code without taking up an editor tab.

  • Header: pulse dot (red = active loops, green = clean) and engine badge (Rust / TS)
  • KPI grid: session time, total loops, time lost, and tokens saved — updates on every change
  • Active loops list: hash, repeat count, and time wasted per loop
  • All-time savings (tokens + cost avoided) when signed in with web sync
  • Quick-action buttons: Copy Optimized Context, Open Dashboard, Reset Session
  • Auth row: signed-in email + Sign Out, or a Sign In CTA

#Session dashboard

Run LoopGuard: Show Dashboard to open the full in-editor webview panel. This opens beside your active editor and shows the complete session view.

  • Current session time, time lost, tokens saved, and estimated cost avoided
  • The active loop list for the current session
  • Whether the native helper is active or the editor fallback is in use
  • Quick next-step suggestions when the session is visibly repeating

#CLI stats and Wrapped

If you use loopguard-ctx from the terminal (Claude Code, Cursor, Codex), stats sync automatically at the end of every session — no sign-in required.

  • A device UUID is generated at ~/.loopguard-ctx/device.json on first run.
  • The Stop hook calls loopguard-ctx sync in the background.
  • Stats are stored anonymously — only token counts and session totals, never source code.

View and share your stats card at loopguard.vercel.app/wrapped. Paste your device ID to generate a shareable link.

# Get your device ID
cat ~/.loopguard-ctx/device.json

# Or check savings directly in the terminal
loopguard-ctx wrapped

#Account and session sync

If you sign in, LoopGuard syncs your session metrics to the web dashboard within moments after changes, periodically in the background, and again at session end.

The web dashboard refreshes periodically, so it feels close to live, but it still depends on the extension’s sync cadence.

Note

Sync is optional. Core loop detection and focused context still work locally without an account.

#MCP server

loopguard-ctx can run as a local MCP server so agents can ask LoopGuard for focused reads, compact search, directory maps, and smaller shell output.

Use the extension command if you already installed LoopGuard in the editor:

LoopGuard: Configure MCP Server

Manual config examples:

// JSON-style config
{
  "mcpServers": {
    "loopguard-ctx": {
      "command": "/absolute/path/to/loopguard-ctx"
    }
  }
}

# Codex CLI (~/.codex/config.toml)
[mcp_servers.loopguard-ctx]
command = "/absolute/path/to/loopguard-ctx"
args = []

Cursor

Run loopguard-ctx setup --agent=cursor from a project root if you want both the MCP config and a small project rule file.

loopguard-ctx setup --agent=cursor

This configures ~/.cursor/mcp.json and can add .cursor/rules/loopguard-ctx.mdc in the current project.

Windsurf

Run loopguard-ctx setup --agent=windsurf from a project root to configure Windsurf and add the project rules file.

loopguard-ctx setup --agent=windsurf

This configures ~/.codeium/windsurf/mcp_config.json and can add .windsurfrules in the current project.

Codex CLI

Use the extension command or run the helper directly:

loopguard-ctx setup --agent=codex

This writes ~/.codex/config.toml and a small instruction file under ~/.codex/.

Claude Code

Use the helper install if you want the full terminal workflow:

loopguard-ctx setup --agent=claude

Today this sets up ~/.claude.json, local hook entries in ~/.claude/settings.json, and a helper guidance file at ~/.claude/CLAUDE.md.

Note

Run ctx_session load at the start of every Claude Code session to restore the previous task context and saved findings.

Gemini CLI

To wire up Gemini CLI and compatible Gemini-family tools such as Antigravity, run the setup tool:

loopguard-ctx setup --agent=gemini

This configures ~/.gemini/settings/mcp.json and installs the local guidance file those tools use for LoopGuard MCP workflows.

#Shell helper

The shell helper keeps verbose terminal output smaller before you paste it into chat or hand it to an agent.

# From the extension
LoopGuard: Install Shell Hooks

# Or directly
loopguard-ctx init

Supported shells today: bash, zsh, and fish.

Warning

Shell behavior varies by shell and tool. If you want the most predictable agent integration, MCP is the stronger path.

#Binary installation details

The extension bundles the platform helper under its bin/ directory. The standalone install path uses the same helper binary.

If you need it outside the extension, use the install script or download a release binary manually from GitHub.

#Advanced helper tools

These four tools shipped in v3 and are available to every agent that connects via the MCP server — Claude Code, Cursor, Windsurf, and Codex CLI. They run entirely locally with no LLM call.

ctx_loop_hint — Root cause hint engine

When you are stuck in a loop on the same error, ctx_loop_hint analyzes the error text and returns a specific diagnosis and fix suggestion — no AI call, no network request. It covers TypeScript, Rust, Python, Go, React, and generic syntax errors.

# MCP (Claude Code / Cursor / Windsurf / Codex CLI)
ctx_loop_hint(error_text: "Cannot read properties of undefined (reading 'map')")

# CLI
loopguard-ctx hint "Cannot read properties of undefined (reading 'map')"

# VS Code / Cursor / Windsurf extension
# Shown automatically in the loop alert notification detail

Example output:

ctx_loop_hint — 100% confidence · pattern: null_access
─────────────────────────────────────────
Diagnosis:   A value is undefined before it is accessed.
Suggestion:  Add optional chaining (?.) or a null guard before the access.
─────────────────────────────────────────
Run ctx_memory(action="record", ...) after resolving.
  • Covers 20+ error patterns across six languages
  • Confidence score — low-confidence matches are filtered out
  • After resolving, record the fix with ctx_memory so future sessions skip it
  • Available to all MCP-connected tools, not just the VS Code extension

ctx_forecast — Token cost estimator

Before starting a complex task, ctx_forecast estimates how many tokens it will likely consume and what that costs across four models.

# MCP
ctx_forecast(task: "Refactor the auth middleware to use Zod validation")

# CLI
loopguard-ctx forecast "Refactor the auth middleware to use Zod validation"

# Extension: hover the LoopGuard status bar item to see the forecast
# Claude Code hook: forecast runs automatically on each new prompt

Output includes a cost table comparing Sonnet, Haiku, GPT-4o, and Gemini Flash — with and without focused reads. Use it to decide which model fits the budget before you start.

InputDescription
taskTask description — used to classify complexity
filesOptional list of files you plan to read

ctx_memory — Local fix memory store

ctx_memory stores the patterns that worked when you broke a loop, keyed by error fingerprint. On future sessions it surfaces matching fixes before you start repeating the same cycle.

# MCP — record a fix after resolving a loop
ctx_memory(
  action="record",
  error_text="Cannot find module '@loopguard/core'",
  fix_file="packages/core/src/index.ts",
  fix_description="Run npm run build in packages/core to rebuild dist/ first"
)

# CLI equivalents
loopguard-ctx memory record "Cannot find module" --fix-file="packages/core/src/index.ts" --fix-desc="rebuild dist/ first"
loopguard-ctx memory query "Cannot find module"
loopguard-ctx memory list
loopguard-ctx memory stats

# Extension: Past fixes rail in the LoopGuard dashboard (last 5 entries)
ActionDescription
recordStore a new fix pattern
queryFind fixes matching the current error (fuzzy match)
listShow all stored patterns for this project
statsHow many patterns stored, total hits avoided
clearRemove all stored patterns
Note

Stored at ~/.loopguard-ctx/memory.json — local only, never synced.

ctx_predict — Predictive file pre-selection

Before reading any file, ctx_predict ranks every file in the workspace by predicted relevance to your task description. It uses keyword overlap, path matching, and session history to score files so you read the right ones first.

# MCP
ctx_predict(task: "Fix the Zod validation on the auth route")

# CLI
loopguard-ctx predict "Fix the Zod validation on the auth route" --path=. --limit=10

# Extension: Copy Optimized Context appends predicted related files automatically

Returns a ranked list with read suggestions. Use it right after ctx_session load and before any ctx_read calls.

  • No LLM call — pure keyword and path scoring
  • Session history boost — files touched this session rank higher
  • Respects workspace root and skips node_modules, .git, target
  • Configurable result limit (default: 10)

ctx_knowledge — Project knowledge store

ctx_knowledge stores facts, architectural decisions, and team conventions by category so any agent in the same project can retrieve them without re-deriving them. Data lives at ~/.loopguard-ctx/knowledge.json — never leaves the device.

# MCP — store a fact any agent can retrieve
ctx_knowledge(action="set", key="arch.auth", value="Supabase JWT + RLS on all tables", category="architecture")
ctx_knowledge(action="set", key="api.style", value="REST, Zod validation on every route", category="convention")

# Retrieve
ctx_knowledge(action="get", key="arch.auth")

# List all for this project, optionally filtered by category
ctx_knowledge(action="list")
ctx_knowledge(action="list", category="architecture")

# Remove or wipe
ctx_knowledge(action="delete", key="arch.auth")
ctx_knowledge(action="clear")
  • Grouped by category — architecture, decision, convention, or any label you choose
  • Fuzzy key matching — ctx_knowledge(get, key="auth") finds "arch.auth" automatically
  • Capped at 2000 entries per project
  • Available to all MCP-connected tools — Claude Code, Cursor, Codex CLI, and Gemini-family tools

ctx_agent — Multi-agent scratchpad

ctx_agent is a shared read/write scratchpad that multiple agents can access simultaneously. Start a task in Claude Code, hand it off to Cursor, and the second agent picks up exactly where you left off.

# Write a note before stopping work
ctx_agent(action="write", agent="claude-code", label="current-task",
  content="Refactoring auth middleware — stopped at line 84 in authService.ts, next: add Zod schema")

# Another agent reads it to continue
ctx_agent(action="read", label="current-task")

# See all notes left by all agents for this project
ctx_agent(action="list")

# Auto-expire a note after 4 hours
ctx_agent(action="write", agent="cursor", label="scratch", content="...", ttl_hours=4)

# Clean up
ctx_agent(action="delete", label="current-task")
ctx_agent(action="clear")
  • Works across Claude Code, Cursor, Codex CLI, and Gemini-family tools
  • Optional TTL: notes auto-expire after N hours so the pad stays clean
  • List groups notes by agent so you can see who wrote what
  • Stored at ~/.loopguard-ctx/agent-scratchpad.json — local only, never synced

#All settings

SettingTypeDefaultDescription
loopguard.sensitivitystring"medium"Loop detection threshold: low | medium | high
loopguard.enableContextEnginebooleantrueEnable or disable focused context copy
loopguard.enableNotificationsbooleantrueShow or hide LoopGuard notifications
loopguard.loopThresholdnumber3Exact repetition count override

#settings.json

{
  "loopguard.sensitivity": "medium",
  "loopguard.loopThreshold": 3,
  "loopguard.enableContextEngine": true,
  "loopguard.enableNotifications": true
}

#Loops not detected

  • Make sure detection is not paused.
  • Try higher sensitivity if the message shape is changing slightly.
  • Check that the issue appears in the VS Code Problems panel.
  • Use View → Output → LoopGuard to inspect activity and error logs.

#Binary not found

If the helper cannot be found:

  • Reinstall the extension or rerun the helper installer.
  • Check that the helper exists in the extension bin directory or on your PATH.
  • On macOS, clear quarantine if Gatekeeper blocked the binary.
  • On Linux, make sure the file is executable.

#MCP setup failed

  • Make sure loopguard-ctx itself runs before troubleshooting MCP.
  • Confirm that the target config file was updated.
  • Restart the target app after editing MCP config.
  • Use loopguard-ctx doctor for the helper path, especially for Claude Code.

#Sign-in issues

LoopGuard sign-in uses a browser callback back into the editor. If that handoff fails:

  • Make sure your default browser is configured correctly.
  • On Linux, verify the vscode:// URI handler registration.
  • Cursor uses cursor:// automatically when installed there.
  • On remote or SSH sessions, dashboard sign-in is best done from a local desktop session for now.

See what shipped in v1 and v2, and what is coming in v3 — with the full feature list for every IDE and CLI tool.

loopguard.vercel.app/roadmap →

Something missing? Open an issue on GitHub or email support@loopguard.dev.