K Agent AtlasKimi Code · Systems
05 · Loop、Planning、Policy 与 Verification

Part 05

Loop、Planning、Policy 与 Verification

让概率决策成为稳定、可停止、可证明的闭环。

2,881 行约 113 分钟研究基线 2026-08-03

Agent Loop、Planning、Policy 与 Verification:闭环控制深潜

定位:这是 Coding Agent 控制面的系统参考,不是 prompt 技巧合集,也不是项目教程。它回答一个核心问题:怎样让概率性的模型,在部分可观测、工具有副作用、环境不断变化的真实软件系统里,持续朝可验证目标前进,同时保持安全、可停止、可恢复和可审计。

在线复核截止:2026-08-03 17:14(Asia/Shanghai)。 Kimi 的 Loop/Plan 主体分析固定到不可变快照 29c9e2ab20a1646ad33f2b7c999b450152f9c01a;同日 freshness ledger 继续追踪至公开 main75395f6。论文状态、产品 contract 与源码事实分别标注;未来 main 变化不自动改变固定快照结论。

证据标签

时间敏感的判断使用以下标签;没有标签的算法、控制论与工程设计内容,是本文的架构综合,不冒充某篇论文或某个产品的既成实现。

标签 含义 可支持的结论
[SRC] 固定 commit 的公开源码或正式规范 该快照中可直接确认的实现事实
[OFFICIAL] 厂商官方工程/安全/产品材料 该厂商公开描述的行为;不是跨产品通则,也不是独立评测
[PEER] 已正式发表或录用的同行评议材料 其任务与实验范围内的研究证据
[PREPRINT] arXiv/OpenReview 预印本或未确认录用稿 研究信号;必须保留样本、设置和复现限制
[INFERENCE] 从多个事实推导的架构判断 可讨论的解释,不是源码作者或论文作者的明示结论
[OPEN] 存在争议或尚无充分证据 不能在面试中陈述成行业定论

Freshness 复核还确认:e22479a → 29c9e2a 期间,本章涉及的 loop/plan 控制路径主要是错误类型规范化,并补入 first-class plan domain;29c9e2a → 75395f6 又新增 TurnStartedUserPromptQueuedTaskStarted 与按需 SessionHeartbeat 等外部 lifecycle hook,核心 loop admission/continuation 语义未因此改写。正文永久链接固定在已逐路径审阅的 29c9e2a,新增 hook contract 单独记账。


0. 先给结论

  1. Agent Loop 不是 while (true),而是一个带状态估计、准入、授权、执行回执、验证、恢复和终止语义的闭环控制器。 模型只是候选动作生成器,不应同时拥有全部控制权。
  2. “会 planning”不是先输出一份长清单。 真正的 planning 是维护一个可被新证据修正的任务模型:目标、约束、未知项、依赖、风险、验收条件和当前证据。
  3. Goal、spec、subgoal、task、plan 不是同义词。 Goal 说明要改变什么;spec 说明什么结果才被接受;subgoal 是必要中间条件;task 是可分派工作单元;plan 是当前认为可行、随证据变化的路线。
  4. Policy 是动作集合上的硬边界,不是给模型的一段建议。 Prompt 可以引导;policy gate 必须基于已解析的能力、资源、身份、数据来源和 effect,在执行前独立裁决。
  5. 执行成功不等于任务成功。 exit_code=0 只证明某个进程按自己的契约结束;“任务完成”必须由与用户意图尽量一致、且尽量独立于生成器的证据体系支持。
  6. Retry、recover、reconcile、replan、fallback、failover、rollback、escalate 是八种不同动作。 把它们统称为 retry,会造成重复副作用、预算失控和根因不可见。
  7. 停止条件是正确性的一部分。 Agent 既要避免过早宣布完成,也要避免没有新信息的无限循环;成功、阻塞、预算耗尽、风险越界、用户取消和目标被替换必须是不同终态。
  8. Budget 是向量,不是一个 max_steps 至少包括 step、turn、token、wall time、cost、tool attempts、external effects、approval burden 和 verification reserve。
  9. 不确定性不应只显示成一个“置信度”。 要区分目标理解、状态估计、动作结果、验证覆盖和安全风险的不确定性,并把它们转成不同的控制动作。
  10. 闭环稳定的核心不是让模型“更努力”,而是让真实状态、观测、动作、证据和目标持续对齐。 振荡、重复、漂移和“看起来在进展”都是控制系统失稳的表现。

一句压缩定义:

Reliable Agent Control
  = explicit state machine
  + mutable task model
  + independent action policy
  + effect-aware execution
  + externally grounded verification
  + bounded recovery
  + evidence-based stopping

1. 对象论:先把五个最常混淆的概念拆开

1.1 五类对象

对象 精确定义 典型内容 生命周期 谁可修改 失败表现
Goal 希望世界状态发生的方向性变化 “修复登录回归”“解释根因” 可跨 turn/session 用户授权;运行时可暂停/阻塞/完成 目标漂移、伪完成
Spec 对可接受结果的规范性约束 行为、边界、非功能要求、验收标准 相对稳定;修改应有来源 用户或权威 artifact 只完成字面功能,破坏隐含契约
Subgoal 达成 Goal 所需的中间状态谓词 “先复现”“定位首次错误边界” 随证据创建、完成或废弃 planner 错误分解、局部最优
Task 有 owner、输入、输出、状态和验收的可执行工作单元 “检查 auth middleware 的 session 传播” queued → running → verified/failed/... orchestrator/worker 责任不清、重复执行
Plan 当前关于如何从现状到目标的可修正假设 步骤、依赖、分支、风险、验证点 高频修订 planner/controller 过时、僵化、计划崇拜

它们的关系不是“从大到小的一张 todo list”:

User intent
   ├── Goal: desired state change
   └── Spec: admissible outcome set
           ↓ constrains
Belief about current state
           ↓
Planner proposes Subgoals and Tasks
           ↓ arranged as
Plan = current route hypothesis
           ↓ constrained by
Policy = admissible action set
           ↓ checked by
Verification = evidence that state entered the spec's acceptance set

1.2 用状态谓词表达,避免语言上的“差不多”

设真实世界状态为 x,Agent 对它只能形成信念状态 b

  • Goal:希望 G(x) = true
  • Spec:必须同时满足 S₁(x) ∧ S₂(x) ... ∧ Sₙ(x)
  • Subgoal i:中间谓词 gᵢ(x) = true
  • Task j:尝试把状态从 x_t 变为 x_{t+1} 的工作单元;
  • Plan:关于“哪些 task 以什么依赖和顺序能让 G ∧ S 成立”的当前模型;
  • Verification:从观测 o 推断 G ∧ S 是否成立的过程。

这种表达揭示一个关键事实:计划完成不推出目标完成,任务执行成功也不推出 spec 满足。

1.3 Spec 的四层

成熟 Coding Agent 至少要区分:

  1. Intent spec:用户真正想解决的问题;
  2. Behavior spec:可观察行为应该怎样变化;
  3. Change spec:允许修改哪些表面、保持哪些边界;
  4. Evidence spec:什么证据足以宣布完成。

例如“修复按钮没反应”:

Intent      用户能完成提交,不再卡住
Behavior    合法输入提交一次;非法输入给出明确错误
Change      不重写整个表单框架,不改变 API contract
Evidence    复现失败 → 修复后交互测试通过 → 网络请求仅一次 → 回归测试通过

如果只有 change spec,Agent 很容易把“改了代码”误判成“问题解决”。

1.4 Plan 的正确不变量

一个 plan 至少应保持:

  • 每个 active task 指向某个 subgoal 或未知项;
  • 每个 subgoal 指向 Goal/Spec 中的必要条件;
  • 依赖边不能循环,除非显式表示迭代控制;
  • 每个高风险 action 前有 precondition 与 policy decision;
  • 每个完成声明后有 evidence reference;
  • 新证据与旧假设冲突时,计划必须可失效;
  • 被放弃分支保留原因,避免稍后无意识重走。

Plan 的价值是约束搜索和暴露未知,不是让执行器机械服从旧判断。


2. 闭环控制模型:从 OODA 到 Agent Runtime

2.1 为什么必须按控制系统理解

真实 Coding Agent 面对的是部分可观测系统:

  • 仓库内容可能在变化;
  • 测试可能 flaky;
  • 工具输出会被截断;
  • 模型看到的是投影后的 context,不是真实世界全量状态;
  • 一个命令可能执行成功但副作用未落到预期资源;
  • 验证器可能只覆盖 spec 的一部分;
  • 用户可能在执行中改变目标。

用最小形式化表示:

x(t+1) = F(x(t), u(t), w(t))       # 真实环境状态转移,w 是外部扰动
o(t)   = H(x(t), v(t))             # 工具/传感器观测,v 是噪声/截断/延迟
b(t)   = Update(b(t-1), o(t))      # Agent 的信念状态
a*(t)  ~ ModelPolicy(b, goal, plan) # 模型提出候选动作
u(t)   = PolicyGate(a*, identity, provenance, risk)
y(t)   = Verifier(x/o/artifacts)   # 关于完成度的证据信号

模型通常既不知道完整 x,也不直接控制 F;它只能根据 b 生成候选动作。因此最危险的架构错误,是把模型的自然语言判断直接当成世界状态真值。

2.2 Observe–Orient–Decide–Act–Evaluate

OODA 用于 Agent 时还不够,必须显式加上 Evaluate,因为软件任务的完成不能由动作发生本身推出:

阶段 控制问题 产物 典型缺陷
Observe 现在收到了什么原始证据? typed observation、receipt、artifact ref 截断未标记、缓存过期、错误流丢失
Orient 这些证据对目标、约束、未知项意味着什么? belief delta、假设、风险、plan delta 把猜测当事实、目标漂移
Decide 下一动作的信息价值、预期进展、成本和风险是什么? candidate action + rationale metadata 只选“最可能成功”,忽略可证伪性
Act 动作是否被授权,副作用是否可追踪? intent、policy verdict、effect receipt 未知副作用盲重试
Evaluate 实际状态是否改善,哪些 spec 已有证据? verifier result、progress delta、next disposition 自评偏差、只看 test exit code

完整循环不是环上五个 prompt,而是五个责任边界:

flowchart LR O["Observe\nraw evidence"] --> R["Orient\nbelief and task model"] R --> D["Decide\ncandidate action"] D --> P{"Policy gate"} P -->|approve| A["Act\neffectful execution"] P -->|ask| H["Human or authority"] P -->|deny| R H -->|approved| A H -->|rejected or changed| R A --> E["Evaluate\nexternal evidence"] E -->|progress| O E -->|contradiction| R E -->|verified success| C["Complete"] E -->|blocked or exhausted| S["Stop with explicit status"]

2.3 Orient 是最被低估的一层

Observe 不等于把 tool output 拼到 messages;Orient 至少要完成:

  1. provenance 分类:用户、repo、网页、工具、模型推断分别来自哪里;
  2. freshness 判断:证据是当前状态还是旧快照;
  3. contradiction detection:新证据是否推翻已有假设;
  4. information gain:本次动作究竟减少了哪个未知;
  5. causal attribution:变化是候选修复导致,还是环境噪声;
  6. task model update:哪些 task 完成、失效、需要新增;
  7. risk update:新的写入范围、权限或外部 effect 是否出现。

把 Orient 全交给下一轮 LLM 的自由文本,会让“状态更新”不可观测。运行时至少应持久化 typed observations 和 plan/evidence delta;模型如何解释可以变化,但证据不应丢。

2.4 Evaluate 与 Observe 的差别

  • Observe 问:“发生了什么?”
  • Evaluate 问:“这对目标满足度意味着什么?”

例如测试输出 23 passed 是 observation;只有结合:

  • 测试是否覆盖目标行为;
  • 是否跑的是正确 workspace/config;
  • 是否有 skipped/flaky;
  • 是否产生额外回归;
  • 测试是否可被候选 patch 篡改;

才能得到 evaluation。Observation 是事实载荷,evaluation 是基于 verifier contract 的判定。


3. Agent Loop:状态机、事件和伪代码

3.1 三层生命周期

不要把所有东西都叫 step:

层级 含义 典型边界
Goal run 跨多个用户/自动 turn 的持续目标 pause、resume、blocked、complete
Turn 一次用户输入或系统续作触发的工作区间 queued、running、completed、failed、cancelled
Step 一次 context materialization + model inference + tool batch/answer queued、running、completed、failed、cancelled
Tool attempt 单个 tool intent 的一次执行尝试 proposed、authorized、committed、observed、reconciled

这四层应有不同 ID、budget、取消语义和持久化粒度。

3.2 建议状态机

stateDiagram-v2 [*] --> Admitted Admitted --> Materializing Materializing --> Inferring Inferring --> DecisionValidated DecisionValidated --> AwaitingAuthorization: effect requires policy DecisionValidated --> Observing: answer or no effect AwaitingAuthorization --> Executing: approved AwaitingAuthorization --> Orienting: denied with alternative AwaitingAuthorization --> Blocked: required authority unavailable Executing --> Reconciling: effect status unknown Executing --> Observing: receipt known Reconciling --> Observing: effect established Reconciling --> Failed: cannot establish effect safely Observing --> Verifying Verifying --> Orienting: new evidence or failure Orienting --> Materializing: continue or replan Verifying --> Completed: acceptance proven enough Verifying --> Blocked: external dependency Verifying --> Failed: terminal error Materializing --> Cancelled Inferring --> Cancelled Executing --> Cancelled AwaitingAuthorization --> Cancelled Completed --> [*] Blocked --> [*] Failed --> [*] Cancelled --> [*]

Reconciling 不能省略:请求超时不代表 effect 未发生。例如 git push 返回流断开时,正确动作是检查远端 ref,而不是再次 push;支付、发消息、发布等外部 effect 更不能盲重放。

3.3 一份可落地的核心伪代码

def run_turn(turn, goal, spec, budgets, signal):
    state = restore_or_initialize(turn, goal, spec)

    while True:
        signal.throw_if_cancelled()
        enforce_hard_budgets(budgets, state)

        if terminal := evaluate_non_model_stop_conditions(state, budgets):
            return terminal

        context = project_context(
            goal=goal,
            spec=spec,
            belief=state.belief,
            plan=state.plan,
            evidence=state.evidence,
            policy_summary=state.policy_summary,
            budget=budgets.snapshot(),
        )

        candidate = model.propose_next_decision(context)
        decision = validate_decision_schema(candidate)

        if decision.kind == "final":
            verdict = verify_completion(goal, spec, state, decision.claims)
            persist(verdict)
            if verdict.sufficient:
                return Completed(evidence=verdict.evidence)
            state = orient(state, verdict.counterevidence)
            budgets.charge("false_completion_attempt")
            continue

        action = bind_tool_contract(decision.tool_call)
        risk = assess_risk(action, state, goal, spec)
        verdict = policy_gate.authorize(
            action=action,
            actor=turn.delegated_identity,
            provenance=state.provenance,
            risk=risk,
        )
        persist(verdict)

        if verdict.kind == "deny":
            state = orient(state, policy_observation(verdict))
            if verdict.terminal:
                return Blocked(reason=verdict.reason)
            continue

        if verdict.kind == "ask":
            approval = await_authority(verdict.request, signal)
            persist(approval)
            state = orient(state, approval)
            if not approval.approved:
                continue

        intent = persist_intent_before_effect(action, idempotency_key())
        try:
            receipt = execute(action, intent, signal)
        except UnknownEffectError as error:
            receipt = reconcile(action, intent, error)
        except Exception as error:
            disposition = classify_and_recover(error, action, state, budgets)
            persist(disposition)
            if disposition.kind == "retry":
                budgets.charge("retry")
                bounded_backoff(disposition)
                continue
            if disposition.kind == "replan":
                state = orient(state, disposition.evidence)
                continue
            return disposition.as_terminal()

        observation = normalize_observation(receipt)
        persist(observation)
        state = orient(state, observation)

        step_verdict = verify_progress(goal, spec, state, action, observation)
        persist(step_verdict)
        state = update_task_model(state, step_verdict)
        budgets.charge_from(action, receipt, step_verdict)

