SuperAPI AI Directory

autonomous-loops

Agents & models

View repository

Updated 10-16 07:23

About this skill

Autonomous Loops Skill

Patterns, architectures, and reference implementations for autonomously running Claude Code loops. Covers everything from simple claude -p pipelines to full RFC-driven multi-agent DAG orchestration.

When to Use

  • Set up autonomous development workflows that run without human intervention
  • Choose the right loop architecture for your problem (simple vs complex)
  • Build CI/CD-style continuous development pipelines
  • Run parallel agents with merge coordination mechanisms
  • Persist context between loop iterations
  • Add quality gates and cleanup stages to autonomous workflows

Loop Pattern Spectrum

From simplest to most complex:

Pattern Complexity Best For
Sequential Pipeline Low Daily development steps, scripted workflows
NanoClaw REPL Low Interactive persistent sessions
Infinite Agentic Loop Medium Parallel content generation, spec-driven work
Continuous Claude PR Loop Medium Multi-day iteration projects with CI gates
De-Sloppify Pattern Add-on Quality cleanup after any implementation step
Ralphinho / RFC-Driven DAG High Large features, multi-unit parallel work with merge queue

1. Sequential Pipeline ( claude -p)

The simplest loop. breaks daily development into a series of non-interactive claude -p calls. Each call is a focused step with an explicit prompt.

Core Insight

If you can't understand a loop like this, it means you can't even drive an LLM to fix your code in interactive mode.

claude -p flag runs Claude Code non-interactively with a prompt and exits when done. Chain calls to build a pipeline:

#!/bin/bash
# daily-dev.sh — 功能分支的顺序流水线

set -e

# 第 1 步:实现功能
claude -p "阅读 docs/auth-spec.md 中的规约。在 src/auth/ 中实现 OAuth2 登录。先写测试 (TDD)。不要创建任何新的文档文件。"

# 第 2 步:去杂质 (De-sloppify, 清理环节)
claude -p "检查上一次提交更改的所有文件。删除任何不必要的类型测试、过度防御性的检查或对语言特性的测试(例如,测试 TypeScript 泛型是否工作)。保留真实的业务逻辑测试。清理后运行测试套件。"

# 第 3 步:验证
claude -p "运行完整的构建、代码检查(lint)、类型检查和测试套件。修复任何失败。不要添加新功能。"

# 第 4 步:提交
claude -p "为所有暂存的更改创建一个约定式提交(conventional commit)。使用 'feat: add OAuth2 login flow' 作为消息。"

Key Design Principles

  1. Each step is isolated — each claude -p call has a fresh context window, meaning there is no context contamination between steps.
  2. Order matters — steps execute in order. Each step builds on the filesystem state left by the previous step.
  3. Negative instructions are dangerous — don't say "don't test the type system." Instead, add a separate cleanup step (see De-Sloppify Pattern)。
  4. Exit codes propagate — set -e will stop the pipeline on failure.

Variants

Using Model Routing:

# 使用 Opus 进行调研(深度推理)
claude -p --model opus "分析代码库架构并编写添加缓存的计划..."

# 使用 Sonnet 进行实现(快速且强大)
claude -p "根据 docs/caching-plan.md 中的计划实现缓存层..."

# 使用 Opus 进行审查(彻底)
claude -p --model opus "检查所有更改是否存在安全问题、竞态条件和边界情况..."

With environment context:

# 通过文件传递上下文,而不是增加提示词长度
echo "重点领域:auth 模块,API 速率限制" > .claude-context.md
claude -p "阅读 .claude-context.md 获取优先级信息。按顺序处理它们。"
rm .claude-context.md

With --allowedTools limit:

# 只读分析阶段
claude -p --allowedTools "Read,Grep,Glob" "审计此代码库的安全漏洞..."

# 只写实现阶段
claude -p --allowedTools "Read,Write,Edit,Bash" "实现 security-audit.md 中的修复方案..."

2. NanoClaw REPL

ECC's built-in persistence loop. A session-aware REPL that synchronously invokes claude -p with the full conversation history.

# 启动默认会话
node scripts/claw.js

# 带有技能上下文的命名会话
CLAW_SESSION=my-project CLAW_SKILLS=tdd-workflow,security-review node scripts/claw.js

