跳到主内容
@wquguru
精选88MarkTechPost(RSS)技巧与观点

Harness机制解析:4种方案解决长任务上下文溢出与目标丢失

Context Engineering Inside the Harness: 4 Mechanisms That Beat Context Overflow and Goal Loss on Long-Horizon Tasks

原文
发到 X
推荐理由

Agent工程师必读,文中给出了各主流框架处理长上下文的具体阈值与代码级配置,直接指导工程落地。

An agent, in its simplest form, is an LLM calling tools in a loop. That loop works for short jobs. Give it a task that runs for an hour and 200 tool calls, and it breaks in 2 predictable ways. The AWS Samples design guide for autonomous cloud coding agents names them directly: shallow agents suffer from context overflow, get distracted (goal loss), and do not maintain state over long periods. The layer that fixes this is not the model. It is the harness, which AWS describes as managing everything but the model.

智能体(Agent)最简单的形式,就是在一个循环中调用工具的 LLM。这个循环适用于短任务。如果给它一个运行一小时、包含 200 次工具调用的任务,它就会以两种可预测的方式崩溃。AWS 自主云编码智能体的设计指南直接指出了这些问题:浅层智能体会因上下文溢出而失效,容易分心(目标丢失),并且无法在长时间内维持状态。解决这一问题的层级不是模型本身,而是“Harness”(框架/支撑结构),AWS 将其描述为管理除模型之外的一切内容。

This article opens up that layer. Compaction, memory strategy, context budgeting, and todo-state are the machinery that turns a shallow loop into a deep agent. We look at how LangChain Deep Agents, Claude Code, Manus, OpenAI Codex, and Amazon Bedrock AgentCore implement each one, with the actual thresholds they ship.

本文深入探讨了这个层级。压缩(Compaction)、记忆策略、上下文预算管理和待办状态(todo-state)是将浅层循环转化为深层智能体的核心机制。我们考察了 LangChain Deep Agents、Claude Code、Manus、OpenAI Codex 和 Amazon Bedrock AgentCore 如何分别实现这些机制,以及它们实际交付使用的具体阈值。

Why a bigger window does not fix it

为什么更大的窗口并不能解决问题

The obvious fix is a larger context window. The evidence says it helps less than expected. Chroma’s Context Rot report evaluated 18 LLMs, including GPT-4.1, Claude 4, Gemini 2.5, and Qwen3, and found that performance grows increasingly unreliable as input length grows, even on simple retrieval tasks. Anthropic’s context engineering guide explains the mechanism: attention creates n² pairwise relationships for n tokens, so every added token depletes a finite “attention budget.” Context is a resource with diminishing returns, not a bucket.

显而易见的解决方案是更大的上下文窗口。但证据表明,其效果不如预期。Chroma 的《上下文旋转报告》评估了包括 GPT-4.1、Claude 4、Gemini 2.5 和 Qwen3 在内的 18 个 LLM,发现随着输入长度的增加,性能变得越来越不可靠,即使在简单的检索任务上也是如此。Anthropic 的上下文工程指南解释了其机制:注意力机制会为 n 个 token 创建 n² 对两两关系,因此每增加一个 token 都会消耗有限的“注意力预算”。上下文是一种具有边际递减效应的资源,而不是一个无底洞。

For an agent loop, this is worse than it sounds. Manus reports that a typical task needs around 50 tool calls, and that the input-to-output token ratio runs near 100:1. Each observation lands in context and stays there. The original instruction drifts toward the middle of the window, which is exactly where recall degrades. Goal loss is not only a model bug. It is the expected outcome of an unmanaged context on a long enough task.

对于智能体循环而言,情况比听起来更糟。Manus 报告称,典型任务大约需要 50 次工具调用,且输入到输出的 token 比例接近 100:1。每次观察结果都会进入上下文并留在那里。原始指令会逐渐漂移至窗口的中间位置,而这正是召回率下降的区域。目标丢失不仅仅是模型的缺陷。它是长时间任务中未管理的上下文所导致的必然结果。

Mechanism 1: Context budgeting and offloading

机制一:上下文预算管理与卸载

The first job of a harness is deciding what never enters the window at all. Deep Agents ships 2 offloading rules with hard numbers. When a tool response exceeds 20,000 tokens, it is written to the filesystem and replaced with a file path plus a preview of the first 10 lines. When session context crosses 85% of the model’s window, older write and edit tool calls, whose full file contents already live on disk, are truncated to a pointer. Only after offloading runs out of room does the harness fall back to summarization.