伪代码中最重要的所有权:

  • model proposes
  • schema validator parses
  • policy gate authorizes
  • executor commits effect
  • journal records intent/receipt
  • verifier judges evidence
  • controller decides continue/replan/stop

任何一个对象同时拥有“提议、放行、执行、判成功”四权,都会形成不可审计的自证闭环。

3.4 Step 边界必须具备的原子性

一次 step 不一定数据库意义上全原子,但应保持这些不变量:

  1. 完整 tool call 未形成前不执行;
  2. effect 前先持久化 intent;
  3. effect 后尽可能持久化 receipt;
  4. observation 只有在进入 journal 后才能进入下一次 context;
  5. provider wire 需要的 tool result 必须完整闭合;
  6. cancellation 不得把“已提交 effect”伪装成“未执行”;
  7. retry 是新的 attempt,不能覆盖原 attempt 的证据;
  8. step 结束原因必须是结构化枚举,而不是从自然语言猜测。

3.5 并行 tool calls 仍属于控制问题

模型一次给出多个 tool calls 时,不能按“都能 async”决定并发。应建立资源 effect 集:

ReadSet(action)   = action 可能读取的逻辑资源
WriteSet(action)  = action 可能修改的逻辑资源
External(action)  = 不受本地事务控制的 effect

两个 action 可并行的必要条件通常是:

Write(A) ∩ (Read(B) ∪ Write(B)) = ∅
Write(B) ∩ Read(A) = ∅
并且 failure/cancellation semantics 可组合

只读命令也可能冲突:一个读取 build artifact,另一个正在重建;两个网络查询可能共享 rate-limit budget。并发调度需要考虑资源冲突、配额、公平性、结果顺序、部分失败和取消传播。


4. Planning:不是一种算法,而是一组控制策略

证据边界: ReAct、Tree of Thoughts、Graph of Thoughts、LATS、Reflexion 是 2022–2023 年奠定概念语言的研究,不是“2026 最新产品默认实现”的证据。它们用于解释设计空间;当前 Kimi、Codex、Claude 等公开材料并未证明生产控制面普遍直接运行 ToT、GoT 或 MCTS。把论文范式名称映射到产品内部算法,属于没有依据的过度归因。

4.1 Reactive / ReAct

ReAct把 reasoning 与 action 交错:每次根据最新 observation 决定下一步。

thought → action → observation → thought → action ...

适合:

  • feedback 快;
  • action 低成本、可逆;
  • 环境未知,预先长计划很快过时;
  • 下一步高度依赖刚获得的证据。

弱点:

  • horizon 长时容易局部贪心;
  • 缺少全局依赖和验收覆盖;
  • 容易把“持续行动”误当进展;
  • 重复观察、来回改动和忘记旧失败分支。

工程上,ReAct 必须补上显式 task/evidence state、no-progress detection 和 hard budgets,不能只靠 conversation history。

4.2 Plan-and-Execute

先构建高层 plan,再由执行器逐项完成:

planner(goal, state) -> tasks[]
executor(task_i)      -> result_i
controller(results)   -> continue / revise plan

适合:

  • 跨模块依赖明确;
  • 有高成本 setup;
  • 多个 task 可并行;
  • 需要提前暴露风险和用户决策;
  • 验收覆盖必须完整。

主要风险是 open-loop execution:如果 planner 产出后不再根据 observation 修订,计划会成为过期脚本。真正可靠的是 plan–execute–observe–replan,不是一次性 plan-and-execute。

4.3 Iterative Planning / Receding Horizon

借鉴 Model Predictive Control:每次规划一个有限 horizon,只执行第一段,再根据真实反馈重规划。

repeat:
    forecast H-step routes
    choose route with best expected utility/risk
    execute only next bounded action or slice
    observe actual state
    re-estimate and replan

它在 Coding Agent 中通常是最稳健的默认:

  • 保留全局方向;
  • 不把远期猜测当事实;
  • 能吸收编译、测试、repo 探索等真实反馈;
  • 允许在高风险 effect 前缩短控制 horizon。

代价是更多 planner 调用和 plan churn;需要 replan trigger 和最小承诺窗口,否则会每步重写整个计划。

4.4 Hierarchical Planning

把 Goal 分为多个抽象层:

Goal
  ├── diagnostic subgoal
  │     ├── reproduce
  │     └── isolate first failing boundary
  ├── change subgoal
  │     ├── preserve invariants
  │     └── implement minimal mechanism change
  └── verification subgoal
        ├── targeted check
        └── regression check

优势是降低每层分支因子,并让不同 worker 只看到必要上下文。风险是高层错误分解被下层高质量执行放大。所以上层 subgoal 也必须有可证伪性,不能只在叶子节点验证。

4.5 Search:Tree、Graph 与 MCTS/LATS

Tree of Thoughts

Tree of Thoughts显式生成多个思路节点、评估、剪枝和回溯:

state -> {candidate thought/action branches}
      -> score / prune
      -> expand promising branch

适合组合搜索、多个候选修复和高价值决策;不适合让每个真实副作用都成为“可回溯树节点”。真实世界 action 可能不可逆,搜索应尽量发生在:

  • 纯推理空间;
  • isolated worktree/sandbox;
  • simulation/dry-run;
  • 可丢弃的候选 patch;
  • 有明确 compensation 的事务边界。

Graph of Thoughts

Graph of Thoughts允许分支合并、依赖复用和循环 refinement。对代码任务,更自然的图通常不是“thought graph”,而是:

  • hypothesis–evidence graph;
  • file/symbol dependency graph;
  • task DAG;
  • candidate patch–test evidence graph。

Graph 的收益来自复用和合并,代价是状态管理、去重和信用归因复杂度。

LATS把语言模型的 value/reflection 与树搜索组合。结构上可理解为:

selection -> expansion -> action/rollout -> evaluation -> backpropagation

用于 Coding Agent 时必须问:

  • rollout 是真实执行还是模拟?
  • value 来自 test/oracle 还是同一个模型自评?
  • branch state 能否隔离?
  • 搜索预算与最终 verification budget 是否竞争?
  • evaluator 的偏差是否通过 backprop 被系统放大?

如果所有分支都由同一个模型生成和打分,搜索宽度可能只是相关错误的重复采样。

4.6 Reflection 与 Critic

Reflexion把环境反馈转换成语言反思并存入 episodic memory,不通过权重更新也能改变下一次尝试。生产系统应把它拆成三件事:

  1. feedback:外部发生了什么;
  2. diagnosis:为什么失败;
  3. policy hint:下次应怎样不同。

三者不能混在一句自我批评里。尤其 diagnosis 是假设,不是事实。正确记录方式:

Evidence: test X failed with exact assertion Y
Hypothesis: cache invalidation omitted branch Z
Next falsification: inspect call path P or run test Q
Confidence: medium

Critic 有四种独立性等级:

等级 Critic 信息源 价值 主要风险
C0 同一生成结果的即时自评 便宜 自洽偏差、看不到盲点
C1 同模型、独立 context 减少位置/承诺偏差 仍有相关模型偏差
C2 不同模型/专用 reviewer 多样性更高 共享训练先验、成本
C3 外部 oracle/runtime/human evidence 最接近真实状态 覆盖与规模受限

“加一个 critic”不自动等于闭环;关键是 critic 是否接触到了 generator 无法伪造或忽略的外部证据。

4.7 Planning 策略决策表

任务条件 默认策略 为什么 必须补的护栏
单步、低风险、反馈即时 ReAct/direct plan 开销大于收益 schema + quick verifier
环境未知、探索性诊断 iterative ReAct 每个 observation 改变下一步 hypothesis/evidence ledger
跨模块、依赖明确 hierarchical plan + receding horizon 暴露依赖但保持适应 replan trigger
多个独立候选修复 isolated search/tree 可比较多个 patch branch isolation + shared oracle
高风险外部 effect plan + preflight + short horizon 降低不可逆错误 policy gate + approval + receipt
语义/审美质量为主 generator–critic iteration 需要比较与 refinement rubric + human calibration
verifier 很强、生成便宜 search/test-time scaling 可用 verifier 选择 防 reward hacking
verifier 弱、状态不可回滚 conservative plan + human checkpoint 搜索会放大风险 limited action set

4.8 什么时候明确不应 planning

  • action 本身就是最便宜的信息获取;
  • task 只有一个低风险、可验证动作;
  • 环境变化速度高于计划生成速度;
  • 长计划会挤占 context 并造成 anchoring;
  • planner 没有足够状态,只是在把未知包装成步骤;
  • 验证器足够便宜,直接产生候选并验证更有效。

好的回答不是“复杂任务要 planning”,而是:当提前建模依赖、风险或验收覆盖的价值,高于计划过时与额外推理的成本时,才做显式 planning。

4.9 从 prompt-time orchestration 到 trainable controller

[PEER] AgentFlow / In-the-Flow Agentic System Optimization是 ICLR 2026 Oral。它把 planner、executor、verifier、generator 通过 evolving memory 组成多 turn MDP,并直接对 loop 内 planner policy 做 on-policy optimization。这提供了一条不同于“system prompt 里规定 ReAct/Plan-and-Execute”的路线:控制策略本身可以从 trajectories 中训练。

但它不能被解读为 Kimi/Codex/Claude 已采用同一内部架构,也不能证明四模块拆分对 repository-scale Coding Agent 必然最优。它主要支持三个窄判断:

  1. planning quality 取决于 execution/verification feedback,不宜只做离线静态 plan generation;
  2. planner 的训练分布应包含真实多 turn state transition,而不只包含最终 answer reward;
  3. 训练过的 model policy 仍不能拥有 runtime policy gate、effect accounting 和外部 acceptance 的最终权限。

[PEER] Verification-Aware Planning for Multi-Agent Systems(EACL 2026)进一步展示 planner-defined passing criteria 与 subtask verification functions 的联合建模。它支持“计划项应携带 acceptance”这一设计方向;但任务是多 agent benchmark,不能证明自动生成的 Python/NL verifier 在开放软件任务中天然忠实于用户 intent。


5. Plan 的数据模型、版本和失效

5.1 计划项不应只有文本和 done

type PlanItem = {
  id: string
  parentSubgoalId: string
  statement: string
  status: 'candidate' | 'ready' | 'running' | 'verified' | 'failed' | 'blocked' | 'abandoned'
  dependencies: string[]
  preconditions: PredicateRef[]
  acceptance: VerifierRef[]
  evidenceRefs: string[]
  risk: RiskVector
  owner?: AgentOrHumanRef
  revision: number
  invalidatedBy?: EvidenceRef
}

completed 不是一个充分状态。至少要区分:

  • executed:动作发生;
  • observed:结果已拿到;
  • verified:对应 acceptance 成立;
  • accepted:外部责任方接受。

5.2 Plan revision 的语义

每次修改 plan 应回答:

trigger:      哪个新 observation / user decision / policy result 触发
delta:        新增、删除、重排或失效了什么
rationale:    为什么旧路线不再最优或不再可行
preserved:    哪些 goal/spec/decision 不得改变
cost:         已投入工作是否可复用

不要每步全量重写 plan;否则 diff 无法审计,模型也容易悄悄改写目标。用稳定 item ID 和增量事件维护 task model。

5.3 Replan trigger

应重规划:

  • observation 与关键假设矛盾;
  • precondition 不成立;
  • dependency 或接口边界与预期不同;
  • policy 拒绝关键动作;
  • verifier 证明局部方案无效;
  • cost/risk 估计越过阈值;
  • 用户修改 goal/spec;
  • 连续动作没有新增证据;
  • 外部环境版本变化。

不应因以下原因全量重规划:

  • 单个 transient provider error;
  • 同一计划内可局部修正的 tool 参数错误;
  • 无关文件变化;
  • 模型“突然想到”另一种风格但无新证据。

5.4 Replan 的阻尼

计划系统也会振荡。可用以下机制降低 plan thrashing:

  • hysteresis:新方案的预期效用必须显著高于当前方案才切换;
  • minimum commitment:除非安全/证据推翻,至少完成一个 bounded diagnostic slice;
  • local repair first:优先修正受影响子树,不全量重写;
  • cooldown:同一假设刚被否定后,必须有新证据才能恢复;
  • branch tombstone:保存 abandoned 原因和 evidence;
  • switching cost:决策函数显式计入上下文切换、workspace 污染和已投入成本。

6. Policy Gate:模型之外的动作准入控制

6.1 Policy 与 prompt 的边界

Prompt policy: 影响模型倾向,“请不要访问网络”
Runtime policy: 在执行边界阻止 action,“egress=false”

Prompt 是概率机制;policy gate 是能力机制。二者可以同时存在,但不能让 prompt 承担安全边界。

6.2 Gate 的输入不能只有 tool name

成熟 policy evaluation 至少考虑:

actor identity       谁在请求,是否是 subagent/远端 agent
delegation           权力从谁而来,范围和有效期
tool capability      工具类别与声明 effect
normalized args      解析后的目标、命令、URL、资源 ID
resolved resources   realpath/symlink 后的真实对象
data provenance      参数是否来自不可信网页/repo/tool output
workspace trust      当前仓库/目录是否可信
read/write sets      可能触达的资源
external effect      push、send、publish、delete、charge 等
reversibility        可回滚、可补偿、不可逆
blast radius         单文件、repo、account、组织、公开互联网
uncertainty          effect/target 是否能精确解析
budget               剩余 external-effect/approval 风险预算

6.3 四类 verdict

Verdict 语义 对 Loop 的影响
approve 在限定 scope 内可执行 附带 execution metadata/attenuated capability
deny 明确禁止 observation 回给 orient;不得用变体绕过
ask 需要具体 authority 决策 暂停对应 action,而非冻结整个系统
synthetic result 不执行,但以结构化结果结束该 call 适合 dedupe、budget exhaustion、policy-owned fallback

ask 不是更温和的 approve。审批必须显示具体 action、target、effect、风险和授权 scope;“是否允许 Bash”过宽,没有形成有效决策。

6.4 Policy 决策流程