How It Works

  1. Load the conversation history from ~/.claude/claw/{session}.md .
  2. Each user message is sent to claude -p, with the full history as context.
  3. Responses are appended to the session file (Markdown as a database).
  4. Sessions persist across restarts.

NanoClaw vs. Sequential Pipelines

Use Case NanoClaw Sequential Pipeline
Interactive exploration Yes No
Script automation No Yes
Session persistence Built-in Manual
Context accumulation Grows with each turn Each step is new
CI/CD integration Poor Excellent

See the /claw command documentation for details.


3. Infinite Agentic Loop

Dual-prompt system, used to coordinate parallel sub-agents for spec-driven generation. Developed by disler (credit: @disler).

Architecture: Dual-Prompt System

提示词 1 (编排器 Orchestrator)              提示词 2 (子智能体 Sub-Agents)
┌─────────────────────┐             ┌──────────────────────┐
│ 解析规约文件         │             │ 接收完整上下文        │
│ 扫描输出目录         │    部署     │ 读取分配的编号        │
│ 计划迭代             │────────────│ 严格遵守规约          │
│ 分配创意方向         │  N 个智能体 │ 生成唯一的输出        │
│ 管理波次             │             │ 保存到输出目录        │
└─────────────────────┘             └──────────────────────┘

Pattern

  1. Spec analysis — the orchestrator reads the spec file (Markdown) that defines what to generate.
  2. Directory reconnaissance — scans existing output to find the highest iteration number.
  3. Parallel deployment — launches N sub-agents, each of which receives:
    • The complete spec
    • A unique creative direction
    • A specific iteration number (no conflicts)
    • A snapshot of existing iterations (to ensure uniqueness)
  4. Wave management — for infinite mode, deploy 3-5 agents as one wave until context is exhausted.

Implemented via Claude Code commands

Create .claude/commands/infinite.md:

从 $ARGUMENTS 解析以下参数:
1. spec_file — 规约 markdown 的路径
2. output_dir — 保存迭代结果的位置
3. count — 整数 1-N 或 "infinite"

阶段 1:阅读并深度理解规约。
阶段 2:列出 output_dir,找到最高的迭代编号。从 N+1 开始。
阶段 3:计划创意方向 — 每个智能体获得不同的主题/方法。
阶段 4:并行部署子智能体(Task 工具)。每个子智能体接收:
  - 完整规约文本
  - 当前目录快照
  - 分配给他们的迭代编号
  - 他们唯一的创意方向
阶段 5 (无限模式):以 3-5 个为一波次循环,直到上下文过低。

Invoke:

/project:infinite specs/component-spec.md src/ 5
/project:infinite specs/component-spec.md src/ infinite

Batching Strategy

Count Strategy
1-5 All agents run simultaneously
6-20 5 per batch
infinite 3-5 per wave, gradually increasing complexity

Key Insight: Ensure Uniqueness Through Assignment

Don't expect agents to differentiate themselves. The orchestrator willassigneach agent a specific creative direction and iteration number. This prevents duplicate concepts among parallel agents.


4. Continuous Claude PR Loop

Production-grade Shell script, runs Claude Code in a continuous loop, creates PRs, waits for CI, and auto-merges. Developed by AnandChowdhary (credit: @AnandChowdhary).

Core Loop

┌─────────────────────────────────────────────────────┐
│  持续 CLAUDE 迭代 (CONTINUOUS CLAUDE ITERATION)     │
│                                                     │
│  1. 创建分支 (continuous-claude/iteration-N)        │
│  2. 使用增强提示词运行 claude -p                    │
│  3. (可选) 审查者阶段 — 独立的 claude -p             │
│  4. 提交更改 (Claude 生成提交消息)                  │
│  5. 推送并创建 PR (gh pr create)                    │
│  6. 等待 CI 检查 (轮询 gh pr checks)                │
│  7. CI 失败? → 自动修复阶段 (claude -p)            │
│  8. 合并 PR (squash/merge/rebase)                   │
│  9. 返回 main 分支 → 重复                           │
│                                                     │
│  限制条件:--max-runs N | --max-cost $X             │
│            --max-duration 2h | 完成信号             │
└─────────────────────────────────────────────────────┘

Installation

curl -fsSL https://raw.githubusercontent.com/AnandChowdhary/continuous-claude/HEAD/install.sh | bash

Usage

