Context Engineering、State 与 Agent Memory:系统级深潜
范围:Coding Agent 的信息供给、任务状态与跨时间记忆。本文不是 prompt 技巧集,也不是“把对话塞进向量库”的 RAG 教程;它讨论一个长期运行的 Agent 如何在有限注意力、真实仓库、持续副作用和不完美证据下,保持目标、恢复进度、区分事实与猜测,并让每次状态变化可重放、可验证、可撤销。
资料时点:2026-08-03。2026 年论文均按当前公开预印本理解,结论需区分“已复现结构性事实”和“单篇论文报告”。
证据规则:公开源码只证明对应 commit 的实现;厂商工程文档只证明该产品/实验的公开 contract;arXiv 预印本与 Chroma technical report 的数字只在作者声明的模型、harness、dataset 和 evaluator 内成立。本文会把直接证据与工程推论分开,不把“最新”误写成“已经形成共识”。
0. 先给出结论:这不是一个 messages 数组问题
一个可靠 Coding Agent 至少同时维护五种不同对象:
- Evidence universe:仓库、终端、Git、测试、文档、用户输入、运行时和外部服务中可能相关的证据全集;
- Context:本次模型采样真正可见的、经过选择与排布的有限证据;
- Task state:系统对目标、约束、决策、进度、副作用和验证状态的结构化认知;
- Journal:已发生事件的不可变、可重放记录;
- Memory:跨 turn、session、task 或 repo 保留、经治理且可失效的知识。
它们的关系不是“历史越长越好”,而是:
世界产生证据
-> journal 记录发生了什么
-> reducer 从事件重建 task state
-> context engine 为下一决策选择最小充分证据
-> model 产生候选判断或动作
-> verifier 判断结果是否可信
-> memory policy 决定什么值得跨时间保留
最重要的架构判断有八条:
- Context 是一次推理请求的视图,不是系统状态本身。 模型“没看到”不能等价于系统“没保存”。
- Transcript 是给人的投影,不是恢复真相。 UI 可以隐藏、合并或润色;journal 必须保持事件语义。
- Compaction 是有损状态迁移,不是普通摘要。 它必须声明保留的不变量、压缩边界和丢失量。
- Checkpoint 是一组一致性边界,不是一段聊天摘要。 对话、任务、文件、Git、工具副作用、远端资源可能需要不同 checkpoint。
- Memory write 比 memory read 更危险。 错误检索影响一次推理,错误写入会污染未来所有推理。
- Provenance 必须参与 authority。 “来自用户”“来自工具输出”“来自模型推断”不能压平成同一种自然语言事实。
- Long context 与 retrieval 互补。 窗口长度决定能放多少,context engineering 决定放什么、为什么、如何更新。
- Filesystem 可作为外部认知空间,但不能成为隐形垃圾场。 可寻址、可重建、可验证的 artifact 才是认知外化;随手写的自由文本只是另一种污染。
1. 精确对象模型与边界
1.1 六个符号先分清
在 step t 定义:
X_t:外部世界状态,例如 Git working tree、文件内容、进程、远端 issue、测试结果;J_{0:t}:从任务开始到当前的事件日志;S_t:由 journal 与必要外部探测得到的当前任务状态;M_t:可跨当前窗口或会话使用的长期记忆;E_t:当前可访问的候选证据集合;C_t:最终送入模型的 context;a_t:模型提出、策略层接受的下一动作;o_{t+1}:动作产生的 observation/effect receipt。
理想化 Agent transition:
S_t = R(J_{0:t}, X_t^{observed})
E_t = Acquire(q_t, S_t, X_t, M_t)
C_t = Pack(Select(E_t, S_t, B, \pi_c))
a_t \sim \pi_\theta(\cdot \mid C_t)
(X_{t+1}, o_{t+1}) = Execute(a_t, X_t)
J_{t+1} = J_t \oplus Event(a_t, o_{t+1})
这里 B 是 token、延迟、费用和 tool-schema 占用构成的预算,π_c 是 context policy。关键点是 C_t 可随每一步变化,而 S_t 不应因为 context 被 compact、provider 重试或模型切换而消失。
1.2 Context:有限、瞬时、面向下一决策
Context 是某次采样的输入 token 序列及其结构语义。它包含的不只是用户 prompt,还可能包括:
| 成分 | 典型内容 | 是否应稳定 |
|---|---|---|
| Authority | system policy、权限、不可覆盖约束 | 高 |
| Goal contract | 用户目标、非目标、验收条件、已确认决策 | 高 |
| Task projection | 当前 phase、todo、阻塞、下一判断 | 中高 |
| Repository evidence | 代码、符号、测试、配置、diff、历史 | 动态 |
| Trajectory evidence | 最近动作、失败、effect receipt、验证 | 动态 |
| Tool surface | 当前可用工具及必要 schema | 动态/按需 |
| Retrieved memory | 经 scope 与 provenance 过滤的事实/策略 | 动态 |
Context 的目标函数不是“装满窗口”,而是在预算内最大化下一动作质量:
\max_{C \subseteq E_t}
\underbrace{I(A^*; C \mid S_t)}_{decision\ information}
+ \lambda_1 AuthorityCoverage(C)
+ \lambda_2 ConstraintSurvival(C)
- \lambda_3 Redundancy(C)
- \lambda_4 StalenessRisk(C)
- \lambda_5 InjectionRisk(C)
约束:
Tokens(C) \le B_{tokens},\quad Latency(C) \le B_{latency},\quad Cost(C) \le B_{cost}
I(A*; C | S_t) 实际不可直接计算,工程上用 relevance、control-path proximity、test proximity、freshness、authority、uncertainty reduction 和 downstream lift 代理。
1.3 State:不依赖模型是否记得的系统事实
Task state 至少包含:
identity task/session/repo/worktree/model/harness IDs
goal 目标、非目标、验收器、权限边界
phase orient / diagnose / plan / mutate / verify / handoff
decisions 用户决定、架构选择、被否决方案及原因
hypotheses 当前假设、置信度、支持/反对证据
progress 已完成、待办、阻塞、下一动作
effects 已执行命令、文件变更、外部写入、提交/部署
verification 测试、检查、失败 cohort、未验证项
ownership worker/lease/cancellation/approval 状态
versions repo commit、schema、tool/model/config 版本
State 有多个层次,不能用一个 JSON blob 解决:
| 层 | 生命周期 | 示例 | 真相来源 |
|---|---|---|---|
| In-step scratch | 一次模型/工具调用 | 当前解析结果、局部候选 | 内存 |
| Turn state | 一轮用户任务 | 当前计划、待处理 tool calls | agent scope |
| Session state | 多轮连续工作 | 决策、progress、context counters | journal/reducer |
| Durable task state | 跨进程/跨机器 | goal、checkpoint、effects、verification | durable store |
| Environment state | 独立于 Agent | 文件、Git、进程、远端资源 | authoritative systems |
| Derived projection | 可丢弃重建 | transcript、UI status、search index | reducers/indexers |
1.4 Journal:事实序列,不是解释序列
Journal 应记录“发生的事件”,例如:
turn.started
user.message.appended
step.started
tool.call.proposed
permission.granted
tool.effect.committed
tool.result.observed
verification.recorded
context.compaction.applied
turn.completed
Journal 不应把 model narrative 当作系统事实。模型说“测试已通过”不等于 verification.recorded(exit=0, command=..., artifact=...)。
事件记录最小结构:
type JournalEvent = {
eventId: string;
streamId: string;
sequence: number;
type: string;
schemaVersion: number;
occurredAt: string;
causationId?: string;
correlationId: string;
actor: { kind: "user" | "agent" | "tool" | "system"; id: string };
payload: unknown;
provenance: Provenance;
};
1.5 Memory:跨 scope 的、经治理的可复用知识
Memory 与 journal 的本质差异:
- Journal 追求 发生过什么 的完整性;
- Memory 追求 未来什么值得被检索和授权使用 的效用;
- Journal 通常 append-only;memory 允许 revise、merge、invalidate、expire、delete;
- Journal 可作为 memory 的 provenance,但 memory 不能替代 journal。
1.6 Transcript:给人的可读视图
Transcript 可合并流式 token、隐藏内部事件、折叠工具输出、显示摘要和状态。它是 projection:
Transcript_t = P_{human}(J_{0:t}, S_t)
模型请求也应是另一种 projection:
Context_t = P_{model}(J_{0:t}, S_t, M_t, E_t, B)
把二者共用一个可变 messages 数组,会产生四类债务:UI 改动影响 provider wire;provider 修复污染持久历史;compaction 破坏审计;恢复逻辑依赖展示格式。
2. 总体架构:读路径、写路径、状态路径必须分开
2.1 四条 plane
| Plane | 负责什么 | 稳定接口 |
|---|---|---|
| Evidence plane | 获取、标准化、版本化外部证据 | evidence atom + provenance |
| State plane | journal、reducer、checkpoint、restore | event schema + state model |
| Context plane | selection、packing、compaction、projection | context item + budget decision |
| Memory plane | candidate、verification、scope、invalidation | typed memory transition |
深模块原则:模型侧只看到简单的 ContextEnvelope,而 acquisition、ranking、dedupe、version check、packing、repair、telemetry 藏在 context engine 内;memory consumer 只获得“已授权 claim bundle”,而不是任意向量命中。
type ContextEnvelope = {
authority: ContextBlock[];
goal: ContextBlock[];
state: ContextBlock[];
evidence: ContextBlock[];
recentTrajectory: ContextBlock[];
tools: ToolDescriptor[];
memory: AuthorizedClaimBundle[];
budgetReport: ContextBudgetReport;
};
2.2 数据不应相互冒充
| 对象 | 可被压缩 | 可被删除 | 可直接授权事实 | 可用于恢复 |
|---|---|---|---|---|
| Raw journal | 否,除非另行归档 | 按合规策略 | 否 | 是 |
| Task state | 可重建 projection | 可重建 | 是,限结构化字段 | 是 |
| Transcript | 是 | 是 | 否 | 否 |
| Model context | 是 | 每次重建 | 只在 provenance/role 边界内 | 否 |
| Memory | 是,需 transition verify | 是,需审计 | 是,按类型授权 | 辅助 |
| Environment | 不由 Agent 压缩 | 外部权限决定 | 是,重新观察后 | 是,需探测 |
3. Context Pipeline:Acquire → Normalize → Select → Pack → Refresh
3.1 Acquisition 不是“搜一次代码”
Acquisition 的输入是信息缺口而不是自然语言 issue 原文。先判断当前要回答哪类问题:
| 搜索意图 | 真正问题 | 首选信号 |
|---|---|---|
| Locate definition | 定义在哪里 | exact symbol、LSP、AST |
| Trace control path | 谁决定最终行为 | references、call graph、entrypoint |
| Locate configuration truth | 哪个配置实际生效 | config key、load/merge order、runtime log |
| Explain failure | 首次错误发生在哪 | error text、trace、failing test、boundary logs |
| Estimate change surface | 改动会影响谁 | reference/import/build/test graph |
| Recover intent | 为什么这样设计 | Git history、PR/issue、adjacent tests/docs |
| Verify behavior | 什么证明它成立 | executable tests、assertions、artifact receipts |
| Discover unknown vocabulary | 命名尚不清楚 | semantic/BM25/docs,再回到结构检索 |
Acquisition 是闭环:
3.2 Repository cognition 的九种互补信号
- Path/name:目录、文件名、扩展名、约定位置;
- Lexical:标识符、错误文本、配置 key、API path;
- Syntactic:AST、tree-sitter、声明/引用、类型;
- Semantic graph:import、call、dataflow、ownership、build dependency;
- Execution evidence:stack trace、logs、coverage、test failure;
- Repository history:Git log/blame/diff、revert、rename;
- Contract evidence:tests、schema、types、protocol、migration;
- Natural-language semantics:issue 与实现命名不一致时的 embedding/BM25;
- Environment evidence:真实 binary、process、env/config source、deployed artifact。
没有单一检索器在所有任务上占优。2026 年预印本 SWE-Explore 在 848 个 issue、10 种语言、203 个仓库上按固定 line budget 评 coverage、ranking、context efficiency;Agent Retrieval Bench 覆盖 427 个样本、25 个仓库和五类 retrieval/selective-retrieval 任务,报告没有单一 retrieval family 全面占优,并且其 logged-agent trajectory 有 27%–35% 的样本完全漏掉 gold file。两者支持“file localization 不等于有效 context acquisition”,但证据边界不同:SWE-Explore 的 line-level gold 来自成功 Agent trajectory,衡量的是对已观测成功路径的覆盖,不是唯一或完备的 oracle;Agent Retrieval Bench 的结论也只应外推到其 frozen repo/task 构造。
3.3 控制路径优先,而不是相似代码优先
对真实 bug/架构问题,证据价值通常按以下顺序递减:
实际 entrypoint / runtime owner
> 决定行为的 merge/dispatch/reducer
> 边界 schema 与相邻 verifier/test
> 直接 caller/callee
> 历史变更与架构说明
> 相似实现
> 宽泛语义命中
“看起来相似”的模块可能不是运行路径。Context engine 应记录每个 evidence item 与控制路径的关系,而不只是 cosine score。
3.4 Evidence normalization
候选证据进入排序前,应统一成 typed evidence:
type EvidenceAtom = {
evidenceId: string;
kind: "source" | "test" | "config" | "trace" | "git" | "doc" | "user" | "tool";
locator: string; // file:line, commit, trace span, URL, event id
version: string; // commit/hash/etag/schema version
observedAt: string;
content: string;
scope: Scope;
authority: "authoritative" | "corroborating" | "untrusted";
freshness: number;
injectionRisk: number;
relations: EvidenceRelation[];
};
Normalization 解决四个问题:去掉大输出噪声、保留 locator、标记版本、把内容与 authority 分离。一个网页里的 prompt instruction 可以是证据内容,但不能因此获得 system authority。
3.5 Selection:多目标、带覆盖约束的预算优化
实用评分可写成:
score(e_i)=
w_r rel(e_i,q_t)
+w_c control(e_i,S_t)
+w_v verifierProximity(e_i)
+w_f freshness(e_i)
+w_a authority(e_i)
+w_u uncertaintyReduction(e_i)
-w_k tokenCost(e_i)
-w_d duplication(e_i,C)
-w_s stalenessRisk(e_i)
-w_p poisoningRisk(e_i)
但只按独立分数取 top-k 会重复选择同一事实。可加入 MMR 式多样化:
e^*=\arg\max_{e\in E\setminus C}
\left[\lambda score(e)-(1-\lambda)\max_{c\in C}sim(e,c)\right]
更重要的是设置覆盖约束:goal contract、用户显式决定、当前 diff、未验证 effect、失败原因等类别至少保留一个有效 block。它们不是和普通代码片段竞争 top-k 的软相关项。
3.6 Phase-aware selection
同一任务不同 phase 需要不同 context:
| Phase | 高价值 context | 应降权内容 |
|---|---|---|
| Orient | repo map、入口、规则、构建/测试 | 细碎旧 tool output |
| Diagnose | trace、首次异常、控制路径、对照组 | 未验证的修复建议 |
| Design | contract、invariants、ownership、tradeoffs | 重复堆栈 |
| Mutate | 目标文件、邻接类型/测试、当前 diff | 大范围架构文档 |
| Verify | acceptance criteria、commands、artifact state | 早期探索噪声 |
| Handoff | decisions、effects、open risks、next action | 完整逐步 transcript |
这说明 retrieval policy 应条件化于 S_t.phase,而不是全程使用相同 top-k。
3.7 Packing:选对证据仍可能因为排布失败
Packing 决定顺序、分组、格式、重复、prefix 稳定性和 positional salience。建议语义层次:
[Authority]
[Goal / Non-goals / Acceptance]
[Current state / Decisions / Open risks]
[Relevant evidence bundles, each with source+version]
[Recent action/effect/verifier receipts]
[Tools needed for this step]
[Explicit next-decision question]
关键规则:
- 高 authority 与低 trust 内容必须用结构边界隔开;
- evidence 与 inference 分栏,不能在改写时混成一段;
- 直接相关片段旁边放 locator、version 和上下游关系;
- 把当前决策问题显式放在末尾,避免模型把任务当开放总结;
- 稳定 system/tool prefix 有利于 KV cache,但不能为了 cache 固化过期配置;
- tool schema 按需暴露,避免数百工具挤压 evidence;
- 关键约束可在首尾用不同表述做结构性提醒,但不要机械重复所有内容。
3.8 Lost-in-the-middle 与 context rot 不是同一个现象
- Lost-in-the-middle:相关信息在长序列中间时利用率下降,表现出位置偏置。经典研究 Lost in the Middle 观察到开头/末尾优于中间;RULER 又表明简单 needle retrieval 不能代表多跳、聚合等真实长上下文能力。
- Context rot:这是输入增长后利用可靠性下降的一组任务相关现象,而不是已经证明对所有模型、任务都单调成立的单一机制。Chroma 的 2025 Context Rot 技术报告在 18 个当时模型、受控的 NIAH 变体、LongMemEval 与 repeated-words 任务上观察到非均匀退化;2026 年预印本 Diagnosing and Mitigating Context Rot in Long-horizon Search则在四个开源模型、三个 deep-search benchmark 上报告累计 context 会增加过早放弃或不确定作答。二者是互补的 task-specific evidence,不应被解读为一个统一因果定律。
- Contamination:错误、冲突或恶意内容进入 context,改变决策;它可以在短 context 发生。
- Staleness:context 中的证据版本已落后于环境;它与长度无关。
因此“把关键内容放末尾”只缓解位置问题,不解决证据冲突、陈旧、预算、污染和全局 rot。
3.9 Refresh:Context 是物化视图,要主动失效
Context item 应声明 invalidation dependency:
file evidence invalidated by file hash / commit change
symbol graph invalidated by index version
test result invalidated by code/config/env change
remote API state invalidated by TTL / etag / webhook event
tool descriptor invalidated by capability/version change
memory claim invalidated by source/repo/model/policy version
Context refresh 不应依赖模型“想起来再搜”。高风险 decision 前,系统可强制 revalidate authority evidence。
4. Compression:不是一种算法,而是不同损失语义
4.1 四类 compression
| 类型 | 方法 | 丢失性 | 适合 | 主要风险 |
|---|---|---|---|---|
| Structural | 去 schema 重复、折叠固定前缀、引用 artifact | 低 | tool schema、静态规则 | 引用失效 |
| Deterministic extractive | head/tail、错误行、diff hunks、top spans | 可计算 | logs、tests、大文件 | 漏掉隐含关联 |
| Semantic abstractive | LLM summary、decision digest | 高 | trajectory、讨论、handoff | hallucination/omission |
| Learned policy | 模型学习何时 compact、保留什么 | 高且分布相关 | 长 horizon agent | reward/harness 过拟合 |
4.2 压缩单位要与恢复单位一致
- 若未来需要精确引用,保存 source locator + extract,不只保存 summary;
- 若未来需要重跑,保存 command + cwd + env/config identity + exit/effect receipt;
- 若未来需要继续修改,保存 diff/commit/worktree pointer;
- 若未来需要避免重复失败,保存 hypothesis + failure evidence + invalidated action;
- 若未来只需用户可读,才可以只保留叙述摘要。
压缩质量应按后续行为衡量,而不是 ROUGE 或“看起来完整”。
4.3 Hierarchical compression
raw event
-> normalized event receipt
-> step digest
-> phase digest
-> task handoff
-> reusable memory candidate
每一级都必须保留指向下一级原始对象的 provenance。层级摘要可以减少 token,但不能把不可逆压缩伪装成事实删除。
4.4 Output compression 与 history compaction 分开
Tool output compression 发生在 evidence ingestion:例如只提取 10,000 行日志的异常窗口,同时保存原 artifact pointer。
History compaction 发生在 trajectory projection:把多个 step 压成可恢复状态。
两者混在一起会导致:一次超长工具输出触发整个会话摘要;摘要又丢掉该输出的 locator;后续无法回读原证据。
5. Long Context、Retrieval 与 External Cognition 的真实边界
5.1 三条路径不是互斥方案
| 路径 | 核心能力 | 最强场景 | 弱点 |
|---|---|---|---|
| Latent long context | 一次 attention 内跨片段整合 | 关系密集、范围已知、需要整体综合 | 成本、位置偏置、rot、不可审计 |
| Retrieval | 从大语料选择候选证据 | 稀疏相关、可索引、查询明确 | query miss、chunk/排名错、跨片段综合 |
| External cognition | 文件/索引/程序把大任务分解成可执行操作 | 超大语料、可计算、可重读、需审计 | workspace 治理、工具错误、状态碎片化 |
2026 年预印本 Coding Agents are Effective Long-Context Processors 在其 benchmark/model 组合中,让 off-the-shelf Coding Agent 通过文件系统、终端与可执行代码处理最高达三万亿 token 的语料库,并报告相对已发表 SOTA 平均提升 17.3%。它为“把部分长信息处理从单次 latent attention 外化为显式交互”提供了强结果,但不是无限上下文证明:数字来自作者设定的任务、agent、tool harness 与对比基线,尚不能推出任意 Coding Agent 都能无损处理任意规模语料。
5.2 选择边界
优先 long context,当:
- 证据集合已知且相互依赖密集;
- 需要一次性全局比较或保持精细措辞;
- 检索 query 难以在不知道答案时构造;
- token/latency 在预算内且模型在目标长度已被真实评测。
优先 retrieval,当:
- universe 很大、相关证据稀疏;
- locator、版本、scope 可稳定索引;
- 任务可通过多轮 hypothesis-driven search 收敛;
- 需要限制未信任内容进入上下文。
优先 external cognition,当:
- 内容规模远超窗口;
- 可用确定性工具过滤、聚合、排序、计算;
- 中间结果需要跨 compaction/session 保存;
- 需要人/Agent 共同检查证据与过程。
真实系统通常是:retrieval 找到工作集 → external tools 处理/重组 → long context 综合关键片段。
5.3 Filesystem as external cognition
好的 external cognition artifact 具备:
addressable 有稳定路径/ID
typed 知道是 evidence、claim、plan、receipt 还是 cache
versioned 绑定 commit/input/hash
reproducible 能从 source 重新生成
inspectable 人和工具可读
scoped 不跨 task/repo 泄漏
garbage-collected 生命周期明确
不好的模式:
- 随机文件名与无 manifest;
- 把模型猜测写成“facts.md”;
- 复制完整源文件但无版本;
- 多个 Agent 同时改同一 scratchpad;
- artifact 被 compaction 提到,却已被删除;
- 将 cache 当 source of truth;
- 使用隐藏目录长期积累敏感信息且无清理策略。
可以把 workspace manifest 建模为:
type CognitiveArtifact = {
id: string;
path: string;
kind: "evidence" | "index" | "analysis" | "plan" | "receipt" | "cache";
sourceIds: string[];
inputDigest: string;
generatedBy: string;
createdAt: string;
expiresAt?: string;
rebuildCommand?: string;
authority: "source" | "derived" | "hypothesis";
};
6. State、Event Sourcing 与 Replay
6.1 为什么长期 Agent 值得用 event sourcing 思维
Agent loop 同时存在流式输出、并行工具、取消、retry、compaction、resume、模型/provider 切换与 UI 投影。直接不断覆盖 session.json 会丢失:
- 某个 state 是如何得到的;
- 工具 effect 是否真的发生;
- retry 前后是否重复提交;
- compaction 前原历史是什么;
- 恢复后为何出现不同 projection;
- schema 升级应如何迁移。
Event sourcing 不要求把所有业务都变成复杂 CQRS;最小价值是:关键状态变化用不可变、有序、版本化事件表示,当前视图由 deterministic reducer 得到。
6.2 Reducer 的工程约束
对 reducer R:
S_{n+1}=R(S_n,e_{n+1})
应满足:
- Deterministic:相同 initial state + event sequence 得到相同 state;
- Pure or effect-isolated:replay 不重新执行外部副作用;
- Version-aware:event schema 能 migrate 或由 versioned reducer 读取;
- Order-explicit:并发事件必须通过 sequence/causation 形成可解释顺序;
- Partial-tail tolerant:崩溃留下半条记录时能检测而非静默接受;
- Idempotent ingestion:重复 event ID 不产生重复状态;
- Observable repair:若为 provider wire 修复消息顺序,必须留下 anomaly telemetry。
6.3 Agent state machine
不应把 LLM request finished 当 turn completed,更不应把 assistant text says done 当 task completed。
6.4 Replay 与 environment reconciliation
Journal 能恢复 Agent 认知,不能保证外部世界仍与记录一致。Resume 必须做 reconciliation:
1. validate journal tail and schema
2. replay deterministic state
3. inspect current repo/worktree/commit
4. inspect pending or ambiguous effects
5. compare artifact hashes and remote resource versions
6. mark stale evidence and invalid checkpoints
7. synthesize explicit recovery state
8. only then build model context
对于“命令已发送但结果未记录”的 crash window,状态是 effect_unknown,不是自动假定失败或成功。恢复策略取决于 effect 是否可查询、幂等、可补偿。
6.5 State consistency 不等于强一致数据库
需要区分:
- journal append 与内存 reducer 的原子性;
- context projection 与 journal 最新 sequence 的一致性;
- 本地 Agent state 与 Git/filesystem 的一致性;
- 多 worker lease 与外部 effect 的 exactly-once 幻觉。
很多工具无法做到 exactly once。更诚实的 contract 是:at-least-once delivery + idempotency key + effect receipt + reconciliation。
7. Checkpoint:恢复点是一个向量
7.1 四类 checkpoint
| Checkpoint | 保存什么 | 用途 | 不能证明什么 |
|---|---|---|---|
| Cognitive | goal、decisions、hypotheses、todo | 让模型接班 | 外部 effect 已发生 |
| Conversation | provider/model context boundary、summary | 跨窗口继续 | 文件/远端状态一致 |
| Workspace | commit、diff、file hashes、artifacts | 恢复代码现场 | 用户目标仍未变化 |
| Effect | command/API idempotency key、receipt、remote version | 避免重复副作用 | 后续 verification 通过 |
完整 checkpoint 可写成向量:
K_t = \langle jSeq, taskVersion, repoCommit, worktreeDigest,
effectWatermark, memoryVersion, contextEpoch, verifierState \rangle
只有各分量兼容,才可称为可恢复 checkpoint。
7.2 Checkpoint protocol
Checkpoint 不能先宣称成功、再异步 flush 关键 journal;否则 crash 后会恢复到一个不存在的状态。
7.3 Checkpoint 与 Git
Git 是代码状态的优秀 checkpoint,但不是 Agent 全状态:
- untracked artifact、进程、数据库、远端 API effect 不在 commit 中;
- commit 不包含为何改、验收条件、未验证风险;
- working tree 可能有用户预存改动,不能被 Agent checkpoint 覆盖;
- 多 worktree/branch 必须记录精确 root、HEAD、index 和 dirty digest。
因此 Git pointer 应是 K_t 的一个字段,不是 checkpoint 的全部。
8. Compaction:受约束的有损状态迁移
8.1 正确定义
给定旧 context/history H_t 与 task state S_t,compactor 输出较短表示 Z_t:
Z_t = Compress(H_t,S_t), \quad |Z_t| \ll |H_t|
真正目标不是文本相似,而是对未来相关决策保持近似等价:
\pi(a \mid Z_t, E_{future}) \approx \pi(a \mid H_t, E_{future})
在不可逆 effect、安全约束、用户决定等关键类别上,不应只要求概率近似,而应要求不变量严格保持。
8.2 Compaction invariants
至少保留:
- 用户真实目标、显式非目标和 acceptance criteria;
- authority/policy/权限边界;
- 用户已确认决定及其适用范围;
- 已验证事实,连同 locator、版本和证据强度;
- 当前 working state:root、branch、HEAD、dirty files、artifact pointers;
- 已发生 effect 与 effect receipt;
- 已证伪假设、失败尝试和不可重复路径;
- 未验证项、开放风险与阻塞;
- todo 的状态与依赖;
- 下一步最高信息增益动作;
- summary 覆盖的 journal range、生成器版本和 token before/after;
- 可回溯到原始 journal/artifact 的 provenance。
8.3 Compaction state machine
8.4 事务边界与竞态
Compaction 最危险的不是 summary 文笔,而是并发:
- compactor 对
H_t生成摘要期间,用户又发来真实输入; - tool result 到达但 summary 只看到 tool call;
- context 被 undo/clear;
- retry 的旧 compaction 晚于新 compaction 提交;
- summary 成功但 journal rewrite 失败;
- compact 后系统 prompt/tool surface 已变化。
可接受策略:冻结 compactable prefix,允许新真实用户消息作为 tail;提交前检查 prefix identity/sequence;用 CAS/epoch 防止旧结果覆盖新状态;compaction op 与 state measurement 同一 consistency boundary;提交后重新注入动态规则与 task state。
8.5 Trigger policy
| Trigger | 优点 | 风险 |
|---|---|---|
| Token threshold | 简单稳定 | 太晚时 compactor 自己也 overflow |
| Phase boundary | 语义完整 | phase 识别错误 |
| Marginal utility | 在 context rot 前主动压缩 | utility 估计困难 |
| Error-triggered | 对 provider overflow 自愈 | 已进入失败路径,重试成本高 |
| User/manual | 可控 | 用户不了解系统预算 |
| Learned trigger | 与 policy 联合优化 | 分布、model/harness 耦合 |
成熟系统通常用 soft threshold 后台准备、hard threshold 阻塞提交、overflow 作为最后恢复,并限制每 turn compaction 次数避免死循环。
8.6 Compaction、reset、branch、retrieval 的取舍
| 机制 | 保留什么 | 清除什么 | 适合 |
|---|---|---|---|
| Rolling compaction | 同一身份下的结构化连续性 | 原始细节 | 单一长期目标 |
| Clean reset + handoff | 显式 task state/artifacts | attention 污染、旧 trajectory | phase/agent/model 切换 |
| Branch/fork | 共同前缀,各自轨迹 | 不互相污染 | 并行假设/方案探索 |
| Retrieval from journal | 按需恢复原细节 | 不常驻窗口 | 可索引长历史 |
| Full replay | 最大完整性 | 无 | 调试/审计,不适合每步 |
8.7 Learned compaction 的前沿
CompactionRL 是 2026 年 7 月预印本,把任务执行与 summary generation 联合训练;作者报告 GLM-4.5-Air 在 SWE-bench Verified / Terminal-Bench 2.0 分别达到 66.8% / 24.5%,较其对照提升 7.0 / 3.1 个百分点,另一个 GLM-4.7-Flash 配置也报告提升。它支持“compaction 可以成为 agentic post-training 的训练目标”,但目前仍是特定模型、训练配方、harness 和 benchmark 下的作者结果,不能推出跨模型的通用最优。
OpenAI 的 Codex agent loop 公开说明 与 2026 年 Responses API computer environment 说明明确区分早期自然语言 summary 与当前 /responses/compact 返回的 opaque compaction item,并说明 Codex 会在阈值后自动使用该机制;这是 OpenAI/Codex 产品与 API 的公开 contract,不证明同一机制能无条件迁移到其他模型。Anthropic 的 2026 long-running harness给出了更细的模型依赖边界:其 Sonnet 4.5 实验中 compaction alone 不足、需要 clean reset + structured handoff;后续 Opus 4.5 harness 则使用连续 session 与 SDK automatic compaction。两条证据共同说明 reset/compaction 是由模型和任务决定的设计分支,而非固定优劣排序。
9. Memory:从自然语言便签升级为可信状态系统
9.1 Memory 的分类是多轴,不是一张四分类表
常见 episodic/semantic/procedural/preference 只描述内容语义,还必须同时标记 scope、authority、temporality 与 mutability:
| 轴 | 可能值 | 为什么重要 |
|---|---|---|
| Content kind | evidence / claim / cue / decision / procedure / preference / failure lesson | 决定如何授权使用 |
| Scope | step / task / session / repo / workspace / user / org | 防止跨边界泄漏 |
| Source role | user / tool / code / runtime / model inference / evaluator | 决定可信度上限 |
| Time | observed_at / valid_from / valid_to / superseded_at | 区分“旧事实”与“错误事实” |
| Mutability | append-only / revisable / replaceable / derived | 决定更新协议 |
| Verification | unverified / corroborated / verified / invalidated | 决定是否能驱动高风险行动 |
| Sensitivity | public / workspace / personal / secret-ref | 决定存储和检索权限 |
9.2 Typed memory:Evidence、Claim、Cue、Policy 分离
扁平 memory 如“项目使用 PostgreSQL,应该运行 X”混合了事实、策略和建议。更安全的 IR:
type Provenance = {
sourceType: "user" | "repo" | "tool" | "runtime" | "external" | "model" | "evaluator";
sourceId: string;
locator?: string;
observedAt: string;
version?: string;
transformChain: string[];
};
type EvidenceMemory = {
kind: "evidence";
id: string;
payloadRef: string;
provenance: Provenance;
scope: Scope;
};
type ClaimMemory = {
kind: "claim";
id: string;
statement: string;
support: string[]; // evidence IDs
contradicts: string[];
confidence: number;
validFrom?: string;
validTo?: string;
verification: "unverified" | "corroborated" | "verified" | "invalidated";
scope: Scope;
};
type CueMemory = {
kind: "cue";
id: string;
queryHints: string[];
targets: string[]; // claim/evidence/policy IDs
scope: Scope;
};
type PolicyMemory = {
kind: "policy";
id: string;
applicability: Predicate;
procedureRef: string;
evidenceOfSuccess: string[];
counterexamples: string[];
modelHarnessVersion?: string;
scope: Scope;
};
MemIR把扁平 memory 的 source-monitoring failure 称为 provenance-role collapse,并通过 evidence、cue、claim 分离限制 factual authority。最值得吸收的不是具体 schema,而是:类型决定权限;被检索到不等于被授权当事实。
9.3 Memory write pipeline
Write policy 应回答:
- 这条信息未来是否有重复价值?
- 是否已有更 authoritative source 可实时读取?若有,优先存 cue/locator 而非复制事实;
- 它属于哪个 scope?
- source 是 observation、user assertion、model inference 还是 evaluator judgment?
- 是否包含个人/敏感/secret 数据?
- 是新增、修订、合并、否定、失效还是只增加 corroboration?
- 什么事件会使它失效?
- 写入失败是否会影响当前任务,是否需要同步阻塞?
9.4 默认不应写 memory 的内容
- 单次模型猜测;
- 可从当前仓库低成本、权威地重新读取的普通代码事实;
- 一次工具失败推导出的全局规则;
- 未经用户许可的敏感偏好或身份推断;
- 包含 token、secret、private key 的内容;
- 只对某个 model/harness workaround 有效,却未记录版本的 procedure;
- 即将被 code/config 变更淘汰的临时细节;
- evaluator 给出的纯标量好坏而无证据解释。
9.5 Memory read pipeline
Memory read 不是向量 top-k:
query intent
-> scope/ACL pre-filter
-> type-specific retrieval routes
-> version/time/invalidation filter
-> contradiction grouping
-> evidence-backed authorization
-> diversity + budget selection
-> provenance-scoped projection
候选可按下式排序:
ReadScore(m)=relevance\times applicability\times freshness\times confidence
\times provenanceStrength\times scopeCompatibility
- contradictionRisk - privacyRisk - tokenCost
乘法比简单加法更符合直觉:scope 不兼容或已失效时,相关度再高也不应进入 context。
9.6 Claim bundle 而不是孤立句子
向模型投影 memory 时,建议形成 bundle:
Claim: 当前 repo 的 canonical launcher 是 ./matrix
Status: verified at commit abc123
Support: AGENTS.md:..., script hash..., successful run receipt...
Scope: repo
Counterevidence: none
Invalidates when: launcher file or AGENTS.md changes
Authority: actionable for startup; not authority for production deploy
这样模型能区分“这是什么”“凭什么”“能用于什么动作”“何时需要重验”。
9.7 Memory update 是 transition,不是 upsert
定义旧 memory M_t、新证据 E_t、候选操作 u_t:
\hat M_{t+1}=U(M_t,E_t,u_t)
transition verifier:
V(M_t,E_t,\hat M_{t+1}) \rightarrow
\{accept, revise, reject\}
必须评估:
- Coverage:新证据中的重要信息是否保留;
- Preservation:与新证据无关的旧事实是否被错误覆盖;
- Faithfulness:新增/修改 claim 是否得到 evidence 支持;
- Temporal correctness:旧状态是被否定、被替代、过期,还是只在另一时间有效;
- Provenance continuity:merge 后能否回到原证据;
- Scope isolation:更新是否跨 user/repo/task 泄漏;
- Authority non-escalation:model inference 不能因反复总结变成 authoritative fact;
- Sensitivity preservation:压缩/merge 不能丢掉 privacy 标签;
- Rollbackability:能否定位并撤销此次 transition 的影响。
TrustMem是 2026 年预印本,把 memory transition 的 omission、corruption、hallucination 作为一级故障。作者相对各错误类型的最强 baseline,分别报告这三类 transition error 降低 40.1%、79.1%、50.0%,并报告 HaluMem memory extraction 提升 12.14 F1;这些数字不能跨 dataset、memory schema 或模型直接外推。更稳健的结构结论是:评测单位应从“最终回答对不对”前移到“每次持久状态迁移是否保持 coverage、preservation、faithfulness”。
9.8 Temporal memory 与 invalidation
不能用最后写入覆盖一切:
2026-01: default model = A
2026-06: default model = B
二者都可能是历史上正确的。正确表示是 interval/supersession:
claim_A valid=[2026-01, 2026-06), superseded_by=claim_B
claim_B valid=[2026-06, ?), observed_at=..., source=config@commit
失效机制:
- Dependency invalidation:source file/hash/config version 改变;
- TTL:外部价格、运行状态、人员角色等高漂移事实;
- Event invalidation:branch switch、deployment、permission revoke;
- Contradiction invalidation:更高 authority 新证据;
- Model/harness invalidation:procedural memory 对新版本不再适用;
- Manual correction:用户明确更正,保留 audit 而非抹去历史。
9.9 Memory consolidation 的冲突语义
遇到冲突时,不应用 LLM 直接“融合成更自然的一句话”。先分类:
| 冲突类型 | 处理 |
|---|---|
| Temporal succession | 两条都留,建立 valid interval/supersedes |
| Scope difference | 分开存,限制适用 scope |
| Source disagreement | 建 claim set,保留双方 provenance,降 authority/请求重验 |
| Granularity overlap | 保留 canonical claim,子 claim 作为支持/限定 |
| True correction | invalidate 旧 claim,指向 correction evidence |
| Procedure drift | versioned policy,旧版本归档而非无声覆盖 |
9.10 Memory contagion:污染来自 evaluator,不只来自摘要
Memory Contagion是单作者 2026 年预印本,形式化了跨时间的 evaluator bias propagation:在其长度偏好、权威偏好实验中,即使 consolidation 使用 oracle,偏差仍可经 memory 影响未来 Agent。论文称长度偏好被 consolidation 稳健削弱,而权威偏好被放大的结果仅是 single-run preliminary estimate;因此这里把它视为需要进入 risk model 的新 failure mode,而不是已被广泛复现的普遍定律。
这意味着 memory data flywheel 必须审计整条因果链:
防线不是只做更强 summarizer:
- evaluator calibration 与多 judge disagreement;
- 保存 outcome evidence,不只保存 evaluator preference;
- memory candidate 记录 evaluator/version;
- 分 cohort 测量 bias amplification;
- shadow memory 与 canary retrieval;
- 对高影响 memory 支持 provenance traceback、rollback、unlearning;
- 避免把“过去模型喜欢的轨迹”直接当“未来模型应遵循的 procedure”。
9.11 Memory utility 与 integrity 的双目标
Objective = TaskLift - \alpha HallucinatedWrite - \beta Corruption
- \gamma ScopeLeak - \delta StaleUse - \epsilon RetrievalCost
只追求回答提升会鼓励多写、多检索;只追求零错误会导致什么都不记。真正的 operating point 需要按风险分层:低风险偏好可宽松写,高风险系统事实必须强 evidence 或现读现用。
10. Provenance:从 metadata 上升为 authorization plane
10.1 Provenance chain
一条 claim 可能经历:
source file@commit
-> tool read output
-> extracted evidence span
-> model-generated claim
-> memory consolidation
-> retrieved context bundle
-> action decision
每次 transform 都应记录:输入 IDs、transformer/model/version、时间、输出 ID、是否有损。这样才能回答“这个行动受哪条原始证据影响”。
10.2 Authority lattice
不是所有来源可简单按一个总分排序。可定义偏序:
system policy > user-authorized goal
runtime effect receipt > model narration of effect
executed test result > model prediction of test
current source@HEAD > stale memory copy
explicit user preference > inferred preference
但 authority 依赖问题:运行时日志对“实际发生了什么”高权威,对“用户想要什么”没有权威;用户对目标高权威,对当前 binary 的内部状态未必高权威。
10.3 Influence provenance
普通 data lineage 说明数据从哪里来;Agent 还需要 influence lineage:哪条 evidence 真正影响了选择、生成和 action approval。建议在 trace 中记录:
- retrieved candidate IDs;
- selected/dropped IDs 及 reason code;
- context position 与 token span;
- claim bundle 被哪个 step 使用;
- action 引用了哪些 evidence/constraint;
- verifier 看到了哪些原始证据,而非只看 summary。
这同时服务安全、debug、memory rollback 和 eval attribution。
11. 极端失败模式:系统在哪些边界真正断裂
11.1 Context acquisition failure
| 失败 | 表面症状 | 根因 | 正确诊断信号 |
|---|---|---|---|
| Gold file miss | 改了相似模块但无效 | query/graph exploration 错 | retrieval coverage、control-path distance |
| Control-path decoy | 修了 UI,真实 owner 在 server/config | 只用 lexical/semantic | runtime trace + config merge path |
| Version mismatch | 引用不存在的 API/行为 | index/cache 过期 | evidence version vs HEAD |
| Search fixation | 反复改写同一 query | policy 不会切 retrieval family | unique evidence yield/step |
| Over-expansion | 拉入整个 graph | 无 budget/phase policy | tokens per useful evidence |
| Test blind spot | 代码找到,验收契约没找到 | 只搜实现 | test proximity coverage |
11.2 Context selection/packing failure
- 目标和非目标在 compaction 后合并,Agent“正确地”做错范围;
- 重复的低价值 log 把唯一关键 exception 挤到中间;
- tool schema 占据窗口大部分,实际 repo evidence 不足;
- stale memory 与 current source 同时出现却无版本,模型随机选一个;
- untrusted repository text 伪装成 authority instruction;
- 把 verifier failure 压成“测试基本通过”;
- context 末尾只写“继续”,没有明确当前决策问题;
- multimedia/data URI 导致 body limit,而系统错误地做 token compaction;
- provider wire 要求 assistant-tool adjacency,投影中的孤儿结果导致请求拒绝;
- context repair 静默发生,团队误以为 journal 原始数据就是合法的。
11.3 State/replay failure
- journal 先 append tool call,effect 已发生,result 未落盘;resume 重复提交;
- reducer replay 执行真实 tool,造成二次副作用;
- event schema 新旧混用,迁移后顺序语义改变;
- UI transcript 被当 journal,折叠输出丢失 toolCallId;
- worker lease 已丢但旧 worker 继续写;
- cancellation 只停 LLM stream,不停工具进程;
- checkpoint 指向不存在的 artifact 或已删除 worktree;
- task state 说“clean”,实际 working tree 有用户改动;
- derived index 被误当 source of truth,重建后行为变化;
- clock-based ordering 处理并发,跨机器时钟偏移重排事件。
11.4 Compaction failure
- Goal drift:语义相近但 acceptance 改变;
- Negative-evidence erasure:失败原因丢失,Agent 重试已证伪路径;
- Effect hallucination:把“准备执行”写成“已经执行”;
- Uncertainty collapse:多个假设被总结成确定结论;
- Provenance severance:结论还在,source locator 丢失;
- Boundary race:summary 生成期间的新 tool result 被覆盖;
- Compaction spiral:压缩后仍超窗,重复 compaction 直到信息耗尽;
- Summary truncation:provider finish reason 被忽略,把半段摘要提交;
- Policy drift:旧 system/tool instructions 被摘要保留,压过新版本;
- Undo illusion:UI 允许 undo 跨越 compaction boundary,但原始细节不可恢复;
- False continuity:summary 看似流畅,正确下一步率显著下降;
- Sensitive-data laundering:原 evidence 有隐私标签,summary 变成普通文本。
11.5 Memory failure
| 失败 | 示例 | 系统性后果 |
|---|---|---|
| Omission | 更新偏好时丢掉例外条件 | 未来持续误用 |
| Corruption | 新 repo 配置覆盖另一个 repo 的事实 | 跨 scope 故障 |
| Hallucinated write | 模型推测被写成 verified fact | 持久系统状态错误 |
| Provenance-role collapse | 用户引述第三方被存成用户本人观点 | authority 错位 |
| Temporal flattening | 历史默认值被当当前值 | stale action |
| Procedure fossilization | 临时 workaround 变永久 playbook | 技术债自我复制 |
| Evaluator contagion | judge 偏好进入 procedure memory | 跨时间行为偏置 |
| Retrieval monoculture | 总是召回同一类成功经验 | 探索能力下降 |
| Privacy overreach | 从一次对话推断全局偏好 | 信任/合规风险 |
| Unlearning gap | 删除正文但索引/cache/summary 仍留 | 实际未删除 |
11.6 800K benign context 后的危险动作
Classifier Context Rot是 2026 年预印本;作者在一项“识别 Coding Agent 隐蔽危险动作”的数据集上报告,Opus 4.6、GPT-5.4、Gemini 3.1 对置于 800K benign token 之后的危险动作,其漏检率相较 isolated action 高 2–30 倍。这个数字是特定 monitor/dataset/长度切片的结果,不是这些模型全部安全任务的总失效率。对 Agent 架构的合理含义是:
- 安全 verifier 不能只消费和 actor 同一份无限累计 context;
- 高风险 tool action 应给 monitor 构建独立、短而完整的 evidence packet;
- periodic reminders 可是缓解,但不能替代结构化 action/effect/authority projection;
- monitor eval 必须沿 transcript length、danger position、benign clutter 做压力曲线。
12. Observability:先看清信息如何进入决策
12.1 每次 context build 的 trace
type ContextBuildTrace = {
contextId: string;
taskId: string;
stepId: string;
contextEpoch: number;
model: string;
maxTokens: number;
candidateCount: number;
selected: Array<{
evidenceId: string;
kind: string;
sourceVersion: string;
scoreComponents: Record<string, number>;
tokenCount: number;
position: [number, number];
}>;
dropped: Array<{ evidenceId: string; reason: string }>;
coverage: Record<string, boolean>;
repairs: string[];
cache: { prefixHit: number; retrievalHit: number };
buildLatencyMs: number;
};
不要记录 secret/完整敏感正文;记录 stable ID、hash、类别、版本、决策 reason,必要时受控链接到原 artifact。
12.2 State/replay telemetry
- journal sequence / flush watermark / corruption tail;
- replay duration、event count、migration versions;
- reducer repair/anomaly counts;
- pending/ambiguous effects;
- checkpoint age、referential-integrity failures;
- environment reconciliation mismatch;
- lease/cancellation propagation latency;
- projection sequence lag;
- restore 后首个正确动作率。
12.3 Compaction telemetry
- source:manual/threshold/overflow/phase;
- compacted journal range、context epoch;
- tokens before/after、ratio、summary output tokens;
- kept user messages、head/tail 分布、dropped count;
- retry、overflow shrink、truncation、latency;
- invariant verifier pass/fail;
- post-compaction next-action divergence;
- repeated-work / repeated-failure rate;
- compaction count per turn/task;
- recovery after provider overflow;
- summary provenance coverage。
12.4 Memory telemetry
- write candidate/accept/revise/reject rates;
- transition omission/corruption/hallucination;
- memory size by scope/type/sensitivity;
- stale retrieval / invalidated-use rate;
- provenance completeness;
- contradiction set size/resolution latency;
- task lift with/without memory;
- harmful retrieval rate;
- evaluator/model/version distribution;
- rollback blast radius;
- delete/unlearning completeness。
13. Evaluation:把“找到、保留、恢复、迁移”拆开测
13.1 Context acquisition metrics
设 gold evidence 集合 G,在预算 B 下选择 C:
Coverage@B = \frac{|G\cap C|}{|G|}
Precision@B = \frac{|Relevant\cap C|}{|C|}
BudgetYield = \frac{\sum_{e\in C}utility(e)}{Tokens(C)/1000}
还需:
- first useful evidence rank;
- gold control-path distance;
- line-level recall under fixed budget;
- unique evidence yield per query/step;
- query-family switching rate after no-yield;
- abstention/strategy-change correctness;
- downstream diagnosis/edit lift;
- stale/poisoned evidence inclusion rate。
13.2 Packing/position eval
固定相同 evidence set,扰动:
- 顺序:head/middle/tail;
- 无关 token 量与相似干扰项;
- 冲突证据与 authority 标签;
- tool schema 数量;
- stable prefix 与动态规则位置;
- context 总长度;
- 单针、多针、多跳、聚合、比较任务。
输出不仅看 answer accuracy,还看 constraint following、source attribution、uncertainty calibration 与 action selection。
13.3 Compaction continuation equivalence
在同一 checkpoint 建三条 replay:
A: full eligible history
B: compacted history
C: clean reset + structured handoff + on-demand journal retrieval
比较:
ActionAgreement = P(a_{next}^A = a_{next}^B)
GoalSurvival = \frac{preserved\ critical\ goal\ facts}{all\ critical\ goal\ facts}
FailureAvoidance = 1 - P(repeat\ disproven\ path)
以及:
- continuation success;
- extra steps/tokens/wall time;
- duplicate completed work;
- effect-state correctness;
- verifier choice consistency;
- uncertainty calibration;
- provenance recoverability;
- sensitive label preservation;
- long-after-compaction degradation,多次 compaction 累积误差。
“摘要事实问答全部答对”仍不够:Agent 可能记得事实但选择错误下一步。
13.4 Replay/recovery eval
故障注入矩阵:
| 注入点 | 应验证 |
|---|---|
| tool call journaled, effect before receipt | resume 不盲目重复,进入 reconcile |
| partial journal tail | 检测并隔离,不静默 replay |
| compaction candidate generated, not committed | 恢复旧 epoch |
| compaction committed, injection not refreshed | restore 能补齐动态 state |
| schema N/N+1 混合 | migration 后 projection 一致 |
| worker lease loss | 旧 worker 不能继续 commit |
| Git HEAD/dirty tree changed externally | checkpoint 标 stale |
| artifact missing/hash mismatch | fail closed 或重建 |
| provider switch | wire projection 保持合法 |
| media body rejection | degrade/strip 而非无效 token summary |
13.5 Memory transition eval
构造 (M_t, E_t, candidate M_{t+1}),标注:
- 新事实、无关旧事实、冲突事实、时间演化、scope 变化;
- evidence 与 unsupported assertion;
- sensitivity 与 deletion request;
- evaluator bias/source-role trap。
分别测 coverage、preservation、faithfulness,而不是合成一个模糊分数。再做长期 rollouts:错误 transition 经过多次 retrieve/consolidate 后如何放大。
13.6 Memory causal lift
至少有四个条件:
No memory
Raw history retrieval
Governed typed memory
Oracle relevant evidence
只比较有/无 memory 会把 retrieval、compression、model familiarity、额外 token 混在一起。还应做 memory corruption、staleness、scope leakage 的对抗切片。
13.7 Context Eval Card
每次对外声明“支持 1M / 长任务 / 持久记忆”时,应附:
Model / provider / harness / tool versions
Task distribution and repo snapshot
Raw window and effective context policy
Acquisition methods and indexes
Packing order and tool-schema footprint
Compaction trigger/format/count
Memory scope/write/read/invalidation policy
Failure injection coverage
Verifier and judge calibration
Success, cost, latency, safety, recovery metrics
Known blind spots and unsupported generalizations
14. 关键设计决策表
14.1 Journal vs snapshot
| 选择 | 适合 | 代价 | 判断 |
|---|---|---|---|
| Only mutable snapshot | 短、低风险 demo | 无历史、难恢复 | 不适合长期 Coding Agent |
| Journal only | 审计强、事件量可控 | replay 成本 | 配 periodic snapshot/index |
| Journal + derived snapshots | 长期生产 Agent | schema/reducer 复杂度 | 通常最稳妥 |
14.2 Extractive vs abstractive compaction
| 维度 | Extractive | Abstractive |
|---|---|---|
| Faithfulness | 较高 | 依赖模型/verifier |
| Compression ratio | 较低 | 高 |
| Implicit relations | 保留困难 | 可综合 |
| Provenance | 容易 | 需显式映射 |
| 适用 | logs、代码、receipts | decisions、phase handoff |
最佳实践是 hybrid:关键 contract/effect/IDs 结构化或 extractive,叙述关系 abstractive,原始 evidence 可回读。
14.3 Store fact vs store locator
| 条件 | 存事实 | 存 locator/cue |
|---|---|---|
| Source 稳定但读取昂贵 | 是 | 同时存 |
| Source 高频变化且易读 | 否/短 TTL | 是 |
| 需要历史时间点 | versioned fact | versioned locator |
| 高风险 action | 仅作 cache,执行前重验 | 是 |
| Source 可能消失 | 是,带许可/合规 | 是 |
14.4 Global vs scoped memory
默认最窄 scope。只有在跨任务重复验证、无敏感泄漏、适用条件明确时,才提升 scope。Scope promotion 本身是一种需审计的 transition,不应由 embedding 相似度自动完成。
14.5 Eager vs lazy tool/context exposure
| 策略 | 优点 | 风险 |
|---|---|---|
| Eager all tools/docs | 模型一次可见 | token、歧义、攻击面 |
| Lazy discovery | 小 context、清晰 surface | discovery miss、额外延迟 |
| Two-stage catalog → schema | 平衡 | 需要稳定 capability protocol |
14.6 Model summarizer vs dedicated compactor
- 同模型 compaction:policy alignment 较好,但长轨迹能力不足时会一起失败;
- 强模型 compactor:质量可能更高,但成本、风格和 private-context boundary 复杂;
- 小模型 compactor:便宜并可并行,但对隐含约束和代码状态易失真;
- deterministic + LLM hybrid:结构字段由系统提取,模型只综合关系,通常更可控。
15. 公开实现与产品 contract 对照:Kimi 不是 frontier 上界
以下映射基于 MoonshotAI 公开仓库截至 2026-08-03 17:14(UTC+8) 的 main,审阅快照为 75395f6abb17f83f30d16b51f4e060a639f43622;它说明公开实现呈现的机制,不推断内部未公开系统。下列证据链接全部固定到该 commit,避免 main 后续漂移。
Kimi Code 的价值是提供了可逐行审阅的 implementation evidence,不代表 Context/State/Memory 的行业上界。闭源产品可能公开更强的 product contract 却不公开内部算法;其他开源 harness 也可能采用不同且同样重要的状态模型。正确用法是把 Kimi 当一个高信息量实现样本,再与 Codex、Claude Code、pi 的一手资料做三角校验。
15.1 Context Memory:journal-backed conversation model
公开的 contextMemoryService.ts 显示:
- context history 由 Agent-scoped
wiremodel 持有; - append、clear、applyCompaction、undo 都通过 op dispatch;
- live splice 发布
context.spliced,replay 静默重建,避免恢复产生伪 live event; - context size 与 splice/undo/compaction 协同更新;
- compaction 不是直接替换一个随意 messages 变量,而是有结构化 op 与计量结果。
对应本文:journal/reducer 是恢复边界,context 是可重建 model projection,live event 与 replay side effect 分离。
15.2 Loop event folding:原始事件与模型消息投影分离
loopEventFold.ts 将 step.begin/content.part/tool.call/tool.result/step.end 事件折叠为 assistant/tool messages,并处理:
- open step 的 settle;
- pending tool 的 interrupted result;
- tool exchange 期间延迟普通 message,保持 provider 所需 adjacency;
- 无可发送内容的 partial assistant 丢弃;
- live dispatch 与 replay 使用同一 fold 语义。
这是 event sourcing 价值的具体例子:持久化记录更接近事实事件,模型 wire message 是 reducer 产物。
15.3 Context Projector:provider-wire projection 与 repair telemetry
contextProjectorService.ts 负责把 stored context 投影为 provider message,并显式修复/记录:
- tool result 移回对应 call 或对缺失 result 合成中断结果;
- orphan/duplicate call/result 丢弃;
- leading non-user message 丢弃;
- consecutive assistants 合并;
- 空白/vacuous message 丢弃;
- 媒体 body-size/格式失败时只读侧 degrade/strip,原历史保留;
- repair signature 去重,同时发 log 与
context_projection_repairedtelemetry。
对应本文的原则:journal truth、model projection、provider compatibility 与 observability 分层;修复不能静默篡改历史。
15.4 Wire:单一 replay consistency boundary
wire.ts 的公开 contract 将 replayable model state 与 journal 置于一个 Agent-scoped aggregate,包含 dispatch/seal/restore/flush/getModel;注释明确 restore 涵盖 validate、migrate、rewrite、replay、rehydrate 与 ordered restore hook。
对应本文:journal append、model reduce、migration、blob handling 和 restore 不应由调用方跨多个服务临时协调。
15.5 Compaction handoff shape:保留真实用户输入的 head/tail
compactionHandoff.ts 的公开实现展示:
- compaction summary 作为带
origin: compaction_summary的 user-role context message; - 真实用户输入与 injection/shell/task/retry/hook 等 origin 分开处理;
- 用户消息预算默认最多约 20K token,并在需要截断时保留约 2K head + recent tail;
- 中间省略以显式 elision reminder 表示,并记录 omitted token;
- compaction result 记录 tokens before/after、kept user count、dropped count;
- legacy tail shape 有迁移兼容路径。
这里最深的设计不是具体 20K/2K 数字,而是:用户原始输入具有独立 provenance/disposition,摘要之外仍保留头尾,并显式承认中间有省略。
15.6 Full Compaction:后台准备、阻塞、overflow recovery 与并发安全
fullCompactionService.ts 公开机制包括:
- manual/auto source、每 turn 最大 compaction 次数;
- soft/strategy trigger 与需要时阻塞当前 turn;
- provider context overflow 后触发 compaction 并把 failed driver 放回队头;
- 观察实际 overflow 以收紧 effective max context;
- compaction 自己 overflow 时按比例保留 recent history、重试并记录 dropped count;
- truncated/empty summary 不提交,必要时进一步 shrink;
- 提交前
historySafeToCompact检查原 prefix identity,允许新增真实 user input 作为安全 tail; - compaction 后 refresh system prompt、重新 inject 动态 context;
- TODO 被结构化追加到 summary;
- completed/failed/cancelled/blocking 与 token/latency/usage 都有事件和 telemetry。
这是一个完整的 compaction control path,而非单一 summary prompt。
15.7 Undo boundary:不假装跨有损压缩可逆
contextOps.ts 的 computeUndoCut 遇到 compaction summary 会停止,公开错误原因包含 compaction_boundary。这是诚实的产品 contract:有损 compaction 后不能把 UI undo 伪装成原历史仍完整。
15.8 Blob dehydration/rehydration
同一 context ops/model 公开说明:持久化时可把大 data URI offload 为 blob reference;replay 后只对 surviving state rehydrate,已经被 compaction 丢弃的 media 不做无意义 I/O。
对应本文:大 payload 生命周期、journal record 与当前 context projection 分离,token overflow 与 body-size/media failure 是不同错误语义。
15.9 可继续追问 Kimi 的架构张力
公开实现已经清楚处理 context history、wire projection、full compaction、replay 与 repair;面试中更高级的问题不是“有没有 memory”,而是:
- context acquisition/repo retrieval 与这套 journal-backed context 如何合并评测;
- compaction invariant verifier 是否只靠生成完整性,还是有结构化/行为级 replay;
- Agent-scoped state、session/workspace state 与长期 semantic/procedural memory 如何划分;
- 新 model/harness 版本下旧 procedural memory 如何失效;
- compaction telemetry 如何归因到 downstream success,而非只看压缩比;
- provider-specific projector repair 如何进入 eval 与兼容性 contract;
- 多 Agent 是否共享 evidence/memory,如何保留 influence provenance 与 scope isolation。
15.10 先定义三种证据:Product Fact、Implementation Fact、Inference
| 标签 | 含义 | 可以声称 | 不可以声称 |
|---|---|---|---|
| Product fact | 官方产品/开发者文档明确承诺或描述的行为 | 用户可观察 contract、配置、版本要求 | 未公开的数据结构、算法、训练细节 |
| Implementation fact | 固定 commit 的公开源码或 schema 可直接验证 | 该快照真实控制路径与默认值 | 未公开服务、未来版本、作者设计意图之外的普遍规律 |
| Inference | 从多个 fact 推导的工程判断 | 明确标注“本文推论”后的架构结论 | 冒充某家产品事实或行业共识 |
后文按这个标签使用证据。尤其要避免两种常见错误:把 Kimi Code 中名为 contextMemory 的 per-agent conversation history 当成长时 semantic memory;把 Codex/Claude Code 文档里的产品行为反推成未经公开的内部实现。
15.11 Codex native compaction:产品 contract 强,内部实现边界需克制
Product fact:OpenAI 的 Unrolling the Codex agent loop 明确说明:Codex 早期 compaction 会用现有 conversation + custom instructions 生成自然语言 summary;当前 Responses API 提供 /responses/compact,返回可替代旧 input 的 item list,其中包含 opaque type=compaction / encrypted_content,Codex 在超过 auto_compact_limit 后自动调用。2026 年 Responses API computer environment进一步说明,后续窗口由 compaction item 与前窗的高价值部分构成,并把 container filesystem 描述为让 Agent 按需读取、解析、转换资源的 context surface。
Implementation fact:上述页面公开了 client/API control flow 和 wire item contract;它们没有公开 compaction item 内部表示、训练数据、完整不变量 verifier 或所有“高价值部分”的选择算法。因此本文不把 opaque compaction 等同于某种已知 text-summary schema,也不声称它天然满足本文列出的全部 transition invariants。
Inference:native item、模型训练与 API endpoint 联动,说明 frontier compaction 正在成为 model–API–harness 的共同能力,而不仅是外部 summarizer。这个推论支持“评测必须绑定 model + endpoint + harness version”,不支持“opaque 一定优于结构化文本”。
15.12 Claude Code:auto memory、分层 instructions 与长任务 handoff
Product fact — auto memory:Claude Code memory 文档说明,每个 session 从 fresh context 开始,跨 session 信息由人工维护的 CLAUDE.md 与 Claude 自写的 auto memory 两套机制承载。auto memory 自 Claude Code v2.1.59 起可用且默认开启;按 Git repository 建立本机目录,worktree 和子目录共享;MEMORY.md 的前 200 行或 25KB 在每次 session 起始加载,详细 topic files 按需读取;文件是可查看、编辑、删除的 plain Markdown。文档同时明确:这些内容进入 context,而不是强制执行配置。
Product fact — compaction:How Claude Code works说明 Claude Code 接近窗口限制时会先清理旧 tool outputs,必要时再总结 conversation;早期 conversation-only instruction 可能丢失,持久规则应进入 CLAUDE.md。Memory 文档进一步说明 project-root CLAUDE.md 会在 /compact 后从磁盘重读并重新注入,而 nested CLAUDE.md 等到再次读取对应子目录文件才重载。
Product/experiment fact — handoff:Anthropic 2026 long-running harness区分了 in-place compaction 与 clean reset + structured handoff:其 Sonnet 4.5 实验需要 reset 处理 context anxiety,而后续 Opus 4.5 harness 可在 continuous session 中依赖 SDK automatic compaction。这是特定 Anthropic harness/model 的实验事实,不是所有 Claude Code task 的固定策略。
Implementation fact 边界:Claude Code 文档公开了文件位置、加载上限、scope 与用户可见行为,但本文没有对应的完整公开源码快照证明 auto-memory write policy、consolidation algorithm 或 compaction summary internals。因此“默认开启”“per-repo shared across worktrees”“200 行/25KB”等是 product fact,不应包装成源码审计结论。
Inference:Claude Code 把跨时间知识拆成用户拥有的 instructions、Agent 自写且可审计的 memory、当前 session compaction、以及模型依赖的 structured handoff。这支持“memory/compaction/handoff 是不同时间尺度的模块”,但 auto memory 的 transition integrity 仍需单独评测,官方文档的存在不等于写入一定正确。
15.13 pi:compaction 与 session tree 的另一种公开实现
以下 pi 证据固定到 badlogic/pi-mono 的 c6eb6281a806a9c5d7ec41d2850692f7f7ebcb59(2026-08-03)。
Implementation fact — append-only session tree:session-manager.ts 将 session 定义为 JSONL 中的 append-only tree,每个 entry 有 id/parentId,active leaf 决定当前路径;buildSessionContext() 从 leaf 向 root 解析 active path。公开的 session-format.md说明历史分支保存在同一 session file,旧线性格式会迁移到 tree schema。
Implementation fact — compaction entry:compaction 实现在 contextTokens > contextWindow - reserveTokens 时判定应 compact;该快照默认 reserveTokens=16384、keepRecentTokens=20000。它选择 cut point、生成结构化 summary,并追加含 summary / firstKeptEntryId / tokensBefore / usage / readFiles / modifiedFiles 的 CompactionEntry。重建 context 时使用 summary 加 firstKeptEntryId 之后的保留消息;原 session JSONL 中的完整历史没有被物理删除。
Implementation fact — branch summary:branch-summarization.ts在 session-tree navigation 离开分支时,可把被放弃路径压成 BranchSummaryEntry 附着到新位置,并累计 read/modified file tracking。公开 compaction 文档还暴露 session_before_compact / session_before_tree hooks,允许取消或提供自定义 summary。
Inference:pi 明确区分“archival history tree”和“active model path”,并把 branch change 也当成需要 handoff 的信息边界。这为非线性 Agent trajectory 提供了比单一线性 transcript 更直接的状态模型。它仍不自动证明 summary fidelity;full history 可回看也不等于当前模型能自动恢复被压缩掉的细节。
15.14 四个系统放在一起看
| 系统 | 已核验的证据类型 | Active context 跨窗机制 | 跨 session / 分支机制 | 证据边界 |
|---|---|---|---|---|
| Kimi Code | pinned public implementation | text summary + selected real-user head/tail,经 wire op 提交 | wire replay;公开 contextMemory 是 per-agent conversation history |
不代表内部 Kimi 服务或行业上界 |
| Codex / Responses | official product/API contract | opaque native compaction item + high-value prior items | 本节不从公开材料推断长期 semantic memory | compaction internals 未公开 |
| Claude Code | official product docs + Anthropic harness report | old-tool cleanup + conversation summary;root instructions 重注入 | per-repo auto memory;特定长任务可 structured handoff/reset | write/consolidation internals 未做源码审计 |
| pi | pinned public implementation | CompactionEntry + firstKeptEntryId recent path |
append-only JSONL session tree + optional branch summary | summary fidelity 仍需行为级 eval |
由此能得到三条标注为 Inference 的 frontier 判断:
- 没有唯一 frontier representation:opaque native item、结构化文本 summary、user-message head/tail、session-tree branch summary 都在真实系统中存在;
- archive、active context、memory、handoff 正在分层:完整历史可留在 journal/tree,模型只消费当前 path/projection;跨 session 的可复用知识另有 memory/instruction layer;
- 能力上界必须按组合评测:不能用 Kimi public repo、Codex product claim、Claude docs 或 pi implementation 中任一者代替
model × harness × state model × compactor × verifier的端到端证据。
16. 2025–2026 前沿证据:哪些已成结构事实,哪些仍需谨慎
16.1 已有多条一手资料交叉支持的结构判断
Context window 不是有效 context size
2023 的 lost-in-the-middle、2024 的 RULER、Chroma 2025 context-rot 技术报告、2026 deep-search rot 与 classifier-rot 预印本,分别在检索、多针/多跳、受控简单任务、深度搜索和安全监控中观察到长度或位置相关退化。它们共同支持一个有限结论:声明支持的最大 token 数不等于已经证明在全部任务上稳定可用的 effective context。退化形态和幅度依赖模型、任务、位置与干扰内容,因此工程上应测 performance × length × position × clutter × task complexity 曲线,而不是假设统一阈值。
Context management 是循环内 policy
Anthropic 的 Effective context engineering把 context engineering 定义为每次 inference 对不断增长信息的动态策展,并明确讨论 just-in-time retrieval、compaction、structured note-taking;OpenAI 的 Codex loop 与 Kimi Code 公开源码也把 compaction/projection 放在运行循环内。这是三个公开系统/团队的收敛设计信号,不等于已证明所有 Agent 都应采用同一 policy。
外部可执行认知是长上下文的重要补充
2026 预印本 Coding Agents are Effective Long-Context Processors 在其任务与 agent 组合中报告 filesystem + code/terminal tools 能有效执行长语料搜索、过滤、索引和计算。它支持 external cognition 是 latent long context 的有力补充;“最有价值的是查询、authority 与 artifact 回读”是本文据此做出的工程归纳,不是论文直接证明的普遍排序。
Compaction 正从运行时 fallback 进入模型训练目标
OpenAI 在 GPT-5.1-Codex-Max 与 2026 Codex loop / Responses API 材料中说明其模型和产品使用跨窗口 compaction;2026 的 CompactionRL 又从预印本训练研究侧报告联合优化执行与压缩的结果。可以确认的趋势是 compaction 已进入训练与模型—harness 协同设计;跨 model/harness 的收益、触发策略和保真度仍必须单独验证。
Memory 的评测单位正从 read accuracy 转向 transition integrity
TrustMem 聚焦 coverage/preservation/faithfulness,MemIR 聚焦 provenance-role separation,Memory Contagion 聚焦 evaluator bias 的跨时间传播。三者是 2026 年相邻但独立的预印本证据;“memory 应被视为持久状态、授权与数据治理问题,而不只是向量召回”是本文综合它们得到的工程结论,并非三篇论文已共同建立的统一标准。
16.2 仍处早期、不能过度推断的方向
Fully learned context policy
让模型端到端学习 acquire/select/compact/write/read 可能提升整体 reward,但可解释性、分布外失效、隐私 scope、rollback 与 benchmark overfit 都未解决。较可信的近期形态是:模型学习软策略,系统保持 hard invariants、effect state、authority 与 audit boundary。
One universal memory representation
typed memory 很重要,但不存在已证明适用于 coding、personalization、research、多 Agent 协作的唯一 schema。应保留稳定原则:source-role separation、temporal semantics、scope、transition verification;具体 atom/graph/vector 结构按任务选。
Context-free “infinite agents”
跨多个窗口或 session 可以扩展 horizon,但每次 compression、handoff、retrieval、environment reconciliation 都有误差。任务寿命增长不是免费线性扩展,真正瓶颈会转向 verifier、state integrity 和组织记忆。
Memory self-improvement flywheel
从成功 trajectory 自动蒸馏 procedure 可能有效,也可能把 evaluator bias、harness workaround、偶然性放大。没有 counterfactual、held-out task、versioning 与 rollback 的 memory flywheel,不应称为持续学习。
16.3 面试时如何表达证据强度
建议用三档语言:
- Confirmed in public implementation:公开源码可直接定位机制,例如 Kimi Code wire/projector/compaction;
- Supported by multiple independent evaluations:例如长 context 利用随长度/位置退化;
- Promising preprint result:例如具体 learned compaction 或 memory transition 训练增益,说明数字与设定,不外推为行业定论。
17. 首席讲师级深追问:30 组答题骨架
每组不是背诵答案,而是展示定义、机制、取舍、失败、可观测性和验证闭环。
Q1. 1M context 是否让 retrieval 和 compaction 过时?
结论:没有。窗口长度是容量上限,retrieval/compaction 解决证据稀疏、成本、位置偏置、staleness、污染与跨窗口状态迁移。
展开骨架:
- 区分 raw window、effective usable context、task horizon;
- 说明 long context、retrieval、external cognition 各自强项;
- 引入 lost-in-middle/context rot 与 tool-schema footprint;
- 给出 hybrid:多路检索 → 外部处理 → 关键证据长上下文综合;
- 评测 length × position × clutter × task,而不是 NIAH 单点。
深追问防守:如果模型未来完全消除位置退化,retrieval 仍提供 freshness、authority filtering、隐私隔离、成本和可审计 provenance。
Q2. Context 和 State 的根本区别是什么?
结论:Context 是某次模型请求的有限视图;State 是系统对任务/环境的持久认知。Context 可以丢弃重建,State 必须跨 compaction、retry、resume 存活。
展开骨架:用 C_t=P(S_t,J,M,E,B);举例模型未看到旧 tool receipt,但 state 仍必须知道 effect 已发生;指出把二者放同一 messages 数组导致恢复、审计和 UI/provider 耦合。
Q3. Transcript 为什么不能当 journal?
结论:Transcript 服务人类可读,允许折叠、合并、隐藏;journal 服务事实重放,必须有稳定 ID、顺序、因果、schema 和 effect 语义。
展开骨架:以流式 assistant、tool call/result、retry、partial step 为例;说明 transcript projection 和 model projection 应由同一 journal 生成,但面向不同消费者。
Q4. Repository context engine 应如何设计?
结论:不是 embedding top-k,而是 hypothesis-driven、phase-aware 的多路 acquisition loop。
展开骨架:
- 搜索意图分类;
- lexical → symbol/AST → graph → trace/test/git → semantic;
- control-path proximity、freshness、authority、token cost 综合排序;
- 读到新 symbol 后动态扩展;
- 固定 line/token budget 单独评 coverage、rank、downstream lift。
Q5. 为什么 semantic retrieval 不能单栈解决代码仓库?
结论:代码的 exact identifier、类型、引用、build/test/config graph 和运行路径包含 embedding 不稳定表达的结构信号。
展开骨架:semantic 适合命名未知与自然语言 issue;lexical 适合 error/key;LSP/AST 适合 symbol;trace/test 适合真实控制路径。没有单一路线覆盖全部任务。
Q6. Context selection 如何形式化?
结论:带 hard coverage constraints 的预算优化,而非简单 top-k。
展开骨架:定义 relevance/control/authority/freshness/uncertainty reduction,减 token/redundancy/staleness/poisoning;用 MMR 做多样化;goal、用户决定、未决 effect 等作为 mandatory slots。
Q7. Packing 有什么技术含量?
结论:相同 evidence 的顺序、authority 隔离、bundle 结构、重复和 tool footprint 会改变行为。
展开骨架:stable authority prefix;goal/state;evidence+locator+version;recent effect/verifier;末尾 current decision;沿位置/长度/干扰项做 eval。
Q8. 什么是 context rot?与 lost-in-the-middle 有何区别?
结论:lost-in-middle 是位置相关利用退化;context rot 是输入增长导致更广泛的性能/判断/监控退化,可能包含早停、拒答、漏检。
展开骨架:引用长 context eval 证据;指出首尾重复只缓解位置偏置;工程上用裁剪、阶段摘要、独立 monitor packet、长度压力评测。
Q9. 怎样判断 context 足够了?
结论:不是 token 满,而是关键 claim 有 evidence、冲突已显式、控制路径闭环、下一动作的 expected information gain 不再高于执行/验证。
展开骨架:coverage requirements、uncertainty ledger、abstention;对高风险行动要求 authority evidence fresh;低风险探索可容忍不完整。
Q10. Compaction 的目标函数是什么?
结论:未来行动/验证行为等价,而非摘要文本相似。
展开骨架:π(a|compact,future)≈π(a|full,future);关键 invariant 严格保留;行为级 A/B replay;测重复工作、重走失败路径、effect correctness、最终成功与成本。
Q11. Compaction 必须保留哪些不变量?
结论:goal/non-goal、验收、authority、用户决定、verified facts+provenance、effects、working state、negative evidence、open risks、todo/next action、summary range/version。
深追问防守:不是全部都写进自由文本;contract/effects/IDs 应结构化,叙述关系再摘要。
Q12. Compaction 怎样处理并发的新消息和 tool result?
结论:冻结 prefix,提交前验证 prefix identity/sequence;允许定义清楚的安全 tail;用 epoch/CAS 防旧 compaction 覆盖新状态。
展开骨架:tool call 尚无 result 的 prefix 不应被总结成已完成;commit op 与 token state 同 consistency boundary;提交后 refresh 动态 prompt/injections。
Q13. Compaction 自己 overflow 怎么办?
结论:这是独立恢复路径。需在 hard limit 前触发;若 compaction request overflow,受控 shrink、保留 recent/critical、记录 dropped count、限制尝试次数,最终 fail explicit。
错误答案:无限 retry 或继续对 summary 做 summary,会形成 compaction spiral。
Q14. 何时选择 clean reset 而不是 compaction?
结论:当 phase/agent/model 切换、trajectory 污染严重、旧策略锚定明显,且外部 state/artifacts 足够可靠时,reset + structured handoff 更干净。
取舍:连续性损失 vs 污染清除;用同 checkpoint 三路 replay 实证,而非品牌偏好。
Q15. Checkpoint 与 compaction 有什么区别?
结论:Compaction 缩短模型可见历史;checkpoint 建立可恢复一致性边界。Checkpoint 是 journal seq、task version、repo/worktree、effect watermark、memory/context epoch、verifier state 的向量。
Q16. 为什么 Git commit 不是完整 checkpoint?
结论:Git 只覆盖部分 workspace;不含目标、决策、remote effects、process、untracked artifacts、verification 和 user-owned dirty state。
展开骨架:把 Git pointer 纳入 vector checkpoint;resume 时 environment reconcile。
Q17. Event sourcing 对 Agent 有何价值,代价是什么?
结论:价值是 replay、debug、migration、多投影、effect audit;代价是 event schema、reducer、snapshot、migration 与并发顺序复杂度。
高级回答:不主张把所有 scratch state event-source;只把恢复/审计/跨边界关键 transition journal 化,保持模块深度。
Q18. 如何处理“工具可能执行成功,但结果没记下来”?
结论:状态是 unknown,不是 success/failure。用 idempotency key、effect receipt、查询式 reconciliation;不可查询且不可逆时需要人工决策。
展开骨架:区分 delivery semantics 与 effect semantics;不要承诺 exactly-once 幻觉。
Q19. Replay 为什么不能简单重放 tool calls?
结论:Replay 应重放事件到 state,不重新执行副作用。Tool effect 的重试必须经过独立 recovery policy、idempotency 与当前环境确认。
Q20. Working memory、episodic memory、semantic memory、procedural memory 如何划界?
结论:内容分类不足,还要给 scope、source role、time、verification、sensitivity。Working state 属于当前任务;episodic 是可追溯经历;semantic 是相对稳定 claim;procedural 是有适用条件和成功证据的策略。
Q21. Memory write policy 应默认宽松还是保守?
结论:按风险分层,事实/全局 procedure 保守,低风险显式偏好可相对宽松。可从 authority source 低成本重读的内容优先存 locator/cue。
关键点:错误 write 是持久系统故障,错误 read 通常只影响一次 context。
Q22. Typed memory 解决了什么?
结论:阻止 provenance-role collapse。Evidence、claim、cue、policy、preference 的 authority 不同;检索到 evidence 不等于可以直接把其中任意文本当真。
展开骨架:claim 必须引用 support IDs;projection 按 provenance scope;transform chain 保留 source role。
Q23. Memory 中两个事实冲突如何 merge?
结论:先判 temporal succession、scope difference、source disagreement、true correction,再决定 supersede、并存、invalidate。不能让 LLM 润色成模糊折中。
Q24. 怎样评测 memory?
结论:三层:transition integrity、retrieval/authorization、downstream causal lift。
展开骨架:coverage/preservation/faithfulness;scope/freshness/contradiction;no-memory/raw-history/typed-memory/oracle 四组;长期 contamination rollout。
Q25. 什么是 Memory Contagion?
结论:偏差可从 evaluator → trajectory → consolidation → memory → future agent 跨时间传播,即使 consolidation 本身完美。
展开骨架:保存 outcome evidence 与 evaluator/version;calibration、多 judge、bias cohort、shadow/canary memory、rollback;不能只升级 summarizer。
Q26. 如何做 memory invalidation?
结论:TTL 只是一个手段。更可靠的是 source dependency、version/event invalidation、temporal supersession、model/harness compatibility 与 manual correction。
深追问防守:执行高风险动作前重读 authoritative source;memory 仅作 cue/cache。
Q27. Filesystem 作为 external cognition 有何风险?
结论:路径漂移、无类型、并发覆盖、敏感残留、cache 冒充 truth、artifact 删除、版本不匹配。
展开骨架:manifest、kind/authority、input digest、rebuild command、scope、GC;只让可寻址可重建 artifact 进入 handoff。
Q28. 怎样避免 prompt injection 通过 repo/memory 获取 authority?
结论:内容通道与 authority 通道分离。Repo/web/memory evidence 按 untrusted data 进入;只有系统/用户授权策略控制 action。Provenance-scoped projection、capability restriction 与高风险 revalidation 共同防护。
Q29. 你会怎样评测 Kimi Code 的 compaction?
结论:利用其公开 wire/compaction telemetry 和 replayable state,在同一 journal checkpoint 做 full/compact/reset 三路 continuation;沿多次 compaction、并发 user tail、tool pending、overflow、truncated summary、provider switch 做故障注入。
指标:goal survival、next-action agreement、repeated failure、effect correctness、continuation success、token/latency、repair count、provenance recovery。
Q30. 如果只能为 Context/State/Memory 设一个北极星指标,会选什么?
结论:没有单一无害指标;若必须选,选在真实 checkpoint 上、固定 verifier 下的 risk-adjusted continuation success per cost,并设 integrity guardrails。
NorthStar = \frac{P(successful\ verified\ continuation)-\lambda P(integrity/safety\ failure)}{tokens+latency+human\ review\ cost}
高级回答:coverage、compaction ratio、memory hit rate 都易被 gaming;必须由 goal/effect/provenance/memory integrity guardrail 限制。
18. 面试中的完整系统回答模板
遇到任何 Context/State/Memory 题目,按以下顺序展开,能避免只讲名词:
- 对象与边界:这是 context view、task state、journal、memory 还是 environment truth?
- 生命周期:何时创建、更新、压缩、失效、恢复、删除?
- 数据流:source → normalize/provenance → select/project → model/action → journal/memory;
- 硬不变量:goal、authority、effects、source role、scope、temporal correctness;
- 设计分支:long context/retrieval/external cognition,snapshot/journal,compact/reset,fact/locator;
- 极端失败:race、overflow、partial effect、stale index、poisoning、contagion;
- 可观测性:stable IDs、版本、selection reason、transition、repair、effect receipt;
- 评测:固定 checkpoint 的对照/故障注入/downstream continuation;
- 证据强度:公开实现、跨研究共识、单篇 preprint 分开说;
- Kimi 映射:落到 wire、context model、projector、full compaction、telemetry 的公开控制路径。
一个高质量的两分钟总答:
我不会把 context、state 和 memory 视为同一个 messages 数组。Context 是每次推理的有限物化视图;state 是独立于模型注意力的任务事实;journal 是可重放事件;memory 是经 scope、provenance、时间与 transition verifier 治理的跨会话知识。读路径上,我会按当前 phase 用 lexical、symbol、graph、Git、trace、semantic 多路获取证据,做 authority/freshness/控制路径/预算排序,再按 authority、goal、state、evidence、effect 的层级打包。写路径上,tool effects 先变成 receipt 和 journal event,再由 reducer 重建 state;只有有重复价值且通过 coverage、preservation、faithfulness 检查的候选才进入 memory。长任务中 compaction 必须保持 goal、用户决定、verified facts、effects、失败路径、working state 和 provenance,并通过 full/compact/reset 三路 continuation replay 测行为等价。Kimi Code 公开架构里的 wire、loop-event fold、context projector、full compaction 和 repair telemetry,正好体现了这些边界:持久事实、模型投影、provider repair 与有损压缩不是一层。
19. 一手资料索引
Kimi / Moonshot
- Kimi Code 公开仓库
- 本文审阅的 Kimi Code commit:75395f6
- Agent context memory service
- Context memory ops / replay reducers
- Loop event fold
- Compaction handoff shape
- Context projector
- Full compaction service
- Wire aggregate contract
Claude Code / pi 产品与公开实现
- Claude Code: How Claude remembers your project
- Claude Code: How Claude Code works
- Claude Code: Explore the context window
- pi 本文审阅 commit:c6eb628
- pi session manager / tree implementation
- pi session JSONL tree format
- pi compaction implementation
- pi branch summarization implementation
- pi compaction and branch-summarization documentation
Context、长上下文与 external cognition
- Anthropic: Effective context engineering for AI agents, 2025
- Anthropic: Harness design for long-running applications
- OpenAI: Unrolling the Codex agent loop, 2026
- OpenAI: Equipping the Responses API with a computer environment
- OpenAI: GPT-5.1-Codex-Max and native compaction, 2025
- Chroma technical report: Context Rot, 2025
- Lost in the Middle, 2023
- RULER, 2024
- Coding Agents are Effective Long-Context Processors, 2026
- Diagnosing and Mitigating Context Rot in Long-horizon Search, 2026
- Classifier Context Rot, 2026
- CompactionRL, 2026
Repository acquisition / retrieval
Memory integrity 与 provenance
20. 最终审视:真正“讲透”的判定标准
Context/State/Memory 的系统理解至少应能独立回答以下问题,而不依赖产品口号:
- 能否画出 raw evidence、journal、state、context、transcript、memory 的边界与数据流?
- 能否解释一次模型请求为什么选择这些证据、丢弃哪些证据、版本是什么?
- 能否在 context 被清空后从 journal + environment 恢复 task state?
- 能否识别 tool effect 已发生但 receipt 未落盘的未知状态?
- 能否定义 compaction 的 invariant、事务边界和行为级 A/B eval?
- 能否说明 long context、retrieval、external cognition 的条件边界?
- 能否让 memory claim 追到 evidence,并阻止 source role 在多次摘要中升级?
- 能否对 memory write 做 coverage、preservation、faithfulness、scope、time 检查?
- 能否发现和回滚 evaluator bias 经 memory 传播的影响?
- 能否用 Kimi Code 公开源码指出 journal-backed context、projection repair、compaction race handling 与 undo boundary 的真实控制路径?
如果只能讲“向量数据库、摘要、1M context、RAG”,还停留在组件名层面;如果能说明状态所有权、事件语义、证据 authority、压缩不变量、恢复协议、转移完整性与行为级评测,才进入 Coding Agent infra 的系统层。