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
feat(openclaw): add runtime query config (#2646)
Mingjian Que740b7fcbe789
diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsindex 2e6fee244..bfaafbd59 100644--- a/examples/openclaw-plugin/auto-recall.ts+++ b/examples/openclaw-plugin/auto-recall.ts@@ -1,5 +1,6 @@import type { FindResult, FindResultItem, OpenVikingClient } from "./client.js";import type { ParsedMemoryOpenVikingConfig } from "./config.js";+import type { EffectiveQueryConfig } from "./query-config.js";import {pickMemoriesForInjection,postProcessMemories,@@ -523,6 +524,7 @@ export async function buildLongTermMemoryRecallContext(params: {ovSessionId?: string;rawUserTextPreview?: string;queryTruncated?: boolean;+ queryConfig?: EffectiveQueryConfig;}): Promise<{ section?: string; memoryCount: number; estimatedTokens: number }> {const { cfg, client, agentId, peerId, queryText, logger, verbose } = params;@@ -538,8 +540,13 @@ export async function buildLongTermMemoryRecallContext(params: {return withTimeout((async () => {- const candidateLimit = Math.max(cfg.recallLimit * 4, 20);- const searchPlan = resolveRecallSearchPlan(cfg.recallTargetTypes, {+ const queryConfig = params.queryConfig;+ const candidateLimit = queryConfig?.candidateLimit ?? Math.max(cfg.recallLimit * 4, 20);+ const scoreThreshold = queryConfig?.scoreThreshold ?? cfg.recallScoreThreshold;+ const recallLimit = queryConfig?.recallLimit ?? cfg.recallLimit;+ const maxInjectedChars = queryConfig?.maxInjectedChars ?? cfg.recallMaxInjectedChars;+ const recallPreferAbstract = queryConfig?.recallPreferAbstract ?? cfg.recallPreferAbstract;+ const searchPlan = resolveRecallSearchPlan(queryConfig?.resourceTypes ?? cfg.recallTargetTypes, {ovSessionId: params.ovSessionId,agentId,});@@ -624,9 +631,13 @@ export async function buildLongTermMemoryRecallContext(params: {const leafOnly = uniqueMemories.filter((m) => (!m.level || m.level === 2) && !isExperienceMemory(m));const processed = postProcessMemories(leafOnly, {limit: candidateLimit,- scoreThreshold: cfg.recallScoreThreshold,+ scoreThreshold,});- const memories = pickMemoriesForInjection(processed, cfg.recallLimit, queryText);+ const memories = pickMemoriesForInjection(processed, recallLimit, queryText, scoreThreshold, queryConfig ? {+ weights: queryConfig.rankingWeights,+ categoryWeights: queryConfig.categoryWeights,+ resourceTypeWeights: queryConfig.resourceTypeWeights,+ } : undefined);const recordTrace = (injectedMemories: FindResultItem[], injectedCount: number, estimatedTokens?: number) => {params.traceRecorder?.record({schemaVersion: "1.0",@@ -671,15 +682,15 @@ export async function buildLongTermMemoryRecallContext(params: {memories,(uri) => client.read(uri, peerId),{- recallPreferAbstract: cfg.recallPreferAbstract,- recallMaxInjectedChars: cfg.recallMaxInjectedChars,+ recallPreferAbstract,+ recallMaxInjectedChars: maxInjectedChars,includeUri: true,},);if (memoryLines.length === 0) {verbose?.(- `openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${cfg.recallMaxInjectedChars}`,+ `openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${maxInjectedChars}`,);recordTrace([], 0, 0);return { memoryCount: 0, estimatedTokens: 0 };@@ -687,7 +698,7 @@ export async function buildLongTermMemoryRecallContext(params: {const section = buildLongTermMemorySection(memoryLines);verbose?.(- `openviking: injecting ${memoryLines.length} memories (${section.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${cfg.recallMaxInjectedChars})`,+ `openviking: injecting ${memoryLines.length} memories (${section.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${maxInjectedChars})`,);verbose?.(`openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex 18b930b44..e01c2e700 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -79,6 +79,8 @@ export type MemoryOpenVikingConfig = {enabledTools?: string[] | string;/** Agent-visible tool blocklist applied after enabledTools. Supports exact tool names or groups. */disabledTools?: string[] | string;+ /** Optional JSON file path for runtime query config overrides. Empty means in-memory only. */+ runtimeQueryConfigPath?: string;agentExperience?: {enabled?: boolean;recallLimit?: number;@@ -415,6 +417,7 @@ export const memoryOpenVikingConfigSchema = {"enableAddResourceTool","enabledTools","disabledTools",+ "runtimeQueryConfigPath","agentExperience",],"openviking config",@@ -586,6 +589,10 @@ export const memoryOpenVikingConfigSchema = {enableAddResourceTool: cfg.enableAddResourceTool === true,enabledTools,disabledTools,+ runtimeQueryConfigPath:+ typeof cfg.runtimeQueryConfigPath === "string" && cfg.runtimeQueryConfigPath.trim()+ ? expandHomeDir(cfg.runtimeQueryConfigPath.trim())+ : "",agentExperience: {enabled:typeof agentExperienceRaw.enabled === "boolean"@@ -801,5 +808,11 @@ export const memoryOpenVikingConfigSchema = {help: "Agent-visible tool blocklist applied after enabledTools. Accepts the same tool names or groups.",advanced: true,},+ runtimeQueryConfigPath: {+ label: "Runtime Query Config Path",+ placeholder: "~/.openclaw/openviking/runtime-query-config.json",+ help: "Optional JSON file for /ov-query-config runtime overrides. Empty keeps overrides in memory only.",+ advanced: true,+ },},};diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex f0a5bbee3..8379ef6c2 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";import { DEFAULT_PHASE2_POLL_TIMEOUT_MS } from "./client.js";import type { OpenVikingClient, OVMemoryPolicy, OVMessage } from "./client.js";import type { MemoryOpenVikingConfig, ParsedMemoryOpenVikingConfig } from "./config.js";+import type { RuntimeQueryConfigStore } from "./query-config.js";import {AUTO_RECALL_SOURCE_MARKER,buildGatedAgentExperienceRecallContext,@@ -1092,6 +1093,7 @@ export function createMemoryOpenVikingContextEngine(params: {sessionKey?: string;ovSessionId?: string;}) => void;+ queryConfigStore?: RuntimeQueryConfigStore;traceRecorder?: { record(entry: RecallTraceEntry): void };}): ContextEngineWithCommit {const {@@ -1103,6 +1105,7 @@ export function createMemoryOpenVikingContextEngine(params: {getClient,resolveAgentId,rememberSessionAgentId,+ queryConfigStore,traceRecorder,} = params;@@ -1407,6 +1410,14 @@ export function createMemoryOpenVikingContextEngine(params: {`chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,);}+ const effectiveQuery = queryConfigStore+ ? await queryConfigStore.getEffective({+ peerId: agentId,+ sessionId: assembleParams.sessionId,+ sessionKey,+ ovSessionId: OVSessionId,+ })+ : undefined;const experienceRecall = experienceRecallEnabled? await buildGatedAgentExperienceRecallContext({cfg,@@ -1435,6 +1446,7 @@ export function createMemoryOpenVikingContextEngine(params: {ovSessionId: OVSessionId,rawUserTextPreview: recallQuery.query,queryTruncated: recallQuery.truncated,+ queryConfig: effectiveQuery,}): { memoryCount: 0, estimatedTokens: 0 };const longTermRecallWithQuery: AssembleRecall = { ...longTermRecall, queryChars: recallQuery.finalChars };diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex 0cfe8a16b..46eced7f0 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -54,6 +54,12 @@ import {type RecallTraceResult,type RecallTraceSource,} from "./recall-trace.js";+import {+ RuntimeQueryConfigStore,+ normalizeRuntimeQueryParams,+ type QueryConfigContext,+ type RuntimeQueryParams,+} from "./query-config.js";export {buildMemoryLines,buildMemoryLinesWithBudget,@@ -438,6 +444,68 @@ function getBoolFlag(flags: Map<string, string | boolean>, name: string): booleareturn flags.get(name) === true;}+function getOptionalBoolFlag(flags: Map<string, string | boolean>, name: string): boolean | undefined {+ const value = flags.get(name);+ if (value === undefined) return undefined;+ if (value === true) return true;+ if (value === false) return false;+ const normalized = value.trim().toLowerCase();+ if (["1", "true", "yes", "on"].includes(normalized)) return true;+ if (["0", "false", "no", "off"].includes(normalized)) return false;+ throw new Error(`--${name} must be a boolean`);+}++function parseNumberMapFlag(flags: Map<string, string | boolean>, name: string): Record<string, number> | undefined {+ const raw = getStringFlag(flags, name);+ if (!raw) return undefined;+ const result: Record<string, number> = {};+ for (const item of raw.split(",")) {+ const [key, rawValue, ...rest] = item.split("=");+ const trimmedKey = key?.trim();+ const trimmedValue = rawValue?.trim();+ if (!trimmedKey || !trimmedValue || rest.length > 0) {+ throw new Error(`--${name} must use key=value pairs separated by commas`);+ }+ const value = Number(trimmedValue);+ if (!Number.isFinite(value)) {+ throw new Error(`--${name} value for ${trimmedKey} must be a number`);+ }+ result[trimmedKey] = value;+ }+ return result;+}++function parseQueryConfigPatch(flags: Map<string, string | boolean>): RuntimeQueryParams {+ const patch: RuntimeQueryParams = {};+ const numberFields: Array<[string, keyof RuntimeQueryParams]> = [+ ["recallLimit", "recallLimit"],+ ["candidateLimit", "candidateLimit"],+ ["candidateMultiplier", "candidateMultiplier"],+ ["scoreThreshold", "scoreThreshold"],+ ["maxInjectedChars", "maxInjectedChars"],+ ["ovSearchLimit", "ovSearchLimit"],+ ];+ for (const [flag, field] of numberFields) {+ if (flags.has(flag)) {+ (patch as Record<string, unknown>)[field] = getNumberFlag(flags, flag);+ }+ }+ const resourceTypes = getStringFlag(flags, "resourceTypes");+ if (resourceTypes) patch.resourceTypes = resourceTypes;+ const targetUri = getStringFlag(flags, "targetUri");+ if (targetUri) patch.targetUri = targetUri;+ const recallPreferAbstract = getOptionalBoolFlag(flags, "recallPreferAbstract");+ if (recallPreferAbstract !== undefined) patch.recallPreferAbstract = recallPreferAbstract;++ const rankingWeights = parseNumberMapFlag(flags, "weight") ?? parseNumberMapFlag(flags, "rankingWeights");+ if (rankingWeights) patch.rankingWeights = rankingWeights;+ const categoryWeights = parseNumberMapFlag(flags, "categoryWeight") ?? parseNumberMapFlag(flags, "categoryWeights");+ if (categoryWeights) patch.categoryWeights = categoryWeights;+ const resourceTypeWeights = parseNumberMapFlag(flags, "resourceTypeWeight") ?? parseNumberMapFlag(flags, "resourceTypeWeights");+ if (resourceTypeWeights) patch.resourceTypeWeights = resourceTypeWeights as RuntimeQueryParams["resourceTypeWeights"];+ return patch;+}+function createTraceId(source: RecallTraceSource): string {return `${source}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;}@@ -784,6 +852,17 @@ const contextEnginePlugin = {queryMaxDays: cfg.traceRecallQueryMaxDays,}): undefined;+ const queryConfigStore = new RuntimeQueryConfigStore({+ staticConfig: cfg,+ path: cfg.runtimeQueryConfigPath || undefined,+ });+ const queryConfigReady = queryConfigStore.load();+ const toQueryConfigContext = (session: PluginSessionRouting): QueryConfigContext => ({+ peerId: session.agentId,+ sessionId: session.sessionId,+ sessionKey: session.sessionKey,+ ovSessionId: session.ovSessionId,+ });const isBypassedSession = (ctx?: {sessionId?: string;@@ -1611,22 +1690,29 @@ const contextEnginePlugin = {if (!query) {throw new Error("query is required");}- const limit = Math.max(1, Math.floor(input.limit ?? 10));+ const effectiveQuery = traceCtx+ ? await queryConfigStore.getEffective(toQueryConfigContext(traceCtx), {+ ovSearchLimit: input.limit,+ targetUri: input.uri,+ })+ : undefined;+ const limit = Math.max(1, Math.floor(input.limit ?? effectiveQuery?.ovSearchLimit ?? 10));+ const searchUri = input.uri ?? effectiveQuery?.targetUri;const client = await getClient();let result: FindResult;const searches: RecallTraceEntry["searches"] = [];- if (input.uri) {+ if (searchUri) {const started = Date.now();- result = await client.find(query, { targetUri: input.uri, limit, actorPeerId });+ result = await client.find(query, { targetUri: searchUri, limit, actorPeerId });const items = [...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),...(result.resources ?? []).map((item) => toTraceResult(item, "resource")),...(result.skills ?? []).map((item) => toTraceResult(item, "skill")),].slice(0, cfg.traceRecallMaxResultsPerSearch);searches.push({- resourceType: inferRecallResourceType(input.uri) ?? "resource",- targetUriInput: input.uri,- targetUriResolved: input.uri,+ resourceType: inferRecallResourceType(searchUri) ?? "resource",+ targetUriInput: searchUri,+ targetUriResolved: searchUri,limit,durationMs: Date.now() - started,total: result.total ?? items.length,@@ -1747,12 +1833,13 @@ const contextEnginePlugin = {},});return {- content: [{ type: "text" as const, text: formatOVSearchText(query, input.uri, result) }],+ content: [{ type: "text" as const, text: formatOVSearchText(query, searchUri, result) }],details: {action: "searched",query,- uri: input.uri,+ uri: searchUri,peer_id: actorPeerId ?? null,+ queryConfig: effectiveQuery,memories: result.memories ?? [],resources: result.resources ?? [],skills: result.skills ?? [],@@ -2099,6 +2186,65 @@ const contextEnginePlugin = {},});+ api.registerCommand?.({+ name: "ov-query-config",+ description: "Get or update OpenViking runtime query config.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ if (isBypassedSession(ctx)) {+ const bypassed = makeBypassedToolResult("ov-query-config");+ return { text: bypassed.content[0]!.text, details: bypassed.details };+ }+ const parsed = parseFlagArgs(ctx.args ?? "");+ const action = parsed.positionals[0] ?? "get";+ const rawScope = getStringFlag(parsed.flags, "scope");+ const scope: "claw" | "session" =+ rawScope === "peer" || rawScope === "claw" ? "claw" : "session";+ const session = resolvePluginSessionRouting(ctx);+ const queryCtx = toQueryConfigContext(session);++ if (action === "get") {+ const effective = await queryConfigStore.getEffective(queryCtx);+ return { text: JSON.stringify({ scope, effective }, null, 2), details: { scope, effective } };+ }+ if (action === "set") {+ const patch = parseQueryConfigPatch(parsed.flags);+ const { params, warnings } = normalizeRuntimeQueryParams(patch as RuntimeQueryParams & Record<string, unknown>);+ if (Object.keys(params).length === 0) {+ throw new Error("No query config parameters provided for /ov-query-config set");+ }+ await queryConfigStore.set(scope, queryCtx, params);+ const effective = await queryConfigStore.getEffective(queryCtx);+ return {+ text: `Updated OpenViking query config (${scope}).${warnings.length ? ` Warnings: ${warnings.join("; ")}` : ""}`,+ details: { scope, params, warnings, effective },+ };+ }+ if (action === "unset") {+ const fields = parsed.positionals.slice(1);+ if (fields.length === 0) {+ throw new Error("Usage: /ov-query-config unset <field...> [--scope session|peer]");+ }+ await queryConfigStore.unset(scope, queryCtx, fields);+ const effective = await queryConfigStore.getEffective(queryCtx);+ return {+ text: `Unset OpenViking query config fields (${scope}): ${fields.join(", ")}`,+ details: { scope, fields, effective },+ };+ }+ if (action === "reset") {+ await queryConfigStore.reset(scope, queryCtx);+ const effective = await queryConfigStore.getEffective(queryCtx);+ return { text: `Reset OpenViking query config (${scope}).`, details: { scope, effective } };+ }+ throw new Error("Usage: /ov-query-config get|set|unset|reset [--scope session|peer] [--recallLimit N] [--candidateLimit N] [--scoreThreshold N] [--resourceTypes user,resource]");+ } catch (err) {+ return { text: `OpenViking query config failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ });+registerOpenVikingTool((ctx: ToolContext) => ({name: "memory_recall",@@ -2127,22 +2273,31 @@ const contextEnginePlugin = {const session = resolvePluginSessionRouting(ctx);const peerId = resolveToolSearchPeerId(ctx, session);const { query } = params as { query: string };- const limit =- typeof (params as { limit?: number }).limit === "number"- ? Math.max(1, Math.floor((params as { limit: number }).limit))- : cfg.recallLimit;- const scoreThreshold =- typeof (params as { scoreThreshold?: number }).scoreThreshold === "number"- ? Math.max(0, Math.min(1, (params as { scoreThreshold: number }).scoreThreshold))- : cfg.recallScoreThreshold;- const targetUri =- typeof (params as { targetUri?: string }).targetUri === "string"- ? (params as { targetUri: string }).targetUri- : undefined;- const requestedResourceTypes = Object.prototype.hasOwnProperty.call(params, "resourceTypes")- ? (params as { resourceTypes?: unknown }).resourceTypes- : undefined;- const requestLimit = Math.max(limit * 4, 20);+ const requestOverrides: RuntimeQueryParams = {};+ if (typeof (params as { limit?: number }).limit === "number") {+ requestOverrides.recallLimit = (params as { limit: number }).limit;+ }+ if (typeof (params as { scoreThreshold?: number }).scoreThreshold === "number") {+ requestOverrides.scoreThreshold = (params as { scoreThreshold: number }).scoreThreshold;+ }+ if (typeof (params as { targetUri?: string }).targetUri === "string") {+ requestOverrides.targetUri = (params as { targetUri: string }).targetUri;+ }+ if (Object.prototype.hasOwnProperty.call(params, "resourceTypes")) {+ requestOverrides.resourceTypes = (params as { resourceTypes?: unknown }).resourceTypes as RuntimeQueryParams["resourceTypes"];+ }+ const effectiveQuery = await queryConfigStore.getEffective(+ toQueryConfigContext(session),+ requestOverrides,+ );+ const limit = effectiveQuery.recallLimit;+ const scoreThreshold = effectiveQuery.scoreThreshold;+ const targetUri = effectiveQuery.targetUri;+ const requestedResourceTypes = effectiveQuery.resourceTypes;+ const requestLimit = effectiveQuery.candidateLimit;+ const recallPreferAbstract = effectiveQuery.sources.recallPreferAbstract === "static"+ ? false+ : effectiveQuery.recallPreferAbstract;const recallClient = await getClient();if (cfg.logFindRequests) {@@ -2263,7 +2418,11 @@ const contextEnginePlugin = {limit: requestLimit,scoreThreshold,});- const memories = pickMemoriesForInjection(processed, limit, query);+ const memories = pickMemoriesForInjection(processed, limit, query, scoreThreshold, {+ weights: effectiveQuery.rankingWeights,+ categoryWeights: effectiveQuery.categoryWeights,+ resourceTypeWeights: effectiveQuery.resourceTypeWeights,+ });const candidateTraceResults = leafOnly.map((item) => toTraceResult(item, inferRecallResourceType(item.uri) === "resource" ? "resource" : "memory")).slice(0, cfg.traceRecallMaxResultsPerSearch);@@ -2322,8 +2481,8 @@ const contextEnginePlugin = {memories,(uri) => recallClient.read(uri, peerId),{- recallPreferAbstract: false,- recallMaxInjectedChars: cfg.recallMaxInjectedChars,+ recallPreferAbstract,+ recallMaxInjectedChars: effectiveQuery.maxInjectedChars,},);if (memoryLines.length === 0) {@@ -2332,7 +2491,7 @@ const contextEnginePlugin = {content: [{type: "text",- text: `No complete OpenViking memories fit recallMaxInjectedChars=${cfg.recallMaxInjectedChars}.`,+ text: `No complete OpenViking memories fit recallMaxInjectedChars=${effectiveQuery.maxInjectedChars}.`,},],details: {@@ -2341,7 +2500,8 @@ const contextEnginePlugin = {total: result.total ?? memories.length,scoreThreshold,requestLimit,- recallMaxInjectedChars: cfg.recallMaxInjectedChars,+ recallMaxInjectedChars: effectiveQuery.maxInjectedChars,+ queryConfig: effectiveQuery,},};}@@ -2359,7 +2519,8 @@ const contextEnginePlugin = {total: result.total ?? memories.length,scoreThreshold,requestLimit,- recallMaxInjectedChars: cfg.recallMaxInjectedChars,+ recallMaxInjectedChars: effectiveQuery.maxInjectedChars,+ queryConfig: effectiveQuery,},};},@@ -3294,6 +3455,7 @@ const contextEnginePlugin = {getClient,resolveAgentId,rememberSessionAgentId,+ queryConfigStore,traceRecorder,});return contextEngineRef;@@ -3312,6 +3474,7 @@ const contextEnginePlugin = {api.registerService({id: "openviking",start: async (ctx?: unknown) => {+ await queryConfigReady;const routeRegistered = registerRecallTraceRoutes(ctx);await (await getClient()).healthCheck().catch(() => {});api.logger.info(diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.jsonindex 311881269..3855fb06e 100644--- a/examples/openclaw-plugin/install-manifest.json+++ b/examples/openclaw-plugin/install-manifest.json@@ -21,6 +21,7 @@"session-transcript-repair.ts","runtime-utils.ts","recall-trace.ts",+ "query-config.ts","commands/setup.ts","plugin/openviking-feature-gates.ts","config/feature-gates.json",diff --git a/examples/openclaw-plugin/memory-ranking.ts b/examples/openclaw-plugin/memory-ranking.tsindex 33ef56954..b5fb99fb6 100644--- a/examples/openclaw-plugin/memory-ranking.ts+++ b/examples/openclaw-plugin/memory-ranking.ts@@ -182,6 +182,28 @@ type RecallQueryProfile = {wantsTemporal: boolean;};+export type RankingWeights = {+ baseScore?: number;+ leaf?: number;+ event?: number;+ preference?: number;+ lexicalOverlapMax?: number;+};++export type RankingOptions = {+ weights?: RankingWeights;+ categoryWeights?: Record<string, number>;+ resourceTypeWeights?: Record<string, number>;+};++const DEFAULT_RANKING_WEIGHTS = {+ baseScore: 1,+ leaf: 0.12,+ event: 0.1,+ preference: 0.08,+ lexicalOverlapMax: 0.2,+};+function buildRecallQueryProfile(query: string): RecallQueryProfile {const text = query.trim();const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) ?? [];@@ -193,7 +215,11 @@ function buildRecallQueryProfile(query: string): RecallQueryProfile {};}-function lexicalOverlapBoost(tokens: string[], text: string): number {+function lexicalOverlapBoost(+ tokens: string[],+ text: string,+ maxBoost = DEFAULT_RANKING_WEIGHTS.lexicalOverlapMax,+): number {if (tokens.length === 0 || !text) {return 0;}@@ -204,18 +230,37 @@ function lexicalOverlapBoost(tokens: string[], text: string): number {matched += 1;}}- return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);+ return Math.min(maxBoost, (matched / Math.min(tokens.length, 4)) * maxBoost);+}++function inferResourceType(item: FindResultItem): string | undefined {+ if (item.uri.startsWith("viking://resources")) return "resource";+ if (item.uri.startsWith("viking://session/")) return "session";+ if (item.uri.startsWith("viking://user/")) return "user";+ if (item.uri.startsWith("viking://agent/")) return "agent";+ return undefined;}-function rankForInjection(item: FindResultItem, query: RecallQueryProfile): number {+function rankForInjection(+ item: FindResultItem,+ query: RecallQueryProfile,+ options?: RankingOptions,+): number {// Keep ranking simple and stable: semantic score + light query-aware boosts.- const baseScore = clampScore(item.score);+ const weights = { ...DEFAULT_RANKING_WEIGHTS, ...(options?.weights ?? {}) };+ const baseScore = clampScore(item.score) * weights.baseScore;const abstract = (item.abstract ?? item.overview ?? "").trim();- const leafBoost = isLeafLikeMemory(item) ? 0.12 : 0;- const eventBoost = query.wantsTemporal && isEventMemory(item) ? 0.1 : 0;- const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? 0.08 : 0;- const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`);- return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost;+ const leafBoost = isLeafLikeMemory(item) ? weights.leaf : 0;+ const eventBoost = query.wantsTemporal && isEventMemory(item) ? weights.event : 0;+ const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? weights.preference : 0;+ const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`, weights.lexicalOverlapMax);+ const category = (item.category ?? "").toLowerCase();+ const categoryBoost = category+ ? (options?.categoryWeights?.[category] ?? options?.categoryWeights?.[item.category ?? ""] ?? 0)+ : 0;+ const resourceType = inferResourceType(item);+ const resourceTypeBoost = resourceType ? (options?.resourceTypeWeights?.[resourceType] ?? 0) : 0;+ return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost + categoryBoost + resourceTypeBoost;}export function pickMemoriesForInjection(@@ -223,13 +268,16 @@ export function pickMemoriesForInjection(limit: number,queryText: string,scoreThreshold: number = 0,+ rankingOptions?: RankingOptions,): FindResultItem[] {if (items.length === 0 || limit <= 0) {return [];}const query = buildRecallQueryProfile(queryText);- const sorted = [...items].sort((a, b) => rankForInjection(b, query) - rankForInjection(a, query));+ const sorted = [...items].sort((a, b) =>+ rankForInjection(b, query, rankingOptions) - rankForInjection(a, query, rankingOptions)+ );const deduped: FindResultItem[] = [];const seen = new Set<string>();for (const item of sorted) {diff --git a/examples/openclaw-plugin/query-config.ts b/examples/openclaw-plugin/query-config.tsnew file mode 100644index 000000000..f7b43a788--- /dev/null+++ b/examples/openclaw-plugin/query-config.ts@@ -0,0 +1,400 @@+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";+import { dirname } from "node:path";++import type { MemoryOpenVikingConfig } from "./config.js";+import { normalizeResourceTypes, type RecallResourceType } from "./recall-trace.js";++export type RuntimeQueryParams = {+ recallLimit?: number;+ candidateLimit?: number;+ candidateMultiplier?: number;+ scoreThreshold?: number;+ maxInjectedChars?: number;+ recallPreferAbstract?: boolean;+ resourceTypes?: RecallResourceType[] | string;+ targetUri?: string;+ ovSearchLimit?: number;+ rankingWeights?: {+ baseScore?: number;+ leaf?: number;+ event?: number;+ preference?: number;+ lexicalOverlapMax?: number;+ };+ resourceTypeWeights?: Partial<Record<RecallResourceType, number>>;+ categoryWeights?: Record<string, number>;+};++type RuntimeQueryParamsPatch = RuntimeQueryParams & Record<string, unknown>;+type ConfigSource = "request" | "session" | "claw" | "static" | "default";+type RuntimeScope = "claw" | "session";++export type QueryConfigContext = {+ peerId: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+};++export type EffectiveQueryConfig = {+ recallLimit: number;+ candidateLimit: number;+ candidateMultiplier: number;+ scoreThreshold: number;+ maxInjectedChars: number;+ recallPreferAbstract: boolean;+ resourceTypes: RecallResourceType[];+ targetUri?: string;+ ovSearchLimit: number;+ rankingWeights: {+ baseScore: number;+ leaf: number;+ event: number;+ preference: number;+ lexicalOverlapMax: number;+ };+ resourceTypeWeights: Record<string, number>;+ categoryWeights: Record<string, number>;+ sources: Record<string, ConfigSource>;+ warnings: string[];+};++type RuntimeRecord = {+ params: RuntimeQueryParams;+ updatedAt: number;+ updatedBy?: string;+ peerId?: string;+ expiresAt?: number;+};++type RuntimeFile = {+ schemaVersion: "1.0";+ updatedAt: number;+ claws: Record<string, RuntimeRecord>;+ sessions: Record<string, RuntimeRecord>;+};++const DEFAULT_CANDIDATE_MULTIPLIER = 4;+const DEFAULT_OV_SEARCH_LIMIT = 10;+const DEFAULT_RANKING_WEIGHTS = {+ baseScore: 1,+ leaf: 0.12,+ event: 0.1,+ preference: 0.08,+ lexicalOverlapMax: 0.2,+};++function toNumber(value: unknown): number | undefined {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value === "string" && value.trim() !== "") {+ const parsed = Number(value);+ if (Number.isFinite(parsed)) return parsed;+ }+ return undefined;+}++function clampInteger(value: unknown, min: number, max: number): number | undefined {+ const n = toNumber(value);+ if (n === undefined) return undefined;+ return Math.max(min, Math.min(max, Math.floor(n)));+}++function clampNumber(value: unknown, min: number, max: number): number | undefined {+ const n = toNumber(value);+ if (n === undefined) return undefined;+ return Math.max(min, Math.min(max, n));+}++function shallowNumberRecord(value: unknown, min: number, max: number): Record<string, number> | undefined {+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;+ const result: Record<string, number> = {};+ for (const [key, raw] of Object.entries(value)) {+ const n = clampNumber(raw, min, max);+ if (n !== undefined) result[key] = n;+ }+ return result;+}++export function normalizeRuntimeQueryParams(value: RuntimeQueryParamsPatch): { params: RuntimeQueryParams; warnings: string[] } {+ const warnings: string[] = [];+ const params: RuntimeQueryParams = {};++ const recallLimit = clampInteger(value.recallLimit, 1, 50);+ if (recallLimit !== undefined) params.recallLimit = recallLimit;+ const candidateMultiplier = clampInteger(value.candidateMultiplier, 1, 20);+ if (candidateMultiplier !== undefined) params.candidateMultiplier = candidateMultiplier;+ const candidateLimit = clampInteger(value.candidateLimit, 1, 200);+ if (candidateLimit !== undefined) params.candidateLimit = candidateLimit;+ const scoreThreshold = clampNumber(value.scoreThreshold, 0, 1);+ if (scoreThreshold !== undefined) params.scoreThreshold = scoreThreshold;+ const maxInjectedChars = clampInteger(value.maxInjectedChars, 100, 50_000);+ if (maxInjectedChars !== undefined) params.maxInjectedChars = maxInjectedChars;+ const ovSearchLimit = clampInteger(value.ovSearchLimit, 1, 100);+ if (ovSearchLimit !== undefined) params.ovSearchLimit = ovSearchLimit;++ if (typeof value.recallPreferAbstract === "boolean") params.recallPreferAbstract = value.recallPreferAbstract;+ if (value.resourceTypes !== undefined) params.resourceTypes = normalizeResourceTypes(value.resourceTypes);+ if (typeof value.targetUri === "string" && value.targetUri.trim()) {+ const targetUri = value.targetUri.trim();+ if (!targetUri.startsWith("viking://")) throw new Error("targetUri must start with viking://");+ params.targetUri = targetUri;+ }++ const rankingWeights = shallowNumberRecord(value.rankingWeights, 0, 2);+ if (rankingWeights) params.rankingWeights = rankingWeights;+ const resourceTypeWeights = shallowNumberRecord(value.resourceTypeWeights, -1, 2);+ if (resourceTypeWeights) params.resourceTypeWeights = resourceTypeWeights as Partial<Record<RecallResourceType, number>>;+ const categoryWeights = shallowNumberRecord(value.categoryWeights, -1, 2);+ if (categoryWeights) params.categoryWeights = categoryWeights;++ if (params.candidateLimit !== undefined && params.recallLimit !== undefined && params.candidateLimit < params.recallLimit) {+ params.candidateLimit = params.recallLimit;+ warnings.push("candidateLimit was raised to recallLimit");+ }++ return { params, warnings };+}++export function resolveSessionQueryConfigKey(ctx: Partial<QueryConfigContext>): string | undefined {+ if (ctx.ovSessionId) return `ov:${ctx.ovSessionId}`;+ if (ctx.sessionId) return `session:${ctx.sessionId}`;+ if (ctx.sessionKey) return `key:${ctx.sessionKey}`;+ return undefined;+}++function emptyRuntimeFile(): RuntimeFile {+ return { schemaVersion: "1.0", updatedAt: Date.now(), claws: {}, sessions: {} };+}++function isRuntimeFile(value: unknown): value is RuntimeFile {+ return !!value && typeof value === "object" && !Array.isArray(value) && (value as RuntimeFile).schemaVersion === "1.0";+}++export class RuntimeQueryConfigStore {+ private data: RuntimeFile = emptyRuntimeFile();+ private lastMtimeMs = 0;+ private loadPromise: Promise<void> | undefined;+ private writeQueue: Promise<void> = Promise.resolve();++ static createInMemory(staticConfig: Required<MemoryOpenVikingConfig>): RuntimeQueryConfigStore {+ return new RuntimeQueryConfigStore({ staticConfig });+ }++ constructor(private readonly options: { staticConfig: Required<MemoryOpenVikingConfig>; path?: string }) {}++ async load(): Promise<void> {+ if (!this.options.path) return;+ const loadPromise = this.loadFromDisk({ resetOnFailure: true });+ this.loadPromise = loadPromise;+ try {+ await loadPromise;+ } finally {+ if (this.loadPromise === loadPromise) this.loadPromise = undefined;+ }+ }++ private async loadFromDisk(options?: { resetOnFailure?: boolean }): Promise<void> {+ try {+ const raw = await readFile(this.options.path!, "utf8");+ const parsed = JSON.parse(raw);+ if (isRuntimeFile(parsed)) this.data = parsed;+ const s = await stat(this.options.path!);+ this.lastMtimeMs = s.mtimeMs;+ } catch {+ if (options?.resetOnFailure) this.data = emptyRuntimeFile();+ }+ }++ private async waitForInitialLoad(): Promise<void> {+ if (this.loadPromise) await this.loadPromise;+ }++ async reloadIfChanged(options?: { force?: boolean }): Promise<void> {+ if (!this.options.path) return;+ await this.waitForInitialLoad();+ try {+ const s = await stat(this.options.path);+ if (!options?.force && s.mtimeMs === this.lastMtimeMs) return;+ const raw = await readFile(this.options.path, "utf8");+ const parsed = JSON.parse(raw);+ if (isRuntimeFile(parsed)) {+ this.data = parsed;+ this.lastMtimeMs = s.mtimeMs;+ }+ } catch {+ // Keep the last known-good in-memory config.+ }+ }++ async set(scope: RuntimeScope, ctx: QueryConfigContext, patch: RuntimeQueryParamsPatch): Promise<{ warnings: string[] }> {+ await this.waitForInitialLoad();+ const { params, warnings } = normalizeRuntimeQueryParams(patch);+ const key = this.keyForScope(scope, ctx);+ const bucket = scope === "claw" ? this.data.claws : this.data.sessions;+ bucket[key] = { params, updatedAt: Date.now(), updatedBy: "command", peerId: ctx.peerId };+ this.data.updatedAt = Date.now();+ await this.persist();+ return { warnings };+ }++ async unset(scope: RuntimeScope, ctx: QueryConfigContext, fields: string[]): Promise<void> {+ await this.waitForInitialLoad();+ const key = this.keyForScope(scope, ctx);+ const bucket = scope === "claw" ? this.data.claws : this.data.sessions;+ const record = bucket[key];+ if (!record) return;+ for (const field of fields) {+ delete (record.params as Record<string, unknown>)[field];+ }+ record.updatedAt = Date.now();+ this.data.updatedAt = Date.now();+ await this.persist();+ }++ async reset(scope: RuntimeScope, ctx: QueryConfigContext): Promise<void> {+ await this.waitForInitialLoad();+ const key = this.keyForScope(scope, ctx);+ const bucket = scope === "claw" ? this.data.claws : this.data.sessions;+ delete bucket[key];+ this.data.updatedAt = Date.now();+ await this.persist();+ }++ async getEffective(ctx: QueryConfigContext, requestOverrides?: RuntimeQueryParamsPatch): Promise<EffectiveQueryConfig> {+ await this.reloadIfChanged();+ const cfg = this.options.staticConfig;+ const warnings: string[] = [];+ const effective: EffectiveQueryConfig = {+ recallLimit: cfg.recallLimit,+ candidateMultiplier: DEFAULT_CANDIDATE_MULTIPLIER,+ candidateLimit: Math.max(cfg.recallLimit * DEFAULT_CANDIDATE_MULTIPLIER, 20),+ scoreThreshold: cfg.recallScoreThreshold,+ maxInjectedChars: cfg.recallMaxInjectedChars,+ recallPreferAbstract: cfg.recallPreferAbstract,+ resourceTypes: normalizeResourceTypes(cfg.recallTargetTypes),+ ovSearchLimit: DEFAULT_OV_SEARCH_LIMIT,+ rankingWeights: { ...DEFAULT_RANKING_WEIGHTS },+ resourceTypeWeights: {},+ categoryWeights: {},+ sources: {+ recallLimit: "static",+ candidateMultiplier: "default",+ candidateLimit: "default",+ scoreThreshold: "static",+ maxInjectedChars: "static",+ recallPreferAbstract: "static",+ resourceTypes: "static",+ ovSearchLimit: "default",+ rankingWeights: "default",+ },+ warnings,+ };++ let candidateLimitExplicit = false;+ candidateLimitExplicit = this.applyLayer(effective, this.data.claws[ctx.peerId]?.params, "claw", candidateLimitExplicit);+ const sessionRecord = this.findSessionRecord(ctx);+ if (sessionRecord) candidateLimitExplicit = this.applyLayer(effective, sessionRecord.params, "session", candidateLimitExplicit);+ if (requestOverrides) {+ const normalized = normalizeRuntimeQueryParams(requestOverrides);+ warnings.push(...normalized.warnings);+ this.applyLayer(effective, normalized.params, "request", candidateLimitExplicit);+ }+ effective.candidateLimit = Math.max(effective.candidateLimit, effective.recallLimit);+ return effective;+ }++ private applyLayer(+ effective: EffectiveQueryConfig,+ params: RuntimeQueryParams | undefined,+ source: ConfigSource,+ candidateLimitExplicit: boolean,+ ): boolean {+ if (!params) return candidateLimitExplicit;+ if (params.recallLimit !== undefined) {+ effective.recallLimit = params.recallLimit;+ effective.sources.recallLimit = source;+ if (!candidateLimitExplicit) {+ effective.candidateLimit = Math.max(effective.recallLimit * effective.candidateMultiplier, 20);+ effective.sources.candidateLimit = source;+ }+ }+ if (params.candidateMultiplier !== undefined) {+ effective.candidateMultiplier = params.candidateMultiplier;+ effective.sources.candidateMultiplier = source;+ if (!candidateLimitExplicit) {+ effective.candidateLimit = Math.max(effective.recallLimit * params.candidateMultiplier, 20);+ effective.sources.candidateLimit = source;+ }+ }+ if (params.candidateLimit !== undefined) {+ effective.candidateLimit = params.candidateLimit;+ effective.sources.candidateLimit = source;+ candidateLimitExplicit = true;+ }+ if (params.scoreThreshold !== undefined) {+ effective.scoreThreshold = params.scoreThreshold;+ effective.sources.scoreThreshold = source;+ }+ if (params.maxInjectedChars !== undefined) {+ effective.maxInjectedChars = params.maxInjectedChars;+ effective.sources.maxInjectedChars = source;+ }+ if (params.recallPreferAbstract !== undefined) {+ effective.recallPreferAbstract = params.recallPreferAbstract;+ effective.sources.recallPreferAbstract = source;+ }+ if (params.resourceTypes !== undefined) {+ effective.resourceTypes = Array.isArray(params.resourceTypes) ? [...params.resourceTypes] : normalizeResourceTypes(params.resourceTypes);+ effective.sources.resourceTypes = source;+ }+ if (params.targetUri !== undefined) {+ effective.targetUri = params.targetUri;+ effective.sources.targetUri = source;+ }+ if (params.ovSearchLimit !== undefined) {+ effective.ovSearchLimit = params.ovSearchLimit;+ effective.sources.ovSearchLimit = source;+ }+ if (params.rankingWeights) {+ effective.rankingWeights = { ...effective.rankingWeights, ...params.rankingWeights };+ effective.sources.rankingWeights = source;+ }+ if (params.resourceTypeWeights) effective.resourceTypeWeights = { ...effective.resourceTypeWeights, ...params.resourceTypeWeights };+ if (params.categoryWeights) effective.categoryWeights = { ...effective.categoryWeights, ...params.categoryWeights };+ return candidateLimitExplicit;+ }++ private keyForScope(scope: RuntimeScope, ctx: QueryConfigContext): string {+ if (scope === "claw") return ctx.peerId;+ const key = resolveSessionQueryConfigKey(ctx);+ if (!key) throw new Error("session scope requires ovSessionId, sessionId, or sessionKey");+ return key;+ }++ private findSessionRecord(ctx: QueryConfigContext): RuntimeRecord | undefined {+ const keys = [+ ctx.ovSessionId ? `ov:${ctx.ovSessionId}` : undefined,+ ctx.sessionId ? `session:${ctx.sessionId}` : undefined,+ ctx.sessionKey ? `key:${ctx.sessionKey}` : undefined,+ ].filter((key): key is string => Boolean(key));+ for (const key of keys) {+ const record = this.data.sessions[key];+ if (record) return record;+ }+ return undefined;+ }++ private async persist(): Promise<void> {+ if (!this.options.path) return;+ const operation = this.writeQueue.catch(() => undefined).then(async () => {+ await mkdir(dirname(this.options.path!), { recursive: true });+ const temp = `${this.options.path}.${process.pid}.${Date.now()}.tmp`;+ await writeFile(temp, JSON.stringify(this.data, null, 2), "utf8");+ await rename(temp, this.options.path!);+ const s = await stat(this.options.path!);+ this.lastMtimeMs = s.mtimeMs;+ });+ this.writeQueue = operation.catch(() => undefined);+ await operation;+ }+}diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex d42a7bf93..5161c7a7d 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -3,6 +3,7 @@ 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 { RuntimeQueryConfigStore } from "../../query-config.js";import { RecallTraceMemoryStore } from "../../recall-trace.js";import { estimateAgentMessagesTokens, estimateTextTokens } from "../../token-estimator.js";@@ -45,6 +46,7 @@ function makeEngine(opts?: {cfgOverrides?: Record<string, unknown>;traceRecorder?: RecallTraceMemoryStore;+ queryConfigStore?: RuntimeQueryConfigStore;},) {const logger = makeLogger();@@ -72,6 +74,7 @@ function makeEngine(getClient,resolveAgentId,traceRecorder: opts?.traceRecorder,+ queryConfigStore: opts?.queryConfigStore,});return {@@ -259,6 +262,75 @@ describe("context-engine assemble()", () => {expect(recorded.searches[0]!.targetUriResolved).toBeUndefined();});+ it("applies session effective query config to transformContext auto-recall", async () => {+ const localCfg = memoryOpenVikingConfigSchema.parse({+ ...cfg,+ autoRecall: true,+ recallPreferAbstract: true,+ });+ const queryConfigStore = RuntimeQueryConfigStore.createInMemory(localCfg);+ await queryConfigStore.set(+ "session",+ { peerId: "agent:session-dynamic-query", sessionId: "session-dynamic-query" },+ {+ recallLimit: 1,+ candidateLimit: 3,+ scoreThreshold: 0.5,+ resourceTypes: ["user"],+ maxInjectedChars: 1000,+ },+ );+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "unused",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ recallPreferAbstract: true,+ },+ queryConfigStore,+ },+ );+ client.find.mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/default/memories/high",+ level: 2,+ category: "preferences",+ abstract: "High-confidence dynamic query memory.",+ score: 0.9,+ },+ {+ uri: "viking://user/default/memories/low",+ level: 2,+ category: "facts",+ abstract: "Low-confidence memory should be filtered.",+ score: 0.1,+ },+ ],+ total: 2,+ });++ const result = await engine.assemble({+ sessionId: "session-dynamic-query",+ messages: [{ role: "user", content: "which dynamic query memory applies?" }],+ });++ expect(client.find).toHaveBeenCalledTimes(1);+ expect(client.find.mock.calls[0]?.[1]).toMatchObject({+ contextType: "memory",+ limit: 3,+ });+ expect(client.find.mock.calls[0]?.[1].targetUri).toBeUndefined();+ expect(String(result.messages[0]?.content)).toContain("High-confidence dynamic query memory.");+ expect(String(result.messages[0]?.content)).not.toContain("Low-confidence memory should be filtered.");+ });+it("passes sender peer_id to transformContext auto-recall when peer_role is person", async () => {vi.stubGlobal("fetch",diff --git a/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts b/examples/openclaw-plugin/tests/ut/memory-ranking.test.tsindex caa90fd5c..ca56d20d8 100644--- a/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts+++ b/examples/openclaw-plugin/tests/ut/memory-ranking.test.ts@@ -255,4 +255,31 @@ describe("pickMemoriesForInjection", () => {const result = pickMemoriesForInjection(items, 1, "When did the user deploy?");expect(result[0]!.uri).toBe("event");});++ it("uses custom ranking weights without mutating semantic score", () => {+ const items = [+ mem({ uri: "fact", category: "facts", score: 0.8, abstract: "knows Python" }),+ mem({ uri: "pref", category: "preferences", score: 0.72, abstract: "prefers TypeScript" }),+ ];++ const result = pickMemoriesForInjection(items, 1, "What does the user prefer?", 0, {+ weights: { preference: 0.2 },+ });++ expect(result[0]!.uri).toBe("pref");+ expect(result[0]!.score).toBe(0.72);+ });++ it("uses category weights to tune ranking", () => {+ const items = [+ mem({ uri: "fact", category: "facts", score: 0.9, abstract: "knows Python" }),+ mem({ uri: "case", category: "cases", score: 0.7, abstract: "incident case" }),+ ];++ const result = pickMemoriesForInjection(items, 1, "unrelated query", 0, {+ categoryWeights: { cases: 0.35 },+ });++ expect(result[0]!.uri).toBe("case");+ });});diff --git a/examples/openclaw-plugin/tests/ut/query-config.test.ts b/examples/openclaw-plugin/tests/ut/query-config.test.tsnew file mode 100644index 000000000..589a7b482--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/query-config.test.ts@@ -0,0 +1,178 @@+import { describe, expect, it } from "vitest";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { memoryOpenVikingConfigSchema } from "../../config.js";+import {+ RuntimeQueryConfigStore,+ normalizeRuntimeQueryParams,+ resolveSessionQueryConfigKey,+} from "../../query-config.js";++describe("normalizeRuntimeQueryParams", () => {+ it("clamps values and normalizes resourceTypes", () => {+ const normalized = normalizeRuntimeQueryParams({+ recallLimit: 999,+ candidateMultiplier: 0,+ candidateLimit: 2,+ scoreThreshold: 2,+ maxInjectedChars: 10,+ ovSearchLimit: 999,+ resourceTypes: "resource,user",+ });++ expect(normalized.params).toMatchObject({+ recallLimit: 50,+ candidateMultiplier: 1,+ candidateLimit: 50,+ scoreThreshold: 1,+ maxInjectedChars: 100,+ ovSearchLimit: 100,+ resourceTypes: ["resource", "user"],+ });+ expect(normalized.warnings).toContain("candidateLimit was raised to recallLimit");+ });++ it("rejects non-viking targetUri", () => {+ expect(() => normalizeRuntimeQueryParams({ targetUri: "https://example.com/doc" })).toThrow("targetUri must start with viking://");+ });+});++describe("resolveSessionQueryConfigKey", () => {+ it("prefers ovSessionId then sessionId then sessionKey", () => {+ expect(resolveSessionQueryConfigKey({ ovSessionId: "ov1", sessionId: "s1", sessionKey: "k1" })).toBe("ov:ov1");+ expect(resolveSessionQueryConfigKey({ sessionId: "s1", sessionKey: "k1" })).toBe("session:s1");+ expect(resolveSessionQueryConfigKey({ sessionKey: "k1" })).toBe("key:k1");+ expect(resolveSessionQueryConfigKey({})).toBeUndefined();+ });+});++describe("RuntimeQueryConfigStore", () => {+ it("merges default, static, claw, session, and request layers with field sources", async () => {+ const cfg = memoryOpenVikingConfigSchema.parse({+ recallLimit: 6,+ recallScoreThreshold: 0.15,+ recallMaxInjectedChars: 4000,+ recallTargetTypes: ["user", "agent"],+ });+ const store = RuntimeQueryConfigStore.createInMemory(cfg);++ await store.set("claw", { peerId: "assistant-a" }, { recallLimit: 8, scoreThreshold: 0.25, resourceTypes: ["resource"] });+ await store.set("session", { peerId: "assistant-a", ovSessionId: "ov-session" }, { recallLimit: 3 });++ const effective = await store.getEffective(+ { peerId: "assistant-a", ovSessionId: "ov-session" },+ { scoreThreshold: 0.05 },+ );++ expect(effective.recallLimit).toBe(3);+ expect(effective.scoreThreshold).toBe(0.05);+ expect(effective.resourceTypes).toEqual(["resource"]);+ expect(effective.candidateLimit).toBe(20);+ expect(effective.sources.recallLimit).toBe("session");+ expect(effective.sources.scoreThreshold).toBe("request");+ expect(effective.sources.resourceTypes).toBe("claw");+ });++ it("preserves lower-priority explicit candidateLimit when a higher-priority layer changes only recallLimit", async () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 6 });+ const store = RuntimeQueryConfigStore.createInMemory(cfg);++ await store.set("claw", { peerId: "assistant-a" }, { candidateLimit: 80 });+ await store.set("session", { peerId: "assistant-a", sessionId: "s1" }, { recallLimit: 3 });++ const effective = await store.getEffective({ peerId: "assistant-a", sessionId: "s1" });++ expect(effective.recallLimit).toBe(3);+ expect(effective.candidateLimit).toBe(80);+ expect(effective.sources.recallLimit).toBe("session");+ expect(effective.sources.candidateLimit).toBe("claw");+ });++ it("persists runtime config and reloads modified files", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ov-query-config-"));+ try {+ const path = join(dir, "runtime-query-config.json");+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 6 });+ const store = new RuntimeQueryConfigStore({ staticConfig: cfg, path });+ await store.load();+ await store.set("claw", { peerId: "assistant-a" }, { recallLimit: 9 });++ const saved = JSON.parse(await readFile(path, "utf8"));+ expect(saved.claws["assistant-a"].params.recallLimit).toBe(9);++ saved.claws["assistant-a"].params.recallLimit = 4;+ await writeFile(path, JSON.stringify(saved), "utf8");+ await store.reloadIfChanged({ force: true });++ const effective = await store.getEffective({ peerId: "assistant-a" });+ expect(effective.recallLimit).toBe(4);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it("serializes writes behind an in-flight initial load", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ov-query-config-"));+ try {+ const path = join(dir, "runtime-query-config.json");+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 6 });+ await writeFile(path, JSON.stringify({+ schemaVersion: "1.0",+ updatedAt: Date.now(),+ claws: { "assistant-a": { params: { recallLimit: 9 }, updatedAt: Date.now() } },+ sessions: {},+ }), "utf8");+ const store = new RuntimeQueryConfigStore({ staticConfig: cfg, path });++ const loadPromise = store.load();+ const setPromise = store.set("claw", { peerId: "assistant-a" }, { recallLimit: 2 });+ await Promise.all([loadPromise, setPromise]);++ const effective = await store.getEffective({ peerId: "assistant-a" });+ expect(effective.recallLimit).toBe(2);+ expect(effective.sources.recallLimit).toBe("claw");+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it("keeps the persistence queue usable after a transient write failure", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ov-query-config-"));+ try {+ const blockedParent = join(dir, "blocked-parent");+ const path = join(blockedParent, "runtime-query-config.json");+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 6 });+ await writeFile(blockedParent, "not a directory", "utf8");+ const store = new RuntimeQueryConfigStore({ staticConfig: cfg, path });++ await expect(store.set("claw", { peerId: "assistant-a" }, { recallLimit: 2 })).rejects.toThrow();+ await rm(blockedParent, { force: true });++ await expect(store.set("claw", { peerId: "assistant-a" }, { recallLimit: 3 })).resolves.toBeDefined();+ const saved = JSON.parse(await readFile(path, "utf8"));+ expect(saved.claws["assistant-a"].params.recallLimit).toBe(3);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });++ it("unsets one field and resets scoped runtime config", async () => {+ const cfg = memoryOpenVikingConfigSchema.parse({ recallLimit: 6, recallScoreThreshold: 0.15 });+ const store = RuntimeQueryConfigStore.createInMemory(cfg);++ await store.set("session", { peerId: "assistant-a", sessionId: "s1" }, { recallLimit: 2, scoreThreshold: 0.4 });+ expect((await store.getEffective({ peerId: "assistant-a", sessionId: "s1" })).recallLimit).toBe(2);++ await store.unset("session", { peerId: "assistant-a", sessionId: "s1" }, ["recallLimit"]);+ const afterUnset = await store.getEffective({ peerId: "assistant-a", sessionId: "s1" });+ expect(afterUnset.recallLimit).toBe(6);+ expect(afterUnset.scoreThreshold).toBe(0.4);++ await store.reset("session", { peerId: "assistant-a", sessionId: "s1" });+ const afterReset = await store.getEffective({ peerId: "assistant-a", sessionId: "s1" });+ expect(afterReset.recallLimit).toBe(6);+ expect(afterReset.scoreThreshold).toBe(0.15);+ });+});diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex f0c5cf042..8c6c2f80b 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -393,6 +393,156 @@ describe("Tool: memory_recall (registration)", () => {expect(result.content[0]!.text).not.toContain("x".repeat(200));expect(result.details.count).toBe(1);});++ it("applies /ov-query-config session settings to subsequent memory_recall", async () => {+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/system/status") {+ return okResponse({ user: "default" });+ }+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();+ return okResponse({+ memories: [+ makeMemory({+ uri: "viking://user/default/memories/high",+ abstract: "High score runtime memory",+ score: 0.92,+ }),+ makeMemory({+ uri: "viking://user/default/memories/low",+ abstract: "Low score runtime memory",+ score: 0.1,+ }),+ ],+ resources: [],+ skills: [],+ total: 2,+ });+ }+ if (requestUrl.pathname === "/api/v1/content/read") {+ return okResponse("High score runtime memory content");+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, commands, api } = setupPlugin(undefined, {+ recallLimit: 6,+ recallTargetTypes: ["user", "agent"],+ });+ contextEnginePlugin.register(api as any);+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();++ await command!.handler({+ args: "set --scope session --recallLimit 1 --candidateLimit 3 --scoreThreshold 0.5 --resourceTypes user",+ commandBody: "",+ sessionId: "runtime-session",+ agentId: "main",+ });++ const tool = factoryTools.get("memory_recall")!({ sessionId: "runtime-session", agentId: "main" });+ const result = await tool.execute("tc-memory-recall-runtime", {+ query: "runtime memory",+ }) as ToolResult;++ expect(result.content[0]!.text).toContain("High score runtime memory content");+ expect(result.content[0]!.text).not.toContain("Low score runtime memory");+ const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>+ String(calledUrl).includes("/api/v1/search/find")+ );+ expect(findCalls).toHaveLength(1);+ const body = JSON.parse(String((findCalls[0]![1] as RequestInit).body));+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();+ expect(body.limit).toBe(3);+ });++ it("applies /ov-query-config session settings to subsequent ov_search", async () => {+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/system/status") {+ return okResponse({ user: "default" });+ }+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ expect(body.target_uri).toBe("viking://resources/project");+ expect(body.limit).toBe(2);+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/spec.md",+ abstract: "Project spec",+ score: 0.9,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({});+ });+ vi.stubGlobal("fetch", fetchMock);++ const { factoryTools, commands, api } = setupPlugin();+ contextEnginePlugin.register(api as any);+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();++ await command!.handler({+ args: "set --scope session --ovSearchLimit 2 --targetUri viking://resources/project",+ commandBody: "",+ sessionId: "runtime-search-session",+ agentId: "main",+ });++ const search = factoryTools.get("ov_search")!({ sessionId: "runtime-search-session", agentId: "main" });+ const result = await search.execute("tc-ov-search-runtime", {+ query: "project spec",+ }) as ToolResult;++ expect(result.details.uri).toBe("viking://resources/project");+ expect(result.details.total).toBe(1);+ });++ it("supports /ov-query-config get, unset, and reset for session scope", async () => {+ const { commands, api } = setupPlugin(undefined, {+ recallLimit: 6,+ recallScoreThreshold: 0.15,+ });+ contextEnginePlugin.register(api as any);+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();+ const ctx = {+ commandBody: "",+ sessionId: "runtime-session-config",+ agentId: "main",+ };++ const setResult = await command!.handler({+ ...ctx,+ args: "set --scope session --recallLimit 2 --scoreThreshold 0.4",+ });+ expect(setResult.text).toContain("Updated OpenViking query config");+ expect((setResult.details?.effective as any).recallLimit).toBe(2);+ expect((setResult.details?.effective as any).scoreThreshold).toBe(0.4);++ const getResult = await command!.handler({ ...ctx, args: "get --scope session" });+ expect((getResult.details?.effective as any).recallLimit).toBe(2);+ expect((getResult.details?.effective as any).scoreThreshold).toBe(0.4);++ const unsetResult = await command!.handler({ ...ctx, args: "unset recallLimit --scope session" });+ expect(unsetResult.text).toContain("Unset OpenViking query config fields");+ expect((unsetResult.details?.effective as any).recallLimit).toBe(6);+ expect((unsetResult.details?.effective as any).scoreThreshold).toBe(0.4);++ const resetResult = await command!.handler({ ...ctx, args: "reset --scope session" });+ expect(resetResult.text).toContain("Reset OpenViking query config");+ expect((resetResult.details?.effective as any).recallLimit).toBe(6);+ expect((resetResult.details?.effective as any).scoreThreshold).toBe(0.15);+ });});describe("Tool: memory_store (behavioral)", () => {