Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(openclaw): route auto recall through assemble (#1835)
AutoCoder4d6f5b65bd24
diff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.mdindex 2eb08d6df..be613c1c5 100644--- a/examples/openclaw-plugin/INSTALL-AGENT.md+++ b/examples/openclaw-plugin/INSTALL-AGENT.md@@ -45,7 +45,7 @@ openclaw --versionRequirements:- Node.js >= 22-- OpenClaw >= 2026.3.7+- OpenClaw >= 2026.4.24### 3. Detect or start OpenViking serverdiff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.mdindex f42725e7a..b6482e638 100644--- a/examples/openclaw-plugin/INSTALL-ZH.md+++ b/examples/openclaw-plugin/INSTALL-ZH.md@@ -9,7 +9,7 @@| 组件 | 版本要求 || --- | --- || Node.js | >= 22 |-| OpenClaw | >= 2026.3.7 |+| OpenClaw | >= 2026.4.24 |插件以远程模式连接到已有的 OpenViking 服务。它不会帮你启动 OpenViking server。需要先启动 OpenViking,并保持服务运行,再把插件的 `baseUrl` 指向这个 HTTP 服务。默认本地地址是 `http://127.0.0.1:1933`。diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.mdindex 602f6493e..54e3272c2 100644--- a/examples/openclaw-plugin/INSTALL.md+++ b/examples/openclaw-plugin/INSTALL.md@@ -9,7 +9,7 @@ Use [OpenViking](https://github.com/volcengine/OpenViking) as the long-term memo| Component | Required Version || --- | --- || Node.js | >= 22 |-| OpenClaw | >= 2026.3.7 |+| OpenClaw | >= 2026.4.24 |The plugin connects to an existing OpenViking server. It does not start the OpenViking server for you. Start OpenViking first, keep it running, then point the plugin `baseUrl` at that HTTP service. The default local URL is `http://127.0.0.1:1933`.diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex eaa2aee17..1ce7375f4 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -19,7 +19,7 @@ This document is not an installation guide. It is an implementation-focused desiIn the current implementation, the plugin plays four roles at once:- `context-engine`: implements `assemble`, `afterTurn`, and `compact`-- hook layer: handles `before_prompt_build`, `session_start`, `session_end`, `agent_end`, and `before_reset`+- hook layer: handles `session_start`, `session_end`, `agent_end`, and `before_reset`- tool provider: registers memory/archive tools plus OpenViking resource and skill import tools- runtime manager: connects to and monitors a remote OpenViking service@@ -79,18 +79,23 @@ For OpenViking servers that include PR #1356, the plugin no longer treats agentThe plugin cannot auto-discover this policy today because `/api/v1/system/status` does not expose it. Configure the two booleans explicitly so they stay aligned with the server-side account policy.-## Prompt-Front Recall Flow+## assemble Recall Flow-Today the main recall path still lives in `before_prompt_build`:+Auto-recall now runs through `assemble()`. OpenClaw calls the same context engine method in two shapes, and the plugin assigns different responsibilities to each shape:-1. Extract the latest user text from `messages` or `prompt`.-2. Resolve the agent routing for the current `sessionId/sessionKey`.-3. Run a quick availability precheck so prompt building does not stall when OpenViking is unavailable.-4. Query both `viking://user/memories` and `viking://agent/memories` in parallel.-5. Deduplicate, threshold-filter, rerank, and trim the results under a token budget.-6. Prepend the selected memories as a `<relevant-memories>` block.+1. Preflight assemble: params include `prompt`; `messages` is still old history. The plugin reads archive/session context back from OpenViking and rebuilds history.+2. transformContext assemble: params do not include `prompt`; the latest `messages` entry is already the current user turn. The plugin only runs long-term recall and prepends the memory block to that user message content.++During recall, the plugin:++1. Extracts query text from the latest user message.+2. Resolves the agent routing for the current `sessionId/sessionKey`.+3. Runs a quick availability precheck so model requests do not stall when OpenViking is unavailable.+4. Queries both `viking://user/memories` and `viking://agent/memories` in parallel.+5. Deduplicates, threshold-filters, reranks, and trims the results under a token budget.+6. Prepends the selected memories as a `<relevant-memories>` block to the current user message; it does not append a standalone synthetic user message.The reranking logic is not pure vector-score sorting. The current implementation also considers:@@ -107,7 +112,7 @@ Session handling is the main axis of this design. In the current implementation### What `assemble()` does-`assemble()` is not just replaying old chat history. It reads session context back from OpenViking under a token budget, then rebuilds OpenClaw-facing messages:+During preflight, `assemble()` is not just replaying old chat history. It reads session context back from OpenViking under a token budget, then rebuilds OpenClaw-facing messages:- `latest_archive_overview` becomes `[Session History Summary]`- `pre_archive_abstracts` becomes `[Archive Index]`@@ -205,7 +210,7 @@ The repo also contains a more future-looking design draft at `docs/design/opencl- this README describes current implemented behavior- the older draft discusses a stronger future move into context-engine-owned lifecycle control-- in the current version, the main automatic recall path still lives in `before_prompt_build`, not fully in `assemble()`+- in the current version, the main automatic recall path lives in `assemble()`: preflight rebuilds history, transformContext injects long-term memories- in the current version, `afterTurn()` already appends to the OpenViking session, but commit remains threshold-triggered and asynchronous on that path- in the current version, `compact()` already uses `commit(wait=true)`, but it is still focused on synchronous commit plus readback rather than owning every orchestration concerndiff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex b69214d19..2f9069b46 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -19,7 +19,7 @@按当前代码职责看,插件同时扮演四个角色:- `context-engine`:实现 `assemble`、`afterTurn`、`compact`-- Hook 层:接管 `before_prompt_build`、`session_start`、`session_end`、`agent_end`、`before_reset`+- Hook 层:接管 `session_start`、`session_end`、`agent_end`、`before_reset`- Tool 提供者:注册 memory/archive 工具,以及 OpenViking resource 和 skill 导入工具- 运行时管理器:连接并监控远程 OpenViking 服务@@ -79,18 +79,23 @@插件当前无法从 `/api/v1/system/status` 自动发现这两个 policy,因此需要显式配置,使其与服务端 account policy 保持一致。-## Prompt 前召回链路+## assemble 召回链路-当前主召回路径仍然挂在 `before_prompt_build`,流程是:+自动召回现在由 `assemble()` 承接。OpenClaw 会在同一个 context engine 上调用两次 `assemble()`,插件按调用形态区分职责:-1. 从 `messages` 或 `prompt` 中提取最后一条用户文本。+1. preflight assemble:调用参数里带 `prompt`,`messages` 还是旧历史;插件从 OpenViking 回读 archive/session context 并重建历史。+2. transformContext assemble:调用参数里不带 `prompt`,最后一条 `messages` 已经是本轮 user;插件只做长期记忆召回,并把记忆块 prepend 到这条 user message 的 content 开头。++召回阶段会:++1. 从最后一条 user message 提取查询文本。2. 基于当前 `sessionId/sessionKey` 解析本轮的 agent 路由。-3. 先做一次快速可用性检查,避免在 OpenViking 不可用时把 prompt 前链路拖死。+3. 先做一次快速可用性检查,避免在 OpenViking 不可用时拖慢模型请求。4. 并行检索 `viking://user/memories` 和 `viking://agent/memories`。5. 在插件侧做去重、阈值筛选、重排和 token budget 裁剪。-6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到 prompt。+6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。这里的重排不是单纯依赖向量分数。当前实现还会额外考虑:@@ -107,7 +112,7 @@ Session 是这套设计的主轴。当前实现里,它覆盖了"历史组装### `assemble()` 负责什么-`assemble()` 并不是简单地把旧聊天记录塞回来,而是按 token budget 从 OpenViking 回读当前 session context,然后重新组装成 OpenClaw 可消费的消息:+preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来,而是按 token budget 从 OpenViking 回读当前 session context,然后重新组装成 OpenClaw 可消费的消息:- `latest_archive_overview` 被改写成 `[Session History Summary]`- `pre_archive_abstracts` 被改写成 `[Archive Index]`@@ -205,7 +210,7 @@ OpenViking 服务需要独立部署并运行,插件才能连接到它。- 本文描述的是当前实现已经落地的行为。- 旧设计稿讨论的是"进一步把更多主链路迁入 context-engine 生命周期"的目标态。-- 当前版本里,自动 recall 的主入口仍然在 `before_prompt_build`,并没有完全迁到 `assemble()`。+- 当前版本里,自动 recall 的主入口已经迁到 `assemble()`:preflight 重建历史,transformContext 注入长期记忆。- 当前版本里,`afterTurn()` 已经负责增量写入 OpenViking session,但它仍然依赖阈值触发异步 commit。- 当前版本里,`compact()` 已经走 `commit(wait=true)`,但它的职责仍以"同步提交 + 结果回读"为主,而不是承载一切上层编排。@@ -262,4 +267,3 @@ ov tui---安装、升级、卸载请查看 [INSTALL-ZH.md](./INSTALL-ZH.md)。-diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsnew file mode 100644index 000000000..a3b5d98cc--- /dev/null+++ b/examples/openclaw-plugin/auto-recall.ts@@ -0,0 +1,257 @@+import type { FindResult, FindResultItem, OpenVikingClient } from "./client.js";+import type { MemoryOpenVikingConfig } from "./config.js";+import {+ pickMemoriesForInjection,+ postProcessMemories,+ summarizeInjectionMemories,+ toJsonLog,+} from "./memory-ranking.js";+import { quickRecallPrecheck, withTimeout } from "./process-manager.js";+import { sanitizeUserTextForCapture } from "./text-utils.js";++const AUTO_RECALL_TIMEOUT_MS = 5_000;+const RECALL_QUERY_MAX_CHARS = 4_000;+export const AUTO_RECALL_SOURCE_MARKER = "Source: openviking-auto-recall";++type Logger = {+ info: (msg: string) => void;+ warn?: (msg: string) => void;+};++export type PreparedRecallQuery = {+ query: string;+ truncated: boolean;+ originalChars: number;+ finalChars: number;+};++export function prepareRecallQuery(rawText: string): PreparedRecallQuery {+ const sanitized = sanitizeUserTextForCapture(rawText).trim();+ const originalChars = sanitized.length;++ if (!sanitized) {+ return {+ query: "",+ truncated: false,+ originalChars: 0,+ finalChars: 0,+ };+ }++ const query =+ sanitized.length > RECALL_QUERY_MAX_CHARS+ ? sanitized.slice(0, RECALL_QUERY_MAX_CHARS).trim()+ : sanitized;++ return {+ query,+ truncated: sanitized.length > RECALL_QUERY_MAX_CHARS,+ originalChars,+ finalChars: query.length,+ };+}++/** Estimate token count using chars/4 heuristic for diagnostics. */+export function estimateTokenCount(text: string): number {+ if (!text) return 0;+ return Math.ceil(text.length / 4);+}++export type BuildMemoryLinesOptions = {+ recallPreferAbstract: boolean;+};++async function resolveMemoryContent(+ item: FindResultItem,+ readFn: (uri: string) => Promise<string>,+ options: BuildMemoryLinesOptions,+): Promise<string> {+ let content: string;++ if (options.recallPreferAbstract && item.abstract?.trim()) {+ content = item.abstract.trim();+ } else if (item.level === 2) {+ try {+ const fullContent = await readFn(item.uri);+ content =+ fullContent && typeof fullContent === "string" && fullContent.trim()+ ? fullContent.trim()+ : (item.abstract?.trim() || item.uri);+ } catch {+ content = item.abstract?.trim() || item.uri;+ }+ } else {+ content = item.abstract?.trim() || item.uri;+ }++ return content;+}++export async function buildMemoryLines(+ memories: FindResultItem[],+ readFn: (uri: string) => Promise<string>,+ options: BuildMemoryLinesOptions,+): Promise<string[]> {+ const lines: string[] = [];+ for (const item of memories) {+ const content = await resolveMemoryContent(item, readFn, options);+ lines.push(`- [${item.category ?? "memory"}] ${content}`);+ }+ return lines;+}++export type BuildMemoryLinesWithBudgetOptions = BuildMemoryLinesOptions & {+ recallMaxInjectedChars?: number;+ recallTokenBudget?: number;+};++/**+ * Build memory lines with a character budget constraint.+ *+ * Individual memories are never truncated. A memory that cannot fit within the+ * remaining character budget is skipped so only complete memory entries are+ * injected.+ */+export async function buildMemoryLinesWithBudget(+ memories: FindResultItem[],+ readFn: (uri: string) => Promise<string>,+ options: BuildMemoryLinesWithBudgetOptions,+): Promise<{ lines: string[]; estimatedTokens: number }> {+ const charBudget = options.recallMaxInjectedChars ?? options.recallTokenBudget ?? 0;+ const lines: string[] = [];+ let totalTokens = 0;+ let totalChars = 0;++ for (const item of memories) {+ if (totalChars >= charBudget) {+ break;+ }++ const content = await resolveMemoryContent(item, readFn, options);+ const line = `- [${item.category ?? "memory"}] ${content}`;+ const separatorChars = lines.length > 0 ? 1 : 0;+ const projectedChars = totalChars + separatorChars + line.length;++ if (projectedChars > charBudget) {+ continue;+ }++ const lineTokens = estimateTokenCount(line);++ lines.push(line);+ totalTokens += lineTokens;+ totalChars = projectedChars;+ }++ return { lines, estimatedTokens: totalTokens };+}++export function buildRecallContextBlock(memoryLines: string[]): string {+ return [+ "<relevant-memories>",+ AUTO_RECALL_SOURCE_MARKER,+ "The following OpenViking memories may be relevant:",+ ...memoryLines,+ "</relevant-memories>",+ ].join("\n");+}++export async function buildAutoRecallContext(params: {+ cfg: Required<MemoryOpenVikingConfig>;+ client: OpenVikingClient;+ agentId: string;+ queryText: string;+ logger: Logger;+ verbose?: (message: string) => void;+}): Promise<{ block?: string; memoryCount: number; estimatedTokens: number }> {+ const { cfg, client, agentId, queryText, logger, verbose } = params;++ if (!cfg.autoRecall || queryText.length < 5) {+ return { memoryCount: 0, estimatedTokens: 0 };+ }++ const precheck = await quickRecallPrecheck(cfg.baseUrl);+ if (!precheck.ok) {+ verbose?.(`openviking: skipping auto-recall because precheck failed (${precheck.reason})`);+ return { memoryCount: 0, estimatedTokens: 0 };+ }++ return withTimeout(+ (async () => {+ const candidateLimit = Math.max(cfg.recallLimit * 4, 20);+ const autoRecallPromises: Promise<FindResult>[] = [+ client.find(queryText, {+ targetUri: "viking://user/memories",+ limit: candidateLimit,+ scoreThreshold: 0,+ }, agentId),+ client.find(queryText, {+ targetUri: "viking://agent/memories",+ limit: candidateLimit,+ scoreThreshold: 0,+ }, agentId),+ ];+ if (cfg.recallResources) {+ autoRecallPromises.push(+ client.find(queryText, {+ targetUri: "viking://resources",+ limit: candidateLimit,+ scoreThreshold: 0,+ }, agentId),+ );+ }+ const autoRecallSettled = await Promise.allSettled(autoRecallPromises);++ const allMemories: FindResultItem[] = [];+ for (const s of autoRecallSettled) {+ if (s.status === "fulfilled") {+ allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));+ } else {+ logger.warn?.(`openviking: auto-recall search failed: ${String(s.reason)}`);+ }+ }++ const uniqueMemories = allMemories.filter((memory, index, self) =>+ index === self.findIndex((m) => m.uri === memory.uri)+ );+ const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);+ const processed = postProcessMemories(leafOnly, {+ limit: candidateLimit,+ scoreThreshold: cfg.recallScoreThreshold,+ });+ const memories = pickMemoriesForInjection(processed, cfg.recallLimit, queryText);++ if (memories.length === 0) {+ return { memoryCount: 0, estimatedTokens: 0 };+ }++ const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(+ memories,+ (uri) => client.read(uri, agentId),+ {+ recallPreferAbstract: cfg.recallPreferAbstract,+ recallMaxInjectedChars: cfg.recallMaxInjectedChars,+ },+ );++ if (memoryLines.length === 0) {+ verbose?.(+ `openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${cfg.recallMaxInjectedChars}`,+ );+ return { memoryCount: 0, estimatedTokens: 0 };+ }++ const block = buildRecallContextBlock(memoryLines);+ verbose?.(+ `openviking: injecting ${memoryLines.length} memories (${block.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${cfg.recallMaxInjectedChars})`,+ );+ verbose?.(+ `openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,+ );++ return { block, memoryCount: memoryLines.length, estimatedTokens };+ })(),+ AUTO_RECALL_TIMEOUT_MS,+ "openviking: auto-recall search timeout",+ );+}diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.tsindex 4c77fe700..16e48458f 100644--- a/examples/openclaw-plugin/commands/setup.ts+++ b/examples/openclaw-plugin/commands/setup.ts@@ -21,6 +21,10 @@ type CommandBuilder = {action: (fn: (...args: unknown[]) => void | Promise<void>) => CommandBuilder;};+type RegisterCliArgs = {+ program: CommandProgram;+};+function tr(langZh: boolean, en: string, zh: string): string {return langZh ? zh : en;}@@ -182,8 +186,7 @@ export function registerSetupCli(api: any): void {}api.registerCli(- ({ program: rawProgram }) => {- const program = rawProgram as CommandProgram;+ ({ program }: RegisterCliArgs) => {const ovCmd = program.command("openviking").description("OpenViking plugin commands");ovCmd@@ -191,7 +194,8 @@ export function registerSetupCli(api: any): void {.description("Interactive setup wizard for OpenViking plugin configuration").option("--reconfigure", "Force re-entry of all configuration values").option("--zh", "Chinese prompts")- .action(async (options: { reconfigure?: boolean; zh?: boolean }) => {+ .action(async (rawOptions: unknown) => {+ const options = (rawOptions ?? {}) as { reconfigure?: boolean; zh?: boolean };const zh = detectLangZh(options as Record<string, unknown>);const configDir = OPENCLAW_DIR;const configPath = path.join(configDir, "openclaw.json");diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex ef7d881c5..6e4d8f6a6 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -56,7 +56,7 @@ const DEFAULT_CAPTURE_MAX_LENGTH = 24000;const DEFAULT_RECALL_LIMIT = 6;const DEFAULT_RECALL_SCORE_THRESHOLD = 0.15;const DEFAULT_RECALL_MAX_CONTENT_CHARS = 5000;-const DEFAULT_RECALL_PREFER_ABSTRACT = true;+const DEFAULT_RECALL_PREFER_ABSTRACT = false;const DEFAULT_RECALL_MAX_INJECTED_CHARS = 4000;const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];@@ -282,7 +282,10 @@ export const memoryOpenVikingConfigSchema = {50,Math.min(10000, Math.floor(toNumber(cfg.recallMaxContentChars, DEFAULT_RECALL_MAX_CONTENT_CHARS))),),- recallPreferAbstract: cfg.recallPreferAbstract === true,+ recallPreferAbstract:+ typeof cfg.recallPreferAbstract === "boolean"+ ? cfg.recallPreferAbstract+ : DEFAULT_RECALL_PREFER_ABSTRACT,recallMaxInjectedChars,recallTokenBudget: recallMaxInjectedChars,commitTokenThreshold: Math.max(diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex 193854b71..3a553c590 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -2,11 +2,15 @@ import { createHash } from "node:crypto";import { DEFAULT_PHASE2_POLL_TIMEOUT_MS } from "./client.js";import type { OpenVikingClient, OVMessage } from "./client.js";import type { MemoryOpenVikingConfig } from "./config.js";+import {+ AUTO_RECALL_SOURCE_MARKER,+ buildAutoRecallContext,+ prepareRecallQuery,+} from "./auto-recall.js";import {compileSessionPatterns,getCaptureDecision,extractNewTurnMessages,- extractSingleMessageText,shouldBypassSession,} from "./text-utils.js";import {@@ -90,6 +94,7 @@ type ContextEngine = {sessionId: string;sessionKey?: string;messages: AgentMessage[];+ prompt?: string;tokenBudget?: number;runtimeContext?: Record<string, unknown>;}) => Promise<AssembleResult>;@@ -216,6 +221,78 @@ function messageDigest(messages: AgentMessage[], maxCharsPerMsg = 2000): Array<{});}+function extractAgentMessageText(message: AgentMessage | undefined): string {+ if (!message) {+ return "";+ }+ const raw = message.content;+ if (typeof raw === "string") {+ return raw;+ }+ if (Array.isArray(raw)) {+ return raw+ .map((block) => {+ if (!block || typeof block !== "object") {+ return "";+ }+ const b = block as Record<string, unknown>;+ if (b.type === "text" && typeof b.text === "string") {+ return b.text;+ }+ return "";+ })+ .filter(Boolean)+ .join("\n");+ }+ return "";+}++function hasAutoRecallBlock(message: AgentMessage | undefined): boolean {+ return extractAgentMessageText(message).includes(AUTO_RECALL_SOURCE_MARKER);+}++function prependTextToMessageContent(content: unknown, text: string): unknown {+ if (typeof content === "string") {+ return `${text}\n\n${content}`;+ }+ if (Array.isArray(content)) {+ if (content.length === 0) {+ return [{ type: "text", text }];+ }+ const first = content[0];+ if (+ first &&+ typeof first === "object" &&+ (first as Record<string, unknown>).type === "text" &&+ typeof (first as Record<string, unknown>).text === "string"+ ) {+ return [+ {+ ...(first as Record<string, unknown>),+ text: `${text}\n\n${(first as Record<string, unknown>).text as string}`,+ },+ ...content.slice(1),+ ];+ }+ return [{ type: "text", text }, ...content];+ }+ return text;+}++function prependRecallToLatestUserMessage(messages: AgentMessage[], recallBlock: string): AgentMessage[] {+ const latest = messages.at(-1);+ if (!latest || latest.role !== "user" || hasAutoRecallBlock(latest)) {+ return messages;+ }+ return [+ ...messages.slice(0, -1),+ {+ ...latest,+ content: prependTextToMessageContent(latest.content, recallBlock),+ },+ ];+}+function emitDiag(log: Logger, stage: string, sessionId: string, data: Record<string, unknown>, enabled = true): void {if (!enabled) return;log.info(`openviking: diag ${JSON.stringify({ ts: Date.now(), stage, sessionId, data })}`);@@ -907,6 +984,12 @@ export function createMemoryOpenVikingContextEngine(params: {const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(assembleParams);const sender = extractRuntimeSenderId(assembleParams.runtimeContext);+ const latestMessage = messages.at(-1);+ const isMainAssemble =+ Object.prototype.hasOwnProperty.call(assembleParams, "availableTools") ||+ Object.prototype.hasOwnProperty.call(assembleParams, "citationsMode") ||+ Object.prototype.hasOwnProperty.call(assembleParams, "prompt");+ const isTransformContextAssemble = !isMainAssemble;const originalTokens = roughEstimate(messages);@@ -930,6 +1013,70 @@ export function createMemoryOpenVikingContextEngine(params: {return assemblePassthrough(OVSessionId, "session_bypassed", messages, originalTokens);}+ if (isTransformContextAssemble) {+ if (latestMessage?.role !== "user") {+ return assemblePassthrough(OVSessionId, "transform_context_non_user_tail", messages, originalTokens, {+ latestRole: latestMessage?.role ?? null,+ });+ }+ if (!cfg.autoRecall) {+ return assemblePassthrough(OVSessionId, "transform_context_auto_recall_disabled", messages, originalTokens);+ }+ if (hasAutoRecallBlock(latestMessage)) {+ return assemblePassthrough(OVSessionId, "transform_context_recall_already_injected", messages, originalTokens);+ }++ const recallQuery = prepareRecallQuery(extractAgentMessageText(latestMessage));+ if (!recallQuery.query || recallQuery.query.length < 5) {+ return assemblePassthrough(OVSessionId, "transform_context_empty_recall_query", messages, originalTokens);+ }+ if (recallQuery.truncated) {+ logger.info(+ `openviking: recall query truncated (` ++ `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,+ );+ }++ try {+ const client = await getClient();+ const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;+ const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);+ const recall = await buildAutoRecallContext({+ cfg,+ client,+ agentId,+ queryText: recallQuery.query,+ logger,+ verbose: (message) => logger.info(message),+ });++ if (!recall.block) {+ return assemblePassthrough(OVSessionId, "transform_context_no_recall_hits", messages, originalTokens, {+ memoryCount: recall.memoryCount,+ });+ }++ const withRecall = prependRecallToLatestUserMessage(messages, recall.block);+ const estimatedTokens = roughEstimate(withRecall);+ diag("assemble_result", OVSessionId, {+ passthrough: false,+ phase: "transform_context",+ outputMessagesCount: withRecall.length,+ inputTokenEstimate: originalTokens,+ estimatedTokens,+ autoRecallMemoryCount: recall.memoryCount,+ autoRecallTokens: recall.estimatedTokens,+ messages: messageDigest(withRecall),+ });+ return { messages: withRecall, estimatedTokens };+ } catch (err) {+ logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);+ return assemblePassthrough(OVSessionId, "transform_context_recall_failed", messages, originalTokens, {+ error: String(err),+ });+ }+ }+try {const client = await getClient();const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 2e51c34d1..512617ed9 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -16,8 +16,6 @@ import type {import { formatMessageFaithful, toRoleId } from "./context-engine.js";import {compileSessionPatterns,- extractLatestUserText,- sanitizeUserTextForCapture,shouldBypassSession,extractNewTurnMessages,} from "./text-utils.js";@@ -25,17 +23,31 @@ import {clampScore,postProcessMemories,formatMemoryLines,- toJsonLog,- summarizeInjectionMemories,- pickMemoriesForInjection,} from "./memory-ranking.js";-import { quickRecallPrecheck, withTimeout } from "./process-manager.js";+import { withTimeout } from "./process-manager.js";import {createMemoryOpenVikingContextEngine,openClawSessionToOvStorageId,openClawSessionRefToOvStorageId,} from "./context-engine.js";import type { ContextEngineWithCommit } from "./context-engine.js";+import {+ buildMemoryLines,+ buildMemoryLinesWithBudget,+ estimateTokenCount,+ prepareRecallQuery,+} from "./auto-recall.js";+export {+ buildMemoryLines,+ buildMemoryLinesWithBudget,+ estimateTokenCount,+ prepareRecallQuery,+};+export type {+ BuildMemoryLinesOptions,+ BuildMemoryLinesWithBudgetOptions,+ PreparedRecallQuery,+} from "./auto-recall.js";type PluginLogger = {debug?: (message: string) => void;@@ -163,8 +175,6 @@ type OpenClawPluginApi = {) => void;};-const AUTO_RECALL_TIMEOUT_MS = 5_000;-const RECALL_QUERY_MAX_CHARS = 4_000;const DEFAULT_OPENCLAW_AGENT_ID = "main";/**@@ -184,39 +194,6 @@ export function sanitizeOpenVikingAgentIdHeader(raw: string): string {return normalized.length > 0 ? normalized : "ov_agent";}-export type PreparedRecallQuery = {- query: string;- truncated: boolean;- originalChars: number;- finalChars: number;-};--export function prepareRecallQuery(rawText: string): PreparedRecallQuery {- const sanitized = sanitizeUserTextForCapture(rawText).trim();- const originalChars = sanitized.length;-- if (!sanitized) {- return {- query: "",- truncated: false,- originalChars: 0,- finalChars: 0,- };- }-- const query =- sanitized.length > RECALL_QUERY_MAX_CHARS- ? sanitized.slice(0, RECALL_QUERY_MAX_CHARS).trim()- : sanitized;-- return {- query,- truncated: sanitized.length > RECALL_QUERY_MAX_CHARS,- originalChars,- finalChars: query.length,- };-}-export function tokenizeCommandArgs(args: string): string[] {const tokens: string[] = [];let current = "";@@ -1421,153 +1398,6 @@ const mergeFindResults = (results: FindResult[]): FindResult => {api.on("session_end", async (_event: unknown, ctx?: HookAgentContext) => {rememberSessionAgentId(ctx ?? {});});- api.on("before_prompt_build", async (event: unknown, ctx?: HookAgentContext) => {- rememberSessionAgentId(ctx ?? {});-- if (cfg.logFindRequests) {- api.logger.info(- `openviking: hook before_prompt_build ctx=${JSON.stringify({- sessionId: ctx?.sessionId,- sessionKey: ctx?.sessionKey,- agentId: ctx?.agentId,- })}`,- );- }- if (isBypassedSession(ctx)) {- verboseRoutingInfo(- `openviking: bypassing before_prompt_build due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,- );- return;- }- const agentId = resolveAgentId(ctx?.sessionId, ctx?.sessionKey);- let client: OpenVikingClient;- try {- client = await withTimeout(- getClient(),- 5000,- "openviking: client initialization timeout (OpenViking service not ready yet)"- );- } catch (err) {- api.logger.warn?.(`openviking: failed to get client: ${String(err)}`);- return;- }-- const eventObj = (event ?? {}) as { messages?: unknown[]; prompt?: string };- const latestUserText = extractLatestUserText(eventObj.messages);- const rawRecallQuery =- latestUserText ||- (typeof eventObj.prompt === "string" ? sanitizeUserTextForCapture(eventObj.prompt) : "");- const recallQuery = prepareRecallQuery(rawRecallQuery);- const queryText = recallQuery.query;- if (!queryText) {- return;- }- if (recallQuery.truncated) {- verboseRoutingInfo(- `openviking: recall query truncated (` +- `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,- );- }-- const prependContextParts: string[] = [];-- if (cfg.autoRecall && queryText.length >= 5) {- const precheck = await quickRecallPrecheck(cfg.baseUrl);- if (!precheck.ok) {- verboseRoutingInfo(- `openviking: skipping auto-recall because precheck failed (${precheck.reason})`,- );- } else {- try {- await withTimeout(- (async () => {- const candidateLimit = Math.max(cfg.recallLimit * 4, 20);- const autoRecallPromises: Promise<FindResult>[] = [- client.find(queryText, {- targetUri: "viking://user/memories",- limit: candidateLimit,- scoreThreshold: 0,- }, agentId),- client.find(queryText, {- targetUri: "viking://agent/memories",- limit: candidateLimit,- scoreThreshold: 0,- }, agentId),- ];- if (cfg.recallResources) {- autoRecallPromises.push(- client.find(queryText, {- targetUri: "viking://resources",- limit: candidateLimit,- scoreThreshold: 0,- }, agentId),- );- }- const autoRecallSettled = await Promise.allSettled(autoRecallPromises);-- const allMemories: FindResultItem[] = [];- for (const s of autoRecallSettled) {- if (s.status === "fulfilled") {- allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));- } else {- api.logger.warn(`openviking: auto-recall search failed: ${String(s.reason)}`);- }- }-- const uniqueMemories = allMemories.filter((memory, index, self) =>- index === self.findIndex((m) => m.uri === memory.uri)- );- const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);- const processed = postProcessMemories(leafOnly, {- limit: candidateLimit,- scoreThreshold: cfg.recallScoreThreshold,- });- const memories = pickMemoriesForInjection(processed, cfg.recallLimit, queryText);-- if (memories.length > 0) {- const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(- memories,- (uri) => client.read(uri, agentId),- {- recallPreferAbstract: cfg.recallPreferAbstract,- recallMaxInjectedChars: cfg.recallMaxInjectedChars,- },- );- const memoryContext = memoryLines.join("\n");- if (memoryLines.length === 0) {- verboseRoutingInfo(- `openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${cfg.recallMaxInjectedChars}`,- );- return;- }- verboseRoutingInfo(- `openviking: injecting ${memoryLines.length} memories (${memoryContext.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${cfg.recallMaxInjectedChars})`,- );- verboseRoutingInfo(- `openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,- );- prependContextParts.push(- "<relevant-memories>\nThe following OpenViking memories may be relevant:\n" +- `${memoryContext}\n` +- "</relevant-memories>",- );- }- })(),- AUTO_RECALL_TIMEOUT_MS,- "openviking: auto-recall search timeout",- );- } catch (err) {- api.logger.warn(`openviking: auto-recall failed: ${String(err)}`);- }- }- }-- if (prependContextParts.length > 0) {- return {- prependContext: prependContextParts.join("\n\n"),- };- }- });api.on("agent_end", async (_event: unknown, ctx?: HookAgentContext) => {rememberSessionAgentId(ctx ?? {});});@@ -1612,7 +1442,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {return contextEngineRef;});api.logger.info(- "openviking: registered context-engine (before_prompt_build=auto-recall, afterTurn=auto-capture, assemble=archive+active, session→OV id=uuid-or-sha256 + diag/Phase2 options)",+ "openviking: registered context-engine (assemble=archive+active+auto-recall, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)",);} else {api.logger.warn(@@ -1637,99 +1467,4 @@ const mergeFindResults = (results: FindResult[]): FindResult => {},};-/** Estimate token count using chars/4 heuristic for diagnostics. */-export function estimateTokenCount(text: string): number {- if (!text) return 0;- return Math.ceil(text.length / 4);-}--export type BuildMemoryLinesOptions = {- recallPreferAbstract: boolean;-};--async function resolveMemoryContent(- item: FindResultItem,- readFn: (uri: string) => Promise<string>,- options: BuildMemoryLinesOptions,-): Promise<string> {- let content: string;-- if (options.recallPreferAbstract && item.abstract?.trim()) {- content = item.abstract.trim();- } else if (item.level === 2) {- try {- const fullContent = await readFn(item.uri);- content =- fullContent && typeof fullContent === "string" && fullContent.trim()- ? fullContent.trim()- : (item.abstract?.trim() || item.uri);- } catch {- content = item.abstract?.trim() || item.uri;- }- } else {- content = item.abstract?.trim() || item.uri;- }-- return content;-}--export async function buildMemoryLines(- memories: FindResultItem[],- readFn: (uri: string) => Promise<string>,- options: BuildMemoryLinesOptions,-): Promise<string[]> {- const lines: string[] = [];- for (const item of memories) {- const content = await resolveMemoryContent(item, readFn, options);- lines.push(`- [${item.category ?? "memory"}] ${content}`);- }- return lines;-}--export type BuildMemoryLinesWithBudgetOptions = BuildMemoryLinesOptions & {- recallMaxInjectedChars?: number;- recallTokenBudget?: number;-};--/**- * Build memory lines with a character budget constraint.- *- * Individual memories are never truncated. A memory that cannot fit within the- * remaining character budget is skipped so only complete memory entries are- * injected.- */-export async function buildMemoryLinesWithBudget(- memories: FindResultItem[],- readFn: (uri: string) => Promise<string>,- options: BuildMemoryLinesWithBudgetOptions,-): Promise<{ lines: string[]; estimatedTokens: number }> {- const charBudget = options.recallMaxInjectedChars ?? options.recallTokenBudget ?? 0;- const lines: string[] = [];- let totalTokens = 0;- let totalChars = 0;-- for (const item of memories) {- if (totalChars >= charBudget) {- break;- }-- const content = await resolveMemoryContent(item, readFn, options);- const line = `- [${item.category ?? "memory"}] ${content}`;- const separatorChars = lines.length > 0 ? 1 : 0;- const projectedChars = totalChars + separatorChars + line.length;-- if (projectedChars > charBudget) {- continue;- }-- const lineTokens = estimateTokenCount(line);-- lines.push(line);- totalTokens += lineTokens;- totalChars = projectedChars;- }-- return { lines, estimatedTokens: totalTokens };-}-export default contextEnginePlugin;diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.jsonindex bf6e895a1..746b37615 100644--- a/examples/openclaw-plugin/install-manifest.json+++ b/examples/openclaw-plugin/install-manifest.json@@ -1,6 +1,6 @@{"manifestVersion": "1.0",- "pluginVersion": "2026.4.9",+ "pluginVersion": "2026.4.33","plugin": {"id": "openviking","kind": "context-engine",@@ -15,6 +15,7 @@],"optional": ["context-engine.ts",+ "auto-recall.ts","client.ts","process-manager.ts","memory-ranking.ts",@@ -33,7 +34,7 @@"omitDev": true},"compatibility": {- "minOpenclawVersion": "2026.3.7",+ "minOpenclawVersion": "2026.4.24","minOpenvikingVersion": "0.2.9"}}diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex 82314f29b..a51ede901 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -126,7 +126,7 @@},"commitTokenThreshold": {"label": "Commit Token Threshold",- "placeholder": "2000",+ "placeholder": "20000","advanced": true,"help": "Minimum estimated pending tokens before auto-commit triggers. Set to 0 to commit every turn."},diff --git a/examples/openclaw-plugin/package-lock.json b/examples/openclaw-plugin/package-lock.jsonindex ae6971e98..421ffa5c7 100644--- a/examples/openclaw-plugin/package-lock.json+++ b/examples/openclaw-plugin/package-lock.json@@ -16,7 +16,7 @@"vitest": "^4.1.0"},"engines": {- "openclaw": ">=2026.3.7"+ "openclaw": ">=2026.4.24"}},"node_modules/@emnapi/core": {diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.jsonindex 6af92dfc2..e01691ec7 100644--- a/examples/openclaw-plugin/package.json+++ b/examples/openclaw-plugin/package.json@@ -16,7 +16,7 @@"test:watch": "vitest"},"engines": {- "openclaw": ">=2026.3.7"+ "openclaw": ">=2026.4.24"},"dependencies": {"@sinclair/typebox": "0.34.48",@@ -27,12 +27,12 @@"./index.ts"],"compat": {- "pluginApi": ">=2026.3.7",- "minGatewayVersion": "2026.3.7"+ "pluginApi": ">=2026.4.24",+ "minGatewayVersion": "2026.4.24"},"build": {- "openclawVersion": "2026.3.7",- "pluginSdkVersion": "2026.3.7"+ "openclawVersion": "2026.4.24",+ "pluginSdkVersion": "2026.4.24"}},"devDependencies": {diff --git a/examples/openclaw-plugin/runtime-utils.ts b/examples/openclaw-plugin/runtime-utils.tsindex 87fe2f3e3..953e7cb1e 100644--- a/examples/openclaw-plugin/runtime-utils.ts+++ b/examples/openclaw-plugin/runtime-utils.ts@@ -1,4 +1,4 @@-import type { ChildProcess, SpawnOptions } from "node:child_process";+import type { ChildProcess, ExecSyncOptionsWithStringEncoding, SpawnOptions } from "node:child_process";const cp: typeof import("node:child_process") = require("node:child_process");@@ -15,9 +15,9 @@ export function launchProcess(export function runSync(command: string,- options: { encoding: "utf-8"; shell?: string | boolean; env?: NodeJS.ProcessEnv },+ options: ExecSyncOptionsWithStringEncoding,): string {- return _execSync(command, options) as string;+ return _execSync(command, options);}const _env = globalThis["process"];diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.jsindex 1b6183767..99b9f83bc 100755--- a/examples/openclaw-plugin/setup-helper/install.js+++ b/examples/openclaw-plugin/setup-helper/install.js@@ -47,6 +47,7 @@ const FALLBACK_LEGACY = {id: "memory-openviking",kind: "memory",slot: "memory",+ minOpenclawVersion: "2026.3.7",required: ["index.ts", "config.ts", "openclaw.plugin.json", "package.json"],optional: ["package-lock.json", ".gitignore"],};@@ -57,15 +58,19 @@ const FALLBACK_CURRENT = {id: "openviking",kind: "context-engine",slot: "contextEngine",+ minOpenclawVersion: "2026.4.24",required: ["index.ts", "config.ts", "package.json", "openclaw.plugin.json"],optional: ["context-engine.ts",+ "auto-recall.ts","client.ts","process-manager.ts","memory-ranking.ts","text-utils.ts","tool-call-id.ts","session-transcript-repair.ts",+ "runtime-utils.ts",+ "commands/setup.ts","tsconfig.json","package-lock.json",".gitignore",@@ -702,7 +707,7 @@ async function resolvePluginConfig() {}}- resolvedMinOpenclawVersion = compatVer || "2026.3.7";+ resolvedMinOpenclawVersion = compatVer || fallback.minOpenclawVersion || "2026.3.7";resolvedMinOpenvikingVersion = "";}diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.mdindex fc18b0c44..d4f9e732f 100644--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md@@ -10,7 +10,7 @@ description: OpenViking long-term memory plugin guide. Once installed, the plugi- **Auto-Capture**: At `afterTurn` (end of one user turn run), automatically extracts memories from user/assistant messages- `semantic` mode: captures all qualifying user text, relying on OpenViking's extraction pipeline to filter- `keyword` mode: only captures text matching trigger words (e.g. "remember", "preference", etc.)-- **Auto-Recall**: At `before_prompt_build`, automatically searches for relevant memories and injects them into context+- **Auto-Recall**: In `assemble()`, automatically searches for relevant memories and prepends them to the current user message context## Available Toolsdiff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.tsindex 1d007bb2c..70027b4bb 100644--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts@@ -108,6 +108,7 @@ describe("context-engine assemble()", () => {const liveMessages = [{ role: "user", content: "fallback live message" }];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-1",messages: liveMessages,tokenBudget: 4096,@@ -180,6 +181,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-running",messages: [],});@@ -240,6 +242,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-missing-id",messages: [],});@@ -268,6 +271,7 @@ describe("context-engine assemble()", () => {});await engine.assemble({+ prompt: "current user prompt",sessionId: "session-with-sender",messages: [{ role: "user", content: "hello" }],runtimeContext: { senderId: "telegram:12345" },@@ -306,6 +310,7 @@ describe("context-engine assemble()", () => {];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-fallback",messages: liveMessages,tokenBudget: 1024,@@ -347,6 +352,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-budgeted",messages: [],tokenBudget: 1024,diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.tsindex 43eecc76b..dfea626bf 100644--- a/examples/openclaw-plugin/tests/ut/config.test.ts+++ b/examples/openclaw-plugin/tests/ut/config.test.ts@@ -35,6 +35,15 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.recallTokenBudget).toBe(4000);});+ it("honors explicit recallPreferAbstract=false without changing the default", () => {+ const cfgDefault = memoryOpenVikingConfigSchema.parse({});+ const cfgFalse = memoryOpenVikingConfigSchema.parse({ recallPreferAbstract: false });+ const cfgTrue = memoryOpenVikingConfigSchema.parse({ recallPreferAbstract: true });+ expect(cfgDefault.recallPreferAbstract).toBe(false);+ expect(cfgFalse.recallPreferAbstract).toBe(false);+ expect(cfgTrue.recallPreferAbstract).toBe(true);+ });+it("uses recallMaxInjectedChars as the canonical auto-recall character budget", () => {const cfg = memoryOpenVikingConfigSchema.parse({recallMaxInjectedChars: 1234,diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex d71a05cf0..52c9813f8 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -47,6 +47,8 @@ function makeEngine(const logger = makeLogger();const client = {getSessionContext: vi.fn().mockResolvedValue(contextResult),+ find: vi.fn().mockResolvedValue({ memories: [], resources: [], total: 0 }),+ read: vi.fn().mockResolvedValue(""),} as unknown as OpenVikingClient;const getClient = vi.fn().mockResolvedValue(client);const resolveAgentId = vi.fn((sessionId: string) => `agent:${sessionId}`);@@ -69,7 +71,11 @@ function makeEngine(return {engine,- client: client as unknown as { getSessionContext: ReturnType<typeof vi.fn> },+ client: client as unknown as {+ getSessionContext: ReturnType<typeof vi.fn>;+ find: ReturnType<typeof vi.fn>;+ read: ReturnType<typeof vi.fn>;+ },getClient,logger,resolveAgentId,@@ -77,6 +83,195 @@ function makeEngine(}describe("context-engine assemble()", () => {+ it("prepends auto-recall to the latest user message during transformContext", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "This OV context must not be rebuilt during transformContext.",+ pre_archive_abstracts: [],+ messages: [+ {+ id: "stored-current-user",+ role: "user",+ created_at: "2026-04-30T00:00:00Z",+ parts: [{ type: "text", text: "stale stored prompt" }],+ },+ ],+ estimatedTokens: 12,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ recallPreferAbstract: true,+ },+ },+ );+ client.find+ .mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/default/memories/rust-pref",+ level: 2,+ category: "preferences",+ abstract: "User prefers Rust for backend tasks.",+ score: 0.93,+ },+ ],+ total: 1,+ })+ .mockResolvedValueOnce({ memories: [], total: 0 });++ const sourceMessages = [+ { role: "user", content: "[Session History Summary]\nOlder archive summary." },+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "what backend language should we use?" },+ ];++ const result = await engine.assemble({+ sessionId: "session-transform",+ messages: sourceMessages,+ });++ expect(client.getSessionContext).not.toHaveBeenCalled();+ expect(result.messages).toHaveLength(sourceMessages.length);+ expect(result.messages[0]).toBe(sourceMessages[0]);+ expect(result.messages[1]).toBe(sourceMessages[1]);+ expect(result.messages[2]?.role).toBe("user");+ expect(result.messages[2]?.content).toMatch(/^<relevant-memories>/);+ expect(result.messages[2]?.content).toContain("Source: openviking-auto-recall");+ expect(result.messages[2]?.content).toContain("User prefers Rust for backend tasks.");+ expect(result.messages[2]?.content).toContain("what backend language should we use?");+ expect(result.systemPromptAddition).toBeUndefined();+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("passes through transformContext messages when the latest message is not user", async () => {+ const { engine, getClient } = makeEngine(+ {+ latest_archive_overview: "unused",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ },+ },+ );+ const sourceMessages = [+ { role: "user", content: "run the tool" },+ {+ role: "assistant",+ content: [{ type: "toolCall", id: "tool_1", name: "bash", arguments: {} }],+ },+ ];++ const result = await engine.assemble({+ sessionId: "session-tool-loop",+ messages: sourceMessages,+ });++ expect(getClient).not.toHaveBeenCalled();+ expect(result.messages).toBe(sourceMessages);+ expect(result.estimatedTokens).toBe(roughEstimate(sourceMessages));+ });++ it("passes through transformContext latest user messages when auto-recall is disabled", async () => {+ const { engine, getClient } = makeEngine({+ latest_archive_overview: "unused",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ });+ const sourceMessages = [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "what backend language should we use?" },+ ];++ const result = await engine.assemble({+ sessionId: "session-auto-recall-disabled",+ messages: sourceMessages,+ });++ expect(getClient).not.toHaveBeenCalled();+ expect(result.messages).toBe(sourceMessages);+ expect(result.estimatedTokens).toBe(roughEstimate(sourceMessages));+ });++ it("treats prompt-less assemble with availableTools as main assemble", async () => {+ const { engine, client, resolveAgentId } = makeEngine({+ latest_archive_overview: "# Session Summary\nPreviously discussed repository setup.",+ pre_archive_abstracts: [+ {+ archive_id: "archive_001",+ abstract: "Previously discussed repository setup.",+ },+ ],+ messages: [+ {+ id: "msg_main_no_prompt",+ role: "assistant",+ created_at: "2026-03-24T00:00:00Z",+ parts: [{ type: "text", text: "Stored answer from OpenViking." }],+ },+ ],+ estimatedTokens: 120,+ stats: {+ ...makeStats(),+ totalArchives: 1,+ includedArchives: 1,+ archiveTokens: 40,+ activeTokens: 80,+ },+ });++ const liveMessages = [{ role: "user", content: "fallback live message" }];+ const result = await engine.assemble({+ sessionId: "session-main-no-prompt",+ messages: liveMessages,+ tokenBudget: 4096,+ availableTools: new Set(),+ });++ expect(resolveAgentId).toHaveBeenCalledWith(+ "session-main-no-prompt",+ undefined,+ "session-main-no-prompt",+ );+ expect(client.getSessionContext).toHaveBeenCalledWith(+ "session-main-no-prompt",+ 4096,+ "agent:session-main-no-prompt",+ );+ expect(client.find).not.toHaveBeenCalled();+ expect(result.messages[0]).toEqual({+ role: "user",+ 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." }],+ });+ expect(result.systemPromptAddition).toContain("Session Context Guide");+ });+it("assembles summary archive and completed tool parts into agent messages", async () => {const { engine, client, resolveAgentId } = makeEngine({latest_archive_overview: "# Session Summary\nPreviously discussed repository setup.",@@ -117,6 +312,7 @@ describe("context-engine assemble()", () => {const liveMessages = [{ role: "user", content: "fallback live message" }];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-1",messages: liveMessages,tokenBudget: 4096,@@ -176,6 +372,7 @@ describe("context-engine assemble()", () => {const liveMessages = [{ role: "user", content: "fallback live message" }];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "runtime-session",sessionKey: "agent:main:cron:nightly:run:1",messages: liveMessages,@@ -219,6 +416,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-running",messages: [],});@@ -279,6 +477,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-missing-id",messages: [],});@@ -322,6 +521,7 @@ describe("context-engine assemble()", () => {];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-fallback",messages: liveMessages,tokenBudget: 1024,@@ -348,6 +548,7 @@ describe("context-engine assemble()", () => {];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-new-user",messages: liveMessages,});@@ -383,6 +584,7 @@ describe("context-engine assemble()", () => {];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-empty-parts",messages: liveMessages,});@@ -427,6 +629,7 @@ describe("context-engine assemble()", () => {});const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-budgeted",messages: [],tokenBudget: 1024,@@ -457,6 +660,7 @@ describe("context-engine assemble()", () => {];const result = await engine.assemble({+ prompt: "current user prompt",sessionId: "session-error",messages: liveMessages,});@@ -491,7 +695,11 @@ describe("context-engine assemble()", () => {stats: { ...makeStats(), activeTokens: 50 },});- const result = await engine.assemble({ sessionId: "session-tool-only", messages: [] });+ const result = await engine.assemble({+ prompt: "current user prompt",+ sessionId: "session-tool-only",+ messages: [],+ });const emptyContentMsg = result.messages.find((m) => typeof m.content === "string" && m.content === "",diff --git a/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts b/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.tsindex 3eb18ae63..f90db4566 100644--- a/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts+++ b/examples/openclaw-plugin/tests/ut/plugin-bypass-session-patterns.test.ts@@ -39,26 +39,31 @@ function setupPlugin(pluginConfig?: Record<string, unknown>) {}describe("plugin bypass session patterns", () => {- it("bypasses before_prompt_build before any OV client work", async () => {- const { handlers, logger } = setupPlugin({+ it("bypasses context-engine assemble before any OV client work", async () => {+ const { registerContextEngine, logger } = setupPlugin({bypassSessionPatterns: ["agent:*:cron:**"],});- const hook = handlers.get("before_prompt_build");- expect(hook).toBeTruthy();+ const factory = registerContextEngine.mock.calls[0]?.[1] as (() => {+ assemble: (params: {+ sessionId: string;+ sessionKey?: string;+ prompt?: string;+ messages: Array<{ role: string; content: string }>;+ }) => Promise<{ messages: Array<{ role: string; content: string }> }>;+ }) | undefined;+ expect(factory).toBeTruthy();+ const engine = factory!();+ const liveMessages = [{ role: "user", content: "Alice: hi\nBob: hello" }];- const result = await hook!(- {- messages: [{ role: "user", content: "Alice: hi\nBob: hello" }],- prompt: "Alice: hi\nBob: hello",- },- {- sessionId: "runtime-session",- sessionKey: "agent:main:cron:nightly:run:1",- },- );+ const result = await engine.assemble({+ sessionId: "runtime-session",+ sessionKey: "agent:main:cron:nightly:run:1",+ prompt: "Alice: hi\nBob: hello",+ messages: liveMessages,+ });- expect(result).toBeUndefined();+ expect(result.messages).toBe(liveMessages);expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining("failed to get client"),);diff --git a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.tsindex dbe28c08b..dba0d3347 100644--- a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts+++ b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts@@ -212,20 +212,10 @@ describe("plugin normal flow with healthy backend", () => {await service!.start();- const beforePromptBuild = handlers.get("before_prompt_build");- expect(beforePromptBuild).toBeTruthy();- const hookResult = await beforePromptBuild!(- { messages: [{ role: "user", content: "what backend language should we use?" }] },- { agentId: "main", sessionId: "session-normal", sessionKey: "agent:main:normal" },- );-- expect(hookResult).toMatchObject({- prependContext: expect.stringContaining("User prefers Rust for backend tasks."),- });-const contextEngine = contextEngineFactory!() as {assemble: (params: {sessionId: string;+ prompt?: string;messages: Array<{ role: string; content: string }>;}) => Promise<{ messages: Array<{ role: string; content: unknown }> }>;afterTurn: (params: {@@ -238,6 +228,7 @@ describe("plugin normal flow with healthy backend", () => {const assembled = await contextEngine.assemble({sessionId: "session-normal",+ prompt: "what backend language should we use?",messages: [{ role: "user", content: "fallback" }],});@@ -250,6 +241,20 @@ describe("plugin normal flow with healthy backend", () => {content: [{ type: "text", text: "Stored answer from OpenViking." }],});+ const transformed = await contextEngine.assemble({+ sessionId: "session-normal",+ messages: [+ ...(assembled.messages as Array<{ role: string; content: string }>),+ { role: "user", content: "what backend language should we use?" },+ ],+ });++ const latest = transformed.messages.at(-1);+ expect(latest?.role).toBe("user");+ expect(String(latest?.content)).toContain("Source: openviking-auto-recall");+ expect(String(latest?.content)).toContain("User prefers Rust for backend tasks.");+ expect(String(latest?.content)).toContain("what backend language should we use?");+await contextEngine.afterTurn({sessionId: "session-normal",sessionFile: "",diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex 1e846013a..802b7b3bb 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -768,16 +768,16 @@ describe("Plugin registration", () => {);});- it("registers hooks: session_start, session_end, before_prompt_build, agent_end, before_reset, after_compaction", () => {+ it("registers hooks: session_start, session_end, agent_end, before_reset, after_compaction", () => {const { api } = setupPlugin();contextEnginePlugin.register(api as any);const hookNames = api.on.mock.calls.map((c: unknown[]) => c[0]);expect(hookNames).toContain("session_start");expect(hookNames).toContain("session_end");- expect(hookNames).toContain("before_prompt_build");expect(hookNames).toContain("agent_end");expect(hookNames).toContain("before_reset");expect(hookNames).toContain("after_compaction");+ expect(hookNames).not.toContain("before_prompt_build");});it("plugin has correct metadata", () => {diff --git a/openviking/session/memory_extractor.py b/openviking/session/memory_extractor.pyindex de765097e..b09f1502e 100644--- a/openviking/session/memory_extractor.py+++ b/openviking/session/memory_extractor.py@@ -283,7 +283,7 @@ class MemoryExtractor:config = get_openviking_config()output_language = resolve_with_override(config,- lambda fb: self._detect_output_language(messages, fallback_language=fb),+ lambda: self._detect_output_language(messages, fallback_language="en"),)history_summary = str(context.get("summary") or "")