Agent Loop Guide

Iterative AI task execution with automatic recovery

Agent Loop Guide

Prompt-first procedure: Describe the outcome you want in your agent conversation. The agent should select and load the appropriate AIWG assets, explain material changes, request any needed approval, and report verification evidence. Exact commands and flags appear only in the CLI reference.

Iterative AI task execution with automatic recovery - iteration beats perfection.

Overview

Al transforms single-pass AI execution into iterative completion loops. Instead of hoping a task succeeds on the first try, Al keeps iterating until verifiable completion criteria are met.

┌──────────────────────────────────────────┐
│            AGENT LOOP                    │
│                                          │
│   Execute → Verify → Learn → Iterate     │
│      ↑                          │        │
│      └──────────────────────────┘        │
│                                          │
│   Until: criteria met OR limits reached  │
└──────────────────────────────────────────┘

Three Modes

ModeCommandBest ForSession Duration
Internal`/ralph`Tasks that fit in one sessionMinutes to ~1 hour
External`/ralph-external`Long-running tasks (6-8 hours)Multiple sessions
Daemonthe agent-owned daemon operationAlways-on supervisionContinuous (days/weeks)

Quick Start

Internal Al (Single Session)

# Fix all failing tests
/ralph "Fix all failing tests" the completion option "npm test passes"

# TypeScript migration
/ralph "Convert src/ to TypeScript" the completion option "npx tsc --noEmit passes" the max-iterations option 20

# Coverage target
/ralph "Add tests until 80% coverage" the completion option "npm run coverage shows >= 80%"

External Al (Multi-Session)

# Long-running migration with crash recovery
/ralph-external "Migrate codebase to TypeScript" \
  the completion option "npx tsc --noEmit exits 0" \
  the max-iterations option 20 \
  the budget option 5.0

# With Codex provider instead of Claude
/ralph-external "Implement auth feature" \
  the completion option "npm test -- --testPathPattern=auth passes" \
  the provider option codex

# With enhanced memory and cross-task learning
/ralph-external "Fix all failing tests" \
  the completion option "npm test passes" \
  the memory option complex \
  the cross-task option

Commands Reference

Internal Al

CommandDescription
`/ralph`Start iterative task loop
`/ralph-status`Check current loop status
`/ralph-abort`Abort running loop
`/ralph-resume`Resume interrupted loop

External Al

CommandDescription
`/ralph-external`Start external supervisor loop
`/ralph-external-status`Check external loop status
`/ralph-external-abort`Abort external loop and cleanup

Natural Language Triggers

Al also responds to natural language:

  • "ralph this: [task]"
  • "keep trying until [condition]"
  • "loop until [criteria]"
  • "iterate on [task] until [done]"
  • "run crash-resilient loop to..." (external)

Writing Completion Criteria

Good (objectively verifiable):

"npm test passes"
"npx tsc --noEmit exits with code 0"
"npm run lint passes"
"coverage report shows >= 80%"

Poor (subjective):

"code is good"
"feature is complete"

The criteria must be a command that returns a clear pass/fail status.

When to Use Al

Al is a power tool. Used correctly, it delivers overnight. Used incorrectly, it burns tokens producing junk.

SituationUse Al?Instead
Greenfield with no docsNOUse AIWG intake/flows first
Vague requirementsNOWrite use cases first
Clear spec, need implementationYES-
Tests failing, need fixesYES-
Migration with clear rulesYES-

Key insight: Al excels at HOW to build, but thrashes on WHAT to build. Define your requirements first, then let Al implement.

Internal vs External

Use Internal (`/ralph`) When:

  • Task fits within a single session
  • Context corruption isn't a concern
  • Fast iteration cycles needed
  • Simple verification criteria

Use External (`/ralph-external`) When:

  • Task may take 6-8 hours
  • Need crash recovery
  • Context corruption is a risk
  • Progress tracking across sessions is important
  • Running overnight or unattended

External Al Features

External Al provides additional capabilities:

FeatureDescription
Multi-Provider SupportTarget Claude or Codex via the provider option
Pre/Post SnapshotsCaptures git status, .the agent-owned state operation before/after each session
Session TranscriptFull CLI transcript capture
Two-Phase AssessmentOrient (understand) → Generate (continue)
Crash RecoveryResume from last checkpoint on failure
Research-Backed OptionsMemory capacity, cross-task learning, best output selection, early stopping
Provider AdapterCapability-based degradation across providers

Configuration Options

/ralph-external "<task>" the completion option "<criteria>" [options]