Harness 的首要工作是决定哪些内容根本不应进入上下文窗口。Deep Agents 提供了两条带有具体数值的卸载规则。当工具响应超过 20,000 个 token 时,它会被写入文件系统,并被替换为文件路径加上前 10 行的预览。当会话上下文达到模型窗口的 85% 时,那些完整文件内容已存在于磁盘上的旧版写入和编辑工具调用会被截断为指针。只有在卸载机制耗尽空间后,Harness 才会回退到摘要生成。

Claude Code applies the same budgeting to what loads before the first prompt. Auto memory is capped at the first 200 lines or 25KB. MCP tool schemas stay deferred by default, with only tool names listed, and full schemas load on demand via tool search. After compaction, any re-read file over 5,000 tokens comes back as a path reference rather than content. The context window simulation in the Claude Code docs makes the payoff concrete: a research subagent reads 6,100 tokens of files and returns a 420-token result to the parent.

Claude Code 对首次提示符之前加载的内容应用相同的预算限制。自动记忆功能上限为前 200 行或 25KB。MCP 工具模式默认保持延迟加载,仅列出工具名称,完整模式通过工具搜索按需加载。压缩后,任何重新读取的超过 5,000 token 的文件将以路径引用而非内容形式返回。Claude Code 文档中的上下文窗口模拟展示了具体收益:一个研究子代理读取了 6,100 token 的文件,并向父代理返回了 420 token 的结果。

That subagent pattern is budgeting at the architecture level. Anthropic’s guide notes that each subagent may burn tens of thousands of tokens exploring, but returns a distilled summary, often 1,000 to 2,000 tokens. The AWS AgentCore walkthrough builds exactly this: a coordinator spawns 3 browser subagents in parallel, each in its own MicroVM, and an analyst subagent receives only their structured findings. AWS reports a 4 to 6 minute expected runtime, and notes that sequential processing would take up to 3x longer.

这种子代理模式是在架构层面进行预算控制。Anthropic 的指南指出,每个子代理在探索过程中可能消耗数万 token,但会返回一个提炼后的摘要,通常为 1,000 到 2,000 token。AWS AgentCore 的分步教程正是构建于此:协调器并行启动 3 个浏览器子代理,每个子代理运行在独立的 MicroVM 中,而分析子代理仅接收它们的结构化发现结果。AWS 报告预期运行时间为 4 到 6 分钟,并指出顺序处理可能需要长达 3 倍的时间。

Mechanism 2: Compaction

机制 2:压缩(Compaction)

When offloading is not enough, the harness summarizes. Compaction is the practice of taking a conversation nearing the window limit, summarizing it, and reinitiating a new context with the summary. It is also where goal loss most often happens, because a lossy summary can drop the one constraint that mattered.

当卸载不足以应对时,框架会进行摘要总结。压缩是指将接近窗口限制对话进行总结,并使用该摘要重新启动新上下文的实践。这也是目标丢失最常发生的环节,因为有损摘要可能会丢弃唯一重要的约束条件。

The implementations differ in what they promise to keep. Claude Code’s compaction prompt preserves architectural decisions, unresolved bugs, and implementation details while discarding redundant tool outputs. Right after compaction it re-reads up to 5 of the files modified most recently, reloads the rules matching those files, and re-injects invoked skill bodies, capped at 5,000 tokens per skill and 25,000 total. The docs are explicit that detailed instructions from early in the conversation may be lost, which is why persistent rules belong in the project-root CLAUDE.md, which is re-injected from disk. Users can steer the pass with /compact focus on the auth bug fix or move the trigger point with /autocompact.

各实现在承诺保留的内容上有所不同。Claude Code 的压缩提示词会保留架构决策、未解决的 bug 以及实现细节,同时丢弃冗余的工具输出。压缩完成后,它会重新读取最近修改最多的最多 5 个文件,重新加载与这些文件匹配的规则,并重新注入被调用的技能主体,每个技能上限为 5,000 token,总计上限为 25,000 token。文档明确指出,对话早期的详细指令可能会丢失,因此持久化规则应放在项目根目录的 CLAUDE.md 中,以便从磁盘重新注入。用户可以通过 /compact focus on the auth bug fix 引导流程关注身份验证 bug 修复,或通过 /autocompact 移动触发点。

Deep Agents made goal preservation a structural feature. Its summary is a structured document with dedicated fields for session intent, artifacts created, and next steps. The LangChain team added those fields after forced-summarization experiments showed the change improved performance. The full original transcript is also written to the filesystem, so a fact that was summarized away can be recovered by read_file later.

Deep Agents 将目标保留作为结构特性。其摘要是一个结构化文档,包含专门用于会话意图、已创建工件和下一步操作的字段。LangChain 团队在强制摘要实验表明该改进能提升性能后添加了这些字段。完整的原始转录文本也会写入文件系统,因此被摘要省略的事实可以通过稍后的 read_file 操作恢复。