# 基础:10 次迭代
continuous-claude --prompt "为所有未测试的函数添加单元测试" --max-runs 10

# 限制成本
continuous-claude --prompt "修复所有 linter 错误" --max-cost 5.00

# 限制时间
continuous-claude --prompt "提高测试覆盖率" --max-duration 8h

# 带有代码审查阶段
continuous-claude \
  --prompt "添加身份验证功能" \
  --max-runs 10 \
  --review-prompt "运行 npm test && npm run lint,修复任何失败"

# 通过工作树 (worktrees) 并行运行
continuous-claude --prompt "添加测试" --max-runs 5 --worktree tests-worker &
continuous-claude --prompt "重构代码" --max-runs 5 --worktree refactor-worker &
wait

Cross-iteration context:SHARED_TASK_NOTES.md

Key innovation: a SHARED_TASK_NOTES.md file that persists between iterations:

## 进度
- [x] 为 auth 模块添加了测试 (迭代 1)
- [x] 修复了 token 刷新的边界情况 (迭代 2)
- [ ] 仍需:速率限制测试,错误边界测试

## 下一步
- 下一步专注于速率限制模块
- tests/helpers.ts 中的 mock 设置可以复用

Claude reads this file at the start of an iteration and updates it at the end of the iteration. This bridges the context gap between independent claude -p calls.

CI Failure Recovery

When a PR check fails, Continuous Claude automatically:

  1. Via gh run list get the failed run ID.
  2. Start a new claude -p。
  3. Claude via gh run view checks the logs, fixes the code, commits and pushes.
  4. Wait for checks again (retry up to --ci-retry-max times).

Completion Signal

Claude can signal "I'm done" by outputting a magic phrase:

continuous-claude \
  --prompt "修复问题跟踪器中的所有 bug" \
  --completion-signal "CONTINUOUS_CLAUDE_PROJECT_COMPLETE" \
  --completion-threshold 3  # 连续 3 次信号后停止

Emitting the completion signal for three consecutive iterations will stop the loop, preventing wasted credits on already-completed work.

Key Configuration

Flag Purpose
--max-runs N Stop after N successful iterations
--max-cost $X Stop after spending $X
--max-duration 2h Stop after the specified time
--merge-strategy squash Merge strategy: squash, merge, or rebase
--worktree <name> Parallel execution via git worktrees
--disable-commits Dry-run mode (no git operations)
--review-prompt "..." Add a reviewer phase for each iteration
--ci-retry-max N Automatically fix CI failures (default: 1)

5. The De-Sloppify Pattern

An add-on pattern applicable to any loop. Add a dedicated cleanup/refactoring step after each Implementer step.

The Problem

When you ask an LLM to implement a feature via TDD, its understanding of "writing tests" can be too rigid:

  • Testing whether TypeScript's type system works (testing typeof x === 'string')
  • Writing overly defensive runtime checks for things the type system already guarantees
  • Testing framework behavior instead of business logic
  • Excessive error handling obscuring the actual code

Why Not Use Negative Instructions?

Adding "don't test the type system" or "don't add unnecessary checks" to the implementer prompt has side effects:

  • The model becomes hesitant about all tests
  • It skips reasonable edge-case tests
  • Quality drops unpredictably

The Solution: A Separate Cleanup Phase

Instead of constraining the implementer, let it go all out. Then add a focused cleanup agent:

# 第 1 步:实现(让它彻底发挥)
claude -p "通过完整的 TDD 实现该功能。测试要彻底。"

# 第 2 步:去杂质 (独立的上下文,专注的清理)
claude -p "审查工作树中的所有更改。删除:
- 验证语言/框架行为而不是业务逻辑的测试
- 类型系统已经强制执行的冗余类型检查
- 对不可能状态的过度防御性错误处理
- Console.log 语句
- 被注释掉的代码

保留所有业务逻辑测试。清理后运行测试套件以确保没有破坏任何功能。"

Using It in a Loop Context

for feature in "${features[@]}"; do
  # 实现
  claude -p "通过 TDD 实现 $feature。"

  # 去杂质
  claude -p "清理阶段:审查更改,删除测试/代码杂质,运行测试。"

  # 验证
  claude -p "运行构建 + lint + 测试。修复任何失败。"

  # 提交
  claude -p "提交并附带消息:feat: add $feature"
done

Key Insight

