mcpField
S
skill-iterative-loop

skill-iterative-loop

github.com/nyldnAgent 工作流4.3k57 次安装今天更新
代码仓库

关于 skill-iterative-loop

skill-iterative-loop 是面向 Codex CLI 的有界迭代执行技能。它设定目标、成功条件并跟踪进展,还能检测停滞,并提供基于指标的验证与回滚流程。

主要功能

  1. 01设定目标和可衡量的退出条件
  2. 02限制迭代次数并跟踪进展
  3. 03检测重复结果和循环
  4. 04应用自我调节阈值
  5. 05支持指标验证与回滚

适用场景

  1. 01通过有限轮次改进代码或测试
  2. 02修改尝试方式后重试操作
  3. 03针对指定指标进行优化
  4. 04进展停滞时停止并重新评估

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/nyldn/claude-octopus --skill skill-iterative-loop

安装后在 Claude Code 中输入/skill-iterative-loop确认已加载。

附带文件agents/openai.yaml

详细介绍

宿主:Codex CLI — 此技能原为 Claude Code 设计,后适配至 Codex。 交叉引用命令在 Codex 中使用已安装的技能名称,而非 /octo:* 斜杠命令。 使用当前活动的 Codex shell 和子 Agent 工具。在当前会话未明确提供某个提供商、模型或宿主子 Agent 前,不得声称其可用。 宿主工具的对应项请参见 skills/blocks/codex-host-adapter.md。

迭代循环执行

概述

采用明确的目标、退出条件和进度跟踪,系统地进行迭代执行。

核心原则: 定义目标 → 设置最大迭代次数 → 执行 → 评估 → 继续循环或完成。

何时使用

在用户希望进行以下操作时使用此技能:

  • 多次执行任务并逐步完善
  • 循环执行,直到满足某个条件
  • 迭代改进某些内容(代码、测试、性能)
  • 修改后重试操作
  • 分轮逐步增强

请勿用于:

  • 单次执行(“运行一次测试”)
  • 手动逐步操作
  • 没有上限的无限循环
  • 简单的重试逻辑(请使用 skill-debug)

流程

阶段 1:循环设置
步骤 1:了解意图
**Loop Intent:**

