架构 — 第三代 AI Harness 参考架构
1. 阅读说明与定位
1.1. 本章回答的三个问题
本篇是白皮书技术分量最重的两章之一,与第 2 章(概念与发展历史)衔接,回答三个问题:
- 第三代(运行时与评估为中心)Harness 实际长什么样——每一层由哪些组件构成,层与层之间以什么契约衔接;
- 每一层为什么是现在这个形状——它要克服的失败是什么,为此付出了什么代价;
- 一个组织如何判断自己的 Harness 处在什么水平——给出按 5 级成熟度逐层判定的自评工具。
三代演进的时间轴与背景见第 2 章;六层模型在各行业的落地形态见第 4 章(实践)。
1.2. 术语与口径约定
- AI Harness(人工智能驾驭层 / 智能体运行时框架):位于基础模型与真实业务系统之间的工程化承载层,把模型的不确定性转化为工程上的可预期性。定义全文统一,不得改写。
- 六层能力模型:L1 上下文工程层、L2 工具与执行层、L3 编排与控制层、L4 记忆与状态层、L5 评估与观测层、L6 治理与安全层。
- 三代演进:提示词工程时代(2020—2023)→ 工具与编排时代(2023—2025)→ 运行时与评估时代(2025—至今)。
- 事实与判断的区分:本章引用的工程参数均标注来源等级;由本项目推导的结论明确标注"本文判断"。B/C 级来源的数字一律标注 ,仅作方向性参考。
- 来源等级:A 级为厂商或官方一手;B 级为权威二手;C 级为社区转述(数字不核实不引用)。
2. 第三代参考架构总览
2.1. 分层的依据:被失败界定的层
六层模型不是先验的功能划分,而是每一层对应一类独立涌现的瓶颈。当一个长周期智能体任务失败时,工程师的归因几乎总是落在以下六类之一:
| 失败归因 | 对应层 |
|---|---|
| 它根本没看到那份关键文件 / 上下文太长导致丢信息 | L1 |
| 它想做的动作没有被正确定义为工具 / 执行产生了预期外的副作用 | L2 |
| 它做这件事的顺序是错的 / 卡在某个循环里出不来 | L3 |
| 换一次会话它就"忘了"上一轮做到哪 | L4 |
| 它说"完成了",但实际上没完成 | L5 |
| 它做了不该做的事 / 花超预算了 / 谁干的查不出来 | L6 |
层是被失败界定的,不是被功能清单界定的。(本文判断)这是判断一个新组件应该归入哪层的实用判据。
2.2. 总体架构图
图 2-1|第三代架构总览:六层分层设计
┌──────────────────────────────────────────────────────────────────┐
│ L6 治理与安全层 Governance & Safety │
│ 权限 · 沙箱策略 · 凭据保护 · 机械强制 · 熵治理 · 预算护栏 │
│ (横向切面,对 L1~L5 全部施加约束并记录审计) │
└──────────────────────────────────────────────────────────────────┘
▲ ▲ ▲ ▲
│ 约束 │ 约束 │ 约束 │ 审计
┌──┴────────┐ ┌───┴────────┐ ┌───┴─────────┐ ┌──┴──────────┐
│ L1 上下文 │─►│ L2 工具与 │─►│ L3 编排与 │─►│ L5 评估与 │
│ 工程层 │ │ 执行层 │ │ 控制层 │ │ 观测层 │
│ 看到什么 │ │ 能做什么 │ │ 按什么顺序做 │ │ 做得好不好 │
└───────────┘ └────────────┘ └─────────────┘ └─────────────┘
▲ │ │
│ 反馈:改变下次看到什么 │ │
└──────────────────────────────┴───────────────────┘
▲
┌────┴───────────────────────────────────────────┐
│ L4 记忆与状态层 Memory & State │
│ 会话态 · 长期记忆 · 检查点 · 工件 │
│ (时间维度的横向支撑层) │
└────────────────────────────────────────────────┘ 需要强调的是,图中 L5 与 L1 之间的反馈边是第三代与第二代的结构性区别:第二代里评估是外挂的(跑一次榜单,看一眼分数),第三代里评估的输出会回流改变下一次的上下文组装,形成闭环。
2.3. 六层职责总表
| 层 | 名称 | 英文 | 职责 | 输入 | 输出 | 典型实现 |
|---|---|---|---|---|---|---|
| L1 | 上下文工程层 | Context Engineering | 决定模型"看到什么" | 环境状态、检索结果、指令 | 组装后的 token 序列 | RAG、Context Compaction、Prompt Assembly、SKILL.md 渐进式披露、KV Cache 复用 |
| L2 | 工具与执行层 | Tooling & Execution | 决定模型"能做什么" | 工具调用意图 | 受控环境中的副作用 | MCP、Function Calling、沙箱执行器、Computer Use |
| L3 | 编排与控制层 | Orchestration & Control | 决定"按什么顺序做" | 任务目标 | 执行步骤序列 | Agent Loop、Plan-and-Execute、DAG / Workflow、Sub-agent |
| L4 | 记忆与状态层 | Memory & State | 决定"记住什么" | 会话历史、工件 | 跨窗口可恢复的状态 | Session Store、Episodic / Semantic Memory、Checkpoint |
| L5 | 评估与观测层 | Evaluation & Observability | 决定"做得好不好" | 执行轨迹、产物 | 判定、指标、回归信号 | Trace、Eval Set、Golden Dataset、Online Metrics |
| L6 | 治理与安全层 | Governance & Safety | 决定"不能做什么" | 策略、预算、合规要求 | 允许 / 拒绝 + 审计记录 | RBAC、护栏模型、审计日志、Budget Guardrail |
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 rot(上下文腐烂) | 性能梯度,而非硬性悬崖 | 上下文变长时性能渐进退化,不存在安全阈值;上下文必须被持续治理 |
| attention budget(注意力预算) | 自注意力的 n² 关联特性使每增加一个 token 都稀释对其他 token 的注意力 | 上下文是稀缺资源,每放入一个 token 都有机会成本 |
由此推出一条反直觉但被反复验证的结论(本文判断):往上下文里多塞信息,通常是负优化。L1 的建设重点不是"检索更多",而是"删掉更多"。
3.2. 关键组件
| 组件 | 机制 | 来源 |
|---|---|---|
| 压缩(Compaction) | 官方分若干档,最安全轻量的一档为 tool result clearing(清空工具调用结果),已在 Claude Developer Platform 上线。调优纪律:先最大化召回,再提升精度——顺序反了会丢掉后续步骤需要的关键约束 | Anthropic,A 级 |
| 外化笔记与 agentic memory | 把笔记持久化到上下文窗口之外(Claude Code 的 to-do list、NOTES.md),Memory tool 随 Sonnet 4.5 进入 public beta | Anthropic,A 级 |
| 子智能体上下文隔离 | 子 agent 可用数万 token 深入探索,只回传 1,000~2,000 tokens 浓缩摘要——用上下文换并行度,代价是摘要损耗 | Anthropic,A 级 |
| Skills 与渐进式披露 | 三级加载:启动时只载入 name + description;命中后读 SKILL.md 全文;按需读 bundled 文件。官方论断:"the amount of context that can be bundled into a skill is effectively unbounded" | Anthropic(2025-10-16 发布,2025-12-18 转开放标准),A 级 |
除 Anthropic 官方四分法外,业界另一套常用分类法是 LangChain 四支柱(Write / Select / Compress / Isolate,B 级),与官方策略可互相映射:前三项对应压缩、笔记与检索,sub-agent 对应 Isolate。
3.3. 代表性实现
| 实现 | 形态 | 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/ 外置 | A |
| Google ADK | 官方 SDK | Session / Runner 作为状态边界 | A |
| LangChain / LangGraph | 开源框架 | 四支柱理论最完整的落地,可通过 node 边界做 Isolate | B |
3.4. 设计权衡
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 召回 vs 精度 | 全量塞入(高召回、易腐烂) vs 精准检索(高精度、易遗漏) | 官方给的顺序:先召回后精度 |
| 深度 vs 干净 | 主上下文全量保留 vs 子 agent 摘要(干净但有损) | 任务是否需要跨步骤强一致性 |
| 静态注入 vs 动态加载 | 一次性注入全部指令 vs Skills 渐进披露 | 路由命中率是否足够高;命中率低时渐进披露反而更差 |
3.5. 典型失败模式
| 失败模式 | 含义 | 典型症状 |
|---|---|---|
| context poisoning | 错误信息在会话中被当作事实传播 | 一次工具报错后,后续全部推理建立在错误前提上 |
| context distraction | 关键信息被噪声淹没 | 检索返回 50 段相关片段,模型只用了前 3 段 |
| context confusion | 冗余信息导致失焦 | 指令中加入过多"也可以这样"的建议,模型随机二选一 |
| context clash | 上下文内部指令冲突 | AGENTS.md 与 SKILL.md 对同一问题给出不同做法 |
量化补充(C 级):2025 年研究显示"语义一致但无关的数据可使性能下降超过 45%";Chroma Research 2025-07 测试 18 个前沿模型,每一个都随上下文变长而退化。
4. L2 工具与执行层
4.1. 职责与组件构成
L2 回答的问题是:模型能对环境施加哪些动作,这些动作在哪里执行。三类组件:
| 组件类别 | 作用 | 代表 |
|---|---|---|
| 工具注册与描述 | 把外部能力声明为结构化接口 | Function Calling、JSON Schema 工具描述 |
| 连接协议 | 让工具生态与宿主应用解耦 | MCP(Model Context Protocol) |
| 执行环境 | 限定动作的作用范围与副作用边界 | 沙箱(Seatbelt / bubblewrap + socat / Landlock + seccomp) |
工具设计准则(Anthropic,A 级):自包含、对错误健壮、用途极其明确;避免功能过载与决策点含糊;少样本示例"多样而典型"。与之呼应的是系统提示词的"正确海拔"(right altitude)原则:足够具体以有效引导行为,又足够灵活以给模型留下判断空间。
4.2. MCP:连接标准及其演进
MCP 采用 Host / Client / Server 三角色架构(A 级):Host 为顶层应用,内含 Client;Client 与每个 Server 保持 1:1 连接;Server 暴露 Tools / Resources / Prompts。传输方式:本地 stdio,远程 Streamable HTTP,消息基于 JSON-RPC 2.0。
五版规范演进链(MCP 官方协议版本页等,A 级):
| 版本 | 关键变更 |
|---|---|
| 2024-11-05 | 初始协议版本:stdio + HTTP+SSE;三原语 |
| 2025-03-26 | Streamable HTTP 取代 HTTP+SSE;OAuth 2.1;工具注解 |
| 2025-06-18 | Elicitation;结构化工具输出;MCP-Protocol-Version 头必需;移除 JSON-RPC batching(破坏性变更) |
| 2025-11-25 | Tasks(异步状态跟踪);并行工具调用;服务端 agent 循环 |
| 2026-07-28 | 协议核心无状态化(移除 initialize 握手与 Mcp-Session-Id);引入 Extensions 框架;强化授权;正式弃用策略(最短 12 个月窗口) |
Google 官方对 MCP 与 A2A 的分工界定(《A year of open collaboration》,2026-04-16,A 级):MCP 管内部工具接入,A2A 管智能体之间的外部协同。两者是不同方向的连接协议,不是竞争关系。
从演进链可以读出三个取向(本文判断):从有状态会话走向无状态请求;从"够用就行"走向"可演进";从"只有工具"走向"服务端也有 agent"。
4.3. 沙箱:副作用边界的工程实现
Claude Code 沙箱是目前公开披露最完整的 Agent 沙箱设计(A 级)。
核心安全公理:文件系统隔离与网络隔离缺一不可——无网络隔离,被攻陷的 agent 可以外传 SSH 密钥;无文件系统隔离,被攻陷的 agent 可以轻易逃逸并获取网络访问。
| 项目 | 参数 |
|---|---|
| macOS 实现 | Seatbelt |
| Linux / WSL2 实现 | bubblewrap + socat(可选 seccomp 过滤器) |
| 默认写入 | 沙箱内命令只能写当前工作目录与会话临时目录 |
| 默认读取 | 默认全机可读(除被显式拒绝的目录) |
| 网络出口 | 只能经 unix domain socket 连接沙箱外代理服务器;新域名首次请求时提示批准 |
| 凭据保护 | sandbox.credentials 可对文件(~/.aws/credentials、~/.ssh)与环境变量(GITHUB_TOKEN、NPM_TOKEN)执行 deny;v2.1.199+ 支持 mode: "mask" |
量化效果(A 级,本层最核心的数字):Anthropic 内部使用发现,沙箱化安全地将权限提示减少了 84%。
横向对照(Codex CLI,B 级,具体参数 ):macOS 用 sandbox-exec(Seatbelt),Linux 用 Landlock + seccomp,Windows 用 job objects;默认禁用网络;批准档位为 Suggest / Auto-edit / Full-auto。2026-04 新增 Auto-review 模式,内部会话为人类审批而停止的次数约为手动模式的 1/200,审阅批准率约 99%。
4.4. 设计权衡与失败模式
| 权衡 | 两端 | 立场 |
|---|---|---|
| 沙箱强度 vs 可用性 | 强隔离(安全但常需逃生舱) vs 弱隔离(好用但风险外溢) | 隔离要成对(文件系统 + 网络),而非"尽量强" |
| 工具数量 vs 准确率 | 工具越多能力越广 vs 选择越难 | 减法优先。Vercel 把工具数从 15 削减到 2,准确率 80% → 100%,Token −37%,速度 3.5×(C 级) |
| 原生插件 vs 标准协议 | 性能好但锁定 vs 解耦但有余开销 | 第三代普遍选 MCP 路线;偏离需有明确理由 |
典型失败模式:工具语义重叠导致随机选择且不可复现;dangerouslyDisableSandbox 被频繁使用使隔离形同虚设;子进程继承凭据环境变量导致泄漏;网络出口失控外传数据;工具数膨胀导致准确率与成本双输。对策分别为:工具评审做"两两可区分性"检查、关闭逃生舱(Strict sandbox mode)、凭据显式 deny / mask、强制代理与出口白名单、定期工具减法。
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. 长时运行的两代官方解法
第一代官方解法(Anthropic《Effective harnesses for long-running agents》,A 级):Initializer Agent + Coding Agent 双 Agent 分工。 Initializer 产出交接包:init.sh(环境一键拉起)、claude-progress.txt(进度文件)、初始 git commit(回滚基点)、JSON 功能清单(含 passes 字段的任务总账本)。Coding Agent 会话开场三步固定为:pwd 确认目录 → 读取 git 日志与进度文件 → 读取功能清单选最高优先级未完成项。两条硬规矩:移除或修改测试不可接受;会话结束必须把环境留在可合并的干净状态。
第二代官方解法(Anthropic《Harness design for long-running application development》,2026,A 级):Planner / Generator / Evaluator 三角色分工(设计灵感来自 GAN)。Planner 把 1~4 句高层提示转成完整产品规格,刻意停留在高层;Generator 每个 sprint 实现一个功能;Evaluator 对产品深度、功能性、视觉设计、代码质量四项评分,每项有硬阈值,任一项低于阈值则该迭代失败。三个关键机制:
- Sprint Contract(冲刺契约):编码前就"要构建什么 + 如何验证成功"达成共识——在开始之前先就"完成"的定义达成一致,这是该层最重要的过程设计。
- self-evaluation bias(自卖自夸):agent 自评会"自信地称赞"明显平庸的作品,这是分离 Evaluator 的根本理由。
- context anxiety(上下文焦虑):agent 在上下文接近上限时倾向仓促收尾、提前宣布完成。
未决问题(官方自陈,A 级):单个通用编码代理是否总是最优,还是拆成专职代理的多代理架构更好——目前尚不清楚。
第三条路线:托管化运行时(2026-09-12 快照增补;2026-09-13 快照升级证据等级)。 上述两代解法都是 Anthropic 给出的自建 Harness 方法论——团队自己搭编排、自己管状态、自己设计评估。2026 年出现了与之并列的第三条路线:由厂商代管运行时本身。可引证的两个节点是 AWS Bedrock AgentCore 于 2026-06 转 GA,以及 OpenAI Agents API 于 2026-09-10 进入公测(A级——OpenAI 官方 Changelog 记载,2026-09-13 快照核实;上一快照依媒体报道记为 09-11,已修正;详见 08-发展展望 §4.3 与调研库 03-市场研究/02-AI-Agents组/21-openai-agents-api.md)。其形态是把 L3 编排、L4 状态持久化与 L5 追踪观测打包为服务端能力,调用方不再自建循环,只提交任务与工具集。
三条路线的取舍可归结为一个权衡:
| 维度 | 自建 Harness(Anthropic 两代解法) | 托管化运行时(AgentCore / Agents API) |
|---|---|---|
| 控制力 | 循环、状态、评估集全部可控可改 | 循环与状态由厂商定义,可改范围受 API 约束 |
| 建设成本 | 高,需自建编排、检查点与评估设施 | 低,开箱可用 |
| 轨迹数据归属 | 落在自有存储,可沉淀为评估集与失败模式库 | 落在厂商侧,取回与迁移能力取决于平台导出能力 |
| 迁移成本 | 与模型解耦,换模型成本低 | 与平台强绑定,跨平台迁移需重写编排层 |
| 适用判断 | 长时、高风险、需审计留痕的任务 | 中短时、容错高、追求上线速度的任务 |
判断:托管化运行时并不取代自建 Harness,而是把"自建"的必要性上移——它吸收的是通用编排与状态持久化这部分无差异能力,而 04-实践 章反复出现的瓶颈(行业判据、评估集、治理红线)仍然无法被托管,仍需自建。这与本白皮书"Harness 是独立工程层"的核心判断一致:正因为它是独立的一层,才既可以被厂商托管,也可以在托管之上继续叠加自建约束。
5.3. 设计权衡与失败模式
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 单 Agent vs 多 Agent | 上下文连贯 vs 并行与干净窗口 | 官方自陈"尚不清楚",建议按任务做 A/B |
| 规划粒度 | Planner 给足细节 vs 刻意停留高层 | 官方选择刻意停留高层 |
| 确定性 vs 灵活性 | 状态机可复现 vs LLM 路由适应性强 | 业务流程选前者,探索任务选后者;Google ADK 的答案是两者并存 |
| 成本 vs 质量 | 多 Agent 明显更贵 | 对比实验显示(C 级):单 Agent 20 分钟 / $9 / 产出不可用;三 Agent 6 小时 / $200 / 产出完整可玩 |
典型失败模式与对策:无限循环 → 迭代上限 + 反漂移检测;目标漂移 → Sprint Contract + 周期性重注入原始目标;提前宣布完成 → 强制清单式自我验证;环境脏状态 → 结束前回到可合并干净状态;测试被修改以通过 → 把"移除或修改测试"定为不可接受。
6. L4 记忆与状态层
6.1. 职责与问题陈述
L4 回答的问题是:跨会话、跨上下文窗口时,状态如何交接。Anthropic 官方对这一难题的表述极为形象(A 级):
想象一个由工程师轮班工作的软件项目,每位新工程师上班时,对前一班发生的事情毫无记忆。
这句话也解释了为什么 L4 在第三代才成为独立关注点:第一、二代的任务时长还在单个上下文窗口内,问题根本不会出现。
6.2. 关键机制
跨窗口状态交接的官方方案(A 级):
| 交接载体 | 承载内容 | 特点 |
|---|---|---|
claude-progress.txt | 自然语言进度记录 | 可读、可被模型理解 |
| git 历史 | 结构化变更记录 | 可回滚、可 diff |
JSON 功能清单(含 passes) | 任务总账本 | 机器可判定的完成度 |
| 初始 git commit | 回滚基点 | 保证每轮可回到已知健康状态 |
配套两条纪律:动手实现新功能之前必须先跑端到端健康度检查(理由是模型"倾向于在没有充分测试的情况下就宣布功能完成");给 agent 配备浏览器自动化工具(如 Playwright MCP)做人工级验证,官方明确表示这显著提升了表现。
Compaction 与 Context Reset 的分工(A 级):Compaction 就地摘要,保留连续性,但"上下文焦虑"仍在;Context Reset 清空后重新注入,给干净白板,但交接产物必须足够完整。二者关系可以概括为(本文判断):Compaction 是治标(延缓腐烂),Reset 是治本(彻底清创),但 Reset 的成本转移到 L4 层的交接质量上。
Git 作为状态载体:第三代的一个显著特征是把 Git 当作状态与记忆的载体,而不是另起一套记忆数据库——好处是继承人类工程团队已有的全部工具(diff、blame、revert、CI),代价是需要额外约定提交粒度与分支策略。
6.3. 设计权衡与失败模式
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 自然语言 vs 结构化状态 | 灵活但不可机判 vs 可机判但僵化 | 官方选择两者都要 |
| 保留 vs 重置 | 连续性好 vs 干净 | 长任务建议周期性 Reset + 高质量交接包 |
| 专用记忆库 vs Git | 语义检索强 vs 工具生态成熟 | 第三代普遍取 Git 优先,专用记忆作为补充 |
典型失败模式与对策:失忆重启 → 强制开场三步;进度文件腐烂 → 把 git 历史作为唯一事实源,进度文件只做摘要;脏交接 → 干净状态收尾 + 开场健康度预检;检查点粒度失控 → 显式约定提交粒度与分支策略。
7. L5 评估与观测层
7.1. 职责与第一原则
L5 回答的问题是:做得好不好,如何判定,如何回归。这一层在第三代获得了最高的地位提升,原因可以用一句官方判断概括(Anthropic,A 级):
"Harness design is key to performance at the frontier of agentic coding."
第一原则:评估者与被评估者分离。 官方观察(A 级):让 agent 评估自己的作品时,它会"自信地称赞"——即便人类观察者眼中质量明显平庸。官方给出的理由是:
把一个独立的 Evaluator 调教得怀疑,远比让 Generator 自我批判容易得多。(灵感来自 GAN)
实现方式:Evaluator 对四个维度分别设定硬阈值,任一项低于阈值则该迭代失败,并把详细失败原因反馈给 Generator。这条原则对非编码场景同样成立(本文判断):做任何主观质量类 agent 任务时,都应设置一个与生成方隔离的判定方,无论它是一条规则、一个脚本,还是另一个模型。
7.2. 外部基准与内置闭环
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 级)确立的原则是程序化判分:测试通过即通过。Terminal-Bench 的原则同样是 "either the automated tests pass or they do not"。
可观测性对 agent 开放是 OpenAI《Harness engineering》(2026-02-11,A 级)给出的一个极具启发性的实践:应用可按 git worktree 独立启动;浏览器调试协议(Chrome DevTools Protocol)接入 agent 运行时;指标与日志经本地可观测栈暴露,agent 可用 LogQL 与 PromQL 直接查询;性能要求写成可测量的验收条件(示例:"确保服务启动在 800ms 内完成")。其工程意义是:把 L5 的观测能力反向供给 L1 作为上下文——agent 不再是盲写的黑盒。
7.3. 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."
以下对照数据全部为 B/C 级来源,一律标注 ,仅作方向性参考:
| 对照项 | 数据 | 说明 |
|---|---|---|
| Factory Droid + GPT-5.3-Codex | 77.3% | 与下一行同为 GPT-5.3-Codex |
| OpenAI Simple Codex + GPT-5.3-Codex | 75.1% | 2.2 个百分点纯由 scaffold 差异造成 |
| KRAFTON Terminus-KIRA + Claude Opus 4.6 | 74.7% | 与下一行同为 Claude Opus 4.6 |
| Bigai TongAgents + Claude Opus 4.6 | 71.9% | 相差 2.8 个百分点 |
| LangChain 仅改 Harness(同模型、同 API) | 52.8% → 66.5% | 排名从 30 名外跃升至前 5 |
LangChain 那次 "52.8% → 66.5%" 的五项改动清单(C 级,,但改动项本身有工程参考价值)全部不涉及换模型:
- 强制清单式自我验证后才允许说"完成";
- 启动前扫描目录结构并注入环境上下文;
- 反漂移检测——重复编辑同一文件时告警;
- 调整推理预算——规划验证多想、实现少想;
- 自动失败模式分析。
7.4. 设计权衡与失败模式
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 主观评分 vs 二值判据 | 覆盖主观任务 vs 客观可复现 | 优先把主观任务"翻译"成可二值判定的子项;无法二值化的才用 Evaluator 评分 + 硬阈值 |
| 评估频率 vs 成本 | 每步评(贵但反馈及时) vs 终局评(省但归因难) | 短链路终局评,长链路分 sprint 评 |
| 覆盖率 vs 维护成本 | 评估集越大越准 vs 越难维护 | 与其铺量,不如做"每次真实失败都补一条回归 case" |
典型失败模式与对策:自卖自夸 → 评估者与被评估者分离;评估集过拟合 → 定期轮换评估集、保留 held-out 集;只看终局分 → 轨迹级 tracing;指标与业务脱节 → 建立自己的 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.failIfUnavailable 可设为硬失败——沙箱起不来就拒绝运行,而不是悄悄降级。这是治理健壮性的一条重要经验(本文判断):不要让安全机制有静默降级路径。
架构约束的机械强制(OpenAI,A 级):分层依赖规则被机械强制而非靠 code review 口头约定——
Types → Config → Repo → Service → Runtime → UI 横切关注点只能经 Providers 单一接口进入。品味不变量(Taste Invariants)通过自研 linter 静态强制结构化日志、schema 与类型命名约定、文件大小限制。最关键的工程技巧是:linter 的错误消息被写成向 agent 上下文注入修复指令——linter 不只是"报错",而是"报错 + 教 agent 怎么改"。这把 L6 的失败信号直接转化为 L1 的上下文输入,形成闭环。官方总结:
在人类优先的工作流中,这些规则可能令人觉得迂腐;有了 agent,它们成为倍增器——一旦编码,立即处处生效。
垃圾回收:对抗熵增(OpenAI,A 级):doc-gardening agent 定期扫描过时文档并自动发起修复 PR。官方归纳的四大失败模式:上下文是稀缺资源;过多指导变成无指导(AGENTS.md 写得太长,agent 会像人一样跳过阅读);文档立即腐烂;难以机械验证。
8.3. 设计权衡与失败模式
| 权衡 | 两端 | 取舍依据 |
|---|---|---|
| 硬失败 vs 静默降级 | 可用性 vs 安全确定性 | 治理机制应避免静默降级 |
| 中心强制 vs 局部自治 | 一致性 vs 灵活性 | 官方答案:中心强制边界,局部允许自治 |
| 规则数量 vs 遵从度 | 规则越全越好 vs 太多则被忽略 | 规则要少而可机械强制;过多文档等于无文档 |
典型失败模式与对策:权限疲劳 → 沙箱化 + Auto-allow(−84% 提示);文档腐烂 → doc-gardening agent + 文档纳入 CI 校验;规则不可机检 → 自研 linter、错误消息写成修复指令;审计不可追溯 → 全层 tracing + 结构化日志;预算失控 → Budget Guardrail + 单步/单任务成本上限。
9. Harness Loop:把模型不确定性收敛为可控迭代
前八章把六层逐层拆开;本章回到把它们串起来的那根轴——主循环。用一句话区分两个视角:六层模型回答"Harness 由什么组成",Harness Loop 回答"Harness 每一秒在做什么"。
9.1. 为什么 Loop 是 Harness 的第一公民
对"Loop 是 Harness 的第一公民"这一判断,有三组相互独立的证据(本文判断,证据均标注来源等级):
其一,官方命名证据。 Anthropic《Loop engineering: Getting started with loops》(2026-06-30,A 级)以"循环"为核心命题,官方定义为"循环 = 智能体重复执行工作周期,直到满足停止条件";Claude Agent SDK 官方文档设专章《How the agent loop works》(A 级);OpenAI 则直接把 agent loop 等同于 harness 的核心——"可复用的部分就是 agent loop"(《Codex as a platform》,A 级)。两大头部厂商不约而同地以循环、而非模型,作为产品与文档叙事的中心。
其二,评测变量证据。 OpenAI 官方披露(A 级,信息截止 2026-09-12):在 ARC-AGI-3 基准上,保留推理(retained reasoning)+ 上下文压缩使 GPT-5.6 Sol 得分从 13.3% 提升至 38.3%,同时输出 token 减少 6 倍。同一模型、只改循环机制,提升 25 个百分点——这与 7.3 节 Terminal-Bench "榜单排名的是系统而非模型"互为印证:循环设计是独立于模型的性能变量。
其三,失败模式证据。 Anthropic 官方命名的长任务失败模式——一次性做太多(one-shot)与过早宣告完成(premature completion)——都是循环级失败:不是某一步做错,而是圈的边界设计错误(A 级)。业界流传的 $47,000 多代理乒乓失控事故(B 级,verified: partial,多帖一致但无具名受害企业)展示了无界循环的成本后果;业界实践估计失控循环成本可达正常任务的 30 倍(C 级)。
三组证据合起来的结论是(本文判断):模型的不确定性来自单次调用,循环把单次调用变成可观测、可校验、可终止的迭代单元——收敛不发生在模型里,发生在循环里。
9.2. Loop × 六层模型对照
Harness Loop 不是第六层之外的"第七层",而是六层在时间维度上的展开。统一对照如下:
| 层 | 在 Loop 中的位置 | 官方证据 |
|---|---|---|
| L1 上下文工程层 | 每圈开头的目标装配:prompt = 系统提示 + 工具定义 + 会话历史 + 工具结果回流 | Anthropic SDK 五步官方定义(A 级);compact_boundary 消息显式标记压缩边界(A 级) |
| L2 工具与执行层 | 每圈中段的工具执行:调度、确认、沙箱执行 | Codex 审批门与沙箱档位(A 级);Gemini CLI CoreToolScheduler 四步(B 级) |
| L3 编排与控制层 | 循环本体:再计划与控制流转移 | 子代理派发、handoff、LangGraph 条件边(A / B 级) |
| L4 记忆与状态层 | 每圈结尾的状态更新与跨圈检查点 | LangGraph Checkpointer 每 superstep 落盘(B 级);进度文件 + git 交接(A 级) |
| L5 评估与观测层 | 每圈的观测校验:用量、成本、完成判定 | ResultMessage 携带 token 用量与成本(A 级);/goal 评估模型核验(A 级) |
| L6 治理与安全层 | 包住整环的治理边界:约束并记录每一圈 | hooks 拦截、审批档位、预算上限、OTel 审计(A 级) |
对照关系如图 9-1 所示。
图 9-1|Harness Loop × 六层模型对照
示意图:基于本文分析,对照口径沿用本库参数卡统一六层模型(信息截止 2026-09-12)。
9.3. 终止条件与治理边界:把 L6 写进循环里
"循环什么时候停"不是实现细节,而是 Harness 与使用者的核心契约。统一口径把终止条件分为五级:
| 级别 | 终止条件 | 代表机制 | 证据等级 |
|---|---|---|---|
| ① | 任务完成判定(DoD 校验) | 无工具调用的最终响应;complete_task 工具;/goal 评估模型核验未达标打回 | A / B |
| ② | 预算耗尽 | max_budget_usd 费用阈值;显式 token 预算(如 "use 10k tokens") | A |
| ③ | 权限边界触发 | hooks 拦截;审批档位 × 沙箱档位正交组合;guardrail tripwire 即抛异常终止 | A |
| ④ | 人工中断(HITL) | interrupt_before 挂起等人工续跑(可恢复);RunState 恢复被中断的运行 | A / B |
| ⑤ | 死循环检测 / 到期 | max_turns 抛 MaxTurnsExceeded;recursion_limit 默认 25 熔断;周期任务 7 天自动到期 | A / B |
第三代治理的关键动作,是把 L6 从"循环外的审批人"改写为"循环内的每一圈"(本文判断):hooks 拦截发生在工具执行之前,在圈内(A 级);审批档位(untrusted / on-request / never)与沙箱档位(read-only / workspace-write / danger-full-access)正交组合,定义了每一圈的可行域(A 级);Auto-review 自动审批子代理按计划动作与近期上下文放行低风险操作、截停高风险操作(A 级);OpenAI 自部署实践中,OTel 遥测把每圈的 prompt、审批决定、工具结果、网络事件全部导出接 SIEM(A 级)。
官方对预算的态度值得直接引用(A 级):"预算上限是生产 agent 的良好默认。" 超限语义同样有讲究:LangGraph 的 recursion_limit 被官方论坛定位为"熔断器而非业务逻辑",超限是"可恢复的暂停"而非死亡——配合 Checkpointer 可从最后落盘状态续跑(B 级);业界实践建议超限时返回部分结果(进度摘要)而非裸错误(C 级)。
9.4. 框架循环语义光谱
各框架的循环语义落在一条光谱上:一端是结构性有界循环("结构决定何时停"),另一端是模型自主循环 + 治理兜底("模型决定何时停")。
- 结构性有界:Dify 的 Iteration 节点遍历数组、每元素物化独立子引擎,并行度默认 10、单节点最大迭代默认 100;n8n / Coze 的可视化循环节点属同一模式——迭代必须有界于数组长度而非 LLM 停止条件(B 级,n8n / Coze 官方一手循环文档未直接获取,见 15 节缺口声明)。
- 条件有界:Dify 的 Loop 节点由 loop_count + break_conditions + 跨轮继承的 loop_variables 构成;MAF Workflow 要求循环必须至少一条条件退出边 + max_turns 兜底(B 级)。AutoGen GroupChat 因 LLM 选人导致循环不可预测、终止条件含糊时可无限循环,是"隐式消息循环 → 显式类型化图"演进的直接动因(B 级)。
- 模型自主 + 兜底:LangGraph 条件边到 END + recursion_limit 熔断 + Checkpointer 可恢复(B 级);OpenAI Agents SDK 的 final_output + max_turns + guardrail tripwire(A 级);Codex harness 的 assistant message + 审批门(A 级);Claude Code 的无工具调用响应 + 预算 / hooks(A 级)。
光谱分布如图 9-2 所示。
图 9-2|框架循环语义光谱
示意图:基于本文分析(信息截止 2026-09-12)。
9.5. 企业落地建议
把 Loop 当作第一公民来建设,意味着预算、遥测与人工介入都应围绕"圈"来设计,而不是围绕单次 API 调用。三条主线:
| 主线 | 建议 | 依据 |
|---|---|---|
| 循环预算 | 三重硬限组合:迭代上限(简单问答 10 / 研究型 25 / 编码型 50~100,按 p95 合法任务 2~10 倍设定)+ token 预算(合法任务均值 10 倍,消耗 80% 即告警)+ 墙钟超时(p95 的 2~3 倍);超限返回部分结果(进度摘要)而非裸错误;kill switch 带唯一 ID 置于网关层——逃逸的 agent 不会遵守自己代码里的限额 | 业界实践,C 级;"预算上限是生产 agent 的良好默认"为官方表述(A 级) |
| 循环遥测 | 按 OTel span 树(session → step → LLM call)组织轨迹;核心指标:每步延迟分位(P50 / P95 / P99)、每会话 token、按模型与步拆分的成本、错误率与重试频率;启发式告警"超过 10 步疑似循环";对合规敏感场景启用审批决定与网络事件的全量导出接 SIEM | 社区观测方案(B 级);Codex 原生 OTel 导出(A 级) |
| HITL 门 | 审批档位 × 沙箱档位正交组合,按任务授予权限、用完即收;破坏性动作默认拒绝;循环中挂起必须可恢复(挂起而非杀死),恢复点落盘 | Codex 审批与沙箱文档(A 级);LangGraph interrupt_before + Checkpointer(B 级) |
三条主线的共同逻辑与本章开头一致:单次调用的不确定性无法消除,但每一圈可以被装配、被观测、被约束、被终止。 循环预算把"失控"变成"可预期的止损",遥测把"黑盒迭代"变成"可归因的轨迹",HITL 门把"人工审批"从循环外的瓶颈变成循环内的弹性闸门。
Loop 与层间契约的关系(每圈跨层时的数据流转约定)见第 10 章。
10. 层间契约与数据流
10.1. 主执行链与两条横向支撑
主执行链为 L1 → L2 → L3:先决定看到什么,再决定能做什么,最后决定按什么顺序做。横向支撑为 L4(时间维:跨会话、跨窗口的状态)与 L6(约束维:权限、预算、审计)。闭合回路为 L5 → L1:评估与观测的输出回流,改变下一次的上下文组装。
10.2. 两个关键反馈回路
第三代架构中存在两个已被官方实证的跨层闭环(本文判断,均有 A 级证据支撑):
| 回路 | 路径 | 官方证据 |
|---|---|---|
| 治理回路 | L6 → L1 | 自研 linter 的错误消息直接向 agent 上下文注入修复指令(OpenAI) |
| 评估回路 | L5 → L1 | 可观测性栈对 agent 开放(LogQL / PromQL 查询),agent 像工程师一样看日志、查指标、验证改动是否达标(OpenAI);Evaluator 的失败原因回流给 Generator(Anthropic) |
10.3. 层间契约清单
| 契约 | 上游承诺 | 下游依赖 |
|---|---|---|
| L1 → L2 | 工具结果以受控体积、结构化形式进入上下文 | 工具单次返回超限时截断并摘要,禁止大输出直接灌入 |
| L2 → L3 | 每个工具调用有明确副作用分级(只读 / 工作区写 / 沙箱执行 / 共享状态写 / 破坏性) | 编排层据此决定自动执行还是请求人工确认 |
| L3 → L4 | 每个编排阶段产出可持久化的状态(进度、清单、检查点) | 新会话按固定开场三步恢复状态 |
| L3 → L5 | 任务开始前先就"完成"的定义达成契约(Sprint Contract) | Evaluator 按契约判定,而不是事后解释 |
| L4 → L1 | 交接包(进度文件 + git + 功能清单)完整可机读 | 下一次上下文组装可直接消费 |
| L6 → 全部 | 权限拒绝必须可追溯,安全机制无静默降级 | 所有层的执行记录进入 append-only 审计日志 |
| L5 → L1 | 每次真实失败补一条回归 case | 回归信号改变上下文组装策略 |
11. 从第二代到第三代的关键跃迁
11.1. 六条跃迁清单
| # | 跃迁 | 第二代做法 | 第三代做法 |
|---|---|---|---|
| 1 | 上下文从"自然增长"到"主动治理" | 上下文随对话自然累积 | 压缩、外化笔记、子 agent 隔离、渐进披露四件套 |
| 2 | 工具从"厂商专有"到"中立标准" | Function Calling / 插件(专有) | MCP → AAIF 中立治理 |
| 3 | 评估从"外挂榜单"到"内置闭环" | 跑一次公开榜看分数 | 内置 tracing + Evaluator 角色 + 反馈回流 L1 |
| 4 | 状态从"会话内"到"跨窗口交接" | 会话结束即失忆 | 进度文件 + git + 功能清单 + 健康度预检 |
| 5 | 治理从"手工提示"到"沙箱与机械强制" | 逐条权限弹窗 | 双维隔离 + 凭据保护 + 自研 linter 注入修复 |
| 6 | 角色从"人指挥"到"人掌舵" | 人逐步指挥每个动作 | Human Steer, Agent Execute |
第 6 条是整个跃迁的哲学内核:人的工作从"操作"上移到"设计环境、反馈回路与控制系统"(OpenAI 原文:"Our most difficult challenges now center on designing environments, feedback loops, and control systems.")。
11.2. 跃迁的完整范式样例
第三代 Harness 最完整的公开实证,是 OpenAI《Harness engineering》(2026-02-11,A 级)披露的内部实验,以下数字全部为一手:
| 指标 | 数值 |
|---|---|
| 起点 | 2025-08 下旬对空仓库首次提交;脚手架由 Codex CLI + GPT-5 生成,连最初的 AGENTS.md 也是 Codex 写的 |
| 五个月后代码量 | 约 100 万行(应用逻辑、基础设施、工具、文档、内部开发工具) |
| PR 数 / 工程师数 / 人均日 PR | 约 1,500 / 3 名(后扩至 7 名)/ 3.5 |
| 时间成本 | 约为手写的 1/10 |
| 人类手写代码 | 0 行 |
| 单任务最长运行时长 | 超过 6 小时 |
一条反直觉观察:团队从 3 人扩至 7 人后吞吐反而上升——与传统软件工程"加人会让 PR 冲突加剧"的直觉相反,说明该 Harness 的协调开销低于新增人力带来的产出。
六项关键工程决策及其归属层:
| 决策 | 内容 | 归属层 |
|---|---|---|
| AGENTS.md 从百科全书改为目录 | 约 100 行注入上下文,细节位于结构化 docs/;"给 Codex 一张地图,而不是一本 1000 页的说明书" | L1 |
| linter 错误消息写成修复指令 | 报错直接向 agent 上下文注入修复方法 | L6 → L1 闭环 |
| doc-gardening agent | 自动扫描过时文档并发起修复 PR | L6 |
| 分层架构约束的机械强制 | 单向依赖链;横切关注点仅经 Providers | L6 |
| 可观测性对 agent 开放 | git worktree 启动、Chrome DevTools Protocol、LogQL / PromQL | L5 → L1 |
| 最小阻塞合并哲学 | PR 短命,测试 flakiness 靠重跑解决——"纠错成本低,等待成本高" | L3 |
另有一条通用选型原则(本文判断,值得单独记住):倾向"无聊的技术"(可组合性、API 稳定性、在训练语料中广泛存在)。在 agent 会写代码的系统里,技术的"模型熟悉度"是真实的选型指标,与性能、生态并列。
11.3. 跃迁尚未完成的部分
以下问题为官方自陈尚未解决的(A 级):
- 单 Agent vs 多 Agent 之争未决——Anthropic 明确表示"目前尚不清楚";
- 跨领域泛化未验证——编码场景的经验能否推广到科学研究或金融建模等其他长周期任务,"答案尚在摸索中";
- Harness 自身缺乏评估方法——martinfowler.com 提出的开放问题:我们需要类似代码覆盖率和变异测试的 Harness 覆盖率与质量评估方法(尚未出现);
- 熵治理仍靠补丁——doc-gardening 是对腐烂的补救,而非对腐烂的根治。
12. 跨层横切关注点
以下四类关注点不属于任何单层,而是穿透六层的横切面。把它们单独立章,是因为工程实践中最常见的失败,不是某一层没建好,而是某一类横切需求只在一层被处理、在其他层被遗漏(本文判断)。
12.1. 成本:从 token 计费到任务级预算
成本约束穿透六层的方式:
| 层 | 成本接口 |
|---|---|
| L1 | attention budget 是成本的第一形态:多塞一个 token 既是钱也是质量损失 |
| L2 | 工具调用按次计费;工具减法(Vercel 15 → 2)同时降低成本与提高准确率 |
| L3 | 编排结构的成本量级差异巨大:单 Agent(20 分钟 / $9 / 不可用)对三 Agent(6 小时 / $200 / 完整可玩),;最小阻塞合并哲学"纠错成本低,等待成本高"是成本—质量的显式取舍 |
| L4 | 上下文压缩与 Context Reset 直接节省 token 成本;Skills 用代码替代 token(官方经济理由:排序一个列表,用 token 生成远贵于跑一次排序算法) |
| L5 | 评估本身有成本;分 sprint 评估是为控制评估开销 |
| L6 | Budget Guardrail 设单次任务与单日预算上限,超限即中断并升级 |
12.2. 延迟:从响应速度到端到端闭环时长
延迟在智能体场景的含义已经改变:单个调用慢几百毫秒通常不重要,端到端闭环时长(从任务发起到可验证完成)才是关键指标(本文判断)。横切表现:
- L2:沙箱启动与工具往返是延迟常项;非沙箱执行的延迟节省不应以安全为代价。
- L3:长时运行架构把"延迟"重新定义为"小时级"——单任务最长超过 6 小时(OpenAI,A 级);中断与恢复能力因此成为延迟问题的真正解法。
- L5:性能要求被写成可测量验收条件("确保服务启动在 800ms 内完成",OpenAI,A 级),延迟从体验问题变为 L5 的判定对象。
- L1:上下文越长推理越慢且越贵,压缩同时是延迟优化。
12.3. 可观测性:从应用监控到轨迹回放
- 贯穿要求:任一任务的全过程 Trace 必须可回放——工具调用、文件变更、命令输出摘要、推理步数索引。缺 Trace 的失败不可复盘,等于团队在黑暗中调参(本文判断)。
- 正向供给:观测数据对 agent 开放(LogQL / PromQL),agent 用它自我验证——可观测性从"给人看"变成"L5 → L1 的反馈源"。
- 成本归因:Trace 是成本与质量归因的基础;没有 Trace,无法回答"这次改动变好了还是变坏了"。
- L6 依赖:审计不可追溯的对策就是全层 tracing + 结构化日志(OpenAI 把结构化日志列为品味不变量机械强制)。
12.4. 安全:从单点防御到穿透六层的纵深
| 层 | 安全接口 |
|---|---|
| L1 | context poisoning 是一种安全事件:被污染的上下文会让后续所有推理建立在错误前提上;指令文件本身是攻击面(外部内容可注入指令) |
| L2 | 沙箱双维隔离(文件系统 + 网络)是安全的地基;凭据保护 deny / mask |
| L3 | 编排层的风险是"过度代理":权限按任务授予、用完即收;破坏性动作默认拒绝 |
| L4 | 记忆投毒:被写入长期记忆的错误信息会跨会话持续传播 |
| L5 | 评估集本身需防污染;held-out 集不可见 |
| L6 | 权限、审计、预算是安全策略的执行与记录面 |
13. 架构成熟度自评表
13.1. 框架说明与五级定义
重要说明:下表为本项目基于前述公开资料自行构建的分析框架,并非任何标准组织发布的规范,也不是任何厂商的官方模型。其价值在于提供一把可操作的标尺,帮助组织定位自身 Harness 能力并进行代际对齐。请勿将其作为合规依据或行业基准使用。
| 等级 | 名称 | 通用定义 |
|---|---|---|
| L0 | 缺失 | 该层不存在或完全依赖人工;问题不被系统性察觉 |
| L1 | 手工 | 存在做法,但靠人执行、靠约定维持;不可复现、不可回归 |
| L2 | 工具化 | 有专门工具或组件;能自动执行,但缺乏治理策略 |
| L3 | 系统化 | 有明确策略与默认架构;能被度量,能在 CI 中回归 |
| L4 | 闭环自治 | 该层的输出自动回流改善其他层;具备抗熵机制 |
13.2. 六层 × 五级自评表
| 层 | L0 缺失 | L1 手工 | L2 工具化 | L3 系统化 | L4 闭环自治 |
|---|---|---|---|---|---|
| L1 上下文工程 | 上下文自然累积,无管理 | 人工挑选粘贴上下文 | 接入 RAG / 检索 | 有压缩 + 外化笔记 + 子 agent 隔离 + 渐进披露四件套;有 attention budget 意识 | 上下文组装策略由 L5 反馈自动调整;Skills 与 docs 自动裁剪更新 |
| L2 工具与执行 | 模型只能输出文本 | 少量硬编码工具 | Function Calling + 若干自有工具 | 工具经 MCP 标准化接入;运行在双维隔离沙箱(文件系统 + 网络) | 工具集根据使用数据与失败反馈自动增删 |
| L3 编排与控制 | 单轮调用 | 人工串流程 | 编排框架单次循环 | 支持长时运行、Sprint Contract、sub-agent 派发、确定性 + 动态路由并存 | 编排结构本身可被评估与自动选型;能对自己做失败模式分析 |
| L4 记忆与状态 | 会话结束即失忆 | 人工写交接说明 | 有会话持久化 | 进度文件 + git + 机器可读任务清单 + 开场健康度预检 | 状态交接被自动校验;脏状态在下一轮开场前被自动修复 |
| L5 评估与观测 | 靠人眼看结果 | 人工抽查 | 偶尔跑公开基准 | 内置 tracing + 自建 Golden Dataset + 每次真实失败补一条回归 case | 评估者与被评估者分离且 Evaluator 独立演进;held-out 集防过拟合;观测数据反向供给 L1 |
| L6 治理与安全 | 无边界 | 逐条人工审批 | 有权限配置 | 沙箱 + 凭据保护 + 自研 linter 机械强制;failIfUnavailable 硬失败 | 治理规则可被 agent 理解并自我修复(错误消息即修复指令);熵增被持续自动治理 |
13.3. 结果解读与使用建议
| 得分形态 | 判读 | 建议动作 |
|---|---|---|
| 多数层处于 L0~L1 | 尚不具备第三代 Harness,处于第二代早期 | 优先建 L2(工具标准化)与 L5(至少要有回归集),其余层暂缓 |
| 多数层处于 L2 | 典型的"工具很全但不稳定"状态 | 优先攻 L1(上下文治理)与 L6(沙箱),这两个是最常见的瓶颈 |
| 多数层处于 L3 | 已达第三代主流水平 | 重点是保持:建立本 Harness 的回归机制,防止随模型升级而退化 |
| 出现 L4 层 | 处于前沿探索 | 警惕 Harness 过度复杂化可能被下一次模型升级直接抹平 |
| 层间差距 ≥ 2 级 | 存在结构性短板 | 短板层决定整体上限,优先补齐 |
层间差距 ≥ 2 级这一条尤其重要(本文判断):Harness 的整体产出受限于最弱的一层,而不是最强的那层——这与软件系统的木桶效应一致。例如一个 L1 只有 L1 级(手工粘贴上下文)但 L2 达到 L3 级的系统,其表现往往不如两者均为 L2 级的系统。
使用建议:每半年自评一次,结果用于纵向比较而非横向得分;逐层给出具体证据,不写抽象的"中等";优先关注最弱层;警惕"评估通胀"——当一个层被评到 L3 却没有任何可回归的证据(例如没有 Golden Dataset),应当降回 L2。
14. 总结
第三代 Harness 的架构可以用一句话概括:它是一个把模型的输出分布,通过六层结构收窄到工程可接受区间的系统。
- L1 决定模型看到什么——关键瓶颈是注意力预算,核心手段是删除而非添加;
- L2 决定模型能做什么——MCP 解决了接入标准,沙箱解决了副作用边界;
- L3 决定按什么顺序做——从单循环走到 Planner / Generator / Evaluator 的分工;
- L4 决定记住什么——Git 成为主流的状态载体,跨窗口交接是长任务的生命线;
- L5 决定做得好不好——第一原则是评估者与被评估者分离;
- L6 决定不能做什么——治理不是速度的敌人,官方实证是权限提示减少 84%。
把六层串起来的是九个字:看得见、做得稳、能回归。成本、延迟、可观测性与安全四类横切关注点穿透六层,任何一层遗漏,都会在其他层以事故的形式补课。
六层模型在各行业的差异化落地——谁的重心在 L4、谁的重心在 L5、谁的 ground truth 是物理定律——见第 4 章(实践)。
15. 信息缺口声明
本篇涉及以下信息缺口,已在正文对应位置标注 ,在此汇总:
- 第 3.5 节:上下文退化"性能下降超过 45%"与 Chroma Research "18 个前沿模型全部退化"(C 级)。
- 第 4.3 节:Codex CLI 沙箱参数、约 95% Rust 代码占比、Auto-review 的 1/200 与 99%(B 级)。
- 第 4.4 节:Vercel 工具数 15 → 2 的准确率 80% → 100%、Token −37%、速度 3.5×(C 级)。
- 第 5.3 节:单 Agent(20 分钟 / $9 / 不可用)与三 Agent(6 小时 / $200 / 完整可玩)对比实验数字(C 级)。
- 第 7.3 节:Terminal-Bench 榜单数字(77.3% / 75.1% / 74.7% / 71.9%)、LangChain 52.8% → 66.5%,官方站(tbench.ai)当前榜单未直接抓取,全部为第三方转述。
- MCP 初始版本口径差异:2024-11-05(Ruby SDK 记为 Initial protocol revision)与 2024-11-25(公开宣布)两种口径并存,本篇取 2024-11-05 为初始版本并列呈现差异。
- Anthropic《How we built our multi-agent research system》的确切 URL 与发布日期未验证。
- ISO/IEC 层面的智能体互联国际标准编号:暂无权威信息。
本轮新增(第 9 章 Harness Loop)
- 《Unrolling the Codex agent loop》《Unlocking the Codex harness》《Codex as a platform》等 OpenAI 官方博客的具体发布日期未在检索结果中直接返回(第 9 章)。
- $47,000 多代理乒乓失控案例为 verified: partial(多帖一致、无具名受害企业),正文已按"业界流传的代表性事故复盘"表述(第 9.1 节)。
- 三重硬限经验值与"失控循环成本约为正常任务 30 倍"为业界实践汇总(C 级),仅作方向性参考(第 9.5 节)。
- n8n / Coze 循环节点缺独立一手官方文档,仅经可视化工作流有界循环共性模式间接覆盖(第 9.4 节)。
16. 参考资料
- Effective context engineering for AI agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Effective harnesses for long-running agents — Anthropic,2025。https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
- Harness design for long-running application development — Anthropic,2026。https://www.anthropic.com/engineering/harness-design-long-running-apps
- Harness engineering: leveraging Codex in an agent-first world — OpenAI,2026-02-11。https://openai.com/index/harness-engineering/
- Sandboxing: a safer and more autonomous approach — Anthropic,2025。https://www.anthropic.com/engineering/claude-code-sandboxing
- Introducing the Model Context Protocol — Anthropic,2024-11-25。https://www.anthropic.com/news/model-context-protocol
- Model Context Protocol 官方规范(2026-07-28)— MCP / AAIF。https://modelcontextprotocol.io/specification/2026-07-28/
- A year of open collaboration: Celebrating the anniversary of A2A — Google,2026-04-16。https://opensource.googleblog.com/
- Equipping agents for the real world with Agent Skills — Anthropic,2025-10-16(2025-12-18 开放标准更新)。https://www.anthropic.com/news/skills
- 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/
- Harness engineering for coding agent users — Birgitta Böckeler,martinfowler.com,2026。https://martinfowler.com/articles/harness-engineering.html
- SWE-bench — Jimenez、Yang 等(Princeton),2023-10(ICLR 2024 Oral)。https://www.swebench.com/
- Terminal-Bench — Stanford / Laude Institute,2025。https://www.tbench.ai/
- Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF,2025-12-09。https://aaif.io/
- 2025 Stack Overflow Developer Survey — Stack Overflow,2025-07-29。https://survey.stackoverflow.co/2025/
- How the agent loop works — Anthropic,2026。https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
- Building agents with the Claude Agent SDK — Anthropic,2025。https://claude.com/blog/building-agents-with-the-claude-agent-sdk
- Loop engineering: Getting started with loops — Claude Code 团队,Anthropic,2026-06-30。https://claude.com/blog/getting-started-with-loops
- A harness for every task: dynamic workflows in Claude Code — Anthropic,2026。https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code
- Unrolling the Codex agent loop — OpenAI,2025—2026(发布日期 ,见第 15 节)。https://openai.com/index/unrolling-the-codex-agent-loop/
- Codex as a platform: build on the open agent harness — OpenAI Developers,2026。https://developers.openai.com/blog/codex-as-a-platform
- Running agents — OpenAI Agents SDK 官方文档,2026。https://openai.github.io/openai-agents-python/running_agents/
- Running Codex safely at OpenAI — OpenAI,2026。https://openai.com/index/running-codex-safely/
- Agent approvals & security — Codex 官方文档,2026。https://developers.openai.com/codex/sandbox
- gemini-cli(开源仓库与 ReAct 循环文档)— Google,2025—2026。https://github.com/google-gemini/gemini-cli
- What does recursionLimit actually count in createAgent? — LangChain 官方论坛,2025—2026。https://forum.langchain.com/t/what-does-recursionlimit-actually-count-in-createagent-langchain-js/3460
- Dify 节点系统文档(Iteration / Loop 节点)— LangGenius,2026(经 DeepWiki 结构化索引)。https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
- Iteration Node — Agent Patterns Catalog,2026。https://www.agentpatternscatalog.org/patterns/iteration-node
- Runaway Tool Loops — PolicyLayer,2026(案例发生于 2025-11,verified: partial)。https://policylayer.com/attacks/runaway-tool-loops
Architecture — The Third-Generation AI Harness Reference Architecture
1. Reading Guide and Positioning
1.1. The Three Questions This Chapter Answers
This chapter is one of the two with the heaviest technical weight in the white paper; it connects with Chapter 2 (Concepts and Development History) and answers three questions:
- What a third-generation (runtime- and evaluation-centric) Harness actually looks like — which components make up each layer, and what contracts link the layers to one another;
- Why each layer has its current shape — what failures it has to overcome, and what price was paid for that;
- How an organization can judge what level its own Harness is at — providing a self-assessment tool that judges each layer against a five-level maturity scale.
For the timeline and background of the three-generation evolution, see Chapter 2; for the forms in which the six-layer model lands in each industry, see Chapter 4 (Practice).
1.2. Terminology and Baseline Conventions
- AI Harness (AI riding layer / agent runtime framework): the engineered carrying layer between the foundation model and real business systems, which turns the model's uncertainty into engineering predictability. The definition is unified throughout and must not be rewritten.
- Six-layer capability model: L1 Context Engineering Layer, L2 Tooling and Execution Layer, L3 Orchestration and Control Layer, L4 Memory and State Layer, L5 Evaluation and Observability Layer, L6 Governance and Safety Layer.
- Three-generation evolution: the prompt engineering era (2020—2023) → the tooling and orchestration era (2023—2025) → the runtime and evaluation era (2025—present).
- Distinguishing fact from judgment: every engineering parameter cited in this chapter is labeled with a source tier; conclusions derived by this project are explicitly marked "this document's judgment". Numbers from Tier-B/C sources are uniformly flagged as unverified and serve only as directional reference.
- Source tiers: Tier A is vendor or official primary; Tier B is authoritative secondary; Tier C is community paraphrase (numbers unverified and not quoted).
2. Overview of the Third-Generation Reference Architecture
2.1. The Basis for Layering: Layers Defined by Failures
The six-layer model is not an a priori functional division, but rather each layer corresponds to a class of independently emergent bottleneck. When a long-cycle agent task fails, the engineer's attribution almost always falls into one of the following six categories:
| Failure Attribution | Corresponding Layer |
|---|---|
| It never saw that critical file / the context was too long and information was lost | L1 |
| The action it wanted to perform was not correctly defined as a tool / the execution produced unexpected side effects | L2 |
| The order in which it did this thing was wrong / it got stuck in some loop and couldn't get out | L3 |
| In a new session it "forgot" how far it got in the previous round | L4 |
| It said "done", but it actually wasn't done | L5 |
| It did something it shouldn't have / it overshot the budget / we can't find out who did it | L6 |
Layers are defined by failures, not by feature lists. (this document's judgment) This is the practical criterion for judging which layer a new component should belong to.
2.2. Overall Architecture Diagram
图 2-1|第三代架构总览:六层分层设计
┌──────────────────────────────────────────────────────────────────┐
│ L6 治理与安全层 Governance & Safety │
│ 权限 · 沙箱策略 · 凭据保护 · 机械强制 · 熵治理 · 预算护栏 │
│ (横向切面,对 L1~L5 全部施加约束并记录审计) │
└──────────────────────────────────────────────────────────────────┘
▲ ▲ ▲ ▲
│ 约束 │ 约束 │ 约束 │ 审计
┌──┴────────┐ ┌───┴────────┐ ┌───┴─────────┐ ┌──┴──────────┐
│ L1 上下文 │─►│ L2 工具与 │─►│ L3 编排与 │─►│ L5 评估与 │
│ 工程层 │ │ 执行层 │ │ 控制层 │ │ 观测层 │
│ 看到什么 │ │ 能做什么 │ │ 按什么顺序做 │ │ 做得好不好 │
└───────────┘ └────────────┘ └─────────────┘ └─────────────┘
▲ │ │
│ 反馈:改变下次看到什么 │ │
└──────────────────────────────┴───────────────────┘
▲
┌────┴───────────────────────────────────────────┐
│ L4 记忆与状态层 Memory & State │
│ 会话态 · 长期记忆 · 检查点 · 工件 │
│ (时间维度的横向支撑层) │
└────────────────────────────────────────────────┘ It should be emphasized that the feedback edge between L5 and L1 in the diagram is the structural difference between the third and second generations: in the second generation evaluation is bolted on (run a benchmark once, glance at the score), while in the third generation the output of evaluation flows back to change the next round of context assembly, forming a closed loop.
2.3. Six-Layer Responsibility Master Table
| Layer | Name | English | Responsibility | Input | Output | Typical Implementations |
|---|---|---|---|---|---|---|
| L1 | Context Engineering Layer | Context Engineering | Decides what the model "sees" | Environment state, retrieval results, instructions | The assembled token sequence | RAG, Context Compaction, Prompt Assembly, SKILL.md progressive disclosure, KV Cache reuse |
| L2 | Tooling and Execution Layer | Tooling & Execution | Decides what the model "can do" | Tool invocation intent | Side effects in a controlled environment | MCP, Function Calling, sandboxed executors, Computer Use |
| L3 | Orchestration and Control Layer | Orchestration & Control | Decides "in what order to do it" | Task goal | Sequence of execution steps | Agent Loop, Plan-and-Execute, DAG / Workflow, Sub-agent |
| L4 | Memory and State Layer | Memory & State | Decides "what to remember" | Session history, artifacts | State recoverable across windows | Session Store, Episodic / Semantic Memory, Checkpoint |
| L5 | Evaluation and Observability Layer | Evaluation & Observability | Decides "how well it was done" | Execution trace, products | Verdicts, metrics, regression signals | Trace, Eval Set, Golden Dataset, Online Metrics |
| L6 | Governance and Safety Layer | Governance & Safety | Decides "what must not be done" | Policies, budgets, compliance requirements | Allow / deny + audit records | RBAC, guardrail models, audit logs, Budget Guardrail |
3. The L1 Context Engineering Layer
3.1. Responsibility and Problem Statement
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.
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 the most widely cited:
"Context engineering is the delicate art and science of filling the context window with just the right information for the next step."
The two official theoretical foundations of this layer are:
| Concept | Official Statement | Engineering Meaning |
|---|---|---|
| context rot | Performance gradient, not a hard cliff | As the context grows, performance degrades gradually; there is no safe threshold; the context must be continuously governed |
| attention budget | The n² relational property of self-attention means each additional token dilutes attention on the other tokens | The context is a scarce resource; every token placed in carries an opportunity cost |
This yields a counterintuitive but repeatedly verified conclusion (this document's judgment): cramming more information into the context is usually a negative optimization. The priority of building L1 is not "retrieve more" but "delete more".
3.2. Key Components
| Component | Mechanism | Source |
|---|---|---|
| Compaction | Officials divide it into several tiers; the safest and lightest tier is tool result clearing (clearing tool call results), already live on the Claude Developer Platform. Tuning discipline: maximize recall first, then improve precision — reversing the order loses the critical constraints later steps need | Anthropic, Tier A |
| Externalized notes and agentic memory | Persist notes outside the context window (Claude Code's to-do list, NOTES.md); the Memory tool entered public beta alongside Sonnet 4.5 | Anthropic, Tier A |
| Sub-agent context isolation | A sub-agent can explore deeply using tens of thousands of tokens, returning only a 1,000~2,000-token condensed summary — context in exchange for parallelism, at the cost of summary loss | Anthropic, Tier A |
| Skills and progressive disclosure | Three-tier loading: at startup load only name + description; on a hit read the full SKILL.md; on demand read bundled files. Official claim: "the amount of context that can be bundled into a skill is effectively unbounded" | Anthropic (released 2025-10-16, converted to an open standard 2025-12-18), Tier A |
Besides Anthropic's official four-way split, another widely used industry taxonomy is the LangChain four pillars (Write / Select / Compress / Isolate, Tier B), which maps onto the official strategies: the first three correspond to compaction, notes, and retrieval; the sub-agent corresponds to Isolate.
3.3. Representative Implementations
| Implementation | Form | L1 Techniques | Source Tier |
|---|---|---|---|
| Claude Agent SDK / Claude Code | Official SDK + CLI | The full four-piece set (compaction / note / memory tool / sub-agent), SKILL.md progressive disclosure | A |
| OpenAI Agents SDK / Codex | Official SDK + CLI | The "AGENTS.md as table of contents" strategy: about 100 lines injected into context, details externalized in structured docs/ | A |
| Google ADK | Official SDK | Session / Runner as the state boundary | A |
| LangChain / LangGraph | Open-source framework | The most complete realization of the four-pillar theory; Isolate is achievable at node boundaries | B |
3.4. Design Trade-offs
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Recall vs precision | Full dump (high recall, prone to rot) vs precise retrieval (high precision, prone to omission) | The order given officially: recall first, precision later |
| Depth vs cleanliness | Keep the full main context vs sub-agent summaries (clean but lossy) | Whether the task requires cross-step strong consistency |
| Static injection vs dynamic loading | Inject all instructions at once vs Skills progressive disclosure | Whether the routing hit rate is high enough; when the hit rate is low, progressive disclosure is actually worse |
3.5. Typical Failure Modes
| Failure Mode | Meaning | Typical Symptoms |
|---|---|---|
| context poisoning | Erroneous information is propagated as fact within the session | After a single tool error, all subsequent reasoning builds on the wrong premise |
| context distraction | Key information is drowned by noise | Retrieval returns 50 relevant passages; the model uses only the first 3 |
| context confusion | Redundant information causes loss of focus | Too many "you could also do it this way" suggestions in the instructions; the model picks randomly between two |
| context clash | Conflicting instructions inside the context | AGENTS.md and SKILL.md give different approaches to the same problem |
Quantitative supplement (Tier C): 2025 research found that "semantically consistent but irrelevant data can degrade performance by more than 45%"; Chroma Research tested 18 frontier models in 2025-07, and every one degraded as the context grew.
4. The L2 Tooling and Execution Layer
4.1. Responsibility and Component Composition
The question L2 answers is: what actions the model can apply to the environment, and where those actions execute. Three classes of components:
| Component Class | Role | Representative |
|---|---|---|
| Tool registration and description | Declare external capabilities as structured interfaces | Function Calling, JSON Schema tool descriptions |
| Connection protocol | Decouple the tool ecosystem from the host application | MCP (Model Context Protocol) |
| Execution environment | Bound the scope of actions and the boundary of side effects | Sandbox (Seatbelt / bubblewrap + socat / Landlock + seccomp) |
Tool design guidelines (Anthropic, Tier A): self-contained, robust to errors, extremely clear in purpose; avoid feature overload and ambiguous decision points; few-shot examples should be "diverse and typical". Echoing this is the "right altitude" principle for system prompts: specific enough to effectively guide behavior, yet flexible enough to leave the model room for judgment.
4.2. MCP: The Connection Standard and Its Evolution
MCP adopts a Host / Client / Server three-role architecture (Tier A): the Host is the top-level application, containing Clients; each Client maintains a 1:1 connection with a Server; the Server exposes Tools / Resources / Prompts. Transport: local stdio, remote Streamable HTTP, messages based on JSON-RPC 2.0.
The five-version specification evolution chain (MCP official protocol versions page, etc., Tier A):
| Version | Key Changes |
|---|---|
| 2024-11-05 | Initial protocol version: stdio + HTTP+SSE; the three primitives |
| 2025-03-26 | Streamable HTTP replaces HTTP+SSE; OAuth 2.1; tool annotations |
| 2025-06-18 | Elicitation; structured tool output; the MCP-Protocol-Version header becomes mandatory; JSON-RPC batching removed (breaking change) |
| 2025-11-25 | Tasks (asynchronous state tracking); parallel tool calls; server-side agent loop |
| 2026-07-28 | The protocol core made stateless (the initialize handshake and Mcp-Session-Id removed); the Extensions framework introduced; authorization strengthened; formal deprecation policy (minimum 12-month window) |
Google's official division of labor between MCP and A2A ("A year of open collaboration", 2026-04-16, Tier A): MCP manages internal tool integration, A2A manages external coordination between agents. The two are connection protocols in different directions, not a competitive relationship.
From the evolution chain, three orientations can be read (this document's judgment): from stateful sessions to stateless requests; from "good enough" to "evolvable"; from "tools only" to "agents on the server side too".
4.3. Sandbox: The Engineering Implementation of the Side-Effect Boundary
The Claude Code sandbox is the most completely publicly disclosed Agent sandbox design to date (Tier A).
Core security axiom: 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.
| Item | Parameter |
|---|---|
| macOS implementation | Seatbelt |
| Linux / WSL2 implementation | bubblewrap + socat (optional seccomp filter) |
| Default write | Commands in the sandbox can write only to the current working directory and the session temporary directory |
| Default read | Readable machine-wide by default (except explicitly denied directories) |
| Network egress | Only via a unix domain socket to a proxy server running outside the sandbox; the first request to a new domain prompts for approval |
| Credential protection | sandbox.credentials can deny access to files (~/.aws/credentials, ~/.ssh) and environment variables (GITHUB_TOKEN, NPM_TOKEN); v2.1.199+ supports mode: "mask" |
Quantified effect (Tier A, the most core number in this layer): Anthropic's internal use found that sandboxing safely reduced permission prompts by 84%.
Horizontal comparison (Codex CLI, Tier B, specific parameters flagged as unverified): macOS uses sandbox-exec (Seatbelt), Linux uses Landlock + seccomp, Windows uses job objects; network disabled by default; approval tiers are Suggest / Auto-edit / Full-auto. In 2026-04 an Auto-review mode was added; internal sessions stopping for human approval occur at about 1/200 the rate of the manual mode, with a review approval rate of about 99%.
4.4. Design Trade-offs and Failure Modes
| Trade-off | The Two Poles | Position |
|---|---|---|
| Sandbox strength vs usability | Strong isolation (safe but often needs an escape hatch) vs weak isolation (easy to use but risk spills over) | Isolation must come in pairs (filesystem + network), not "as strong as possible" |
| Tool count vs accuracy | More tools, broader capability vs more tools, harder choice | Subtraction first. Vercel cut the tool count from 15 to 2: accuracy 80% → 100%, Token −37%, speed 3.5× (Tier C) |
| Native plugins vs standard protocol | Better performance but lock-in vs decoupled but with residual overhead | The third generation generally picks the MCP route; deviations need a clear reason |
Typical failure modes: overlapping tool semantics cause random choice that is not reproducible; frequent use of dangerouslyDisableSandbox makes isolation a mere formality; child processes inheriting credential environment variables cause leaks; uncontrolled network egress exfiltrates data; an inflated tool count causes a double loss in accuracy and cost. The corresponding countermeasures: a "pairwise distinguishability" check in tool review, closing the escape hatch (Strict sandbox mode), explicit deny / mask for credentials, a mandatory proxy with an egress whitelist, and regular tool subtraction.
5. The L3 Orchestration and Control Layer
5.1. Responsibility and Orchestration Forms
The question L3 answers is: in what order to act, who does what, and how to recover after an interruption.
| Form | Applicable To | Representative |
|---|---|---|
| Single loop (Agent Loop) | General tasks; the model autonomously decides the next step | ReAct loop, Claude Code main loop |
| Plan-then-execute (Plan-and-Execute) | Long-cycle tasks requiring global planning | Claude Code Plan Mode, the three-Agent architecture |
| Directed acyclic graph / workflow | Business processes with high determinism requirements | DAG / Workflow engines, Google ADK SequentialAgent |
| Sub-agent dispatch | Complex research tasks that can be explored in parallel | Sub-agent architecture, multi-agent research systems |
5.2. Two Generations of Official Solutions for Long-Running
First-generation official solution (Anthropic "Effective harnesses for long-running agents", Tier A): the Initializer Agent + Coding Agent dual-Agent division of labor. The Initializer produces the handoff package: init.sh (one-command environment startup), claude-progress.txt (progress file), the initial git commit (rollback base point), and a JSON feature list (the master task ledger with a passes field). The Coding Agent's three opening steps are fixed: pwd to confirm the directory → read the git log and progress file → read the feature list and select the highest-priority unfinished item. Two hard rules: removing or modifying tests is unacceptable; the session must end with the environment left in a mergeable clean state.
Second-generation official solution (Anthropic "Harness design for long-running application development", 2026, Tier A): the Planner / Generator / Evaluator three-role division of labor (design inspiration from GANs). The Planner turns 1~4 high-level prompt sentences into a complete product specification, deliberately staying high-level; the Generator implements one feature per sprint; the Evaluator scores four items — product depth, functionality, visual design, code quality — each with a hard threshold; if any falls below its threshold the iteration fails. Three key mechanisms:
- Sprint Contract: before coding, reach consensus on "what to build + how to verify success" — agree on the definition of "done" before starting; this is the most important process design in this layer.
- self-evaluation bias (self-praise): agent self-evaluation will "confidently praise" clearly mediocre work; this is the fundamental reason for separating the Evaluator.
- 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): whether a single general-purpose coding agent is always optimal, or a multi-agent architecture split into specialized agents is better — this is currently unclear.
A third route: the managed runtime (supplemented in the 2026-09-12 snapshot; evidence tier upgraded in the 2026-09-13 snapshot). Both generations of solutions above are the self-built Harness methodology given by Anthropic — the team builds its own orchestration, manages its own state, and designs its own evaluation. In 2026 a third route emerged alongside them: the vendor manages the runtime itself. The two citable milestones are AWS Bedrock AgentCore reaching GA in 2026-06, and the OpenAI Agents API entering public beta on 2026-09-10 (Tier A — recorded in the OpenAI official Changelog, verified in the 2026-09-13 snapshot; the previous snapshot, following media reports, had recorded it as 09-11, now corrected; see 08-Development Outlook §4.3 and the research library 03-Market Research/02-AI-Agents Group/21-openai-agents-api.md for details). Its form is packaging L3 orchestration, L4 state persistence, and L5 tracing and observability as server-side capabilities; callers no longer build their own loop, and only submit tasks and toolsets.
The trade-offs among the three routes reduce to one trade-off:
| Dimension | Self-built Harness (Anthropic's two generations of solutions) | Managed runtime (AgentCore / Agents API) |
|---|---|---|
| Control | The loop, state, and evaluation set are all controllable and modifiable | The loop and state are defined by the vendor; the modifiable scope is constrained by the API |
| Build cost | High; requires building orchestration, checkpoints, and evaluation facilities in-house | Low; ready to use out of the box |
| Ownership of trajectory data | Lands in your own storage; can accumulate into evaluation sets and failure-mode libraries | Lands on the vendor side; retrieval and migration capability depend on the platform's export capability |
| Migration cost | Decoupled from the model; low cost to swap models | Strongly bound to the platform; cross-platform migration requires rewriting the orchestration layer |
| Applicability judgment | Long-duration, high-risk tasks requiring audit trails | Medium- to short-duration, fault-tolerant tasks pursuing time-to-launch |
Judgment: the managed runtime does not replace the self-built Harness, but moves the necessity of "self-building" upward — what it absorbs is the general orchestration and state persistence part of the non-differentiated capability, while the bottlenecks that recur throughout the 04-Practice chapter (industry criteria, evaluation sets, governance red lines) still cannot be managed and still require self-building. This is consistent with the white paper's core judgment that "the Harness is an independent engineering layer": precisely because it is an independent layer, it can be managed by a vendor, and self-built constraints can continue to be layered on top of the managed service.
5.3. Design Trade-offs and Failure Modes
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Single Agent vs Multi-Agent | Context coherence vs parallelism and clean windows | Officials acknowledge "currently unclear"; recommend per-task A/B testing |
| Planning granularity | Planner gives full detail vs deliberately staying high-level | Officials choose to deliberately stay high-level |
| Determinism vs flexibility | State machines are reproducible vs LLM routing is highly adaptive | Business processes choose the former, exploratory tasks choose the latter; Google ADK's answer is that both coexist |
| Cost vs quality | Multi-Agent is obviously more expensive | Comparison experiments show (Tier C): single Agent 20 minutes / $9 / unusable output; three Agent 6 hours / $200 / complete playable output |
Typical failure modes and countermeasures: infinite loop → iteration cap + anti-drift detection; goal drift → Sprint Contract + periodic re-injection of the original goal; early completion declaration → forced checklist-style self-verification; dirty environment state → return to a mergeable clean state before ending; tests modified to pass → declare "removing or modifying tests" unacceptable.
6. The L4 Memory and State Layer
6.1. Responsibility and Problem Statement
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. Key Mechanisms
The official scheme for cross-window state handoff (Tier A):
| Handoff Vehicle | Carried Content | Characteristic |
|---|---|---|
claude-progress.txt | Natural-language progress record | Readable, understandable by the model |
| git history | Structured change record | Rollback-able, diff-able |
JSON feature list (with passes) | Master task ledger | Machine-decidable completion degree |
| Initial git commit | Rollback base point | Guarantees each round can return to a known healthy state |
Two accompanying disciplines: before starting to implement a new feature, an end-to-end health check must be run first (the rationale being that the model "tends to declare a feature complete without adequate testing"); equip the agent with browser automation tools (such as Playwright MCP) for human-level verification — officials explicitly state this significantly improved performance.
The division of labor between Compaction and Context Reset (Tier A): Compaction summarizes in place, preserving continuity, but "context anxiety" remains; Context Reset clears and re-injects, giving a clean whiteboard, but the handoff artifacts must be sufficiently complete. The relationship between the two can be summarized as (this document's judgment): 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.
Git as the state carrier: a distinctive feature of the third generation is treating Git as the carrier of state and memory, rather than starting a separate memory database — the benefit 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.
6.3. Design Trade-offs and Failure Modes
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Natural language vs structured state | Flexible but not machine-decidable vs machine-decidable but rigid | Officials choose to want both |
| Preserve vs reset | Good continuity vs clean | For long tasks, recommend periodic Reset + a high-quality handoff package |
| Dedicated memory store vs Git | Strong semantic retrieval vs mature tool ecosystem | The third generation generally takes Git-first, with dedicated memory as a supplement |
Typical failure modes and countermeasures: amnesiac restart → force the three opening steps; progress file decay → treat git history as the single source of truth, the progress file only summarizes; dirty handoff → wrap up in a clean state + an opening health pre-check; checkpoint granularity out of control → explicitly agree on commit granularity and branching strategy.
7. The L5 Evaluation and Observability Layer
7.1. Responsibility and First Principle
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."
First principle: separate the evaluator from the evaluated. Official observation (Tier A): when an agent evaluates its own work, it will "confidently praise" it — even when human observers clearly see mediocre quality. The rationale given officially is:
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; if any falls below its threshold the iteration fails, and the detailed failure reasons are fed back to the Generator. This principle also holds for non-coding scenarios (this document's judgment): 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.2. External Benchmarks and the Built-in Closed Loop
The two components of L5 are mutually irreplaceable:
| Component | Role | Representative |
|---|---|---|
| External benchmarks | Cross-system horizontal comparison, judging "what rank in the industry" | SWE-bench / SWE-bench Verified, Terminal-Bench |
| Built-in evaluation closed loop | Regression and CI of one's own tasks, judging "did this change make things worse" | Eval Set, Golden Dataset, Trace analysis, Google ADK AgentEvaluator |
External benchmarks prevent self-congratulation (your own eval all green yet no competitiveness); the built-in closed 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. Terminal-Bench's principle is likewise "either the automated tests pass or they do not".
Open observability to the agent is a highly inspiring practice given by OpenAI in "Harness engineering" (2026-02-11, Tier A): applications can be started independently per git worktree; the browser debugging protocol (Chrome DevTools Protocol) is wired into the agent runtime; metrics and logs are exposed via the local observability stack, and the agent can query directly with LogQL and PromQL; performance requirements are written as measurable acceptance conditions (example: "ensure the service starts within 800ms"). Its engineering significance is: feed L5's observability capability back to L1 as context — the agent is no longer a blind-writing black box.
7.3. Quantitative Evidence of Harness Differences
The evidence that best demonstrates the value of L5 is the quantification of 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."
The following comparison data all come from Tier-B/C sources and are uniformly flagged as unverified, serving only as directional reference:
| Comparison Item | Data | Note |
|---|---|---|
| Factory Droid + GPT-5.3-Codex | 77.3% | Same GPT-5.3-Codex as the next row |
| OpenAI Simple Codex + GPT-5.3-Codex | 75.1% | 2.2 percentage points caused purely by scaffold difference |
| KRAFTON Terminus-KIRA + Claude Opus 4.6 | 74.7% | Same Claude Opus 4.6 as the next row |
| Bigai TongAgents + Claude Opus 4.6 | 71.9% | Differs by 2.8 percentage points |
| LangChain changed only the Harness (same model, same API) | 52.8% → 66.5% | Rank jumped from outside 30th to the top 5 |
The five-item change list behind LangChain's "52.8% → 66.5%" (Tier C, unverified numbers, but the changes themselves have engineering reference value) all involve no model swap:
- Force checklist-style self-verification before allowing "done" to be said;
- Scan the directory structure before startup and inject environment context;
- Anti-drift detection — warn when repeatedly editing the same file;
- Adjust the reasoning budget — think more for planning and verification, less for implementation;
- Automated failure-mode analysis.
7.4. Design Trade-offs and Failure Modes
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Subjective scoring vs binary criteria | Cover subjective tasks vs objectively reproducible | Prefer translating subjective tasks into binary-decidable sub-items; only use Evaluator scoring + hard thresholds when binary decision is impossible |
| Evaluation frequency vs cost | Per-step evaluation (expensive but timely feedback) vs end-state evaluation (cheap but hard attribution) | End-state evaluation for short chains, per-sprint evaluation for long chains |
| Coverage vs maintenance cost | Larger evaluation sets are more accurate vs harder to maintain | Rather than spreading wide, do "add one regression case for every real failure" |
Typical failure modes and countermeasures: self-praise → separate the evaluator from the evaluated; evaluation set overfitting → rotate evaluation sets periodically, keep a held-out set; only looking at end-state scores → trajectory-level tracing; metrics disconnected from business → build your own Golden Dataset rather than only chasing public leaderboards.
8. The L6 Governance and Safety Layer
8.1. Responsibility and Governance Philosophy
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 is "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. Key Mechanisms
Layered permission configuration (taking Claude Code as an example, Tier A): project level .claude/settings.local.json distributed with the repository; user level ~/.claude/settings.json carrying personal preferences; organization level managed settings mandatorily pushed down, individuals cannot override. Among these, sandbox.failIfUnavailable can be set to hard failure — if the sandbox cannot start, refuse to run, rather than quietly degrading. This is an important lesson in governance robustness (this document's judgment): do not give safety mechanisms a silent degradation path.
Mechanical enforcement of architectural constraints (OpenAI, Tier A): the layered dependency rule is mechanically enforced rather than relying on verbal code review conventions —
Types → Config → Repo → Service → Runtime → UI Cross-cutting concerns can only enter through the single Providers interface. Taste Invariants are statically enforced via a self-built linter — structured logging, schema and type naming conventions, file size limits. The most critical engineering trick is: the linter's error messages are written as repair instructions injected into the agent context — 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. Official summary:
In human-first workflows, these rules may feel pedantic; with agents, they become multipliers — once codified, they take effect everywhere immediately.
Garbage collection: countering entropy growth (OpenAI, Tier A): the doc-gardening agent periodically scans outdated documentation and automatically initiates repair PRs. The four major failure modes summarized officially: context is a scarce resource; too much guidance becomes no guidance (when AGENTS.md is written too long, the agent skips reading it, just like a human); documentation rots immediately; hard to verify mechanically.
8.3. Design Trade-offs and Failure Modes
| Trade-off | The Two Poles | Basis for the Choice |
|---|---|---|
| Hard failure vs silent degradation | Availability vs safety certainty | Governance mechanisms should avoid silent degradation |
| Central enforcement vs local autonomy | Consistency vs flexibility | Official answer: the center enforces boundaries, the periphery allows autonomy |
| Number of rules vs compliance | More rules the better vs too many and they are ignored | Rules must be few and mechanically enforceable; excessive documentation equals no documentation |
Typical failure modes and countermeasures: permission fatigue → sandboxing + Auto-allow (−84% prompts); documentation decay → doc-gardening agent + bring documentation into CI validation; rules not machine-checkable → self-built linter, error messages written as repair instructions; audit not traceable → full-layer tracing + structured logs; budget out of control → Budget Guardrail + per-step / per-task cost caps.
9. Harness Loop: Converging Model Uncertainty into Controllable Iteration
The previous eight chapters took the six layers apart layer by layer; this chapter returns to the axis that strings them together — the main loop. One sentence to distinguish the two perspectives: the six-layer model answers "what the Harness consists of", while the Harness Loop answers "what the Harness is doing every second".
9.1. Why the Loop is the First Citizen of the Harness
For the judgment "the Loop is the first citizen of the Harness", there are three sets of mutually independent evidence (this document's judgment; evidence all labeled with source tiers):
First, official naming evidence. Anthropic's "Loop engineering: Getting started with loops" (2026-06-30, Tier A) takes the "loop" as its core proposition, with the official definition "loop = the agent repeatedly executes work cycles until the stop condition is met"; the Claude Agent SDK official documentation has a dedicated chapter "How the agent loop works" (Tier A); OpenAI directly equates the agent loop with the core of the harness — "the reusable part is the agent loop" ("Codex as a platform", Tier A). The two leading vendors, in unison, take the loop — not the model — as the center of their product and documentation narratives.
Second, evaluation-variable evidence. OpenAI officially disclosed (Tier A, information as of 2026-09-12): 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×. Same model, only the loop mechanism changed, a 25-percentage-point improvement — this mutually corroborates section 7.3's Terminal-Bench "the leaderboard ranks systems, not models": loop design is a performance variable independent of the model.
Third, failure-mode evidence. The long-task failure modes named officially by Anthropic — doing too much at once (one-shot) and premature completion declaration (premature completion) — are both loop-level failures: not that some step was done wrong, but that the loop's boundary was designed wrong (Tier A). The $47,000 multi-agent ping-pong loss-of-control incident circulating in the industry (Tier B, verified: partial, multiple posts consistent but no named victim company) shows the cost consequences of an unbounded loop; industry practice estimates an out-of-control loop's cost can reach 30× a normal task (Tier C).
The conclusion of combining the three sets of evidence is (this document's judgment): the model's uncertainty comes from the single call; the loop turns the single call into an observable, verifiable, terminable iteration unit — convergence does not happen inside the model, it happens inside the loop.
9.2. Loop × Six-Layer Model Comparison
The Harness Loop is not a "seventh layer" beyond the six layers, but the unfolding of the six layers along the time dimension. The unified comparison is as follows:
| Layer | Position in the Loop | Official Evidence |
|---|---|---|
| L1 Context Engineering Layer | The goal assembly at the start of each turn: prompt = system prompt + tool definitions + session history + tool result backflow | Anthropic SDK five-step official definition (Tier A); the compact_boundary message explicitly marks compaction boundaries (Tier A) |
| L2 Tooling and Execution Layer | The tool execution in the middle of each turn: scheduling, confirmation, sandbox execution | Codex approval gate and sandbox tiers (Tier A); Gemini CLI CoreToolScheduler four steps (Tier B) |
| L3 Orchestration and Control Layer | The loop body itself: re-planning and control-flow transfer | Sub-agent dispatch, handoff, LangGraph conditional edges (Tier A / B) |
| L4 Memory and State Layer | The state update at the end of each turn and cross-turn checkpoints | LangGraph Checkpointer writes to disk at each superstep (Tier B); progress file + git handoff (Tier A) |
| L5 Evaluation and Observability Layer | The observational verification of each turn: usage, cost, completion judgment | The ResultMessage carries token usage and cost (Tier A); /goal evaluation-model verification (Tier A) |
| L6 Governance and Safety Layer | The governance boundary wrapping the entire ring: constraining and recording every turn | Hooks interception, approval tiers, budget caps, OTel audit (Tier A) |
The correspondence is shown in Figure 9-1.
图 9-1|Harness Loop × 六层模型对照
示意图:基于本文分析,对照口径沿用本库参数卡统一六层模型(信息截止 2026-09-12)。
9.3. Termination Conditions and the Governance Boundary: Writing L6 into the Loop
"When does the loop stop" is not an implementation detail but the core contract between the Harness and its users. The unified criterion divides termination conditions into five tiers:
| Tier | Termination Condition | Representative Mechanism | Evidence Tier |
|---|---|---|---|
| ① | Task completion judgment (DoD check) | Final response without tool invocations; complete_task tool; /goal evaluation-model verification — if unmet, sent back | A / B |
| ② | Budget exhausted | max_budget_usd cost threshold; explicit token budget (e.g., "use 10k tokens") | A |
| ③ | Permission boundary triggered | Hooks interception; approval tier × sandbox tier orthogonal combination; guardrail tripwire throws an exception and terminates | A |
| ④ | Human interruption (HITL) | interrupt_before suspends awaiting human continuation (recoverable); RunState recovers interrupted runs | A / B |
| ⑤ | Dead-loop detection / expiry | max_turns throws MaxTurnsExceeded; recursion_limit defaults to 25 as a circuit breaker; periodic tasks auto-expire after 7 days | A / B |
The key action of third-generation governance is rewriting L6 from "the approver outside the loop" into "every turn inside the loop" (this document's judgment): hooks interception happens before tool execution, inside the loop (Tier A); approval tiers (untrusted / on-request / never) and sandbox tiers (read-only / workspace-write / danger-full-access) combine orthogonally, defining the feasible domain of each turn (Tier A); Auto-review automatically approves sub-agent actions according to the planned action and recent context, passing low-risk operations and halting high-risk ones (Tier A); in OpenAI's self-deployment practice, OTel telemetry exports every turn's prompt, approval decisions, tool results, and network events to SIEM (Tier A).
The official attitude toward budgets is worth quoting directly (Tier A): "a budget cap is a good default for production agents." The semantics of exceeding limits are also nuanced: LangGraph's recursion_limit is positioned by the official forum as "a circuit breaker rather than business logic"; exceeding it is "a recoverable pause" rather than death — with the Checkpointer it can continue from the last persisted state (Tier B); industry practice recommends returning partial results (a progress summary) rather than a bare error when exceeded (Tier C).
9.4. The Framework Loop Semantics Spectrum
Each framework's loop semantics falls on a spectrum: one end is structural bounded loops ("structure decides when to stop"), the other end is model-autonomous loops + governance as backstop ("the model decides when to stop").
- Structurally bounded: Dify's Iteration node traverses an array, materializing an independent sub-engine per element; parallelism defaults to 10, per-node maximum iteration defaults to 100; n8n / Coze visual loop nodes belong to the same pattern — iteration must be bounded by array length rather than an LLM stopping condition (Tier B; n8n / Coze official first-hand loop documentation was not directly obtained; see section 15's gap statement).
- Conditionally bounded: Dify's Loop node consists of loop_count + break_conditions + loop_variables inherited across rounds; MAF Workflow requires a loop to have at least one conditional exit edge + a max_turns backstop (Tier B). AutoGen GroupChat has unpredictable loops due to LLM speaker selection and can loop infinitely when termination conditions are ambiguous — this is the direct driver of the "implicit message loop → explicit typed graph" evolution (Tier B).
- Model-autonomous + backstop: LangGraph conditional edge to END + recursion_limit circuit breaker + Checkpointer recoverable (Tier B); the OpenAI Agents SDK's final_output + max_turns + guardrail tripwire (Tier A); the Codex harness's assistant message + approval gate (Tier A); Claude Code's response without tool invocations + budget / hooks (Tier A).
The spectrum distribution is shown in Figure 9-2.
图 9-2|框架循环语义光谱
示意图:基于本文分析(信息截止 2026-09-12)。
9.5. Enterprise Deployment Recommendations
Building the Loop as a first citizen means that budget, telemetry, and human intervention should all be designed around the "turn", not around a single API call. Three main lines:
| Main Line | Recommendation | Basis |
|---|---|---|
| Loop budget | Triple hard-limit combination: iteration cap (simple Q&A 10 / research-type 25 / coding-type 50~100, set at 2~10× the p95 legitimate task) + token budget (10× the mean of legitimate tasks, warn at 80% consumption) + wall-clock timeout (2~3× the p95); when exceeded, return partial results (a progress summary) rather than a bare error; the kill switch, with a unique ID, is placed at the gateway layer — an escaped agent will not honor the limits in its own code | Industry practice, Tier C; "a budget cap is a good default for production agents" is the official statement (Tier A) |
| Loop telemetry | Organize trajectories per the OTel span tree (session → step → LLM call); core metrics: per-step latency percentiles (P50 / P95 / P99), per-session tokens, cost split by model and step, error rate and retry frequency; heuristic alarm "suspected loop after more than 10 steps"; for compliance-sensitive scenarios, enable full export of approval decisions and network events to SIEM | Community observability scheme (Tier B); Codex native OTel export (Tier A) |
| HITL gate | Approval tier × sandbox tier orthogonal combination; grant permissions per task and revoke once used; destructive actions denied by default; suspension inside the loop must be recoverable (suspend, not kill); the recovery point is written to disk | Codex approval and sandbox documentation (Tier A); LangGraph interrupt_before + Checkpointer (Tier B) |
The common logic of the three main lines is consistent with the opening of this chapter: the uncertainty of a single call cannot be eliminated, but every turn can be assembled, observed, constrained, and terminated. The loop budget turns "loss of control" into "predictable stop-loss"; telemetry turns "black-box iteration" into "attributable trajectories"; the HITL gate turns "human approval" from a bottleneck outside the loop into a flexible gate inside the loop.
For the relationship between the Loop and inter-layer contracts (the data-flow conventions when crossing layers each turn), see Chapter 10.
10. Inter-Layer Contracts and Data Flow
10.1. The Main Execution Chain and Two Lateral Supports
The main execution chain is L1 → L2 → L3: first decide what to see, then decide what can be done, and finally decide in what order to do it. The lateral supports are L4 (time dimension: state across sessions and windows) and L6 (constraint dimension: permissions, budget, audit). The closed loop is L5 → L1: the output of evaluation and observability flows back, changing the next round of context assembly.
10.2. Two Key Feedback Loops
The third-generation architecture contains two cross-layer closed loops already evidenced officially (this document's judgment; both supported by Tier-A evidence):
| Loop | Path | Official Evidence |
|---|---|---|
| Governance loop | L6 → L1 | The self-built linter's error messages directly inject repair instructions into the agent context (OpenAI) |
| Evaluation loop | L5 → L1 | The observability stack is open to the agent (LogQL / PromQL queries); the agent looks at logs, queries metrics, and verifies whether changes meet the standard, like an engineer (OpenAI); the Evaluator's failure reasons flow back to the Generator (Anthropic) |
10.3. Inter-Layer Contract Checklist
| Contract | Upstream Commitment | Downstream Dependency |
|---|---|---|
| L1 → L2 | Tool results enter the context in controlled volume and structured form | When a single tool return exceeds the limit, truncate and summarize; forbid pouring large output in directly |
| L2 → L3 | Every tool invocation has a clear side-effect tier (read-only / workspace write / sandbox execution / shared-state write / destructive) | The orchestration layer decides on this basis whether to auto-execute or request human confirmation |
| L3 → L4 | Every orchestration stage produces persistable state (progress, lists, checkpoints) | New sessions restore state via the fixed three opening steps |
| L3 → L5 | Before a task starts, reach a contract on the definition of "done" (Sprint Contract) | The Evaluator judges according to the contract, rather than explaining after the fact |
| L4 → L1 | The handoff package (progress file + git + feature list) is complete and machine-readable | The next context assembly can consume it directly |
| L6 → all | Permission denials must be traceable; safety mechanisms have no silent degradation | All layers' execution records enter the append-only audit log |
| L5 → L1 | One regression case added for every real failure | Regression signals change the context assembly strategy |
11. Key Leaps from Second to Third Generation
11.1. The Six-Item Leap List
| # | Leap | Second-Generation Approach | Third-Generation Approach |
|---|---|---|---|
| 1 | Context from "natural growth" to "active governance" | Context accumulates naturally with the conversation | The four-piece set: compaction, externalized notes, sub-agent isolation, progressive disclosure |
| 2 | Tools from "vendor-proprietary" to "neutral standard" | Function Calling / plugins (proprietary) | MCP → AAIF neutral governance |
| 3 | Evaluation from "bolted-on leaderboards" to "built-in closed loop" | Run a public leaderboard once and check the score | Built-in tracing + Evaluator role + feedback backflow to L1 |
| 4 | State from "in-session" to "cross-window handoff" | Amnesia at session end | Progress file + git + feature list + health pre-check |
| 5 | Governance from "manual prompting" to "sandbox and mechanical enforcement" | Per-item permission popups | Dual-dimension isolation + credential protection + self-built linter injecting repairs |
| 6 | Role from "human commanding" to "human steering" | Human commands each action step by step | Human Steer, Agent Execute |
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.").
11.2. The Complete Paradigm Sample of the Leap
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:
| Metric | Value |
|---|---|
| Starting point | First commit to an empty repository in late 2025-08; the scaffold was generated by Codex CLI + GPT-5, including the initial AGENTS.md, which was also written by Codex |
| Code volume after five months | About 1 million lines (application logic, infrastructure, tools, documentation, internal developer tools) |
| PR count / engineer count / per-capita daily PRs | About 1,500 / 3 engineers (later expanded to 7) / 3.5 |
| Time cost | About 1/10 of hand-writing |
| Hand-written code by humans | 0 lines |
| Longest single-task runtime | Over 6 hours |
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 belonging layers:
| Decision | Content | Belonging Layer |
|---|---|---|
| AGENTS.md changed from encyclopedia to table of contents | About 100 lines injected into context; details in structured docs/; "give Codex a map, not a 1000-page manual" | L1 |
| Linter error messages written as repair instructions | Errors directly inject repair methods into the agent context | L6 → L1 closed loop |
| doc-gardening agent | Automatically scans outdated documentation and initiates repair PRs | L6 |
| Mechanical enforcement of layered architecture constraints | Unidirectional dependency chain; cross-cutting concerns only via Providers | L6 |
| Observability open to the agent | git worktree startup, Chrome DevTools Protocol, LogQL / PromQL | L5 → L1 |
| Minimal-blocking merge philosophy | 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 universal selection principle (this document's judgment, worth remembering separately): prefer "boring technology" (composability, API stability, widespread presence in training corpora). In systems where agents write code, the technology's "model familiarity" is a real selection metric, alongside performance and ecosystem.
11.3. The Parts of the Leap Not Yet Completed
The following problems are officially acknowledged as unresolved (Tier A):
- The single-Agent vs multi-Agent debate is undecided — Anthropic explicitly states "currently unclear";
- Cross-domain generalization unverified — whether coding-scenario experience can generalize to other long-cycle tasks such as scientific research or financial modeling; "the answer is still being explored";
- The Harness itself lacks evaluation methods — the open question raised on martinfowler.com: we need Harness coverage and quality evaluation methods analogous to code coverage and mutation testing (not yet appeared);
- Entropy governance still relies on patches — doc-gardening is a remedy for decay, not a root cure for decay.
12. Cross-Layer Cross-Cutting Concerns
The following four classes of concerns belong to no single layer; they are cross-cutting aspects that pierce all six layers. They are given a chapter of their own because, in engineering practice, the most common failure is not that some layer was not built well, but that a class of cross-cutting need was handled in one layer and overlooked in the others (this document's judgment).
12.1. Cost: From Token Billing to Task-Level Budgets
How cost constraints pierce the six layers:
| Layer | Cost Interface |
|---|---|
| L1 | The attention budget is the first form of cost: stuffing in one more token is both money and a quality loss |
| L2 | Tool calls are billed per invocation; tool subtraction (Vercel 15 → 2) lowers cost and improves accuracy simultaneously |
| L3 | The cost magnitudes of orchestration structures differ enormously: single Agent (20 minutes / $9 / unusable) versus three Agent (6 hours / $200 / complete and playable); the minimal-blocking merge philosophy "the cost of correction is low, the cost of waiting is high" is an explicit cost—quality trade-off |
| L4 | Context compaction and Context Reset directly save token cost; Skills replace tokens with code (official economic rationale: sorting a list by token generation is far more expensive than running a sorting algorithm once) |
| L5 | Evaluation itself has a cost; per-sprint evaluation is for controlling evaluation overhead |
| L6 | The Budget Guardrail sets per-task and per-day budget caps; when exceeded, interrupt and escalate |
12.2. Latency: From Response Speed to End-to-End Closed-Loop Duration
The meaning of latency in agent scenarios has changed: a single call being a few hundred milliseconds slower is usually unimportant; end-to-end closed-loop duration (from task initiation to verifiable completion) is the key metric (this document's judgment). Cross-cutting manifestations:
- L2: Sandbox startup and tool round-trips are constant latency terms; the latency savings of non-sandbox execution should not come at the cost of safety.
- L3: Long-running architectures redefine "latency" as "hour-scale" — the longest single task exceeds 6 hours (OpenAI, Tier A); interruption and recovery capability therefore become the true solution to the latency problem.
- L5: Performance requirements are written as measurable acceptance conditions ("ensure the service starts within 800ms", OpenAI, Tier A); latency becomes an object of L5 judgment rather than an experience problem.
- L1: The longer the context, the slower and more expensive the reasoning; compaction is simultaneously a latency optimization.
12.3. Observability: From Application Monitoring to Trajectory Replay
- Pervasive requirement: The full-process Trace of any task must be replayable — tool invocations, file changes, command output summaries, reasoning step indices. Failures without a Trace cannot be post-mortemed, equal to the team tuning parameters in the dark (this document's judgment).
- Forward supply: Observational data is open to the agent (LogQL / PromQL); the agent uses it to self-verify — observability becomes "a feedback source from L5 → L1" rather than "for humans to see".
- Cost attribution: The Trace is the foundation of cost and quality attribution; without a Trace, one cannot answer "did this change make things better or worse".
- L6 dependency: The countermeasure for audit not being traceable is full-layer tracing + structured logs (OpenAI lists structured logging as a mechanically enforced taste invariant).
12.4. Safety: From Single-Point Defense to Depth Piercing All Six Layers
| Layer | Safety Interface |
|---|---|
| L1 | Context poisoning is a safety event: a polluted context puts all subsequent reasoning on a wrong premise; the instruction file itself is an attack surface (external content can inject instructions) |
| L2 | Sandbox dual-dimension isolation (filesystem + network) is the foundation of safety; credential protection deny / mask |
| L3 | The orchestration layer's risk is "over-authorization": permissions granted per task and revoked once used; destructive actions denied by default |
| L4 | Memory poisoning: erroneous information written into long-term memory propagates continuously across sessions |
| L5 | The evaluation set itself needs protection from pollution; the held-out set is invisible |
| L6 | Permissions, audit, and budget are the execution and recording surface of safety policy |
13. Architecture Maturity Self-Assessment Table
13.1. Framework Notes and Five-Level Definitions
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.
| Level | Name | Generic Definition |
|---|---|---|
| L0 | Missing | The layer does not exist or fully depends on humans; problems are not systematically noticed |
| L1 | Manual | Practices exist, but rely on human execution and conventions to maintain; not reproducible, not regression-testable |
| L2 | Tool-based | Dedicated tools or components exist; can execute automatically, but lack governance policy |
| L3 | Systematized | Clear policy and default architecture; can be measured and can regress in CI |
| L4 | Closed-loop autonomous | The layer's output automatically flows back to improve other layers; possesses anti-entropy mechanisms |
13.2. Six-Layer × Five-Level Self-Assessment Table
| Layer | L0 Missing | L1 Manual | L2 Tool-based | L3 Systematized | L4 Closed-loop Autonomous |
|---|---|---|---|---|---|
| L1 Context Engineering | Context accumulates naturally, no management | Manually selecting and pasting context | Connected to RAG / retrieval | The four-piece set of compaction + externalized notes + sub-agent isolation + progressive disclosure; has attention budget awareness | Context assembly strategy automatically adjusted by L5 feedback; Skills and docs auto-trimmed and updated |
| L2 Tooling and Execution | The model can only output text | A few hard-coded tools | Function Calling + several proprietary tools | Tools standardized via MCP; running in a dual-dimension isolated sandbox (filesystem + network) | The toolset is automatically added/removed based on usage data and failure feedback |
| L3 Orchestration and Control | Single-turn invocation | Manually chaining processes | Orchestration framework single loop | Supports long-running, Sprint Contract, sub-agent dispatch, determinism + dynamic routing coexisting | The orchestration structure itself can be evaluated and auto-selected; can perform failure-mode analysis on itself |
| L4 Memory and State | Amnesia at session end | Manually writing handoff notes | Has session persistence | Progress file + git + machine-readable task list + opening health pre-check | State handoff automatically verified; dirty state auto-repaired before the next round opens |
| L5 Evaluation and Observability | Relies on human eyes to see results | Manual spot checks | Occasionally runs public benchmarks | Built-in tracing + self-built Golden Dataset + one regression case added for every real failure | The evaluator is separated from the evaluated and the Evaluator evolves independently; the held-out set prevents overfitting; observational data is fed back to L1 |
| L6 Governance and Safety | No boundaries | Per-item human approval | Has permission configuration | Sandbox + credential protection + self-built linter mechanical enforcement; failIfUnavailable hard failure | Governance rules can be understood by the agent and self-repaired (the error message is the repair instruction); entropy growth is continuously auto-governed |
13.3. Result Interpretation and Usage Recommendations
| Score Pattern | Reading | Suggested Action |
|---|---|---|
| Most layers at L0~L1 | Does not yet have a third-generation Harness; at early second generation | Prioritize building L2 (tool standardization) and L5 (at least a regression set); defer other layers |
| Most layers at L2 | Typical "tools are complete but unstable" state | Prioritize attacking L1 (context governance) and L6 (sandbox); these two are the most common bottlenecks |
| Most layers at L3 | Reached third-generation mainstream level | The focus is maintaining: build this Harness's regression mechanism to prevent degradation as models upgrade |
| L4 layers appear | At frontier exploration | Be wary that excessive Harness complexity may be directly flattened by the next model upgrade |
| Inter-layer gap ≥ 2 levels | Structural weakness exists | The weak layer determines the overall ceiling; prioritize filling it |
The item inter-layer gap ≥ 2 levels is especially important (this document's judgment): 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.
Usage recommendations: self-assess once every six months, using the results for longitudinal comparison rather than horizontal scores; give specific evidence layer by layer, do not write abstract "medium"; prioritize the weakest layer; 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.
14. 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.
What strings the six layers together is nine characters: visible, stable, regressable. The four classes of cross-cutting concerns — cost, latency, observability, and safety — pierce the six layers; any layer's omission will be made up in the other layers in the form of incidents.
For the differentiated landing of the six-layer model across industries — whose center of gravity is in L4, whose is in L5, whose ground truth is physical law — see Chapter 4 (Practice).
15. Information Gap Statement
This document involves the following information gaps; they have been flagged in the corresponding places in the body and are summarized here:
- Section 3.5: context degradation "performance drop exceeding 45%" and Chroma Research "all 18 frontier models degraded" (Tier C).
- Section 4.3: Codex CLI sandbox parameters, about 95% Rust code share, Auto-review's 1/200 and 99% (Tier B).
- Section 4.4: Vercel's tool count 15 → 2 accuracy 80% → 100%, Token −37%, speed 3.5× (Tier C).
- Section 5.3: the comparison experiment numbers for single Agent (20 minutes / $9 / unusable) versus three Agent (6 hours / $200 / complete and playable) (Tier C).
- Section 7.3: Terminal-Bench leaderboard numbers (77.3% / 75.1% / 74.7% / 71.9%), LangChain 52.8% → 66.5%; the official site's (tbench.ai) current leaderboard was not directly scraped; all are third-party paraphrases.
- Differing wording on MCP's initial version: two criteria coexist — 2024-11-05 (the Ruby SDK records it as Initial protocol revision) and 2024-11-25 (public announcement); this document takes 2024-11-05 as the initial version and presents the difference in parallel.
- The exact URL and publication date of Anthropic's "How we built our multi-agent research system" are unverified.
- The ISO/IEC-level agent interconnection international standard number: no authoritative information currently.
Newly added this round (Chapter 9, Harness Loop)
- The specific publication dates of OpenAI official blog posts such as "Unrolling the Codex agent loop", "Unlocking the Codex harness", and "Codex as a platform" were not directly returned in the search results (Chapter 9).
- 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" (section 9.1).
- The triple hard-limit empirical values and "an out-of-control loop's cost is about 30× a normal task" are an industry practice compilation (Tier C); directional reference only (section 9.5).
- n8n / Coze loop nodes lack independent first-hand official documentation; only indirectly covered via the common bounded-loop pattern of visualization workflows (section 9.4).
16. References
- Effective context engineering for AI agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
- Effective harnesses for long-running agents — Anthropic, 2025. https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents
- Harness design for long-running application development — Anthropic, 2026. https://www.anthropic.com/engineering/harness-design-long-running-apps
- Harness engineering: leveraging Codex in an agent-first world — OpenAI, 2026-02-11. https://openai.com/index/harness-engineering/
- Sandboxing: a safer and more autonomous approach — Anthropic, 2025. https://www.anthropic.com/engineering/claude-code-sandboxing
- Introducing the Model Context Protocol — Anthropic, 2024-11-25. https://www.anthropic.com/news/model-context-protocol
- Model Context Protocol official specification (2026-07-28) — MCP / AAIF. https://modelcontextprotocol.io/specification/2026-07-28/
- A year of open collaboration: Celebrating the anniversary of A2A — Google, 2026-04-16. https://opensource.googleblog.com/
- Equipping agents for the real world with Agent Skills — Anthropic, 2025-10-16 (2025-12-18 open standard update). https://www.anthropic.com/news/skills
- 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/
- Harness engineering for coding agent users — Birgitta Böckeler, martinfowler.com, 2026. https://martinfowler.com/articles/harness-engineering.html
- SWE-bench — Jimenez, Yang et al. (Princeton), 2023-10 (ICLR 2024 Oral). https://www.swebench.com/
- Terminal-Bench — Stanford / Laude Institute, 2025. https://www.tbench.ai/
- Linux Foundation Announces the Formation of the AAIF — Linux Foundation / AAIF, 2025-12-09. https://aaif.io/
- 2025 Stack Overflow Developer Survey — Stack Overflow, 2025-07-29. https://survey.stackoverflow.co/2025/
- How the agent loop works — Anthropic, 2026. https://docs.anthropic.com/en/docs/agent-sdk/agent-loop
- Building agents with the Claude Agent SDK — Anthropic, 2025. https://claude.com/blog/building-agents-with-the-claude-agent-sdk
- Loop engineering: Getting started with loops — Claude Code team, Anthropic, 2026-06-30. https://claude.com/blog/getting-started-with-loops
- A harness for every task: dynamic workflows in Claude Code — Anthropic, 2026. https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code
- Unrolling the Codex agent loop — OpenAI, 2025—2026 (publication date unverified, see section 15). https://openai.com/index/unrolling-the-codex-agent-loop/
- Codex as a platform: build on the open agent harness — OpenAI Developers, 2026. https://developers.openai.com/blog/codex-as-a-platform
- Running agents — OpenAI Agents SDK official documentation, 2026. https://openai.github.io/openai-agents-python/running_agents/
- Running Codex safely at OpenAI — OpenAI, 2026. https://openai.com/index/running-codex-safely/
- Agent approvals & security — Codex official documentation, 2026. https://developers.openai.com/codex/sandbox
- gemini-cli (open-source repository and ReAct loop documentation) — Google, 2025—2026. https://github.com/google-gemini/gemini-cli
- What does recursionLimit actually count in createAgent? — LangChain official forum, 2025—2026. https://forum.langchain.com/t/what-does-recursionlimit-actually-count-in-createagent-langchain-js/3460
- Dify node system documentation (Iteration / Loop nodes) — LangGenius, 2026 (via DeepWiki structured index). https://deepwiki.com/langgenius/dify-docs/1.3-node-system-overview
- Iteration Node — Agent Patterns Catalog, 2026. https://www.agentpatternscatalog.org/patterns/iteration-node
- Runaway Tool Loops — PolicyLayer, 2026 (case occurred in 2025-11, verified: partial). https://policylayer.com/attacks/runaway-tool-loops