Instead of adding negative instructions that affect downstream quality, add a separate de-sloppify phase. Two focused agents are better than one constrained agent.


6. Ralphinho / RFC-Driven DAG Orchestration

The most complex pattern. An RFC-driven multi-agent pipeline that decomposes a spec into a dependency DAG (directed acyclic graph), runs each unit through a layered quality pipeline, and lands it via an agent-driven merge queue. Developed by enitrat (credit: @enitrat).

Architecture Overview

RFC/PRD 文档
       │
       ▼
  分解 DECOMPOSITION (AI)
  将 RFC 分解为具有依赖 DAG 的工作单元
       │
       ▼
┌──────────────────────────────────────────────────────┐
│  RALPH 循环 (最多 3 次迭代)                          │
│                                                      │
│  对于每个 DAG 层(按依赖关系顺序执行):             │
│                                                      │
│  ┌── 质量流水线 (单元之间并行运行) ───────────────┐  │
│  │  每个单元在自己的工作树中:                     │  │
│  │  调研 → 计划 → 实现 → 测试 → 审查              │  │
│  │  (深度根据复杂度层级而异)                      │  │
│  └────────────────────────────────────────────────┘  │
│                                                      │
│  ┌── 合并队列 Merge Queue ────────────────────────┐  │
│  │  变基到 main → 运行测试 → 落地或剔除 (Evict)    │  │
│  │  被剔除的单元带着冲突上下文重新进入循环         │  │
│  └────────────────────────────────────────────────┘  │
│                                                      │
└──────────────────────────────────────────────────────┘

RFC Decomposition

The AI reads the RFC and generates work units:

interface WorkUnit {
  id: string;              // kebab-case 标识符
  name: string;            // 人类可读的名称
  rfcSections: string[];   // 该单元处理哪些 RFC 章节
  description: string;     // 详细描述
  deps: string[];          // 依赖项(其他单元 ID)
  acceptance: string[];    // 具体的验收标准
  tier: "trivial" | "small" | "medium" | "large"; // 复杂度层级
}

Decomposition rules:

  • Prefer fewer, more cohesive units (minimize merge risk)
  • Minimize file overlap across units (avoid conflicts)
  • Keep tests and implementation together (never separate "implement X" and "test X")
  • Establish dependencies only when there is a real code dependency

The dependency DAG determines execution order:

第 0 层: [unit-a, unit-b]     ← 无依赖,并行运行
第 1 层: [unit-c]             ← 依赖于 unit-a
第 2 层: [unit-d, unit-e]     ← 依赖于 unit-c

Complexity Tiers

Different tiers correspond to different pipeline depths:

Tier Pipeline Stages
trivial implement → test
small implement → test → code review
medium research → plan → implement → test → PRD review + code review → review fixes
large research → plan → implement → test → PRD review + code review → review fixes → final review

This prevents expensive operations on simple changes while ensuring architectural changes are thoroughly reviewed.

Independent Context Windows (Eliminating Author Bias)

Each stage runs in its own agent process, with its own context window:

Stage Model Purpose
Research Sonnet Read the codebase + RFC, generate a context document
Plan Opus Design implementation steps
Implement Codex Write code according to the plan
Test Sonnet Run the build + test suite
PRD Review Sonnet Specification compliance check
Code Review Opus Quality + security check
Review Fixes Codex Address issues found in review
Final Review Opus Quality gate (large tier only)

Core design: The reviewer is never the person who wrote the code. This eliminates author bias — the most common source of oversights in self-review.

Merge Queue with Eviction

After the quality pipeline completes, units enter the merge queue:

单元分支
    │
    ├─ 变基 (Rebase) 到 main
    │   └─ 冲突? → 剔除 (EVICT)(捕获冲突上下文)
    │
    ├─ 运行构建 + 测试
    │   └─ 失败? → 剔除 (EVICT)(捕获测试输出)
    │
    └─ 通过 → 快进 (Fast-forward) main,推送,删除分支

File overlap intelligence:

  • Non-overlapping units land in parallel speculatively
  • Overlapping units land one by one, rebasing each time

Eviction recovery: When evicted, the full context (conflicting files, diff, test output) is captured and fed back to the implementer in the next Ralph loop:

## 合并冲突 — 在下次落地前解决

