Agents(智能体工程化)
1. 介绍
1.1. 背景:从"一个会聊天的模型"到"一群可编排的执行单元"
2023 年前后,行业主流形态是"一个模型 + 一段提示词"。这种形态在单次对话中表现良好,但一旦任务需要多步执行、需要调用外部系统、需要中断恢复、需要多人协作,就暴露出结构性缺陷:模型不知道自己"做到哪一步",也没有机制保证它"不会做过头"。
2025 年之后,形态发生了根本变化。智能体(Agent)不再是提示词的另一种说法,而成为运行在 Harness 之上的执行单元:它有明确的循环结构(Agent Loop)、有可派发的子单元(Sub-agent)、有显式的交接协议(Handoff)、有可被外部系统拦截的事件钩子(Hooks)、有可回放的轨迹(Trace)。
这一变化的关键意义在于:智能体本身成为了一个可以被工程化管理的对象。就像进程之于操作系统——进程有生命周期、有优先级、有资源配额、有终止信号;智能体同样需要这些。
1.2. 定义
Agents 方向(智能体工程化):研究与实践智能体自身的结构、协作、交接、终止与控制机制的工程领域。它不关注单次生成质量(那是 Coding 与 Eval 方向的事),而关注:
- 一个智能体的循环如何开始、如何推进、如何判定结束;
- 多个智能体之间如何分工、如何传参、如何避免上下文互相污染;
- 外部系统如何在关键节点确定性地拦截或改写智能体的行为;
- 智能体失败时如何保存状态、如何恢复、如何不重复已完成的副作用。
依据项目参数卡,Agent(智能体)是运行在 Harness 之上的执行单元,Harness 是 Agent 的"底盘"。本方向讨论的正是这个底盘的控制面。
1.3. 在 AI Harness 体系中的定位
图 1-1|Agents 在 Harness 六层体系中的定位
数据来源:基于本文分析绘制的示意图。
本方向横跨 Harness 六层,主层为 L3 编排与控制层,次层为 L2 工具与执行层与 L6 治理与安全层。
| Harness 层 | 本方向的职责 | 具体形态 |
|---|---|---|
| L1 上下文工程 | 次 | 决定每个子智能体"看到什么":上下文隔离策略、共享摘要、指令文件就近优先 |
| L2 工具与执行 | 次 | 决定子智能体"能做什么":工具集切分、副作用分级、沙箱边界 |
| L3 编排与控制 | 主 | Agent Loop、Plan-and-Execute、Sub-agent 派发与 Handoff、事件钩子、中断与恢复 |
| L4 记忆与状态 | 参与 | 检查点(Checkpoint)、会话状态、子智能体产出的工件(Artifact) |
| L5 评估与观测 | 参与 | 轨迹采集、步数/成本指标、循环不收敛检测 |
| L6 治理与安全 | 次 | 权限分级、破坏性操作硬拦截、预算护栏、审计留痕 |
1.4. 瓶颈所在层
本方向的瓶颈不在模型能力,而在 L3 编排与控制层,具体表现为三个结构性难题:
- 循环不收敛。智能体缺少明确的终止判定时,会在"再试一次""换个思路"之间反复震荡,消耗掉全部预算却无实质进展。DORA 2025(2025-11-12)显示 30% 的 AI 任务单次耗时超过 4 小时——这一数字侧面反映了长时程任务中控制机制的缺位。
- 上下文互相污染。多个子智能体共享同一上下文时,任一单元的中间过程(错误尝试、废弃方案)都会污染其他单元的判断;完全隔离又会导致公共约束丢失。
- 控制依赖模型的自觉。把"不要删除文件""不要强制推送"写进提示词,等于把安全边界建立在模型的记忆与意愿之上。这是不可靠的:约束必须是确定性的、可被外部系统执行的。
第三个难题的破解方式,正是本方向近年最重要的工程进展:用事件钩子(Hooks)把控制从"提示"变成"机制"。
1.5. 价值
- 把不确定性收敛到可枚举的状态机。智能体的行为空间从"无限"变成"有限状态 + 有限转移",这是可测试、可审计的前提。
- 让安全边界可执行。依赖提示词的约束是建议;依赖钩子的约束是规则。
- 让失败可恢复。有检查点的智能体,失败时损失的是时间,不是全部进度。
- 让协作可分工。多智能体的价值不在"多个模型一起想",而在并行 + 隔离 + 汇总——把大任务切成互不干扰的写分区,各自完成后合并。
2. 名词解释
| 术语 | 英文 / 缩写 | 释义 |
|---|---|---|
| 智能体 | Agent | 运行在 Harness 之上的执行单元;具备循环结构、工具调用能力与终止条件 |
| 智能体循环 | Agent Loop | "观察—思考—行动—观察"的迭代结构,是智能体的基本运行形态 |
| 子智能体 | Sub-agent | 由父智能体派发的下级执行单元,通常拥有独立的上下文窗口与工具子集 |
| 交接 | Handoff | 一个智能体把任务(连同状态与产出)显式转交给另一个智能体的协议动作 |
| 多智能体系统 | Multi-Agent System / MAS | 由多个智能体组成、通过消息或共享状态协作的系统 |
| 编排器 | Orchestrator | 负责任务拆解、派发、汇总与终止判定的控制组件 |
| 事件钩子 | Hooks | 在智能体生命周期的确定节点被触发的外部脚本或策略,用于确定性地拦截或改写行为 |
| 工具调用前钩子 | PreToolUse | 在工具被实际执行之前触发的事件,可用于阻断、改写输入或自动授权 |
| 工具调用后钩子 | PostToolUse | 在工具执行之后触发的事件,可用于校验结果、注入上下文或触发后续动作 |
| 终止钩子 | Stop / SubagentStop | 在智能体(或子智能体)即将结束运行时触发的事件,可用于阻止结束并要求继续工作 |
| 上下文压缩前钩子 | PreCompact | 在上下文压缩发生之前触发的事件,可用于归档关键信息 |
| 阻断型退出码 | Blocking Exit Code | 钩子以特定退出码(如退出码 2)结束时,表示"阻断本次动作并把反馈交回模型"的约定语义 |
| 工具契约 | Tool Contract | 工具的机器可读声明:名称、参数模式、副作用级别、幂等性、超时、输出体积上限 |
| 幂等性 | Idempotency | 同一操作重复执行多次与执行一次的效果相同,是重试安全性的前提 |
| 检查点与恢复 | Checkpoint / Resume | 在关键节点保存运行状态,使中断后可从断点继续而非从头开始 |
| 上下文隔离 | Context Isolation | 子智能体之间不共享完整上下文,仅通过显式契约传递必要信息的策略 |
| 终止条件 | Termination Condition | 智能体判定"任务已完成并可以停止"的明确、可检查的条件 |
| 预算护栏 | Budget Guardrail | 对步数、Token、调用次数、时长设定的硬上限,超限即中断并升级 |
| 模型上下文协议 | Model Context Protocol / MCP | 智能体与外部工具/数据源之间的开放连接协议,是 L2 层的事实标准之一 |
| 轨迹 | Trace | 智能体全过程的结构化记录,是评估、复盘与审计的原始材料 |
| 循环不收敛 | Non-convergence | 智能体在预算内未取得实质进展却持续迭代的失效状态 |
| 写分区 | Write Partition | 多智能体并行时按文件或模块划分的互斥写入范围,用于避免并发写冲突 |
3. 案例
说明:以下案例依据公开可核实的一手来源整理。案例中的效果数字均为来源方公布口径,引用时须连同评测日期与配置一并标注。
3.1. 案例一:事件钩子驱动的多智能体编排
来源:Anthropic,Claude Code 官方文档(Hooks 章节),https://docs.claude.com/en/docs/claude-code/hooks
3.1.1. 背景
早期的智能体产品把安全与流程约束写进系统提示词。工程实践中暴露出三类问题:约束在长任务中被上下文压缩挤出;模型在"完成任务的压力"下自行合理化越界行为;同类约束需要在多个入口重复书写,导致条款漂移。
3.1.2. 方案
将控制点从"提示词内"外移到"生命周期事件上",形成一张确定性的事件—策略表。核心设计如下:
表 3-1 智能体生命周期事件表(九类事件)
| 事件 | 触发时机 | 典型用途 | 可否阻断 |
|---|---|---|---|
SessionStart | 会话开始时 | 加载项目上下文、注入环境说明、初始化预算计数 | 否(可注入上下文) |
UserPromptSubmit | 用户提交提示词时 | 输入校验、敏感信息过滤、任务分类与路由 | 是 |
PreToolUse | 工具调用之前 | 权限拦截、参数改写、危险命令拒绝、自动授权低风险工具 | 是(核心控制点) |
PostToolUse | 工具调用之后 | 结果校验、输出体积裁剪、触发后续动作、记录证据 | 是(可附加反馈) |
Notification | 系统发出通知时 | 等待人工输入时的自定义提醒、外部系统联动 | 否 |
SubagentStop | 子智能体即将结束时 | 校验子智能体产出是否合格,不合格则要求继续 | 是(可阻止结束) |
Stop | 主智能体即将结束时 | 校验完成度(如测试是否跑过),未完成则要求继续 | 是(可阻止结束) |
PreCompact | 上下文压缩之前 | 归档关键决策与约束,防止压缩丢失 | 否(可注入上下文) |
SessionEnd | 会话结束时 | 归档 Trace、生成任务小结、清理临时状态 | 否 |
表 3-2 钩子退出码语义(典型约定)
| 退出码 | 语义 | 智能体的后续行为 |
|---|---|---|
| 0 | 成功,无附加信息 | 正常继续;标准输出在部分模式下对用户可见 |
| 2 | 阻断 | 当前动作被阻止;标准错误被回传给模型,模型据此调整行为 |
| 其他非 0 | 非阻断性错误 | 动作继续;错误仅供日志与观测使用 |
退出码 2 的语义是本方向的关键设计:它把"不行"从一个语言层面的请求,变成了一个系统层面的事实。模型可以再次尝试,但无法绕过。
表 3-3 优先级与就近原则
指令与控制策略的优先级由高到低为:
| 优先级 | 来源 | 说明 |
|---|---|---|
| 1(最高) | 用户显式指令 | 会话中直接给出的指令覆盖一切配置 |
| 2 | 就近/子目录指令文件 | 最靠近被操作对象的指令优先 |
| 3 | 项目级指令文件 | 项目根目录下的约定 |
| 4 | 用户级全局指令 | 个人偏好,仅在不与项目约定冲突时生效 |
| 5(最低) | 企业级托管策略 | 组织级基线,可被上层覆盖但通常设为不可覆盖 |
3.1.3. 效果
- 安全约束从"提示"变为"机制":危险命令的拦截不再依赖模型的记忆,而由钩子在工具执行前确定性阻断。
- 长任务中约束不再丢失:
PreCompact事件保证压缩前归档关键条款;SessionStart保证每次会话重新注入。 - 完成度可被强制校验:
Stop钩子可检查"测试是否跑过""证据是否齐备",未满足则阻止结束。 - 该模式已被多个智能体产品借鉴,成为第三代 Harness(运行时与评估时代)的标志性特征之一。
3.2. 案例二:企业内部多智能体研发流水线
来源:阿里巴巴集团公开技术实践(2025-09);腾讯 CodeBuddy 公开实践(2025-08)
3.2.1. 背景
大型研发组织的痛点不是"能不能生成代码",而是跨仓库、跨语言、跨团队的一致性:一个需求往往同时触及前端、后端、配置与测试,单点智能体难以覆盖,且生成结果需要满足组织内部的框架约定、命名规范与安全基线。
3.2.2. 方案
采用"编排器 + 专职子智能体"的分层结构:
- 编排器(Orchestrator):负责需求拆解、任务派发、依赖排序与结果汇总;自身不写业务代码。
- 专职子智能体:按职责切分(需求分析、编码、测试生成、代码审查、文档),每类子智能体拥有独立的上下文窗口与最小化的工具子集。
- 写分区:并行子智能体按模块划分互斥写入范围,禁止并发写同一文件。
- Handoff 契约:子智能体之间不共享完整上下文,仅传递结构化产物(变更清单、接口签名、测试结果)与约束摘要。
- 组织约定注入:通过分层指令文件把框架约定、命名规范、安全基线注入到每一层,就近覆盖。
- 人工确认点前置:在派发之前确认拆解方案与影响面,而非在全部完成后审查。
3.2.3. 效果
公开的量化结果中,腾讯 CodeBuddy 的实践(2025-08)显示 Code Review 时间下降 80%+。阿里巴巴于 2025-09 公开的内部实践同样指向"研发流程级集成"而非"单点提效"。
需要强调的是:上述为厂商自评口径。企业落地时应建立内部度量(见 05-eval.md),并以端到端指标而非环节耗时作为结论依据——这是因为环节提速可能被下游环节的成本增加抵消(详见 3.3 与 05-eval 中的"自评—实测背离"讨论)。
3.3. 案例三:长时程终端任务的智能体能力边界
来源:Terminal-Bench 2.0 官方榜单,https://www.tbench.ai/
3.3.1. 背景
Terminal-Bench 是一类面向长时程终端操作任务的智能体基准:智能体需要在真实的终端环境中,通过数十至数百步命令完成系统配置、故障排查、环境搭建等任务。与"写代码"不同,这类任务的每一步都可能改变系统状态,且不可逆。
3.3.2. 方案(评测设计视角)
Terminal-Bench 2.0 的设计体现出本方向的三个关键控制要求:
- 步数与时长预算:任务在有限步数内完成,考察智能体的规划效率而非穷举能力。
- 状态可判定:每个任务有明确的通过/失败判定(通常是一组断言脚本),避免主观评分。
- 环境隔离:每轮评测在干净环境中进行,避免上一轮的状态污染下一轮——这正是"智能体副作用必须可隔离"的工程要求。
3.3.3. 效果
| 模型 | 得分 | 评测日期 | 备注 |
|---|---|---|---|
| Claude Sonnet 4.5 | 51.0% | 2025-09-29 | 该榜首个突破 50% 的成绩 |
| GPT-5.2 | 54.0% | 2025-12-11 | 后续刷新 |
解读:即使在最好的公开成绩下,仍有近半数长时程终端任务失败。这说明本方向的瓶颈确实不在"模型够不够聪明",而在控制机制——如何规划、如何止损、如何在不可逆操作前停下。Terminal-Bench 2.0 的完整榜单数字与更细分项得分标注为 。
4. 实践标准
4.1. AGENTS.md 规范
以下为本方向的完整 AGENTS.md 原文,置于代码块中以便直接复制。使用时须叠加组级 AGENTS.md 的共同条款,冲突时以就近优先原则消解。
# AGENTS.md —— 软件工程 · Agents 方向(智能体工程化)
## 角色与边界
- 本文件约束**构建与运行智能体系统**的工作:Agent Loop 设计、Sub-agent 定义、Handoff 协议、Hooks 配置、编排器实现、智能体运行时改造。
- 允许自行完成:设计循环结构、定义子智能体契约、配置事件钩子、实现终止条件、编写 Handoff 数据结构、构造 Trace 采集点、设置预算护栏。
- 禁止自行完成:为智能体授予共享状态写权限(S 级)或破坏性权限(D 级)、关闭或绕过已有的拦截钩子、修改审计配置、删除 Trace。
- 边界判定:凡改变**智能体可执行动作集合**的改动,一律视为安全相关变更,须走人工评审。
## 环境假设
- 提供智能体运行时(Agent Runtime),支持:循环控制、子智能体派发、事件钩子注册、检查点保存与恢复。
- 提供容器或微虚机沙箱,智能体的一切命令执行均在沙箱内完成。
- 提供 Trace 采集与存储,保证全过程可回放。
- 提供成本与步数计量,且支持设置硬上限。
- 提供工具注册中心,每个工具有机器可读的副作用分级声明。
- 缺失任一项时,降级执行并在任务开始时声明缺失项与风险。
## 上下文加载顺序(Context Budget)
1. 任务契约:目标、产出物、验收标准(固定,不压缩)
2. 就近指令文件:当前目录及其祖先链
3. 运行时现状清单:已有的子智能体定义、钩子配置、工具注册表
4. 相关实现源码:循环、派发、钩子处理逻辑
5. 测试与仿真:智能体行为的测试用例与仿真脚本
6. 历史事故记录:循环不收敛、越权、上下文污染事件
7. 工具结果:按需追加
每一步记入 Token 预算表;超限执行压缩而非截断,压缩前须经 PreCompact 归档关键约束。
## 工具契约
- 所有工具必须有声明:名称、参数模式、副作用级别(R/W/X/S/D)、幂等性、超时、输出体积上限。无声明工具不得注册。
- 子智能体的工具集必须是父级工具集的**子集**,遵循最小权限。
- S 级与 D 级工具默认不在任何子智能体中启用;确需时须在契约中逐项列出并说明必要性。
- 所有执行类工具必须设置超时;超时即失败,进入失败处理流程。
- 输出超过约定行数时必须截断并给出定位信息(路径 + 行号区间)。
## 任务执行流程(SOP)
1. 解析任务契约,明确产出物与验收标准;契约缺失则停止并澄清。
2. 绘制控制流图:状态、转移、终止条件、异常处理分支。
3. 确定子智能体切分方案与写分区边界。
4. 定义 Handoff 契约:传递字段、类型、必填性、失败语义。
5. 设计事件钩子表:事件、触发条件、判定逻辑、退出码语义。
6. 设定预算护栏:步数上限、Token 上限、时长上限、重试上限。
7. 实现后用仿真脚本验证控制流(含终止条件可达性测试)。
8. 输出配置与说明,进入人工评审。
## 验证与证据要求
必须通过以下验证并留存证据:
| 验证项 | 判定方式 | 证据 |
|---|---|---|
| 终止条件可达 | 遍历状态图,存在从任一状态到终止态的路径 | 状态图 + 可达性分析结论 |
| 循环有界 | 步数上限存在且可被运行时强制执行 | 配置 + 超限触发测试记录 |
| 上下文隔离有效 | 子智能体之间不共享完整上下文 | 隔离测试:一个子单元注入噪声,另一单元不受影响 |
| 拦截确定 | 危险动作被钩子阻断,模型无法绕过 | 拦截测试:每种 D 级动作至少一次实测拦截 |
| 检查点可恢复 | 中断后从检查点恢复,不重复已完成副作用 | 恢复测试:中断—恢复—比对副作用次数 |
| Trace 完整 | 全过程工具调用可回放 | Trace 样本 + 回放校验 |
| 预算生效 | 超限时中断并升级 | 超限测试记录 |
| 并行无写冲突 | 并发子智能体不写同一文件 | 并发测试记录 |
禁止以"逻辑上应该没问题"作为验证结论;禁止用修改断言的方式让验证通过。
## 失败与升级策略
| 失败 | 处理 |
|---|---|
| 循环不收敛(步数超预算且无进展) | 强制终止,保存检查点,输出进展与卡点,上报 |
| 越权被拦截 | 不得绕过;记录意图与命令,转入人工升级 |
| 子智能体产出不合格 | 由 SubagentStop 钩子判定为不合格并要求继续;超过重试上限则终止并上报 |
| 恢复后副作用重复 | 判定检查点设计缺陷,回滚并修复;禁止以去重脚本掩盖 |
| 契约冲突(Handoff 字段不一致) | 停止派发,上报冲突点 |
升级三要素:已尝试动作与结果、卡点现象与证据、建议选项及风险。缺一无效。
## 安全与合规红线
1. 禁止为智能体授予 D 级(破坏性/不可逆)权限;确需时须逐命令人工确认并留痕。
2. 禁止关闭、绕过、或降低已有拦截钩子的严格程度;钩子变更须走安全评审。
3. 禁止子智能体继承父级全部权限;权限必须显式最小化授予。
4. 禁止删除、篡改、压缩 Trace 与审计日志。
5. 禁止在指令文件、配置、日志中写入密钥、Token 与个人信息。
6. 遵循 OWASP Agentic AI 威胁与缓解清单(T&C,2025-12-09;V1.0,2026-03-16),重点防范目标劫持、工具滥用、身份与权限混淆、记忆投毒。
7. 遵循 OWASP Top 10 MCP(2025-12-07),对工具服务端做来源审查与权限最小化。
8. 组织级落地对齐 ISO/IEC 42001:2023 的角色职责与成文信息要求。
## 禁止事项
1. 禁止把安全约束只写在提示词里而不用钩子做硬拦截。
2. 禁止设计无终止条件的循环。
3. 禁止让多个子智能体并发写同一文件而不做写分区。
4. 禁止在检查点中遗漏工具副作用记录。
5. 禁止一次性请求过宽权限。
6. 禁止以"模型认为"作为技术判断依据。
7. 禁止使用 `[待填写]`、`XX`、`___` 之外的非标准占位符;不确定处统一使用 `[待填写]`。
## 输出格式
- 控制流图(状态与转移的文字化描述或图)
- 子智能体清单:名称、职责、工具子集、上下文范围、写分区
- Handoff 契约:字段名、类型、必填、失败语义
- 事件钩子表:事件、触发条件、判定逻辑、退出码语义
- 预算配置:步数、Token、时长、重试上限
- 验证记录:八项验证的逐项结果
- 变更说明五段:改了什么 / 为什么 / 如何验证 / 风险 / 如何回滚
## 评估与自检
| 自检项 | 判定 |
|---|---|
| 终止条件是否明确且可达 | 是 / 否 |
| 循环是否有硬边界 | 是 / 否 |
| 子智能体上下文是否隔离 | 是 / 否 |
| 危险动作是否由钩子硬拦截 | 是 / 否 |
| 检查点是否可恢复且不重复副作用 | 是 / 否 |
| Trace 是否完整可回放 | 是 / 否 |
| 预算护栏是否生效 | 是 / 否 |
| 并行写分区是否互斥 | 是 / 否 |
任一"否"须显式列出;自检不通过即任务未完成。 4.2. SKILL.md 规范
---
name: multi-agent-orchestration-setup
description: 设计与落地一套多智能体编排系统:拆解任务、切分子智能体与写分区、定义 Handoff 契约、配置事件钩子与退出码语义、设定预算护栏与终止条件,并通过八项控制流验证。当需要让多个智能体协作完成一项工程任务,或为既有智能体系统补足控制面时使用。
version: 1.0
created: 2026-09-12
---
# 多智能体编排系统搭建
## 适用场景
- 单个智能体无法在预算内完成的大任务,需要拆解与并行。
- 任务可按模块/文件/职责切分,且各部分的写入范围互不重叠。
- 需要为既有智能体系统补足控制面:终止条件、拦截钩子、检查点、预算护栏。
- 需要把"不要做某事"从提示词升级为确定性机制。
不适用于:单步任务、无法切分的整体性创作、无判定标准的开放式探索。
## 前置条件
| 类别 | 要求 | 缺失时处置 |
|---|---|---|
| 任务契约 | 目标、产出物、验收标准明确 | 停止,先补全契约 |
| 运行时 | 支持子智能体派发与事件钩子注册 | 降级为单智能体 + 外部脚本控制 |
| 沙箱 | 命令执行在容器或微虚机内 | 禁止执行,升级 |
| 工具注册 | 工具有副作用分级声明 | 先补齐声明 |
| Trace | 工具调用与文件变更可完整记录 | 降级执行并声明"不可回放" |
| 计量 | 步数/Token/时长可设上限 | 设定保守默认上限 |
## 输入
- 任务描述与验收标准
- 仓库或系统的模块边界
- 可用工具清单及其副作用分级
- 预算上限(步数 / Token / 时长)
- 现有智能体与钩子配置(如为改造任务)
## 输出
- 控制流图(状态、转移、终止条件、异常分支)
- 子智能体清单(职责、工具子集、上下文范围、写分区)
- Handoff 契约(字段、类型、必填、失败语义)
- 事件钩子表(事件、触发条件、判定逻辑、退出码语义)
- 预算与护栏配置
- 八项控制流验证记录
- 五段式变更说明
## 执行步骤
1. **拆解**:按写分区而非按"思考角色"切分任务。判断标准是"两部分的写入范围是否重叠"——重叠则不得并行。
2. **定义子智能体**:为每个分区设定职责、工具子集(父级子集)、上下文范围(仅含本分区必要信息)。
3. **设计 Handoff 契约**:只传结构化产物与约束摘要,不传完整上下文。字段须有类型与失败语义。
4. **配置事件钩子**:至少覆盖 `PreToolUse`(拦截)、`PostToolUse`(校验)、`Stop`(完成度)、`SubagentStop`(子单元质量)。明确退出码 2 为阻断语义。
5. **设定终止条件**:必须写成可检查的断言(如"测试命令退出码为 0 且失败数为 0"),不得写成"任务看起来完成了"。
6. **设定预算护栏**:步数、Token、时长、重试上限,且由运行时强制执行。
7. **设计检查点**:在每个不可逆动作之前保存,检查点须记录已产生的副作用清单。
8. **仿真验证**:用脚本跑通八项验证(终止可达、循环有界、隔离有效、拦截确定、恢复无重复、Trace 完整、预算生效、并行无冲突)。
9. **交付**:输出配置、说明与验证记录,进入人工评审。
## 质量标准(DoD)
1. 终止条件明确、可检查、可达。
2. 循环存在运行时强制的硬边界,超限即中断。
3. 子智能体上下文隔离,且工具集为父级子集。
4. 每一类 D 级动作都有实测通过的拦截记录。
5. 检查点可恢复,恢复后不重复任何已完成的副作用。
6. Trace 完整且可回放。
7. 并行写分区互斥,无并发写同一文件。
8. 预算护栏在实测中确实触发中断。
9. 未触及权限与安全红线。
10. 变更说明五段齐全,回滚方案不依赖智能体继续参与。
## 常见失败与处理
| 失败 | 表现 | 处理 |
|---|---|---|
| 循环不收敛 | 步数耗尽无实质进展 | 强制终止 + 保存检查点 + 上报卡点 |
| 上下文污染 | 子单元引入无关信息影响判断 | 收紧 Handoff 字段,只传结构化产物 |
| 越权尝试 | 试图执行 D 级操作 | 不得绕过;记录并升级 |
| 拦截失效 | 钩子未触发或被绕过 | 判定为阻断性缺陷,回滚 |
| 恢复后重复副作用 | 非幂等动作被重放 | 修复检查点记录,禁止用去重脚本掩盖 |
| 写冲突 | 两子单元改同一文件 | 重新划分写分区或改为串行 |
| 终止条件不可达 | 断言永远为假 | 修正断言,或增加"最大努力后上报"的兜底分支 |
## 示例
**场景**:为一个 12 万行的单体仓库做"模块 A 的接口迁移",涉及 40 个调用点。
- 切分:按目录划分 5 个写分区,每区 8 个调用点;交叉引用点单独列为串行区。
- 子智能体:5 个迁移单元(工具集 = 读文件 + 编辑 + 构建/测试,无 git push),1 个汇总单元。
- Handoff:传 `{file, oldSymbol, newSymbol, verified: bool, testCmd, exitCode}`。
- 钩子:`PreToolUse` 拦截任何 `git push` / `rm -rf` / `git checkout --`(退出码 2);`Stop` 校验"全量测试已执行且失败数为 0"。
- 预算:单区步数上限 60,全局 Token 上限按团队默认。
- 验证:八项全过;其中拦截测试逐一实测 3 类危险命令均被阻断。
- 交付:变更集 40 个文件,每文件一句话说明;回滚为 `git revert` 单个合并提交。 4.3. 落地检查清单
设计阶段
- [ ] 控制流图已绘制,状态与转移完整,无孤立状态
- [ ] 终止条件是可检查的断言,不是主观描述
- [ ] 已证明从任一状态存在到终止态的路径
- [ ] 循环有运行时强制的步数硬上限
- [ ] 子智能体切分依据是写分区而非"思考角色"
- [ ] 各写分区互不重叠,交叉部分已识别并设为串行
- [ ] Handoff 契约字段明确:名称、类型、必填、失败语义
- [ ] Handoff 只传结构化产物与约束摘要,不传完整上下文
控制与拦截
- [ ]
PreToolUse已覆盖全部 D 级动作,退出码 2 语义已在团队内统一 - [ ]
PostToolUse已用于结果校验与输出体积裁剪 - [ ]
Stop/SubagentStop已用于完成度与产出质量校验 - [ ]
PreCompact已用于归档关键约束,防止压缩丢失 - [ ]
SessionStart/SessionEnd已用于上下文注入与 Trace 归档 - [ ] 每一类危险动作均有实测通过的拦截记录(非"应该会拦截")
- [ ] 权限按最小授予,子智能体工具集为父级子集
状态与恢复
- [ ] 每个不可逆动作之前有检查点
- [ ] 检查点记录已产生的副作用清单
- [ ] 恢复测试通过:中断—恢复—副作用次数与预期一致(无重复)
- [ ] 会话状态与工件存储分离,工件有版本标识
可观测与度量
- [ ] Trace 完整记录工具调用、文件变更、命令输出摘要
- [ ] Trace 可回放,且已实际回放校验一次
- [ ] 步数 / Token / 时长 / 重试次数均有计量与上限
- [ ] 超限实测会触发中断并升级(非仅配置存在)
- [ ] 循环不收敛有独立检测与告警
合规与评审
- [ ] 未触及权限与安全红线
- [ ] Trace 与审计日志不可被智能体删除或篡改
- [ ] 涉及权限变更的改动已走人工评审并留痕
- [ ] 已对齐 OWASP Agentic AI 与 OWASP Top 10 MCP 的缓解项
- [ ] 变更说明五段齐全,回滚方案可执行且不依赖智能体
5. 总结
Agents 方向回答的是一个看似简单、实则决定成败的问题:当一个模型被赋予行动能力之后,谁来控制它?
本方向的核心结论有三点:
- 瓶颈在 L3 编排与控制层,不在模型能力层。Terminal-Bench 2.0 上最好的公开成绩(GPT-5.2,54.0%,2025-12-11)意味着近半数长时程任务仍然失败。失败的原因大多不是"想不出办法",而是规划失效、止损失效、不可逆操作前没有停下。
- 约束必须是机制而非提示。把安全边界写进提示词,等于把安全交给模型的记忆与意愿。事件钩子(Hooks)+ 阻断型退出码(退出码 2)把"不行"从语言请求变成系统事实,这是第三代 Harness 最关键的工程进展。
- 多智能体的价值在隔离而非集思。并行的前提是写分区互斥;协作的前提是 Handoff 契约显式;恢复的前提是检查点记录副作用。缺了这三者,"多智能体"只会把错误并行化。
对落地团队的建议是:先补控制面,再谈能力面。在终止条件、拦截钩子、检查点三件事做完之前,任何关于"我们的智能体有多强"的判断都是不可信的。
信息缺口声明
- 事件钩子的完整配置选项清单(含选项名称、取值与默认值)在本文撰写时未能逐条核实,官方文档表述为一组配置项;具体数值以所用产品的官方文档为准。本文仅给出事件表与退出码语义等已核实部分。
- Terminal-Bench 2.0 的完整榜单数字与细分项得分标注为 。
- 案例 3.2 中的厂商实践数字为自评口径,缺乏第三方复现;引用时须标注"自评"属性,不得与实测数据混用。
- 本方向的部分企业案例细节与来源 URL 待检索报告补充后回填。
6. 参考资料
- Claude Code 文档 · Hooks(事件表与退出码语义) — Anthropic。https://docs.claude.com/en/docs/claude-code/hooks
- Claude Code 文档 · Sub-agents — Anthropic。https://docs.claude.com/en/docs/claude-code/sub-agents
- Claude Code 文档 · Memory(CLAUDE.md 配置位置与 @import) — Anthropic。https://docs.claude.com/en/docs/claude-code/memory
- AGENTS.md 官方站点 — Linux Foundation / Agentic AI Foundation,2025-12-09。https://agents.md/
- Model Context Protocol 官方规范 — Anthropic 等。https://modelcontextprotocol.io/
- Terminal-Bench 官方榜单 — Laude Institute 等。https://www.tbench.ai/
- OWASP Agentic AI 威胁与缓解(T&C,2025-12-09;V1.0,2026-03-16) — OWASP。https://genai.owasp.org/
- OWASP Top 10 for MCP — OWASP,2025-12-07。https://genai.owasp.org/resource/agentic-ai-top-10/
- OWASP Top 10 for LLM Applications 2025 — OWASP,2025-11-10。https://owasp.org/www-project-top-10-for-large-language-model-applications/
- ISO/IEC 42001:2023 人工智能管理体系 — ISO/IEC,2023。https://www.iso.org/standard/42001
- DORA 2025 State of AI-assisted Software Development — Google Cloud / DORA,2025-11-12。https://dora.dev/research/2025/dora-report/
- Anthropic 工程博客 · 构建有效的智能体(Building effective agents) — Anthropic。https://www.anthropic.com/research/building-effective-agents
Agents (Agent Engineering)
1. Introduction
1.1. Background: From "a model that chats" to "a set of orchestrated execution units"
Around 2023, the dominant industry form was "one model + one prompt." This form performs well in a single conversation, but once a task requires multi-step execution, calling external systems, interrupting and resuming, or multi-person collaboration, it exposes structural flaws: the model does not know "how far it has gotten," and there is no mechanism guaranteeing it "will not overreach."
After 2025, the form changed fundamentally. An agent is no longer another way of describing a prompt, but rather becomes a execution unit running on Harness: it has a clear loop structure (Agent Loop), dispatchable sub-units (Sub-agent), an explicit handoff protocol (Handoff), event hooks (Hooks) that can be intercepted by external systems, and a replayable trace (Trace).
The key significance of this change is that the agent itself has become an object that can be managed through engineering. Just as a process relates to an operating system — a process has a lifecycle, priority, resource quota, and termination signal; agents need the same.
1.2. Definition
Agents direction (Agent Engineering): an engineering field that studies and practices the structure, collaboration, handoff, termination, and control mechanisms of agents themselves. It does not focus on single-generation quality (that is the concern of the Coding and Eval directions), but rather on:
- how an agent's loop starts, advances, and decides to end;
- how multiple agents divide work, pass parameters, and avoid mutual context pollution;
- how external systems deterministically intercept or rewrite an agent's behavior at key nodes;
- how an agent saves state on failure, recovers, and avoids repeating already-completed side effects.
According to the project parameter card, an Agent is a execution unit running on Harness; Harness is the Agent's "chassis." This direction discusses precisely the control plane of this chassis.
1.3. Position within the AI Harness System
图 1-1|Agents 在 Harness 六层体系中的定位
数据来源:基于本文分析绘制的示意图。
This direction spans the six layers of Harness; the primary layer is the L3 Orchestration and Control Layer, with secondary layers of L2 Tools and Execution Layer and L6 Governance and Security Layer.
| Harness Layer | Responsibility of This Direction | Specific Form |
|---|---|---|
| L1 Context Engineering | Secondary | Determines what each sub-agent "sees": context isolation strategy, shared summaries, nearest-first instruction files |
| L2 Tools and Execution | Secondary | Determines what sub-agents "can do": tool-set partitioning, side-effect grading, sandbox boundary |
| L3 Orchestration and Control | Primary | Agent Loop, Plan-and-Execute, Sub-agent dispatch and Handoff, event hooks, interruption and recovery |
| L4 Memory and State | Participates | Checkpoint, session state, artifacts produced by sub-agents |
| L5 Evaluation and Observability | Participates | Trace collection, step/cost metrics, loop non-convergence detection |
| L6 Governance and Security | Secondary | Permission grading, hard interception of destructive operations, budget guardrails, audit trail |
1.4. Bottleneck Layer
The bottleneck of this direction is not in model capability, but in the L3 Orchestration and Control Layer, manifesting as three structural problems:
- Loop non-convergence. When an agent lacks a clear termination decision, it oscillates between "try again" and "try another approach," consuming the entire budget with no substantive progress. DORA 2025 (2025-11-12) shows that 30% of AI tasks take more than 4 hours per run — this figure indirectly reflects the absence of control mechanisms in long-horizon tasks.
- Mutual context pollution. When multiple sub-agents share the same context, the intermediate process of any unit (mistaken attempts, discarded plans) pollutes the judgment of other units; full isolation in turn causes shared constraints to be lost.
- Control depends on the model's self-awareness. Writing "do not delete files" and "do not force push" into the prompt amounts to building the security boundary on the model's memory and will. This is unreliable: constraints must be deterministic and executable by external systems.
The solution to the third difficulty is precisely the most important engineering progress of this direction in recent years: use event hooks (Hooks) to turn control from "a prompt" into "a mechanism".
1.5. Value
- Converge uncertainty into an enumerable state machine. The agent's behavior space changes from "infinite" to "finite states + finite transitions" — the precondition for testability and auditability.
- Make the security boundary executable. Constraints that rely on prompts are suggestions; constraints that rely on hooks are rules.
- Make failures recoverable. For an agent with checkpoints, failure loses time, not the entire progress.
- Make collaboration a division of labor. The value of multi-agent is not "many models thinking together," but parallelism + isolation + aggregation — cutting a large task into non-interfering write partitions, then merging the results once each is complete.
2. Glossary
| Term | English / Abbreviation | Definition |
|---|---|---|
| Agent | Agent | An execution unit running on Harness; has a loop structure, tool-calling capability, and a termination condition |
| Agent Loop | Agent Loop | The iterative structure of "observe—think—act—observe", the basic running form of an agent |
| Sub-agent | Sub-agent | A subordinate execution unit dispatched by a parent agent, usually with an independent context window and a tool subset |
| Handoff | Handoff | A protocol action in which one agent explicitly transfers a task (together with state and outputs) to another agent |
| Multi-Agent System | Multi-Agent System / MAS | A system composed of multiple agents that collaborate via messages or shared state |
| Orchestrator | Orchestrator | A control component responsible for task decomposition, dispatch, aggregation, and termination decisions |
| Event Hooks | Hooks | External scripts or policies triggered at deterministic nodes in an agent's lifecycle, used to deterministically intercept or rewrite behavior |
| Pre-tool-use hook | PreToolUse | An event triggered before a tool is actually executed, usable to block, rewrite input, or auto-authorize |
| Post-tool-use hook | PostToolUse | An event triggered after a tool executes, usable to validate results, inject context, or trigger follow-up actions |
| Termination hook | Stop / SubagentStop | An event triggered when an agent (or sub-agent) is about to end, usable to prevent ending and require continued work |
| Pre-compaction hook | PreCompact | An event triggered before context compaction occurs, usable to archive critical information |
| Blocking Exit Code | Blocking Exit Code | A convention meaning that when a hook ends with a specific exit code (e.g., exit code 2), it "blocks this action and returns feedback to the model" |
| Tool Contract | Tool Contract | A machine-readable declaration of a tool: name, parameter schema, side-effect level, idempotency, timeout, output-size limit |
| Idempotency | Idempotency | Repeating the same operation multiple times has the same effect as performing it once; the precondition of retry safety |
| Checkpoint / Resume | Checkpoint / Resume | Saving running state at key nodes so that an interruption can resume from the breakpoint rather than start over |
| Context Isolation | Context Isolation | A strategy in which sub-agents do not share the full context, passing only necessary information through explicit contracts |
| Termination Condition | Termination Condition | A clear, checkable condition by which an agent decides "the task is complete and can stop" |
| Budget Guardrail | Budget Guardrail | A hard upper limit on steps, tokens, call count, and duration; exceeding it interrupts and escalates |
| Model Context Protocol | Model Context Protocol / MCP | An open connection protocol between agents and external tools/data sources; one of the de-facto standards of the L2 layer |
| Trace | Trace | A structured record of an agent's entire process; the raw material for evaluation, review, and audit |
| Non-convergence | Non-convergence | A failure state in which an agent keeps iterating within budget without substantive progress |
| Write Partition | Write Partition | A mutually exclusive write scope divided by file or module when multiple agents run in parallel, used to avoid concurrent write conflicts |
3. Case Studies
Note: The following cases are compiled from verifiable primary public sources. The effect figures in the cases follow the stated figures of their sources; when citing, the evaluation date and configuration must be noted together.
3.1. Case 1: Multi-agent orchestration driven by event hooks
Source: Anthropic, Claude Code official documentation (Hooks section), https://docs.claude.com/en/docs/claude-code/hooks
3.1.1. Background
Early agent products wrote security and process constraints into system prompts. Engineering practice exposed three kinds of problems: constraints are squeezed out by context compaction in long tasks; the model rationalizes out-of-bounds behavior under "pressure to complete the task"; and the same kinds of constraints must be repeatedly written at multiple entry points, leading to clause drift.
3.1.2. Approach
Move the control points from "within the prompt" to "on lifecycle events", forming a deterministic event—policy table. The core design is as follows:
Table 3-1 Agent lifecycle event table (nine types of events)
| Event | Trigger Timing | Typical Use | Can Block |
|---|---|---|---|
SessionStart | At session start | Load project context, inject environment description, initialize budget counting | No (can inject context) |
UserPromptSubmit | When the user submits a prompt | Input validation, sensitive-information filtering, task classification and routing | Yes |
PreToolUse | Before a tool call | Permission interception, parameter rewriting, dangerous-command rejection, auto-authorizing low-risk tools | Yes (core control point) |
PostToolUse | After a tool call | Result validation, output-size trimming, triggering follow-up actions, recording evidence | Yes (can attach feedback) |
Notification | When the system sends a notification | Custom reminders while waiting for human input, external-system integration | No |
SubagentStop | When a sub-agent is about to end | Validate whether the sub-agent's output is qualified; if not, require it to continue | Yes (can prevent ending) |
Stop | When the main agent is about to end | Validate completeness (e.g., whether tests were run); if not complete, require continuing | Yes (can prevent ending) |
PreCompact | Before context compaction | Archive key decisions and constraints to prevent loss during compaction | No (can inject context) |
SessionEnd | At session end | Archive the Trace, generate a task summary, clean up temporary state | No |
Table 3-2 Hook exit-code semantics (typical convention)
| Exit Code | Semantics | The Agent's Subsequent Behavior |
|---|---|---|
| 0 | Success, no additional information | Continue normally; standard output is visible to the user in some modes |
| 2 | Block | The current action is blocked; standard error is returned to the model, and the model adjusts its behavior accordingly |
| Other non-zero | Non-blocking error | The action continues; the error is for logging and observability only |
The semantics of exit code 2 are a key design of this direction: it turns "no" from a request at the language level into a fact at the system level. The model can try again, but it cannot bypass it.
Table 3-3 Priority and the nearest-first principle
The priority of instructions and control policies, from highest to lowest, is:
| Priority | Source | Description |
|---|---|---|
| 1 (highest) | Explicit user instruction | Instructions given directly in the session override all configuration |
| 2 | Nearest/subdirectory instruction file | The instruction closest to the operated object takes priority |
| 3 | Project-level instruction file | Conventions in the project root directory |
| 4 | User-level global instruction | Personal preferences, effective only when not conflicting with project conventions |
| 5 (lowest) | Enterprise-level managed policy | Organization-level baseline; can be overridden by upper layers but is usually set as non-overridable |
3.1.3. Results
- Safety constraints change from "a prompt" to "a mechanism": interception of dangerous commands no longer relies on the model's memory, but is deterministically blocked by hooks before a tool executes.
- Constraints no longer get lost in long tasks: the
PreCompactevent archives key clauses before compaction;SessionStartre-injects them at each session. - Completeness can be forcibly validated: the
Stophook can check "whether tests ran" and "whether evidence is complete", blocking the end if unsatisfied. - This pattern has been adopted by several agent products and has become one of the hallmark features of the third-generation Harness (the runtime and evaluation era).
3.2. Case 2: In-enterprise multi-agent R&D pipeline
Source: Alibaba Group public technical practice (2025-09); Tencent CodeBuddy public practice (2025-08)
3.2.1. Background
The pain point of large R&D organizations is not "whether code can be generated", but consistency across repositories, languages, and teams: a single requirement often touches frontend, backend, configuration, and tests at the same time; a single-point agent struggles to cover it all, and the generated results must satisfy the organization's framework conventions, naming standards, and security baseline.
3.2.2. Approach
A layered structure of "orchestrator + dedicated sub-agents" is adopted:
- Orchestrator: responsible for requirement decomposition, task dispatch, dependency sorting, and result aggregation; it does not write business code itself.
- Dedicated sub-agents: partitioned by responsibility (requirements analysis, coding, test generation, code review, documentation); each type of sub-agent has an independent context window and a minimized tool subset.
- Write partitions: parallel sub-agents divide mutually exclusive write ranges by module, prohibiting concurrent writes to the same file.
- Handoff contracts: sub-agents do not share the full context, passing only structured artifacts (change lists, interface signatures, test results) and constraint summaries.
- Organization-convention injection: framework conventions, naming standards, and security baseline are injected into each layer through layered instruction files, with nearest-first overriding.
- Human confirmation points moved forward: confirm the decomposition plan and blast radius before dispatch, rather than reviewing only after everything is complete.
3.2.3. Results
Among the public quantitative results, Tencent CodeBuddy's practice (2025-08) shows Code Review time reduced by 80%+. Alibaba's internal practice published in 2025-09 likewise points to "R&D-process-level integration" rather than "single-point efficiency gains".
It must be emphasized that the above figures are the vendors' self-reported figures. When deploying in an enterprise, internal metrics should be established (see 05-eval.md), and conclusions should be based on end-to-end metrics rather than per-stage timings — because a speedup in one stage may be offset by increased cost in downstream stages (see the "self-report vs. measurement divergence" discussion in 3.3 and 05-eval).
3.3. Case 3: The capability boundary of agents for long-horizon terminal tasks
Source: Terminal-Bench 2.0 official leaderboard, https://www.tbench.ai/
3.3.1. Background
Terminal-Bench is a class of agent benchmark oriented toward long-horizon terminal-operation tasks: the agent must complete tasks such as system configuration, troubleshooting, and environment setup in a real terminal environment through dozens to hundreds of commands. Unlike "writing code", each step of such tasks may change the system state and is irreversible.
3.3.2. Approach (evaluation design perspective)
Terminal-Bench 2.0's design reflects three key control requirements of this direction:
- Step and time budget: tasks complete within a limited number of steps, examining the agent's planning efficiency rather than its exhaustive capability.
- Determinable state: each task has a clear pass/fail decision (usually a set of assertion scripts), avoiding subjective scoring.
- Environment isolation: each round runs in a clean environment, preventing the previous round's state from polluting the next — precisely the engineering requirement that "agent side effects must be isolatable".
3.3.3. Results
| Model | Score | Evaluation Date | Notes |
|---|---|---|---|
| Claude Sonnet 4.5 | 51.0% | 2025-09-29 | First score above 50% on this leaderboard |
| GPT-5.2 | 54.0% | 2025-12-11 | Later update |
Interpretation: Even at the best public result, nearly half of the long-horizon terminal tasks still fail. This shows that the bottleneck of this direction is indeed not "whether the model is smart enough", but the control mechanism — how to plan, how to stop losses, and how to stop before an irreversible operation. The full leaderboard figures and finer-grained sub-scores of Terminal-Bench 2.0 are marked as [To be verified].
4. Practice Standards
4.1. AGENTS.md Specifications
The following is the complete AGENTS.md text for this direction, placed in a code block for direct copying. When using it, the common clauses of the group-level AGENTS.md must be applied on top; when conflicts arise, resolve them by the nearest-first principle.
# AGENTS.md —— 软件工程 · Agents 方向(智能体工程化)
## 角色与边界
- 本文件约束**构建与运行智能体系统**的工作:Agent Loop 设计、Sub-agent 定义、Handoff 协议、Hooks 配置、编排器实现、智能体运行时改造。
- 允许自行完成:设计循环结构、定义子智能体契约、配置事件钩子、实现终止条件、编写 Handoff 数据结构、构造 Trace 采集点、设置预算护栏。
- 禁止自行完成:为智能体授予共享状态写权限(S 级)或破坏性权限(D 级)、关闭或绕过已有的拦截钩子、修改审计配置、删除 Trace。
- 边界判定:凡改变**智能体可执行动作集合**的改动,一律视为安全相关变更,须走人工评审。
## 环境假设
- 提供智能体运行时(Agent Runtime),支持:循环控制、子智能体派发、事件钩子注册、检查点保存与恢复。
- 提供容器或微虚机沙箱,智能体的一切命令执行均在沙箱内完成。
- 提供 Trace 采集与存储,保证全过程可回放。
- 提供成本与步数计量,且支持设置硬上限。
- 提供工具注册中心,每个工具有机器可读的副作用分级声明。
- 缺失任一项时,降级执行并在任务开始时声明缺失项与风险。
## 上下文加载顺序(Context Budget)
1. 任务契约:目标、产出物、验收标准(固定,不压缩)
2. 就近指令文件:当前目录及其祖先链
3. 运行时现状清单:已有的子智能体定义、钩子配置、工具注册表
4. 相关实现源码:循环、派发、钩子处理逻辑
5. 测试与仿真:智能体行为的测试用例与仿真脚本
6. 历史事故记录:循环不收敛、越权、上下文污染事件
7. 工具结果:按需追加
每一步记入 Token 预算表;超限执行压缩而非截断,压缩前须经 PreCompact 归档关键约束。
## 工具契约
- 所有工具必须有声明:名称、参数模式、副作用级别(R/W/X/S/D)、幂等性、超时、输出体积上限。无声明工具不得注册。
- 子智能体的工具集必须是父级工具集的**子集**,遵循最小权限。
- S 级与 D 级工具默认不在任何子智能体中启用;确需时须在契约中逐项列出并说明必要性。
- 所有执行类工具必须设置超时;超时即失败,进入失败处理流程。
- 输出超过约定行数时必须截断并给出定位信息(路径 + 行号区间)。
## 任务执行流程(SOP)
1. 解析任务契约,明确产出物与验收标准;契约缺失则停止并澄清。
2. 绘制控制流图:状态、转移、终止条件、异常处理分支。
3. 确定子智能体切分方案与写分区边界。
4. 定义 Handoff 契约:传递字段、类型、必填性、失败语义。
5. 设计事件钩子表:事件、触发条件、判定逻辑、退出码语义。
6. 设定预算护栏:步数上限、Token 上限、时长上限、重试上限。
7. 实现后用仿真脚本验证控制流(含终止条件可达性测试)。
8. 输出配置与说明,进入人工评审。
## 验证与证据要求
必须通过以下验证并留存证据:
| 验证项 | 判定方式 | 证据 |
|---|---|---|
| 终止条件可达 | 遍历状态图,存在从任一状态到终止态的路径 | 状态图 + 可达性分析结论 |
| 循环有界 | 步数上限存在且可被运行时强制执行 | 配置 + 超限触发测试记录 |
| 上下文隔离有效 | 子智能体之间不共享完整上下文 | 隔离测试:一个子单元注入噪声,另一单元不受影响 |
| 拦截确定 | 危险动作被钩子阻断,模型无法绕过 | 拦截测试:每种 D 级动作至少一次实测拦截 |
| 检查点可恢复 | 中断后从检查点恢复,不重复已完成副作用 | 恢复测试:中断—恢复—比对副作用次数 |
| Trace 完整 | 全过程工具调用可回放 | Trace 样本 + 回放校验 |
| 预算生效 | 超限时中断并升级 | 超限测试记录 |
| 并行无写冲突 | 并发子智能体不写同一文件 | 并发测试记录 |
禁止以"逻辑上应该没问题"作为验证结论;禁止用修改断言的方式让验证通过。
## 失败与升级策略
| 失败 | 处理 |
|---|---|
| 循环不收敛(步数超预算且无进展) | 强制终止,保存检查点,输出进展与卡点,上报 |
| 越权被拦截 | 不得绕过;记录意图与命令,转入人工升级 |
| 子智能体产出不合格 | 由 SubagentStop 钩子判定为不合格并要求继续;超过重试上限则终止并上报 |
| 恢复后副作用重复 | 判定检查点设计缺陷,回滚并修复;禁止以去重脚本掩盖 |
| 契约冲突(Handoff 字段不一致) | 停止派发,上报冲突点 |
升级三要素:已尝试动作与结果、卡点现象与证据、建议选项及风险。缺一无效。
## 安全与合规红线
1. 禁止为智能体授予 D 级(破坏性/不可逆)权限;确需时须逐命令人工确认并留痕。
2. 禁止关闭、绕过、或降低已有拦截钩子的严格程度;钩子变更须走安全评审。
3. 禁止子智能体继承父级全部权限;权限必须显式最小化授予。
4. 禁止删除、篡改、压缩 Trace 与审计日志。
5. 禁止在指令文件、配置、日志中写入密钥、Token 与个人信息。
6. 遵循 OWASP Agentic AI 威胁与缓解清单(T&C,2025-12-09;V1.0,2026-03-16),重点防范目标劫持、工具滥用、身份与权限混淆、记忆投毒。
7. 遵循 OWASP Top 10 MCP(2025-12-07),对工具服务端做来源审查与权限最小化。
8. 组织级落地对齐 ISO/IEC 42001:2023 的角色职责与成文信息要求。
## 禁止事项
1. 禁止把安全约束只写在提示词里而不用钩子做硬拦截。
2. 禁止设计无终止条件的循环。
3. 禁止让多个子智能体并发写同一文件而不做写分区。
4. 禁止在检查点中遗漏工具副作用记录。
5. 禁止一次性请求过宽权限。
6. 禁止以"模型认为"作为技术判断依据。
7. 禁止使用 `[待填写]`、`XX`、`___` 之外的非标准占位符;不确定处统一使用 `[待填写]`。
## 输出格式
- 控制流图(状态与转移的文字化描述或图)
- 子智能体清单:名称、职责、工具子集、上下文范围、写分区
- Handoff 契约:字段名、类型、必填、失败语义
- 事件钩子表:事件、触发条件、判定逻辑、退出码语义
- 预算配置:步数、Token、时长、重试上限
- 验证记录:八项验证的逐项结果
- 变更说明五段:改了什么 / 为什么 / 如何验证 / 风险 / 如何回滚
## 评估与自检
| 自检项 | 判定 |
|---|---|
| 终止条件是否明确且可达 | 是 / 否 |
| 循环是否有硬边界 | 是 / 否 |
| 子智能体上下文是否隔离 | 是 / 否 |
| 危险动作是否由钩子硬拦截 | 是 / 否 |
| 检查点是否可恢复且不重复副作用 | 是 / 否 |
| Trace 是否完整可回放 | 是 / 否 |
| 预算护栏是否生效 | 是 / 否 |
| 并行写分区是否互斥 | 是 / 否 |
任一"否"须显式列出;自检不通过即任务未完成。 4.2. SKILL.md Specifications
---
name: multi-agent-orchestration-setup
description: 设计与落地一套多智能体编排系统:拆解任务、切分子智能体与写分区、定义 Handoff 契约、配置事件钩子与退出码语义、设定预算护栏与终止条件,并通过八项控制流验证。当需要让多个智能体协作完成一项工程任务,或为既有智能体系统补足控制面时使用。
version: 1.0
created: 2026-09-12
---
# 多智能体编排系统搭建
## 适用场景
- 单个智能体无法在预算内完成的大任务,需要拆解与并行。
- 任务可按模块/文件/职责切分,且各部分的写入范围互不重叠。
- 需要为既有智能体系统补足控制面:终止条件、拦截钩子、检查点、预算护栏。
- 需要把"不要做某事"从提示词升级为确定性机制。
不适用于:单步任务、无法切分的整体性创作、无判定标准的开放式探索。
## 前置条件
| 类别 | 要求 | 缺失时处置 |
|---|---|---|
| 任务契约 | 目标、产出物、验收标准明确 | 停止,先补全契约 |
| 运行时 | 支持子智能体派发与事件钩子注册 | 降级为单智能体 + 外部脚本控制 |
| 沙箱 | 命令执行在容器或微虚机内 | 禁止执行,升级 |
| 工具注册 | 工具有副作用分级声明 | 先补齐声明 |
| Trace | 工具调用与文件变更可完整记录 | 降级执行并声明"不可回放" |
| 计量 | 步数/Token/时长可设上限 | 设定保守默认上限 |
## 输入
- 任务描述与验收标准
- 仓库或系统的模块边界
- 可用工具清单及其副作用分级
- 预算上限(步数 / Token / 时长)
- 现有智能体与钩子配置(如为改造任务)
## 输出
- 控制流图(状态、转移、终止条件、异常分支)
- 子智能体清单(职责、工具子集、上下文范围、写分区)
- Handoff 契约(字段、类型、必填、失败语义)
- 事件钩子表(事件、触发条件、判定逻辑、退出码语义)
- 预算与护栏配置
- 八项控制流验证记录
- 五段式变更说明
## 执行步骤
1. **拆解**:按写分区而非按"思考角色"切分任务。判断标准是"两部分的写入范围是否重叠"——重叠则不得并行。
2. **定义子智能体**:为每个分区设定职责、工具子集(父级子集)、上下文范围(仅含本分区必要信息)。
3. **设计 Handoff 契约**:只传结构化产物与约束摘要,不传完整上下文。字段须有类型与失败语义。
4. **配置事件钩子**:至少覆盖 `PreToolUse`(拦截)、`PostToolUse`(校验)、`Stop`(完成度)、`SubagentStop`(子单元质量)。明确退出码 2 为阻断语义。
5. **设定终止条件**:必须写成可检查的断言(如"测试命令退出码为 0 且失败数为 0"),不得写成"任务看起来完成了"。
6. **设定预算护栏**:步数、Token、时长、重试上限,且由运行时强制执行。
7. **设计检查点**:在每个不可逆动作之前保存,检查点须记录已产生的副作用清单。
8. **仿真验证**:用脚本跑通八项验证(终止可达、循环有界、隔离有效、拦截确定、恢复无重复、Trace 完整、预算生效、并行无冲突)。
9. **交付**:输出配置、说明与验证记录,进入人工评审。
## 质量标准(DoD)
1. 终止条件明确、可检查、可达。
2. 循环存在运行时强制的硬边界,超限即中断。
3. 子智能体上下文隔离,且工具集为父级子集。
4. 每一类 D 级动作都有实测通过的拦截记录。
5. 检查点可恢复,恢复后不重复任何已完成的副作用。
6. Trace 完整且可回放。
7. 并行写分区互斥,无并发写同一文件。
8. 预算护栏在实测中确实触发中断。
9. 未触及权限与安全红线。
10. 变更说明五段齐全,回滚方案不依赖智能体继续参与。
## 常见失败与处理
| 失败 | 表现 | 处理 |
|---|---|---|
| 循环不收敛 | 步数耗尽无实质进展 | 强制终止 + 保存检查点 + 上报卡点 |
| 上下文污染 | 子单元引入无关信息影响判断 | 收紧 Handoff 字段,只传结构化产物 |
| 越权尝试 | 试图执行 D 级操作 | 不得绕过;记录并升级 |
| 拦截失效 | 钩子未触发或被绕过 | 判定为阻断性缺陷,回滚 |
| 恢复后重复副作用 | 非幂等动作被重放 | 修复检查点记录,禁止用去重脚本掩盖 |
| 写冲突 | 两子单元改同一文件 | 重新划分写分区或改为串行 |
| 终止条件不可达 | 断言永远为假 | 修正断言,或增加"最大努力后上报"的兜底分支 |
## 示例
**场景**:为一个 12 万行的单体仓库做"模块 A 的接口迁移",涉及 40 个调用点。
- 切分:按目录划分 5 个写分区,每区 8 个调用点;交叉引用点单独列为串行区。
- 子智能体:5 个迁移单元(工具集 = 读文件 + 编辑 + 构建/测试,无 git push),1 个汇总单元。
- Handoff:传 `{file, oldSymbol, newSymbol, verified: bool, testCmd, exitCode}`。
- 钩子:`PreToolUse` 拦截任何 `git push` / `rm -rf` / `git checkout --`(退出码 2);`Stop` 校验"全量测试已执行且失败数为 0"。
- 预算:单区步数上限 60,全局 Token 上限按团队默认。
- 验证:八项全过;其中拦截测试逐一实测 3 类危险命令均被阻断。
- 交付:变更集 40 个文件,每文件一句话说明;回滚为 `git revert` 单个合并提交。 4.3. Landing Checklist
Design Phase
- [ ] Control-flow diagram has been drawn; states and transitions are complete, with no isolated states
- [ ] The termination condition is a checkable assertion, not a subjective description
- [ ] A path from any state to a termination state has been proven to exist
- [ ] The loop has a runtime-enforced hard step cap
- [ ] Sub-agent partitioning is based on write partitions rather than "thinking roles"
- [ ] Write partitions do not overlap; intersecting parts have been identified and set as serial
- [ ] Handoff contract fields are clear: name, type, required/optional, failure semantics
- [ ] Handoff passes only structured artifacts and constraint summaries, not the full context
Control and Interception
- [ ]
PreToolUsecovers all D-level actions, and the exit-code-2 semantics are unified across the team - [ ]
PostToolUseis used for result validation and output-size trimming - [ ]
Stop/SubagentStopare used for completeness and output-quality validation - [ ]
PreCompactis used to archive key constraints and prevent loss during compaction - [ ]
SessionStart/SessionEndare used for context injection and Trace archiving - [ ] Every kind of dangerous action has a verified-passing interception record (not "it should intercept")
- [ ] Permissions are granted on a least-privilege basis; sub-agent tool sets are subsets of the parent
State and Recovery
- [ ] There is a checkpoint before every irreversible action
- [ ] Checkpoints record the list of side effects already produced
- [ ] Recovery test passes: after interruption—recovery, the side-effect count matches expectations (no duplicates)
- [ ] Session state and artifact storage are separated; artifacts carry version identifiers
Observability and Metrics
- [ ] Trace fully records tool calls, file changes, and command-output summaries
- [ ] Trace is replayable and has actually been replayed and validated once
- [ ] Steps / tokens / time / retry counts are all metered and capped
- [ ] Exceeding the limit is actually tested to trigger interruption and escalation (not merely that the configuration exists)
- [ ] Loop non-convergence has independent detection and alerting
Compliance and Review
- [ ] No permission or security red lines have been crossed
- [ ] Trace and audit logs cannot be deleted or tampered with by agents
- [ ] Changes involving permission changes have gone through human review with an audit trail
- [ ] Mitigations from OWASP Agentic AI and OWASP Top 10 MCP have been aligned
- [ ] The five-part change description is complete, and the rollback plan is executable without depending on the agent
5. Summary
The Agents direction answers a seemingly simple yet decisive question: once a model is given the ability to act, who controls it?
This direction has three core conclusions:
- The bottleneck lies in the L3 Orchestration and Control Layer, not the model capability layer. The best public score on Terminal-Bench 2.0 (GPT-5.2, 54.0%, 2025-12-11) means that nearly half of long-horizon tasks still fail. Most failures are not because "no approach could be found", but because planning failed, loss-stopping failed, or it did not stop before an irreversible operation.
- Constraints must be mechanisms, not prompts. Writing the security boundary into a prompt means entrusting security to the model's memory and will. Event hooks (Hooks) + blocking exit codes (exit code 2) turn "no" from a language request into a system fact; this is the most critical engineering progress of the third-generation Harness.
- The value of multi-agent lies in isolation, not brainstorming. The premise of parallelism is mutually exclusive write partitions; the premise of collaboration is explicit Handoff contracts; the premise of recovery is checkpoints recording side effects. Without these three, "multi-agent" only parallelizes errors.
The recommendation for teams deploying this is: build the control plane first, then talk about the capability plane. Until the three things — termination conditions, interception hooks, and checkpoints — are done, any judgment about "how powerful our agent is" is unreliable.
Information Gap Declaration
- The complete configuration-option list for event hooks (including option names, values, and defaults) could not be verified item by item at the time of writing; the official documentation describes them as a set of configuration items. The specific values follow the official documentation of the product in use. This document only provides the already-verified parts such as the event table and exit-code semantics.
- The full leaderboard figures and sub-score details of Terminal-Bench 2.0 are marked as
[To be verified]. - The vendor practice figures in Case 3.2 are self-reported and lack third-party reproduction; when citing, the "self-reported" attribute must be noted and they must not be mixed with measured data.
- Some enterprise-case details and source URLs of this direction await backfilling after the retrieval report is supplemented.
6. References
- Claude Code Docs · Hooks (event table and exit-code semantics) — Anthropic. https://docs.claude.com/en/docs/claude-code/hooks
- Claude Code Docs · Sub-agents — Anthropic. https://docs.claude.com/en/docs/claude-code/sub-agents
- Claude Code Docs · Memory (CLAUDE.md configuration location and @import) — Anthropic. https://docs.claude.com/en/docs/claude-code/memory
- AGENTS.md official site — Linux Foundation / Agentic AI Foundation, 2025-12-09. https://agents.md/
- Model Context Protocol official specification — Anthropic and others. https://modelcontextprotocol.io/
- Terminal-Bench official leaderboard — Laude Institute and others. https://www.tbench.ai/
- OWASP Agentic AI Threats and Mitigations (T&C, 2025-12-09; V1.0, 2026-03-16) — OWASP. https://genai.owasp.org/
- OWASP Top 10 for MCP — OWASP, 2025-12-07. https://genai.owasp.org/resource/agentic-ai-top-10/
- OWASP Top 10 for LLM Applications 2025 — OWASP, 2025-11-10. https://owasp.org/www-project-top-10-for-large-language-model-applications/
- ISO/IEC 42001:2023 AI management systems — ISO/IEC, 2023. https://www.iso.org/standard/42001
- DORA 2025 State of AI-assisted Software Development — Google Cloud / DORA, 2025-11-12. https://dora.dev/research/2025/dora-report/
- Anthropic Engineering Blog · Building effective agents — Anthropic. https://www.anthropic.com/research/building-effective-agents