架构演进


1. 阅读说明与定位

1.1. 本篇回答的三个问题

01-介绍.md 确立了 AI Harness 的定义与六层能力模型02-发展历史.md 确立了三代演进的时间轴。本篇是两者的交汇点,回答三个问题:

  1. 当代(第三代)Harness 实际长什么样——每一层由哪些组件构成,这些组件之间如何衔接;
  2. 每一层的工程设计为什么是现在这个形状——它要克服的失败是什么,为此付出了什么代价;
  3. 一个组织如何判断自己的 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 横向切面 · 主执行链 L1→L2→L3→L5 · L4 状态支撑 · 示意:基于本文分析绘制 L6 治理与安全层 权限 · 沙箱策略 · 凭据保护 · 机械强制 · 熵治理 · 预算护栏 横向切面 L1 上下文工程 看到什么 压缩 / 笔记 / 隔离 L2 工具与执行 能做什么 MCP / 沙箱 / 副作用 L3 编排与控制 按什么顺序做 规划 / 状态机 / 派发 L5 评估与观测 做得好不好 Trace / Eval / A-B 约束 审计 L4 记忆与状态层 跨上下文窗口的状态交接 · 检查点与工件 状态 状态 反馈:改变下次看到什么 主执行链 L1→L2→L3→L5 构成核心闭环;L4 在 L1~L3 之下提供状态支撑; L6 作为横向切面对全部层级施加约束并记录审计。
┌──────────────────────────────────────────────────────────────────┐
│  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 中的 namedescription
第一层(启动)只把每个 skill 的 name + description 载入系统提示词
第二层(命中)读取完整 SKILL.md 全文
第三层(按需)读取 bundled 文件,如 reference.mdforms.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官方 SDKSession / Runner 作为状态边界(跨 curtailed 会话的类型化状态)A
LangChain / LangGraph开源框架四支柱理论最完整的落地,可通过 node 边界做 IsolateB

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-26Streamable HTTP 取代 HTTP+SSE;OAuth 2.1;工具注解(readOnly / destructive / idempotent);音频内容;Completions
2025-06-18Elicitation;结构化工具输出;资源链接;保护资源元数据;_meta 字段;MCP-Protocol-Version 头变为必需;移除 JSON-RPC batching(破坏性变更)
2025-11-25Tasks(异步状态跟踪);并行工具调用;服务端 agent 循环;sampling 中的工具调用
2026-07-28协议核心无状态化(移除 initialize 握手与 Mcp-Session-Id,版本随每次请求在 _meta 携带);引入 Extensions 框架(Tasks、MCP Apps);强化授权;正式弃用策略(最短 12 个月窗口);在新版中弃用 Roots / Sampling / Logging

从这条演进链可以读出第三代 Harness 在协议层的三个明确取向:

  1. 从有状态会话走向无状态请求——2026-07-28 移除握手与会话 ID,使远程 MCP server 可以像普通 Web 服务一样水平扩展;
  2. 从"够用就行"走向"可演进"——12 个月最短弃用窗口是标准化治理成熟的标志,意味着使用者可以安全地做依赖规划;
  3. 从"只有工具"走向"服务端也有 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:

  1. 自包含、对错误健壮、用途极其明确
  2. 避免功能过载与决策点含糊——一个工具做多件事会让模型在选择时犹豫,也会让失败原因难以归因;
  3. 少样本示例要"多样而典型",而非罗列边界情况。

与之呼应的是系统提示词的"正确海拔"(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_TOKENNPM_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 CodeCodex CLI
macOS 原语Seatbeltsandbox-exec(Seatbelt)
Linux 原语bubblewrap + socat(+ 可选 seccomp)Landlock + seccomp
Windows 原语不支持原生 Windows / WSL1job objects
默认网络经代理 unix socket,新域名需批准默认禁用网络
默认写入当前工作目录 + 会话临时目录限定当前目录
批准档位Auto-allow / Regular permissionsSuggest / Auto-edit / Full-auto
来源等级AB(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 级)

  1. 执行 pwd 确认当前工作目录;
  2. 读取 git 日志与进度文件;
  3. 读取功能清单,选出最高优先级的未完成项。

会话结束约束:必须把环境留在可合并的干净状态

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 返回详细失败原因

三个关键机制

  1. Sprint Contract(冲刺契约):编码前 Generator 提出"要构建什么 + 如何验证成功",Evaluator 审查并达成共识。在开始之前先就"完成"的定义达成一致——这是该层最重要的过程设计。
  2. self-evaluation bias(自卖自夸):官方观察到 agent 自评会"自信地称赞"自己在人类眼中明显平庸的作品。这正是分离 Evaluator 的根本理由(详见 7.2 节)。
  3. 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 可用 LogQLPromQL 直接查询
示例提示词"确保服务启动在 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-Codex77.3%与下一行同为 GPT-5.3-Codex
OpenAI Simple Codex + GPT-5.3-Codex75.1%2.2 个百分点纯由 scaffold 差异造成
KRAFTON Terminus-KIRA + Claude Opus 4.674.7%与下一行同为 Claude Opus 4.6
Bigai TongAgents + Claude Opus 4.671.9%相差 2.8 个百分点
LangChain 仅改 Harness(同模型、同 API)52.8% → 66.5%排名从 30 名外跃升至前 5

LangChain 那次 "52.8% → 66.5%" 的五项改动清单是全篇最具迁移价值的内容之一(C 级, 数字,但改动项本身有工程参考价值):

  1. 强制清单式自我验证后才允许说"完成"
  2. 启动前扫描目录结构并注入环境上下文
  3. 反漂移检测——重复编辑同一文件时告警;
  4. 调整推理预算——规划验证多想、实现少想
  5. 自动失败模式分析

这五项全部不涉及换模型,全部属于 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.enabledsandbox.failIfUnavailableallowUnsandboxedCommandsfilesystem.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_TOKENNPM_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-gardening agent:定期扫描过时文档并自动发起修复 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 级):

厂商官方表述来源
Anthropicgather 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 单圈结构与六层模型对应

Harness Loop 单圈结构与六层模型对应 L6 治理与安全层:权限门 · 预算护栏 · 审计 —— 约束并记录整环每一圈 目标装配 L1 · 上下文工程层 计划 L3 · 编排与控制层 工具执行 L2 · 工具与执行层 一个完整工作周期(turn) 模型 (被承载对象) 观测反馈 L5 · 评估与观测层 状态更新 L4 · 记忆与状态层 再计划 L3 · 回到编排层 回到 L3 再计划(下一圈开始) 实线:单圈控制流;虚线框:被承载对象。示意图:基于 Anthropic / OpenAI / Google 官方循环描述绘制(信息截止 2026-09-12)。

示意图:基于本文分析,机制依据三家官方循环描述(A 级,信息截止 2026-09-12)。

9.2. 单圈结构:三家官方实现的同构性

无论 Claude Code、Codex 还是 Gemini CLI,单圈(一个 turn)都是同一结构:上下文装配 → 模型推理 → 工具调用 → 结果校验回流。这是"Loop 是 Harness 的心脏"在工程上的直接体现——心脏的跳动方式是同构的,差异只在瓣膜(确认门、审批门)与循环的出口条件。