def authorize(action, actor, state):
    bound = resolve_and_normalize(action)       # shell AST, realpath, URL, resource ID
    if not schema_valid(bound):
        return Deny("invalid_action", terminal=False)

    caps = actor.delegated_capabilities.attenuate(bound.requested_scope)
    if not caps.covers(bound.effect):
        return Deny("capability_absent", terminal=not alternative_exists(bound))

    if provenance_violation(bound, state.information_labels):
        return Deny("information_flow_violation", terminal=False)

    risk = score_effect(bound, state)
    rule = most_specific_matching_rule(bound, actor, state)

    if rule.decision == "deny":
        return Deny(rule.reason)
    if rule.decision == "approve" and risk <= rule.max_risk:
        return Approve(scope=rule.scope, metadata=rule.metadata)
    return Ask(render_concrete_effect(bound, risk), allowable_scopes(bound))

需要 fail closed 的是“无法确定目标但动作可能高风险”;不应一律 fail closed 的是普通低风险解析错误,否则 utility 会崩溃。正确设计是先限制能力和 effect surface,再按风险处理未知。

6.5 Policy 与 Planning 的双向关系

Planning 不应先产出一个越权 plan,再逐项被 gate 拒绝。Planner 应获得可用能力摘要,在搜索阶段避免不可行路线;但最终执行仍需 gate,因为:

  • plan 可能过期;
  • args 在执行前才具体化;
  • context 中可能出现注入;
  • delegated identity/budget 可能变化。

[PREPRINT] 2026 年的 Optimizing Agent Planning for Security and Autonomy在 AgentDojo/WASP 和其 information-flow-control 设计下报告:security-aware planning 可以提高保持安全时无需 HITL 的 consequential-action 比例。它不证明所有确定性 policy 都会减少审批,也不证明现实开发环境中的 utility;可稳健吸收的是:让 planner 感知 policy 可行域可能提高可用性,但 planner 不能取代 enforcement。

6.6 Approval fatigue 的控制

降低审批负担的正确杠杆:

  • OS sandbox 和 workspace-scoped write;
  • capability attenuation;
  • session rule 只缓存足够具体的 pattern;
  • 相同 effect 的批量审批,但明确上限;
  • risk-adaptive gate;
  • 低风险 deterministic policy 自动放行;
  • 让 planner 选择无需高权限的等价路线。

错误做法是看到审批多就扩大默认权限。Approval burden 本身应是 budget 和 eval 指标。


7. Error Semantics:按“能否安全推进”分类,而不是按异常类名分类

7.1 三轴错误模型

任何 failure 都至少要从三条轴判断。

轴一:发生在哪个边界

边界 例子 首要 owner
Goal/spec 目标矛盾、验收缺失 product/user contract
Context/orient 旧状态、关键信息丢失、错误 provenance context/harness
Planning 依赖遗漏、错误分解、计划过期 planner/controller
Decision/schema 不存在的工具、非法参数 model adapter/validator
Policy 越权、过度拒绝、审批状态丢失 policy plane
Execution command/API/tool 失败 tool/runtime/environment
Effect accounting effect 已发生但 receipt 丢失 executor/journal
Observation 输出截断、顺序错误、缓存过期 tool adapter
Verification oracle 覆盖不足、flaky、judge 偏差 eval/verifier
Persistence/recovery journal 不完整、replay 非确定 runtime/storage

轴二:effect certainty

NOT_COMMITTED   已知副作用未发生;可以考虑重试
COMMITTED       已有唯一 receipt;禁止重复提交
UNKNOWN         可能发生;先 reconcile
PARTIAL         部分子 effect 已发生;按每个 effect 分解
COMPENSATED     effect 发生后已执行补偿,但状态未必等于原状态

HTTP status、进程退出码和 effect certainty 不是一回事。客户端超时可能对应 UNKNOWN,服务端 500 也可能在写入后发生。

轴三:可恢复动作

动作 精确定义 是否改变原计划 典型使用
Retry 同一语义请求的新 attempt transient network/provider,且 effect 未提交或幂等
Recover 修复当前机制状态后继续 局部 重连、恢复进程、重建 context
Reconcile 查明不确定 effect 的真实状态 超时后查远端 ref/job/payment ID
Replan 基于新证据改变路线 policy denied、假设被证伪
Fallback 使用能力较弱但契约明确的路径 可能 图像降级为文本、换本地 search
Failover 切换等价服务实例/provider 尽量不变 provider outage;需协议兼容
Rollback 撤销已提交改变 否,但改变环境 patch/release 回退;可能非完美逆操作
Escalate 把决策交给更高 authority 暂停 权限、歧义、高风险

7.2 Recovery 决策表

Failure Effect certainty 正确 disposition 禁止做法
provider 429/overload NOT_COMMITTED bounded retry + Retry-After + shared budget 每层各自无限 retry
auth/quota/config NOT_COMMITTED fail fast、换明确 capability 或阻塞 把永久错误当 transient
tool args/schema invalid NOT_COMMITTED 结构化 observation,让 model 修正;限次数 猜测参数并执行
tool not found NOT_COMMITTED 区分动态未披露、server unavailable、真不存在 同名模糊 fallback
permission denied NOT_COMMITTED replan 或明确 blocked 用 shell/别名绕 gate
approval rejected NOT_COMMITTED 把 rejection 当用户决策;不重复询问相同 effect 换措辞继续 ask
context overflow NOT_COMMITTED compact、drop media、换 context strategy 盲减 completion token
command exit non-zero 取决于工具 解析失败类别与产生的部分 artifact 统一 retry 命令
response stream 中断 UNKNOWN 只有完整 committed tool intent 才可能执行;查 receipt 补全半截 JSON 执行
external API timeout UNKNOWN 按 idempotency key/status endpoint reconcile 无 key 重放写请求
test flaky COMMITTED observation 重跑需标记独立样本并做 flake attribution 只保留通过那次
verifier failure 已有变更 生成 counterevidence,replan 或 rollback 要求模型“再自信一点”
no progress 多种 新证据要求 → falsification → stop/escalate 无差别增加 steps
user cancel 可能 PARTIAL abort in-flight;保存已发生 effect 与合法 wire 伪装成 system failure 后自动重试

7.3 Retry 的五个必要条件

只有同时满足时才应自动 retry:

  1. failure 被判定为 transient;
  2. 原请求的 effect 确定未发生,或有可靠 idempotency;
  3. 下一 attempt 有合理成功概率;
  4. retry 消耗计入共享 budget;
  5. retry 不会掩盖需要 replan 的语义错误。

指数退避只解决拥塞,不解决语义。一个错误路线被 exponential backoff 后仍是错误路线。

7.4 Retry amplification

如果 provider adapter、LLM requester、step loop、job queue 各重试 rᵢ 次,总 attempt 上界近似:

attempts = Πᵢ (rᵢ + 1)

三层各 retry 3 次不是 9 次,而可能是 64 次。可靠系统应有:

  • 单一 retry ownership;
  • attempt lineage;
  • shared deadline/budget;
  • provider 的 Retry-After 传播;
  • 上层只看到结构化 disposition,不再次猜测。

7.5 Error 应携带什么

type AgentError = {
  code: StableErrorCode
  owner: 'model' | 'harness' | 'policy' | 'tool' | 'environment' | 'verifier'
  retryable: boolean
  effectCertainty: 'not_committed' | 'committed' | 'unknown' | 'partial'
  recoverability: 'retry' | 'recover' | 'reconcile' | 'replan' | 'escalate' | 'terminal'
  requestId?: string
  toolCallId?: string
  idempotencyKey?: string
  traceId: string
  userImpact: string
  safeMessage: string
  detailsRef?: ArtifactRef
}

retryable: true 本身不够,因为它没有说明 effect 是否安全重放,也没有说明谁拥有重试。


8. Stop Conditions:完成、停止和失败必须分开

8.1 终态集合

建议 turn/goal 至少有:

终态 含义 必须附带
completed_verified acceptance 已有足够证据 evidence set、coverage、remaining uncertainty
completed_unverified 只能交付候选,未满足验证 contract 为什么无法验证;不得伪装成功
blocked 外部条件阻止继续,Agent 无有意义的下一动作 blocker、已尝试、解除条件
budget_exhausted 某硬预算达到 已用/剩余、当前进度、未验证项
risk_stopped 风险或 policy 边界触发 policy/risk reason、可选安全路径
failed terminal mechanism/semantic failure stable error、owner、恢复建议
cancelled authority 主动取消 已发生 effect、未完成状态
superseded goal/spec 被新输入替换 新旧目标关联、废弃 work

如果 API 只能返回 success/failure,产品层会被迫把 blocked、cancelled、unverified 都塞进错误或成功,最终不可运营。

8.2 成功停止条件

成功不能由以下信号单独触发:

  • 模型输出没有 tool calls;
  • 模型说“已完成”;
  • 所有 plan items 被模型标成 done;
  • 某条命令 exit 0;
  • 代码有 diff;
  • 单个测试通过;
  • token 快用完。

成功应满足:

Goal predicate evidence sufficient
AND mandatory spec invariants covered
AND no known blocking counterevidence
AND verification provenance acceptable
AND external effects reconciled
AND final artifact state persisted

“sufficient” 是 risk-aware 的,不等于逻辑全知。低风险文案可由 lint + 人眼抽样;数据库迁移需要更强证据和回滚检查。

8.3 Stagnation / no-progress

不要只检测相同 tool+args。更完整的 no-progress 信号:

  • repeated action fingerprint;
  • repeated observation hash;
  • belief/plan 连续 k 步没有有效 delta;
  • acceptance coverage 不增加;
  • 同一失败 root cause 重复;
  • A→B→A 状态周期;
  • token/cost 增长但信息增益接近零;
  • 反复扩大搜索却没有新可证伪假设。

递进式控制:

Stage 1  要求声明下一动作预期产生的“新信息”
Stage 2  要求选择最便宜的 falsification test
Stage 3  replan / retrieve missing input / switch strategy
Stage 4  明确 blocked 或交付现有证据
Stage 5  hard stop,禁止再调用工具

Stagnation detector 也会误报:长编译或大规模测试可能短时间无 observation,但仍在进展。因此要看 action semantics、heartbeat 和预计 duration,不能只看墙钟。

8.4 Blocked 的严格语义

blocked 表示:

  • 有一个对目标必要的未满足 precondition;
  • 当前 capability/authority 下没有安全替代路线;
  • 继续行动不会获得能解除它的新证据;
  • 解除依赖于具体外部变化或用户决策。

“任务很难”“仍需更多工作”“模型不确定”都不是 blocked。Blocked message 必须指出:

blocking predicate
evidence that it is unmet
why alternatives are exhausted or disallowed
exact authority/input/state change needed
partial effects already committed

8.5 Cancellation 的一致性

取消有三层:

  • turn cancel:停止当前用户请求;
  • step cancel:停止当前 inference/tool batch;
  • tool cancel:请求具体执行器终止。

取消不是回滚。收到 cancel 后:

  1. 中止尚未提交的 action;
  2. 对已开始的 tool 发 cancellation;
  3. 等待/查询 effect receipt;
  4. 标记未知或部分 effect;
  5. 闭合 provider tool-call wire;
  6. 持久化可续接 checkpoint;
  7. 向用户报告已发生和未确认的状态。

9. Budget Controller:资源、风险和验证的联合调度

9.1 Budget 是向量

B = {
  steps,
  turns,
  input_tokens,
  output_tokens,
  wall_clock,
  monetary_cost,
  tool_attempts_by_class,
  external_effects,
  write_volume,
  network_egress,
  approval_requests,
  subagent_fanout,
  verification_reserve
}

不同 budget 不能完全互换。剩余 token 很多不意味着可以继续发外部消息;step 未耗尽也不意味着审批负担仍可接受。

9.2 Goal、turn、step 的分层预算

Goal budget
  ├── Turn slice A
  │     ├── inference
  │     ├── tools
  │     └── verification reserve
  ├── Turn slice B
  └── recovery reserve

子任务的预算必须从父预算中预留,而不是各自认为拥有全部额度。并发 subagents 尤其需要全局 cost/rate/effect controller。

9.3 Soft threshold 与 hard cap

  • soft threshold:触发更便宜策略、缩短 horizon、压缩 context、减少 search width;
  • hard cap:禁止新 effect,进入结构化终止;
  • emergency reserve:只允许 reconciliation、cleanup、verification 和最终状态持久化。

若 step cap 到达时连 verification 都没预算,设计已经失败。生成预算和验证预算必须在开始时分配。

9.4 边际效用控制

候选动作可用简化效用函数比较:

U(a) = P(progress | a, b) * ΔGoal
     + InformationGain(a)
     - λc * Cost(a)
     - λt * Latency(a)
     - λr * ExpectedRisk(a)
     - λs * SwitchingCost(a)

接近预算末尾时,控制器不应简单让模型“尽快完成”,而应提高:

  • λc:成本权重;
  • λr:风险权重;
  • verification reserve 的优先级;
  • 选择信息增益高、能证伪关键假设的动作概率。

这是一种 gain scheduling:根据剩余资源和风险动态调整 policy,而不是在所有阶段使用同一行为风格。

9.5 Budget 决策表

状态 控制动作
预算充足、状态未知 探索,优先高信息增益 observation
已定位根因、方案清晰 收缩搜索,进入最小变更与验证
token 紧张、artifact 可外置 compact context,不删 goal/spec/evidence pointers
wall time 紧张、长测试进行中 保留运行、减少新分支,等待有价值 observation
external-effect budget 紧张 使用 dry-run/local simulation;审批高风险 effect
approval burden 高 重规划为低权限路径;不能静默扩权
step 接近 hard cap 停止广泛探索,执行最关键 verifier 或明确未验证
已越过 hard cap 拒绝新工具,只允许终止/持久化/必要 reconciliation

9.6 Budget 本身要可观测

每次 charge 应记录:

  • budget dimension;
  • delta 和累计值;
  • action/attempt/agent owner;
  • 是否来自 retry/recovery/verification;
  • soft/hard threshold transition;
  • 谁批准了预算扩展。

否则成本分析只能看到总 token,无法回答“为什么这个任务贵”。


10. Verification:从“跑了测试”到证据工程

10.1 Verification 的目标

Verification 不是给答案打一个总分,而是判断一组 claims:

Claim: 用户报告的问题已消失
Claim: 关键既有行为未回归
Claim: 修改没有越过允许边界
Claim: 外部 effect 落在目标资源
Claim: artifact 可由用户使用/部署

每个 claim 需要:

  • verifier;
  • evidence provenance;
  • coverage;
  • freshness;
  • independence;
  • known blind spots。

10.2 验证层级

这不是绝对线性排名,但通常从更确定、更局部走向更语义化:

层级 例子 能证明什么 不能证明什么
V0 Schema/static JSON schema、parser、lint、typecheck 结构/静态约束 运行行为与用户意图
V1 Invariant/diff 禁止路径、依赖边界、secret scan、migration invariant 局部安全/架构约束 完整功能
V2 Unit/component tests 针对函数/模块的确定性测试 特定行为 集成和真实环境
V3 Integration/runtime 服务启动、browser、API、CLI、真实 workspace 可执行行为 未覆盖路径与长期效果
V4 Simulation/replay sandbox、dry-run、trace replay、fault injection 风险较低地验证动态 模拟与真实环境差距
V5 Domain oracle 编译器、账本、协议 checker、golden state 高信度领域谓词 oracle 未编码的 intent
V6 LLM/agent judge rubric review、语义比较、代码审查 难程序化质量 自洽偏差、可重复性
V7 Human/authority 用户验收、专家审查、责任性决策 意图与责任边界 规模、稳定性、疲劳