Compaction has moved into the API layer too. OpenAI’s Responses API offers server-side compaction via context_management with a compact_threshold, plus a standalone /responses/compact endpoint that returns a compacted context window containing an opaque encrypted compaction item; OpenAI instructs developers to pass that returned window unchanged into the next call. OpenAI says Codex relies on this mechanism to sustain long-running coding tasks. The Claude Developer Platform exposes a compact_20260112 context-management edit with custom instructions and a pause_after_compaction option for inserting content before the model continues. When you write custom instructions there, they replace the default prompt entirely, so a compaction prompt is a real engineering artifact, not a setting.

压缩(Compaction)也已进入 API 层。OpenAI 的 Responses API 通过 context_management 提供带有 compact_threshold 的服务端压缩功能,以及一个独立的 /responses/compact 端点,返回包含不透明加密压缩项的压缩上下文窗口;OpenAI 指示开发者将该返回的窗口原样传入下一次调用。OpenAI 表示 Codex 依赖此机制来维持长时间运行的编码任务。Claude Developer Platform 提供了一个名为 compact_20260112 的 context-management 编辑选项,支持自定义指令和 pause_after_compaction 选项,以便在模型继续处理前插入内容。当你在其中编写自定义指令时,它们会完全替换默认提示词,因此压缩提示词是一个真正的工程产物,而非一个设置项。

Mechanism 3: Todo-state and recitation

机制 3:待办状态与复述

Compaction protects the goal at the moment of summarization. Todo-state protects it on every turn in between. Manus described the trick plainly: its agent creates a todo.md and rewrites it step by step, checking items off. Rewriting the list recites the objectives into the end of the context, pushing the global plan into the model’s recent attention span and reducing “lost in the middle” drift. No architecture change is required. It is natural language used to bias the model’s own attention.

压缩在摘要时刻保护目标。待办状态(Todo-state)则在每次交互之间保护目标。Manus 直白地描述了这一技巧:其代理创建一个 todo.md 文件并逐步重写它,逐项勾选完成。重写列表会将目标复述到上下文的末尾,将全局计划推入模型的近期注意力范围,从而减少“迷失在中间”的漂移现象。无需进行架构更改。这是利用自然语言来引导模型自身的注意力。

The evidence on todo-state is not one-sided. Deep Agents shipped a write_todos tool by default until v0.7 in July 2026, when LangChain made TodoListMiddleware opt-in after its evals across 3 task categories showed slightly better reward and lower cost with todos disabled. LangChain still recommends turning it back on for long multi-step tasks, less capable models, and UIs that show progress. Claude Code keeps a todo list and re-injects the plan written in plan mode from disk after compaction. Anthropic’s guide calls the general pattern structured note-taking: the agent writes a NOTES.md or TODO file outside the window and reloads it. Its Claude Plays Pokémon example maintained tallies across thousands of game steps, then read its own notes after each context reset and resumed multi-hour sequences.

关于 todo-state 的证据并非一面之词。Deep Agents 默认提供了 write_todos 工具,直到 2026 年 7 月的 v0.7 版本。当时 LangChain 在针对三个任务类别的评估中显示,禁用 todos 时奖励略高且成本更低,因此将 TodoListMiddleware 改为可选配置。LangChain 仍建议在长多步任务、能力较弱的模型以及需要展示进度的 UI 中重新启用该功能。Claude Code 会维护一个待办列表,并在压缩后从磁盘重新注入计划模式下编写的计划。Anthropic 的指南将该通用模式称为结构化笔记记录:代理在上下文窗口外写入 NOTES.md 或 TODO 文件,然后重新加载它。其 Claude Plays Pokémon 示例在数千个游戏步骤中维持了计数,然后在每次上下文重置后读取自己的笔记,并恢复持续数小时的序列。

The pattern behind all of these is that the goal exists as a mutable artifact, not only as a message in history. Messages age and get summarized. A file that is rewritten every few turns is always recent, always short, and survives any reset. Whether that is worth its per-turn token cost depends on the model and the task length, which is exactly what the Deep Agents evals measured.

所有这些背后的模式是,目标作为一个可变工件存在,而不仅仅是历史中的一条消息。消息会随着时间推移被摘要。一个每隔几个回合就被重写的文件始终是最新的、简短的,并且能幸存于任何重置。这是否值得其每个回合的 token 成本,取决于模型和任务长度,而这正是 Deep Agents 评估所衡量的内容。

Mechanism 4: Memory strategy across sessions

机制 4:跨会话的记忆策略

更进一步:量化金融体系

看懂新闻只是起点——沿量化金融路径,把它变成能交付的工程能力

进入量化体系 →

相似阅读

关联信息,但可能不是同一事件