Anthropic Claude Agent SDK 的官方五步定义(《How the agent loop works》,A 级):

  1. 接收 prompt(含系统提示、工具定义、会话历史);
  2. Claude 评估并响应(文本或工具调用);
  3. SDK 执行工具并收集结果;
  4. 步骤 2~3 重复,每完成一次完整周期为一个 turn;
  5. 输出不含工具调用的最终响应与 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 harnessassistant message;审批门与沙箱边界turn 内多轮推理—工具迭代;retained reasoning + 上下文压缩
Gemini CLIcomplete_task 显式终止CoreToolScheduler 确认门(会话内白名单免重复确认);1M token 长上下文

9.3. 跨圈机制:五类控制流

单圈之上,Harness Loop 依赖五类跨圈机制维持长任务的可持续性(依据 Anthropic 官方工程博客与各框架文档,标注见行内):

机制做法指向证据等级
Compaction(压缩)接近上下文上限时自动摘要历史消息;Agent SDK 以 compact_boundary 消息类型显式标记压缩边界指回 L1A
Context Reset(上下文重置)清空上下文、更换新 Agent,靠结构化交接物续跑;官方用它治理"上下文焦虑"与自我评估偏差——区别于 Compaction 的就地摘要指回 L1A
计划修订主 Agent 汇总子代理结果后决定追加派发或修订策略;Claude Code 支持任务中途注入指令实时改向指回 L3A(改向机制细节为社区逆向,B)
子智能体派发并行 + 独立上下文窗口,只回传浓缩摘要;官方给出按任务复杂度分级的努力缩放规则:简单事实 1 个代理 3~10 次工具调用,对比类 2~4 个子代理各 10~15 次,复杂研究 10 个以上子代理旁路子环A
检查点持久化进度文件 + git 历史 + 功能清单跨会话交接;MAF Workflow 原生 checkpointing;LangGraph Checkpointer 每 superstep 落盘指回 L4A / 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|跨圈控制流与终止条件分级

跨圈控制流与终止条件分级 Harness Loop 主循环进行中 跨圈机制(圈与圈之间) Compaction / Context Reset 就地摘要 或 清空重注入 指回 L1 计划修订 追加子代理 / 中途改向 指回 L3 子智能体派发 独立上下文窗口 只回传摘要 检查点持久化 进度文件 / git / 落盘 指回 L4 终止条件分级(五级出口) ① 任务完成 DoD 校验通过 无工具调用响应 / complete_task / 评估模型 正常出口 ② 预算耗尽 max_budget_usd / token 预算 / 墙钟超时 ③ 权限边界触发 hooks 拦截 / 审批门 / 沙箱边界 ④ 人工中断(HITL) 挂起等人工续跑 可恢复 ⑤ 死循环检测 / 到期 轮数熔断 / 重复状态 / 周期任务自动到期 ② ~ ⑤:治理出口 —— 非正常终止;超限应返回部分结果(进度摘要)而非裸错误 轮数熔断经验值:LangGraph recursion_limit 默认 25,官方论坛建议设为最坏情况 superstep 的 5~10 倍。示意图:基于本文分析(信息截止 2026-09-12)。

