核心命題: 所有的 AI Agent 最終都是一個循環。但循環怎麼設計,決定了 agent 是可靠的工程師還是華麗的 demo。本文對比七種 AI Agent 的循環架構,從源碼級解剖到架構決策分析。
覆蓋系統: Claude Code · Cursor · Aider · Cline · SWE-agent · OpenHands · OpenClaw Loop Engineering
方法論: 原始碼級分析 + 架構文件對比 + 生產環境實戰驗證
1. 為什麼循環是 Agent 的一切
2026 年,AI Agent 領域達成了兩項共識:
共識一: Agent = LLM + Tools + Loop。沒有循環,模型只是一次性問答機器。有了循環,模型才能觀察世界、採取行動、獲取反饋、迭代修正。
共識二: 循環的設計比模型本身更重要。一個設計良好的循環可以讓中等模型超越劣質循環中的頂級模型。
Claude Code 的源碼分析者 Vincent Qiao 寫道:
「The agent loop is 1,730 lines of a single
while(true)that does everything. It streams model responses, executes tools concurrently, compresses context through four layers, recovers from five categories of errors, tracks token budgets with diminishing returns detection, runs stop hooks that can force the model back to work, manages prefetch pipelines for memory and skills, and produces a typed discriminated union of exactly why it stopped.」
這個 while(true) 是所有 agent 系統的共同核心,但每個系統的實作方式有著根本性的差異。本文解剖七種主要方法。
2. 七種循環架構深度對比
2.1 Claude Code — 單一巨型 while(true)
循環類型: AsyncGenerator based single-loop
核心結構:
while (true) {
1. Prepare messages (compress, trim, collapse — 五層壓縮管線)
2. Call Claude API (streaming)
3. Collect model response
4. Has tool_use? → Execute tools concurrently → Collect results → continue
5. No tool_use? → Check Stop Hooks → Check recovery needed → Otherwise exit
6. Assemble [original + assistant response + tool results]
7. Enter next iteration
}
關鍵設計決策:
| 設計 | 實現 | 影響 |
|---|---|---|
| 單一代碼路徑 | query.ts - 1730 行的單一 query() 函數,所有入口(REPL、SDK、subagent、headless)都走這條路 |
任何改進自動惠及所有場景 |
| 並行工具執行 | StreamingToolExecutor — 模型還在輸出時就開始執行工具 |
延遲顯著降低 |
| Stop Hook | 外部腳本在 turn 結束前強制檢查結果。不通過則 block turn(最多 8 次) | 執行-驗證分離 |
| 7 種恢復路徑 | Token 超限 escalate、Context 耗盡 auto-compact、Model overload fallback、Permission deny、Tool crash、Stuck detection、Max turns | 盡一切可能不中斷 |
| 五層壓縮 | Budget Reduction → Snip → Microcompact → Context Collapse → Auto-Compact | 避免上下文爆炸 |
循環中的驗證:
Anthropic 的官方架構文件(ArXiv: 2604.14228)明確指出:
「Agents tend to respond by confidently praising the work, even when quality is mediocre, motivating separation of generation from evaluation.」
Claude Code 將驗證嵌入循環的三個階段:蒐集上下文 → 採取行動 → 驗證結果。這不是三個獨立的步驟,而是一個交織的循環——代碼修改後立即執行測試,測試失敗後立即讀取錯誤訊息並修正。
2.2 Cursor — 多智能體矩陣 + 模型競賽
循環類型: Multi-Agent Orchestration + Model Race Pattern
五層 Harness 架構:
1. Interface Layer → 任務入口(Slack, GitHub, IDE, Mobile)
2. Orchestration Layer → Plan mode, Model Router, Race Pattern, Subagent Dispatch
3. Execution Layer → 隔離 VM(非本機),多個 agent 並行
4. Verification Layer → 每個 agent 可用 Computer Use、Video、Screenshot、Logs 自我驗證
5. Output Layer → PR + Artifacts(非聊天訊息)
模型競賽(Race Pattern):
Cursor 最具創新性的設計是將同一個問題同時發送給多個模型,選擇最佳結果。
Dispatch problem → Model A | Model B | Model C (parallel)
→ Select best output
Cursor 團隊報告這種模式「顯著提高了最終輸出質量」,尤其是對於需要少量精確修改的高難度 bug。
Agents 的隔離執行:
Cursor 為每個 agent 自動建立獨立的 git worktree。每個 agent 在自己的 worktree 中編輯、構建、測試程式碼,互不干擾。這解決了並行 agent 最困難的問題:檔案衝突。
模型路由:
Composer 2(Cursor 自研 MoE) → 常規編碼
Claude → 推理密集型子任務
Gemini → 大上下文窗口處理
GPT-5 Codex → 長時間雲端 agent
2.3 Aider — Git 即記憶,架構師-編輯器分離
循環類型: Single-agent loop with Git-as-memory + Architect/Editor split
核心循環:
User prompt
→ RepoMap (PageRank 圖排序,選擇最相關的程式碼上下文)
→ 組裝 context (system prompt + repo map + chat history + files)
→ LLM 調用
→ 解析 edit(whole-file / diff / udiff / search-replace)
→ 應用 edit
→ Lint(自動)
→ Test(可選)
→ 若有 error → Reflection Loop(最多 max_reflections 次自動修正)
→ Git auto-commit(每個 edit 一個 commit)
RepoMap — Aider 的標誌性創新:
Aider 不將整個程式碼庫塞入 prompt,而是:
- 建立整個 repo 的符號圖(symbol graph)— 每個定義和引用都是一個節點和邊
- 使用 PageRank 選擇最相關的程式碼上下文
- 動態調整 token 預算內的上下文量
這使得 Aider 能在大規模程式碼庫中保持對全局結構的理解,而不會超出 context window。
Architect + Editor 分離:
Phase 1: Architect(強推理模型,如 Claude Opus)
→ 分析問題 → 生成詳細修改計劃 → 提交給用戶審批
Phase 2: Editor(快速模型,如 Claude Haiku)
→ 按照計劃逐步執行 edit → Lint → Test → 自動修正
Git 作為記憶:
Aider 將每個 AI edit 自動 commit 到 git,生成描述性的 commit message。/undo 就是 git revert。這使得整個編輯歷史完全可追溯。
2.4 Cline — VS Code 原生 Plan/Act 雙模
循環類型: Event-driven streaming loop with Plan/Act separation
核心架構:
VSCode Extension Host
├── Controller(狀態管理中心)
├── Task(每個任務獨立實例,確保隔離)
│ └── Agent Loop:
│ while (not done) {
│ API request → streaming response
│ → parse XML tool calls
│ → Safety check (user approval)
│ → Execute tool
│ → Git shadow checkpoint
│ → Update context & state
│ → Intelligent truncation
│ }
└── Webview Provider(React-based UI)
Plan / Act 雙模:
Cline 原生支援兩種獨立的操作模式:
| 模式 | 行為 | 模型配置 |
|---|---|---|
| Plan | 分析問題 → 提出修改計劃 → 用戶審批。不修改任何程式碼 | 強推理模型 |
| Act | 按照已批准的計劃逐步執行 edit → 測試 → 修正 | 快速模型 |
技術亮點:
- XML Tool Calling: 對不支援原生 JSON tool call 的模型,使用 XML 格式進行工具調用解析
- Git Shadow Versioning: 建立獨立的 git 歷史,不干擾用戶的 git 歷史。agent 可以自由 commit/rollback
- Generative Streaming UI: 工具執行過程實時可視化——diffs、瀏覽器互動、命令輸出
- Context Window Intelligence: 智能截斷算法,保留語義關鍵的上下文
Cline SDK(2026 重構):
2026 年 Cline 將其核心循環抽取為獨立的 @cline/agents 套件——一個無狀態的執行時循環。這意味著任何應用程式都可以嵌入 Cline 的 agent 循環。
2.5 SWE-agent — Agent-Computer Interface
循環類型: ReAct-style loop with purpose-built ACI
核心概念:ACI(Agent-Computer Interface)
SWE-agent 的核心洞察是:LLM agent 是一類新的終端用戶,需要專門設計的介面。
就像人類使用 IDE(語法高亮、自動補全、除錯器)來輔助程式設計一樣,agent 也需要專門設計的工具介面。
循環結構:
for each step:
Agent generates: Thought + Action
ACI executes action:
- find_file / search_file / search_dir (程式碼搜索,最多 50 結果)
- open / goto (文件導航)
- edit (含 linter 反饋— 無效 edit 被丟棄,agent 重試)
- bash (標準 Linux 命令)
ACI returns: formatted observation + linter errors
Agent updates context → next step
ACI 的關鍵設計:
| 設計 | 原因 |
|---|---|
| 搜索結果限制在 50 條 | 防止 agent 被過多結果淹沒 |
| 編輯時即時 linter 反饋 | 語法錯誤立即被捕獲,agent 必須修正後才能繼續 |
| 無效編輯被丟棄 | 防止損壞程式碼庫 |
| 結構化的錯誤訊息格式 | 讓 agent 能理解錯誤而非被迷惑 |
效能: SWE-bench pass@1 12.5%(遠超當時所有非互動式 LM),HumanEvalFix 87.7%。
2.6 OpenHands — 內置循環恢復 + Security Analyzer
循環類型: State Machine with built-in recovery
核心架構:
AgentController
└── step() loop:
1. Pending Actions? → execute and return
2. Condensation? → compress history → return condensed view
3. LLM Query → generate next actions
4. Safety Check → Security Analyzer (Low/Medium/High)
5. Confirmation Check → if needs approval, WAITING state
6. Execute Tools → return observations
7. StuckDetector → if stuck, attempt_loop_recovery()
StuckDetector + Loop Recovery:
def is_stuck(self) -> bool:
if self.delegate and self.delegate._is_stuck():
return True
return self._stuck_detector.is_stuck(self.headless_mode)
def attempt_loop_recovery(self) -> bool:
recovery_point = self._stuck_detector.stuck_analysis.loop_start_idx
# 截斷記憶到循環起點
await self._truncate_memory_to_point(recovery_point)
# 用最後一條用戶訊息重新啟動 agent
await self._restart_with_last_user_message(stuck_analysis)
這是極少數將循環檢測和恢復作為架構級機制(而非 prompt 建議)的方案。
Security Analyzer 三級風險:
| 風險 | 行為 |
|---|---|
| Low | 直接執行 |
| Medium | 記錄警告 + 監控執行 |
| High | 阻止執行 + 請求用戶確認 |
2.7 OpenClaw Loop Engineering — 我們的自建系統
循環類型: Cron-driven hierarchical multi-agent loop
三層架構:
Main Agent (Interface)
└── 接收老闆指令 → 分配任務 → 轉發結果
Looper Agent (Executor)
└── cron 觸發 (每 4h/2h/1h/30min)
→ 讀取 LOOP.md + STATE.json
→ 執行七階段內循環(max 30 retries)
→ spawn coder-deepseek 做 checker
→ 寫入 STATE.json
Coder Agents (Workers)
└── coder-deepseek / coder-qwen / coder-minimax / coder-glm
→ 執行具體的檢查 / 修復 / 驗證任務
七階段內循環:
for attempt in 1..30:
Observe → 讀 LOOP.md(不可變檢查清單)+ STATE.json(上次狀態)
Plan → update_plan 結構化步驟
Execute → 5 項強制檢查 + exec/write 實際操作
Verify → spawn coder-deepseek(獨立 checker,非 self-verify)
Diagnose → 分析失敗原因(timeout / service_down / connection_refused / data_missing)
Adjust → 根據策略遞進(1-5 輕微 / 6-15 中等 / 16-30 重型)
Retry → 回到 Observe,直到全 PASS 或 max_retries 用盡
10 個 Auto-Healing Loop:
| Loop | 排程 | 功能 |
|---|---|---|
| system-health | 每 4h | Qdrant / CC / Cron / OMLX / Tunnel 五項巡檢 |
| daily-triage | 每日 9AM | 跟進事項 + 郵件 + session 分診 |
| cc-babysitter | 每 15min | CC session 監控 + escalation |
| agent-orchestrator | 每 30min | coder-* 健康檢查 + 負載分配 |
| email-watch | 每 2h | 郵件掃描 + 分類 + 緊急通知 |
| pr-review | 每 4h | GitHub PR 監控 + 自動審查 |
| rnd-discovery | 每日 2AM | 程式碼庫 TODO/FIXME + 踩坑模式掃描 |
| report-generator | 每日 23:00 | 綜合日報生成 |
| meaning-discovery | 每週 | 意義發現 + 方向校準 |
| evolution | 每月 1 號 | 自我進化 + 過時內容清理 |
方法論強制機制:
- 不可變檢查清單: LOOP.md 頂部的 ⛔ 區塊禁止任何 agent 增刪改檢查項目
- Gate 0 完整性校驗: checker 強制檢查是否所有項目都已執行
- OMLX L3 外部驗證:
score_enforcer.py獨立掃描 STATE.json,連續 unhealthy → 外部告警 - compliance_score: 每個 STATE.json 記錄七階段完成度(0-7),score_enforcer 每小時掃描
實戰教訓: 在生產環境中,我們的 agent 在純 prompt 驗證機制下連續 5 次(20 小時)跳過 verify 階段。重構為架構強制後,compliance 顯著改善。這直接驗證了本文的核心論點。
3. 橫向對比矩陣
| 系統 | 循環形狀 | 執行-驗證分離 | 自我修復 | 上下文管理 | 多模型 | 複雜度 |
|---|---|---|---|---|---|---|
| Claude Code | 單一 while(true) | Stop Hook + Subagent | ✅ 7 recovery paths | 五層壓縮 | ❌ 單一 | 中 |
| Cursor | 多 Agent 平行 | Race Pattern(多模型輸出比較) | ❌ | 各 Agent 獨立 context | ✅ Multi-model router | 最高 |
| Aider | Git-based loop | Architect+Editor 分離 | ✅ Lint+Test reflection | RepoMap (PageRank) | ✅ 雙模型 split | 低 |
| Cline | Event-driven streaming | Plan/Act 雙模 | ❌ 需用戶介入 | Intelligent truncation | ✅ 33+ providers | 中 |
| SWE-agent | ReAct-style | ACI linter feedback | ❌ 單步修正 | History processors | ❌ 單一 | 低 |
| OpenHands | State Machine | Security Analyzer | ✅ Loop Recovery | Condenser auto-compress | ✅ Optional router | 高 |
| OpenClaw Loop | Cron-driven hierarchy | Gate 0 + coder-deepseek checker | ✅ 30 retries + 4-strategy escalation | STATE.json + iteration_history | ✅ 5 agents | 中 |
4. 五個架構維度的深度分析
4.1 循環形狀:單一巨型 vs. 多階段分離
| 策略 | 代表 | 優點 | 缺點 |
|---|---|---|---|
| 單一巨型循環 | Claude Code, Cline | 簡單、一個 code path 處理所有場景、改進自動惠及全部 | 難以分離關注點、context 膨脹快 |
| 架構師-編輯器分離 | Aider, Cline Plan/Act | 計劃質量高、執行速度快、可換模型 | 多一次 API 調用、計劃可能不準確 |
| 多 Agent 並行 | Cursor, OpenClaw | 不同任務用不同 agent、隔離執行、可並行 | 協調複雜、狀態同步困難 |
| Cron-driven hierarchy | OpenClaw | 定時自動、不依賴用戶觸發、獨立驗證層 | 延遲較大、非即時 |
4.2 執行-驗證分離:誰來判斷 agent 做對了?
這是本文的核心命題,也是所有系統分化的關鍵點。
| 系統 | 驗證機制 | 強制性 |
|---|---|---|
| Claude Code | Stop Hook — 外部腳本在 turn 邊界強制檢查 | 🔴 架構強制(block turn) |
| Cursor | Race Pattern — 多模型並行輸出,選擇最佳 | 🟠 統計性(非確定性) |
| Aider | Lint + Test reflection loop — 硬信號驅動 | 🟠 可配置 |
| Cline | 用戶手動審批(Plan/Act) | 🟡 人為 |
| SWE-agent | ACI linter — 無效編輯自動丟棄 | 🟠 工具層 |
| OpenHands | Security Analyzer — 三級風險評估 | 🟠 可配置 |
| OpenClaw | Gate 0 + coder-deepseek + L3 score_enforcer | 🔴 三層強制 |
核心洞察: 驗證的強制性從「人為」(用戶自己檢查)到「架構強制」(Stop Hook、Gate 0)是一個連續光譜。愈靠近架構強制端,系統愈可靠,但實現成本愈高。
4.3 自我修復:agent 能否自己從錯誤中恢復?
| 系統 | 修復機制 | 自主程度 |
|---|---|---|
| Claude Code | 7 recovery paths(token/context/model/tool 等多種錯誤分類處理) | 🔴 全自動 |
| OpenHands | StuckDetector → 截斷記憶到循環起點 → 重新開始 | 🔴 全自動 |
| Aider | Lint error → reflection loop → 自動修正(max_reflections 次) | 🟠 半自動 |
| OpenClaw | 30 retries + 四級策略遞進(輕微→中等→重型調整) | 🔴 全自動 |
4.4 上下文管理:如何防止 context window 爆炸?
| 系統 | 策略 |
|---|---|
| Claude Code | 五層壓縮管線:Budget → Snip → Microcompact → Collapse → Auto-Compact |
| Cursor | 每個 agent 獨立 context + 只注入相關程式碼片段(semantic search) |
| Aider | RepoMap(PageRank 圖排序,只發送最相關的符號定義) |
| Cline | Intelligent Truncation — 保留語義關鍵部分,丟棄重複內容 |
| SWE-agent | History processors + 結構化錯誤訊息(抑制冗餘輸出) |
| OpenClaw | STATE.json 持久化 + iteration_history — 每次執行獨立 session,不依賴累積 context |
4.5 多模型策略:一個模型統治 vs. 多元生態
| 策略 | 系統 | 適用場景 |
|---|---|---|
| 單一最強模型 | Claude Code, SWE-agent | 任務類型單一,模型能力足夠 |
| Router(動態分配) | Cursor Auto mode | 不同子任務需要不同模型特性 |
| Race(並行競賽) | Cursor Race Pattern | 高難度 bug,少量精確修改 |
| Architect+Editor(前後分離) | Aider, Cline Plan/Act | 複雜多步驟任務 |
| 專職 Agent Pool | OpenClaw (5 agents) | 不同 agent 負責不同領域 |
5. 從對比到實踐:我們的選擇與教訓
5.1 為什麼我們選擇了 Cron-Driven Hierarchy
我們的需求與主流 IDE agent 不同:
| 需求 | IDE Agent(Claude Code/Cursor) | 我們的系統(OpenClaw Loop) |
|---|---|---|
| 觸發方式 | 用戶輸入 prompt | 定時自動(cron) |
| 時間尺度 | 秒-分鐘 | 小時-天 |
| 任務類型 | 寫程式碼、修 bug | 系統巡檢、郵件監控、agent 協調 |
| 驗證需求 | 測試通過 | 服務健康 + 合規審計 |
| 可靠性要求 | 可接受偶爾失敗 | 連續監控不可中斷 |
傳統的「用戶觸發 → agent 執行 → 用戶驗證」循環無法滿足我們的需求。我們需要一個不依賴人類在環路中的自動化系統。
5.2 我們從這次對比中學到的最重要教訓
教訓一:Claude Code 的 Stop Hook 是最簡潔也最強力的驗證機制。 我們已將其思想移植到 Gate 0 和 L3 score_enforcer 中。
教訓二:Cursor 的 Race Pattern 暗示了未來方向。 對於高風險決策(如 OMLX 服務判定),同時讓多個模型判斷並比較結果可能比單一 checker 更可靠。
教訓三:Aider 的 RepoMap 是上下文管理的典範。 不把所有東西塞入 prompt,而是智慧選擇最相關的上下文。我們的 LOOP.md + STATE.json 模式正是受此啟發。
教訓四:OpenHands 的 Loop Recovery 是我們下一步要實現的。 將 stuck detection 從 cron timeout 升級為真正的行為模式檢測。
教訓五:SWE-agent 的 ACI 理念提醒我們——工具設計就是介面設計。 我們的 LOOP.md 格式、STATE.json schema、cron prompt 結構,本質上都是 Agent-Computer Interface。
6. 結論
2026 年的 AI Agent 系統正在從「demo 階段」進入「生產階段」。在這個轉變中,循環架構的選擇比模型選擇更重要。
七個系統的對比揭示了幾條反覆出現的設計原則:
-
循環形狀要匹配任務特性。 短期編碼任務適合單一 while(true);長期監控任務適合 cron-driven hierarchy。
-
驗證不能靠自覺。 Claude Code 的 Stop Hook、Cursor 的 Race Pattern、我們的 Gate 0——所有可靠的驗證機制都是架構強制的,不是 prompt 建議的。
-
上下文管理決定天花板。 Aider 的 RepoMap、Claude Code 的五層壓縮、Cursor 的隔離 context——在大規模任務中,context 管理能力直接決定 agent 能走多遠。
-
多模型策略是競爭優勢。 無論是 Cursor 的 Race Pattern、Aider 的 Architect+Editor,還是我們的專職 Agent Pool,使用多個模型的組合幾乎總是優於單一模型。
-
自我修復必須是架構級功能。 OpenHands 的 Loop Recovery 和 Claude Code 的 7 recovery paths 是正確的方向——將修復邏輯寫成程式碼,而非寫進 prompt。
本文基於 2026 年 6 月 14 日在君澤智庫生產環境中進行的 Loop Engineering 全面審計。所有程式碼引用均來自對應項目的公開原始碼或官方文件。