Skip to content

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

feat(reset-context): on session commit clear, reset context without changing session identity (#4937)

Zayn Jarvisb1c0bef43a42
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index 4ccd60b2e..411309579 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -1421,6 +1421,10 @@ Commit a session. Message archiving (Phase 1) completes immediately. Summary gen
|-----------|------|----------|---------|-------------|
| session_id | str | Yes | - | Session ID to commit |
| keep_recent_count | int | No | 0 | Number of recent live messages to retain (kept live, not archived) after commit. `0` (default) archives all messages. |
+| reset_context | bool | No | false | HTTP API: archive all live messages, then append a boundary archive containing only a `.done` marker with `context_reset`. Keeps the session ID and raw history, clears injected context and stops future summaries from inheriting pre-reset overviews. Requires `keep_recent_count=0` and no `retention_mode`. |
+
+`reset_context` is used by the OpenClaw plugin reset hook and `Session.commit_async()`. It also creates a boundary when there are no live messages, unless the newest archive is already a reset boundary. Memory extraction for older archives can finish independently; long-term memories are preserved. SDK/CLI convenience options are not added in this change.
+
The effective policy is resolved in this order: Session `.meta.json`, latest
`settings/user_config.json`, then the kernel default. The fully resolved policy
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index 8c7acfd11..8071461a4 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -1392,6 +1392,10 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \
|------|------|------|--------|------|
| session_id | str | 是 | - | 要提交的会话 ID |
| keep_recent_count | int | 否 | 0 | 提交后保留为 live 状态的最近消息数 (保持 live, 不归档)。`0` (默认) 归档全部消息。 |
+| reset_context | bool | 否 | false | HTTP API:归档全部 live messages 后追加只含 `.done`(带 `context_reset`)的边界 archive,目录内没有消息文件。保留 session ID 和原始历史,清空注入上下文,并阻止后续摘要继承 reset 前的 overview。要求 `keep_recent_count=0`,且不设置 `retention_mode`。 |
+
+`reset_context` 供 OpenClaw 插件 reset hook 和 `Session.commit_async()` 使用;没有 live messages 时也会创建边界;若最新 archive 已是 reset 边界则不重复创建。旧 archive 的记忆提取可以继续完成,长期记忆保留。本次未增加 SDK/CLI 的专用参数。
+
有效策略按 Session `.meta.json`、最新 `settings/user_config.json`、内核默认值的
顺序解析。Phase 2 开始前会将完整有效策略固化到异步任务。
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 1637f8eff..829851f61 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -80,6 +80,7 @@ export type CommitSessionResult = {
task_id?: string;
archive_uri?: string;
archived?: boolean;
+ reset_context?: boolean;
/** Present when wait=true and extraction completed. Keyed by category. */
memories_extracted?: Record<string, number>;
error?: string;
@@ -845,6 +846,8 @@ export class OpenVikingClient {
* preserves the pre-v2 "archive everything" behavior.
*/
keepRecentCount?: number;
+ /** Start empty context in the same session after archiving. */
+ resetContext?: boolean;
agentId?: string;
},
): Promise<CommitSessionResult> {
@@ -866,6 +869,9 @@ export class OpenVikingClient {
if (keepRecentCount > 0) {
body.keep_recent_count = keepRecentCount;
}
+ if (options?.resetContext) {
+ body.reset_context = true;
+ }
const result = await this.request<CommitSessionResult>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
{ method: "POST", body: JSON.stringify(body) },
@@ -873,6 +879,10 @@ export class OpenVikingClient {
options?.agentId,
);
+ if (options?.resetContext && result.reset_context !== true) {
+ throw new Error("OpenViking server did not confirm reset_context; upgrade the server with the plugin.");
+ }
+
if (!options?.wait || !result.task_id) {
return result;
}
diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.ts
index 543807395..20c551c66 100644
--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts
+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts
@@ -370,6 +370,7 @@ export async function commitOpenVikingSession({
const commitResult = await client.commitSession(ovId, {
wait: true,
keepRecentCount: 0,
+ resetContext: true,
});
const memCount = totalExtractedMemories(commitResult.memories_extracted);
if (commitResult.status === "failed") {
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 01fa7ab07..7065155d9 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -805,3 +805,24 @@ describe("OpenVikingClient canonical namespace policy", () => {
expect(body).not.toHaveProperty("role_id");
});
});
+
+
+describe("OpenVikingClient session reset", () => {
+ it("requests an empty archive boundary on the same session", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({
+ session_id: "same-session", status: "skipped", reset_context: true,
+ }));
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });
+ await client.commitSession("same-session", { keepRecentCount: 0, resetContext: true });
+ const [url, init] = transport.mock.calls[0] as [string, RequestInit];
+ expect(url).toContain("/sessions/same-session/commit");
+ expect(JSON.parse(String(init.body))).toEqual({ reset_context: true });
+ });
+});
+
+
+it("does not report reset success when an older server ignores reset_context", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({ session_id: "s", status: "skipped" }));
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });
+ await expect(client.commitSession("s", { resetContext: true })).rejects.toThrow("did not confirm reset_context");
+});
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 8ac40bc20..1a820d9ff 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -120,7 +120,7 @@ describe("context-engine commitOVSession()", () => {
await engine.commitOVSession({ sessionId: "s1" });
- expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });
+ expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true, keepRecentCount: 0, resetContext: true });
});
it("uses sessionKey-derived OV session ID for commitOVSession", async () => {
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
index 5c2667c1b..e4ac350de 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
@@ -222,6 +222,7 @@ describe("context-engine lifecycle service seam", () => {
expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {
wait: true,
keepRecentCount: 0,
+ resetContext: true,
});
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("memories=5"));
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("trace_id=trace-1"));
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index ef6d5748c..f4544c46e 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -598,6 +598,11 @@ class CommitRequest(BaseModel):
behavior.
"""
+ reset_context: bool = Field(
+ default=False,
+ strict=True,
+ description="Append an empty archive boundary after archiving all messages; keep session ID.",
+ )
keep_recent_count: int = Field(
default=0,
ge=0,
@@ -643,6 +648,8 @@ class CommitRequest(BaseModel):
@model_validator(mode="after")
def validate_turn_retention_opt_in(self) -> "CommitRequest":
+ if self.reset_context and (self.keep_recent_count != 0 or self.retention_mode is not None):
+ raise ValueError("reset_context requires keep_recent_count=0 and no retention_mode")
if self.retention_mode is None and any(
value is not None
for value in (
@@ -680,6 +687,8 @@ async def commit_session(
commit_kwargs.update(
{key: value for key, value in optional_retention.items() if value is not None}
)
+ if body.reset_context:
+ commit_kwargs["reset_context"] = True
event_tags = _commit_event_tags(body.extraction_metadata)
if event_tags is not None:
commit_kwargs["event_tags"] = event_tags
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 63d8cf7ec..b268a4cea 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -373,6 +373,7 @@ class SessionService:
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
event_tags: Optional[List[str]] = None,
+ reset_context: bool = False,
) -> Dict[str, Any]:
"""Commit a session (archive messages and extract memories).
@@ -394,6 +395,7 @@ class SessionService:
retained_message_token_budget=retained_message_token_budget,
min_raw_tail_steps=min_raw_tail_steps,
event_tags=event_tags,
+ reset_context=reset_context,
)
async def commit_async(
@@ -407,6 +409,7 @@ class SessionService:
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
event_tags: Optional[List[str]] = None,
+ reset_context: bool = False,
) -> Dict[str, Any]:
"""Async commit a session.
@@ -436,6 +439,8 @@ class SessionService:
)
if event_tags is not None:
commit_kwargs["event_tags"] = event_tags
+ if reset_context:
+ commit_kwargs["reset_context"] = True
result = await session.commit_async(**commit_kwargs)
self._record_lifecycle_metric("commit", "ok" if result.get("status") else "error")
self._record_archive_metric("ok" if result.get("archived") else "skip")
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 8776cdaaa..cf39a0e98 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -1860,6 +1860,7 @@ class Session:
persist_keep_recent_count: bool = True,
record_auto_commit_success: bool = False,
event_tags: Optional[List[str]] = None,
+ reset_context: bool = False,
) -> Dict[str, Any]:
"""Archive immediately and enqueue restart-safe Phase 2 processing.
@@ -1876,6 +1877,8 @@ class Session:
behavior of archiving everything. The plugin's afterTurn path
typically passes its configured value (default 10); the compact
path passes ``0``.
+ reset_context: Archive all live messages, then append an empty completed
+ archive to stop context and future summaries at this boundary.
persist_keep_recent_count: When ``True`` (default), ``keep_recent_count``
is remembered in meta for subsequent add_message() accounting.
The idle full-commit path passes ``False`` with
@@ -1895,6 +1898,8 @@ class Session:
from openviking.storage.queuefs import QueueManager, get_queue_manager
from openviking.storage.queuefs.session_commit_msg import SessionCommitMsg
+ if reset_context and (keep_recent_count != 0 or retention_mode is not None):
+ raise ValueError("reset_context requires keep_recent_count=0 and no retention_mode")
trace_id = tracer.get_trace_id()
keep_recent_count = max(0, int(keep_recent_count or 0))
if retention_mode not in (None, RETENTION_MODE_TURN_BUDGET):
@@ -2035,6 +2040,8 @@ class Session:
min_raw_tail_steps=effective_min_tail,
)
await self._save_meta()
+ if reset_context:
+ await self._append_context_reset_archive()
get_current_telemetry().set("memory.extracted", 0)
return {
"session_id": self.session_id,
@@ -2044,6 +2051,7 @@ class Session:
"archived": False,
"reason": "no_messages",
"trace_id": trace_id,
+ **({"reset_context": True} if reset_context else {}),
}
total = len(self._messages)
@@ -2224,16 +2232,15 @@ class Session:
self._messages = original_messages
self._compression.compression_index -= 1
raise
+ if reset_context:
+ await self._append_context_reset_archive()
finally:
await self._viking_fs._async_agfs.pathlock_release(lease)
# Lock released; Phase 1 intent, queue item, retained root, metadata and
# ready metadata are all durable.
self._compression.original_count += len(messages_to_archive)
- logger.info(
- f"Archived: {len(messages_to_archive)} messages → "
- f"history/archive_{self._compression.compression_index:03d}/"
- )
+ logger.info(f"Archived: {len(messages_to_archive)} messages → {archive_uri}/")
return {
"session_id": self.session_id,
@@ -2242,12 +2249,49 @@ class Session:
"archive_uri": archive_uri,
"archived": True,
"trace_id": trace_id,
+ **({"reset_context": True} if reset_context else {}),
"estimated_active_tokens": (
retention_plan.estimated_active_tokens if retention_plan else 0
),
"budget_exceeded": retention_plan.budget_exceeded if retention_plan else False,
}
+ async def _is_context_reset_archive(self, archive_uri: str) -> bool:
+ """Return True when the archive's ``.done`` marks a context reset boundary."""
+ try:
+ done = json.loads(await self._viking_fs.read_file(f"{archive_uri}/.done", ctx=self.ctx))
+ except Exception:
+ return False
+ return isinstance(done, dict) and done.get("context_reset") is True
+
+ async def _append_context_reset_archive(self) -> None:
+ """Publish a boundary archive while holding the Phase 1 session lock.
+
+ The directory holds only ``.done``: terminal archives never have their
+ ``messages.jsonl`` read, and a missing overview already reads as empty.
+ """
+ # ponytail: reuse archive ordering; no second session identity or context store.
+ newest = f"{self._session_uri}/history/archive_{self._compression.compression_index:03d}"
+ if self._compression.compression_index > 0 and await self._is_context_reset_archive(newest):
+ return # Context is already empty; no second boundary needed.
+ self._compression.compression_index += 1
+ archive_uri = (
+ f"{self._session_uri}/history/archive_{self._compression.compression_index:03d}"
+ )
+ try:
+ await self._viking_fs.write_file(
+ f"{archive_uri}/.done",
+ json.dumps({"context_reset": True, "working_memory_enabled": False}),
+ ctx=self.ctx,
+ )
+ except Exception as exc:
+ # A directory left without any marker reads as pending and would
+ # block the next Phase 2 forever; no queue owns this archive.
+ await self._write_failed_marker(archive_uri, stage="context_reset", error=str(exc))
+ raise
+ self._meta.commit_count = self._compression.compression_index
+ await self._save_meta()
+
async def finalize_cancelled_commit(self, archive_uri: str) -> None:
"""Make a cancelled queued commit terminal without discarding its raw archive."""
await self._write_failed_marker(
@@ -3251,6 +3295,8 @@ class Session:
terminal["archive_uri"], overview
),
}
+ elif await self._is_context_reset_archive(terminal["archive_uri"]):
+ terminal = None
else:
# A required overview that is missing or unreadable still keeps
# the archive terminal here; the warning is emitted by the full
@@ -3523,6 +3569,7 @@ class Session:
"archive_id": state.archive_id,
"archive_uri": state.archive_uri,
"index": state.index,
+ "context_reset": state.done.get("context_reset") is True,
}
)
@@ -3588,6 +3635,8 @@ class Session:
exclude_archive_uri,
before_archive_index,
):
+ if archive.get("context_reset"):
+ break
overview = await self._read_archive_overview(archive["archive_uri"])
if not overview:
continue
diff --git a/tests/server/test_api_session_reset.py b/tests/server/test_api_session_reset.py
new file mode 100644
index 000000000..be7f19e72
--- /dev/null
+++ b/tests/server/test_api_session_reset.py
@@ -0,0 +1,177 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Reset keeps raw history without reviving context through late or future summaries."""
+
+import json
+
+import pytest
+
+from openviking.server.identity import RequestContext, Role
+from openviking.session.session import Session
+from openviking.storage.queuefs import SessionCommitMsg, get_queue_manager
+from openviking_cli.session.user_id import UserIdentifier
+from openviking_cli.utils.config import OPENVIKING_CONFIG_ENV
+from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton
+
+
[email protected](autouse=True)
+def isolated_config(tmp_path, monkeypatch):
+ config = tmp_path / "ov.conf"
+ config.write_text(
+ json.dumps(
+ {
+ "storage": {
+ "workspace": str(tmp_path / "data"),
+ "agfs": {"backend": "local"},
+ "vectordb": {"backend": "local"},
+ },
+ "embedding": {
+ "dense": {
+ "provider": "openai",
+ "model": "test",
+ "api_key": "test-key",
+ "dimension": 2048,
+ }
+ },
+ }
+ )
+ )
+ monkeypatch.setenv(OPENVIKING_CONFIG_ENV, str(config))
+ OpenVikingConfigSingleton.reset_instance()
+ yield
+ OpenVikingConfigSingleton.reset_instance()
+
+
+async def test_reset_empty_archive_survives_late_summary_and_next_commit(
+ client, service, monkeypatch
+):
+ jobs = []
+ summary_inputs = []
+
+ async def enqueue(queue_name, data):
+ jobs.append(SessionCommitMsg(**data))
+ return data["task_id"]
+
+ async def summarize(self, messages, latest_archive_overview="", **kwargs):
+ summary_inputs.append((messages[0].content, latest_archive_overview))
+ return "# Summary\n" + latest_archive_overview + "\n" + messages[0].content
+
+ monkeypatch.setattr(get_queue_manager(), "enqueue", enqueue)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", summarize)
+ base = "/api/v1/sessions/reset-same-id"
+ created = await client.post(
+ "/api/v1/sessions",
+ json={
+ "session_id": "reset-same-id",
+ "memory_policy": {"memory_types": [], "working_memory": {"enabled": True}},
+ },
+ )
+ assert created.status_code == 200, created.text
+
+ async def add(text):
+ response = await client.post(f"{base}/messages", json={"role": "user", "content": text})
+ assert response.status_code == 200, response.text
+
+ async def commit(**options):
+ response = await client.post(f"{base}/commit", json=options)
+ assert response.status_code == 200, response.text
+ return response.json()["result"]
+
+ async def context():
+ response = await client.get(f"{base}/context")
+ assert response.status_code == 200, response.text
+ return response.json()["result"]
+
+ async def finish(job):
+ ctx = RequestContext(user=UserIdentifier.from_dict(job.user), role=Role.USER)
+ session = service.sessions.session(
+ ctx, session_id=job.session_id, session_uri=job.session_uri
+ )
+ await session.load()
+ assert await session.resume_queued_commit(job)
+ assert await session._archive_terminal_state(job.archive_uri) == "completed"
+ return session
+
+ await add("old task one")
+ await commit() # Leave Phase 2 pending across reset.
+ await add("old task two")
+ reset = await commit(reset_context=True)
+ assert reset["session_id"] == "reset-same-id"
+ assert reset["archive_uri"].endswith("archive_002")
+ empty = await context()
+ assert empty["messages"] == []
+ assert empty["latest_archive_overview"] == ""
+ assert empty["stats"]["failedArchives"] == 0
+ assert reset["reset_context"] is True
+
+ # Complete both old jobs after the boundary: raw history remains, context stays empty.
+ await finish(jobs[0])
+ session = await finish(jobs[1])
+ assert summary_inputs[1][1].endswith("old task one")
+ assert (await context())["latest_archive_overview"] == ""
+ fs = session._viking_fs
+ boundary = f"{session._session_uri}/history/archive_003"
+ assert not await fs.exists(f"{boundary}/.overview.md", ctx=session.ctx)
+ assert not await fs.exists(f"{boundary}/messages.jsonl", ctx=session.ctx)
+ assert json.loads(await fs.read_file(f"{boundary}/.done", ctx=session.ctx))["context_reset"]
+ assert "old task two" in await fs.read_file(
+ f"{jobs[1].archive_uri}/messages.jsonl", ctx=session.ctx
+ )
+
+ # Reset an already-empty session: confirmed, but no second boundary directory.
+ assert (await commit(reset_context=True))["reset_context"] is True
+ assert not await fs.exists(f"{session._session_uri}/history/archive_004", ctx=session.ctx)
+ # Summarize new work without old overview fallback.
+ await add("new task")
+ assert (await context())["messages"][0]["parts"][0]["text"] == "new task"
+ await commit()
+ await finish(jobs[-1])
+ assert summary_inputs[-1] == ("new task", "")
+ final = await context()
+ assert "new task" in final["latest_archive_overview"]
+ assert "old task" not in final["latest_archive_overview"]
+ assert len(jobs) == 3 # Empty reset archives do not enqueue extraction.
+
+
+ "options",
+ [
+ {"reset_context": True, "keep_recent_count": 1},
+ {"reset_context": True, "retention_mode": "turn_budget"},
+ {"reset_context": "true"},
+ ],
+)
+async def test_reset_rejects_retention_and_non_boolean_flag(client, options):
+ response = await client.post("/api/v1/sessions/unused/commit", json=options)
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
+
+
+async def test_reset_write_failure_does_not_block_next_archive(service, monkeypatch):
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)
+ session = service.sessions.session(ctx, session_id="reset-write-failure")
+ await session.ensure_exists()
+ fs = session._viking_fs
+ write = fs.write_file
+ failed = False
+
+ async def fail_once(uri, content, **kwargs):
+ nonlocal failed
+ if uri.endswith("archive_001/.done") and not failed:
+ failed = True
+ raise OSError("transient reset write failure")
+ return await write(uri, content, **kwargs)
+
+ monkeypatch.setattr(fs, "write_file", fail_once)
+ with pytest.raises(OSError, match="transient reset write failure"):
+ await session.commit_async(reset_context=True)
+
+ boundary = f"{session._session_uri}/history/archive_001"
+ assert await session._archive_terminal_state(boundary) == "failed"
+ assert await session._can_run_archive(2)
+ # Retrying reset publishes a new terminal boundary rather than reusing the partial one.
+ assert (await session.commit_async(reset_context=True))["reset_context"] is True
+ context = await session.get_session_context()
+ assert context["messages"] == []
+ assert context["latest_archive_overview"] == ""
+ assert context["stats"]["failedArchives"] == 0