circuit-breaker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Overview

概述

The circuit-breaker skill is a safety mechanism that prevents infinite loops, resource exhaustion, and accidental destruction during autonomous development. It operates at the loop level (complementing
resilient-execution
which operates at the task level). Without circuit-breaker protection, autonomous loops can waste hours on stagnant problems, exhaust API limits, or accidentally destroy configuration files. This skill enforces hard boundaries that keep autonomous operations productive and safe.
Announce at start: "Circuit breaker is active — monitoring for stagnation, rate limits, and file protection."

circuit-breaker 技能是一种安全机制,可防止自主开发过程中出现无限循环、资源耗尽和意外破坏。它运行在循环层面(作为运行在任务层面
resilient-execution
的补充)。如果没有circuit-breaker保护,自主循环可能会在停滞的问题上浪费数小时、耗尽API限额,或是意外损坏配置文件。本技能会强制执行硬性边界,保障自主操作高效、安全运行。
启动时播报: "熔断器已激活——正在监控停滞状态、速率限制和文件保护规则。"

Phase 1: Circuit State Check

第1阶段:熔断器状态检查

Before each loop iteration, check the current circuit state:
+-----------+     threshold     +-----------+     cooldown     +------------+
|  CLOSED   |----exceeded----->|   OPEN    |----elapsed------>| HALF-OPEN  |
|  (normal) |                  |  (halted) |                  |  (probe)   |
+-----------+                  +-----------+                  +-----+------+
     ^                                                              |
     |                          success                             |
     +--------------------------------------------------------------+
     |                          failure                             |
     |                    +-----------+                              |
     +--------------------+   OPEN    |<----------------------------+
                          +-----------+
StateMeaningAction
CLOSEDNormal operationExecute iteration, monitor all thresholds
OPENHalted due to threshold breachReport status, wait for cooldown, or escalate
HALF-OPENProbing after cooldownAllow ONE iteration. If success: close. If failure: re-open.
STOP: Check circuit state BEFORE executing any loop iteration. Do NOT execute if circuit is OPEN.

每次循环迭代前,检查当前熔断器状态:
+-----------+     threshold     +-----------+     cooldown     +------------+
|  CLOSED   |----exceeded----->|   OPEN    |----elapsed------>| HALF-OPEN  |
|  (normal) |                  |  (halted) |                  |  (probe)   |
+-----------+                  +-----------+                  +-----+------+
     ^                                                              |
     |                          success                             |
     +--------------------------------------------------------------+
     |                          failure                             |
     |                    +-----------+                              |
     +--------------------+   OPEN    |<----------------------------+
                          +-----------+
状态含义执行操作
CLOSED正常运行执行迭代,监控所有阈值
OPEN因阈值触发已暂停上报状态,等待冷却,或升级问题
HALF-OPEN冷却后试探运行仅允许执行1次迭代。成功则关闭熔断器,失败则重新开启
停止操作:执行任何循环迭代前必须先检查熔断器状态。如果熔断器处于OPEN状态,禁止执行迭代。

Phase 2: Stagnation Detection

第2阶段:停滞检测

Monitor these thresholds continuously during autonomous operation:
ConditionThresholdDetection MethodAction
No progress3 consecutive loops with zero meaningful changesTrack files modified + tasks completed per loopOPEN circuit
Identical errors5 consecutive loops producing the same errorCompare error messages across iterationsOPEN circuit
Output decline70% decline in output volume across iterationsCompare output line count across last 3 iterationsOPEN circuit
Permission denials3 consecutive tool permission failuresTrack permission errorsOPEN circuit
Test fix loop>80% of effort spent on test fixes onlyTrack work type per iterationOPEN circuit, investigate root cause
Circular approachSame 2-3 approaches alternating without resolutionTrack approach historyOPEN circuit
自主运行过程中持续监控以下阈值:
触发条件阈值检测方法执行操作
无进展连续3次循环无任何有效变更追踪每次循环的文件修改量+任务完成量开启熔断器
相同错误连续5次循环返回相同错误对比不同迭代的错误信息开启熔断器
输出下降迭代间输出量下降70%对比最近3次迭代的输出行数开启熔断器
权限拒绝连续3次工具调用权限失败追踪权限错误开启熔断器
测试修复循环超过80%的工作量仅用于修复测试追踪每次迭代的工作类型开启熔断器,排查根因
循环方案交替使用2-3种相同方案仍未解决问题追踪方案历史开启熔断器