正确做法是 evidence composition,不是永远“越高越好”。例如 typecheck 比 LLM judge 更适合判类型,但用户才有权批准删除生产数据。

10.3 Verification hierarchy 的关键细节

Static

  • 快、便宜、可前置;
  • 适合 schema、类型、依赖边界、policy invariant;
  • 容易被误用为“编译通过即功能完成”。

Tests

  • 只有在测试本身可信、运行环境正确、覆盖 claim 时才是证据;
  • inherited tests 可能 broken、过时或可被 patch 绕过;
  • Agent 修改 tests 时要区分“合法更新预期”与“删除失败信号”。

Simulation

  • 用于不可逆 effect 的预演和搜索分支;
  • 必须记录 fidelity gap;
  • simulation pass 之后,生产 effect 仍需 runtime receipt 和 postcondition。

Oracle

  • oracle 应尽量读取 generator 无法直接伪造的世界状态;
  • artifact、容器、网络、测试权限可隔离;
  • oracle 也可能只验证 proxy,需要持续更新。

LLM judge

至少要:

  • blind input,避免看到品牌/候选顺序;
  • calibration set;
  • 明确 rubric 和 abstain;
  • judge version 固定;
  • 人审抽样和 disagreement 监控;
  • 不让 generator 在同一 context 中直接覆盖 judge。

Human

  • human review 不是自动完美 oracle;
  • 必须提供压缩但完整的 decision evidence,而非海量 trace;
  • 高审批频率会造成 rubber-stamping;
  • 人应负责规范性/不可逆决策,机器负责可自动验证的重复检查。

10.4 生成器与验证器独立性

验证器的有效性来自信息与激励独立:

Weak:   same model, same context, asks itself "did I succeed?"
Better: fresh context, explicit rubric, sees diff + evidence
Strong: deterministic test/oracle in isolated environment
Strongest available: multiple orthogonal evidence channels + authority acceptance

独立性包括:

  • process isolation:generator 不能修改 oracle;
  • data separation:held-out cases 不进 context;
  • provenance separation:自述与工具证据分栏;
  • model diversity:降低相关错误,但不能替代外部事实;
  • incentive separation:verifier 不以“让任务看起来完成”为目标。

10.5 Verification Horizon

[PREPRINT] 2026 年预印本 The Verification Horizon把验证信号放在 scalability、faithfulness、robustness 三维上;“固定 reward 会随 policy 增强而饱和或被利用”是作者基于其四类 reward construction 与内部/公开 benchmark 得出的主张,不是已证明的普遍定理。对工程的稳健启示不是接受论文所有经验数字,而是:

  1. verifier 是可演化产品,不是一次写完的 test suite;
  2. generator capability 提升后要重新 audit verifier blind spots;
  3. proxy pass rate 与真实用户接受度的 gap 必须持续测量;
  4. verification budget 会成为比 generation throughput 更硬的瓶颈。

10.6 Progress Mirage

[PREPRINT] 最新预印本 When Do Agent Loops Mistake Stagnation for Progress?是 23 页、预注册的 pilot measurement study。作者报告:在其固定 agent/tool surface 的 54 个 cycles 中,agent 每次都声称进展,但 56% 的 cycle 经隔离 world-state oracle 测得 delta 为零或负;最强 in-band judge 在该设置中也有高误判。这个小样本、单一任务族和特定 evaluator channel 不能外推成通用失败率。它支持的窄结论是:当成功信号位于 transcript 之外时,只靠同一信息带内的 self-report/judge 可能无法可靠估计真实进展。 “模型必然把所有合理叙事当进展”则属于过度归因。

对应控制措施:

  • progress 必须绑定 external state delta;
  • completion claim 与 verifier evidence 分离;
  • 检查 negative delta,不只看 pass/fail;
  • 连续“自评进展但 oracle 无改善”触发 breaker。

10.7 Verifier 失败模式

Failure 例子 诊断
Coverage gap 只跑 unit test,没有真实登录链路 claim–evidence matrix 有空列
Proxy gaming 修改测试让它不再检查错误行为 test diff、held-out oracle
Contamination generator 看过 hidden cases provenance/audit
Correlated judge reviewer 重复 generator 盲点 disagreement + external evidence
Flakiness 重跑结果随机 repeated seeded runs、flake model
Stale oracle spec 已变化但 golden 未更新 oracle version 与 spec version
Environment mismatch 本地 pass、部署 fail environment fingerprint
Oververification 低风险变化跑过重套件 marginal coverage per cost
False authority 模型说“用户应该满意” 用户 acceptance 才是规范性信号

10.8 Claim–Evidence Matrix

                    lint  unit  integration  runtime  oracle  human
claim: syntax         ✓
claim: target fix           ✓       ✓           ✓
claim: no regression        △       ✓           ✓
claim: correct account                                      ✓
claim: product taste                           △       △      ✓

它的作用不是做表格,而是暴露:

  • 哪个 claim 完全没证据;
  • 哪个 claim 只有同源 proxy;
  • 哪个验证重复但不增加覆盖;
  • 哪些不确定性必须对用户披露。

10.9 闭环 code review

[PREPRINT] 2026 年 SWE-Review研究 generate–review–revise loop,并在其 SWE-Review-Bench/Traj 设置中报告 reviewer 对后续 revision 的帮助。它尚不足以证明任何 reviewer agent 都优于静态 review。应保持两个判断:

  • review feedback 只有在 revision 后重新跑外部 verifier 才闭环;
  • reviewer agent 的“accept”不能替代 tests、runtime 和用户 intent。

Review 的最好作用是发现新的 claims/counterexamples 并指导下一步验证,不是成为最终神谕。

10.10 Validator feedback 也有接口语义

[PREPRINT] Structured Feedback Improves Repair in an LLM Agent Loop把 generator 与控制 acceptance/budget/trace 的外部 validator 分开,并比较 raw diagnostics 与包含 failure location、observed value、admissible alternatives 的反馈。作者在 50 个 paired TextWorld games、four-call cap 和两个较小开源模型上报告显著提升;ablation 中大部分收益来自提供 admissible alternatives,而 JSON 与等价 prose 没有明显差别。

可吸收的窄结论:

  • verifier 反馈必须可操作,不能只返回 failed
  • 失败位置、观测值和允许修复空间应是 typed semantics;
  • 结构化数据的价值来自字段契约、可追踪和 adapter 稳定,不是 JSON 语法本身有推理魔力。

限制同样重要:任务是 TextWorld,不是 repository-scale coding;样本 50、调用上限 4、模型较旧,不能把论文中的绝对提升直接用于 frontier Coding Agent 容量规划。


11. Uncertainty、Risk 与 Adaptive Autonomy

11.1 一个置信度数字为什么无用

至少区分五类不确定性:

类型 问题 典型控制动作
Intent uncertainty 用户究竟要什么,spec 是否冲突 澄清或选择可逆解释
State uncertainty 当前 repo/runtime/远端真实状态是什么 observation/reconciliation
Epistemic uncertainty 哪个因果假设正确 高信息增益实验/搜索
Outcome uncertainty 动作会造成什么 effect simulation、缩小 scope、approval
Verification uncertainty 证据覆盖是否足够 增加 orthogonal verifier/披露
Normative uncertainty 哪个风险/取舍由谁决定 交给合法 authority

“confidence=0.7”无法告诉控制器下一步该查状态、跑测试还是问用户。

11.2 不要迷信模型口头置信度

更可信的不确定性信号包括:

  • 多个独立采样/模型之间的 disagreement;
  • state retrieval 是否缺失关键资源;
  • hypothesis 能否解释全部 observations;
  • test/benchmark 的分布外程度;
  • tool output 是否截断或 stale;
  • verifier coverage;
  • action 是否超出历史已验证 scope;
  • 与相似 trace 的 empirical success/recovery rate。

[PEER] ACL 2026 的 Agent UQ 综述把 agent UQ 的难点放到非确定环境中的时间演化、交互和多阶段决策上。由此得到的工程建议是测 trajectory-level calibration,而不只看单次文本的 token probability;这条建议是本文的 [INFERENCE],不是该综述已经给出统一可用指标。

11.3 Risk vector

Risk(a) = {
  impact,
  likelihood,
  reversibility,
  blast_radius,
  privilege,
  data_sensitivity,
  external_visibility,
  effect_uncertainty,
  verifier_strength
}

Risk 不是一个静态 tool label。同一个 shell tool:

  • rg 读取可信 workspace,低风险;
  • 读取 secret 后发网络,高风险;
  • git push --force 作用于共享分支,高风险;
  • 在 isolated throwaway branch 运行格式化,中低风险。

11.4 Adaptive autonomy 不是自动升级权限

Autonomy 至少是一个向量:

scope       可触达哪些资源
duration    能连续运行多久
initiative  能否自发创建后续任务
effects     能执行何种副作用
delegation  能否创建/授权其他 agent
oversight   何时需要检查点

风险自适应控制应改变:

  • planning depth;
  • verifier strength;
  • action scope;
  • approval threshold;
  • tool availability;
  • allowed concurrency;
  • stop sensitivity。

而不是因为 agent 过去做对过几次,就永久获得更大账户权限。

11.5 Earned trust 的边界

[PEER] Hedwig已被 ACM CAIS 2026 demo track 接收;其 formative survey 为 21 名使用 coding agents 的软件工程师,并展示根据开发者反馈跨 session 调整自主性的 CLI prototype。可吸收的原则是“熟悉且被验证的行为减少摩擦,超出已知范围时收紧监督”。demo-track prototype 与小样本形成性研究不是动态自治安全性或生产效果的普遍证明。要避免:

  • 把个人偏好学习误当安全授权;
  • 从“允许改这个目录”外推到相似目录;
  • 反馈 memory 被 repo/网页注入污染;
  • permission cache 没有 scope、expiry 和 provenance;
  • 任务风险变化后仍沿用旧自治等级。

动态自治必须是 bounded、revocable、auditable、scope-specific

11.6 Oversight 模式

[PREPRINT] Human oversight of agentic systems in practice从其软件 agent 开发者研究中归纳四种监督工作:a priori control、co-planning、real-time monitoring、post hoc review。样本与研究方法决定了它是实践 taxonomy,不是四阶段完备性定理。映射到控制面:

模式 控制点 适合
A priori control spec、policy、sandbox、预算预设 可提前表达的硬边界
Co-planning 高风险分支/需求歧义对齐 规范性或架构决策
Real-time monitoring live trace、interrupt、approval 长任务和外部 effect
Post hoc review diff、artifact、receipts、verifier report 可回滚结果和质量审查

监督不是单个 HITL popup,而是一组在不同时间尺度上的控制手段。

11.7 风险—自治决策表

不确定性 / 风险 自治策略
低风险、强 verifier、可逆 自动执行 + post hoc review
低风险、弱 verifier 限定 scope + 更强 evidence requirement
高风险、状态确定、authority 明确 具体 preflight + approval + receipt
高风险、effect 不确定 禁止执行,先 simulation/reconciliation
intent 不确定、变化可逆 选择最小可逆解释并显式说明
intent 不确定、不可逆 co-plan / ask before effect
model disagreement 高 扩展 observation 或独立 reviewer,不扩大 effect
budget 低、风险上升 缩短 horizon,保留 verification/reconciliation reserve

12. Closed-loop Stability:稳定性、振荡和漂移

12.1 稳定到底指什么

对概率性 Agent 很难像线性系统一样给全局稳定证明,但可定义工程性质:

  • Safety:任何时刻不越过不可接受状态集合;
  • Boundedness:token、steps、effects、cost、fanout 有界;
  • Liveness:有可行路线和足够资源时最终继续推进,而非死锁;
  • Convergence:验证过的未满足约束总体减少;
  • Recoverability:故障后能回到已知 checkpoint 或明确终止;
  • Non-oscillation:不在有限状态集间无新证据循环;
  • Goal invariance:目标/spec 不因 context 变换悄然改变。

12.2 Lyapunov 式进展函数

可以构建近似势能函数 V

V(state) = weighted_unverified_requirements
         + unresolved_high_risk_unknowns
         + known_regressions
         + unreconciled_effects
         + blocking_dependencies

理想动作使期望 E[V(t+1) - V(t)] < 0。但必须注意:

  • “写了更多代码”不是 V 下降;
  • model 自评不能直接修改 V
  • 只有新外部证据或权威决定才能改变相应项;
  • 某个局部 test pass 可能降低一项,同时新回归提高另一项。

这是 heuristic,不是对 LLM 的数学稳定证明;它的价值是迫使系统把“进展”绑定到可观测状态。

12.3 常见振荡模式

振荡 表现 根因 阻尼机制
Patch oscillation A 修法与 B 修法来回切换 没保存反证/切换成本 branch tombstone + stronger switch threshold
Plan thrashing 每步重写整份 plan horizon 太长、无局部修订 receding horizon + local repair
Tool repetition 相同调用和结果循环 no-progress 不可见 fingerprint + novelty requirement + breaker
Permission chattering ask→reject→同义 ask rejection 未成为约束 session decision state + policy feedback
Retry storm 多层 retry 同时触发 retry ownership 不清 one owner + shared budget/backoff
Verifier chasing 修一个 test 坏另一个,再反向修 spec 冲突或 patch 局部补偿 invariant set + regression suite + root cause
Context oscillation compact 后找回旧细节,又丢新约束 compaction 无不变量 typed task/evidence state
Multi-agent ping-pong reviewer/generator 反复同样意见 无接受准则或独立证据 disagreement protocol + oracle

12.4 Chattering、overshoot 和 controller gain

控制“增益”可理解为 observation 对下一动作幅度的影响:

  • 增益太高:单个 flaky test 就推翻全部方案,产生 plan thrash;
  • 增益太低:多次明确失败仍坚持旧路线;
  • 响应延迟:基于旧状态继续发多个 write,造成 overshoot;
  • noisy verifier:临界阈值附近反复完成/未完成。

阻尼手段:

  • confidence-weighted update;
  • 多个独立 observation 再改变高层 belief;
  • completion/permission threshold 加 hysteresis;
  • write serialization;
  • action cooldown;
  • 在长延迟 action 期间限制 speculative effects;
  • 只对局部 plan subtree 更新。

12.5 Drift taxonomy

Drift 定义 检测
Goal drift 执行逐渐偏离用户问题 goal hash / invariant reminder / claim mapping
Spec drift 验收条件被悄悄弱化 versioned spec delta with authority
State drift belief 落后于真实 workspace/remote freshness、version、re-observe
Plan drift task list仍指向已失效假设 dependency/precondition invalidation
Context drift compaction/retrieval 改写决定或证据 full-vs-compact replay、typed preservation
Policy drift 配置/身份变化但旧 approval 继续生效 policy version、scope/expiry check
Verifier drift tests/rubric 不再代表 intent acceptance correlation、broken-task audit
Model drift provider/model update 改变 tool behavior model/harness versioned eval
Environment drift dependency、API、branch 在运行中变化 environment fingerprint / optimistic concurrency

