Skip to content

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

fix(openclaw): support turn retention and consistent pending tokens (#4972)

Zayn Jarvise757dd374927
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 6128587fa..290612a9a 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -227,6 +227,14 @@ After that, the plugin checks `pending_tokens`. Once it reaches `commitTokenThre
Memory extraction on this automatic path is commit-dependent. Short but important facts can stay only in the live session until a threshold commit, `/compact`, or an explicit store happens.
+Auto-commit keeps the most recent 10 messages by default (`commitKeepRecentCount`). This count-based window can start mid-turn. With a server that supports turn-aware retention, set `"commitRetentionMode": "turn_budget"` in the plugin config to opt in:
+
+- `commitKeepRecentCount` is ignored. The server defaults apply: up to 3 recent user turns, a 12,000-token retention budget, and at least the final assistant/tool step.
+- For an oversized newest turn, the server retains its user question and recent steps and checkpoints the archived prefix. The mandatory tail can exceed the retention budget.
+- `pending_tokens` counts only messages that will leave the live window, not a user question shared with the archive.
+
+Manual commit and `/compact` still archive everything. Leave the option unset (or use `"message_count"`) to preserve existing behavior.
+
### Explicit long-term memory writes
When the user explicitly asks the agent to remember, save, or store an important long-term fact, preference, project, or decision, prefer `memory_store` over waiting for normal auto-capture. `memory_store` writes the text to an OpenViking session and calls `commit(wait=true)`, so it is the reliable integration-side path for facts that should be available as long-term memory as soon as possible.
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 6d72cc258..3c3a42a9b 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -244,6 +244,14 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来
这条自动路径是 best-effort,并且依赖 commit。短但重要的事实可能会先停留在 live session 里,直到阈值 commit、`/compact` 或显式存储发生后,才进入长期记忆抽取流程。
+自动 commit 默认保留最近 10 条消息(`commitKeepRecentCount`),这个按条数切分的窗口可能从一轮对话中间开始。如果服务端支持按轮保留,可在插件配置中设置 `"commitRetentionMode": "turn_budget"` 来启用:
+
+- 忽略 `commitKeepRecentCount`,采用服务端默认值:最多保留最近 3 轮用户对话、12,000 Token 保留预算,以及至少最后一个 assistant/tool 步骤。
+- 最新一轮过长时,服务端保留用户问题与最近步骤,将更早的步骤归档并生成检查点;必须保留的尾部可能超过保留预算。
+- `pending_tokens` 只计算将离开活跃窗口的消息,不重复计入归档与活跃窗口共有的用户问题。
+
+手动 commit 和 `/compact` 仍然全部归档。不设置该选项(或使用 `"message_count"`)即可保持原有行为。
+
### 显式长期记忆写入
当用户明确要求 Agent “记住”“保存”“存一下”某个重要长期事实、偏好、项目或决定时,应优先使用 `memory_store`,而不是等待普通 auto-capture 自然触发。`memory_store` 会把文本写入 OpenViking session 并调用 `commit(wait=true)`,因此是集成侧让重要事实尽快进入长期记忆的可靠路径。
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 829851f61..ebd8f7d66 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -848,6 +848,8 @@ export class OpenVikingClient {
keepRecentCount?: number;
/** Start empty context in the same session after archiving. */
resetContext?: boolean;
+ /** Opt in to the server's turn-aware defaults instead of message-count retention. */
+ retentionMode?: "turn_budget";
agentId?: string;
},
): Promise<CommitSessionResult> {
@@ -862,11 +864,14 @@ export class OpenVikingClient {
sessionId,
wait: options?.wait ?? false,
keepRecentCount,
+ retentionMode: options?.retentionMode,
},
options?.agentId,
);
const body: Record<string, unknown> = {};
- if (keepRecentCount > 0) {
+ if (options?.retentionMode === "turn_budget") {
+ body.retention_mode = "turn_budget";
+ } else if (keepRecentCount > 0) {
body.keep_recent_count = keepRecentCount;
}
if (options?.resetContext) {
diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.ts
index 7279cc696..b732c5dde 100644
--- a/examples/openclaw-plugin/commands/setup.ts
+++ b/examples/openclaw-plugin/commands/setup.ts
@@ -82,6 +82,7 @@ const CONFIG_KEYS_TO_PRESERVE = [
"recallPreferAbstract",
"recallTokenBudget",
"commitTokenThresholdRatio",
+ "commitRetentionMode",
"commitKeepRecentCount",
"bypassSessionPatterns",
"emitStandardDiagnostics",
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index fca6a9f68..dc9cc4469 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -68,11 +68,13 @@ export type MemoryOpenVikingConfig = {
* compatibility). Set to 0 to commit every turn.
*/
commitTokenThresholdRatio?: number;
+ /** Auto-commit retention: legacy message count (default) or the server's turn-budget policy. */
+ commitRetentionMode?: "message_count" | "turn_budget";
/**
* 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.
+ * server as `keep_recent_count`. Default 10. Ignored in turn_budget mode.
+ * The compact path ignores this value and always passes 0.
*/
commitKeepRecentCount?: number;
bypassSessionPatterns?: string[];
@@ -538,6 +540,7 @@ export const memoryOpenVikingConfigSchema = {
"recallTokenBudget",
"commitTokenThreshold",
"commitTokenThresholdRatio",
+ "commitRetentionMode",
"commitKeepRecentCount",
"bypassSessionPatterns",
"ingestReplyAssist",
@@ -588,6 +591,14 @@ export const memoryOpenVikingConfigSchema = {
? (cfg.apiKey as string | OpenVikingSecretRef)
: getEnv("OPENVIKING_API_KEY") || undefined;
const captureMode = cfg.captureMode;
+ const commitRetentionMode = cfg.commitRetentionMode;
+ if (
+ commitRetentionMode !== undefined &&
+ commitRetentionMode !== "message_count" &&
+ commitRetentionMode !== "turn_budget"
+ ) {
+ throw new Error('openviking commitRetentionMode must be "message_count" or "turn_budget"');
+ }
if (
typeof captureMode !== "undefined" &&
captureMode !== "semantic" &&
@@ -666,6 +677,7 @@ export const memoryOpenVikingConfigSchema = {
0,
Math.min(1, toNumber(cfg.commitTokenThresholdRatio, DEFAULT_COMMIT_TOKEN_THRESHOLD_RATIO)),
),
+ commitRetentionMode: commitRetentionMode ?? "message_count",
commitKeepRecentCount: Math.max(
0,
Math.min(
@@ -916,13 +928,18 @@ export const memoryOpenVikingConfigSchema = {
advanced: true,
help: "Auto-commit triggers once estimated pending tokens reach this fraction (0-1) of the model context window (e.g. 0.5 = 50%). Set to 0 to commit every turn.",
},
+ commitRetentionMode: {
+ label: "Commit Retention Mode",
+ advanced: true,
+ help: "Auto-commit only: message_count (default) keeps recent messages; turn_budget uses the server's turn-aware defaults. Manual commit and compact still archive everything.",
+ },
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.",
+ "Forwarded as keep_recent_count to the server in message_count mode; ignored in turn_budget mode. Compact path always uses 0.",
},
emitStandardDiagnostics: {
label: "Standard diagnostics (diag JSON lines)",
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index 1cf9e3c2a..65358fa1e 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -204,11 +204,16 @@
"advanced": true,
"help": "Auto-commit triggers once estimated pending tokens reach this fraction (0-1) of the model context window (e.g. 0.5 = 50%). Set to 0 to commit every turn."
},
+ "commitRetentionMode": {
+ "label": "Commit Retention Mode",
+ "advanced": true,
+ "help": "Auto-commit only: message_count (default) keeps recent messages; turn_budget uses the server's turn-aware defaults. Manual commit and compact still archive everything."
+ },
"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."
+ "help": "Number of most-recent messages kept live after an afterTurn commit in message_count mode; ignored in turn_budget mode. Compact path always uses 0."
},
"emitStandardDiagnostics": {
"label": "Standard diagnostics (diag JSON lines)",
@@ -405,6 +410,10 @@
"minimum": 0,
"maximum": 1
},
+ "commitRetentionMode": {
+ "type": "string",
+ "enum": ["message_count", "turn_budget"]
+ },
"commitKeepRecentCount": {
"type": "number",
"minimum": 0,
diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.ts
index 20c551c66..0519e586a 100644
--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts
+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts
@@ -140,6 +140,7 @@ export type AfterTurnOpenVikingSessionParams = {
autoCapture: boolean;
commitTokenThresholdRatio: number;
commitKeepRecentCount: number;
+ commitRetentionMode?: "message_count" | "turn_budget";
logFindRequests: boolean;
peer_role?: OpenVikingPeerRole;
};
@@ -987,7 +988,9 @@ export async function afterTurnOpenVikingSession({
const commitResult = await client.commitSession(ovSessionId, {
wait: false,
- keepRecentCount: cfg.commitKeepRecentCount,
+ ...(cfg.commitRetentionMode === "turn_budget"
+ ? { retentionMode: "turn_budget" as const }
+ : { keepRecentCount: cfg.commitKeepRecentCount }),
});
logger.info(
`openviking: committed session=${ovSessionId}, ` +
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index 70ef9f927..a04bf0cd9 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -20,6 +20,8 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.recallMaxInjectedChars).toBe(4000);
expect(cfg.recallTokenBudget).toBe(4000);
expect(cfg.commitTokenThresholdRatio).toBe(0.5);
+ expect(cfg.commitRetentionMode).toBe("message_count");
+ expect(cfg.commitKeepRecentCount).toBe(10);
expect(cfg.captureMode).toBe("semantic");
expect(cfg.captureMaxLength).toBe(24000);
expect(cfg.autoRecallTimeoutMs).toBe(15000);
@@ -253,6 +255,11 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.recallScoreThreshold).toBe(1);
});
+ it.each(["unknown", "", null, 0, false])("rejects invalid commitRetentionMode %j", (value) => {
+ expect(() => memoryOpenVikingConfigSchema.parse({ commitRetentionMode: value }))
+ .toThrow('commitRetentionMode must be "message_count" or "turn_budget"');
+ });
+
it("throws on invalid captureMode", () => {
expect(() =>
memoryOpenVikingConfigSchema.parse({ captureMode: "fast" }),
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
index 4b2676565..62f4d09f4 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
-import type { OpenVikingClient } from "../../client.js";
+import { OpenVikingClient } from "../../client.js";
import { memoryOpenVikingConfigSchema } from "../../config.js";
import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
@@ -283,11 +283,25 @@ describe("context-engine afterTurn()", () => {
expect(client.commitSession).not.toHaveBeenCalled();
});
- it("commits when pendingTokens >= threshold", async () => {
+ it.each([
+ { cfgOverrides: {}, expectedBody: { keep_recent_count: 10 } },
+ { cfgOverrides: { commitRetentionMode: "message_count", commitKeepRecentCount: 7 }, expectedBody: { keep_recent_count: 7 } },
+ { cfgOverrides: { commitKeepRecentCount: 0 }, expectedBody: {} },
+ { cfgOverrides: { commitRetentionMode: "turn_budget" }, expectedBody: { retention_mode: "turn_budget" } },
+ ])("commits with $expectedBody when pendingTokens >= threshold", async ({ cfgOverrides, expectedBody }) => {
const { engine, client } = makeEngine({
commitTokenThresholdRatio: 0.1,
getSession: { pending_tokens: 25000 },
- });
+ cfgOverrides,
+ });
+ const transport = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ status: "ok", result: { status: "completed", archived: true },
+ })));
+ const commitClient = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "test-agent", 5000,
+ "", "", undefined, false, true, { transport },
+ );
+ client.commitSession.mockImplementation(commitClient.commitSession.bind(commitClient));
const messages = [
{ role: "user", content: "some meaningful content here for testing" },
@@ -304,6 +318,11 @@ describe("context-engine afterTurn()", () => {
expect(client.commitSession).toHaveBeenCalledTimes(1);
const commitCall = client.commitSession.mock.calls[0];
expect(commitCall[1]).toMatchObject({ wait: false });
+ expect(transport).toHaveBeenCalledTimes(1);
+ const [url, init] = transport.mock.calls[0] as [string, RequestInit];
+ expect(url).toMatch(/\/sessions\/s1\/commit$/);
+ expect(init.method).toBe("POST");
+ expect(JSON.parse(init.body as string)).toEqual(expectedBody);
});
it("keeps afterTurn write and commit enabled when recall target types default to resources only", async () => {
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
index 1a820d9ff..310d35463 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -22,12 +22,13 @@ function makeLogger() {
};
}
-function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {
+function makeEngine(commitResult: unknown, opts?: { throwError?: Error; commitRetentionMode?: string }) {
const cfg = memoryOpenVikingConfigSchema.parse({
mode: "remote",
baseUrl: "http://127.0.0.1:1933",
autoCapture: false,
autoRecall: false,
+ commitRetentionMode: opts?.commitRetentionMode,
});
const logger = makeLogger();
@@ -71,15 +72,20 @@ function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {
}
describe("context-engine commitOVSession()", () => {
- it("returns true on successful commit", async () => {
- const { engine } = makeEngine({
+ it.each(["message_count", "turn_budget"])("manual commit archives everything in %s mode", async (commitRetentionMode) => {
+ const { engine, client } = makeEngine({
status: "completed",
archived: false,
memories_extracted: { core: 1 },
- });
+ }, { commitRetentionMode });
const ok = await engine.commitOVSession({ sessionId: "test-session" });
expect(ok).toBe(true);
+ expect(client.commitSession.mock.calls[0][1]).toEqual({
+ wait: true,
+ keepRecentCount: 0,
+ resetContext: true,
+ });
});
it("returns false on failed commit", async () => {
@@ -245,13 +251,13 @@ describe("context-engine compact()", () => {
expect(getClient).not.toHaveBeenCalled();
});
- it("returns compacted=true when commit succeeds with archived=true", async () => {
- const { engine } = makeEngine({
+ it.each(["message_count", "turn_budget"])("compact archives everything in %s mode", async (commitRetentionMode) => {
+ const { engine, client } = makeEngine({
status: "completed",
archived: true,
task_id: "task-1",
memories_extracted: { core: 3, preferences: 1 },
- });
+ }, { commitRetentionMode });
const result = await engine.compact({
sessionId: "s1",
@@ -261,6 +267,7 @@ describe("context-engine compact()", () => {
expect(result.ok).toBe(true);
expect(result.compacted).toBe(true);
expect(result.reason).toBe("commit_completed");
+ expect(client.commitSession.mock.calls[0][1]).toEqual({ wait: true, keepRecentCount: 0 });
});
it("returns compacted=false when commit succeeds with archived=false", async () => {
diff --git a/examples/openclaw-plugin/tests/ut/setup-command.test.ts b/examples/openclaw-plugin/tests/ut/setup-command.test.ts
index 072ad8c30..02dd80a08 100644
--- a/examples/openclaw-plugin/tests/ut/setup-command.test.ts
+++ b/examples/openclaw-plugin/tests/ut/setup-command.test.ts
@@ -1,17 +1,21 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
+import * as readline from "node:readline";
import { afterEach, describe, expect, it, vi } from "vitest";
import { __test__ as setupCommandTest } from "../../commands/setup.js";
import { defaultSetupIO } from "../../services/setup/config-writer.js";
import { createOpenVikingSetupService } from "../../services/setup/setup-flow.js";
+vi.mock("node:readline", () => ({ createInterface: vi.fn() }));
+
describe("openviking setup agent prefix validation", () => {
const tempDirs: string[] = [];
afterEach(() => {
vi.restoreAllMocks();
+ vi.unstubAllEnvs();
for (const dir of tempDirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
}
@@ -37,6 +41,40 @@ describe("openviking setup agent prefix validation", () => {
expect(setupCommandTest.resolveSetupPeerRole("person")).toBe("sender");
});
+ it("interactive reconfiguration preserves the selected retention policy", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openviking-setup-"));
+ tempDirs.push(dir);
+ const configPath = path.join(dir, "openclaw.json");
+ fs.writeFileSync(configPath, JSON.stringify({ plugins: { entries: { openviking: { config: {
+ mode: "remote", baseUrl: "http://127.0.0.1:1",
+ commitRetentionMode: "turn_budget", commitKeepRecentCount: 7,
+ } } } } }));
+ vi.stubEnv("OPENCLAW_STATE_DIR", dir);
+ vi.resetModules();
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.mocked(readline.createInterface).mockReturnValue({
+ question: (_prompt: string, reply: (answer: string) => void) => reply(""),
+ close: vi.fn(),
+ } as unknown as readline.Interface);
+ const actions = new Map<string, (options: unknown) => Promise<void>>();
+ let command = "";
+ const program = {
+ command(name: string) { command = name; return this; },
+ description() { return this; },
+ option() { return this; },
+ action(handler: (options: unknown) => Promise<void>) { actions.set(command, handler); return this; },
+ };
+ const { registerSetupCli } = await import("../../commands/setup.js");
+ registerSetupCli({ registerCli: (register: (args: unknown) => void) => register({ program }) });
+
+ await actions.get("setup")!({ reconfigure: true });
+
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
+ expect(config.plugins.entries.openviking.config).toMatchObject({
+ commitRetentionMode: "turn_budget", commitKeepRecentCount: 7,
+ });
+ });
+
it("non-interactive setup can persist resource-only recallTargetTypes for post-install opt-in", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openviking-setup-"));
tempDirs.push(dir);
diff --git a/openviking/session/session.py b/openviking/session/session.py
index cf39a0e98..425f4caa7 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -792,7 +792,6 @@ class Session:
"""Calculate pending tokens without mutating session state."""
if (
self._meta.retention_mode == RETENTION_MODE_TURN_BUDGET
- and self._meta.keep_recent_turn_count > 0
and self._meta.retained_message_token_budget > 0
):
plan = plan_retention(
diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.py
index 0aa929072..b0fc7e0b5 100644
--- a/tests/unit/session/test_session_commit_resume.py
+++ b/tests/unit/session/test_session_commit_resume.py
@@ -4,11 +4,12 @@
import inspect
import json
from dataclasses import fields
+from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
-from openviking.message import Message, TextPart
+from openviking.message import Message, TextPart, ToolPart
from openviking.service.task_tracker import TaskStatus, TaskTracker, set_task_tracker
from openviking.session.session import Session
from openviking.storage.queuefs.session_commit_msg import SessionCommitMsg
@@ -50,6 +51,84 @@ class _MemoryVikingFS:
async def write_file(self, uri, content, ctx=None, lease_ref=None):
self.files[uri] = content
+ async def append_file(self, uri, content, ctx=None):
+ self.files[uri] += content
+
+ async def exists(self, uri, ctx=None):
+ return uri in self.files or any(path.startswith(f"{uri}/") for path in self.files)
+
+ async def ls(self, uri, ctx=None):
+ prefix = f"{uri}/"
+ names = {
+ path[len(prefix) :].split("/")[0] for path in self.files if path.startswith(prefix)
+ }
+ return [{"name": name} for name in sorted(names)]
+
+
+ "keep_count, keep_turns, archive_count",
+ [(10, None, 5), (10, 1, 2), (10, 0, 15), (0, None, 15)],
+)
+async def test_commit_retention_boundary_and_pending_tokens_after_reload(
+ monkeypatch, keep_count, keep_turns, archive_count
+):
+ session_uri = "viking://user/default/sessions/session-1"
+ messages = [
+ Message(id="old-user", role="user", parts=[TextPart("old question")]),
+ Message(id="old-assistant", role="assistant", parts=[TextPart("old answer")]),
+ Message(id="latest-user", role="user", parts=[TextPart("latest question")]),
+ *[
+ Message(
+ id=f"step-{i}",
+ role="assistant",
+ parts=[
+ ToolPart(tool_id=f"tool-{i}", tool_name="read", tool_output=f"result {i}"),
+ ],
+ )
+ for i in range(12)
+ ],
+ ]
+ storage = _MemoryVikingFS(
+ {
+ f"{session_uri}/messages.jsonl": "\n".join(message.to_jsonl() for message in messages),
+ }
+ )
+ tracker = TaskTracker(_TaskStore())
+ monkeypatch.setattr("openviking.session.session._enabled_memory_types", lambda: set())
+ monkeypatch.setattr("openviking.service.task_tracker.get_task_tracker", lambda: tracker)
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.get_queue_manager",
+ lambda: SimpleNamespace(enqueue=AsyncMock()),
+ )
+ session = Session(viking_fs=storage, session_id="session-1", session_uri=session_uri)
+ turn_options = (
+ {"retention_mode": "turn_budget", "keep_recent_turn_count": keep_turns}
+ if keep_turns is not None
+ else {}
+ )
+ result = await session.commit_async(keep_recent_count=keep_count, **turn_options)
+ archived = await session._read_archive_messages(result["archive_uri"])
+ retained = messages[archive_count:]
+ assert [message.id for message in archived] == [m.id for m in messages[:archive_count]]
+ assert [message.id for message in session.messages] == [m.id for m in retained]
+ assert session.meta.pending_tokens == 0
+
+ reloaded = Session(viking_fs=storage, session_id="session-1", session_uri=session_uri)
+ await reloaded.load()
+ assert reloaded.meta.pending_tokens == 0
+ appended = await reloaded.add_message_async("user", [TextPart("next question")])
+ if keep_turns == 0 or keep_count == 0:
+ expected = appended.estimated_tokens
+ elif keep_turns == 1:
+ expected = sum(message.estimated_tokens for message in retained)
+ else:
+ expected = retained[0].estimated_tokens
+ assert reloaded.meta.pending_tokens == expected
+ fresh = Session(viking_fs=storage, session_id="session-1", session_uri=session_uri)
+ await fresh.load()
+ assert fresh.meta.pending_tokens == expected
+
def test_phase2_auto_commit_policy_parameters_are_appended():
signature = inspect.signature(Session._run_memory_extraction)
@@ -97,9 +176,9 @@ async def test_resume_queued_commit_continues_phase2(monkeypatch):
assert session._run_memory_extraction.await_args.kwargs["auto_commit_policy"] == {
"pending_token_threshold": 8000
}
- assert [
- item.id for item in session._run_memory_extraction.await_args.kwargs["messages"]
- ] == ["archived"]
+ assert [item.id for item in session._run_memory_extraction.await_args.kwargs["messages"]] == [
+ "archived"
+ ]
@pytest.mark.asyncio
@@ -150,9 +229,7 @@ async def test_session_context_skips_pending_archive_with_missing_messages(monke
session,
"_list_archive_refs",
AsyncMock(
- return_value=[
- {"archive_id": "archive_001", "archive_uri": archive_uri, "index": 1}
- ]
+ return_value=[{"archive_id": "archive_001", "archive_uri": archive_uri, "index": 1}]
),
)
diff --git a/tests/unit/session/test_wm_v2_guards.py b/tests/unit/session/test_wm_v2_guards.py
index 5fb1a782d..e55fb8b7a 100644
--- a/tests/unit/session/test_wm_v2_guards.py
+++ b/tests/unit/session/test_wm_v2_guards.py
@@ -7,11 +7,14 @@ These tests target pure/static methods on Session and related helpers,
so they don't need a running OpenViking server.
"""
+import json
+from unittest.mock import AsyncMock
+
import pytest
from openviking.message.message import Message
from openviking.message.part import ContextPart, TextPart, ToolPart
-from openviking.session.session import WM_SEVEN_SECTIONS, Session
+from openviking.session.session import WM_SEVEN_SECTIONS, Session, SessionMeta
# -----------------------------------------------------------------------
# Helpers
@@ -415,7 +418,7 @@ class TestWmRecoverOpsFromRaw:
class TestRebuildPendingTokens:
- """Test the _rebuild_pending_tokens math using _calc_pending_tokens helper."""
+ """Cover legacy count math and the real turn-budget append/load lifecycle."""
def test_no_keep_sums_all(self):
assert _calc_pending_tokens([100, 200, 300], keep_recent_count=0) == 600
@@ -435,6 +438,42 @@ class TestRebuildPendingTokens:
def test_keep_equals_total(self):
assert _calc_pending_tokens([100, 200], keep_recent_count=2) == 0
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "keep_turns, budget, expected", [(0, 1000, 600), (1, 1000, 0), (1, 400, 200)]
+ )
+ async def test_turn_budget_pending_tokens_survive_append_and_reload(
+ self, keep_turns, budget, expected
+ ):
+ session = Session(viking_fs=None)
+ session._meta = SessionMeta(
+ retention_mode="turn_budget",
+ keep_recent_count=10,
+ keep_recent_turn_count=keep_turns,
+ retained_message_token_budget=budget,
+ )
+ for role, text in [
+ ("user", "u" * 400),
+ ("assistant", "a" * 800),
+ ("assistant", "b" * 1200),
+ ]:
+ await session.add_message_async(role, [TextPart(text)])
+ # A partial turn duplicates its user anchor into the archive, but it is
+ # still live and must not be counted as pending a second time.
+ assert session._meta.pending_tokens == expected
+
+ # Loading must rebuild the counter from durable messages, not trust a
+ # stale persisted value or fall back to the legacy keep_recent_count.
+ session._meta.pending_tokens = 9999
+ storage = AsyncMock()
+ storage.read_file.side_effect = [
+ "\n".join(message.to_jsonl() for message in session.messages),
+ json.dumps(session._meta.to_dict()),
+ ]
+ reloaded = Session(viking_fs=storage)
+ await reloaded.load()
+ assert reloaded._meta.pending_tokens == expected
+
# =======================================================================
# _is_wm_v2 detection (tests the condition in _generate_archive_summary_async)