Stagnation Scoring

停滞评分规则

Each iteration, compute a progress score:
IndicatorScore
New test passing that was previously failing+3
Task marked complete+5
File modified with meaningful changes+1
Build/lint error resolved+2
Same error as previous iteration-2
No files modified-3
Reverted previous changes-1
Threshold: If cumulative score across 3 iterations is negative, OPEN the circuit.
STOP: If any threshold is breached, OPEN the circuit immediately. Do NOT attempt "one more try."

每次迭代计算一次进展评分:
指标得分
此前失败的测试新增通过+3
任务标记为完成+5
文件被有效修改+1
构建/语法错误被修复+2
和上一次迭代返回相同错误-2
无文件被修改-3
回滚了之前的修改-1
阈值: 如果3次迭代的累计得分为负,开启熔断器。
停止操作:一旦触发任何阈值,立即开启熔断器。禁止尝试「再试一次」。

Phase 3: Recovery Protocol

第3阶段:恢复协议

When the circuit opens, follow this recovery sequence:
熔断器开启后,遵循以下恢复流程:

Cooldown Period

冷却期

  • Default: 30 minutes before retry
  • Purpose: Prevents rapid cycling through the same failing state
  • After cooldown: Circuit enters HALF-OPEN state
  • 默认值: 重试前等待30分钟
  • 目的: 防止短时间内反复进入相同的失败状态
  • 冷却结束后: 熔断器进入HALF-OPEN状态

HALF-OPEN Behavior

HALF-OPEN状态规则

  1. Allow exactly ONE iteration to execute
  2. If successful (positive progress score): Close circuit, resume normal operation
  3. If failed (same stagnation pattern): Re-open circuit, double the cooldown timer
  1. 仅允许执行1次迭代
  2. 如果执行成功(进展评分为正):关闭熔断器,恢复正常运行
  3. 如果执行失败(出现相同停滞模式):重新开启熔断器,冷却时间翻倍

Recovery Strategy Decision Table

恢复策略决策表

Stagnation TypeStrategy 1Strategy 2Strategy 3Strategy 4
No progress (stuck on same task)Regenerate plan with fresh analysisBreak stuck task into 3+ subtasksSkip to next task, return laterEscalate to user
Identical errors (same error repeating)Change approach entirelyCheck if error is environmentalSearch for known issue/workaroundEscalate with error log
Test fix loop (tests keep breaking)Review test assumptionsCheck if implementation approach is flawedSimplify implementation scopeEscalate with test analysis
Circular approach (alternating same fixes)Step back and re-analyze root causeTry approach NOT yet attemptedReduce scope to minimal working versionEscalate with approach history
STOP: After recovery, monitor the next 3 iterations closely. If stagnation recurs, escalate immediately.

停滞类型策略1策略2策略3策略4
无进展(卡在同一任务)基于全新分析重新生成方案将卡住的任务拆分为3个以上子任务跳过当前任务,后续再处理升级通知用户
相同错误(重复返回同一错误)完全更换解决思路检查是否为环境导致的错误搜索已知问题/解决方案附带错误日志升级问题
测试修复循环(测试持续失败)复查测试假设是否合理检查实现方案是否存在缺陷缩小实现范围附带测试分析升级问题
循环方案(交替使用相同修复逻辑)退回步骤重新分析根因尝试从未使用过的方案缩减范围到最小可运行版本附带方案历史升级问题
停止操作:恢复后密切监控接下来的3次迭代。如果再次出现停滞,立即升级问题。

Phase 4: Rate Limiting

第4阶段:速率限制

Track and enforce API usage limits:
ParameterDefaultPurpose
MAX_CALLS_PER_HOUR100Prevents API overuse
Reset windowHourly (rolling)Automatic counter reset
Countdown displayActiveShows remaining calls before limit
追踪并强制执行API使用限额:
参数默认值目的
MAX_CALLS_PER_HOUR100防止API过度调用
重置窗口小时级(滚动计算)自动重置计数器
倒计时展示开启展示限额耗尽前的剩余调用次数