12.6 防漂移不变量

跨 context/turn 必须保存:

  • exact goal 与 authority;
  • versioned spec;
  • user decisions;
  • current workspace/branch/config fingerprints;
  • committed effects 和 receipts;
  • verified claims 与 evidence refs;
  • unresolved counterevidence;
  • abandoned hypotheses;
  • remaining budgets;
  • current autonomy/policy scope。

这些是控制状态,不应只埋在自然语言摘要里。

12.7 Deadlock 与 livelock

  • deadlock:等待互相依赖的 approval/task/resource,系统没有活动;
  • livelock:系统持续执行动作但 world state 不改善;
  • starvation:某个重要 verifier/task 一直被更便宜任务抢占;
  • priority inversion:低价值长任务占着 sandbox/lock,阻止高风险 reconciliation。

所需机制:

  • wait-for graph;
  • deadline 和 cancellation propagation;
  • resource lease;
  • priority inheritance;
  • verification reserve;
  • progress watchdog 基于 state delta,不是 event frequency。

13. Trace 与 Evaluation:控制面必须能回答“为什么走到这里”

13.1 Trace 不是聊天记录

聊天记录只显示给模型/用户的内容;控制 trace 还必须包含没有进入 prompt 的系统事实:

GoalRun
  Turn
    Step
      context.materialized
      model.request / model.response
      decision.validated
      policy.evaluated
      approval.requested / resolved
      tool.intent
      tool.effect / receipt
      observation.persisted
      verifier.started / result
      belief.delta
      plan.revised
      budget.charged
      stop.evaluated

长输出放 artifact store,trace 只存 hash、size、truncation、preview policy 和 ref。不要把 secret、credential、private source 全量复制进 telemetry。

13.2 稳定 ID 体系

至少关联:

session_id
goal_id
turn_id
step_id
model_request_id
provider_request_id / trace_id
tool_call_id
tool_attempt_id
effect_id / idempotency_key
approval_id
verifier_run_id
plan_revision
artifact_id

tool_call_id 表示模型意图,tool_attempt_id 表示执行尝试,effect_id 表示世界中的唯一副作用;三者不能复用同一个 ID。

13.3 Decision event

不要记录不可控的完整隐式 chain-of-thought;记录能审计控制行为的结构化 decision metadata:

{
  "type": "agent.decision",
  "goal_id": "g-...",
  "turn_id": 12,
  "step_id": "s-...",
  "plan_revision": 7,
  "candidate_kind": "tool_call",
  "tool_name": "Shell",
  "expected_new_evidence": "reproduce failing auth redirect",
  "target_claims": ["claim-login-regression"],
  "preconditions": ["dev-server-running"],
  "risk_class": "workspace-write-low",
  "budget_snapshot_ref": "b-...",
  "context_projection_hash": "...",
  "model": "...",
  "harness_version": "..."
}

核心是能回答:该动作依据哪个状态、预期产生什么新证据、推进哪个 claim、当时 policy/budget 是什么。

13.4 Policy trace

{
  "type": "policy.decision",
  "tool_call_id": "tc-...",
  "actor": "main-agent",
  "delegation_ref": "cap-...",
  "policy_version": "p-...",
  "normalized_target_hash": "...",
  "effect": "external_write",
  "decision": "ask",
  "rule_id": "git-shared-remote",
  "reason_code": "external_shared_state",
  "approval_scope_offered": "this-ref-only"
}

不要只打 permission_denied=true;否则无法区分正确阻止、过度拒绝和配置缺失。

13.5 Verification trace

{
  "type": "verification.result",
  "verifier_run_id": "v-...",
  "verifier_kind": "integration_test",
  "verifier_version": "...",
  "environment_fingerprint": "...",
  "claims": ["target-fix", "no-double-submit"],
  "result": "pass",
  "coverage": {"target-fix": 1.0, "no-regression": 0.35},
  "evidence_refs": ["artifact://..."],
  "independence": "isolated_process",
  "known_blind_spots": ["third-party-oauth-not-exercised"],
  "duration_ms": 4812
}

13.6 结果指标

主指标应是:

Verified Task Success under explicit budget and risk contract

必须配套:

  • regression-free rate;
  • false-completion rate;
  • human acceptance;
  • destructive/unauthorized incident;
  • rollback/compensation rate;
  • completion latency/cost;
  • unverified completion rate。

13.7 控制过程指标

类别 指标 解释
Planning plan precision、invalidated task rate、replan usefulness plan 是否减少无效搜索
Progress verified progress/step、information gain/cost 行动是否真实推进
Recovery recovery success、time-to-recover、duplicate-effect rate 故障处理是否安全有效
Stop premature stop、late stop、stagnation precision/recall 终止控制是否校准
Policy violation、over-denial、approval burden、decision latency 安全与可用性平衡
Verification claim coverage、oracle disagreement、flake、judge calibration 证据质量
Stability repeat streak、A↔B cycles、plan churn、goal drift 闭环是否振荡
Budget verified success/token/cost/time、verification share 资源效率

单独优化 tool-call 数、steps 或 token 都可能伤害正确性:更少 steps 可能是过早完成,更多 steps 可能是 livelock。

13.8 Planning 的 counterfactual eval

固定同一 checkpoint 做 A/B:

A: reactive
B: explicit static plan
C: receding-horizon plan
D: search + independent verifier

保持模型、tool、context、budget、task 一致,比较:

  • verified success;
  • time/cost;
  • redundant actions;
  • plan invalidation;
  • recovery;
  • failure distribution。

不要只比较最终 pass rate;planning 可能在简单任务上不增分但增成本,也可能只在长 horizon/high-risk cohort 中产生价值。

13.9 Stop detector 的 eval

建立包含这些标签的 trajectory 集:

  • genuine progress;
  • slow but valid progress;
  • exact repetition;
  • semantic repetition;
  • oscillation;
  • blocked;
  • premature completion;
  • impossible/contradictory goal。

测:

stagnation precision/recall
steps saved before hard cap
valid work incorrectly stopped
false completion caught
user escalation quality

Breaker 过强会把难任务切断;过弱会浪费预算。需要按 task horizon、tool latency 和 risk 分层校准。

13.10 Fault injection

控制面测试至少注入:

  • provider 429、5xx、空响应、流中断;
  • tool 执行成功但 receipt 丢失;
  • tool 输出截断和延迟乱序;
  • cancellation 发生在 intent 前、effect 中、receipt 后;
  • policy config 热更新;
  • approval surface 断连;
  • test flaky;
  • workspace 被其他进程修改;
  • compaction 丢一个关键 constraint;
  • repeated identical tool calls;
  • verifier 被 candidate patch 篡改;
  • goal 在 turn 中途被 supersede。

评测的不只是“最后能否恢复”,还要验证 journal、wire、effect uniqueness、budget 和用户可见状态都一致。

13.11 失败归因

每个 failure sample 建议记录:

critical_step
first_incorrect_or_missing_decision
symptom
root_cause
recoverable_at_step
minimal_counterfactual_fix
owner(model|context|planning|policy|tool|runtime|verifier|product)

最终失败发生在 test,不等于 root cause 属于 verifier;也可能是早先错误 plan、stale context 或 tool observation 截断。归因要找 first divergence,不要只给最后一个异常打标签。


14. Kimi Code 公开实现映射:控制理论如何落到真实 harness

本节的实现陈述均为 [SRC]:只描述 29c9e2a 固定快照可确认的事实,并把“源码已有机制”和“面试中可进一步讨论的设计空间”分开。它不能证明 Moonshot 内部服务、未公开分支或未来版本采用相同设计。

14.1 Loop 不是自循环的单体

公开的 AgentLoopService拥有:

  • pending turn FIFO;
  • 每个 turn 的 StepRequestQueue
  • active turn 与 cancellation;
  • step hooks;
  • error-handler registry;
  • loop events、wire persistence 和 telemetry;
  • maxStepsPerTurn enforcement。

源码注释明确强调:loop 本身只 drain requests 和 dispatch errors,不主动 enqueue continuation。 这是一个很好的深模块边界:队列执行机制与“为什么继续”分开。

AgentLoopContinuationService作为 aspect 监听 onDidFinishStep;当 finish reason 为 tool_calls 且没有 stopTurn 时,enqueue continuation。[INFERENCE] 这种拆分允许 continuation policy 独立演进,而不必把 enqueue 原因写进核心 drain loop;“可替换”是接口结构提供的设计可能,不代表公开产品已经运行多个 continuation policy。

14.2 Turn / Step 状态和终止

loop.ts公开类型区分:

  • StepState = queued | running | completed | failed | cancelled
  • turn result:completed | failed | cancelled
  • step finishReason 与 hook stopTurn
  • loop status 与 active trace ID。

核心完成路径是队列无 pending request,或 hook 明确 stopTurn;provider filtered 被转为结构化错误。面试中的进一步追问:turn completed 是否等于用户任务 verified? 答案应是否定的——这是 runtime lifecycle completion,不等于业务 acceptance。

14.3 Step retry 占用正常 step budget

AgentStepRetryService

  • 只 claim isRetryableGenerateError
  • 使用 exponential backoff,并尊重 Retry-After
  • 以 failed driver ID 计连续 attempts;
  • 成功 step 或新 turn 后重置;
  • retry 重新排到队头;
  • retry 像普通 step 一样消费 maxSteps

这个细节很重要:恢复不是“免费旁路”,否则可靠性机制会绕过 budget。

loop_control 配置公开了 maxStepsPerTurnmaxRetriesPerStepmaxRalphIterationsreservedContextSizecompactionTriggerRatio,并支持 step/retry 的 env override。这里能确认的是 schema 与 override;仅凭字段存在,不能推断所有字段都参与同一 loop 路径或生产默认值为何。

14.4 Policy gate 与审批回路

AgentPermissionGate挂在 tool executor 的 pre-execution hook:

  • 运行 permission policy chain;
  • 记录 permission_policy_decision telemetry;
  • approve 可携带 execution metadata;
  • deny/result veto;
  • ask 使用 cold waitUntil factory,避免在其他 listener 已经 veto/pass 时仍启动审批。

AgentToolApprovalService拥有 approval requested/resolved events、session-scope rules、telemetry 和 rejection feedback。对 worker/subagent 的拒绝信息还明确要求不要重试相同调用或绕过限制。

这体现了正确边界:policy 判风险,approval broker 管 authority round-trip,executor 只在裁决后执行。

14.5 Tool dedupe 是一个渐进式稳定器

AgentToolDedupeService做两层处理:

  • 同 step 的相同 call 以 synthetic result 去重;
  • 跨 step 连续重复时逐级注入控制反馈。

公开快照中的阈值:

repeat 3   要求先说清“期望获得什么新信息”
repeat 5   三选一:falsification / missing input / conclude
repeat 8   要求输出最终状态,不再工具调用
repeat 12  force stop

这比“看到重复立即停止”更合理:先改变 controller 的决策条件,再升级到 hard stop。它仍主要检测 canonical tool+args 的重复;更高级的 semantic no-progress、A↔B oscillation 和 acceptance coverage stagnation 是可继续讨论的方向。

14.6 Plan mode 是 first-class artifact 与 effect guard

AgentPlanService通过 wire 管理 plan-mode 状态,向 context 注入 plan mode,把提交的 plan revision 原子写入 agent 自己的 blob scope,并记录 path、SHA-256 和 byte length。它还在 tool pre-execution 边界执行 plan-mode guard:

  • Write/Edit 只允许写当前 plan file;
  • 其他 Write/Edit、TaskStopCronCreateCronDelete 被 veto;
  • auto permission mode 下,ExitPlanMode 被交给 cold review path;只有 execution display 是非空 plan_review 时,才真正发起用户 approval round-trip;
  • 用户可 approve、要求 revise、reject and exit 或 dismiss。

plan.ts公开的 PlanData 只有 id/content/path;因此必须避免过度映射:[SRC] 公开实现确认了 versioned plan artifact、mode lifecycle 和 effect restriction,没有确认本文第 5 章设想的 typed task DAG、precondition、acceptance 或自动 replan 都由 AgentPlanService 原生维护。后者是架构建议,不是 Kimi 源码事实。

14.7 Goal lifecycle 已成为独立 domain

最新公开快照中的 goal/types.ts定义:

  • active | paused | blocked | complete
  • objective 与 completion criterion;
  • token、turn、wall-clock budgets;
  • 使用量、剩余量与 over-budget report。

AgentGoalService把 goal 存进 wire model,处理 replay、fork、deadline、usage accounting、自动 continuation、budget stop、goal tool stale result 和 goal-start review。值得注意的实现判断:

  • replay 出来的 active goal 会被恢复为 paused,避免 crash 后无意继续 effect;
  • budget hard stop 后拒绝更多 tool calls,只允许写最终状态;
  • goal continuation 要求模型每 turn 做 bounded useful slice;
  • complete 必须进行 completion audit;
  • goal 与 turn 分离,允许一个长期 goal 跨多个 turn。

[INFERENCE] 这些结构是从“conversation loop”走向 durable goal runtime 的公开信号;它不能单独证明长目标在任意 crash、tool effect 或分布式执行场景下已经具备 exactly-once 或端到端 durable execution 保证。

14.8 Kimi 中 Verification 的位置

公开实现能确认 tool results、tests/shell/browser 等 evidence 可以回流,goal continuation prompt 也要求 completion audit;但在上述控制面模块中,没有看到一个统一、独立、领域无关的 VerifierService 替所有任务判断 spec。这里应谨慎表述:

  • verification 很可能由模型、工具、repo tests、具体产品 surface 和 eval 系统共同承担;
  • runtime completed 不应被解释成 task verified;
  • 是否要把 claim–evidence、verifier registry、completion gate 做成 first-class service,是设计选择,不应只凭公开仓库推断内部路线。

面试时更好的问题:

当前线上 false-completion 的主要 cohort 是模型没有主动验证、tool evidence 不完整、测试/oracle 覆盖不足,还是 runtime 没把 verification contract 一等化?不同 cohort 的 owner 和改法完全不同。

14.9 Kimi 架构的控制面总结

GoalService         owns durable objective lifecycle and long budget
PlanService         owns plan-mode artifact, revision and effect guard
LoopService         owns admission, turn/step drain, cancellation, state events
Continuation        owns why tool results cause another model step
StepRetry           owns bounded retryable provider recovery
ToolExecutor        owns action execution and receipts/results
PermissionGate      owns risk adjudication before effect
ToolApproval        owns authority round-trip and scoped approval rules
ToolDedupe          owns repetition damping and forced stop
Context/Compaction  owns what state is projected to the model
Telemetry/Wire      owns audit, replay and operational evidence

这正是 Coding Agent Infra 的本质:把模型外的控制责任做成深模块,而不是在 system prompt 里堆更多指令。


15. 2026 前沿证据:哪些已稳,哪些仍需谨慎

15.1 官方公开行为与跨来源收敛判断

Harness 是 agent 行为的一部分

