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): inject agent experience memories (#2281)
Mingjian Que790daaf8852a
diff --git a/docs/design/openclaw-agent-experience-memory-design.md b/docs/design/openclaw-agent-experience-memory-design.mdnew file mode 100644index 000000000..b3eb43574--- /dev/null+++ b/docs/design/openclaw-agent-experience-memory-design.md@@ -0,0 +1,532 @@+# OpenClaw 接入 OpenViking Agent Experience Recall 设计++日期:2026-05-28++## 当前结论++OpenViking 已经负责从 session commit 后的轨迹中抽取 agent experience。本 PR 不重做经验抽取、不改 commit policy,也不新增“长期记忆/经验记忆是否抽取”的控制面。++本 PR 只做运行期使用面:++1. 经验记忆功能默认关闭,必须显式配置 `agentExperience.enabled: true` 才启用。+2. 启用后,OpenClaw 在 `transformContext assemble` 阶段判断当前 turn 是否像执行任务。+3. 符合条件时,从 `viking://agent/memories/experiences` 检索 agent experience。+4. 同一轮也保留原有长期记忆 auto recall,并把 experience 和长期记忆分成不同 section。+5. 使用统一的 `<openviking-context>` 外壳注入到 latest user message 前;即使只有长期记忆,也使用这个外壳。+6. `afterTurn` 写 session 前剥离 `<openviking-context>`,避免把召回内容再次写回 OV。++这是一版“OpenClaw 能用 OV 经验记忆”的基准实现,不是完整的多 hook experience system。++## 不在本 PR 中处理的事++以下内容明确不属于本 PR:++- 不新增或修改 OV 服务端的 trajectory -> experience 抽取逻辑。+- 不新增 commit 时的 extraction policy。一次 commit 是否抽长期记忆、是否抽 experience,由 OV core 后续控制面解决。+- 不改变现有 `afterTurn()` session capture 主链路。+- 不改变现有 `compact()` / `commitSession()` 触发策略。+- 不新增 OpenClaw host hook。+- 不实现 skill load / subagent start / write preflight 的自动注入。+- 不新增 `experience_recall` 工具。+- 不把 experience 和普通长期记忆混成同一种记忆格式。++## 为什么接在 transformContext assemble++OpenClaw 插件当前有两类 assemble:++- preflight assemble:用于回读 OV session context,把已有 session 上下文给 OpenClaw。+- transformContext assemble:LLM 看到消息前最后一次改写消息上下文。++经验记忆是“执行前提醒”,应该发生在 LLM 决策前。当前 OpenClaw 插件没有 MemOS 那种 `before_prompt_build` hook,也没有 `before_subagent_start` / 可中断 `before_tool_call`。因此当前可落地的正确位置是 transformContext assemble。++当前代码路径:++```text+examples/openclaw-plugin/context-engine.ts+ assemble()+ -> isTransformContextAssemble+ -> latestMessage.role === "user"+ -> prepareRecallQuery()+ -> shouldRecallAgentExperience()+ -> buildAgentExperienceRecallContext()+ -> buildLongTermMemoryRecallContext()+ -> buildOpenVikingContextBlock()+ -> prependRecallToLatestUserMessage()+```++## 当前 PR 的文件改动++### `examples/openclaw-plugin/config.ts`++新增 `agentExperience` 配置,并在 parse 阶段补齐默认值:++```ts+agentExperience?: {+ enabled?: boolean;+ recallLimit?: number;+ scoreThreshold?: number;+ maxInjectedChars?: number;+ minQueryChars?: number;+};+```++默认值:++```ts+{+ enabled: false,+ recallLimit: 3,+ scoreThreshold: 0.35,+ maxInjectedChars: 6000,+ minQueryChars: 12,+}+```++`enabled` 默认是 `false`,这是保守发布开关:默认不触发 experience recall,也不增加额外检索请求。用户确认服务端 experience 数据质量和注入效果后,再显式打开。++`ParsedMemoryOpenVikingConfig` 是 schema parse 后的运行期类型,重点是让 `agentExperience` 的子字段也变成 required,避免 TypeScript 仍然认为 `recallLimit` / `maxInjectedChars` 可能是 undefined。++### `examples/openclaw-plugin/auto-recall.ts`++新增经验召回相关逻辑,但仍放在 `auto-recall.ts` 中。原因是当前插件还没有统一 recall source 目录体系,经验召回和长期记忆召回共享 query preparation、timeout、token estimate、context block 构造等基础设施。++核心新增/调整:++- `OPENVIKING_CONTEXT_TAG = "openviking-context"`+- `ExperienceRecallTrigger`+- `shouldRecallAgentExperience()`+- `isCronSession()`+- `buildAgentExperienceRecallContext()`+- `buildOpenVikingContextBlock()`+- `buildLongTermMemorySection()`+- `buildLongTermMemoryRecallContext()` 过滤掉 experience memory,避免 experience 出现在长期记忆区;同时生成 `Long-term Memories` section,交给统一外壳注入。++经验召回复用配置项 `autoRecallTimeoutMs`,不单独开 experience timeout;默认值仍是 `5000ms`。++### `examples/openclaw-plugin/context-engine.ts`++在 transformContext assemble 中接入两路 recall:++```text+experience recall+ -> 只查 viking://agent/memories/experiences+ -> 受 agentExperience 配置和 shouldRecallAgentExperience 控制++long-term recall+ -> 查 viking://user/memories+ -> 查 viking://agent/memories+ -> recallResources=true 时查 viking://resources+ -> 过滤掉 experiences+```++然后统一生成 `<openviking-context>` 外壳:++```ts+const combinedBlock = buildOpenVikingContextBlock({+ sections: [experienceRecall.block, recall.section],+});+```++如果没有 experience 命中,普通长期记忆仍然作为 `Long-term Memories` section 放入 `<openviking-context>`。如果两个结果都为空,直接 passthrough,不改写 messages。++### `examples/openclaw-plugin/text-utils.ts`++新增剥离:++```text+<openviking-context ...>...</openviking-context>+```++并保留历史格式清理:++```text+<relevant-memories>...</relevant-memories>+```++这样 `afterTurn()` 写 session 前会清理当前格式和历史格式注入块,避免本轮召回内容进入下一轮抽取。运行时新注入统一使用 `<openviking-context>`。++### tests++PR 中保留单元测试:++- `tests/ut/agent-experience-recall.test.ts`+- `tests/ut/context-engine-assemble.test.ts`+- `tests/ut/context-engine-afterTurn.test.ts`+- `tests/ut/text-utils.test.ts`++`tests/integration/test_openclaw_openviking_strict_e2e.py` 只作为本地严格联调脚本保留,不进入远端 PR。++## 运行时流程++### 1. 进入 assemble++当前只在 transformContext assemble 阶段自动注入。前置条件:++- session 没有被 `bypassSessionPatterns` 命中。+- latest message 是 user。+- `cfg.autoRecall` 或 `cfg.agentExperience.enabled` 至少一个开启。+- latest user message 没有已经包含 `<openviking-context>`。+- `prepareRecallQuery()` 清理后的 query 非空,且长度至少 5。++如果以上任一条件不满足,直接 passthrough。++### 2. 生成 query++query 来自 latest user message:++```ts+const recallQuery = prepareRecallQuery(extractAgentMessageText(latestMessage));+```++`prepareRecallQuery()` 会先调用 `sanitizeUserTextForCapture()`,因此旧的注入块、sender metadata、conversation metadata 等噪音不会进入 recall query。query 最长 4000 字符,超出会截断并写日志。++### 3. 判断是否要查 experience++经验召回首先受总开关控制:`agentExperience.enabled` 默认关闭。只有显式开启后,才会进入 `shouldRecallAgentExperience()`。这个 task gate 是内置逻辑,不再提供单独配置开关。++硬跳过:++- session bypass。+- query 为空或短于 `agentExperience.minQueryChars`。+- latest user text 已包含 `<openviking-context>`。++强制召回:++- `triggerHint` 不是 `task_start`,例如 `cron_start`。+- `sessionKey` 包含 `:cron:`,或 `runtimeContext.isCron === true`,或 `runtimeContext.automationKind === "cron"`。++普通 task gate 使用确定性打分:++```text++3 write/edit/modify/delete/migrate/deploy/release/configure/patch 等副作用动作++2 fix/debug/test/build/run/implement/refactor/integrate/troubleshoot 等执行动作++2 error/exception/failed/retry/traceback/test failed 等失败信号++2 文件路径、代码对象、hook/API/tool/package/module 等工程对象++1 经验/踩坑/最佳实践/avoid/best practice/lesson/pitfall 等经验意图+-3 闲聊、翻译、总结当前对话等非执行场景+-2 纯知识问答,并且没有工程对象和执行动词+```++`score >= 3` 才自动查 experience。++### 4. 检索 experience++经验召回只查 agent experience 目录:++```ts+client.find(queryText, {+ targetUri: "viking://agent/memories/experiences",+ limit: Math.max(expCfg.recallLimit * 4, 12),+ scoreThreshold: expCfg.scoreThreshold,+}, agentId)+```++后处理:++- 只保留 URI/category 看起来是 experience 的结果。+- 按 URI 去重。+- 截到 `agentExperience.recallLimit` 条,默认 3。+- `level === 2` 时用 `client.read()` 读取完整内容;否则使用 abstract / overview / uri。+- 只渲染结构化 experience,或者 metadata/URI 明确标记为 experience 的内容。+- 总注入字符不超过 `agentExperience.maxInjectedChars`。+- 受 `autoRecallTimeoutMs` 控制;超时或失败只 warn,不阻塞 OpenClaw。++当前不查 raw trajectories。++### 5. 渲染 experience++OV experience 当前主要结构是:++```markdown+## Situation+...++## Approach+...++## Reflect+...+```++OpenClaw 注入时映射为更适合执行期阅读的字段:++```markdown+### Experience: <filename>+Source: <uri>+Score: <score>++Trigger:+- from Situation++Do:+- from Approach++Avoid:+- from Reflect++Scope:+- from Situation++Check:+- from Reflect or Approach+```++如果原文缺某个字段,会用摘要或固定 fallback 补齐,避免给 LLM 一个空标题。++### 6. 检索长期记忆++原有 auto recall 保留,但输出不再直接包 `<relevant-memories>`。它现在只生成 `## Long-term Memories` section,再交给统一外壳。transformContext assemble 和非 transformContext assemble 都统一注入 `<openviking-context>`。++搜索范围:++- `viking://user/memories`+- `viking://agent/memories`+- `viking://resources`,仅 `recallResources=true`++后处理:++- 合并结果并按 URI 去重。+- 只保留 leaf memory。+- 过滤掉 experience memory,避免和 `Agent Experiences` 重复。+- 使用现有 `postProcessMemories()` / `pickMemoriesForInjection()` 排序和截断。+- 使用 `recallMaxInjectedChars` 做完整条目预算控制,单条记忆不截半。++### 7. 注入外壳++长期记忆单独注入时也使用统一外壳:++```markdown+<openviking-context>+## Long-term Memories++Source: openviking-auto-recall+The following OpenViking memories may be relevant:+- [profile] ...+</openviking-context>++<original latest user message>+```++同时注入 agent experience 和长期记忆时:++```markdown+<openviking-context>+## Agent Experiences++These are prior execution lessons learned by this agent. Use them as task guidance, not as user facts.++### Experience: openclaw-plugin-file-write-guard+Source: viking://agent/main/memories/experiences/openclaw-plugin-file-write-guard.md+Score: 0.910++Trigger:+- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。++Do:+- 在写回 OV session 前剥离注入上下文块。++Avoid:+- 避免把注入经验再次写回 transcript。++Scope:+- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。++Check:+- 避免把注入经验再次写回 transcript。++## Long-term Memories++Source: openviking-auto-recall+The following OpenViking memories may be relevant:+- [profile] ...+</openviking-context>++<original latest user message>+```++规则:++- 外壳统一用 `<openviking-context>`,表达“OpenViking 注入的上下文”,不绑定 OpenClaw/VikingBot/Codex 任一消费方。+- 内部用 Markdown section 区分经验记忆和长期记忆。+- `Agent Experiences` 在前,因为它影响执行策略。+- `Long-term Memories` 在后,因为它更多是用户事实、偏好、资源。+- 没有命中的 section 直接省略。+- 两个 section 都没有时,不注入任何东西。+- 清理逻辑兼容历史 `<relevant-memories>` 和当前 `<openviking-context>`。++## 为什么 experience block 和 long-term block 不合成一个 section++它们都属于 recall,但语义不同:++- long-term memory 是事实/偏好/资源,回答时可以当作上下文事实。+- agent experience 是执行策略/踩坑/验证方式,只能当作任务指导,不能当成用户事实。++如果混在同一个 bullet list 里,模型容易把“以前修 bug 的做法”当成“当前用户事实”。所以它们共享 `<openviking-context>` 外壳,但必须分 section。++## 与 MemOS 的关系++MemOS OpenClaw adapter 的自动注入点是 `before_prompt_build`,返回 `{ prependContext }`。它不是每个 tool 调用前无脑注入,也不是 subagent 启动时一定注入。++OV OpenClaw 当前没有这个 hook,但 transformContext assemble 在语义上等价于“LLM prompt 构造前最后一次上下文改写”。所以本 PR 采用 transformContext assemble。++MemOS 值得参考的是三点:++- 用一个外层 block 包住注入内容,便于清理。+- 经验和普通记忆分区展示。+- 经验要渲染成行动指导,而不是原始轨迹。++本 PR 不复刻 MemOS 的 L1 Trace / L2 Policy / L3 World Model / Skill 层级。OV 服务端已经负责 trajectory 和 experience 的沉淀,OpenClaw 插件只消费结果。++## 与 VikingBot 的关系++VikingBot 目前已有多个经验注入点:++- skill 读取后追加 `## Related Experiences`+- subagent task 前追加 `## Agent Experience`+- write tool 前检测写类工具,插入 `## Relevant Agent Experience`+- cron/benchmark 场景通过任务 prompt 读取 experience++这些是 VikingBot 内部 agent loop 的直接拼接逻辑,不是一个跨插件的公共 envelope。++因此新外壳不应该叫 `vikingbot-context`,也不应该叫 `openclaw-context`。`<openviking-context>` 更适合作为 OV 面向不同 agent 插件的统一注入外壳。未来 VikingBot 如果迁移到公共插件协议,也可以选择复用这个 envelope;但本 PR 不改 VikingBot。++## 后续更精确接入点++下列入口从原理上适合注入 experience,但需要 OpenClaw host 暴露更精确的 hook 或可中断控制面。当前 PR 不实现。++### Skill 加载时++适合原因:agent 已经选择读取某个 `SKILL.md`,此时用 skill name/description 查经验,注入到 skill 内容旁边,相关性比全局 prompt 更高。++需要 host 支持:++```ts+tool_result_persist / after_tool_call+ -> 允许插件修改 read_file(SKILL.md) 返回给 LLM 的 tool result+```++插件逻辑:++```text+read_file(SKILL.md)+ -> parse name/description+ -> query experiences+ -> append "Related Experiences" to this tool result only+```++### Subagent 启动时++适合原因:subagent 是冷启动,最需要携带“类似子任务过去怎么做”的经验。++需要 host 支持:++```ts+before_subagent_start(event: {+ task?: string;+ mission?: string;+ profile?: string;+ childSessionKey?: string;+}) -> { prependContext?: string }+```++如果 host 只有 `subagent_spawned`,那通常已经太晚,只能记录元数据,不能保证改到子 agent 初始 prompt。++### Write 类工具调用前++适合原因:写文件、改文件、删除文件是副作用动作,经验最能减少“写了又改”的情况。++但正确实现必须支持 cancel/replan:++```text+LLM 准备调用 write_file/edit_file+ -> plugin 查经验+ -> 若命中,取消当前 tool call+ -> 把经验作为 user/context message 插入+ -> 重新让 LLM 决定是否还要写、怎么写+```++如果 host 只允许不可变的 `before_tool_call`,那这点不能正确做。继续执行原 tool call 意味着经验来得太晚。++### Cron 重复任务++cron 原理上适合注入 experience,因为任务重复、经验命中率高。++当前 PR 已经支持在 transformContext assemble 中识别:++```text+sessionKey includes ":cron:"+runtimeContext.isCron === true+runtimeContext.automationKind === "cron"+```++识别后 trigger 是 `cron_start`,并绕过普通 task gate。前提是该 cron session 没被 `bypassSessionPatterns` 跳过。不要默认把 cron 加入 bypass。++如果未来 host 暴露 automation name/prompt,query 应该从当前 latest user message 扩展为:++```text+sessionKey+automation name+automation prompt+latest task text+recent failure/success summary+```++## 清理与防污染++经验召回最容易出的问题是自我污染:本轮注入的经验被当成本轮用户输入写回 session,下次 commit 又把它抽成新的经验。++当前 PR 的防线:++1. assemble 前检查 latest user message 是否已有 `<openviking-context>`,有则不重复注入。+2. `sanitizeUserTextForCapture()` 会剥离:+ - `<openviking-context>`+ - 历史 `<relevant-memories>`+3. `afterTurn()` 写 session 前走现有文本清理路径,因此注入块不会写回 OV。+4. long-term recall 过滤 experience URI/category,避免 experience 被长期记忆 section 再注入一次。++## 测试覆盖++当前 PR 的单元测试覆盖:++- 普通知识问答不会触发 experience recall。+- 执行型任务会触发 experience recall。+- cron trigger 会强制 recall。+- experience memory 不会出现在 `Long-term Memories` section。+- 已存在 `<openviking-context>` 会阻止重复注入。+- `<openviking-context>` / 历史 `<relevant-memories>` 会被清理。+- afterTurn 写 session 前会剥离注入块。++本地严格 e2e 脚本保留在工作区,但不进入远端 PR。++## 验收标准++合并前应满足:++- `npm run typecheck` 通过。+- `npm run build` 通过。+- `npm run test` 通过。+- PR diff 不包含 `tests/integration/test_openclaw_openviking_strict_e2e.py`。+- 默认配置下不会触发 experience recall;必须显式设置 `agentExperience.enabled: true`。+- 默认关闭 experience 时,普通长期记忆 auto recall 也使用 `<openviking-context>` 外壳。+- 普通问答不会因为默认配置无脑注入 experience。+- 执行型任务在有相关 experience 命中时注入 `Agent Experiences` section。+- 同一 block 中长期记忆和经验记忆分区清晰。+- 注入块不会被写回 OV session。++## 最终边界++```text+OpenClaw 插件负责:+ - 判断当前 turn 是否值得使用 agent experience+ - 检索 viking://agent/memories/experiences+ - 渲染 Agent Experiences section+ - 与 Long-term Memories 共同放入 <openviking-context>+ - 写 session 前清理注入块++OpenViking 服务端负责:+ - session commit+ - trajectory 抽取+ - experience 生成和更新+ - memory vectorization+ - 未来的抽取 policy / world model / skill 演进+```diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex 758b0d2b2..c737884ef 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -155,7 +155,7 @@ During recall, the plugin:3. Runs a quick availability precheck so model requests do not stall when OpenViking is unavailable.4. Queries `viking://user/memories` and optionally `viking://resources`.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.+6. Prepends the selected memories as a `## Long-term Memories` section inside `<openviking-context>` 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:@@ -190,7 +190,7 @@ That means OpenClaw sees "compressed history summary + archive index + active me- it slices only the newly added messages- it keeps only `user` / `assistant` capture text- it preserves `toolCall` / `toolResult` content in the serialized turn text-- it strips injected `<relevant-memories>` blocks and metadata noise before capture+- it strips injected `<openviking-context>` blocks, historical `<relevant-memories>` blocks, and metadata noise before capture- it appends the sanitized turn text into the OpenViking sessionAfter that, the plugin checks `pending_tokens`. Once the session crosses `commitTokenThreshold`, it triggers `commit(wait=false)`:diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex b3075f409..6db7c7165 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -155,7 +155,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking3. 先做一次快速可用性检查,避免在 OpenViking 不可用时拖慢模型请求。4. 检索 `viking://user/memories`,并按配置可选检索 `viking://resources`。5. 在插件侧做去重、阈值筛选、重排和 token budget 裁剪。-6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。+6. 把最终记忆以 `## Long-term Memories` section 放进 `<openviking-context>`,再 prepend 到当前 user message;不会追加独立 synthetic user message。这里的重排不是单纯依赖向量分数。当前实现还会额外考虑:@@ -190,7 +190,7 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来- 只切出本轮新增消息,不重写整段对话- 只保留 `user` / `assistant` 相关文本内容- 会把 `toolCall` / `toolResult` 格式化进 capture 文本-- 会先剥掉注入过的 `<relevant-memories>` 和元数据噪音+- 会先剥掉注入过的 `<openviking-context>`、历史 `<relevant-memories>` 和元数据噪音- 最终把清洗后的增量内容追加到 OpenViking session之后插件会读取 session 的 `pending_tokens`。当它超过 `commitTokenThreshold` 时,会触发一次 `commit(wait=false)`:diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsindex 271f8577d..b0ff3438c 100644--- a/examples/openclaw-plugin/auto-recall.ts+++ b/examples/openclaw-plugin/auto-recall.ts@@ -1,5 +1,5 @@import type { FindResult, FindResultItem, OpenVikingClient } from "./client.js";-import type { MemoryOpenVikingConfig } from "./config.js";+import type { ParsedMemoryOpenVikingConfig } from "./config.js";import {pickMemoriesForInjection,postProcessMemories,@@ -12,12 +12,41 @@ import { estimateTextTokens } from "./token-estimator.js";const RECALL_QUERY_MAX_CHARS = 4_000;export const AUTO_RECALL_SOURCE_MARKER = "Source: openviking-auto-recall";+export const OPENVIKING_CONTEXT_TAG = "openviking-context";type Logger = {info: (msg: string) => void;warn?: (msg: string) => void;};+const WRITE_OR_EFFECT_RE =+ /\b(write|edit|modify|delete|remove|migrate|deploy|release|publish|configure|patch)\b|写|改|修改|删除|迁移|部署|发布|配置|打补丁/i;+const EXECUTION_RE =+ /\b(fix|debug|test|build|run|implement|refactor|integrate|repair|troubleshoot)\b|修复|调试|测试|构建|运行|实现|重构|对接|排查/i;+const FAILURE_RE =+ /\b(error|exception|traceback|failed|failure|retry|exit code|test failed)\b|报错|异常|失败|重试|挂了|不通过/i;+const ENGINEERING_OBJECT_RE =+ /(?:^|\s)(?:[\w.-]+\/[\w./-]+|[\w./-]+\.(?:ts|tsx|js|jsx|py|go|rs|java|md|json|ya?ml|toml|sh|sql))\b|`[^`]+`|\b(?:repo|workspace|plugin|service|component|hook|api|tool|package|module)\b|仓库|工作区|插件|服务|组件|接口|工具|模块|文件/i;+const EXPERIENCE_INTENT_RE =+ /经验|踩坑|最佳实践|不要再|按之前|avoid|best practice|lesson|pitfall/i;+const QUESTION_ONLY_RE =+ /^(?:什么是|是什么|区别|解释|讲讲|怎么看|为什么|如何理解|where is|what is|explain|difference between)\b|[??]$/i;+const CASUAL_RE = /闲聊|翻译|总结当前对话|天气|笑话|hello|hi\b|你好/i;++export type ExperienceRecallTrigger =+ | "task_start"+ | "skill_load"+ | "subagent_start"+ | "write_preflight"+ | "cron_start";++export type ExperienceRecallDecision = {+ recall: boolean;+ trigger?: ExperienceRecallTrigger;+ score: number;+ reason: string;+};+export type PreparedRecallQuery = {query: string;truncated: boolean;@@ -89,6 +118,16 @@ function formatMemoryLine(].join("\n");}+function isExperienceMemory(item: FindResultItem): boolean {+ const category = (item.category ?? "").toLowerCase();+ return (+ item.uri.includes("/memories/experiences/") ||+ item.uri.includes("/experiences/") ||+ category === "experience" ||+ category === "experiences"+ );+}+async function resolveMemoryContent(item: FindResultItem,readFn: (uri: string) => Promise<string>,@@ -174,25 +213,265 @@ export async function buildMemoryLinesWithBudget(return { lines, estimatedTokens: totalTokens };}-export function buildRecallContextBlock(memoryLines: string[]): string {+export function buildLongTermMemorySection(memoryLines: string[]): string {return [- "<relevant-memories>",+ "## Long-term 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>;+export function buildOpenVikingContextBlock(params: {+ sections: Array<string | undefined>;+}): string {+ const sections = params.sections+ .map((section) => section?.trim())+ .filter((section): section is string => Boolean(section));+ if (sections.length === 0) {+ return "";+ }+ return [+ `<${OPENVIKING_CONTEXT_TAG}>`,+ sections.join("\n\n"),+ `</${OPENVIKING_CONTEXT_TAG}>`,+ ].join("\n");+}++function runtimeFlag(runtimeContext: unknown, key: string): unknown {+ return runtimeContext && typeof runtimeContext === "object"+ ? (runtimeContext as Record<string, unknown>)[key]+ : undefined;+}++export function isCronSession(sessionKey?: string, runtimeContext?: unknown): boolean {+ return Boolean(+ sessionKey?.includes(":cron:") ||+ runtimeFlag(runtimeContext, "isCron") === true ||+ runtimeFlag(runtimeContext, "automationKind") === "cron",+ );+}++export function shouldRecallAgentExperience(input: {+ latestUserText: string;+ sessionKey?: string;+ runtimeContext?: unknown;+ triggerHint?: ExperienceRecallTrigger;+ minQueryChars?: number;+ isBypassed?: boolean;+}): ExperienceRecallDecision {+ const text = sanitizeUserTextForCapture(input.latestUserText).trim();+ const minQueryChars = input.minQueryChars ?? 12;++ if (input.isBypassed) {+ return { recall: false, score: 0, reason: "session_bypassed" };+ }+ if (!text || text.length < minQueryChars) {+ return { recall: false, score: 0, reason: "query_too_short" };+ }+ if (/<openviking-context\b/i.test(input.latestUserText)) {+ return { recall: false, score: 0, reason: "already_injected" };+ }++ const trigger = input.triggerHint ?? (isCronSession(input.sessionKey, input.runtimeContext) ? "cron_start" : "task_start");+ if (trigger !== "task_start") {+ return { recall: true, trigger, score: 99, reason: "forced_trigger" };+ }++ let score = 0;+ if (WRITE_OR_EFFECT_RE.test(text)) score += 3;+ if (EXECUTION_RE.test(text)) score += 2;+ if (FAILURE_RE.test(text)) score += 2;+ if (ENGINEERING_OBJECT_RE.test(text)) score += 2;+ if (EXPERIENCE_INTENT_RE.test(text)) score += 1;++ if (CASUAL_RE.test(text)) score -= 3;+ if (QUESTION_ONLY_RE.test(text) && !ENGINEERING_OBJECT_RE.test(text) && !EXECUTION_RE.test(text)) {+ score -= 2;+ }++ if (score >= 3) {+ return { recall: true, trigger: "task_start", score, reason: "task_execution" };+ }+ return { recall: false, score, reason: score < 0 ? "non_execution" : "below_threshold" };+}++function sectionAfter(markdown: string, heading: string): string {+ const re = new RegExp(`(?:^|\\n)##\\s+${heading}\\s*\\n([\\s\\S]*?)(?=\\n##\\s+|$)`, "i");+ return markdown.match(re)?.[1]?.trim() ?? "";+}++function bulletize(text: string, fallback: string): string[] {+ const cleaned = text+ .split(/\n+/)+ .map((line) => line.replace(/^[-*]\s*/, "").trim())+ .filter(Boolean);+ const lines = cleaned.length > 0 ? cleaned : [fallback];+ return lines.slice(0, 5).map((line) => `- ${line}`);+}++function titleFromUri(uri: string): string {+ const raw = decodeURIComponent(uri.split("/").pop() ?? "experience").replace(/\.md$/i, "");+ return raw || "experience";+}++function renderExperience(item: FindResultItem, content: string): string | null {+ const situation = sectionAfter(content, "Situation");+ const approach = sectionAfter(content, "Approach");+ const reflect = sectionAfter(content, "Reflect");+ const hasStructuredExperience = Boolean(situation || approach || reflect);+ if (!hasStructuredExperience && !isExperienceMemory(item)) {+ return null;+ }++ const score = typeof item.score === "number" ? item.score.toFixed(3) : "n/a";+ return [+ `### Experience: ${titleFromUri(item.uri)}`,+ `Source: ${item.uri}`,+ `Score: ${score}`,+ "",+ "Trigger:",+ ...bulletize(situation, item.abstract?.trim() || content.slice(0, 240).trim() || "Similar execution situation."),+ "",+ "Do:",+ ...bulletize(approach, "Use the proven execution path from this experience."),+ "",+ "Avoid:",+ ...bulletize(reflect, "Avoid repeating failure modes called out by this experience."),+ "",+ "Scope:",+ ...bulletize(situation, "Applies to similar agent execution tasks."),+ "",+ "Check:",+ ...bulletize(reflect || approach, "Verify the task outcome before final response."),+ ].join("\n");+}++export async function buildAgentExperienceRecallContext(params: {+ cfg: ParsedMemoryOpenVikingConfig;+ client: OpenVikingClient;+ agentId: string;+ queryText: string;+ trigger: ExperienceRecallTrigger;+ logger: Logger;+ verbose?: (message: string) => void;+}): Promise<{ block?: string; count: number; estimatedTokens: number; skippedReason?: string }> {+ const { cfg, client, agentId, queryText, trigger, logger, verbose } = params;+ const expCfg = cfg.agentExperience;+ if (!expCfg.enabled) {+ return { count: 0, estimatedTokens: 0, skippedReason: "disabled" };+ }++ const precheck = await quickRecallPrecheck(client, agentId);+ if (!precheck.ok) {+ verbose?.(`openviking: skipping agent experience recall because precheck failed (${precheck.reason})`);+ return { count: 0, estimatedTokens: 0, skippedReason: precheck.reason };+ }++ return withTimeout(+ (async () => {+ const result = await client.find(queryText, {+ targetUri: "viking://agent/memories/experiences",+ limit: Math.max(expCfg.recallLimit * 4, 12),+ scoreThreshold: expCfg.scoreThreshold,+ }, agentId);++ const candidates = (result.memories ?? [])+ .filter(isExperienceMemory)+ .filter((item, index, self) => index === self.findIndex((m) => m.uri === item.uri))+ .slice(0, expCfg.recallLimit);++ if (candidates.length === 0) {+ return { count: 0, estimatedTokens: 0, skippedReason: "no_hits" };+ }++ const rendered: string[] = [];+ let chars = 0;+ for (const item of candidates) {+ const content = item.level === 2+ ? await client.read(item.uri, agentId).catch(() => item.abstract ?? item.uri)+ : item.abstract ?? item.overview ?? item.uri;+ const exp = renderExperience(item, content);+ if (!exp) continue;+ const projected = chars + (rendered.length > 0 ? 2 : 0) + exp.length;+ if (projected > expCfg.maxInjectedChars) continue;+ rendered.push(exp);+ chars = projected;+ }++ if (rendered.length === 0) {+ return { count: 0, estimatedTokens: 0, skippedReason: "no_structured_hits" };+ }++ const block = [+ "## Agent Experiences",+ "",+ "These are prior execution lessons learned by this agent. Use them as task guidance, not as user facts.",+ "",+ ...rendered,+ ].join("\n");+ verbose?.(`openviking: injecting ${rendered.length} agent experiences for trigger=${trigger}`);+ return { block, count: rendered.length, estimatedTokens: estimateTokenCount(block) };+ })(),+ cfg.autoRecallTimeoutMs,+ "openviking: agent experience recall timeout",+ ).catch((err) => {+ logger.warn?.(`openviking: agent experience recall failed: ${String(err)}`);+ return { count: 0, estimatedTokens: 0, skippedReason: "failed" };+ });+}++export async function buildGatedAgentExperienceRecallContext(params: {+ cfg: ParsedMemoryOpenVikingConfig;+ client: OpenVikingClient;+ agentId: string;+ queryText: string;+ sessionKey?: string;+ runtimeContext?: unknown;+ logger: Logger;+ verbose?: (message: string) => void;+}): Promise<{ block?: string; count: number; estimatedTokens: number; skippedReason?: string }> {+ const { cfg, client, agentId, queryText, sessionKey, runtimeContext, logger, verbose } = params;+ if (!cfg.agentExperience.enabled) {+ return { count: 0, estimatedTokens: 0, skippedReason: "disabled" };+ }++ const triggerHint = isCronSession(sessionKey, runtimeContext)+ ? "cron_start"+ : "task_start";+ const decision = shouldRecallAgentExperience({+ latestUserText: queryText,+ sessionKey,+ runtimeContext,+ triggerHint,+ minQueryChars: cfg.agentExperience.minQueryChars,+ isBypassed: false,+ });+ if (!decision.recall) {+ return { count: 0, estimatedTokens: 0, skippedReason: decision.reason };+ }++ return buildAgentExperienceRecallContext({+ cfg,+ client,+ agentId,+ queryText,+ trigger: decision.trigger ?? "task_start",+ logger,+ verbose,+ });+}++export async function buildLongTermMemoryRecallContext(params: {+ cfg: ParsedMemoryOpenVikingConfig;client: OpenVikingClient;agentId: string;peerId?: string;queryText: string;logger: Logger;verbose?: (message: string) => void;-}): Promise<{ block?: string; memoryCount: number; estimatedTokens: number }> {+}): Promise<{ section?: string; memoryCount: number; estimatedTokens: number }> {const { cfg, client, agentId, peerId, queryText, logger, verbose } = params;if (!cfg.autoRecall || queryText.length < 5) {@@ -240,7 +519,7 @@ export async function buildAutoRecallContext(params: {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 leafOnly = uniqueMemories.filter((m) => (!m.level || m.level === 2) && !isExperienceMemory(m));const processed = postProcessMemories(leafOnly, {limit: candidateLimit,scoreThreshold: cfg.recallScoreThreshold,@@ -268,15 +547,15 @@ export async function buildAutoRecallContext(params: {return { memoryCount: 0, estimatedTokens: 0 };}- const block = buildRecallContextBlock(memoryLines);+ const section = buildLongTermMemorySection(memoryLines);verbose?.(- `openviking: injecting ${memoryLines.length} memories (${block.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${cfg.recallMaxInjectedChars})`,+ `openviking: injecting ${memoryLines.length} memories (${section.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${cfg.recallMaxInjectedChars})`,);verbose?.(`openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,);- return { block, memoryCount: memoryLines.length, estimatedTokens };+ return { section, memoryCount: memoryLines.length, estimatedTokens };})(),cfg.autoRecallTimeoutMs,"openviking: auto-recall search timeout",diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex 85dcc7387..8c9df465b 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -45,6 +45,20 @@ export type MemoryOpenVikingConfig = {emitStandardDiagnostics?: boolean;/** When true, log tenant routing for semantic find and session writes (messages/commit) to the plugin logger. */logFindRequests?: boolean;+ agentExperience?: {+ enabled?: boolean;+ recallLimit?: number;+ scoreThreshold?: number;+ maxInjectedChars?: number;+ minQueryChars?: number;+ };+};++/** Runtime config after memoryOpenVikingConfigSchema.parse() has applied defaults. */+export type ParsedMemoryOpenVikingConfig = Required<+ Omit<MemoryOpenVikingConfig, "agentExperience">+> & {+ agentExperience: Required<NonNullable<MemoryOpenVikingConfig["agentExperience"]>>;};const DEFAULT_BASE_URL = "http://127.0.0.1:1933";@@ -64,6 +78,13 @@ const DEFAULT_BYPASS_SESSION_PATTERNS: string[] = [];const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;const DEFAULT_PEER_ROLE = "none" as const;const DEFAULT_PEER_PREFIX = "";+const DEFAULT_AGENT_EXPERIENCE = {+ enabled: false,+ recallLimit: 3,+ scoreThreshold: 0.35,+ maxInjectedChars: 6000,+ minQueryChars: 12,+};function resolvePeerPrefix(configured: unknown): string {if (typeof configured === "string" && configured.trim()) {@@ -126,6 +147,12 @@ function toStringArray(value: unknown, fallback: string[]): string[] {return fallback;}+function toRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? value as Record<string, unknown>+ : {};+}+/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */function envFlag(name: string): boolean {const v = getEnv(name);@@ -153,7 +180,7 @@ function resolveDefaultBaseUrl(): string {}export const memoryOpenVikingConfigSchema = {- parse(value: unknown): Required<MemoryOpenVikingConfig> {+ parse(value: unknown): ParsedMemoryOpenVikingConfig {if (!value || typeof value !== "object" || Array.isArray(value)) {value = {};}@@ -192,9 +219,16 @@ export const memoryOpenVikingConfigSchema = {"ingestReplyAssistIgnoreSessionPatterns","emitStandardDiagnostics","logFindRequests",+ "agentExperience",],"openviking config",);+ const agentExperienceRaw = toRecord(cfg.agentExperience);+ assertAllowedKeys(+ agentExperienceRaw,+ ["enabled", "recallLimit", "scoreThreshold", "maxInjectedChars", "minQueryChars"],+ "openviking config agentExperience",+ );const mode = "remote" as const;const peerRole = resolvePeerRole(cfg.peer_role);@@ -296,6 +330,37 @@ export const memoryOpenVikingConfigSchema = {cfg.logFindRequests === true ||envFlag("OPENVIKING_LOG_ROUTING") ||envFlag("OPENVIKING_DEBUG"),+ agentExperience: {+ enabled:+ typeof agentExperienceRaw.enabled === "boolean"+ ? agentExperienceRaw.enabled+ : DEFAULT_AGENT_EXPERIENCE.enabled,+ recallLimit: Math.max(+ 1,+ Math.min(+ 10,+ Math.floor(toNumber(agentExperienceRaw.recallLimit, DEFAULT_AGENT_EXPERIENCE.recallLimit)),+ ),+ ),+ scoreThreshold: Math.min(+ 1,+ Math.max(0, toNumber(agentExperienceRaw.scoreThreshold, DEFAULT_AGENT_EXPERIENCE.scoreThreshold)),+ ),+ maxInjectedChars: Math.max(+ 500,+ Math.min(+ 50_000,+ Math.floor(toNumber(agentExperienceRaw.maxInjectedChars, DEFAULT_AGENT_EXPERIENCE.maxInjectedChars)),+ ),+ ),+ minQueryChars: Math.max(+ 1,+ Math.min(+ 500,+ Math.floor(toNumber(agentExperienceRaw.minQueryChars, DEFAULT_AGENT_EXPERIENCE.minQueryChars)),+ ),+ ),+ },};},uiHints: {diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex f1bef7e51..1c772c299 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -1,16 +1,19 @@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 } from "./config.js";+import type { MemoryOpenVikingConfig, ParsedMemoryOpenVikingConfig } from "./config.js";import {AUTO_RECALL_SOURCE_MARKER,- buildAutoRecallContext,+ buildGatedAgentExperienceRecallContext,+ buildLongTermMemoryRecallContext,+ buildOpenVikingContextBlock,prepareRecallQuery,} from "./auto-recall.js";import {compileSessionPatterns,getCaptureDecision,extractNewTurnMessages,+ stripOpenVikingContextInjection,shouldBypassSession,} from "./text-utils.js";import {@@ -196,7 +199,7 @@ type RecallQueryInput = {source: "latestUserMessage" | "prompt" | "none";};-type AssembleRecall = Awaited<ReturnType<typeof buildAutoRecallContext>> & {+type AssembleRecall = Awaited<ReturnType<typeof buildLongTermMemoryRecallContext>> & {queryChars: number;};@@ -310,7 +313,11 @@ function extractAgentMessageText(message: AgentMessage | undefined): string {}function hasAutoRecallBlock(message: AgentMessage | undefined): boolean {- return extractAgentMessageText(message).includes(AUTO_RECALL_SOURCE_MARKER);+ const text = extractAgentMessageText(message);+ return (+ text.includes(AUTO_RECALL_SOURCE_MARKER) ||+ /<openviking-context\b/i.test(text)+ );}function prependTextToMessageContent(content: unknown, text: string): unknown {@@ -1094,7 +1101,7 @@ export function createMemoryOpenVikingContextEngine(params: {id: string;name: string;version?: string;- cfg: Required<MemoryOpenVikingConfig>;+ cfg: ParsedMemoryOpenVikingConfig;logger: Logger;getClient: () => Promise<OpenVikingClient>;/** Extra args help match hook-populated routing when OpenClaw provides sessionKey / OV session id. */@@ -1314,7 +1321,7 @@ export function createMemoryOpenVikingContextEngine(params: {);}- const recall = await buildAutoRecallContext({+ const recall = await buildLongTermMemoryRecallContext({cfg,client: params.client ?? await getClient(),agentId: params.agentId,@@ -1456,7 +1463,9 @@ export function createMemoryOpenVikingContextEngine(params: {latestRole: latestMessage?.role ?? null,});}- if (!cfg.autoRecall) {+ const longTermRecallEnabled = cfg.autoRecall;+ const experienceRecallEnabled = cfg.agentExperience.enabled;+ if (!longTermRecallEnabled && !experienceRecallEnabled) {return assemblePassthrough(OVSessionId, "transform_context_auto_recall_disabled", messages, originalTokens);}if (hasAutoRecallBlock(latestMessage)) {@@ -1472,23 +1481,63 @@ export function createMemoryOpenVikingContextEngine(params: {}try {+ const client = await getClient();const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);const peerId = resolveAssembleRecallPeerId(agentId, sender);- const recall = await buildRecallForAssemble({- ovSessionId: OVSessionId,- agentId,- peerId,- queryInput: recallQueryInput,+ const recallQuery = prepareRecallQuery(recallQueryInput.text);+ if (!recallQuery.query || recallQuery.query.length < 5) {+ diag("assemble_recall_skip", OVSessionId, {+ reason: "empty_or_short_query",+ querySource: recallQueryInput.source,+ queryChars: recallQuery.finalChars,+ peerId: peerId ?? null,+ });+ return assemblePassthrough(OVSessionId, "transform_context_empty_recall_query", messages, originalTokens);+ }+ if (recallQuery.truncated) {+ logger.info(+ `openviking: recall query truncated (` ++ `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,+ );+ }+ const experienceRecall = experienceRecallEnabled+ ? await buildGatedAgentExperienceRecallContext({+ cfg,+ client,+ agentId,+ queryText: recallQuery.query,+ sessionKey,+ runtimeContext: assembleParams.runtimeContext,+ logger,+ verbose: (message) => logger.info(message),+ })+ : { count: 0, estimatedTokens: 0, skippedReason: "disabled" };+ const longTermRecall = longTermRecallEnabled+ ? await buildLongTermMemoryRecallContext({+ cfg,+ client,+ agentId,+ peerId,+ queryText: recallQuery.query,+ logger,+ verbose: (message) => logger.info(message),+ })+ : { memoryCount: 0, estimatedTokens: 0 };+ const longTermRecallWithQuery: AssembleRecall = { ...longTermRecall, queryChars: recallQuery.finalChars };++ const combinedBlock = buildOpenVikingContextBlock({+ sections: [experienceRecall.block, longTermRecallWithQuery.section],});- if (!recall.block) {+ if (!combinedBlock) {return assemblePassthrough(OVSessionId, "transform_context_no_recall_hits", messages, originalTokens, {- ...recallDiagFields({ recall, queryInput: recallQueryInput, peerId }),+ ...recallDiagFields({ recall: longTermRecallWithQuery, queryInput: recallQueryInput, peerId }),+ experienceCount: experienceRecall.count,});}- const withRecall = prependRecallToLatestUserMessage(messages, recall.block);+ const withRecall = prependRecallToLatestUserMessage(messages, combinedBlock);const estimatedTokens = roughEstimate(withRecall);diag("assemble_result", OVSessionId, {passthrough: false,@@ -1496,7 +1545,9 @@ export function createMemoryOpenVikingContextEngine(params: {outputMessagesCount: withRecall.length,inputTokenEstimate: originalTokens,estimatedTokens,- ...recallDiagFields({ recall, queryInput: recallQueryInput, peerId, sender }),+ ...recallDiagFields({ recall: longTermRecallWithQuery, queryInput: recallQueryInput, peerId, sender }),+ autoRecallExperienceCount: experienceRecall.count,+ autoRecallExperienceTokens: experienceRecall.estimatedTokens,messages: messageDigest(withRecall),});return { messages: withRecall, estimatedTokens };@@ -1540,18 +1591,21 @@ export function createMemoryOpenVikingContextEngine(params: {});}}+ const recallContextBlock = recall.section+ ? buildOpenVikingContextBlock({ sections: [recall.section] })+ : "";let ctx;try {ctx = await client.getSessionContext(OVSessionId, tokenBudget, agentId);} catch (ctxErr) {- if (recall.block) {+ if (recallContextBlock) {return assembleRecallOnlyResult({ovSessionId: OVSessionId,reason: "recall_only_context_unavailable",baseMessages: messages,originalTokens,recall,- recallBlock: recall.block,+ recallBlock: recallContextBlock,queryInput: recallQueryInput,peerId,sender,@@ -1566,14 +1620,14 @@ export function createMemoryOpenVikingContextEngine(params: {const activeCount = ctx?.messages?.length ?? 0;if (!ctx || (!hasArchives && activeCount === 0)) {- if (recall.block) {+ if (recallContextBlock) {return assembleRecallOnlyResult({ovSessionId: OVSessionId,reason: "recall_only_no_ov_data",baseMessages: messages,originalTokens,recall,- recallBlock: recall.block,+ recallBlock: recallContextBlock,queryInput: recallQueryInput,peerId,sender,@@ -1604,8 +1658,8 @@ export function createMemoryOpenVikingContextEngine(params: {});}- const outputMessages = recall.block- ? injectRecallIntoContext(sanitized, recall.block)+ const outputMessages = recallContextBlock+ ? injectRecallIntoContext(sanitized, recallContextBlock): sanitized;const assembledTokens = roughEstimate(outputMessages) + instruction.tokens;const tokensSaved = originalTokens - assembledTokens;@@ -1749,11 +1803,8 @@ export function createMemoryOpenVikingContextEngine(params: {for (const msg of extractedMessages) {const ovParts = msg.parts.map((part) => {if (part.type === "text") {- // 清理 relevant-memories 块- const cleaned = part.text- .replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/gi, " ")- .replace(/\s+/g, " ")- .trim();+ // Strip OpenViking-injected context blocks.+ const cleaned = stripOpenVikingContextInjection(part.text);return { type: "text" as const, text: cleaned };} else {return {diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.jsonindex 70356476e..8656d342f 100644--- a/examples/openclaw-plugin/openclaw.plugin.json+++ b/examples/openclaw-plugin/openclaw.plugin.json@@ -325,6 +325,29 @@},"logFindRequests": {"type": "boolean"+ },+ "agentExperience": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "type": "boolean",+ "default": false,+ "description": "Enable agent experience memory recall. Default is false for conservative rollout."+ },+ "recallLimit": {+ "type": "number"+ },+ "scoreThreshold": {+ "type": "number"+ },+ "maxInjectedChars": {+ "type": "number"+ },+ "minQueryChars": {+ "type": "number"+ }+ }}}}diff --git a/examples/openclaw-plugin/tests/ut/agent-experience-recall.test.ts b/examples/openclaw-plugin/tests/ut/agent-experience-recall.test.tsnew file mode 100644index 000000000..248724d3c--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/agent-experience-recall.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";++import { shouldRecallAgentExperience } from "../../auto-recall.js";++describe("shouldRecallAgentExperience", () => {+ it("skips ordinary knowledge questions", () => {+ const result = shouldRecallAgentExperience({+ latestUserText: "preflight assemble 和 transformcontext assemble是什么区别",+ });+ expect(result.recall).toBe(false);+ });++ it("recalls for execution tasks", () => {+ const result = shouldRecallAgentExperience({+ latestUserText: "修一下 OpenClaw 插件里 afterTurn 写入 tool result 的问题",+ });+ expect(result.recall).toBe(true);+ expect(result.reason).toBe("task_execution");+ });++ it("forces recall for cron sessions", () => {+ const result = shouldRecallAgentExperience({+ latestUserText: "每天同步 benchmark 结果并生成报告",+ sessionKey: "agent:main:cron:nightly:run:1",+ triggerHint: "cron_start",+ });+ expect(result.recall).toBe(true);+ expect(result.reason).toBe("forced_trigger");+ expect(result.trigger).toBe("cron_start");+ });+});diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.tsindex a9306635c..d9a543739 100644--- a/examples/openclaw-plugin/tests/ut/config.test.ts+++ b/examples/openclaw-plugin/tests/ut/config.test.ts@@ -27,6 +27,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {expect(cfg.peer_role).toBe("none");expect(cfg.peer_prefix).toBe("");expect(cfg.emitStandardDiagnostics).toBe(false);+ expect(cfg.agentExperience.enabled).toBe(false);});it("defaults recallMaxInjectedChars to the 4000-character memory budget", () => {@@ -84,6 +85,14 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {).toThrow("unknown keys");});+ it("throws on unknown agentExperience keys", () => {+ expect(() =>+ memoryOpenVikingConfigSchema.parse({+ agentExperience: { autoRecall: true },+ }),+ ).toThrow("agentExperience has unknown keys");+ });+it("resolves environment variables in apiKey", () => {process.env.TEST_OV_API_KEY = "sk-test-key-123";const cfg = memoryOpenVikingConfigSchema.parse({diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.tsindex 0d5cd029d..6a42b9ab3 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts@@ -288,13 +288,13 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage.mock.calls[1][5]).toBe("test-agent");});- it("sanitizes <relevant-memories> from user content but not from assistant", async () => {+ it("sanitizes injected context blocks from user content", async () => {const { engine, client } = makeEngine();const messages = [{role: "user",- content: "my question <relevant-memories>injected memory data</relevant-memories> more text",+ content: "my question <openviking-context>injected memory data</openviking-context> more text",},];@@ -308,7 +308,7 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage).toHaveBeenCalledTimes(1);expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");const storedContent = (client.addSessionMessage.mock.calls[0][2] as Array<{ text?: string }>)[0].text;- expect(storedContent).not.toContain("relevant-memories");+ expect(storedContent).not.toContain("openviking-context");expect(storedContent).not.toContain("injected memory data");expect(storedContent).toContain("my question");});@@ -603,12 +603,12 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage.mock.calls[2][1]).toBe("assistant");});- it("sanitizes <relevant-memories> from assistant content", async () => {+ it("sanitizes injected context blocks from assistant content", async () => {const { engine, client } = makeEngine();const messages = [{ role: "user", content: "question" },- { role: "assistant", content: "Here is context <relevant-memories>data</relevant-memories> end" },+ { role: "assistant", content: "Here is context <openviking-context>data</openviking-context> end" },];await engine.afterTurn!({@@ -620,7 +620,7 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage).toHaveBeenCalledTimes(2);const assistantParts = client.addSessionMessage.mock.calls[1][2] as Array<{ text?: string }>;- expect(assistantParts.map(p => p.text).join(" ")).not.toContain("relevant-memories");+ expect(assistantParts.map(p => p.text).join(" ")).not.toContain("openviking-context");expect(assistantParts.map(p => p.text).join(" ")).toContain("Here is context");});diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex 1ebedd38a..fd2a2e197 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -141,7 +141,8 @@ describe("context-engine assemble()", () => {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).toMatch(/^<openviking-context>/);+ expect(result.messages[2]?.content).toContain("## Long-term Memories");expect(result.messages[2]?.content).toContain("Source: openviking-auto-recall");expect(result.messages[2]?.content).toContain("<uri>viking://user/default/memories/rust-pref</uri>",@@ -187,7 +188,7 @@ describe("context-engine assemble()", () => {messages: sourceMessages,});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {expect(call[1]).toMatchObject({ peerId: "wx_user-01_abc" });}@@ -265,12 +266,15 @@ describe("context-engine assemble()", () => {prompt,});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {expect(call[1]).toMatchObject({ peerId: "ou_bcc" });}expect(result.messages[0]?.role).toBe("user");expect(result.messages[0]?.content).toContain("Source: openviking-auto-recall");+ expect(result.messages[0]?.content).toContain("<openviking-context>");+ expect(result.messages[0]?.content).toContain("## Long-term Memories");+ expect(result.messages[0]?.content).not.toContain("<relevant-memories>");expect(result.messages[0]?.content).toContain("正在维护的项目:openviking");} finally {vi.unstubAllGlobals();@@ -317,7 +321,7 @@ describe("context-engine assemble()", () => {].join("\n"),});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {expect(call[1]).toMatchObject({ peerId: "trusted_runtime-user" });}@@ -361,7 +365,7 @@ describe("context-engine assemble()", () => {messages: sourceMessages,});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {expect(call[1]).toMatchObject({ peerId: "agent:session-assistant-peer" });}@@ -370,6 +374,233 @@ describe("context-engine assemble()", () => {}});+ it("keeps experience memories out of Long-term Memories and renders them in Agent Experiences", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ recallPreferAbstract: true,+ agentExperience: {+ enabled: true,+ recallLimit: 3,+ scoreThreshold: 0.35,+ maxInjectedChars: 6000,+ minQueryChars: 12,+ },+ },+ },+ );++ const experienceHit = {+ uri: "viking://agent/main/memories/experiences/openclaw-plugin-file-write-guard.md",+ level: 2,+ category: "experience",+ abstract: "经验摘要",+ score: 0.91,+ };+ const longTermHit = {+ uri: "viking://user/default/memories/profile.md",+ level: 2,+ category: "profile",+ abstract: "张明的主要技术栈是 Elixir 和 Zig。",+ score: 0.83,+ };++ client.find+ .mockResolvedValueOnce({+ memories: [experienceHit],+ total: 1,+ })+ .mockResolvedValueOnce({+ memories: [longTermHit],+ total: 1,+ })+ .mockResolvedValueOnce({+ memories: [experienceHit],+ total: 1,+ });++ client.read.mockImplementation(async (uri: string) => {+ if (uri === experienceHit.uri) {+ return [+ "## Situation",+ "- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。",+ "",+ "## Approach",+ "- 在写回 OV session 前剥离注入上下文块。",+ "",+ "## Reflect",+ "- 避免把注入经验再次写回 transcript。",+ ].join("\n");+ }+ if (uri === longTermHit.uri) {+ return "张明的主要技术栈是 Elixir 和 Zig。";+ }+ return "";+ });++ const result = await engine.assemble({+ sessionId: "session-transform-experience",+ messages: [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题,并告诉我张明的技术栈。" },+ ],+ });++ const injected = String(result.messages[1]?.content ?? "");+ expect(injected).toMatch(/^<openviking-context>/);+ expect(injected).not.toContain("<relevant-memories>");+ expect(injected).toContain("## Agent Experiences");+ expect(injected).toContain("### Experience: openclaw-plugin-file-write-guard");+ expect(injected).toContain("## Long-term Memories");+ expect(injected).toContain("张明的主要技术栈是 Elixir 和 Zig。");++ const longTermSection = injected.split("## Long-term Memories")[1] ?? "";+ expect(longTermSection).not.toContain("### Experience:");+ expect(longTermSection).not.toContain("剥离注入上下文块");+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("keeps task gating enabled when agent experience is enabled", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: false,+ agentExperience: {+ enabled: true,+ },+ },+ },+ );++ const result = await engine.assemble({+ sessionId: "session-transform-experience-gated",+ messages: [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "preflight assemble 和 transformcontext assemble是什么区别" },+ ],+ });++ expect(client.find).not.toHaveBeenCalled();+ expect(result.messages[1]?.content).toBe("preflight assemble 和 transformcontext assemble是什么区别");+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("does not recall agent experiences by default", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ status: "ok" }),+ }),+ );+ try {+ const { engine, client } = makeEngine(+ {+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: false,+ },+ },+ );++ const result = await engine.assemble({+ sessionId: "session-experience-default-off",+ messages: [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ { role: "user", content: "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题" },+ ],+ });++ expect(client.find).not.toHaveBeenCalled();+ expect(result.messages[1]?.content).toBe("修一下 OpenClaw 插件里 afterTurn 写回 session 的问题");+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("does not inject again when latest user message already has an OpenViking context block", async () => {+ const { engine, getClient } = makeEngine(+ {+ latest_archive_overview: "unused",+ pre_archive_abstracts: [],+ messages: [],+ estimatedTokens: 0,+ stats: makeStats(),+ },+ {+ cfgOverrides: {+ autoRecall: true,+ agentExperience: {+ enabled: true,+ },+ },+ },+ );+ const sourceMessages = [+ { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },+ {+ role: "user",+ content: [+ "<openviking-context>",+ "already injected OpenViking context",+ "</openviking-context>",+ "",+ "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题",+ ].join("\n"),+ },+ ];++ const result = await engine.assemble({+ sessionId: "session-existing-openviking-context-block",+ messages: sourceMessages,+ });++ expect(getClient).not.toHaveBeenCalled();+ expect(result.messages).toBe(sourceMessages);+ expect(result.estimatedTokens).toBe(roughEstimate(sourceMessages));+ });+it("passes through transformContext messages when the latest message is not user", async () => {const { engine, getClient } = makeEngine({@@ -410,6 +641,10 @@ describe("context-engine assemble()", () => {messages: [],estimatedTokens: 0,stats: makeStats(),+ }, {+ cfgOverrides: {+ autoRecall: false,+ },});const sourceMessages = [{ role: "assistant", content: [{ type: "text", text: "Previous answer." }] },diff --git a/examples/openclaw-plugin/tests/ut/text-utils.test.ts b/examples/openclaw-plugin/tests/ut/text-utils.test.tsindex 29c9b0ff5..f375425a8 100644--- a/examples/openclaw-plugin/tests/ut/text-utils.test.ts+++ b/examples/openclaw-plugin/tests/ut/text-utils.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {sanitizeUserTextForCapture,+ stripOpenVikingContextInjection,getCaptureDecision,extractNewTurnMessages,extractNewTurnTexts,@@ -19,6 +20,14 @@ describe("sanitizeUserTextForCapture", () => {expect(result).toContain("world");});+ it("strips <openviking-context> blocks", () => {+ const input = "hello <openviking-context>context</openviking-context> world";+ const result = sanitizeUserTextForCapture(input);+ expect(result).not.toContain("openviking-context");+ expect(result).toContain("hello");+ expect(result).toContain("world");+ });+it("strips metadata JSON blocks with ≥3 metadata keys", () => {const input = 'prefix ```json\n{"session":"s1","userId":"u1","agentId":"a1","channel":"ch"}\n``` suffix';const result = sanitizeUserTextForCapture(input);@@ -61,6 +70,19 @@ describe("sanitizeUserTextForCapture", () => {});});+describe("stripOpenVikingContextInjection", () => {+ it("strips OpenViking context and relevant memories injected blocks", () => {+ const input = [+ "hello",+ "<openviking-context>ctx</openviking-context>",+ "<relevant-memories>legacy</relevant-memories>",+ "world",+ ].join(" ");+ const result = stripOpenVikingContextInjection(input);+ expect(result).toBe("hello world");+ });+});+describe("getCaptureDecision", () => {it("semantic mode: normal text → shouldCapture=true", () => {const result = getCaptureDecision("我喜欢用 Python 写代码,平时也用 Go", "semantic", 24000);diff --git a/examples/openclaw-plugin/text-utils.ts b/examples/openclaw-plugin/text-utils.tsindex 4f715f8fc..a0494df42 100644--- a/examples/openclaw-plugin/text-utils.ts+++ b/examples/openclaw-plugin/text-utils.ts@@ -12,6 +12,7 @@ export const MEMORY_TRIGGERS = [const CJK_CHAR_REGEX = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;+const OPENVIKING_CONTEXT_BLOCK_RE = /<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi;const CONVERSATION_METADATA_BLOCK_RE =/(?:^|\n)\s*(?:Conversation info|Conversation metadata|会话信息|对话信息)\s*(?:\([^)]+\))?\s*:\s*```[\s\S]*?```/gi;/** Strips "Sender (untrusted metadata): ```json ... ```" so capture sends clean text to OpenViking extract. */@@ -60,6 +61,7 @@ export function sanitizeUserTextForCapture(text: string): string {return "";}return text+ .replace(OPENVIKING_CONTEXT_BLOCK_RE, " ").replace(RELEVANT_MEMORIES_BLOCK_RE, " ").replace(CONVERSATION_METADATA_BLOCK_RE, " ").replace(SENDER_METADATA_BLOCK_RE, " ")@@ -73,6 +75,14 @@ export function sanitizeUserTextForCapture(text: string): string {.trim();}+export function stripOpenVikingContextInjection(text: string): string {+ return text+ .replace(OPENVIKING_CONTEXT_BLOCK_RE, " ")+ .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")+ .replace(/\s+/g, " ")+ .trim();+}+export function looksLikeQuestionOnlyText(text: string): boolean {if (!QUESTION_CUE_RE.test(text) || MEMORY_INTENT_RE.test(text)) {return false;