Rate Limit Behavior

速率限制规则

  1. Track API calls per rolling hour
  2. At 80% of limit: display warning, prioritize remaining calls
  3. At 100% of limit: pause execution, display countdown to reset
  4. Never exceed limit — wait for reset window
  1. 按滚动小时追踪API调用量
  2. 达到限额80%时:展示警告,优先分配剩余调用额度
  3. 达到100%限额时:暂停执行,展示重置倒计时
  4. 绝对禁止超出限额——等待窗口重置后再继续

Three-Layer Timeout Detection

三层超时检测

For long-running operations (especially API calls with extended limits):
LayerDetectionFallback
1. Timeout guardExit code 124 or timeout signalCapture partial output, log what completed
2. JSON validationParse response structureAttempt text extraction from raw response
3. Text fallbackRaw output captureLog everything, report for human review

针对长时间运行的操作(尤其是有延长限额的API调用):
层级检测逻辑降级方案
1. 超时防护退出码124或超时信号捕获部分输出,记录已完成的内容
2. JSON校验解析响应结构尝试从原始响应中提取文本内容
3. 文本兜底原始输出捕获记录所有内容,上报供人工审核

Phase 5: File Protection

第5阶段:文件保护

<HARD-GATE> Configuration files must NEVER be deleted during autonomous operations. This is non-negotiable. </HARD-GATE>
<HARD-GATE> 自主运行过程中绝对不得删除配置文件,这是不可协商的硬性规则。 </HARD-GATE>

Protected Paths

受保护路径

PathTypeWhy Protected
.ralph/
DirectoryLoop state and configuration
.ralphrc
FileRalph configuration
IMPLEMENTATION_PLAN.md
FileCurrent plan — source of truth for loop
AGENTS.md
FileAgent definitions
specs/
DirectorySpecifications — source of truth for features
.claude/
DirectoryClaude Code configuration
CLAUDE.md
FileAgent operating manual
memory/
DirectoryPersisted learnings across sessions
路径类型保护原因
.ralph/
目录循环状态和配置信息
.ralphrc
文件Ralph配置文件
IMPLEMENTATION_PLAN.md
文件当前计划——循环的可信来源
AGENTS.md
文件Agent定义
specs/
目录需求规范——功能的可信来源
.claude/
目录Claude Code配置
CLAUDE.md
文件Agent操作手册
memory/
目录跨会话持久化的学习内容

Protection Mechanisms

保护机制

MechanismHow It WorksWhen It Triggers
Allowlist enforcementOnly permitted tools can modify protected filesBefore any file write to protected path
Integrity validationCheck protected files exist after each iterationEnd of every loop iteration
Pre-operation checksVerify protected files before destructive operationsBefore
rm
,
git clean
,
git checkout .
Restricted commandsBlock
git clean
,
git rm
on protected paths,
rm -rf
on config dirs
When command targets protected path
机制实现逻辑触发时机
白名单强制校验仅允许授权工具修改受保护文件向受保护路径写入文件前
完整性校验每次迭代后检查受保护文件是否存在每次循环迭代结束时
操作前检查执行破坏性操作前校验受保护文件执行
rm
git clean
git checkout .
命令限制禁止对受保护路径执行
git clean
git rm
,禁止对配置目录执行
rm -rf
命令目标为受保护路径时

Pre-Destructive Operation Checklist

破坏性操作前检查清单

Before any
rm
,
git clean
, or
git checkout .
:
  1. List all files that will be affected
  2. Check each against the protected paths list
  3. If ANY protected file would be affected: ABORT and report
  4. If safe: proceed with caution
  5. After operation: verify all protected files still exist
STOP: If a protected file is missing after any operation, halt immediately and restore it.

执行任何
rm
git clean
git checkout .
前:
  1. 列出所有将被影响的文件
  2. 逐一和受保护路径列表比对
  3. 如果有任何受保护文件会被影响:中止操作并上报
  4. 确认安全后:谨慎执行操作
  5. 操作完成后:校验所有受保护文件仍然存在
停止操作:如果任何操作后发现受保护文件丢失,立即暂停运行并恢复文件。

