Files
knowledge-base/4 - Resources/Claude-Code/Autonomous Loops 自主循环模式.md
2026-04-06 23:27:39 +02:00

11 KiB
Raw Blame History

created, type, tags, source
created type tags source
2026-04-06 resource
resource
claude-code
AI-tools
autonomous-loops
agent-orchestration
ECC
~/.claude/skills/autonomous-loops/SKILL.md

Autonomous Loops 自主循环模式

ECC 提供的让 Claude Code 在无人干预下持续循环工作的模式集合。v1.10.0 中 autonomous-loops 已标记为兼容保留,新的 canonical 名称是 continuous-agent-loop

相关笔记:dmux 多Agent并行编排Everything Claude Code 完整指南Ralphinho RFC-DAG 编排模式Autonomous Agent Harness 自主代理框架ECC 编排替代方案 (orchestrate 迁移)

模式选择流程

单个聚焦的改动?
├─ 是 -> Sequential Pipeline
└─ 否 -> 有写好的 spec/RFC
         ├─ 是 -> 需要并行实现?
         │        ├─ 是 -> Ralphinho (DAG)
         │        └─ 否 -> Continuous PR Loop
         └─ 否 -> 需要同一事物的多个变体?
                  ├─ 是 -> Infinite Agentic Loop
                  └─ 否 -> Sequential + De-Sloppify

模式总览

模式 复杂度 适用场景 上下文管理
Sequential Pipeline 单功能开发、日常 bugfix 每步全新上下文,靠文件系统传递
NanoClaw REPL 交互式探索、持久会话 Markdown 文件累积历史
Infinite Agentic Loop 批量内容生成、多变体 Orchestrator 分配方向
Continuous PR Loop 多天迭代、提升覆盖率 SHARED_TASK_NOTES.md 桥接
De-Sloppify 附加 任何实现步骤后的清理 独立清理 agent
Ralphinho RFC-DAG 大型功能、多 unit 并行 DAG 依赖 + 合并队列

模式 1: Sequential Pipeline

最简单最实用。把开发拆成多个 claude -p 非交互调用,串行执行。

核心原理

  • 每次 claude -p 是全新上下文,无前一步记忆
  • 靠文件系统状态在步骤间传递信息
  • set -e 任何步骤失败就停止

基本模板

#!/bin/bash
set -e

# 实现
claude -p "Read the spec in docs/spec.md. Implement the feature. Write tests first (TDD)."

# 清理 (De-Sloppify)
claude -p "Review all changes. Remove unnecessary tests and defensive checks. Run tests."

# 验证
claude -p "Run full build, lint, test suite. Fix any failures. Do not add new features."

# 提交
claude -p "Create a conventional commit for all staged changes."

进阶技巧

按复杂度选模型:

claude -p --model haiku "Fix import ordering in src/utils.ts"       # 简单
claude -p --model sonnet "Implement caching layer"                   # 中等
claude -p --model opus "Refactor auth module to strategy pattern"    # 复杂

限制工具权限:

claude -p --allowedTools "Read,Grep,Glob" "Audit for security..."   # 只读分析
claude -p --allowedTools "Read,Write,Edit,Bash" "Implement fixes..."  # 可写实现

通过文件传递上下文:

echo "Focus: auth module, API rate limiting" > .claude-context.md
claude -p "Read .claude-context.md for priorities. Work through them."
rm .claude-context.md

实际例子smart-support 加反馈评分功能

#!/bin/bash
set -e

# Step 1: 规划
claude -p "Read docs/DEVELOPMENT-PLAN.md and docs/ARCHITECTURE.md.
Plan a user feedback rating feature:
- Backend: POST /api/feedback, store in PostgreSQL
- Frontend: thumbs up/down on AI reply
- Analytics: feedback stats query
Write plan to docs/phases/feedback-plan.md"

# Step 2: 后端 TDD
claude -p "Read docs/phases/feedback-plan.md.
Create backend/app/feedback/models.py and router.py.
Write tests FIRST in backend/tests/unit/test_feedback.py.
Follow patterns from backend/app/analytics/.
Run pytest --cov=app."