Goal: [what should be achieved]
Success criteria: [how do we know we're done]
Max iterations: [safety limit]
Per-iteration tasks: [what to do each loop]
步骤 2:明确参数

如果不明确,请使用 AskUserQuestion:

  • 最大迭代次数: 最多执行多少次?
  • 成功条件: 满足什么条件时可以提前停止?
  • 每轮操作: 每一轮具体要做什么?
  • 失败处理: 如果一直无法成功,该怎么办?
步骤 3:安全检查
**Safety Validation:**

- [ ] Max iterations defined (no infinite loops)
- [ ] Success condition is measurable
- [ ] Each iteration makes progress
- [ ] Failure exit strategy exists
- [ ] User aware of potential duration

未定义最大迭代次数时,绝不继续。

阶段 2:循环执行
步骤 1:初始化循环
**Starting Iterative Loop**

Goal: [description]
Max iterations: [N]
Success criteria: [condition]


### Iteration 1 / [N]
步骤 2:执行迭代

每轮迭代:

**Iteration [current] / [max]**

**Actions:**
1. [Action 1]
   → [result/output]
2. [Action 2]
   → [result/output]
3. [Action 3]
   → [result/output]

**Evaluation:**
- Success criteria met? [Yes/No]
- Progress made? [Yes/No]
- Issues found: [list any issues]

**Status:** [Continue/Success/Need intervention]

步骤 3:跟踪进度

使用任务计划工具跟踪迭代:

Iteration Progress:
✓ Iteration 1 - [what was done]
✓ Iteration 2 - [what was done]
⚙️ Iteration 3 - [in progress]
- Iteration 4 - [pending]
- Iteration 5 - [pending]
阶段 3:退出条件
退出条件 1:成功
🎉 **Success! Loop complete.**

**Goal achieved:** [description]
**Iterations used:** [N] / [max]

**Final state:**
[description of what was achieved]

**Summary of iterations:**
1. Iteration 1: [what happened]
2. Iteration 2: [what happened]
...
N. Iteration N: [what happened] ✓ Success
退出条件 2:达到最大迭代次数
⚠️ **Max iterations reached without full success**

**Iterations completed:** [max]
**Goal:** [description]
**Current state:** [how close we got]

**Progress made:**
- [Improvement 1]
- [Improvement 2]
- [Improvement 3]

**Remaining issues:**
- [Issue 1]
- [Issue 2]

**Options:**
1. Accept current state (substantial progress made)
2. Continue with [N] more iterations
3. Change approach (current method may not work)

What would you like to do?
退出条件 3:未检测到进展
🛑 **Stopping early: No progress detected**

**Iteration:** [N] / [max]
**Reason:** Last [M] iterations showed no improvement

**Analysis:**
This suggests the current approach may be fundamentally flawed.

**Recommendation:**
Rather than continue looping, let's:
1. Analyze why no progress is being made
2. Consider alternative approaches
3. Re-evaluate the goal or success criteria

Shall we pause and reassess?

常见模式

模式 1:带测试的循环
User: "Loop around 5 times auditing, enhancing, testing, until it's done"

Implementation:

**Loop Goal:** Code passes all quality gates
**Max Iterations:** 5
**Per-iteration:**
1. Audit code for issues
2. Enhance/fix identified issues
3. Run tests
4. Check if all pass

**Success:** All tests pass + no issues found

Execute:
Iteration 1:
- Audit → Found 8 issues
- Fix → Fixed 8 issues
- Test → 2 tests still failing
- Continue

Iteration 2:
- Audit → Found 2 new issues from fixes
- Fix → Fixed 2 issues
- Test → All tests pass ✓
- Success! Stopping early (2/5 iterations used)
模式 2:性能优化循环
User: "Keep trying optimizations until we hit < 100ms response time"

Implementation:

**Loop Goal:** Response time < 100ms
**Max Iterations:** 10
**Per-iteration:**
1. Measure current performance
2. Identify bottleneck
3. Apply optimization
4. Re-measure

**Success:** Response time < 100ms

Execute:
Iteration 1: 450ms → Cache database queries → 280ms (Continue)
Iteration 2: 280ms → Add index to frequent query → 150ms (Continue)
Iteration 3: 150ms → Implement response compression → 85ms (Success!)
模式 3:带退避的重试
User: "Try deploying, retry up to 3 times if it fails"

Implementation:

**Loop Goal:** Successful deployment
**Max Iterations:** 3
**Per-iteration:**
1. Attempt deployment
2. Check status
3. If failed, wait before retry

**Success:** Deployment succeeds

Execute:
Iteration 1: Deploy → Failed (API timeout) → Wait 10s
Iteration 2: Deploy → Failed (API timeout) → Wait 20s
Iteration 3: Deploy → Success ✓
模式 4:渐进式完善
User: "Iterate 4 times improving the error messages based on user feedback"

Implementation:

**Loop Goal:** Error messages meet clarity standard
**Max Iterations:** 4
**Per-iteration:**
1. Review current error messages
2. Identify confusing ones
3. Rewrite for clarity
4. Evaluate against criteria

**Success:** All messages rated 8+/10 for clarity

Execute each iteration with progressive improvement

与其他技能集成

与 skill-debug 配合
Loop for debugging:
"Keep debugging until all tests pass, max 5 tries"

Each iteration:
- Use skill-debug to investigate failure
- Apply fix
- Re-run tests
- Evaluate
与 skill-audit 配合
Loop for comprehensive checking:
"Loop 3 times auditing different aspects"

Iteration 1: Audit security
Iteration 2: Audit performance
Iteration 3: Audit accessibility
与 skill-tdd 配合
Loop for TDD cycles:
"Do 5 red-green-refactor cycles"

Each iteration:
- Write failing test (red)
- Make it pass (green)
- Refactor (refactor)
- Evaluate and continue

最佳实践

1. 始终定义最大迭代次数

良好示例:

Loop max 5 times trying to fix the issue

危险示例:

Keep trying until it works
(What if it never works? Infinite loop!)
2. 制定可衡量的成功标准

良好示例:

Success: All 15 tests pass AND code coverage > 80%

较差示例:

Success: Code looks better
(Too subjective)
3. 让进展清晰可见
**Progress Tracking:**

Iteration 1: 5/15 tests passing
Iteration 2: 10/15 tests passing
Iteration 3: 13/15 tests passing
Iteration 4: 15/15 tests passing ✓
4. 成功后尽早退出

目标达成后,不要继续循环:

**Iteration 2/5:** All tests pass!

Stopping early - goal achieved.
No need to continue to iteration 3.
5. 检测停滞
Iteration 4: 10/15 tests passing
Iteration 5: 10/15 tests passing
Iteration 6: 10/15 tests passing

⚠️ No progress in 3 iterations - stopping to reassess approach

危险信号——请勿这样做

操作危险原因
未设置最大迭代次数可能会无限循环
成功标准含糊不知道何时停止
未跟踪进度无法判断是否取得进展
忽视停滞在无效方法上浪费时间
每轮执行相同操作如果不起作用,就需要换一种方法

策略轮换

如果策略轮换钩子触发,请立即更改方法。不要重试相同的方法。下一次尝试前,请说明你会如何改变做法。连续多次使用同一工具失败后,钩子就会触发——这是一个强烈信号,表明当前方法从根本上行不通,而不只是稍有偏差。

自我调节(强制)

每个迭代循环都必须跟踪一个会累积危险信号的自我调节分数。这可以防止 Agent 在没有实际进展的情况下不断“修复”问题,导致循环失控。

滑动窗口卡住检测

在头脑中维护一个包含最近 10 次迭代(若运行次数不足 10 次,则包含已有迭代)的窗口。每次迭代后,检查是否存在重复模式:

单一状态重复: 是否连续 3 次或更多次出现相同结果或错误?

  • 相同的测试失败、相同的错误消息、修改了相同的文件 → 卡住

多步循环检测: 是否出现 A→B→A→B 的振荡?

  • 第 N 次迭代修改文件 X,第 N+1 次修改文件 Y,第 N+2 次又修改文件 X,第 N+3 次又修改文件 Y → 检测到循环
  • 比较各次迭代中修改的文件和错误消息,而不仅仅是成功或失败

首次检测到时: 向用户说明该模式。明确承认问题后,尝试一次诊断性重试:“这个模式已经重复出现——接下来我会换一种做法:[具体改动]。”

第二次检测到时: 立即停止。 显示检测到的循环,并询问用户是要采用完全不同的方法继续,还是停止。

WTF 可能性评分

从 0% 开始累计评分。每发生一项事件,评分都会增加。

默认权重(可通过 ~/.claude-octopus/loop-config.conf 覆盖):

事件评分影响
回退(git revert、撤销、回滚)+15%
修改与声明目标无关的文件+20%
修复需要更改 3 个以上文件+5%
第 15 次修复尝试之后每额外尝试一次修复 +1%
剩余问题全部为低严重性+10%

如果 WTF 评分超过 20%: 立即停止。 显示:

  1. 当前 WTF 评分及其增加原因
  2. 迄今已完成的工作
  3. 询问用户:“要换一种方法继续,还是就此停止?”

硬性上限: 最多 50 次迭代,不论评分或进度如何。无一例外。

可配置权重

循环开始时,检查 ~/.claude-octopus/loop-config.conf 是否存在。如果存在,读取其中的键值对并使用这些值替代默认值。格式:

# Loop Self-Regulation Configuration
WINDOW_SIZE=10
REVERT_PENALTY=15
UNRELATED_FILES_PENALTY=20
LARGE_FIX_PENALTY=5
AFTER_FIX_15_PENALTY=1
ALL_LOW_SEVERITY_PENALTY=10
WTF_THRESHOLD=20
HARD_CAP=50
STUCK_THRESHOLD=3

如果文件不存在,则使用上方所示的默认值。用户可以创建此文件,为其工作流调整灵敏度。

如何跟踪

这不需要外部工具。在循环过程中进行心中跟踪即可:

  • 每次迭代后,记下修改的文件、结果以及是否发生回退
  • 与最近迭代的滑动窗口进行比较
  • 累计 WTF 评分
  • 在每次迭代摘要中同时报告迭代次数和自我调节评分:
Iteration 5/20 | Self-regulation: 10% (1 revert, 0 unrelated files)
与策略轮换的交互

策略轮换钩子和自我调节机制相辅相成:

  • 策略轮换会在连续的工具失败时触发(同一工具、相同错误)
  • 自我调节会在结果出现模式时触发(循环、回退、范围蔓延)
  • 两者可以独立触发。如果两者同时触发,则停止——循环肯定已卡住。

安全机制

1. 迭代次数上限
MAX_ITERATIONS = user_specified or 10  # Always have a limit
HARD_CAP = 50  # Absolute maximum regardless of user setting
2. 自我调节评分
Track WTF score across iterations.
If score > 20%: STOP and ask user.
3. 滑动窗口检测
Track last 10 iterations.
If repeated pattern detected twice: STOP and ask user.
4. 进度检测
If last 3 iterations show same result:
  → Stop and ask user
5. 时间限制(适用于长时间运行的操作)
If total time > 30 minutes:
  → Checkpoint progress
  → Ask user if should continue
6. 用户检查点
Every N iterations:
  → Show progress
  → Ask if should continue or adjust approach

快速参考

模式最大迭代次数成功标准提前退出
测试直至通过5-10所有测试均通过是
性能优化10-20指标 < 目标值是
退避重试3-5操作成功是
渐进式改进3-7达到质量阈值可能
全面审计3-5覆盖所有方面否

指标验证模式

当用户指定指标命令时,切换到机械式指标验证模式。此模式以自动化测量、基于 git 的实验和回归时自动回滚,取代主观评估。

未指定指标时,回退到标准循环行为(见上文)。

核心原则
  • 每次迭代只做一项更改(原子性)——绝不合并多个互不相关的更改
  • 仅进行机械验证——不做主观的“看起来不错”判断;由指标命令决定
  • 指标回退时自动还原——如果指标变差,则运行 git revert HEAD --no-edit
  • 简单优先——指标结果相同且代码更少时,保留更简单的版本
  • Git 即记忆——每项实验都必须在验证前以 experiment: 前缀提交
  • 保护命令也必须通过——即使指标有所改善,只要保护命令失败,就还原更改
参数
参数格式必填说明
MetricMetric: <shell command>是(此模式下)stdout 输出一个数字(指标值)的命令
DirectionDirection: higher|lower是指标值越高或越低越好
GuardGuard: <shell command>否更改要保留,该命令必须以 0 退出;在指标命令之后运行
IterationsIterations: N否最大迭代次数(默认:不设上限,持续运行直到中断)
实验日志

所有结果均以 JSONL 格式记录到 .claude-octopus/experiments/<YYYY-MM-DD>.jsonl。

每行都是一个 JSON 对象:

{"iteration": 1, "timestamp": "2026-03-21T14:30:00Z", "metric": 72.5, "best": 72.5, "status": "kept", "description": "Add index to users table", "commit": "abc1234"}

字段:

  • iteration — 迭代次数(从 1 开始;迭代 0 为基准值)
  • timestamp — ISO 8601 时间戳
  • metric — 指标命令测得的值
  • best — 迄今为止的最佳指标值
  • status — "kept"(有所改善)、"reverted"(出现回退)或 "error"(指标命令或保护命令崩溃)
  • description — 对所做更改的一行摘要
  • commit — 实验提交的简短 Git SHA(可能还原之前)
执行约定

每次迭代都必须严格按照以下顺序执行。不得跳过或调整任何步骤。

迭代 0:建立基准值
  1. 如果实验日志目录不存在,则创建该目录:
    mkdir -p .claude-octopus/experiments
    
  2. 检查是否已有实验日志——如果 .claude-octopus/experiments/<today>.jsonl 存在,则读取日志以确定当前最佳指标值和迭代次数。从下一次迭代编号继续。
  3. 运行指标命令并捕获输出的数字。这就是基准值。
  4. 记录基准值:
    {"iteration": 0, "timestamp": "...", "metric": <baseline>, "best": <baseline>, "status": "baseline", "description": "Baseline measurement", "commit": "<current HEAD short SHA>"}
    
  5. 向用户报告基准值。
后续每轮迭代(1..N)

步骤 1:检查状态。 阅读实验日志(.claude-octopus/experiments/<today>.jsonl),查看 git 历史记录(git log --oneline -10),确定已尝试的内容、奏效的内容以及失败的内容。

步骤 2:选择下一项改动。 根据奏效、失败或尚未尝试的内容,确定一项重点改动。请勿将多个无关改动合并在一起。

步骤 3:进行改动。 只实现一项原子性改动。

步骤 4:验证前先进行 Git 提交。 使用 experiment: 前缀提交:

git add -A && git commit -m "experiment: <one-line description of the change>"

这样无论结果如何,每项实验都会记录在 git 历史记录中。

步骤 5:运行机械验证。 执行指标命令并记录数值结果。

步骤 6:评估并采取行动。

  • 如果指标有所改善(Direction=higher 时数值更高,Direction=lower 时数值更低):

    • 如果指定了 Guard 命令,现在运行该命令。
      • 如果 Guard 通过(退出码为 0)→ 保留此提交。更新最佳指标。
      • 如果 Guard 失败(退出码非零)→ 还原:git revert HEAD --no-edit。将状态记录为 "reverted"。
    • 如果没有 Guard → 保留此提交。更新最佳指标。
  • 如果指标保持不变:

    • 检查此改动是否降低了代码复杂度或缩减了代码量。如果代码更简单 → 保留(优先选择简洁)。
    • 否则 → 还原:git revert HEAD --no-edit。将状态记录为 "reverted"。
  • 如果指标变差:

    • 还原:git revert HEAD --no-edit。将状态记录为 "reverted"。
  • 如果指标命令崩溃(退出码非零,且没有数值输出):

    • 尝试快速修复(仅尝试一次)。如果修复成功,重新测量。
    • 如果仍然无法运行 → 还原:git revert HEAD --no-edit。将状态记录为 "error"。

步骤 7:记录结果。 将 JSONL 条目追加到 .claude-octopus/experiments/<today>.jsonl。

步骤 8:报告本轮迭代摘要。 显示:

Iteration N: <description>
  Metric: <value> (best: <best>) — <kept|reverted|error>

步骤 9:重复 — 转到下一轮迭代的步骤 1,除非:

  • 达到迭代次数上限 → 停止并报告最终摘要
  • 用户中断 → 停止并报告最终摘要
恢复行为

如果今天的实验日志已存在:

  1. 阅读日志,确定最后一轮迭代的编号和当前最佳指标值
  2. 从下一轮迭代开始
  3. 使用记录的最佳值作为比较基准
  4. 这样便可在不同会话中停止并恢复实验
最终摘要

循环结束时(迭代次数用尽或用户停止),报告:

Experiment Complete
  Iterations: N
  Baseline: <initial metric>
  Final best: <best metric>
  Improvement: <delta> (<percentage>%)
  Kept: K changes, Reverted: R changes, Errors: E
示例
/octo:loop Metric: npm test -- --coverage | grep 'All files' | awk '{print $(10)}' Direction: higher Guard: npm test Iterations: 20

此流程将:

  1. 测量基线代码覆盖率
  2. 每轮迭代:进行一项改动,以 experiment: ... 为前缀提交,并测量代码覆盖率
  3. 如果覆盖率提高且 npm test 通过 → 保留
  4. 如果覆盖率下降或测试失败 → git revert HEAD --no-edit
  5. 经过 20 轮迭代后,报告总提升幅度

核心要点

Iterative loop → Clear goal + Max iterations + Progress tracking + Exit strategy
Otherwise → Infinite loops + Wasted effort + Unclear when done

明确目标。设定上限。追踪进展。知道何时停止。

评论

支持 Markdown