intermediateclaude-codeclaude-codehooksskillspractical

Chapter 4 of 8

Loop Engineering in Claude Code: A Practical Guide

From hooks and CLAUDE.md to skills and the /loop command — build autonomous coding loops step by step.

Claude Code (github.com/anthropics/claude-code) is the most loop-engineering-ready coding agent available today. Its built-in features — hooks, CLAUDE.md, skills, slash commands, and the /loop command — are specifically designed to support autonomous iterative systems. This guide walks you through building real loop engineering patterns with Claude Code, drawing on documented case studies and production-verified practices.

Why Claude Code for Loop Engineering?

Claude Code exposes 27 lifecycle hook events as of v2.1.116 (per the official docs at code.claude.com/docs/en/hooks), making it the most hook-rich CLI agent in the ecosystem. Compare that to Aider (github.com/paul-gauthier/aider, 30K+ GitHub stars), which follows a git-first manual loop model where every edit becomes a reviewable commit, or Cursor (cursor.com), which relies on its IDE-integrated Agent mode rather than lifecycle hooks. Claude Code's hook architecture gives you fine-grained control at every point in the agent's execution cycle.

Key features that map directly to loop engineering patterns:

FeatureLoop Engineering Role
Hooks (27 lifecycle events)Automate actions before/after tool calls, edits, git ops, and session events
CLAUDE.mdPersistent project context and behavioral rules across sessions
SkillsReusable, parameterized loop patterns defined as markdown
/loop CommandSet up recurring autonomous tasks on a schedule or self-paced
MemoryCross-session state persistence for long-running loops
Sub-agentsSpawn parallel agents for batch loop execution

Pattern 1: Auto-Verify Loop with Hooks

Setup

Create a .claude/settings.json file in your project root:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx eslint --fix $FILE"
      }
    ]
  }
}

This hook runs ESLint automatically after every file edit. If the edit introduces a lint error, Claude Code sees the error output in the hook response and self-corrects — creating an autonomous correction loop without human intervention.

How It Works

Claude edits file -> Hook triggers ESLint -> Error found? -> Claude fixes -> Hook triggers again -> Clean? -> Done

The loop continues until the code passes linting. You never need to type "fix the lint errors" — the system handles it autonomously.

Pattern 2: Test-Driven Loop with Multi-Step Verification

Combine hooks with test runners and type checking for a more rigorous verification loop. This pattern addresses the four major production agent failure scenarios — exception handling, blind retries, context overflow, and infinite loops — by baking guard rails directly into the loop.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx tsc --noEmit 2>&1 | tail -10 && npm test -- --findRelatedTests $FILE 2>&1 | tail -20"
      }
    ]
  }
}

Now every edit is followed by type-check verification and relevant test execution. The agent sees test failures and fixes them iteratively. To prevent infinite retry loops, add a max-iteration constraint in CLAUDE.md:

## Loop Safety
- If a test fix fails 3 consecutive times, stop and report the issue
- Never modify test files to make tests pass
- Always revert changes if a fix introduces new failures

Pattern 3: CLAUDE.md for Loop Configuration

Use CLAUDE.md to define the loop's goals, constraints, and verification criteria. As the official Claude Code best practices guide (code.claude.com/docs/en/best-practices) recommends, CLAUDE.md serves as the single source of truth for project-specific agent behavior.

# Project: My API Service

## Loop Engineering Rules
- After any code change, run `npm test` and fix any failures before proceeding
- All new endpoints must have corresponding test files in src/__tests__/
- Use TypeScript strict mode — no `any` types allowed
- Follow existing code patterns in this repository
- When refactoring, ensure all existing tests continue to pass
- Max 3 retry attempts per fix — report blockages instead of looping forever

## Architecture
- Routes are in `src/routes/`
- Services are in `src/services/`
- Tests mirror the source structure in `src/__tests__/`

This configuration persists across sessions. As the context engineering principles from the Dakou framework recommend, CLAUDE.md acts as an anchor — externalizing critical decisions beyond the context window so the loop never loses sight of its goals.

Pattern 4: Skills as Reusable Loop Components

Skills encapsulate complex loop patterns into reusable, parameterized commands. Define a skill for a common refactoring loop:

<!-- .claude/skills/refactor-loop.md -->
# Refactor Loop

When the user runs `/refactor-loop <pattern> <target>`:

1. Search the codebase for all files matching `<pattern>`
2. For each file:
   a. Read the file and understand its structure
   b. Apply the refactoring described in `<target>`
   c. Run tests: `npm test -- --findRelatedTests <file>`
   d. If tests fail, revert and try a different approach (max 3 attempts)
   e. If tests pass, proceed to the next file
3. Report: files modified, tests status, any issues found
4. Commit all changes with a descriptive message

Invoke the entire migration loop with a single command: /refactor-loop "useState" "useReducer". This is conceptually similar to how Aider (github.com/paul-gauthier/aider) handles refactoring via its git-first workflow, but Claude Code's skill system adds autonomous retry logic and multi-file orchestration.

Pattern 5: The /loop Command for Recurring Tasks

# Run a health check every 10 minutes
/loop 10m check that the dev server is running and report errors

# Monitor test status continuously
/loop 5m run npm test and report any failures

# Self-paced loop — let Claude decide when to check
/loop monitor the build and fix any breakages

Pattern 6: Parallel Sub-Agents for Batch Operations