[OFFICIAL] OpenAI 对 Codex loop 的公开拆解把 harness 描述为协调用户、模型和工具的核心执行逻辑,并说明当模型输出 assistant message 时 turn 结束、控制回到用户;这证明的是 loop termination contract,不是任务已经通过独立 verifier。Codex App Server进一步公开 thread persistence、typed item lifecycle、tool execution 和统一 policy model。[INFERENCE] 结合 Kimi 固定源码与这些公开实现,可以高置信得出:Agent 行为由 model+harness 共同决定,跨系统比较不能只报 model name。

长任务需要 generator–evaluator 分离和结构化交接

[OFFICIAL] Anthropic 2026 长任务 harness 实验展示其 frontend/application-development 设置中的 planner/generator/evaluator 分工和跨 context handoff。它是厂商案例,不是独立 benchmark,也不证明所有长任务的最优架构。与 Kimi durable goal/plan artifact、OpenAI versioned plans 交叉看,[INFERENCE] “长任务需要 context 之外的可续接状态和验证”是强收敛信号;“必须使用三 agent 架构”不是。

自动化速度必须匹配自动化验证

[OFFICIAL] OpenAI Harness Engineering是一个内部仓库案例,描述以 automated tests、guardrails、agent review、versioned plans 和 repository legibility 支撑 agent throughput。它不能给出通用因果效应大小;与 verification 研究交叉后可吸收的 [INFERENCE] 是:generation throughput 上升时,约束、验证和垃圾回收必须共同扩容。

公开产品中的 risk-adaptive approval

[OFFICIAL] Running Codex safely at OpenAI公开描述:auto-approval subagent 接收 planned action 与 recent context,例行低风险动作可自动批准;managed network policy 对陌生 domain 要求审批,同时保留 agent-native telemetry。这是 OpenAI 内部部署行为,不是可复现 benchmark,也不能证明“LLM reviewer 本身构成安全边界”。稳健架构解读是:reviewer 提供风险分类,真正边界仍由 sandbox、network policy、allowed modes 和 telemetry 共同组成。

15.2 Codex、Claude Code、pi:frontier harness 机制审计

本节不是产品功能清单,而是一次 控制系统审计。截至 2026-08-03,审计快照为:

系统 审计快照 可见性边界
Codex openai/codex@bb5054f 核心 loop、compaction、goal、steering、multi-agent 源码可核验;服务端模型与部分产品策略不可见
Claude Code anthropics/claude-code@7ef6eec 与官方文档 仓库主要是 changelog、文档和示例,不是核心 runtime 源码;只能确认公开行为,不能还原内部 reducer/scheduler
pi earendil-works/pi@c6eb628 低层 loop、AgentSession、compaction 和扩展接口源码可核验;运行质量仍需 workload 证据

以下额外使用四级证据标记:

  • [SRC]:固定 commit 的源码直接证明;
  • [OFFICIAL]:厂商文档、changelog 或产品说明直接承诺的行为;
  • [INFERENCE]:由多个可见机制支持、但实现没有直接公开的工程判断;
  • [OPEN]:截至快照仍不能由一手资料确认。

先立四条审计纪律:

  1. 开源可见性不等于先进性。 它提高可审计性,不自动提高成功率、稳定性或产品完成度;
  2. 源码存在不等于默认启用。 必须同时看 feature maturity、default、配置和调用路径;
  3. 产品文档不等于内部实现。 “可 steer”“可恢复”不能自动推出 FIFO、exactly-once、durable mailbox 或 crash consistency;
  4. 修过某类 bug 不等于该类 bug 已消失。 Changelog 证明团队看见了 failure mode,不能证明剩余发生率为零。

15.2.1 六个维度的横向结论

维度 Codex Claude Code pi 审计结论
Agent loop [SRC] sampling、tool execution、tool result、pending input、follow-up 和 stop hook 有明确控制路径 [OFFICIAL] 公开 gather context → act → verify → repeat;内部状态机不可见 [SRC] 双层 loop、tool batch、steering/follow-up 顺序可直接读取 三者都已超越单纯 while(tool_call);但只有源码可见系统能审计精确边界
长任务 [SRC] thread goal 持久化、恢复后重建、idle continuation、budget/status accounting [OFFICIAL] session resume、background session、agent view、checkpoint;另有长任务 harness 实验 [SRC] JSONL session tree、resume/fork/compaction;没有内建 durable goal auto-continuation “长对话可恢复”“后台进程仍运行”“目标能自治续跑”是三个不同合同
Steering [SRC] active turn + expected turn ID + pending queue;review/compact turn 拒绝 steer [OFFICIAL] 支持 interrupt、correction、queued/high-priority message;精确 delivery/preemption 语义未公开 [SRC] 当前 assistant turn 和全部 tool calls 完成后,在下一次 LLM request 前注入 steer() 的名字没有价值;关键是 admission、delivery、ordering、preemption、persistence
Compaction [SRC] typed compacted item、保留真实 user input、重注入 canonical context、mid/pre-turn 触发与 telemetry [OFFICIAL] 先清旧 tool output,再总结;重载部分 CLAUDE.md/memory/skills;有 retry/thrash breaker [SRC] recent-span 保留、split-turn/tool-pair 安全、迭代 summary、branch summary、结构化 handoff Compaction 是状态投影/检查点,不是普通“聊天摘要”
Subagent [SRC] registry、depth/concurrency、context fork、mailbox、wait/interrupt;v2 当前不是默认路径 [OFFICIAL] subagent、background agent、agent teams、worktree batch 是不同产品对象;teams 仍 experimental [SRC] 核心刻意不内建 subagent;示例扩展通过独立 pi 进程提供并行/链式模式 spawn 只是入口;还需 topology、budget、isolation、mailbox、join、cancel、merge contract
可恢复性边界 [OPEN] 外部非幂等 effect 的 exactly-once 与完整 crash matrix 不能仅由这些文件证明 [OPEN] 内部 journal、队列持久性、mailbox 交付语义不可见 [SRC] session 可恢复;设计文档明确 in-flight stream 不可恢复、非幂等工具不应盲 retry 恢复 transcript 不等于恢复 execution;恢复 execution 不等于安全重放 effect

不能据此直接排出一个“总冠军”。控制实验至少要固定:同一 model family、同一 repository snapshot、同一工具权限、同一 context/token/time/effect budget、同一 hidden oracle 和同一失败注入。否则测到的是 model、harness、UX、权限和预算的混合效应。

15.2.2 Codex:把 turn、pending input、durable goal 和 agent topology 分层

可验证的 loop contract

[SRC] session/turn.rs显示:一次 model sample 可能产生 function calls 或 assistant output;tool 执行结果进入下一次 sample;只有在模型不要求 follow-up、没有 pending input,且 stop hook 没有要求继续时,turn 才真正结束。普通任务外层还会在 turn 结束后检查 pending input,再决定是否开始新的 pass。

model sample
   | tool calls?
   +-- yes --> execute/drain tools --> persist observations --+
   |                                                    |
   +-- no/assistant output -----------------------------+
                                                        v
                                   model_follow_up OR pending_input?
                                      | yes                  | no
                                      v                      v
                              compact if necessary      stop hook
                                      |                      |
                                      +---- next sample <----+ continue
                                                             |
                                                           finish

这里有一个容易被忽略的细节:pending input 在构造下一次 request 前才 drain;当模型自己的 tool continuation 尚未闭合时,系统可以推迟注入用户输入,避免把异步 steer 插进一个因果链的错误位置。[INFERENCE] 这是比“收到消息立刻拼 prompt”更成熟的做法:steering latency 与 trajectory consistency 需要显式权衡。

Steering 不是取消,也不是任意时点改写 context

[SRC] steer_input只接受 active task;可携带 expected_turn_id,从而拒绝注入已经结束或已经切换的旧 turn。Regular turn 可 steer,Review/Compact turn 明确拒绝。[SRC] input_queue.rs又把 human steer 与 inter-agent mailbox 分开;后者还区分 trigger_turn=true/false

因此需要区分:

steer       = 给当前 causal trajectory 增加下一轮输入
interrupt   = 请求停止当前执行
mailbox     = agent 间投递信息,可只排队,也可触发新 turn
follow-up   = 在目标仍未完成时安排下一次自治执行

[OPEN] 这些路径不能自动证明任意外部 tool effect 可被抢占、回滚或 exactly-once。expected_turn_id 解决 stale admission,不等于解决 effect cancellation。

Compaction 是有生命周期的 history replacement

[SRC] compact.rs和 remote compaction 路径表明,Codex 不只生成一段 summary:它保留预算内的真实用户输入、生成 summary、重新注入 canonical initial/world context、写入 typed CompactedItem/replacement history、重算 usage,并记录 trigger、reason、implementation、phase、status。turn.rs 还区分 pre-turn 与 mid-turn compaction;mid-turn 只在确实仍需 follow-up 且 context 达线时发生。

[SRC] 当前快照中 RemoteCompactionV2 为 stable/default-enabled;这证明当前源码的 feature state,不证明每个历史客户端、企业配置和服务端 rollout 都走同一路径。源码还明确警告多次 compaction 可能降低准确度,因此“能无限续聊”不能被翻译成“语义无损”。

Durable goal 是 conversation 之上的自治状态机

[SRC] ext/goal/runtime.rscontinuation.md给出一种更强的长任务合同:goal 随 thread 持久化,resume 时恢复;thread idle 且 goal active 时可自动继续;目标状态变更与“检查 idle 后启动 turn”共享串行化边界;token/time 在 tool finish、turn stop/abort 等边界记账;turn error 可阻塞 goal,budget 逼近时先 steer 当前 turn 收束,而不是无条件再开一轮。

Continuation prompt 仍包含完整 objective,并要求基于当前状态、逐 requirement 审计完成度和严格判断 blocker。[INFERENCE] 这里真正先进的不是“自动多跑几轮”,而是把:

durable objective
status transition
continuation admission
budget accounting
completion audit

从聊天文本提升为 runtime-owned object。[SRC] 当前快照中 Goals 为 stable/default-enabled;但 [OPEN] 这仍未证明复杂外部 effect 的 crash-safe exactly-once,也未证明 completion audit 对所有 workload 都足够可靠。

Multi-agent v2 的价值在消息语义,不在 agent 数量

[SRC] 当前 v2 handler 支持:full/no/last-N context fork,受限的 model/reasoning override,共享 session registry,depth/concurrency 上限,queue-only send_message,可触发新 turn 的 followup_task,可被 human steer 或 mailbox 唤醒的 wait,以及显式 interrupt_agent。这使“信息到达”和“开始执行”成为不同事件。

[SRC] 但当前 feature registry 中 legacy multi-agent 为 stable/default-on,MultiAgentV2 为 stable/default-off;默认配置不是无限并发,源码默认上限会约束 root/children 和 spawn depth。不能把某个运行环境的高并发 override 写成产品默认能力。

[OPEN] 多 agent 共享 workspace 时,registry/mailbox 并不提供冲突自由的文件合并;必须另行用 worktree、文件所有权、patch queue 或 merge arbitration 解决 write-write conflict。

15.2.3 Claude Code:产品 surface 很强,但内部机制必须诚实标为未知

能确认的是行为合同,而非 reducer 实现

[OFFICIAL] How Claude Code works把核心行为描述为 gather context → take action → verify → repeat,并允许用户在工作中 interrupt/steer。官方 changelog 也持续提及 queued messages、high-priority message、interrupt 和 background task 的修复。

[OPEN] 官方公开仓库不是 runtime source,因此不能由这些文档确认:

  • high-priority 与普通 queued message 的精确 ordering;
  • 已在运行的 tool 能否、何时被抢占;
  • delivery 是否 transactional/durable;
  • provider stream、tool result、user steer 由怎样的 reducer 串行化;
  • crash 后 mailbox 是否 at-most-once、at-least-once 或 exactly-once。

这不是说 Claude Code “落后”,而是说 mechanism-level auditability 较低。产品行为可能更成熟,但证据类型必须正确。

三种“长任务”不要混为一谈

[OFFICIAL] Claude Code 同时公开了:

  1. session resume:JSONL transcript、/resume/continue/compact
  2. agent view/background sessions:terminal detach 后 session 继续运行,可 attach/log/stop,编辑类 dispatch 可进入 isolated worktree;
  3. checkpoint/rewind:对 Claude 做出的文件编辑保存局部快照,但不撤销 Bash side effects 或外部系统变化。

三者分别解决 conversation persistence、process liveness、local edit rollback。它们都不能单独证明 durable goal semantics,也不能安全重放非幂等 API 调用。Anthropic 的长任务 harness 实验展示 planner/generator/evaluator 与结构化 handoff,是有价值的厂商实验;[OPEN] 它不是 Claude Code production runtime 采用同一内部架构的证据。

Compaction 已经显式承认“哪些状态会丢”

[OFFICIAL] Context window 文档glossary说明:系统先清理较旧 tool outputs,再总结 conversation;root CLAUDE.md、unscoped rules 与 auto memory 会重新加载,而 path-scoped rules、nested CLAUDE.md 需要再次读取匹配文件才能恢复;invoked skills 的重注入也受 token cap 和淘汰顺序限制。

这是重要的 frontier 实践:把 compaction 后的不变量和可能丢失项写成产品合同。当前 changelog 还公开了连续 compaction/retry 的 circuit breaker,用来避免 refill thrash。[OPEN] 公开资料没有给出 summary schema、信息保真率、隐藏状态 hash 或可复现 compaction oracle,因此不能称其为“语义无损 checkpoint”。

Subagent、background agent、agent team 是不同拓扑

[OFFICIAL] Agents 文档Subagents 文档把 subagent 定义为单个 session 内的隔离 context worker;agent view管理独立 background sessions;agent teams则是 experimental lead + independent teammate sessions + shared task list + peer mailbox。/batch 另以 worktree-isolated agents 并行产出变更。

截至本快照,changelog 的最新公开行为包括:nested subagents 默认深度 3,以及 concurrent subagent cap 默认 20。它们是产品行为,不等于 scheduler 内部实现。Agent teams 仍需显式启用;teammates 默认也不因“team”而自动获得 worktree isolation,仍需任务分区和 ownership discipline。

因此 Claude Code 显示出的 frontier 重点是 拓扑产品化:同一人机界面区分 delegation、background execution、team coordination 和 isolated batch。[OPEN] mailbox durability、dependency transition 的原子性、跨 worktree merge arbitration 和 cancellation linearizability 仍未由公开资料证明。

15.2.4 pi:最小核心提供清晰 safe point,但把产品责任交给 host/extension

双层 loop 把 steering 和 follow-up 的优先级写死

[SRC] packages/agent/src/agent-loop.ts有两个嵌套循环:inner loop 处理 assistant/tool/steering,outer loop 在当前 turn 无 tool、无 steering 后再消费 follow-up。tool calls 默认可并行;preflight 顺序执行;持久化 tool result 时恢复 source order。shouldStopAfterTurn 是 graceful boundary:assistant、tool batch 与 turn_end 完成后、steering/follow-up poll 前停止,而不是中止在途 stream/tool。

sample
  -> execute complete tool batch
  -> persist results in source order
  -> turn_end
  -> shouldStopAfterTurn?
  -> steering queue
  -> next sample
  -> only when no tool/no steering: follow-up queue