示意图:基于本文分析,终止条件口径沿用本库参数卡统一分级(信息截止 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 harnessagent loop(core 运行时)assistant message / 审批门 / 沙箱边界线程持久化 + retained reasoningL1~L6 全环
Gemini CLIcli 驱动 + core 执行的 ReAct 循环complete_task / 确认门会话历史L2 / L3 为主
OpenAI Agents SDKRunner 循环final_output / max_turns / guardrail tripwireRunState / SessionL3 为主
LangGraph显式状态机图循环(节点 + 条件边)条件边到 END / recursion_limit(默认 25)Checkpointer 按 thread_id 每步落盘,可从检查点恢复L3 / L4
AutoGen / MAF会话消息循环 → 类型化图工作流终止条件 / max_turns / 条件退出边MAF checkpointing / AgentThreadL3 / L4
DifyIteration / Loop 两种节点数组长度(Iteration)或 loop_count + break_conditions(Loop)变量池快照 / loop_variables 跨轮继承L3
n8n / Coze可视化循环节点有界迭代(结构性边界,非 LLM 停止条件)节点间变量L3

三个值得展开的语义差异(来源等级见表内标注):

  1. LangGraph:超限不是死亡,而是可恢复的暂停(B 级,源码佐证)。recursion_limit 触发的 GraphRecursionError 配合 Checkpointer,可从最后落盘状态恢复或提高预算续跑——"熔断器而非业务逻辑"。
  2. AutoGen → MAF:从隐式消息循环到显式图循环(B 级)。AutoGen 的 GroupChat 因 LLM 选人导致循环不可预测、终止条件含糊时可无限循环,这是"隐式消息循环 → 显式类型化图"演进的直接动因;MAF 的 Workflow 提供类型化循环步骤、checkpointing、HITL 与中间件管线(含 token 预算强制)。社区对比数据显示 MAF 显式转换较 GroupChat 减少 23% LLM 调用(B 级第三方转述)。
  3. 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 角色 + 反馈回流 L1Responses API 内置 tracing、三 Agent 架构(A)
4状态从"会话内"到"跨窗口交接"会话结束即失忆进度文件 + git + 功能清单 + 健康度预检长时运行 harness 两代(A)
5治理从"手工提示"到"沙箱与机械强制"逐条权限弹窗双维隔离 + 凭据保护 + 自研 linter 注入修复Claude Code 沙箱(A,−84% 提示)
6角色从"人指挥"到"人掌舵"人逐步指挥每个动作Human Steer, Agent ExecuteOpenAI《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 数 / 工程师数 / 人均日 PR1,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自动扫描过时文档并发起修复 PRL6
分层架构约束的机械强制单向依赖链 Types → Config → Repo → Service → Runtime → UI;横切关注点仅经 ProvidersL6
可观测性对 agent 开放git worktree 启动、Chrome DevTools Protocol、LogQL / PromQL 查询L5 → L1
最小阻塞合并哲学最小阻塞合并门,PR 短命,测试 flakiness 靠重跑解决——"纠错成本低,等待成本高"L3

此外还有一条技术选型原则值得单独记住:倾向"无聊的技术"(可组合性、API 稳定性、在训练语料中广泛存在)。官方举的例子是自研 map-with-concurrency 而非引入 p-limit——理由是模型对"训练语料中广泛存在的东西"掌握得更好。

这条原则对所有 Harness 设计通用:在 agent 会写代码的系统里,技术的"模型熟悉度"是真实的选型指标,与性能、生态并列。

10.3. 跃迁尚未完成的部分

第三代远不是终点。以下问题是官方自陈尚未解决的(A 级):

  1. 单 Agent vs 多 Agent 之争未决——Anthropic 明确表示"目前尚不清楚";
  2. 跨领域泛化未验证——上述经验能否推广到科学研究或金融建模等其他长周期任务,"答案尚在摸索中";
  3. Harness 自身缺乏评估方法——martinfowler.com 提出的开放问题:我们需要类似代码覆盖率和变异测试的 Harness 覆盖率与质量评估方法(尚未出现);
  4. 熵治理仍靠补丁——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. 使用建议

  1. 每半年自评一次,并把结果记录下来用于对比——自评本身的价值在于纵向比较,而非横向得分。
  2. 评估时逐层给出具体证据,不写抽象的"中等",要写"我们的 context 压实靠的是 XXX"。
  3. 优先关注最弱层,而不是平均分。
  4. 警惕"评估通胀":当一个层被评到 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. 信息缺口声明

本节汇总本篇涉及的信息缺口,已在正文对应位置标注 或说明来源等级。

已存在于本次调研、可跨来源复用的缺口

  1. Anthropic《How we built our multi-agent research system》的确切 URL 与发布日期:仅在 context engineering 博客中以链接形式被引用,未验证。
  2. MCP "首个公开规范版本"表述差异:2024-11-05(Ruby SDK 记为 Initial protocol revision)与 2024-11-25(公开宣布与生态启动)两种口径并存,本篇并列呈现。

数字来源等级不足,本篇已标注

  1. 第 3.10 节:上下文退化的"性能下降超过 45%"与 Chroma Research "18 个前沿模型全部退化"。
  2. 第 4.6 节:Codex CLI "2026 年初约 95% Rust"、Auto-review 的 "1/200" 与 "99%",以及审阅模型型号 "GPT-5.4 Thinking"。
  3. 第 4.7 节:Vercel 工具数 15 → 2 的准确率 80% → 100%、Token −37%、速度 3.5×。
  4. 第 5.7 节:Anthropic 单 Agent(20 分钟 / $9 / 不可用)与三 Agent(6 小时 / $200 / 完整可玩)的对比实验数字。
  5. 第 7.5 节:Terminal-Bench 2.0 全部榜单数字(77.3% / 75.1% / 74.7% / 71.9%)、LangChain 52.8% → 66.5%,以及 easy 约 65% → hard 约 16% 的难度梯度。
  6. 第 7.5 节:Terminal-Bench 官方站(tbench.ai)当前榜单数据未直接抓取,全部为第三方转述。

本篇未涉及但属于本模块共同缺口的项目

  1. ISO/IEC 智能体互联国际标准编号:暂无权威信息
  2. "Agent Harness"术语首创出处:暂无权威信息
  3. Claude 模型 2026 年各版本时间线:仅见于第三方 GitHub 时间线仓库,标 。

本轮新增(第 9 章 Harness Loop)

  1. 《Unrolling the Codex agent loop》《Unlocking the Codex harness》《Codex as a platform》等 OpenAI 官方博客的具体发布日期未在检索结果中直接返回(第 9.2 / 9.3 节)。
  2. $47,000 多代理乒乓失控案例为 verified: partial(多帖一致、无具名受害企业),正文已按"业界流传的代表性事故复盘"表述并保留数字(第 9.6 节)。
  3. 业界三重硬限经验值(迭代上限 10 / 25 / 50~100、token 预算 10 倍均值、墙钟超时 2~3 倍 p95)为业界实践汇总(C 级),仅作方向性参考(第 9.4 节)。
  4. n8n / Coze 循环节点缺独立一手官方文档,仅经可视化工作流有界循环共性模式间接覆盖(第 9.5 节)。
  5. MAF 较 AutoGen GroupChat 减少 23% LLM 调用为第三方转述(B 级),官方一手文稿未直接命中(第 9.5 节)。

完整清单见 06-参考资料.md 第 9 节。


14. 参考资料

  1. Effective context engineering for AI agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
  2. Effective harnesses for long-running agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
  3. Harness design for long-running application development — Anthropic,2026。https://www.anthropic.com/engineering/harness-design-long-running-apps
  4. 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
  5. Introducing Agent Skills — Anthropic,2025-10-16(2025-12-18 开放标准更新)。https://www.anthropic.com/news/skills
  6. Sandboxing: a safer and more autonomous approach — Anthropic,2025。https://www.anthropic.com/engineering/claude-code-sandboxing
  7. Claude Code 官方文档 · Sandboxing(中文版)— Anthropic,2026。https://code.claude.com/docs/zh-TW/sandboxing
  8. Claude Code 官方文档 · Choose a sandbox environment — Anthropic,2026。https://code.claude.com/docs/en/sandbox-environments
  9. Introducing the Model Context Protocol — Anthropic,2024-11-25。https://www.anthropic.com/news/model-context-protocol
  10. Harness engineering: leveraging Codex in an agent-first world — OpenAI,2026-02-11。https://openai.com/index/harness-engineering/
  11. Harness engineering(中文版)— OpenAI,2026-02-11。https://openai.com/zh-Hans-CN/index/harness-engineering/
  12. New tools for building agents(Responses API + Agents SDK)— OpenAI,2025-03-11。https://openai.com/blog/new-tools-for-building-agents
  13. 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/
  14. A year of open collaboration: Celebrating the anniversary of A2A — Google Open Source Blog,2026-04-16。https://opensource.googleblog.com/
  15. Agent Development Kit — AI Wiki,2026。https://aiwiki.ai/wiki/google_adk
  16. Model Context Protocol 官方站与规范 — MCP / AAIF,2024—2026。https://modelcontextprotocol.io/https://modelcontextprotocol.io/specification/2026-07-28/
  17. MCP Protocol Versions(版本演进表)— MCP Ruby SDK,2026。https://ruby.sdk.modelcontextprotocol.io/protocol-versions/
  18. MCP Rust 层协议版本枚举 — mcpkit(docs.rs)。https://docs.rs/mcpkit/latest/enum.ProtocolVersion.html
  19. Model Context Protocol 词条(含规范演进)— Klu。http://klu.ai/glossary/model-context-protocol
  20. Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF,2025-12-09。https://aaif.io/
  21. Harness engineering for coding agent users — Birgitta Böckeler,martinfowler.com,2026。https://martinfowler.com/articles/harness-engineering.html
  22. SWE-bench: Can Language Models Resolve Real-World GitHub Issues? — Jimenez、Yang 等(Princeton),2023-10(ICLR 2024 Oral)。https://www.swebench.com/
  23. Terminal-Bench — Stanford / Laude Institute,2025。https://www.tbench.ai/
  24. Context engineering 词条(命名链与四支柱)— AI Wiki,2025—2026。https://aiwiki.ai/wiki/context_engineering
  25. OpenAI Codex 词条(沙箱原语、批准模式、Rust 重写)— AI Wiki,2026。https://aiwiki.ai/wiki/codex
  26. Agent Harness:2026 年 AI 工程的核心范式 — 腾讯云开发者社区,2026。https://developer.cloud.tencent.com/article/2698416
  27. Terminal-Bench: The CLI Autonomy Standard — AgentMarketCap,2026-04-09。https://agentmarketcap.ai/blog/2026/04/09/terminal-bench-cli-autonomy-standard-coding-agents
  28. Anthropic 的 Harness 工程架构演进(中文综述)— 阿里云开发者社区,2026。https://developer.aliyun.com/article/1724413
  29. How the agent loop works — Anthropic,2026。https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
  30. Building agents with the Claude Agent SDK — Anthropic,2025。https://claude.com/blog/building-agents-with-the-claude-agent-sdk
  31. Loop engineering: Getting started with loops — Claude Code 团队,Anthropic,2026-06-30。https://claude.com/blog/getting-started-with-loops
  32. 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
  33. How we built our multi-agent research system — Anthropic,2025。https://www.anthropic.com/engineering/multi-agent-research-system
  34. Unrolling the Codex agent loop — OpenAI,2025—2026(发布日期 ,见第 13 节)。https://openai.com/index/unrolling-the-codex-agent-loop/
  35. Codex as a platform: build on the open agent harness — OpenAI Developers,2026。https://developers.openai.com/blog/codex-as-a-platform
  36. Running agents — OpenAI Agents SDK 官方文档,2026。https://openai.github.io/openai-agents-python/running_agents/
  37. Running Codex safely at OpenAI — OpenAI,2026。https://openai.com/index/running-codex-safely/
  38. Agent approvals & security — Codex 官方文档,2026。https://developers.openai.com/codex/sandbox
  39. gemini-cli(开源仓库与 ReAct 循环文档)— Google,2025—2026。https://github.com/google-gemini/gemini-cli
  40. 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
  41. Dify 节点系统文档(Iteration / Loop 节点)— LangGenius,2026(经 DeepWiki 结构化索引)。https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
  42. Iteration Node — Agent Patterns Catalog,2026。https://www.agentpatternscatalog.org/patterns/iteration-node
  43. 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:

  1. What a contemporary (third-generation) Harness actually looks like — which components make up each layer, and how these components connect to one another;
  2. Why the engineering design of each layer has its current shape — what failures it has to overcome, and what price was paid for that;
  3. How an organization can judge what level its own Harness is at — providing an actionable self-assessment tool.

1.2. Boundaries with Prior Documents

ContentOwnershipHandling in This Document
Definition of Harness, etymology, definition of the six-layer model01-IntroductionCited directly, not redefined
Timeline of the three-generation division, milestones, historical causes02-Development HistoryCited only when necessary, no historical narration
Components, parameters, design trade-offs, and failure modes of each layerThis documentDeveloped in detail
Prospects for standardization and trend extrapolation04-Future DevelopmentNo trend prediction is made in this document
Product-by-product analysis of specific platforms03-Market ResearchThis 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—

AttributionCorresponding Layer
It never saw that critical file / the context was too long and information was lostL1
The action it wanted to perform was not correctly defined as a tool / the execution produced unexpected side effectsL2
The order in which it did this thing was wrong / it got stuck in some loop and couldn't get outL3
In a new session it "forgot" how far it got in the previous roundL4
It said "done", but it actually wasn't doneL5
It did something it shouldn't have / it overshot the budget / we can't find out who did itL6

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 横向切面 · 主执行链 L1→L2→L3→L5 · L4 状态支撑 · 示意:基于本文分析绘制 L6 治理与安全层 权限 · 沙箱策略 · 凭据保护 · 机械强制 · 熵治理 · 预算护栏 横向切面 L1 上下文工程 看到什么 压缩 / 笔记 / 隔离 L2 工具与执行 能做什么 MCP / 沙箱 / 副作用 L3 编排与控制 按什么顺序做 规划 / 状态机 / 派发 L5 评估与观测 做得好不好 Trace / Eval / A-B 约束 审计 L4 记忆与状态层 跨上下文窗口的状态交接 · 检查点与工件 状态 状态 反馈:改变下次看到什么 主执行链 L1→L2→L3→L5 构成核心闭环;L4 在 L1~L3 之下提供状态支撑; L6 作为横向切面对全部层级施加约束并记录审计。
┌──────────────────────────────────────────────────────────────────┐
│  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

LayerNameEnglishResponsibilityInputOutputTypical Implementations
L1上下文工程层Context EngineeringDecides what the model "sees"Environment state, retrieval results, instructionsThe assembled token sequenceRAG, Context Compaction, Prompt Assembly, progressive disclosure via SKILL.md, KV Cache reuse
L2工具与执行层Tooling & ExecutionDecides what the model "can do"Tool invocation intentSide effects in a controlled environmentMCP, Function Calling, sandboxed executors, Computer Use
L3编排与控制层Orchestration & ControlDecides "in what order to do it"Task goalSequence of execution stepsAgent Loop, Plan-and-Execute, DAG / Workflow, Sub-agent
L4记忆与状态层Memory & StateDecides "what to remember"Session history, artifactsState recoverable across windowsSession Store, Episodic / Semantic Memory, Checkpoint
L5评估与观测层Evaluation & ObservabilityDecides "how well it was done"Execution trace, productsVerdicts, metrics, regression signalsTrace, Eval Set, Golden Dataset, Online Metrics
L6治理与安全层Governance & SafetyDecides "what must not be done"Policies, budgets, compliance requirementsAllow / deny + audit recordsRBAC, 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):