Phase 6: Monitoring and Metrics

第6阶段:监控和指标

Track these metrics across loop iterations:
MetricPurposeAlert Threshold
Loop countTotal iterations executed>20 for a single task
Tasks completedProgress measurement0 for 3+ iterations
Files modifiedChange velocity0 for 3+ iterations
Test pass rateQuality trendDeclining for 3+ iterations
Error frequencyStagnation early warningIncreasing for 3+ iterations
Output volumeProductivity trend70% decline
API calls remainingRate limit proximity<20% remaining
Progress scoreOverall healthNegative for 3 iterations
跨循环迭代追踪以下指标:
指标目的告警阈值
循环次数已执行的总迭代数单个任务超过20次
已完成任务进度衡量连续3次以上迭代完成数为0
已修改文件变更速度连续3次以上迭代修改数为0
测试通过率质量趋势连续3次以上迭代持续下降
错误频率停滞早期预警连续3次以上迭代持续上升
输出量生产率趋势下降70%
剩余API调用量速率限制接近程度剩余不足20%
进展评分整体健康度连续3次迭代为负

Per-Iteration Status Log

每次迭代状态日志

markdown
undefined
markdown
undefined

Iteration [N] — [timestamp]

Iteration [N] — [timestamp]

  • Circuit state: CLOSED / HALF-OPEN
  • Tasks completed: [N]
  • Files modified: [list]
  • Tests: [X passed, Y failed, Z skipped]
  • Errors encountered: [list]
  • Progress score: [+/- N]
  • API calls remaining: [N]
  • Stagnation risk: LOW / MEDIUM / HIGH

---
  • Circuit state: CLOSED / HALF-OPEN
  • Tasks completed: [N]
  • Files modified: [list]
  • Tests: [X passed, Y failed, Z skipped]
  • Errors encountered: [list]
  • Progress score: [+/- N]
  • API calls remaining: [N]
  • Stagnation risk: LOW / MEDIUM / HIGH

---

Anti-Patterns / Common Mistakes

反模式/常见错误

What NOT to DoWhy It FailsWhat to Do Instead
Ignore stagnation signalsWastes hours on unsolvable problemsOpen circuit at threshold breach
Manually override open circuitBypasses safety mechanismFollow recovery protocol properly
Skip file protection checksConfig deletion derails entire projectAlways verify protected files after operations
Set cooldown to zeroRapid cycling through same failureRespect 30-minute minimum cooldown
Count test-fix-only iterations as progressMasks the real problem (flawed approach)Flag >80% test-fix effort as stagnation
Delete and recreate protected filesLoses configuration stateNever delete protected files, only update
Ignore rate limit warningsHits hard limit mid-operationPrioritize when at 80% of limit
Run destructive commands without pre-checksMay delete protected filesAlways check affected files first

禁止操作失败原因正确做法
忽视停滞信号在无法解决的问题上浪费数小时触发阈值时立即开启熔断器
手动覆盖开闸状态绕过安全机制严格遵循恢复协议
跳过文件保护检查配置删除会导致整个项目中断操作后始终校验受保护文件
将冷却期设为0短时间内反复进入相同失败状态遵守最少30分钟的冷却期要求
将仅修复测试的迭代算作进展掩盖真正的问题(方案缺陷)将超过80%工作量用于测试修复的情况标记为停滞
删除并重建受保护文件丢失配置状态绝对不删除受保护文件,仅做更新
忽视速率限制警告操作过程中触发硬限制达到80%限额时优先分配调用资源
不做前置检查直接执行破坏性命令可能删除受保护文件始终先检查会被影响的文件列表

Anti-Rationalization Guards

反合理化防护

ThoughtReality
"One more try will fix it"That is what you said 3 iterations ago. Open the circuit.
"The error is almost fixed""Almost" for 5 iterations means the approach is wrong.
"I cannot stop now, I am so close"Sunk cost fallacy. Open circuit, reassess.
"The cooldown is too long"The cooldown prevents wasting more time on the same failure.
"These config files are not important"They are protected for a reason. Do not delete them.
"The rate limit will not be hit"Track it. Do not guess.
"This is a different error"Check if it is truly different or the same root cause manifesting differently.
Do NOT override an open circuit. Follow the recovery protocol.