# Step 3: 前端
claude -p "Read docs/phases/feedback-plan.md.
Create FeedbackButton component. Wire into chat message.
Call POST /api/feedback on click."

# Step 4: 清理
claude -p "Review git diff. Remove test slop, console.log, commented code.
Run pytest --cov=app."

# Step 5: 验证 + 提交
claude -p "Run pytest --cov=app --cov-report=term-missing. Fix failures."
claude -p "Stage feedback-related files. Commit: feat: add user feedback rating"

模式 2: NanoClaw REPL

ECC 内置的持久会话 REPL对话历史存储为 Markdown。

启动

node ~/.claude/scripts/claw.js

# 带名称和技能
CLAW_SESSION=my-project CLAW_SKILLS=tdd-workflow,security-review node ~/.claude/scripts/claw.js

内置命令

命令 功能
/model 切换模型
/load 动态加载 skill
/branch 会话分支
/search 跨会话搜索
/compact 压缩历史
/export 导出为 md/json/txt
/metrics 会话指标

vs Sequential Pipeline

NanoClaw Sequential Pipeline
交互式
上下文累积 每轮增长 每步全新
会话持久化 内置 手动
CI/CD 集成
适合 探索性工作 脚本自动化

模式 3: Infinite Agentic Loop

按 spec 批量并行生成多个变体。Orchestrator 读 spec分配不同创意方向给 N 个子 agent。

原理

  1. Orchestrator 读取 specification 文件
  2. 扫描 output 目录找到最高迭代号
  3. 并行启动 N 个子 agent每个分配不同的创意方向和迭代号
  4. infinite 模式下以 3-5 个为一波持续生成

设置

创建 .claude/commands/infinite.md

Parse the following arguments from $ARGUMENTS:
1. spec_file -- path to the specification markdown
2. output_dir -- where iterations are saved
3. count -- integer 1-N or "infinite"

PHASE 1: Read and deeply understand the specification.
PHASE 2: List output_dir, find highest iteration number. Start at N+1.
PHASE 3: Plan creative directions -- each agent gets a DIFFERENT theme.
PHASE 4: Deploy sub-agents in parallel (Task tool).
PHASE 5 (infinite mode): Loop in waves of 3-5 until context is low.

调用

/project:infinite specs/component-spec.md src/ 5          # 生成5个
/project:infinite specs/component-spec.md src/ infinite    # 持续生成

批次策略

数量 策略
1-5 全部同时
6-20 每批5个
infinite 每波3-5个逐步提升复杂度

关键:通过分配确保唯一性

不要依赖 agent 自行区分。Orchestrator 显式分配每个 agent 的创意方向和迭代号,避免重复。


模式 4: Continuous PR Loop

生产级自动 PR 循环:建分支 -> 实现 -> 建 PR -> 等 CI -> 合并 -> 循环。

循环流程

1. Create branch (continuous-claude/iteration-N)
2. Run claude -p with enhanced prompt
3. (Optional) Reviewer pass
4. Commit changes
5. Push + create PR (gh pr create)
6. Wait for CI checks (poll gh pr checks)
7. CI failure? -> Auto-fix pass
8. Merge PR
9. Return to main -> repeat

使用

# 基本10轮迭代
continuous-claude --prompt "Add unit tests for untested functions" --max-runs 10

# 限制花费
continuous-claude --prompt "Fix all linter errors" --max-cost 5.00

# 限制时间
continuous-claude --prompt "Improve test coverage" --max-duration 8h

# 带 review pass
continuous-claude \
  --prompt "Add authentication feature" \
  --max-runs 10 \
  --review-prompt "Run npm test && npm run lint, fix any failures"

# 并行 (worktree 隔离)
continuous-claude --prompt "Add tests" --worktree tests-worker &
continuous-claude --prompt "Refactor" --worktree refactor-worker &
wait

