---
name: autonomous-loop
description: "Autonomous Loop 'Tackle Until Solved' - Self-referential iteration agent for complex multi-step tasks. Persists work between iterations until completion criteria met."
---

# Autonomous Loop "Tackle Until Solved"

Self-referential AI iteration agent that persists work and loops until task completion. Inspired by Ralph Loop methodology.

## Philosophy

**Iteration > Perfection.** The loop continuously refines work until success criteria are met. Each iteration sees previous work in files and can improve upon it.

**Failures Are Data.** Test failures, errors, and incomplete implementations inform the next iteration.

**Persistence Wins.** Keep trying until the task is complete. The loop handles retry logic automatically.

## When to Use

**Good for:**
- Well-defined tasks with clear success criteria
- Tasks requiring iteration and refinement (getting tests to pass)
- Greenfield implementations where you can walk away
- Tasks with automatic verification (tests, linters, build checks)
- Architecture and system design with validation
- Multi-step implementations (5+ steps)

**Not good for:**
- Tasks requiring human judgment or design decisions
- One-shot operations
- Tasks with unclear success criteria
- Production debugging (use targeted debugging instead)

## Usage

```
/autonomous-loop "Build a REST API for todos. Requirements: CRUD operations, input validation, tests. When all tests pass, output <promise>COMPLETE</promise>."
```

## How It Works

The autonomous loop creates a self-referential feedback cycle:

1. **Initialize**: Creates task file with success criteria
2. **Iterate**: Works on task using available tools
3. **Evaluate**: Checks completion criteria
4. **Persist**: Saves all work to files (visible next iteration)
5. **Repeat**: If not complete, loop continues

Each iteration sees:
- Modified files from previous attempts
- Git history of changes
- Test results and error messages
- Any documentation or notes created

## Completion Detection

The loop exits when **ANY** of these conditions are met:

1. **Completion Promise**: Output `<promise>YOUR_PHRASE</promise>` when criteria are unequivocally true
2. **Max Iterations**: Reached iteration limit (safety mechanism)
3. **Manual Stop**: User intervention

**CRITICAL**: Never output a false completion promise. The promise statement must be completely and unequivocally TRUE.

## Prompt Writing Best Practices

### 1. Clear Completion Criteria

**Bad**: "Build a todo API and make it good."

**Good**:
```markdown
Build a REST API for todos.

When complete:
- All CRUD endpoints working (POST, GET, PUT, DELETE)
- Input validation in place (required fields, data types)
- Tests passing with >80% coverage
- README with API documentation

Output: <promise>COMPLETE</promise>
```

### 2. Incremental Goals

**Bad**: "Create a complete e-commerce platform."

**Good**:
```markdown
Build an e-commerce platform in phases:
Phase 1: User authentication (JWT, tests)
Phase 2: Product catalog (list/search, tests)
Phase 3: Shopping cart (add/remove, tests)

Output <promise>COMPLETE</promise> when all phases done.
```

### 3. Self-Correction Instructions

**Bad**: "Write code for feature X."

**Good**:
```markdown
Implement feature X following TDD:
1. Write failing tests
2. Implement feature
3. Run tests
4. If any fail, debug and fix
5. Refactor if needed
6. Repeat until all green
7. Output: <promise>COMPLETE</promise>
```

### 4. Always Use Safety Limits

```markdown
# Use iteration limits as safety net
Max iterations: 50

# If stuck after reasonable attempts:
- Document what's blocking progress
- List what was attempted
- Suggest alternative approaches
- Output <promise>BLOCKED</promise> with details
```

## Loop Behavior

### State Persistence

Work persists between iterations:
- **Files**: All created/modified files remain
- **Git History**: Each commit is visible next iteration
- **State File**: Tracks iteration count and status
- **Logs**: Full history of all iterations

### Self-Referential Pattern

```
Iteration 1: "Build API" → Creates files, tests fail
Iteration 2: "Build API" → Sees files, fixes bugs, tests pass
Iteration 3: "Build API" → Sees passing tests, adds docs
Iteration 4: "Build API" → Verifies all criteria, outputs <promise>COMPLETE</promise>
```

The prompt NEVER changes between iterations. The agent sees its own previous work and iteratively improves.

## Configuration

Environment variables (optional):

```bash
# Agent selection
LOOP_AGENT=claude|gemini|auto

# Safety limits
LOOP_MAX_ITERATIONS=100
LOOP_MAX_RUNTIME=14400  # 4 hours in seconds

# Verbosity
LOOP_VERBOSE=true
```

## Files Created

```
.loop/
├── PROMPT.md       # Task with success criteria
├── config.yml      # Loop configuration
├── state.json      # Progress tracking (iteration, status)
└── iterations/
    ├── 001.md      # First iteration output
    ├── 002.md      # Second iteration output
    └── final.md    # Final validated result
```

## Monitoring Progress

While loop is running:
```bash
# Check current iteration
cat .loop/state.json | jq '.iteration, .status'

# View latest output
cat .loop/iterations/final.md

# See all history
ls -la .loop/iterations/
```

## Example Tasks

**API Development**:
```
/autonomous-loop "Build a REST API for user management. Endpoints: create, read, update, delete, list. Add input validation, error handling, and unit tests. Output <promise>ALL_TESTS_PASSING</promise> when coverage >80% and all tests green."
```

**Feature Implementation**:
```
/autonomous-loop "Implement real-time notifications using WebSockets. Requirements: connection management, broadcast messaging, reconnection logic, tests. Output <promise>NOTIFICATIONS_WORKING</promise> when demo succeeds."
```

**System Design**:
```
/autonomous-loop "Design a microservices architecture for e-commerce. Services: auth, products, orders, payments. Include API contracts, data flow diagrams, deployment strategy. Output <promise>DESIGN_COMPLETE</promise> when all services defined with integration points."
```

## Technical Details

- **Pattern**: Self-referential feedback loop
- **State**: Stored in `.loop/` directory
- **Persistence**: File-based (git-friendly)
- **Completion**: Promise phrase or iteration limit
- **Inspiration**: Ralph Loop by Geoffrey Huntley

## Stopping the Loop

- **Natural completion**: Output promise phrase when criteria met
- **Iteration limit**: Set `--max-iterations` for safety
- **Manual stop**: User can interrupt at any time

## Success Principles

1. **Write Clear Criteria**: Ambiguity causes infinite loops
2. **Use Safety Limits**: Always set max-iterations
3. **Testable Goals**: Completion must be verifiable
4. **Incremental Progress**: Break large tasks into phases
5. **Trust the Loop**: Let iteration refine the work

## References

- Original technique: https://ghuntley.com/ralph/
- Philosophy: Persistent iteration despite setbacks