错误想法实际情况
"再试一次就能修好"你前3次迭代也是这么说的,开启熔断器。
"这个错误马上就能修好"连续5次迭代都「马上修好」说明你的方案有问题。
"我不能停,马上就完成了"沉没成本谬误,开启熔断器重新评估。
"冷却时间太长了"冷却期是为了避免你在同一个问题上浪费更多时间。
"这些配置文件不重要"它们被保护是有原因的,不要删除。
"不会触发速率限制的"做好追踪,不要猜。
"这是不同的错误"检查是真的不同,还是同一个根因的不同表现。
禁止覆盖开闸状态,严格遵循恢复协议。

Integration Points

集成点

SkillRelationship
resilient-execution
Task-level retries (3 attempts). Circuit-breaker activates AFTER resilient-execution exhausts retries within individual tasks.
autonomous-loop
Circuit-breaker monitors the loop. Opens circuit when loop-level stagnation detected.
ralph-status
Status block provides metrics for stagnation detection.
verification-before-completion
Circuit-breaker ensures verification passes before closing a loop.
self-learning
Stagnation patterns are persisted to memory for future avoidance.
auto-improvement
Circuit-breaker events feed into improvement metrics.
技能关联关系
resilient-execution
任务级重试(3次尝试)。circuit-breaker会在
resilient-execution
耗尽单个任务的重试次数后激活。
autonomous-loop
circuit-breaker监控循环运行,检测到循环级停滞时开启熔断器。
ralph-status
状态模块提供停滞检测所需的指标。
verification-before-completion
circuit-breaker会确保校验通过后才关闭循环。
self-learning
停滞模式会被持久化到内存中,用于后续规避。
auto-improvement
circuit-breaker事件会作为改进指标的输入。

Scope Clarification

范围说明

ScopeSkillBehavior
Task-level
resilient-execution
Try 3 approaches for a single failing task
Loop-level
circuit-breaker
Halt the entire loop when patterns indicate systemic failure
The circuit breaker activates AFTER resilient-execution has exhausted its retries within individual tasks. If tasks keep failing despite 3 retries each, the circuit breaker detects the pattern.

范围所属技能行为
任务级
resilient-execution
单个失败任务尝试3种解决思路
循环级
circuit-breaker
当模式表明存在系统性故障时,暂停整个循环
circuit-breaker会在
resilient-execution
耗尽单个任务的重试次数后激活。如果每个任务都经过3次重试仍然持续失败,circuit-breaker会检测到该模式。

Process Summary

流程总结

  1. Before each loop iteration: Check circuit state (CLOSED/HALF-OPEN/OPEN)
  2. If OPEN: Report status, wait for cooldown, or escalate
  3. If HALF-OPEN: Allow one probe iteration, evaluate result
  4. If CLOSED: Execute normally, monitor all thresholds
  5. After each iteration: Update metrics, compute progress score, evaluate thresholds
  6. If threshold exceeded: Open circuit, report reason, begin cooldown
  7. After cooldown: Enter HALF-OPEN, allow one probe
  8. After probe: Close if successful, re-open with doubled cooldown if failed

  1. 每次循环迭代前: 检查熔断器状态(CLOSED/HALF-OPEN/OPEN)
  2. 如果为OPEN: 上报状态,等待冷却,或升级问题
  3. 如果为HALF-OPEN: 允许一次试探迭代,评估执行结果
  4. 如果为CLOSED: 正常执行,监控所有阈值
  5. 每次迭代后: 更新指标,计算进展评分,评估阈值触发情况
  6. 如果触发阈值: 开启熔断器,上报原因,进入冷却期
  7. 冷却结束后: 进入HALF-OPEN状态,允许一次试探迭代
  8. 试探后: 成功则关闭熔断器,失败则重新开启并将冷却时间翻倍

Skill Type

技能类型

RIGID — Thresholds and protection rules must be followed exactly. Do not relax circuit breaker conditions. Do not override open circuits. Do not skip file protection checks. Do not ignore stagnation signals.
RIGID——必须严格遵守阈值和保护规则。不得放宽熔断器条件、不得手动覆盖开闸状态、不得跳过文件保护检查、不得忽视停滞信号。