[SRC] packages/agent/README.md明确:streaming 时的 steer 会排队,直到当前 assistant turn 和所有 tool calls 完成,才在下一次 LLM request 前送达;follow-up 更晚。queue 可选择 one-at-a-time 或 all。

这给出了很干净的 safe-point semantics,但 trade-off 也清楚:[SRC] steer 不会抢占正在执行的慢/危险 tool。需要低延迟 abort 的系统,必须把 cancellation token、effect policy 和 tool-specific stop 另做一层,不能只复用 steer。

AgentSession 是当前产品控制面,新的 Harness 文档仍属过渡态

[SRC] AgentSession拥有 persistence、extension integration、retry 和 auto-compaction;streaming 中的新 prompt 必须显式标为 steerfollowUp。auto-compaction 能识别旧 usage,避免 compact 后立即再次 compact;context overflow 只在 compact 后重试一次,再失败就返回可操作错误,防止无限 thrash;manual compact 会先 abort active agent operation。

仓库中的新 AgentHarness 设计把 orchestration 进一步抽象,但其文档仍将 auto-compaction/retry decision points 标为未完成且未迁移就绪。[SRC] 因此审计当前 shipped coding CLI 时应以 AgentSession 为准,不能把 roadmap 当 runtime。

Compaction 对 tool pair、分支和 handoff 有明确结构

[SRC] Compaction 文档给出默认 reserve/keep-recent budget、迭代 summary、split-turn handling 和 branch summarization。它不会从 tool result 中间切断 call/result pair;结构化 summary 包含 Goal、Constraints、Progress、Key Decisions、Next Steps、Critical Context,并累积已读/已修改文件。/tree 切换分支时还可用 branch summary 保留被放弃 trajectory 的必要信息。

[INFERENCE] 这比“摘要最后 N 条消息”强,因为它保留因果配对和跨 branch handoff;但 [OPEN] summary 仍是有损模型生成物,源码没有提供任务无关的完备性证明。

“没有内建 subagent”是边界选择,不是功能遗漏的简单同义词

[SRC] coding-agent README明确把 no built-in subagents、no plan mode、no permission popups、no background bash 作为最小核心哲学;通过 extension/package/tmux 组合能力。官方 subagent example以独立 pi subprocess 实现单任务、并行、链式执行、streaming、usage 和 abort。

因此不能说“pi 已内建成熟 multi-agent runtime”。示例证明 extension surface 足以构建它,不证明 core 提供 durable mailbox、crash recovery、global budget、workspace isolation 或 conflict-free merge。相反,最小核心的优势是 ownership 清楚,代价是 host 必须承担这些系统责任。

[SRC] Durable harness 设计笔记也明确指出:runtime JS dependencies 需重建、in-flight provider stream 不可恢复、非幂等 tools 不应自动重试。该文件是设计/未来方向,不应包装成已经 shipping 的 durable execution。

15.2.5 从三个系统真正应该吸收的 frontier 原则

原则一:conversation turn 与 durable work 必须是两个对象
ConversationTurn
  - user/model/tool causal exchange
  - short-lived cancellation boundary

DurableWork
  - objective/spec/status/budget
  - continuation admission
  - checkpoint/reconciliation
  - verified completion

Codex goal 最接近第二层;Claude background session 强在 process/product lifecycle;pi 强在透明的 session/loop primitive。它们解决的是不同问题,不能用一个“支持长任务”布尔值表示。

原则二:Steering 必须定义五件事
  1. Admission:当前是否有可 steer 的 execution,如何拒绝 stale turn;
  2. Delivery boundary:provider stream 中、tool batch 后、turn_end 后还是下个 turn;
  3. Ordering:human steer、tool result、agent mailbox、follow-up 谁先;
  4. Preemption:是否取消 model stream、在途 tool 或仅影响下一次 request;
  5. Persistence:crash/resume 后 queued input 是否仍在,交付语义是什么。

没有这五项,steer() 只是 UI 动词,不是 infra contract。

原则三:Compaction 应当是 versioned reducer/checkpoint

一个成熟 compactor 至少要保存:

  • canonical goal/spec 与 authority decisions;
  • unresolved blockers、pending approvals、budget 和 active plan state;
  • tool call/result pairing、effect intent/receipt 和 unknown-effect reconciliation;
  • verified facts 与 provenance,而不只保存 model narrative;
  • branch/abandoned decision 及原因;
  • 被保留、被重注入、可能丢失的字段说明;
  • compaction trigger/reason/version/input hash/output hash/quality telemetry。

Codex 的 typed lifecycle、Claude 的重注入/丢失合同、pi 的 tool-pair/branch-aware summary 分别覆盖了其中不同部分,没有任何一个公开证据足以证明“无限 context 且零语义损失”。

原则四:Subagent runtime 的最小完备合同远大于 spawn
Topology       parent/child/team/independent session
Context        full/none/selected history + provenance
Authority      tool/permission/model/budget delegation
Workspace      shared ownership or isolated worktree
Messaging      queue/trigger/priority/delivery semantics
Join           wait/timeout/partial result/completion envelope
Cancellation   cooperative stop vs process kill vs effect reconciliation
Recovery       registry/mailbox/task state durability
Merge          patch ownership/conflict resolution/verification

Codex v2 更接近 scheduler primitive;Claude Code 更接近完整产品 topology;pi 更接近可组合 process primitive。[INFERENCE] 对 Kimi 最值得吸收的不是照搬某个 UI,而是把这八类合同变成 typed interfaces 和 trace events。

原则五:停止、完成、验证必须分开

三套系统都能决定“这一轮不再继续”,但这与“用户目标已满足”不是一回事:

loop_stop_reason
    != durable_work_status
    != verification_result
    != authority_acceptance

真正 frontier 的 harness 应允许:assistant 已结束但 verifier 要求继续;process 仍在后台但 goal 已 blocked;subagents 全部返回但 merge 未验证;compaction 成功但关键 authority instruction 已丢失风险上升。停止条件是 controller 状态,不是模型最后一句话。

15.2.6 仍然必须诚实保留的未知项

系统 不能由当前一手资料证明的关键事项
Codex 非幂等外部 effect 的 exactly-once;所有产品 surface 是否统一走 v2 multi-agent;多次 compaction 的语义保真率;共享 workspace 的自动 merge safety
Claude Code 内部 event reducer;steer/tool/mailbox 精确 ordering 与 durability;compaction schema/quality oracle;team dependency 更新和 cancellation 的原子性
pi core-level durable goal auto-continuation;crash 后 in-flight queue/tool recovery;内建 multi-agent registry/mailbox/isolation;extension 组合后的全局 budget 与 policy 一致性
三者共同 在固定 model、权限、预算和 oracle 下,谁在长任务、动态 steering、context rollover、并行冲突和 fault injection 上具有统计显著优势

面试中最高质量的回答不是“某产品最先进”,而是:

我会先把 loop、durable work、steering、compaction、delegation 的合同拆开,再用相同模型、工具、预算和 fault matrix 做 replayable evaluation。开源决定我能审计到哪一层,产品体验决定用户能否有效操控,最终 verified outcome 才决定系统是否更强;三者不能互相替代。

15.3 2026 最新但应视为研究信号

证据 状态 新信息 应如何使用 不能直接外推
Progress Mirage PREPRINT, preregistered pilot 在其 54-cycle 设置中,自评与 out-of-band world-state delta 严重脱节 外部 oracle、progress delta、breaker 56% 不是行业失败率
Verification Horizon PREPRINT v2 作者提出 scalability/faithfulness/robustness 三维与 verifier co-evolution verifier audit、反 reward hacking “无固定 reward 长期有效”仍是研究主张
SWE-Review PREPRINT v1 在其 benchmark 中,agentic review 提升后续 revision 闭环 review trajectory/eval reviewer accept 不是最终 oracle
Structured Feedback PREPRINT v1, 50 paired TextWorld games actionable repair feedback 优于 raw diagnostic;JSON 本身未显优势 typed failure semantics 不能外推到 repo-scale/frontier model 绝对增益
ICAE-Bench PREPRINT v1 用 grounded hidden constraints 与 interactive user simulation 评测模糊需求处理 intent/spec clarification eval user simulator 仍不等于真实用户
AgentFlow PEER, ICLR 2026 Oral planner/executor/verifier/generator 组成可训练 multi-turn MDP trajectory-level controller training 不是公开 Coding Agent 产品架构证据
VeriMAP PEER, EACL 2026 plan decomposition 同时产生 passing criteria/VFs verification-aware planning 自动 VF 仍可能偏离真实 intent
Security-aware planning PREPRINT 特定 IFC+benchmark 下提升安全条件内的自治 policy-aware search planning 不能替代 enforcement
Hedwig PEER, ACM CAIS 2026 demo;survey n=21 CLI prototype 根据 oversight feedback 调整 autonomy scoped earned trust 的交互设计 不能泛化为生产效果、永久提权或安全证明
Agent UQ PEER, ACL 2026 agent UQ 涉及 trajectory、环境和交互动态 分类型 uncertainty、校准研究 尚无单一成熟通用指标

15.4 三条反直觉判断

  1. [INFERENCE] 更长 planning 不一定更可靠。 环境反馈密集时,远期计划更适合暴露依赖,而不应成为不可修订脚本;目前没有跨开放 coding workload 的统一最优 horizon。
  2. [INFERENCE] 更多 reflection 不一定减少错误。 没有新外部 evidence 的 reflection 仍共享原信息边界;它可能修正表达,也可能强化错误叙事,效果取决于 feedback grounding。
  3. [OPEN] 更强 generator 是否系统性增加 verification 难度,尚不能用单个研究定量。 Verification Horizon 和 reward-hacking 文献给出结构性风险,但“generator 越强必然越难验证”不是定理。工程上应持续测 policy capability 与 verifier error/coverage 的相对变化。

15.5 当前仍未解决的问题

  • 如何定义跨开放任务通用且不易被 gaming 的 progress signal;
  • 如何对长 horizon 的 verifier coverage 做可计算估计;
  • 如何在不暴露 hidden oracle 的情况下给 agent 足够可操作 feedback;
  • 如何校准 trajectory-level uncertainty;
  • 如何证明 policy、delegation 和 memory/compaction 后仍保持信息流约束;
  • 如何在并行 agents 中避免相关错误和共享 verifier saturation;
  • 如何让 goal/spec 在用户不断修订时保持 versioned causal history;
  • 如何把人类 oversight 放在最有规范性价值、而非最频繁的位置。

16. 二十组面试深追问与专家回答骨架

这些不是背诵答案。每组都沿“定义 → 机制 → trade-off → failure → evidence → Kimi 映射”展开,面试官可以从任一点继续追。

16.1 为什么 Agent Loop 不能只是 while(true)

主问题

设计一个可取消、可恢复、有限预算的 Coding Agent Loop。

深追问

  1. 模型没有 tool call 时为什么不能直接认为任务完成?
  2. 中途 crash 后从哪里 resume,哪些 tool 可以 replay?
  3. turn、step、tool attempt 应怎样区分?

回答骨架

  • 先定义三层/四层 lifecycle 和显式状态机;
  • admission → context → inference → decision validation → policy → effect → observation → verification;
  • intent-before-effect、receipt-after-effect、unknown effect reconciliation;
  • cancellation 与 rollback 分离;
  • completed runtime turnverified task success 分离;
  • step/turn/token/effect 等向量预算;
  • journal + reducer 恢复,非幂等工具不盲 replay。

高质量收束

Loop 的价值不是重复调用模型,而是保存“下一动作为什么合法、发生了什么、凭什么继续或停止”的控制语义。


16.2 OODA 中最难的是哪一步?

主问题

Observe、Orient、Decide、Act、Evaluate 各自如何落到 Coding Agent?

深追问

  1. Observe 和 Evaluate 有何本质区别?
  2. Orient 为什么不能只靠把 tool output 丢回 context?
  3. 如果 observation stale,系统如何知道?

回答骨架

  • Observe 产 typed evidence;Evaluate 把 evidence 对齐 claims/spec;
  • Orient 负责 provenance、freshness、contradiction、belief/plan delta;
  • context 是状态投影,不是状态本身;
  • 用 version/fingerprint/timestamp/truncation metadata;
  • 动作前重新确认高风险 preconditions;
  • external state delta 驱动 progress,而非模型叙事。

16.3 Goal、Spec、Subgoal、Task、Plan 为什么要分开?

主问题

给定“修复登录问题”,怎样建立控制对象?

深追问

  1. Plan item 全 done 是否足够?
  2. 用户改变需求时修改 goal 还是 spec?
  3. completion criterion 应属于哪里?

回答骨架

  • Goal 是 desired state change;spec 是 admissible outcome set;
  • subgoal 是中间谓词;task 是有 owner/state/evidence 的 work unit;
  • plan 是当前路线假设,必须可失效;
  • completion criteria 是 evidence spec 的一部分,也可被 goal snapshot 引用;
  • 用户修改要形成 versioned authority event;
  • task executedverified 分开。

反例

如果把 plan 当 spec,模型为了“完成计划”会保留已经被新证据推翻的步骤;如果把 goal 当 task,跨 turn 状态和预算无法表达。


16.4 什么情况下选 ReAct,什么情况下选显式 planning?

主问题

Reactive loop 和 plan-and-execute 的取舍是什么?

深追问

  1. 长任务一定先做完整 plan 吗?
  2. 怎样量化 planning 是否有价值?
  3. 为什么 receding horizon 往往比静态 plan 稳?

回答骨架

  • 用 horizon、feedback latency、reversibility、dependency、risk、parallelism 判断;
  • 低风险即时反馈用 ReAct;跨模块/高风险用 hierarchical plan;
  • 真实环境易变化时用 receding horizon,只执行下一 bounded slice;
  • A/B 固定 model/tool/context/budget;比较 verified success、redundancy、plan invalidation、cost;
  • planning 的价值是减少搜索、暴露依赖/风险/验收,不是生成更多文本。

16.5 Plan 什么时候应该失效?

主问题

如何维护一个长任务 plan 而不让它过时或频繁抖动?

深追问

  1. 每个 observation 后都 replan 是否更自适应?
  2. 怎样避免 A/B 两套方案来回切?
  3. 如何保存已放弃分支?

回答骨架

  • 定义 replan triggers:关键假设被证伪、precondition/依赖/policy/budget 改变;
  • 局部 subtree repair 优先;
  • hysteresis、minimum commitment、switching cost、cooldown;
  • stable plan item ID + versioned delta;
  • branch tombstone 保留 abandoned reason/evidence;
  • goal/spec 和 verified evidence 是 plan revision 不可随意改变的不变量。

16.6 Tree/Graph/MCTS 搜索如何用于真实 Coding Agent?

主问题

如果让 Agent 同时探索多个修复方案,怎样设计?

深追问

  1. 真实 tool effect 可以作为搜索树节点回溯吗?
  2. 分支怎样隔离 workspace?
  3. 同一模型生成并打分多个分支有什么问题?

回答骨架

  • 搜索优先发生在 reasoning、patch、worktree、sandbox、simulation;
  • 外部不可逆 effect 不具备普通 backtracking 语义;
  • 每 branch 有 environment snapshot、budget、artifact、trace;
  • 用独立 tests/oracle 评分,不能只用同模型 self-value;
  • 相关错误、branch contamination、search cost 与 verification saturation;
  • 最终 merge 前在 canonical workspace 重放并全量验证。

