Chapter 11 · Domain 6(本章 skill 权重合计 3.8%)
Context Engineering先分清量与方向,再决定 prune、compact 还是 isolate
TS 6.1 管的是上下文里放什么、何时裁掉、何时把工作隔离出去。本章把 context bloat 与 context drift 分成两种失效模式,再推导 tool output pruning、compaction、subagent 与 multi-step workflow 的对症手法。
一、Bloat 是量的问题;drift 是方向的问题
Context bloat (上下文膨胀)是 working set 变得过大:旧 tool outputs、重复文件、已完成分支和无关来回仍在每轮输入里。它的直接信号是 input tokens、cost 与 latency 上升,真正风险还包括相关 evidence 被噪音稀释。官方 context-window 文档同样提醒:更多 context 不会自动更好,token 数增长时 accuracy 与 recall 会退化,这种现象称为 context rot 。
Context drift (上下文漂移)则是当前工作方向偏离目标:agent 继续追逐已否决的假设、把旧要求当现要求,或在多轮修正后仍沿用早期 plan。它可能发生在一个并不大的 window 里,因此「token 少」不能排除 drift;反过来,巨大的日志堆也可能仍围绕正确目标,只是 bloated。两者常同时出现,但 diagnosis 与修法不同。
失效模式 最强信号 直接手法 不对症的动作
Bloat · 量 input tokens 持续涨;大段旧 results 每轮重发;相关信息召回变差 prune 已消费 payload;compact 冗长 history;把高噪声探索隔离 只重写一句目标,却继续携带全部旧输出
Drift · 方向 输出围绕旧 goal / rejected assumption;遗漏最新 acceptance criteria 重新注入 current goal、constraints、approved decisions 与 next step;清掉冲突旧方向 只扩大 window 或无差别删短内容
诊断口诀 — 先问「带得太多吗?」再问「带的是当前任务吗?」前者决定要不要减量,后者决定要不要重新定向;不能用同一条 token threshold 代替两次判断。
二、Pruning:删 payload,保留 decision state
请求里的 system prompt、全部 messages、tool results、images、documents 与 tool definitions 都计入 context window;本轮 output 也占窗口。Prompt caching 只改变 cached prefix 的计费方式,cached tokens 仍占 window。因此「把全部旧 tool output 缓存起来」不是 pruning,只是给同一份 bloat 换了价格标签。
Tool output pruning 的最小安全单元不是「删掉一轮」,而是把已消费的 bulky payload 换成可继续推理的 decision state:结论、来源或 artifact pointer、仍未解决的约束,以及需要时如何重取原文。原始 search dump、完整 test log 或重复 file content 可以离开 active context;尚未验证的 error、唯一证据和后续步骤依赖的精确值不能因为长就删。
Tool output 处理 Active context 留什么
8,000 行测试日志,失败已定位到 2 个 case Prune raw log command、2 个 failure、artifact path、修复后复跑条件
检索得到 40 个候选,3 个来源已核验 Prune candidates 3 条 evidence + URL / file pointer;标出未决冲突
下一步要精确 patch 的 30 行 code 暂时保留 精确 snippet 与 file location;完成 edit 后再降为 summary
这既是工程 pattern,也有官方产品机制。Messages API 的 beta context editing 支持 tool result clearing;clear_tool_uses_20250919 会在 history 超过配置 threshold 后清理旧 tool results,适合 heavy tool-use workflow。未启用这类机制的 stateless loop,仍由应用决定下一次请求重发哪些 history。
Pruning 还会碰到 ch02 的 cached-prefix 链:context editing 真正清理 content 时会让 cached prompt prefix 失效,所以不要每轮只剪一点造成反复 cache rewrite;一次清出足够空间,再让后续请求复用新 prefix。最终边界也要靠 telemetry:仅 input 已超 window 时 API 返回 400 invalid_request_error(prompt is too long);在 Claude 4.5 及更新模型上,generation 触到 window limit 时以 stop_reason: "model_context_window_exceeded" 停止。这些是失败信号,不是 context-management strategy。
三、Compaction:把 history 变成有损的 state transition
Compaction(上下文压缩)用 summary 代替冗长 conversation。Claude Code 在接近 context limit 时会自动管理:先清较旧 tool outputs,必要时再总结 conversation;requests 与关键 code snippets 会保留,但早期 detailed instructions 可能丢失。官方没有在这条说明里承诺一个固定百分比,所以不要把猜测的「80% 自动触发」写进 runbook 或题目。
手动控制点是 /compact:可用 CLAUDE.md 的 Compact Instructions 或给命令附 focus,说明 summary 要保住什么。项目根 CLAUDE.md 在 compaction 后会从磁盘重读并重新注入,但它不能替代 task-specific state;当前 goal、non-negotiable constraints、approved decisions、modified artifacts、validation evidence 与 next step 仍要在 summary 里显式出现。
Before compaction
current goal + acceptance criteria
approved decisions + rejected assumptions
artifacts changed + evidence pointers
unresolved risks + exact next step
After compaction
verify every field above survived
re-read authoritative task state
continue only after direction matches
Compaction 主要缓解 bloat;只有 summary 把 latest goal 与 decisions 放回中心时,它才顺带纠正 drift。若 summary 把一个已否决假设写成结论,context 虽然变短,方向反而更稳定地错下去。P9 的裁决不是「越短越好」,而是以最小体量保留下一步所需的正确信息。
四、Isolation:让噪声在别的 window 里结束
Pruning 与 compaction 都在修同一个 context;context isolation 则改变工作边界。Claude Code subagent 默认在自己的 fresh context window 里工作;只有 fork 才从当前 conversation 的副本开始。无论哪种,subagent 的 tool calls 不进入主 context,结束时主循环拿回 summary。这适合大量 file reads、search results 或独立 verification:主循环消费结论,不消费探索过程。
隔离形态 传入 传回 适用信号
Fresh subagent 窄 task、sources / tools、completion criteria、return schema summary、evidence pointers、unresolved items 探索噪声大,但不依赖完整 parent history
Forked subagent 当前 conversation 的副本 + 专门任务 summary 任务确实依赖 parent 的大量既有 context
Multi-step workflow 每个 stage 的最小 input contract 持久化 artifact + 下一 stage brief research → implement → verify 可分段,且各段 evidence 不必互相全量重放
Isolation 不是「多开 agent 就省 context」。把 parent 的完整 transcript 复制给每个 worker,或让它们回传全部 raw logs,只是把 bloat 搬家。有效 contract 要让 noisy intermediate work 在局部 window 里结束,只把可校验结果与必要 provenance 带回。ch09 解决 memory 的 write / store / retrieve 生命周期;本章解决这些 state 在某一轮该进入哪个 window、何时退出。
考点回链 — 本章覆盖:TS 6.1(context window management;bloat 与 drift 的区分和预防;tool output pruning;Claude Code automatic / manual compaction;经 fresh / forked subagent 与 multi-step agentic workflow 做 context isolation)。相邻考点:memory 的 write / store / retrieve pattern 与 framework fit 见
ch09 ;instruction placement、few-shot 与 defensive output handling 见
ch10 ;tool schema 与 dispatch 见
ch12 。
本章题组
QUESTION 01 · TS 6.1 · BLOAT DIAGNOSIS
A 42-turn incident agent still follows the current goal and acceptance criteria, but its input has grown to 165,000 tokens. Telemetry shows that 78% is old raw tool output from already-resolved hypotheses, while p95 latency and recall errors are rising. What is the most direct diagnosis and response?
A Diagnose context drift and repeat the unchanged goal at the end of the prompt, while preserving all 165,000 tokens so the agent can still inspect every resolved hypothesis on every turn.
B Diagnose context bloat; prune consumed tool payloads, retain conclusions, evidence pointers, unresolved constraints, and the goal, and re-fetch raw evidence only when a pointer becomes relevant.
C Move the request to a larger context window and keep every raw result indefinitely, treating additional capacity as proof that irrelevant evidence no longer affects token cost, latency, or recall.
D Switch to a more capable model and retain the stale tool payloads, treating the recall errors as a model-capability problem rather than a context-shape problem.
正确 B 方向仍正确,量却被已解决分支撑大;这是 bloat。保留 decision state 与 provenance、移出 bulky payload,直接作用在 trace 已定位的来源。
D2 无关杠杆 违反 P6 A :题干明确说明 goal 与 criteria 仍被遵循,重复同一目标不处理 78% 的旧输出,误把量的问题诊断成方向问题。
D6 半对半错 违反 P9 C :更大 window 可能暂时推迟 overflow,但不会让旧 evidence 变相关,也不会消除重复 token 与 attention cost。
D4 换模型当解法 违反 P6 D :telemetry 已把主要占用定位到 stale output;换模型没有裁掉任何一条噪声。
QUESTION 02 · TS 6.1 · DRIFT DIAGNOSIS
A migration session uses only 24,000 input tokens and its token count is stable. Twelve turns ago, the target changed from MySQL to PostgreSQL, yet the agent keeps proposing MySQL-specific schemas because the original plan remains prominent. Which intervention best addresses the failure?
A Diagnose drift: remove the obsolete MySQL decision, re-anchor on PostgreSQL, the latest constraints and approved decisions, and make the next migration step the sole active plan.
B Prune the largest test log but keep both database plans in context, using remaining token count as the signal that no further curation is needed.
C Increase the context-window capacity so both database plans can remain equally prominent, expecting more space to make the model infer which mutually conflicting target is current.
D Spawn a new agent but fork the complete conflicting transcript and provide no explicit current target, assuming a separate worker identity removes directional bias while preserving every earlier assumption.
正确 A 24,000 tokens 且用量稳定,不是量先失控;输出持续追随 obsolete goal 才是强信号。删除冲突旧方向并重注 latest state,直接修 drift。
D2 无关杠杆 违反 P6 B :随手删一份 log 可能减量,却保留了导致错误输出的 MySQL plan,没作用在已定位的方向源头。
D2 无关杠杆 违反 P9 C :容量增加不能裁决两份冲突 requirement;更多空间只会让过期方向继续存在。
D6 半对半错 违反 P9 D :fork 是真实隔离形态,但它复制了完整冲突 history;没有 current-goal contract,就把 drift 一起复制过去。
QUESTION 03 · TS 6.1 · SAFE TOOL-OUTPUT PRUNING
A search tool returned 30,000 tokens of JSON. The agent has already validated three facts, stored the raw response at an artifact path, and recorded one unresolved contradiction. The next step needs the facts and contradiction, not the full JSON. What should the application place in the next request?
A Keep the entire JSON in a cached prefix because cache reads are cheaper, and assume cheaper billing means those 30,000 tokens no longer occupy the context window or dilute later retrieval.
B Delete the raw JSON, the three validated facts, the artifact path, and the unresolved contradiction together, because safe pruning requires removing every trace of a completed tool call.
C Copy the full JSON into a Tool Evidence section in root CLAUDE.md so compaction and future sessions can retrieve it from versioned project instructions.
D Send the three facts, provenance, artifact pointer, unresolved contradiction, and retrieval instructions; keep the bulky JSON outside active context until its pointer is needed for reinspection.
正确 D raw payload 已完成证据提炼且可按 pointer 重取;下一轮真正需要的是 validated facts、provenance 与 unresolved state。这样减量而不丢 decision state。
D6 半对半错 违反 P9 A :cache read 可能降低计费,但 cached prefix 仍占 window;它没有完成 pruning。
D6 半对半错 违反 P9 B :删 raw JSON 合理,连 facts、pointer 与未决冲突一起删则让下一轮失去必要 evidence。
D5 错层承载 违反 P4 C :一次 task-specific tool result 不该住进跨 session 的 project instruction 文件;它既不是稳定规则,也会污染后续任务。
QUESTION 04 · TS 6.1 · PRUNING AND CACHE INVALIDATION
A beta Messages API agent enables tool-result clearing. Production telemetry shows a small clear on nearly every turn, cache_creation_input_tokens repeatedly spikes, and cache_read_input_tokens stays near zero. The active context remains safely below its limit. What change best matches the documented interaction?
A Keep clearing on every turn because server-side context editing preserves the old cached prefix byte-for-byte, so the repeated cache creation must come from unrelated model sampling variance.
B Disable pruning and rely only on prompt caching, since cheap cache reads remove cached tokens from the context window and therefore solve both the cache churn and future bloat.
C Clear less often but in meaningful batches: clearing invalidates the prefix, so reclaim enough tokens once, verify the new prefix in usage, and then let subsequent requests reuse it.
D Switch models and keep clearing every turn, expecting greater capability to stabilize the cache prefix after each mutation.
正确 C 官方行为是 tool result clearing 发生时 cached prefix 失效;小剪多次会反复付 write。一次回收足够空间,再复用新 prefix,才对上 telemetry。
D1 凭空捏造 违反 P5 A :context editing 不会在删 content 后保留原 hash;选项给真实机制安上了相反职责。
D6 半对半错 违反 P9 B :caching 能改变价格,却不让 cached tokens 退出 context;取消 pruning 会重新积累 bloat。
D4 换模型当解法 违反 P6 D :prefix 因 content mutation 改变,与模型 capability 无关;换模型还会引入另一条版本与缓存变量。
QUESTION 05 · TS 6.1 · CLAUDE CODE COMPACTION
In Claude Code, /context shows the session approaching its limit after a long refactor. The next phase still needs the accepted API decisions, modified-file list, failed test evidence, and rollback step. A persistent rule already lives in project-root CLAUDE.md. What should the developer do?
A Run /compact with focus instructions for accepted decisions, evidence pointers, the open constraint, and rollback; verify the summary, while root CLAUDE.md retains only persistent policy.
B Set autoCompactAt: 80 in project settings and let the threshold preserve all task state across automatic summaries.
C Wait until the context overflows and returns an API error because Claude Code compaction starts only after a failed request, then expect the retry to reproduce every early instruction verbatim.
D Use /clear immediately without recording the accepted decisions, evidence, or rollback step, because a completely empty context automatically reconstructs task-specific state from project-root CLAUDE.md.
正确 A /compact 可带 focus;summary 是有损 handoff,所以续跑前复核关键 task state。root CLAUDE.md 会重注 persistent rule,但不代存本次 refactor 的全部状态。
D1 凭空捏造 违反 P5 B :autoCompactAt 是本书自制的干扰项,没有官方出处;官方只说明接近 limit 自动管理,且早期细节可能丢失。
D6 半对半错 违反 P5 C :自动 compaction 真实存在,但触发描述是 approach limit,不是先等 overflow;也没有 verbatim 保留保证。
D6 半对半错 违反 P9 D :/clear 确实释放全部 conversation context,却也丢掉未持久化 task state;CLAUDE.md 只保存项目规则。
QUESTION 06 · TS 6.1 · CONTEXT OVERFLOW
A preflight count shows that the request input alone exceeds the selected model's context window. The API returns HTTP 400 with invalid_request_error and prompt is too long; no assistant content was generated. What should the client do before retrying?
A Parse the 400 body as a partially generated assistant answer, because an input-overflow error always includes the text produced before stop_reason: "model_context_window_exceeded".
B Increase max_tokens while sending the identical oversized input, since a larger output allowance also expands the model's fixed input capacity and prevents the same validation failure.
C Curate the input before retrying: prune or compact stale material while preserving required constraints and evidence, then recount the resulting request.
D Mark the identical oversized history as a cached prefix and retry, because cached input tokens are excluded from context-window accounting even though they remain part of the request.
正确 C 仅 input 已超窗时请求在生成前以 400 失败;先减少 active context、保住必要 state 并重计,才改变失败条件。
D1 凭空捏造 违反 P5 A :这条 400 路径没有 assistant output;model_context_window_exceeded 是另一种生成过程中触顶的 stop reason。
D2 无关杠杆 违反 P6 B :错误源头是 input alone 超限,增加 output allowance 不会扩大 input capacity,反而让总预算更紧。
D6 半对半错 违反 P9 D :cache 可能改变计费,但 cached prefix 仍计入 window;同一 oversized input 仍会 400。
QUESTION 07 · TS 6.1 · SUBAGENT ISOLATION
A parent session is ready to implement a fix and has 55% of its context remaining. Repository research will read about 60 files, but the parent needs only confirmed findings, source locations, and unresolved questions. The research does not depend on the full parent transcript. Which design provides real context isolation?
A Fork the full parent conversation into a subagent so it inherits all prior decisions, and require a complete audit bundle containing every file body and command output.
B Launch several fresh subagents but broadcast the complete parent transcript to each and concatenate all raw exploration logs back into the main conversation before implementation.
C Perform all 60 file reads in the parent because a subagent's individual tool calls are automatically copied into the parent context when it finishes, eliminating any possible context saving.
D Use one fresh, narrowly scoped subagent and request a concise result schema with findings, source pointers, and unresolved questions.
正确 D 任务不依赖 parent history,fresh subagent 可让 60-file exploration 留在独立 window;主循环只接收后续 implementation 所需的 summary 与 provenance。
D6 半对半错 违反 P9 A :fork 是真实模式,但题干不需要 parent history;再回传全部 payload 会同时放大输入与输出两端的 bloat。
D6 半对半错 违反 P9 B :fresh workers 看似隔离,却被完整 transcript 与 raw-log merge 抵消,噪声最终仍回到主 context。
D1 凭空捏造 违反 P5 C :官方行为恰好相反:subagent tool calls 留在自己的 context,主循环拿回 summary。
QUESTION 08 · TS 6.1 · MULTI-STEP ISOLATION
A three-stage workflow performs research, implementation, and verification. Each stage can produce more than 40,000 tokens of intermediate output, but downstream stages need only approved decisions, artifact locations, the change set, and acceptance criteria. How should the developer pass context across stages?
A Run every stage in one continuous conversation and preserve all intermediate output verbatim, because cross-stage correctness requires every later model call to reread the entire research and implementation transcript.
B Give each stage a minimal input contract and persist its artifact plus a verified handoff summary; send the verifier the change set and criteria, not the research dump.
C Compact after every individual tool call and deploy a separate summarization service before measuring whether stage boundaries alone keep the working sets within budget.
D Cache every stage's raw output and prepend it to the next stage, assuming lower cache-read pricing turns a 40,000-token intermediate transcript into zero active context.
正确 B stage boundary 是天然 isolation seam:持久化 artifact 与 verified summary,下一 stage 只接收完成职责需要的 state,既保 provenance 又不全量重放。
D5 错层承载 违反 P9 A :正确性需要 decision state 与 evidence pointer,不要求每一轮重读所有 intermediate payload;这把 context 当 transcript warehouse。
D7 过度工程 违反 P10 C :每次 tool call 都 compact 并先建独立服务,跨过了尚未验证的轻量 stage handoff,还会制造大量 summary churn。
D6 半对半错 违反 P9 D :cache 可能省 input 价格,但 40,000 tokens 仍占 window;它没有建立 isolation。