Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

Introduce Working Memory v2: 7-section session memory, anti-bloat guards, sliding-window tokens, and OpenClaw integration (#1782)

Eurakaxun51342319b41d
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 307bb5f57..308c8aed7 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -686,20 +686,39 @@ export class OpenVikingClient {
*/
async commitSession(
sessionId: string,
- options?: { wait?: boolean; timeoutMs?: number; agentId?: string },
+ options?: {
+ wait?: boolean;
+ timeoutMs?: number;
+ agentId?: string;
+ /**
+ * WM v2: number of most-recent messages to keep live after commit.
+ * Forwarded as `keep_recent_count` in the POST body. 0 (default)
+ * preserves the pre-v2 "archive everything" behavior.
+ */
+ keepRecentCount?: number;
+ },
): Promise<CommitSessionResult> {
+ const keepRecentCount =
+ options?.keepRecentCount != null && Number.isFinite(options.keepRecentCount)
+ ? Math.max(0, Math.floor(options.keepRecentCount))
+ : 0;
await this.emitRoutingDebug(
"session commit POST (archive + memory extraction)",
{
path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
sessionId,
wait: options?.wait ?? false,
+ keepRecentCount,
},
options?.agentId,
);
+ const body: Record<string, unknown> = {};
+ if (keepRecentCount > 0) {
+ body.keep_recent_count = keepRecentCount;
+ }
const result = await this.request<CommitSessionResult>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
- { method: "POST", body: JSON.stringify({}) },
+ { method: "POST", body: JSON.stringify(body) },
options?.agentId,
);
@@ -764,6 +783,40 @@ export class OpenVikingClient {
);
}
+ async grepSessionArchives(
+ sessionId: string,
+ pattern: string,
+ options: {
+ archiveId?: string;
+ caseInsensitive?: boolean;
+ nodeLimit?: number;
+ levelLimit?: number;
+ agentId?: string;
+ } = {},
+ ): Promise<{
+ matches: Array<{ line: number; uri: string; content: string }>;
+ count: number;
+ match_count?: number;
+ files_scanned?: number;
+ }> {
+ const baseUri = `viking://session/${sessionId}/history`;
+ const uri = options.archiveId ? `${baseUri}/${options.archiveId}` : baseUri;
+ return this.request(
+ "/api/v1/search/grep",
+ {
+ method: "POST",
+ body: JSON.stringify({
+ uri,
+ pattern,
+ case_insensitive: options.caseInsensitive ?? true,
+ ...(options.nodeLimit !== undefined ? { node_limit: options.nodeLimit } : {}),
+ ...(options.levelLimit !== undefined ? { level_limit: options.levelLimit } : {}),
+ }),
+ },
+ options.agentId,
+ );
+ }
+
async deleteSession(sessionId: string, agentId?: string): Promise<void> {
await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" }, agentId);
}
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index 6e4d8f6a6..fc9c439d4 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -38,6 +38,13 @@ export type MemoryOpenVikingConfig = {
/** @deprecated Use recallMaxInjectedChars. */
recallTokenBudget?: number;
commitTokenThreshold?: number;
+ /**
+ * WM v2: number of most-recent messages to keep live after an afterTurn
+ * commit so the next turn still has immediate context. Forwarded to the
+ * server as `keep_recent_count`. Default 10. The compact path ignores this
+ * value and always passes 0.
+ */
+ commitKeepRecentCount?: number;
bypassSessionPatterns?: string[];
/**
* When true (default), emit structured `openviking: diag {...}` lines (and any future
@@ -59,6 +66,7 @@ const DEFAULT_RECALL_MAX_CONTENT_CHARS = 5000;
const DEFAULT_RECALL_PREFER_ABSTRACT = false;
const DEFAULT_RECALL_MAX_INJECTED_CHARS = 4000;
const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;
+const DEFAULT_COMMIT_KEEP_RECENT_COUNT = 10;
const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];
const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;
const DEFAULT_AGENT_PREFIX = "";
@@ -176,6 +184,7 @@ export const memoryOpenVikingConfigSchema = {
"recallPreferAbstract",
"recallTokenBudget",
"commitTokenThreshold",
+ "commitKeepRecentCount",
"bypassSessionPatterns",
"ingestReplyAssist",
"ingestReplyAssistMinSpeakerTurns",
@@ -292,6 +301,13 @@ export const memoryOpenVikingConfigSchema = {
0,
Math.min(100_000, Math.floor(toNumber(cfg.commitTokenThreshold, DEFAULT_COMMIT_TOKEN_THRESHOLD))),
),
+ commitKeepRecentCount: Math.max(
+ 0,
+ Math.min(
+ 1_000,
+ Math.floor(toNumber(cfg.commitKeepRecentCount, DEFAULT_COMMIT_KEEP_RECENT_COUNT)),
+ ),
+ ),
bypassSessionPatterns: toStringArray(
cfg.bypassSessionPatterns,
toStringArray(
@@ -436,6 +452,14 @@ export const memoryOpenVikingConfigSchema = {
advanced: true,
help: "Minimum estimated pending tokens before auto-commit triggers. Set to 0 to commit every turn.",
},
+ commitKeepRecentCount: {
+ label: "Commit Keep Recent Count",
+ placeholder: String(DEFAULT_COMMIT_KEEP_RECENT_COUNT),
+ advanced: true,
+ help:
+ "Number of most-recent messages to keep live after an afterTurn commit. " +
+ "Forwarded as keep_recent_count to the server. Compact path always uses 0.",
+ },
emitStandardDiagnostics: {
label: "Standard diagnostics (diag JSON lines)",
advanced: true,
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index 3a553c590..2c7b58547 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -605,40 +605,29 @@ function buildSystemPromptAddition(): string {
return [
"## Session Context Guide",
"",
- "Your conversation history may include:",
+ "Your conversation history includes two layers:",
"",
- "1. **[Session History Summary]** — A compressed summary of all prior",
- " conversation sessions. Use it to understand background and continuity.",
- " It is lossy: specific details (commands, file paths, code, config",
- " values) may have been compressed away. It may be omitted when the",
- " token budget is tight.",
+ "1. **[Session History Summary]** — A compressed summary of all prior turns",
+ " in this session. It is organized into structured sections (Key Facts,",
+ " Timeline, People, etc.). Use it for background and continuity.",
+ " The summary is lossy: specific details (exact dates, numbers, names,",
+ " small events) may have been compressed away.",
"",
- "2. **[Archive Index]** — A list of archive entries in chronological order",
- " (archive_001 is the oldest, higher numbers are more recent). Most",
- " lines summarize one archive; the latest archive may appear as an ID",
- " pointer only.",
- "",
- "3. **Active messages** — The current, uncompressed conversation.",
- "",
- "**When you need precise details from a prior session:**",
- "",
- "1. Review [Archive Index] to identify which archive likely contains",
- " the information you need.",
- "2. Call `ov_archive_expand` with that archive ID to retrieve the",
- " archived conversation content.",
- "3. If multiple archives look relevant, try the most recent one first.",
- "4. Answer using the retrieved content together with active messages.",
+ "2. **Active messages** — The most recent uncompressed turns.",
"",
"**Rules:**",
- "- If active messages conflict with archive content, trust active",
- " messages as the newer source of truth.",
- "- Only expand an archive when the existing context lacks the specific detail needed.",
- "- If [Session History Summary] is absent, use [Archive Index] and active",
- " messages to decide whether to expand an archive.",
- "- Do not fabricate details from summaries. When uncertain, expand first",
- " or state that the information comes from a compressed summary.",
- "- After expanding, cite the archive ID in your answer",
- ' (e.g. "Based on archive_003, ...").',
+ "- When active messages conflict with the Summary, trust active messages",
+ " as the newer source of truth.",
+ "- Do not fabricate details the Summary does not state explicitly.",
+ "- **CRITICAL: Before answering 'no information' or 'not mentioned',",
+ " you MUST carefully re-read EVERY section of the [Session History Summary].",
+ " The answer may be expressed with different wording than the question.",
+ " Look for synonyms, related facts, and indirect references.**",
+ "- If the Summary mentions a topic but lacks the specific detail asked,",
+ " use the `ov_archive_search` tool to grep the original archived messages",
+ " for the exact detail. Try 2-3 different keywords extracted from the question.",
+ "- Only conclude information is unavailable AFTER both checking the Summary",
+ " thoroughly AND searching the archives with at least 2 keyword variations.",
].join("\n");
}
@@ -649,8 +638,8 @@ function buildInstructionPrompt(): { text: string; tokens: number } {
function buildArchiveMemory(
archiveOverview: string | undefined,
- preAbstracts: Array<{ archive_id: string; abstract: string }>,
- budget: number,
+ _preAbstracts: Array<{ archive_id: string; abstract: string }>,
+ _budget: number,
): { messages: AgentMessage[]; tokens: number } {
const messages: AgentMessage[] = [];
@@ -661,33 +650,7 @@ function buildArchiveMemory(
});
}
- if (preAbstracts.length > 0) {
- const lines = preAbstracts.map((a) => `${a.archive_id}: ${a.abstract}`);
- messages.push({
- role: "user",
- content: `[Archive Index]\n${lines.join("\n")}`,
- });
- }
-
- let tokens = roughEstimate(messages);
- if (budget === BUDGET_UNLIMITED || tokens <= budget || preAbstracts.length <= ARCHIVE_INDEX_TRIM_LIMIT) {
- return { messages, tokens };
- }
-
- const trimmed = preAbstracts.slice(-ARCHIVE_INDEX_TRIM_LIMIT);
- const trimmedMessages: AgentMessage[] = [];
- if (archiveOverview) {
- trimmedMessages.push({
- role: "user",
- content: `[Session History Summary]\n${archiveOverview}`,
- });
- }
- trimmedMessages.push({
- role: "user",
- content: `[Archive Index]\n${trimmed.map((a) => `${a.archive_id}: ${a.abstract}`).join("\n")}`,
- });
- tokens = roughEstimate(trimmedMessages);
- return { messages: trimmedMessages, tokens };
+ return { messages, tokens: roughEstimate(messages) };
}
/** Merge consecutive assistant messages by concatenating their content arrays. */
@@ -833,7 +796,11 @@ export function createMemoryOpenVikingContextEngine(params: {
ovSessionId: ovId,
});
const agentId = resolveAgentId(sessionId, sessionKey, ovId);
- const commitResult = await client.commitSession(ovId, { wait: true, agentId });
+ const commitResult = await client.commitSession(ovId, {
+ wait: true,
+ agentId,
+ keepRecentCount: 0,
+ });
const memCount = totalExtractedMemories(commitResult.memories_extracted);
if (commitResult.status === "failed") {
logger.warn?.(`openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}`);
@@ -1290,7 +1257,11 @@ export function createMemoryOpenVikingContextEngine(params: {
return;
}
- const commitResult = await client.commitSession(OVSessionId, { wait: false, agentId });
+ const commitResult = await client.commitSession(OVSessionId, {
+ wait: false,
+ agentId,
+ keepRecentCount: cfg.commitKeepRecentCount,
+ });
logger.info(
`openviking: committed session=${OVSessionId}, ` +
`status=${commitResult.status}, archived=${commitResult.archived ?? false}, ` +
@@ -1385,7 +1356,11 @@ export function createMemoryOpenVikingContextEngine(params: {
logger.info(
`openviking: compact committing session=${OVSessionId} (wait=true, tokenBudget=${tokenBudget})`,
);
- const commitResult = await client.commitSession(OVSessionId, { wait: true, agentId });
+ const commitResult = await client.commitSession(OVSessionId, {
+ wait: true,
+ agentId,
+ keepRecentCount: 0,
+ });
const memCount = totalExtractedMemories(commitResult.memories_extracted);
if (commitResult.status === "failed") {
diff --git a/examples/openclaw-plugin/docs/workmemory-v2-design.md b/examples/openclaw-plugin/docs/workmemory-v2-design.md
new file mode 100644
index 000000000..bb3d80a71
--- /dev/null
+++ b/examples/openclaw-plugin/docs/workmemory-v2-design.md
@@ -0,0 +1,338 @@
+# OpenViking Working Memory v2 — 设计文档
+
+## 文档目标
+
+本文描述 OpenViking Working Memory v2(以下简称 WM v2)的当前实现:设计原则、数据结构、协议、流程,以及对应代码位置。
+
+---
+
+## 当前能力
+
+### afterTurn(每轮对话后自动归档)
+
+| 能力 | 说明 |
+|---|---|
+| 自动检测归档时机 | `pending_tokens` 滑动窗口,O(1) 计算 |
+| 增量更新 WM | tool_call + JSON schema + 服务端 Guards |
+| 归档后保留最近消息 | `keep_recent_count`,保持上下文连贯 |
+
+### compact(主动上下文压缩)
+
+| 能力 | 说明 |
+|---|---|
+| 全量重写 WM 并归档 | `keep_recent_count=0`,彻底压缩 |
+
+### assemble(构建 LLM 上下文)
+
+| 能力 | 说明 |
+|---|---|
+| WM overview 作为会话摘要 | 结构化 7 段模板 + 旧格式自动升级 |
+| 按 archive_id 展开归档原文 | `ov_archive_expand` 工具 / API 读取单个 completed archive 的原始消息 |
+| 按关键词跨 archive 回查 | `ov_archive_search` 工具,服务端 grep 命中消息 + archive 标签 |
+
+### 通用
+
+| 能力 | 说明 |
+|---|---|
+| 信息保留 Guards | 5 个段级保护函数 |
+
+---
+
+## 一、设计方案
+
+### 1.1 设计原则
+
+**原则 1:archive 本体就是 working memory,用固定的结构化模板承载**
+
+archive 的 `.overview.md` 是**固定 7 段结构化模板**(Session Title / Current State / Task & Goals / Key Facts & Decisions / Files & Context / Errors & Corrections / Open Issues)。每段有明确的职责,LLM 不能随意增删段落。
+
+有结构才能做增量更新——LLM 对每个段独立发 `KEEP` / `UPDATE` / `APPEND` 操作,未变化的段发 `KEEP` 由服务端原样复制(零 token 消耗、零信息丢失),变化的段走校验后合并。
+
+向后兼容性的 3 条保证:
+
+- `assemble()` 消费的仍然是 `latest_archive_overview`,无新增数据通路
+- `getSessionContext()` 返回字段不变
+- 存储结构(`archive_NNN/.overview.md`)不变
+
+**原则 2:信息保留是系统责任,不是 LLM 责任**
+
+LLM 只负责「判断变了什么」,服务端 guard 函数负责「保证不丢信息」。具体机制见 §1.4。
+
+**原则 3:向后兼容与平滑升级**
+
+- 不配置新字段时行为完全不变,`keep_recent_count=0` 等价于全量归档
+- 已有旧格式 overview 的会话:服务端自动检测 overview 是否包含 WM 7 段 header。如果是 legacy 格式,走创建路径全量生成 WM,不走 tool_call 增量更新——下一次 commit 时自动完成格式升级,无需手动迁移
+
+### 1.2 WM 数据结构
+
+WM 是一份 Markdown 文档,固定 7 个 section,顺序不变:
+
+```markdown
+# Working Memory
+
+## Session Title
+_简短独特的 5-10 词标题,信息密集_
+
+## Current State
+_当前工作状态、待完成任务、下一步_
+
+## Task & Goals
+_用户目标、关键设计决策、解释性上下文_
+
+## Key Facts & Decisions
+_重要结论、技术选择及理由、用户偏好与约束_
+
+## Files & Context
+_重要文件 / 函数 / 模块及路径_
+
+## Errors & Corrections
+_遇到的错误及修复、用户纠正、失败方案_
+
+## Open Issues
+_未解决问题、阻塞项、后续风险_
+```
+
+每段上限 ~2000 tokens,总 WM 上限 ~12000 tokens(prompt 指引层面的预算约束)。服务端 guard 在单段 ≥ 25 bullets 或 ≥ 1500 tokens 时触发 consolidation 提醒。
+
+### 1.3 增量更新协议
+
+WM 更新通过 **tool_call(function calling)+ JSON schema** 实现:LLM 调用 `update_working_memory` 工具,以结构化 JSON 提交对 7 个段的逐段操作。JSON schema 强约束保证漏段、多段、格式错误在 schema 层直接拦截。
+
+#### tool schema 定义
+
+```python
+WM_SEVEN_SECTIONS = [
+ "Session Title", "Current State", "Task & Goals",
+ "Key Facts & Decisions", "Files & Context",
+ "Errors & Corrections", "Open Issues",
+]
+
+WM_UPDATE_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "update_working_memory",
+ "parameters": {
+ "type": "object",
+ "required": ["sections"],
+ "additionalProperties": False,
+ "properties": {
+ "sections": {
+ "type": "object",
+ "required": list(WM_SEVEN_SECTIONS), # 7 段全部必填
+ "additionalProperties": False,
+ "properties": {name: _WM_SECTION_OP_SCHEMA
+ for name in WM_SEVEN_SECTIONS},
+ }
+ },
+ },
+ },
+}
+```
+
+每段的操作(`_WM_SECTION_OP_SCHEMA`)用 `oneOf` 约束为三种形状之一:
+
+- `{"op": "KEEP"}` — 原样保留
+- `{"op": "UPDATE", "content": "..."}` — 全段替换
+- `{"op": "APPEND", "items": ["...", "..."]}` — 追加条目
+
+`op` 字段使用 `"type": "string", "enum": ["KEEP"]` 形式,兼容更多 JSON Schema 版本。`additionalProperties: false` + `required` 把 LLM 输出严格钉在这个 schema 里。
+
+#### 段级合并
+
+服务端 `_merge_wm_sections(old_wm, ops)` 按 `WM_SEVEN_SECTIONS` 常量遍历 7 段:
+
+- **KEEP** → 原样复制旧内容
+- **UPDATE** → 用 LLM 提供的 content 替换(先经过该段的 guard 校验)
+- **APPEND** → 旧内容 + LLM 提供的 items(渲染为 `- item`)
+- 漏段 / 未知 op → 兜底 KEEP
+
+关键实现:`session.py: _merge_wm_sections()` + `_parse_wm_sections()`
+
+### 1.4 服务端 Guards
+
+Guards 是服务端在合并 LLM 提交的操作时按段执行的语义校验函数:**即使 LLM 说 UPDATE,服务端也根据段的特性决定是否接受**。
+
+7 个段的保护策略:
+
+| 段 | 数据特点 | Guard | 规则 |
+|---|---|---|---|
+| Session Title | **锚定型**:会话身份标识,不应随意变更 | `_wm_enforce_title_stability` | UPDATE 与旧 title meaningful-word overlap < 1 → 回退 KEEP |
+| Current State | **易变型**:每轮反映当前状态 | 无 | LLM 可自由 UPDATE |
+| Task & Goals | **易变型**:目标随会话推进自然变化 | 无 | LLM 可自由 UPDATE |
+| Key Facts & Decisions | **累积型**:重要结论不断积累,丢失代价高 | `_wm_enforce_key_facts_consolidation` | 双阈值验证:bullet count ≥ 旧 15% 且 lexical anchor coverage ≥ 70%。被拒时提取新 items 做 APPEND |
+| Files & Context | **引用型**:文件路径一旦提及不应消失 | `_wm_enforce_files_no_regression` | UPDATE 丢失旧路径 → KEEP + APPEND 新路径 |
+| Errors & Corrections | **只增型**:错误记录只增不删 | `_wm_enforce_append_only` | UPDATE 降级为 APPEND,去重后只追加新条目 |
+| Open Issues | **跟踪型**:未解决项不应被静默丢弃 | `_wm_enforce_open_issues_resolved` | silently drop 的 item → 加 `[restored]` 标签恢复 |
+
+Errors 是纯 append-only(UPDATE 总被降级为 APPEND);Key Facts 允许「受控合并」——LLM 提交的合并 UPDATE 通过双阈值验证后可被接受。
+
+关键实现:`session.py: _wm_enforce_*()` 5 个函数。单元测试覆盖在 `tests/unit/session/test_wm_v2_guards.py`(共 107 用例覆盖 5 个 guard + growth + 通用 schema)。
+
+### 1.5 滑动窗口与 pending_tokens
+
+`SessionMeta` 维护 `pending_tokens: int` 和 `keep_recent_count: int`,持久化到 `.meta.json`。
+
+- `add_message` 时:新消息进入保留窗口尾部,窗口头部被挤出的消息 token 累加到 `pending_tokens`
+- `commit` 时 `pending_tokens` 归零
+- `GET /sessions/{id}` 直接读 meta,O(1)
+
+服务端有防御性 clamp:`pending_tokens` 与 `keep_recent_count` 都 `max(0, ...)`。`CommitRequest.keep_recent_count` 在 router 层有 `ge=0, le=10_000` 约束。
+
+关键实现:`session.py: add_message()` + `SessionMeta`、`routers/sessions.py: CommitRequest`
+
+### 1.6 保留最近消息
+
+commit 归档时不全量清空消息,保留最近 N 条维持上下文连贯。
+
+- 参数 `keep_recent_count` 由插件在 commit API body 中传入
+- `afterTurn` 路径默认 10,`compact` 路径硬编码 0
+- OV 存储模型保证 `tool_use` / `tool_result` 配对完整性(ToolPart 自包含)
+
+关键实现:`session.py: commit_async(keep_recent_count)`、`routers/sessions.py: CommitRequest`、`context-engine.ts`、`client.ts`
+
+---
+
+## 二、流程
+
+### 2.1 afterTurn 流程
+
+插件端不变,commit 在服务端完成:
+
+```
+[插件] afterTurn
+ ├── extractNewTurnMessages → 提取新消息
+ ├── addSessionMessage → 逐条 POST /sessions/{id}/messages
+ │ 服务端: append msg + 滑动窗口更新 pending_tokens + save meta
+ ├── GET /sessions/{id} → 返回 pending_tokens(O(1))
+ └── pending_tokens >= commitTokenThreshold?
+ │
+ YES → commitSession(wait=false, keepRecentCount=cfg.commitKeepRecentCount)
+ │
+ [服务端 commit_async]
+ │
+ ├── Phase 1(同步,不阻塞返回)
+ │ ├── split_idx = total - keep_recent_count
+ │ ├── 归档 messages[:split_idx] → archive_NNN/
+ │ ├── 保留 messages[split_idx:]
+ │ └── pending_tokens = 0, 更新 meta
+ │
+ └── Phase 2(asyncio.create_task 后台执行,包在
+ request_wait_tracker.register_request / wait_for_request /
+ cleanup 包络内,确保所有下游 enqueue 都被等待)
+ ├── 读旧 WM: _get_latest_completed_archive_overview()
+ ├── 有旧 WM?
+ │ YES → ov_wm_v2_update prompt + tool_call
+ │ → guards 检查每段决策
+ │ → _merge_wm_sections 段级合并
+ │ NO → ov_wm_v2 prompt 全量创建
+ ├── 写入 archive_NNN/.overview.md + .abstract.md + .meta.json
+ ├── 提取 long-term memory(compressor_v2,需 archive_uri 才能写 memory_diff.json)
+ ├── 等待 embedding / semantic 队列排空(wait_for_request)
+ └── 写入 .done(最后写,标志该 archive 全部状态终结)
+```
+
+Phase 2 关键细节:
+
+- **格式检测**:读取旧 overview 后,先检查是否包含 WM 7 段 header(`any(f"## {s}" in overview for s in WM_SEVEN_SECTIONS)`)。如果是 legacy 格式,走创建路径而非 tool_call 更新——保证平滑升级
+- **Section reminders**:更新路径中,`_build_wm_section_reminders()` 从旧 WM 提取每段当前状态摘要,注入到 update prompt 的 `wm_section_reminders` 变量
+- **完整回退链**:tool_call 缺失 → `_fallback_generate_wm_creation` 重跑(传入旧 WM 作为上下文);JSON parse 失败 → 正则 recovery → 段级 guard 兜底 KEEP;VLM 不可用 → 占位 summary
+- **Phase 2 队列等待**:`register_request` + `wait_for_request(timeout=_PHASE2_QUEUE_WAIT_TIMEOUT_SECONDS=1800s)` 是必需的——否则下游 `compressor` / `memory_updater` 通过 `register_*_root` 注册的 embedding / semantic 队列无人 await,会让 `tracker.complete()` 与 `.done` 在向量化 / 语义入库**之前**就触发,导致调用方看到 commit 完成但 memory 不可检索
+
+### 2.2 compact 流程
+
+```
+[插件] compact
+ └── commitSession(wait=true, keepRecentCount=0)
+ ├── Phase 1: 全部消息 → archive, messages.clear()
+ ├── Phase 2: 读旧 WM → 创建/更新 → 写入
+ └── 返回 → getSessionContext → 回读最新 WM
+```
+
+### 2.3 assemble(上下文组装)
+
+instruction / archive / session 三分区:
+
+```
+┌──────────── System Prompt ────────────────────┐
+│ systemPromptAddition(语义示意,非逐字): │
+│ 1. [Session History Summary] 是压缩摘要 │
+│ 2. Active messages 是最新未压缩上下文 │
+│ 3. 二者冲突时优先 active messages │
+│ 4. 缺细节时询问用户,不要猜 │
+│ + 原始 system prompt │
+└────────────────────────────────────────────────┘
+
+┌──── Layer 1: Archive Memory (≤8K tokens) ─────┐
+│ [user] [Session History Summary] │
+│ # Working Memory │
+│ ## Session Title │
+│ ## Current State │
+│ ## Task & Goals │
+│ ## Key Facts & Decisions │
+│ ## Files & Context │
+│ ## Errors & Corrections │
+│ ## Open Issues │
+└────────────────────────────────────────────────┘
+
+┌──── Layer 2: Session Context ─────────────────┐
+│ server 侧合并后的 ctx.messages: │
+│ - 未完成 archive 的 pending messages │
+│ - 当前 live session messages │
+└────────────────────────────────────────────────┘
+
+┌──── Layer 3: Reserved (≥20K tokens) ──────────┐
+│ LLM 回复空间 │
+└────────────────────────────────────────────────┘
+```
+
+实现要点:
+
+- `pre_archive_abstracts` 字段保留在 API(向后兼容),但服务端固定返回空数组,插件侧 `buildArchiveMemory()` 只消费 `latest_archive_overview`
+- 若需要具体 archive 原文,模型走两条路径:按 `archive_id` 用 `ov_archive_expand` 展开;或用 `ov_archive_search` 按关键词跨 archive grep(见 §三)
+
+---
+
+## 三、归档对话回查工具
+
+OpenViking 在插件侧暴露两个独立的 archive 回查工具。
+
+### 3.1 `ov_archive_expand`
+
+- **插件工具**:`ov_archive_expand`,参数 `archiveId: string`
+- **服务端 API**:`GET /api/v1/sessions/{session_id}/archives/{archive_id}`,server 返回 `{archive_id, abstract, overview, messages}`
+- **工具输出给 LLM**:archive header(`## archive_id` + `**Summary**: abstract` + `**Messages**: N`) + 全部原始 messages(faithful 文本格式)。`overview` 不重复输出(已经在主上下文 `[Session History Summary]` 里)
+- **工具 description 文本**:`"Retrieve original messages from a compressed session archive. Use when a session summary lacks specific details such as exact commands, file paths, code snippets, or config values. Check [Archive Index] to find the right archive ID."`
+
+### 3.2 `ov_archive_search`
+
+- **插件工具**:`ov_archive_search`,参数 `query: string` + 可选 `archiveId: string`
+- **客户端封装**:`client.grepSessionArchives(sessionId, pattern, options)`
+- **服务端 API**:`POST /api/v1/search/grep`,body `{uri, pattern, case_insensitive}`。`uri` 默认 `viking://session/{sessionId}/history`(覆盖所有 archive);指定 `archiveId` 时收窄为 `viking://session/{sessionId}/history/{archiveId}`
+- **工具输出给 LLM**:最多 12 条命中消息,每条最多 1500 字符,附 archive 标签(如 `archive_005`)和行号
+- **行为约束**:
+ - 默认遍历所有 archive(新到旧)
+ - 默认永远不返回完整 archive 原文
+ - case-insensitive;正则元字符自动转义为字面量匹配
+- **工具 description 文本**:`"Keyword-grep across all archived original conversation messages of the current session. Use this whenever the [Session History Summary] does not contain the specific detail the user is asking about. Extract 2-3 concrete entity words from the question (names, places, objects, dates) and search each separately. Only conclude information is unavailable after trying at least 2 different keyword variations."`
+
+---
+
+## 四、关键代码索引
+
+| 主题 | 路径 |
+|---|---|
+| WM 7 段常量与 schema | `openviking/session/session.py: WM_SEVEN_SECTIONS / _WM_SECTION_OP_SCHEMA / WM_UPDATE_TOOL` |
+| 段级合并 | `openviking/session/session.py: _merge_wm_sections() / _parse_wm_sections()` |
+| 5 个 Guards | `openviking/session/session.py: _wm_enforce_*()` |
+| Phase 2 主循环 | `openviking/session/session.py: _run_memory_extraction()` |
+| 滑动窗口 / pending_tokens | `openviking/session/session.py: SessionMeta / add_message()` |
+| commit API + keep_recent_count clamp | `openviking/server/routers/sessions.py: CommitRequest` |
+| WM v2 prompt 模板 | `prompts/templates/compression/ov_wm_v2.yaml`、`ov_wm_v2_update.yaml` |
+| 插件 commit / afterTurn / compact | `examples/openclaw-plugin/context-engine.ts` |
+| 插件 ov_archive_search 工具 | `examples/openclaw-plugin/index.ts: ov_archive_search` |
+| 插件 ov_archive_expand 工具 | `examples/openclaw-plugin/index.ts: ov_archive_expand` |
+| 单元测试 | `tests/unit/session/test_wm_v2_guards.py`、`test_working_memory_growth.py`、`test_working_memory_v2.py`(共 107 用例) |
+
+---
+
+> **创建**:2026-05-02
diff --git a/examples/openclaw-plugin/docs/workmemory-v2-test-report.md b/examples/openclaw-plugin/docs/workmemory-v2-test-report.md
new file mode 100644
index 000000000..3e53b5b3a
--- /dev/null
+++ b/examples/openclaw-plugin/docs/workmemory-v2-test-report.md
@@ -0,0 +1,146 @@
+# OpenViking Working Memory v2 — 测试报告
+
+> 数据集:locomo10 · MemoryArena group_travel_planner · 模型:doubao-seed-2-0-code-preview
+> 创建:2026-05-02
+
+---
+
+## 核心结论
+
+1. **LoCoMo 长对话事实召回**:WM v2 在 152Q 上达 **79.61%**(旧版 23.68%,**+55.93pp**);35Q 上达 **94.29%**(旧版 28.57%,**+65.7pp**)。
+2. **Token 效率**:
+ - **35Q**:WM v2 总 QA tokens **184,497**(旧版 144,797,**多 27.4%**);但准确率涨 +65.7pp,单题成本(tok/correct)从 14,480 降到 **5,591**(约 **1/2.6**)。
+ - **152Q**:WM v2 总 QA tokens **1,510,190**(旧版 2,280,098,**节省 33.8%**);准确率涨 +55.93pp,单题成本从 63,336 降到 **12,481**(约 **1/5.1**)。
+ - 整体趋势:35Q 是「以 token 换准确率」(总量略增 + 单题大幅降本),152Q 是**双向收益**(总量降 + 单题降)。
+3. **纯工作记忆是主体收益**:关闭长期记忆向量召回仍能达 **73.03%**(152Q),autoRecall 在此基础上再补 **+6.58pp**。
+4. **MemoryArena 跨会话规划任务**:跟 OV 主分支无 WM 严格 A/B 大体持平(**QA +3.06pp / Action −2.04pp**);跟 MC 原生比 WM v2 显著领先(**QA +35.03pp / token −21.76%**)。该任务不直接验证工作记忆,结论不外推到 LoCoMo。
+
+---
+
+## 一、测试目标
+
+验证 WM v2(结构化 7 段模板 + tool_call 增量更新 + 服务端 Guards + `keep_recent_count`)相比旧版(`compression.structured_summary` v1)的实际效果。重点回答 3 个问题:
+
+1. WM v2 在小样本(35Q)和大样本(152Q)下相对 Main 的准确率提升
+2. WM v2 结构化 overview 的独立贡献(关闭向量召回)
+3. WM v2 + autoRecall 联合方案的最佳效果
+
+---
+
+## 二、测试环境
+
+| 项 | 值 |
+|---|---|
+| LLM | doubao-seed-2-0-code-preview |
+| Embedding | doubao-embedding-vision-251215 |
+| Gateway | OpenClaw 2026.4.27 |
+| Main 分支 | OpenViking @ `origin/main`,commit `4d6f5b65` |
+| WM2 分支 | 工作记忆代码 |
+| Judge | doubao-seed-2-0-code-preview-260215 |
+
+---
+
+## 三、LoCoMo 测试结果
+
+### 3.1 测试组
+
+| 测试组 | 说明 | autoRecall | 设计目的 |
+|---|---|---|---|
+| **WM2** | 工作记忆 + 长期记忆 + 工具回溯 | on | WM v2 全功能端到端测试 |
+| WM2-NOREC | 工作记忆 + 工具回溯(关闭长期记忆) | off | 隔离工作记忆 + 工具回溯的独立贡献,看不靠向量召回时还能拿多少分 |
+| MAIN | 原 overview + 长期记忆 + 老版工具回溯(仓库主分支代码) | on | 旧版基线 |
+| MC | OpenClaw 原生记忆(关闭 OpenViking) | — | 横向对比 OpenClaw 原生记忆方案 |
+
+### 3.2 数据集
+
+| 数据集 | session 数 | QA 数 | 说明 |
+|---|---|---|---|
+| locomo-small | 19 | 35 | LoCoMo sample 0 前 35 题,小样本快速对照 |
+| locomo10 case0 | 19 | 152 | LoCoMo sample 0 完整 |
+
+> Ingest 和 QA 同会话(QA 会话连续,复用前题上下文)——目的是测试工作记忆。
+
+### 3.3 locomo-small(35Q)
+
+| 测试组 | 准确率 | QA tokens | tok/correct |
+|---|---|---|---|
+| MAIN | 28.57% (10/35) | 144,797 | 14,480 |
+| **WM2** | **94.29% (33/35)** | **184,497** | **5,591** |
+| WM2-NOREC | 88.57% (31/35) | 124,246 | **4,008** |
+| MC | 42.86% (15/35) | 2,352,395 | 156,826 |
+
+**对比**:
+
+- **纯工作记忆(WM2-NOREC 测试组,关闭长期记忆向量召回)相比旧版 MAIN**:准确率从 28.57% 提升到 88.57%,**+60.0pp**;QA tokens 反而下降 14.2%(144,797 → 124,246),单题成本从 14,480 降到 **4,008**(**3.6× 效率**)。仅靠结构化 7 段 overview + 工具回溯,无需任何向量召回,已经能拿到大部分提升,且 token 同时节省。
+- **叠加长期记忆向量召回(WM2 测试组)相比纯工作记忆**:准确率再升 **+5.7pp**(88.57% → 94.29%);代价是 QA tokens 增加 48.5%(124,246 → 184,497),单题成本从 4,008 升到 **5,591**。长期记忆是用 token 换最后一段准确率的细节召回,边际收益递减但仍正向。
+- **OpenClaw 原生记忆(MC 测试组,关闭 OpenViking 改由 LLM 主动 memorySearch)横向对照**:仅 42.86%,单题成本 156,826(是 WM2 的 **28 倍**)——准确率比 WM2 低 **51.4pp**,无竞争力。
+
+### 3.4 locomo10 case0(152Q)
+
+将 §3.3 对照扩展到 locomo10 case0 全量 152 道 QA:
+
+| 测试组 | 准确率 | QA tokens | tok/correct |
+|---|---|---|---|
+| MAIN | 23.68% (36/152) | 2,280,098 | 63,336 |
+| **WM2** | **79.61% (121/152)** | **1,510,190** | **12,481** |
+| WM2-NOREC | 73.03% (111/152) | 1,622,319 | 14,615 |
+
+**对比**:
+
+- **纯工作记忆(WM2-NOREC 测试组,关闭长期记忆向量召回)相比旧版 MAIN**:准确率从 23.68% 提升到 73.03%,**+49.35pp**;QA tokens 同时下降 28.8%(2,280,098 → 1,622,319),单题成本从 63,336 降到 **14,615**(**4.3× 效率**)。在大样本上,纯结构化工作记忆已贡献整体提升的约 88%(49.35 / 55.93),且 token 大幅节省。
+- **叠加长期记忆向量召回(WM2 测试组)相比纯工作记忆**:准确率再升 **+6.58pp**(73.03% → 79.61%);QA tokens **再节省 6.9%**(1,622,319 → 1,510,190),单题成本从 14,615 降到 **12,481**。与 35Q 的「以 token 换准确率」不同,长样本上长期记忆是**双向收益**——既提升准确率,又因更高效答题而节省 token。
+
+---
+
+## 四、MemoryArena Group Travel 对比测试
+
+MemoryArena `group_travel_planner` 是跨会话的旅行规划任务(slot-filling + 后续 QA),**不直接验证工作记忆能力**——每个 task 是独立 session,没有跨题上下文累积。本节把它作为另一个测试场景,从两个角度看 WM v2 的表现:
+
+1. **跟 MC 原生比**(§4.2):WM v2 相对「OpenClaw 自带 memorySearch」的整体能力差距
+2. **严格 A/B**(§4.3):跟 OV 主分支无 WM(OV-noWM)做同源对比,单变量评估 WM 改造对此类任务有无副作用
+
+### 4.1 数据集与方法
+
+| 维度 | 说明 |
+|---|---|
+| 数据集 | MemoryArena `group_travel_planner`(270 task / 1869 subtask 的多日多人旅行规划) |
+| 子样本 | sample0 / sample1 / sample2 共 **294 道 slot-level QA** |
+| 任务结构 | slot-filling 旅行规划 + 后续 QA(跨 task 独立 session) |
+
+**指标说明**:
+
+- **Action**:slot-filling 规划阶段的执行准确率——agent 在多步规划过程(订机票、订酒店、选餐厅等)中正确填充 expected slot(如 flight number / departure time / arrival time)的比例。衡量 agent 在规划**执行阶段**的动作准确性。
+- **QA**:slot-filling 完成后问答阶段的答题准确率——agent 基于 task 上下文回答 slot-level 问题的正确率。衡量 agent 在**记忆/检索阶段**的能力。
+- **Combined Tokens**:规划阶段(run)+ 问答阶段(QA)两阶段消耗的总 token。
+
+### 4.2 WM v2 vs MC 原生
+
+把 WM v2 跟 MC 原生(关闭 OpenViking、由 LLM 主动调 `memorySearch`)放在同一数据集上对比:
+
+| 方案 | sample0 Action | sample1 Action | sample2 Action | **Agg Action** | **Agg QA** | Combined Tokens |
+|---|---|---|---|---|---|---|
+| MC memorySearch | 8/104 | 24/70 | 26/120 | 58/294 (19.73%) | 74/294 (25.17%) | 7,158,830 |
+| **WM v2** | **66/104** | **38/70** | **79/120** | **183/294 (62.24%)** | **177/294 (60.20%)** | 5,601,097 |
+
+WM v2 相比 MC 原生:**Action +42.52pp**,**QA +35.03pp**,Combined Tokens **−21.76%**。
+
+### 4.3 严格 A/B(WM v2 vs OV-noWM)
+
+| Sample | OV-noWM Action | OV-noWM QA | WM v2 Action | WM v2 QA |
+|---|---|---|---|---|
+| sample0 | 71/104 (**68.27%**) | 65/104 (**62.50%**) | 66/104 (63.46%) | 60/104 (57.69%) |
+| sample1 | 52/70 (**74.29%**) | 45/70 (**64.29%**) | 38/70 (54.29%) | 38/70 (54.29%) |
+| sample2 | 66/120 (55.00%) | 58/120 (48.33%) | **79/120 (65.83%)** | **79/120 (65.83%)** |
+| **Aggregate** | **189/294 (64.29%)** | 168/294 (57.14%) | 183/294 (62.24%) | **177/294 (60.20%)** |
+
+WM v2 vs OV-noWM:**Action −2.04pp**(OV-noWM 略胜),**QA +3.06pp**(WM 略胜),token +2.75%。per-sample 异质性较高(sample1 OV-noWM 大幅领先、sample2 WM v2 大幅领先),aggregate 大体持平。
+
+### 4.4 观察
+
+- **跟 MC 原生比**:WM v2 在 QA 准确率上 **+35.03pp**(25.17% → 60.20%),同时 token 节省 **21.76%**——在 slot-filling 任务上 OpenViking + 工作记忆的整体表现远胜 MC 自检索方案。
+- **跟 OV-noWM 严格 A/B**:QA 略胜(**+3.06pp**)/ Action 略输(**−2.04pp**)/ token 略增(**+2.75%**)——没有显著退化也没有显著提升,符合预期(slot-filling 不直接受工作记忆改造影响)。
+- **任务定位**:MemoryArena 是跨会话规划任务,每个 task 独立 session,**不直接测工作记忆**;以上两组对比说明 WM v2 在此类任务上**没有副作用**,且仍显著优于 MC 自检索方案。
+
+---
+
+> **创建**:2026-05-02
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 512617ed9..2c64a1fac 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -1104,7 +1104,11 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
undefined,
roleId,
);
- const commitResult = await c.commitSession(sessionId, { wait: true, agentId: session.agentId });
+ const commitResult = await c.commitSession(sessionId, {
+ wait: true,
+ agentId: session.agentId,
+ keepRecentCount: 0,
+ });
const memoriesCount = totalCommitMemories(commitResult);
if (commitResult.status === "failed") {
api.logger.warn(
@@ -1280,6 +1284,108 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
}),
{ name: "memory_forget" },
);
+
+ api.registerTool(
+ (ctx: ToolContext) => ({
+ name: "ov_archive_search",
+ label: "Archive Search (OpenViking)",
+ description:
+ "Keyword-grep across all archived original conversation messages of the current session. " +
+ "Use this whenever the [Session History Summary] does not contain the specific detail " +
+ "the user is asking about. Extract 2-3 concrete entity words from the question " +
+ "(names, places, objects, dates) and search each separately. " +
+ "Only conclude information is unavailable after trying at least 2 different keyword variations.",
+ parameters: Type.Object({
+ query: Type.String({
+ description:
+ "A single keyword or short phrase to grep. Use concrete nouns, names, dates, " +
+ "or distinctive phrases. Case-insensitive. Prefer entity words over full sentences.",
+ }),
+ archiveId: Type.Optional(
+ Type.String({
+ description: 'Optional: limit search to one archive (e.g. "archive_005")',
+ }),
+ ),
+ }),
+ async execute(_toolCallId: string, params: Record<string, unknown>) {
+ if (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("ov_archive_search");
+ }
+ rememberSessionAgentId(ctx);
+ const sessionId = ctx.sessionId ?? "";
+ const sessionKey = ctx.sessionKey ?? "";
+ if (!sessionId && !sessionKey) {
+ return {
+ content: [{ type: "text", text: "Error: no active session." }],
+ details: { error: "no_session" },
+ };
+ }
+ const ovSessionId = openClawSessionToOvStorageId(ctx.sessionId, ctx.sessionKey);
+ const query = String((params as { query?: string }).query ?? "").trim();
+ const archiveId = (params as { archiveId?: string }).archiveId;
+
+ if (!query) {
+ return {
+ content: [{ type: "text", text: "Error: query is required." }],
+ details: { error: "missing_param", param: "query" },
+ };
+ }
+
+ const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ api.logger.info?.(`openviking: ov_archive_search query="${query}" escaped="${escapedQuery}" archive=${archiveId ?? "all"} session=${ovSessionId}`);
+
+ try {
+ const client = await getClient();
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const result = await client.grepSessionArchives(ovSessionId, escapedQuery, {
+ archiveId,
+ caseInsensitive: true,
+ agentId,
+ });
+
+ if (!result.matches || result.matches.length === 0) {
+ return {
+ content: [{
+ type: "text",
+ text: `No matches found for "${query}". Try a different keyword — ` +
+ "the original conversation may use different wording than the question. " +
+ "Try synonyms, related terms, or shorter fragments.",
+ }],
+ details: { query, matchCount: 0 },
+ };
+ }
+
+ const MAX_MATCHES = 12;
+ const MAX_LINE_LEN = 1500;
+ const shown = result.matches.slice(0, MAX_MATCHES);
+ const blocks = shown.map((m, i) => {
+ const archiveTag = m.uri.match(/archive_\d+/)?.[0] ?? "unknown";
+ const truncated = m.content.length > MAX_LINE_LEN
+ ? m.content.slice(0, MAX_LINE_LEN) + "…(truncated)"
+ : m.content;
+ return `## Match ${i + 1}: ${archiveTag} (line ${m.line})\n${truncated}`;
+ });
+
+ const header = `Found ${result.matches.length} match(es) for "${query}"` +
+ (result.matches.length > MAX_MATCHES ? ` (showing first ${MAX_MATCHES})` : "") + ":";
+
+ return {
+ content: [{ type: "text", text: header + "\n\n" + blocks.join("\n\n") }],
+ details: { query, matchCount: result.matches.length },
+ };
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ api.logger.error?.(`openviking: ov_archive_search error: ${msg}`);
+ return {
+ content: [{ type: "text", text: `Archive search failed: ${msg}` }],
+ details: { error: msg },
+ };
+ }
+ },
+ }),
+ { name: "ov_archive_search" },
+ );
+
api.registerTool((ctx: ToolContext) => ({
name: "ov_archive_expand",
label: "Archive Expand (OpenViking)",
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index a51ede901..2f8638beb 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -130,6 +130,12 @@
"advanced": true,
"help": "Minimum estimated pending tokens before auto-commit triggers. Set to 0 to commit every turn."
},
+ "commitKeepRecentCount": {
+ "label": "Commit Keep Recent Count",
+ "placeholder": "10",
+ "advanced": true,
+ "help": "WM v2: number of most-recent messages kept live after an afterTurn commit. Compact path always uses 0."
+ },
"emitStandardDiagnostics": {
"label": "Standard diagnostics (diag JSON lines)",
"advanced": true,
@@ -219,6 +225,11 @@
"commitTokenThreshold": {
"type": "number"
},
+ "commitKeepRecentCount": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 1000
+ },
"bypassSessionPatterns": {
"type": "array",
"items": {
diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
index 70027b4bb..8aefd7db3 100644
--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
@@ -125,10 +125,6 @@ describe("context-engine assemble()", () => {
role: "user",
content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
},
- {
- role: "user",
- content: "[Archive Index]\narchive_001: Previously discussed repository setup.",
- },
{
role: "assistant",
content: [
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
index 52c9813f8..ff4f2db35 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -262,10 +262,6 @@ describe("context-engine assemble()", () => {
content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
});
expect(result.messages[1]).toEqual({
- role: "user",
- content: "[Archive Index]\narchive_001: Previously discussed repository setup.",
- });
- expect(result.messages[2]).toEqual({
role: "assistant",
content: [{ type: "text", text: "Stored answer from OpenViking." }],
});
@@ -329,10 +325,6 @@ describe("context-engine assemble()", () => {
content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
});
expect(result.messages[1]).toEqual({
- role: "user",
- content: "[Archive Index]\narchive_001: Previously discussed repository setup.",
- });
- expect(result.messages[2]).toEqual({
role: "assistant",
content: [
{ type: "text", text: "I checked the latest context." },
@@ -345,7 +337,7 @@ describe("context-engine assemble()", () => {
},
],
});
- expect(result.messages[3]).toEqual({
+ expect(result.messages[2]).toEqual({
role: "toolResult",
toolCallId: "tool_123",
toolName: "read_file",
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index 802b7b3bb..007df8416 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -611,10 +611,10 @@ describe("OpenViking search command parsing", () => {
});
describe("Plugin registration", () => {
- it("registers all 6 tools", () => {
+ it("registers all 7 tools", () => {
const { api } = setupPlugin();
contextEnginePlugin.register(api as any);
- expect(api.registerTool).toHaveBeenCalledTimes(6);
+ expect(api.registerTool).toHaveBeenCalledTimes(7);
});
it("registers import and search commands", () => {
diff --git a/openviking/prompts/templates/compression/ov_wm_v2.yaml b/openviking/prompts/templates/compression/ov_wm_v2.yaml
new file mode 100644
index 000000000..61172aad8
--- /dev/null
+++ b/openviking/prompts/templates/compression/ov_wm_v2.yaml
@@ -0,0 +1,87 @@
+metadata:
+ id: "compression.ov_wm_v2"
+ name: "Working Memory v2 - Creation"
+ description: "Produce a structured Working Memory document for a session archive (no prior WM)."
+ version: "2.2.0"
+ language: "en"
+ category: "compression"
+
+variables:
+ - name: "messages"
+ type: "string"
+ description: "Session content to summarize into the new Working Memory"
+ required: true
+ - name: "latest_archive_overview"
+ type: "string"
+ description: "Optional prior Working Memory. When provided, still-valid info should be carried forward."
+ required: false
+ default: ""
+
+template: |
+ You are a session note-taker. Produce a structured Working Memory document
+ that captures everything a future assistant would need to seamlessly continue
+ this conversation — whether the topic is coding, personal stories, research,
+ planning, or anything else.
+
+ {% if latest_archive_overview %}
+ Previous Working Memory (carry forward still-valid information):
+ <previous_working_memory>
+ {{ latest_archive_overview }}
+ </previous_working_memory>
+ {% endif %}
+
+ Conversation content:
+ <session_content>
+ {{ messages }}
+ </session_content>
+
+ Output a complete Working Memory using the 7-section structure below.
+
+ RULES:
+ - All 7 section headers and italic descriptions must appear unchanged.
+ - Write INFO-DENSE content: names, numbers, dates, locations, exact values.
+ - For temporal facts, record the EVENT date, not the conversation date.
+ Example: conversation on May 8 mentions "I went yesterday" -> record "7 May".
+ - "Current State" is highest priority — always reflect the latest status.
+ It must be a brief 2-5 sentence snapshot, NOT a comprehensive fact dump.
+ Detailed facts belong in "Key Facts & Decisions".
+ - "Key Facts & Decisions" records durable facts about the USER'S WORLD — not
+ about the note-taking process itself. Include people, relationships, events,
+ choices, constraints, preferences, technical decisions, etc.
+ - "Files & Context" is for any referenced resource that a future answer might
+ depend on: file paths, document links, key URLs. Apply a relevance filter —
+ omit decorative media or bulk URL dumps that carry no answerable information.
+ - If previous WM is provided: carry forward valid info, update changed items.
+ - Keep each section under ~2000 tokens; the entire document under ~12000 tokens.
+ These budgets are intentionally generous — prefer preserving concrete facts
+ over terseness. Only compress when genuinely approaching the budget.
+ - Do not fabricate information.
+ - Focus on actionable, specific information that enables continuation.
+
+ Output:
+
+ # Working Memory
+
+ ## Session Title
+ _A short and distinctive 5-10 word descriptive title for the session. Info-dense, no filler._
+
+ ## Current State
+ _2-5 sentences MAX: What is the latest status? What is unresolved or pending? Immediate next steps. NOT a fact dump._
+
+ ## Task & Goals
+ _What is the purpose or topic of this conversation? Key objectives, design decisions, or context that frames the discussion._
+
+ ## Key Facts & Decisions
+ _Stable facts about the user's world: conclusions, relationships, preferences, constraints, technical choices with rationale, commitments, dates, quantities. One bullet per fact._
+
+ ## Files & Context
+ _Referenced resources that future answers may depend on: file paths, document links, key URLs — each with why it matters. Omit bulk media/search dumps._
+
+ ## Errors & Corrections
+ _Mistakes, misunderstandings, or failed approaches — and how they were corrected. User corrections to assistant's assumptions._
+
+ ## Open Issues
+ _Unresolved questions, blockers, follow-ups, risks, or topics to revisit._
+
+llm_config:
+ temperature: 0.0
diff --git a/openviking/prompts/templates/compression/ov_wm_v2_update.yaml b/openviking/prompts/templates/compression/ov_wm_v2_update.yaml
new file mode 100644
index 000000000..d306beca0
--- /dev/null
+++ b/openviking/prompts/templates/compression/ov_wm_v2_update.yaml
@@ -0,0 +1,199 @@
+metadata:
+ id: "compression.ov_wm_v2_update"
+ name: "Working Memory v2 - Incremental Update (tool_call)"
+ description: "Incrementally update an existing Working Memory by emitting per-section decisions via the `update_working_memory` tool."
+ version: "2.4.0"
+ language: "en"
+ category: "compression"
+
+variables:
+ - name: "latest_archive_overview"
+ type: "string"
+ description: "Current (prior) Working Memory to be updated."
+ required: true
+ - name: "messages"
+ type: "string"
+ description: "New conversation content since the last update."
+ required: true
+ - name: "wm_section_reminders"
+ type: "string"
+ description: "Dynamic section-size warnings generated from the current Working Memory."
+ required: false
+ default: ""
+
+template: |
+ You are the Working Memory maintainer for a long-running session. Your one and
+ only job is to produce a per-section decision via the `update_working_memory`
+ tool. The session will keep going for many more rounds, so information you
+ drop now is GONE — nobody else will put it back.
+
+ <current_wm>
+ {{ latest_archive_overview }}
+ </current_wm>
+
+ <new_content>
+ {{ messages }}
+ </new_content>
+
+ {% if wm_section_reminders %}
+ {{ wm_section_reminders }}
+ {% endif %}
+
+ # RULE 0 — Produce a continuation-grade Working Memory.
+
+ The goal is a document that lets a future assistant seamlessly continue the
+ conversation. Concrete facts (names, dates, decisions, relationships, exact
+ values) MUST survive. But repetitive events of the same type should be
+ consolidated into patterns — "Caroline attended 5 pride parades" is better
+ than 5 separate entries. The test: can a new assistant answer the user's
+ likely follow-up questions from this WM alone?
+
+ Before you choose an op for a section, mentally list the CONCRETE FACTS it
+ currently holds:
+ * names, relationships, and personal details of people mentioned
+ * dates, locations, and events (who did what, when, where)
+ * explicit decisions with rationale
+ * preferences, constraints, commitments, and promises
+ * file paths, module names, technical parameters (if applicable)
+ * error messages, root causes, fixes (if applicable)
+ * follow-up items that were not yet resolved
+
+ If an item on that list is still true (not contradicted by <new_content>), it
+ MUST appear in your output — either verbatim or as part of a consolidated
+ summary that preserves the same concrete details. Losing a durable fact is a
+ correctness bug.
+ Exception: raw exhaustive URL/image/search result dumps are NOT durable facts
+ unless the user explicitly asked to preserve them or a specific URL was used
+ as evidence. Summarize or prune bulk URL lists instead of copying them forward.
+
+ # RULE 1 — Op semantics (re-read carefully).
+
+ - **KEEP** — The existing section already reflects reality. Server preserves
+ it byte-for-byte. Emit {"op": "KEEP"}.
+
+ - **UPDATE** — Rewrite the section with full content. CRITICAL: an UPDATE must
+ include every still-valid concrete fact from the previous version PLUS the
+ new information. UPDATE is "previous + diff", not "only the new stuff".
+ Emit {"op": "UPDATE", "content": "<full new body, markdown, NO header line>"}.
+
+ - **APPEND** — Add one or more bullet items to the existing body. Use this for
+ sections that grow monotonically (new decisions, new errors, new references).
+ Server will render each item as "- <item>" under the existing body.
+ Emit {"op": "APPEND", "items": ["item 1", "item 2", ...]}.
+
+ Default preference order when in doubt: KEEP > APPEND > UPDATE.
+ Pick UPDATE only when APPEND is wrong (e.g. a short dynamic status line that
+ always replaces the previous one).
+
+ # RULE 2 — Per-section op selection.
+
+ - **Session Title** — default KEEP.
+ Change ONLY if the conversation topic has *completely* pivoted
+ (e.g. "we're no longer discussing X, we're now doing Y").
+ Adding a new subtopic, correcting a fact, or completing a phase is NOT enough
+ to change the title.
+
+ - **Current State** — default UPDATE. This is the only section that may shrink.
+ But the new body MUST still reference any pending item from the previous
+ Current State that is not yet resolved.
+ It answers: "What is the latest status?" Keep it to 2-5 sentences MAXIMUM.
+ It is NOT a fact dump, reference index, error log, or full summary.
+
+ - **Task & Goals** — default KEEP. UPDATE only if the purpose or objectives
+ have changed. If UPDATE, include ALL earlier goals plus the new ones.
+
+ - **Key Facts & Decisions** — APPEND for genuinely new facts or decisions.
+ This section records durable facts about the USER'S WORLD: people,
+ relationships, events, preferences, technical choices, commitments.
+ When <section_size_warnings> indicates this section is oversized, you
+ MUST use UPDATE with a consolidated version:
+
+ Consolidation rules:
+ 1. Group related facts by TOPIC (e.g., "Caroline's art", "Melanie's
+ family trips", "adoption journey"). Each topic gets ONE summary
+ bullet covering the pattern + most recent specific detail.
+ 2. Preserve: names, dates, exact numbers, decisions with rationale,
+ relationships, preferences. These are non-negotiable anchors.
+ 3. Drop: intermediate chronological steps that don't change the
+ current state (e.g., 5 separate "attended pride parade" entries
+ become "Caroline regularly attends pride parades; most recently
+ on [date], felt [emotion]").
+ 4. The consolidation target is a "continuation-grade" fact list:
+ enough to answer follow-up questions without re-reading history,
+ but not a verbatim transcript of every event.
+ 5. Target: <=25 bullets. If the section currently has >25 bullets,
+ consolidation is MANDATORY.
+
+ When no <section_size_warnings> are present, UPDATE is only allowed
+ when an earlier fact was explicitly contradicted; in that case the
+ UPDATE content MUST list the correction and still contain every
+ non-contradicted earlier fact.
+ Do not record routine process steps — only facts, decisions, or
+ conclusions that a future answer might depend on.
+
+ - **Files & Context** — default **APPEND** for newly-referenced resources.
+ UPDATE only to annotate an already-listed item with new status; the UPDATE
+ content MUST still include every item listed before.
+ Include only resources directly relevant to future answers — file paths,
+ document links, key URLs — plus why each matters. Do NOT append exhaustive
+ media/search/image URL dumps. Bulk non-durable URLs should be summarized
+ as counts with only representative or actually-used links.
+
+ - **Errors & Corrections** — **APPEND ONLY.** Never UPDATE this section.
+ Every mistake, misunderstanding, correction, or failed approach is a
+ permanent part of the session's history — even after it is resolved.
+ This includes: user correcting the assistant's assumptions, factual
+ misattributions, wrong dates, incorrect relationships, failed technical
+ approaches, etc. If there are genuinely no new corrections this round,
+ emit KEEP.
+
+ - **Open Issues** — default UPDATE. Explicitly mark resolved items rather
+ than silently dropping them. Example:
+ - [resolved] Question about Caroline's adoption agency
+ - [new] Need to verify the camping trip date
+ Do not drop an unresolved item just because it was not discussed this round.
+ However, items tagged `[silently dropped, restored]` were already given a
+ second chance by the server — you may safely mark them `[resolved]` if the
+ conversation has moved on and they are no longer actionable.
+ Also, if an issue has remained unactioned for several rounds (no user
+ follow-up, no assistant action), consolidate such stale items into a single
+ summary line rather than carrying each one forward indefinitely.
+
+ # RULE 3 — Self-check BEFORE emitting the tool call.
+
+ Run this checklist silently. If any item fails, fix the corresponding section
+ before emitting.
+
+ 1. For every section that is NOT KEEP, does my output contain every concrete
+ fact (name, date, relationship, decision, constraint) from the previous
+ section?
+ 2. Did I keep Session Title stable (no UPDATE unless the whole topic changed)?
+ 3. Did I use APPEND (not UPDATE) for `Errors & Corrections`? For
+ `Key Facts & Decisions`, did I consolidate via UPDATE when
+ <section_size_warnings> triggered, preserving all names/dates/numbers?
+ 4. Did I mark resolved Open Issues rather than deleting them?
+ 5. Is every bullet in my output a concrete fact (name / date / number / place),
+ not a vague phrase like "general improvements"?
+ 6. For temporal facts, did I use the EVENT date (not the conversation date)?
+ Example: conversation on May 8 mentioning "I went yesterday" → "7 May".
+
+ # RULE 4 — Output constraints.
+
+ - The tool schema requires a decision for ALL 7 sections. Do not skip any.
+ - Current State must be 2-5 sentences maximum and should normally be under
+ ~150 words.
+ - Each section body stays under ~2000 tokens. The entire Working Memory
+ stays under ~12000 tokens. If a section would exceed ~2000 tokens via
+ APPEND, consolidate older bullets INSIDE an UPDATE (carrying EVERY
+ durable fact) and include the new items. If the entire WM would exceed
+ ~12000 tokens, merge redundant bullets while preserving Current State,
+ Errors & Corrections, and every concrete fact / decision rationale.
+ - For Files & Context, apply a relevance filter before APPEND: keep resources
+ that future answers actually depend on; summarize broad image/search/result
+ URL lists instead of preserving each raw URL.
+ - Do not fabricate information not grounded in <new_content> or <current_wm>.
+ - You MUST call `update_working_memory` exactly once. No freeform text
+ outside the tool call.
+
+llm_config:
+ temperature: 0.0
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index f8a43865a..829727876 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -5,8 +5,8 @@
import logging
from typing import Any, Dict, List, Literal, Optional
-from fastapi import APIRouter, Depends, Path, Query, Request
-from pydantic import BaseModel, model_validator
+from fastapi import APIRouter, Body, Depends, Path, Query, Request
+from pydantic import BaseModel, Field, model_validator
from openviking.message.part import TextPart, part_from_dict
from openviking.server.auth import get_request_context
@@ -174,8 +174,7 @@ async def get_session(
)
result = session.meta.to_dict()
result["user"] = session.user.to_dict()
- pending_tokens = sum(m.estimated_tokens for m in session.messages)
- result["pending_tokens"] = pending_tokens
+ result["pending_tokens"] = int(session.meta.pending_tokens or 0)
return Response(status="ok", result=result)
@@ -233,9 +232,31 @@ async def delete_session(
return Response(status="ok", result={"session_id": session_id})
+class CommitRequest(BaseModel):
+ """Commit request body.
+
+ WM v2: ``keep_recent_count`` allows the plugin to retain a tail of recent
+ messages in the live session after commit so the next turn still has
+ immediate context. Default 0 preserves the pre-v2 "archive everything"
+ behavior.
+ """
+
+ keep_recent_count: int = Field(
+ default=0,
+ ge=0,
+ le=10_000,
+ description=(
+ "Number of most-recent messages to keep live after commit. "
+ "Plugin's afterTurn path typically passes its configured value "
+ "(default 10); compact path passes 0 to archive everything."
+ ),
+ )
+
+
@router.post("/{session_id}/commit")
async def commit_session(
session_id: str = Path(..., description="Session ID"),
+ body: CommitRequest = Body(default_factory=CommitRequest),
_ctx: RequestContext = Depends(get_request_context),
):
"""Commit a session (archive and extract memories).
@@ -245,7 +266,9 @@ async def commit_session(
polling progress via ``GET /tasks/{task_id}``.
"""
service = get_service()
- result = await service.sessions.commit_async(session_id, _ctx)
+ result = await service.sessions.commit_async(
+ session_id, _ctx, keep_recent_count=body.keep_recent_count
+ )
return Response(status="ok", result=result).model_dump(exclude_none=True)
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 5d53914ec..833129e72 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -202,20 +202,31 @@ class SessionService:
self._record_lifecycle_metric("delete", "error")
raise NotFoundError(session_id, "session")
- async def commit(self, session_id: str, ctx: RequestContext) -> Dict[str, Any]:
+ async def commit(
+ self,
+ session_id: str,
+ ctx: RequestContext,
+ keep_recent_count: int = 0,
+ ) -> Dict[str, Any]:
"""Commit a session (archive messages and extract memories).
Delegates to commit_async() for true non-blocking behavior.
Args:
session_id: Session ID to commit
+ keep_recent_count: See :meth:`commit_async`.
Returns:
Commit result
"""
- return await self.commit_async(session_id, ctx)
+ return await self.commit_async(session_id, ctx, keep_recent_count=keep_recent_count)
- async def commit_async(self, session_id: str, ctx: RequestContext) -> Dict[str, Any]:
+ async def commit_async(
+ self,
+ session_id: str,
+ ctx: RequestContext,
+ keep_recent_count: int = 0,
+ ) -> Dict[str, Any]:
"""Async commit a session.
Phase 1 (archive) always runs inline. Phase 2 (memory extraction)
@@ -223,6 +234,8 @@ class SessionService:
Args:
session_id: Session ID to commit
+ keep_recent_count: Number of most-recent messages to keep in the
+ live session after commit. ``0`` archives everything.
Returns:
Commit result with keys: session_id, status, task_id,
@@ -230,7 +243,7 @@ class SessionService:
"""
self._ensure_initialized()
session = await self.get(session_id, ctx)
- result = await session.commit_async()
+ result = await session.commit_async(keep_recent_count=keep_recent_count)
self._record_lifecycle_metric("commit", "ok" if result.get("status") else "error")
self._record_archive_metric("ok" if result.get("archived") else "skip")
return result
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 2116160ac..8d7284101 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -15,6 +15,7 @@ from uuid import uuid4
from openviking.core.namespace import canonical_session_uri
from openviking.message import Message, Part
+from openviking.message.part import ContextPart, TextPart, ToolPart
from openviking.server.identity import RequestContext, Role
from openviking.telemetry import get_current_telemetry, tracer
from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
@@ -34,6 +35,103 @@ _ARCHIVE_WAIT_POLL_SECONDS = 0.1
_PHASE2_QUEUE_WAIT_TIMEOUT_SECONDS = 1800.0
+def _wm_debug(msg: str) -> None:
+ """Log a WM v2 debug message via the standard logger."""
+ logger.debug("wm_v2: %s", msg)
+
+
+# =====================================================================
+# Working Memory v2
+# ---------------------------------------------------------------------
+# Phase 2 of a commit generates / updates a structured 7-section Working
+# Memory document stored at archive_NNN/.overview.md.
+#
+# First commit: call `compression.ov_wm_v2` with a plain completion.
+# Subsequent commits: call `compression.ov_wm_v2_update` with the
+# `update_working_memory` tool to get a per-section decision, then let
+# the server do section-level merge against the previous WM.
+# =====================================================================
+
+WM_SEVEN_SECTIONS: List[str] = [
+ "Session Title",
+ "Current State",
+ "Task & Goals",
+ "Key Facts & Decisions",
+ "Files & Context",
+ "Errors & Corrections",
+ "Open Issues",
+]
+
+_WM_SECTION_OP_SCHEMA: Dict[str, Any] = {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": ["op"],
+ "additionalProperties": False,
+ "properties": {"op": {"type": "string", "enum": ["KEEP"]}},
+ },
+ {
+ "type": "object",
+ "required": ["op", "content"],
+ "additionalProperties": False,
+ "properties": {
+ "op": {"type": "string", "enum": ["UPDATE"]},
+ "content": {
+ "type": "string",
+ "description": (
+ "FULL replacement content for this section, markdown, "
+ "WITHOUT the '## <section>' header line."
+ ),
+ },
+ },
+ },
+ {
+ "type": "object",
+ "required": ["op", "items"],
+ "additionalProperties": False,
+ "properties": {
+ "op": {"type": "string", "enum": ["APPEND"]},
+ "items": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "New bullet-style items to append under the existing "
+ "section body. Omit heading / bullet markers; the "
+ "server renders each item as '- <item>'."
+ ),
+ },
+ },
+ },
+ ]
+}
+
+WM_UPDATE_TOOL: Dict[str, Any] = {
+ "type": "function",
+ "function": {
+ "name": "update_working_memory",
+ "description": (
+ "Emit a per-section decision (KEEP / UPDATE / APPEND) for the "
+ "7-section Working Memory document."
+ ),
+ "parameters": {
+ "type": "object",
+ "required": ["sections"],
+ "additionalProperties": False,
+ "properties": {
+ "sections": {
+ "type": "object",
+ "required": list(WM_SEVEN_SECTIONS),
+ "additionalProperties": False,
+ "properties": {
+ name: _WM_SECTION_OP_SCHEMA for name in WM_SEVEN_SECTIONS
+ },
+ }
+ },
+ },
+ },
+}
+
+
@dataclass
class SessionCompression:
"""Session compression information."""
@@ -95,6 +193,16 @@ class SessionMeta:
"total_tokens": 0,
}
)
+ # Working-Memory v2: token accounting for sliding window + keep window.
+ # pending_tokens is the cumulative estimated_tokens of messages that fall
+ # OUTSIDE the recent-keep window and will be archived on the next commit.
+ # Maintained O(1) inside add_message(); rebuilt from messages on load.
+ pending_tokens: int = 0
+ # keep_recent_count is the last value passed from the plugin through
+ # POST /sessions/{id}/commit body. It is remembered so subsequent
+ # add_message calls can maintain pending_tokens consistently across
+ # process restarts.
+ keep_recent_count: int = 0
def to_dict(self) -> Dict[str, Any]:
data = {
@@ -110,6 +218,8 @@ class SessionMeta:
"last_commit_at": self.last_commit_at,
"llm_token_usage": dict(self.llm_token_usage),
"embedding_token_usage": dict(self.embedding_token_usage),
+ "pending_tokens": self.pending_tokens,
+ "keep_recent_count": self.keep_recent_count,
}
if self.total_message_count is not None:
data["total_message_count"] = self.total_message_count
@@ -151,6 +261,8 @@ class SessionMeta:
embedding_token_usage={
"total_tokens": embedding_token_usage.get("total_tokens", 0),
},
+ pending_tokens=max(0, int(data.get("pending_tokens", 0) or 0)),
+ keep_recent_count=max(0, int(data.get("keep_recent_count", 0) or 0)),
)
@@ -255,8 +367,34 @@ class Session:
for message in self._messages:
self._record_participant(message)
+ # WM v2: always rebuild pending_tokens from current messages so the
+ # counter stays consistent across restarts and is also backfilled for
+ # legacy sessions whose .meta.json predates these fields. O(n) once,
+ # subsequent add_message() maintains it in O(1).
+ self._rebuild_pending_tokens()
+
self._loaded = True
+ def _rebuild_pending_tokens(self) -> None:
+ """Recompute ``pending_tokens`` from the current message list.
+
+ Used on load and as a safety net after rollbacks. Respects the
+ currently remembered ``keep_recent_count`` from meta.
+ """
+ keep = max(0, int(self._meta.keep_recent_count or 0))
+ total = len(self._messages)
+ if keep <= 0:
+ self._meta.pending_tokens = sum(
+ int(m.estimated_tokens or 0) for m in self._messages
+ )
+ elif total > keep:
+ self._meta.pending_tokens = sum(
+ int(m.estimated_tokens or 0) for m in self._messages[: total - keep]
+ )
+ else:
+ self._meta.pending_tokens = 0
+ self._meta.pending_tokens = max(0, self._meta.pending_tokens)
+
async def exists(self) -> bool:
"""Check whether this session already exists in storage."""
try:
@@ -290,17 +428,6 @@ class Session:
return
run_async(self._save_meta())
- async def _load_latest_meta(self) -> SessionMeta:
- """Load the latest persisted metadata, falling back to the current instance state."""
- try:
- meta_content = await self._viking_fs.read_file(
- f"{self._session_uri}/.meta.json",
- ctx=self.ctx,
- )
- return SessionMeta.from_dict(json.loads(meta_content))
- except Exception:
- return self._meta
-
@property
def messages(self) -> List[Message]:
"""Get message list."""
@@ -373,7 +500,20 @@ class Session:
# Update statistics
if role == "user":
self._stats.total_turns += 1
- self._stats.total_tokens += msg.estimated_tokens
+ msg_tokens = int(msg.estimated_tokens or 0)
+ self._stats.total_tokens += msg_tokens
+
+ # WM v2: maintain pending_tokens via sliding window.
+ # keep_recent_count == 0 (never-committed or compact path that chose 0):
+ # every new message contributes to pending.
+ # keep_recent_count > 0:
+ # only the message pushed OUT of the tail-keep window contributes.
+ keep = int(self._meta.keep_recent_count or 0)
+ if keep <= 0:
+ self._meta.pending_tokens += msg_tokens
+ elif len(self._messages) > keep:
+ pushed_out = self._messages[-(keep + 1)]
+ self._meta.pending_tokens += int(pushed_out.estimated_tokens or 0)
self._append_to_jsonl(msg)
@@ -412,19 +552,29 @@ class Session:
self._save_tool_result(tool_id, msg, output, status)
self._update_message_in_jsonl()
+ self._rebuild_pending_tokens()
- def commit(self) -> Dict[str, Any]:
+ def commit(self, keep_recent_count: int = 0) -> Dict[str, Any]:
"""Sync wrapper for commit_async()."""
- return run_async(self.commit_async())
+ return run_async(self.commit_async(keep_recent_count=keep_recent_count))
@tracer("session.commit")
- async def commit_async(self) -> Dict[str, Any]:
+ async def commit_async(self, keep_recent_count: int = 0) -> Dict[str, Any]:
"""Async commit session: archive immediately, extract memories in background.
- Phase 1 (Archive prep, PathLock-protected): Copy messages, clear live
- session, increment compression index. Uses a distributed filesystem lock
- (PathLock) so this works across workers and processes.
- Phase 2 (Memory extraction): Always runs in background via asyncio.create_task().
+ Phase 1 (Archive prep, PathLock-protected): Split messages into
+ archive/retain parts, write the retained tail back to messages.jsonl,
+ then persist the archive. Uses a distributed filesystem lock (PathLock)
+ so this works across workers and processes.
+ Phase 2 (Memory extraction): Always runs in background via
+ asyncio.create_task().
+
+ Args:
+ keep_recent_count: Number of most-recent messages to keep in the
+ live session after commit. ``0`` (default) preserves the old
+ behavior of archiving everything. The plugin's afterTurn path
+ typically passes its configured value (default 10); the compact
+ path passes ``0``.
Returns a task_id for tracking Phase 2 progress.
"""
@@ -433,12 +583,19 @@ class Session:
from openviking_cli.exceptions import FailedPreconditionError
trace_id = tracer.get_trace_id()
- logger.info(f"[TRACER] session_commit started, trace_id={trace_id}")
+ keep_recent_count = max(0, int(keep_recent_count or 0))
+ logger.info(
+ f"[TRACER] session_commit started, trace_id={trace_id}, "
+ f"keep_recent_count={keep_recent_count}"
+ )
# ===== Phase 1: Snapshot + clear (PathLock-protected) =====
# Fast pre-check: skip lock entirely if no messages (common case avoids
# unnecessary filesystem lock acquisition).
if not self._messages:
+ self._meta.pending_tokens = 0
+ self._meta.keep_recent_count = keep_recent_count
+ await self._save_meta()
get_current_telemetry().set("memory.extracted", 0)
return {
"session_id": self.session_id,
@@ -463,6 +620,9 @@ class Session:
# Authoritative check under lock: handles the race where two concurrent
# callers both passed the pre-check but only the first should archive.
if not self._messages:
+ self._meta.pending_tokens = 0
+ self._meta.keep_recent_count = keep_recent_count
+ await self._save_meta()
get_current_telemetry().set("memory.extracted", 0)
return {
"session_id": self.session_id,
@@ -473,20 +633,48 @@ class Session:
"trace_id": trace_id,
}
+ # WM v2 boundary: if all live messages already fit inside the keep
+ # window, there is nothing to archive — just remember the new
+ # keep_recent_count and reset pending_tokens so the next
+ # add_message uses the sliding-window path.
+ total = len(self._messages)
+ if keep_recent_count > 0 and total <= keep_recent_count:
+ self._meta.pending_tokens = 0
+ self._meta.keep_recent_count = keep_recent_count
+ self._meta.message_count = total
+ await self._save_meta()
+ get_current_telemetry().set("memory.extracted", 0)
+ return {
+ "session_id": self.session_id,
+ "status": "accepted",
+ "task_id": None,
+ "archive_uri": None,
+ "archived": False,
+ "reason": "all_within_keep_window",
+ "trace_id": trace_id,
+ }
+
self._compression.compression_index += 1
- messages_to_archive = self._messages.copy()
- self._messages.clear()
+ if keep_recent_count > 0:
+ split_idx = total - keep_recent_count
+ messages_to_archive = self._messages[:split_idx]
+ self._messages = self._messages[split_idx:]
+ else:
+ messages_to_archive = self._messages.copy()
+ self._messages = []
try:
- await self._write_to_agfs_async(messages=[])
+ # Persist the retained tail (may be empty when keep=0). This
+ # replaces messages.jsonl under the lock, consistent with the
+ # previous behavior of writing empty messages on full clear.
+ await self._write_to_agfs_async(messages=self._messages)
except Exception as e:
# Rollback: restore messages so they aren't lost
- logger.error(f"[commit] Failed to write empty messages.jsonl: {e}")
- self._messages.extend(messages_to_archive)
+ logger.error(f"[commit] Failed to write messages.jsonl: {e}")
+ self._messages = list(messages_to_archive) + list(self._messages)
self._compression.compression_index -= 1
raise
- # Lock released — live session is now clean.
- # Any add_message() from here appends to the fresh empty list.
+ # Lock released — live session now contains only the retained tail.
# ===== Phase 1 continued: Write raw archive (no LLM calls, no lock needed) =====
archive_uri = (
@@ -500,9 +688,12 @@ class Session:
ctx=self.ctx,
)
- await self._mark_archive_committed_meta(
- archive_index=self._compression.compression_index,
- )
+ # WM v2: live session is now the retained tail; pending_tokens resets
+ # because anything that was pending has been archived.
+ self._meta.message_count = len(self._messages)
+ self._meta.pending_tokens = 0
+ self._meta.keep_recent_count = keep_recent_count
+ await self._save_meta()
self._compression.original_count += len(messages_to_archive)
logger.info(
@@ -560,11 +751,11 @@ class Session:
from openviking.telemetry.registry import register_telemetry, unregister_telemetry
tracker = get_task_tracker()
+ request_wait_tracker = get_request_wait_tracker()
memories_extracted: Dict[str, int] = {}
active_count_updated = 0
telemetry = OperationTelemetry(operation="session_commit_phase2", enabled=True)
- request_wait_tracker = get_request_wait_tracker()
archive_index = self._archive_index_from_uri(archive_uri)
redo_task_id: Optional[str] = None
@@ -662,9 +853,7 @@ class Session:
if self._viking_fs:
for usage in usage_records:
try:
- await self._viking_fs.link(
- self._session_uri, usage.uri, ctx=self.ctx
- )
+ await self._viking_fs.link(self._session_uri, usage.uri, ctx=self.ctx)
except Exception as e:
logger.warning(f"Failed to create relation to {usage.uri}: {e}")
@@ -674,8 +863,8 @@ class Session:
if self._vikingdb_manager:
uris = [u.uri for u in usage_records if u.uri]
try:
- active_count_updated = (
- await self._vikingdb_manager.increment_active_count(self.ctx, uris)
+ active_count_updated = await self._vikingdb_manager.increment_active_count(
+ self.ctx, uris
)
except Exception as e:
logger.debug(f"Could not update active_count for usage URIs: {e}")
@@ -696,7 +885,8 @@ class Session:
str(exc),
)
logger.warning(
- "Timed out waiting for request-scoped queues for telemetry_id=%s after %.1fs; continuing phase2 completion",
+ "Timed out waiting for request-scoped queues for "
+ "telemetry_id=%s after %.1fs; continuing phase2 completion",
telemetry.telemetry_id,
_PHASE2_QUEUE_WAIT_TIMEOUT_SECONDS,
)
@@ -1171,8 +1361,15 @@ class Session:
telemetry_snapshot: Any,
) -> None:
"""Reload and merge latest meta state before persisting commit results."""
- latest_meta = await self._load_latest_meta()
- live_message_count = await self._read_live_message_count()
+ latest_meta = self._meta
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ latest_meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception:
+ latest_meta = self._meta
if telemetry_snapshot:
llm = telemetry_snapshot.summary.get("tokens", {}).get("llm", {})
@@ -1188,21 +1385,8 @@ class Session:
latest_meta.memories_extracted["total"] = (
latest_meta.memories_extracted.get("total", 0) + count
)
- latest_meta.message_count = live_message_count
- self._meta = latest_meta
- await self._save_meta()
-
- async def _mark_archive_committed_meta(
- self,
- archive_index: int,
- ) -> None:
- """Persist metadata for a completed Phase 1 archive."""
- latest_meta = await self._load_latest_meta()
- live_message_count = await self._read_live_message_count()
-
- latest_meta.commit_count = max(latest_meta.commit_count, archive_index)
latest_meta.last_commit_at = get_current_timestamp()
- latest_meta.message_count = live_message_count
+ latest_meta.message_count = await self._read_live_message_count()
self._meta = latest_meta
await self._save_meta()
@@ -1231,6 +1415,26 @@ class Session:
first_line = summary.split("\n")[0].strip()
return first_line if first_line else ""
+ @staticmethod
+ def _format_message_for_wm(m: Message) -> str:
+ """Format a single message for WM generation, including all parts.
+
+ Includes TextPart, ToolPart (name + status + full output), and
+ ContextPart so the WM LLM sees the complete conversation.
+ """
+ lines: List[str] = []
+ for p in m.parts:
+ if isinstance(p, TextPart) and p.text.strip():
+ lines.append(p.text)
+ elif isinstance(p, ToolPart) and p.tool_name:
+ status = p.tool_status or "completed"
+ output = p.tool_output or ""
+ lines.append(f"[tool:{p.tool_name} ({status})] {output}")
+ elif isinstance(p, ContextPart) and p.abstract:
+ lines.append(f"[context] {p.abstract}")
+ body = "\n".join(lines) if lines else "(no content)"
+ return f"[{m.role}]: {body}"
+
def _generate_archive_summary(
self,
messages: List[Message],
@@ -1240,7 +1444,7 @@ class Session:
if not messages:
return ""
- formatted = "\n".join([f"[{m.role}]: {m.content}" for m in messages])
+ formatted = "\n".join(self._format_message_for_wm(m) for m in messages)
vlm = get_openviking_config().vlm
if vlm and vlm.is_available():
@@ -1266,30 +1470,905 @@ class Session:
messages: List[Message],
latest_archive_overview: str = "",
) -> str:
- """Generate structured summary for archive (async)."""
+ """Generate Working Memory document for the current archive (async).
+
+ Two paths:
+
+ * No prior WM -> call ``compression.ov_wm_v2`` with a plain completion
+ and return the full 7-section markdown.
+ * Has prior WM -> call ``compression.ov_wm_v2_update`` with the
+ ``update_working_memory`` tool forced on; parse per-section
+ decisions and merge them against the previous WM. On any
+ tool_call / JSON / schema anomaly, fall back to the creation
+ prompt so we never persist malformed output as WM.
+ """
+ _wm_debug(f"_generate_archive_summary_async called "
+ f"messages={len(messages)} prior_wm={len(latest_archive_overview)}B")
if not messages:
return ""
- formatted = "\n".join([f"[{m.role}]: {m.content}" for m in messages])
+ formatted = "\n".join(self._format_message_for_wm(m) for m in messages)
vlm = get_openviking_config().vlm
- if vlm and vlm.is_available():
- try:
- from openviking.prompts import render_prompt
+ if not (vlm and vlm.is_available()):
+ turn_count = len([m for m in messages if m.role == "user"])
+ return (
+ f"# Session Summary\n\n"
+ f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ )
+
+ try:
+ from openviking.prompts import render_prompt
+ except Exception as e:
+ logger.warning(f"Prompt module unavailable: {e}")
+ turn_count = len([m for m in messages if m.role == "user"])
+ return (
+ f"# Session Summary\n\n"
+ f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ )
+
+ # -------- Detect WM v2 format --------
+ _is_wm_v2 = latest_archive_overview and any(
+ f"## {s}" in latest_archive_overview for s in WM_SEVEN_SECTIONS
+ )
+ # -------- Branch 1: no prior WM (or legacy format) -> full creation --------
+ if not latest_archive_overview or not _is_wm_v2:
+ _wm_debug(
+ f"branch=CREATE (prior={'legacy' if latest_archive_overview else 'none'} "
+ f"{len(latest_archive_overview or '')}B)"
+ )
+ try:
prompt = render_prompt(
- "compression.structured_summary",
- {
- "messages": formatted,
- "latest_archive_overview": latest_archive_overview,
- },
+ "compression.ov_wm_v2",
+ {"messages": formatted, "latest_archive_overview": latest_archive_overview or ""},
)
return await vlm.get_completion_async(prompt)
except Exception as e:
- logger.warning(f"LLM summary failed: {e}")
+ _wm_debug(f"creation failed: {e}")
+ logger.warning(f"WM creation failed: {e}")
+ turn_count = len([m for m in messages if m.role == "user"])
+ return (
+ f"# Session Summary\n\n"
+ f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ )
- turn_count = len([m for m in messages if m.role == "user"])
- return f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
+ # -------- Branch 2: has prior WM v2 -> tool_call incremental update --------
+ _wm_debug(f"branch=UPDATE (prior WM={len(latest_archive_overview)}B)")
+ try:
+ reminders = Session._build_wm_section_reminders(latest_archive_overview)
+ if reminders:
+ _wm_debug(f"section_reminders injected ({len(reminders)}B)")
+ update_prompt = render_prompt(
+ "compression.ov_wm_v2_update",
+ {
+ "messages": formatted,
+ "latest_archive_overview": latest_archive_overview,
+ "wm_section_reminders": reminders,
+ },
+ )
+ resp = await vlm.get_completion_async(
+ prompt=update_prompt,
+ tools=[WM_UPDATE_TOOL],
+ tool_choice={
+ "type": "function",
+ "function": {"name": "update_working_memory"},
+ },
+ )
+ except Exception as e:
+ import traceback as _tb
+ _wm_debug(
+ f"tool_call raised: {type(e).__name__}: {e} "
+ f"tb={_tb.format_exc()[-400:]}"
+ )
+ logger.warning(
+ "WM update tool_call failed (%s); falling back to creation prompt", e
+ )
+ return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
+
+ has_tc = bool(getattr(resp, "has_tool_calls", False) and getattr(resp, "tool_calls", None))
+ _preview = (str(resp)[:200]).replace(chr(10), " ")
+ _finish = getattr(resp, "finish_reason", "n/a")
+ _usage = getattr(resp, "usage", {}) or {}
+ _wm_debug(
+ f"resp type={type(resp).__name__} has_tool_calls={has_tc} "
+ f"finish_reason={_finish!r} usage={_usage} preview={_preview!r}"
+ )
+
+ if not has_tc:
+ logger.warning(
+ "WM update: LLM returned no tool_call; falling back to creation prompt"
+ )
+ return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
+
+ try:
+ raw_args = resp.tool_calls[0].arguments
+ _wm_debug(
+ f"raw_args type={type(raw_args).__name__} "
+ f"preview={str(raw_args)[:400]!r}"
+ )
+ args = raw_args
+ if isinstance(args, str):
+ args = json.loads(args)
+ if not isinstance(args, dict):
+ raise ValueError(f"tool_call arguments is not a dict: {type(args).__name__}")
+
+ # OV's VLM backend wraps unparseable JSON strings as {"raw": "..."}.
+ # Try a best-effort recovery: json.loads the raw string; if that
+ # still fails, attempt a tolerant parse (add a closing brace if the
+ # string looks truncated, extract up to the last valid JSON object).
+ if list(args.keys()) == ["raw"] and isinstance(args["raw"], str):
+ raw_str = args["raw"]
+ _wm_debug(f"args has only 'raw' key; attempting recovery len={len(raw_str)}")
+ recovered = None
+ try:
+ recovered = json.loads(raw_str)
+ except Exception:
+ # Try to close a truncated JSON by appending closing braces
+ # for every unmatched opener.
+ try:
+ opens = raw_str.count("{") - raw_str.count("}")
+ if opens > 0:
+ patched = raw_str.rstrip().rstrip(",") + ("}" * opens)
+ recovered = json.loads(patched)
+ _wm_debug(
+ f"recovered by closing {opens} brace(s); "
+ f"patched_len={len(patched)}"
+ )
+ except Exception as e2:
+ _wm_debug(f"brace-close recovery failed: {e2}")
+ if isinstance(recovered, dict):
+ args = recovered
+ _wm_debug(f"recovered args keys={list(args.keys())}")
+
+ _wm_debug(f"args keys={list(args.keys())}")
+ # Tolerant: if LLM returned {"Session Title": {...}, ...} without
+ # the outer "sections" wrapper, treat the top-level as ops.
+ if "sections" in args and isinstance(args["sections"], dict):
+ ops = args["sections"]
+ elif all(k in args for k in WM_SEVEN_SECTIONS):
+ _wm_debug("args has section keys directly; accepting as ops")
+ ops = args
+ else:
+ raise ValueError(
+ f"tool_call arguments.sections missing; keys={list(args.keys())}"
+ )
+ if not isinstance(ops, dict):
+ raise ValueError("ops is not a dict")
+ except Exception as e:
+ _wm_debug(
+ f"args parse failed: {type(e).__name__}: {e}; "
+ f"attempting regex recovery from raw"
+ )
+ # Regex salvage: when the LLM emits slightly-broken JSON (curly
+ # quote, unescaped newline, truncated string), OV's VLM backend
+ # wraps it as {"raw": "..."} and all structural parsing fails. We
+ # still try to pull each section's op directly via regex before
+ # falling back to the creation prompt. Missing sections default
+ # to KEEP in _merge_wm_sections so old content is preserved.
+ raw_for_recovery = ""
+ if isinstance(raw_args, str):
+ raw_for_recovery = raw_args
+ elif isinstance(raw_args, dict):
+ if isinstance(raw_args.get("raw"), str):
+ raw_for_recovery = raw_args["raw"]
+ else:
+ try:
+ raw_for_recovery = json.dumps(raw_args, ensure_ascii=False)
+ except Exception:
+ raw_for_recovery = str(raw_args)
+ salvaged = Session._wm_recover_ops_from_raw(raw_for_recovery)
+ if salvaged:
+ _wm_debug(
+ f"regex recovery salvaged {len(salvaged)}/"
+ f"{len(WM_SEVEN_SECTIONS)} sections: "
+ f"{[(k, v.get('op')) for k, v in salvaged.items()]}"
+ )
+ logger.info(
+ "WM update: regex recovery salvaged %d/%d sections; "
+ "proceeding with partial ops",
+ len(salvaged),
+ len(WM_SEVEN_SECTIONS),
+ )
+ return self._merge_wm_sections(latest_archive_overview, salvaged)
+ _wm_debug(
+ "regex recovery salvaged 0 sections; falling back to creation prompt"
+ )
+ logger.warning(
+ "WM update: tool_call arguments parse failed (%s); "
+ "regex recovery found nothing; falling back to creation prompt",
+ e,
+ )
+ return await self._fallback_generate_wm_creation(formatted, messages, latest_archive_overview)
+
+ _wm_debug(
+ f"ops keys={list(ops.keys())[:7]} "
+ f"ops_summary={[(k, v.get('op') if isinstance(v, dict) else type(v).__name__) for k, v in ops.items()][:7]}"
+ )
+ return self._merge_wm_sections(latest_archive_overview, ops)
+
+ async def _fallback_generate_wm_creation(
+ self,
+ formatted_messages: str,
+ messages: List[Message],
+ prior_overview: str = "",
+ ) -> str:
+ """Re-run WM creation prompt when the update tool_call path fails.
+
+ Passes ``prior_overview`` so the creation prompt can incorporate
+ accumulated context instead of generating from scratch.
+ """
+ _wm_debug(
+ f"fallback creation prompt: prior_overview={len(prior_overview)}B "
+ f"messages={len(messages)}"
+ )
+ try:
+ from openviking.prompts import render_prompt
+
+ prompt = render_prompt(
+ "compression.ov_wm_v2",
+ {"messages": formatted_messages, "latest_archive_overview": prior_overview},
+ )
+ return await get_openviking_config().vlm.get_completion_async(prompt)
+ except Exception as e:
+ logger.warning(f"WM creation fallback failed: {e}")
+ turn_count = len([m for m in messages if m.role == "user"])
+ return (
+ f"# Session Summary\n\n"
+ f"**Overview**: {turn_count} turns, {len(messages)} messages"
+ )
+
+ @staticmethod
+ def _parse_wm_sections(text: str) -> Dict[str, str]:
+ """Parse an existing WM markdown into {header_line: body_text}.
+
+ Header comparison is case-sensitive on purpose: the update path only
+ uses this output to look up bodies by our own canonical headers.
+ """
+ sections: Dict[str, str] = {}
+ current: Optional[str] = None
+ buf: List[str] = []
+ for line in (text or "").splitlines():
+ stripped = line.strip()
+ if stripped.startswith("## "):
+ if current is not None:
+ sections[current] = "\n".join(buf).strip()
+ current = stripped
+ buf = []
+ elif current is not None:
+ buf.append(line)
+ if current is not None:
+ sections[current] = "\n".join(buf).strip()
+ return sections
+
+ _WM_SECTION_BULLET_THRESHOLD = 25
+ _WM_SECTION_TOKEN_THRESHOLD = 1500
+ _WM_OVERSIZED_APPEND_CAP = 5
+ _WM_CONSOLIDATION_SENTINEL = (
+ "[⚠ CONSOLIDATION REQUIRED: Key Facts exceeds size limit. "
+ "You MUST use UPDATE to merge and compress existing bullets "
+ "before adding new facts.]"
+ )
+
+ @staticmethod
+ def _build_wm_section_reminders(overview: str) -> str:
+ """Compute dynamic section-size warnings for the WM update prompt.
+
+ Scans the current overview, counts bullets and estimates tokens for
+ each section. Returns an XML block that the prompt template can
+ inject verbatim so the LLM knows which sections need consolidation.
+ """
+ if not overview:
+ return ""
+ sections = Session._parse_wm_sections(overview)
+ warnings: List[str] = []
+ for header, body in sections.items():
+ name = header.lstrip("#").strip()
+ if name in Session._WM_APPEND_ONLY_SECTIONS:
+ continue
+ items = Session._wm_extract_bullet_items(body)
+ est_tokens = len(body) // 4
+ if (
+ len(items) > Session._WM_SECTION_BULLET_THRESHOLD
+ or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD
+ ):
+ warnings.append(
+ f'WARNING: "{name}" has {len(items)} bullets '
+ f"(~{est_tokens} tokens).\n"
+ f"This section MUST be consolidated via UPDATE. Group "
+ f"related facts by topic into category summaries. "
+ f"Preserve names, dates, and exact values but merge "
+ f"repetitive events into patterns.\n"
+ f"Target: <={Session._WM_SECTION_BULLET_THRESHOLD} "
+ f"bullets, <={Session._WM_SECTION_TOKEN_THRESHOLD} tokens."
+ )
+ if not warnings:
+ return ""
+ return "<section_size_warnings>\n" + "\n\n".join(warnings) + "\n</section_size_warnings>"
+
+ # Sections where server enforces APPEND-only regardless of what the LLM emits.
+ _WM_APPEND_ONLY_SECTIONS = frozenset({
+ "Errors & Corrections",
+ })
+
+ # Very loose path-like token regex used to detect file paths that existed
+ # in prior Files & Context and MUST NOT silently disappear after UPDATE.
+ _WM_PATH_LIKE_RE = re.compile(
+ r"(?:[\w./\\-]+\.(?:py|ts|tsx|js|jsx|md|yaml|yml|json|sh|ps1|cmd|bat|toml|ini|cfg|rs|go))"
+ r"|(?:[a-zA-Z_][\w\-]*(?:/[a-zA-Z_][\w\-]*){1,})",
+ re.IGNORECASE,
+ )
+
+ _WM_TITLE_STOPWORDS = frozenset({
+ "the", "a", "an", "and", "or", "of", "to", "in", "on", "for",
+ "with", "by", "at", "from", "session", "title", "working", "memory",
+ "plan", "plans", "notes", "note",
+ })
+
+ @staticmethod
+ def _wm_recover_ops_from_raw(raw_str: str) -> Dict[str, Any]:
+ """Best-effort regex recovery of per-section ops from a malformed
+ tool_call arguments string.
+
+ Used when OV's VLM backend wraps non-JSON tool-call args as
+ ``{"raw": "..."}`` (typical when the LLM emits unescaped characters
+ inside a string value, uses curly quotes, or emits a truncated JSON).
+ Scans the raw text for each of the 7 fixed section names and their
+ ``{"op": "KEEP|UPDATE|APPEND", ...}`` markers. Partial UPDATE
+ content / APPEND items are tolerated; sections that cannot be found
+ at all are simply omitted (the merge step will then default them to
+ KEEP and preserve the prior content).
+
+ Returns a partial ops dict (possibly fewer than 7 sections).
+ """
+ if not raw_str:
+ return {}
+
+ ops: Dict[str, Any] = {}
+ names_alt = "|".join(re.escape(n) for n in WM_SEVEN_SECTIONS)
+
+ # --- KEEP: "Name": {"op": "KEEP"} ---
+ keep_re = re.compile(
+ rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"KEEP"\s*\}}'
+ )
+ for m in keep_re.finditer(raw_str):
+ ops.setdefault(m.group(1), {"op": "KEEP"})
+
+ # --- UPDATE: "Name": {"op": "UPDATE", "content": "..."} ---
+ # Capture content non-greedily up to either:
+ # (a) a closing '"}' that ends the section, or
+ # (b) the start of the next section key (meaning content string was truncated).
+ # DOTALL so newlines inside content don't end the match.
+ update_re = re.compile(
+ rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"UPDATE"\s*,\s*"content"\s*:\s*"'
+ rf'((?:[^"\\]|\\.)*?)'
+ rf'(?:"\s*\}}|(?="\s*,\s*"(?:' + names_alt + r')"))',
+ re.DOTALL,
+ )
+ for m in update_re.finditer(raw_str):
+ header = m.group(1)
+ if header in ops:
+ continue
+ captured = m.group(2)
+ try:
+ content = json.loads('"' + captured + '"')
+ except Exception:
+ content = captured
+ ops[header] = {"op": "UPDATE", "content": content}
+
+ # --- APPEND: "Name": {"op": "APPEND", "items": [...]} ---
+ # Tolerate truncated array (no closing ']').
+ append_re = re.compile(
+ rf'"({names_alt})"\s*:\s*\{{\s*"op"\s*:\s*"APPEND"\s*,\s*"items"\s*:\s*\['
+ rf'([\s\S]*?)(?:\]|$)',
+ )
+ item_re = re.compile(r'"((?:[^"\\]|\\.)*)"', re.DOTALL)
+ for m in append_re.finditer(raw_str):
+ header = m.group(1)
+ if header in ops:
+ continue
+ items_raw = m.group(2)
+ items: List[str] = []
+ for im in item_re.finditer(items_raw):
+ captured = im.group(1)
+ try:
+ items.append(json.loads('"' + captured + '"'))
+ except Exception:
+ items.append(captured)
+ ops[header] = {"op": "APPEND", "items": items}
+
+ return ops
+
+ @staticmethod
+ def _wm_extract_bullet_items(text: str) -> List[str]:
+ """Extract bullet-like items from a markdown section body.
+
+ Recognizes ``- ...``, ``* ...``, ``1. ...``, ``2) ...`` lines, as well
+ as plain non-bullet lines (treated as single items).
+ """
+ items: List[str] = []
+ for line in (text or "").splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ m = re.match(r"^(?:[-*]|\d+[\.)])\s+(.*)$", stripped)
+ if m:
+ item = m.group(1).strip()
+ else:
+ item = stripped
+ if item:
+ items.append(item)
+ return items
+
+ @staticmethod
+ def _wm_enforce_append_only(
+ header: str, op: Any, old_content: str
+ ) -> Dict[str, Any]:
+ """Guard: force KEEP/APPEND semantics on APPEND-only sections.
+
+ - KEEP and APPEND pass through.
+ - UPDATE is demoted: its content is parsed for bullet items; any items
+ that are not already present in the old body are re-emitted as APPEND
+ items, so nothing from the LLM's rewrite is lost but nothing from
+ the old body is dropped either.
+ - None/unknown op -> KEEP.
+ """
+ if not isinstance(op, dict):
+ return {"op": "KEEP"}
+ op_name = (op.get("op") or "").upper()
+ if op_name in ("KEEP", "APPEND"):
+ return op
+ if op_name != "UPDATE":
+ return {"op": "KEEP"}
+
+ new_content = (op.get("content") or "").strip()
+ new_items = Session._wm_extract_bullet_items(new_content)
+ old_lower = (old_content or "").lower()
+ fresh_items = []
+ for it in new_items:
+ key = it.strip("_* `").lower()
+ if key and key not in old_lower:
+ fresh_items.append(it)
+ _wm_debug(
+ f"guard: section {header!r} UPDATE -> forced APPEND "
+ f"(llm_items={len(new_items)}, fresh_after_dedup={len(fresh_items)})"
+ )
+ if not fresh_items:
+ return {"op": "KEEP"}
+ return {"op": "APPEND", "items": fresh_items}
+
+ _WM_KEY_FACTS_MIN_BULLET_RATIO = 0.15
+ _WM_KEY_FACTS_MIN_ANCHOR_COVERAGE = 0.70
+
+ _WM_ANCHOR_DATE_RE = re.compile(
+ r"\b\d{4}-\d{2}-\d{2}\b"
+ r"|\b\d{1,2}\s+(?:January|February|March|April|May|June"
+ r"|July|August|September|October|November|December)\s+\d{4}\b",
+ re.IGNORECASE,
+ )
+ _WM_ANCHOR_NUMBER_RE = re.compile(
+ r"\b\d+\s+(?:years?|months?|weeks?|days?|kids?|children"
+ r"|hours?|miles?|times?|sessions?|rounds?|visits?"
+ r"|dollars?|euros?|pounds?|bedrooms?|paintings?"
+ r"|people|persons?)\b"
+ r"|\$\d[\d,]*"
+ r"|\b\d+\s+(?:AM|PM)\b",
+ re.IGNORECASE,
+ )
+ _WM_ANCHOR_DECISION_RE = re.compile(
+ r"\b(?:because|decided|chose|committed|agreed|resolved)\b",
+ re.IGNORECASE,
+ )
+ _WM_ANCHOR_STOPWORDS = frozenset({
+ "the", "a", "an", "and", "or", "of", "to", "in", "on", "for",
+ "with", "by", "at", "from", "is", "are", "was", "were", "has",
+ "have", "had", "been", "be", "will", "would", "could", "should",
+ "may", "might", "shall", "this", "that", "these", "those",
+ "not", "no", "but", "if", "then", "so", "as", "it", "its",
+ "they", "their", "them", "she", "her", "he", "him", "his",
+ "we", "our", "us", "you", "your", "who", "which", "what",
+ "when", "where", "how", "why", "all", "each", "every",
+ "both", "few", "more", "most", "other", "some", "such",
+ "than", "too", "very", "also", "just", "about", "after",
+ "before", "between", "into", "through", "during", "again",
+ "further", "once", "here", "there", "over", "under", "out",
+ "up", "down", "off", "own", "same", "only", "new", "old",
+ "key", "facts", "decisions", "session", "working", "memory",
+ })
+
+ @staticmethod
+ def _extract_lexical_anchors(text: str) -> set:
+ """Extract fact-preserving anchors: dates, numbers, proper nouns,
+ decision markers."""
+ anchors: set = set()
+ for m in Session._WM_ANCHOR_DATE_RE.finditer(text):
+ anchors.add(m.group().lower().strip())
+ for m in Session._WM_ANCHOR_NUMBER_RE.finditer(text):
+ anchors.add(m.group().lower().strip())
+ for m in Session._WM_ANCHOR_DECISION_RE.finditer(text):
+ anchors.add(m.group().lower().strip())
+ for token in re.findall(r"\b[A-Z][a-zA-Z]{2,}\b", text):
+ if token.lower() not in Session._WM_ANCHOR_STOPWORDS:
+ anchors.add(token.lower())
+ return anchors
+
+ @staticmethod
+ def _salvage_new_items_from_rejected_update(
+ new_content: str, old_content: str
+ ) -> Dict[str, Any]:
+ """When a consolidation UPDATE is rejected, salvage genuinely new
+ items from the update content and APPEND them so we don't lose
+ facts from the current round."""
+ new_items = Session._wm_extract_bullet_items(new_content)
+ old_lower = (old_content or "").lower()
+ fresh_items = []
+ for it in new_items:
+ key = it.strip("_* `").lower()
+ if key and key not in old_lower:
+ fresh_items.append(it)
+ if fresh_items:
+ _wm_debug(
+ f"guard: salvaged {len(fresh_items)} new items from rejected UPDATE"
+ )
+ return {"op": "APPEND", "items": fresh_items}
+ return {"op": "KEEP"}
+
+ @staticmethod
+ def _wm_enforce_key_facts_consolidation(
+ op: Any, old_content: str
+ ) -> Dict[str, Any]:
+ """Guard: allow controlled consolidation for Key Facts & Decisions.
+
+ Layer 1 — reject trivially small UPDATEs (< 15% bullet count).
+ Layer 2 — require >= 70% lexical anchor coverage.
+ Rejection salvages genuinely new items from the rejected UPDATE
+ via APPEND, so current-round facts are not silently lost.
+
+ Anti-bloat: when Key Facts is already oversized (bullets or tokens
+ exceed threshold), APPEND is throttled:
+ - 1x~2x threshold → accept only genuinely new items (deduped),
+ capped at _WM_OVERSIZED_APPEND_CAP
+ - >2x threshold (emergency) → reject all normal facts, insert a
+ single idempotent consolidation sentinel; on subsequent rounds
+ the sentinel is already present so nothing is added (hard stop)
+ """
+ if not isinstance(op, dict):
+ return {"op": "KEEP"}
+ op_name = (op.get("op") or "").upper()
+ if op_name == "KEEP":
+ return op
+ if op_name == "APPEND":
+ old_items = Session._wm_extract_bullet_items(old_content or "")
+ est_tokens = len(old_content or "") // 4
+ bullet_over = len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD
+ token_over = est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD
+ if not bullet_over and not token_over:
+ return op
+ append_items = op.get("items") or []
+ if not append_items:
+ raw = (op.get("content") or "").strip()
+ append_items = Session._wm_extract_bullet_items(raw)
+ append_items = [str(it) for it in append_items if it]
+ old_lower = (old_content or "").lower()
+ fresh = [
+ it for it in append_items
+ if it.strip("_* `").lower() not in old_lower
+ ]
+ emergency = (
+ len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD * 2
+ or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD * 2
+ )
+ if emergency:
+ sentinel = Session._WM_CONSOLIDATION_SENTINEL
+ if sentinel.lower() in old_lower:
+ _wm_debug(
+ f"guard: Key Facts APPEND blocked (emergency, "
+ f"sentinel already present): "
+ f"bullets={len(old_items)} est_tok={est_tokens} — "
+ f"dropped {len(fresh)} new item(s)"
+ )
+ return {"op": "KEEP"}
+ _wm_debug(
+ f"guard: Key Facts APPEND blocked (emergency, "
+ f"inserting sentinel): "
+ f"bullets={len(old_items)} est_tok={est_tokens} — "
+ f"dropped {len(fresh)} new item(s)"
+ )
+ return {"op": "APPEND", "items": [sentinel]}
+ cap = Session._WM_OVERSIZED_APPEND_CAP
+ accepted = fresh[:cap]
+ _wm_debug(
+ f"guard: Key Facts APPEND throttled (oversized): "
+ f"bullets={len(old_items)} est_tok={est_tokens} — "
+ f"input={len(append_items)} deduped={len(fresh)} "
+ f"accepted={len(accepted)} (cap={cap})"
+ )
+ if not accepted:
+ return {"op": "KEEP"}
+ return {"op": "APPEND", "items": accepted}
+ if op_name != "UPDATE":
+ return {"op": "KEEP"}
+
+ new_content = (op.get("content") or "").strip()
+ old_items = Session._wm_extract_bullet_items(old_content or "")
+ new_items = Session._wm_extract_bullet_items(new_content)
+
+ if not old_items:
+ return op
+
+ est_tokens = len(old_content or "") // 4
+ is_emergency = (
+ len(old_items) > Session._WM_SECTION_BULLET_THRESHOLD * 2
+ or est_tokens > Session._WM_SECTION_TOKEN_THRESHOLD * 2
+ )
+
+ # Layer 1: reject trivially small consolidation
+ ratio = len(new_items) / len(old_items) if old_items else 1.0
+ if ratio < Session._WM_KEY_FACTS_MIN_BULLET_RATIO:
+ _wm_debug(
+ f"guard: Key Facts consolidation REJECTED (layer1): "
+ f"new={len(new_items)} / old={len(old_items)} = "
+ f"{ratio:.2%} < {Session._WM_KEY_FACTS_MIN_BULLET_RATIO:.0%}"
+ )
+ salvaged = Session._salvage_new_items_from_rejected_update(
+ new_content, old_content
+ )
+ if is_emergency and salvaged.get("op") == "APPEND":
+ _wm_debug(
+ "guard: suppressing salvage APPEND (emergency level)"
+ )
+ return {"op": "KEEP"}
+ return salvaged
+
+ # Layer 2: lexical anchor coverage
+ old_anchors = Session._extract_lexical_anchors(old_content or "")
+ if old_anchors:
+ new_anchors = Session._extract_lexical_anchors(new_content)
+ covered = len(old_anchors & new_anchors)
+ coverage = covered / len(old_anchors)
+ if coverage < Session._WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:
+ _wm_debug(
+ f"guard: Key Facts consolidation REJECTED (layer2): "
+ f"anchor coverage={coverage:.2%} "
+ f"({covered}/{len(old_anchors)}) < "
+ f"{Session._WM_KEY_FACTS_MIN_ANCHOR_COVERAGE:.0%}"
+ )
+ salvaged = Session._salvage_new_items_from_rejected_update(
+ new_content, old_content
+ )
+ if is_emergency and salvaged.get("op") == "APPEND":
+ _wm_debug(
+ "guard: suppressing salvage APPEND (emergency level)"
+ )
+ return {"op": "KEEP"}
+ return salvaged
+ _wm_debug(
+ f"guard: Key Facts consolidation ACCEPTED: "
+ f"bullets {len(old_items)}->{len(new_items)} "
+ f"({ratio:.1%}), "
+ f"anchors={coverage:.1%} ({covered}/{len(old_anchors)})"
+ )
+ else:
+ _wm_debug(
+ f"guard: Key Facts consolidation ACCEPTED (no old anchors): "
+ f"bullets {len(old_items)}->{len(new_items)}"
+ )
+
+ return op
+
+ @staticmethod
+ def _wm_enforce_files_no_regression(op: Any, old_content: str) -> Dict[str, Any]:
+ """Guard: don't let a 'Files & Context' UPDATE drop file paths.
+
+ If the LLM returns UPDATE whose content is missing one or more file
+ paths that existed in the old content, reject the UPDATE. If the LLM
+ introduced any new paths, surface them as an APPEND; otherwise KEEP.
+ """
+ if not isinstance(op, dict):
+ return {"op": "KEEP"}
+ op_name = (op.get("op") or "").upper()
+ if op_name != "UPDATE":
+ return op
+
+ new_content = (op.get("content") or "").strip()
+ old_paths = set(Session._WM_PATH_LIKE_RE.findall(old_content or ""))
+ new_paths = set(Session._WM_PATH_LIKE_RE.findall(new_content))
+ missing = {p for p in old_paths if p not in new_paths}
+ if not missing:
+ return op
+
+ added_paths = new_paths - old_paths
+ _wm_debug(
+ f"guard: 'Files & Context' UPDATE drops {len(missing)} paths "
+ f"{sorted(list(missing))[:5]}; forcing KEEP (+ APPEND new paths="
+ f"{len(added_paths)})"
+ )
+ if added_paths:
+ # Preserve the old body as-is, then append the genuinely-new items
+ # the LLM added (with a short rationale line if we can find one).
+ new_items: List[str] = []
+ for path in sorted(added_paths):
+ # Try to pull the LLM's own phrasing for that path from new_content
+ for line in new_content.splitlines():
+ if path in line:
+ new_items.append(line.strip().lstrip("-*").strip())
+ break
+ else:
+ new_items.append(f"{path} (newly referenced)")
+ return {"op": "APPEND", "items": new_items}
+ return {"op": "KEEP"}
+
+ @staticmethod
+ def _wm_enforce_title_stability(op: Any, old_content: str) -> Dict[str, Any]:
+ """Guard: reject Session Title UPDATE when it drifts too far.
+
+ Heuristic: if the meaningful-word overlap between the old title and
+ the proposed new title is 0, treat it as drift and fall back to KEEP.
+ This catches the common failure where the LLM rewrites the title each
+ round based on the latest delta instead of the overall session scope.
+ """
+ if not isinstance(op, dict):
+ return {"op": "KEEP"}
+ op_name = (op.get("op") or "").upper()
+ if op_name != "UPDATE":
+ return op
+
+ new_content = (op.get("content") or "").strip()
+
+ def meaningful_words(text: str) -> set:
+ tokens = re.findall(r"[A-Za-z][A-Za-z0-9\.]{2,}|[\d\.]+", text or "")
+ return {
+ t.lower() for t in tokens
+ if t.lower() not in Session._WM_TITLE_STOPWORDS
+ }
+
+ old_w = meaningful_words(old_content)
+ new_w = meaningful_words(new_content)
+
+ # If the previous title was empty we have nothing to compare against.
+ if not old_w:
+ return op
+ # If overlap >= 1 meaningful word, accept the rewording.
+ if len(old_w & new_w) >= 1:
+ return op
+ _wm_debug(
+ f"guard: Session Title drift rejected "
+ f"(old={old_content[:80]!r}, new={new_content[:80]!r}); KEEP"
+ )
+ return {"op": "KEEP"}
+
+ @staticmethod
+ def _wm_enforce_open_issues_resolved(op: Any, old_content: str) -> Dict[str, Any]:
+ """Guard: don't let an Open Issues UPDATE silently drop items.
+
+ Any bullet from the old body whose first 40 lowercase chars do not
+ appear anywhere in the new content is considered silently dropped.
+ We append those items back with a ``[silently dropped, restored]``
+ marker so the caller can see the LLM's intent but no information is
+ lost.
+ """
+ if not isinstance(op, dict):
+ return op
+ op_name = (op.get("op") or "").upper()
+ if op_name != "UPDATE":
+ return op
+
+ new_content = (op.get("content") or "").strip()
+ new_lower = new_content.lower()
+ old_items = Session._wm_extract_bullet_items(old_content or "")
+ dropped: List[str] = []
+ for it in old_items:
+ if "[silently dropped, restored]" in it:
+ continue
+ snippet = it[:40].lower().strip("_* `").strip()
+ if snippet and snippet not in new_lower:
+ dropped.append(it)
+ if not dropped:
+ return op
+
+ _wm_debug(
+ f"guard: Open Issues UPDATE silently dropped {len(dropped)} "
+ f"items; restoring once (will not restore again if re-dropped)"
+ )
+ restored = "\n".join(
+ f"- [silently dropped, restored] {it}" for it in dropped
+ )
+ merged = (new_content + ("\n" if new_content else "") + restored).strip()
+ return {"op": "UPDATE", "content": merged}
+
+ @staticmethod
+ def _merge_wm_sections(old_wm: str, ops: Dict[str, Any]) -> str:
+ """Merge LLM per-section ops into a new Working Memory document.
+
+ ``ops`` is the schema-validated dict shaped like::
+
+ {"Session Title": {"op": "KEEP"},
+ "Current State": {"op": "UPDATE", "content": "..."},
+ "Open Issues": {"op": "APPEND", "items": ["...", "..."]}}
+
+ Per-section server-side guards run BEFORE the op is applied:
+
+ - ``Errors & Corrections`` is append-only; UPDATE is demoted to
+ APPEND of only-new items.
+ - ``Key Facts & Decisions`` uses a fact-preserving dual-threshold
+ guard: UPDATE is accepted only if the consolidated content has
+ >= 15% of old bullet count AND >= 70% lexical anchor coverage.
+ Rejected UPDATEs fall back to APPEND (salvaging new facts)
+ or KEEP if no new facts can be extracted.
+ - ``Files & Context`` UPDATE that loses old file paths is rejected
+ (KEEP + APPEND newly-added paths instead).
+ - ``Session Title`` UPDATE with zero meaningful-word overlap against
+ the prior title is rejected (KEEP instead).
+ - ``Open Issues`` UPDATE that silently drops old items restores them
+ with an explicit marker.
+
+ Missing sections or unknown ops default to ``KEEP`` (the schema
+ should prevent this, but we stay defensive so a buggy LLM or
+ schema-loose backend cannot wipe out the prior WM).
+ """
+ _wm_debug(
+ f"_merge_wm_sections entry old_wm={len(old_wm or '')}B "
+ f"sections={list((ops or {}).keys())[:7]}"
+ )
+ old_sections = Session._parse_wm_sections(old_wm)
+
+ parts: List[str] = ["# Working Memory", ""]
+ for header in WM_SEVEN_SECTIONS:
+ full_header = f"## {header}"
+ op = (ops or {}).get(header)
+ old_content = old_sections.get(full_header, "").rstrip()
+
+ # ---------- per-section guards ----------
+ if old_content:
+ if header == "Session Title":
+ op = Session._wm_enforce_title_stability(op, old_content)
+ elif header == "Key Facts & Decisions":
+ op = Session._wm_enforce_key_facts_consolidation(op, old_content)
+ elif header in Session._WM_APPEND_ONLY_SECTIONS:
+ op = Session._wm_enforce_append_only(header, op, old_content)
+ elif header == "Files & Context":
+ op = Session._wm_enforce_files_no_regression(op, old_content)
+ elif header == "Open Issues":
+ op = Session._wm_enforce_open_issues_resolved(op, old_content)
+ # ----------------------------------------
+
+ if op is None:
+ new_content = old_content
+ else:
+ op_name = (op.get("op") or "").upper() if isinstance(op, dict) else ""
+ if op_name == "KEEP":
+ new_content = old_content
+ elif op_name == "UPDATE":
+ new_content = (op.get("content") or "").strip()
+ elif op_name == "APPEND":
+ items = op.get("items") or []
+ bad_items = [s for s in items if not isinstance(s, str)]
+ if bad_items:
+ logger.warning(
+ "wm_v2: dropped %d non-string APPEND item(s) in section %r: %s",
+ len(bad_items), header, [type(s).__name__ for s in bad_items],
+ )
+ appended = "\n".join(
+ f"- {s.strip()}" for s in items if isinstance(s, str) and s.strip()
+ )
+ if old_content and appended:
+ new_content = f"{old_content}\n{appended}"
+ else:
+ new_content = old_content or appended
+ else:
+ logger.warning(
+ "WM update: unknown op %r for section %r; keeping old content",
+ op,
+ header,
+ )
+ new_content = old_content
+
+ parts.append(full_header)
+ if new_content:
+ parts.append(new_content)
+ parts.append("")
+
+ return "\n".join(parts).rstrip() + "\n"
def _write_archive(
self,
diff --git a/openviking_cli/utils/config/vlm_config.py b/openviking_cli/utils/config/vlm_config.py
index 8e32a80aa..f941809da 100644
--- a/openviking_cli/utils/config/vlm_config.py
+++ b/openviking_cli/utils/config/vlm_config.py
@@ -278,6 +278,7 @@ class VLMConfig(BaseModel):
prompt: str = "",
thinking: bool = False,
tools: Optional[List[Dict[str, Any]]] = None,
+ tool_choice: Optional[Any] = None,
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, Any]:
"""Get LLM completion asynchronously."""
@@ -285,6 +286,7 @@ class VLMConfig(BaseModel):
prompt=prompt,
thinking=thinking,
tools=tools,
+ tool_choice=tool_choice,
messages=messages,
)
diff --git a/tests/unit/session/test_wm_v2_guards.py b/tests/unit/session/test_wm_v2_guards.py
new file mode 100644
index 000000000..f334613f6
--- /dev/null
+++ b/tests/unit/session/test_wm_v2_guards.py
@@ -0,0 +1,665 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Unit tests for WM v2 guards, regex recovery, merge, and pending_tokens.
+
+These tests target pure/static methods on Session and related helpers,
+so they don't need a running OpenViking server.
+"""
+
+from openviking.session.session import Session, WM_SEVEN_SECTIONS
+
+
+# -----------------------------------------------------------------------
+# Helpers
+# -----------------------------------------------------------------------
+
+def _make_wm(**section_bodies: str) -> str:
+ """Build a valid WM v2 markdown document for test input.
+
+ Keyword args map section short-names (underscored) to body text:
+ _make_wm(session_title="Debug Session", current_state="Working")
+ Unmapped sections get empty bodies.
+ """
+ parts = ["# Working Memory", ""]
+ for section in WM_SEVEN_SECTIONS:
+ key = section.lower().replace(" ", "_").replace("&", "and")
+ body = section_bodies.get(key, "")
+ parts.append(f"## {section}")
+ if body:
+ parts.append(body)
+ parts.append("")
+ return "\n".join(parts).rstrip() + "\n"
+
+
+def _calc_pending_tokens(tokens: list, keep_recent_count: int) -> int:
+ """Mirror the _rebuild_pending_tokens math for unit testing."""
+ msgs = [type("M", (), {"estimated_tokens": t})() for t in tokens]
+ keep = int(keep_recent_count or 0)
+ total = len(msgs)
+ if keep <= 0:
+ return sum(int(m.estimated_tokens or 0) for m in msgs)
+ elif total > keep:
+ return sum(int(m.estimated_tokens or 0) for m in msgs[:total - keep])
+ return 0
+
+
+# =======================================================================
+# _parse_wm_sections
+# =======================================================================
+
+class TestParseWmSections:
+ def test_round_trip(self):
+ wm = _make_wm(session_title="My Session", current_state="Idle")
+ parsed = Session._parse_wm_sections(wm)
+ assert parsed["## Session Title"] == "My Session"
+ assert parsed["## Current State"] == "Idle"
+ assert parsed.get("## Task & Goals", "") == ""
+
+ def test_empty_input(self):
+ assert Session._parse_wm_sections("") == {}
+ assert Session._parse_wm_sections(None) == {}
+
+ def test_multiline_body(self):
+ body = "- item 1\n- item 2\n- item 3"
+ wm = _make_wm(key_facts_and_decisions=body)
+ parsed = Session._parse_wm_sections(wm)
+ assert "item 1" in parsed["## Key Facts & Decisions"]
+ assert "item 3" in parsed["## Key Facts & Decisions"]
+
+
+# =======================================================================
+# _wm_extract_bullet_items
+# =======================================================================
+
+class TestExtractBulletItems:
+ def test_dash_bullets(self):
+ items = Session._wm_extract_bullet_items("- foo\n- bar\n- baz")
+ assert items == ["foo", "bar", "baz"]
+
+ def test_numbered_list(self):
+ items = Session._wm_extract_bullet_items("1. first\n2. second\n3) third")
+ assert items == ["first", "second", "third"]
+
+ def test_plain_lines(self):
+ items = Session._wm_extract_bullet_items("plain line one\nplain line two")
+ assert items == ["plain line one", "plain line two"]
+
+ def test_skips_headings_and_blank(self):
+ items = Session._wm_extract_bullet_items("# heading\n\n- real")
+ assert items == ["real"]
+
+ def test_empty(self):
+ assert Session._wm_extract_bullet_items("") == []
+ assert Session._wm_extract_bullet_items(None) == []
+
+
+# =======================================================================
+# _wm_enforce_append_only (Key Facts, Errors & Corrections)
+# =======================================================================
+
+class TestEnforceAppendOnly:
+ def test_keep_passes_through(self):
+ op = {"op": "KEEP"}
+ result = Session._wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")
+ assert result == {"op": "KEEP"}
+
+ def test_append_passes_through(self):
+ op = {"op": "APPEND", "items": ["new item"]}
+ result = Session._wm_enforce_append_only("Key Facts & Decisions", op, "- old fact")
+ assert result == op
+
+ def test_update_demoted_to_append(self):
+ old = "- existing fact"
+ op = {"op": "UPDATE", "content": "- existing fact\n- brand new fact"}
+ result = Session._wm_enforce_append_only("Key Facts & Decisions", op, old)
+ assert result["op"] == "APPEND"
+ assert "brand new fact" in result["items"]
+
+ def test_update_with_all_duplicates_becomes_keep(self):
+ old = "- fact alpha\n- fact beta"
+ op = {"op": "UPDATE", "content": "- fact alpha\n- fact beta"}
+ result = Session._wm_enforce_append_only("Key Facts & Decisions", op, old)
+ assert result["op"] == "KEEP"
+
+ def test_none_op_becomes_keep(self):
+ result = Session._wm_enforce_append_only("Errors & Corrections", None, "old")
+ assert result == {"op": "KEEP"}
+
+ def test_unknown_op_becomes_keep(self):
+ result = Session._wm_enforce_append_only("Errors & Corrections", {"op": "DELETE"}, "old")
+ assert result == {"op": "KEEP"}
+
+
+# =======================================================================
+# _wm_enforce_files_no_regression
+# =======================================================================
+
+class TestEnforceFilesNoRegression:
+ def test_keep_passes_through(self):
+ result = Session._wm_enforce_files_no_regression({"op": "KEEP"}, "- src/main.py")
+ assert result == {"op": "KEEP"}
+
+ def test_update_preserving_all_paths(self):
+ old = "- src/main.py\n- config.yaml"
+ op = {"op": "UPDATE", "content": "- src/main.py updated\n- config.yaml stays\n- new.ts added"}
+ result = Session._wm_enforce_files_no_regression(op, old)
+ assert result["op"] == "UPDATE"
+
+ def test_update_dropping_path_rejected(self):
+ old = "- src/main.py\n- src/utils.ts\n- config.yaml"
+ op = {"op": "UPDATE", "content": "- src/main.py\n- config.yaml"}
+ result = Session._wm_enforce_files_no_regression(op, old)
+ assert result["op"] in ("KEEP", "APPEND")
+
+ def test_update_dropping_path_but_adding_new(self):
+ old = "- src/main.py\n- src/utils.ts"
+ op = {"op": "UPDATE", "content": "- src/main.py\n- brand_new/file.go"}
+ result = Session._wm_enforce_files_no_regression(op, old)
+ assert result["op"] in ("KEEP", "APPEND")
+ if result["op"] == "APPEND":
+ items_text = " ".join(result.get("items", []))
+ assert "brand_new/file.go" in items_text
+
+ def test_append_passes_through(self):
+ op = {"op": "APPEND", "items": ["new_dir/new_file.rs"]}
+ result = Session._wm_enforce_files_no_regression(op, "- src/main.py")
+ assert result == op
+
+ def test_none_op(self):
+ result = Session._wm_enforce_files_no_regression(None, "old")
+ assert result == {"op": "KEEP"}
+
+
+# =======================================================================
+# _wm_enforce_title_stability
+# =======================================================================
+
+class TestEnforceTitleStability:
+ def test_keep_passes_through(self):
+ result = Session._wm_enforce_title_stability({"op": "KEEP"}, "old title")
+ assert result == {"op": "KEEP"}
+
+ def test_update_with_overlap_accepted(self):
+ op = {"op": "UPDATE", "content": "Debug Session Refinement"}
+ result = Session._wm_enforce_title_stability(op, "Debug Session Setup")
+ assert result["op"] == "UPDATE"
+
+ def test_update_with_zero_overlap_rejected(self):
+ op = {"op": "UPDATE", "content": "Completely Different Topic"}
+ result = Session._wm_enforce_title_stability(op, "Database Migration Plan")
+ assert result == {"op": "KEEP"}
+
+ def test_empty_old_title_accepts_anything(self):
+ op = {"op": "UPDATE", "content": "Brand New Title"}
+ result = Session._wm_enforce_title_stability(op, "")
+ assert result["op"] == "UPDATE"
+
+ def test_stopwords_only_old_title_accepts(self):
+ """When old title has NO meaningful words (all stopwords), any update is accepted."""
+ op = {"op": "UPDATE", "content": "The Plan for Notes"}
+ result = Session._wm_enforce_title_stability(op, "A Session Title")
+ assert result["op"] == "UPDATE"
+
+ def test_meaningful_words_no_overlap_rejected(self):
+ op = {"op": "UPDATE", "content": "React Components"}
+ result = Session._wm_enforce_title_stability(op, "Python Migration Tools")
+ assert result == {"op": "KEEP"}
+
+
+# =======================================================================
+# _wm_enforce_open_issues_resolved
+# =======================================================================
+
+class TestEnforceOpenIssuesResolved:
+ def test_update_preserving_all_passes(self):
+ old = "- bug in auth module\n- slow query on /api/users"
+ new_content = "- bug in auth module (investigating)\n- slow query on /api/users\n- new: memory leak"
+ op = {"op": "UPDATE", "content": new_content}
+ result = Session._wm_enforce_open_issues_resolved(op, old)
+ assert result["op"] == "UPDATE"
+ assert "memory leak" in result["content"]
+
+ def test_update_silently_dropping_item_restores(self):
+ old = "- bug in auth module\n- slow query on /api/users"
+ op = {"op": "UPDATE", "content": "- slow query on /api/users"}
+ result = Session._wm_enforce_open_issues_resolved(op, old)
+ assert result["op"] == "UPDATE"
+ assert "silently dropped, restored" in result["content"]
+ assert "bug in auth" in result["content"]
+
+ def test_keep_passes_through(self):
+ result = Session._wm_enforce_open_issues_resolved({"op": "KEEP"}, "old")
+ assert result == {"op": "KEEP"}
+
+ def test_already_restored_item_not_restored_again(self):
+ """Items already tagged [silently dropped, restored] should NOT be
+ restored a second time -- they had their chance."""
+ old = (
+ "- [silently dropped, restored] stale follow-up issue\n"
+ "- fresh unresolved bug"
+ )
+ op = {"op": "UPDATE", "content": "- fresh unresolved bug"}
+ result = Session._wm_enforce_open_issues_resolved(op, old)
+ assert "stale follow-up" not in result["content"]
+ assert "fresh unresolved bug" in result["content"]
+
+ def test_multi_layer_restored_tags_not_restored(self):
+ """Items with nested [silently dropped, restored] tags must not
+ be restored again (regression guard for the old accumulation bug)."""
+ old = (
+ "- [silently dropped, restored] [silently dropped, restored] old issue\n"
+ "- active issue"
+ )
+ op = {"op": "UPDATE", "content": "- active issue"}
+ result = Session._wm_enforce_open_issues_resolved(op, old)
+ assert "old issue" not in result["content"]
+ assert "active issue" in result["content"]
+
+ def test_fresh_item_still_restored_once(self):
+ """A fresh item (no tag) that gets dropped should be restored with
+ the marker exactly once."""
+ old = "- never-restored issue\n- kept issue"
+ op = {"op": "UPDATE", "content": "- kept issue"}
+ result = Session._wm_enforce_open_issues_resolved(op, old)
+ assert "[silently dropped, restored]" in result["content"]
+ assert "never-restored issue" in result["content"]
+
+
+# =======================================================================
+# _merge_wm_sections
+# =======================================================================
+
+class TestMergeWmSections:
+ def test_all_keep(self):
+ old = _make_wm(session_title="Title", current_state="Working")
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ result = Session._merge_wm_sections(old, ops)
+ assert "## Session Title" in result
+ assert "Title" in result
+ assert "Working" in result
+
+ def test_update_current_state(self):
+ old = _make_wm(current_state="Idle")
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ ops["Current State"] = {"op": "UPDATE", "content": "Active debugging"}
+ result = Session._merge_wm_sections(old, ops)
+ assert "Active debugging" in result
+ assert "Idle" not in result
+
+ def test_append_to_open_issues(self):
+ old = _make_wm(open_issues="- existing issue")
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ ops["Open Issues"] = {"op": "APPEND", "items": ["new issue found"]}
+ result = Session._merge_wm_sections(old, ops)
+ assert "existing issue" in result
+ assert "new issue found" in result
+
+ def test_missing_section_defaults_to_keep(self):
+ old = _make_wm(session_title="Original Title")
+ ops = {}
+ result = Session._merge_wm_sections(old, ops)
+ assert "Original Title" in result
+
+ def test_guard_key_facts_update_accepted_when_no_anchors(self):
+ """With trivially small content and no lexical anchors, UPDATE passes
+ the consolidation guard — old items are replaced."""
+ old = _make_wm(key_facts_and_decisions="- fact A\n- fact B")
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": "- fact A\n- fact C"}
+ result = Session._merge_wm_sections(old, ops)
+ assert "fact A" in result
+ assert "fact C" in result
+ assert "fact B" not in result
+
+ def test_guard_title_drift_blocked(self):
+ old = _make_wm(session_title="Database Migration Plan")
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ ops["Session Title"] = {"op": "UPDATE", "content": "Completely Unrelated Topic"}
+ result = Session._merge_wm_sections(old, ops)
+ assert "Database Migration Plan" in result
+ assert "Completely Unrelated Topic" not in result
+
+ def test_all_seven_sections_present(self):
+ old = _make_wm()
+ ops = {s: {"op": "KEEP"} for s in WM_SEVEN_SECTIONS}
+ result = Session._merge_wm_sections(old, ops)
+ for section in WM_SEVEN_SECTIONS:
+ assert f"## {section}" in result
+
+ def test_none_ops(self):
+ old = _make_wm(session_title="Keep Me")
+ result = Session._merge_wm_sections(old, None)
+ assert "Keep Me" in result
+ for section in WM_SEVEN_SECTIONS:
+ assert f"## {section}" in result
+
+
+# =======================================================================
+# _wm_recover_ops_from_raw
+# =======================================================================
+
+class TestWmRecoverOpsFromRaw:
+ def test_recover_keep_ops(self):
+ raw = '"Session Title": {"op": "KEEP"}, "Current State": {"op": "KEEP"}'
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert ops["Session Title"] == {"op": "KEEP"}
+ assert ops["Current State"] == {"op": "KEEP"}
+
+ def test_recover_update_op(self):
+ raw = '"Current State": {"op": "UPDATE", "content": "Now debugging auth"}'
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert ops["Current State"]["op"] == "UPDATE"
+ assert "debugging auth" in ops["Current State"]["content"]
+
+ def test_recover_append_op(self):
+ raw = '"Open Issues": {"op": "APPEND", "items": ["new bug", "another issue"]}'
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert ops["Open Issues"]["op"] == "APPEND"
+ assert "new bug" in ops["Open Issues"]["items"]
+ assert "another issue" in ops["Open Issues"]["items"]
+
+ def test_recover_mixed_ops(self):
+ raw = (
+ '"Session Title": {"op": "KEEP"}, '
+ '"Current State": {"op": "UPDATE", "content": "active"}, '
+ '"Open Issues": {"op": "APPEND", "items": ["todo"]}'
+ )
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert len(ops) == 3
+ assert ops["Session Title"]["op"] == "KEEP"
+ assert ops["Current State"]["op"] == "UPDATE"
+ assert ops["Open Issues"]["op"] == "APPEND"
+
+ def test_empty_input(self):
+ assert Session._wm_recover_ops_from_raw("") == {}
+ assert Session._wm_recover_ops_from_raw(None) == {}
+
+ def test_partial_recovery(self):
+ raw = '"Session Title": {"op": "KEEP"}, garbled content here...'
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert "Session Title" in ops
+ assert len(ops) >= 1
+
+ def test_truncated_update_content(self):
+ raw = (
+ '"Session Title": {"op": "KEEP"}, '
+ '"Current State": {"op": "UPDATE", "content": "partial content '
+ )
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert "Session Title" in ops
+
+ def test_escaped_content(self):
+ raw = r'"Current State": {"op": "UPDATE", "content": "line1\nline2 with \"quotes\""}'
+ ops = Session._wm_recover_ops_from_raw(raw)
+ assert ops["Current State"]["op"] == "UPDATE"
+ assert "line1" in ops["Current State"]["content"]
+
+
+# =======================================================================
+# _rebuild_pending_tokens (via SessionMeta simulation)
+# =======================================================================
+
+class TestRebuildPendingTokens:
+ """Test the _rebuild_pending_tokens math using _calc_pending_tokens helper."""
+
+ def test_no_keep_sums_all(self):
+ assert _calc_pending_tokens([100, 200, 300], keep_recent_count=0) == 600
+
+ def test_keep_2_of_5(self):
+ assert _calc_pending_tokens([100, 200, 300, 400, 500], keep_recent_count=2) == 600
+
+ def test_keep_more_than_total(self):
+ assert _calc_pending_tokens([100, 100, 100], keep_recent_count=10) == 0
+
+ def test_none_tokens_treated_as_zero(self):
+ assert _calc_pending_tokens([None, None, None], keep_recent_count=0) == 0
+
+ def test_empty_messages(self):
+ assert _calc_pending_tokens([], keep_recent_count=0) == 0
+
+ def test_keep_equals_total(self):
+ assert _calc_pending_tokens([100, 200], keep_recent_count=2) == 0
+
+
+# =======================================================================
+# _is_wm_v2 detection (tests the condition in _generate_archive_summary_async)
+# =======================================================================
+
+class TestIsWmV2Detection:
+ def _is_wm_v2(self, overview: str) -> bool:
+ """Mirror the detection logic from session.py."""
+ return bool(overview) and any(
+ f"## {s}" in overview for s in WM_SEVEN_SECTIONS
+ )
+
+ def test_valid_v2(self):
+ wm = _make_wm(session_title="Test")
+ assert self._is_wm_v2(wm) is True
+
+ def test_legacy_format(self):
+ legacy = "Session overview: this is a legacy format with no sections"
+ assert self._is_wm_v2(legacy) is False
+
+ def test_empty(self):
+ assert self._is_wm_v2("") is False
+ assert self._is_wm_v2(None) is False
+
+ def test_partial_sections(self):
+ partial = "## Session Title\nSome title\n## Current State\nWorking"
+ assert self._is_wm_v2(partial) is True
+
+ def test_wrong_heading_level(self):
+ """'### Session Title' contains '## Session Title' as substring -> matches."""
+ wrong = "### Session Title\nSome title"
+ assert self._is_wm_v2(wrong) is True
+
+ def test_no_section_headers(self):
+ no_headers = "Just some plain text without any section headers."
+ assert self._is_wm_v2(no_headers) is False
+
+
+# =======================================================================
+# WM_PATH_LIKE_RE
+# =======================================================================
+
+class TestWmPathLikeRe:
+ def test_python_file(self):
+ assert Session._WM_PATH_LIKE_RE.search("src/main.py")
+
+ def test_typescript_file(self):
+ assert Session._WM_PATH_LIKE_RE.search("components/App.tsx")
+
+ def test_deep_path(self):
+ assert Session._WM_PATH_LIKE_RE.search("openviking/session/session")
+
+ def test_yaml_file(self):
+ assert Session._WM_PATH_LIKE_RE.search("config.yaml")
+
+ def test_no_match_plain_word(self):
+ assert not Session._WM_PATH_LIKE_RE.search("hello")
+
+
+# =======================================================================
+# pending_tokens defensive clamp
+# =======================================================================
+
+class TestPendingTokensClamp:
+ """Verify that pending_tokens is always clamped to >= 0."""
+
+ def test_negative_pending_tokens_clamped_on_rebuild(self):
+ result = _calc_pending_tokens([], keep_recent_count=0)
+ assert result >= 0
+
+ def test_negative_keep_recent_count_treated_as_zero(self):
+ result = _calc_pending_tokens([100, 200], keep_recent_count=-5)
+ assert result == 300
+
+ def test_from_dict_clamps_negative_pending(self):
+ from openviking.session.session import SessionMeta
+ data = {"pending_tokens": -100, "keep_recent_count": -5}
+ meta = SessionMeta.from_dict(data)
+ assert meta.pending_tokens >= 0
+ assert meta.keep_recent_count >= 0
+
+
+# =======================================================================
+# APPEND non-string items handling
+# =======================================================================
+
+class TestAppendNonStringItems:
+ """APPEND items that are not strings should be dropped (not crash)."""
+
+ def test_append_with_mixed_types_keeps_strings(self):
+ old_wm = _make_wm(open_issues="- Existing issue")
+ ops = {
+ "Session Title": {"op": "KEEP"},
+ "Current State": {"op": "KEEP"},
+ "Task & Goals": {"op": "KEEP"},
+ "Key Facts & Decisions": {"op": "KEEP"},
+ "Files & Context": {"op": "KEEP"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "APPEND", "items": ["valid item", 42, None, {"bad": True}]},
+ }
+ merged = Session._merge_wm_sections(old_wm, ops)
+ assert "valid item" in merged
+ assert "Existing issue" in merged
+ assert "42" not in merged
+
+ def test_append_with_empty_items(self):
+ old_wm = _make_wm(open_issues="- Existing issue")
+ ops = {
+ "Session Title": {"op": "KEEP"},
+ "Current State": {"op": "KEEP"},
+ "Task & Goals": {"op": "KEEP"},
+ "Key Facts & Decisions": {"op": "KEEP"},
+ "Files & Context": {"op": "KEEP"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "APPEND", "items": []},
+ }
+ merged = Session._merge_wm_sections(old_wm, ops)
+ assert "Existing issue" in merged
+
+
+# =======================================================================
+# _merge_wm_sections edge cases
+# =======================================================================
+
+class TestMergeWmSectionsEdgeCases:
+
+ def test_missing_ops_default_to_keep(self):
+ old_wm = _make_wm(
+ session_title="Original Title",
+ current_state="Running",
+ )
+ merged = Session._merge_wm_sections(old_wm, {})
+ assert "Original Title" in merged
+ assert "Running" in merged
+
+ def test_unknown_op_defaults_to_keep(self):
+ old_wm = _make_wm(current_state="Running")
+ ops = {
+ "Session Title": {"op": "KEEP"},
+ "Current State": {"op": "UNKNOWN_OP"},
+ "Task & Goals": {"op": "KEEP"},
+ "Key Facts & Decisions": {"op": "KEEP"},
+ "Files & Context": {"op": "KEEP"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "KEEP"},
+ }
+ merged = Session._merge_wm_sections(old_wm, ops)
+ assert "Running" in merged
+
+ def test_all_sections_update(self):
+ old_wm = _make_wm(
+ session_title="Old Title",
+ current_state="Old State",
+ )
+ ops = {
+ "Session Title": {"op": "UPDATE", "content": "Old Title (updated)"},
+ "Current State": {"op": "UPDATE", "content": "New State"},
+ "Task & Goals": {"op": "UPDATE", "content": "New Goals"},
+ "Key Facts & Decisions": {"op": "UPDATE", "content": "- New fact"},
+ "Files & Context": {"op": "UPDATE", "content": "- new/file.py"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "UPDATE", "content": "- New issue"},
+ }
+ merged = Session._merge_wm_sections(old_wm, ops)
+ assert "New State" in merged
+ assert "New Goals" in merged
+
+
+# -----------------------------------------------------------------------
+# _format_message_for_wm
+# -----------------------------------------------------------------------
+
+from openviking.message.message import Message
+from openviking.message.part import TextPart, ToolPart, ContextPart
+
+
+def _msg(role, parts):
+ """Convenience builder for a Message with an auto-id."""
+ return Message(id="test-msg", role=role, parts=parts)
+
+
+class TestFormatMessageForWm:
+ """Tests for Session._format_message_for_wm."""
+
+ def test_text_only(self):
+ m = _msg("user", [TextPart(text="Hello world")])
+ result = Session._format_message_for_wm(m)
+ assert result == "[user]: Hello world"
+
+ def test_tool_part_included(self):
+ m = _msg("assistant", [
+ ToolPart(tool_name="search", tool_status="completed",
+ tool_output="found 3 results"),
+ ])
+ result = Session._format_message_for_wm(m)
+ assert "[tool:search (completed)]" in result
+ assert "found 3 results" in result
+ assert result.startswith("[assistant]:")
+
+ def test_context_part_included(self):
+ m = _msg("assistant", [
+ ContextPart(abstract="Summary of prior session"),
+ ])
+ result = Session._format_message_for_wm(m)
+ assert "[context] Summary of prior session" in result
+
+ def test_mixed_parts(self):
+ m = _msg("assistant", [
+ TextPart(text="Let me check."),
+ ToolPart(tool_name="read_file", tool_status="completed",
+ tool_output="/path/to/file content here"),
+ TextPart(text="Done reading."),
+ ])
+ result = Session._format_message_for_wm(m)
+ lines = result.split("\n")
+ assert lines[0] == "[assistant]: Let me check."
+ assert "[tool:read_file (completed)]" in lines[1]
+ assert "Done reading." in lines[2]
+
+ def test_empty_parts(self):
+ m = _msg("user", [])
+ result = Session._format_message_for_wm(m)
+ assert "(no content)" in result
+
+ def test_whitespace_only_text_skipped(self):
+ m = _msg("user", [TextPart(text=" ")])
+ result = Session._format_message_for_wm(m)
+ assert "(no content)" in result
+
+ def test_tool_with_empty_output(self):
+ m = _msg("assistant", [
+ ToolPart(tool_name="delete", tool_status="completed", tool_output=""),
+ ])
+ result = Session._format_message_for_wm(m)
+ assert "[tool:delete (completed)]" in result
+
+ def test_tool_default_status(self):
+ m = _msg("assistant", [
+ ToolPart(tool_name="run", tool_output="ok"),
+ ])
+ result = Session._format_message_for_wm(m)
+ assert "(pending)" in result
diff --git a/tests/unit/session/test_working_memory_growth.py b/tests/unit/session/test_working_memory_growth.py
new file mode 100644
index 000000000..25a4c08ff
--- /dev/null
+++ b/tests/unit/session/test_working_memory_growth.py
@@ -0,0 +1,580 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Tests for Working Memory growth behavior and anti-bloat guards."""
+
+from openviking.session.session import Session
+
+
+def _wm(
+ *,
+ current_state: str = "Actively updating Working Memory behavior.",
+ key_facts: str = "- Decision 0: keep the current WM shape.",
+ files_context: str = "- openviking/session/session.py - WM merge logic.",
+ errors: str = "",
+ open_issues: str = "",
+) -> str:
+ sections = {
+ "Session Title": "Working Memory Growth Checks",
+ "Current State": current_state,
+ "Task & Goals": "Understand whether current WM sections can grow without bound.",
+ "Key Facts & Decisions": key_facts,
+ "Files & Context": files_context,
+ "Errors & Corrections": errors,
+ "Open Issues": open_issues,
+ }
+ parts = ["# Working Memory", ""]
+ for header, body in sections.items():
+ parts.extend([f"## {header}", body, ""])
+ return "\n".join(parts).rstrip() + "\n"
+
+
+def _keep_all() -> dict:
+ return {
+ "Session Title": {"op": "KEEP"},
+ "Current State": {"op": "KEEP"},
+ "Task & Goals": {"op": "KEEP"},
+ "Key Facts & Decisions": {"op": "KEEP"},
+ "Files & Context": {"op": "KEEP"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "KEEP"},
+ }
+
+
+def _section_items(wm: str, header: str) -> list[str]:
+ parsed = Session._parse_wm_sections(wm)
+ return Session._wm_extract_bullet_items(parsed.get(f"## {header}", ""))
+
+
+def _section_body(wm: str, header: str) -> str:
+ parsed = Session._parse_wm_sections(wm)
+ return parsed.get(f"## {header}", "")
+
+
+# =====================================================================
+# Monotonic-growth tests (unchanged behavior for APPEND-driven sections)
+# =====================================================================
+
+def test_key_facts_section_grows_monotonically_under_repeated_appends():
+ merged = _wm()
+
+ for idx in range(1, 51):
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": [f"Decision {idx}: keep module_{idx}.py because contract {idx} is stable."],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) == 51
+ assert items[0] == "Decision 0: keep the current WM shape."
+ assert items[-1] == "Decision 50: keep module_50.py because contract 50 is stable."
+
+
+def test_errors_and_corrections_section_grows_with_each_new_error():
+ merged = _wm(errors="- Round 0: initial mismatch between prompt and merge logic.")
+
+ for idx in range(1, 41):
+ ops = _keep_all()
+ ops["Errors & Corrections"] = {
+ "op": "APPEND",
+ "items": [f"Round {idx}: corrected assumption {idx} after verification."],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+
+ items = _section_items(merged, "Errors & Corrections")
+
+ assert len(items) == 41
+ assert items[0] == "Round 0: initial mismatch between prompt and merge logic."
+ assert items[-1] == "Round 40: corrected assumption 40 after verification."
+
+
+def test_files_and_context_section_can_keep_growing_with_unique_paths():
+ merged = _wm(files_context="- src/file_0.py - initial reference.")
+
+ for idx in range(1, 31):
+ ops = _keep_all()
+ ops["Files & Context"] = {
+ "op": "APPEND",
+ "items": [f"src/file_{idx}.py - referenced during round {idx}."],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+
+ items = _section_items(merged, "Files & Context")
+
+ assert len(items) == 31
+ assert items[0] == "src/file_0.py - initial reference."
+ assert items[-1] == "src/file_30.py - referenced during round 30."
+
+
+# =====================================================================
+# Key Facts consolidation guard — Layer 1: bullet-count ratio
+# =====================================================================
+
+def test_key_facts_consolidation_rejected_when_trivially_small():
+ """A 1-bullet UPDATE for 41 old bullets (2.4%) is rejected.
+
+ The rejected UPDATE's content is checked for genuinely new items.
+ Since the consolidation summary is just a restatement, it gets
+ salvaged as a new APPEND item (not present verbatim in old content).
+ Old items are preserved, and the new summary is appended.
+ """
+ key_facts = "\n".join(
+ f"- Decision {idx}: keep module_{idx}.py because API contract {idx} is stable."
+ for idx in range(1, 42)
+ )
+ old_wm = _wm(key_facts=key_facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": (
+ "- Consolidated summary: keep modules 1-41 because their API contracts are stable."
+ ),
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) == 42
+ assert "Decision 1: keep module_1.py because API contract 1 is stable." in items
+ assert any("Consolidated summary" in it for it in items)
+
+
+# =====================================================================
+# Key Facts consolidation guard — Layer 2: anchor coverage
+# =====================================================================
+
+_RICH_KEY_FACTS = "\n".join([
+ "- Caroline adopted a rescue dog named Biscuit on 15 March 2024.",
+ "- Melanie's family took 3 camping trips to Yellowstone because the kids love hiking.",
+ "- Caroline attended pride parade on 10 June 2023, felt empowered.",
+ "- Caroline attended pride parade on 9 June 2024, brought friends.",
+ "- Sweden trip planned for August 2025 with budget of 5000 dollars.",
+ "- Decided to use Python because the team has 4 years experience.",
+ "- Marcus is Caroline's brother, lives in Portland.",
+ "- Caroline volunteers at the shelter every Saturday morning.",
+ "- Adoption agency: Bright Futures, contacted on 2024-01-20.",
+ "- Melanie decided to homeschool the kids because local schools are overcrowded.",
+ "- Caroline's art exhibition on 22 November 2024 at Gallery One.",
+ "- Biscuit has a vet appointment every 6 months at Pawsome Clinic.",
+ "- Marcus committed to help with the Sweden trip logistics.",
+ "- Caroline chose watercolor over oil painting because of studio ventilation.",
+ "- Family reunion planned for December 2025 in Portland.",
+ "- Melanie's oldest child starts college in September 2026.",
+ "- Caroline resolved to run a half-marathon in Spring 2025.",
+ "- Budget for art supplies: 200 dollars per month.",
+ "- Caroline's neighbor Jake offered to pet-sit Biscuit during Sweden trip.",
+ "- Melanie agreed to share camping gear for the next Yellowstone trip.",
+ "- Caroline took a ceramics class starting January 2025.",
+ "- Marcus and Caroline share a joint savings account for family events.",
+ "- Bright Futures agency requires 3 home visits before approval.",
+ "- Caroline prefers morning runs, usually 5 miles along the river trail.",
+ "- Melanie's youngest allergic to peanuts, diagnosed at age 2.",
+ "- Gallery One charges 500 dollars for exhibition space.",
+ "- Caroline decided to switch from acrylic to watercolor in March 2024.",
+ "- Portland family home has 4 bedrooms, enough for reunion guests.",
+ "- Sweden itinerary: Stockholm 3 days, Gothenburg 2 days, countryside 2 days.",
+ "- Caroline's running group meets every Wednesday at 6 AM.",
+ "- Melanie committed to volunteer at kids' school fundraiser.",
+ "- Jake is a retired teacher, lives next door since 2020.",
+ "- Caroline's half-marathon target time: under 2 hours.",
+ "- Art exhibition features 12 watercolor paintings.",
+ "- Melanie's camping trips always in July because of school schedule.",
+ "- Caroline and Marcus talk every Sunday evening by phone.",
+ "- Biscuit is a 3 years old golden retriever mix.",
+ "- Bright Futures requires background checks completed by February 2025.",
+ "- Caroline's studio is in the garage, converted in 2023.",
+ "- Melanie drives a minivan because she has 3 kids.",
+ "- Family agreed on a $2000 budget cap for the reunion dinner.",
+])
+
+_GOOD_CONSOLIDATION = "\n".join([
+ "- Caroline adopted rescue dog Biscuit (golden retriever mix, 3 years old) on 15 March 2024; vet at Pawsome Clinic every 6 months. Neighbor Jake (retired teacher, next door since 2020) offered to pet-sit during Sweden trip.",
+ "- Caroline regularly attends pride parades; most recently on 9 June 2024, brought friends.",
+ "- Caroline's art: switched from acrylic to watercolor (March 2024) because of studio ventilation; exhibition on 22 November 2024 at Gallery One (12 paintings, 500 dollars space); studio in garage, converted 2023. Budget 200 dollars/month.",
+ "- Caroline took ceramics class starting January 2025; resolved to run half-marathon Spring 2025 (target under 2 hours, runs 5 miles mornings along river trail, group meets Wednesdays 6 AM).",
+ "- Caroline volunteers at shelter every Saturday morning.",
+ "- Marcus is Caroline's brother, lives in Portland; committed to help with Sweden trip; they share joint savings for family events; talk every Sunday evening.",
+ "- Melanie's family: 3 camping trips to Yellowstone (always July, because school schedule, kids love hiking); agreed to share gear. Oldest starts college September 2026. Youngest allergic to peanuts (diagnosed age 2). Melanie drives minivan because 3 kids. Decided to homeschool because local schools overcrowded. Committed to school fundraiser volunteer.",
+ "- Sweden trip planned August 2025, budget 5000 dollars: Stockholm 3 days, Gothenburg 2 days, countryside 2 days.",
+ "- Adoption agency Bright Futures, contacted 2024-01-20: requires 3 home visits and background checks by February 2025.",
+ "- Decided to use Python because team has 4 years experience.",
+ "- Family reunion December 2025 in Portland (4-bedroom home, enough for guests); agreed $2000 budget cap for reunion dinner.",
+])
+
+
+def test_key_facts_consolidation_accepted_when_anchors_preserved():
+ """A 41-to-11 consolidation (26.8%) with high anchor coverage passes."""
+ old_wm = _wm(key_facts=_RICH_KEY_FACTS)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": _GOOD_CONSOLIDATION,
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) <= 15
+ body = _section_body(merged, "Key Facts & Decisions")
+ assert "Caroline" in body
+ assert "Melanie" in body
+ assert "Marcus" in body
+ assert "Biscuit" in body
+ assert "Yellowstone" in body
+ assert "Sweden" in body
+ assert "Portland" in body
+
+
+def test_key_facts_consolidation_rejected_when_anchors_missing():
+ """An UPDATE that drops most names/dates/numbers is rejected.
+
+ Old items are preserved; any genuinely new items from the rejected
+ UPDATE are salvaged via APPEND.
+ """
+ old_wm = _wm(key_facts=_RICH_KEY_FACTS)
+ vague_items = [
+ "- The user has various personal plans and family activities.",
+ "- Several trips are being planned for the coming year.",
+ "- Art and running are important hobbies.",
+ "- Family relationships are strong and supportive.",
+ "- Multiple commitments have been made regarding future events.",
+ "- The user works with technology and has team preferences.",
+ "- Pet care arrangements are in place.",
+ "- Educational decisions have been discussed.",
+ ]
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": "\n".join(vague_items),
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) >= 41
+ body = _section_body(merged, "Key Facts & Decisions")
+ assert "Caroline adopted a rescue dog named Biscuit" in body
+
+
+def test_key_facts_consolidation_accepted_at_low_volume_with_anchors():
+ """A 41-to-10 consolidation (~24% volume) passes when anchors are kept."""
+ old_wm = _wm(key_facts=_RICH_KEY_FACTS)
+
+ consolidated = "\n".join([
+ "- Caroline adopted Biscuit (golden retriever, 3 years old) on 15 March 2024; vet every 6 months at Pawsome Clinic.",
+ "- Caroline attends pride parades regularly; latest 9 June 2024.",
+ "- Caroline's art: watercolor (switched March 2024 because ventilation); exhibition 22 November 2024 at Gallery One, 12 paintings, 500 dollars. Studio in garage since 2023. Budget 200 dollars/month. Also took ceramics January 2025.",
+ "- Caroline runs half-marathon Spring 2025, target under 2 hours; runs 5 miles mornings, group Wednesdays 6 AM. Volunteers shelter Saturdays.",
+ "- Marcus: Caroline's brother, Portland. Joint savings, Sunday calls. Committed to Sweden trip help.",
+ "- Melanie: 3 kids, minivan, homeschooling because overcrowded schools. Oldest college September 2026, youngest peanut allergy diagnosed age 2. Camping Yellowstone in July (3 trips, kids love hiking). Fundraiser volunteer.",
+ "- Sweden August 2025, 5000 dollars: Stockholm 3 days, Gothenburg 2 days, countryside 2 days. Jake (neighbor since 2020, retired teacher) pet-sits Biscuit.",
+ "- Adoption: Bright Futures contacted 2024-01-20; 3 home visits, background checks by February 2025.",
+ "- Team decided Python because 4 years experience.",
+ "- Family reunion December 2025 Portland, 4 bedrooms, $2000 dinner cap.",
+ ])
+
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": consolidated}
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) == 10
+ body = _section_body(merged, "Key Facts & Decisions")
+ for name in ["Caroline", "Melanie", "Marcus", "Biscuit", "Jake"]:
+ assert name in body
+ for date in ["15 March 2024", "2024-01-20", "December 2025"]:
+ assert date in body
+
+
+# =====================================================================
+# _extract_lexical_anchors — mixed-case and multi-word entities
+# =====================================================================
+
+def test_extract_anchors_catches_mixed_case_names():
+ """OpenAI, McCloud, JavaScript etc. should be captured as anchors."""
+ text = (
+ "- Used OpenAI API for the project.\n"
+ "- McCloud reviewed the PR on 2024-03-15.\n"
+ "- Rewrote the frontend in JavaScript."
+ )
+ anchors = Session._extract_lexical_anchors(text)
+ assert "openai" in anchors
+ assert "mccloud" in anchors
+ assert "javascript" in anchors
+
+
+def test_extract_anchors_catches_standard_proper_nouns():
+ """Standard Titlecase names like Caroline, Sweden, Portland."""
+ text = "- Caroline traveled to Sweden and visited Portland."
+ anchors = Session._extract_lexical_anchors(text)
+ assert "caroline" in anchors
+ assert "sweden" in anchors
+ assert "portland" in anchors
+
+
+def test_extract_anchors_filters_stopwords():
+ """Common English words should be filtered even if capitalized."""
+ text = "The And Other Some These Those"
+ anchors = Session._extract_lexical_anchors(text)
+ assert "the" not in anchors
+ assert "other" not in anchors
+ assert "some" not in anchors
+
+
+# =====================================================================
+# Salvage: rejected consolidation still preserves new facts (P1 fix)
+# =====================================================================
+
+def test_key_facts_rejected_consolidation_salvages_new_facts():
+ """When consolidation is rejected (layer1 or layer2), genuinely new
+ items from the UPDATE content are APPENDed so current-round facts
+ are not silently lost."""
+ key_facts = "\n".join(
+ f"- Decision {idx}: keep module_{idx}.py because API contract {idx} is stable."
+ for idx in range(1, 42)
+ )
+ old_wm = _wm(key_facts=key_facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": (
+ "- Summary: all modules stable.\n"
+ "- NEW: Caroline adopted a puppy named Max on 2024-06-15."
+ ),
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+
+ assert len(items) >= 42
+ assert "Decision 1: keep module_1.py because API contract 1 is stable." in items
+ body = _section_body(merged, "Key Facts & Decisions")
+ assert "Caroline adopted a puppy named Max" in body
+
+
+# =====================================================================
+# _build_wm_section_reminders
+# =====================================================================
+
+def test_build_wm_section_reminders_triggers_above_threshold():
+ key_facts = "\n".join(
+ f"- Fact {idx}: something important about item {idx}."
+ for idx in range(1, 35)
+ )
+ wm = _wm(key_facts=key_facts)
+
+ reminders = Session._build_wm_section_reminders(wm)
+
+ assert "<section_size_warnings>" in reminders
+ assert "Key Facts" in reminders
+ assert "34 bullets" in reminders
+ assert "MUST be consolidated" in reminders
+
+
+def test_build_wm_section_reminders_skips_append_only_sections():
+ """Errors & Corrections should never get consolidation warnings
+ even if oversized, because it's append-only."""
+ errors = "\n".join(
+ f"- Error {idx}: something went wrong in round {idx}."
+ for idx in range(1, 40)
+ )
+ wm = _wm(errors=errors)
+
+ reminders = Session._build_wm_section_reminders(wm)
+
+ assert "Errors" not in reminders
+
+
+def test_build_wm_section_reminders_silent_below_threshold():
+ key_facts = "\n".join(
+ f"- Fact {idx}: something about item {idx}."
+ for idx in range(1, 10)
+ )
+ wm = _wm(key_facts=key_facts)
+
+ reminders = Session._build_wm_section_reminders(wm)
+
+ assert reminders == ""
+
+
+# =====================================================================
+# Wiring test: _generate_archive_summary_async passes reminders
+# =====================================================================
+
+def test_wm_section_reminders_consistent_with_prompt_template():
+ """Verify _build_wm_section_reminders output matches the format expected
+ by ov_wm_v2_update.yaml (XML tags that the Jinja2 template injects)."""
+ big_key_facts = "\n".join(
+ f"- Fact {idx}: person_{idx} decided thing_{idx} on 2024-01-{idx:02d}."
+ for idx in range(1, 35)
+ )
+ prior_wm = _wm(key_facts=big_key_facts)
+
+ reminders = Session._build_wm_section_reminders(prior_wm)
+
+ assert reminders.startswith("<section_size_warnings>")
+ assert reminders.endswith("</section_size_warnings>")
+ assert "Key Facts & Decisions" in reminders
+ assert "34 bullets" in reminders
+ assert "MUST be consolidated" in reminders
+ assert f"<={Session._WM_SECTION_BULLET_THRESHOLD} bullets" in reminders
+ assert f"<={Session._WM_SECTION_TOKEN_THRESHOLD} tokens" in reminders
+
+
+# =====================================================================
+# Aggregate document size test (adapted for new guard behavior)
+# =====================================================================
+
+def test_working_memory_document_size_keeps_increasing_across_rounds():
+ merged = _wm(
+ key_facts="- Decision 0: keep the current WM shape.",
+ files_context="- src/file_0.py - initial reference.",
+ errors="- Round 0: initial mismatch between prompt and merge logic.",
+ )
+ initial_size = len(merged)
+
+ for idx in range(1, 61):
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": [f"Decision {idx}: keep module_{idx}.py because contract {idx} is stable."],
+ }
+ ops["Files & Context"] = {
+ "op": "APPEND",
+ "items": [f"src/file_{idx}.py - referenced during round {idx}."],
+ }
+ ops["Errors & Corrections"] = {
+ "op": "APPEND",
+ "items": [f"Round {idx}: corrected assumption {idx} after verification."],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+
+ assert len(merged) > initial_size
+ kf_items = _section_items(merged, "Key Facts & Decisions")
+ assert len(kf_items) == 52, (
+ f"Key Facts should stop at 52 (51 facts + 1 consolidation sentinel); "
+ f"got {len(kf_items)}"
+ )
+ assert any("CONSOLIDATION REQUIRED" in it for it in kf_items), (
+ "Emergency sentinel must be present when Key Facts exceeds 2x threshold"
+ )
+ assert len(_section_items(merged, "Files & Context")) == 61
+ assert len(_section_items(merged, "Errors & Corrections")) == 61
+
+
+# =====================================================================
+# Anti-bloat guard: focused tests for each path
+# =====================================================================
+
+def test_antibloat_normal_append_passes_under_threshold():
+ """APPEND with fewer than threshold bullets should pass without throttling."""
+ facts = "\n".join(f"- Fact {i}" for i in range(10))
+ merged = _wm(key_facts=facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": ["New fact A", "New fact B"],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert len(items) == 12
+ assert "New fact A" in items
+ assert "New fact B" in items
+
+
+def test_antibloat_throttled_append_caps_at_5():
+ """APPEND beyond threshold but under 2x should accept at most 5 new items."""
+ facts = "\n".join(f"- Fact {i}" for i in range(30))
+ merged = _wm(key_facts=facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": [f"Extra {i}" for i in range(10)],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert len(items) == 35, (
+ f"Expected 30 + 5 (capped) = 35; got {len(items)}"
+ )
+
+
+def test_antibloat_throttled_dedup_filters_existing():
+ """Throttled APPEND should skip items already present in old content."""
+ facts = "\n".join(f"- Fact {i}" for i in range(30))
+ merged = _wm(key_facts=facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": ["Fact 0", "Fact 1", "Brand new insight"],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert "Brand new insight" in items
+ assert items.count("Fact 0") == 1
+
+
+def test_antibloat_emergency_inserts_sentinel_and_stops():
+ """APPEND beyond 2x threshold should insert sentinel once, then hard stop."""
+ facts = "\n".join(f"- Fact {i}" for i in range(55))
+ merged = _wm(key_facts=facts)
+
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": ["Emergency fact A"],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert len(items) == 56, f"Expected 55 + 1 sentinel = 56; got {len(items)}"
+ assert any("CONSOLIDATION REQUIRED" in it for it in items)
+ assert "Emergency fact A" not in items
+
+ ops2 = _keep_all()
+ ops2["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": ["Emergency fact B"],
+ }
+ merged = Session._merge_wm_sections(merged, ops2)
+ items2 = _section_items(merged, "Key Facts & Decisions")
+ assert len(items2) == 56, (
+ f"Sentinel already present — should stay at 56; got {len(items2)}"
+ )
+ assert "Emergency fact B" not in items2
+
+
+def test_antibloat_salvage_bypass_blocked_at_emergency():
+ """UPDATE rejected by Layer1/2 → salvage APPEND should be suppressed
+ when Key Facts is at emergency level."""
+ facts = "\n".join(
+ f"- Person_{i} decided thing_{i} on 2024-01-{i % 28 + 1:02d}."
+ for i in range(55)
+ )
+ merged = _wm(key_facts=facts)
+
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": "- Only one bullet.",
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert len(items) == 55, (
+ f"Salvage APPEND should be suppressed at emergency level; got {len(items)}"
+ )
+
+
+def test_antibloat_nonstring_items_handled():
+ """Non-string items in APPEND should not crash the guard."""
+ facts = "\n".join(f"- Fact {i}" for i in range(30))
+ merged = _wm(key_facts=facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "APPEND",
+ "items": [123, None, "Valid new fact", True],
+ }
+ merged = Session._merge_wm_sections(merged, ops)
+ items = _section_items(merged, "Key Facts & Decisions")
+ assert "Valid new fact" in items
diff --git a/tests/unit/session/test_working_memory_v2.py b/tests/unit/session/test_working_memory_v2.py
new file mode 100644
index 000000000..617c20617
--- /dev/null
+++ b/tests/unit/session/test_working_memory_v2.py
@@ -0,0 +1,121 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Unit tests for Working Memory v2 merge guardrails."""
+
+from openviking.session.session import Session
+
+
+def _wm(
+ *,
+ current_state: str = "Actively updating Working Memory v2 prompts.",
+ key_facts: str = "- Decision 1: keep existing WM v2 schema.",
+ files_context: str = "- openviking/session/session.py - WM merge logic.",
+ errors: str = "",
+ open_issues: str = "",
+) -> str:
+ sections = {
+ "Session Title": "Working Memory v2 Guardrails",
+ "Current State": current_state,
+ "Task & Goals": "Improve WM v2 prompt and merge behavior.",
+ "Key Facts & Decisions": key_facts,
+ "Files & Context": files_context,
+ "Errors & Corrections": errors,
+ "Open Issues": open_issues,
+ }
+ parts = ["# Working Memory", ""]
+ for header, body in sections.items():
+ parts.extend([f"## {header}", body, ""])
+ return "\n".join(parts).rstrip() + "\n"
+
+
+def _keep_all() -> dict:
+ return {
+ "Session Title": {"op": "KEEP"},
+ "Current State": {"op": "KEEP"},
+ "Task & Goals": {"op": "KEEP"},
+ "Key Facts & Decisions": {"op": "KEEP"},
+ "Files & Context": {"op": "KEEP"},
+ "Errors & Corrections": {"op": "KEEP"},
+ "Open Issues": {"op": "KEEP"},
+ }
+
+
+def test_dynamic_reminders_flag_large_key_facts_and_bulk_urls():
+ key_facts = "\n".join(
+ f"- Decision {i}: keep module_{i}.py because API contract {i} is stable."
+ for i in range(1, 42)
+ )
+ files_context = "\n".join(
+ f"- https://example.com/images/{i}.png - raw parser image URL."
+ for i in range(1, 23)
+ )
+
+ reminders = Session._build_wm_section_reminders(
+ _wm(key_facts=key_facts, files_context=files_context)
+ )
+
+ assert "<section_size_warnings>" in reminders
+ assert '"Key Facts & Decisions" has 41 bullets' in reminders
+ assert "consolidated via UPDATE" in reminders
+
+
+def test_key_facts_allows_safe_consolidation_when_oversized():
+ """Consolidation UPDATE with too few bullets (1/41 < 15%) is rejected;
+ the new consolidated summary is salvaged as APPEND while old items are kept."""
+ key_facts = "\n".join(
+ f"- Decision {i}: keep module_{i}.py because API contract {i} is stable."
+ for i in range(1, 42)
+ )
+ old_wm = _wm(key_facts=key_facts)
+ consolidated = (
+ "- Decisions 1-41: keep the stable API contracts for "
+ + ", ".join(f"module_{i}.py" for i in range(1, 42))
+ + "."
+ )
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {"op": "UPDATE", "content": consolidated}
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+
+ assert consolidated in merged
+ assert "- Decision 1: keep module_1.py because API contract 1 is stable." in merged
+ assert "module_41.py" in merged
+
+
+def test_key_facts_rejects_unsafe_consolidation_that_drops_anchors():
+ key_facts = "\n".join(
+ f"- Decision {i}: keep module_{i}.py because API contract {i} is stable."
+ for i in range(1, 42)
+ )
+ old_wm = _wm(key_facts=key_facts)
+ ops = _keep_all()
+ ops["Key Facts & Decisions"] = {
+ "op": "UPDATE",
+ "content": "- New decision: only module_1.py remains relevant.",
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+
+ assert "- Decision 41: keep module_41.py because API contract 41 is stable." in merged
+ assert "- New decision: only module_1.py remains relevant." in merged
+
+
+def test_files_context_update_blocked_when_dropping_path_like_tokens():
+ """Files & Context guard rejects UPDATE that drops path-like tokens from
+ old content; result falls back to KEEP so both items are preserved."""
+ old_wm = _wm(
+ files_context=(
+ "- openviking/session/session.py - WM merge logic.\n"
+ "- https://example.com/images/unused.png - raw parser image URL."
+ )
+ )
+ ops = _keep_all()
+ ops["Files & Context"] = {
+ "op": "UPDATE",
+ "content": "- openviking/session/session.py - WM merge logic.",
+ }
+
+ merged = Session._merge_wm_sections(old_wm, ops)
+
+ assert "openviking/session/session.py" in merged
+ assert "unused.png" in merged