代理架構:建構AI驅動的開發工作框架
# 建構正式環境AI代理工作框架的完整系統。涵蓋技能、掛鉤、記憶、子代理、多代理編排,以及讓AI程式碼代理成為可靠基礎設施的設計模式。
TL;DR:Claude Code不是具備檔案存取能力的聊天框,而是一個可程式化 runtime,擁有29個已記錄的生命週期事件,每個事件都可透過模型無法略過的 shell scripts 掛上 hook。將 hooks 疊成 dispatchers,dispatchers 疊成 skills,skills 疊成 agents,agents 疊成 workflows,就能得到一套自主開發 harness:它會強制執行限制、委派工作、跨 sessions 保留 memory,並協調多 agent deliberation。Claude Code v2.1.147 新增預設關閉的
Workflowtool(CLAUDE_CODE_WORKFLOWS=1),讓確定性的 multi-agent orchestration 從純 userland scripts 逐步走向 first-party runtime primitive;v2.1.149 則從安全面強化同一個教訓,修正 PowerShell permission-bypass 與 git-worktree sandbox allowlist 問題。Hooks 與 evidence gates 仍然掌握正確性。5253 本指南涵蓋這套堆疊的每一層:從單一 hook 到10-agent consensus system。無需任何 frameworks。全部使用 bash 與 JSON。
Andrej Karpathy 為圍繞 LLM agent 成長出的東西取了一個詞:claws。也就是讓 agent 能在 context window 之外抓住現實世界的 hooks、scripts 與 orchestration。1 多數開發者把 AI coding agents 視為互動式助理。他們輸入 prompt,看它編輯檔案,然後繼續下一步。這種框架會把生產力限制在您能親自監督的範圍內。
基礎架構的心智模型不同:AI coding agent 是一個具備 LLM kernel 的可程式化 runtime。模型採取的每個動作,都會通過您控制的 hooks。您定義的是 policies,而不是 prompts。模型在您的基礎架構中運作,就像 web server 在 nginx rules 中運作。您不會坐在 nginx 前面逐一輸入 requests。您會設定它、部署它,並監控它。
這個差異很重要,因為基礎架構會複利成長。一個能阻擋 bash commands 中憑證的 hook,會保護每個 session、每個 agent、每次自主執行。一個編碼了評估 rubric 的 skill,不論由您呼叫或由 agent 呼叫,都會一致套用。一個負責安全 code review 的 agent,不論您是否正在觀看,都會執行同樣的檢查。2
重點摘要
- Hooks 保證執行;prompts 不會。 對 linting、formatting、安全檢查,以及任何無論模型行為如何都必須每次執行的事項使用 hooks。Exit code 2 會阻擋動作。Exit code 1 只會警告。3
- Skills 編碼會自動啟用的領域專業知識。
description欄位決定一切。Claude 使用 LLM reasoning(不是關鍵字比對)來判斷何時套用 skill。4 - Subagents 防止 context bloat。 用於探索與分析的隔離 context windows,可讓主要 session 保持精簡。並行執行獨立 subagents;當 workers 需要持續協調時,則使用 agent teams。5
- Memory 存在於檔案系統。 檔案會跨 context windows 持續保留。CLAUDE.md、MEMORY.md、rules directories 與 handoff documents 形成結構化外部 memory system。6
- Multi-agent deliberation 能捕捉盲點。 單一 agent 無法挑戰自己的假設。兩個具備不同評估優先順序的獨立 agents,能抓出 quality gates 無法處理的結構性失敗。7
- Harness pattern 就是整個系統。 CLAUDE.md、hooks、skills、agents 與 memory 不是彼此獨立的功能。它們會組合成一個位於您與模型之間的確定性層,並能隨自動化規模擴展。
如何使用本指南
| 經驗 | 從這裡開始 | 接著探索 |
|---|---|---|
| 每天使用 Claude Code,想更進一步 | Harness Pattern | Skills System、Hook Architecture |
| 建置自主 workflows | Subagent Patterns | Multi-Agent Orchestration、Production Patterns |
| 評估 agent architecture | 為什麼 Agent Architecture 很重要 | Decision Framework、Security Considerations |
| 設定 team harness | CLAUDE.md Design | Hook Architecture、Quick Reference Card |
每個章節都建立在前一節之上。最後的 Decision Framework 提供查找表,協助您針對每一類問題選擇合適的機制。
五分鐘黃金路徑
在深入探討之前,這是從零到建立可運作 harness 的最短路徑。一個 hook、一個 skill、一個 subagent,一個成果。
步驟 1:建立安全 hook(2 分鐘)
建立 .claude/hooks/block-secrets.sh:
#!/bin/bash
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if echo "$CMD" | grep -qEi '(AKIA|sk-|ghp_|password=)'; then
echo "BLOCKED: Potential secret in command" >&2
exit 2
fi
在 .claude/settings.json 中串接:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{ "type": "command", "command": ".claude/hooks/block-secrets.sh" }]
}
]
}
}
結果:Claude 執行的每一個 bash 指令都會被篩檢是否洩漏憑證。模型無法略過此檢查。
步驟 2:建立程式碼審查 skill(1 分鐘)
建立 .claude/skills/reviewer/SKILL.md,包含 frontmatter(name: reviewer、description: Review code for security issues, bugs, and quality problems. Use when examining changes, reviewing PRs, or auditing code.、allowed-tools: Read, Grep, Glob)以及檢查清單:SQL injection、XSS、硬編碼密鑰、缺漏的錯誤處理、超過 50 行的函式。
結果:每當您提及審查、檢查或稽核時,Claude 會自動啟用這項專業能力。
步驟 3:派出 subagent(30 秒)
在任何 Claude Code session 中,請 Claude 使用獨立代理審查最近 3 次 commit 的安全問題。Claude 會派出一個 Explore agent 讀取 diff、套用您的審查 skill,並回傳摘要。您的主要 context 保持乾淨。
您現在擁有什麼
一個三層 harness:決定性的安全關卡(hook)、會自動啟用的領域專業知識(skill),以及保護您 context 的隔離分析(subagent)。以下每一節都會深入擴展這三層中的一層。
為什麼 Agent Architecture 至關重要
Simon Willison 用一個觀察點出了當前的時刻:撰寫程式碼現在很便宜。8 沒錯。但隨之而來的推論是,驗證現在才是昂貴的部分。缺乏驗證基礎架構的廉價程式碼,只會大規模製造 bug。真正值得投資的不是更好的提示詞,而是模型周圍那套能捕捉模型遺漏之處的系統。
有三股力量讓 agent architecture 成為必要:
Context window 是有限且會耗損的。每一次檔案讀取、工具輸出與對話輪次都會消耗 token。Microsoft Research 與 Salesforce 針對 15 個 LLM 進行了超過 20 萬次模擬對話測試,發現從單輪互動到多輪互動平均效能下降 39%。9 退化最快在兩輪之內就開始,並依循可預測的曲線:前 30 分鐘還能精準完成多檔案編輯,到第 90 分鐘就退化為單檔案的隧道視野。更長的 context window 並無法解決這個問題。同一份研究的「Concat」條件(將完整對話作為單一提示詞)以相同內容達到單輪效能的 95.1%。退化來自輪次邊界,而非 token 上限。
模型行為是機率性的,而非決定性的。告訴 Claude「編輯檔案後一律執行 Prettier」大約有 80% 的時候會成功。3 模型可能忘記、可能優先考慮速度,或判斷該變更「太小」。對於合規、安全與團隊標準而言,80% 並不可接受。Hooks 能保證執行:每一次 Edit 或 Write 都會觸發您的 formatter,次次如此,毫無例外。決定性勝過機率性。
單一視角會遺漏多維度的問題。一個審查 API endpoint 的 agent 檢查了身份驗證、驗證了輸入清理並核對了 CORS 標頭。一切看似無恙。但第二個 agent 在獨立提示下以滲透測試者身份介入,發現該 endpoint 接受無上限的查詢參數,可能透過資料庫查詢放大觸發阻斷服務攻擊。7 第一個 agent 從未檢查這點,因為其評估框架中並未把查詢複雜度視為安全面向。這個缺口是結構性的。再多的提示詞工程也無法彌補。
Agent architecture 同時解決這三者:hooks 強制執行決定性限制、subagents 管理 context 隔離,而多代理協調提供獨立視角。它們共同構成了 harness。
Harness 模式
Harness 並非框架,而是一種模式:由檔案、腳本與慣例組成的可組合集合,將 AI 編碼代理包裝在確定性的基礎設施之中。其組成元件如下:
┌──────────────────────────────────────────────────────────────┐
│ THE HARNESS PATTERN │
├──────────────────────────────────────────────────────────────┤
│ ORCHESTRATION │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ Agent │ │ Agent │ │ Consensus │ │
│ │ Teams │ │ Spawning │ │ Validation│ │
│ └────────────┘ └────────────┘ └────────────┘ │
│ Multi-agent deliberation, parallel research, voting │
├──────────────────────────────────────────────────────────────┤
│ EXTENSION LAYER │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Skills │ │ Hooks │ │ Memory │ │ Agents │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ Domain expertise, deterministic gates, persistent state, │
│ specialized subagents │
├──────────────────────────────────────────────────────────────┤
│ INSTRUCTION LAYER │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ CLAUDE.md + .claude/rules/ + MEMORY.md │ │
│ └──────────────────────────────────────────────────────┘ │
│ Project context, operational policy, cross-session memory │
├──────────────────────────────────────────────────────────────┤
│ CORE LAYER │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Main Conversation Context (LLM) │ │
│ └──────────────────────────────────────────────────────┘ │
│ Your primary interaction; finite context; costs money │
└──────────────────────────────────────────────────────────────┘
指令層(Instruction Layer): CLAUDE.md 檔案與規則目錄定義代理對您專案的認知。它們會在工作階段啟動以及每次壓縮(compaction)後自動載入,是代理的長期架構記憶。
擴充層(Extension Layer): skills 提供根據情境自動啟用的領域專業知識。hooks 提供在每次符合條件的工具呼叫時觸發的確定性閘道。記憶檔案則跨工作階段保存狀態。自訂代理(agents)提供專門的 subagents 設定。
編排層(Orchestration Layer): 多代理模式協調獨立代理進行研究、審查與審議。生成預算(spawn budgets)防止失控的遞迴。共識驗證確保品質。
關鍵洞察:大多數使用者完全在核心層中工作,眼睜睜看著情境膨脹、成本攀升。進階使用者則設定指令層與擴充層,僅將核心層用於編排與最終決策。2
託管式與自架式 Harness(2026 年 4 月)
整個 2026 年初,「自行打造 harness」是唯一真正可行的路線。2026 年 4 月,情況改變了。Anthropic 於 4 月 8 日推出公開測試版的 Claude Managed Agents:將 harness 迴圈、工具執行、沙盒容器與狀態持久化整合為 REST API,計費方式為標準 token 加上每個工作階段每小時 0.08 美元。OpenAI 於 4 月 16 日發布的 Agents SDK 更新則將相同的分層方式正式化——將 harness 與運算視為獨立層,並提供原生沙盒供應商(Blaxel、Cloudflare、Daytona、E2B、Modal、Runloop、Vercel),以及在容器遺失時透過快照與還原(snapshot/rehydrate)保留狀態的機制。2324
OpenAI 端更深層的 SDK 表面則隨著 openai-agents Python v0.14.0 推出(2026 年 4 月 15 日發布、4 月 16 日公告):Agent 的 SandboxAgent 子類別具備 default_manifest、沙盒指令與 capabilities;Manifest 描述全新工作區契約(檔案、目錄、本機檔案、Git 儲存庫、env、users、mounts);SandboxRunConfig 用於針對每次執行配置沙盒用戶端、即時 session 注入、manifest 覆寫、快照與具現化(materialization)並行限制。內建 capabilities 涵蓋 shell 存取、檔案系統編輯、影像檢查、skills、沙盒記憶與壓縮。沙盒記憶會跨執行保存擷取出的經驗教訓,並逐步揭露;工作區支援本機檔案、Git 儲存庫項目以及遠端掛載(S3、R2、GCS、Azure Blob、S3 Files);快照可在不同供應商之間移植。後端:UnixLocalSandboxClient、DockerSandboxClient,以及透過選用 extras 連接 Blaxel、Cloudflare、Daytona、E2B、Modal、Runloop 與 Vercel 的託管用戶端。24
對於希望將 Claude Code runtime 以函式庫形式嵌入 Python 專案的情境——介於「shell out 呼叫 claude」與「以 REST API 連接 Managed Agents」之間——claude-agent-sdk-python 是第三種選擇。4 月 28 至 29 日的系列更新(v0.1.69 → v0.1.71)將內建的 CLI 升級至 v2.1.123,將 mcp 相依套件的下限提升至 >=1.19.0(舊版本會悄悄丟棄處理程序內 MCP 工具回傳的 CallToolResult,使模型只看到一個驗證錯誤的二進位資料),並讓 SandboxNetworkConfig 與 TypeScript SDK 的綱要對齊(allowedDomains、deniedDomains、allowManagedDomainsOnly、allowMachLookup)。30
若您的 harness 包含語音或即時(realtime)層,openai-agents-python v0.17.0(2026 年 5 月 8 日)將 RealtimeAgent 的預設值更新為 gpt-realtime-2。41 既有的即時工作階段會自動採用新的預設值;如需在評估期間維持舊行為,請明確固定先前的模型版本。
架構上的分岔已然成形:
| 維度 | 自架式 harness(本指南預設) | 託管式 harness(Claude Managed Agents/OpenAI Agents SDK) |
|---|---|---|
| 營運負擔 | 一切由您運行 | 廠商負責迴圈、沙盒與狀態 |
| 客製化程度 | 完全可控——自訂 hooks、skills 與記憶 | 受限——擴充點由廠商定義 |
| 成本模型 | Token 加上自架運算成本 | Token 加上 runtime 小時溢價 |
| 狀態持久性 | 由您自行設計 | 廠商在斷線間執行檢查點保存 |
| 代理團隊編排 | 自行打造 | 廠商提供的多代理協調機制 |
何時選擇何者: 自架式仍適合已具備基礎設施實力、希望掌控自家 skills/hooks,或正在深度優化特定工作流程的團隊。託管式則適合沒有專責平台工程師的團隊、當交付速度比客製化更重要時,或當代理執行需要可靠地撐過筆電闔上而您不想自行建構持久化層時。兩者並非互斥——您可以運行自架 harness,並透過其 REST API 將特定的長時間執行任務委派給 Managed Agents。
Harness 在磁碟上的樣貌
~/.claude/
├── CLAUDE.md # Personal global instructions
├── settings.json # User-level hooks and permissions
├── skills/ # Personal skills (44+)
│ ├── code-reviewer/SKILL.md
│ ├── security-auditor/SKILL.md
│ └── api-designer/SKILL.md
├── agents/ # Custom subagent definitions
│ ├── security-reviewer.md
│ └── code-explorer.md
├── rules/ # Categorized rule files
│ ├── security.md
│ ├── testing.md
│ └── git-workflow.md
├── hooks/ # Hook scripts
│ ├── validate-bash.sh
│ ├── auto-format.sh
│ └── recursion-guard.sh
├── configs/ # JSON configuration
│ ├── recursion-limits.json
│ └── deliberation-config.json
├── state/ # Runtime state
│ ├── recursion-depth.json
│ └── agent-lineage.json
├── handoffs/ # Session handoff documents
│ └── deliberation-prd-7.md
└── projects/ # Per-project memory
└── {project}/memory/MEMORY.md
.claude/ # Project-level (in repo)
├── CLAUDE.md # Project instructions
├── settings.json # Project hooks
├── skills/ # Team-shared skills
├── agents/ # Team-shared agents
└── rules/ # Project rules
此結構中的每個檔案都有其用途。~/.claude/ 樹狀目錄是適用於所有專案的個人基礎設施。各儲存庫中的 .claude/ 樹狀目錄則為專案專屬,並透過 git 共用。兩者結合,構成完整的 harness。
Skills System
Skills是由模型叫用的擴充功能。Claude會根據脈絡自動探索並套用它們,不需要您明確呼叫。4只要發現自己在不同工作階段反覆重新說明同一段脈絡,就是該建立skill的時候。
何時建立Skill
| 情境 | 建立… | 原因 |
|---|---|---|
| 每個工作階段都貼上同一份檢查清單 | Skill | 會自動啟用的領域專業知識 |
| 明確執行同一串命令序列 | Slash command | 由使用者叫用、觸發方式可預期的動作 |
| 需要隔離分析,避免污染脈絡 | Subagent | 用於專注工作的獨立脈絡視窗 |
| 需要一次性prompt並附上特定指示 | 無需建立 | 直接輸入即可。不是所有事情都需要抽象化。 |
Skills適合放置Claude永遠可用的知識。Slash commands則適合您明確觸發的動作。如果正在兩者之間取捨,請問自己:「Claude應該自動套用這項內容,還是應該由我決定何時執行?」
建立Skill
Skills可以放在4種位置,範圍由廣到窄如下:4
| 範圍 | 位置 | 適用對象 |
|---|---|---|
| Enterprise | Managed settings | 組織中的所有使用者 |
| Personal | ~/.claude/skills/<name>/SKILL.md |
您的所有專案 |
| Project | .claude/skills/<name>/SKILL.md |
僅此專案 |
| Plugin | <plugin>/skills/<name>/SKILL.md |
啟用plugin的位置 |
每個skill都需要一個含有YAML frontmatter的SKILL.md檔案:
---
name: code-reviewer
description: Review code for security vulnerabilities, performance issues,
and best practice violations. Use when examining code changes, reviewing
PRs, analyzing code quality, or when asked to review, audit, or check code.
allowed-tools: Read, Grep, Glob
---
# Code Review Expertise
## Security Checks
When reviewing code, verify:
### Input Validation
- All user input sanitized before database operations
- Parameterized queries (no string interpolation in SQL)
- Output encoding for rendered HTML content
### Authentication
- Session tokens validated on every protected endpoint
- Permission checks before data mutations
- No hardcoded credentials or API keys in source
Frontmatter參考
| 欄位 | 必填 | 用途 |
|---|---|---|
name |
是 | 唯一識別碼(小寫、連字號、最多64個字元) |
description |
是 | 探索觸發條件(最多1024個字元)。Claude會用它判斷何時套用skill |
allowed-tools |
否 | 限制Claude的能力(例如唯讀用的Read, Grep, Glob) |
disable-model-invocation |
否 | 防止自動啟用;skill只會透過/skill-name啟用 |
user-invocable |
否 | 設為false可完全從/選單隱藏 |
model |
否 | 覆寫skill啟用時使用的模型 |
context |
否 | 設為fork即可在隔離的脈絡視窗中執行 |
agent |
否 | 以subagent執行,並擁有自己的隔離脈絡 |
hooks |
否 | 定義限定於此skill的生命週期hooks |
$ARGUMENTS |
否 | 字串替換:會替換成使用者在/skill-name後輸入的內容 |
Description欄位至關重要
工作階段開始時,Claude Code會擷取每個skill的name和description,並注入Claude的脈絡。當您送出訊息時,Claude會使用語言模型推理判斷是否有相關skill。對Claude Code原始碼的獨立分析確認了此機制:skill descriptions會被注入系統prompt的available_skills區段,模型則使用標準語言理解來選擇相關skills。10
不佳的description:
description: Helps with code
有效的description:
description: Review code for security vulnerabilities, performance issues,
and best practice violations. Use when examining code changes, reviewing
PRs, analyzing code quality, or when asked to review, audit, or check code.
有效的description會包含:它做什麼(針對特定問題類型review code)、何時使用(檢查變更、PR、品質分析),以及使用者自然會輸入的觸發片語(review、audit、check)。
脈絡預算
所有skill descriptions共用一個脈絡預算,會以脈絡視窗的1%動態調整,並以8,000個字元作為後備值。4如果skills很多,請讓每個description保持精簡,並把關鍵使用情境放在最前面。您可以透過SLASH_COMMAND_TOOL_CHAR_BUDGET環境變數覆寫預算,11但更好的修正方式是寫出更短、更精準的descriptions。工作階段中執行/context,即可檢查是否有skills被排除。
支援檔案與組織方式
Skills可以參照同一目錄中的額外檔案:
~/.claude/skills/code-reviewer/
├── SKILL.md # Required: frontmatter + core expertise
├── SECURITY_PATTERNS.md # Referenced: detailed vulnerability patterns
└── PERFORMANCE_CHECKLIST.md # Referenced: optimization guidelines
請在SKILL.md中使用相對連結參照它們。Claude會在skill啟用時按需讀取這些檔案。請將SKILL.md控制在500行以內,並把詳細參考資料移到支援檔案中。12
透過Git分享Skills
Project skills(repo根目錄中的.claude/skills/)會透過版本控制分享:4
mkdir -p .claude/skills/domain-expert
# ... write SKILL.md ...
git add .claude/skills/
git commit -m "feat: add domain-expert skill for payment processing rules"
git push
隊友pull之後,就會自動取得skill。不需要安裝,也不需要設定。這是讓團隊共享專業知識最有效的方式。
Skills作為Prompt Library
除了單一用途skills之外,目錄結構也可作為井然有序的prompt library:
~/.claude/skills/
├── code-reviewer/ # Activates on: review, audit, check
├── api-designer/ # Activates on: design API, endpoint, schema
├── sql-analyst/ # Activates on: query, database, migration
├── deploy-checker/ # Activates on: deploy, release, production
└── incident-responder/ # Activates on: error, failure, outage, debug
每個skill都編碼了您專業知識的不同面向。合在一起,它們形成一個知識庫,讓Claude能根據脈絡自動取用。初階開發者不必開口,也能取得資深層級的指引。
Skills可與Hooks組合
Skills可以在frontmatter中定義自己的hooks,且只在skill執行期間啟用。這會建立特定領域的行為,同時不污染其他工作階段:2
---
name: deploy-checker
description: Verify deployment readiness. Use when preparing to deploy,
release, or push to production.
hooks:
PreToolUse:
- matcher: Bash
hooks:
- type: command
command: "bash -c 'INPUT=$(cat); CMD=$(echo \"$INPUT\" | jq -r \".tool_input.command\"); if echo \"$CMD\" | grep -qE \"deploy|release|publish\"; then echo \"DEPLOYMENT COMMAND DETECTED. Running pre-flight checks.\" >&2; fi'"
---
Philosophy skills會透過SessionStart hooks自動啟用,將品質約束注入每個工作階段,而不需明確叫用。Skill本身是知識。Hook則是執行約束。兩者合在一起,形成一層政策。
常見Skill錯誤
Descriptions過於寬泛。如果git-rebase-helper skill會在任何git相關prompt中啟用(rebase、merge、cherry-pick,甚至git status),就會污染80%的工作階段脈絡。修正方式是收緊description,或加入disable-model-invocation: true並要求明確透過/skill-name叫用。4
太多skills競爭預算。Skills越多,代表越多descriptions會競爭1%的脈絡預算。如果注意到skills沒有啟用,請用/context檢查被排除的項目。比起大量模糊的skills,應優先保留少量、描述清楚的skills。
關鍵資訊埋在支援檔案中。Claude會立即讀取SKILL.md,但只會在需要時存取支援檔案。如果關鍵資訊在支援檔案中,Claude可能找不到。請把必要資訊直接放在SKILL.md裡。4
SDK Skill介面(2026年5月8日)
基於claude-agent-sdk-python v0.1.77+的自架harness,應使用ClaudeAgentOptions上的skills選項宣告可用skills,而不是在allowed_tools中使用舊版"Skill"值。37"Skill"簡寫已被棄用,專用選項能讓Claude Code取得更結構化的資訊,了解哪些skills可用。v0.1.77中內建的CLI是v2.1.133。
.claude/skills/中的Plugin與Skill匯流(2026年5月29日)
Skills一直都會從專案的.claude/skills/目錄載入。Claude Code v2.1.157將該目錄延伸到plugins:放在.claude/skills/中的plugin現在無需marketplace註冊即可自動載入,而claude plugin init <name>會在該處搭建新的plugin骨架,並預先串好manifest與SKILL.md。58這彌合了過去分處不同位置的兩種專案工具形態:一種是直接commit到repo的裸skill,另一種是綁定skill、hooks與MCP server的plugin,但後者以往需要透過marketplace安裝。對harness設計的實際影響是:專案範圍工具不再需要繞道registry才能發布。寫好、commit,隊友在git pull後就會取得同一套介面。Plugins仍然負責可打包安裝的使用情境(hooks + skills + MCP servers + agents放在同一個ZIP);改變之處在於,專案不再需要只為了從自己的樹狀結構載入一個plugin,就架設marketplace。
將內建介面隱藏作為治理(2026年6月8日)
Skills是能力,而能力也是攻擊面。Claude Code v2.1.169加入disableBundledSkills設定(以及對應的CLAUDE_CODE_DISABLE_BUNDLED_SKILLS環境變數),可讓模型完全看不到內建skills、workflows與內建slash commands。60對經過強化或受監管的harness而言,這是刻意縮減攻擊面:已稽核並核准特定project與personal skills集合的operator,可以壓下Anthropic隨附的所有內容,讓模型只會針對operator審核過的介面進行推理。請把它視為tool allowlist。預設值代表廣泛能力,而關閉預設值是一項治理決策,不是便利性切換。
巢狀.claude/skills與Closest-Wins解析(2026年6月16日)
Claude Code v2.1.178讓專案工具具備位置感知能力。巢狀.claude/skills目錄中的skills現在會在您處理該目錄底下的檔案時載入,而不只從repo根目錄載入;如果名稱衝突,巢狀skill會顯示為<dir>:<name>,因此兩者都仍可存取。63同一版也讓其餘專案介面以最接近工作目錄的方式解析:當agent、workflow或output-style名稱在巢狀.claude/目錄之間衝突時,離工作目錄最近者勝出;而儲存project-scope workflow時,目標會是最接近的既有.claude/workflows/,不再一律是根目錄。63對monorepo或repo-of-repos而言,這就是單一扁平全域介面與按套件脈絡啟用的工具之間的差別。services/api/.claude/skills/可以承載API專屬skills,只有在該樹狀結構中工作時才會浮現,且不會與同名的services/web/ skill衝突。
Hook 架構
Hooks 是由 Claude Code 生命週期事件觸發的 shell commands。3它們以一般 scripts 形式在 LLM 外部執行,不是由模型解讀的 prompts。模型想執行 rm -rf /?一段 10 行的 bash script 會先對照 blocklist 檢查該 command,並在 shell 看到之前拒絕它。無論模型是否願意,hook 都會觸發。
可用事件
截至本指南更新時,Claude Code 在 8 個類別中公開了 29 個已記載的生命週期事件。事件清單會隨版本發布而增加,因此請把參考文件視為唯一可信來源;在接上 production hooks 前,請先查看 cheat sheet 的目前完整表格:13
| 類別 | 事件 | 可以封鎖? |
|---|---|---|
| Session | SessionStart, Setup, SessionEnd |
否 |
| User / completion | UserPromptSubmit, UserPromptExpansion, Stop, StopFailure, TeammateIdle |
Prompt/expansion/stop/idle 可以封鎖;StopFailure 不行 |
| Tool | PreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch |
Pre/permission/batch 可以封鎖;post events 不行 |
| Subagent / task | SubagentStart, SubagentStop, TaskCreated, TaskCompleted |
Stop/task events 可以封鎖;start 不行 |
| Context | PreCompact, PostCompact, InstructionsLoaded |
PreCompact 可以封鎖;post/load 不行 |
| Filesystem / workspace | CwdChanged, FileChanged, WorktreeCreate, WorktreeRemove |
Worktree 建立可以封鎖;其他不行 |
| Configuration / notification | ConfigChange, Notification |
Config changes 可以封鎖,但 policy settings 例外;notifications 不行 |
| MCP | Elicitation, ElicitationResult |
可以 |
Exit Code 語意
Exit codes 決定 hooks 是否封鎖動作:3
| Exit Code | 意義 | 動作 |
|---|---|---|
| 0 | 成功 | Operation 繼續。Stdout 會在 verbose mode 顯示。 |
| 2 | Blocking error | Operation 停止。Stderr 會成為送回 Claude 的錯誤訊息。 |
| 1, 3, etc. | Non-blocking error | Operation 繼續。Stderr 只會在 verbose mode 顯示(Ctrl+O)。 |
關鍵:每個 security hook 都必須使用 exit 2,不是 exit 1。Exit 1 是 non-blocking warning。危險 command 仍會執行。這是各團隊最常見的 hook 錯誤。14
Hook 設定
Hooks 放在 settings files 中。Project-level(.claude/settings.json)用於 shared hooks。User-level(~/.claude/settings.json)用於 personal hooks:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/validate-bash.sh"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash -c 'if [[ \"$FILE_PATH\" == *.py ]]; then black --quiet \"$FILE_PATH\" 2>/dev/null; fi'"
}
]
}
]
}
}
matcher 欄位會篩選特定事件的值。對 tool events 而言,它會比對 tool_name 值,例如 Bash、Edit、Write、Read、Glob、Grep、像 mcp__server__tool 這類 MCP tool names,或用 * 表示所有 tools。Simple names 和以 | 分隔的 lists 是 exact matches;含有其他字元的值則是 JavaScript regular expressions。有些 events 不支援 matchers,只要設定就一定會觸發。13
Hook Input/Output Protocol
Hooks 會從 stdin 收到含完整 context 的 JSON:
{
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite"
},
"session_id": "abc-123",
"agent_id": "main",
"agent_type": "main"
}
若需要進階控制,PreToolUse hooks 可以輸出 JSON 來修改 tool input、注入 context,或做出 permission decisions。請使用 hookSpecificOutput wrapper;較舊的 top-level decision/reason 格式已不建議用於 PreToolUse:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "Command validated and modified",
"updatedInput": {
"command": "npm test -- --coverage --ci"
},
"additionalContext": "Note: This database has a 5-second query timeout."
}
}
3 種保證
撰寫任何 hook 前,先問:我需要哪一種保證?14
格式保證會在事後確保一致性。Write/Edit 上的 PostToolUse hooks 會在每次檔案變更後執行 formatter。模型輸出並不重要,因為 formatter 會將一切正規化。
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash -c 'if [[ \"$FILE_PATH\" == *.py ]]; then black --quiet \"$FILE_PATH\" 2>/dev/null; elif [[ \"$FILE_PATH\" == *.js ]] || [[ \"$FILE_PATH\" == *.ts ]]; then npx prettier --write \"$FILE_PATH\" 2>/dev/null; fi'"
}
]
}
]
}
}
安全保證會在危險動作執行前阻止它們。Bash 上的 PreToolUse hooks 會檢查 commands,並以 exit code 2 封鎖 destructive patterns:
#!/bin/bash
# validate-bash.sh — block dangerous commands
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$CMD" | grep -qE "rm\s+-rf\s+/|git\s+push\s+(-f|--force)\s+(origin\s+)?main|git\s+reset\s+--hard|DROP\s+TABLE"; then
echo "BLOCKED: Dangerous command detected: $CMD" >&2
exit 2
fi
品質保證會在決策點驗證狀態。git commit commands 上的 PreToolUse hooks 會執行 linter 或 test suite,若 quality checks 失敗就封鎖 commit:
#!/bin/bash
# quality-gate.sh — lint before commit
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$CMD" | grep -qE "^git\s+commit"; then
if ! LINT_OUTPUT=$(ruff check . --select E,F,W 2>&1); then
echo "LINT FAILED -- fix before committing:" >&2
echo "$LINT_OUTPUT" >&2
exit 2
fi
fi
Shell Commands 以外的 Hook 類型
Claude Code 支援 5 種 hook types:13
Command hooks(type: "command")會執行 shell scripts。快速、可預測,而且沒有 token cost。
MCP tool hooks(type: "mcp_tool")會呼叫已連線 MCP server 上的 tool。當 validation logic 已經位於 MCP 邊界後方,且不需要另外寫 shell script 時,適合使用它們。
Prompt hooks(type: "prompt")會把 single-turn prompt 傳給快速的 Claude model。模型回傳 { "ok": true } 表示允許,或 { "ok": false, "reason": "..." } 表示封鎖。適合用於 regex 無法表達的細緻評估。
Agent hooks(type: "agent")會產生具備 tool access(Read、Grep、Glob)的 subagent 來進行 multi-turn verification。它們仍屬實驗性;production gates 請優先使用 command hooks,只有在檢查確實需要檢視實際檔案或 test output 時,才保留 agent hooks:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "agent",
"prompt": "Verify all unit tests pass. Run the test suite and check results. $ARGUMENTS",
"timeout": 120
}
]
}
]
}
}
截至 Claude Code v2.1.140,agent hook input 包含 subagent_type,可讓 shared hook 區分 security-reviewer run、explorer 或 generic worker,而不必從 prompt text 猜測。49
HTTP hooks(type: "http")會把 event 的 JSON input 以 POST request 傳送到 URL,並接收 JSON 回來。適用於 webhooks、external notification services,或以 API 為基礎的 validation(v2.1.63+)。不支援 SessionStart events:
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "http",
"url": "https://your-webhook.example.com/hook",
"headers": { "Authorization": "Bearer $WEBHOOK_TOKEN" },
"allowedEnvVars": ["WEBHOOK_TOKEN"],
"timeout": 10
}
]
}
]
}
}
Async Hooks
Hooks 可以在背景執行而不封鎖 execution。對 notifications 和 logging 這類非關鍵操作,加入 async: true:13
{
"type": "command",
"command": ".claude/hooks/notify-slack.sh",
"async": true
}
Async 適合 notifications、telemetry 和 backups。絕不要將 async 用於 formatting、validation,或任何必須在下一個動作前完成的事項。
Dispatchers 優於獨立 Hooks
若同一個 event 觸發 7 個 hooks,且每個 hook 都各自讀取 stdin,會產生 race conditions。兩個 hooks 同時寫入同一個 JSON state file,會截斷該 JSON。所有後續解析該檔案的 hooks 都會壞掉。2
解法是:每個 event 使用一個 dispatcher,從 cached stdin 依序執行 hooks:
#!/bin/bash
# dispatcher.sh — run hooks sequentially with cached stdin
INPUT=$(cat)
HOOK_DIR="$HOME/.claude/hooks/pre-tool-use.d"
for hook in "$HOOK_DIR"/*.sh; do
[ -x "$hook" ] || continue
echo "$INPUT" | "$hook"
EXIT_CODE=$?
if [ "$EXIT_CODE" -eq 2 ]; then
exit 2 # Propagate block
fi
done
Debugging Hooks
以下是 debugging hooks 靜默失敗的 5 個技巧:14
- 獨立測試 scripts。Pipe sample JSON:
echo '{"tool_input":{"command":"git commit -m test"}}' | bash your-hook.sh - 使用 stderr 輸出 debug 資訊。Exit code 2 的 stderr 會作為錯誤訊息回饋給 Claude。Non-blocking stderr(exit 1、3 等)只會在 verbose mode(Ctrl+O)中出現。
- 留意 jq failures。錯誤的 JSON paths 會靜默回傳
null。請用真實 tool input 測試jqexpressions。 - 確認 exit codes。使用
exit 1的 PreToolUse hook 看似有效,實際上沒有任何強制力。 - 保持 hooks 快速。Hooks 會同步執行。所有 hooks 都應低於 2 秒,最好低於 500ms。
SDK 端 Hook Event Streaming
以 claude-agent-sdk-python(v0.1.74+,2026年5月6日)建置的 self-hosted harnesses,可以直接從 message stream 訂閱 hook events,而不必透過 shell-script callbacks。36在 ClaudeAgentOptions 設定 include_hook_events=True 後,HookEventMessage objects(PreToolUse、PostToolUse、Stop 等)會從與 assistant messages 和 tool results 相同的 iterator 產出。這呼應了 TypeScript SDK 的 includeHookEvents option;同一版也將 bundled CLI 升到 v2.1.129。
當 harness 本身已經位於 Python 中,而且您希望 hook signals 與 model output 位在同一段 control flow 裡,event-stream pattern 就很合適。對於會組合多個 tools、跨 Claude Code 與 Codex 共享 hooks,或需要 exit-code semantics 來封鎖的 harnesses,shell-script hook contract(exit codes、stdin JSON、dispatchers)仍然是正解。
Effort 和 Session Provenance(2026年5月7-8日)
Claude Code v2.1.132 和 v2.1.133 的兩項新增功能,讓 hooks 和 subprocesses 更清楚掌握其 execution context:3839
- hook input 中的
effort.level。Hooks 現在會在同一份帶有tool_input和session_id的 input 中,收到effort.levelJSON 欄位。同一個值也會匯出為$CLAUDE_EFFORTenv var,因此 Bash commands 不必解析 JSON 就能讀取。可用它依 effort tier 調整 hook cost:在low跳過昂貴 validation,在xhigh或max執行完整 security gate。 - Bash subprocesses 上的
CLAUDE_CODE_SESSION_IDenv var。Bash tool subprocesses 現在會看到與 hooks 相同的session_id值,並以CLAUDE_CODE_SESSION_ID暴露。這補上了 provenance gap;過去記錄 per-session state 的 tools 無法將 subprocess events 與 hook events 關聯起來。
這兩個 signals 不需要修改程式碼即可使用;既有 hooks 若忽略新欄位,仍會繼續運作。
autoMode.hard_deny 和 v2.1.136 Hook/Plugin 修正(2026年5月8日)
Claude Code v2.1.136 為 auto mode 新增 hard-deny tier,並修正一批影響 long-running harnesses 的 plugin 和 MCP 問題:40
settings.autoMode.hard_deny。Auto mode classifier rules 會無條件封鎖,不受 user intent 或 allow exceptions 影響。它位於既有 allow/deny matchers 之上,是不可協商的 governance lever。請將它用於絕不能被覆寫的規則(force-push to main、含有 secrets 的檔案、production database access),即使 operator 已在個人設定中核准更廣泛類別也一樣。- MCP servers 不再於
/clear後消失。在 VS Code extension、JetBrains plugin 和 Agent SDK 中,設定於.mcp.json、plugins 和 claude.ai connectors 的 servers 曾在/clear後靜默從 active set 掉出。修正在 v2.1.136 落地。如果您看過「MCP server X went missing mid-session」,原因就是這個。 - MCP OAuth refresh-token 在 concurrent refresh 時遺失。擁有多個 remote MCP servers 的使用者,應該不再需要每天重新驗證。Concurrent refresh writes 之前會彼此覆寫。
- Plan mode 現在會正確封鎖 file writes。相符的
Edit(...)allow rule 之前會繞過 plan-mode write protection。現在無論 allow rules 如何,Plan mode 都會被強制執行。 - Plugin
Stop和UserPromptSubmithooks 不再於 mid-session 失敗。Cache cleanup 之前會刪除仍被 running session 使用的 plugin-version files,特別導致這兩個 hook events 壞掉。修正後會將 in-use versions 固定保留。 plugin.json中的skillsentry。設定skills之前會隱藏 plugin 的預設skills/目錄。現在該 entry 會正確組合;若指向 file path,會明確報錯,而不是靜默失敗。CLAUDE_ENV_FILESessionStart hook env vars 過期。SessionStart hooks 透過CLAUDE_ENV_FILE匯出的 vars,之前會在/resume或/clear後過期。v2.1.136 已修正。Sessions 現在會在這些 events 重新 source env file。
對 governance harnesses 而言,操作上最值得注意的是 autoMode.hard_deny(新的 lever)和 MCP 消失問題的修正(會破壞 long sessions 的 silent failure)。其他都是 quality-of-life cleanup。
Structured Hook Arguments 和 Block Continuation(2026年5月11日)
Claude Code v2.1.139 新增兩個對 production harnesses 重要的 hook 細節:command hooks 的 args: string[] exec form,以及 PostToolUse hooks 的 continueOnBlock。4244當 hook 需要 dynamic values 或 path placeholders 時,請優先使用 args。它會直接 spawn command,不經 shell,因此排除一整類 quoting 和 injection 錯誤。
當 PostToolUse hook 應將 rejection reason 回饋給 Claude 並繼續該 turn,而不是結束流程時,使用 continueOnBlock。請把它視為 operator-experience 功能,不是 security bypass。Blocking gate 仍應封鎖 unsafe outcome。
同一版本會把 CLAUDE_PROJECT_DIR 傳給 MCP stdio servers,並讓 plugin configs 在 commands 中引用 ${CLAUDE_PROJECT_DIR}。42MCP tools 應從該值解析 project-relative paths,而不是依賴剛好啟動 server 的 process working directory。
Claude Code v2.1.140 主要是給 harness operators 的 reliability release:它修正 settings changes 時 ConfigChange hooks 不觸發的問題,補上 disableAllHooks 和 allowManagedHooksOnly 在不同 settings levels 間無法正確組合的 edge cases,並避免 permission dialogs 暴露由 hook results 回傳的非預期 environment variables。49這讓本節既有 governance patterns 更可靠;不需要新的 hook architecture。
Claude Code v2.1.141 新增 hook-output terminalSequence 欄位,可在沒有 controlling terminal 的情況下用於 desktop notifications、window titles 和 bells。50請把它視為 operator signaling,而非 enforcement。Security 和 quality gates 仍應透過一般 blocking contract 溝通失敗:structured hook output 加上阻止 unsafe action 的 exit behavior。同一版本也新增 claude agents --cwd <path>,用於將 Agent View 限定到單一目錄;新增 CLAUDE_CODE_PLUGIN_PREFER_HTTPS,供沒有 GitHub SSH keys 的環境安裝 plugins;並新增 ANTHROPIC_WORKSPACE_ID,用於涵蓋多個 workspace 的 workload-identity federation rules。50這些都是 team harnesses 的 architecture details:更窄的 operational views、更少的 plugin-install assumptions,以及明確的 enterprise token scoping。
Claude Code v2.1.142 對 background-session orchestration 的重要性高於 hook semantics。51claude agents 現在可以使用明確的 directory、settings、MCP、plugin、permission、model 和 effort flags dispatch background sessions,而不必依賴 wrapper state。Fast mode 現在預設使用 Opus 4.7;只有在 harness 已量測出對 Opus 4.6 行為有依賴時,才 pin CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE=1。Root-level plugin SKILL.md discovery 和 plugin-provided LSP visibility 可降低 packaging ambiguity。針對 MCP_TOOL_TIMEOUT、pre-existing background-session worktrees、daemon sleep/wake 和 post-upgrade cleanup,以及 plugin cache cleanup 的修正,補上了否則看起來像 orchestration bugs 的 reliability gaps。
Stop-hook steering、cross-session authority 和 multi-agent v2(2026年6月)
6 月初的 4 項變更,對 harness 和 multi-agent design 很重要。59
Stop/SubagentStop hooks 取得 steering channel。自 Claude Code v2.1.163 起,Stop 或 SubagentStop hook 可以回傳 hookSpecificOutput.additionalContext,將 feedback 交給 Claude 並讓 turn 繼續,而不會把 response 標示為 hook error。在此之前,Stop hook 真正可用的 lever 只有 exit-2 block;它會顯示成 error,且計入 consecutive-block cap。對 quality-gate harness 來說,這是更乾淨的 primitive:偵測到「你說完成但 tests 還是紅的」的 Stop hook,現在可以注入「以下仍在失敗,請繼續」,而不是 hard-block。真正的停止條件才使用 block;「尚未完成,原因如下」則使用 additionalContext。
Cross-session messaging 不再攜帶借來的 authority。v2.1.166 強化了 multi-session 情境:透過 SendMessage 從另一個 Claude session 轉送的 messages,不再帶有 originating user 的 authority,因此 receiving session 會拒絕 relayed permission requests,auto mode 也會封鎖它們。如果您的 orchestration 讓 agents 彼此傳訊,請把 inbound message 視為 untrusted data,而不是 authenticated instruction。這與 security section 套用到 tool output 的原則相同,只是延伸到 inter-agent messaging。
Model resilience 成為一等設定。fallbackModel setting 現在最多可串接 3 個 backup models,當 primary overloaded 或 unavailable 時依序嘗試;若遇到 unexpected non-retryable API errors,該 turn 也會在 fallback 上自動重試一次。對 long-running autonomous harness 來說,這會把短暫的 primary-model outage 轉化為 graceful degradation,而不是 dropped run。claude agents --json 也新增 waitingFor 欄位(v2.1.162),可揭露 blocked background session 正在等待什麼,例如 permission prompt;對任何輪詢 agent fleet 的 coordinator 都是 observability 上的提升。
用於 clean-room governance 和 troubleshooting 的 Safe mode。Claude Code v2.1.169 新增 --safe-mode flag(以及對應的 CLAUDE_CODE_SAFE_MODE environment variable),可在啟動 session 時一次停用所有 customization:CLAUDE.md、plugins、skills、hooks 和 MCP servers。60這是 harness 的反向操作:刻意的 clean-room。用它回答每位 operator 終究會問的問題:「這個行為來自模型,還是來自我設定的東西?」當 hook 誤觸、skill 在不該啟動時啟動,或 MCP server 汙染 context,--safe-mode 會提供已知為空的 baseline 供您比對。它也是 governance primitive:一種在沒有 harness 平常授予之 persistent authority 的情況下執行裸模型的方法。當您需要重現結果,且不讓任何 operator-defined scaffolding 影響它時,這點很重要。
關於 model tiers 的說明。本指南將 Opus 4.8 視為 Claude Code 的 agentic default,也就是除非另行選擇,否則用於執行 autonomous harnesses 的模型。截至 2026年6月9日,Anthropic 推出 Claude Fable 5(claude-fable-5),這是位於 Opus 之上的新 tier,被描述為其最強大的模型,也就是可供一般使用且經安全化的「Mythos-class」系統,可在 Claude Code v2.1.170 透過 /model claude-fable-5 選用。60Opus 4.8 仍是 agentic default;請在 raw reasoning depth 足以合理化成本的決策上,刻意選用更高 tier,而不是把它當作整個 fleet 的 blanket setting。
Codex 發布 multi-agent v2。Codex CLI v0.137.0 讓 runtime choice 留在每個 thread 上,為 spawned agents 提供更乾淨的 follow-up 和 metadata defaults(hide_spawn_agent_metadata 現在預設為 true),並將 raw parent events 傳播給 child listeners。它的 subagent model 維持明確:built-in default/worker/explorer agent types、以 TOML 定義的 custom agents,以及 concurrency controls(agents.max_threads 預設 6,agents.max_depth 預設 1)。同一版本新增 v1 skills extension,具備 per-turn skill-catalog resolution 和新的 thread-start/turn-error lifecycle contributor events,在保留 kernel-sandbox posture 作為預設邊界的同時,縮小與 Claude Code hook/skill surface 的差距。接著 Codex v0.138.0–v0.139.0 將 multi-agent v2 強化到可用於 production:inter-agent message payloads 現在已加密,v2 agent config catalog 加上 agent-residency LRU 會管理哪些 agents 保持 resident,而 concurrency 依 active execution 計算,不再依 spawned threads 計算,所以 idle agents 不再占用 slot。61lifecycle API 也更成熟;close_agent 更名為 interrupt_agent(v0.139.0),以反映它是 interrupt running agent,而不只是關閉 handle;由 subagent 引發的 MCP startup warnings 現在會限定在 owning thread,不會重複冒到 parent transcript。61對任何建置 Codex-side orchestration 的人而言,這些就是 demo 和 fleet 的差別:encrypted message transport、bounded residency、execution-counted concurrency,以及不會跨 thread boundary 洩漏的 warnings。Codex v0.140.0 接著開啟跨 tool seam:/import 可從 Claude Code 選擇性拉取 setup、project config 和 recent chats 到 Codex,而 sessions 也變成可永久刪除(codex delete / /delete,含 confirmation safeguards)。64/import 是官方第一次承認 operators 會在 harnesses 之間移動;您為其中一個建立的 configuration,不再被困在原地。
記憶與脈絡
每一段 AI 對話都在有限的 context window 內運作。隨著對話變長,系統會壓縮較早的回合,為新內容騰出空間。這種壓縮會造成資訊流失。第 3 輪記錄的架構決策,到了第 15 輪可能已不復存在。9
多輪崩解的 3 種機制
MSR/Salesforce 研究指出 3 種彼此獨立的機制,每一種都需要不同的介入方式:9
| 機制 | 會發生什麼 | 介入方式 |
|---|---|---|
| Context compression | 較早資訊被捨棄,以容納新內容 | 將狀態 checkpoint 到檔案系統 |
| Reasoning coherence loss | 模型在不同回合之間,與自己先前的決策互相矛盾 | Fresh-context iteration(Ralph loop) |
| Coordination failure | 多個 agents 持有不同的狀態快照 | agents 之間使用共享狀態協定 |
策略 1:以檔案系統作為記憶
跨越 context 邊界時,最可靠的記憶存在於檔案系統中。Claude Code 會在每個 session 開始時,以及每次 compaction 後,讀取 CLAUDE.md 和記憶檔案。6
~/.claude/
├── configs/ # 14 JSON configs (thresholds, rules, budgets)
│ ├── deliberation-config.json
│ ├── recursion-limits.json
│ └── consensus-profiles.json
├── hooks/ # 95 lifecycle event handlers
├── skills/ # 44 reusable knowledge modules
├── state/ # Runtime state (recursion depth, agent lineage)
├── handoffs/ # 49 multi-session context documents
├── docs/ # 40+ system documentation files
└── projects/ # Per-project memory directories
└── {project}/memory/
└── MEMORY.md # Always loaded into context
MEMORY.md 檔案會跨 session 記錄錯誤、決策與模式。當您發現 bash 中 VAR 為 0 時,set -e 會讓 ((VAR++)) 失敗,就應該記錄下來。3 個 session 之後,當您在 Python 遇到類似的整數邊界案例時,MEMORY.md 條目就會浮現這個模式。15
Auto Memory(v2.1.32+): Claude Code 會自動記錄並回想專案脈絡。工作期間,Claude 會將觀察寫入 ~/.claude/projects/{project-path}/memory/MEMORY.md。Auto memory 會在 session 開始時,將前 200 行載入 system prompt。請保持精簡,並連結到獨立的主題檔案以存放詳細筆記。6
記憶整理優先於記憶量(2026 年 5 月): 一篇近期關於 LLM-agent cooperation 的 arXiv 預印本,將擴大 recall 視為可能的失敗模式:在作者的實驗中,更長的可見歷史在 28 組 model-game 設定中的 18 組降低了合作表現。48 請把這視為設計警訊,而不是已成定律。production 規則已經足夠清楚:保持 MEMORY.md 簡短、連結到詳細資料,並在 handoffs 中放入可供決策的摘要。原始逐字稿傾印、tool logs 和冗長 recall feeds 應放在可搜尋的儲存空間,而不是自動進入 active prompt。
策略 2:主動 Compaction
Claude Code 的 /compact command 會摘要對話並釋放 context 空間,同時保留關鍵決策、檔案內容與任務狀態。15
何時 compact: - 完成一個明確子任務後(功能已實作、bug 已修復) - 開始處理 codebase 的新區域前 - 當 Claude 開始重複或遺忘先前脈絡時 - 在高強度 session 中,大約每 25-30 分鐘一次
CLAUDE.md 中的自訂 compaction instructions:
# Summary Instructions
When using compact, focus on:
- Recent code changes
- Test results
- Architecture decisions made this session
Compaction 保護對話;/cd command(Claude Code v2.1.169)保護 prompt cache。它能在不中斷該回合已累積 cache 的情況下,將 session 在中途移到新的 working directory。60 在此之前,變更目錄代表必須開啟新的 session,cache 也會變冷。對於長時間執行、需要從一個 repository 轉向 sibling repository 的 session,這在 monorepo 和多服務工作中很常見,/cd 能保留昂貴的 cached prefix,同時重新指向檔案系統脈絡。
策略 3:Session Handoffs
對於橫跨多個 session 的任務,請建立 handoff documents 來捕捉完整狀態:
## Handoff: Deliberation Infrastructure PRD-7
**Status:** Hook wiring complete, 81 Python unit tests passing
**Files changed:** hooks/post-deliberation.sh, hooks/deliberation-pride-check.sh
**Decision:** Placed post-deliberation in PostToolUse:Task, pride-check in Stop
**Blocked:** Spawn budget model needs inheritance instead of depth increment
**Next:** PRD-8 integration tests in tests/test_deliberation_lib.py
Status/Files/Decision/Blocked/Next 結構能以最低 token 成本,為後續 session 提供完整脈絡。使用 claude -c(continue)開始新的 session,或讀取 handoff document,都能直接進入實作。15
策略 4:Fresh-Context Iteration(Ralph Loop)
對於超過 60-90 分鐘的 sessions,每次 iteration 都啟動一個新的 Claude instance。狀態透過檔案系統延續,而不是透過對話記憶延續。每個 iteration 都能取得完整的 context budget:16
Iteration 1: [200K tokens] -> writes code, creates files, updates state
Iteration 2: [200K tokens] -> reads state from disk, continues
Iteration 3: [200K tokens] -> reads updated state, continues
...
Iteration N: [200K tokens] -> reads final state, verifies criteria
與單一長 session 相比:
Minute 0: [200K tokens available] -> productive
Minute 30: [150K tokens available] -> somewhat productive
Minute 60: [100K tokens available] -> degraded
Minute 90: [50K tokens available] -> significantly degraded
Minute 120: [compressed, lossy] -> errors accumulate
每個 iteration 使用 fresh context 的做法,會以 15-20% 的額外成本換取 orient step(讀取狀態檔案、掃描 git history),但每次 iteration 都能保有完整的認知資源。16 成本效益計算如下:60 分鐘以內的 sessions,單一對話效率較高。超過 90 分鐘後,即使有額外成本,fresh-context 仍會產生品質更高的輸出。
策略 5:Managed Memory Curation(Dreaming)
Anthropic 的 Claude Managed Agents 於 2026 年 5 月 6 日將 Dreaming 加入為 Research Preview。35 根據 Anthropic:「Dreaming 是一個排程程序,會檢閱您的 agent sessions 和 memory stores,擷取模式並整理記憶,讓您的 agents 隨時間改進。」35
Dreaming 在 sessions 之間於背景執行,不位於 critical path。它是對 filesystem-as-memory 模式的補充,而非取代:您的 MEMORY.md 檔案仍是承重面;Dreaming 會將整理過的記憶條目寫入 Managed Agents memory store,agent 會在 session 開始時讀取。對於同時混用自架檔案系統狀態與 managed-side curation 的 harnesses,這兩種模式可以並存。
| Filesystem Memory | Dreaming(Managed) | |
|---|---|---|
| 記憶存放位置 | 您的 repo,納入版本控制 | Anthropic 管理的 memory store |
| 更新時機 | 您手動寫入條目,或透過 hooks 寫入 | sessions 之間的背景程序 |
| 捕捉內容 | 您標記的決策、錯誤、模式 | 從 session history 擷取的模式 |
| 最適合 | 專案專屬的組織知識 | 跨 session、手動難以察覺的模式探索 |
Dreaming 仍處於 Research Preview,因此行為可能改變。上文記錄的 session-handoffs 和 CLAUDE.md patterns,仍是 self-hosted harnesses 的權威記憶機制。
反模式
只需要 10 行,卻讀取整個檔案。 單次讀取 2,000 行檔案會消耗 15,000-20,000 tokens。請使用行偏移:Read file.py offset=100 limit=20 能省下絕大多數成本。15
將冗長錯誤輸出留在 context 中。 除錯完成後,您的 context 可能仍保留 40 多個失敗 iteration 的 stack traces。修好 bug 後執行一次 /compact,就能釋放這些多餘負擔。
每個 session 一開始就讀取所有檔案。 讓 Claude Code 的 glob 和 grep tools 依需求尋找相關檔案,避免預先載入 100,000+ tokens 的不必要內容。15
Subagent 模式
Subagents 是專門化的 Claude 實例,能獨立處理複雜任務。它們會以乾淨的 context 啟動(不受主對話污染),使用指定 tools 執行作業,並以摘要形式回傳結果。探索結果不會膨脹您的主對話;只有結論會回傳。5
內建 Subagent 類型
| 類型 | Model | 模式 | Tools | 適用情境 |
|---|---|---|---|---|
| Explore | Haiku(快速) | 唯讀 | Glob, Grep, Read, safe bash | 探索 codebase、尋找檔案 |
| General-purpose | 繼承 | 完整讀寫 | 所有可用項目 | 複雜研究+修改 |
| Plan | 繼承(或 Opus) | 唯讀 | Read, Glob, Grep, Bash | 執行前規劃 |
建立自訂 Subagents
在 .claude/agents/(專案)或 ~/.claude/agents/(個人)中定義 subagents:
---
name: security-reviewer
description: Expert security code reviewer. Use PROACTIVELY after any code
changes to authentication, authorization, or data handling.
tools: Read, Grep, Glob, Bash
model: opus
permissionMode: plan
---
You are a senior security engineer reviewing code for vulnerabilities.
When invoked:
1. Identify the files that were recently changed
2. Analyze for OWASP Top 10 vulnerabilities
3. Check for secrets, hardcoded credentials, SQL injection
4. Report findings with severity levels and remediation steps
Focus on actionable security findings, not style issues.
Subagent 設定欄位
| 欄位 | 必填 | 用途 |
|---|---|---|
name |
是 | 唯一識別碼(小寫+連字號) |
description |
是 | 何時叫用(加入「PROACTIVELY」可鼓勵自動委派) |
tools |
否 | 以逗號分隔。若省略,會繼承所有 tools。支援 Agent(agent_type) 以限制可生成的 agents |
disallowedTools |
否 | 要拒絕的 tools,會從繼承或指定清單中移除。自 v2.1.178 起,MCP 伺服器層級規格(mcp__server、mcp__server__*、mcp__*)會在此正確比對;較早版本會靜默忽略這些規則,因此原本用來封鎖 MCP 伺服器的 deny rule 實際上不會生效。63 |
model |
否 | sonnet、opus、haiku、inherit(預設:inherit) |
permissionMode |
否 | default、acceptEdits、delegate、dontAsk、bypassPermissions、plan |
maxTurns |
否 | subagent 停止前的最大 agentic turns 數 |
memory |
否 | 持久化 memory 範圍:user、project、local |
skills |
否 | 啟動時自動將 skill 內容載入 subagent context。自 v2.1.133 起,subagents 也會透過 Skill tool 探索專案、使用者與 plugin skills,方式與父 session 相同。較早版本會靜默地將這些內容從 subagent context 中丟棄。39 |
hooks |
否 | 限定於此 subagent 執行的生命週期 hooks |
background |
否 | 一律作為背景任務執行 |
isolation |
否 | 設為 worktree 以使用隔離的 git worktree 副本 |
Worktree 隔離
Subagents 可以在暫時性的 git worktrees 中運作,提供完整且隔離的 repository 副本:5
---
name: experimental-refactor
description: Attempt risky refactoring in isolation
isolation: worktree
tools: Read, Write, Edit, Bash, Grep, Glob
---
You have an isolated copy of the repository. Make changes freely.
If the refactoring succeeds, the changes can be merged back.
If it fails, the worktree is discarded with no impact on the main branch.
Worktree 隔離對可能破壞 codebase 的實驗性工作至關重要。
平行 Subagents
對於不需要彼此協調的獨立研究任務,使用平行 subagents:5
> Have three explore agents search in parallel:
> 1. Authentication code
> 2. Database models
> 3. API routes
每個 agent 都在自己的 context window 中執行,找出相關程式碼,並回傳摘要。主 context 保持乾淨。
Recursion Guard
如果沒有 spawn 限制,agents 會委派給 agents,而後者再委派給其他 agents;每一層都會遺失 context 並消耗 tokens。recursion guard 模式會強制執行預算:16
#!/bin/bash
# recursion-guard.sh — enforce spawn budget
CONFIG_FILE="${HOME}/.claude/configs/recursion-limits.json"
STATE_FILE="${HOME}/.claude/state/recursion-depth.json"
MAX_DEPTH=2
MAX_CHILDREN=5
DELIB_SPAWN_BUDGET=2
DELIB_MAX_AGENTS=12
# Read current depth
current_depth=$(jq -r '.depth // 0' "$STATE_FILE" 2>/dev/null)
if [[ "$current_depth" -ge "$MAX_DEPTH" ]]; then
echo "BLOCKED: Maximum recursion depth ($MAX_DEPTH) reached" >&2
exit 2
fi
# Increment depth using safe arithmetic (not ((VAR++)) with set -e)
new_depth=$((current_depth + 1))
jq --argjson d "$new_depth" '.depth = $d' "$STATE_FILE" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"
關鍵教訓: 使用 spawn budgets,而不只是 depth limits。以深度為基礎的限制會追蹤父子鏈(例如深度 3 時封鎖),但會漏掉寬度問題:深度 1 有 23 個 agents,仍然只是「depth 1」。spawn budget 會追蹤每個 parent 的 active children 總數,並以可設定的最大值封頂。budget model 對應的是實際失敗模式(agents 總數過多),而不是替代指標(巢狀層級過多)。7
遞迴委派現在是一級支援的深度能力。 自 Claude Code v2.1.172(2026年6月10日)起,sub-agents 可以生成自己的 sub-agents,最多巢狀 5 層;過去委派實際上只能到 1 層。62 這讓上方的 recursion guard 更加重要,而不是更不重要:平台現在允許的,正是 agents 委派給 agents、並燃燒 context 與 tokens 的鏈條。因此 spawn budget 與 depth cap 才是避免 5 層樹狀結構擴散成數百個 active agents 的關鍵。請將 5 層視為平台允許的上限,而不是預設應追求的目標。
Auto mode 現在會在 spawns 啟動前進行審核。 Claude Code v2.1.178 補上了 matching governance 的缺口:在 auto mode 中,subagent spawns 會在 subagent 啟動前,由 permission classifier 評估,而不是等它開始採取行動後才評估。63 過去,subagent 可能被生成來請求 parent session 原本會被阻擋的動作,而 spawn 本身就是繞過點。在 spawn time 進行審核,意味著 recursion guard 與 permission model 終於接上:child 不能被用來漂白 policy 禁止的動作。
Agent Teams(Research Preview)
Agent Teams 會協調多個 Claude Code 實例;它們各自獨立工作,透過共用 mailbox 與 task list 溝通,也能挑戰彼此的發現:5
| 元件 | 角色 |
|---|---|
| Team lead | 建立 team、生成 teammates、協調工作的主 session |
| Teammates | 處理指派任務的獨立 Claude Code 實例 |
| Task list | teammates 會認領並完成的共用工作項目(以 file lock 保護) |
| Mailbox | 用於 inter-agent communication 的訊息系統 |
啟用方式:export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
何時使用 agent teams,而非 subagents:
| Subagents | Agent Teams | |
|---|---|---|
| Communication | 只回報結果 | Teammates 可直接互相傳訊 |
| Coordination | Main agent 管理所有工作 | 共用 task list,並可自我協調 |
| Best for | 只在意結果的聚焦任務 | 需要討論與協作的複雜工作 |
| Token cost | 較低 | 較高(每位 teammate=獨立 context window) |
Agent View 與 Goal Loops(2026年5月)
Claude Code v2.1.139 加入了 Agent View,這是一個以 claude agents 啟動的 research-preview 介面,可在同一個畫面查看執行中、遭封鎖與已完成的 Claude Code sessions。4243 官方文件將它描述為一種 dispatch 並管理多個 sessions、查看每個 session 正在做什麼,以及辨識哪些 session 需要操作員輸入的方式。43 這讓 multi-agent 工作擁有最終摘要無法提供的 operations view。
在推廣 subagent 或 team 模式時使用 Agent View:檢查哪些 sessions 遭封鎖、哪些仍在執行,以及工作分配是否符合預期架構。不要把它當作品質證明。它是 observability;tests、review gates 與 evidence reports 仍然決定工作是否健全。
同一版本也加入了 /goal,可設定 completion condition,並讓 Claude 跨 turns 持續執行直到條件達成;支援 interactive、-p 與 Remote Control 使用。42 請將 /goal 視為 session-scoped completion loop,而不是 deterministic gates 的替代品。它有助於讓 agent 專注在目標上,但凡是失敗必須阻擋流程的地方,tests、citation checks、deploy checks 與 security hooks 仍應由 command 或 script 支撐。
Workflow Tool(v2.1.147+)
Claude Code v2.1.147 加入了預設關閉的 Workflow tool,用於 deterministic multi-agent orchestration。使用 CLAUDE_CODE_WORKFLOWS=1 啟用。52 從架構上看,這一點很重要,因為它為 Claude Code 提供第一方 orchestration primitive,可處理過去需要自訂 dispatch scripts、mailbox state 與 subagent coordination conventions 的流程。
不要刪除其周邊 harness。Workflow 可以結構化執行,但不會取代您的 safety model。保留 PreToolUse 與 PostToolUse hooks 作為阻擋層;保留 spawn budgets 或 workflow step budgets,以防止寬度失控;讓 filesystem state 可稽核;並讓最終 evidence reports 位於 model 自我評估之外。實務上:用 Workflow 定義 orchestration shape;用 hooks、tests 與 review gates 判定真相。
多代理人協作
單一代理人 AI 系統存在結構性盲點:無法質疑自身的假設。7 多代理人協商在任何決策定案前,強制從多個角度進行獨立評估。
跨工具協作(2026年4月): Google 於 4 月 7 日開源 Scion — 這是一個多代理人 hypervisor,可將 Claude Code、Gemini CLI 及其他「深度代理人」作為並行行程執行,每個代理人都擁有獨立的容器、git worktree 與憑證。可在本機、hub 或 Kubernetes 上執行。其明確的設計理念是「以隔離取代約束」— 代理人在基礎架構層強制的邊界內以高度自主性運作,而非依賴提示中的限制。25 這直接將 subagent 隔離的論述延伸至不同工具廠商之間。若您的工作流程橫跨 Claude 與 OpenAI 模型,Scion 是首個真正可作為跨工具 subagent 參考實作的方案,提供每個代理人專屬的 worktree 與憑證隔離。
辯論並非萬靈丹: M3MAD-Bench 研究群組(2026 年初)發現,多代理人辯論會出現停滯,且可能被誤導性共識顛覆 — 當其他代理人自信地堅持錯誤答案時,正確的論點反而會落敗。26 Tool-MAD 透過讓每個代理人擁有異質的工具存取權限,並在裁判階段使用 Faithfulness/Relevance 分數來改善此問題。若您正在建構辯論式協作架構,應投資於(a)每個代理人的工具異質性,以及(b)量化的裁判評分,而非假設代理人愈多答案就愈好。
託管多代理人協作與成果(公開測試版)
如果您不想自行建構下方所述的協商基礎架構,Multiagent Orchestration 已於 2026 年 5 月 6 日進入 Claude Managed Agents 的公開測試階段。35 根據 Anthropic 的說法:「當工作量過大、單一代理人難以勝任時,多代理人協作可讓主導代理人將任務拆解成多個部分,並委派給各自擁有專屬模型、提示與工具的專家代理人。」35 專家代理人「在共享檔案系統上並行工作,並貢獻於主導代理人的整體脈絡。」35
追蹤功能也內建其中。根據 Anthropic:「您也可以在 Claude Console 中追蹤每一個步驟:哪個代理人做了什麼、按什麼順序、為何如此,讓您完全掌握任務如何被委派與執行的全貌。」35
搭配的公開測試版功能是 Outcomes。根據 Anthropic:「您撰寫一份描述成功樣貌的評分標準(rubric),代理人即會朝該目標努力。獨立的評分器在自己的脈絡視窗中依您的標準評估輸出,因此不會受到代理人推理過程的影響。」35 這是本節後續所述雙閘驗證模式的託管服務版本:rubric 取代了手寫的閘門,獨立評分器則取代了共識驗證器。
| 自託管協商(本節內容) | 託管 Multiagent + Outcomes | |
|---|---|---|
| 專家路由 | 您自行撰寫生成邏輯 | 主導代理人將任務拆解成多個部分 |
| 驗證 | 雙閘 hooks + 共識評分 | Rubric + 獨立脈絡中的評分器 |
| 追蹤 | 您自行埋點 | Claude Console |
| 適用情境 | 需要完全控制或特定工具組合的模式 | 標準委派模式,且驗證 rubric 即為契約 |
| 計費方式 | 僅 token 與 harness 成本 | 標準 token 加上 Managed Agents 工作階段時數費率(4 月 8 日推出時的基礎價;參見 23) |
當驗證需要與您自己的 hook 介面整合(PreToolUse 阻擋、退出碼語意、自訂 dispatcher),或當 harness 必須在沒有外部相依性的情況下執行時,自託管協商仍是正確答案。當標準委派加上 rubric 評分就是您實際需要的契約時,託管 Multiagent 才是正確答案。
最小可行協商
從 2 個代理人與 1 條規則開始:代理人必須在看到彼此成果之前獨立評估。7
Decision arrives
|
v
Confidence check: is this risky, ambiguous, or irreversible?
|
+-- NO -> Single agent decides (normal flow)
|
+-- YES -> Spawn 2 agents with different system prompts
Agent A: "Argue FOR this approach"
Agent B: "Argue AGAINST this approach"
|
v
Compare findings
|
+-- Agreement with different reasoning -> Proceed
+-- Genuine disagreement -> Investigate the conflict
+-- Agreement with same reasoning -> Suspect herding
此模式涵蓋了 80% 的價值。其餘所有方法都只是漸進式改善。
信心觸發機制
並非每個任務都需要協商。信心評分模組會評估四個面向:17
- 模糊性 - 該查詢是否有多種有效詮釋?
- 領域複雜度 - 是否需要專業知識?
- 風險程度 - 該決策是否可逆?
- 脈絡相依性 - 是否需要理解更廣泛的系統?
評分對應至三個等級:
| 等級 | 門檻 | 動作 |
|---|---|---|
| HIGH | 0.85+ | 不經協商直接執行 |
| MEDIUM | 0.70-0.84 | 執行但記錄信心註記 |
| LOW | 低於 0.70 | 觸發完整的多代理人協商 |
門檻會依任務類型調整。安全性決策需要 0.85 共識。文件變更僅需 0.50。這可避免簡單任務過度設計,同時確保高風險決策獲得審視。7
狀態機
七個階段,每個階段都由前一個階段把關:7
IDLE -> RESEARCH -> DELIBERATION -> RANKING -> PRD_GENERATION -> COMPLETE
|
(or FAILED)
RESEARCH: 獨立代理人各自調查主題。每個代理人都會獲得不同的角色設定(Technical Architect、Security Analyst、Performance Engineer 等)。脈絡隔離確保代理人在研究階段無法看到彼此的發現。
DELIBERATION: 代理人查看所有研究結果並產出替代方案。Debate 代理人辨識衝突。Synthesis 代理人整合不互相矛盾的發現。
RANKING: 每個代理人針對每個提案,依 5 個加權面向評分:
| 面向 | 權重 |
|---|---|
| Impact | 0.25 |
| Quality | 0.25 |
| Feasibility | 0.20 |
| Reusability | 0.15 |
| Risk | 0.15 |
雙閘驗證架構
兩道驗證閘門可在不同階段攔截問題:7
Gate 1:共識驗證(PostToolUse hook)。在每個協商代理人完成後立即執行: 1. 階段必須至少達到 RANKING 2. 至少 2 個代理人完成(可設定) 3. 共識分數達到任務適應性門檻 4. 若任何代理人持反對意見,必須記錄其疑慮
Gate 2:Pride Check(Stop hook)。在工作階段可關閉前執行: 1. 方法多元:呈現多個獨特角色 2. 矛盾透明性:反對意見有記錄理由 3. 複雜度處理:至少產出 2 個替代方案 4. 共識信心:分類為強(高於 0.85)或中等(0.70-0.84) 5. 改善證據:最終信心超越初始信心
於不同生命週期點放置兩道 hook,正好對應失敗實際發生的方式:有些是瞬時的(分數差),有些是漸進的(多樣性低、缺漏反對意見記錄)。7
為何意見一致是危險的
Charlan Nemeth 從 1986 年開始研究少數派異議,直至 2018 年出版《In Defense of Troublemakers》。有異議者的群體比快速達成一致的群體做出更好的決策。異議者不必是對的。光是表達不同意這個動作,就能迫使多數派檢視原本會跳過的假設。18
Wu 等人測試 LLM 代理人是否能進行真正的辯論,發現若缺乏結構性的異議誘因,代理人會收斂至聽起來最有自信的初始回應,無論其正確性如何。19 Liang 等人將根本原因歸結為「Degeneration-of-Thought」:一旦 LLM 對某立場建立信心,自我反思便無法產生新穎的反對論點,這使得多代理人評估在結構上有其必要性。20
獨立性是關鍵設計約束。兩個代理人若能看到彼此的發現,評估同一份部署策略時的分數為 0.45 與 0.48。同樣的代理人若彼此不可見:分數為 0.45 與 0.72。0.48 與 0.72 之間的差距,就是從眾效應的代價。7
偵測虛假共識
從眾偵測模組會追蹤代理人未經真正評估即達成共識的模式:7
分數聚集: 在 10 分制中,每個代理人的評分都落在 0.3 分以內,這暗示共享脈絡受到污染,而非獨立評估。當五個代理人評估身分驗證重構時,安全風險全都評在 7.1 至 7.4 之間,以新的脈絡隔離重新執行後,分數則散佈於 5.8 至 8.9 之間。
樣板式反對意見: 代理人複製彼此的疑慮用語,而非產生獨立的反對意見。
少數派觀點缺席: 來自具有衝突優先順序的角色卻全數同意(Security Analyst 與 Performance Engineer 鮮少在所有事情上達成一致)。
從眾偵測器能捕捉明顯的案例(約 10-15% 的協商中代理人收斂得太快)。剩餘的 85-90%,則由共識與 pride check 閘門提供充分的驗證。
協商中無效的做法
自由形式的辯論回合。 在資料庫索引討論中進行三輪來回文字辯論,產生了 7,500 token 的辯論內容。第一輪:真實的意見分歧。第二輪:重述立場。第三輪:以不同字眼重複相同論點。結構化的面向評分取代了自由形式辯論,將成本降低 60%,同時提升了排序品質。7
單一驗證閘門。 第一版實作只在工作階段結束時執行一個驗證 hook。某代理人完成協商時共識分數為 0.52(低於門檻),接著繼續處理無關任務 20 分鐘,直到工作階段結束的 hook 才標記出失敗。拆分為兩道閘門(一道在任務完成時、一道在工作階段結束時)後,可在不同生命週期點捕捉相同問題。7
協商成本
每個研究代理人約處理 5,000 token 的脈絡,並產出 2,000-3,000 token 的發現。3 個代理人就是每個決策額外 15,000-24,000 token。10 個代理人則約為 50,000-80,000 token。7
依當前 Opus 定價,3 個代理人的協商成本約為 $0.68-0.90。10 個代理人的協商成本為 $2.25-3.00。系統會在約 10% 的決策上觸發協商,因此攤平至所有決策後,每個工作階段的成本為 $0.23-0.30。是否值得,取決於一個錯誤決策的代價有多高。
何時應該協商
| 應協商 | 應跳過 |
|---|---|
| 安全性架構 | 文件錯字 |
| 資料庫綱要設計 | 變數重新命名 |
| API 契約變更 | 日誌訊息更新 |
| 部署策略 | 註解措辭調整 |
| 相依套件升級 | 測試夾具更新 |
CLAUDE.md設計
CLAUDE.md是AI agent的作業政策,不是給人看的README。21agent不需要理解您為什麼使用conventional commits。它需要知道要執行的確切命令,以及「完成」是什麼樣子。
優先順序層級
| 位置 | 範圍 | 共用 | 使用情境 |
|---|---|---|---|
| Enterprise managed settings | 組織 | 所有使用者 | 公司標準 |
./CLAUDE.md或./.claude/CLAUDE.md |
專案 | 透過git | 團隊脈絡 |
~/.claude/CLAUDE.md |
使用者 | 所有專案 | 個人偏好 |
./CLAUDE.local.md |
專案本機 | 永不 | 個人專案筆記 |
.claude/rules/*.md |
專案規則 | 透過git | 分類政策 |
~/.claude/rules/*.md |
使用者規則 | 所有專案 | 個人政策 |
規則檔案會自動載入,並提供結構化脈絡,不會讓CLAUDE.md變得雜亂。6
會被忽略的內容
這些模式通常不會對agent行為產生可觀察的變化:21
沒有命令的散文段落。「我們重視乾淨且經過良好測試的程式碼」是文件,不是作業指令。agent會讀取它,然後繼續撰寫沒有測試的程式碼,因為其中沒有可執行的指示。
模糊的指令。「小心處理資料庫migration」不是限制。「套用migration前先執行alembic check。如果缺少downgrade路徑就中止。」才是。
互相矛盾的優先事項。「快速前進並迅速出貨」加上「確保完整測試覆蓋率」加上「將執行時間維持在5分鐘內」再加上「每次commit前執行完整整合測試。」agent無法同時滿足這4項要求,預設會略過驗證。21
沒有強制機制的風格指南。「遵循Google Python Style Guide」但沒有ruff check --select D,agent就沒有機制驗證是否符合規範。
有效的寫法
命令優先的指示:
## Build and Test Commands
- Install: `pip install -r requirements.txt`
- Lint: `ruff check . --fix`
- Format: `ruff format .`
- Test: `pytest -v --tb=short`
- Type check: `mypy app/ --strict`
- Full verify: `ruff check . && ruff format --check . && pytest -v`
收尾定義:
## Definition of Done
A task is complete when ALL of the following pass:
1. `ruff check .` exits 0
2. `pytest -v` exits 0 with no failures
3. `mypy app/ --strict` exits 0
4. Changed files have been staged and committed
5. Commit message follows conventional format: `type(scope): description`
依任務組織的區段:
## When Writing Code
- Run `ruff check .` after every file change
- Add type hints to all new functions
## When Reviewing Code
- Check for security issues: `bandit -r app/`
- Verify test coverage: `pytest --cov=app --cov-fail-under=80`
## When Releasing
- Update version in `pyproject.toml`
- Run full suite: `pytest -v && ruff check . && mypy app/`
升級規則:
## When Blocked
- If tests fail after 3 attempts: stop and report the failing test with full output
- If a dependency is missing: check `requirements.txt` first, then ask
- Never: delete files to resolve errors, force push, or skip tests
撰寫順序
如果從零開始,請依照以下優先順序加入區段:21
- 建置與測試命令(agent需要先知道這些,才能做任何有用的事)
- 完成定義(避免錯誤宣稱完成)
- 升級規則(避免破壞性的變通做法)
- 依任務組織的區段(減少解析無關指示)
- 目錄範圍界定(monorepo:讓服務指示彼此隔離)
在前4項可正常運作前,先略過風格偏好。
檔案匯入
在CLAUDE.md中參照其他檔案:
See @README.md for project overview
Coding standards: @docs/STYLE_GUIDE.md
API documentation: @docs/API.md
Personal preferences: @~/.claude/preferences.md
匯入語法:相對路徑(@docs/file.md)、絕對路徑(@/absolute/path.md),或家目錄(@~/.claude/file.md)。最大深度:5層匯入。6
跨工具指示相容性
AGENTS.md是各大AI coding tool都能辨識的開放標準。21如果您的團隊使用多種工具,請將AGENTS.md作為標準來源,並把相關區段鏡像到工具專屬檔案:
| 工具 | 原生檔案 | 會讀取AGENTS.md嗎? |
|---|---|---|
| Codex CLI | AGENTS.md | 會(原生) |
| Cursor | .cursor/rules |
會(原生) |
| GitHub Copilot | .github/copilot-instructions.md |
會(原生) |
| Amp | AGENTS.md | 會(原生) |
| Windsurf | .windsurfrules |
會(原生) |
| Claude Code | CLAUDE.md | 不會(格式不同) |
AGENTS.md中的模式(命令優先、收尾明確、依任務組織)可用於任何工具的指示檔。不要維護會彼此偏移的平行指示集。撰寫一份權威來源,並進行鏡像。
Codex對等注意事項
Codex現在已為主要harness層提供一級等價功能,但遷移是模式轉譯,不是檔案複製。Codex會在工作開始前讀取AGENTS.md,將來自~/.codex的全域指引,與專案及巢狀repository指示分層套用。31Codex skills使用相同的SKILL.md心智模型,並採用漸進式揭露:Codex一開始只看到skill名稱、描述與檔案路徑,只有在決定使用時才載入完整skill。32Codex也有原生hooks、plugin-bundled hooks、managed hooks、MCP支援,以及明確的subagent工作流程。3334
Codex v0.138.0–v0.139.0強化了AGENTS.md在非平凡工作區中的探索機制:載入現在會經由環境的檔案系統抽象層,並在探索走訪期間保留邏輯路徑,因此即使工作區是遠端檔案系統或符號連結樹,也能選到正確檔案。61只要您的標準AGENTS.md是權威來源,而agent正在掛載、容器實體化或符號連結的checkout上作業,這點就很重要;這些情境中,天真的路徑走訪可能會悄悄選到錯誤的指示檔,甚至完全找不到。若您在多個服務間鏡像一份權威AGENTS.md,請將此版本視為信任agent實際載入檔案就是您所寫檔案的最低基準。
接著,Codex v0.141.0強化了遠端執行路徑本身:remote executors現在會透過已驗證且端對端加密的Noise-relay channels連線(控制平面與executor不再信任兩者之間的relay),跨平台遠端執行會保留executor原生的工作目錄與shell,而TLS也接受企業proxy使用的P-521憑證簽章。65如果您的orchestration會跨網路邊界驅動Codex executors,這就是信任relay假設與端對端加密假設之間的差別。請把它視為任何remote-executor拓撲的基準。
實務對應如下:
| Claude Code harness層 | Codex對應項 | 遷移規則 |
|---|---|---|
CLAUDE.md / .claude/rules/ |
AGENTS.md / 巢狀AGENTS.override.md |
讓命令與完成規則維持標準;只有在目錄範圍確實不同時才拆分 |
.claude/skills/<name>/SKILL.md |
.agents/skills/<name>/SKILL.md或plugin skill |
移植可重複使用的工作流程,但要依Codex的啟用措辭與budget重寫描述 |
.claude/settings.json hooks |
Codex config.toml、plugin hooks或managed requirements hooks |
優先移植deterministic gates;廣泛啟用前,先以真實tool events測試每個hook |
.claude/agents/*.md |
~/.codex/agents/*.toml、.codex/agents/*.toml或內建worker / explorer |
只移植具有重複價值的agents;偏好明確委派,因為Codex subagents是明確啟用的 |
| Plugins | Codex plugins | 在本機hooks與skills已獲驗證後,使用plugins作為散布單位 |
重要差異在於:Claude subagents可依描述自動選取,而Codex目前將subagent工作流程記載為明確啟用。因此,在Codex中,skills與hooks才是always-on harness行為的合理預設;subagents則適合用於刻意安排的平行工作、review與探索。
測試您的指示
驗證agent確實讀取並遵循您的指示:
# Check active instructions
claude --print "What instructions are you following for this project?"
# Verify specific rules are active
claude --print "What is your definition of done?"
關鍵測試:要求agent說明您的建置命令。如果它無法逐字重現,代表指示可能太冗長(內容被推出脈絡之外)、太模糊(agent無法擷取可執行指示),或根本沒有被發現。GitHub對2,500個repository的分析發現,模糊性造成了大多數失敗。21
生產環境模式
Opus 4.7 長期任務模式(2026年4月)
Claude Opus 4.7(2026年4月16日)推出了幾項特定能力,會改變 harness 需要防範的事項:29
- 工具失敗韌性: Opus 4.7 會在工具失敗後繼續執行,而這類失敗過去會中斷 Opus 4.6 session。您可以減少 subagent 程式碼中的防禦性重試 wrapper,但不能完全移除。保留 hook 層級的防護;刪減 prompt 內「如果工具失敗,就再試三次」這類 scaffolding。
xhigheffort tier(僅 Opus-4.7): 介於high與max之間。建議作為 coding 與 agentic workload 的預設值。對長時間執行的 subagents 而言,xhigh明顯優於high,且 token 成本增幅低於效能增幅。max仍適合單次高難度推理;xhigh則更適合持續性任務。- Token 預算上限: 可透過
output_config.task_budget為每次 agent 執行設定(beta headertask-budgets-2026-03-13)。模型會看到持續倒數的預算,並優雅地將工作範圍收斂在預算內,而不是意外耗盡。適合用於 agentic loops,讓 token 支出可預測,同時不犧牲短 prompt 的品質。 - 隱含需求感知: 第一個通過「implicit-need」測試的 Claude model,能辨識使用者字面請求低估實際需求的情況。這會降低 CLAUDE.md 中「clarifying rules」區段的必要性。如果您的 CLAUDE.md 有 200 行「使用者要求 Y 時也要考慮 X」這類 guardrails,請修剪已由模型原生涵蓋的部分。
Worktree Base、Sandbox Paths 與 Admin Settings(2026年5月7日)
Claude Code v2.1.133 新增了 4 個值得 production harness 了解的 admin-tier settings:39
| Setting | Values | What it does |
|---|---|---|
worktree.baseRef |
fresh(預設)| head |
新 worktrees 會再次從 origin/<default> 建立分支。這是從 v2.1.128 的 breaking-default revert,該版本曾使用本機 HEAD。如果您的團隊仰賴未 push 的 commits 能在新 worktrees 中使用,請設定 worktree.baseRef: "head"。 |
sandbox.bwrapPath |
absolute path | 在 Linux/WSL host 上固定 Bubblewrap binary 的位置,適用於它不在 $PATH,或您交付 vendored version 的情況。 |
sandbox.socatPath |
absolute path | 同樣概念,用於 sandbox networking 使用的 socat binary。 |
parentSettingsBehavior |
'first-wins'(預設)| 'merge' |
Admin-tier 控制 SDK managedSettings 如何與上層 enterprise/team settings 組合。'merge' 讓 child session 繼承並擴充;'first-wins' 則讓 parent 保持權威。 |
worktree.baseRef revert 是需要提醒使用者的重點:若 agents 仰賴 v2.1.128-v2.1.132 的行為(worktrees 從本機 HEAD 建立分支),fresh worktrees 將無法存取未 push 的工作,除非重新選擇加入。
Enterprise Observability 的 OTel Feedback Survey(2026年5月8日)
Claude Code v2.1.136 新增 CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL,讓透過 OpenTelemetry 擷取回應的企業可重新啟用 session 內品質問卷。40 如果您的組織將 OTel events 匯入中央 observability stack,這個 env var 會把問卷放回 data path,讓品質訊號能和 latency、error metrics 走同一條 pipeline。請將其視為 opt-in:預設會抑制問卷,這對非 OTel 部署是正確選擇。
Quality Loop
所有非平凡變更都必須採用的強制 review 流程:
- Implement - 撰寫程式碼
- Review - 重新閱讀每一行。抓出錯字、邏輯錯誤、不清楚的區段
- Evaluate - 執行 evidence gate。檢查 patterns、edge cases、test coverage
- Refine - 修正每個問題。絕不推給「之後」
- Zoom Out - 檢查 integration points、imports、相鄰程式碼是否有 regressions
- Repeat - 若任何 evidence gate criterion 失敗,回到第 4 步
- Report - 列出變更內容、驗證方式,並引用具體 evidence
Evidence Gate
「我相信」和「應該可以」不是 evidence。請引用 file paths、test output,或具體程式碼。
| Criterion | Required Evidence |
|---|---|
| 遵循 codebase patterns | 說明 pattern 名稱,以及它存在於哪個檔案 |
| 最簡可行解法 | 說明拒絕了哪些更簡單的替代方案,以及原因 |
| 已處理 edge cases | 列出具體 edge cases,以及各自如何處理 |
| Tests pass | 貼上顯示 0 failures 的 test output |
| 無 regressions | 說明已檢查的檔案/功能 |
| 解決實際問題 | 說明使用者需求,以及此作法如何回應 |
如果無法為任何一列提出 evidence,請回到 Refine。22
Human Merge Authority
一篇 2026年5月的 arXiv 研究分析了 29,585 個 AI-agent pull-request lifecycle,將 operational agency 與 merge governance 區分開來。47 有用的架構教訓很簡單:agents 可以開始工作、推進 branches、開 PRs、review 工作並摘要風險,但 merge authority 仍應是獨立的 governance boundary。
請在 harness 中明確建立這條界線。讓 agents 準備 PRs 並蒐集 evidence;除非組織有另行稽核過的 automation policy,否則 merges、releases 與 destructive repository operations 都必須要求 human approval。當 automation 執行 merge 時,請保留 logs,用來區分執行者,以及授權該行為的人或 policy。
Error Handling Patterns
Atomic file writes。 多個 agents 同時寫入同一個 state file 會毀損 JSON。請先寫入 .tmp 檔案,再以 mv 原子性搬移。OS 保證同一 filesystem 上的 mv 具備 atomic 特性。17
# Atomic state update
jq --argjson d "$new_depth" '.depth = $d' "$STATE_FILE" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"
State corruption recovery。 如果 state 損毀,recovery pattern 會從安全預設值重建,而不是直接 crash:16
if ! jq -e '.depth' "$RECURSION_STATE_FILE" &>/dev/null; then
# Corrupted state file, recreate with safe defaults
echo '{"depth": 0, "agent_id": "root", "parent_id": null}' > "$RECURSION_STATE_FILE"
echo "- Recursion state recovered (was corrupted)"
fi
((VAR++)) bash trap。 ((VAR++)) 在 VAR 為 0 時會回傳 exit code 1,因為 0++ 會求值為 0,而 bash 會將其視為 false。啟用 set -e 時,這會讓 script 終止。請改用 VAR=$((VAR + 1))。16
Blast Radius Classification
依 blast radius 為每個 agent action 分類,並據此 gate:2
| Classification | Examples | Gate |
|---|---|---|
| Local | File writes、test runs、linting | Auto-approve |
| Shared | Git commits、branch creation | Warn + proceed |
| External | Git push、API calls、deployments | Require human approval |
Remote Control(從任何 browser 或 mobile app 連線到本機 Claude Code)會把「External」gate 從阻塞等待變成 async notification。當您用手機 review 前一項任務時,agent 仍會繼續處理下一項任務。2
Autonomous Runs 的 Task Specification
有效的 autonomous tasks 包含三個元素:objective、completion criteria 與 context pointers:16
OBJECTIVE: Implement multi-agent deliberation with consensus validation.
COMPLETION CRITERIA:
- All tests in tests/test_deliberation_lib.py pass (81 tests)
- post-deliberation.sh validates consensus above 70% threshold
- recursion-guard.sh enforces spawn budget (max 12 agents)
- No Python type errors (mypy clean)
CONTEXT:
- Follow patterns in lib/deliberation/state_machine.py
- Consensus thresholds in configs/deliberation-config.json
- Spawn budget model: agents inherit budget, not increment depth
Criteria 必須可由機器驗證:test pass/fail、linter output、HTTP status codes、file existence checks。早期有個任務要求 agent「write tests that pass」,結果產生了 assert True 和 assert 1 == 1。技術上正確。實務上毫無價值。16
| Criteria Quality | Example | Outcome |
|---|---|---|
| 模糊 | “Tests pass” | Agent 寫出 trivial tests |
| 可衡量但不完整 | “Tests pass AND coverage >80%” | Tests 覆蓋行數,卻沒有測試有意義的行為 |
| 完整 | “All tests pass AND coverage >80% AND no type errors AND linter clean AND each test class tests a distinct module” | Production-quality output |
需要留意的 Failure Modes
| Failure Mode | Description | Prevention |
|---|---|---|
| Shortcut Spiral | 為了更快完成而跳過 quality loop steps | Evidence gate 要求為每項 criterion 提供 proof |
| Confidence Mirage | 未執行 verification 卻說「I’m confident」 | 在 completion reports 中禁止 hedging language |
| Phantom Verification | 未在本 session 執行 tests,卻宣稱 tests pass | Stop hook 會獨立執行 tests |
| Deferred Debt | committed code 中出現 TODO/FIXME/HACK | git commit 的 PreToolUse hook 會掃描 diff |
| Filesystem Pollution | abandoned iterations 留下的 dead-end artifacts | completion criteria 中加入 cleanup step |
一段具體的 Session Trace
以下是一段 autonomous run 的 session trace,該執行處理一個含 5 個 stories 的 PRD:2
-
SessionStart 觸發。 Dispatcher 注入:current date、project detection、philosophy constraints、cost tracking initialization。共 5 個 hooks,總計 180ms。
-
Agent 讀取 PRD,規劃第一個 story。
UserPromptSubmit觸發。Dispatcher 注入:active project context、session drift baseline。 -
Agent 呼叫 Bash 執行 tests。
PreToolUse:Bash觸發。Credentials check、sandbox validation、project detection。90ms。Tests 執行。PostToolUse:Bash觸發:activity heartbeat logged、drift check。 -
Agent 呼叫 Write 建立檔案。
PreToolUse:Write觸發:file scope check。PostToolUse:Write觸發:lint check、commit tracking。 -
Agent 完成 story。
Stop觸發。Quality gate 檢查:agent 是否引用 evidence?是否有 hedging language?diff 中是否有 TODO comments?若任何檢查失敗,exit 2,agent 會繼續。 -
Independent verification: 一個 fresh agent 執行 test suite,不信任前一個 agent 的 self-report。
-
3 個 code review agents 平行 spawn。 各自獨立 review diff。若任何 reviewer 標記 CRITICAL,該 story 會回到 queue。
-
Story 通過。下一個 story 載入。 這個 cycle 會為全部 5 個 stories 重複執行。
5 個 stories 總共觸發約 340 個 hooks。Hooks 總耗時約 12 秒。這些 overhead 在單次 overnight run 中阻止了 3 次 credential leaks、1 個 destructive command,以及 2 個 incomplete implementations。
Case Study:Overnight PRD Processing
一個 production harness 在 8 次 overnight sessions 中處理了 12 個 PRDs(47 個 stories)。Metrics 比較前 4 個 PRDs(minimal harness:僅 CLAUDE.md)與後 8 個(full harness:hooks、skills、quality gates、multi-agent review)。
| Metric | Minimal(4 個 PRDs) | Full Harness(8 個 PRDs) | Change |
|---|---|---|---|
| Credential leaks | 2 個 leaked to git | 7 個 blocked pre-commit | 從 reactive 變 preventive |
| Destructive commands | 1 次 force-push to main | 4 個 blocked | Exit 2 enforcement |
| False completion rate | 35% failed tests | 4% | Evidence gate + Stop hook |
| Revision rounds/story | 2.1 | 0.8 | Skills + quality loop |
| Context degradation | 6 incidents | 1 incident | Filesystem memory |
| Token overhead | 0% | ~3.2% | 可忽略 |
| Hook time/story | 0s | ~2.4s | 可忽略 |
兩次 credential leaks 需要輪替 API keys 並稽核 downstream services:約 4 小時的 incident response。防止同等事件所需的 harness overhead,是每個 story 2.4 秒的 bash。False completion rate 從 35% 降到 4%,原因是 Stop hook 會在允許 agent 回報完成前,獨立執行 tests。
安全性考量
可信任 Agent 的五大原則(Anthropic,2026年4月)
Anthropic 於2026年4月9日發布了 Agent 可信任性的正式框架。27這五項原則與本指南中的 Evidence Gate 思維相呼應,並進一步延伸:
| 原則 | 意義 | 此 harness 如何滿足 |
|---|---|---|
| 人類控制 | 在每個決策點都保有有意義的人類覆寫能力 | hooks 管控 tool calls;PreCompact 阻擋;Auto Mode classifier 作為檢查層 |
| 價值對齊 | Agent 動作追隨使用者意圖,而不是相鄰目標 | CLAUDE.md 作為明確的意圖規格;skills 作為能力範圍界定 |
| 安全性 | 抵抗對抗性輸入與 prompt injection | Sandbox + deny-rules + hook 層的輸入驗證 |
| 透明度 | 可稽核的決策與動作紀錄 | Hook logging;session transcripts;skill-invocation traces |
| 隱私 | 適當的資料處理與治理 | Credential env-var scrubbing;hook 層的 secret detection |
Anthropic 也將 MCP 捐贈給 Linux Foundation 的 Agentic AI Foundation,並加入 AGENTS.md(目前由 OpenAI、Google、Cursor、Factory、Sourcegraph 共同維護)。Agent 互通性標準如今已成為供應商中立。27
Skill sandbox tooling:對於將 skills 視為攻擊面的團隊,Permiso 的 SandyClaw(2026年4月2日推出)會在專用 sandbox 中執行 skills,並提供由 Sigma/YARA/Nova/Snort 偵測支援、有證據依據的判定。這是 skill-sandbox 類別中的首款產品。28
Sandbox
Claude Code 支援選用的 sandbox 模式(透過 settings.json 或 /sandbox 指令啟用),使用作業系統層級隔離(macOS 上的 seatbelt、Linux 上的 bubblewrap)限制網路存取與檔案系統操作。啟用後,sandbox 會防止模型任意發出網路請求,或存取專案目錄外的檔案。若未使用 sandbox,Claude Code 則採用權限式模型,由您核准或拒絕個別 tool calls。13
2026年5月安全底線。Claude Code v2.1.149 修復了 PowerShell 工作目錄權限繞過、多個 PowerShell allow-rule 與 stale-variable 權限分析缺口,以及 git-worktree sandbox 寫入 allowlist 錯誤;該錯誤涵蓋整個主要 repository root,而不只是共用的 git internals。53如果您的 harness 允許 PowerShell 或 worktree-isolated agents,請將 v2.1.149+ 視為底線,並保持 shell rules 嚴格。寬泛的 PowerShell(*) 與整個 repo 的寫入例外,是 orchestration 捷徑,不是安全邊界。
OpenAI Agents SDK sandbox lockdown(v0.17.0,2026年5月8日)。在 OpenAI 端,openai-agents-python v0.17.0 收緊了一個平行邊界:LocalFile.src 與 LocalDir.src 現在被限制在 materialization base_dir 內(套用 manifest 時 SDK process 的目前工作目錄),除非來源透過 Manifest.extra_path_grants 搭配 SandboxPathGrant 明確授權。41相對本機來源會從 base_dir 解析;絕對路徑必須已位於其中,或附帶 grant。這關閉了一個本機 artifact 邊界問題:舊版本允許 manifests 將任意 host paths 拉入 sandbox workspace。遷移方式:在 manifest 層級使用 SandboxPathGrant(path=..., read_only=True) 宣告可信任 host roots,以供唯讀掛載。請將 extra_path_grants 視為可信任的應用程式設定;切勿從模型輸出或不可信任的 manifest input 填入 grants。
OpenAI Agents SDK 後續底線(v0.17.3)。0.17.1-0.17.3 系列加入更多 sandbox 與 session 強化:archive extraction limits、GitRepo subpath validation、更清楚的 sandbox-provider errors、mountpoint credentials 不進入 sandbox commands、拒絕相對 sandbox workspace roots,以及 Vercel-sandbox terminal-state handling。54如果您使用的是 OpenAI-hosted 或 provider-backed sandboxes,而不只是 Claude Code hooks,請將 0.17.3 視為本節模式的目前底線。
權限邊界
權限系統會在多個層級管控操作:
| 層級 | 控制項 | 範例 |
|---|---|---|
| 工具權限 | 哪些工具可以使用 | 將 subagent 限制為 Read、Grep、Glob |
| 檔案權限 | 哪些檔案可以修改 | 阻擋寫入 .env、credentials.json |
| 指令權限 | 哪些 bash 指令可以執行 | 阻擋 rm -rf、git push --force |
| 網路權限 | 哪些網域可以存取 | MCP server connections 的 allowlist |
參數層級權限規則(2026年6月)
Claude Code v2.1.178 將權限規則從工具層級延伸到參數層級:Tool(param:value) 會比對工具的輸入參數,並以 * 作為萬用字元。標準範例是 Agent(model:opus),這條規則會阻擋 subagents 在特定 model tier 上產生。63從架構上看,這補上了上方四層表格無法表達的缺口:過去您只能整體允許或拒絕某個工具,卻無法約束它被如何呼叫。如今治理政策可以用確定性規則表達「subagents 可以產生,但不可使用 Fable 5 tier」或「允許 Bash,但不可帶此 flag」,而不必仰賴 prompt 層級請求。
配套的 managed setting enforceAvailableModels(v2.1.175)則由上而下限制模型選擇:它會固定 Default model,並防止使用者或專案範圍設定擴大 managed availableModels allowlist。63兩者相輔相成:allowlist 定義 session 中實際存在的 tiers,而參數層級規則則限制 subagents 如何從中取用。
Auto-Mode 破壞性指令防護欄(2026年6月)
Claude Code v2.1.183 收窄了 auto mode 對於會悄悄遺失工作或拆除環境的操作所造成的爆炸半徑。除非您在 session 中明確要求,auto mode 現在會硬性阻擋:破壞性 git 操作(git reset --hard、git checkout -- .、git clean -fd、git stash drop);在該 commit 不是 agent 於本 session 建立時執行 git commit --amend;以及基礎設施拆除(terraform destroy、pulumi destroy、cdk destroy),除非您指定了特定 stack。65從架構上看,這是上述 spawn-vetting 與參數層級規則的補足:它管控的不是哪個工具或它如何產生,而是依據意圖管控一小組特定不可逆指令。agent 仍可執行它們,但只能在明確指示下執行,不能自行發起。對於自主式 harness,請在自己的 PreToolUse hooks 中編碼相同原則:會摧毀狀態的指令應採 deny-by-default 規則,只有明確的操作者訊號才能解除。
Prompt Injection 防禦
Skills 與 hooks 針對 prompt injection 提供縱深防禦:
帶有工具限制的 skills可防止遭入侵的 prompt 取得寫入權限:
allowed-tools: Read, Grep, Glob
PreToolUse hooks會驗證每個 tool call,不受模型如何被提示影響:
# Block credential file access regardless of prompt
if echo "$FILE_PATH" | grep -qE "\.(env|pem|key|credentials)$"; then
echo "BLOCKED: Sensitive file access" >&2
exit 2
fi
Subagent 隔離限制爆炸半徑。具有 permissionMode: plan 的 subagent 即使 prompt 遭入侵,也無法做出變更。
Agent Logs 與 Guardrails 都是安全面
2026年5月的兩則公告強化了一個模式:agent infrastructure 會創造敏感內容與可執行政策外洩或逃逸的新位置。GitHub Advisory GHSA-f3jg-756w-gm35 涵蓋 Gryph Agents 的 payload-filter 問題,在預設記錄行為下,敏感的 tool-payload content 可能留存在本機 SQLite logs 中。45OSV GHSA-wxxx-gvqv-xp7p 則涵蓋 LiteLLM custom-code guardrail 在受管理員保護的 proxy endpoint 中發生 sandbox escape。46
正式環境規則是:將 agent transcripts、tool payloads、SQLite logs 與 guardrail execution 視為敏感基礎設施。持久化前先遮蔽、套用保留期限,並確保 custom guardrail code 受到 sandbox 保護且可審查。prompt 層級的「不要記錄 secrets」規則並不足夠;logging 與 guardrail path 需要確定性測試。
Hook 安全性
若 HTTP hooks 會將環境變數插入 headers,必須有明確的 allowedEnvVars 清單,避免任意環境變數遭外洩:13
{
"type": "http",
"url": "https://api.example.com/notify",
"headers": {
"Authorization": "Bearer $MY_TOKEN"
},
"allowedEnvVars": ["MY_TOKEN"]
}
人類與 Agent 的責任分工
Agent 架構中的安全性需要清楚劃分人類與 agent 的責任:17
| 人類責任 | Agent 責任 |
|---|---|
| 問題定義 | Pipeline execution |
| 信心門檻 | 在門檻內執行 |
| 共識要求 | 共識計算 |
| 品質閘門準則 | 品質閘門執行 |
| 錯誤分析 | 錯誤偵測 |
| 架構決策 | 架構選項 |
| 領域脈絡注入 | 文件產生 |
模式是:需要組織脈絡、倫理判斷或策略方向的決策,由人類負責。需要在大型可能性空間中進行計算搜尋的決策,由 agents 負責。Hooks 負責強制維持這條邊界。
遞迴 Hook 強制執行
Hooks 也會在 subagent 動作時觸發。13如果 Claude 透過 Agent tool 產生 subagent,您的 PreToolUse 與 PostToolUse hooks 會針對 subagent 使用的每個工具執行。若沒有遞迴 hook 強制執行,subagent 就可能繞過您的安全閘門。SubagentStop 事件讓您能在 subagent 完成時執行清理或驗證。
這不是選配。若 agent 產生的 subagent 沒有套用您的 security hooks,那個 agent 就能在您的閘門只看著主對話無所作為時,force-push 到 main、讀取 credential files,或執行破壞性指令。
成本即架構
成本是一項架構決策,不是營運上的事後補救。2分為三個層級:
Token 層級。System prompt compression。移除教學式程式碼範例(模型知道 APIs)、合併跨檔案的重複規則,並以約束取代解釋。「拒絕符合敏感路徑的 tool calls」與一段 15 行說明為何不應讀取 credentials 的文字,能完成同樣工作。
Agent 層級。以 fresh spawns 取代長對話。自主執行中的每個 story 都會取得一個具備乾淨脈絡的新 agent。由於每個 agent 都從頭開始,脈絡不會膨脹。以 briefing 取代 memory:模型執行清楚 briefing 的效果,勝過在累積 30 步的脈絡中摸索。
架構層級。當操作是無狀態時,優先採用 CLI,而不是 MCP。針對一次性評估呼叫 claude --print 成本較低,且不增加連線開銷。當工具需要持久狀態或串流時,MCP 才合理。
決策框架
何時使用各機制:
| 問題 | 使用 | 原因 |
|---|---|---|
| 每次編輯後格式化程式碼 | PostToolUse hook | 必須每次都以確定性方式執行 |
| 封鎖危險的 bash 命令 | PreToolUse hook | 必須在執行前封鎖,exit code 2 |
| 套用安全性審查模式 | Skill | 會根據情境自動啟用的領域專業 |
| 探索 codebase 而不污染 context | Explore subagent | 隔離的 context,只回傳摘要 |
| 安全地執行實驗性重構 | Worktree-isolated subagent | 若變更失敗,可以直接捨棄 |
| 從多個角度審查程式碼 | Parallel subagents 或 Agent Team | 獨立評估可避免盲點 |
| 決定不可逆的架構 | Multi-agent deliberation | 信心觸發器 + 共識驗證 |
| 跨 session 保存決策 | MEMORY.md | 檔案系統可跨越 context 邊界 |
| 分享團隊標準 | Project CLAUDE.md + .claude/rules/ | 透過 Git 分發,並自動載入 |
| 定義專案建置/測試命令 | CLAUDE.md | agent 可以驗證的命令優先指示 |
| 執行長時間自主開發 | Ralph loop(fresh-context iteration) | 每次 iteration 都有完整 context 預算與檔案系統狀態 |
| session 結束時通知 Slack | Async Stop hook | 非阻塞,不會拖慢 session |
| commit 前驗證品質 | git commit 上的 PreToolUse hook | 若 lint/tests 失敗,就封鎖 commit |
| 強制執行完成標準 | Stop hook | 防止 agent 在任務完成前停止 |
Skills vs Hooks vs Subagents
| 維度 | Skills | Hooks | Subagents |
|---|---|---|---|
| Invocation | 自動(LLM 推理) | 確定性(事件驅動) | 明確指定或自動委派 |
| Guarantee | 機率性(由模型決定) | 確定性(一定觸發) | 確定性(隔離 context) |
| Context cost | 注入主要 context | 零(在 LLM 外執行) | 獨立的 context window |
| Token cost | Description 預算(window 的 1%,fallback 為 8,000 字元) | 零 | 每個 subagent 都有完整 context |
| Best for | 領域專業 | 政策強制執行 | 聚焦工作、探索 |
FAQ
hooks 到底多少才算太多?
限制在於效能,而不是數量。每個 hook 都會同步執行,因此 hook 總執行時間會加到每次相符的 tool call 上。若每個 hook 都能在 200ms 內完成,即使 user-level 與 project-level settings 合計有 95 個 hooks,也不會有明顯延遲。需要留意的門檻是:如果某個 PostToolUse hook 讓每次檔案編輯多出超過 500ms,session 就會開始顯得遲鈍。部署前,請先用 time profile 您的 hooks。14
hooks 可以阻止 Claude Code 執行命令嗎?
可以。PreToolUse hooks 只要以 code 2 結束,就能封鎖任何 tool action。Claude Code 會取消待處理的 action,並把 hook 的 stderr output 顯示給模型。Claude 會看到拒絕原因,並建議更安全的替代方案。Exit 1 則是非阻塞警告,action 仍會繼續執行。3
hook 設定檔應該放在哪裡?
hook 設定放在 .claude/settings.json 可作為 project-level hooks(commit 到 repository,與團隊共享),或放在 ~/.claude/settings.json 作為 user-level hooks(個人使用,套用到每個專案)。兩者同時存在時,project-level hooks 優先。script 檔案請使用絕對路徑,避免 working directory 造成問題。14
每個決策都需要 deliberation 嗎?
不需要。confidence module 會從 4 個維度為決策評分(歧義度、複雜度、風險、context dependency)。只有整體信心分數低於 0.70 的決策才會觸發 deliberation,約占總決策的 10%。文件修正、變數重新命名與例行編輯會完全略過 deliberation。安全性架構、資料庫 schema 變更,以及不可逆部署則會穩定觸發。7
如何測試一個設計來產生分歧的系統?
成功路徑與失敗路徑都要測。成功:agents 有建設性地分歧,並達成共識。失敗:agents 太快收斂、永遠無法收斂,或超過 spawn 預算。End-to-end tests 會用確定性的 agent responses 模擬每種情境,驗證兩道 validation gates 都能捕捉每個已記錄的 failure mode。production deliberation system 會在 3 層執行 141 項 tests:48 個 bash integration tests、81 個 Python unit tests,以及 12 個 end-to-end pipeline simulations。7
deliberation 對延遲有什麼影響?
3-agent deliberation 會增加 30-60 秒的實際等待時間(agents 會透過 Agent tool 依序執行)。10-agent deliberation 會增加 2-4 分鐘。consensus 與 pride check hooks 各自在 200ms 內完成。主要瓶頸是每個 agent 的 LLM inference time,而不是 orchestration overhead。7
CLAUDE.md 檔案應該多長?
每個 section 保持在 50 行以內,整份檔案控制在 150 行內。太長的檔案會被 context windows 截斷,因此請把最關鍵的指示放在前面:命令與 closure definitions 應該早於風格偏好。21
這套方法能與 Claude Code 以外的工具搭配嗎?
這些架構原則(hooks 作為確定性 gates、skills 作為領域專業、subagents 作為隔離 contexts、檔案系統作為 memory)在概念上適用於任何 agentic system。具體實作使用 Claude Code 的 lifecycle events、matcher patterns 與 Agent tool。AGENTS.md 會把相同模式帶到 Codex、Cursor、Copilot、Amp 與 Windsurf。21 即使實作細節取決於特定工具,harness pattern 本身仍是 tool-agnostic。
快速參考卡
Hook Configuration
{
"hooks": {
"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "script.sh"}]}],
"PostToolUse": [{"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "format.sh"}]}],
"Stop": [{"matcher": "", "hooks": [{"type": "agent", "prompt": "Verify tests pass. $ARGUMENTS"}]}],
"SessionStart": [{"matcher": "", "hooks": [{"type": "command", "command": "setup.sh"}]}]
}
}
Skill Frontmatter
---
name: my-skill
description: What it does and when to use it. Include trigger phrases.
allowed-tools: Read, Grep, Glob
---
Subagent Definition
---
name: my-agent
description: When to invoke. Include PROACTIVELY for auto-delegation.
tools: Read, Grep, Glob, Bash
model: opus
permissionMode: plan
---
Instructions for the subagent.
Exit Codes
| Code | 意義 | 用途 |
|---|---|---|
| 0 | 成功 | 允許 operation |
| 2 | 封鎖 | Security gates、quality gates |
| 1 | 非阻塞警告 | Logging、advisory messages |
關鍵命令
| Command | 目的 |
|---|---|
/compact |
壓縮 context,保留 decisions |
/context |
檢視 context allocation 與 active skills |
/agents |
管理 subagents |
/goal <condition> |
讓 Claude 持續朝 completion condition 工作 |
claude agents |
開啟 Agent View,檢視 running、blocked 與 completed sessions |
CLAUDE_CODE_WORKFLOWS=1 |
啟用 Workflow tool,以進行確定性的 multi-agent orchestration |
claude -c |
繼續最近的 session |
claude --print |
一次性 CLI invocation(沒有 conversation) |
# <note> |
將 note 新增到 memory file |
/memory |
檢視並管理 auto-memory |
檔案位置
| Path | 目的 |
|---|---|
~/.claude/CLAUDE.md |
個人全域 instructions |
.claude/CLAUDE.md |
專案 instructions(git-shared) |
.claude/settings.json |
專案 hooks 與 permissions |
~/.claude/settings.json |
使用者 hooks 與 permissions |
~/.claude/skills/<name>/SKILL.md |
個人 skills |
.claude/skills/<name>/SKILL.md |
專案 skills(git-shared) |
~/.claude/agents/<name>.md |
個人 subagent definitions |
.claude/agents/<name>.md |
專案 subagent definitions |
.claude/rules/*.md |
專案 rule files |
~/.claude/rules/*.md |
使用者 rule files |
~/.claude/projects/{path}/memory/MEMORY.md |
Auto-memory |
變更記錄
| 日期 | 變更 |
|---|---|
| 2026-06-20 | 指南 v1.20:Claude Code v2.1.183 + Codex v0.141.0 — 治理與遠端執行安全性。 在安全性考量中加入auto-mode 破壞性命令防護欄(CC v2.1.183 會硬性封鎖未經您要求的 git reset --hard/checkout -- ./clean -fd/stash drop、針對非 agent commit 的 git commit --amend,以及未指定具名 stack 的 terraform/pulumi/cdk destroy),並將其定位為意圖層級規則,補足參數層級規則與 spawn 審查;也在 Codex 對等說明中加入加密 Noise-relay 遠端執行器(Codex v0.141.0:端對端加密執行器通道、跨平台 cwd/shell 保留、P-521 TLS)。 |
| 2026-06-16 | 指南 v1.19:Claude Code v2.1.173–v2.1.179 治理與範圍界定基礎能力,加上 Codex v0.140.0 跨工具匯入。 將 v2.1.178 版本整合進正文:在安全性 → 權限邊界中加入參數層級權限規則 Tool(param:value) 與 * 萬用字元(例如以 Agent(model:opus) 封鎖某個模型層級),並納入 enforceAvailableModels 受管設定(v2.1.175);auto mode 現在會在啟動前審查 subagent spawn,補上以 spawn 繞過限制的缺口(Subagent Patterns);在巢狀 .claude/ 樹中,skills/agents/workflows/output-styles 支援巢狀 .claude/skills 載入 + 最近者優先解析(Skills System);並修正 disallowedTools MCP server-spec 比對問題(Subagent Configuration Fields)。在 Codex 對等說明中加入 Codex /import 跨工具可攜性與永久刪除 session(v0.140.0)。 |
| 2026-06-10 | 指南 v1.18:遞迴 sub-agents(Claude Code v2.1.172)。 在 Recursion Guard 小節加入註記:Claude Code sub-agents 現在可以 spawn 自己的 sub-agents,最多巢狀 5 層;過去 delegation 實質上只有 1 層(v2.1.172,6月10日)。將 userland spawn-budget/depth-cap 模式重新定位為防止 5 層樹狀結構向外爆量展開的控制機制;5 層視為平台上限,而非預設值。 |
| 2026-06-09 | 指南 v1.17:Claude Code v2.1.169–v2.1.170 + Codex v0.138.0–v0.139.0 治理與 multi-agent-v2 強化。 將 5 項已驗證的 harness 架構變更整合進正文。Skills System 新增 「將內建表面隱藏作為治理」小節:disableBundledSkills 設定(以及 CLAUDE_CODE_DISABLE_BUNDLED_SKILLS env var)會向模型隱藏內建 skills、workflows 與內建 slash commands,作為有意識的攻擊面縮減(v2.1.169)。June Hook-Architecture 小節新增 --safe-mode flag(以及 CLAUDE_CODE_SAFE_MODE),可在停用所有自訂項目的情況下啟動 session,包括 CLAUDE.md、plugins、skills、hooks、MCP,用於 clean-room 疑難排解與治理(v2.1.169);另加入模型層級註記:Anthropic 的 Claude Fable 5(claude-fable-5)於 6月9日推出,作為高於 Opus 的 Mythos-class 層級,可在 v2.1.170 透過 /model claude-fable-5 選用,而 Opus 4.8 仍是 Claude Code 的 agentic 預設模型。Memory and Context 新增 /cd command(v2.1.169),可將 session 移到新的工作目錄,同時不中斷 session 中途的 prompt cache。Multi-Agent Orchestration / Codex Parity 針對生產環境強化:close_agent 更名為 interrupt_agent(v0.139.0)、加密 inter-agent message payloads、v2 agent config catalog、agent-residency LRU,以及以 active execution 計算 concurrency(v0.138.0)、AGENTS.md discovery 改經由 environment filesystems 並保留 logical paths,以便在遠端或符號連結 workspace 正確選取檔案(v0.138.0/v0.139.0),以及subagent MCP 啟動警告限定在所屬 thread,不再重複進入 parent(v0.139.0)。 |
| 2026-06-08 | 指南 v1.16:來自 Claude Code v2.1.162–v2.1.166 + Codex v0.137.0 的 6 月 agent 架構模式。 新增 「Stop-hook steering、cross-session authority 與 multi-agent v2」小節,涵蓋 4 項與 harness 相關的變更:(1) Stop/SubagentStop hooks 可回傳 hookSpecificOutput.additionalContext,注入「尚未完成,原因如下」回饋,並在沒有 hook-error block 的情況下延續該 turn(v2.1.163);(2) cross-session messaging 已強化,另一個 session 透過 SendMessage relay 的訊息不再帶有原始使用者的 authority;請將傳入的 inter-agent messages 視為不受信任的資料(v2.1.166);(3) fallbackModel 設定最多可串接 3 個備援模型,並針對不可重試的 API errors 進行一次性 fallback retry,且 claude agents --json 新增 waitingFor 欄位以支援 fleet observability(v2.1.162/166);(4) Codex multi-agent v2(v0.137.0)會讓 runtime 跟隨每個 thread,將 hide_spawn_agent_metadata 預設為 true,將 parent events 傳播給 child listeners,並加入 v1 skills extension,支援 per-turn catalog resolution 與 thread-start/turn-error lifecycle contributor events。AGENTS.md 沒有規格變更(仍由 Agentic-AI-Foundation 管理,沒有 versioned changelog)。 |
| 2026-05-31 | 指南 v1.15:Claude Code v2.1.157 + Hermes v0.15.1/v0.15.2 修補。 新增 「.claude/skills/ 中的 Plugin 與 Skill 匯流」小節:Claude Code v2.1.157 會將專案 .claude/skills/ 目錄中的任何資料夾自動載入為 plugin,無需 marketplace 註冊;claude plugin init <name> 會在該處 scaffolds 新 plugin,包含 manifest + SKILL.md。這對 harness 的影響很實際:小範圍專案工具不再為了進入版本控制而付出 manifest 成本;plugins 仍負責可 bundled-install 的 ZIP 形狀。同一版本也提供 EnterWorktree,可在 session 中途於 Claude 管理的 worktrees 間切換,並在 agent 完成後讓背景 worktrees 保持解鎖,使 git worktree remove/prune 能乾淨運作。Hermes Agent v0.15.1(5月29日)是同日 Velocity hotfix:修正 loopback mode 下 dashboard 401 reload-loop、Docker 現在需要明確設定 HERMES_DASHBOARD_INSECURE=1、MCP bare commands(npx、npm、node)可在 Docker 中解析、Skills page 恢復、Kanban workers 可乾淨回應 SIGTERM、Skills.sh catalog 透過 sitemap 從 858 增長到 19,932 筆。Hermes v0.15.2(5月29日)是僅限封裝的 hotfix,將 plugin.yaml manifests 納入 wheel 與 sdist 發行。 |
| 2026-05-28 | 指南 v1.14:Claude Code v2.1.152-v2.1.154 + Codex v0.134.0-v0.135.0 + Hermes v0.15.0 架構模式整理。 Claude Code 調整預設值並新增 orchestration primitives:Opus 4.8 現在是預設模型,預設 high effort,並新增 /effort xhigh;dynamic workflows 可透過 /workflows 在背景 orchestrate 數十到數百個 agents;除 Haiku/Sonnet/Opus 4.7 及更早版本外,lean system prompt 現在是所有模型的預設;新的 MessageDisplay hook event 讓 hooks 能在 assistant text 顯示時轉換或隱藏它;skill/command frontmatter 中的 disallowed-tools 會在 skill 啟用期間移除 tools;/reload-skills 可在不重新啟動的情況下重新掃描 skill directories;SessionStart hooks 可回傳 reloadSkills: true 並設定 hookSpecificOutput.sessionTitle;--fallback-model 可在 primary 缺失時於 session 中途切換;auto mode 不再需要 opt-in consent;pluginSuggestionMarketplaces managed setting 可將 context-aware suggestions 限定於組織 marketplaces;claude agents 接受 ! <command> background-shell sessions;plugins 可宣告 defaultEnabled: false;stdio MCP subprocess env 現在包含 CLAUDE_CODE_SESSION_ID 與 CLAUDECODE=1。Codex v0.134.0 讓 --profile 成為主要 profile selector,涵蓋 CLI、TUI permissions 與 sandbox flows(legacy configs 會被拒絕並提供 migration guidance)、新增本機 conversation-history search、改善 MCP setup,支援 per-server environment targeting 與 streamable HTTP servers 的 OAuth,並允許唯讀 MCP tools 在宣告 readOnlyHint 時並行執行;v0.135.0 新增更豐富的 codex doctor diagnostics、/status remote details、vim text-object editing、/permissions 中的 named permission profiles,以及 Python SDK 中的 Sandbox presets。Hermes Agent v0.15.0(5月28日)發布 Velocity release:run_agent.py 跨 14 個 modules 重構 76%、multi-agent Kanban v2 支援 auto-decomposition 與 swarm topology、Bitwarden Secrets Manager 以一個 bootstrap token 取代 per-provider keys、以 3 個 security chokepoints 防禦 Brainworm-class prompt injection 的 Promptware defense、skill bundles、可在單一 terminal 管理 multi-session 的 TUI session orchestrator,以及快 4,500 倍且移除 LLM dependency 的 session_search。Harness 架構意涵:named-profile 模式(Codex --profile、Claude Code pluginSuggestionMarketplaces)正成為 multi-tenant agent runtimes 的標準設定 primitive;並行唯讀 MCP tools(Codex readOnlyHint)是分散非變更性 context fetches 的正確模式;MessageDisplay hook 為 operators 提供第一級 transformation surface,這是過去 PostToolUse 或 Stop 無法觸及的;lean-system-prompt 預設則移除了長期存在於 operator-defined context 與 provider scaffolding 之間的取捨。 |
| 2026-05-24 | 指南 v1.13:Claude Code v2.1.150 + OpenAI Agents SDK v0.17.3 安全性與現況更新。 本機 claude --version 回傳 2.1.144 (Claude Code),而 @anthropic-ai/claude-code 的 npm latest 回傳 2.1.150,GitHub latest release 回傳 v2.1.150。新增 v2.1.149 harness 指引,涵蓋 PowerShell permission-bypass 修正、PowerShell allow-rule/stale-variable permission-analysis 修正,以及 git-worktree sandbox write-allowlist 修正;並註明 v2.1.150 僅為內部基礎設施更新,沒有宣布面向使用者的變更。openai-agents 的 PyPI latest 回傳 0.17.3,因此 OpenAI sandbox 小節現已註明 0.17.1-0.17.3 的後續強化,涵蓋 archive extraction、GitRepo subpaths、sandbox credentials、relative workspace roots 與 provider terminal-state handling。5354 |
| 2026-05-21 | 指南 v1.12:Claude Code v2.1.147 Workflow 整理。 本機 claude --version 回傳 2.1.144 (Claude Code),而 @anthropic-ai/claude-code 的 npm latest 回傳 2.1.147。新增預設關閉的 Workflow tool,作為第一方 deterministic multi-agent orchestration primitive;並釐清 hooks、tests、review gates、spawn budgets 與 evidence reports 仍是 correctness boundary。52 |
| 2026-05-15 | 指南 v1.11:Claude Code v2.1.142 background-session 與 plugin reliability 整理。 本機 claude --version 回傳 2.1.141 (Claude Code),而 @anthropic-ai/claude-code 的 npm latest 回傳 2.1.142。新增 operator guidance,涵蓋新的 claude agents dispatch flags、Opus 4.7 Fast-mode default、root-level plugin SKILL.md discovery、plugin LSP visibility、MCP_TOOL_TIMEOUT remote HTTP/SSE behavior,以及 background-session / daemon / plugin-cache reliability fixes。51 |
| 2026-05-14 | 指南 v1.10:Claude Code v2.1.141 operator-signaling 與 scoping 整理。 本機 claude --version 回傳 2.1.141 (Claude Code),@anthropic-ai/claude-code 的 npm latest 回傳 2.1.141。新增 terminalSequence hook 指引,將其定位為 operator signaling 而非 enforcement;註明可用 claude agents --cwd <path> 進行目錄範圍的 Agent View;並記錄 CLAUDE_CODE_PLUGIN_PREFER_HTTPS 加上 ANTHROPIC_WORKSPACE_ID 對 plugin installation 與 workload-identity federation scoping 的架構影響。50 |
| 2026-05-13 | 指南 v1.9:Claude Code v2.1.140 reliability 整理。 本機 claude --version 回傳 2.1.140 (Claude Code)。在 agent-hook 指引中加入 subagent_type,並更新 hook governance 小節,涵蓋 v2.1.140 對 ConfigChange、disableAllHooks、allowManagedHooksOnly、permission-dialog env-var display、settings sync 後 custom style reset、Windows Git Bash native-package fallback,以及 /scroll-speed behavior 的修正。49 |
| 2026-05-11 | 指南 v1.8:Claude Code v2.1.139 現況整理 + 聚焦 agent-security/memory 掃描。 已驗證本機 claude --version 為 2.1.139,並新增 v2.1.139 operational changes:透過 claude agents 使用 Agent View、/goal completion loops、command-hook args、PostToolUse continueOnBlock、MCP CLAUDE_PROJECT_DIR,以及 OpenTelemetry active-time fix。424344 新增來自〈The Memory Curse〉arXiv preprint 的 memory-curation warning、來自 PR-lifecycle arXiv preprint 的 human merge-authority guidance,以及來自 Gryph Agents 與 LiteLLM advisories 的 agent-log/guardrail security guidance。45464748 修正 Skills vs Hooks vs Subagents token-budget 列的過時內容,從 2% 更新為目前的 1% / 8,000-character skill-description budget。 |
| 2026-05-09 | 指南 v1.7:針對 Claude Code v2.1.136 + openai-agents-python v0.17.0 的第 3 天後續更新。 在 Hook Architecture 中加入 autoMode.hard_deny 與 v2.1.136 hook/plugin fixes 小節,涵蓋新的 unconditional-block tier、跨 VS Code/JetBrains/Agent SDK 的 MCP-disappears-after-/clear 修正、MCP OAuth concurrent refresh 時遺失 refresh-token、當 Edit(...) allow rule 符合時 plan-mode write-block 修正、plugin Stop/UserPromptSubmit cache-cleanup race、skills entry 隱藏預設 skills/ dir,以及 CLAUDE_ENV_FILE SessionStart-hook env vars 在 /resume//clear 後過期。40 在 Production Patterns 中新增 OTel Feedback Survey 小節,涵蓋 CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL。40 以 openai-agents-python v0.17.0 lockdown 擴充 The Sandbox 小節:LocalFile.src / LocalDir.src 被限制在 base_dir 內,除非透過 Manifest.extra_path_grants 搭配 SandboxPathGrant 授權。41 在 Managed vs. Self-Hosted Harnesses 中加入 RealtimeAgent default-model note(gpt-realtime-2)。41 僅 changelog:Claude Code v2.1.137(Win VSCode activation fix)、v2.1.138(internal fixes);claude-agent-sdk-python v0.1.78(CLI v2.1.136 bundle)、v0.1.79(CLI v2.1.137 bundle)、v0.1.80(CLI v2.1.138 bundle)。 |
| 2026-05-08 | 指南 v1.6:針對 Claude Code v2.1.132/v2.1.133 + SDK v0.1.77 的第 2 天後續更新。 在 Skills System 中新增 SDK Skill Surface 小節,涵蓋 ClaudeAgentOptions 的 skills option,以及 allowed_tools 中 "Skill" 的棄用。37 在 Hook Architecture 中新增 Effort and Session Provenance 小節,涵蓋新的 effort.level JSON field + hook input 上的 $CLAUDE_EFFORT env var,以及 Bash subprocesses 上的 CLAUDE_CODE_SESSION_ID env var。3839 在 Subagent Configuration Fields 表格中加入 Subagent skill discovery fix(subagents 現在會透過 Skill tool 探索 project、user 與 plugin skills;v2.1.133 之前會被靜默丟棄)。39 在 Production Patterns 中新增 Worktree Base, Sandbox Paths, and Admin Settings 小節,涵蓋 worktree.baseRef(破壞性預設從 local HEAD 還原回 origin/<default>)、sandbox.bwrapPath、sandbox.socatPath 與 parentSettingsBehavior。39 |
| 2026-05-07 | 指南 v1.5:Claude Managed Agents,5月6日舊金山擴充。 在 Memory and Context 中新增 Strategy 5(Managed Memory Curation: Dreaming, Research Preview),並以表格對照 filesystem-as-memory 與 Dreaming。35 在 Multi-Agent Orchestration 開頭新增 Managed Multiagent Orchestration(Public Beta)與 Outcomes(Public Beta),包含 Anthropic 對 shared-filesystem specialists 與 Claude Console tracing 的逐字引述,以及與 self-hosted deliberation 的比較表。新增 SDK 端 hook event streaming 小節,涵蓋 claude-agent-sdk-python v0.1.74 的 include_hook_events 與 HookEventMessage。36 僅 changelog:Claude Code v2.1.124-v2.1.131(claude project purge、project dirs 的 --dangerously-skip-permissions、skill_activated invocation_trigger、PostToolUse format-on-save fix、PreToolUse JSON+exit-2 blocking fix、skillOverrides settings);claude-agent-sdk-python v0.1.72(CLI 2.1.126)、v0.1.73(session_store_flush)、v0.1.75(CLI 2.1.131)、v0.1.76(api_error_status);openai-agents-python v0.15.0-v0.16.1,其中 v0.16.0(5月7日)預設使用 gpt-5.4-mini、移除隱含的 max_turns 上限,並新增 SDK 端 tool execution concurrency。 |
| 2026-05-07 | 指南 v1.4:依據目前官方文件與本機 runtime 證據更新 Claude Code hook 與 skill 機制(claude --version 2.1.132,codex --version 回傳 codex-cli 0.128.0)。將 hook surface 從 22/26+ 更新為 29 個已記錄 events、將 skill-description budget 從 2%/16,000 修正為 1%/8,000、將 hook-type count 從 4 種改為 5 種並加入 mcp_tool、移除未支援的固定「10 個 parallel subagents」說法,並新增 public-safe Codex parity section,涵蓋 AGENTS.md、skills、hooks、plugins 與明確 subagent workflows。 |
| 2026-04-29 | 指南 v1.3:在 Managed vs. Self-Hosted Harnesses 小節中擴充 OpenAI Agents SDK 覆蓋範圍,加入 openai-agents Python v0.14.0(4月15日)的具名 SDK surface:SandboxAgent、Manifest、SandboxRunConfig、採漸進揭露的 sandbox memory、workspace mounts(S3/R2/GCS/Azure)、portable snapshots,以及 local/Docker/hosted client backends(Blaxel、Cloudflare、Daytona、E2B、Modal、Runloop、Vercel)。以主要 v0.14.0 release-notes citation 取代次要 Help Net Security 引用。新增 claude-agent-sdk-python v0.1.69-v0.1.71(4月28-29日)的短註,作為第 3 種 self-hosted 選項(將 Claude Code runtime 作為 Python library 嵌入):bundled Claude CLI 提升至 v2.1.123、將 mcp dependency floor 提高至 >=1.19.0(較舊版本會靜默丟棄 in-process MCP tools 的 CallToolResult)、Trio nursery cancellation fix,以及 SandboxNetworkConfig allowlist-field 與 TS SDK 對等。v0.14.7-v0.14.8 SDK refinements 記錄於 [^58]。 |
| 2026-04-25 | 指南 v1.2:Google Cloud Next 2026(4月22-24日) — Vertex AI 更名為 Gemini Enterprise Agent Platform;Agentspace 併入統一的 Gemini Enterprise;Workspace Studio(no-code agent builder);Model Garden 中有 200+ models,包含 Anthropic Claude;來自 Box、Workday、Salesforce、ServiceNow 的 partner agents;ADK v1.0 stable 橫跨 4 種語言;Project Mariner(web-browsing agent);具 Apigee 作為 API-to-agent bridge 的 managed MCP servers;A2A protocol v1.0 已在 150 個組織投入生產。Microsoft Agent Framework 1.0(2026年4月):stable APIs、LTS 承諾、完整 MCP 支援、.NET + Python。可即時視覺化 agent execution 與 tool calls 的 browser-based DevUI,與 1.0 stable surface 同步以 preview 形式發布。Salesforce Headless 360(4月15日,TDX):每一項 Salesforce capability(CRM、service、marketing、ecommerce)都以 API/MCP tool/CLI command 暴露,讓 Claude Code、Cursor 與 Codex 等 agents 無需瀏覽器即可在平台上建構。(TDX 2026 於 4月15-16日舉行;Headless 360 公告日期為 4月15日。)MetaComp StableX KYA(4月21日):針對受監管金融服務(payments、compliance、wealth)的 Know Your Agent governance framework,由持牌金融機構推出,屬同類首創;可在 Claude、Claude Code、OpenClaw 與其他相容 AI platforms 上使用。Claude Managed Agents pricing:session 執行期間每 session-hour $0.08,閒置時不收 runtime charge,另加一般 Claude model token rates。(依 Anthropic 的 Claude pricing page;public-beta 於 2026年4月8日推出。)Memory for Managed Agents 於 2026年4月23日以 managed-agents-2026-04-01 beta header 進入 public beta。所有 Managed Agents endpoints 現在都需要此 beta header。 |
| 2026-04-16 | 指南 v1.1:新增 Managed vs. Self-Hosted Harnesses 小節,涵蓋 Claude Managed Agents(4月8日 beta)與 OpenAI Agents SDK harness/compute separation(4月16日)。新增 Scion cross-tool multi-agent hypervisor(4月7日,Google)。記錄 M3MAD-Bench debate plateau finding。新增 The Five Principles of Trustworthy Agents(Anthropic,4月9日)+ MCP/AGENTS.md Linux Foundation governance。加入 Permiso SandyClaw skill-sandbox 參照。新增 Opus 4.7 Long-Horizon Patterns:tool-failure resilience、xhigh effort tier、token-budget ceiling(task_budget beta)、implicit-need awareness,減少 CLAUDE.md scaffolding。 |
| 2026-03-24 | 初次發布 |
參考資料
-
Andrej Karpathy 談到「claws」作為 LLM agents 之上的新層。 HN discussion(406分,917則留言)。 ↩
-
作者的實作。84個 hooks、48個 skills、19個 agents,約15,000行 orchestration。記錄於 Claude Code as Infrastructure。 ↩↩↩↩↩↩↩↩
-
Anthropic,〈Claude Code Hooks: Exit Codes〉。code.claude.com/docs/en/hooks。對多數事件而言,exit 0 允許、exit 2 封鎖、exit 1 警告;
WorktreeCreate更嚴格。 ↩↩↩↩↩ -
Anthropic,〈Extend Claude with Skills〉。code.claude.com/docs/en/skills。Skill 結構、frontmatter 欄位、以 LLM 為基礎的比對,以及 1% / 8,000字元的 description 預算。 ↩↩↩↩↩↩↩
-
Anthropic,〈Claude Code Sub-agents〉。code.claude.com/docs/en/sub-agents。隔離情境、worktree 支援、agent teams。 ↩↩↩↩↩
-
Anthropic,〈Claude Code Documentation〉。docs.anthropic.com/en/docs/claude-code。Memory 檔案、CLAUDE.md、auto-memory。 ↩↩↩↩↩
-
作者的 multi-agent deliberation system。10個研究 personas、7階段 state machine、141項測試。記錄於 Multi-Agent Deliberation。 ↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩↩
-
Simon Willison,〈Writing code is cheap now〉。Agentic Engineering Patterns。 ↩
-
Laban, Philippe 等,〈LLMs Get Lost In Multi-Turn Conversation〉,arXiv:2505.06120,2025年5月。Microsoft Research 與 Salesforce。15個 LLMs、200,000多段對話,平均效能下降39%。 ↩↩↩
-
Mikhail Shilkov,〈Inside Claude Code Skills: Structure, Prompts, Invocation〉。mikhail.io。針對 skill discovery、context injection,以及
available_skillsprompt 區段的獨立分析。 ↩ -
Claude Code Source,
SLASH_COMMAND_TOOL_CHAR_BUDGET。github.com/anthropics/claude-code。 ↩ -
Anthropic,〈Skill Authoring Best Practices〉。platform.claude.com。500行限制、支援檔案、命名慣例。 ↩
-
Anthropic,〈Claude Code Hooks: Lifecycle Events〉。code.claude.com/docs/en/hooks。29個已記錄的 lifecycle events、hook 類型、matcher 行為、async hooks、HTTP hooks、prompt hooks、agent hooks,以及 MCP tool hooks。 ↩↩↩↩↩↩↩
-
作者的 Claude Code hooks 教學。從零開始建立5個 production hooks。記錄於 Claude Code Hooks Tutorial。 ↩↩↩↩↩
-
作者橫跨50個 sessions 的 context window 管理。記錄於 Context Window Management。 ↩↩↩↩↩
-
作者的 Ralph Loop 實作。以 filesystem state 與 spawn budgets 進行 fresh-context iteration。記錄於 The Ralph Loop。 ↩↩↩↩↩↩↩
-
作者的 deliberation system 架構。3,500行 Python、12個模組、confidence trigger、consensus validation。記錄於 Building AI Systems: From RAG to Agents。 ↩↩↩
-
Nemeth, Charlan,In Defense of Troublemakers: The Power of Dissent in Life and Business,Basic Books,2018。 ↩
-
Wu, H., Li, Z., and Li, L.,〈Can LLM Agents Really Debate?〉arXiv:2511.07784,2025。 ↩
-
Liang, T. 等,〈Encouraging Divergent Thinking in Large Language Models through Multi-Agent Debate〉,EMNLP 2024。 ↩
-
作者對實際 repositories 中 AGENTS.md 的分析。記錄於 AGENTS.md Patterns。另見:GitHub Blog,〈How to Write a Great agents.md: Lessons from Over 2,500 Repositories〉。 ↩↩↩↩↩↩↩↩
-
作者的 quality loop 與 evidence gate 方法論。屬於 Jiro Craftsmanship system 的一部分。 ↩
-
Anthropic,〈Claude Managed Agents Overview〉。Public beta 於2026年4月8日推出。Harness-as-a-service,具備 session checkpointing、bundled sandbox、REST API。定價:標準 tokens + 每 session-hour 0.08美元。Beta header
managed-agents-2026-04-01。 ↩↩ -
OpenAI,〈openai-agents Python v0.14.0 release notes〉。2026年4月15日發布;公告於4月16日涵蓋。將 Sandbox Agents SDK 介面作為既有
Agent/Runner流程上的 beta 層引入:SandboxAgent、Manifest(workspace contract)、SandboxRunConfig、capabilities(shell、filesystem editing、image inspection、skills、sandbox memory、compaction)、workspace mounts(local、Git、remote: S3、R2、GCS、Azure Blob、S3 Files)、具備 path normalization 與 symlink preservation 的可攜式 snapshots,以及用於 resume 的 run-state serialization。Backends:UnixLocalSandboxClient、DockerSandboxClient,以及透過 optional extras 提供的 Blaxel、Cloudflare、Daytona、E2B、Modal、Runloop、Vercel hosted clients。4月16日公告摘要見 Help Net Security。 ↩↩ -
Google Cloud,〈Scion: Multi-Agent Hypervisor〉。2026年4月7日開源。將 Claude Code、Gemini CLI 與其他 deep agents 編排為隔離處理程序,並為每個 agent 配置 container、git worktree 與 credentials。支援 local/hub/Kubernetes 部署模式。InfoQ coverage。 ↩
-
Multi-agent debate research cluster,2026年第1至第2季。Wu 等,〈Can LLM Agents Really Debate?〉(arXiv 2511.07784);M3MAD-Bench —— multi-model multi-agent debate benchmark,顯示效能趨於停滯,且容易受到誤導性 consensus 影響;Tool-MAD —— 每個 agent 的 heterogeneous tool assignment + Faithfulness/Relevance judge scores。 ↩
-
Anthropic,〈Our framework for developing safe and trustworthy agents〉。2026年4月9日。五項原則:human control、value alignment、security、transparency、privacy。MCP 捐助 Linux Foundation 的 Agentic AI Foundation。 ↩↩
-
Permiso Security,〈SandyClaw: First Dynamic Sandbox for AI Agent Skills〉。2026年4月2日。Skill execution sandbox,具備 Sigma/YARA/Nova/Snort 偵測與有 evidence-backed 的 verdicts。 ↩
-
Anthropic,〈Introducing Claude Opus 4.7〉。2026年4月16日。Long-horizon agent 改進:相較 Opus 4.6,SWE-Bench production task resolution 提升3倍、tool-failure resilience、
xhigheffort tier、task budgets(beta)、implicit-need awareness。Messages API breaking changes 亦請參閱 What’s new in Opus 4.7。 ↩ -
綜合參考資料 — OpenAI
openai-agents-pythonv0.14.7(2026年4月28日)和 v0.14.8(2026年4月29日);Anthropicclaude-agent-sdk-pythonv0.1.69(4月28日)、v0.1.70(4月28日)和 v0.1.71(4月29日)。v0.14.7重點:在 tool items 上加入tool_name/call_id便利屬性、提高 Phase 2 memory consolidation 回合限制、為 sandbox compaction 加入 GPT-5.5 別名、強化 tar/zip 成員驗證、拒絕LocalFile來源中的符號連結、從 Responses API呼叫移除未設定欄位。v0.14.8重點:保留MCP重新匯出 import 錯誤、為 sandbox prompt-instruction 區段加上分隔。claude-agent-sdk-python v0.1.69為ClaudeAgentOptions欄位加入 docstrings,並將隨附的CLI升級至 v2.1.121;v0.1.70將mcp相依性的最低版本提高到>=1.19.0(較舊版本會默默丟棄來自處理程序內MCP工具處理常式的CallToolResult回傳)、修正以options.stderr設定疊代query()時,提早取消造成的 Trio nursery 損壞問題(stderr reader 現在使用spawn_detached()),並將隨附的CLI升級至 v2.1.122;v0.1.71在SandboxNetworkConfig加入網域 allowlist 欄位(allowedDomains、deniedDomains、allowManagedDomainsOnly、allowMachLookup),以對齊TypeScript schema,並將隨附的CLI升級至 v2.1.123。 ↩ -
OpenAI,“使用 AGENTS.md 的自訂指示”。Codex會在工作前讀取全域與專案
AGENTS.md/AGENTS.override.md檔案,合併從根目錄到目前目錄的指引,並以project_doc_max_bytes限制專案文件大小。 ↩ -
OpenAI,“Agent Skills”。Codex skills 使用
SKILL.md、progressive disclosure、明確的$skill呼叫,以及依描述進行的隱式啟用。 ↩ -
OpenAI,“Codex Hooks”。Codex hooks 支援 config 中的 command hooks、plugin hooks、managed hooks、支援事件的 matchers、stdin JSON輸入,以及JSON輸出欄位。 ↩
-
OpenAI,“Codex Subagents”和“Codex CLI 0.128.0 變更記錄”。Codex支援明確的平行 subagent workflows、內建
default、worker和exploreragents、自訂 TOML agents、繼承的 sandbox policy、plugin-bundled hooks、hook 啟用狀態,以及 0.128.0 中持久保存的/goalworkflows。 ↩ -
Anthropic,“Claude Managed Agents 新功能”。2026年5月6日。Dreaming(Research Preview):排程背景處理程序,會檢閱 agent sessions 和 memory stores、擷取模式,並整理 memories。Outcomes(Public Beta):以 rubric 為基礎的評估,由另一個 grader 在自己的 context window 中依 rubric 為輸出評分,因此不會受到 agent 推理影響。Multiagent Orchestration(Public Beta):lead agent 將工作的部分內容委派給 specialists,每個 specialist 都有自己的 model、prompt 和 tools;specialists 在共享檔案系統上平行工作,並為 lead agent 的整體 context 做出貢獻,所有步驟都可在Claude Console 中完整追蹤。 ↩↩↩↩↩↩↩↩
-
Anthropic,
claude-agent-sdk-pythonv0.1.74。2026年5月6日。將include_hook_events加入ClaudeAgentOptions;設定後,hook events(PreToolUse、PostToolUse、Stop、其他)會由CLI發出,並以HookEventMessage形式從 message stream 產生,對應TypeScript SDK的includeHookEvents。隨附的Claude CLI升級至 v2.1.129。 ↩↩ -
Anthropic,
claude-agent-sdk-pythonv0.1.77。2026年5月8日。棄用allowed_tools中的"Skill"值,改用ClaudeAgentOptions上的專用skills選項,讓Claude Code取得更多關於可用 skills 的結構化訊號,改善Command failed例外的錯誤訊息,並隨附Claude CLI v2.1.133。 ↩↩ -
Anthropic,Claude Code v2.1.132。2026年5月6日。為 Bash tool subprocesses 加入
CLAUDE_CODE_SESSION_ID環境變數(與 hooks 已可見的session_id一致)、加入CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN以保留對話於原生 scrollback、更新/tui fullscreen啟動畫面(降低記憶體、支援滑鼠、選取時自動複製),並包含約二十項錯誤修正,涵蓋 SIGINT graceful shutdown、surrogate emoji--resume損壞、plan-mode--permission-mode旗標、Indic 和 ZWJ 游標處理、NFD vim ops、以/開頭的貼上內容被吞掉、MCP無界記憶體、MCPtools/list重試、Bedrock + VertexENABLE_PROMPT_CACHING_1H400,以及 statuslinecontext_window顯示累計 tokens。 ↩↩ -
Anthropic,Claude Code v2.1.133。2026年5月7日。Hooks 現在會收到
effort.levelJSON輸入和$CLAUDE_EFFORT環境變數(也可從 Bash commands 讀取)。Subagents 會透過Skilltool 探索 project、user 和 plugin skills(迴歸修正)。新的 admin settings:worktree.baseRef(fresh|head)會在 v2.1.128 改用本機HEAD後,將 worktree base 還原為origin/<default>;sandbox.bwrapPath和sandbox.socatPath會在 Linux/WSL 上固定 sandbox binaries;parentSettingsBehavior('first-wins' | 'merge')控制SDKmanagedSettings如何與 parent settings 組合。其他修正:parallel-session 401-after-refresh-token-race、drive-root allow-rule scoping、MCP OAuth proxy/mTLS 支援、Remote Control stop/interrupt 完成取消、跨 session/effort外洩、--remote-control列於--help。 ↩↩↩↩↩↩ -
Anthropic,Claude Code v2.1.136。2026年5月8日。加入
settings.autoMode.hard_deny,用於 auto-mode classifier rules,可不受使用者意圖或允許例外影響而無條件封鎖;加入CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTEL,讓企業能重新啟用 session 內 quality survey,透過 OpenTelemetry 擷取回應。對操作人員有影響的修正:來自.mcp.json、plugins 和 claude.ai connectors 的MCP servers,在 VS Code、JetBrains 和 Agent SDK中執行/clear後會無聲消失;MCP OAuth refresh tokens 會在並行重新整理時遺失;當存在相符的Edit(...)allow rule 時,plan mode 未封鎖檔案寫入;cache cleanup 刪除仍在執行的版本時,pluginStop/UserPromptSubmithooks 失敗;plugin.json中的skills項目隱藏 plugin 預設的skills/目錄;CLAUDE_ENV_FILESessionStart-hook 環境變數在/resume或/clear後過期。另有約三十項涵蓋 TUI、自動完成與終端機算繪的精修與可靠性修正。配套版本:v2.1.137(5月9日,VSCode extension Windows 啟用修正)、v2.1.138(5月9日,內部修正);claude-agent-sdk-pythonv0.1.78、v0.1.79和 v0.1.80 分別將隨附的Claude CLI升級至 v2.1.136、v2.1.137 和 v2.1.138。 ↩↩↩↩ -
OpenAI,
openai-agents-pythonv0.17.0。2026年5月8日。RealtimeAgent預設為gpt-realtime-2。Sandbox local-source materialization 現在會將LocalFile.src和LocalDir.src限制在 manifestbase_dir內(套用 manifest 時的SDK處理程序目前工作目錄),除非來源透過Manifest.extra_path_grants搭配SandboxPathGrant明確授權。相對 local sources 會從base_dir解析;絕對來源必須已位於其中,或位於明確 grant 之下。遷移:在 manifest 層級宣告受信任的 host roots,最好設為唯讀。請將extra_path_grants視為受信任的應用程式設定;不要用 model output 或不受信任的 manifest input 填入。另包含 Responses context-managementextra_args衝突修正。 ↩↩↩↩ -
Anthropic, Claude Code v2.1.139。2026年5月。2026年5月11日的目前工作階段本機證據:
claude --version傳回2.1.139 (Claude Code)。版本說明新增 Agent View(claude agents)、/goal、hookargs: string[]、PostToolUse的continueOnBlock、MCP stdio 伺服器的CLAUDE_PROJECT_DIR、${CLAUDE_PROJECT_DIR}的 plugin 命令插值,以及包含--print模式中claude_code.active_time.totalOpenTelemetry 發出的修正。 ↩↩↩↩↩ -
Anthropic, 「使用 agent view 管理多個 agents」。Agent View 文件說明如何從單一畫面派送並管理多個 Claude Code 工作階段、查看每個工作階段正在執行的內容,以及識別需要操作員輸入的工作階段。該頁面將 Agent View 標示為 Research Preview,並記載本機工作階段限制。 ↩↩↩
-
Anthropic, 「Claude Code Hooks」。Hook 文件涵蓋 command-hook 欄位、
PreToolUse、PostToolUse、exit-code 行為、hook 輸入/輸出,以及直接 slash-command 展開路徑。 ↩↩ -
GitHub Advisory Database, GHSA-f3jg-756w-gm35 / CVE-2026-45046。「Gryph Agents Payload Filter 未能移除敏感內容的 Tool Payload。」發布於2026年5月;描述在預設記錄行為下,敏感的
file-writepayload 內容仍保留在本機 SQLite logs 中,並已於 Gryph v0.7.0 修正。 ↩↩ -
OSV, GHSA-wxxx-gvqv-xp7p / CVE-2026-40217。「LiteLLM 的 custom-code guardrail 存在 sandbox escape。」發布於2026年5月11日;描述受管理員保護的
POST /guardrails/test_custom_code端點,會在手工打造的 sandbox 中執行使用者提供的 Python,並建議升級,或在無法升級時封鎖該端點。 ↩↩ -
Young Jo (seph) Chung and Safwat Hassan, 「協作者還是 Assistnat?AI Coding Agents 如何在 Pull Request 生命週期中分工」, arXiv:2605.08017v1, 2026年5月。摘要報告分析 OpenAI、Copilot、Devin、Cursor 與 Claude Code 的 29,585 個 PR 生命週期,區分 operational agency 與 merge governance。 ↩↩
-
Jiayuan Liu et al., 「記憶詛咒:擴展回想如何侵蝕 LLM Agents 的合作意圖」, arXiv:2605.08060v1, 2026年5月。摘要報告橫跨 7 個 LLMs 與 4 款遊戲、共 500 回合的實驗;擴展可存取歷史在 28 個 model-game 設定中,有 18 個降低了合作程度。 ↩↩
-
Anthropic, Claude Code v2.1.140。2026年5月12日。將
subagent_type新增至 agent hook 輸入,並修正ConfigChangehooks、disableAllHooks、allowManagedHooksOnly、hook 結果中的 permission-dialog env-var 顯示、settings 更新後的自訂樣式重設、Windows Git Bash 上的原生套件解析 fallback,以及/scroll-speed。 ↩↩↩ -
Anthropic, Claude Code v2.1.141。2026年5月13日。將
terminalSequence新增至 hook JSON 輸出,以支援桌面通知、視窗標題與鈴聲;新增CLAUDE_CODE_PLUGIN_PREFER_HTTPS以供 HTTPS plugin-source clone;新增ANTHROPIC_WORKSPACE_ID以限定 workload identity federation workspace 範圍;新增claude agents --cwd <path>以供 Agent View 目錄篩選;新增/feedback工作階段附件選項,可選最近 24 小時或 7 天;並提供相關的 agent、background-job、hook、MCP、Remote Control、permission-dialog 與 terminal-rendering 修正。2026年5月14日的目前工作階段驗證:claude --version傳回2.1.141 (Claude Code),且npm view @anthropic-ai/claude-code version dist-tags.latest time.modified --json傳回最新版本2.1.141。 ↩↩↩ -
Anthropic, Claude Code v2.1.142。2026年5月14日。新增供 background sessions 使用的
claude agents派送 flags(--add-dir、--settings、--mcp-config、--plugin-dir、--permission-mode、--model、--effort、--dangerously-skip-permissions),將 Fast mode 預設改為 Opus 4.7,並以CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE=1作為固定版本覆寫;當不存在skills/目錄時,會將 root-level pluginSKILL.md檔案公開為 skills;在 plugin details 中顯示 plugin 提供的 LSP 伺服器;在取代現有 GitHub App 連線前發出警告;並修正MCP_TOOL_TIMEOUT、background-session worktree、daemon sleep/wake、post-upgrade daemon cleanup、plugin cache,以及 Agent View 可靠性問題。2026年5月15日的目前工作階段驗證:claude --version傳回2.1.141 (Claude Code),npm latest 傳回2.1.142。 ↩↩ -
Anthropic, Claude Code v2.1.147。2026年5月21日。新增預設關閉的
Workflowtool,用於確定性的 multi-agent orchestration(CLAUDE_CODE_WORKFLOWS=1)、固定的 background sessions、取代/simplify的/code-review [effort] --comment、REPL 與 Workflow sandbox 強化、auto-updater diagnostics、large-diff rendering 改進、prompt-history deduplication,以及 enterprise login restrictions、PowerShell 行為、MCP pagination、Agent View、plugins、hook conditions、貼上文字與 stripped-image loops 的修正。2026年5月21日的目前工作階段驗證:claude --version傳回2.1.144 (Claude Code),且npm view @anthropic-ai/claude-code version dist-tags.latest time.modified --json傳回最新版本2.1.147,time.modified為2026-05-21T20:38:35.053Z。 ↩↩↩ -
Anthropic, Claude Code v2.1.148、v2.1.149、v2.1.150,以及 Claude Code CHANGELOG。v2.1.148 修正 v2.1.147 造成的 Bash exit-code regression。v2.1.149 新增
/usage依類別限制用量、/diff鍵盤捲動、GFM task-list rendering,以及 EnterpriseallowAllClaudeAiMcps;harness 相關修正包含 PowerShellcdpermission bypasses、PowerShell prefix/wildcard 與 stale-variable permission analysis、git-worktree sandbox write-allowlist scope、macOS 上 Bashfind造成的 vnode exhaustion、managed-settings approval freezes、otelHeadersHelperpath-space diagnostics,以及 Remote Control session rename sync。v2.1.150 僅含內部基礎架構。2026年5月24日的目前工作階段驗證:本機claude --version傳回2.1.144 (Claude Code),而 npm latest 傳回2.1.150,time.modified為2026-05-23T04:03:10.243Z;GitHub latest release 傳回v2.1.150,發布時間為2026-05-23T04:03:51Z。 ↩↩↩ -
OpenAI,
openai-agents-pythonv0.17.1、v0.17.2,以及 v0.17.3。v0.17.1 新增 sandbox-provider error details、archive extraction limits、GitRepo subpath validation,以及 tracing/session/realtime 修正。v0.17.2 修正 Conversations reasoning persistence、local approval rejection reasons、AsyncSQLiteSession settings,以及 realtime unknown-tool behavior。v0.17.3 讓 mountpoint credentials 不會進入 sandbox commands、拒絕相對 sandbox workspace roots、處理 terminal Vercel sandbox states,並修正 output-schema、guardrail、runtime 與 memory import 邊界案例。2026年5月24日的目前工作階段驗證:python3 -m pip index versions openai-agents傳回最新版本0.17.3;GitHub latest release 傳回v0.17.3,發布時間為2026-05-19T01:27:36Z。 ↩↩ -
Claude Code 變更日誌(canonical)、v2.1.152 發行說明、v2.1.153 發行說明、v2.1.154 發行說明。v2.1.152(5月27日)新增
MessageDisplayhook event、skill/command frontmatter 中的disallowed-tools、/reload-skills、SessionStarthook 的reloadSkills與sessionTitle輸出、/code-review --fix套用至 working tree、pluginSuggestionMarketplaces受管理設定、移除 auto-mode opt-in,以及--fallback-model的工作階段中途切換。v2.1.153(5月28日)讓/model儲存為新工作階段預設值,並以s表示僅限目前工作階段;新增 plugin marketplaces 的skipLfs;在 status-line env 中顯示COLUMNS/LINES;並持久保留 macOS background-agent 的「隱私權與安全性」授權。v2.1.154(5月28日)將 Opus 4.8 設為預設,且預設採用高 effort,並新增/effort xhigh;透過/workflows導入動態 workflows;讓 Opus 4.8 的 Fast mode 可用 2× 費率換取 2.5× 速度;除 Haiku/Sonnet/Opus 4.7 及更早版本外,所有模型預設使用精簡 system prompt;讓claude agents接受! <command>以用於 background-shell sessions;允許 plugins 宣告defaultEnabled: false;將CLAUDE_CODE_SESSION_ID與CLAUDECODE=1傳遞至 stdio MCP 子程序環境;並棄用CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE(6月1日移除)。 ↩ -
Codex Changelog(OpenAI Developers)與openai/codex releases。Codex CLI 0.134.0(2026年5月26日)新增本機對話歷史搜尋;讓
--profile成為 CLI/TUI/sandbox 流程中的主要 profile 選擇器,並支援舊版設定遷移;改善 MCP setup,加入每部伺服器的環境目標設定,以及 streamable HTTP servers 的 OAuth;透過保留本機$ref/$defs並在公開前壓縮過大的 schemas,使 connector tool schemas 更可靠;並允許並行執行標示readOnlyHint的唯讀 MCP tools。Codex CLI 0.135.0(2026年5月28日)新增更完整的codex doctor診斷;在/status中顯示遠端連線詳細資料與伺服器版本;新增 vim text-object 編輯,改善 word/line-end 行為並支援可設定的 interrupt-turn;讓/permissions理解具名 permission profiles;在支援的 macOS 與 Linux 上封裝 bundled patched zsh helper;並在 Python SDK 中為 thread 與 turn APIs 新增友善的Sandboxpresets。 ↩ -
Hermes Agent v0.15.0 發行說明。「The Velocity release。」1,302 次 commits、747 個 merged PRs、321 位社群貢獻者。
run_agent.py重構 76%(跨 14 個 modules,16,083 → 3,821 行)。Multi-agent Kanban 平台,具備 auto-decomposition、swarm topology、per-task model overrides、scheduled tasks 與 worktree management。session_search重新設計後快了 4,500×,並移除 LLM 依賴。針對 Brainworm 類 prompt injection,在 3 個 security chokepoints 提供 Promptware 防禦。整合 Bitwarden Secrets Manager,以單一 bootstrap token 取代各 provider keys。Skill bundles 可用一個 slash command 載入多個 skills。TUI session orchestrator 可在一個終端機中管理多個 sessions。Krea 2 與 FAL image-generation providers;xAI integration round(web-search plugin、OAuth upstream、retired-model detection、natural TTS pauses)。 ↩ -
Claude Code v2.1.157 發行說明與Claude Code 變更日誌(canonical)。2026年5月29日。放在專案
.claude/skills/目錄中的 plugins 現在會自動載入,不再需要 marketplace;claude plugin init <name>會在該目錄中搭建全新的 plugin;/plugin新增參數自動完成。另外:EnterWorktree可以在工作階段中途切換 Claude 管理的 worktrees;background worktrees 會在 agent 完成後保持解鎖,讓git worktree remove/prune能順利運作;當OTEL_LOG_TOOL_DETAILS=1時,tool_decisiontelemetry events 會包含tool_parameters。也包含多項 bug fixes:無法處理的圖片現在會降級為文字 placeholders;auto/bypass mode 中的 sandbox network permission prompts;background-session retire-on-park;以及 tmux / VS Code / Cursor / Windsurf 中的 terminal rendering。 ↩ -
Claude Code 變更日誌(canonical)與Codex CLI v0.137.0 發行說明,2026年6月。Claude Code v2.1.162(6月3日)在
claude agents --json中新增waitingFor;v2.1.163(6月4日)為Stop/SubagentStop的非錯誤回饋新增hookSpecificOutput.additionalContext;v2.1.166(6月6日)強化跨工作階段SendMessage權限(轉送訊息不再帶有 user authority),並新增fallbackModel設定(最多 3 個 fallbacks,針對 non-retryable errors 進行一次性重試)。Codex CLI v0.137.0(6月4日)推出 multi-agent v2(runtime-with-thread、hide_spawn_agent_metadata預設為 true、parent→child event propagation)、具備 per-turn catalog resolution 的 v1 skills extension,以及 thread-start/turn-error lifecycle contributor events;Codex subagents docs確認 default/worker/explorer agent types 與agents.max_threads/max_depthconcurrency controls。AGENTS.md(agents.md)未發布版本化 spec 變更。目前工作階段驗證日期為 2026年6月8日。 ↩ -
Anthropic、Claude Code v2.1.169 發行說明與v2.1.170 發行說明,2026年6月8日至9日。v2.1.169 新增
disableBundledSkills設定與CLAUDE_CODE_DISABLE_BUNDLED_SKILLS(向模型隱藏 bundled skills、workflows 與內建 slash commands);新增--safe-mode旗標與CLAUDE_CODE_SAFE_MODE(以停用所有自訂項目的狀態啟動工作階段:CLAUDE.md、plugins、skills、hooks 與 MCP servers);並新增/cd命令(將工作階段移至新的工作目錄,不破壞 prompt cache)。v2.1.170 讓 Claude Fable 5(claude-fable-5)可透過/model claude-fable-5選用,而 Opus 4.8 仍是 Claude Code 的 agentic default。模型級別發布:Anthropic、“Claude Fable 5”,2026年6月9日 — 屬於 Opus 之上的「Mythos-class」級別,描述為 Anthropic 迄今最強大且可安全供一般用途使用的模型。 ↩↩↩↩ -
OpenAI,Codex CLI rust-v0.138.0 發行說明(2026年6月8日)與rust-v0.139.0 發行說明(2026年6月9日)。v0.138.0 透過 encrypted inter-agent message payloads、v2 agent config catalog、agent-residency LRU,以及依 active execution 而非 spawned threads 計算 concurrency,強化 multi-agent v2。v0.139.0 將
close_agentlifecycle API 重新命名為interrupt_agent,並將 subagent MCP startup warnings 限定在 owning thread,避免再重複出現在 parent。AGENTS.md discovery 在兩個版本中都已強化:載入會透過 environment filesystems 路由,並在 discovery 期間保留 logical paths,確保 remote 與 symlinked workspaces 能正確選取檔案。 ↩↩↩ -
Anthropic,Claude Code v2.1.172版本資訊(2026年6月10日)。Sub-agents現在可以產生自己的sub-agents,並支援最多5層深度的遞迴委派;先前的委派實際上只有1層。 ↩
-
Anthropic,Claude Code v2.1.175版本資訊和v2.1.178版本資訊,2026年6月12日至15日。v2.1.175新增
enforceAvailableModels受管理設定(固定Default模型,並防止使用者/專案設定擴大受管理的availableModels允許清單)。v2.1.178新增Tool(param:value)權限規則語法,可用*萬用字元比對工具的輸入參數(例如Agent(model:opus));從巢狀.claude/skills目錄載入skills,並在名稱衝突時以<dir>:<name>消除歧義;在碰撞時解析最接近cwd的巢狀.claude/agents、workflows和output-styles(專案範圍的workflow儲存目標會指向最近既有的.claude/workflows/);在啟動前以auto-mode分類器評估subagent產生;並修正subagentdisallowedTools中的MCP伺服器層級規格(mcp__server、mcp__server__*、mcp__*)遭到靜默忽略的問題。 ↩↩↩↩↩↩ -
OpenAI,Codex CLI rust-v0.140.0版本資訊,2026年6月15日(從v0.140.0-alpha系列升格為stable)。新增
/import,可從Claude Code選擇性匯入設定、專案設定和近期聊天;透過codex delete、/delete和app-serverthread/delete永久刪除工作階段,並具備確認防護;為檔案、plugins和skills提供統一的@提及選單;以及/usagetoken活動檢視。 ↩ -
Anthropic,Claude Code v2.1.183版本資訊,2026年6月19日——當您未要求捨棄工作時,auto mode會阻擋破壞性git命令(
git reset --hard、git checkout -- .、git clean -fd、git stash drop)、阻擋對本工作階段中非agent建立的commit執行git commit --amend,並阻擋terraform destroy/pulumi destroy/cdk destroy,除非您要求的是特定stack。OpenAI,Codex CLI rust-v0.141.0版本資訊,2026年6月18日(從v0.141.0-alpha系列升格為stable)——遠端executors使用已驗證、端對端加密的Noise-relay通道;跨平台遠端執行會保留executor原生工作目錄和shell;TLS支援企業proxy使用的P-521憑證簽章。 ↩↩