跨迭代上下文SHARED_TASK_NOTES.md

每轮开始读、结束写,桥接 claude -p 的无记忆问题:

## Progress
- [x] app/feedback/ - 65% -> 92% (iteration 1)
- [x] app/graph.py - 70% -> 88% (iteration 2)
- [ ] app/openapi/ - 68% (next target)

## Overall: 82% -> 91%

CI 失败自动恢复

自动 gh run view 查日志 -> 修代码 -> 推送 -> 重新等 CI最多 --ci-retry-max 次)。

完成信号

continuous-claude \
  --prompt "Fix all bugs" \
  --completion-signal "CONTINUOUS_CLAUDE_PROJECT_COMPLETE" \
  --completion-threshold 3   # 连续3轮"完成"才停

关键配置

Flag 功能
--max-runs N 最多 N 轮
--max-cost $X 花费上限
--max-duration 2h 时间上限
--merge-strategy squash squash/merge/rebase
--worktree <name> 并行用 worktree
--disable-commits 干跑模式
--review-prompt "..." 每轮加 review
--ci-retry-max N CI 失败自动修复次数

实际例子:提升 smart-support 测试覆盖率

continuous-claude \
  --prompt "Read backend/tests/ and find modules with lowest coverage.
    Write unit tests for the least-covered module.
    Use pytest patterns from conftest.py.
    Run pytest --cov=app --cov-report=term-missing.
    Update SHARED_TASK_NOTES.md with progress." \
  --max-runs 8 \
  --max-cost 10.00 \
  --review-prompt "Run pytest --cov=app. If coverage < 95%, note gaps." \
  --completion-signal "COVERAGE_TARGET_MET" \
  --completion-threshold 2

模式 5: De-Sloppify (附加清理 Pass)

不是独立模式,而是加在任何实现步骤后的清理。

问题

LLM 做 TDD 时过度测试:测类型系统能不能工作、加不必要的防御性检查。

错误做法

在提示里说"不要测类型系统" -> 模型变畏首畏尾,跳过正常测试。

正确做法

让实现步骤自由发挥,然后加独立清理 agent

for feature in "${features[@]}"; do
  claude -p "Implement $feature with TDD."
  claude -p "Cleanup: remove test/code slop, run tests."
  claude -p "Run build + lint + tests. Fix failures."
  claude -p "Commit: feat: add $feature"
done

核心洞察:两个专注的 agent 优于一个受约束的 agent。


ECC 内置命令

启动循环

/ecc:loop-start sequential           # Sequential 模式
/ecc:loop-start continuous-pr        # PR 循环模式
/ecc:loop-start rfc-dag              # Ralphinho 模式
/ecc:loop-start infinite             # 无限生成模式

/ecc:loop-start sequential --mode safe   # safe = 严格质量门
/ecc:loop-start sequential --mode fast   # fast = 减少检查

监控

/ecc:loop-status              # 查看当前循环状态
/ecc:loop-status --watch      # 持续监控

故障恢复

1. 冻结循环
2. 运行 /harness-audit
3. 缩小范围到失败的 unit
4. 用明确的验收标准重试

反模式

反模式 问题 正确做法
无退出条件的无限循环 烧钱 始终设 max-runs/max-cost/max-duration
迭代间无上下文桥梁 重复劳动 用 SHARED_TASK_NOTES.md
对同一失败盲目重试 浪费 捕获错误上下文给下次
用否定指令代替清理 pass 质量下降 De-Sloppify 独立 pass
所有 agent 在同一上下文 自我审查偏差 每阶段独立进程
并行任务编辑同一文件 冲突 git worktree 隔离

组合使用

  1. Sequential + De-Sloppify -- 最常见,每个实现步骤后加清理
  2. Continuous PR + De-Sloppify -- --review-prompt 里加清理指令
  3. 任何循环 + Verification -- 提交前用 /ecc:verify 做质量门
  4. 简单循环里用分级模型 -- 简单任务 Haiku复杂任务 Opus