Use Claude Code's sub-agent capability to spawn parallel loops for batch processing. This is the same scaling pattern that Cursor 2.0 applies with up to 8 parallel agents in its Agent mode, and that Windsurf (windsurf.ai) implements through its Cascade multi-step execution engine.

Task: Migrate all 50 API endpoints from v1 to v2

1. List all endpoint files
2. Spawn 4 parallel sub-agents, each handling ~12 files
3. Each sub-agent runs the refactor loop independently
4. Merge results and verify the complete build passes

For comparison, MetaGPT (github.com/geekan/MetaGPT, 45K+ stars) implements a similar multi-agent parallel workflow at the framework level, assigning roles like Architect, Engineer, and QA to specialized agents. Claude Code's sub-agent approach is lighter weight but achieves the same horizontal scaling effect.

Token Cost Management for Long-Running Loops

One of the biggest risks with autonomous loops is uncontrolled token consumption. Claude 3.5 Sonnet costs $3.00 per 1M input tokens (Anthropic official pricing), and long-running loops can accumulate costs quickly. A token-optimization guide documents these strategies:

  1. Layered model strategy — use Sonnet for routine loop iterations, Opus only for complex reasoning
  2. Precise scoping — tell the loop exactly which files to touch, reducing irrelevant context
  3. Prompt caching — cache CLAUDE.md and other static context to avoid re-processing
  4. Context compaction — use /compact during long sessions to compress conversation history
  5. Reduced output — instruct the loop to reply with minimal verbosity
  6. Controlled task scope — break large tasks into smaller, focused loop iterations
  7. Disable extended thinking — turn off deep thinking for simple fix-and-verify cycles

Apply these in your CLAUDE.md loop configuration:

## Cost Control
- Use concise replies — no explanations unless asked
- Run `/compact` after every 10 loop iterations
- Scope each loop iteration to a single file or function
- Never load files unrelated to the current task

Complete Example: Autonomous Bug Fix Loop

Here is a complete loop engineering system for autonomous bug fixing, combining hooks, CLAUDE.md rules, and safety constraints.

CLAUDE.md Configuration

# Bug Fix Loop Rules

## Goal
Fix all reported bugs from the GitHub issues list.

## Loop Behavior
1. Read each issue description carefully
2. Locate the relevant code using grep and file search
3. Write a targeted fix
4. The PostToolUse hook will run type-checks and tests automatically
5. If tests fail, analyze the failure and retry (max 3 attempts)
6. If tests pass, commit with a descriptive message and move to the next issue
7. Report a summary when done: issues fixed, skipped, and blocked

## Constraints
- Do not modify test files to make tests pass
- Do not introduce new dependencies
- Preserve existing API contracts
- If a bug cannot be fixed after 3 attempts, skip and report
- Stop the loop if cumulative token usage exceeds your budget

Hook Configuration

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "command": "npx tsc --noEmit 2>&1 | tail -10 && npm test 2>&1 | tail -30"
      }
    ]
  }
}

Execution

Simply tell Claude Code: "Fix all open bugs from the GitHub issues list." The loop handles the rest autonomously — editing, verifying, retrying, committing, and reporting.

How Claude Code Compares to Other Loop-Ready Tools

Different tools implement loop engineering with different trade-offs:

ToolLoop MechanismAutonomy LevelBest For
Claude Code27 lifecycle hooks + /loop + skillsHigh — fully autonomous loopsComplex multi-file refactoring, overnight tasks
Aider (github.com/paul-gauthier/aider)Git-first commit-review cycleMedium — human-in-the-loopGit-heavy workflows with manual review
Cursor (cursor.com)IDE Agent mode with parallel agentsMedium — guided autonomyInteractive development with visual feedback
Ralph Wiggum pluginBash while true wrapperVery high — unboundedOvernight batch processing with cost awareness
OpenHands (github.com/All-Hands-AI/OpenHands)Sandbox-based agent platformHigh — containerizedIsolated, reproducible coding environments
Cline (github.com/cline/cline)VS Code plugin with MCP supportMedium — task-by-taskIDE-integrated workflows with tool protocols

Best Practices

  1. Start simple — begin with a single PostToolUse hook for linting, then add test and build verification incrementally
  2. Define clear success criteria — the loop must know exactly when it is done; use CLAUDE.md to anchor these criteria
  3. Set iteration limits — prevent infinite loops with max-retry constraints and token budgets; this directly addresses the production failure pattern of blind retries
  4. Log everything — enable detailed logging so you can debug loop behavior post-hoc
  5. Test on small tasks first — run loops on low-risk files before trusting them with critical code paths
  6. Review outcomes — always review the final diff, even if the loop ran autonomously; use Claude Code's built-in git integration or Aider-style commit review
  7. Use the layered model strategy — , assign expensive models only to reasoning-heavy loop steps

Key Takeaways

  • Claude Code is built for loop engineering — its 27 lifecycle hooks, CLAUDE.md, skills, /loop command, and sub-agents map directly to loop patterns
  • Hooks create automatic verification cycles (lint, type-check, test, build) that run after every edit
  • CLAUDE.md provides persistent loop configuration, acting as a context anchor per the Dakou framework's principles
  • Skills encapsulate reusable loop patterns as parameterized slash commands
  • /loop and the Ralph Wiggum plugin enable recurring autonomous tasks — teams have shipped 6 repositories overnight at hackathons using this pattern
  • Sub-agents enable parallel loop execution at scale, similar to Cursor 2.0's multi-agent architecture
  • Token cost management is critical for long-running loops — use layered model strategies, context compaction, and scoped tasks to keep costs under control