LayerFirst Generation · Prompt EngineeringSecond Generation · Tools and OrchestrationThird Generation · Runtime and Evaluation
L1No governance, relies on Few-shotPreliminary RAG, no compaction strategyCompaction + notes + sub-agents + Skills — the four-piece set
L2No toolsFunction Calling (vendor-proprietary)MCP standardization + strongly isolated sandbox
L3Single-turnMulti-agent orchestration frameworksBuilt into official SDKs + long-running + three-role division of labor
L4StatelessPreliminary session memoryCross-window state handoff + checkpoints + Git as the state carrier
L5Manual subjective judgmentExternal benchmark leaderboardsBuilt-in evaluation loop + independent Evaluator + trace tracking
L6NoneManual permission promptsSandbox + 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:

ConceptOfficial StatementEngineering Implication
context rotExplicitly 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 budgetThe n² relational property of self-attention means each additional token dilutes attention on the other tokensContext 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:

StrategyApplicable Task Characteristics
CompactionTasks requiring many round-trips
Note-takingIterative development with clear milestones
Multi-agent / Sub-agentComplex 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".

ElementContent
Minimal formmy-skill/SKILL.md directory, extensible with scripts/, references/, assets/
Required metadataname 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 supportExecutable 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):

PillarMeaningCorresponding Implementation
WriteExternalize statescratchpad, NOTES.md
SelectPrecise retrievalRAG, memory retrieval, tool and few-shot selection
CompressSummarize, trim, pruneCompaction, tool result clearing
IsolateIsolationsub-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

ImplementationFormL1 TechniquesSource Tier
Claude Agent SDK / Claude CodeOfficial SDK + CLIThe full four-piece set (compaction / notes / memory tool / sub-agent), progressive disclosure via SKILL.mdA
OpenAI Agents SDK / CodexOfficial SDK + CLIThe "AGENTS.md as directory" strategy, ~100 lines of context injected + structured docs/ externalized (see section 10.2)A
Google ADKOfficial SDKSession / Runner as the state boundary (typed state across curtailed sessions)A
LangChain / LangGraphOpen-source frameworkThe most complete realization of the four-pillar theory; Isolate is achievable at node boundariesB

3.9. Design Trade-offs

Three core trade-offs of the L1 layer:

Trade-offThe Two PolesBasis for the Choice
Recall vs precisionFull dump (high recall, prone to rot) vs precise retrieval (high precision, prone to omission)The order given officially: recall first, precision later
Depth vs cleanlinessKeep 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 loadingInject 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 ModeMeaningTypical Symptoms
context poisoningErroneous information is propagated as fact within the sessionAfter a single tool error, all subsequent reasoning builds on the wrong premise
context distractionKey information is drowned by noiseRetrieval returns 50 relevant passages; the model uses only the first 3
context confusionRedundant information causes loss of focusToo many "you could also do it this way" suggestions in the instructions; the model starts picking randomly between two
context clashConflicting instructions inside the contextAGENTS.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 ClassRoleRepresentative
Tool registration and descriptionDeclare external capabilities as structured interfaces callable by the modelFunction Calling, JSON Schema tool descriptions
Connection protocolDecouple the tool ecosystem from the host applicationMCP (Model Context Protocol)
Execution environmentBound the scope of actions and the boundary of side effectsSandbox (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):

RoleResponsibilityDescription
HostTop-level application (IDE, chat app, multi-agent orchestration framework)Contains Clients
ClientMaintains a 1:1 connection with each ServerHandles protocol negotiation and routing
ServerLightweight programExposes 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:

VersionKey Changes
2024-11-05Initial protocol version: stdio + HTTP+SSE; the three primitives Tools / Resources / Prompts; Sampling, Roots, progress notifications, logging, pagination
2025-03-26Streamable HTTP replaces HTTP+SSE; OAuth 2.1; tool annotations (readOnly / destructive / idempotent); audio content; Completions
2025-06-18Elicitation; 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-25Tasks (asynchronous state tracking); parallel tool calls; server-side agent loop; tool calls in sampling
2026-07-28Protocol 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:

  1. 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;
  2. 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;
  3. 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-05 as 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:

  1. Self-contained, robust to errors, extremely clear in purpose;
  2. 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;
  3. 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

ItemParameter
macOS implementationSeatbelt
Linux / WSL2 implementationbubblewrap + socat (optional seccomp filter, via npm install -g @anthropic-ai/sandbox-runtime)
Not supportedNative Windows; WSL1
Default writeCommands in the sandbox can write only to the current working directory and the session temporary directory ($TMPDIR is set to that directory)
Default readReadable machine-wide by default (except explicitly denied directories)
Network egressOnly 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

ModeBehavior
Auto-allowSandboxed commands are approved automatically, no per-command prompts
Regular permissionsStill 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

DimensionClaude CodeCodex CLI
macOS primitiveSeatbeltsandbox-exec (Seatbelt)
Linux primitivebubblewrap + socat (+ optional seccomp)Landlock + seccomp
Windows primitiveNative Windows / WSL1 not supportedjob objects
Default networkVia a proxy unix socket; new domains require approvalNetwork disabled by default
Default writeCurrent working directory + session temporary directoryRestricted to the current directory
Approval tiersAuto-allow / Regular permissionsSuggest / Auto-edit / Full-auto
Source tierAB (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-offThe Two PolesPosition of This Section
Sandbox strength vs usabilityStrong 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 accuracyMore tools, broader capability vs more tools, harder choiceSubtraction first. Vercel cut the tool count from 15 to 2: accuracy 80% → 100%, tokens −37%, speed 3.5× (Tier C)
Native plugins vs standard protocolBetter performance but lock-in vs decoupled but with overheadThe third generation generally picks the MCP route; deviations need a clear reason

4.8. Failure Modes

Failure ModeManifestationCountermeasure
Tool semantic overlapTwo tools have similar descriptions; the model picks randomly and unreproduciblyDo a "pairwise distinguishability" check in tool review
Sandbox escape normalized under the name of the escape hatchdangerouslyDisableSandbox is used frequently; isolation becomes a mere formalityDisable the escape hatch (Strict sandbox mode); turn exceptions into explicit approvals
Credentials leaked via environment variablesChild processes inherit GITHUB_TOKEN and the likeUse sandbox.credentials to deny / mask explicitly
Network egress out of controlThe agent exfiltrates data over arbitrary DNSMandatory proxy + new-domain approval + egress whitelist
Over-toolingBloated tool count causes a double loss in accuracy and costDo 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:

FormApplicable ToRepresentative
Single loop (Agent Loop)General tasks; the model decides the next step autonomouslyReAct loop, Claude Code main loop
Plan-then-execute (Plan-and-Execute)Long-cycle tasks requiring global planningClaude Code Plan Mode, the three-agent architecture
Directed acyclic graph / workflowBusiness processes with high determinism requirementsDAG / Workflow engines, Google ADK SequentialAgent
Sub-agent dispatchComplex research tasks that can be explored in parallelSub-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)

ArtifactPurpose
init.shEnvironment startup script, ensuring every new session can bring up a runnable environment with one command
claude-progress.txtProgress file, carrying "how far it got" across sessions
Initial git commitProvides a rollback base point
JSON feature listA 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)

  1. Run pwd to confirm the current working directory;
  2. Read the git log and the progress file;
  3. 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).

RoleResponsibilityOfficial Detail
PlannerTurns 1~4 high-level prompt sentences into a complete product specificationDeliberately stays high-level, does not touch implementation details
GeneratorImplements one feature per sprint, self-evaluates first, then hands off to the EvaluatorConstrained by the Sprint Contract
EvaluatorScores four items: product depth, functionality, visual design, code qualityEach 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

  1. 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.
  2. 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).
  3. 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 CategoryContent
AgentOrchestration body
ToolsExecutable actions
SessionsSession state
RunnersExecution 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-offThe Two PolesBasis for the Choice
Single Agent vs Multi-AgentContext coherence vs parallelism and clean windowsAnthropic officially acknowledges "currently unclear"; recommends per-task A/B testing
Planning granularityPlanner 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 flexibilityState machines are reproducible vs LLM routing is highly adaptiveBusiness processes choose the former, exploratory tasks choose the latter; ADK's answer is both coexist
Cost vs qualityMulti-Agent is obviously more expensiveComparison experiments show (Tier C): single Agent 20 minutes / $9 / unusable output; three Agent 6 hours / $200 / complete playable output

5.8. Failure Modes