16.7 Reflection 和 Critic 为什么经常无效?

主问题

加一个 reviewer/critic 是否就能显著提升可靠性?

深追问

  1. 同模型自评有什么偏差?
  2. 反思应该存 memory 吗?
  3. critic disagreement 如何解决?

回答骨架

  • reflection 必须建立在新 feedback 上,否则是 correlated narrative;
  • 拆 evidence、diagnosis hypothesis、next falsification;
  • memory 只把被证实的策略与来源/适用范围持久化,不能把猜测固化;
  • critic 独立性分同 context、fresh context、different model、external oracle;
  • disagreement 触发具体 counterexample/test,不靠第三个 judge 无限投票;
  • reviewer feedback 后必须 revision + re-verification 才闭环。

16.8 Retry、Recover、Replan、Fallback 有什么区别?

主问题

Provider、工具和 verifier 都失败时,Loop 怎样决定下一步?

深追问

  1. HTTP 500 是否总能 retry?
  2. 多层 retry 为什么危险?
  3. failover 到另一个模型有什么语义风险?

回答骨架

  • 先按 boundary、effect certainty、recoverability 三轴分类;
  • retry 是相同语义 attempt,replan 改路线,fallback 降能力,failover 换等价服务;
  • 只有 transient + safe replay/idempotency + budget 才自动 retry;
  • 多层 retry attempt 数乘法放大,必须单一 owner 与共享 deadline;
  • 模型 failover 要检查 tool protocol、thinking preservation、context window、finish reason、token accounting;
  • error event 带 owner、effect certainty、stable code。

16.9 请求超时后如何避免重复副作用?

主问题

Agent 发出一个外部写请求后连接断开,应当怎样恢复?

深追问

  1. idempotency key 足够吗?
  2. 如果服务端不支持查询状态呢?
  3. cancellation 正好发生在 commit 后怎么办?

回答骨架

  • intent 持久化在 effect 前,含 effect ID/idempotency key;
  • 连接错误产生 UNKNOWN,进入 reconciliation,不直接重放;
  • 查 status endpoint、远端资源、event log 或 effect receipt;
  • key 需要服务端真正去重、scope 和 retention;客户端自带字符串不构成幂等;
  • 不可查询/不可幂等的高风险 tool 默认不自动 retry,升级 authority;
  • cancel 不等于未发生,最终报告 partial/unknown effect。

16.10 怎样定义任务“完成”?

主问题

模型已经修改代码并说完成,runtime 要不要结束?

深追问

  1. 所有测试通过为何仍可能不完成?
  2. 无法运行测试时怎么办?
  3. 谁拥有最终 completion authority?

回答骨架

  • runtime 可以结束当前 step/turn,但 goal completion 需要 claim–evidence;
  • tests 可能覆盖不足、broken、被修改、环境错误;
  • goal/spec claims、counterevidence、effect reconciliation、artifact persistence;
  • 无法验证时返回 completed_unverified 或 blocked,不伪装 verified;
  • 规范性/不可逆接受归用户或合法 authority,机械事实由 oracle;
  • verifier strength 按 risk 调整。

16.11 怎样检测“有动作但无进展”?

主问题

如何阻止 Agent 在同一个问题上无限打转?

深追问

  1. 只做 tool+args dedupe 有什么漏网?
  2. 长时间编译会被误判 stagnation 吗?
  3. hard stop 前应怎样干预?

回答骨架

  • exact fingerprint + semantic action/observation + belief/plan/evidence delta;
  • 检测 A↔B cycle、acceptance coverage stagnation、information gain/cost;
  • tool-specific expected duration 和 heartbeat 防误判;
  • 渐进式:声明新信息 → falsification → replan/missing input → final status → hard stop;
  • 测 detector precision/recall 和 valid work interrupted;
  • Kimi public dedupe 3/5/8/12 是实际渐进设计例子。

16.12 Budget 应怎样设计?

主问题

有了 max_steps 为什么仍不够?

深追问

  1. retry 是否计入 step budget?
  2. 临近 budget 时如何保证验证?
  3. 并行 subagents 如何共享预算?

回答骨架

  • budget 是 step/turn/token/time/cost/tool/effect/approval/fanout 向量;
  • retry/recovery 必须计费;
  • 父预算切 slice,不能每个子 agent 认为自己有全额;
  • 预留 verification、reconciliation、cleanup emergency reserve;
  • soft threshold 做 gain scheduling,hard cap 禁止新 effect;
  • 指标看 verified success per cost,不追求最低 token。

16.13 为什么 Policy Gate 必须在模型外?

主问题

System prompt 已写“不要执行危险命令”,还需要什么?

深追问

  1. Policy 只按 tool name 判断够吗?
  2. repo 中的恶意指令如何影响 tool call?
  3. askdeny 和 synthetic result 怎样选择?

回答骨架

  • prompt 是概率引导,gate 是 capability enforcement;
  • 输入包含 identity、delegation、normalized args、realpath、provenance、effect、blast radius、reversibility;
  • capability attenuation + information-flow policy;
  • deny 形成约束,模型不得通过替代工具绕过;
  • ask 针对具体 effect/scope;
  • synthetic result 适合 policy-owned no-execution path;
  • policy-aware planning 提升 utility,但执行前仍重新授权。

16.14 如何平衡 approval fatigue 与安全?

主问题

如果每个 shell command 都弹窗,用户会全部点击同意;怎么办?

深追问

  1. 是否应学习用户过去的批准并永久自动放行?
  2. session approval 缓存什么?
  3. 自主性可以动态提升吗?

回答骨架

  • 先缩小 sandbox/capability,不靠更多 prompts;
  • 缓存具体 resource/effect pattern,带 scope、expiry、policy version、authority;
  • familiar low-risk behavior 可减少摩擦,超出 scope 收紧;
  • preference memory 不等于 security grant;
  • approval burden 是 eval/budget;
  • 人审聚焦规范性/不可逆决策,确定性低风险规则自动化。

16.15 你会怎样建立 Verification Hierarchy?

主问题

Coding Agent 的验证从哪一层开始,何时升级?

深追问

  1. typecheck、test、browser、LLM judge 哪个更权威?
  2. 怎样验证 tests 本身没有被 gaming?
  3. 如何控制 verification cost?

回答骨架

  • 先把 spec 拆 claims;为每个 claim 选择最适 verifier;
  • static/invariant → unit → integration/runtime → simulation/oracle → judge → human;
  • 层级按 claim,不是全局 ranking;
  • isolated/held-out oracle、test diff、mutation/counterexample、environment fingerprint;
  • claim–evidence matrix 找 coverage gap;
  • 按风险和边际 coverage/cost 升级。

16.16 LLM Judge 如何校准?

主问题

UI 品质或代码设计难用 deterministic tests,怎样让 LLM judge 可用?

深追问

  1. 同一个模型当 generator 和 judge 可以吗?
  2. 多 judge 投票是否解决偏差?
  3. judge 何时 abstain?

回答骨架

  • 显式 rubric、blind ordering、fresh context、固定 version;
  • calibration set 对齐专家标注,测 precision/recall、rank consistency、subgroup bias;
  • 不同模型降低相关偏差但不产生真实 oracle;
  • judge 必须输出 claim-level evidence、uncertainty 和 abstain;
  • 高风险或 disagreement 交给 human/domain oracle;
  • 持续监控 judge–user acceptance gap。

16.17 怎样解释 Agent Loop 的稳定性?

主问题

“闭环稳定”在 LLM Agent 中是什么意思?

深追问

  1. 能给 LLM Agent 做数学稳定证明吗?
  2. 什么是 Agent 的 overshoot/chattering?
  3. 怎样设计 progress function?

回答骨架

  • 不承诺普遍数学证明;定义 safety、boundedness、liveness、convergence、recoverability、non-oscillation;
  • 用 weighted unmet verified constraints 等 heuristic potential V
  • 只有外部证据能降低 V
  • high gain 导致 flaky test 推翻全局计划,low gain 导致坚持错误路线;
  • hysteresis、local update、commitment window、freshness、write serialization;
  • trace 监控 cycle、plan churn、goal drift。

16.18 怎样评测 Loop 改动而不是只看最终 benchmark?

主问题

你给 loop 加了 planning/verification/retry,怎样证明它真的更好?

深追问

  1. pass rate 提升是否足够?
  2. 如何区分 model 与 harness 的责任?
  3. 线上 trace 如何转成 eval?

回答骨架

  • Evaluation Card 固定 model、harness、tool、budget、timeout、environment;
  • outcome:verified success、regression、false completion、incident、acceptance;
  • process:redundancy、replan usefulness、recovery、approval、stability、cost;
  • checkpoint replay 和 component ablation;
  • 找 first divergence 与 minimal counterfactual fix;
  • 线上 trace 按 failure cohort 脱敏抽样,构造可重放 scenario/fault injection。

16.19 Kimi Code 的 Loop 与 Plan 边界有什么值得讨论?

主问题

从公开源码看,Kimi Code 如何组织 loop、plan mode、continuation、retry 和 permission?

深追问

  1. 为什么 loop 自己不 enqueue continuation 是好设计?
  2. retry 为什么要消费 max steps?
  3. tool dedupe 的渐进反馈优于立即 hard stop 在哪里?
  4. AgentPlanService 是否等于一个动态 planner?

回答骨架

  • AgentLoopService 只 drain queue、dispatch error;机制与 policy 分离;
  • AgentPlanService 管 versioned plan artifact、plan-mode lifecycle 与 effect guard;公开 contract 不包含 task DAG 或自动 replan,不能把 plan mode 直接等同 planner algorithm;
  • continuation aspect 根据 tool_calls enqueue;
  • retry plugin 只 claim retryable provider error、尊重 backoff、进入普通 step accounting;
  • permission gate 在 tool pre-execution hook,approval 是独立 round-trip;
  • dedupe 阈值逐步从 novelty/falsification 引导升级到 force stop;
  • 进一步设计问题:semantic stagnation、claim-level verifier、goal completion 与 turn completion 的连接。

16.20 现场系统设计:为 Kimi 设计“可验证长任务控制面”

主问题

设计一个让 Coding Agent 跨多个 context/turn 完成长任务、可恢复且不伪完成的系统。

深追问

  1. 服务重启后怎样保证不重复执行外部 effect?
  2. compaction 后怎样防 goal/spec/verification drift?
  3. 同时运行多个 candidate branch 时如何选择?
  4. 用户何时介入?

回答骨架

Goal domain
  versioned objective/spec/completion claims/budgets

Control runtime
  turn admission + step queue + receding-horizon planner
  typed state + append-only journal + reducer/checkpoints

Action plane
  normalized tool contracts + policy gate + sandbox
  intent/effect/receipt + idempotency/reconciliation

Evidence plane
  artifact store + verifier registry + claim-evidence graph
  isolated deterministic oracle first, judge/human where needed

Stability plane
  no-progress/oscillation detection + bounded retry + stop taxonomy

Observability
  goal/turn/step/tool/effect/verifier IDs + budget + decision branch

权衡要明确:

  • plan 不持有真实世界真值,journal/evidence 才持有;
  • branch search 只在 isolated state 做,最终 canonical replay;
  • compaction 保存 typed invariants,不靠摘要记忆全部控制状态;
  • user 介入规范性歧义、高风险 effect 和 weak-verifier acceptance;
  • hard budget 到达后只留 reconciliation/verification/finalization reserve;
  • success 是 claim coverage 足够,而不是 agent 停止说话。

最终收束

我会把 Model 看作 stochastic proposer,把 Agent Infra 做成 evidence-driven controller。性能的上限来自模型,系统是否稳定、可控、可验证,主要取决于 model 之外的状态、policy、effect 和 verifier contract。


17. 知识闭环检查

如果真正掌握本 Part,应能在不依赖框架名的情况下回答:

  • 为什么 model response、decision、action、effect、observation、verification 是六个不同对象;
  • 为什么 runtime turn completed 不等于 goal verified;
  • Goal/spec/subgoal/task/plan 的所有权、版本和失效语义;
  • ReAct、static plan、receding horizon、tree/graph search 的适用边界;
  • 为什么真实不可逆 effect 不能当普通搜索树节点回溯;
  • reflection 在没有新外部 evidence 时为何可能放大自洽偏差;
  • retry/recover/reconcile/replan/fallback/failover/rollback/escalate 的区别;
  • 如何用 intent、receipt、idempotency 和 reconciliation 处理 unknown effect;
  • 为什么 stop conditions 与 correct action selection 同等重要;
  • 如何检测 exact repeat、semantic stagnation、A↔B oscillation 和 slow valid progress;
  • 如何切分 goal/turn/step/subagent budgets 并预留 verification;
  • prompt policy 与 runtime policy 的边界;
  • policy gate 为什么必须看到 normalized args、identity、provenance 和 effect;
  • verification hierarchy 每层能证明和不能证明什么;
  • 如何校准 LLM judge,并知道它何时应该 abstain;
  • 如何把 uncertainty 类型映射成 observation、simulation、approval 或 human decision;
  • bounded adaptive autonomy 为什么不等于自动永久提权;
  • 如何定义闭环 safety、boundedness、liveness、convergence 和 non-oscillation;
  • trace 如何定位 first divergence 而不是只记录最后 error;
  • Kimi 公开实现中 loop、plan、continuation、retry、permission、dedupe、goal 的真实 ownership,以及哪些只是本文的架构建议。

18. 一手资料索引

基础范式

2026 同行评议的 Planning / Reasoning

2026 Agent Loop、验证与自治

Frontier harness 一手工程资料

Codex 精确源码快照(bb5054f,2026-08-03)

Claude Code 官方产品资料与 changelog 快照

pi 精确源码快照(c6eb628,2026-08-03)

Kimi Code 精确源码快照(29c9e2a,2026-08-03)


19. 最终心智模型

                    User / Authority
                     goal + spec
                          |
                          v
              +------------------------+
              |  Task Model / Planner  |
              | belief, subgoals, plan |
              +-----------+------------+
                          | candidate decision
                          v
                +---------+---------+
                |   Policy Gate     |
                | identity/effect   |
                +----+----------+---+
                     |          |
                approve       ask/deny
                     |          |
                     v          v
              +------+-----+  Authority
              |  Executor  |
              | intent/effect/receipt
              +------+-----+
                     | observation
                     v
              +------+----------------+
              | Evidence + Verifiers  |
              | claim coverage/oracle |
              +------+----------------+
                     | progress/counterevidence
                     v
              +------+----------------+
              | Closed-loop Controller|
              | replan/retry/stop     |
              | budget/stability      |
              +-----------------------+

最关键的所有权边界:

Model proposes.
Policy authorizes.
Executor effects.
Journal remembers.
Verifier establishes evidence.
Controller decides whether to continue.
Authority owns normative acceptance.

只要这七句话仍然清楚,模型、planner 算法、工具协议和产品 surface 都可以快速演进,而系统不会退化成不可控的 prompt 拼装。

⌘ K

搜索术语、机制、故障或面试问题