你之前的实现与先落地的另一个单元冲突。
请重构你的更改,以避开下面的冲突文件/行。

{带有 diff 的完整剔除上下文}

Data flow between stages

research.contextFilePath ──────────────────→ plan
plan.implementationSteps ──────────────────→ implement
implement.{filesCreated, whatWasDone} ─────→ test, reviews
test.failingSummary ───────────────────────→ reviews, implement (下一次迭代)
reviews.{feedback, issues} ────────────────→ review-fix → implement (下一次迭代)
final-review.reasoning ────────────────────→ implement (下一次迭代)
evictionContext ───────────────────────────→ implement (合并冲突后)

Worktree Isolation

Each unit runs in an isolated worktree (using jj/Jujutsu, not git):

/tmp/workflow-wt-{unit-id}/

Pipeline stages of the same unitShareone worktree, thereby preserving state (context files, plan files, code changes) throughout the entire process of research → plan → implement → test → review.

Key Design Principles

  1. Deterministic execution — upfront decomposition locks in parallelism and ordering.
  2. Human review at leverage points — the work plan is the highest-leverage intervention point.
  3. Separation of concerns — Each phase is executed by a separate agent in a separate context window.
  4. Conflict recovery with context — The full culling context enables intelligent re-runs rather than blind retries.
  5. Hierarchy-driven depth — Trivial changes skip research/review; large changes get maximum scrutiny.
  6. Resumable workflows — Full state is persisted to SQLite; can be resumed from any point.

When to use Ralphinho vs simple mode

Signal Use Ralphinho Use simple mode
Multiple interdependent units of work Yes No
Need parallel implementation Yes No
High likelihood of merge conflicts Yes No (sequential execution is enough)
Single-file change No Yes (sequential pipeline)
Multi-day project Yes Maybe (continuous-claude)
Spec/RFC already written Yes Maybe
Quickly iterating on something No Yes (NanoClaw or pipeline)

Choosing the right mode

Decision matrix

任务是否为单个专注的更改?
├─ 是 → 顺序流水线 (Sequential Pipeline) 或 NanoClaw
└─ 否 → 是否有书面的规约/RFC?
         ├─ 是 → 是否需要并行实现?
         │        ├─ 是 → Ralphinho (DAG 编排)
         │        └─ 否 → Continuous Claude (迭代式 PR 循环)
         └─ 否 → 是否需要同一事物的多个变体?
                  ├─ 是 → 无限智能体循环 (Infinite Agentic Loop, 规约驱动生成)
                  └─ 否 → 带去杂质阶段的顺序流水线

Mode combinations

These modes combine well:

  1. Sequential pipeline + de-crufting — The most common combination. Each implementation step has a cleanup phase.

  2. Continuous Claude + de-crufting — In each iteration, add a de-crufting instruction to --review-prompt .

  3. Any loop + verification — Before committing, use ECC's /verify command or verification-loop skill as a gate.

  4. Borrow Ralphinho's layered approach in a simple loop — Even in a sequential pipeline, you can assign simple tasks to Haiku and complex tasks to Opus:

    # 简单的格式化修复
    claude -p --model haiku "修复 src/utils.ts 中的导入顺序"
    
    # 复杂的架构更改
    claude -p --model opus "重构 auth 模块以使用策略模式"
    

Anti-Patterns

Common mistakes

  1. Infinite loop with no exit condition — Always set max-runs, max-cost, max-duration, or a completion signal.

  2. No context bridge between iterations — Each claude -p call is brand new. Use SHARED_TASK_NOTES.md or filesystem state to bridge context.

  3. Repeating the same failure — If an iteration fails, don't just retry. Capture the error context and provide it to the next attempt.

  4. Negative instructions instead of a cleanup phase — Don't say "don't do X." Add a separate phase that removes X.

  5. All agents share one context window — For complex workflows, separate concerns into different agent processes. The reviewer should never be the author.

  6. Ignoring file overlap in parallel work — If two parallel agents might edit the same file, you need a merge strategy (sequential landing, rebasing, or conflict resolution).


References

Project Author Link
Ralphinho enitrat Thanks: @enitrat
Infinite Agentic Loop disler Thanks: @disler
Continuous Claude AnandChowdhary Thanks: @AnandChowdhary
NanoClaw ECC In this repository, the /claw command
Verification Loop ECC In this repository, the skills/verification-loop/