Failure ModeManifestationCountermeasure
Infinite loopThe same action repeats without progressIteration cap + anti-drift detection (warn when repeatedly editing the same file)
Goal driftGradually deviates from the original goalSprint Contract + periodic re-injection of the original goal
Early completion declarationHasty wrap-up under context anxietyForce checklist-style self-verification before allowing "done" to be output (see section 7.5, LangChain's first change)
Dirty environment stateThe previous round left behind unclosed half-productsOfficial hard rule: must return to a mergeable clean state before ending
Tests modified to passCriteria 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 VehicleCarried ContentCharacteristic
claude-progress.txtNatural-language progress recordReadable, understandable by the model
git historyStructured change recordRollback-able, diff-able
JSON feature list (with passes)Master task ledgerMachine-decidable completion degree
Initial git commitRollback base pointGuarantees 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:

MechanismApproachAdvantageCost
CompactionIn-place summarization and compressionPreserves continuitycontext anxiety remains
Context ResetClear the context then re-injectGives a clean whiteboardHandoff 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-offThe Two PolesBasis for the Choice
Natural language vs structured stateclaude-progress.txt is flexible but not machine-decidable vs JSON list is machine-decidable but rigidOfficial choice: want both
Preserve vs resetGood continuity vs cleanFor long tasks, recommend periodic Reset + high-quality handoff package
Dedicated memory store vs GitStrong semantic retrieval vs mature tool ecosystemThe third generation generally takes Git-first, with dedicated memory as a supplement

6.6. Failure Modes

Failure ModeManifestationCountermeasure
Amnesiac restartEach new session repeats already-completed workForce the three opening steps: pwd → read log and progress file → read list and pick the highest-priority unfinished item
Progress file decayclaude-progress.txt does not match actual git stateTreat git history as the single source of truth; the progress file only summarizes
Dirty handoffThe previous round left behind half-products / failing testsMust return to a mergeable clean state before ending; the next round's opening runs an end-to-end health test
Checkpoint granularity out of controlCommits 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:

ComponentRoleRepresentative
External benchmarksCross-system horizontal comparison, judging "what rank in the industry"SWE-bench / SWE-bench Verified, Terminal-Bench
Built-in evaluation loopRegression 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.

MeasureDetail
Start per worktreeApplications can be started independently per git worktree; the agent can obtain its own runtime instance
Browser debugging protocolChrome DevTools Protocol wired into the agent runtime
Expose metrics and logsExposed 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 ItemDataNote
Factory Droid + GPT-5.3-Codex77.3%Same GPT-5.3-Codex as the next row
OpenAI Simple Codex + GPT-5.3-Codex75.1%2.2 percentage points caused purely by scaffold difference
KRAFTON Terminus-KIRA + Claude Opus 4.674.7%Same Claude Opus 4.6 as the next row
Bigai TongAgents + Claude Opus 4.671.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):

  1. Force checklist-style self-verification before allowing "done" to be said;
  2. Scan the directory structure before startup and inject environment context;
  3. Anti-drift detection — warn when repeatedly editing the same file;
  4. Adjust the reasoning budget — think more for planning and verification, less for implementation;
  5. 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-offThe Two PolesBasis for the Choice
Subjective scoring vs binary criteriaCover subjective tasks vs objectively reproduciblePrefer translating subjective tasks into binary-decidable sub-items; only use Evaluator scoring + hard thresholds when binary decision is truly impossible
Evaluation frequency vs costPer-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 costLarger evaluation sets are more accurate vs harder to maintainRather than spreading wide, do "add one regression case for every real failure"

7.7. Failure Modes

Failure ModeManifestationCountermeasure
Self-praise (self-evaluation bias)Self-evaluation all green, human review fails itSeparate the evaluator from the evaluated
Evaluation set overfittingThe agent learns to "game" the eval instead of truly doing wellRotate evaluation sets periodically; keep a held-out set invisible to the agent
Only looking at end-state scoresKnows things got worse but not whereTrajectory-level tracing (e.g., Responses API built-in tracing, ADK step-by-step trajectory scoring)
Metrics disconnected from businessBenchmark rose but users feel nothingBuild 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):

LevelConfiguration LocationPurpose
Project level.claude/settings.local.jsonDistributed with the repository, shared by the team
User level~/.claude/settings.jsonPersonal preferences
Organization levelmanaged settingsMandatorily 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"):

ModeBehaviorApplicable To
denyCompletely invisible~/.aws/credentials, ~/.ssh
maskMasked displaytokens 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-gardening agent: 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-offThe Two PolesBasis for the Choice
Hard failure vs silent degradationAvailability vs safety certaintyGovernance mechanisms should avoid silent degradation (sandbox.failIfUnavailable hard failure)
Central enforcement vs local autonomyConsistency vs flexibilityOfficial answer: the center enforces boundaries, the periphery allows autonomy
Number of rules vs complianceMore rules the better vs too many and they are ignoredOfficial answer: rules must be few and mechanically enforceable; excessive documentation equals no documentation

8.7. Failure Modes

Failure ModeManifestationCountermeasure
Permission fatigueFrequent prompts cause users to click approve uniformlySandboxing + Auto-allow (official data: −84% prompts)
Documentation decayAGENTS.md / docs disconnected from actual codedoc-gardening agent + bring documentation into CI validation
Rules not machine-checkableCan only rely on verbal review conventionsSelf-built linter, error messages written as repair instructions
Audit not traceableAfter an incident, cannot find out which agent did itFull-layer tracing + structured logs (enforced as taste invariants)
Budget out of controlLong-task cost unpredictableBudget 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):

VendorOfficial StatementSource
Anthropicgather 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 单圈结构与六层模型对应

Harness Loop 单圈结构与六层模型对应 L6 治理与安全层:权限门 · 预算护栏 · 审计 —— 约束并记录整环每一圈 目标装配 L1 · 上下文工程层 计划 L3 · 编排与控制层 工具执行 L2 · 工具与执行层 一个完整工作周期(turn) 模型 (被承载对象) 观测反馈 L5 · 评估与观测层 状态更新 L4 · 记忆与状态层 再计划 L3 · 回到编排层 回到 L3 再计划(下一圈开始) 实线:单圈控制流;虚线框:被承载对象。示意图:基于 Anthropic / OpenAI / Google 官方循环描述绘制(信息截止 2026-09-12)。

示意图:基于本文分析,机制依据三家官方循环描述(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):

  1. Receive the prompt (including system prompt, tool definitions, session history);
  2. Claude evaluates and responds (text or tool invocation);
  3. The SDK executes tools and collects results;
  4. Steps 2~3 repeat; each completed full cycle is one turn;
  5. 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):

ImplementationLoop ExitIn-Loop Protection Mechanism
Claude Code / Agent SDKResponse without tool invocations; max_turns / max_budget_usd hard capsPre-exit recovery path: context folding → reactive compression → double the output budget and retry; only exit for real when all fail
Codex harnessAssistant message; approval gate and sandbox boundaryMultiple reasoning—tool iterations within a turn; retained reasoning + context compression
Gemini CLIcomplete_task explicit terminationCoreToolScheduler 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):

MechanismApproachPoints ToEvidence Tier
CompactionAutomatically summarize historical messages when approaching the context limit; the Agent SDK explicitly marks compaction boundaries with the compact_boundary message typeBack to L1A
Context ResetClear 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 summarizationBack to L1A
Plan revisionThe 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 redirectionBack to L3A (redirection mechanism details are community reverse-engineering, B)
Sub-agent dispatchParallel + 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-agentsSide-loopA
Checkpoint persistenceProgress file + git history + feature list handed off across sessions; MAF Workflow native checkpointing; LangGraph Checkpointer writes to disk at each superstepBack to L4A / 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|跨圈控制流与终止条件分级

跨圈控制流与终止条件分级 Harness Loop 主循环进行中 跨圈机制(圈与圈之间) Compaction / Context Reset 就地摘要 或 清空重注入 指回 L1 计划修订 追加子代理 / 中途改向 指回 L3 子智能体派发 独立上下文窗口 只回传摘要 检查点持久化 进度文件 / git / 落盘 指回 L4 终止条件分级(五级出口) ① 任务完成 DoD 校验通过 无工具调用响应 / complete_task / 评估模型 正常出口 ② 预算耗尽 max_budget_usd / token 预算 / 墙钟超时 ③ 权限边界触发 hooks 拦截 / 审批门 / 沙箱边界 ④ 人工中断(HITL) 挂起等人工续跑 可恢复 ⑤ 死循环检测 / 到期 轮数熔断 / 重复状态 / 周期任务自动到期 ② ~ ⑤:治理出口 —— 非正常终止;超限应返回部分结果(进度摘要)而非裸错误 轮数熔断经验值:LangGraph recursion_limit 默认 25,官方论坛建议设为最坏情况 superstep 的 5~10 倍。示意图:基于本文分析(信息截止 2026-09-12)。

