Skip to content

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

fix(openclaw-plugin): unify session and agent-prefix routing across compact, commit, and tools (#1832)

x__dot17cfaac87cbb
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index e8963a0a5..193854b71 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -95,6 +95,7 @@ type ContextEngine = {
}) => Promise<AssembleResult>;
compact: (params: {
sessionId: string;
+ sessionKey?: string;
sessionFile: string;
tokenBudget?: number;
force?: boolean;
@@ -107,7 +108,11 @@ type ContextEngine = {
export type ContextEngineWithCommit = ContextEngine & {
/** Commit (archive + extract) the OV session. Returns true on success. */
- commitOVSession: (sessionId: string, sessionKey?: string) => Promise<boolean>;
+ commitOVSession: (params: {
+ sessionId: string;
+ sessionKey?: string;
+ runtimeContext?: Record<string, unknown>;
+ }) => Promise<boolean>;
};
type Logger = {
@@ -730,7 +735,13 @@ export function createMemoryOpenVikingContextEngine(params: {
const isBypassedSession = (params: { sessionId?: string; sessionKey?: string }): boolean =>
shouldBypassSession(params, bypassSessionPatterns);
- async function doCommitOVSession(sessionId: string, sessionKey?: string): Promise<boolean> {
+ async function doCommitOVSession(params: {
+ sessionId: string;
+ sessionKey?: string;
+ runtimeContext?: Record<string, unknown>;
+ }): Promise<boolean> {
+ const { sessionId } = params;
+ const { sessionKey, ovSessionId: ovId } = resolveSessionIdentity(params);
if (isBypassedSession({ sessionId, sessionKey })) {
logger.warn?.(
`openviking: commit skipped because session is bypassed (sessionId=${sessionId}, sessionKey=${sessionKey ?? "none"})`,
@@ -739,7 +750,6 @@ export function createMemoryOpenVikingContextEngine(params: {
}
try {
const client = await getClient();
- const ovId = openClawSessionToOvStorageId(sessionId, sessionKey);
rememberSessionAgentId?.({
sessionId,
sessionKey,
@@ -774,7 +784,7 @@ export function createMemoryOpenVikingContextEngine(params: {
return typeof key === "string" && key.trim() ? key.trim() : undefined;
}
- function extractAssembleSessionKey(params: {
+ function resolveSessionKey(params: {
sessionKey?: string;
runtimeContext?: Record<string, unknown>;
}): string | undefined {
@@ -785,6 +795,18 @@ export function createMemoryOpenVikingContextEngine(params: {
return extractSessionKey(params.runtimeContext);
}
+ function resolveSessionIdentity(params: {
+ sessionId: string;
+ sessionKey?: string;
+ runtimeContext?: Record<string, unknown>;
+ }): { sessionKey: string | undefined; ovSessionId: string } {
+ const sessionKey = resolveSessionKey(params);
+ return {
+ sessionKey,
+ ovSessionId: openClawSessionToOvStorageId(params.sessionId, sessionKey),
+ };
+ }
+
function extractRuntimeAgentId(
runtimeContext: Record<string, unknown> | undefined,
): string | undefined {
@@ -883,12 +905,11 @@ export function createMemoryOpenVikingContextEngine(params: {
async assemble(assembleParams): Promise<AssembleResult> {
const { messages } = assembleParams;
const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;
- const sessionKey = extractAssembleSessionKey(assembleParams);
+ const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(assembleParams);
const sender = extractRuntimeSenderId(assembleParams.runtimeContext);
const originalTokens = roughEstimate(messages);
- const OVSessionId = openClawSessionToOvStorageId(assembleParams.sessionId, sessionKey);
rememberSessionAgentId?.({
sessionId: assembleParams.sessionId,
sessionKey,
@@ -998,14 +1019,8 @@ export function createMemoryOpenVikingContextEngine(params: {
}
try {
- const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);
- const sessionKey =
- (typeof afterTurnParams.sessionKey === "string" && afterTurnParams.sessionKey.trim()) ||
- extractSessionKey(afterTurnParams.runtimeContext);
- const OVSessionId = openClawSessionToOvStorageId(
- afterTurnParams.sessionId,
- sessionKey,
- );
+ const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);
+ const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(afterTurnParams);
const runtimeAgentId = extractRuntimeAgentId(afterTurnParams.runtimeContext);
if (runtimeAgentId) {
rememberSessionAgentId?.({
@@ -1172,8 +1187,7 @@ export function createMemoryOpenVikingContextEngine(params: {
},
async compact(compactParams): Promise<CompactResult> {
- const OVSessionId = compactParams.sessionId;
- const sessionKey = extractSessionKey(compactParams.runtimeContext);
+ const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(compactParams);
const tokenBudget = validTokenBudget(compactParams.tokenBudget) ?? 128_000;
diag("compact_entry", OVSessionId, {
tokenBudget,
@@ -1198,7 +1212,7 @@ export function createMemoryOpenVikingContextEngine(params: {
}
const client = await getClient();
- const agentId = resolveAgentId(OVSessionId);
+ const agentId = resolveAgentId(compactParams.sessionId, sessionKey, OVSessionId);
const tokensBeforeOriginal = validTokenBudget(compactParams.currentTokenCount);
let preCommitEstimatedTokens: number | undefined;
if (typeof tokensBeforeOriginal !== "number") {
@@ -1418,9 +1432,27 @@ export function createMemoryOpenVikingContextEngine(params: {
},
};
} catch (err) {
- logger.warn?.(`openviking: compact commit failed for session=${OVSessionId}: ${String(err)}`);
+ const errorMessage = String(err);
+ if (errorMessage.includes("[NOT_FOUND]") && errorMessage.includes("Session not found")) {
+ logger.info(
+ `openviking: compact skipped because OV session does not exist ` +
+ `(session=${OVSessionId}, agentId=${agentId})`,
+ );
+ diag("compact_result", OVSessionId, {
+ ok: true,
+ compacted: false,
+ reason: "session_not_found",
+ error: errorMessage,
+ });
+ return {
+ ok: true,
+ compacted: false,
+ reason: "session_not_found",
+ };
+ }
+ logger.warn?.(`openviking: compact commit failed for session=${OVSessionId}: ${errorMessage}`);
diag("compact_error", OVSessionId, {
- error: String(err),
+ error: errorMessage,
});
return {
ok: false,
@@ -1432,7 +1464,7 @@ export function createMemoryOpenVikingContextEngine(params: {
tokensBefore: tokensBefore,
tokensAfter: undefined,
details: {
- error: String(err),
+ error: errorMessage,
},
},
};
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index f56f7aedf..2e51c34d1 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -33,6 +33,7 @@ import { quickRecallPrecheck, withTimeout } from "./process-manager.js";
import {
createMemoryOpenVikingContextEngine,
openClawSessionToOvStorageId,
+ openClawSessionRefToOvStorageId,
} from "./context-engine.js";
import type { ContextEngineWithCommit } from "./context-engine.js";
@@ -56,6 +57,13 @@ type SessionAgentLookup = {
ovSessionId?: string;
};
+type PluginSessionRouting = {
+ sessionId?: string;
+ sessionKey?: string;
+ ovSessionId?: string;
+ agentId: string;
+};
+
type SessionAgentResolveBranch =
| "session_resolved"
| "config_only_fallback"
@@ -605,6 +613,34 @@ const contextEnginePlugin = {
},
});
+ const resolvePluginSessionRouting = (ctx?: SessionAgentLookup): PluginSessionRouting => {
+ const sessionId = typeof ctx?.sessionId === "string" ? ctx.sessionId.trim() : "";
+ const sessionKey = typeof ctx?.sessionKey === "string" ? ctx.sessionKey.trim() : "";
+ let ovSessionId = typeof ctx?.ovSessionId === "string" ? ctx.ovSessionId.trim() : "";
+
+ if (!ovSessionId && (sessionId || sessionKey)) {
+ ovSessionId = openClawSessionToOvStorageId(
+ sessionId || undefined,
+ sessionKey || undefined,
+ );
+ }
+
+ const session = {
+ agentId: ctx?.agentId,
+ sessionId: sessionId || undefined,
+ sessionKey: sessionKey || undefined,
+ ovSessionId: ovSessionId || undefined,
+ };
+ rememberSessionAgentId(session);
+
+ return {
+ sessionId: session.sessionId,
+ sessionKey: session.sessionKey,
+ ovSessionId: session.ovSessionId,
+ agentId: resolveAgentId(session.sessionId, session.sessionKey, session.ovSessionId),
+ };
+ };
+
const formatResourceImportText = (result: AddResourceResult): string => {
const root = result.root_uri ? ` ${result.root_uri}` : "";
const warnings = result.warnings?.length ? ` Warnings: ${result.warnings.join("; ")}` : "";
@@ -819,8 +855,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("ov_import");
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const session = resolvePluginSessionRouting(ctx);
return executeImport({
kind: params.kind === "skill" ? "skill" : "resource",
source: typeof params.source === "string" ? params.source : undefined,
@@ -831,7 +866,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
instruction: typeof params.instruction === "string" ? params.instruction : undefined,
wait: typeof params.wait === "boolean" ? params.wait : undefined,
timeout: typeof params.timeout === "number" ? params.timeout : undefined,
- }, agentId);
+ }, session.agentId);
},
}),
{ name: "ov_import" },
@@ -852,13 +887,12 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("ov_search");
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const session = resolvePluginSessionRouting(ctx);
return searchOpenViking({
query: String((params as { query?: unknown }).query ?? ""),
uri: typeof params.uri === "string" ? params.uri : undefined,
limit: typeof params.limit === "number" ? params.limit : undefined,
- }, agentId);
+ }, session.agentId);
},
}),
{ name: "ov_search" },
@@ -874,10 +908,9 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
const bypassed = makeBypassedToolResult("ov_import");
return { text: bypassed.content[0]!.text, details: bypassed.details };
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId);
+ const session = resolvePluginSessionRouting(ctx);
const input = parseOvImportCommandArgs(ctx.args ?? "");
- const result = await executeImport(input, agentId);
+ const result = await executeImport(input, session.agentId);
return { text: result.content[0]!.text, details: result.details };
} catch (err) {
return { text: `OpenViking import failed: ${err instanceof Error ? err.message : String(err)}` };
@@ -895,10 +928,9 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
const bypassed = makeBypassedToolResult("ov_search");
return { text: bypassed.content[0]!.text, details: bypassed.details };
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId);
+ const session = resolvePluginSessionRouting(ctx);
const input = parseOvSearchCommandArgs(ctx.args ?? "");
- const result = await searchOpenViking(input, agentId);
+ const result = await searchOpenViking(input, session.agentId);
return { text: result.content[0]!.text, details: result.details };
} catch (err) {
return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };
@@ -928,8 +960,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("memory_recall");
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const session = resolvePluginSessionRouting(ctx);
const { query } = params as { query: string };
const limit =
typeof (params as { limit?: number }).limit === "number"
@@ -948,7 +979,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
const recallClient = await getClient();
if (cfg.logFindRequests) {
api.logger.info(
- `openviking: memory_recall X-OpenViking-Agent="${agentId}" ` +
+ `openviking: memory_recall X-OpenViking-Agent="${session.agentId}" ` +
`(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,
);
}
@@ -963,7 +994,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: requestLimit,
scoreThreshold: 0,
},
- agentId,
+ session.agentId,
);
} else {
const searchPromises: Promise<FindResult>[] = [
@@ -974,7 +1005,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: requestLimit,
scoreThreshold: 0,
},
- agentId,
+ session.agentId,
),
recallClient.find(
query,
@@ -983,7 +1014,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: requestLimit,
scoreThreshold: 0,
},
- agentId,
+ session.agentId,
),
];
if (cfg.recallResources) {
@@ -995,7 +1026,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: requestLimit,
scoreThreshold: 0,
},
- agentId,
+ session.agentId,
),
);
}
@@ -1061,22 +1092,25 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("memory_store");
}
- rememberSessionAgentId(ctx);
- const storeAgentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const session = resolvePluginSessionRouting(ctx);
const { text } = params as { text: string };
const role =
typeof (params as { role?: string }).role === "string"
? (params as { role: string }).role
: "user";
- const sessionIdIn = (params as { sessionId?: string }).sessionId;
+ const explicitSessionId =
+ typeof (params as { sessionId?: unknown }).sessionId === "string" &&
+ (params as { sessionId: string }).sessionId.trim()
+ ? openClawSessionRefToOvStorageId((params as { sessionId: string }).sessionId)
+ : undefined;
if (cfg.logFindRequests) {
api.logger.info?.(
- `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${sessionIdIn ?? "auto"})`,
+ `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${explicitSessionId ?? "auto"})`,
);
}
- let sessionId = sessionIdIn;
+ let sessionId = explicitSessionId;
let usedTempSession = false;
try {
const c = await getClient();
@@ -1084,17 +1118,16 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
sessionId = `memory-store-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
usedTempSession = true;
}
- sessionId = openClawSessionToOvStorageId(sessionId, ctx.sessionKey);
const roleId = role === "user" ? toRoleId(extractToolSenderId(ctx)) : undefined;
await c.addSessionMessage(
sessionId,
role,
[{ type: "text" as const, text }],
- storeAgentId,
+ session.agentId,
undefined,
roleId,
);
- const commitResult = await c.commitSession(sessionId, { wait: true, agentId: storeAgentId });
+ const commitResult = await c.commitSession(sessionId, { wait: true, agentId: session.agentId });
const memoriesCount = totalCommitMemories(commitResult);
if (commitResult.status === "failed") {
api.logger.warn(
@@ -1180,8 +1213,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("memory_forget");
}
- rememberSessionAgentId(ctx);
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ const session = resolvePluginSessionRouting(ctx);
const client = await getClient();
const uri = (params as { uri?: string }).uri;
if (uri) {
@@ -1191,7 +1223,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
details: { action: "rejected", uri },
};
}
- await client.deleteUri(uri, agentId);
+ await client.deleteUri(uri, session.agentId);
return {
content: [{ type: "text", text: `Forgotten: ${uri}` }],
details: { action: "deleted", uri },
@@ -1227,7 +1259,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: requestLimit,
scoreThreshold: 0,
},
- agentId,
+ session.agentId,
);
const candidates = postProcessMemories(result.memories ?? [], {
limit: requestLimit,
@@ -1247,7 +1279,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
}
const top = candidates[0];
if (candidates.length === 1 && clampScore(top.score) >= 0.85) {
- await client.deleteUri(top.uri, agentId);
+ await client.deleteUri(top.uri, session.agentId);
return {
content: [{ type: "text", text: `Forgotten: ${top.uri}` }],
details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },
@@ -1289,9 +1321,9 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
if (isBypassedSession(ctx)) {
return makeBypassedToolResult("ov_archive_expand");
}
- rememberSessionAgentId(ctx);
+ const session = resolvePluginSessionRouting(ctx);
const archiveId = String((params as { archiveId?: string }).archiveId ?? "").trim();
- const sessionId = ctx.sessionId ?? "";
+ const sessionId = session.sessionId ?? "";
api.logger.info?.(`openviking: ov_archive_expand invoked (archiveId=${archiveId || "(empty)"}, sessionId=${sessionId || "(empty)"})`);
if (!archiveId) {
@@ -1302,25 +1334,19 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
};
}
- const sessionKey = ctx.sessionKey ?? "";
- if (!sessionId && !sessionKey) {
+ if (!session.ovSessionId) {
return {
content: [{ type: "text", text: "Error: no active session." }],
details: { error: "no_session" },
};
}
- const ovSessionId = openClawSessionToOvStorageId(
- ctx.sessionId,
- ctx.sessionKey,
- );
try {
const client = await getClient();
- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
const detail = await client.getSessionArchive(
- ovSessionId,
+ session.ovSessionId,
archiveId,
- agentId,
+ session.agentId,
);
const header = [
@@ -1342,7 +1368,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
archiveId: detail.archive_id,
messageCount: detail.messages.length,
sessionId,
- ovSessionId,
+ ovSessionId: session.ovSessionId,
},
};
} catch (err) {
@@ -1350,7 +1376,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
api.logger.warn?.(`openviking: ov_archive_expand failed (archiveId=${archiveId}, sessionId=${sessionId}): ${msg}`);
return {
content: [{ type: "text", text: `Failed to expand ${archiveId}: ${msg}` }],
- details: { error: msg, archiveId, sessionId, ovSessionId },
+ details: { error: msg, archiveId, sessionId, ovSessionId: session.ovSessionId },
};
}
},
@@ -1555,7 +1581,10 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
const sessionId = ctx?.sessionId;
if (sessionId && contextEngineRef) {
try {
- const ok = await contextEngineRef.commitOVSession(sessionId, ctx?.sessionKey);
+ const ok = await contextEngineRef.commitOVSession({
+ sessionId,
+ sessionKey: ctx?.sessionKey,
+ });
if (ok) {
api.logger.info(`openviking: committed OV session on reset for session=${sessionId}`);
}
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 c73ab74c6..096a9ecf4 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it, vi } from "vitest";
import type { OpenVikingClient } from "../../client.js";
import { memoryOpenVikingConfigSchema } from "../../config.js";
-import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";
+import {
+ createMemoryOpenVikingContextEngine,
+ openClawSessionToOvStorageId,
+} from "../../context-engine.js";
function makeLogger() {
return {
@@ -56,6 +59,7 @@ function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {
commitSession: ReturnType<typeof vi.fn>;
},
logger,
+ resolveAgentId,
};
}
@@ -67,7 +71,7 @@ describe("context-engine commitOVSession()", () => {
memories_extracted: { core: 1 },
});
- const ok = await engine.commitOVSession("test-session");
+ const ok = await engine.commitOVSession({ sessionId: "test-session" });
expect(ok).toBe(true);
});
@@ -77,7 +81,7 @@ describe("context-engine commitOVSession()", () => {
error: "extraction error",
});
- const ok = await engine.commitOVSession("test-session");
+ const ok = await engine.commitOVSession({ sessionId: "test-session" });
expect(ok).toBe(false);
});
@@ -87,7 +91,7 @@ describe("context-engine commitOVSession()", () => {
task_id: "task-timeout",
});
- const ok = await engine.commitOVSession("test-session");
+ const ok = await engine.commitOVSession({ sessionId: "test-session" });
expect(ok).toBe(false);
});
@@ -96,7 +100,7 @@ describe("context-engine commitOVSession()", () => {
throwError: new Error("connection refused"),
});
- const ok = await engine.commitOVSession("test-session");
+ const ok = await engine.commitOVSession({ sessionId: "test-session" });
expect(ok).toBe(false);
});
@@ -107,11 +111,28 @@ describe("context-engine commitOVSession()", () => {
memories_extracted: {},
});
- await engine.commitOVSession("s1");
+ await engine.commitOVSession({ sessionId: "s1" });
expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });
});
+ it("uses sessionKey-derived OV session ID for commitOVSession", async () => {
+ const { engine, client, resolveAgentId } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.commitOVSession({
+ sessionId: "plain-session",
+ sessionKey: "agent:main:main",
+ });
+
+ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");
+ expect(client.commitSession.mock.calls[0][0]).toBe(ovSessionId);
+ expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);
+ });
+
it("logs memories extracted count", async () => {
const { engine, logger } = makeEngine({
status: "completed",
@@ -119,7 +140,7 @@ describe("context-engine commitOVSession()", () => {
memories_extracted: { core: 3, preferences: 1 },
});
- await engine.commitOVSession("s1");
+ await engine.commitOVSession({ sessionId: "s1" });
expect(logger.info).toHaveBeenCalledWith(
expect.stringContaining("memories=4"),
@@ -148,7 +169,7 @@ describe("context-engine commitOVSession()", () => {
resolveAgentId,
});
- const ok = await engine.commitOVSession("runtime-session", "agent:main:cron:nightly:run:1");
+ const ok = await engine.commitOVSession({ sessionId: "runtime-session", sessionKey: "agent:main:cron:nightly:run:1" });
expect(ok).toBe(false);
expect(getClient).not.toHaveBeenCalled();
@@ -338,6 +359,43 @@ describe("context-engine compact()", () => {
expect(commitCallSessionId).toBe("a1b2c3d4-e5f6-7890-abcd-ef1234567890");
});
+ it("uses sessionKey-derived OV session ID and resolver context when compact receives a non-UUID sessionId", async () => {
+ const { engine, client, resolveAgentId } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.compact({
+ sessionId: "plain-session",
+ sessionFile: "",
+ runtimeContext: { sessionKey: "agent:main:main", agentId: "main" },
+ });
+
+ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");
+ expect(client.commitSession.mock.calls[0][0]).toBe(ovSessionId);
+ expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);
+ });
+
+ it("prefers top-level sessionKey over runtimeContext sessionKey in compact params", async () => {
+ const { engine, client, resolveAgentId } = makeEngine({
+ status: "completed",
+ archived: false,
+ memories_extracted: {},
+ });
+
+ await engine.compact({
+ sessionId: "plain-session",
+ sessionKey: "agent:top:main",
+ sessionFile: "",
+ runtimeContext: { sessionKey: "agent:runtime:main" },
+ });
+
+ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:top:main");
+ expect(client.commitSession.mock.calls[0][0]).toBe(ovSessionId);
+ expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:top:main", ovSessionId);
+ });
+
it("passes agentId to commitSession", async () => {
const { engine, client } = makeEngine({
status: "completed",
@@ -369,4 +427,24 @@ describe("context-engine compact()", () => {
expect.stringContaining("commit failed"),
);
});
+
+ it("returns compacted=false when commit reports the OV session does not exist", async () => {
+ const { engine, client, logger } = makeEngine(null, {
+ throwError: new Error("OpenViking request failed [NOT_FOUND]: Session not found: s-missing"),
+ });
+
+ const result = await engine.compact({
+ sessionId: "s-missing",
+ sessionFile: "",
+ currentTokenCount: 123,
+ });
+
+ expect(result.ok).toBe(true);
+ expect(result.compacted).toBe(false);
+ expect(result.reason).toBe("session_not_found");
+ expect(client.commitSession).toHaveBeenCalledTimes(1);
+ expect(logger.warn).not.toHaveBeenCalledWith(
+ expect.stringContaining("compact commit failed"),
+ );
+ });
});
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index 1681b2af1..1e846013a 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -223,6 +223,71 @@ describe("Tool: memory_store (behavioral)", () => {
expect(body.role).toBe("user");
expect(body.role_id).toBe("wx_user-01_abc");
});
+
+ it("uses a temporary session by default instead of the current tool session", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "default" });
+ }
+ if (url.includes("/messages")) {
+ return okResponse({ session_id: "sess-1" });
+ }
+ if (url.endsWith("/commit")) {
+ return okResponse({ status: "completed", archived: false, memories_extracted: {} });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const tool = factoryTools.get("memory_store")!({
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:main",
+ });
+
+ await tool.execute("tc-memory-store", { text: "hello from tool" });
+
+ const messageCall = fetchMock.mock.calls.find(([url]) =>
+ String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),
+ );
+ expect(String(messageCall?.[0])).toContain("/api/v1/sessions/memory-store-");
+ });
+
+ it("normalizes explicit memory_store sessionId without using current sessionKey", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "default" });
+ }
+ if (url.includes("/messages")) {
+ return okResponse({ session_id: "sess-1" });
+ }
+ if (url.endsWith("/commit")) {
+ return okResponse({ status: "completed", archived: false, memories_extracted: {} });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const tool = factoryTools.get("memory_store")!({
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:main",
+ });
+
+ await tool.execute("tc-memory-store", {
+ text: "hello from tool",
+ sessionId: "C:\\Users\\test",
+ });
+
+ const messageCall = fetchMock.mock.calls.find(([url]) =>
+ String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),
+ );
+ expect(String(messageCall?.[0])).not.toContain("runtime-session");
+ expect(String(messageCall?.[0])).not.toContain("agent%3Amain%3Amain");
+ expect(String(messageCall?.[0])).toMatch(/\/api\/v1\/sessions\/[a-f0-9]{64}\/messages$/);
+ });
});
describe("Tool: memory_forget (behavioral)", () => {