架构演进
1. 阅读说明与定位
1.1. 本篇回答的三个问题
01-介绍.md 确立了 AI Harness 的定义与六层能力模型,02-发展历史.md 确立了三代演进的时间轴。本篇是两者的交汇点,回答三个问题:
- 当代(第三代)Harness 实际长什么样——每一层由哪些组件构成,这些组件之间如何衔接;
- 每一层的工程设计为什么是现在这个形状——它要克服的失败是什么,为此付出了什么代价;
- 一个组织如何判断自己的 Harness 处在什么水平——给出可操作的自评工具。
1.2. 与前序文档的边界
| 内容 | 归属 | 本篇的处理 |
|---|---|---|
| Harness 的定义、词源、六层模型定义 | 01-介绍 | 直接引用,不重复定义 |
| 三代划分的时间轴、里程碑、历史成因 | 02-发展历史 | 仅在必要时引用,不做历史叙述 |
| 各层的组件、参数、设计权衡、失败模式 | 本篇 | 展开论述 |
| 标准化前景与趋势外推 | 04-未来发展 | 不在本篇做趋势预测 |
| 具体平台的逐产品剖析 | 03-市场研究 | 本篇只取"代表性实现"作为层内样例 |
1.3. 技术参数的来源等级约定
本篇大量引用厂商公布的工程参数。凡引用均标注来源等级,规则沿用 README.md 第 5.2 节:
- A 级:厂商官方一手(Anthropic / OpenAI / Google / Linux Foundation / MCP 官方等),可直接引用;
- B 级:权威二手(Wikipedia、AI Wiki、TechCrunch、GIGAZINE 等),需注明转述;
- C 级:社区与自媒体解读,其数字一律标 。
本篇出现的所有 数字,只能作为方向性参考,不得作为选型或决策依据。
2. 第三代架构总览
2.1. 分层的依据:从"能力分区"到"瓶颈分区"
第三代 Harness 之所以能被稳定地分为六层,不是因为六层是某种先验的功能划分,而是因为每一层对应一类独立涌现的瓶颈。这一点可以从掷 DAG 式的失败归因反推:当一个长周期 agent 任务失败时,工程师的归因几乎总是落在以下六类之一——
| 归因 | 对应层 |
|---|---|
| 它根本没看到那份关键文件 / 上下文太长导致丢信息 | L1 |
| 它想做的动作没有被正确定义为工具 / 执行产生了预期外的副作用 | L2 |
| 它做这件事的顺序是错的 / 卡在某个循环里出不来 | L3 |
| 换一次会话它就"忘了"上一轮做到哪 | L4 |
| 它说"完成了",但实际上没完成 | L5 |
| 它做了不该做的事 / 花超预算了 / 谁干的查不出来 | L6 |
层是被失败界定的,不是被功能清单界定的。 这是判断一个新组件应该归入哪层的实用判据。
2.2. 分层设计总图
图 2-1|第三代架构总览:六层分层设计
┌──────────────────────────────────────────────────────────────────┐
│ L6 治理与安全层 Governance & Safety │
│ 权限 · 沙箱策略 · 凭据保护 · 架构约束 · 熵治理 · 预算护栏 │
│ (横向切面,对 L1~L5 全部施加约束并记录审计) │
└──────────────────────────────────────────────────────────────────┘
▲ ▲ ▲ ▲
│ 约束 │ 约束 │ 约束 │ 审计
┌──┴────────┐ ┌───┴────────┐ ┌───┴─────────┐ ┌──┴──────────┐
│ L1 上下文 │─►│ L2 工具与 │─►│ L3 编排与 │─►│ L5 评估与 │
│ 工程层 │ │ 执行层 │ │ 控制层 │ │ 观测层 │
│ 看到什么 │ │ 能做什么 │ │ 按什么顺序做 │ │ 做得好不好 │
└───────────┘ └────────────┘ └─────────────┘ └─────────────┘
▲ │ │
│ 反馈:改变下次看到什么 │ │
└──────────────────────────────┴───────────────────┘
▲
┌────┴───────────────────────────────────────────┐
│ L4 记忆与状态层 Memory & State │
│ 会话态 · 长期记忆 · 检查点 · 工件 │
│ (时间维度的横向支撑层) │
└────────────────────────────────────────────────┘ 需要强调的是,图中 L5 与 L1 之间的反馈边是第三代与第二代的结构性区别:第二代里评估是外挂的(跑一次榜单,看一眼分数),第三代里评估的输出会回流改变下一次的上下文组装,形成闭环。
2.3. 六层职责、边界与数据流
| 层 | 名称 | 英文 | 职责 | 输入 | 输出 | 典型实现 |
|---|---|---|---|---|---|---|
| L1 | 上下文工程层 | Context Engineering | 决定模型"看到什么" | 环境状态、检索结果、指令 | 组装后的 token 序列 | RAG、Context Compaction、Prompt Assembly、SKILL.md 渐进式披露、KV Cache 复用 |
| L2 | 工具与执行层 | Tooling & Execution | 决定模型"能做什么" | 工具调用意图 | 受控环境中的副作用 | MCP、Function Calling、沙箱执行器、Computer Use |
| L3 | 编排与控制层 | Orchestration & Control | 决定"按什么顺序做" | 任务目标 | 执行步骤序列 | Agent Loop、Plan-and-Execute、DAG / Workflow、Sub-agent |
| L4 | 记忆与状态层 | Memory & State | 决定"记住什么" | 会话历史、工件 | 跨窗口可恢复的状态 | Session Store、Episodic / Semantic Memory、Checkpoint |
| L5 | 评估与观测层 | Evaluation & Observability | 决定"做得好不好" | 执行轨迹、产物 | 判定、指标、回归信号 | Trace、Eval Set、Golden Dataset、Online Metrics |
| L6 | 治理与安全层 | Governance & Safety | 决定"不能做什么" | 策略、预算、合规要求 | 允许 / 拒绝 + 审计记录 | RBAC、护栏模型、审计日志、Budget Guardrail |
主执行链为 L1 → L2 → L3,横向支撑为 L4(时间维)与 L6(约束维),闭合回路为 L5 → L1。
2.4. 与三代演进的对照
本篇所述六层在三代中的成熟度差异如下(纵向看每一层,可以看出第三代的工程重心落在 L1、L2、L5、L6):
| 层 | 第一代 · 提示词工程 | 第二代 · 工具与编排 | 第三代 · 运行时与评估 |
|---|---|---|---|
| L1 | 无治理,靠 Few-shot | 初步 RAG,无压缩策略 | 压缩 + 笔记 + 子 agent + Skills 四件套 |
| L2 | 无工具 | Function Calling(厂商专有) | MCP 标准化 + 强隔离沙箱 |
| L3 | 单轮 | 多智能体编排框架 | 官方 SDK 内置 + 长时运行 + 三角色分工 |
| L4 | 无状态 | 初步会话记忆 | 跨窗口状态交接 + 检查点 + Git 作为状态载体 |
| L5 | 人工主观判断 | 外部基准榜单 | 内置评估闭环 + 独立 Evaluator + 轨迹追踪 |
| L6 | 无 | 手工权限提示 | 沙箱 + 凭据保护 + linter 机械强制 + 熵治理 |
3. L1 上下文工程层
3.1. 层的定位
L1 回答的问题是:在这一步推理之前,模型应该看到哪些 token。它是整个 Harness 中唯一直接作用于模型输入接口的一层,因此在三代演进中始终处在最核心的位置。
Anthropic 在《Effective context engineering for AI agents》(2025,A 级)中给出的官方定义是:在 LLM 推理期间,策展并维护那组最优 Token(信息)的一整套策略。
Andrej Karpathy 在 2025-06-25 给出的定义被广泛引用:
"Context engineering is the delicate art and science of filling the context window with just the right information for the next step."
但他紧接着的补充更有价值——他说 context engineering 只是 "an emerging thick layer of non-trivial software that coordinates individual LLM calls into full LLM apps" 的一小部分。这句话精确界定了 L1 在六层中的位置:它是必要的一层,但远非全部。
3.2. 官方问题陈述:context rot 与注意力预算
Anthropic 官方立起的两个概念,构成了 L1 层的理论基础:
| 概念 | 官方表述 | 工程含义 |
|---|---|---|
| context rot(上下文腐烂) | 明确其为"性能梯度,而非硬性悬崖" | 上下文变长时性能是渐进退化,不存在一个安全的"阈值"。因此上下文必须被持续治理,不能靠一次性截断解决 |
| attention budget(注意力预算) | 自注意力的 n² 关联特性导致每增加一个 token 都会稀释对其他 token 的注意力 | 上下文是稀缺资源,不是免费容器。每放入一个 token 都有机会成本 |
这两条合起来推出一个反直觉但被反复验证的工程结论:往上下文里多塞信息,通常是负优化。第 3.10 节会给出对应的失败模式。
3.3. 关键组件一:压缩(Compaction)
官方把 compression 分为若干档,其中"最安全、最轻量"的一档是 tool result clearing(清空工具调用结果),该能力已在 Claude Developer Platform 上线(A 级)。
官方给出的调优顺序是一条重要的工程纪律:
先最大化召回(recall),再提升精度(precision)。
顺序反了会丢掉后续步骤还要用到的关键约束——因为一旦压缩掉的内容无法复原,模型在后续步骤中会基于不完整的信息做出不可逆的错误决策。
3.4. 关键组件二:结构化笔记与 agentic memory
第二条官方策略是把笔记持久化到上下文窗口之外,需要时再拉回。官方案例包括:
- Claude Code 的 to-do list;
- 自定义 agent 的
NOTES.md; - Claude 玩宝可梦时跨数千步维护的精确计数。
官方同时发布了 Memory tool(随 Sonnet 4.5 在 Claude Developer Platform 上进入 public beta,A 级),把外化笔记变成平台能力。
官方给出的选型原则值得直接作为团队规范引用:
| 策略 | 适用任务特征 |
|---|---|
| Compaction | 需要大量往返(round-trip)的任务 |
| Note-taking | 有清晰里程碑的迭代开发 |
| Multi-agent / Sub-agent | 并行探索有红利的复杂研究 |
3.5. 关键组件三:子智能体上下文隔离
第三条官方策略是 Sub-agent architectures,其官方参数(A 级)为:
子 agent 可以用数万 token 深入探索,但只回传 1,000~2,000 tokens 的浓缩摘要。
这是一个典型的"用上下文换并行度 / 换深度"的架构取舍:主 agent 的上下文窗口保持干净,代价是摘要过程中的信息损耗。本层选型时需显式考虑:摘要损失是否可接受。
3.6. 关键组件四:Skills 与渐进式披露
Agent Skills(Anthropic,2025-10-16 发布,2025-12-18 转为开放标准,A 级)把 L1 从"如何塞进更多"推向"如何按需加载"。
| 要素 | 内容 |
|---|---|
| 最小形态 | my-skill/SKILL.md 目录,可扩展 scripts/、references/、assets/ |
| 必填元数据 | YAML frontmatter 中的 name 与 description |
| 第一层(启动) | 只把每个 skill 的 name + description 载入系统提示词 |
| 第二层(命中) | 读取完整 SKILL.md 全文 |
| 第三层(按需) | 读取 bundled 文件,如 reference.md、forms.md |
| 代码支持 | 可捆绑可执行代码,代码不进入上下文即可运行 |
Anthropic 官方的论断是:
"the amount of context that can be bundled into a skill is effectively unbounded"
这条设计有效缓解了"能力越多、上下文越挤"的矛盾。同时官方给出了用代码替代 token 的经济学理由:排序一个列表,用 token 生成远贵于跑一次排序算法,且代码具有确定性,使工作流可一致复现。
3.7. 另一套行业分类法:四支柱
除 Anthropic 的官方四分法外,业界另一套被广泛使用的是 LangChain 四支柱(2025-06-23 Harrison Chase《The Rise of Context Engineering》,经 Lance Martin 分类法整理,B 级):
| 支柱 | 含义 | 对应实现 |
|---|---|---|
| Write | 外化状态 | scratchpad、NOTES.md |
| Select | 精准检索 | RAG、记忆检索、工具与少样本选择 |
| Compress | 摘要、裁剪、剪枝 | Compaction、tool result clearing |
| Isolate | 隔离 | 子 agent 隔离窗口、沙箱、状态 schema 边界 |
两套分类法可以互相映射:Anthropic 的"前三种策略"基本覆盖 Write / Select / Compress / Isolate 中的前三项,sub-agent 对应 Isolate。
3.8. 代表性实现对比
| 实现 | 形态 | L1 手段 | 来源等级 |
|---|---|---|---|
| Claude Agent SDK / Claude Code | 官方 SDK + CLI | 四件套齐全(compaction / note / memory tool / sub-agent),SKILL.md 渐进式披露 | A |
| OpenAI Agents SDK / Codex | 官方 SDK + CLI | "AGENTS.md 作目录"策略,上下文约 100 行注入 + 结构化 docs/ 外置(见 10.2 节) | A |
| Google ADK | 官方 SDK | Session / Runner 作为状态边界(跨 curtailed 会话的类型化状态) | A |
| LangChain / LangGraph | 开源框架 | 四支柱理论最完整的落地,可通过 node 边界做 Isolate | B |
3.9. 设计权衡
L1 层的三个核心权衡:
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 召回 vs 精度 | 全量塞入(高召回、易腐烂) vs 精准检索(高精度、易遗漏) | 官方给的顺序:先召回后精度 |
| 深度 vs 干净 | 主上下文全量保留(深但易脏) vs 子 agent 摘要(干净但有损) | 任务是否需要跨步骤强一致性 |
| 静态注入 vs 动态加载 | 一次性注入全部指令(简单但贵) vs Skills 渐进披露(省但需路由准确) | 路由命中率是否足够高;命中率低时渐进披露反而更差 |
3.10. 失败模式
L1 层已识别出四类上下文失败(B 级,LangChain 归类经多方转述):
| 失败模式 | 含义 | 典型症状 |
|---|---|---|
| context poisoning | 错误信息在会话中被当作事实传播 | 一次工具报错后,后续全部推理建立在错误前提上 |
| context distraction | 关键信息被噪声淹没 | 检索返回 50 段相关片段,模型只用了前 3 段 |
| context confusion | 冗余信息导致失焦 | 指令中加入过多"也可以这样"的建议,模型开始随机二选一 |
| context clash | 上下文内部指令冲突 | AGENTS.md 与 SKILL.md 对同一问题给出不同做法 |
量化补充(C 级):2025 年研究显示"语义一致但无关的数据可使性能下降超过 45%";Chroma Research 2025-07 测试 18 个前沿模型,每一个都随上下文变长而退化。
工程推论:L1 层的建设重点不是"检索更多",而是"删掉更多"。第 4.4 节 Vercel 的减法实验(工具数 15 → 2,标 )与本节的"一次外部预演(rehearsal)"同理——减少供给常常比增加供给更有效。
4. L2 工具与执行层
4.1. 层的定位
L2 回答的问题是:模型能对环境施加哪些动作,这些动作在哪里执行。该层包含三类组件:
| 组件类别 | 作用 | 代表 |
|---|---|---|
| 工具注册与描述 | 把外部能力声明为模型可调用的结构化接口 | Function Calling、JSON Schema 工具描述 |
| 连接协议 | 让工具生态与宿主应用解耦 | MCP(Model Context Protocol) |
| 执行环境 | 限定动作的作用范围与副作用边界 | 沙箱(Seatbelt / bubblewrap + socat / Landlock + seccomp) |
4.2. MCP:第 2 层的连接标准
MCP 采用 Host / Client / Server 三角色架构(A 级):
| 角色 | 职责 | 说明 |
|---|---|---|
| Host | 顶层应用(IDE、聊天应用、多智能体编排框架) | 内含 Client |
| Client | 与每个 Server 保持 1:1 连接 | 负责协议协商与路由 |
| Server | 轻量级程序 | 暴露 Tools / Resources / Prompts |
传输方式:本地走 stdio,远程走 Streamable HTTP,消息基于 JSON-RPC 2.0。
Google 官方对 MCP 与 A2A 的分工作出了清晰界定(《A year of open collaboration》,2026-04-16,A 级):
"MCP manages internal tool integration, while A2A handles the vital external coordination between autonomous entities."
即:MCP 管内部工具接入,A2A 管智能体之间的外部协同。两者不是竞争关系,而是 Harness 内部不同方向的连接协议。
4.3. MCP 五版规范演进链
以下版本链为一手参数(MCP Ruby SDK Protocol Versions 页 + mcpkit docs.rs + Klu 词条,A 级),可全量引用:
| 版本 | 关键变更 |
|---|---|
| 2024-11-05 | 初始协议版本:stdio + HTTP+SSE;三原语 Tools / Resources / Prompts;Sampling、Roots、进度通知、日志、分页 |
| 2025-03-26 | Streamable HTTP 取代 HTTP+SSE;OAuth 2.1;工具注解(readOnly / destructive / idempotent);音频内容;Completions |
| 2025-06-18 | Elicitation;结构化工具输出;资源链接;保护资源元数据;_meta 字段;MCP-Protocol-Version 头变为必需;移除 JSON-RPC batching(破坏性变更) |
| 2025-11-25 | Tasks(异步状态跟踪);并行工具调用;服务端 agent 循环;sampling 中的工具调用 |
| 2026-07-28 | 协议核心无状态化(移除 initialize 握手与 Mcp-Session-Id,版本随每次请求在 _meta 携带);引入 Extensions 框架(Tasks、MCP Apps);强化授权;正式弃用策略(最短 12 个月窗口);在新版中弃用 Roots / Sampling / Logging |
从这条演进链可以读出第三代 Harness 在协议层的三个明确取向:
- 从有状态会话走向无状态请求——2026-07-28 移除握手与会话 ID,使远程 MCP server 可以像普通 Web 服务一样水平扩展;
- 从"够用就行"走向"可演进"——12 个月最短弃用窗口是标准化治理成熟的标志,意味着使用者可以安全地做依赖规划;
- 从"只有工具"走向"服务端也有 agent"——2025-11-25 的服务端 agent 循环把一部分 L3 职责下沉到了 L2 边界之内(服务端执行域)。
版本状态说明:Wikipedia 与部分来源称 "2024-11-05 初始发布 / 2024-11-25 公开宣布",与 MCP Ruby SDK 仅列
2024-11-05为 "Initial protocol revision" 存在差异,两者可并存表述。详见第 13 节。
4.4. 工具设计准则
Anthropic 官方文档给出了三条工具设计准则(A 级),可直接作为团队工具集评审的 checklist:
- 自包含、对错误健壮、用途极其明确;
- 避免功能过载与决策点含糊——一个工具做多件事会让模型在选择时犹豫,也会让失败原因难以归因;
- 少样本示例要"多样而典型",而非罗列边界情况。
与之呼应的是系统提示词的"正确海拔"(right altitude)原则:既不能写成脆弱的硬编码逻辑,也不能空泛到只剩高层指引,而应"足够具体以有效引导行为,又足够灵活以给模型留下强启发式的判断空间"。
4.5. 沙箱:Claude Code 的官方实现
Claude Code 沙箱是目前公开披露最完整的 Agent 沙箱设计(《Sandboxing: a safer and more autonomous approach》+ 官方文档,A 级)。以下参数可全量引用。
核心安全公理(A 级原文):文件系统隔离与网络隔离缺一不可——
- 无网络隔离,被攻陷的 agent 可以外传 SSH 密钥;
- 无文件系统隔离,被攻陷的 agent 可以轻易逃逸并获取网络访问。
平台实现与默认策略
| 项目 | 参数 |
|---|---|
| macOS 实现 | Seatbelt |
| Linux / WSL2 实现 | bubblewrap + socat(可选 seccomp 过滤器,经 npm install -g @anthropic-ai/sandbox-runtime) |
| 不支持 | 原生 Windows;WSL1 |
| 默认写入 | 沙箱内命令只能写当前工作目录与会话临时目录($TMPDIR 被设为该目录) |
| 默认读取 | 默认全机可读(除被显式拒绝的目录) |
| 网络出口 | 只能经 unix domain socket 连接沙箱外运行的代理服务器;新域名首次请求时提示批准 |
两种运行模式
| 模式 | 行为 |
|---|---|
| Auto-allow | 沙箱化命令自动批准,不逐条提示 |
| Regular permissions | 仍逐条提示 |
即使在自动允许模式下,deny 规则、针对 / 或主目录的 rm -rf 类命令、以及内容范围的 ask 规则仍然生效。
逃生舱与严格模式:提供 dangerouslyDisableSandbox 重试;可通过 allowUnsandboxedCommands: false 关闭,即 Strict sandbox mode。
凭据保护(需 Claude Code v2.1.187+):sandbox.credentials 可对文件(如 ~/.aws/credentials、~/.ssh)与环境变量(如 GITHUB_TOKEN、NPM_TOKEN)执行 deny;v2.1.199+ 支持 mode: "mask"。
流程级沙箱(@anthropic-ai/sandbox-runtime):把整个 Claude Code 进程(含内置工具、MCP server、hooks)包进同一层隔离;默认拒绝写 .git/hooks、.git/config、.mcp.json、.claude/commands、.claude/agents 与 shell 启动文件。
配置路径:.claude/settings.local.json(项目级)/ ~/.claude/settings.json(用户级)/ managed settings(组织级);sandbox.failIfUnavailable 可设为硬失败。
量化效果(A 级,本模块反复引用的核心数字):Anthropic 内部使用发现,沙箱化安全地将权限提示减少了 84%。
4.6. 沙箱实现横向对比
| 维度 | Claude Code | Codex CLI |
|---|---|---|
| macOS 原语 | Seatbelt | sandbox-exec(Seatbelt) |
| Linux 原语 | bubblewrap + socat(+ 可选 seccomp) | Landlock + seccomp |
| Windows 原语 | 不支持原生 Windows / WSL1 | job objects |
| 默认网络 | 经代理 unix socket,新域名需批准 | 默认禁用网络 |
| 默认写入 | 当前工作目录 + 会话临时目录 | 限定当前目录 |
| 批准档位 | Auto-allow / Regular permissions | Suggest / Auto-edit / Full-auto |
| 来源等级 | A | B(AI Wiki 转述,具体参数标 ) |
补充(B 级):Codex CLI 在 2025 下半年从 Node.js 重写为 Rust,至 2026 年初代码库约 95% 为 Rust;官方理由为静态单文件分发、无 GC、内存占用低、可直接调用 OS 沙箱原语。2026-04 新增 Auto-review 模式,内部会话为人类审批而停止的次数约为手动模式的 1/200,审阅者批准率约 99%。
4.7. 设计权衡
| 权衡 | 两端 | 本节立场 |
|---|---|---|
| 沙箱强度 vs 可用性 | 强隔离(安全但常需 escape hatch) vs 弱隔离(好用但风险外溢) | 官方给出的解法是隔离要成对(文件系统 + 网络),而非"尽量强" |
| 工具数量 vs 准确率 | 工具越多能力越广 vs 工具越多选择越难 | 减法优先。Vercel 把工具数从 15 削减到 2,准确率 80% → 100%,Token −37%,速度 3.5×(C 级) |
| 原生插件 vs 标准协议 | 性能好但锁定 vs 解耦但有余开销 | 第三代普遍选 MCP 路线;偏离需有明确理由 |
4.8. 失败模式
| 失败模式 | 表现 | 对策 |
|---|---|---|
| 工具语义重叠 | 两个工具描述相近,模型随机选择且不可复现 | 工具评审时做"两两可区分性"检查 |
| 沙箱逃逸以逃生舱名义常态化 | dangerouslyDisableSandbox 被频繁使用,隔离形同虚设 | 关闭逃生舱(Strict sandbox mode),把例外改为显式审批 |
| 凭据随环境变量泄漏 | 子进程继承 GITHUB_TOKEN 等 | 使用 sandbox.credentials 显式 deny / mask |
| 网络出口失控 | agent 通过任意 DNS 外传数据 | 强制代理 + 新域名批准 + 出口白名单 |
| 过度工具化 | 工具数膨胀导致准确率与成本双输 | 定期做工具减法,把低频工具降级为 Skill(脚本) |
5. L3 编排与控制层
5.1. 层的定位
L3 回答的问题是:按什么顺序做,谁来做什么,中断后怎么恢复。主要编排形态及其适用:
| 形态 | 适用 | 代表 |
|---|---|---|
| 单循环(Agent Loop) | 通用任务,模型自主决策下一步 | ReAct 循环、Claude Code 主循环 |
| 计划-执行(Plan-and-Execute) | 长周期、需要全局规划的任务 | Claude Code Plan Mode、三 Agent 架构 |
| 有向无环图 / 工作流 | 确定性要求高的业务流程 | DAG / Workflow 引擎、Google ADK SequentialAgent |
| 子智能体派发 | 可并行探索的复杂研究任务 | Sub-agent 架构、多 agent 研究系统 |
5.2. Agent Loop 与长时运行的双 Agent 架构
Anthropic《Effective harnesses for long-running agents》(A 级)披露了长时运行任务的第一代官方解法:Initializer Agent + Coding Agent 的双 Agent 分工。
Initializer Agent 的产物(交接包)
| 产物 | 用途 |
|---|---|
init.sh | 环境启动脚本,保证每个新会话能一键拉起可运行环境 |
claude-progress.txt | 进度文件,跨会话传递"做到哪了" |
| 初始 git commit | 提供回滚基点 |
| JSON 功能清单 | 带 passes 布尔字段的功能清单,作为任务的总账本 |
该代架构立下的一条硬规矩是:移除或修改测试是不可接受的。
Coding Agent 的会话开场三步(官方规定,A 级)
- 执行
pwd确认当前工作目录; - 读取 git 日志与进度文件;
- 读取功能清单,选出最高优先级的未完成项。
会话结束约束:必须把环境留在可合并的干净状态。
5.3. Plan-and-Execute 与三 Agent 架构
Anthropic《Harness design for long-running application development》(2026,A 级)披露了第二代官方解法:Planner / Generator / Evaluator 三角色,其设计灵感明确来自生成对抗网络(GAN)。
| 角色 | 职责 | 官方细节 |
|---|---|---|
| Planner | 把 1~4 句高层提示转成完整产品规格 | 刻意停留在高层,不介入实现细节 |
| Generator | 每个 sprint 实现一个功能,先自评再交给 Evaluator | 受 Sprint Contract 约束 |
| Evaluator | 对产品深度、功能性、视觉设计、代码质量四项评分 | 每项有硬阈值,任一项低于阈值则该迭代失败,并向 Generator 返回详细失败原因 |
三个关键机制
- Sprint Contract(冲刺契约):编码前 Generator 提出"要构建什么 + 如何验证成功",Evaluator 审查并达成共识。在开始之前先就"完成"的定义达成一致——这是该层最重要的过程设计。
- self-evaluation bias(自卖自夸):官方观察到 agent 自评会"自信地称赞"自己在人类眼中明显平庸的作品。这正是分离 Evaluator 的根本理由(详见 7.2 节)。
- context anxiety(上下文焦虑):agent 在上下文接近上限时会倾向于仓促收尾、提前宣布完成。
未决问题(官方自陈,A 级):Anthropic 明确表示,"单个通用编码代理是否总是最优,还是拆成测试、QA、清理等专职代理的多代理架构更好——目前尚不清楚"。
5.4. Sub-agent 派发
多 agent 研究系统(Anthropic《How we built our multi-agent research system》,2025,A 级项目、URL )给出了官方的派发模式:
- 主 agent 持有高层计划,负责协调;
- 子 agent 在干净上下文窗口内做深度技术工作或信息检索;
- 子 agent 只回传 1,000~2,000 tokens 摘要(与 3.5 节同源参数);
- 在复杂研究任务上显著优于单 agent。
与内核级 variability(不确定性)的取舍是:并行度换摘要损耗。
5.5. 状态机与确定性工作流
Google ADK(2025-04-09 发布,Apache 2.0,Python 首发,v1.0.0 于 2025-05-20,A 级)提供了另一条路线:把编排做成可声明的原语。
| 原语类别 | 内容 |
|---|---|
| Agent | 编排主体 |
| Tools | 可执行动作 |
| Sessions | 会话状态 |
| Runners | 执行驱动器 |
ADK 的一个重要特征是确定性与动态性并存:
- 确定性工作流 agent:
SequentialAgent/ParallelAgent/LoopAgent; - LLM 驱动的动态路由:
LlmAgent的 transfer 机制。
ADK 还内置了 evaluation harness(AgentEvaluator.evaluate()),可对最终响应与逐步轨迹双重评分,并通过 LangchainTool / CrewaiTool 适配器消费第三方框架工具,支持 MCP、A2A、OpenAPI。
5.6. 中断与恢复
社区与官方均有"让 agent 持续迭代"的同构实践。Anthropic 工程博客提到通过 hooks 或脚本让 agent 持续迭代的方法;社区实践(如 Ralph Wiggum Loop,B 级)的做法是:
通过 hook 拦截模型的退出尝试,在干净上下文窗口中重新注入原始提示词,迫使 agent 围绕完成目标继续工作。
该方法成立的前提是文件系统:每次迭代从新鲜上下文开始,但读取上一次留下的状态。这与 5.2 节的双 Agent 架构在本质上是同一套"外部状态 + 干净上下文"思想,区别只在于 driver 是另一个 agent 还是一个 hook。
5.7. 设计权衡
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 单 Agent vs 多 Agent | 上下文连贯 vs 并行与干净窗口 | Anthropic 官方自陈"尚不清楚",建议按任务做 A/B |
| 规划粒度 | Planner 给足细节(执行稳但僵化) vs 刻意停留高层(灵活但可能偏) | 官方选择:Planner 刻意停留高层 |
| 确定性 vs 灵活性 | 状态机可复现 vs LLM 路由适应性强 | 业务流程选前者,探索任务选后者;ADK 的答案是两者并存 |
| 成本 vs 质量 | 多 Agent 明显更贵 | 对比实验显示(C 级):单 Agent 20 分钟 / $9 / 产出不可用;三 Agent 6 小时 / $200 / 产出完整可玩 |
5.8. 失败模式
| 失败模式 | 表现 | 对策 |
|---|---|---|
| 无限循环 | 同一动作重复执行无进展 | 迭代上限 + 反漂移检测(重复编辑同一文件时告警) |
| 目标漂移 | 逐步偏离原始目标 | Sprint Contract + 周期性重注入原始目标 |
| 提前宣布完成 | context anxiety 下仓促收尾 | 强制清单式自我验证后才允许输出"完成"(见 7.5 节 LangChain 第一条改动) |
| 环境脏状态 | 上一轮留下未清理的半成品 | 官方硬规矩:结束前必须回到可合并的干净状态 |
| 测试被修改以通过 | 为满足"完成"而篡改判据 | 官方硬规矩:移除或修改测试不可接受 |
6. L4 记忆与状态层
6.1. 层的定位
L4 回答的问题是:跨会话、跨上下文窗口时,状态如何交接。
Anthropic 官方对这一难题的表述极为形象(A 级):
想象一个由工程师轮班工作的软件项目,每位新工程师上班时,对前一班发生的事情毫无记忆。
这句话也解释了为什么 L4 在第三代才成为独立关注点:第一、二代的任务时长还在单个上下文窗口内,问题根本不会出现。
6.2. 跨上下文窗口的状态交接
官方(A 级)的完整交接方案:
| 交接载体 | 承载内容 | 特点 |
|---|---|---|
claude-progress.txt | 自然语言进度记录 | 可读、可被模型理解 |
| git 历史 | 结构化变更记录 | 可回滚、可 diff |
JSON 功能清单(含 passes) | 任务总账本 | 机器可判定的完成度 |
| 初始 git commit | 回滚基点 | 保证每轮可回到已知健康状态 |
健康度检查(官方规定):Coding Agent 在动手实现新功能之前,必须先跑一遍端到端测试确认环境健康。官方给出的理由是模型"倾向于在没有充分测试的情况下就宣布功能完成"。
人工级验证(官方建议):给 agent 配备浏览器自动化工具(如 Playwright MCP),让它像真人一样验证产物——官方明确表示这显著提升了表现。
6.3. Compaction 与 Context Reset 的分工
两者常被混为一谈,官方(A 级)明确区分:
| 机制 | 做法 | 优点 | 代价 |
|---|---|---|---|
| Compaction | 就地摘要压缩 | 保留连续性 | context anxiety(上下文焦虑)仍在 |
| Context Reset | 清空上下文后重新注入 | 给干净白板 | 交接产物必须足够完整,否则等于失忆 |
可以这样理解二者关系:Compaction 是治标(延缓腐烂),Reset 是治本(彻底清创),但 Reset 的成本转移到 L4 层的交接质量上。
6.4. 检查点与工件
第三代 Harness 的一个显著特征是:把 Git 当作状态与记忆的载体,而不是另起一套记忆数据库。这一选择的好处是继承了人类工程团队已有的全部工具(diff、blame、revert、CI),代价是需要额外约定提交粒度与分支策略。
Anthropic 官方的做法是把"票据 + 日志 + 代码"三件东西放在一起:claude-progress.txt(日志)+ 功能清单(票据)+ git(代码 + 版本)。
6.5. 设计权衡
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 自然语言 vs 结构化状态 | claude-progress.txt 灵活但不可机判 vs JSON 清单可机判但僵化 | 官方选择:两者都要 |
| 保留 vs 重置 | 连续性好 vs 干净 | 长任务建议周期性 Reset + 高质量交接包 |
| 专用记忆库 vs Git | 语义检索强 vs 工具生态成熟 | 第三代普遍取 Git 优先,专用记忆作为补充 |
6.6. 失败模式
| 失败模式 | 表现 | 对策 |
|---|---|---|
| 失忆重启 | 每个新会话重复已完成的工作 | 强制开场三步:pwd → 读日志与进度文件 → 读清单选最高优先级未完成项 |
| 进度文件腐烂 | claude-progress.txt 与实际 git 状态不符 | 把 git 历史作为唯一事实源,进度文件只做摘要 |
| 脏交接 | 上一轮留下半成品/失败测试 | 结束前必须回到可合并的干净状态;下一轮开场跑端到端健康测试 |
| 检查点粒度失控 | 提交过粗(无法回滚)或过细(噪声) | 显式约定提交粒度与分支策略 |
7. L5 评估与观测层
7.1. 层的定位
L5 回答的问题是:做得好不好,如何判定,如何回归。
这一层在第三代获得了最高的地位提升——原因可以用一句官方判断概括(Anthropic,A 级):
"Harness design is key to performance at the frontier of agentic coding."
而评估层正是 Harness 里唯一能回答"这次改 Harness 到底有没有用"的部分。没有 L5,Harness 工程就无法形成闭环,只能靠直觉调参。
7.2. 第一原则:评估者与被评估者分离
Anthropic 官方(A 级)观察到的现象是 L5 层最重要的设计依据:
让 agent 评估自己的作品时,它会"自信地称赞"——即便人类观察者眼中质量明显平庸。这在无二值判据的主观任务(如设计)上尤其突出。
官方给出的理由与灵感来源值得完整引用:
把一个独立的 Evaluator 调教得怀疑,远比让 Generator 自我批判容易得多。(灵感来自 GAN)
实现方式:Evaluator 对产品深度、功能性、视觉设计、代码质量四个维度分别设定硬阈值,任一项低于阈值则该迭代失败,并把详细失败原因反馈给 Generator。
迁移建议:这条原则对非编码场景同样成立。做任何主观质量类 agent 任务时,都应设置一个与生成方隔离的判定方,无论它是一条规则、一个脚本,还是另一个模型。
7.3. 外部基准与内置评估闭环
L5 层有两个互不可替的组成部分:
| 组成 | 作用 | 代表 |
|---|---|---|
| 外部基准 | 跨系统横向对比,判断"在行业中排第几" | SWE-bench / SWE-bench Verified、Terminal-Bench |
| 内置评估闭环 | 自家任务的回归与 CI,判断"这次改动是否变差" | Eval Set、Golden Dataset、Trace 分析、Google ADK AgentEvaluator |
两者的关系是不可替代的:外部基准防止自嗨(你可以让自家 eval 全绿却毫无竞争力),内置闭环防止退化(外部基准一年跑不了几次,且不能覆盖私有业务)。
SWE-bench(2023-10-10,2,294 个任务实例、12 个 Python 开源仓库,ICLR 2024 Oral,A 级)确立的原则是程序化判分:测试通过即通过,"no partial credit for nice-looking code that fails the tests"。Terminal-Bench 的原则同样是 "either the automated tests pass or they do not"。
7.4. 可观测性对 Agent 开放
OpenAI 在《Harness engineering》(2026-02-11,A 级)中给出一个极具启发性的 L5 实践:把可观测性栈对 agent 本身开放。
| 措施 | 细节 |
|---|---|
| 按 worktree 启动 | 应用可按 git worktree 独立启动,agent 可获得自己的运行时实例 |
| 浏览器调试协议 | Chrome DevTools Protocol 接入 agent 运行时 |
| 指标与日志暴露 | 经本地可观测栈暴露,agent 可用 LogQL 与 PromQL 直接查询 |
| 示例提示词 | "确保服务启动在 800ms 内完成"——把性能要求变成可测量的验收条件 |
这一做法的工程意义是:把 L5 的观测能力反向供给 L1 作为上下文。agent 不再是盲写的黑盒,它可以像工程师一样去看日志、查指标、验证自己的改动是否达标。
7.5. scaffold 效应:Harness 差异的量化
最能说明 L5 价值的证据,是"同一模型、不同 Harness、分数不同"这一现象的量化数据。
Terminal-Bench(Stanford + Laude Institute,2025 发布,A 级项目)在其方法论中直接写明:
"Terminal-Bench does not score a model in isolation. Every result is a model plus an agent harness... the leaderboard is a ranking of systems, not of models."
其 v2.0(2025 年末至 2026 年初发布,89 题,迁移到 Harbor 框架,A 级项目 / 具体数字标 )每道题由 3 名独立人工评审;难度从 easy 到 hard 的准确率从约 65% 降至约 16%,跨档下降约 49%(B 级)。
以下对照数据全部为 B/C 级来源,一律标 ,仅作方向性参考:
| 对照项 | 数据 | 说明 |
|---|---|---|
| Factory Droid + GPT-5.3-Codex | 77.3% | 与下一行同为 GPT-5.3-Codex |
| OpenAI Simple Codex + GPT-5.3-Codex | 75.1% | 2.2 个百分点纯由 scaffold 差异造成 |
| KRAFTON Terminus-KIRA + Claude Opus 4.6 | 74.7% | 与下一行同为 Claude Opus 4.6 |
| Bigai TongAgents + Claude Opus 4.6 | 71.9% | 相差 2.8 个百分点 |
| LangChain 仅改 Harness(同模型、同 API) | 52.8% → 66.5% | 排名从 30 名外跃升至前 5 |
LangChain 那次 "52.8% → 66.5%" 的五项改动清单是全篇最具迁移价值的内容之一(C 级, 数字,但改动项本身有工程参考价值):
- 强制清单式自我验证后才允许说"完成";
- 启动前扫描目录结构并注入环境上下文;
- 反漂移检测——重复编辑同一文件时告警;
- 调整推理预算——规划验证多想、实现少想;
- 自动失败模式分析。
这五项全部不涉及换模型,全部属于 Harness 工程。它们可以直接移植到其他场景。
7.6. 设计权衡
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 主观评分 vs 二值判据 | 覆盖主观任务 vs 客观可复现 | 优先把主观任务"翻译"成可二值判定的子项;实在无法二值化的才用 Evaluator 评分 + 硬阈值 |
| 评估频率 vs 成本 | 每步评(贵但反馈及时) vs 终局评(省但归因难) | 建议:短链路终局评,长链路分 sprint 评(Sprint Contract 即为此设计) |
| 覆盖率 vs 维护成本 | 评估集越大越准 vs 越难维护 | 与其铺量不如做"每次真实失败都补一条回归 case" |
7.7. 失败模式
| 失败模式 | 表现 | 对策 |
|---|---|---|
| 自卖自夸(self-evaluation bias) | 自评全绿、人工看不合格 | 评估者与被评估者分离 |
| 评估集过拟合 | agent 学会了"对付" eval 而非真正做好 | 定期轮换评估集;保留一份 agent 不可见的 held-out 集 |
| 只看终局分 | 知道变差了但不知道哪里变差 | 轨迹级 tracing(如 Responses API 内置 tracing、ADK 逐步轨迹评分) |
| 指标与业务脱节 | benchmark 涨了但用户没感觉 | 建立自己的 Golden Dataset 而非只追公开榜 |
8. L6 治理与安全层
8.1. 层的定位
L6 回答的问题是:什么不能做,做了怎么发现,花多少钱上限是多少。它包含权限模型(RBAC)、护栏模型、审计日志与预算护栏(Budget Guardrail)四类组件,并作为横向切面对 L1~L5 全部施加约束。
必须澄清的常见误解:治理会拖慢速度。 Anthropic 沙箱实证给出了相反结论——权限提示减少 84% 且安全性提升(A 级)。约束不是自主性的对立面,而是自主性的前提。
8.2. 权限模型与沙箱策略
治理策略的分层配置(以 Claude Code 为例,A 级):
| 层级 | 配置位置 | 用途 |
|---|---|---|
| 项目级 | .claude/settings.local.json | 随仓库分发,团队共用 |
| 用户级 | ~/.claude/settings.json | 个人偏好 |
| 组织级 | managed settings | 强制下发,个人不可覆盖 |
关键开关包括 sandbox.enabled、sandbox.failIfUnavailable、allowUnsandboxedCommands、filesystem.allowWrite / denyWrite / denyRead / allowRead。其中 sandbox.failIfUnavailable 可设为硬失败——沙箱起不来就拒绝运行,而不是悄悄降级到非沙箱模式。这是治理健壮性的一条重要经验:不要让安全机制有静默降级路径。
8.3. 凭据保护
sandbox.credentials 提供文件与环境变量两个维度的保护(需 v2.1.187+;v2.1.199+ 支持 mode: "mask"):
| 模式 | 行为 | 适用 |
|---|---|---|
deny | 完全不可见 | ~/.aws/credentials、~/.ssh |
mask | 掩码显示 | 必须存在但不应被读取值的 token |
建议纳入默认 deny 清单:~/.aws/credentials、~/.ssh/*、GITHUB_TOKEN、NPM_TOKEN 及各类云厂商环境变量。
8.4. 架构约束的机械强制
OpenAI 在《Harness engineering》(2026-02-11,A 级)中给出的环境治理实践,是 L6 层最系统的官方案例。
分层依赖规则(单向依赖):每个业务域内代码只能"向前"依赖——
Types → Config → Repo → Service → Runtime → UI 横切关注点只能经 Providers 单一接口进入。该规则被机械强制,而非靠 code review 口头约定。
品味不变量(Taste Invariants):通过自定义 linter 静态强制结构化日志、schema 与类型命名约定、文件大小限制、平台特定可靠性要求。
其中最关键的工程技巧是:因为 linter 是自研的,错误消息被写成向 agent 上下文注入修复指令。也就是说,linter 不只是"报错",而是"报错 + 教 agent 怎么改"。这把 L6 的失败信号直接转化为 L1 的上下文输入,形成闭环。
官方对此的总结可以直接引用:
在人类优先的工作流中,这些规则可能令人觉得迂腐;有了 agent,它们成为倍增器——一旦编码,立即处处生效。
治理哲学被类比为"领导大型工程平台组织:中心强制边界,局部允许自治"。
8.5. 垃圾回收:对抗熵增
OpenAI 把 Harness 工程的第三支柱命名为 Garbage Collection(垃圾回收),对抗的是 agent 大规模产出后的熵增问题。Anthropic 也明确把"上下文还是会腐烂"列为第三条支柱需要处理的议题。
具体机制(A 级):
doc-gardeningagent:定期扫描过时文档并自动发起修复 PR;- 四大失败模式(官方归纳):① 上下文是稀缺资源;② 过多指导变成无指导;③ 立即腐烂(rot immediately);④ 难以机械验证。
其中"过多指导变成无指导"尤其值得注意:当 AGENTS.md 写得太长,agent 会像人一样跳过阅读。这直接推出第 10.2 节的 "AGENTS.md 从百科全书改为目录"决策。
8.6. 设计权衡
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 硬失败 vs 静默降级 | 可用性 vs 安全确定性 | 治理机制应避免静默降级(sandbox.failIfUnavailable 硬失败) |
| 中心强制 vs 局部自治 | 一致性 vs 灵活性 | 官方答案:中心强制边界,局部允许自治 |
| 规则数量 vs 遵从度 | 规则越全越好 vs 太多则被忽略 | 官方答案:规则要少而可机械强制;过多文档等于无文档 |
8.7. 失败模式
| 失败模式 | 表现 | 对策 |
|---|---|---|
| 权限疲劳 | 频繁提示导致用户一律点同意 | 沙箱化 + Auto-allow(官方数据:−84% 提示) |
| 文档腐烂 | AGENTS.md / docs 与实际代码脱节 | doc-gardening agent + 把文档纳入 CI 校验 |
| 规则不可机检 | 只能靠 review 口头约定 | 自研 linter,错误消息写成修复指令 |
| 审计不可追溯 | 出事后查不出是哪个 agent 干的 | 全层 tracing + 结构化日志(作为品味不变量强制) |
| 预算失控 | 长任务成本不可预期 | Budget Guardrail + 单步/单任务成本上限 |
9. Harness Loop:主循环的工程结构
9.1. 定义与定位:Loop 是 Harness 的心脏
前三章逐层拆解了六层各自的组件与权衡,本章把它们装配回运行时的整体形态:Harness Loop(基于 Harness 的智能体主循环)。统一定义沿用本库参数卡,不得改写:
Harness Loop:由 Harness 承载的智能体主循环——智能体在 Harness 提供的运行时内按「目标装配(L1)→ 计划(L3)→ 工具执行(L2)→ 观测反馈(L5)→ 状态更新(L4)→ 再计划」迭代,直到满足终止条件或触发治理边界(L6)。
Anthropic 与 OpenAI 两家头部厂商的三条官方表述与该定义高度一致(A 级):
| 厂商 | 官方表述 | 来源 |
|---|---|---|
| Anthropic | gather context → take action → verify work → repeat(收集上下文 → 行动 → 验证 → 重复) | 《Building agents with the Claude Agent SDK》,2025 |
| Anthropic(Claude Code 团队) | "循环 = 智能体重复执行工作周期,直到满足停止条件" | 《Loop engineering: Getting started with loops》,2026-06-30 |
| OpenAI | "可复用的部分就是 agent loop";harness = 围绕模型的执行系统(理解任务、维持上下文、检查信息、调用工具、暴露进度、处理失败、请求人工批准、返回结果) | 《Codex as a platform》,2026 |
本章的核心命题是:Loop 是 Harness 的心脏,不是 Agent 的属性。脱离 Harness 的裸循环(裸 ReAct)只有 L2 工具执行;Harness Loop 的特征是每一圈都被 L1 装配、被 L5 观测、被 L4 记账、被 L6 约束。这一对应关系如图 9-1 所示。
图 9-1|Harness Loop 单圈结构与六层模型对应
示意图:基于本文分析,机制依据三家官方循环描述(A 级,信息截止 2026-09-12)。
9.2. 单圈结构:三家官方实现的同构性
无论 Claude Code、Codex 还是 Gemini CLI,单圈(一个 turn)都是同一结构:上下文装配 → 模型推理 → 工具调用 → 结果校验回流。这是"Loop 是 Harness 的心脏"在工程上的直接体现——心脏的跳动方式是同构的,差异只在瓣膜(确认门、审批门)与循环的出口条件。
Anthropic Claude Agent SDK 的官方五步定义(《How the agent loop works》,A 级):
- 接收 prompt(含系统提示、工具定义、会话历史);
- Claude 评估并响应(文本或工具调用);
- SDK 执行工具并收集结果;
- 步骤 2~3 重复,每完成一次完整周期为一个 turn;
- 输出不含工具调用的最终响应与 ResultMessage(含 token 用量、成本、session ID)。
循环终止判据 = 产出不含工具调用的响应。
OpenAI Codex 的官方循环描述(《Unrolling the Codex agent loop》,A 级):用户输入 → 组装 prompt → 推理 → 模型要么产出最终 assistant message(循环终止信号),要么请求工具调用 → Agent 执行工具并把输出追加进 prompt → 重新查询。一次 turn 可含多轮"推理—工具"迭代;官方明确指出上下文窗口管理是 agent(harness)的职责之一——这正是 L1 被写进循环的证据。
Gemini CLI 的 ReAct 循环(B 级,官方仓库文档与多源一致):cli 发起推理 → 模型返回 ToolCallRequest → CoreToolScheduler 四步(排队 / 验证 / 确认 / 执行,敏感操作经确认门挂起等用户 UI 确认)→ 工具结果经回调链打包回模型 → 新一轮推理。循环终止:模型调用显式的 complete_task 工具,或触发超时 / 错误等终止条件。
同构中的差异点(B 级社区源码级拆解):
| 实现 | 循环出口 | 圈内保护机制 |
|---|---|---|
| Claude Code / Agent SDK | 无工具调用响应;max_turns / max_budget_usd 硬上限 | 退出前恢复路径:上下文折叠 → 响应式压缩 → 加倍输出预算重试,全部失败才真正退出 |
| Codex harness | assistant message;审批门与沙箱边界 | turn 内多轮推理—工具迭代;retained reasoning + 上下文压缩 |
| Gemini CLI | complete_task 显式终止 | CoreToolScheduler 确认门(会话内白名单免重复确认);1M token 长上下文 |
9.3. 跨圈机制:五类控制流
单圈之上,Harness Loop 依赖五类跨圈机制维持长任务的可持续性(依据 Anthropic 官方工程博客与各框架文档,标注见行内):
| 机制 | 做法 | 指向 | 证据等级 |
|---|---|---|---|
| Compaction(压缩) | 接近上下文上限时自动摘要历史消息;Agent SDK 以 compact_boundary 消息类型显式标记压缩边界 | 指回 L1 | A |
| Context Reset(上下文重置) | 清空上下文、更换新 Agent,靠结构化交接物续跑;官方用它治理"上下文焦虑"与自我评估偏差——区别于 Compaction 的就地摘要 | 指回 L1 | A |
| 计划修订 | 主 Agent 汇总子代理结果后决定追加派发或修订策略;Claude Code 支持任务中途注入指令实时改向 | 指回 L3 | A(改向机制细节为社区逆向,B) |
| 子智能体派发 | 并行 + 独立上下文窗口,只回传浓缩摘要;官方给出按任务复杂度分级的努力缩放规则:简单事实 1 个代理 3~10 次工具调用,对比类 2~4 个子代理各 10~15 次,复杂研究 10 个以上子代理 | 旁路子环 | A |
| 检查点持久化 | 进度文件 + git 历史 + 功能清单跨会话交接;MAF Workflow 原生 checkpointing;LangGraph Checkpointer 每 superstep 落盘 | 指回 L4 | A / B |
两个关键机制在 Anthropic《Harness design for long-running application development》(2026,A 级)中被制度化:Sprint Contract——编码前 Generator 与 Evaluator 协商"完成"的定义,使每一圈的观测校验(L5)有据可依;Context Reset——用"清空 + 交接"替代"摘要 + 续跑",代价转移到 L4 的交接质量(两机制的详细分工见 6.3 节)。
跨圈机制的量化收益有官方硬数据支撑:OpenAI《Codex as a platform》(2026,A 级)披露,在 ARC-AGI-3 基准上,保留推理(retained reasoning)+ 上下文压缩使 GPT-5.6 Sol 得分从 13.3% 提升至 38.3%,同时输出 token 减少 6 倍——这是"harness 设计直接改变结果"的最有力官方数字(信息截止 2026-09-12)。
跨圈控制流与终止条件分级的整体形态如图 9-2 所示。
图 9-2|跨圈控制流与终止条件分级
示意图:基于本文分析,终止条件口径沿用本库参数卡统一分级(信息截止 2026-09-12)。
9.4. 终止条件分级与三重硬限
"循环什么时候停"不是实现细节,而是 Harness 的核心契约。统一口径把终止条件分为五级(与图 9-2 对应):
| 级别 | 终止条件 | 官方机制 | 证据等级 |
|---|---|---|---|
| ① | 任务完成判定(DoD 校验) | 无工具调用的最终响应(Anthropic / OpenAI);complete_task 工具(Gemini CLI);/goal 由独立评估模型校验可验证完成标准,未达标打回继续 | A / B |
| ② | 预算耗尽 | Anthropic SDK 的 max_budget_usd 费用阈值;dynamic workflows 可显式设定 token 预算(如 "use 10k tokens");业界实践为每任务美元上限 | A / B |
| ③ | 权限边界触发 | Claude Code hooks 可在工具执行前拦截、修改或阻止调用;Codex 审批档位(untrusted / on-request / never)× 沙箱档位(read-only / workspace-write / danger-full-access);OpenAI Agents SDK 的 guardrail tripwire 触发即抛异常终止 | A |
| ④ | 人工中断(HITL) | LangGraph 的 interrupt_before 挂起等人工续跑(配合 Checkpointer 可恢复);Gemini CLI 的 shouldConfirmExecute 确认门;OpenAI Agents SDK 的 RunState 支持恢复被中断的运行 | A / B |
| ⑤ | 死循环检测 / 到期 | max_turns 超限抛 MaxTurnsExceeded(OpenAI SDK);LangGraph recursion_limit 默认 25,超限抛 GraphRecursionError——官方论坛将其定位为"熔断器而非业务逻辑";Claude Code 的 /loop 周期任务 7 天自动到期 | A / B |
分级之外,业界实践沉淀出一套三重硬限经验值(C 级,业界实践汇总,仅作方向性参考):
| 硬限 | 经验值 | 对接的失败形态 |
|---|---|---|
| 迭代上限 | 简单问答 10 / 研究型 25 / 编码型 50~100,按 p95 合法任务的 2~10 倍设定 | 无限循环 |
| token 预算 | 合法任务均值的 10 倍;预算消耗 80% 即告警而非耗尽才告警 | 成本风暴 |
| 墙钟超时 | p95 的 2~3 倍;token 生成速度降至基线 1/3 时告警 | 进程僵死 |
三重硬限各接不同失败形态,缺一不可;超限时应返回部分结果(进度摘要)而非裸错误。另有一条结构性结论(业界实践,C 级):kill switch 必须置于网关层并带唯一 ID——逃逸的 agent 不会遵守自己代码里的限额。
9.5. 框架循环语义对比
通用 Harness 之外,各框架的循环语义存在一条清晰的谱系:从"结构决定何时停"(可视化平台的有界循环)到"模型决定何时停 + 治理兜底"(编码 Agent 的自主循环)。
| 实现 | 循环载体 | 停止语义 | 跨圈持久化 | 归属层级 |
|---|---|---|---|---|
| Claude Code / Agent SDK | 单主循环 + 子代理 | 无工具调用响应 / max_turns / 预算 / hooks 拦截 | Compaction + 会话与进度文件 | L1~L6 全环 |
| Codex harness | agent loop(core 运行时) | assistant message / 审批门 / 沙箱边界 | 线程持久化 + retained reasoning | L1~L6 全环 |
| Gemini CLI | cli 驱动 + core 执行的 ReAct 循环 | complete_task / 确认门 | 会话历史 | L2 / L3 为主 |
| OpenAI Agents SDK | Runner 循环 | final_output / max_turns / guardrail tripwire | RunState / Session | L3 为主 |
| LangGraph | 显式状态机图循环(节点 + 条件边) | 条件边到 END / recursion_limit(默认 25) | Checkpointer 按 thread_id 每步落盘,可从检查点恢复 | L3 / L4 |
| AutoGen / MAF | 会话消息循环 → 类型化图工作流 | 终止条件 / max_turns / 条件退出边 | MAF checkpointing / AgentThread | L3 / L4 |
| Dify | Iteration / Loop 两种节点 | 数组长度(Iteration)或 loop_count + break_conditions(Loop) | 变量池快照 / loop_variables 跨轮继承 | L3 |
| n8n / Coze | 可视化循环节点 | 有界迭代(结构性边界,非 LLM 停止条件) | 节点间变量 | L3 |
三个值得展开的语义差异(来源等级见表内标注):
- LangGraph:超限不是死亡,而是可恢复的暂停(B 级,源码佐证)。recursion_limit 触发的 GraphRecursionError 配合 Checkpointer,可从最后落盘状态恢复或提高预算续跑——"熔断器而非业务逻辑"。
- AutoGen → MAF:从隐式消息循环到显式图循环(B 级)。AutoGen 的 GroupChat 因 LLM 选人导致循环不可预测、终止条件含糊时可无限循环,这是"隐式消息循环 → 显式类型化图"演进的直接动因;MAF 的 Workflow 提供类型化循环步骤、checkpointing、HITL 与中间件管线(含 token 预算强制)。社区对比数据显示 MAF 显式转换较 GroupChat 减少 23% LLM 调用(B 级第三方转述)。
- Dify:迭代由数据决定、循环由条件决定(B 级,源码级文档)。Iteration 节点遍历数组、每元素物化独立子引擎,并行度默认 10、单节点最大迭代默认 100,错误处理三档(TERMINATED / CONTINUE_ON_ERROR / REMOVE_ABNORMAL_OUTPUT);Loop 节点由 loop_count 最大次数 + break_conditions 停止条件 + 跨轮继承的 loop_variables 构成。可视化平台把"LLM 决定何时停"替换为结构性有界循环的代表样本;n8n / Coze 的循环节点属同一模式(其官方一手循环文档未直接获取,见 13 节缺口声明)。
9.6. 失败模式与治理
官方命名的循环失败模式(Anthropic 工程博客,A 级):一次性做太多(one-shot)、过早宣告完成(premature completion)、上下文焦虑(context anxiety)、自我评估偏差(自卖自夸),以及早期多代理系统的"50 个子代理 + 对不存在的来源无限搜索 + 互相刷进度"。上述多数失败模式已在 5.8 节从 L3 视角展开,本节聚焦循环整体失控这一特有形态。
代表性事故:多代理乒乓失控(B 级,来源标注 verified: partial——多帖一致但未见具名受害企业,仅作代表性案例参考):业界流传的事故复盘记录了一例四代理市场调研管线(LangChain + A2A)的失控:Analyzer 与 Verifier 两个代理陷入"产出—挑刺—修改"的乒乓循环,因无共享预算、无往返计数,周 API 花费从 $127 依次涨至 $891、$6,240、$18,400,264 小时后在 $47,000 处被手动关停。复盘根因有两条:无每代理预算上限;无可在下一次 API 调用前终止会话的机制。共性教训是:做调用决策的一方,看不见下一次调用的成本。
应用层限流的三种失效(业界实践,C 级):①框架旁路——代码直接调 LLM API 绕过框架限制;②异常吞噬——MaxIterationsExceeded 被 except 静默吞掉后继续循环;③进程重启重置计数器——崩溃重启后循环跨生命周期累积成本。由此得出的结论与 8.5 节 sandbox.failIfUnavailable 硬失败一脉相承:硬边界应在基础设施层(网关 / 代理),而非 agent 自身代码。
循环遥测:Codex 原生支持 OpenTelemetry 日志导出(A 级),导出事件包括用户 prompt、审批决定、工具执行结果、MCP 使用、网络代理放行 / 拦截事件,可接入 SIEM 与合规日志平台;Anthropic 侧 ResultMessage 携带 token 用量、成本与 session ID,/usage、/goal 无参、/workflows 提供技能 / 子代理 / MCP 级用量观测(A 级)。社区观测方案(B 级)给出通用模型:OTel span 树 = session → step → LLM call,核心指标为每步延迟分位(P50 / P95 / P99)、每会话 token、按模型与步拆分的成本、错误率与重试频率;常用启发式告警为"超过 10 步疑似循环"。
治理实践清单(A 级为主):
| 治理措施 | 内容 | 来源 |
|---|---|---|
| hooks 拦截 | 工具执行前拦截 / 修改 / 阻止调用 | Anthropic,A |
| Sprint Contract | 编码前就"完成"的定义达成契约,观测校验有据可依 | Anthropic,A |
| /goal 回合上限 | 评估模型校验 + 显式回合上限(如 "stop after 5 tries") | Anthropic,A |
| /loop 自动到期 | 周期任务建立 7 天后自动到期,防遗忘循环常驻 | Anthropic,A |
| 沙箱 × 审批正交 | 沙箱档位定义技术边界,审批策略决定何时请示;Auto-review 自动放行低风险、截停高风险 | OpenAI,A |
| OTel 审计遥测 | prompt、审批决定、工具结果、网络事件全量导出 | OpenAI,A |
| 预算即默认 | 官方建议"预算上限是生产 agent 的良好默认" | OpenAI / Anthropic 文档同义表述,A |
10. 从第二代到第三代的关键跃迁
10.1. 六条跃迁清单
综合前述六层,第三代相对于第二代发生了六条结构性跃迁:
| # | 跃迁 | 第二代做法 | 第三代做法 | 关键证据(等级) |
|---|---|---|---|---|
| 1 | 上下文从"自然增长"到"主动治理" | 上下文随对话自然累积 | 压缩、外化笔记、子 agent 隔离、渐进披露四件套 | Anthropic context engineering 博客(A) |
| 2 | 工具从"厂商专有"到"中立标准" | Function Calling / 插件(专有) | MCP → AAIF 中立治理 | MCP 发布、AAIF 成立(A) |
| 3 | 评估从"外挂榜单"到"内置闭环" | 跑一次公开榜看分数 | 内置 tracing + Evaluator 角色 + 反馈回流 L1 | Responses API 内置 tracing、三 Agent 架构(A) |
| 4 | 状态从"会话内"到"跨窗口交接" | 会话结束即失忆 | 进度文件 + git + 功能清单 + 健康度预检 | 长时运行 harness 两代(A) |
| 5 | 治理从"手工提示"到"沙箱与机械强制" | 逐条权限弹窗 | 双维隔离 + 凭据保护 + 自研 linter 注入修复 | Claude Code 沙箱(A,−84% 提示) |
| 6 | 角色从"人指挥"到"人掌舵" | 人逐步指挥每个动作 | Human Steer, Agent Execute | OpenAI《Harness engineering》(A) |
第 6 条是整个跃迁的哲学内核:人的工作从"操作"上移到"设计环境、反馈回路与控制系统"(OpenAI 原文:"Our most difficult challenges now center on designing environments, feedback loops, and control systems.")。
10.2. 完整范式样例:OpenAI 百万行代码实验
第三代 Harness 最完整的公开实证,是 OpenAI《Harness engineering》(2026-02-11,A 级)披露的内部实验。以下数字全部为一手,可全量引用:
| 指标 | 数值 |
|---|---|
| 起点 | 2025-08 下旬对空仓库首次提交;脚手架(仓库结构、CI、格式化规则、包管理器、应用框架)由 Codex CLI + GPT-5 生成,连最初的 AGENTS.md 也是 Codex 写的 |
| 五个月后代码量 | 约 100 万行(应用逻辑、基础设施、工具、文档、内部开发工具) |
| PR 数 / 工程师数 / 人均日 PR | 约 1,500 / 3 名(后扩至 7 名)/ 3.5 |
| 时间成本 | 约为手写的 1/10 |
| 人类手写代码 | 0 行 |
| 单任务最长运行时长 | 超过 6 小时 |
注意一条反直觉观察:团队从 3 人扩至 7 人后吞吐反而上升——这与传统软件工程"加人会让 PR 冲突加剧"的直觉相反,说明该 Harness 的协调开销低于新增人力带来的产出。
六项关键工程决策及其对应层
| 决策 | 内容 | 归属层 |
|---|---|---|
| AGENTS.md 从百科全书改为目录 | 约 100 行注入上下文,真识位于结构化 docs/(design-docs / exec-plans / product-specs / references / DESIGN.md / FRONTEND.md / PLANS.md / PRODUCT_SENSE.md / QUALITY_SCORE.md / RELIABILITY.md / SECURITY.md);官方金句"给 Codex 一张地图,而不是一本 1000 页的说明书" | L1 |
| linter 错误消息写成修复指令 | 自研 linter 的报错直接向 agent 上下文注入修复方法 | L6 → L1 闭环 |
| doc-gardening agent | 自动扫描过时文档并发起修复 PR | L6 |
| 分层架构约束的机械强制 | 单向依赖链 Types → Config → Repo → Service → Runtime → UI;横切关注点仅经 Providers | L6 |
| 可观测性对 agent 开放 | git worktree 启动、Chrome DevTools Protocol、LogQL / PromQL 查询 | L5 → L1 |
| 最小阻塞合并哲学 | 最小阻塞合并门,PR 短命,测试 flakiness 靠重跑解决——"纠错成本低,等待成本高" | L3 |
此外还有一条技术选型原则值得单独记住:倾向"无聊的技术"(可组合性、API 稳定性、在训练语料中广泛存在)。官方举的例子是自研 map-with-concurrency 而非引入 p-limit——理由是模型对"训练语料中广泛存在的东西"掌握得更好。
这条原则对所有 Harness 设计通用:在 agent 会写代码的系统里,技术的"模型熟悉度"是真实的选型指标,与性能、生态并列。
10.3. 跃迁尚未完成的部分
第三代远不是终点。以下问题是官方自陈尚未解决的(A 级):
- 单 Agent vs 多 Agent 之争未决——Anthropic 明确表示"目前尚不清楚";
- 跨领域泛化未验证——上述经验能否推广到科学研究或金融建模等其他长周期任务,"答案尚在摸索中";
- Harness 自身缺乏评估方法——martinfowler.com 提出的开放问题:我们需要类似代码覆盖率和变异测试的 Harness 覆盖率与质量评估方法(尚未出现);
- 熵治理仍靠补丁——doc-gardening 是对腐烂的补救,而非对腐烂的根治。
11. Harness 能力成熟度自评表
11.1. 自评框架的构造说明
重要说明:下表为本项目基于前述公开资料自行构建的分析框架,并非任何标准组织发布的规范,也不是任何厂商的官方模型。其价值在于提供一把可操作的标尺,帮助组织定位自身 Harness 能力并进行代际对齐。请勿将其作为合规依据或行业基准使用。
框架对 L1~L6 每层定义五个等级(0~4),并给出每一等级的可判别特征。
11.2. 五级定义
| 等级 | 名称 | 通用定义 |
|---|---|---|
| L0 | 缺失 | 该层不存在或完全依赖人工;问题不被系统性察觉 |
| L1 | 手工 | 存在做法,但靠人执行、靠约定维持;不可复现、不可回归 |
| L2 | 工具化 | 有专门工具或组件;能自动执行,但缺乏治理策略 |
| L3 | 系统化 | 有明确策略与默认架构;能被度量,能在 CI 中回归 |
| L4 | 闭环自治 | 该层的输出自动回流改善其他层;具备抗熵机制(自动纠偏、自动文档治理) |
11.3. 自评表
| 层 | L0 缺失 | L1 手工 | L2 工具化 | L3 系统化 | L4 闭环自治 |
|---|---|---|---|---|---|
| L1 上下文工程 | 上下文自然累积,无管理 | 人工挑选粘贴上下文 | 接入 RAG / 检索 | 有压缩 + 外化笔记 + 子 agent 隔离 + 渐进披露四件套;有 attention budget 意识 | 上下文组装策略由 L5 反馈自动调整;Skills 与 docs 自动裁剪更新 |
| L2 工具与执行 | 模型只能输出文本 | 少量硬编码工具 | Function Calling + 若干自有工具 | 工具经 MCP 标准化接入;运行在双维隔离沙箱(文件系统 + 网络) | 工具集根据使用数据与失败反馈自动增删(如 Vercel 式减法被制度化) |
| L3 编排与控制 | 单轮调用 | 人工串流程 | 编排框架单次循环 | 支持长时运行、Sprint Contract、sub-agent 派发、确定性 + 动态路由并存 | 编排结构本身可被评估与自动选型;能对自己做失败模式分析 |
| L4 记忆与状态 | 会话结束即失忆 | 人工写交接说明 | 有会话持久化 | 进度文件 + git + 机器可读任务清单 + 开场健康度预检 | 状态交接被自动校验;脏状态在下一轮开场前被自动修复 |
| L5 评估与观测 | 靠人眼看结果 | 人工抽查 | 偶尔跑公开基准 | 内置 tracing + 自建 Golden Dataset + 每次真实失败补一条回归 case | 评估者与被评估者分离且 Evaluator 独立演进;held-out 集防过拟合;观测数据反向供给 L1 |
| L6 治理与安全 | 无边界 | 逐条人工审批 | 有权限配置 | 沙箱 + 凭据保护 + 自研 linter 机械强制;failIfUnavailable 硬失败;中心强制边界、局部自治 | 治理规则可被 agent 理解并自我修复(错误消息即修复指令);熵增被持续自动治理(doc-gardening) |
11.4. 结果解读
| 得分形态 | 判读 | 建议动作 |
|---|---|---|
| 多数层处于 L0~L1 | 尚不具备第三代 Harness,处于第二代早期 | 优先建 L2(工具标准化)与 L5(至少要有回归集),其余层暂缓 |
| 多数层处于 L2 | 典型的"工具很全但不稳定"状态 | 优先攻 L1(上下文治理)与 L6(沙箱),这两个是最常见的瓶颈 |
| 多数层处于 L3 | 已达第三代主流水平 | 重点是保持:建立本 Harness 的回归机制,防止随模型升级而退化 |
| 出现 L4 层 | 处于前沿探索 | 注意 04-未来发展 中指出的风险:Harness 过度复杂化可能被下一次模型升级直接抹平 |
| 层间差距 ≥ 2 级 | 存在结构性短板 | 短板层决定了整体上限,优先补齐 |
层间差距 ≥ 2 级这一条尤其重要。Harness 的整体产出受限于最弱的一层,而不是最强的那层——这与软件系统的木桶效应一致。例如,一个 L1 只有 L1 级(手工粘贴上下文)但 L2 达到 L3 级的系统,其表现往往不如两者均为 L2 级的系统。
11.5. 使用建议
- 每半年自评一次,并把结果记录下来用于对比——自评本身的价值在于纵向比较,而非横向得分。
- 评估时逐层给出具体证据,不写抽象的"中等",要写"我们的 context 压实靠的是 XXX"。
- 优先关注最弱层,而不是平均分。
- 警惕"评估通胀":当一个层被评到 L3 却没有任何可回归的证据(例如没有 Golden Dataset),应当降回 L2。
12. 总结
第三代 Harness 的架构可以用一句话概括:它是一个把模型的输出分布,通过六层结构收窄到工程可接受区间的系统。
- L1 决定模型看到什么——关键瓶颈是注意力预算,核心手段是删除而非添加;
- L2 决定模型能做什么——MCP 解决了接入标准,沙箱解决了副作用边界;
- L3 决定按什么顺序做——从单循环走到 Planner / Generator / Evaluator 的分工;
- L4 决定记住什么——Git 成为主流的状态载体,跨窗口交接是长任务的生命线;
- L5 决定做得好不好——第一原则是评估者与被评估者分离;
- L6 决定不能做什么——治理不是速度的敌人,官方实证是权限提示减少 84%。
而把六层串起来的,是九个字:看得见、做得稳、能回归。
下一阶段的问题是:这套架构会不会被更强的模型直接吸收?对这个问题的双向答案见 04-未来发展.md 第 2.1 节;对整个发展阶段的综合判断见 05-总结.md。
13. 信息缺口声明
本节汇总本篇涉及的信息缺口,已在正文对应位置标注 或说明来源等级。
已存在于本次调研、可跨来源复用的缺口
- Anthropic《How we built our multi-agent research system》的确切 URL 与发布日期:仅在 context engineering 博客中以链接形式被引用,未验证。
- MCP "首个公开规范版本"表述差异:2024-11-05(Ruby SDK 记为 Initial protocol revision)与 2024-11-25(公开宣布与生态启动)两种口径并存,本篇并列呈现。
数字来源等级不足,本篇已标注
- 第 3.10 节:上下文退化的"性能下降超过 45%"与 Chroma Research "18 个前沿模型全部退化"。
- 第 4.6 节:Codex CLI "2026 年初约 95% Rust"、Auto-review 的 "1/200" 与 "99%",以及审阅模型型号 "GPT-5.4 Thinking"。
- 第 4.7 节:Vercel 工具数 15 → 2 的准确率 80% → 100%、Token −37%、速度 3.5×。
- 第 5.7 节:Anthropic 单 Agent(20 分钟 / $9 / 不可用)与三 Agent(6 小时 / $200 / 完整可玩)的对比实验数字。
- 第 7.5 节:Terminal-Bench 2.0 全部榜单数字(77.3% / 75.1% / 74.7% / 71.9%)、LangChain 52.8% → 66.5%,以及 easy 约 65% → hard 约 16% 的难度梯度。
- 第 7.5 节:Terminal-Bench 官方站(tbench.ai)当前榜单数据未直接抓取,全部为第三方转述。
本篇未涉及但属于本模块共同缺口的项目
- ISO/IEC 智能体互联国际标准编号:暂无权威信息。
- "Agent Harness"术语首创出处:暂无权威信息。
- Claude 模型 2026 年各版本时间线:仅见于第三方 GitHub 时间线仓库,标 。
本轮新增(第 9 章 Harness Loop)
- 《Unrolling the Codex agent loop》《Unlocking the Codex harness》《Codex as a platform》等 OpenAI 官方博客的具体发布日期未在检索结果中直接返回(第 9.2 / 9.3 节)。
- $47,000 多代理乒乓失控案例为 verified: partial(多帖一致、无具名受害企业),正文已按"业界流传的代表性事故复盘"表述并保留数字(第 9.6 节)。
- 业界三重硬限经验值(迭代上限 10 / 25 / 50~100、token 预算 10 倍均值、墙钟超时 2~3 倍 p95)为业界实践汇总(C 级),仅作方向性参考(第 9.4 节)。
- n8n / Coze 循环节点缺独立一手官方文档,仅经可视化工作流有界循环共性模式间接覆盖(第 9.5 节)。
- MAF 较 AutoGen GroupChat 减少 23% LLM 调用为第三方转述(B 级),官方一手文稿未直接命中(第 9.5 节)。
完整清单见 06-参考资料.md 第 9 节。
14. 参考资料
- Effective context engineering for AI agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Effective harnesses for long-running agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
- Harness design for long-running application development — Anthropic,2026。https://www.anthropic.com/engineering/harness-design-long-running-apps
- Equipping agents for the real world with Agent Skills — Anthropic,2025-10-16。https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills
- Introducing Agent Skills — Anthropic,2025-10-16(2025-12-18 开放标准更新)。https://www.anthropic.com/news/skills
- Sandboxing: a safer and more autonomous approach — Anthropic,2025。https://www.anthropic.com/engineering/claude-code-sandboxing
- Claude Code 官方文档 · Sandboxing(中文版)— Anthropic,2026。https://code.claude.com/docs/zh-TW/sandboxing
- Claude Code 官方文档 · Choose a sandbox environment — Anthropic,2026。https://code.claude.com/docs/en/sandbox-environments
- Introducing the Model Context Protocol — Anthropic,2024-11-25。https://www.anthropic.com/news/model-context-protocol
- Harness engineering: leveraging Codex in an agent-first world — OpenAI,2026-02-11。https://openai.com/index/harness-engineering/
- Harness engineering(中文版)— OpenAI,2026-02-11。https://openai.com/zh-Hans-CN/index/harness-engineering/
- New tools for building agents(Responses API + Agents SDK)— OpenAI,2025-03-11。https://openai.com/blog/new-tools-for-building-agents
- Agent Development Kit: Making it easy to build multi-agent applications — Google,2025-04-09。https://googledevelopers.blogspot.com/en/agent-development-kit-easy-to-build-multi-agent-applications/
- A year of open collaboration: Celebrating the anniversary of A2A — Google Open Source Blog,2026-04-16。https://opensource.googleblog.com/
- Agent Development Kit — AI Wiki,2026。https://aiwiki.ai/wiki/google_adk
- Model Context Protocol 官方站与规范 — MCP / AAIF,2024—2026。https://modelcontextprotocol.io/;https://modelcontextprotocol.io/specification/2026-07-28/
- MCP Protocol Versions(版本演进表)— MCP Ruby SDK,2026。https://ruby.sdk.modelcontextprotocol.io/protocol-versions/
- MCP Rust 层协议版本枚举 — mcpkit(docs.rs)。https://docs.rs/mcpkit/latest/enum.ProtocolVersion.html
- Model Context Protocol 词条(含规范演进)— Klu。http://klu.ai/glossary/model-context-protocol
- Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF,2025-12-09。https://aaif.io/
- Harness engineering for coding agent users — Birgitta Böckeler,martinfowler.com,2026。https://martinfowler.com/articles/harness-engineering.html
- SWE-bench: Can Language Models Resolve Real-World GitHub Issues? — Jimenez、Yang 等(Princeton),2023-10(ICLR 2024 Oral)。https://www.swebench.com/
- Terminal-Bench — Stanford / Laude Institute,2025。https://www.tbench.ai/
- Context engineering 词条(命名链与四支柱)— AI Wiki,2025—2026。https://aiwiki.ai/wiki/context_engineering
- OpenAI Codex 词条(沙箱原语、批准模式、Rust 重写)— AI Wiki,2026。https://aiwiki.ai/wiki/codex
- Agent Harness:2026 年 AI 工程的核心范式 — 腾讯云开发者社区,2026。https://developer.cloud.tencent.com/article/2698416
- Terminal-Bench: The CLI Autonomy Standard — AgentMarketCap,2026-04-09。https://agentmarketcap.ai/blog/2026/04/09/terminal-bench-cli-autonomy-standard-coding-agents
- Anthropic 的 Harness 工程架构演进(中文综述)— 阿里云开发者社区,2026。https://developer.aliyun.com/article/1724413
- How the agent loop works — Anthropic,2026。https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
- Building agents with the Claude Agent SDK — Anthropic,2025。https://claude.com/blog/building-agents-with-the-claude-agent-sdk
- Loop engineering: Getting started with loops — Claude Code 团队,Anthropic,2026-06-30。https://claude.com/blog/getting-started-with-loops
- A harness for every task: dynamic workflows in Claude Code — Anthropic,2026。https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code
- How we built our multi-agent research system — Anthropic,2025。https://www.anthropic.com/engineering/multi-agent-research-system
- Unrolling the Codex agent loop — OpenAI,2025—2026(发布日期 ,见第 13 节)。https://openai.com/index/unrolling-the-codex-agent-loop/
- Codex as a platform: build on the open agent harness — OpenAI Developers,2026。https://developers.openai.com/blog/codex-as-a-platform
- Running agents — OpenAI Agents SDK 官方文档,2026。https://openai.github.io/openai-agents-python/running_agents/
- Running Codex safely at OpenAI — OpenAI,2026。https://openai.com/index/running-codex-safely/
- Agent approvals & security — Codex 官方文档,2026。https://developers.openai.com/codex/sandbox
- gemini-cli(开源仓库与 ReAct 循环文档)— Google,2025—2026。https://github.com/google-gemini/gemini-cli
- What does recursionLimit actually count in createAgent? — LangChain 官方论坛,2025—2026。https://forum.langchain.com/t/what-does-recursionlimit-actually-count-in-createagent-langchain-js/3460
- Dify 节点系统文档(Iteration / Loop 节点)— LangGenius,2026(经 DeepWiki 结构化索引)。https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
- Iteration Node — Agent Patterns Catalog,2026。https://www.agentpatternscatalog.org/patterns/iteration-node
- Runaway Tool Loops — PolicyLayer,2026(案例发生于 2025-11,verified: partial)。https://policylayer.com/attacks/runaway-tool-loops
Architecture Evolution
1. Reading Guide and Positioning
1.1. The Three Questions This Document Answers
01-Introduction.md established the definition and six-layer capability model of AI Harness, and 02-Development History.md established the timeline of the three-generation evolution. This document is the intersection of the two, and it answers three questions:
- What a contemporary (third-generation) Harness actually looks like — which components make up each layer, and how these components connect to one another;
- Why the engineering design of each layer has its current shape — what failures it has to overcome, and what price was paid for that;
- How an organization can judge what level its own Harness is at — providing an actionable self-assessment tool.
1.2. Boundaries with Prior Documents
| Content | Ownership | Handling in This Document |
|---|---|---|
| Definition of Harness, etymology, definition of the six-layer model | 01-Introduction | Cited directly, not redefined |
| Timeline of the three-generation division, milestones, historical causes | 02-Development History | Cited only when necessary, no historical narration |
| Components, parameters, design trade-offs, and failure modes of each layer | This document | Developed in detail |
| Prospects for standardization and trend extrapolation | 04-Future Development | No trend prediction is made in this document |
| Product-by-product analysis of specific platforms | 03-Market Research | This document takes only "representative implementations" as in-layer examples |
1.3. Convention on Source Tiers for Technical Parameters
This document cites many engineering parameters published by vendors. Every citation is labeled with a source tier, following the rules in README.md section 5.2:
- Tier A: vendor official primary sources (Anthropic / OpenAI / Google / Linux Foundation / MCP official, etc.), can be cited directly;
- Tier B: authoritative secondary sources (Wikipedia, AI Wiki, TechCrunch, GIGAZINE, etc.), must be noted as paraphrases;
- Tier C: community and self-media interpretations; their numbers are uniformly flagged as unverified.
All numbers appearing in this document can only serve as directional references and must not be used as the basis for selection or decision-making.
2. Overview of the Third-Generation Architecture
2.1. The Basis for Layering: From "Capability Zoning" to "Bottleneck Zoning"
The reason the third-generation Harness can be stably divided into six layers is not that six layers is some a priori functional division, but that each layer corresponds to a class of independently emergent bottleneck. This can be worked backwards from roll-the-DAG-style failure attribution: when a long-cycle agent task fails, the engineer's attribution almost always falls into one of the following six categories—
| Attribution | Corresponding Layer |
|---|---|
| It never saw that critical file / the context was too long and information was lost | L1 |
| The action it wanted to perform was not correctly defined as a tool / the execution produced unexpected side effects | L2 |
| The order in which it did this thing was wrong / it got stuck in some loop and couldn't get out | L3 |
| In a new session it "forgot" how far it got in the previous round | L4 |
| It said "done", but it actually wasn't done | L5 |
| It did something it shouldn't have / it overshot the budget / we can't find out who did it | L6 |
Layers are defined by failures, not by feature lists. This is the practical criterion for judging which layer a new component should belong to.
2.2. Layered Design Overview Diagram
图 2-1|第三代架构总览:六层分层设计
┌──────────────────────────────────────────────────────────────────┐
│ L6 治理与安全层 Governance & Safety │
│ 权限 · 沙箱策略 · 凭据保护 · 架构约束 · 熵治理 · 预算护栏 │
│ (横向切面,对 L1~L5 全部施加约束并记录审计) │
└──────────────────────────────────────────────────────────────────┘
▲ ▲ ▲ ▲
│ 约束 │ 约束 │ 约束 │ 审计
┌──┴────────┐ ┌───┴────────┐ ┌───┴─────────┐ ┌──┴──────────┐
│ L1 上下文 │─►│ L2 工具与 │─►│ L3 编排与 │─►│ L5 评估与 │
│ 工程层 │ │ 执行层 │ │ 控制层 │ │ 观测层 │
│ 看到什么 │ │ 能做什么 │ │ 按什么顺序做 │ │ 做得好不好 │
└───────────┘ └────────────┘ └─────────────┘ └─────────────┘
▲ │ │
│ 反馈:改变下次看到什么 │ │
└──────────────────────────────┴───────────────────┘
▲
┌────┴───────────────────────────────────────────┐
│ L4 记忆与状态层 Memory & State │
│ 会话态 · 长期记忆 · 检查点 · 工件 │
│ (时间维度的横向支撑层) │
└────────────────────────────────────────────────┘ It should be emphasized that the feedback edge between L5 and L1 in the diagram is the structural difference between the third and second generations: in the second generation evaluation is bolted on (run a benchmark once, glance at the score), while in the third generation the output of evaluation flows back to change the next round of context assembly, forming a closed loop.
2.3. Responsibilities, Boundaries, and Data Flow of the Six Layers
| Layer | Name | English | Responsibility | Input | Output | Typical Implementations |
|---|---|---|---|---|---|---|
| L1 | 上下文工程层 | Context Engineering | Decides what the model "sees" | Environment state, retrieval results, instructions | The assembled token sequence | RAG, Context Compaction, Prompt Assembly, progressive disclosure via SKILL.md, KV Cache reuse |
| L2 | 工具与执行层 | Tooling & Execution | Decides what the model "can do" | Tool invocation intent | Side effects in a controlled environment | MCP, Function Calling, sandboxed executors, Computer Use |
| L3 | 编排与控制层 | Orchestration & Control | Decides "in what order to do it" | Task goal | Sequence of execution steps | Agent Loop, Plan-and-Execute, DAG / Workflow, Sub-agent |
| L4 | 记忆与状态层 | Memory & State | Decides "what to remember" | Session history, artifacts | State recoverable across windows | Session Store, Episodic / Semantic Memory, Checkpoint |
| L5 | 评估与观测层 | Evaluation & Observability | Decides "how well it was done" | Execution trace, products | Verdicts, metrics, regression signals | Trace, Eval Set, Golden Dataset, Online Metrics |
| L6 | 治理与安全层 | Governance & Safety | Decides "what must not be done" | Policies, budgets, compliance requirements | Allow / deny + audit records | RBAC, guardrail models, audit logs, Budget Guardrail |
The main execution chain is L1 → L2 → L3, the lateral supports are L4 (temporal dimension) and L6 (constraint dimension), and the closed loop is L5 → L1.
2.4. Comparison Against the Three-Generation Evolution
The maturity differences of the six layers described in this document across the three generations are as follows (looking at each layer vertically, you can see that the engineering focus of the third generation falls on L1, L2, L5, and L6):
| Layer | First Generation · Prompt Engineering | Second Generation · Tools and Orchestration | Third Generation · Runtime and Evaluation |
|---|---|---|---|
| L1 | No governance, relies on Few-shot | Preliminary RAG, no compaction strategy | Compaction + notes + sub-agents + Skills — the four-piece set |
| L2 | No tools | Function Calling (vendor-proprietary) | MCP standardization + strongly isolated sandbox |
| L3 | Single-turn | Multi-agent orchestration frameworks | Built into official SDKs + long-running + three-role division of labor |
| L4 | Stateless | Preliminary session memory | Cross-window state handoff + checkpoints + Git as the state carrier |
| L5 | Manual subjective judgment | External benchmark leaderboards | Built-in evaluation loop + independent Evaluator + trace tracking |
| L6 | None | Manual permission prompts | Sandbox + credential protection + mechanical enforcement by linters + entropy governance |
3. The L1 Context Engineering Layer
3.1. Positioning of the Layer
The question L1 answers is: before this step of reasoning, which tokens should the model see. It is the only layer in the entire Harness that acts directly on the model's input interface, and therefore has always occupied the most central position across the three generations of evolution.
The official definition given by Anthropic in "Effective context engineering for AI agents" (2025, Tier A) is: during LLM inference, the full set of strategies for curating and maintaining that optimal set of Tokens (information).
The definition given by Andrej Karpathy on 2025-06-25 is widely cited:
"Context engineering is the delicate art and science of filling the context window with just the right information for the next step."
But his immediately following supplement is more valuable—he says context engineering is only a small part of "an emerging thick layer of non-trivial software that coordinates individual LLM calls into full LLM apps". This sentence precisely defines L1's position among the six layers: it is a necessary layer, but far from the whole.
3.2. The Official Problem Statement: context rot and the attention budget
Two concepts erected by Anthropic officially constitute the theoretical foundation of the L1 layer:
| Concept | Official Statement | Engineering Implication |
|---|---|---|
| context rot | Explicitly stated as a "performance gradient, not a hard cliff" | As context grows, performance degrades gradually; there is no safe "threshold". Therefore context must be continuously governed, and a one-shot truncation cannot solve it |
| attention budget | The n² relational property of self-attention means each additional token dilutes attention on the other tokens | Context is a scarce resource, not a free container. Every token placed in carries an opportunity cost |
Together these two yield a counterintuitive but repeatedly verified engineering conclusion: cramming more information into the context is usually a negative optimization. Section 3.10 presents the corresponding failure modes.
3.3. Key Component One: Compaction
The official documentation divides compression into several tiers, of which the "safest and lightest" tier is tool result clearing, a capability already live on the Claude Developer Platform (Tier A).
The tuning order given officially is an important engineering discipline:
Maximize recall first, then improve precision.
Reversing the order loses critical constraints that later steps still need—because once compressed content cannot be restored, the model will make irreversible wrong decisions in later steps based on incomplete information.
3.4. Key Component Two: Structured Notes and Agentic Memory
The second official strategy is to persist notes outside the context window and pull them back when needed. Official cases include:
- Claude Code's to-do list;
- A custom agent's
NOTES.md; - The precise counting Claude maintained across thousands of steps while playing Pokémon.
The official team also released the Memory tool (entered public beta on the Claude Developer Platform alongside Sonnet 4.5, Tier A), turning externalized notes into a platform capability.
The selection principle given officially is worth quoting directly as a team norm:
| Strategy | Applicable Task Characteristics |
|---|---|
| Compaction | Tasks requiring many round-trips |
| Note-taking | Iterative development with clear milestones |
| Multi-agent / Sub-agent | Complex research where parallel exploration has a payoff |
3.5. Key Component Three: Sub-Agent Context Isolation
The third official strategy is Sub-agent architectures, whose official parameters (Tier A) are:
A sub-agent can explore deeply using tens of thousands of tokens, but returns only a condensed summary of 1,000~2,000 tokens.
This is a typical architectural trade-off of "exchanging context for parallelism / for depth": the main agent's context window stays clean, at the price of information loss in the summarization process. When selecting in this layer one must consider explicitly: is the summary loss acceptable.
3.6. Key Component Four: Skills and Progressive Disclosure
Agent Skills (Anthropic, released 2025-10-16, converted to an open standard on 2025-12-18, Tier A) pushes L1 from "how to cram in more" to "how to load on demand".
| Element | Content |
|---|---|
| Minimal form | my-skill/SKILL.md directory, extensible with scripts/, references/, assets/ |
| Required metadata | name and description in the YAML frontmatter |
| First layer (startup) | Only each skill's name + description is loaded into the system prompt |
| Second layer (hit) | Read the complete SKILL.md text |
| Third layer (on demand) | Read bundled files, e.g. reference.md, forms.md |
| Code support | Executable code can be bundled; the code runs without entering the context |
Anthropic's official claim is:
"the amount of context that can be bundled into a skill is effectively unbounded"
This design effectively alleviates the "more capabilities, more crowded context" contradiction. At the same time the official documentation gives the economic argument for replacing tokens with code: sorting a list costs far more in generated tokens than running a sorting algorithm once, and code is deterministic, making workflows consistently reproducible.
3.7. Another Industry Taxonomy: The Four Pillars
Besides Anthropic's official four-way split, another widely used one in the industry is the LangChain four pillars (Harrison Chase, "The Rise of Context Engineering", 2025-06-23, organized per Lance Martin's taxonomy, Tier B):
| Pillar | Meaning | Corresponding Implementation |
|---|---|---|
| Write | Externalize state | scratchpad, NOTES.md |
| Select | Precise retrieval | RAG, memory retrieval, tool and few-shot selection |
| Compress | Summarize, trim, prune | Compaction, tool result clearing |
| Isolate | Isolation | sub-agent isolated windows, sandbox, state schema boundaries |
The two taxonomies map onto each other: Anthropic's "first three strategies" largely cover the first three of Write / Select / Compress / Isolate, and sub-agent corresponds to Isolate.
3.8. Comparison of Representative Implementations
| Implementation | Form | L1 Techniques | Source Tier |
|---|---|---|---|
| Claude Agent SDK / Claude Code | Official SDK + CLI | The full four-piece set (compaction / notes / memory tool / sub-agent), progressive disclosure via SKILL.md | A |
| OpenAI Agents SDK / Codex | Official SDK + CLI | The "AGENTS.md as directory" strategy, ~100 lines of context injected + structured docs/ externalized (see section 10.2) | A |
| Google ADK | Official SDK | Session / Runner as the state boundary (typed state across curtailed sessions) | A |
| LangChain / LangGraph | Open-source framework | The most complete realization of the four-pillar theory; Isolate is achievable at node boundaries | B |
3.9. Design Trade-offs
Three core trade-offs of the L1 layer:
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Recall vs precision | Full dump (high recall, prone to rot) vs precise retrieval (high precision, prone to omission) | The order given officially: recall first, precision later |
| Depth vs cleanliness | Keep the full main context (deep but easily dirtied) vs sub-agent summaries (clean but lossy) | Whether the task requires strong consistency across steps |
| Static injection vs dynamic loading | Inject all instructions at once (simple but expensive) vs progressive Skills disclosure (saves context but requires accurate routing) | Whether the routing hit rate is high enough; when the hit rate is low, progressive disclosure is actually worse |
3.10. Failure Modes
Four classes of context failure have been identified at the L1 layer (Tier B, LangChain's categorization per multiple paraphrases):
| Failure Mode | Meaning | Typical Symptoms |
|---|---|---|
| context poisoning | Erroneous information is propagated as fact within the session | After a single tool error, all subsequent reasoning builds on the wrong premise |
| context distraction | Key information is drowned by noise | Retrieval returns 50 relevant passages; the model uses only the first 3 |
| context confusion | Redundant information causes loss of focus | Too many "you could also do it this way" suggestions in the instructions; the model starts picking randomly between two |
| context clash | Conflicting instructions inside the context | AGENTS.md and SKILL.md give different approaches to the same problem |
Quantitative supplement (Tier C): 2025 research found that "semantically consistent but irrelevant data can degrade performance by more than 45%"; Chroma Research tested 18 frontier models in 2025-07, and every one degraded as the context grew.
Engineering implication: the construction priority of the L1 layer is not "retrieve more" but "delete more". Vercel's subtraction experiment in section 4.4 (tool count 15 → 2, flagged as unverified) is on the same logic as this section's "one external rehearsal"—reducing supply is often more effective than increasing it.
4. The L2 Tooling and Execution Layer
4.1. Positioning of the Layer
The question L2 answers is: what actions the model can apply to the environment, and where those actions execute. The layer contains three classes of components:
| Component Class | Role | Representative |
|---|---|---|
| Tool registration and description | Declare external capabilities as structured interfaces callable by the model | Function Calling, JSON Schema tool descriptions |
| Connection protocol | Decouple the tool ecosystem from the host application | MCP (Model Context Protocol) |
| Execution environment | Bound the scope of actions and the boundary of side effects | Sandbox (Seatbelt / bubblewrap + socat / Landlock + seccomp) |
4.2. MCP: The Connection Standard of Layer 2
MCP adopts a Host / Client / Server three-role architecture (Tier A):
| Role | Responsibility | Description |
|---|---|---|
| Host | Top-level application (IDE, chat app, multi-agent orchestration framework) | Contains Clients |
| Client | Maintains a 1:1 connection with each Server | Handles protocol negotiation and routing |
| Server | Lightweight program | Exposes Tools / Resources / Prompts |
Transport: local uses stdio, remote uses Streamable HTTP, and messages are based on JSON-RPC 2.0.
Google officially gave a clear division of labor between MCP and A2A ("A year of open collaboration", 2026-04-16, Tier A):
"MCP manages internal tool integration, while A2A handles the vital external coordination between autonomous entities."
That is: MCP manages internal tool integration, and A2A manages external coordination between agents. The two are not in competition; they are connection protocols in different directions inside the Harness.
4.3. The Five-Version Spec Evolution Chain of MCP
The following version chain is first-hand parameters (MCP Ruby SDK Protocol Versions page + mcpkit docs.rs + Klu entry, Tier A) and can be cited in full:
| Version | Key Changes |
|---|---|
| 2024-11-05 | Initial protocol version: stdio + HTTP+SSE; the three primitives Tools / Resources / Prompts; Sampling, Roots, progress notifications, logging, pagination |
| 2025-03-26 | Streamable HTTP replaces HTTP+SSE; OAuth 2.1; tool annotations (readOnly / destructive / idempotent); audio content; Completions |
| 2025-06-18 | Elicitation; structured tool output; resource links; protected resource metadata; _meta field; the MCP-Protocol-Version header becomes mandatory; JSON-RPC batching removed (breaking change) |
| 2025-11-25 | Tasks (asynchronous state tracking); parallel tool calls; server-side agent loop; tool calls in sampling |
| 2026-07-28 | Protocol core made stateless (the initialize handshake and Mcp-Session-Id removed; the version rides along in _meta with every request); the Extensions framework introduced (Tasks, MCP Apps); authorization strengthened; formal deprecation policy (minimum 12-month window); Roots / Sampling / Logging deprecated in the new version |
From this evolution chain, three clear orientations of the third-generation Harness at the protocol layer can be read:
- From stateful sessions to stateless requests—the 2026-07-28 removal of the handshake and session ID lets a remote MCP server scale horizontally like an ordinary web service;
- From "good enough" to "evolvable"—the 12-month minimum deprecation window is a marker of mature standardization governance, meaning users can safely plan their dependencies;
- From "tools only" to "agents on the server side too"—the 2025-11-25 server-side agent loop sinks part of the L3 responsibilities inside the L2 boundary (the server-side execution domain).
Version status note: Wikipedia and some sources say "2024-11-05 initial release / 2024-11-25 public announcement", which differs from the MCP Ruby SDK listing only
2024-11-05as the "Initial protocol revision"; the two statements can coexist. See section 13 for details.
4.4. Tool Design Guidelines
Anthropic's official documentation gives three tool design guidelines (Tier A), usable directly as a checklist for team toolset review:
- Self-contained, robust to errors, extremely clear in purpose;
- Avoid feature overload and ambiguous decision points—a tool that does many things makes the model hesitate when choosing, and makes failure causes hard to attribute;
- Few-shot examples should be "diverse and typical", not a list of edge cases.
Echoing this is the "right altitude" principle for system prompts: they must neither be written as fragile hard-coded logic nor be so vague that only high-level guidance remains, but should be "specific enough to effectively guide behavior, yet flexible enough to leave the model room for strong-heuristic judgment".
4.5. Sandbox: The Official Implementation in Claude Code
The Claude Code sandbox is the most completely publicly disclosed agent sandbox design to date ("Sandboxing: a safer and more autonomous approach" + official documentation, Tier A). The following parameters can be cited in full.
Core security axiom (Tier A original text): filesystem isolation and network isolation are both indispensable—
- Without network isolation, a compromised agent can exfiltrate SSH keys;
- Without filesystem isolation, a compromised agent can escape easily and obtain network access.
Platform implementation and default policies
| Item | Parameter |
|---|---|
| macOS implementation | Seatbelt |
| Linux / WSL2 implementation | bubblewrap + socat (optional seccomp filter, via npm install -g @anthropic-ai/sandbox-runtime) |
| Not supported | Native Windows; WSL1 |
| Default write | Commands in the sandbox can write only to the current working directory and the session temporary directory ($TMPDIR is set to that directory) |
| Default read | Readable machine-wide by default (except explicitly denied directories) |
| Network egress | Only via a unix domain socket to a proxy server running outside the sandbox; the first request to a new domain prompts for approval |
Two operating modes
| Mode | Behavior |
|---|---|
| Auto-allow | Sandboxed commands are approved automatically, no per-command prompts |
| Regular permissions | Still prompts per command |
Even in auto-allow mode, deny rules, rm -rf-class commands targeting / or the home directory, and content-scoped ask rules still take effect.
Escape hatch and strict mode: a dangerouslyDisableSandbox retry is provided; it can be disabled via allowUnsandboxedCommands: false, i.e. Strict sandbox mode.
Credential protection (requires Claude Code v2.1.187+): sandbox.credentials can deny access to files (e.g. ~/.aws/credentials, ~/.ssh) and environment variables (e.g. GITHUB_TOKEN, NPM_TOKEN); v2.1.199+ supports mode: "mask".
Process-level sandbox (@anthropic-ai/sandbox-runtime): wraps the entire Claude Code process (including built-in tools, MCP servers, and hooks) in the same isolation layer; by default it denies writes to .git/hooks, .git/config, .mcp.json, .claude/commands, .claude/agents, and shell startup files.
Configuration paths: .claude/settings.local.json (project level) / ~/.claude/settings.json (user level) / managed settings (organization level); sandbox.failIfUnavailable can be set to a hard failure.
Quantified effect (Tier A, the core number repeatedly cited in this module): Anthropic's internal use found that sandboxing safely reduced permission prompts by 84%.
4.6. Cross-Comparison of Sandbox Implementations
| Dimension | Claude Code | Codex CLI |
|---|---|---|
| macOS primitive | Seatbelt | sandbox-exec (Seatbelt) |
| Linux primitive | bubblewrap + socat (+ optional seccomp) | Landlock + seccomp |
| Windows primitive | Native Windows / WSL1 not supported | job objects |
| Default network | Via a proxy unix socket; new domains require approval | Network disabled by default |
| Default write | Current working directory + session temporary directory | Restricted to the current directory |
| Approval tiers | Auto-allow / Regular permissions | Suggest / Auto-edit / Full-auto |
| Source tier | A | B (AI Wiki paraphrase; specific parameters flagged as unverified) |
Supplement (Tier B): Codex CLI was rewritten from Node.js to Rust in the second half of 2025; by early 2026 roughly 95% of the codebase is Rust; the official rationale is static single-file distribution, no GC, low memory footprint, and direct invocation of OS sandbox primitives. In 2026-04 an Auto-review mode was added; internal sessions stopping for human approval occur at roughly 1/200 the rate of the manual mode, with an approver pass rate of about 99%.
4.7. Design Trade-offs
| Trade-off | The Two Poles | Position of This Section |
|---|---|---|
| Sandbox strength vs usability | Strong isolation (safe but often needs an escape hatch) vs weak isolation (easy to use but risk spills over) | The solution given officially is that isolation must come in pairs (filesystem + network), not "as strong as possible" |
| Tool count vs accuracy | More tools, broader capability vs more tools, harder choice | Subtraction first. Vercel cut the tool count from 15 to 2: accuracy 80% → 100%, tokens −37%, speed 3.5× (Tier C) |
| Native plugins vs standard protocol | Better performance but lock-in vs decoupled but with overhead | The third generation generally picks the MCP route; deviations need a clear reason |
4.8. Failure Modes
| Failure Mode | Manifestation | Countermeasure |
|---|---|---|
| Tool semantic overlap | Two tools have similar descriptions; the model picks randomly and unreproducibly | Do a "pairwise distinguishability" check in tool review |
| Sandbox escape normalized under the name of the escape hatch | dangerouslyDisableSandbox is used frequently; isolation becomes a mere formality | Disable the escape hatch (Strict sandbox mode); turn exceptions into explicit approvals |
| Credentials leaked via environment variables | Child processes inherit GITHUB_TOKEN and the like | Use sandbox.credentials to deny / mask explicitly |
| Network egress out of control | The agent exfiltrates data over arbitrary DNS | Mandatory proxy + new-domain approval + egress whitelist |
| Over-tooling | Bloated tool count causes a double loss in accuracy and cost | Do tool subtraction regularly; demote low-frequency tools to Skills (scripts) |
5. The L3 Orchestration and Control Layer
5.1. Positioning of the Layer
The question L3 answers is: in what order to act, who does what, and how to recover after an interruption. The main orchestration forms and their applicability:
| Form | Applicable To | Representative |
|---|---|---|
| Single loop (Agent Loop) | General tasks; the model decides the next step autonomously | ReAct loop, Claude Code main loop |
| Plan-then-execute (Plan-and-Execute) | Long-cycle tasks requiring global planning | Claude Code Plan Mode, the three-agent architecture |
| Directed acyclic graph / workflow | Business processes with high determinism requirements | DAG / Workflow engines, Google ADK SequentialAgent |
| Sub-agent dispatch | Complex research tasks that can be explored in parallel | Sub-agent architectures, multi-agent research systems |
5.2. The Agent Loop and the Dual-Agent Architecture for Long-Running
Anthropic's "Effective harnesses for long-running agents" (Tier A) disclosed the first-generation official solution for long-running tasks: the dual-agent division of labor of Initializer Agent + Coding Agent.
Artifacts of the Initializer Agent (the handoff package)
| Artifact | Purpose |
|---|---|
init.sh | Environment startup script, ensuring every new session can bring up a runnable environment with one command |
claude-progress.txt | Progress file, carrying "how far it got" across sessions |
| Initial git commit | Provides a rollback base point |
| JSON feature list | A feature list with a passes boolean field, serving as the master ledger of the task |
One hard rule established by that generation of architecture: removing or modifying tests is unacceptable.
The three opening steps of the Coding Agent's session (officially stipulated, Tier A)
- Run
pwdto confirm the current working directory; - Read the git log and the progress file;
- Read the feature list and select the highest-priority unfinished item.
Session-end constraint: the environment must be left in a mergeable clean state.
5.3. Plan-and-Execute and the Three-Agent Architecture
Anthropic's "Harness design for long-running application development" (2026, Tier A) disclosed the second-generation official solution: the Planner / Generator / Evaluator three roles, whose design inspiration clearly comes from generative adversarial networks (GANs).
| Role | Responsibility | Official Detail |
|---|---|---|
| Planner | Turns 1~4 high-level prompt sentences into a complete product specification | Deliberately stays high-level, does not touch implementation details |
| Generator | Implements one feature per sprint, self-evaluates first, then hands off to the Evaluator | Constrained by the Sprint Contract |
| Evaluator | Scores four items: product depth, functionality, visual design, code quality | Each item has a hard threshold; if any falls below the threshold the iteration fails, and detailed failure reasons are returned to the Generator |
Three key mechanisms
- Sprint Contract: before coding, the Generator proposes "what to build + how to verify success", and the Evaluator reviews and reaches consensus. Agree on the definition of "done" before starting — this is the most important process design in this layer.
- self-evaluation bias (self-praise): officials observed that agent self-evaluation will "confidently praise" work that is clearly mediocre in human eyes. This is precisely the fundamental reason for separating the Evaluator (see section 7.2 for details).
- context anxiety: when an agent's context approaches its limit, it tends to wrap up hastily and declare completion early.
Open question (officially acknowledged, Tier A): Anthropic explicitly states that "whether a single general-purpose coding agent is always optimal, or a multi-agent architecture split into specialized agents for testing, QA, cleanup, etc. is better — this is currently unclear".
5.4. Sub-agent Dispatch
The multi-agent research system (Anthropic "How we built our multi-agent research system", 2025, Tier-A project, URL flagged as unverified) provides the official dispatch pattern:
- The main agent holds the high-level plan and is responsible for coordination;
- Sub-agents do deep technical work or information retrieval within clean context windows;
- Sub-agents only return 1,000~2,000-token summaries (same-source parameter as section 3.5);
- Significantly outperforms a single agent on complex research tasks.
The trade-off against kernel-level variability (uncertainty) is: parallelism in exchange for summary loss.
5.5. State Machines and Deterministic Workflows
Google ADK (released 2025-04-09, Apache 2.0, Python first, v1.0.0 on 2025-05-20, Tier A) provides another route: making orchestration into declarable primitives.
| Primitive Category | Content |
|---|---|
| Agent | Orchestration body |
| Tools | Executable actions |
| Sessions | Session state |
| Runners | Execution drivers |
An important feature of ADK is the coexistence of determinism and dynamism:
- Deterministic workflow agents:
SequentialAgent/ParallelAgent/LoopAgent; - LLM-driven dynamic routing: the transfer mechanism of
LlmAgent.
ADK also has a built-in evaluation harness (AgentEvaluator.evaluate()), capable of dual-scoring the final response and the step-by-step trajectory, and consuming third-party framework tools via LangchainTool / CrewaiTool adapters, supporting MCP, A2A, and OpenAPI.
5.6. Interruption and Recovery
Both the community and officials have isomorphic practices of "letting agents iterate continuously". Anthropic's engineering blog mentions methods for letting agents iterate continuously via hooks or scripts; the community practice (such as the Ralph Wiggum Loop, Tier B) works as follows:
Intercept the model's exit attempts via hooks, re-inject the original prompt in a clean context window, and force the agent to continue working around the completion goal.
The premise for this method to hold is the file system: each iteration starts from a fresh context, but reads the state left behind by the previous one. This is essentially the same "external state + clean context" idea as the dual-Agent architecture in section 5.2; the only difference is whether the driver is another agent or a hook.
5.7. Design Trade-offs
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Single Agent vs Multi-Agent | Context coherence vs parallelism and clean windows | Anthropic officially acknowledges "currently unclear"; recommends per-task A/B testing |
| Planning granularity | Planner gives full detail (stable but rigid execution) vs deliberately staying high-level (flexible but possibly off-target) | Official choice: Planner deliberately stays high-level |
| Determinism vs flexibility | State machines are reproducible vs LLM routing is highly adaptive | Business processes choose the former, exploratory tasks choose the latter; ADK's answer is both coexist |
| Cost vs quality | Multi-Agent is obviously more expensive | Comparison experiments show (Tier C): single Agent 20 minutes / $9 / unusable output; three Agent 6 hours / $200 / complete playable output |
5.8. Failure Modes
| Failure Mode | Manifestation | Countermeasure |
|---|---|---|
| Infinite loop | The same action repeats without progress | Iteration cap + anti-drift detection (warn when repeatedly editing the same file) |
| Goal drift | Gradually deviates from the original goal | Sprint Contract + periodic re-injection of the original goal |
| Early completion declaration | Hasty wrap-up under context anxiety | Force checklist-style self-verification before allowing "done" to be output (see section 7.5, LangChain's first change) |
| Dirty environment state | The previous round left behind unclosed half-products | Official hard rule: must return to a mergeable clean state before ending |
| Tests modified to pass | Criteria tampered with to satisfy "done" | Official hard rule: removing or modifying tests is unacceptable |
6. The L4 Memory and State Layer
6.1. Positioning of the Layer
The question L4 answers is: how state is handed off across sessions and across context windows.
Anthropic's official statement of this challenge is highly evocative (Tier A):
Imagine a software project staffed by engineers working shifts, where every new engineer, on arriving for their shift, has no memory of what happened on the previous shift.
This statement also explains why L4 only became an independent concern in the third generation: first- and second-generation task durations still fit within a single context window, so the problem simply does not arise.
6.2. State Handoff Across Context Windows
The complete official handoff scheme (Tier A):
| Handoff Vehicle | Carried Content | Characteristic |
|---|---|---|
claude-progress.txt | Natural-language progress record | Readable, understandable by the model |
| git history | Structured change record | Rollback-able, diff-able |
JSON feature list (with passes) | Master task ledger | Machine-decidable completion degree |
| Initial git commit | Rollback base point | Guarantees each round can return to a known healthy state |
Health check (officially stipulated): before the Coding Agent starts implementing a new feature, it must first run an end-to-end test to confirm the environment is healthy. The official rationale is that the model "tends to declare a feature complete without adequate testing".
Human-level verification (officially recommended): equip the agent with browser automation tools (such as Playwright MCP) so it can verify products like a real person — officials explicitly state this significantly improved performance.
6.3. The Division of Labor Between Compaction and Context Reset
The two are often conflated; officials (Tier A) clearly distinguish them:
| Mechanism | Approach | Advantage | Cost |
|---|---|---|---|
| Compaction | In-place summarization and compression | Preserves continuity | context anxiety remains |
| Context Reset | Clear the context then re-inject | Gives a clean whiteboard | Handoff artifacts must be sufficiently complete, otherwise it is equivalent to amnesia |
The relationship between the two can be understood as: Compaction is symptomatic treatment (slowing decay); Reset is radical treatment (complete debridement), but Reset's cost is transferred to the quality of the handoff in the L4 layer.
6.4. Checkpoints and Artifacts
A distinctive feature of third-generation Harness is: treat Git as the carrier of state and memory, rather than starting a separate memory database. The benefit of this choice is inheriting the entire toolkit already used by human engineering teams (diff, blame, revert, CI); the cost is needing extra conventions on commit granularity and branching strategy.
Anthropic's official approach is to put three things — "ticket + log + code" — together: claude-progress.txt (log) + feature list (ticket) + git (code + version).
6.5. Design Trade-offs
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Natural language vs structured state | claude-progress.txt is flexible but not machine-decidable vs JSON list is machine-decidable but rigid | Official choice: want both |
| Preserve vs reset | Good continuity vs clean | For long tasks, recommend periodic Reset + high-quality handoff package |
| Dedicated memory store vs Git | Strong semantic retrieval vs mature tool ecosystem | The third generation generally takes Git-first, with dedicated memory as a supplement |
6.6. Failure Modes
| Failure Mode | Manifestation | Countermeasure |
|---|---|---|
| Amnesiac restart | Each new session repeats already-completed work | Force the three opening steps: pwd → read log and progress file → read list and pick the highest-priority unfinished item |
| Progress file decay | claude-progress.txt does not match actual git state | Treat git history as the single source of truth; the progress file only summarizes |
| Dirty handoff | The previous round left behind half-products / failing tests | Must return to a mergeable clean state before ending; the next round's opening runs an end-to-end health test |
| Checkpoint granularity out of control | Commits too coarse (cannot roll back) or too fine (noise) | Explicitly agree on commit granularity and branching strategy |
7. The L5 Evaluation and Observability Layer
7.1. Positioning of the Layer
The question L5 answers is: how well it was done, how to judge it, how to regress-test it.
This layer received the highest status elevation in the third generation — the reason can be summarized in one official judgment (Anthropic, Tier A):
"Harness design is key to performance at the frontier of agentic coding."
And the evaluation layer is precisely the only part of the Harness that can answer "did this Harness change actually help". Without L5, Harness engineering cannot form a closed loop and can only tune parameters by intuition.
7.2. First Principle: Separate the Evaluator from the Evaluated
The phenomenon observed by Anthropic officially (Tier A) is the most important design basis for the L5 layer:
When an agent evaluates its own work, it will "confidently praise" it — even when human observers clearly see mediocre quality. This is especially pronounced on subjective tasks without binary criteria (such as design).
The rationale and source of inspiration given officially are worth quoting in full:
Training an independent Evaluator to be skeptical is far easier than making the Generator self-critical. (Inspired by GAN)
Implementation: the Evaluator sets hard thresholds separately for four dimensions — product depth, functionality, visual design, code quality; if any falls below its threshold the iteration fails, and the detailed failure reasons are fed back to the Generator.
Transfer suggestion: this principle also holds for non-coding scenarios. For any subjective-quality agent task, one should set up a judge isolated from the generator, whether it is a rule, a script, or another model.
7.3. External Benchmarks and the Built-in Evaluation Loop
The L5 layer has two mutually irreplaceable components:
| Component | Role | Representative |
|---|---|---|
| External benchmarks | Cross-system horizontal comparison, judging "what rank in the industry" | SWE-bench / SWE-bench Verified, Terminal-Bench |
| Built-in evaluation loop | Regression and CI of one's own tasks, judging "did this change make things worse" | Eval Set, Golden Dataset, Trace analysis, Google ADK AgentEvaluator |
The relationship between the two is irreplaceable: external benchmarks prevent self-congratulation (you can make your own eval all green yet have no competitiveness); the built-in loop prevents regression (external benchmarks can only be run a few times a year and cannot cover private business).
SWE-bench (2023-10-10, 2,294 task instances, 12 Python open-source repositories, ICLR 2024 Oral, Tier A) established the principle of programmatic scoring: pass the tests to pass, "no partial credit for nice-looking code that fails the tests". Terminal-Bench's principle is likewise "either the automated tests pass or they do not".
7.4. Open Observability to the Agent
OpenAI gave a highly inspiring L5 practice in "Harness engineering" (2026-02-11, Tier A): open the observability stack to the agent itself.
| Measure | Detail |
|---|---|
| Start per worktree | Applications can be started independently per git worktree; the agent can obtain its own runtime instance |
| Browser debugging protocol | Chrome DevTools Protocol wired into the agent runtime |
| Expose metrics and logs | Exposed via the local observability stack; the agent can query directly with LogQL and PromQL |
| Example prompt | "Ensure the service starts within 800ms" — turning a performance requirement into a measurable acceptance condition |
The engineering significance of this approach is: feed L5's observability capability back to L1 as context. The agent is no longer a blind-writing black box; it can, like an engineer, look at logs, query metrics, and verify whether its own changes meet the standard.
7.5. The scaffold Effect: Quantifying Harness Differences
The evidence that best demonstrates the value of L5 is quantitative data for the phenomenon "same model, different Harness, different score".
Terminal-Bench (Stanford + Laude Institute, released 2025, Tier-A project) states directly in its methodology:
"Terminal-Bench does not score a model in isolation. Every result is a model plus an agent harness... the leaderboard is a ranking of systems, not of models."
Its v2.0 (released late 2025 to early 2026, 89 tasks, migrated to the Harbor framework, Tier-A project / specific numbers flagged as unverified) has each task reviewed by 3 independent human reviewers; accuracy drops from about 65% at easy difficulty to about 16% at hard, a cross-level drop of about 49% (Tier B).
The following comparison data all come from Tier-B/C sources and are uniformly flagged as unverified, serving only as directional reference:
| Comparison Item | Data | Note |
|---|---|---|
| Factory Droid + GPT-5.3-Codex | 77.3% | Same GPT-5.3-Codex as the next row |
| OpenAI Simple Codex + GPT-5.3-Codex | 75.1% | 2.2 percentage points caused purely by scaffold difference |
| KRAFTON Terminus-KIRA + Claude Opus 4.6 | 74.7% | Same Claude Opus 4.6 as the next row |
| Bigai TongAgents + Claude Opus 4.6 | 71.9% | Differs by 2.8 percentage points |
| LangChain changed only the Harness (same model, same API) | 52.8% → 66.5% | Rank jumped from outside 30th to the top 5 |
The five-item change list behind LangChain's "52.8% → 66.5%" is one of the most transferable pieces of content in the entire document (Tier C, unverified numbers, but the changes themselves have engineering reference value):
- Force checklist-style self-verification before allowing "done" to be said;
- Scan the directory structure before startup and inject environment context;
- Anti-drift detection — warn when repeatedly editing the same file;
- Adjust the reasoning budget — think more for planning and verification, less for implementation;
- Automated failure-mode analysis.
All five items involve no model swap and all belong to Harness engineering. They can be directly ported to other scenarios.
7.6. Design Trade-offs
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Subjective scoring vs binary criteria | Cover subjective tasks vs objectively reproducible | Prefer translating subjective tasks into binary-decidable sub-items; only use Evaluator scoring + hard thresholds when binary decision is truly impossible |
| Evaluation frequency vs cost | Per-step evaluation (expensive but timely feedback) vs end-state evaluation (cheap but hard attribution) | Recommendation: end-state evaluation for short chains, per-sprint evaluation for long chains (Sprint Contract is designed for this) |
| Coverage vs maintenance cost | Larger evaluation sets are more accurate vs harder to maintain | Rather than spreading wide, do "add one regression case for every real failure" |
7.7. Failure Modes
| Failure Mode | Manifestation | Countermeasure |
|---|---|---|
| Self-praise (self-evaluation bias) | Self-evaluation all green, human review fails it | Separate the evaluator from the evaluated |
| Evaluation set overfitting | The agent learns to "game" the eval instead of truly doing well | Rotate evaluation sets periodically; keep a held-out set invisible to the agent |
| Only looking at end-state scores | Knows things got worse but not where | Trajectory-level tracing (e.g., Responses API built-in tracing, ADK step-by-step trajectory scoring) |
| Metrics disconnected from business | Benchmark rose but users feel nothing | Build your own Golden Dataset rather than only chasing public leaderboards |
8. The L6 Governance and Safety Layer
8.1. Positioning of the Layer
The question L6 answers is: what must not be done, how to discover it if done, and what is the spending ceiling. It contains four categories of components — permission model (RBAC), guardrail models, audit logs, and budget guardrails — and acts as a cross-cutting aspect applying constraints to all of L1~L5.
A common misconception that must be clarified: governance slows things down. Anthropic's sandbox evidence gives the opposite conclusion — permission prompts reduced by 84% with improved safety (Tier A). Constraints are not the opposite of autonomy; they are the precondition of autonomy.
8.2. Permission Model and Sandbox Strategy
Layered configuration of governance policy (taking Claude Code as an example, Tier A):
| Level | Configuration Location | Purpose |
|---|---|---|
| Project level | .claude/settings.local.json | Distributed with the repository, shared by the team |
| User level | ~/.claude/settings.json | Personal preferences |
| Organization level | managed settings | Mandatorily pushed down, individuals cannot override |
Key switches include sandbox.enabled, sandbox.failIfUnavailable, allowUnsandboxedCommands, filesystem.allowWrite / denyWrite / denyRead / allowRead. Among these, sandbox.failIfUnavailable can be set to hard failure — if the sandbox cannot start, refuse to run, rather than quietly degrading to non-sandbox mode. This is an important lesson in governance robustness: do not give safety mechanisms a silent degradation path.
8.3. Credential Protection
sandbox.credentials provides protection on two dimensions — files and environment variables (requires v2.1.187+; v2.1.199+ supports mode: "mask"):
| Mode | Behavior | Applicable To |
|---|---|---|
deny | Completely invisible | ~/.aws/credentials, ~/.ssh |
mask | Masked display | tokens that must exist but should not have their values read |
Recommended default deny list: ~/.aws/credentials, ~/.ssh/*, GITHUB_TOKEN, NPM_TOKEN, and various cloud vendor environment variables.
8.4. Mechanical Enforcement of Architectural Constraints
The environment governance practice given by OpenAI in "Harness engineering" (2026-02-11, Tier A) is the most systematic official case for the L6 layer.
Layered dependency rule (unidirectional dependency): within each business domain, code can only depend "forward" —
Types → Config → Repo → Service → Runtime → UI Cross-cutting concerns can only enter through the single Providers interface. This rule is mechanically enforced, rather than relying on verbal code review conventions.
Taste Invariants: statically enforced via a custom linter — structured logging, schema and type naming conventions, file size limits, platform-specific reliability requirements.
The most critical engineering trick among them is: because the linter is self-built, error messages are written as repair instructions injected into the agent context. In other words, the linter does not just "report an error" but "reports an error + teaches the agent how to fix it". This directly converts L6's failure signal into L1's context input, forming a closed loop.
The official summary can be quoted directly:
In human-first workflows, these rules may feel pedantic; with agents, they become multipliers — once codified, they take effect everywhere immediately.
The governance philosophy is analogized as "leading a large engineering platform organization: the center enforces boundaries, the periphery allows autonomy".
8.5. Garbage Collection: Countering Entropy Growth
OpenAI named the third pillar of Harness engineering Garbage Collection, targeting the entropy growth problem after large-scale agent output. Anthropic also explicitly lists "context still decays" as an issue the third pillar must handle.
Specific mechanisms (Tier A):
doc-gardeningagent: periodically scans outdated documentation and automatically initiates repair PRs;- Four major failure modes (officially summarized): ① context is a scarce resource; ② too much guidance becomes no guidance; ③ immediate decay (rot immediately); ④ hard to verify mechanically.
Among these, "too much guidance becomes no guidance" is especially noteworthy: when AGENTS.md is written too long, the agent skips reading it, just like a human. This directly leads to the "AGENTS.md changed from encyclopedia to table of contents" decision in section 10.2.
8.6. Design Trade-offs
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Hard failure vs silent degradation | Availability vs safety certainty | Governance mechanisms should avoid silent degradation (sandbox.failIfUnavailable hard failure) |
| Central enforcement vs local autonomy | Consistency vs flexibility | Official answer: the center enforces boundaries, the periphery allows autonomy |
| Number of rules vs compliance | More rules the better vs too many and they are ignored | Official answer: rules must be few and mechanically enforceable; excessive documentation equals no documentation |
8.7. Failure Modes
| Failure Mode | Manifestation | Countermeasure |
|---|---|---|
| Permission fatigue | Frequent prompts cause users to click approve uniformly | Sandboxing + Auto-allow (official data: −84% prompts) |
| Documentation decay | AGENTS.md / docs disconnected from actual code | doc-gardening agent + bring documentation into CI validation |
| Rules not machine-checkable | Can only rely on verbal review conventions | Self-built linter, error messages written as repair instructions |
| Audit not traceable | After an incident, cannot find out which agent did it | Full-layer tracing + structured logs (enforced as taste invariants) |
| Budget out of control | Long-task cost unpredictable | Budget Guardrail + per-step / per-task cost caps |
9. Harness Loop: The Engineering Structure of the Main Loop
9.1. Definition and Positioning: The Loop is the Heart of the Harness
The previous three chapters dissected the components and trade-offs of each of the six layers layer by layer; this chapter assembles them back into the runtime's overall form: Harness Loop (the agent main loop based on the Harness). The unified definition follows this repository's parameter card and must not be rewritten:
Harness Loop: the agent main loop carried by the Harness — the agent iterates within the runtime provided by the Harness as "goal assembly (L1) → planning (L3) → tool execution (L2) → observation feedback (L5) → state update (L4) → re-planning", until the termination condition is met or the governance boundary (L6) is triggered.
Three official statements from the two leading vendors, Anthropic and OpenAI, are highly consistent with this definition (Tier A):
| Vendor | Official Statement | Source |
|---|---|---|
| Anthropic | gather context → take action → verify work → repeat | "Building agents with the Claude Agent SDK", 2025 |
| Anthropic (Claude Code team) | "loop = the agent repeatedly executes work cycles until the stop condition is met" | "Loop engineering: Getting started with loops", 2026-06-30 |
| OpenAI | "the reusable part is the agent loop"; harness = the execution system around the model (understand the task, maintain context, inspect information, invoke tools, expose progress, handle failures, request human approval, return results) | "Codex as a platform", 2026 |
The core proposition of this chapter is: the Loop is the heart of the Harness, not an attribute of the Agent. A bare loop detached from the Harness (bare ReAct) only has L2 tool execution; the characteristic of the Harness Loop is that every turn is assembled by L1, observed by L5, booked by L4, and constrained by L6. This correspondence is shown in Figure 9-1.
图 9-1|Harness Loop 单圈结构与六层模型对应
示意图:基于本文分析,机制依据三家官方循环描述(A 级,信息截止 2026-09-12)。
9.2. Single-Turn Structure: Isomorphism of the Three Official Implementations
Whether Claude Code, Codex, or Gemini CLI, a single turn (one iteration) has the same structure: context assembly → model reasoning → tool invocation → result verification and backflow. This is the direct engineering embodiment of "the Loop is the heart of the Harness" — the heart beats in an isomorphic way; the differences lie only in the valves (confirmation gates, approval gates) and the loop's exit conditions.
Anthropic Claude Agent SDK's official five-step definition ("How the agent loop works", Tier A):
- Receive the prompt (including system prompt, tool definitions, session history);
- Claude evaluates and responds (text or tool invocation);
- The SDK executes tools and collects results;
- Steps 2~3 repeat; each completed full cycle is one turn;
- Output the final response containing no tool invocations, together with the ResultMessage (including token usage, cost, session ID).
Loop termination criterion = producing a response containing no tool invocations.
OpenAI Codex's official loop description ("Unrolling the Codex agent loop", Tier A): user input → assemble prompt → reason → the model either produces a final assistant message (loop termination signal) or requests a tool invocation → the Agent executes the tool and appends the output to the prompt → re-query. A single turn can contain multiple rounds of "reasoning—tool" iteration; officials explicitly point out that context window management is one of the agent's (harness's) responsibilities — this is precisely the evidence that L1 is written into the loop.
Gemini CLI's ReAct loop (Tier B, official repository documentation consistent with multiple sources): the cli initiates reasoning → the model returns a ToolCallRequest → CoreToolScheduler four steps (queue / validate / confirm / execute; sensitive operations are suspended at the confirmation gate awaiting user UI confirmation) → tool results are packaged back to the model via the callback chain → a new round of reasoning. Loop termination: the model invokes the explicit complete_task tool, or a termination condition such as timeout / error is triggered.
Difference points within the isomorphism (Tier B, community source-code-level dissection):
| Implementation | Loop Exit | In-Loop Protection Mechanism |
|---|---|---|
| Claude Code / Agent SDK | Response without tool invocations; max_turns / max_budget_usd hard caps | Pre-exit recovery path: context folding → reactive compression → double the output budget and retry; only exit for real when all fail |
| Codex harness | Assistant message; approval gate and sandbox boundary | Multiple reasoning—tool iterations within a turn; retained reasoning + context compression |
| Gemini CLI | complete_task explicit termination | CoreToolScheduler confirmation gate (in-session whitelist exempt from repeated confirmation); 1M-token long context |
9.3. Cross-Turn Mechanisms: Five Classes of Control Flow
Above the single turn, the Harness Loop relies on five classes of cross-turn mechanisms to maintain the sustainability of long tasks (based on Anthropic's official engineering blog and each framework's documentation; annotations inline):
| Mechanism | Approach | Points To | Evidence Tier |
|---|---|---|---|
| Compaction | Automatically summarize historical messages when approaching the context limit; the Agent SDK explicitly marks compaction boundaries with the compact_boundary message type | Back to L1 | A |
| Context Reset | Clear the context, swap in a new Agent, and continue via structured handoff artifacts; officials use it to govern "context anxiety" and self-evaluation bias — distinct from Compaction's in-place summarization | Back to L1 | A |
| Plan revision | The main Agent aggregates sub-agent results and decides whether to dispatch more or revise strategy; Claude Code supports injecting instructions mid-task for real-time redirection | Back to L3 | A (redirection mechanism details are community reverse-engineering, B) |
| Sub-agent dispatch | Parallel + independent context windows, only condensed summaries returned; officials give effort-scaling rules graded by task complexity: simple facts 1 agent with 3~10 tool calls, comparison-type 2~4 sub-agents with 10~15 each, complex research 10 or more sub-agents | Side-loop | A |
| Checkpoint persistence | Progress file + git history + feature list handed off across sessions; MAF Workflow native checkpointing; LangGraph Checkpointer writes to disk at each superstep | Back to L4 | A / B |
Two key mechanisms are institutionalized in Anthropic's "Harness design for long-running application development" (2026, Tier A): Sprint Contract — before coding, the Generator and Evaluator negotiate the definition of "done", giving each turn's observational verification (L5) a basis; Context Reset — replacing "summarize + continue" with "clear + hand off", transferring the cost to the quality of the L4 handoff (for the detailed division of the two mechanisms, see section 6.3).
The quantified benefits of cross-turn mechanisms are supported by official hard data: OpenAI's "Codex as a platform" (2026, Tier A) disclosed that on the ARC-AGI-3 benchmark, retained reasoning + context compression raised GPT-5.6 Sol's score from 13.3% to 38.3%, while reducing output tokens by 6× — this is the most forceful official number for "Harness design directly changes outcomes" (information as of 2026-09-12).
The overall shape of cross-turn control flow and the tiering of termination conditions is shown in Figure 9-2.
图 9-2|跨圈控制流与终止条件分级
示意图:基于本文分析,终止条件口径沿用本库参数卡统一分级(信息截止 2026-09-12)。
9.4. Termination Condition Tiering and the Triple Hard Limits
"When does the loop stop" is not an implementation detail but the core contract of the Harness. The unified criterion divides termination conditions into five tiers (corresponding to Figure 9-2):
| Tier | Termination Condition | Official Mechanism | Evidence Tier |
|---|---|---|---|
| ① | Task completion judgment (DoD check) | Final response without tool invocations (Anthropic / OpenAI); complete_task tool (Gemini CLI); /goal verified by an independent evaluation model against verifiable completion criteria; if unmet, sent back to continue | A / B |
| ② | Budget exhausted | The Anthropic SDK's max_budget_usd cost threshold; dynamic workflows can explicitly set a token budget (e.g., "use 10k tokens"); industry practice is a per-task dollar cap | A / B |
| ③ | Permission boundary triggered | Claude Code hooks can intercept, modify, or block invocations before tool execution; Codex approval tiers (untrusted / on-request / never) × sandbox tiers (read-only / workspace-write / danger-full-access); the OpenAI Agents SDK's guardrail tripwire throws an exception and terminates when triggered | A |
| ④ | Human interruption (HITL) | LangGraph's interrupt_before suspends awaiting human continuation (recoverable with Checkpointer); Gemini CLI's shouldConfirmExecute confirmation gate; the OpenAI Agents SDK's RunState supports recovering interrupted runs | A / B |
| ⑤ | Dead-loop detection / expiry | max_turns exceeded throws MaxTurnsExceeded (OpenAI SDK); LangGraph recursion_limit defaults to 25, exceeding throws GraphRecursionError — the official forum positions it as "a circuit breaker rather than business logic"; Claude Code's /loop periodic tasks auto-expire after 7 days | A / B |
Beyond the tiering, industry practice has distilled a set of triple hard-limit empirical values (Tier C, industry practice compilation, directional reference only):
| Hard Limit | Empirical Value | Corresponding Failure Form |
|---|---|---|
| Iteration cap | Simple Q&A 10 / research-type 25 / coding-type 50~100, set at 2~10× the p95 legitimate task | Infinite loop |
| Token budget | 10× the mean of legitimate tasks; warn at 80% budget consumption rather than only at exhaustion | Cost storm |
| Wall-clock timeout | 2~3× the p95; warn when token generation speed drops to 1/3 of baseline | Process hang |
The triple hard limits each connect to a different failure form; none can be missing; when exceeded, partial results (a progress summary) should be returned rather than a bare error. There is also one structural conclusion (industry practice, Tier C): the kill switch must be placed at the gateway layer with a unique ID — an escaped agent will not honor the limits in its own code.
9.5. Framework Loop Semantics Comparison
Beyond the generic Harness, there is a clear genealogy across frameworks' loop semantics: from "structure decides when to stop" (bounded loops on visualization platforms) to "the model decides when to stop + governance as backstop" (autonomous loops in coding Agents).
| Implementation | Loop Carrier | Stopping Semantics | Cross-Turn Persistence | Belonging Layer |
|---|---|---|---|---|
| Claude Code / Agent SDK | Single main loop + sub-agents | Response without tool invocations / max_turns / budget / hooks interception | Compaction + session and progress files | Full L1~L6 ring |
| Codex harness | agent loop (core runtime) | Assistant message / approval gate / sandbox boundary | Thread persistence + retained reasoning | Full L1~L6 ring |
| Gemini CLI | cli-driven + core-executed ReAct loop | complete_task / confirmation gate | Session history | Mainly L2 / L3 |
| OpenAI Agents SDK | Runner loop | final_output / max_turns / guardrail tripwire | RunState / Session | Mainly L3 |
| LangGraph | Explicit state-machine graph loop (nodes + conditional edges) | Conditional edge to END / recursion_limit (default 25) | Checkpointer writes to disk at each step by thread_id, recoverable from checkpoints | L3 / L4 |
| AutoGen / MAF | Session message loop → typed graph workflow | Termination condition / max_turns / conditional exit edge | MAF checkpointing / AgentThread | L3 / L4 |
| Dify | Iteration / Loop two node types | Array length (Iteration) or loop_count + break_conditions (Loop) | Variable pool snapshot / loop_variables inherited across rounds | L3 |
| n8n / Coze | Visual loop nodes | Bounded iteration (structural boundary, not an LLM stopping condition) | Inter-node variables | L3 |
Three semantic differences worth expanding on (source tiers annotated in the table):
- LangGraph: exceeding the limit is not death but a recoverable pause (Tier B, source-code corroboration). The GraphRecursionError triggered by recursion_limit, together with the Checkpointer, can recover from the last persisted state or raise the budget to continue — "a circuit breaker rather than business logic".
- AutoGen → MAF: from implicit message loop to explicit graph loop (Tier B). AutoGen's GroupChat has unpredictable loops and ambiguous termination conditions due to LLM speaker selection, allowing infinite loops — this is the direct driver of the "implicit message loop → explicit typed graph" evolution; MAF's Workflow provides typed loop steps, checkpointing, HITL, and a middleware pipeline (including token budget enforcement). Community comparison data show MAF's explicit conversion reduces LLM calls by 23% versus GroupChat (Tier B, third-party paraphrase).
- Dify: iteration decided by data, looping decided by conditions (Tier B, source-code-level documentation). The Iteration node traverses an array, materializing an independent sub-engine per element; parallelism defaults to 10, per-node maximum iteration defaults to 100, with three-tier error handling (TERMINATED / CONTINUE_ON_ERROR / REMOVE_ABNORMAL_OUTPUT); the Loop node consists of loop_count maximum count + break_conditions stopping criteria + loop_variables inherited across rounds. The visualization platform is a representative sample of replacing "the LLM decides when to stop" with structural bounded loops; n8n / Coze loop nodes belong to the same pattern (their official first-hand loop documentation was not directly obtained; see section 13's gap statement).
9.6. Failure Modes and Governance
Loop failure modes named officially (Anthropic engineering blog, Tier A): doing too much at once (one-shot), premature completion declaration (premature completion), context anxiety, self-evaluation bias (self-praise), and early multi-agent systems' "50 sub-agents + infinite searching for nonexistent sources + progress inflation among themselves". Most of these failure modes were already expanded from the L3 perspective in section 5.8; this section focuses on the distinctive form of overall loop loss of control.
Representative incident: multi-agent ping-pong loss of control (Tier B, source annotated verified: partial — multiple posts consistent but no named victim company; for reference as a representative case only): an incident post-mortem circulating in the industry recorded a loss of control in a four-agent market research pipeline (LangChain + A2A): the Analyzer and Verifier agents fell into a "produce—nitpick—revise" ping-pong loop; with no shared budget and no round-trip counting, weekly API spend rose from $127 to $891, $6,240, $18,400 in sequence, and was manually shut down at $47,000 after 264 hours. The post-mortem identified two root causes: no per-agent budget cap; no mechanism to terminate the session before the next API call. The common lesson is: the party making the invocation decision cannot see the cost of the next invocation.
Three failures of application-layer throttling (industry practice, Tier C): ① framework bypass — code calls the LLM API directly, circumventing framework limits; ② exception swallowing — MaxIterationsExceeded is silently swallowed by except and the loop continues; ③ process restart resets counters — after a crash-restart, the loop accumulates cost across lifecycles. The conclusion drawn aligns with section 8.5's sandbox.failIfUnavailable hard failure: hard boundaries should sit at the infrastructure layer (gateway / proxy), not in the agent's own code.
Loop telemetry: Codex natively supports OpenTelemetry log export (Tier A); exported events include user prompts, approval decisions, tool execution results, MCP usage, and network proxy allow / block events, integrable with SIEM and compliance log platforms; on the Anthropic side, the ResultMessage carries token usage, cost, and session ID, and /usage, /goal with no arguments, and /workflows provide skill / sub-agent / MCP-level usage observability (Tier A). The community observability scheme (Tier B) gives a generic model: OTel span tree = session → step → LLM call, with core metrics of per-step latency percentiles (P50 / P95 / P99), per-session tokens, cost split by model and step, and error rate and retry frequency; a common heuristic alarm is "suspected loop after more than 10 steps".
Governance practice checklist (mainly Tier A):
| Governance Measure | Content | Source |
|---|---|---|
| Hooks interception | Intercept / modify / block invocations before tool execution | Anthropic, A |
| Sprint Contract | Reach a contract on the definition of "done" before coding, giving observational verification a basis | Anthropic, A |
| /goal turn cap | Evaluation-model verification + explicit turn cap (e.g., "stop after 5 tries") | Anthropic, A |
| /loop auto-expiry | Periodic tasks auto-expire 7 days after creation, preventing forgotten loops from persisting | Anthropic, A |
| Sandbox × approval orthogonal | Sandbox tiers define the technical boundary; approval policy decides when to ask; Auto-review auto-passes low risk and halts high risk | OpenAI, A |
| OTel audit telemetry | Full export of prompts, approval decisions, tool results, network events | OpenAI, A |
| Budget as default | Officials recommend "a budget cap is a good default for production agents" | OpenAI / Anthropic documentation, synonymous statements, A |
10. Key Leaps from Second to Third Generation
10.1. The Six-Item Leap List
Synthesizing the six layers above, the third generation underwent six structural leaps relative to the second:
| # | Leap | Second-Generation Approach | Third-Generation Approach | Key Evidence (Tier) |
|---|---|---|---|---|
| 1 | Context from "natural growth" to "active governance" | Context accumulates naturally with the conversation | The four-piece set: compression, externalized notes, sub-agent isolation, progressive disclosure | Anthropic context engineering blog (A) |
| 2 | Tools from "vendor-proprietary" to "neutral standard" | Function Calling / plugins (proprietary) | MCP → AAIF neutral governance | MCP release, AAIF founding (A) |
| 3 | Evaluation from "bolted-on leaderboards" to "built-in loop" | Run a public leaderboard once and check the score | Built-in tracing + Evaluator role + feedback backflow to L1 | Responses API built-in tracing, three-Agent architecture (A) |
| 4 | State from "in-session" to "cross-window handoff" | Amnesia at session end | Progress file + git + feature list + health pre-check | Two generations of long-running harness (A) |
| 5 | Governance from "manual prompting" to "sandbox and mechanical enforcement" | Per-item permission popups | Dual-dimension isolation + credential protection + self-built linter injecting repairs | Claude Code sandbox (A, −84% prompts) |
| 6 | Role from "human commanding" to "human steering" | Human commands each action step by step | Human Steer, Agent Execute | OpenAI "Harness engineering" (A) |
The sixth item is the philosophical core of the whole leap: human work moves up from "operating" to "designing environments, feedback loops, and control systems" (OpenAI original: "Our most difficult challenges now center on designing environments, feedback loops, and control systems.").
10.2. Complete Paradigm Sample: OpenAI's Million-Line Code Experiment
The most complete public evidence of the third-generation Harness is the internal experiment disclosed in OpenAI's "Harness engineering" (2026-02-11, Tier A). The following numbers are all first-hand and can be quoted in full:
| Metric | Value |
|---|---|
| Starting point | First commit to an empty repository in late 2025-08; the scaffold (repository structure, CI, formatting rules, package manager, application framework) was generated by Codex CLI + GPT-5, including the initial AGENTS.md, which was also written by Codex |
| Code volume after five months | About 1 million lines (application logic, infrastructure, tools, documentation, internal developer tools) |
| PR count / engineer count / per-capita daily PRs | About 1,500 / 3 engineers (later expanded to 7) / 3.5 |
| Time cost | About 1/10 of hand-writing |
| Hand-written code by humans | 0 lines |
| Longest single-task runtime | Over 6 hours |
Note a counterintuitive observation: throughput actually rose after the team expanded from 3 to 7 people — this contradicts the traditional software engineering intuition that "adding people worsens PR conflicts", indicating that this Harness's coordination overhead is lower than the output brought by the added headcount.
Six key engineering decisions and their corresponding layers
| Decision | Content | Belonging Layer |
|---|---|---|
| AGENTS.md changed from encyclopedia to table of contents | About 100 lines injected into context; the real knowledge lives in structured docs/ (design-docs / exec-plans / product-specs / references / DESIGN.md / FRONTEND.md / PLANS.md / PRODUCT_SENSE.md / QUALITY_SCORE.md / RELIABILITY.md / SECURITY.md); official quote: "give Codex a map, not a 1000-page manual" | L1 |
| Linter error messages written as repair instructions | The self-built linter's errors directly inject repair methods into the agent context | L6 → L1 loop |
| doc-gardening agent | Automatically scans outdated documentation and initiates repair PRs | L6 |
| Mechanical enforcement of layered architecture constraints | Unidirectional dependency chain Types → Config → Repo → Service → Runtime → UI; cross-cutting concerns only via Providers | L6 |
| Observability open to the agent | git worktree startup, Chrome DevTools Protocol, LogQL / PromQL queries | L5 → L1 |
| Minimal-blocking merge philosophy | Minimal-blocking merge gate, PRs short-lived, test flakiness resolved by re-running — "the cost of correction is low, the cost of waiting is high" | L3 |
There is also one technology-selection principle worth remembering separately: prefer "boring technology" (composability, API stability, widespread presence in training corpora). The official example is self-building map-with-concurrency rather than introducing p-limit — the rationale is that models handle "things widely present in training corpora" better.
This principle is universal for all Harness design: in systems where agents write code, the technology's "model familiarity" is a real selection metric, alongside performance and ecosystem.
10.3. The Parts of the Leap Not Yet Completed
The third generation is far from the endpoint. The following problems are officially acknowledged as unresolved (Tier A):
- The single-Agent vs multi-Agent debate is undecided — Anthropic explicitly states "currently unclear";
- Cross-domain generalization unverified — whether the above experience can generalize to other long-cycle tasks such as scientific research or financial modeling; "the answer is still being explored";
- The Harness itself lacks evaluation methods — the open question raised on martinfowler.com: we need Harness coverage and quality evaluation methods analogous to code coverage and mutation testing (not yet appeared);
- Entropy governance still relies on patches — doc-gardening is a remedy for decay, not a root cure for decay.
11. Harness Capability Maturity Self-Assessment Table
11.1. Construction Notes for the Self-Assessment Framework
Important note: the table below is an analysis framework constructed independently by this project based on the aforementioned public materials, not a specification published by any standards organization, nor an official model from any vendor. Its value lies in providing an actionable yardstick to help organizations locate their own Harness capability and perform generational alignment. Please do not use it as a compliance basis or an industry benchmark.
The framework defines five levels (0~4) for each of the L1~L6 layers and gives the identifiable characteristics of each level.
11.2. Five-Level Definitions
| Level | Name | Generic Definition |
|---|---|---|
| L0 | Missing | The layer does not exist or fully depends on humans; problems are not systematically noticed |
| L1 | Manual | Practices exist, but rely on human execution and conventions to maintain; not reproducible, not regression-testable |
| L2 | Tool-based | Dedicated tools or components exist; can execute automatically, but lack governance policy |
| L3 | Systematized | Clear policy and default architecture; can be measured and can regress in CI |
| L4 | Closed-loop autonomous | The layer's output automatically flows back to improve other layers; possesses anti-entropy mechanisms (auto-correction, automatic documentation governance) |
11.3. Self-Assessment Table
| Layer | L0 Missing | L1 Manual | L2 Tool-based | L3 Systematized | L4 Closed-loop Autonomous |
|---|---|---|---|---|---|
| L1 Context Engineering | Context accumulates naturally, no management | Manually selecting and pasting context | Connected to RAG / retrieval | The four-piece set of compression + externalized notes + sub-agent isolation + progressive disclosure; has attention budget awareness | Context assembly strategy automatically adjusted by L5 feedback; Skills and docs auto-trimmed and updated |
| L2 Tooling and Execution | The model can only output text | A few hard-coded tools | Function Calling + several proprietary tools | Tools standardized via MCP; running in a dual-dimension isolated sandbox (filesystem + network) | Toolset automatically added/removed based on usage data and failure feedback (e.g., Vercel-style subtraction institutionalized) |
| L3 Orchestration and Control | Single-turn invocation | Manually chaining processes | Orchestration framework single loop | Supports long-running, Sprint Contract, sub-agent dispatch, determinism + dynamic routing coexisting | The orchestration structure itself can be evaluated and auto-selected; can perform failure-mode analysis on itself |
| L4 Memory and State | Amnesia at session end | Manually writing handoff notes | Has session persistence | Progress file + git + machine-readable task list + opening health pre-check | State handoff automatically verified; dirty state auto-repaired before the next round opens |
| L5 Evaluation and Observability | Relies on human eyes to see results | Manual spot checks | Occasionally runs public benchmarks | Built-in tracing + self-built Golden Dataset + one regression case added for every real failure | Evaluator separated from the evaluated and Evaluator evolves independently; held-out set prevents overfitting; observational data fed back to L1 |
| L6 Governance and Safety | No boundaries | Per-item human approval | Has permission configuration | Sandbox + credential protection + self-built linter mechanical enforcement; failIfUnavailable hard failure; center enforces boundaries, periphery autonomous | Governance rules can be understood by the agent and self-repaired (error message is the repair instruction); entropy growth continuously auto-governed (doc-gardening) |
11.4. Result Interpretation
| Score Pattern | Reading | Suggested Action |
|---|---|---|
| Most layers at L0~L1 | Does not yet have a third-generation Harness; at early second generation | Prioritize building L2 (tool standardization) and L5 (at least a regression set); defer other layers |
| Most layers at L2 | Typical "tools are complete but unstable" state | Prioritize attacking L1 (context governance) and L6 (sandbox); these two are the most common bottlenecks |
| Most layers at L3 | Reached third-generation mainstream level | Focus is on maintaining: build this Harness's regression mechanism to prevent degradation as models upgrade |
| L4 layers appear | At frontier exploration | Note the risk pointed out in 04-Future Development: excessive Harness complexity may be directly flattened by the next model upgrade |
| Inter-layer gap ≥ 2 levels | Structural weakness exists | The weak layer determines the overall ceiling; prioritize filling it |
The item inter-layer gap ≥ 2 levels is especially important. The Harness's overall output is limited by the weakest layer, not the strongest — this is consistent with the bucket effect in software systems. For example, a system whose L1 is only at level L1 (manually pasting context) but whose L2 reaches level L3 will often perform worse than a system where both are at level L2.
11.5. Usage Recommendations
- Self-assess once every six months, and record the results for comparison — the value of the self-assessment itself lies in longitudinal comparison, not horizontal scores.
- Give specific evidence layer by layer during assessment; do not write abstract "medium"; write "our context compaction relies on XXX".
- Prioritize the weakest layer, not the average score.
- Be wary of "evaluation inflation": when a layer is rated L3 but has no regression-testable evidence (e.g., no Golden Dataset), it should be downgraded back to L2.
12. Conclusion
The architecture of the third-generation Harness can be summarized in one sentence: it is a system that narrows the model's output distribution, through a six-layer structure, into the engineeringly acceptable interval.
- L1 decides what the model sees — the key bottleneck is the attention budget; the core means is deletion, not addition;
- L2 decides what the model can do — MCP solved the connection standard; the sandbox solved the side-effect boundary;
- L3 decides in what order to act — from a single loop to the division of labor among Planner / Generator / Evaluator;
- L4 decides what to remember — Git became the mainstream state carrier; cross-window handoff is the lifeline of long tasks;
- L5 decides how well it was done — the first principle is separating the evaluator from the evaluated;
- L6 decides what must not be done — governance is not the enemy of speed; official evidence is an 84% reduction in permission prompts.
And what strings the six layers together is nine characters: visible, stable, regressable.
The question for the next stage is: will this architecture be directly absorbed by stronger models? For the two-sided answer to this question, see section 2.1 of 04-Future Development.md; for a comprehensive judgment on the entire development stage, see 05-Conclusion.md.
13. Information Gap Statement
This section summarizes the information gaps involved in this document; they have been marked in the corresponding places in the body or explained with source tiers.
Gaps already existing in this research, reusable across sources
- The exact URL and publication date of Anthropic's "How we built our multi-agent research system": cited only in link form in the context engineering blog; unverified.
- Differing wording on MCP's "first public specification version": two criteria coexist — 2024-11-05 (the Ruby SDK records it as Initial protocol revision) and 2024-11-25 (public announcement and ecosystem launch); this document presents them in parallel.
Numbers with insufficient source tiers; already flagged in this document
- Section 3.10: context degradation's "performance drop exceeding 45%" and Chroma Research's "all 18 frontier models degraded".
- Section 4.6: Codex CLI's "about 95% Rust in early 2026", Auto-review's "1/200" and "99%", and the review model type "GPT-5.4 Thinking".
- Section 4.7: Vercel's tool count 15 → 2 accuracy 80% → 100%, Token −37%, speed 3.5×.
- Section 5.7: the comparison experiment numbers for Anthropic single Agent (20 minutes / $9 / unusable) vs three Agent (6 hours / $200 / complete and playable).
- Section 7.5: all Terminal-Bench 2.0 leaderboard numbers (77.3% / 75.1% / 74.7% / 71.9%), LangChain 52.8% → 66.5%, and the easy about 65% → hard about 16% difficulty gradient.
- Section 7.5: the Terminal-Bench official site's (tbench.ai) current leaderboard data was not directly scraped; all are third-party paraphrases.
Items not covered in this document but belonging to this module's common gaps
- ISO/IEC agent interconnection international standard number: no authoritative information currently.
- First appearance of the term "Agent Harness": no authoritative information currently.
- Claude models' 2026 version timeline: seen only in third-party GitHub timeline repositories; flagged as unverified.
Newly added this round (Chapter 9, Harness Loop)
- The specific publication dates of OpenAI official blog posts such as "Unrolling the Codex agent loop", "Unlocking the Codex harness", and "Codex as a platform" were not directly returned in the search results (sections 9.2 / 9.3).
- The $47,000 multi-agent ping-pong loss-of-control case is verified: partial (multiple posts consistent, no named victim company); the body has phrased it as "a representative incident post-mortem circulating in the industry" and retained the numbers (section 9.6).
- The industry triple hard-limit empirical values (iteration cap 10 / 25 / 50~100, token budget 10× the mean, wall-clock timeout 2~3× the p95) are an industry practice compilation (Tier C); directional reference only (section 9.4).
- n8n / Coze loop nodes lack independent first-hand official documentation; only indirectly covered via the common bounded-loop pattern of visualization workflows (section 9.5).
- MAF reducing LLM calls by 23% versus AutoGen GroupChat is a third-party paraphrase (Tier B); the official first-hand manuscript was not directly hit (section 9.5).
For the complete list, see section 9 of 06-References.md.
14. References
- Effective context engineering for AI agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Effective harnesses for long-running agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
- Harness design for long-running application development — Anthropic, 2026. https://www.anthropic.com/engineering/harness-design-long-running-apps
- Equipping agents for the real world with Agent Skills — Anthropic, 2025-10-16. https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills
- Introducing Agent Skills — Anthropic, 2025-10-16 (2025-12-18 open standard update). https://www.anthropic.com/news/skills
- Sandboxing: a safer and more autonomous approach — Anthropic, 2025. https://www.anthropic.com/engineering/claude-code-sandboxing
- Claude Code official documentation · Sandboxing (Chinese edition) — Anthropic, 2026. https://code.claude.com/docs/zh-TW/sandboxing
- Claude Code official documentation · Choose a sandbox environment — Anthropic, 2026. https://code.claude.com/docs/en/sandbox-environments
- Introducing the Model Context Protocol — Anthropic, 2024-11-25. https://www.anthropic.com/news/model-context-protocol
- Harness engineering: leveraging Codex in an agent-first world — OpenAI, 2026-02-11. https://openai.com/index/harness-engineering/
- Harness engineering (Chinese edition) — OpenAI, 2026-02-11. https://openai.com/zh-Hans-CN/index/harness-engineering/
- New tools for building agents (Responses API + Agents SDK) — OpenAI, 2025-03-11. https://openai.com/blog/new-tools-for-building-agents
- Agent Development Kit: Making it easy to build multi-agent applications — Google, 2025-04-09. https://googledevelopers.blogspot.com/en/agent-development-kit-easy-to-build-multi-agent-applications/
- A year of open collaboration: Celebrating the anniversary of A2A — Google Open Source Blog, 2026-04-16. https://opensource.googleblog.com/
- Agent Development Kit — AI Wiki, 2026. https://aiwiki.ai/wiki/google_adk
- Model Context Protocol official site and specification — MCP / AAIF, 2024—2026. https://modelcontextprotocol.io/; https://modelcontextprotocol.io/specification/2026-07-28/
- MCP Protocol Versions (version evolution table) — MCP Ruby SDK, 2026. https://ruby.sdk.modelcontextprotocol.io/protocol-versions/
- MCP Rust-layer protocol version enumeration — mcpkit (docs.rs). https://docs.rs/mcpkit/latest/enum.ProtocolVersion.html
- Model Context Protocol entry (including specification evolution) — Klu. http://klu.ai/glossary/model-context-protocol
- Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF, 2025-12-09. https://aaif.io/
- Harness engineering for coding agent users — Birgitta Böckeler, martinfowler.com, 2026. https://martinfowler.com/articles/harness-engineering.html
- SWE-bench: Can Language Models Resolve Real-World GitHub Issues? — Jimenez, Yang et al. (Princeton), 2023-10 (ICLR 2024 Oral). https://www.swebench.com/
- Terminal-Bench — Stanford / Laude Institute, 2025. https://www.tbench.ai/
- Context engineering entry (naming chain and four pillars) — AI Wiki, 2025—2026. https://aiwiki.ai/wiki/context_engineering
- OpenAI Codex entry (sandbox primitives, approval modes, Rust rewrite) — AI Wiki, 2026. https://aiwiki.ai/wiki/codex
- Agent Harness: the core paradigm of AI engineering in 2026 — 腾讯云开发者社区, 2026. https://developer.cloud.tencent.com/article/2698416
- Terminal-Bench: The CLI Autonomy Standard — AgentMarketCap, 2026-04-09. https://agentmarketcap.ai/blog/2026/04/09/terminal-bench-cli-autonomy-standard-coding-agents
- The evolution of Anthropic's Harness engineering architecture (Chinese overview) — 阿里云开发者社区, 2026. https://developer.aliyun.com/article/1724413
- How the agent loop works — Anthropic, 2026. https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
- Building agents with the Claude Agent SDK — Anthropic, 2025. https://claude.com/blog/building-agents-with-the-claude-agent-sdk
- Loop engineering: Getting started with loops — Claude Code team, Anthropic, 2026-06-30. https://claude.com/blog/getting-started-with-loops
- A harness for every task: dynamic workflows in Claude Code — Anthropic, 2026. https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code
- How we built our multi-agent research system — Anthropic, 2025. https://www.anthropic.com/engineering/multi-agent-research-system
- Unrolling the Codex agent loop — OpenAI, 2025—2026 (publication date unverified, see section 13). https://openai.com/index/unrolling-the-codex-agent-loop/
- Codex as a platform: build on the open agent harness — OpenAI Developers, 2026. https://developers.openai.com/blog/codex-as-a-platform
- Running agents — OpenAI Agents SDK official documentation, 2026. https://openai.github.io/openai-agents-python/running_agents/
- Running Codex safely at OpenAI — OpenAI, 2026. https://openai.com/index/running-codex-safely/
- Agent approvals & security — Codex official documentation, 2026. https://developers.openai.com/codex/sandbox
- gemini-cli (open-source repository and ReAct loop documentation) — Google, 2025—2026. https://github.com/google-gemini/gemini-cli
- What does recursionLimit actually count in createAgent? — LangChain official forum, 2025—2026. https://forum.langchain.com/t/what-does-recursionlimit-actually-count-in-createagent-langchain-js/3460
- Dify node system documentation (Iteration / Loop nodes) — LangGenius, 2026 (via DeepWiki structured index). https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
- Iteration Node — Agent Patterns Catalog, 2026. https://www.agentpatternscatalog.org/patterns/iteration-node
- Runaway Tool Loops — PolicyLayer, 2026 (case occurred in 2025-11, verified: partial). https://policylayer.com/attacks/runaway-tool-loops