示意图:基于本文分析,终止条件口径沿用本库参数卡统一分级(信息截止 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):

TierTermination ConditionOfficial MechanismEvidence 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 continueA / B
Budget exhaustedThe 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 capA / B
Permission boundary triggeredClaude 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 triggeredA
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 runsA / B
Dead-loop detection / expirymax_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 daysA / 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 LimitEmpirical ValueCorresponding Failure Form
Iteration capSimple Q&A 10 / research-type 25 / coding-type 50~100, set at 2~10× the p95 legitimate taskInfinite loop
Token budget10× the mean of legitimate tasks; warn at 80% budget consumption rather than only at exhaustionCost storm
Wall-clock timeout2~3× the p95; warn when token generation speed drops to 1/3 of baselineProcess 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).

ImplementationLoop CarrierStopping SemanticsCross-Turn PersistenceBelonging Layer
Claude Code / Agent SDKSingle main loop + sub-agentsResponse without tool invocations / max_turns / budget / hooks interceptionCompaction + session and progress filesFull L1~L6 ring
Codex harnessagent loop (core runtime)Assistant message / approval gate / sandbox boundaryThread persistence + retained reasoningFull L1~L6 ring
Gemini CLIcli-driven + core-executed ReAct loopcomplete_task / confirmation gateSession historyMainly L2 / L3
OpenAI Agents SDKRunner loopfinal_output / max_turns / guardrail tripwireRunState / SessionMainly L3
LangGraphExplicit 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 checkpointsL3 / L4
AutoGen / MAFSession message loop → typed graph workflowTermination condition / max_turns / conditional exit edgeMAF checkpointing / AgentThreadL3 / L4
DifyIteration / Loop two node typesArray length (Iteration) or loop_count + break_conditions (Loop)Variable pool snapshot / loop_variables inherited across roundsL3
n8n / CozeVisual loop nodesBounded iteration (structural boundary, not an LLM stopping condition)Inter-node variablesL3

Three semantic differences worth expanding on (source tiers annotated in the table):

  1. 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".
  2. 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).
  3. 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 MeasureContentSource
Hooks interceptionIntercept / modify / block invocations before tool executionAnthropic, A
Sprint ContractReach a contract on the definition of "done" before coding, giving observational verification a basisAnthropic, A
/goal turn capEvaluation-model verification + explicit turn cap (e.g., "stop after 5 tries")Anthropic, A
/loop auto-expiryPeriodic tasks auto-expire 7 days after creation, preventing forgotten loops from persistingAnthropic, A
Sandbox × approval orthogonalSandbox tiers define the technical boundary; approval policy decides when to ask; Auto-review auto-passes low risk and halts high riskOpenAI, A
OTel audit telemetryFull export of prompts, approval decisions, tool results, network eventsOpenAI, A
Budget as defaultOfficials 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:

#LeapSecond-Generation ApproachThird-Generation ApproachKey Evidence (Tier)
1Context from "natural growth" to "active governance"Context accumulates naturally with the conversationThe four-piece set: compression, externalized notes, sub-agent isolation, progressive disclosureAnthropic context engineering blog (A)
2Tools from "vendor-proprietary" to "neutral standard"Function Calling / plugins (proprietary)MCP → AAIF neutral governanceMCP release, AAIF founding (A)
3Evaluation from "bolted-on leaderboards" to "built-in loop"Run a public leaderboard once and check the scoreBuilt-in tracing + Evaluator role + feedback backflow to L1Responses API built-in tracing, three-Agent architecture (A)
4State from "in-session" to "cross-window handoff"Amnesia at session endProgress file + git + feature list + health pre-checkTwo generations of long-running harness (A)
5Governance from "manual prompting" to "sandbox and mechanical enforcement"Per-item permission popupsDual-dimension isolation + credential protection + self-built linter injecting repairsClaude Code sandbox (A, −84% prompts)
6Role from "human commanding" to "human steering"Human commands each action step by stepHuman Steer, Agent ExecuteOpenAI "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:

MetricValue
Starting pointFirst 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 monthsAbout 1 million lines (application logic, infrastructure, tools, documentation, internal developer tools)
PR count / engineer count / per-capita daily PRsAbout 1,500 / 3 engineers (later expanded to 7) / 3.5
Time costAbout 1/10 of hand-writing
Hand-written code by humans0 lines
Longest single-task runtimeOver 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

DecisionContentBelonging Layer
AGENTS.md changed from encyclopedia to table of contentsAbout 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 instructionsThe self-built linter's errors directly inject repair methods into the agent contextL6 → L1 loop
doc-gardening agentAutomatically scans outdated documentation and initiates repair PRsL6
Mechanical enforcement of layered architecture constraintsUnidirectional dependency chain Types → Config → Repo → Service → Runtime → UI; cross-cutting concerns only via ProvidersL6
Observability open to the agentgit worktree startup, Chrome DevTools Protocol, LogQL / PromQL queriesL5 → L1
Minimal-blocking merge philosophyMinimal-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):

  1. The single-Agent vs multi-Agent debate is undecided — Anthropic explicitly states "currently unclear";
  2. 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";
  3. 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);
  4. 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

LevelNameGeneric Definition
L0MissingThe layer does not exist or fully depends on humans; problems are not systematically noticed
L1ManualPractices exist, but rely on human execution and conventions to maintain; not reproducible, not regression-testable
L2Tool-basedDedicated tools or components exist; can execute automatically, but lack governance policy
L3SystematizedClear policy and default architecture; can be measured and can regress in CI
L4Closed-loop autonomousThe layer's output automatically flows back to improve other layers; possesses anti-entropy mechanisms (auto-correction, automatic documentation governance)

11.3. Self-Assessment Table