Core Options:
  the max-iterations option <n>         Max external iterations (default: 5)
  the model option <name>               Model to use (default: opus)
  the budget option <usd>               Budget per iteration in USD (default: 2.0)
  the timeout option <min>              Timeout per iteration in minutes (default: 60)
  the mcp-config option <json>          MCP server configuration JSON
  the gitea-issue option                Create/link Gitea issue for tracking
  the provider option <name>            CLI provider: claude (default), codex

Research-Backed Options (REF-015, REF-021):
  -m, the memory option <n|preset>      Memory capacity Ω: 1-10 or preset name
                               Presets: simple(1), moderate(3), complex(5), maximum(10)
                               Default: 3 (moderate)
  the cross-task option                 Enable cross-task learning (default: true)
  the no-cross-task option              Disable cross-task learning
  the no-analytics option               Disable iteration analytics
  the no-best-output option             Disable best output selection (use final)
  the no-early-stopping option          Disable early stopping on high confidence

Commands:
  -r, the resume option                 Resume interrupted loop
  -s, the status option                 Show current loop status
  the abort option                      Abort current loop

Multi-Provider Support

Agent loops can target different CLI providers via the provider option. Each provider maps AIWG model names to provider-specific models:

# Run with Codex instead of Claude
/ralph-external "Migrate to TypeScript" \
  the completion option "npx tsc --noEmit exits 0" \
  the provider option codex \
  the budget option 3.0

# Default (Claude)
/ralph-external "Fix tests" the completion option "npm test passes"
AIWG ModelClaudeCodex
`opus`claude-opus-4-6gpt-5.3-codex
`sonnet`claude-sonnet-4-5codex-mini-latest
`haiku`claude-haiku-4-5gpt-5-codex-mini

The provider adapter handles capability differences automatically. If the target provider lacks a capability (e.g., MCP support), Al degrades gracefully and logs a warning.

State & Artifacts

Internal Al

.aiwg/ralph/
├── current-loop.json       # Loop state (for resume)
├── iterations/             # Iteration history
│   ├── iteration-1.md
│   └── ...
└── completion-*.md         # Final reports

External Al

.aiwg/ralph-external/
├── session-state.json      # Active loop state
├── iterations/
│   └── 001/
│       ├── prompt.md           # Prompt used
│       ├── stdout.log          # Captured stdout
│       ├── stderr.log          # Captured stderr
│       ├── pre-snapshot.json   # State before session
│       ├── post-snapshot.json  # State after session
│       ├── analysis.json       # Output analysis
│       └── checkpoints/        # Periodic checkpoints
└── completion-report.md    # Final summary

Persistent Al via Daemon

The daemon mode extends Al into always-on project supervision. Instead of manually launching agent loops, the daemon can trigger them automatically based on file changes, schedules, or messaging commands.

When to Use Daemon Mode

ScenarioUse This Mode
One-off task, quick fixInternal (`/ralph`)
Multi-hour migration, overnight taskExternal (`/ralph-external`)
Continuous monitoring, auto-triggered tasksDaemon (the agent-owned daemon operation)

How It Works

The daemon watches your project and can submit tasks to the Agent Supervisor, which spawns `claude -p` subprocesses — the same mechanism Al uses internally.

Use AIWG to complete this documented outcome: The daemon watches your project and can submit tasks to the Agent Supervisor, which spawns claude -p subprocesses — the same mechanism Al uses internally.
Have it inspect the current state, explain the plan, ask before material
changes, and report the result with verification evidence.

Daemon + Messaging

When messaging adapters are enabled (Slack, Discord, Telegram), you can interact with Ralph-like workflows from chat:

/ask What tests are currently failing?
/status
/approve gate-123

The `/ask` command spawns a `claude -p` process with full project context, just like Al does.

Setup

See the Daemon Guide for full setup instructions and the Messaging Guide for platform integration.

Best Practices

1. Be specific - "Fix auth tests" > "Fix tests" 2. Use verifiable criteria - Commands with exit codes work best 3. Set reasonable limits - 10-20 iterations for most tasks 4. Enable auto-commit - Track progress via git history 5. Define requirements first - Al implements, doesn't design 6. Use external for long tasks - Crash recovery is worth the overhead

Philosophy

"Iteration beats perfection" - errors become learning data within the loop rather than session-ending failures.

Al inverts traditional AI optimization from "unpredictable success" to "predictable failure with automatic recovery."

Examples

See the addon documentation for detailed walkthroughs:

Technical Details

For implementation details:

Credits

Based on the iterative agent loop methodology.