LayerL0 MissingL1 ManualL2 Tool-basedL3 SystematizedL4 Closed-loop Autonomous
L1 Context EngineeringContext accumulates naturally, no managementManually selecting and pasting contextConnected to RAG / retrievalThe four-piece set of compression + externalized notes + sub-agent isolation + progressive disclosure; has attention budget awarenessContext assembly strategy automatically adjusted by L5 feedback; Skills and docs auto-trimmed and updated
L2 Tooling and ExecutionThe model can only output textA few hard-coded toolsFunction Calling + several proprietary toolsTools 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 ControlSingle-turn invocationManually chaining processesOrchestration framework single loopSupports long-running, Sprint Contract, sub-agent dispatch, determinism + dynamic routing coexistingThe orchestration structure itself can be evaluated and auto-selected; can perform failure-mode analysis on itself
L4 Memory and StateAmnesia at session endManually writing handoff notesHas session persistenceProgress file + git + machine-readable task list + opening health pre-checkState handoff automatically verified; dirty state auto-repaired before the next round opens
L5 Evaluation and ObservabilityRelies on human eyes to see resultsManual spot checksOccasionally runs public benchmarksBuilt-in tracing + self-built Golden Dataset + one regression case added for every real failureEvaluator separated from the evaluated and Evaluator evolves independently; held-out set prevents overfitting; observational data fed back to L1
L6 Governance and SafetyNo boundariesPer-item human approvalHas permission configurationSandbox + credential protection + self-built linter mechanical enforcement; failIfUnavailable hard failure; center enforces boundaries, periphery autonomousGovernance 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 PatternReadingSuggested Action
Most layers at L0~L1Does not yet have a third-generation Harness; at early second generationPrioritize building L2 (tool standardization) and L5 (at least a regression set); defer other layers
Most layers at L2Typical "tools are complete but unstable" statePrioritize attacking L1 (context governance) and L6 (sandbox); these two are the most common bottlenecks
Most layers at L3Reached third-generation mainstream levelFocus is on maintaining: build this Harness's regression mechanism to prevent degradation as models upgrade
L4 layers appearAt frontier explorationNote the risk pointed out in 04-Future Development: excessive Harness complexity may be directly flattened by the next model upgrade
Inter-layer gap ≥ 2 levelsStructural weakness existsThe 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

  1. 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.
  2. Give specific evidence layer by layer during assessment; do not write abstract "medium"; write "our context compaction relies on XXX".
  3. Prioritize the weakest layer, not the average score.
  4. 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

  1. 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.
  2. 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

  1. Section 3.10: context degradation's "performance drop exceeding 45%" and Chroma Research's "all 18 frontier models degraded".
  2. 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".
  3. Section 4.7: Vercel's tool count 15 → 2 accuracy 80% → 100%, Token −37%, speed 3.5×.
  4. Section 5.7: the comparison experiment numbers for Anthropic single Agent (20 minutes / $9 / unusable) vs three Agent (6 hours / $200 / complete and playable).
  5. 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.
  6. 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

  1. ISO/IEC agent interconnection international standard number: no authoritative information currently.
  2. First appearance of the term "Agent Harness": no authoritative information currently.
  3. Claude models' 2026 version timeline: seen only in third-party GitHub timeline repositories; flagged as unverified.

Newly added this round (Chapter 9, Harness Loop)

  1. 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).
  2. 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).
  3. 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).
  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).
  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

  1. Effective context engineering for AI agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
  2. Effective harnesses for long-running agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
  3. Harness design for long-running application development — Anthropic, 2026. https://www.anthropic.com/engineering/harness-design-long-running-apps
  4. 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
  5. Introducing Agent Skills — Anthropic, 2025-10-16 (2025-12-18 open standard update). https://www.anthropic.com/news/skills
  6. Sandboxing: a safer and more autonomous approach — Anthropic, 2025. https://www.anthropic.com/engineering/claude-code-sandboxing
  7. Claude Code official documentation · Sandboxing (Chinese edition) — Anthropic, 2026. https://code.claude.com/docs/zh-TW/sandboxing
  8. Claude Code official documentation · Choose a sandbox environment — Anthropic, 2026. https://code.claude.com/docs/en/sandbox-environments
  9. Introducing the Model Context Protocol — Anthropic, 2024-11-25. https://www.anthropic.com/news/model-context-protocol
  10. Harness engineering: leveraging Codex in an agent-first world — OpenAI, 2026-02-11. https://openai.com/index/harness-engineering/
  11. Harness engineering (Chinese edition) — OpenAI, 2026-02-11. https://openai.com/zh-Hans-CN/index/harness-engineering/
  12. New tools for building agents (Responses API + Agents SDK) — OpenAI, 2025-03-11. https://openai.com/blog/new-tools-for-building-agents
  13. 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/
  14. A year of open collaboration: Celebrating the anniversary of A2A — Google Open Source Blog, 2026-04-16. https://opensource.googleblog.com/
  15. Agent Development Kit — AI Wiki, 2026. https://aiwiki.ai/wiki/google_adk
  16. Model Context Protocol official site and specification — MCP / AAIF, 2024—2026. https://modelcontextprotocol.io/; https://modelcontextprotocol.io/specification/2026-07-28/
  17. MCP Protocol Versions (version evolution table) — MCP Ruby SDK, 2026. https://ruby.sdk.modelcontextprotocol.io/protocol-versions/
  18. MCP Rust-layer protocol version enumeration — mcpkit (docs.rs). https://docs.rs/mcpkit/latest/enum.ProtocolVersion.html
  19. Model Context Protocol entry (including specification evolution) — Klu. http://klu.ai/glossary/model-context-protocol
  20. Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF, 2025-12-09. https://aaif.io/
  21. Harness engineering for coding agent users — Birgitta Böckeler, martinfowler.com, 2026. https://martinfowler.com/articles/harness-engineering.html
  22. SWE-bench: Can Language Models Resolve Real-World GitHub Issues? — Jimenez, Yang et al. (Princeton), 2023-10 (ICLR 2024 Oral). https://www.swebench.com/
  23. Terminal-Bench — Stanford / Laude Institute, 2025. https://www.tbench.ai/
  24. Context engineering entry (naming chain and four pillars) — AI Wiki, 2025—2026. https://aiwiki.ai/wiki/context_engineering
  25. OpenAI Codex entry (sandbox primitives, approval modes, Rust rewrite) — AI Wiki, 2026. https://aiwiki.ai/wiki/codex
  26. Agent Harness: the core paradigm of AI engineering in 2026 — 腾讯云开发者社区, 2026. https://developer.cloud.tencent.com/article/2698416
  27. Terminal-Bench: The CLI Autonomy Standard — AgentMarketCap, 2026-04-09. https://agentmarketcap.ai/blog/2026/04/09/terminal-bench-cli-autonomy-standard-coding-agents
  28. The evolution of Anthropic's Harness engineering architecture (Chinese overview) — 阿里云开发者社区, 2026. https://developer.aliyun.com/article/1724413
  29. How the agent loop works — Anthropic, 2026. https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
  30. Building agents with the Claude Agent SDK — Anthropic, 2025. https://claude.com/blog/building-agents-with-the-claude-agent-sdk
  31. Loop engineering: Getting started with loops — Claude Code team, Anthropic, 2026-06-30. https://claude.com/blog/getting-started-with-loops
  32. 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
  33. How we built our multi-agent research system — Anthropic, 2025. https://www.anthropic.com/engineering/multi-agent-research-system
  34. Unrolling the Codex agent loop — OpenAI, 2025—2026 (publication date unverified, see section 13). https://openai.com/index/unrolling-the-codex-agent-loop/
  35. Codex as a platform: build on the open agent harness — OpenAI Developers, 2026. https://developers.openai.com/blog/codex-as-a-platform
  36. Running agents — OpenAI Agents SDK official documentation, 2026. https://openai.github.io/openai-agents-python/running_agents/
  37. Running Codex safely at OpenAI — OpenAI, 2026. https://openai.com/index/running-codex-safely/
  38. Agent approvals & security — Codex official documentation, 2026. https://developers.openai.com/codex/sandbox
  39. gemini-cli (open-source repository and ReAct loop documentation) — Google, 2025—2026. https://github.com/google-gemini/gemini-cli
  40. 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
  41. Dify node system documentation (Iteration / Loop nodes) — LangGenius, 2026 (via DeepWiki structured index). https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
  42. Iteration Node — Agent Patterns Catalog, 2026. https://www.agentpatternscatalog.org/patterns/iteration-node
  43. Runaway Tool Loops — PolicyLayer, 2026 (case occurred in 2025-11, verified: partial). https://policylayer.com/attacks/runaway-tool-loops