Skip to content

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

feat(usage): emit resource-scoped experience usage records (#3921)

agent00f3738edbc3
diff --git a/docs/design/openviking-usage-count-record-implementation-plan.md b/docs/design/openviking-usage-count-record-implementation-plan.md
index 00f24ad5d..12a02d2d8 100644
--- a/docs/design/openviking-usage-count-record-implementation-plan.md
+++ b/docs/design/openviking-usage-count-record-implementation-plan.md
@@ -1,12 +1,12 @@
-# File Usage CountRecord Implementation Plan
+# File Usage Event Log Implementation Plan
**Goal:** 将 Usage Reporter 生成的 `UsageEvent` 转换为稳定的
-`CountRecord` 日志协议,供部署侧日志采集系统读取并投递到下游。
+计量日志协议,供部署侧日志采集系统读取并投递到下游。
**Architecture:** `MemoryUsageExtractor` 继续生成内部 `UsageEvent`。
-`FileLogUsageSink` 在写入专用日志文件前执行单向转换,每行保存一个包含 Kafka
-message key 和对应 `CountRecord` 的 JSON envelope。`unique_id` 作为稳定事件标识,
-供下游在 best-effort 投递发生重复时去重。
+`FileLogUsageSink` 在写入专用日志文件前执行单向转换,每行保存一个扁平 JSON
+计量事件。`object_id` 作为稳定事件标识,供下游在 best-effort 投递发生重复时
+与 `tenant_id` 组成复合键去重。
**Tech Stack:** Python 3.10+、dataclasses、标准库
`datetime` / `json` / `logging`、pytest、Ruff。
@@ -16,58 +16,42 @@ message key 和对应 `CountRecord` 的 JSON envelope。`unique_id` 作为稳定
## 文件结构
- `openviking/usage_reporter/file_log_sink.py`
- - 定义 `UsageEvent -> CountRecord` 私有转换。
- - 构造资源归属 message key。
+ - 定义 `UsageEvent -> 计量日志` 私有转换。
+ - 构造资源归属 `tenant_id`。
- 将记录追加到按 UTC 小时滚动的专用日志文件。
- `tests/unit/usage_reporter/test_file_log_sink.py`
- - 固定 recall/inject 字段映射、毫秒时间戳、扩展字段和未知事件行为。
+ - 固定 recall/inject 字段映射、UTC 时间、租户字段和未知事件行为。
- 验证多 worker 共享文件时的写入和滚动行为。
- `docs/design/openviking-usage-reporter-sink-design.md`
- 定义 Usage Reporter、Sink 扩展点和文件日志协议。
-## CountRecord 映射契约
+## 计量日志映射契约
`memory.recalled` 事件映射为:
```json
{
- "count_name": "experience.recall.count",
- "op_type": "add",
- "amount": 1.0,
- "timestamp": 1785124800000,
- "unique_id": "ue_recall",
+ "event_time": "2026-08-05 11:30:00",
+ "tenant_id": "resource_id:ov-resource-id;account_id:2101858484;user_id:user-1;resource_uri:viking://user/user-1/memories/experiences/exchange.md",
+ "event_name": "experience.recall.count",
+ "object_id": "ue_recall",
+ "count": 1,
"tags": {
- "account_id": "2101858484",
- "user_id": "user-1",
- "resource_uri": "viking://user/user-1/memories/experiences/exchange.md",
"resource_type": "experience"
- },
- "extra": {
- "session_id": "session-1",
- "task_id": "task-1",
- "archive_uri": "viking://user/user-1/sessions/session-1/history/archive_001",
- "message_id": "msg-1",
- "tool_call_id": "call-1",
- "tool_name": "search_experience",
- "attributes": {
- "rank": 1
- }
- },
- "prefix": "ov-resource-id"
+ }
}
```
映射规则:
-- `memory.recalled` 映射为
- `count_name=experience.recall.count`。
-- `memory.injected` 映射为
- `count_name=experience.inject.count`。
-- `op_type` 固定为 `add`,`amount` 固定为 `1.0`。
-- `occurred_at` 转换为毫秒时间戳。
-- `event_id` 写入 `unique_id`,为空时拒绝写入。
-- 非空 `UsageEvent.attributes` 写入 `extra.attributes`。
-- `resource_id_env` 指定的环境变量写入 `prefix`。
+- `memory.recalled` 映射为 `event_name=experience.recall.count`。
+- `memory.injected` 映射为 `event_name=experience.inject.count`。
+- `count` 固定为 `1`。
+- `occurred_at` 转换为 UTC `YYYY-MM-DD HH:MM:SS`。
+- `event_id` 写入 `object_id`,为空时拒绝写入。
+- `tenant_id` 拼接部署 `resource_id`、`account_id`、`user_id` 和 `resource_uri`。
+- `resource_id` 从 `resource_id_env` 指定的环境变量读取,未配置时拒绝启动 Sink。
+- `tags.resource_type` 记录资源类型。
- 未知 `event_type` 拒绝写入,避免产生无法解释的计量记录。
## 文件日志协议
@@ -75,16 +59,16 @@ message key 和对应 `CountRecord` 的 JSON envelope。`unique_id` 作为稳定
日志行格式:
```text
-{"key":"<resource_id>|<account_id>|<user_id>|<resource_uri>","value":<CountRecord JSON>}
+{"event_time":"<UTC time>","tenant_id":"resource_id:<resource>;account_id:<account>;user_id:<user>;resource_uri:<uri>","event_name":"<event>","object_id":"<event_id>","count":1,"tags":{"resource_type":"experience"}}
```
-当 `resource_uri` 为空时,message key 的最后一段使用 `session_id`。
-整行使用 JSON envelope,key 中的 `=`、空格或其他字符不会影响 key/value 拆分。
日志文件不复用 OpenViking stdout,按 UTC 小时滚动,并保留配置数量的历史
文件。多个 server worker 写入同一路径时,文件追加和滚动通过进程间锁串行化。
文件落盘及后续采集均采用 best-effort 语义。下游必须按
-`CountRecord.unique_id` 去重。
+`(tenant_id, object_id)` 复合键去重,不能跨 tenant 仅按 `object_id` 全局去重。
+次数查询按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,并计算
+`sum(count)`。
## 验证
diff --git a/docs/design/openviking-usage-reporter-sink-design.md b/docs/design/openviking-usage-reporter-sink-design.md
index c9ba42c35..08767d339 100644
--- a/docs/design/openviking-usage-reporter-sink-design.md
+++ b/docs/design/openviking-usage-reporter-sink-design.md
@@ -78,7 +78,7 @@ UsageEvent 是 OpenViking 内核和外部 Sink 之间的稳定协议。
"archive_uri": "viking://user/test/sessions/510bb5f9/history/archive_001",
"message_id": "msg_xxx",
"tool_call_id": "call_xxx",
- "tool_name": "read_experience"
+ "tool_name": "mcp__openviking__read"
},
"attributes": {}
}
@@ -90,6 +90,23 @@ UsageEvent 是 OpenViking 内核和外部 Sink 之间的稳定协议。
UsageEvent 是可独立传输和消费的完整事件。`UsageContext` 只用于 Extractor 构造事件,不再重复传给 Sink。
+### 5.1 Experience 使用事件识别
+
+插件使用 OpenViking 原生通用工具消费 Experience,不额外注册 Experience 专用工具:
+
+- 成功的 `find`、`search`、`list` 调用结果中出现 Experience URI,产生 `memory.recalled`。
+- 成功的 `read`、`multi_read` 调用实际读取 Experience URI,产生 `memory.injected`。
+- 支持 OpenCode 的 `openviking_*`、OpenClaw 的 `ov_*` 和
+ `mcp__openviking__*` 命名空间形式;仅按受支持的工具名精确识别。
+- 通用工具返回其他记忆类型时,只保留当前用户 `memories/experiences/` 目录下的规范文件 URI。
+- `search_experience`、`read_experience` 已下线,不再生成使用事件或 Experience 应用关系。
+
+升级时应先升级 Agent 插件,或让插件与 OpenViking 内核同步升级。若先升级内核、
+仍由旧插件调用 `search_experience`、`read_experience`,工具调用本身不受影响,但升级
+窗口内不会生成 Experience 使用事件。历史 archive 中的专用工具记录不做追溯转换。
+OpenClaw 旧配置中的 `enabledTools: ["experience"]` 仍可启动,该 selector 作为迁移
+别名映射到通用 `ov_search`、`ov_read`;新配置不再使用该别名。
+
## 6. UsageSink 机制
OpenViking 开源包定义统一的 Sink 抽象:
@@ -136,36 +153,31 @@ HTTP 请求。日志文件使用 UTC 小时滚动,默认保留 168 个小时
时,通过进程间文件锁串行化写入和滚动;Windows worker 写入后主动关闭文件句柄,
避免其他进程滚动重命名失败。
-### 6.1 文件日志 CountRecord 协议
+### 6.1 文件日志计量协议
`UsageEvent` 继续作为 OpenViking 内部抽取结果和自定义 Sink 的稳定协议。内置
-文件日志 Sink 将 `UsageEvent` 转换为计量接收端使用的 `CountRecord`。每个事件
-写成一行包含 Kafka key/value 的 JSON envelope:
+文件日志 Sink 将 `UsageEvent` 转换为计量接收端使用的扁平 JSON。每个事件写成
+一行:
-```text
-{"key":"ov-xxx|new|test|viking://user/test/memories/experiences/example.md","value":{"count_name":"experience.recall.count","op_type":"add","amount":1.0,"timestamp":1785124800000,"unique_id":"ue_<sha256>","tags":{"account_id":"new","user_id":"test","resource_uri":"viking://user/test/memories/experiences/example.md","resource_type":"experience"},"extra":{"session_id":"session-id","task_id":"task-id","archive_uri":"viking://user/test/sessions/session-id/history/archive_001","message_id":"message-id","tool_call_id":"tool-call-id","tool_name":"search_experience"},"prefix":"ov-xxx"}}
+```json
+{"event_time":"2026-08-05 11:30:00","tenant_id":"resource_id:ov-xxx;account_id:new;user_id:test;resource_uri:viking://user/test/memories/experiences/example.md","event_name":"experience.recall.count","object_id":"ue_<sha256>","count":1,"tags":{"resource_type":"experience"}}
```
字段映射:
-- envelope 的 `key` 与原 Kafka message key 一致,格式为
- `resource_id|account_id|user_id|resource_uri`;`resource_uri` 为空时回退
- 到 `session_id`。
-- envelope 的 `value` 是原 Kafka message value 的完整 JSON,不拆分内部字段。
-- 整行使用 JSON envelope,key 中的分隔符不会影响 key/value 解析。
-- JSON 中的 `prefix` 为 OpenViking 实例的 resource ID。
-- `memory.recalled` 映射为 `count_name=experience.recall.count`。
-- `memory.injected` 映射为 `count_name=experience.inject.count`。
-- `op_type` 固定为 `add`。
-- `amount` 固定为 `1.0`。
-- `timestamp` 由 `occurred_at` 转换为 Unix 毫秒时间戳。
-- JSON 中的 `unique_id` 使用稳定的 `event_id`。
-- JSON 中的 `tags` 保存 `account_id`、`user_id`、`resource_uri` 和
- `resource_type`。
-- JSON 中的 `extra` 保存 `session_id`、可选的 `task_id` 以及 `evidence`
- 中的审计字段。
-- 非空的 `UsageEvent.attributes` 原样写入 `extra.attributes`。
-- 空的可选字段不写入 `extra`。
+- `event_time` 由 `occurred_at` 转换为 UTC `YYYY-MM-DD HH:MM:SS`。
+- `tenant_id` 固定为
+ `resource_id:<resource_id>;account_id:<account_id>;user_id:<user_id>;resource_uri:<resource_uri>`。
+- `memory.recalled` 映射为 `event_name=experience.recall.count`。
+- `memory.injected` 映射为 `event_name=experience.inject.count`。
+- `object_id` 使用稳定的 `event_id`。下游以 `(tenant_id, object_id)` 作为复合去重键,
+ 不跨 tenant 单独按 `object_id` 去重。
+- `count` 固定为 `1`。
+- `tags.resource_type` 固定记录被使用资源的类型;本期只产生
+ `experience` 使用事件。
+
+接收端按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,并通过
+`sum(count)` 聚合使用次数。
无法识别的 `event_type` 不生成含义不明确的计量记录,转换时抛出错误并由
Reporter 的 best-effort 隔离机制处理。
@@ -208,6 +220,9 @@ server:
backup_count: 168
```
+部署时必须设置 `resource_id_env` 指定的环境变量。Sink 使用其值构造
+`tenant_id`,保证不同 OpenViking resource 的数据相互隔离。
+
## 8. 对 OpenViking 的侵入
侵入点控制在 4 个地方。
@@ -256,7 +271,8 @@ Usage Reporter 采用 best-effort 投递语义:
- 多个 Sink 相互隔离,某个 Sink 失败不影响其他 Sink。
- Sink 失败时事件可能丢失,因此本机制不保证 at-least-once。
- 如果 Sink 已写入成功,但进程在 phase2 写入完成标记前退出,phase2 恢复执行时可能重复发送同一事件。
-- 每个事件包含稳定的 `event_id`。Sink 可将其作为 Kafka message key,消费端可按 `event_id` 去重。
+- 每个事件包含稳定的 `event_id`。Sink 可将其作为 Kafka message key;消费端按
+ `(tenant_id, object_id)` 复合键去重。
- `event_id` 只用于识别重复事件,不代表事件一定成功送达。
`event_id` 为以下字段规范序列化后的 SHA-256:
@@ -278,4 +294,4 @@ schema_version
内置文件日志 Sink 在 `write()` 返回前完成本地追加,但不负责 TLS 采集、Kafka
投递或下游确认。文件写入、TLS 采集和下游消费任一阶段都可能在故障时产生丢失
-或重复,消费端需按 `unique_id` 去重,整体保持 best-effort 语义。
+或重复,消费端需按 `(tenant_id, object_id)` 复合键去重,整体保持 best-effort 语义。
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 562d0964d..f27398883 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1569,7 +1569,7 @@ When `root_api_key` is configured in `api_key` mode, the server enables multi-te
### Usage Reporter
-The optional Usage Reporter extracts memory usage events from committed session tool parts. The built-in file log sink writes each event as a `{"key": ..., "value": ...}` JSON envelope to a dedicated hourly rotating file:
+The optional Usage Reporter extracts memory usage events from committed session tool parts. The built-in file log sink writes each event as one flat JSON object to a dedicated hourly rotating file:
```json
{
@@ -1598,9 +1598,15 @@ using `"type": "http"` must migrate to `file_log` and collect the dedicated
log files, or configure a `custom` sink that implements their delivery
contract.
-Set the environment variable named by `resource_id_env` before starting the server. The sink creates the parent directory, appends events immediately, rotates the active file every UTC hour, and retains `backup_count` rotated files. It does not write to the default OpenViking stdout log.
+Set the environment variable named by `resource_id_env` before starting the server. Its value identifies the deployed OpenViking resource and isolates otherwise identical account, user, and URI combinations. The sink creates the parent directory, appends events immediately, rotates the active file every UTC hour, and retains `backup_count` rotated files. It does not write to the default OpenViking stdout log.
-Each line is a JSON envelope with `key` and `value` fields. `key` matches the original Kafka message key and has the form `resource_id|account_id|user_id|resource_uri`; it falls back to `session_id` when `resource_uri` is empty. `value` is the complete object used as the original Kafka message value, containing `count_name`, `op_type`, `amount`, `timestamp`, `unique_id`, `tags`, `extra`, and `prefix`. The JSON envelope preserves delimiters that appear inside the key. File collection and downstream delivery remain best-effort, so consumers should deduplicate by `value.unique_id`.
+Each line has the following form:
+
+```json
+{"event_time":"2026-08-05 11:30:00","tenant_id":"resource_id:ov-example;account_id:default;user_id:default;resource_uri:viking://user/default/memories/experiences/example.md","event_name":"experience.recall.count","object_id":"ue_<sha256>","count":1,"tags":{"resource_type":"experience"}}
+```
+
+`event_time` is UTC. `tenant_id` combines the deployment resource ID, event account, user, and Experience URI. `memory.recalled` maps to `experience.recall.count`, while `memory.injected` maps to `experience.inject.count`. `object_id` is the stable Usage Event ID. Downstream consumers must deduplicate by the composite `(tenant_id, object_id)` key rather than by `object_id` globally. Aggregate usage with `sum(count)` after filtering by `tenant_id`, `event_name`, and the desired `event_time` range. File collection and downstream delivery remain best-effort.
Supported add target URIs:
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 63cfb4700..dd4116536 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1651,7 +1651,7 @@ openviking add-resource ./docs --exclude "*.tmp"
### Usage Reporter
-可选的 Usage Reporter 从已 commit session 的 tool parts 中抽取记忆使用事件。内置文件日志 Sink 将每个事件写成一行 `{"key": ..., "value": ...}` JSON envelope,并按小时滚动专用日志文件:
+可选的 Usage Reporter 从已 commit session 的 tool parts 中抽取记忆使用事件。内置文件日志 Sink 将每个事件写成一行扁平 JSON,并按小时滚动专用日志文件:
```json
{
@@ -1679,9 +1679,15 @@ openviking add-resource ./docs --exclude "*.tmp"
`"type": "http"` 的部署需要迁移为 `file_log` 并采集专用日志文件,或配置实现
原投递协议的 `custom` Sink。
-启动服务前,需要设置 `resource_id_env` 指定的环境变量。Sink 会自动创建父目录、立即追加事件、按 UTC 每小时滚动文件,并保留 `backup_count` 个历史文件;它不会写入 OpenViking 默认 stdout 日志。
+启动服务前需要设置 `resource_id_env` 指定的环境变量。该变量的值用于标识当前部署的 OpenViking 资源,隔离 account、user 和 URI 相同但 resource 不同的数据。Sink 会自动创建父目录、立即追加事件、按 UTC 每小时滚动文件,并保留 `backup_count` 个历史文件;它不会写入 OpenViking 默认 stdout 日志。
-每行是包含 `key` 和 `value` 字段的 JSON envelope。`key` 与原 Kafka 消息键一致,格式为 `resource_id|account_id|user_id|resource_uri`;`resource_uri` 为空时使用 `session_id`。`value` 是原 Kafka 消息的完整对象,包含 `count_name`、`op_type`、`amount`、`timestamp`、`unique_id`、`tags`、`extra` 和 `prefix`。JSON envelope 能完整保留 key 内部的分隔符。文件采集和下游投递仍为 best-effort,消费端应按 `value.unique_id` 去重。
+每行格式如下:
+
+```json
+{"event_time":"2026-08-05 11:30:00","tenant_id":"resource_id:ov-example;account_id:default;user_id:default;resource_uri:viking://user/default/memories/experiences/example.md","event_name":"experience.recall.count","object_id":"ue_<sha256>","count":1,"tags":{"resource_type":"experience"}}
+```
+
+`event_time` 使用 UTC 时间。`tenant_id` 由部署 resource ID、事件所属的 account、user 和 Experience URI 拼接。`memory.recalled` 映射为 `experience.recall.count`,`memory.injected` 映射为 `experience.inject.count`。`object_id` 是稳定的 Usage Event ID。下游必须使用 `(tenant_id, object_id)` 复合键去重,不能跨 tenant 仅按 `object_id` 全局去重。查询时按 `tenant_id`、`event_name` 和 `event_time` 范围过滤,再通过 `sum(count)` 汇总。文件采集和下游投递仍为 best-effort。
支持的 add target URI:
diff --git a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
index 0cc76778f..3e078db47 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
@@ -102,6 +102,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -112,6 +113,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -122,8 +124,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -134,6 +138,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -147,11 +152,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -163,13 +176,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index edc6b96f1..2481cdd6b 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -30,8 +30,7 @@
"Pre-compaction memory extraction",
"Session archive search and original-text read-back",
"Resource ingestion for RAG (add_resource)",
- "Explicit MCP tools for retrieval, memory, resources, watches, filesystem, and code navigation",
- "Experience Memory skill with dedicated search_experience and read_experience tools"
+ "Explicit MCP tools for retrieval, memory, resources, watches, filesystem, and code navigation"
],
"websiteURL": "https://github.com/volcengine/OpenViking"
}
diff --git a/examples/codex-memory-plugin/scripts/capture-utils.mjs b/examples/codex-memory-plugin/scripts/capture-utils.mjs
index 288f729ca..4f01546f3 100644
--- a/examples/codex-memory-plugin/scripts/capture-utils.mjs
+++ b/examples/codex-memory-plugin/scripts/capture-utils.mjs
@@ -171,59 +171,8 @@ function normalizeCodexMcpToolEvents(rolloutEntries) {
});
}
-function parseJsonObject(value) {
- if (typeof value !== "string" || !value.trim()) return null;
- try {
- const parsed = JSON.parse(value);
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
- } catch {
- return null;
- }
-}
-
-function collectExperienceUsageMetadata(rolloutEntries) {
- const metadata = new Map();
- for (const entry of rolloutEntries || []) {
- const payload = entry?.payload;
- if (payload?.type !== "mcp_tool_call_end" || !payload.call_id) continue;
- const toolName = payload.invocation?.tool;
- if (toolName !== "search_experience" && toolName !== "read_experience") continue;
-
- const item = {
- toolName,
- toolInput: payload.invocation?.arguments || {},
- };
- if (toolName === "search_experience") {
- const output = parseJsonObject(mcpResultText(payload.result));
- const results = Array.isArray(output?.results) ? output.results : [];
- item.compactOutput = JSON.stringify({
- results: results
- .map((result) => ({ uri: String(result?.uri || "").trim() }))
- .filter((result) => result.uri),
- });
- }
- metadata.set(payload.call_id, item);
- }
- return metadata;
-}
-
export function extractCaptureTurns(rolloutEntries, cfg = {}) {
- const usageMetadata = collectExperienceUsageMetadata(rolloutEntries);
const deduplicated = deduplicateMcpFunctionEvents(rolloutEntries);
const normalized = normalizeCodexNativeToolEvents(deduplicated);
- const turns = extractSharedCaptureTurns(normalizeCodexMcpToolEvents(normalized), cfg);
- return turns.map((turn) => ({
- ...turn,
- parts: turn.parts.map((part) => {
- if (part?.tool_status !== "completed" || !part.tool_id) return part;
- const metadata = usageMetadata.get(part.tool_id);
- if (!metadata) return part;
-
- const updated = { ...part, tool_input: metadata.toolInput };
- if (metadata.toolName === "search_experience" && !parseJsonObject(part.tool_output)) {
- updated.tool_output = metadata.compactOutput;
- }
- return updated;
- }),
- }));
+ return extractSharedCaptureTurns(normalizeCodexMcpToolEvents(normalized), cfg);
}
diff --git a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
index db4fa4ad4..0c7c68498 100644
--- a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
+++ b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
@@ -261,7 +261,7 @@ test("captures Codex subagent messages and activity with identity", () => {
]);
});
-test("captures Codex mcp_tool_call_end as standard tool parts", () => {
+test("captures generic OpenViking MCP calls as standard tool parts", () => {
const results = {
results: [
{
@@ -279,8 +279,11 @@ test("captures Codex mcp_tool_call_end as standard tool parts", () => {
call_id: "exec-search-1",
invocation: {
server: "openviking-memory",
- tool: "search_experience",
- arguments: { query: "无订单号换货" },
+ tool: "find",
+ arguments: {
+ query: "无订单号换货",
+ target_uri: "viking://user/test/memories/experiences/",
+ },
},
result: {
Ok: {
@@ -296,14 +299,17 @@ test("captures Codex mcp_tool_call_end as standard tool parts", () => {
assert.deepEqual(turns, [
{
role: "assistant",
- text: "[tool-call search_experience] {\"query\":\"无订单号换货\"}",
+ text: "[tool-call find] {\"query\":\"无订单号换货\",\"target_uri\":\"viking://user/test/memories/experiences/\"}",
parts: [
{
type: "tool",
tool_id: "exec-search-1",
- tool_name: "search_experience",
+ tool_name: "find",
tool_status: "running",
- tool_input: { query: "无订单号换货" },
+ tool_input: {
+ query: "无订单号换货",
+ target_uri: "viking://user/test/memories/experiences/",
+ },
},
],
},
@@ -314,9 +320,8 @@ test("captures Codex mcp_tool_call_end as standard tool parts", () => {
{
type: "tool",
tool_id: "exec-search-1",
- tool_name: "search_experience",
+ tool_name: "find",
tool_status: "completed",
- tool_input: { query: "无订单号换货" },
tool_output: JSON.stringify(results),
},
],
@@ -324,7 +329,7 @@ test("captures Codex mcp_tool_call_end as standard tool parts", () => {
]);
});
-test("keeps MCP tool-level errors out of completed Experience tool parts", () => {
+test("keeps MCP tool-level errors out of completed generic read tool parts", () => {
const uri = "viking://user/test/memories/experiences/a.md";
const turns = extractCaptureTurns(
[
@@ -335,7 +340,7 @@ test("keeps MCP tool-level errors out of completed Experience tool parts", () =>
call_id: "exec-read-error",
invocation: {
server: "openviking-memory",
- tool: "read_experience",
+ tool: "read",
arguments: { uri },
},
result: {
@@ -355,7 +360,7 @@ test("keeps MCP tool-level errors out of completed Experience tool parts", () =>
assert.equal(parts.some((part) => part.tool_status === "completed"), false);
});
-test("preserves Experience usage metadata when Codex truncates a long MCP result", () => {
+test("preserves generic read input when Codex truncates a long MCP result", () => {
const uri = "viking://user/test/memories/experiences/long-experience.md";
const turns = extractCaptureTurns(
[
@@ -366,7 +371,7 @@ test("preserves Experience usage metadata when Codex truncates a long MCP result
call_id: "exec-read-long",
invocation: {
server: "openviking-memory",
- tool: "read_experience",
+ tool: "read",
arguments: { uri },
},
result: {
@@ -385,10 +390,10 @@ test("preserves Experience usage metadata when Codex truncates a long MCP result
CAPTURE_CONFIG,
);
- const completed = turns
+ const running = turns
.flatMap((turn) => turn.parts)
- .find((part) => part.tool_status === "completed");
- assert.deepEqual(completed.tool_input, { uri });
+ .find((part) => part.tool_status === "running");
+ assert.deepEqual(running.tool_input, { uri });
});
test("keeps search Experience results parseable when snippets are long", () => {
@@ -402,7 +407,7 @@ test("keeps search Experience results parseable when snippets are long", () => {
call_id: "exec-search-long",
invocation: {
server: "openviking-memory",
- tool: "search_experience",
+ tool: "find",
arguments: { query: "换货" },
},
result: {
diff --git a/examples/codex-memory-plugin/scripts/marketplace.test.mjs b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
index 63887836b..41625fdbc 100644
--- a/examples/codex-memory-plugin/scripts/marketplace.test.mjs
+++ b/examples/codex-memory-plugin/scripts/marketplace.test.mjs
@@ -118,30 +118,6 @@ test("required plugin files are present", () => {
}
});
-test("plugin bundles the Experience Memory skill", () => {
- const skillPath = join(pluginDir, "skills", "ov-experience-memory", "SKILL.md");
- assert.ok(existsSync(skillPath), `missing bundled skill: ${skillPath}`);
- const content = readFileSync(skillPath, "utf-8");
- assert.match(content, /^---[\s\S]*name:\s*ov-experience-memory[\s\S]*---/);
- assert.match(content, /`search_experience`/);
- assert.match(content, /`read_experience`/);
-});
-
-test("Experience Memory skill examples match the search_experience input schema", () => {
- const skillPaths = [
- join(pluginDir, "skills", "ov-experience-memory", "SKILL.md"),
- join(repoRoot, "examples", "skills", "ov-experience-memory", "SKILL.md"),
- ];
- for (const skillPath of skillPaths) {
- const content = readFileSync(skillPath, "utf-8");
- const section = content.match(/## Tool: search_experience([\s\S]*?)## Tool: read_experience/)?.[1];
- assert.ok(section, `missing search_experience section in ${skillPath}`);
- const inputExample = section.match(/Input schema:\s*```json\s*([\s\S]*?)```/)?.[1];
- assert.ok(inputExample, `missing search_experience input example in ${skillPath}`);
- assert.deepEqual(Object.keys(JSON.parse(inputExample)).sort(), ["limit", "query"]);
- }
-});
-
test("plugin.json does not describe legacy MCP tool names", () => {
const manifest = readJson(manifestPath);
const interfaceText = JSON.stringify(manifest.interface || {});
@@ -180,10 +156,10 @@ test(".mcp.json starts the stdio MCP proxy from the plugin root", () => {
execFileSync("node", ["--check", join(pluginDir, "servers", "mcp-proxy.mjs")], { stdio: "pipe" });
});
-test("Codex MCP entrypoint wires the Experience tool provider", () => {
+test("Codex MCP entrypoint forwards only native OpenViking tools", () => {
const entrypoint = readFileSync(join(pluginDir, "servers", "mcp-proxy.mjs"), "utf-8");
- assert.match(entrypoint, /createExperienceToolProvider/);
- assert.match(entrypoint, /localToolProvider/);
+ assert.doesNotMatch(entrypoint, /createExperienceToolProvider/);
+ assert.doesNotMatch(entrypoint, /localToolProvider/);
});
test("canonical MCP tool list matches server registrations", () => {
diff --git a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
index 0cc76778f..3e078db47 100644
--- a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
@@ -102,6 +102,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -112,6 +113,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -122,8 +124,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -134,6 +138,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -147,11 +152,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -163,13 +176,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/examples/codex-memory-plugin/servers/experience-tools.mjs b/examples/codex-memory-plugin/servers/experience-tools.mjs
deleted file mode 100644
index 5df915ce2..000000000
--- a/examples/codex-memory-plugin/servers/experience-tools.mjs
+++ /dev/null
@@ -1,199 +0,0 @@
-const EXPERIENCE_TARGET_URI = "viking://user/memories/experiences/";
-const DEFAULT_LIMIT = 5;
-const MAX_LIMIT = 20;
-const DEFAULT_TIMEOUT_MS = 15000;
-const EXPERIENCE_SIDECAR_FILENAMES = new Set([".abstract.md", ".overview.md", ".relations.json"]);
-
-const EXPERIENCE_TOOL_DEFINITIONS = [
- {
- name: "search_experience",
- description: "Search reusable execution experiences for the current OpenViking user.",
- inputSchema: {
- type: "object",
- properties: {
- query: { type: "string", description: "Task or situation to search for." },
- limit: {
- type: "integer",
- minimum: 1,
- maximum: MAX_LIMIT,
- default: DEFAULT_LIMIT,
- },
- },
- required: ["query"],
- additionalProperties: false,
- },
- },
- {
- name: "read_experience",
- description: "Read one Experience returned by search_experience.",
- inputSchema: {
- type: "object",
- properties: {
- uri: {
- type: "string",
- description: "Canonical viking:// URI of an Experience memory file.",
- },
- },
- required: ["uri"],
- additionalProperties: false,
- },
- },
-];
-
-function result(payload) {
- return {
- content: [{ type: "text", text: JSON.stringify(payload) }],
- };
-}
-
-function errorResult(message) {
- return {
- isError: true,
- content: [{ type: "text", text: String(message) }],
- };
-}
-
-function normalizedBaseUrl(config) {
- const explicit = String(config?.baseUrl || "").trim().replace(/\/+$/, "");
- if (explicit) return explicit;
- const mcpUrl = new URL(String(config?.mcpUrl || ""));
- mcpUrl.pathname = mcpUrl.pathname.replace(/\/mcp\/?$/, "").replace(/\/+$/, "");
- mcpUrl.search = "";
- mcpUrl.hash = "";
- return mcpUrl.toString().replace(/\/+$/, "");
-}
-
-function requestHeaders(config, includeJson = false) {
- const headers = { Accept: "application/json" };
- if (includeJson) headers["Content-Type"] = "application/json";
- if (config?.apiKey) headers.Authorization = `Bearer ${config.apiKey}`;
- if (config?.account) headers["X-OpenViking-Account"] = config.account;
- if (config?.user) headers["X-OpenViking-User"] = config.user;
- if (config?.peerId) headers["X-OpenViking-Actor-Peer"] = config.peerId;
- return headers;
-}
-
-function experiencePrefix(user) {
- const owner = String(user || "").trim();
- return owner ? `viking://user/${owner}/memories/experiences/` : "";
-}
-
-function isExperienceUri(uri, user) {
- const value = String(uri || "").trim();
- if (!value || value.includes("?") || value.includes("#")) return false;
- const prefix = experiencePrefix(user);
- const relative = prefix
- ? (value.startsWith(prefix) ? value.slice(prefix.length) : "")
- : value.match(/^viking:\/\/user\/[^/]+\/memories\/experiences\/(.+)$/)?.[1] || "";
- const segments = relative.split("/");
- const basename = segments.at(-1) || "";
- return Boolean(
- relative
- && segments.length > 0
- && segments.every((segment) => segment && segment !== "." && segment !== "..")
- && !EXPERIENCE_SIDECAR_FILENAMES.has(basename),
- );
-}
-
-function titleFromUri(uri) {
- const basename = String(uri).split("/").at(-1) || String(uri);
- const withoutExtension = basename.replace(/\.md$/i, "");
- try {
- return decodeURIComponent(withoutExtension);
- } catch {
- return withoutExtension;
- }
-}
-
-function clampLimit(value) {
- const parsed = Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : DEFAULT_LIMIT;
- return Math.max(1, Math.min(MAX_LIMIT, parsed));
-}
-
-function requestSignal(config) {
- const configured = Number(config?.timeoutMs);
- const timeoutMs = Math.max(1000, Number.isFinite(configured) ? configured : DEFAULT_TIMEOUT_MS);
- return AbortSignal.timeout(timeoutMs);
-}
-
-async function readJsonResponse(response) {
- const text = await response.text();
- let payload;
- try {
- payload = text ? JSON.parse(text) : {};
- } catch {
- throw new Error(`OpenViking returned invalid JSON (HTTP ${response.status})`);
- }
- if (!response.ok) {
- const detail = payload?.detail || payload?.message || payload?.error?.message || response.statusText;
- throw new Error(`OpenViking request failed (HTTP ${response.status}): ${detail}`);
- }
- return payload;
-}
-
-async function searchExperience(args, config, fetchImpl) {
- const query = String(args?.query || "").trim();
- if (!query) return errorResult("search_experience requires a non-empty query");
- try {
- const response = await fetchImpl(`${normalizedBaseUrl(config)}/api/v1/search/find`, {
- method: "POST",
- headers: requestHeaders(config, true),
- signal: requestSignal(config),
- body: JSON.stringify({
- query,
- target_uri: EXPERIENCE_TARGET_URI,
- limit: clampLimit(args?.limit),
- }),
- });
- const payload = await readJsonResponse(response);
- const memories = Array.isArray(payload?.result?.memories) ? payload.result.memories : [];
- const results = memories
- .filter((item) => isExperienceUri(item?.uri, config?.user))
- .map((item) => ({
- uri: item.uri,
- title: titleFromUri(item.uri),
- score: Number.isFinite(Number(item.score)) ? Number(item.score) : 0,
- snippet: String(item.abstract || item.overview || ""),
- }));
- return result({ results });
- } catch (error) {
- return errorResult(error instanceof Error ? error.message : error);
- }
-}
-
-async function readExperience(args, config, fetchImpl) {
- const uri = String(args?.uri || "").trim();
- if (!isExperienceUri(uri, config?.user)) {
- return errorResult("read_experience requires an Experience URI owned by the current user");
- }
- try {
- const url = `${normalizedBaseUrl(config)}/api/v1/content/read?uri=${encodeURIComponent(uri)}`;
- const response = await fetchImpl(url, {
- method: "GET",
- headers: requestHeaders(config),
- signal: requestSignal(config),
- });
- const payload = await readJsonResponse(response);
- return result({ uri, content: String(payload?.result || "") });
- } catch (error) {
- return errorResult(error instanceof Error ? error.message : error);
- }
-}
-
-export function createExperienceToolProvider({ fetchImpl = globalThis.fetch } = {}) {
- if (typeof fetchImpl !== "function") throw new Error("fetchImpl must be a function");
- return {
- listTools() {
- return EXPERIENCE_TOOL_DEFINITIONS.map((tool) => structuredClone(tool));
- },
- async callTool(params, { config } = {}) {
- if (params?.name === "search_experience") {
- return searchExperience(params.arguments, config, fetchImpl);
- }
- if (params?.name === "read_experience") {
- return readExperience(params.arguments, config, fetchImpl);
- }
- return null;
- },
- };
-}
diff --git a/examples/codex-memory-plugin/servers/experience-tools.test.mjs b/examples/codex-memory-plugin/servers/experience-tools.test.mjs
deleted file mode 100644
index 24099d096..000000000
--- a/examples/codex-memory-plugin/servers/experience-tools.test.mjs
+++ /dev/null
@@ -1,240 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { createExperienceToolProvider } from "./experience-tools.mjs";
-
-const config = {
- baseUrl: "http://openviking.test",
- apiKey: "test-key",
- account: "new",
- user: "test",
- peerId: "peer-a",
-};
-
-function toolPayload(result) {
- assert.equal(result.isError, undefined);
- assert.equal(result.content.length, 1);
- assert.equal(result.content[0].type, "text");
- return JSON.parse(result.content[0].text);
-}
-
-test("lists the two official Experience tools", () => {
- const provider = createExperienceToolProvider({ fetchImpl: async () => assert.fail("unexpected fetch") });
- assert.deepEqual(
- provider.listTools().map((tool) => tool.name),
- ["search_experience", "read_experience"],
- );
-});
-
-test("search_experience searches only the current user's Experience directory", async () => {
- const calls = [];
- const provider = createExperienceToolProvider({
- fetchImpl: async (url, options) => {
- calls.push({ url: String(url), options });
- return new Response(JSON.stringify({
- ok: true,
- result: {
- memories: [
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md",
- score: 0.82,
- abstract: "先验证身份,再逐个定位订单。",
- },
- {
- uri: "viking://user/test/memories/preferences/回复风格.md",
- score: 0.91,
- abstract: "回复简洁。",
- },
- {
- uri: "viking://user/test/memories/experiences/.abstract.md",
- score: 0.95,
- abstract: "Experience 目录摘要。",
- },
- {
- uri: "viking://user/test/memories/experiences/.overview.md",
- score: 0.94,
- abstract: "Experience 目录概览。",
- },
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md?source=codex",
- score: 0.93,
- abstract: "非规范 URI 别名。",
- },
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md#approach",
- score: 0.92,
- abstract: "带片段的 URI 别名。",
- },
- ],
- resources: [],
- skills: [],
- },
- }), { status: 200, headers: { "content-type": "application/json" } });
- },
- });
-
- const result = await provider.callTool(
- { name: "search_experience", arguments: { query: "无订单号换货", limit: 5 } },
- { config },
- );
-
- assert.equal(calls.length, 1);
- assert.equal(calls[0].url, "http://openviking.test/api/v1/search/find");
- assert.equal(calls[0].options.method, "POST");
- assert.equal(calls[0].options.headers.Authorization, "Bearer test-key");
- assert.equal(calls[0].options.headers["X-OpenViking-Account"], "new");
- assert.equal(calls[0].options.headers["X-OpenViking-User"], "test");
- assert.equal(calls[0].options.headers["X-OpenViking-Actor-Peer"], "peer-a");
- assert.deepEqual(JSON.parse(calls[0].options.body), {
- query: "无订单号换货",
- target_uri: "viking://user/memories/experiences/",
- limit: 5,
- });
- assert.deepEqual(toolPayload(result), {
- results: [
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md",
- title: "无订单号换货处理",
- score: 0.82,
- snippet: "先验证身份,再逐个定位订单。",
- },
- ],
- });
-});
-
-test("read_experience reads a canonical Experience URI", async () => {
- const calls = [];
- const uri = "viking://user/test/memories/experiences/无订单号换货处理.md";
- const provider = createExperienceToolProvider({
- fetchImpl: async (url, options) => {
- calls.push({ url: String(url), options });
- return new Response(JSON.stringify({ ok: true, result: "## Approach\n先验证用户身份。" }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- },
- });
-
- const result = await provider.callTool(
- { name: "read_experience", arguments: { uri } },
- { config },
- );
-
- assert.equal(calls.length, 1);
- assert.equal(
- calls[0].url,
- `http://openviking.test/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
- );
- assert.equal(calls[0].options.method, "GET");
- assert.deepEqual(toolPayload(result), { uri, content: "## Approach\n先验证用户身份。" });
-});
-
-test("read_experience rejects non-Experience URIs without an HTTP request", async () => {
- let callCount = 0;
- const provider = createExperienceToolProvider({
- fetchImpl: async () => {
- callCount += 1;
- return new Response();
- },
- });
-
- const result = await provider.callTool(
- {
- name: "read_experience",
- arguments: { uri: "viking://user/test/memories/preferences/回复风格.md" },
- },
- { config },
- );
-
- assert.equal(callCount, 0);
- assert.equal(result.isError, true);
- assert.match(result.content[0].text, /Experience URI/);
-});
-
-test("read_experience rejects noncanonical Experience URI aliases", async () => {
- let callCount = 0;
- const provider = createExperienceToolProvider({
- fetchImpl: async () => {
- callCount += 1;
- return new Response();
- },
- });
- const canonicalUri = "viking://user/test/memories/experiences/无订单号换货处理.md";
-
- for (const uri of [`${canonicalUri}?source=codex`, `${canonicalUri}#approach`]) {
- const result = await provider.callTool(
- { name: "read_experience", arguments: { uri } },
- { config },
- );
- assert.equal(result.isError, true);
- }
- assert.equal(callCount, 0);
-});
-
-test("read_experience rejects internal Experience sidecars", async () => {
- let callCount = 0;
- const provider = createExperienceToolProvider({
- fetchImpl: async () => {
- callCount += 1;
- return new Response();
- },
- });
-
- for (const name of [".abstract.md", ".overview.md", ".relations.json"]) {
- const result = await provider.callTool(
- {
- name: "read_experience",
- arguments: { uri: `viking://user/test/memories/experiences/${name}` },
- },
- { config },
- );
- assert.equal(result.isError, true);
- }
- assert.equal(callCount, 0);
-});
-
-test("read_experience accepts other dot-prefixed Experience files", async () => {
- let callCount = 0;
- const uri = "viking://user/test/memories/experiences/.custom-experience.md";
- const provider = createExperienceToolProvider({
- fetchImpl: async () => {
- callCount += 1;
- return new Response(JSON.stringify({ result: "content" }), { status: 200 });
- },
- });
-
- const result = await provider.callTool(
- { name: "read_experience", arguments: { uri } },
- { config },
- );
-
- assert.equal(result.isError, undefined);
- assert.equal(callCount, 1);
-});
-
-test("Experience HTTP requests inherit the configured timeout signal", async () => {
- const calls = [];
- const uri = "viking://user/test/memories/experiences/无订单号换货处理.md";
- const provider = createExperienceToolProvider({
- fetchImpl: async (url, options) => {
- calls.push({ url: String(url), options });
- if (String(url).includes("/search/find")) {
- return new Response(JSON.stringify({ result: { memories: [] } }), { status: 200 });
- }
- return new Response(JSON.stringify({ result: "content" }), { status: 200 });
- },
- });
- const timeoutConfig = { ...config, timeoutMs: 1234 };
-
- await provider.callTool(
- { name: "search_experience", arguments: { query: "换货" } },
- { config: timeoutConfig },
- );
- await provider.callTool(
- { name: "read_experience", arguments: { uri } },
- { config: timeoutConfig },
- );
-
- assert.equal(calls.length, 2);
- for (const call of calls) assert.ok(call.options.signal instanceof AbortSignal);
-});
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
index 7c5c1d3a2..eadd7ccc7 100644
--- a/examples/codex-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
@@ -16,7 +16,6 @@ import { createLogger } from "../scripts/debug-log.mjs";
import { resolveOpenVikingCredentials } from "../scripts/ov-credentials.mjs";
import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
import { resolveEffectivePeerId } from "../scripts/shared/workspace-peer.mjs";
-import { createExperienceToolProvider } from "./experience-tools.mjs";
export { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
@@ -69,10 +68,8 @@ function readProxyConfig() {
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- const localToolProvider = createExperienceToolProvider();
createOpenVikingMcpProxy({
readConfig: readProxyConfig,
loggerFactory: createLogger,
- localToolProvider,
}).start();
}
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs
index 4a8cc801c..fa96275f0 100644
--- a/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs
+++ b/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs
@@ -199,8 +199,8 @@ test("uses independent POST requests for concurrent calls", async () => {
test("appends local tools to the upstream tools/list result", async () => {
const localTools = [
- { name: "search_experience", description: "Search experiences", inputSchema: { type: "object" } },
- { name: "read_experience", description: "Read an experience", inputSchema: { type: "object" } },
+ { name: "local_probe", description: "Probe locally", inputSchema: { type: "object" } },
+ { name: "local_echo", description: "Echo locally", inputSchema: { type: "object" } },
];
await withServer((_req, res, entry) => {
assert.equal(entry.body.method, "tools/list");
@@ -222,8 +222,8 @@ test("appends local tools to the upstream tools/list result", async () => {
const [response] = await messages();
assert.deepEqual(response.result.tools.map((tool) => tool.name), [
"find",
- "search_experience",
- "read_experience",
+ "local_probe",
+ "local_echo",
]);
assert.equal(requests.length, 1);
});
@@ -231,8 +231,8 @@ test("appends local tools to the upstream tools/list result", async () => {
test("replaces an upstream tool definition when the local tool has the same name", async () => {
const localTool = {
- name: "search_experience",
- description: "Local experience search",
+ name: "local_probe",
+ description: "Local probe",
inputSchema: { type: "object", required: ["query"] },
};
await withServer((_req, res, entry) => {
@@ -242,8 +242,8 @@ test("replaces an upstream tool definition when the local tool has the same name
tools: [
{ name: "find", description: "Find context", inputSchema: { type: "object" } },
{
- name: "search_experience",
- description: "Upstream experience search",
+ name: "local_probe",
+ description: "Upstream probe",
inputSchema: { type: "object", required: ["text"] },
},
],
@@ -272,7 +272,7 @@ test("handles local tools without forwarding tools/call upstream", async () => {
const { proxy, messages } = makeProxy({
url: "http://127.0.0.1:1/mcp",
localToolProvider: {
- listTools: () => [{ name: "search_experience" }],
+ listTools: () => [{ name: "local_probe" }],
async callTool(params, context) {
calls.push({ params, context });
return { content: [{ type: "text", text: '{"results":[]}' }] };
@@ -284,13 +284,13 @@ test("handles local tools without forwarding tools/call upstream", async () => {
jsonrpc: "2.0",
id: 21,
method: "tools/call",
- params: { name: "search_experience", arguments: { query: "换货" } },
+ params: { name: "local_probe", arguments: { query: "test" } },
});
assert.equal(calls.length, 1);
assert.deepEqual(calls[0].params, {
- name: "search_experience",
- arguments: { query: "换货" },
+ name: "local_probe",
+ arguments: { query: "test" },
});
assert.equal(calls[0].context.config.user, "zeus");
assert.deepEqual(await messages(), [
@@ -322,7 +322,7 @@ test("reloads changed credential files before calling a local tool", async (t) =
const { proxy, messages } = makeProxy({
readConfig,
localToolProvider: {
- listTools: () => [{ name: "search_experience" }],
+ listTools: () => [{ name: "local_probe" }],
async callTool(_params, context) {
receivedKeys.push(context.config.apiKey);
return { content: [{ type: "text", text: '{"results":[]}' }] };
@@ -336,7 +336,7 @@ test("reloads changed credential files before calling a local tool", async (t) =
jsonrpc: "2.0",
id: 22,
method: "tools/call",
- params: { name: "search_experience", arguments: { query: "换货" } },
+ params: { name: "local_probe", arguments: { query: "test" } },
});
assert.deepEqual(receivedKeys, ["new-key"]);
diff --git a/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md b/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md
deleted file mode 100644
index 1faa749e2..000000000
--- a/examples/codex-memory-plugin/skills/ov-experience-memory/SKILL.md
+++ /dev/null
@@ -1,156 +0,0 @@
----
-name: ov-experience-memory
-description: >
- Use OpenViking experience memories during task execution. Search relevant
- experiences with search_experience, read selected experiences with
- read_experience, and leave standard tool parts in the committed session so
- OpenViking can report recall and injection usage.
-version: 2026.7.9
-tags:
- - openviking
- - experience-memory
- - agent-memory
- - usage-reporting
----
-
-# OpenViking Experience Memory
-
-Use this skill when the current user request starts or continues an executable
-task, especially tasks involving tools, files, code changes, data operations,
-workflow decisions, or multi-step actions.
-
-Do not use this skill for casual chat, pure explanation, or one-off factual Q&A
-that does not require operational guidance.
-
-## Runtime Contract
-
-The agent runtime must expose two tools with these exact names:
-
-- `search_experience`
-- `read_experience`
-
-OpenViking usage reporting recognizes only completed tool parts with these exact
-tool names. Calls to generic `find`, `search`, `read`, `ov_search`, or `ov_read`
-do not count as experience recall or injection events.
-
-## Tool: search_experience
-
-Purpose: search reusable execution experiences from the OpenViking experience
-library before assembling task context.
-
-Input schema:
-
-```json
-{
- "query": "string",
- "limit": 5
-}
-```
-
-Output schema:
-
-```json
-{
- "results": [
- {
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "title": "example",
- "score": 0.82,
- "snippet": "Short summary or matched situation"
- }
- ]
-}
-```
-
-Implementation:
-
-The runtime tool calls OpenViking `POST /api/v1/search/find` with `target_uri`
-fixed to the current-user shorthand `viking://user/memories/experiences/`.
-Callers provide only `query` and optional `limit`; they cannot override or pass
-`target_uri`. OpenViking resolves the fixed shorthand against the authenticated
-request user. Return only canonical experience memory URIs for that user; never
-hardcode `default` or another user ID.
-
-Usage reporting:
-
-A completed `search_experience` tool part is counted as an experience recall
-event for every `results[].uri` value.
-
-## Tool: read_experience
-
-Purpose: read the full Markdown body of a selected experience and inject it into
-the agent prompt as task execution guidance.
-
-Input schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md"
-}
-```
-
-Output schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "content": "Experience Markdown body"
-}
-```
-
-Implementation:
-
-Call OpenViking `GET /api/v1/content/read?uri=<encoded_uri>` for the selected
-experience URI. Always pass the canonical URI returned by `search_experience`;
-do not construct a URI with a hardcoded user ID. The returned content should be
-inserted into the prompt as operational guidance, not as user profile facts.
-
-Usage reporting:
-
-A completed `read_experience` tool part is counted as an experience injection
-event for `tool_input.uri` or `tool_output.uri`. In this design, reading an
-experience through `read_experience` means the experience was injected into the
-prompt.
-
-## Recommended Flow
-
-1. When a task begins, build a short query from the latest user instruction,
- current plan, active skill name, and important tool/environment context.
-2. Call `search_experience` before final prompt assembly.
-3. Review returned titles/snippets and select only experiences likely to affect
- execution.
-4. Call `read_experience` for selected experience URIs.
-5. Inject the returned Markdown into the prompt under an explicit experience
- section.
-6. Continue task execution.
-7. Commit the session normally. The committed session must include the
- `search_experience` and `read_experience` tool parts so OpenViking can report
- usage.
-
-## Prompt Injection Format
-
-Use a compact and explicit block:
-
-```text
-<openviking-experience-memory>
-The following guidance was retrieved from prior task execution experience.
-Use it as operational guidance. Do not treat it as user identity or preference.
-
-<experience uri="viking://user/<current_user_id>/memories/experiences/example.md">
-...experience markdown...
-</experience>
-</openviking-experience-memory>
-```
-
-## Commit Requirements
-
-The session committed to OpenViking must preserve tool parts with:
-
-- `tool_name`
-- `tool_status`
-- `tool_input`
-- `tool_output`
-- `tool_id`
-
-Only `tool_status == "completed"` is counted. Failed, cancelled, or skipped tool
-parts are ignored by usage reporting.
diff --git a/examples/memory-plugin-shared/lib/capture-utils.mjs b/examples/memory-plugin-shared/lib/capture-utils.mjs
index 2bd98e326..796e19d56 100644
--- a/examples/memory-plugin-shared/lib/capture-utils.mjs
+++ b/examples/memory-plugin-shared/lib/capture-utils.mjs
@@ -101,6 +101,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -111,6 +112,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -121,8 +123,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -133,6 +137,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -146,11 +151,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -162,13 +175,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index f50882025..634005472 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -46,8 +46,6 @@ Once installed, the plugin provides these agent tools:
| `ov_read` | Read the full original content of one exact OpenViking URI |
| `ov_multi_read` | Read the full original content of multiple OpenViking URIs |
| `ov_list` | List OpenViking directories after search to inspect sibling chunks and overview files |
-| `search_experience` | Search reusable execution experiences for the current OpenViking user |
-| `read_experience` | Read one exact Experience returned by `search_experience` |
| `openviking_tool_result_read` | Restore the full original content of an externalized tool result |
| `openviking_tool_result_search` | Search inside an externalized tool result by keyword |
| `openviking_tool_result_list` | List externalized tool results in the current session |
@@ -250,8 +248,6 @@ Beyond automatic behavior, the plugin exposes these tools directly:
- `ov_read`: read one exact `viking://` URI returned by `ov_search` or `ov_list`
- `ov_multi_read`: read multiple exact `viking://` URIs, useful for an overview plus sibling chunks
- `ov_list`: list a hit's parent directory after `ov_search` to recover sibling chunks, `.overview.md`, and related split-document context
-- `search_experience`: search reusable execution experiences for the current OpenViking user
-- `read_experience`: read one exact Experience returned by `search_experience`
They serve different roles:
@@ -265,7 +261,6 @@ They serve different roles:
- `ov_read` turns a ranked hit into original evidence before answering precise documentation, codebase, configuration, or procedural questions
- `ov_multi_read` reads overview and sibling chunks together when a split document needs more context than a single hit
- `ov_list` complements `ov_search` when a ranked hit is only one chunk of a larger procedure or document
-- `search_experience` and `read_experience` provide the exact tool-call contract used by the bundled Experience Memory skill and usage reporting
`ov_archive_expand` is especially important because `assemble()` normally returns archive summaries and indexes, not the full raw transcript.
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 4dabcf51c..6cb4732ea 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -78,8 +78,6 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A
| `ov_read` | 读取 `ov_search` / trace 返回的 `viking://...` OpenViking 虚拟 URI 完整内容 |
| `ov_multi_read` | 一次读取多个精确 `viking://...` URI,适合同时读取 overview 和同级切片 |
| `ov_list` | 在检索后列出 OpenViking 目录,补查同级切片和 `.overview.md` 文件 |
-| `search_experience` | 检索当前 OpenViking 用户的可复用执行经验 |
-| `read_experience` | 读取 `search_experience` 返回的单条 Experience 全文 |
| `openviking_tool_result_list` | 列出当前 session 中被外置的大工具输出 |
| `openviking_tool_result_search` | 在外置工具输出中按关键词搜索 |
| `openviking_tool_result_read` | 通过 `viking://session/.../tool-results/...` ref 分页读取外置工具输出 |
@@ -265,7 +263,7 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来
## 工具层与可展开能力
-这套插件除了自动行为,还会直接暴露一组 Agent 工具;当 `enableAddResourceTool=true` 时才额外暴露 opt-in 的 `add_resource` 导入工具。Agent 可见工具可以通过 `enabledTools` 和 `disabledTools` 灵活裁剪:
+这套插件除了自动行为,默认直接暴露 12 个工具;当 `enableAddResourceTool=true` 时才额外暴露 opt-in 的 `add_resource` 导入工具。Agent 可见工具可以通过 `enabledTools` 和 `disabledTools` 灵活裁剪:
- `memory_recall`:在 memory/resource 目标上显式语义召回
- `memory_store`:把明确的长期事实写入 OpenViking session 并触发阻塞 commit/抽取
@@ -278,13 +276,11 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来
- `ov_read`:读取 `ov_search` 或 recall trace 返回的 `viking://...` OpenViking 虚拟 URI 完整内容
- `ov_multi_read`:读取多个精确 `viking://...` URI,适合同时读取 overview 和同级切片
- `ov_list`:在 `ov_search` 命中后列出父目录,用来补齐同级切片、`.overview.md` 和同源文档上下文
-- `search_experience`:检索当前 OpenViking 用户的可复用执行经验
-- `read_experience`:读取 `search_experience` 返回的单条 Experience 全文
- `openviking_tool_result_list`:列出当前 session 中被外置的大工具输出
- `openviking_tool_result_search`:在外置工具输出中按关键词搜索
- `openviking_tool_result_read`:通过 ref 和 offset/limit 分页读取外置工具输出
-工具选择器支持精确工具名,也支持分组:`default`、`all`、`memory`、`resource_query`、`experience`、`import`、`recall_trace`、`archive`、`tool_result`。例如,禁用记忆并只保留资源查询工具:
+工具选择器支持精确工具名,也支持分组:`default`、`all`、`memory`、`resource_query`、`import`、`recall_trace`、`archive`、`tool_result`。旧配置中的 `experience` 分组作为迁移别名保留,并映射到通用的 `ov_search`、`ov_read`;新配置应使用 `resource_query` 或精确工具名。例如,禁用记忆并只保留资源查询工具:
```json
{
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index c81b231e1..565734b2d 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -170,8 +170,6 @@ export const OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES = [
"ov_read",
"ov_multi_read",
"ov_list",
- "search_experience",
- "read_experience",
"memory_recall",
"ov_recall_trace",
"memory_store",
@@ -192,7 +190,9 @@ export const OPENVIKING_TOOL_GROUPS: Record<string, readonly OpenVikingToolName[
default: OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,
memory: ["memory_recall", "memory_store", "memory_forget"],
resource_query: ["ov_search", "ov_read", "ov_multi_read", "ov_list"],
- experience: ["search_experience", "read_experience"],
+ // Migration alias for configurations that previously selected the removed
+ // search_experience/read_experience tools.
+ experience: ["ov_search", "ov_read"],
import: ["add_resource", "add_skill"],
recall_trace: ["ov_recall_trace"],
archive: ["ov_archive_search", "ov_archive_expand"],
@@ -951,7 +951,7 @@ export const memoryOpenVikingConfigSchema = {
enabledTools: {
label: "Enabled Tools",
placeholder: "default",
- help: "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, experience, import, recall_trace, archive, tool_result. add_resource also requires enableAddResourceTool=true.",
+ help: "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, experience (legacy alias), import, recall_trace, archive, tool_result. add_resource also requires enableAddResourceTool=true.",
advanced: true,
},
disabledTools: {
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 2e1d57e31..822856854 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -19,7 +19,6 @@ import { registerOpenVikingCommands } from "./plugin/command-registration.js";
import { registerRecallTraceRoutes as registerRecallTraceRouteAdapters } from "./plugin/recall-trace-routes.js";
import { createOpenVikingService } from "./plugin/openviking-services.js";
import { registerOpenVikingArchiveTools } from "./plugin/openviking-archive-tools.js";
-import { registerOpenVikingExperienceTools } from "./plugin/openviking-experience-tools.js";
import { createOpenVikingImportRuntime } from "./plugin/openviking-import-runtime.js";
import { registerOpenVikingImportTools } from "./plugin/openviking-import-tools.js";
import { registerOpenVikingLifecycleHooks } from "./plugin/openviking-lifecycle-hooks.js";
@@ -281,15 +280,6 @@ const contextEnginePlugin = {
makeBypassedToolResult,
});
- registerOpenVikingExperienceTools({
- registerTool: registerOpenVikingTool,
- getClient,
- resolvePluginSessionRouting,
- isBypassedSession,
- makeBypassedToolResult,
- userId: cfg.userId,
- });
-
registerOpenVikingMemoryRecallTools({
registerTool: registerOpenVikingTool,
getClient,
diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.json
index 03708430d..c38cf077d 100644
--- a/examples/openclaw-plugin/install-manifest.json
+++ b/examples/openclaw-plugin/install-manifest.json
@@ -41,7 +41,6 @@
".gitignore",
"skills/install-openviking-memory/SKILL.md",
"skills/openviking-context-database/SKILL.md",
- "skills/ov-experience-memory/SKILL.md",
"INSTALL-AGENT.md"
]
},
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index c1ffcdf18..ebb4521ae 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -19,8 +19,6 @@
"ov_read",
"ov_multi_read",
"ov_list",
- "search_experience",
- "read_experience",
"memory_recall",
"ov_recall_trace",
"memory_store",
@@ -254,7 +252,7 @@
"enabledTools": {
"label": "Enabled Tools",
"placeholder": "default",
- "help": "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, experience, import, recall_trace, archive, tool_result. add_resource also requires enableAddResourceTool=true.",
+ "help": "Agent-visible tool allowlist. Accepts tool names or groups: default, all, memory, resource_query, import, recall_trace, archive, tool_result. add_resource also requires enableAddResourceTool=true.",
"advanced": true
},
"disabledTools": {
diff --git a/examples/openclaw-plugin/plugin/openviking-experience-tools.ts b/examples/openclaw-plugin/plugin/openviking-experience-tools.ts
deleted file mode 100644
index 0211683a7..000000000
--- a/examples/openclaw-plugin/plugin/openviking-experience-tools.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import { Type } from "@sinclair/typebox";
-
-import type { FindResult } from "../client.js";
-
-const EXPERIENCE_TARGET_URI = "viking://user/memories/experiences/";
-const DEFAULT_LIMIT = 5;
-const MAX_LIMIT = 20;
-const EXPERIENCE_SIDECAR_FILENAMES = new Set([".abstract.md", ".overview.md", ".relations.json"]);
-
-export type OpenVikingExperienceToolContext = {
- sessionKey?: string;
- sessionId?: string;
- agentId?: string;
- senderId?: string;
- requesterSenderId?: string;
-};
-
-export type OpenVikingExperienceSession = {
- sessionId?: string;
- sessionKey?: string;
- ovSessionId?: string;
- agentId: string;
- actorPeerId?: string;
-};
-
-type OpenVikingExperienceClient = {
- find: (
- query: string,
- options: { targetUri: string; limit: number; scoreThreshold?: number },
- actorPeerId?: string,
- ) => Promise<FindResult>;
- read: (uri: string, actorPeerId?: string) => Promise<unknown>;
-};
-
-export type OpenVikingExperienceToolsDeps = {
- registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;
- getClient: () => Promise<OpenVikingExperienceClient>;
- resolvePluginSessionRouting: (ctx?: OpenVikingExperienceToolContext) => OpenVikingExperienceSession;
- isBypassedSession: (ctx?: OpenVikingExperienceToolContext) => boolean;
- makeBypassedToolResult: (toolName: string) => unknown;
- userId?: string;
-};
-
-function clampLimit(value: unknown): number {
- const parsed = Number.isFinite(Number(value)) ? Math.trunc(Number(value)) : DEFAULT_LIMIT;
- return Math.max(1, Math.min(MAX_LIMIT, parsed));
-}
-
-function experienceRelativePath(uri: string): string {
- return uri.match(/^viking:\/\/user\/[^/]+\/memories\/experiences\/(.+)$/)?.[1] ?? "";
-}
-
-export function isCanonicalExperienceUri(uri: unknown, expectedUserId?: string): uri is string {
- const value = typeof uri === "string" ? uri.trim() : "";
- if (!value || value.includes("?") || value.includes("#")) {
- return false;
- }
- const owner = value.match(/^viking:\/\/user\/([^/]+)\//)?.[1] ?? "";
- if (expectedUserId?.trim() && owner !== expectedUserId.trim()) {
- return false;
- }
- const relative = experienceRelativePath(value);
- const segments = relative.split("/");
- const basename = segments.at(-1) ?? "";
- return Boolean(
- relative
- && segments.every((segment) => segment && segment !== "." && segment !== "..")
- && !EXPERIENCE_SIDECAR_FILENAMES.has(basename)
- );
-}
-
-function titleFromUri(uri: string): string {
- const basename = uri.split("/").at(-1) ?? uri;
- const title = basename.replace(/\.md$/i, "");
- try {
- return decodeURIComponent(title);
- } catch {
- return title;
- }
-}
-
-function jsonToolResult(payload: Record<string, unknown>): {
- content: Array<{ type: "text"; text: string }>;
-} {
- return {
- content: [{ type: "text", text: JSON.stringify(payload) }],
- };
-}
-
-export function registerOpenVikingExperienceTools(deps: OpenVikingExperienceToolsDeps): void {
- deps.registerTool(
- (ctx: OpenVikingExperienceToolContext) => ({
- name: "search_experience",
- label: "Search Experience (OpenViking)",
- description:
- "Search reusable task-execution experiences for the current OpenViking user. " +
- "Use before executing operational or multi-step tasks, then call read_experience for selected results.",
- parameters: Type.Object({
- query: Type.String({ description: "Current task, situation, or execution problem to search for" }),
- limit: Type.Optional(Type.Integer({
- description: `Maximum results to return. Default: ${DEFAULT_LIMIT}; maximum: ${MAX_LIMIT}`,
- minimum: 1,
- maximum: MAX_LIMIT,
- })),
- }, { additionalProperties: false }),
- async execute(_toolCallId: string, params: Record<string, unknown>) {
- if (deps.isBypassedSession(ctx)) {
- return deps.makeBypassedToolResult("search_experience");
- }
- const query = typeof params.query === "string" ? params.query.trim() : "";
- if (!query) {
- throw new Error("query is required");
- }
- const session = deps.resolvePluginSessionRouting(ctx);
- const client = await deps.getClient();
- const result = await client.find(query, {
- targetUri: EXPERIENCE_TARGET_URI,
- limit: clampLimit(params.limit),
- }, session.actorPeerId);
- const results = (result.memories ?? [])
- .filter((item) => isCanonicalExperienceUri(item.uri, deps.userId))
- .map((item) => ({
- uri: item.uri,
- title: titleFromUri(item.uri),
- score: typeof item.score === "number" ? item.score : 0,
- snippet: item.abstract || item.overview || "",
- }));
- return jsonToolResult({ results });
- },
- }),
- { name: "search_experience" },
- );
-
- deps.registerTool(
- (ctx: OpenVikingExperienceToolContext) => ({
- name: "read_experience",
- label: "Read Experience (OpenViking)",
- description:
- "Read the complete Markdown body of one Experience returned by search_experience and use it as execution guidance.",
- parameters: Type.Object({
- uri: Type.String({ description: "Exact canonical Experience URI returned by search_experience" }),
- }, { additionalProperties: false }),
- async execute(_toolCallId: string, params: Record<string, unknown>) {
- if (deps.isBypassedSession(ctx)) {
- return deps.makeBypassedToolResult("read_experience");
- }
- const uri = typeof params.uri === "string" ? params.uri.trim() : "";
- if (!isCanonicalExperienceUri(uri, deps.userId)) {
- throw new Error("uri must be a canonical OpenViking Experience URI returned by search_experience");
- }
- const session = deps.resolvePluginSessionRouting(ctx);
- const client = await deps.getClient();
- const content = await client.read(uri, session.actorPeerId);
- const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);
- return jsonToolResult({ uri, content: text });
- },
- }),
- { name: "read_experience" },
- );
-}
diff --git a/examples/openclaw-plugin/registries/openviking-tools.ts b/examples/openclaw-plugin/registries/openviking-tools.ts
index bca686943..61bb04ff4 100644
--- a/examples/openclaw-plugin/registries/openviking-tools.ts
+++ b/examples/openclaw-plugin/registries/openviking-tools.ts
@@ -1,7 +1,6 @@
export type OpenVikingToolGroup =
| "memory"
| "resource_query"
- | "experience"
| "import"
| "recall_trace"
| "archive"
@@ -14,8 +13,6 @@ export type OpenVikingToolName =
| "ov_read"
| "ov_multi_read"
| "ov_list"
- | "search_experience"
- | "read_experience"
| "memory_recall"
| "ov_recall_trace"
| "memory_store"
@@ -47,8 +44,6 @@ export const OPENVIKING_TOOL_SPECS = [
{ name: "ov_read", group: "resource_query", defaultEnabled: true },
{ name: "ov_multi_read", group: "resource_query", defaultEnabled: true },
{ name: "ov_list", group: "resource_query", defaultEnabled: true },
- { name: "search_experience", group: "experience", defaultEnabled: true },
- { name: "read_experience", group: "experience", defaultEnabled: true },
{ name: "memory_recall", group: "memory", defaultEnabled: true },
{ name: "ov_recall_trace", group: "recall_trace", defaultEnabled: true },
{ name: "memory_store", group: "memory", defaultEnabled: true },
@@ -69,7 +64,6 @@ export const OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES = OPENVIKING_TOOL_SPECS
const OPENVIKING_TOOL_GROUP_ORDER: readonly OpenVikingToolGroup[] = [
"memory",
"resource_query",
- "experience",
"import",
"recall_trace",
"archive",
@@ -79,6 +73,8 @@ const OPENVIKING_TOOL_GROUP_ORDER: readonly OpenVikingToolGroup[] = [
export const OPENVIKING_TOOL_GROUPS: Record<string, readonly OpenVikingToolName[]> = {
all: OPENVIKING_ALL_TOOL_NAMES,
default: OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,
+ // Migration alias for the removed dedicated Experience tools.
+ experience: ["ov_search", "ov_read"],
...Object.fromEntries(
OPENVIKING_TOOL_GROUP_ORDER.map((group) => [
group,
diff --git a/examples/openclaw-plugin/setup-helper/install.js b/examples/openclaw-plugin/setup-helper/install.js
index 561af82c5..652e7aca1 100755
--- a/examples/openclaw-plugin/setup-helper/install.js
+++ b/examples/openclaw-plugin/setup-helper/install.js
@@ -78,7 +78,6 @@ const FALLBACK_CURRENT = {
"session-transcript-repair.ts",
"runtime-utils.ts",
"commands/setup.ts",
- "skills/ov-experience-memory/SKILL.md",
"tsconfig.json",
"package-lock.json",
".gitignore",
diff --git a/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md b/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md
deleted file mode 100644
index 1faa749e2..000000000
--- a/examples/openclaw-plugin/skills/ov-experience-memory/SKILL.md
+++ /dev/null
@@ -1,156 +0,0 @@
----
-name: ov-experience-memory
-description: >
- Use OpenViking experience memories during task execution. Search relevant
- experiences with search_experience, read selected experiences with
- read_experience, and leave standard tool parts in the committed session so
- OpenViking can report recall and injection usage.
-version: 2026.7.9
-tags:
- - openviking
- - experience-memory
- - agent-memory
- - usage-reporting
----
-
-# OpenViking Experience Memory
-
-Use this skill when the current user request starts or continues an executable
-task, especially tasks involving tools, files, code changes, data operations,
-workflow decisions, or multi-step actions.
-
-Do not use this skill for casual chat, pure explanation, or one-off factual Q&A
-that does not require operational guidance.
-
-## Runtime Contract
-
-The agent runtime must expose two tools with these exact names:
-
-- `search_experience`
-- `read_experience`
-
-OpenViking usage reporting recognizes only completed tool parts with these exact
-tool names. Calls to generic `find`, `search`, `read`, `ov_search`, or `ov_read`
-do not count as experience recall or injection events.
-
-## Tool: search_experience
-
-Purpose: search reusable execution experiences from the OpenViking experience
-library before assembling task context.
-
-Input schema:
-
-```json
-{
- "query": "string",
- "limit": 5
-}
-```
-
-Output schema:
-
-```json
-{
- "results": [
- {
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "title": "example",
- "score": 0.82,
- "snippet": "Short summary or matched situation"
- }
- ]
-}
-```
-
-Implementation:
-
-The runtime tool calls OpenViking `POST /api/v1/search/find` with `target_uri`
-fixed to the current-user shorthand `viking://user/memories/experiences/`.
-Callers provide only `query` and optional `limit`; they cannot override or pass
-`target_uri`. OpenViking resolves the fixed shorthand against the authenticated
-request user. Return only canonical experience memory URIs for that user; never
-hardcode `default` or another user ID.
-
-Usage reporting:
-
-A completed `search_experience` tool part is counted as an experience recall
-event for every `results[].uri` value.
-
-## Tool: read_experience
-
-Purpose: read the full Markdown body of a selected experience and inject it into
-the agent prompt as task execution guidance.
-
-Input schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md"
-}
-```
-
-Output schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "content": "Experience Markdown body"
-}
-```
-
-Implementation:
-
-Call OpenViking `GET /api/v1/content/read?uri=<encoded_uri>` for the selected
-experience URI. Always pass the canonical URI returned by `search_experience`;
-do not construct a URI with a hardcoded user ID. The returned content should be
-inserted into the prompt as operational guidance, not as user profile facts.
-
-Usage reporting:
-
-A completed `read_experience` tool part is counted as an experience injection
-event for `tool_input.uri` or `tool_output.uri`. In this design, reading an
-experience through `read_experience` means the experience was injected into the
-prompt.
-
-## Recommended Flow
-
-1. When a task begins, build a short query from the latest user instruction,
- current plan, active skill name, and important tool/environment context.
-2. Call `search_experience` before final prompt assembly.
-3. Review returned titles/snippets and select only experiences likely to affect
- execution.
-4. Call `read_experience` for selected experience URIs.
-5. Inject the returned Markdown into the prompt under an explicit experience
- section.
-6. Continue task execution.
-7. Commit the session normally. The committed session must include the
- `search_experience` and `read_experience` tool parts so OpenViking can report
- usage.
-
-## Prompt Injection Format
-
-Use a compact and explicit block:
-
-```text
-<openviking-experience-memory>
-The following guidance was retrieved from prior task execution experience.
-Use it as operational guidance. Do not treat it as user identity or preference.
-
-<experience uri="viking://user/<current_user_id>/memories/experiences/example.md">
-...experience markdown...
-</experience>
-</openviking-experience-memory>
-```
-
-## Commit Requirements
-
-The session committed to OpenViking must preserve tool parts with:
-
-- `tool_name`
-- `tool_status`
-- `tool_input`
-- `tool_output`
-- `tool_id`
-
-Only `tool_status == "completed"` is counted. Failed, cancelled, or skipped tool
-parts are ignored by usage reporting.
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index 37bae9654..e2eb02e35 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -81,6 +81,12 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.disabledTools).toEqual(["memory_forget", "add_resource"]);
});
+ it("maps the legacy experience group to generic query tools", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ enabledTools: ["experience"] });
+
+ expect(cfg.enabledTools).toEqual(["ov_search", "ov_read"]);
+ });
+
it("does not expose add_resource through enabledTools without enableAddResourceTool", () => {
const cfg = memoryOpenVikingConfigSchema.parse({ enabledTools: "all" });
expect(cfg.enabledTools).not.toContain("add_resource");
@@ -520,4 +526,3 @@ describe("memoryOpenVikingConfigSchema.parse() — apiKey SecretRef (#3522)", ()
expect(cfg2.apiKey).toBe("fallback-key");
});
});
-
diff --git a/examples/openclaw-plugin/tests/ut/openviking-experience-tools.test.ts b/examples/openclaw-plugin/tests/ut/openviking-experience-tools.test.ts
deleted file mode 100644
index 663b9b871..000000000
--- a/examples/openclaw-plugin/tests/ut/openviking-experience-tools.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import {
- isCanonicalExperienceUri,
- registerOpenVikingExperienceTools,
-} from "../../plugin/openviking-experience-tools.js";
-
-type RegisteredTool = {
- name: string;
- execute: (toolCallId: string, params: Record<string, unknown>) => Promise<unknown>;
-};
-
-function createHarness(options: { bypassed?: boolean; userId?: string } = {}) {
- const factories = new Map<string, (ctx: Record<string, unknown>) => RegisteredTool>();
- const client = {
- find: vi.fn(),
- read: vi.fn(),
- };
- registerOpenVikingExperienceTools({
- registerTool(factory, registration) {
- factories.set(registration.name, factory as (ctx: Record<string, unknown>) => RegisteredTool);
- },
- getClient: vi.fn().mockResolvedValue(client),
- resolvePluginSessionRouting: vi.fn().mockReturnValue({
- agentId: "agent-main",
- actorPeerId: "peer-main",
- }),
- isBypassedSession: vi.fn().mockReturnValue(options.bypassed ?? false),
- makeBypassedToolResult: (toolName) => ({ bypassed: toolName }),
- userId: options.userId,
- });
- const tool = (name: string): RegisteredTool => {
- const factory = factories.get(name);
- if (!factory) throw new Error(`tool ${name} was not registered`);
- return factory({ sessionId: "session-1" });
- };
- return { client, factories, tool };
-}
-
-function parseTextResult(value: unknown): Record<string, unknown> {
- const result = value as { content: Array<{ type: string; text: string }> };
- return JSON.parse(result.content[0]!.text) as Record<string, unknown>;
-}
-
-describe("OpenViking Experience tools", () => {
- it("registers the two standard Experience tool names", () => {
- const { factories } = createHarness();
- expect([...factories.keys()]).toEqual(["search_experience", "read_experience"]);
- });
-
- it("searches only the current-user Experience directory and returns canonical results", async () => {
- const { client, tool } = createHarness();
- client.find.mockResolvedValue({
- memories: [
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md",
- score: 0.86,
- abstract: "先确认用户身份,再定位订单。",
- },
- {
- uri: "viking://user/test/memories/experiences/.overview.md",
- score: 0.9,
- },
- {
- uri: "viking://user/test/memories/preferences/换货偏好.md",
- score: 0.8,
- },
- ],
- resources: [],
- skills: [],
- total: 3,
- });
-
- const output = await tool("search_experience").execute("call-search", {
- query: "没有订单号时如何换货",
- limit: 7,
- });
-
- expect(client.find).toHaveBeenCalledWith(
- "没有订单号时如何换货",
- {
- targetUri: "viking://user/memories/experiences/",
- limit: 7,
- },
- "peer-main",
- );
- expect(parseTextResult(output)).toEqual({
- results: [
- {
- uri: "viking://user/test/memories/experiences/无订单号换货处理.md",
- title: "无订单号换货处理",
- score: 0.86,
- snippet: "先确认用户身份,再定位订单。",
- },
- ],
- });
- });
-
- it("reads a canonical Experience and preserves its URI in the tool result", async () => {
- const { client, tool } = createHarness();
- const uri = "viking://user/test/memories/experiences/无订单号换货处理.md";
- client.read.mockResolvedValue("# 无订单号换货处理\n\n先验证用户身份。");
-
- const output = await tool("read_experience").execute("call-read", { uri });
-
- expect(client.read).toHaveBeenCalledWith(uri, "peer-main");
- expect(parseTextResult(output)).toEqual({
- uri,
- content: "# 无订单号换货处理\n\n先验证用户身份。",
- });
- });
-
- it("rejects non-Experience and noncanonical URIs before reading", async () => {
- const { client, tool } = createHarness();
- const readTool = tool("read_experience");
-
- await expect(readTool.execute("call-read", {
- uri: "viking://user/test/memories/preferences/换货偏好.md",
- })).rejects.toThrow("canonical OpenViking Experience URI");
- await expect(readTool.execute("call-read", {
- uri: "viking://user/test/memories/experiences/a.md#approach",
- })).rejects.toThrow("canonical OpenViking Experience URI");
- expect(client.read).not.toHaveBeenCalled();
- });
-
- it("rejects another user's Experience when userId is explicitly configured", async () => {
- const { client, tool } = createHarness({ userId: "current-user" });
-
- await expect(tool("read_experience").execute("call-read", {
- uri: "viking://user/other-user/memories/experiences/a.md",
- })).rejects.toThrow("canonical OpenViking Experience URI");
- expect(client.read).not.toHaveBeenCalled();
- });
-
- it("uses the standard bypass result without calling OpenViking", async () => {
- const { client, tool } = createHarness({ bypassed: true });
-
- await expect(tool("search_experience").execute("call-search", { query: "换货" }))
- .resolves.toEqual({ bypassed: "search_experience" });
- await expect(tool("read_experience").execute("call-read", {
- uri: "viking://user/test/memories/experiences/a.md",
- })).resolves.toEqual({ bypassed: "read_experience" });
- expect(client.find).not.toHaveBeenCalled();
- expect(client.read).not.toHaveBeenCalled();
- });
-});
-
-describe("isCanonicalExperienceUri", () => {
- it("accepts Experience files and rejects sidecars or URI aliases", () => {
- expect(isCanonicalExperienceUri("viking://user/test/memories/experiences/a.md")).toBe(true);
- expect(isCanonicalExperienceUri("viking://user/test/memories/experiences/.overview.md")).toBe(false);
- expect(isCanonicalExperienceUri("viking://user/test/memories/experiences/a.md?version=1")).toBe(false);
- expect(isCanonicalExperienceUri("viking://user/test/memories/experiences/../a.md")).toBe(false);
- });
-});
diff --git a/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts b/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts
index b451f2b95..042f7e42b 100644
--- a/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts
+++ b/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts
@@ -15,8 +15,6 @@ const DEFAULT_TOOL_NAMES = [
"ov_read",
"ov_multi_read",
"ov_list",
- "search_experience",
- "read_experience",
"memory_recall",
"ov_recall_trace",
"memory_store",
@@ -46,7 +44,7 @@ describe("openviking tool registry", () => {
default: DEFAULT_TOOL_NAMES,
memory: ["memory_recall", "memory_store", "memory_forget"],
resource_query: ["ov_search", "ov_read", "ov_multi_read", "ov_list"],
- experience: ["search_experience", "read_experience"],
+ experience: ["ov_search", "ov_read"],
import: ["add_resource", "add_skill"],
recall_trace: ["ov_recall_trace"],
archive: ["ov_archive_search", "ov_archive_expand"],
@@ -67,11 +65,4 @@ describe("openviking tool registry", () => {
expect(memoryOpenVikingConfigSchema.parse({}).enabledTools).not.toContain("add_resource");
expect(memoryOpenVikingConfigSchema.parse({ enableAddResourceTool: true }).enabledTools).toContain("add_resource");
});
-
- it("allows both Experience tools to be disabled as one group", () => {
- const config = memoryOpenVikingConfigSchema.parse({ disabledTools: ["experience"] });
-
- expect(config.enabledTools).not.toContain("search_experience");
- expect(config.enabledTools).not.toContain("read_experience");
- });
});
diff --git a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts b/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
index 6c77c9fb1..81156ff59 100644
--- a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
+++ b/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
@@ -84,15 +84,6 @@ describe("OpenClaw plugin package and install contract", () => {
]));
});
- it("ships the Experience Memory skill with source installs", () => {
- const installManifest = readJson("install-manifest.json");
- const installHelper = readFileSync(join(rootDir, "setup-helper/install.js"), "utf8");
-
- expect(installManifest.files.optional).toContain("skills/ov-experience-memory/SKILL.md");
- expect(existsSync(join(rootDir, "skills/ov-experience-memory/SKILL.md"))).toBe(true);
- expect(installHelper).toContain('"skills/ov-experience-memory/SKILL.md"');
- });
-
it("keeps runtime dependencies and overrides available for installed plugin loading", () => {
const packageJson = readJson("package.json");
diff --git a/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts b/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts
index 2a32b53ff..ed9a4c5b9 100644
--- a/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts
+++ b/examples/openclaw-plugin/tests/ut/plugin-registration.test.ts
@@ -98,14 +98,4 @@ describe("plugin registration", () => {
expect.any(Function),
);
});
-
- it("registers the standard Experience tools by default", () => {
- const api = createPluginApi({});
-
- contextEnginePlugin.register(api as any);
-
- const registeredNames = api.registerTool.mock.calls.map((call) => call[1]?.name);
- expect(registeredNames).toContain("search_experience");
- expect(registeredNames).toContain("read_experience");
- });
});
diff --git a/examples/openclaw-plugin/tests/ut/text-utils.test.ts b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
index 6168511e2..39373c372 100644
--- a/examples/openclaw-plugin/tests/ut/text-utils.test.ts
+++ b/examples/openclaw-plugin/tests/ut/text-utils.test.ts
@@ -321,6 +321,47 @@ describe("extractNewTurnMessages", () => {
},
]);
});
+
+ it("preserves failed toolResult status", () => {
+ const messages = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "toolCall",
+ id: "call_failed",
+ name: "ov_read",
+ arguments: { uri: "viking://user/test/memories/experiences/missing.md" },
+ },
+ ],
+ },
+ {
+ role: "toolResult",
+ toolCallId: "call_failed",
+ toolName: "ov_read",
+ content: [{ type: "text", text: "OpenViking request failed" }],
+ isError: true,
+ },
+ ];
+
+ const { messages: extracted } = extractNewTurnMessages(messages, 0);
+
+ expect(extracted).toEqual([
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "tool",
+ toolCallId: "call_failed",
+ toolName: "ov_read",
+ toolInput: { uri: "viking://user/test/memories/experiences/missing.md" },
+ toolOutput: "OpenViking request failed",
+ toolStatus: "error",
+ },
+ ],
+ },
+ ]);
+ });
});
describe("extractLatestUserText", () => {
diff --git a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
index 7462dbffa..f9dc9170e 100644
--- a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts
@@ -39,43 +39,6 @@ describe("extractNewTurnMessages: toolCallId propagation", () => {
}
});
- it("preserves standard Experience calls as completed ToolParts", () => {
- const uri = "viking://user/test/memories/experiences/无订单号换货处理.md";
- const messages = [
- {
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "call_experience_search",
- name: "search_experience",
- arguments: { query: "没有订单号时如何换货", limit: 5 },
- },
- ],
- },
- {
- role: "toolResult",
- toolCallId: "call_experience_search",
- toolName: "search_experience",
- content: [{ type: "text", text: JSON.stringify({ results: [{ uri }] }) }],
- },
- ];
-
- const { messages: extracted } = extractNewTurnMessages(messages, 0);
- const toolPart = extracted.flatMap((message) => message.parts).find((part) => part.type === "tool");
-
- expect(toolPart).toMatchObject({
- type: "tool",
- toolCallId: "call_experience_search",
- toolName: "search_experience",
- toolInput: { query: "没有订单号时如何换货", limit: 5 },
- toolStatus: "completed",
- });
- if (toolPart?.type === "tool") {
- expect(JSON.parse(toolPart.toolOutput)).toEqual({ results: [{ uri }] });
- }
- });
-
it("sets toolCallId to undefined when original message has no toolCallId", () => {
const messages = [
{
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index 6e1313dd5..4ed964823 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -1988,10 +1988,10 @@ describe("Tool: ov_recall_trace", () => {
});
describe("Plugin registration", () => {
- it("registers all 16 default tools", () => {
+ it("registers all 14 default tools", () => {
const { api } = setupPlugin();
contextEnginePlugin.register(api as any);
- expect(api.registerTool).toHaveBeenCalledTimes(16);
+ expect(api.registerTool).toHaveBeenCalledTimes(14);
});
it("registers only resource query tools when enabledTools is resource_query", () => {
diff --git a/examples/openclaw-plugin/text-utils.ts b/examples/openclaw-plugin/text-utils.ts
index d5667e648..db026d693 100644
--- a/examples/openclaw-plugin/text-utils.ts
+++ b/examples/openclaw-plugin/text-utils.ts
@@ -411,7 +411,7 @@ export function extractNewTurnMessages(
toolName,
toolInput,
toolOutput: output,
- toolStatus: "completed",
+ toolStatus: msg.isError === true ? "error" : "completed",
}],
});
}
diff --git a/examples/opencode-plugin/lib/shared/capture-utils.mjs b/examples/opencode-plugin/lib/shared/capture-utils.mjs
index 0cc76778f..3e078db47 100644
--- a/examples/opencode-plugin/lib/shared/capture-utils.mjs
+++ b/examples/opencode-plugin/lib/shared/capture-utils.mjs
@@ -102,6 +102,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -112,6 +113,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -122,8 +124,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -134,6 +138,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -147,11 +152,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -163,13 +176,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/examples/opencode-plugin/tests/memory-session.test.mjs b/examples/opencode-plugin/tests/memory-session.test.mjs
index 0332b47f6..3f37208c9 100644
--- a/examples/opencode-plugin/tests/memory-session.test.mjs
+++ b/examples/opencode-plugin/tests/memory-session.test.mjs
@@ -215,6 +215,96 @@ test("assistant messages are captured even when finish is not stop", async () =>
})
})
+test("OpenCode tool parts preserve completed and error state fields", async () => {
+ await withCaptureServer(async ({ endpoint, requests }) => {
+ await withTempDir("ov-oc-session-", async (dir) => {
+ const manager = createMemorySessionManager({ config: baseConfig(endpoint), pluginRoot: dir })
+ const sessionID = "oc-tool-parts"
+ const uri = "viking://user/test/memories/experiences/exchange.md"
+
+ await manager.init()
+ for (const [messageID, part] of [
+ [
+ "msg-tool-completed",
+ {
+ id: "part-tool-completed",
+ sessionID,
+ messageID: "msg-tool-completed",
+ type: "tool",
+ callID: "call-tool-completed",
+ tool: "openviking_read",
+ state: {
+ status: "completed",
+ input: { uris: uri },
+ output: "experience contents",
+ },
+ },
+ ],
+ [
+ "msg-tool-error",
+ {
+ id: "part-tool-error",
+ sessionID,
+ messageID: "msg-tool-error",
+ type: "tool",
+ callID: "call-tool-error",
+ tool: "openviking_read",
+ state: {
+ status: "error",
+ input: { uris: uri },
+ error: "OpenViking request failed",
+ },
+ },
+ ],
+ ]) {
+ await manager.handleEvent({
+ type: "message.updated",
+ properties: { info: { id: messageID, sessionID, role: "assistant" } },
+ })
+ await manager.handleEvent({
+ type: "message.part.updated",
+ properties: { part },
+ })
+ }
+
+ await manager.handleEvent({ type: "session.idle", properties: { sessionID } })
+
+ const addMessage = requests.find((request) => request.url === "/api/v1/sessions/oc-oc-tool-parts/messages/batch")
+ assert.ok(addMessage, "session.idle should capture OpenCode tool parts")
+ const body = JSON.parse(addMessage.body)
+ assert.deepEqual(body.messages, [
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "tool",
+ tool_id: "call-tool-completed",
+ tool_name: "openviking_read",
+ tool_status: "completed",
+ tool_input: { uris: uri },
+ tool_output: "experience contents",
+ },
+ ],
+ },
+ {
+ role: "assistant",
+ parts: [
+ {
+ type: "tool",
+ tool_id: "call-tool-error",
+ tool_name: "openviking_read",
+ tool_status: "error",
+ tool_input: { uris: uri },
+ tool_output: "OpenViking request failed",
+ },
+ ],
+ },
+ ])
+ await manager.flushAll({ commit: false })
+ })
+ })
+})
+
test("concurrent saves never race the shared state file (#3877)", async (t) => {
// Widen the race window: concurrent saveState() calls share the same
// `${statePath}.tmp` temp file. A slow writeFile keeps the shared .tmp
diff --git a/examples/pi-coding-agent-extension/shared/capture-utils.mjs b/examples/pi-coding-agent-extension/shared/capture-utils.mjs
index 0cc76778f..3e078db47 100644
--- a/examples/pi-coding-agent-extension/shared/capture-utils.mjs
+++ b/examples/pi-coding-agent-extension/shared/capture-utils.mjs
@@ -102,6 +102,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -112,6 +113,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -122,8 +124,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -134,6 +138,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -147,11 +152,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -163,13 +176,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/examples/skills/ov-experience-memory/SKILL.md b/examples/skills/ov-experience-memory/SKILL.md
index 1faa749e2..787891d4c 100644
--- a/examples/skills/ov-experience-memory/SKILL.md
+++ b/examples/skills/ov-experience-memory/SKILL.md
@@ -1,156 +1,116 @@
---
name: ov-experience-memory
-description: >
- Use OpenViking experience memories during task execution. Search relevant
- experiences with search_experience, read selected experiences with
- read_experience, and leave standard tool parts in the committed session so
- OpenViking can report recall and injection usage.
-version: 2026.7.9
-tags:
- - openviking
- - experience-memory
- - agent-memory
- - usage-reporting
+description: Retrieve and apply OpenViking Experience memories through the Agent runtime's generic OpenViking search and read tools. Use before or during executable, multi-step, or tool-based work such as coding, file or data changes, configuration, deployment, workflow execution, and failure recovery when prior operational guidance could improve reliability. Do not use for casual chat or simple factual questions.
---
# OpenViking Experience Memory
-Use this skill when the current user request starts or continues an executable
-task, especially tasks involving tools, files, code changes, data operations,
-workflow decisions, or multi-step actions.
-
-Do not use this skill for casual chat, pure explanation, or one-off factual Q&A
-that does not require operational guidance.
-
-## Runtime Contract
-
-The agent runtime must expose two tools with these exact names:
-
-- `search_experience`
-- `read_experience`
-
-OpenViking usage reporting recognizes only completed tool parts with these exact
-tool names. Calls to generic `find`, `search`, `read`, `ov_search`, or `ov_read`
-do not count as experience recall or injection events.
-
-## Tool: search_experience
-
-Purpose: search reusable execution experiences from the OpenViking experience
-library before assembling task context.
-
-Input schema:
-
-```json
-{
- "query": "string",
- "limit": 5
-}
-```
-
-Output schema:
-
-```json
-{
- "results": [
- {
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "title": "example",
- "score": 0.82,
- "snippet": "Short summary or matched situation"
- }
- ]
-}
-```
-
-Implementation:
-
-The runtime tool calls OpenViking `POST /api/v1/search/find` with `target_uri`
-fixed to the current-user shorthand `viking://user/memories/experiences/`.
-Callers provide only `query` and optional `limit`; they cannot override or pass
-`target_uri`. OpenViking resolves the fixed shorthand against the authenticated
-request user. Return only canonical experience memory URIs for that user; never
-hardcode `default` or another user ID.
-
-Usage reporting:
-
-A completed `search_experience` tool part is counted as an experience recall
-event for every `results[].uri` value.
-
-## Tool: read_experience
-
-Purpose: read the full Markdown body of a selected experience and inject it into
-the agent prompt as task execution guidance.
-
-Input schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md"
-}
-```
-
-Output schema:
-
-```json
-{
- "uri": "viking://user/<current_user_id>/memories/experiences/example.md",
- "content": "Experience Markdown body"
-}
-```
-
-Implementation:
-
-Call OpenViking `GET /api/v1/content/read?uri=<encoded_uri>` for the selected
-experience URI. Always pass the canonical URI returned by `search_experience`;
-do not construct a URI with a hardcoded user ID. The returned content should be
-inserted into the prompt as operational guidance, not as user profile facts.
-
-Usage reporting:
-
-A completed `read_experience` tool part is counted as an experience injection
-event for `tool_input.uri` or `tool_output.uri`. In this design, reading an
-experience through `read_experience` means the experience was injected into the
-prompt.
-
-## Recommended Flow
-
-1. When a task begins, build a short query from the latest user instruction,
- current plan, active skill name, and important tool/environment context.
-2. Call `search_experience` before final prompt assembly.
-3. Review returned titles/snippets and select only experiences likely to affect
- execution.
-4. Call `read_experience` for selected experience URIs.
-5. Inject the returned Markdown into the prompt under an explicit experience
- section.
-6. Continue task execution.
-7. Commit the session normally. The committed session must include the
- `search_experience` and `read_experience` tool parts so OpenViking can report
- usage.
-
-## Prompt Injection Format
-
-Use a compact and explicit block:
-
-```text
-<openviking-experience-memory>
-The following guidance was retrieved from prior task execution experience.
-Use it as operational guidance. Do not treat it as user identity or preference.
-
-<experience uri="viking://user/<current_user_id>/memories/experiences/example.md">
-...experience markdown...
-</experience>
-</openviking-experience-memory>
-```
-
-## Commit Requirements
-
-The session committed to OpenViking must preserve tool parts with:
-
-- `tool_name`
-- `tool_status`
-- `tool_input`
-- `tool_output`
-- `tool_id`
-
-Only `tool_status == "completed"` is counted. Failed, cancelled, or skipped tool
-parts are ignored by usage reporting.
+Use prior task Experience as advisory operational guidance. Keep the current
+user request, current environment, and verified tool results authoritative.
+Experience retrieval supplements normal context retrieval; it does not replace
+user memory, events, preferences, session archives, resources, or Agent Skills.
+
+## Preconditions
+
+- Use only OpenViking tools that are actually registered in the current Agent
+ runtime.
+- Require both a semantic search capability and an exact URI read capability.
+- If either capability is unavailable, continue without Experience. Do not
+ invent a tool call, fabricate a ToolPart, or replace the Agent tool call with
+ direct HTTP or CLI access.
+- Do not substitute broad memory `recall` for a search scoped to the Experience
+ root. Continue using the runtime's normal recall and retrieval flows when the
+ task also needs user facts, events, decisions, prior conversation, or domain
+ resources.
+
+## Select Runtime Tools
+
+Choose the registered names that match the current runtime:
+
+| Runtime | Search | Read |
+| --- | --- | --- |
+| OpenViking MCP, Codex, Claude Code | `find` or `search` | `read` |
+| OpenCode | `openviking_find` or `openviking_search` | `openviking_read` |
+| OpenClaw | `ov_search` | `ov_read` or `ov_multi_read` |
+
+The host may display MCP names with a namespace such as
+`mcp__openviking__find`. Use the exact registered name and schema shown by the
+runtime. Prefer `find` for a fast task-start lookup and `search` when session
+context or deeper intent analysis is useful.
+
+## Retrieval Workflow
+
+1. Decide whether the request is an executable task. Retrieve Experience for
+ planning, tool use, environment changes, multi-step workflows, or recovery
+ from a failed attempt. Skip retrieval for casual conversation and simple
+ knowledge answers.
+2. Build one concise query containing the task goal, domain object, intended
+ operation, and important constraints. After a failure, include the failed
+ operation and stable error signature.
+3. Search only the current user's Experience root:
+
+ ```text
+ viking://user/memories/experiences
+ ```
+
+ For tools using MCP-style parameters, set `target_uri` to this root. For
+ OpenClaw `ov_search`, set `uri` to this root. Never hardcode `default`,
+ `test`, or another user ID.
+4. Start with `limit=5` and the tool's normal score threshold. Judge results by
+ task, environment, preconditions, and likely effect; title similarity alone
+ is insufficient. If no result is relevant, continue without Experience and
+ do not broaden the search to unrelated memory directories.
+5. Select only the one to three Experience files likely to change execution.
+ Require an exact file URI without a query or fragment. Ignore directories,
+ unrelated memory types, and sidecars such as `.abstract.md`, `.overview.md`,
+ and `.relations.json`.
+6. Read every selected canonical `viking://.../memories/experiences/...` URI
+ with the runtime's OpenViking read tool. Search abstracts help selection but
+ are not a substitute for reading the Experience body.
+7. Apply relevant steps and checks while executing the task. Do not repeat the
+ Experience verbatim to the user unless its content is directly needed in the
+ answer.
+8. If execution fails for a materially new reason, perform at most one focused
+ follow-up search using the failure evidence, then read only newly relevant
+ Experience files.
+
+## Applying Retrieved Experience
+
+- Treat Experience as reusable procedure, not as a user profile, user intent,
+ security policy, or proof that an action succeeded.
+- Follow priority in this order: system and developer instructions, current
+ user request, current environment and tool evidence, then Experience.
+- Ignore stale, incompatible, unsafe, or conflicting guidance. Verify commands,
+ paths, APIs, versions, and destructive actions against the current task.
+- Preserve confirmation requirements and permission boundaries. Prior success
+ never authorizes a destructive or external action in the current session.
+- When multiple Experience files conflict, prefer the one whose preconditions
+ match the current environment; otherwise proceed conservatively and surface
+ the ambiguity when it affects the user.
+
+## Session Evidence
+
+Use real Agent tool calls so the committed OpenViking session retains their
+ToolParts:
+
+- A completed generic OpenViking `find`, `search`, or `list` result containing
+ an Experience URI records recall for that Experience.
+- A completed generic OpenViking `read` or `multi_read` of an Experience URI
+ records injection and can associate the resulting trajectory with that
+ Experience.
+- Failed, cancelled, or incomplete calls do not count.
+
+Do not edit, summarize away, or synthesize these ToolParts before the session
+is committed.
+
+## Example
+
+For a request to fix a deployment failure:
+
+1. Search the Experience root with a query such as
+ `Kubernetes deployment image pull failure private registry`.
+2. Read the most relevant exact Experience URI.
+3. Check that its registry, credential, and rollout assumptions match the
+ current cluster.
+4. Apply the compatible diagnostic steps, verify the live result, and continue
+ the user's task.
diff --git a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
index 0cc76778f..3e078db47 100644
--- a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
@@ -102,6 +102,7 @@ function toolName(block) {
block?.name ||
block?.tool_name ||
block?.toolName ||
+ block?.tool ||
block?.function?.name ||
block?.call?.name ||
"",
@@ -112,6 +113,7 @@ function toolPayload(block, kind) {
if (!block || typeof block !== "object") return "";
if (kind === "call") {
return block.input ??
+ block.state?.input ??
block.arguments ??
block.args ??
block.params ??
@@ -122,8 +124,10 @@ function toolPayload(block, kind) {
"";
}
return block.output ??
+ block.state?.output ??
block.result ??
block.error ??
+ block.state?.error ??
block.data ??
block.content ??
block.text ??
@@ -134,6 +138,7 @@ function toolId(block) {
return oneLine(
block?.call_id ||
block?.callId ||
+ block?.callID ||
block?.tool_call_id ||
block?.toolCallId ||
block?.tool_use_id ||
@@ -147,11 +152,19 @@ function toolId(block) {
function toolStatus(block, kind) {
if (kind === "call") return "running";
- if (block?.is_error || block?.error) return "error";
- const status = oneLine(block?.status || "");
+ if (block?.is_error || block?.error || block?.state?.error) return "error";
+ const status = oneLine(block?.status || block?.state?.status || "");
return status || "completed";
}
+function setToolInput(part, payload) {
+ const input = parseMaybeJson(payload);
+ if (input === "" || input == null) return;
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+}
+
function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
@@ -163,13 +176,11 @@ function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, too
tool_status: toolStatus(block, kind),
};
if (kind === "call") {
- const input = parseMaybeJson(payload);
- if (input !== "" && input != null) {
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
- }
+ setToolInput(part, payload);
} else {
+ if (block?.state?.input !== undefined) {
+ setToolInput(part, block.state.input);
+ }
part.tool_output = stringifyCompact(payload, toolMaxChars);
}
return part;
diff --git a/openviking/session/memory/experience_lineage.py b/openviking/session/memory/experience_lineage.py
index 1241fdf36..e7874cb65 100644
--- a/openviking/session/memory/experience_lineage.py
+++ b/openviking/session/memory/experience_lineage.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import json
+import re
from typing import Any, Iterable
from openviking.core.namespace import canonicalize_uri, uri_parts
@@ -13,6 +14,15 @@ from openviking.server.identity import RequestContext
from openviking.utils.tags import normalize_search_tag
_EXPERIENCE_SIDECAR_FILENAMES = {".abstract.md", ".overview.md", ".relations.json"}
+_READ_TOOL_OPERATIONS = {
+ "read": "read",
+ "multi_read": "multi_read",
+ "openviking_read": "read",
+ "openviking_multi_read": "multi_read",
+ "ov_read": "read",
+ "ov_multi_read": "multi_read",
+}
+_MCP_OPENVIKING_READ_RE = re.compile(r"^mcp__openviking__(read|multi_read)$")
TRAJECTORY_OUTCOMES = ("success", "failure", "partial", "unknown", "unfinished")
@@ -112,28 +122,106 @@ def collect_read_experience_uris(
for part in message.parts:
if not isinstance(part, ToolPart):
continue
- if part.tool_name != "read_experience" or part.tool_status != "completed":
+ operation = _read_operation(part.tool_name)
+ if operation is None or part.tool_status != "completed":
continue
tool_input = part.tool_input if isinstance(part.tool_input, dict) else {}
if not tool_input and part.tool_id:
tool_input = tool_inputs.get((part.tool_id, part.tool_name), {})
- output = _load_mapping(part.tool_output)
- uri = tool_input.get("uri") or output.get("uri")
- canonical_uri = canonical_experience_uri(str(uri or ""), ctx)
- if not canonical_uri or canonical_uri in seen:
- continue
- seen.add(canonical_uri)
- result.append(canonical_uri)
+ output = _load_value(part.tool_output)
+ candidates = list(_iter_named_uris(tool_input))
+ if not candidates:
+ candidates.extend(_iter_named_uris(output))
+ statuses = _read_result_statuses(output) if operation == "multi_read" else {}
+ texts = list(_iter_text_fields(output))
+ for raw_uri in candidates:
+ uri = str(raw_uri or "").strip()
+ canonical_uri = canonical_experience_uri(uri, ctx)
+ if (
+ not canonical_uri
+ or canonical_uri in seen
+ or statuses.get(uri) is False
+ or _read_failed_in_text(uri, texts)
+ ):
+ continue
+ seen.add(canonical_uri)
+ result.append(canonical_uri)
return result
-def _load_mapping(value: Any) -> dict[str, Any]:
- if isinstance(value, dict):
+def _read_operation(tool_name: str) -> str | None:
+ name = str(tool_name or "").strip()
+ operation = _READ_TOOL_OPERATIONS.get(name)
+ if operation is not None:
+ return operation
+ match = _MCP_OPENVIKING_READ_RE.fullmatch(name)
+ return match.group(1) if match is not None else None
+
+
+def _load_value(value: Any) -> Any:
+ if isinstance(value, (dict, list)):
return value
if isinstance(value, str) and value.strip():
try:
- parsed = json.loads(value)
+ return json.loads(value)
except json.JSONDecodeError:
- return {}
- return parsed if isinstance(parsed, dict) else {}
- return {}
+ return value
+ return value
+
+
+def _iter_named_uris(value: Any) -> Iterable[str]:
+ if isinstance(value, dict):
+ for key, child in value.items():
+ if key in {"uri", "uris"}:
+ if isinstance(child, str):
+ yield child
+ elif isinstance(child, list):
+ yield from (item for item in child if isinstance(item, str))
+ if isinstance(child, (dict, list)):
+ yield from _iter_named_uris(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _iter_named_uris(child)
+
+
+def _read_result_statuses(value: Any) -> dict[str, bool]:
+ statuses: dict[str, bool] = {}
+ if isinstance(value, dict):
+ uri = value.get("uri")
+ success = value.get("success")
+ if isinstance(uri, str) and isinstance(success, bool):
+ statuses[uri.strip()] = success
+ for child in value.values():
+ if isinstance(child, (dict, list)):
+ statuses.update(_read_result_statuses(child))
+ elif isinstance(value, list):
+ for child in value:
+ statuses.update(_read_result_statuses(child))
+ return statuses
+
+
+def _iter_text_fields(value: Any) -> Iterable[str]:
+ if isinstance(value, str):
+ yield value
+ elif isinstance(value, dict):
+ for key, child in value.items():
+ if key == "text" and isinstance(child, str):
+ yield child
+ elif isinstance(child, (dict, list)):
+ yield from _iter_text_fields(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _iter_text_fields(child)
+
+
+def _read_failed_in_text(uri: str, texts: Iterable[str]) -> bool:
+ missing_marker = f"(nothing found at {uri})"
+ for text in texts:
+ if missing_marker in text:
+ return True
+ section_marker = f"--- START OF {uri} ---"
+ if section_marker in text:
+ section = text.split(section_marker, 1)[1].split(f"--- END OF {uri} ---", 1)[0]
+ if section.lstrip().startswith("ERROR:"):
+ return True
+ return False
diff --git a/openviking/usage_reporter/extractors.py b/openviking/usage_reporter/extractors.py
index daf970707..75b842b30 100644
--- a/openviking/usage_reporter/extractors.py
+++ b/openviking/usage_reporter/extractors.py
@@ -5,15 +5,48 @@
from __future__ import annotations
import json
+import re
from datetime import datetime
-from typing import Any, Iterable, Protocol
+from typing import Any, Iterable, Literal, Protocol, cast
from openviking.message import Message, ToolPart
from openviking.utils.time_utils import format_iso8601, parse_iso_datetime
from .models import UsageContext, UsageEvent, utc_now_iso
+UsageKind = Literal["recall", "injection"]
+ToolOperation = Literal["find", "search", "list", "read", "multi_read"]
+
_EXPERIENCE_SIDECAR_FILENAMES = {".abstract.md", ".overview.md", ".relations.json"}
+_RECALL_TOOL_OPERATIONS: dict[str, ToolOperation] = {
+ "find": "find",
+ "search": "search",
+ "list": "list",
+ "openviking_find": "find",
+ "openviking_search": "search",
+ "openviking_list": "list",
+ "ov_search": "search",
+ "ov_list": "list",
+}
+_INJECTION_TOOL_OPERATIONS: dict[str, ToolOperation] = {
+ "read": "read",
+ "multi_read": "multi_read",
+ "openviking_read": "read",
+ "openviking_multi_read": "multi_read",
+ "ov_read": "read",
+ "ov_multi_read": "multi_read",
+}
+_MCP_OPENVIKING_TOOL_RE = re.compile(r"^mcp__openviking__(find|search|list|read|multi_read)$")
+_MCP_SEARCH_RESULT_RE = re.compile(r"^- \[[^]]+\]\s+(viking://.+?)\s*$")
+_OPENVIKING_SEARCH_TABLE_ROW_RE = re.compile(
+ r"^\s*\d+\s{2,}(?:memory|resource|skill)\s{2,}"
+ r"(viking://.+?)\s{2,}(?:\d+)?\s{2,}(?:\d+(?:\.\d+)?)?\s{2,}.*$"
+)
+_OPENVIKING_SEARCH_SIMPLE_ROW_RE = re.compile(
+ r"^\s*\d+\s+(?:memory|resource|skill)\s+(viking://\S+)\s*$"
+)
+_LIST_FILE_RE = re.compile(r"^\s*\[file\]\s+(.+?)\s*$")
+_USER_MEMORY_SHORTHAND_PREFIX = "viking://user/memories/"
class UsageExtractor(Protocol):
@@ -27,16 +60,166 @@ class UsageExtractor(Protocol):
) -> list[UsageEvent]: ...
-def _load_mapping(value: Any) -> dict[str, Any]:
- if isinstance(value, dict):
+def _load_json(value: Any) -> Any:
+ if isinstance(value, (dict, list)):
return value
if isinstance(value, str) and value.strip():
try:
- parsed = json.loads(value)
+ return json.loads(value)
except json.JSONDecodeError:
- return {}
- return parsed if isinstance(parsed, dict) else {}
- return {}
+ return value
+ return value
+
+
+def _tool_usage(tool_name: str) -> tuple[UsageKind, ToolOperation] | None:
+ name = tool_name.strip()
+ operation = _RECALL_TOOL_OPERATIONS.get(name)
+ if operation is not None:
+ return "recall", operation
+ operation = _INJECTION_TOOL_OPERATIONS.get(name)
+ if operation is not None:
+ return "injection", operation
+
+ match = _MCP_OPENVIKING_TOOL_RE.fullmatch(name)
+ if match is None:
+ return None
+ operation = cast(ToolOperation, match.group(1))
+ if operation in {"find", "search", "list"}:
+ return "recall", operation
+ return "injection", operation
+
+
+def _iter_named_uris(value: Any) -> Iterable[str]:
+ """Yield URI values from structured `uri`/`uris` fields only."""
+ if isinstance(value, dict):
+ for key, child in value.items():
+ if key in {"uri", "uris"}:
+ if isinstance(child, str):
+ yield child
+ elif isinstance(child, list):
+ for item in child:
+ if isinstance(item, str):
+ yield item
+ if isinstance(child, (dict, list)):
+ yield from _iter_named_uris(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _iter_named_uris(child)
+
+
+def _iter_search_result_uris(value: Any) -> Iterable[str]:
+ """Yield URIs only from known search-result collections, not scope metadata."""
+ if isinstance(value, dict):
+ for key, child in value.items():
+ if key in {"results", "memories", "resources", "skills"}:
+ yield from _iter_named_uris(child)
+ if isinstance(child, (dict, list)):
+ yield from _iter_search_result_uris(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _iter_search_result_uris(child)
+
+
+def _iter_text_fields(value: Any) -> Iterable[str]:
+ if isinstance(value, str):
+ yield value
+ elif isinstance(value, dict):
+ for key, child in value.items():
+ if key == "text" and isinstance(child, str):
+ yield child
+ elif isinstance(child, (dict, list)):
+ yield from _iter_text_fields(child)
+ elif isinstance(value, list):
+ for child in value:
+ yield from _iter_text_fields(child)
+
+
+def _unique_uris(uris: Iterable[str], context: UsageContext) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for raw_uri in uris:
+ uri = _canonicalize_usage_uri(raw_uri, context)
+ if uri in seen or not _is_experience_uri(uri, context):
+ continue
+ seen.add(uri)
+ result.append(uri)
+ return result
+
+
+def _canonicalize_usage_uri(uri: str, context: UsageContext) -> str:
+ normalized = uri.strip()
+ if normalized.startswith(_USER_MEMORY_SHORTHAND_PREFIX):
+ relative = normalized.removeprefix(_USER_MEMORY_SHORTHAND_PREFIX)
+ return f"viking://user/{context.user_id}/memories/{relative}"
+ return normalized
+
+
+def _join_uri(parent: str, child: str) -> str:
+ return f"{parent.rstrip('/')}/{child.lstrip('/')}"
+
+
+def _iter_list_file_uris(value: Any, parent_uri: str) -> Iterable[str]:
+ """Extract files from structured list results without treating directories as recalls."""
+ if not isinstance(value, dict):
+ return
+ entries = value.get("entries")
+ if isinstance(entries, list):
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ if entry.get("isDir") is True or entry.get("is_dir") is True:
+ continue
+ if str(entry.get("type") or "").lower() in {"dir", "directory"}:
+ continue
+ uri = str(entry.get("uri") or "").strip()
+ if uri:
+ yield uri
+ continue
+ name = str(entry.get("name") or "").strip()
+ if name and parent_uri:
+ yield _join_uri(parent_uri, name)
+ for child in value.values():
+ if isinstance(child, (dict, list)):
+ if isinstance(child, dict):
+ yield from _iter_list_file_uris(child, parent_uri)
+ else:
+ for item in child:
+ if isinstance(item, dict):
+ yield from _iter_list_file_uris(item, parent_uri)
+
+
+def _read_result_statuses(value: Any) -> dict[str, bool]:
+ """Return per-URI success flags when a multi-read result exposes them."""
+ statuses: dict[str, bool] = {}
+ if isinstance(value, dict):
+ uri = value.get("uri")
+ success = value.get("success")
+ if isinstance(uri, str) and isinstance(success, bool):
+ statuses[uri.strip()] = success
+ for child in value.values():
+ if isinstance(child, (dict, list)):
+ statuses.update(_read_result_statuses(child))
+ elif isinstance(value, list):
+ for child in value:
+ statuses.update(_read_result_statuses(child))
+ return statuses
+
+
+def _read_failed_in_text(uri: str, texts: Iterable[str], context: UsageContext) -> bool:
+ aliases = [uri]
+ canonical_prefix = f"viking://user/{context.user_id}/memories/"
+ if uri.startswith(canonical_prefix):
+ aliases.append(f"{_USER_MEMORY_SHORTHAND_PREFIX}{uri.removeprefix(canonical_prefix)}")
+ for text in texts:
+ for alias in aliases:
+ if f"(nothing found at {alias})" in text:
+ return True
+ section_marker = f"--- START OF {alias} ---"
+ if section_marker in text:
+ section = text.split(section_marker, 1)[1].split(f"--- END OF {alias} ---", 1)[0]
+ if section.lstrip().startswith("ERROR:"):
+ return True
+ return False
def _is_experience_uri(uri: str, context: UsageContext) -> bool:
@@ -63,7 +246,7 @@ def _event_time(message: Message) -> str:
class MemoryUsageExtractor:
- """Extract memory recalled/injected usage events from official tool parts."""
+ """Extract Experience recall/injection events from OpenViking tool parts."""
name = "memory_usage"
@@ -93,77 +276,125 @@ class MemoryUsageExtractor:
continue
if part.tool_status != "completed":
continue
- if part.tool_name == "search_experience":
+ usage = _tool_usage(part.tool_name)
+ if usage is None:
+ continue
+ kind, operation = usage
+ fallback_input = tool_inputs.get((part.tool_id, part.tool_name), {})
+ if kind == "recall":
events.extend(
- self._extract_search_events(
+ self._extract_recall_events(
part,
+ operation=operation,
context=context,
message=message,
+ fallback_input=fallback_input,
)
)
- elif part.tool_name == "read_experience":
- event = self._extract_read_event(
- part,
- context=context,
- message=message,
- fallback_input=tool_inputs.get((part.tool_id, part.tool_name), {}),
+ else:
+ events.extend(
+ self._extract_injection_events(
+ part,
+ operation=operation,
+ context=context,
+ message=message,
+ fallback_input=fallback_input,
+ )
)
- if event is not None:
- events.append(event)
return events
- def _extract_search_events(
+ def _extract_recall_events(
self,
part: ToolPart,
*,
+ operation: ToolOperation,
context: UsageContext,
message: Message,
+ fallback_input: dict[str, Any],
) -> Iterable[UsageEvent]:
- output = _load_mapping(part.tool_output)
- results = output.get("results", [])
- if not isinstance(results, list):
- return []
+ output = _load_json(part.tool_output)
+ tool_input = part.tool_input if isinstance(part.tool_input, dict) else {}
+ if not tool_input:
+ tool_input = fallback_input
- events: list[UsageEvent] = []
- for result in results:
- if not isinstance(result, dict):
- continue
- uri = str(result.get("uri") or "").strip()
- if not uri or not _is_experience_uri(uri, context):
- continue
- events.append(
- self._build_event(
- event_type="memory.recalled",
- resource_uri=uri,
- part=part,
- context=context,
- message=message,
- )
+ candidates: list[str] = []
+ if operation == "list":
+ parent_uri = str(tool_input.get("uri") or "").strip()
+ candidates.extend(_iter_list_file_uris(output, parent_uri))
+ for text in _iter_text_fields(output):
+ for line in text.splitlines():
+ match = _LIST_FILE_RE.fullmatch(line)
+ if match is None:
+ continue
+ label = match.group(1).split(" - ", 1)[0].strip()
+ if label.startswith("viking://"):
+ candidates.append(label)
+ elif parent_uri:
+ candidates.append(_join_uri(parent_uri, label))
+ else:
+ candidates.extend(_iter_search_result_uris(output))
+ for text in _iter_text_fields(output):
+ for line in text.splitlines():
+ match = _MCP_SEARCH_RESULT_RE.fullmatch(line)
+ if match is None:
+ match = _OPENVIKING_SEARCH_TABLE_ROW_RE.fullmatch(line)
+ if match is None:
+ match = _OPENVIKING_SEARCH_SIMPLE_ROW_RE.fullmatch(line)
+ if match is not None:
+ candidates.append(match.group(1).strip())
+
+ return [
+ self._build_event(
+ event_type="memory.recalled",
+ resource_uri=uri,
+ part=part,
+ context=context,
+ message=message,
)
- return events
+ for uri in _unique_uris(candidates, context)
+ ]
- def _extract_read_event(
+ def _extract_injection_events(
self,
part: ToolPart,
*,
+ operation: ToolOperation,
context: UsageContext,
message: Message,
fallback_input: dict[str, Any],
- ) -> UsageEvent | None:
+ ) -> list[UsageEvent]:
tool_input = part.tool_input if isinstance(part.tool_input, dict) else {}
if not tool_input:
tool_input = fallback_input
- output = _load_mapping(part.tool_output)
- uri = str(tool_input.get("uri") or output.get("uri") or "").strip()
- if not uri or not _is_experience_uri(uri, context):
- return None
- return self._build_event(
- event_type="memory.injected",
- resource_uri=uri,
- part=part,
- context=context,
- message=message,
+ output = _load_json(part.tool_output)
+
+ candidates = list(_iter_named_uris(tool_input))
+ if not candidates:
+ candidates.extend(_iter_named_uris(output))
+ statuses = (
+ {
+ _canonicalize_usage_uri(uri, context): success
+ for uri, success in _read_result_statuses(output).items()
+ }
+ if operation == "multi_read"
+ else {}
)
+ texts = list(_iter_text_fields(output))
+
+ events: list[UsageEvent] = []
+ for uri in _unique_uris(candidates, context):
+ if statuses.get(uri) is False or _read_failed_in_text(uri, texts, context):
+ continue
+ events.append(
+ self._build_event(
+ event_type="memory.injected",
+ resource_uri=uri,
+ part=part,
+ context=context,
+ message=message,
+ )
+ )
+ return events
def _build_event(
self,
diff --git a/openviking/usage_reporter/file_log_sink.py b/openviking/usage_reporter/file_log_sink.py
index 69e72f027..4cd88a8ec 100644
--- a/openviking/usage_reporter/file_log_sink.py
+++ b/openviking/usage_reporter/file_log_sink.py
@@ -1,6 +1,6 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
-"""Hourly rotating key-value usage log sink."""
+"""Hourly rotating usage event log sink."""
from __future__ import annotations
@@ -17,7 +17,7 @@ from typing import TYPE_CHECKING, Any, Iterator
if TYPE_CHECKING:
from .models import UsageEvent
-_COUNT_NAMES = {
+_EVENT_NAMES = {
"memory.recalled": "experience.recall.count",
"memory.injected": "experience.inject.count",
}
@@ -119,79 +119,55 @@ class _ProcessSafeTimedRotatingFileHandler(TimedRotatingFileHandler):
self.rolloverAt = self.computeRollover(int(path_stat.st_mtime))
-def _timestamp_millis(value: str) -> int:
+def _format_event_time(value: str) -> str:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
- return int(parsed.timestamp() * 1000)
+ return parsed.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+
+
+def _build_tenant_id(
+ *,
+ resource_id: str,
+ account_id: str,
+ user_id: str,
+ resource_uri: str,
+) -> str:
+ return (
+ f"resource_id:{resource_id};account_id:{account_id};"
+ f"user_id:{user_id};resource_uri:{resource_uri}"
+ )
-def _to_count_record(event: UsageEvent, *, resource_id: str) -> dict[str, Any]:
+def _to_log_record(event: UsageEvent, *, resource_id: str) -> dict[str, Any]:
record = event.to_dict()
event_type = str(record.get("event_type") or "")
try:
- count_name = _COUNT_NAMES[event_type]
+ event_name = _EVENT_NAMES[event_type]
except KeyError as exc:
raise ValueError(f"unsupported usage event type: {event_type}") from exc
- evidence = record.get("evidence")
- evidence = evidence if isinstance(evidence, dict) else {}
- attributes = record.get("attributes")
- attributes = attributes if isinstance(attributes, dict) else {}
-
- extra = {key: value for key, value in evidence.items() if value not in (None, "")}
- session_id = str(record.get("session_id") or "")
- if session_id:
- extra["session_id"] = session_id
- task_id = record.get("task_id")
- if task_id not in (None, ""):
- extra["task_id"] = task_id
- if attributes:
- extra["attributes"] = attributes
-
- unique_id = str(record.get("event_id") or "").strip()
- if not unique_id:
+ object_id = str(record.get("event_id") or "").strip()
+ if not object_id:
raise ValueError("event_id is required")
- count_record = {
- "count_name": count_name,
- "op_type": "add",
- "amount": 1.0,
- "timestamp": _timestamp_millis(str(record.get("occurred_at") or "")),
- "unique_id": unique_id,
+ account_id = str(record.get("account_id") or "")
+ user_id = str(record.get("user_id") or "")
+ resource_uri = str(record.get("resource_uri") or "")
+ return {
+ "event_time": _format_event_time(str(record.get("occurred_at") or "")),
+ "tenant_id": _build_tenant_id(
+ resource_id=resource_id,
+ account_id=account_id,
+ user_id=user_id,
+ resource_uri=resource_uri,
+ ),
+ "event_name": event_name,
+ "object_id": object_id,
+ "count": 1,
"tags": {
- "account_id": str(record.get("account_id") or ""),
- "user_id": str(record.get("user_id") or ""),
- "resource_uri": str(record.get("resource_uri") or ""),
"resource_type": str(record.get("resource_type") or ""),
},
- "extra": extra,
- }
- count_record["prefix"] = resource_id
- return count_record
-
-
-def _build_message_key(record: dict[str, Any]) -> str:
- tags = record.get("tags")
- tags = tags if isinstance(tags, dict) else {}
- extra = record.get("extra")
- extra = extra if isinstance(extra, dict) else {}
- target = str(tags.get("resource_uri") or extra.get("session_id") or "")
- return "|".join(
- (
- str(record.get("prefix") or ""),
- str(tags.get("account_id") or ""),
- str(tags.get("user_id") or ""),
- target,
- )
- )
-
-
-def _to_log_record(event: UsageEvent, *, resource_id: str) -> dict[str, Any]:
- value = _to_count_record(event, resource_id=resource_id)
- return {
- "key": _build_message_key(value),
- "value": value,
}
diff --git a/tests/session/test_session_usage_reporter.py b/tests/session/test_session_usage_reporter.py
index 14b24726e..69e47b8b8 100644
--- a/tests/session/test_session_usage_reporter.py
+++ b/tests/session/test_session_usage_reporter.py
@@ -4,7 +4,7 @@
import pytest
from openviking.message import ToolPart
-from openviking.server.dependencies import get_service
+from openviking.service.core import OpenVikingService
from openviking.service.task_tracker import get_task_tracker
from openviking.usage_reporter import MemoryUsageExtractor, UsageReporter
@@ -22,7 +22,10 @@ async def _wait_for_task(task_id: str, timeout: float = 30.0) -> dict:
@pytest.mark.asyncio
-async def test_commit_reports_memory_usage_events_to_sink(session):
+async def test_commit_reports_memory_usage_events_to_sink(
+ session,
+ service: OpenVikingService,
+):
reported_events = []
class RecordingSink:
@@ -34,13 +37,13 @@ async def test_commit_reports_memory_usage_events_to_sink(session):
extractors=[MemoryUsageExtractor()],
sinks=[RecordingSink()],
)
- get_service().sessions.set_usage_reporter(reporter)
+ service.sessions.set_usage_reporter(reporter)
session.add_message(
"user",
[
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": experience_uri},
)
diff --git a/tests/session/train/test_trajectory_analyzer_component.py b/tests/session/train/test_trajectory_analyzer_component.py
index 500d0ed31..5cbb84d45 100644
--- a/tests/session/train/test_trajectory_analyzer_component.py
+++ b/tests/session/train/test_trajectory_analyzer_component.py
@@ -165,7 +165,7 @@ async def test_trajectory_rollout_analyzer_extracts_and_persists_trajectory(monk
parts=[
ToolPart(
tool_id="read-1",
- tool_name="read_experience",
+ tool_name="read",
tool_input={"uri": "viking://user/u/memories/experiences/exchange.md"},
tool_output="experience body",
tool_status="completed",
diff --git a/tests/unit/session/memory/test_experience_lineage.py b/tests/unit/session/memory/test_experience_lineage.py
index f569cf3eb..8ecae41c4 100644
--- a/tests/unit/session/memory/test_experience_lineage.py
+++ b/tests/unit/session/memory/test_experience_lineage.py
@@ -1,6 +1,8 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import pytest
+
from openviking.message import Message, ToolPart
from openviking.server.identity import RequestContext, Role
from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOperations
@@ -20,8 +22,9 @@ def _ctx() -> RequestContext:
return RequestContext(user=UserIdentifier("account", "alice"), role=Role.USER)
-def test_collect_read_experience_uris_only_keeps_completed_current_user_reads():
+def test_collect_read_experience_uris_supports_generic_openviking_reads():
uri = "viking://user/alice/memories/experiences/order-exchange.md"
+ opencode_uri = "viking://user/alice/memories/experiences/opencode.md"
messages = [
Message(
id="call",
@@ -29,13 +32,13 @@ def test_collect_read_experience_uris_only_keeps_completed_current_user_reads():
parts=[
ToolPart(
tool_id="read-1",
- tool_name="read_experience",
+ tool_name="mcp__openviking__read",
tool_input={"uri": uri},
tool_status="pending",
),
ToolPart(
tool_id="search-1",
- tool_name="search_experience",
+ tool_name="mcp__openviking__find",
tool_input={"query": "exchange"},
tool_status="completed",
tool_output='{"results":[{"uri":"%s"}]}' % uri,
@@ -48,19 +51,25 @@ def test_collect_read_experience_uris_only_keeps_completed_current_user_reads():
parts=[
ToolPart(
tool_id="read-1",
- tool_name="read_experience",
+ tool_name="mcp__openviking__read",
tool_status="completed",
tool_output='{"uri":"%s"}' % uri,
),
ToolPart(
tool_id="read-2",
- tool_name="read_experience",
+ tool_name="openviking_read",
tool_input={"uri": "viking://user/bob/memories/experiences/other.md"},
tool_status="completed",
),
+ ToolPart(
+ tool_id="read-2-current-user",
+ tool_name="openviking_read",
+ tool_input={"uri": opencode_uri},
+ tool_status="completed",
+ ),
ToolPart(
tool_id="read-3",
- tool_name="read_experience",
+ tool_name="read",
tool_input={"uri": uri},
tool_status="error",
),
@@ -68,7 +77,53 @@ def test_collect_read_experience_uris_only_keeps_completed_current_user_reads():
),
]
- assert collect_read_experience_uris(messages, ctx=_ctx()) == [uri]
+ assert collect_read_experience_uris(messages, ctx=_ctx()) == [uri, opencode_uri]
+
+
[email protected]("tool_name", ["multi_read", "openviking_multi_read"])
+def test_collect_read_experience_uris_filters_failed_multi_read_results(tool_name):
+ first_uri = "viking://user/alice/memories/experiences/first.md"
+ failed_uri = "viking://user/alice/memories/experiences/failed.md"
+ messages = [
+ Message(
+ id="multi-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="multi-read-1",
+ tool_name=tool_name,
+ tool_input={"uris": [first_uri, failed_uri]},
+ tool_status="completed",
+ tool_output=(
+ '{"results":['
+ f'{{"uri":"{first_uri}","success":true}},'
+ f'{{"uri":"{failed_uri}","success":false}}]}}'
+ ),
+ )
+ ],
+ )
+ ]
+
+ assert collect_read_experience_uris(messages, ctx=_ctx()) == [first_uri]
+
+
+def test_collect_read_experience_uris_ignores_removed_dedicated_tool():
+ messages = [
+ Message(
+ id="legacy-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="legacy-read-1",
+ tool_name="read_experience",
+ tool_input={"uri": "viking://user/alice/memories/experiences/legacy.md"},
+ tool_status="completed",
+ )
+ ],
+ )
+ ]
+
+ assert collect_read_experience_uris(messages, ctx=_ctx()) == []
def test_experience_source_tag_uses_experience_uri_as_key():
diff --git a/tests/unit/usage_reporter/test_file_log_sink.py b/tests/unit/usage_reporter/test_file_log_sink.py
index 8faaf4e21..2b9accaf4 100644
--- a/tests/unit/usage_reporter/test_file_log_sink.py
+++ b/tests/unit/usage_reporter/test_file_log_sink.py
@@ -18,24 +18,24 @@ class FakeUsageEvent:
event_id: str = "ue_recall",
event_type: str = "memory.recalled",
session_id: str = "session-1",
- resource_uri: str = "viking://user/user-1/memories/experiences/exchange.md",
+ resource_uri: str = ("viking://user/default/memories/experiences/生成请假邮件通用模版.md"),
) -> None:
self._record = {
"schema_version": "v1",
"event_id": event_id,
"event_type": event_type,
- "account_id": "2101858484",
- "user_id": "user-1",
+ "account_id": "default",
+ "user_id": "default",
"session_id": session_id,
"task_id": "task-1",
- "occurred_at": "2026-07-27T04:00:00Z",
+ "occurred_at": "2026-08-05T19:30:00+08:00",
"resource_uri": resource_uri,
"resource_type": "experience",
"evidence": {
"archive_uri": ("viking://user/user-1/sessions/session-1/history/archive_001"),
"message_id": "msg-1",
"tool_call_id": "call-1",
- "tool_name": "search_experience",
+ "tool_name": "find",
},
"attributes": {"note": "contains spaces\tand tabs"},
}
@@ -44,14 +44,17 @@ class FakeUsageEvent:
return dict(self._record)
-def _parse_line(line: str) -> tuple[str, dict[str, object]]:
- record = json.loads(line)
- return record["key"], record["value"]
+def _parse_line(line: str) -> dict[str, object]:
+ return json.loads(line)
-async def test_file_log_sink_writes_original_kafka_key_and_value(tmp_path, monkeypatch):
[email protected](autouse=True)
+def _resource_id(monkeypatch):
monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+
+
+async def test_file_log_sink_writes_usage_event_record(tmp_path):
log_path = tmp_path / "dedicated" / "usage.log"
sink = FileLogUsageSink(path=log_path)
@@ -62,51 +65,35 @@ async def test_file_log_sink_writes_original_kafka_key_and_value(tmp_path, monke
lines = log_path.read_text(encoding="utf-8").splitlines()
assert len(lines) == 1
- key, value = _parse_line(lines[0])
- assert key == "ov-test|2101858484|user-1|viking://user/user-1/memories/experiences/exchange.md"
- assert value == {
- "count_name": "experience.recall.count",
- "op_type": "add",
- "amount": 1.0,
- "timestamp": 1785124800000,
- "unique_id": "ue_recall",
- "tags": {
- "account_id": "2101858484",
- "user_id": "user-1",
- "resource_uri": "viking://user/user-1/memories/experiences/exchange.md",
- "resource_type": "experience",
- },
- "extra": {
- "archive_uri": "viking://user/user-1/sessions/session-1/history/archive_001",
- "message_id": "msg-1",
- "tool_call_id": "call-1",
- "tool_name": "search_experience",
- "session_id": "session-1",
- "task_id": "task-1",
- "attributes": {"note": "contains spaces\tand tabs"},
- },
- "prefix": "ov-test",
+ assert _parse_line(lines[0]) == {
+ "event_time": "2026-08-05 11:30:00",
+ "tenant_id": (
+ "resource_id:ov-test;account_id:default;user_id:default;resource_uri:"
+ "viking://user/default/memories/experiences/生成请假邮件通用模版.md"
+ ),
+ "event_name": "experience.recall.count",
+ "object_id": "ue_recall",
+ "count": 1,
+ "tags": {"resource_type": "experience"},
}
@pytest.mark.asyncio
-async def test_file_log_sink_message_key_falls_back_to_session_id(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+async def test_file_log_sink_maps_injection_event_name(tmp_path):
log_path = tmp_path / "usage.log"
sink = FileLogUsageSink(path=log_path)
try:
- await sink.write(events=[FakeUsageEvent(resource_uri="", session_id="session-fallback")])
+ await sink.write(events=[FakeUsageEvent(event_type="memory.injected")])
finally:
sink.close()
- key, _value = _parse_line(log_path.read_text(encoding="utf-8").strip())
- assert key == "ov-test|2101858484|user-1|session-fallback"
+ record = _parse_line(log_path.read_text(encoding="utf-8").strip())
+ assert record["event_name"] == "experience.inject.count"
@pytest.mark.asyncio
-async def test_file_log_sink_preserves_equals_signs_in_key(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov=test")
+async def test_file_log_sink_preserves_tenant_id_values(tmp_path):
log_path = tmp_path / "usage.log"
sink = FileLogUsageSink(path=log_path)
@@ -121,20 +108,41 @@ async def test_file_log_sink_preserves_equals_signs_in_key(tmp_path, monkeypatch
finally:
sink.close()
- key, value = _parse_line(log_path.read_text(encoding="utf-8").strip())
- assert key == (
- "ov=test|2101858484|user-1|viking://user/user-1/memories/experiences/exchange=delivered.md"
+ record = _parse_line(log_path.read_text(encoding="utf-8").strip())
+ assert record["tenant_id"] == (
+ "resource_id:ov-test;account_id:default;user_id:default;resource_uri:"
+ "viking://user/user-1/memories/experiences/exchange=delivered.md"
)
- assert value["prefix"] == "ov=test"
- assert (
- value["tags"]["resource_uri"]
- == "viking://user/user-1/memories/experiences/exchange=delivered.md"
+
+
+async def test_file_log_sink_uses_tenant_and_object_as_deduplication_key(tmp_path, monkeypatch):
+ event = FakeUsageEvent(event_id="ue_same_event")
+
+ monkeypatch.setenv("OV_RESOURCE_ID", "ov-first")
+ first = FileLogUsageSink(path=tmp_path / "first.log")
+ monkeypatch.setenv("OV_RESOURCE_ID", "ov-second")
+ second = FileLogUsageSink(path=tmp_path / "second.log")
+ try:
+ await first.write(events=[event])
+ await second.write(events=[event])
+ finally:
+ first.close()
+ second.close()
+
+ first_record = _parse_line((tmp_path / "first.log").read_text(encoding="utf-8").strip())
+ second_record = _parse_line((tmp_path / "second.log").read_text(encoding="utf-8").strip())
+
+ assert first_record["object_id"] == second_record["object_id"] == "ue_same_event"
+ assert first_record["tenant_id"] != second_record["tenant_id"]
+ assert (first_record["tenant_id"], first_record["object_id"]) != (
+ second_record["tenant_id"],
+ second_record["object_id"],
)
@pytest.mark.asyncio
-async def test_file_log_sink_preserves_records_when_workers_roll_over(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+async def test_file_log_sink_preserves_records_when_workers_roll_over(tmp_path):
log_path = tmp_path / "usage.log"
first = FileLogUsageSink(path=log_path)
second = FileLogUsageSink(path=log_path)
@@ -151,12 +159,11 @@ async def test_file_log_sink_preserves_records_when_workers_roll_over(tmp_path,
first.close()
second.close()
- unique_ids = []
+ object_ids = []
for path in tmp_path.glob("usage.log*"):
for line in path.read_text(encoding="utf-8").splitlines():
- _key, value = _parse_line(line)
- unique_ids.append(value["unique_id"])
- assert sorted(unique_ids) == [
+ object_ids.append(_parse_line(line)["object_id"])
+ assert sorted(object_ids) == [
"ue_first_after",
"ue_first_before",
"ue_second_after",
@@ -165,8 +172,7 @@ async def test_file_log_sink_preserves_records_when_workers_roll_over(tmp_path,
@pytest.mark.asyncio
-async def test_closed_handle_preserves_overdue_rollover_deadline(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+async def test_closed_handle_preserves_overdue_rollover_deadline(tmp_path):
log_path = tmp_path / "usage.log"
sink = FileLogUsageSink(path=log_path)
@@ -182,16 +188,14 @@ async def test_closed_handle_preserves_overdue_rollover_deadline(tmp_path, monke
log_files = list(tmp_path.glob("usage.log*"))
assert len(log_files) == 2
- unique_ids = []
+ object_ids = []
for path in log_files:
for line in path.read_text(encoding="utf-8").splitlines():
- _key, value = _parse_line(line)
- unique_ids.append(value["unique_id"])
- assert sorted(unique_ids) == ["ue_after", "ue_before"]
+ object_ids.append(_parse_line(line)["object_id"])
+ assert sorted(object_ids) == ["ue_after", "ue_before"]
-def test_file_log_sink_uses_hourly_utc_rotation(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+def test_file_log_sink_uses_hourly_utc_rotation(tmp_path):
sink = FileLogUsageSink(
path=tmp_path / "usage.log",
rotation_interval_hours=1,
@@ -209,39 +213,45 @@ def test_file_log_sink_uses_hourly_utc_rotation(tmp_path, monkeypatch):
@pytest.mark.parametrize(
- ("environment", "kwargs", "message"),
+ ("kwargs", "message"),
[
- ({}, {"path": "usage.log"}, "OV_RESOURCE_ID is required"),
- ({"OV_RESOURCE_ID": "ov-test"}, {"path": ""}, "path is required"),
+ ({"path": ""}, "path is required"),
(
- {"OV_RESOURCE_ID": "ov-test"},
{"path": "usage.log", "rotation_interval_hours": 0},
"rotation_interval_hours must be positive",
),
(
- {"OV_RESOURCE_ID": "ov-test"},
{"path": "usage.log", "backup_count": -1},
"backup_count must be non-negative",
),
],
)
-def test_file_log_sink_validates_config(
- monkeypatch,
- environment,
- kwargs,
- message,
-):
- monkeypatch.delenv("OV_RESOURCE_ID", raising=False)
- for key, value in environment.items():
- monkeypatch.setenv(key, value)
-
+def test_file_log_sink_validates_config(kwargs, message):
with pytest.raises(ValueError, match=message):
FileLogUsageSink(**kwargs)
+def test_file_log_sink_requires_resource_id(tmp_path, monkeypatch):
+ monkeypatch.delenv("OV_RESOURCE_ID")
+
+ with pytest.raises(ValueError, match="OV_RESOURCE_ID is required"):
+ FileLogUsageSink(path=tmp_path / "usage.log")
+
+
+def test_file_log_sink_reads_configured_resource_id_env(tmp_path, monkeypatch):
+ monkeypatch.setenv("CUSTOM_RESOURCE_ID", "ov-custom")
+ sink = FileLogUsageSink(
+ path=tmp_path / "usage.log",
+ resource_id_env="CUSTOM_RESOURCE_ID",
+ )
+ try:
+ assert sink._resource_id == "ov-custom"
+ finally:
+ sink.close()
+
+
@pytest.mark.asyncio
-async def test_file_log_sink_rejects_unsupported_event(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+async def test_file_log_sink_rejects_unsupported_event(tmp_path):
sink = FileLogUsageSink(path=tmp_path / "usage.log")
try:
@@ -252,8 +262,7 @@ async def test_file_log_sink_rejects_unsupported_event(tmp_path, monkeypatch):
@pytest.mark.asyncio
-async def test_file_log_sink_requires_event_id(tmp_path, monkeypatch):
- monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+async def test_file_log_sink_requires_event_id(tmp_path):
sink = FileLogUsageSink(path=tmp_path / "usage.log")
try:
diff --git a/tests/unit/usage_reporter/test_memory_usage_extractor.py b/tests/unit/usage_reporter/test_memory_usage_extractor.py
index 8f46a49f3..f54559b18 100644
--- a/tests/unit/usage_reporter/test_memory_usage_extractor.py
+++ b/tests/unit/usage_reporter/test_memory_usage_extractor.py
@@ -31,7 +31,7 @@ async def test_memory_usage_extractor_emits_recall_and_injection_events():
TextPart("我要处理无订单号换货"),
ToolPart(
tool_id="call-search",
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_input={"query": "无订单号换货"},
tool_output={"results": [{"uri": experience_uri}, {"uri": "viking://other"}]},
@@ -44,7 +44,7 @@ async def test_memory_usage_extractor_emits_recall_and_injection_events():
parts=[
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": experience_uri},
tool_output="## Situation\n用户未提供订单号但要求换货。",
@@ -57,7 +57,7 @@ async def test_memory_usage_extractor_emits_recall_and_injection_events():
parts=[
ToolPart(
tool_id="call-pending",
- tool_name="read_experience",
+ tool_name="read",
tool_status="running",
tool_input={"uri": experience_uri},
)
@@ -74,9 +74,405 @@ async def test_memory_usage_extractor_emits_recall_and_injection_events():
"archive_uri": _context().archive_uri,
"message_id": "msg-1",
"tool_call_id": "call-search",
- "tool_name": "search_experience",
+ "tool_name": "find",
}
- assert events[1].evidence["tool_name"] == "read_experience"
+ assert events[1].evidence["tool_name"] == "read"
+
+
+async def test_memory_usage_extractor_ignores_removed_dedicated_experience_tools():
+ experience_uri = "viking://user/test/memories/experiences/legacy.md"
+ messages = [
+ Message(
+ id="msg-legacy",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-search",
+ tool_name="search_experience",
+ tool_status="completed",
+ tool_output={"results": [{"uri": experience_uri}]},
+ ),
+ ToolPart(
+ tool_id="call-read",
+ tool_name="read_experience",
+ tool_status="completed",
+ tool_input={"uri": experience_uri},
+ ),
+ ],
+ )
+ ]
+
+ assert await MemoryUsageExtractor().extract(messages=messages, context=_context()) == []
+
+
+ "tool_name",
+ [
+ "find",
+ "search",
+ "openviking_find",
+ "openviking_search",
+ "ov_search",
+ "mcp__openviking__find",
+ "mcp__openviking__search",
+ ],
+)
+async def test_memory_usage_extractor_recognizes_generic_search_tools(tool_name):
+ experience_uris = [
+ f"viking://user/test/memories/experiences/experience-{index}.md" for index in range(10)
+ ]
+ messages = [
+ Message(
+ id="msg-search",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-search",
+ tool_name=tool_name,
+ tool_status="completed",
+ tool_output={
+ "details": {
+ "memories": [
+ *[{"uri": uri} for uri in experience_uris],
+ {"uri": "viking://user/test/memories/preferences/preference.md"},
+ {"uri": "viking://user/test/memories/cases/case.md"},
+ ],
+ "resources": [{"uri": "viking://resources/guide.md"}],
+ }
+ },
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert len(events) == 10
+ assert [event.event_type for event in events] == ["memory.recalled"] * 10
+ assert [event.resource_uri for event in events] == experience_uris
+
+
+async def test_memory_usage_extractor_does_not_count_search_scope_as_result():
+ experience_uri = "viking://user/test/memories/experiences/search-scope.md"
+ messages = [
+ Message(
+ id="msg-empty-search",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-empty-search",
+ tool_name="ov_search",
+ tool_status="completed",
+ tool_input={"query": "missing", "uri": experience_uri},
+ tool_output={
+ "details": {
+ "action": "searched",
+ "uri": experience_uri,
+ "memories": [],
+ "resources": [],
+ "skills": [],
+ "total": 0,
+ }
+ },
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert events == []
+
+
+ "tool_name", ["list", "openviking_list", "ov_list", "mcp__openviking__list"]
+)
+async def test_memory_usage_extractor_list_counts_only_experience_files(tool_name):
+ experience_uri = "viking://user/test/memories/experiences/listed.md"
+ messages = [
+ Message(
+ id="msg-list",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-list",
+ tool_name=tool_name,
+ tool_status="completed",
+ tool_input={"uri": "viking://user/test/memories/experiences/"},
+ tool_output={
+ "details": {
+ "entries": [
+ {"uri": experience_uri, "isDir": False},
+ {
+ "uri": "viking://user/test/memories/experiences/nested",
+ "isDir": True,
+ },
+ {
+ "uri": "viking://user/test/memories/preferences/preference.md",
+ "isDir": False,
+ },
+ ]
+ }
+ },
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.event_type for event in events] == ["memory.recalled"]
+ assert [event.resource_uri for event in events] == [experience_uri]
+
+
+async def test_memory_usage_extractor_parses_mcp_text_search_and_list_results():
+ searched_uri = "viking://user/test/memories/experiences/searched.md"
+ listed_uri = "viking://user/test/memories/experiences/listed.md"
+ messages = [
+ Message(
+ id="msg-mcp-text",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-find",
+ tool_name="mcp__openviking__find",
+ tool_status="completed",
+ tool_output=(
+ "Found 2 item(s):\n\n"
+ f"- [memory 90%] {searched_uri}\n matching experience\n"
+ "- [memory 80%] viking://user/test/memories/preferences/a.md\n"
+ ),
+ ),
+ ToolPart(
+ tool_id="call-list",
+ tool_name="mcp__openviking__list",
+ tool_status="completed",
+ tool_input={"uri": "viking://user/test/memories/experiences/"},
+ tool_output="[file] listed.md\n[dir] nested\n[file] .overview.md",
+ ),
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.resource_uri for event in events] == [searched_uri, listed_uri]
+
+
+async def test_memory_usage_extractor_preserves_spaces_in_openclaw_table_uri():
+ experience_uri = "viking://user/test/memories/experiences/order exchange.md"
+ messages = [
+ Message(
+ id="msg-openclaw-table",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-search",
+ tool_name="ov_search",
+ tool_status="completed",
+ tool_output=(
+ "no type uri "
+ "level score abstract\n"
+ f"1 memory {experience_uri} 2 0.91 exchange procedure"
+ ),
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.resource_uri for event in events] == [experience_uri]
+
+
+async def test_memory_usage_extractor_canonicalizes_short_user_list_uri():
+ messages = [
+ Message(
+ id="msg-short-list",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-list",
+ tool_name="mcp__openviking__list",
+ tool_status="completed",
+ tool_input={"uri": "viking://user/memories/experiences"},
+ tool_output="[file] listed experience.md",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.resource_uri for event in events] == [
+ "viking://user/test/memories/experiences/listed experience.md"
+ ]
+
+
+ ("tool_name", "tool_input"),
+ [
+ ("read", {"uris": "viking://user/test/memories/experiences/read.md"}),
+ ("openviking_read", {"uris": "viking://user/test/memories/experiences/read.md"}),
+ ("ov_read", {"uri": "viking://user/test/memories/experiences/read.md"}),
+ (
+ "mcp__openviking__read",
+ {"uris": "viking://user/test/memories/experiences/read.md"},
+ ),
+ ],
+)
+async def test_memory_usage_extractor_recognizes_generic_read_tools(tool_name, tool_input):
+ messages = [
+ Message(
+ id="msg-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-read",
+ tool_name=tool_name,
+ tool_status="completed",
+ tool_input=tool_input,
+ tool_output="experience content",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.event_type for event in events] == ["memory.injected"]
+ assert [event.resource_uri for event in events] == [
+ "viking://user/test/memories/experiences/read.md"
+ ]
+
+
+ "tool_name",
+ [
+ "multi_read",
+ "openviking_multi_read",
+ "ov_multi_read",
+ "mcp__openviking__multi_read",
+ ],
+)
+async def test_memory_usage_extractor_multi_read_counts_only_successful_experiences(tool_name):
+ success_uri = "viking://user/test/memories/experiences/success.md"
+ failed_uri = "viking://user/test/memories/experiences/failed.md"
+ preference_uri = "viking://user/test/memories/preferences/preference.md"
+ messages = [
+ Message(
+ id="msg-multi-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-multi-read",
+ tool_name=tool_name,
+ tool_status="completed",
+ tool_input={"uris": [success_uri, failed_uri, preference_uri]},
+ tool_output={
+ "details": {
+ "results": [
+ {"uri": success_uri, "success": True},
+ {"uri": failed_uri, "success": False},
+ {"uri": preference_uri, "success": True},
+ ]
+ }
+ },
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert [event.event_type for event in events] == ["memory.injected"]
+ assert [event.resource_uri for event in events] == [success_uri]
+
+
+async def test_memory_usage_extractor_does_not_fuzzy_match_other_mcp_tools():
+ experience_uri = "viking://user/test/memories/experiences/not-openviking.md"
+ messages = [
+ Message(
+ id="msg-other-mcp",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-search",
+ tool_name="mcp__other__search",
+ tool_status="completed",
+ tool_output={"results": [{"uri": experience_uri}]},
+ ),
+ ToolPart(
+ tool_id="call-read",
+ tool_name="mcp__other__read",
+ tool_status="completed",
+ tool_input={"uri": experience_uri},
+ ),
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert events == []
+
+
+async def test_memory_usage_extractor_ignores_generic_read_not_found_result():
+ experience_uri = "viking://user/test/memories/experiences/missing.md"
+ messages = [
+ Message(
+ id="msg-missing-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-read",
+ tool_name="mcp__openviking__read",
+ tool_status="completed",
+ tool_input={"uris": experience_uri},
+ tool_output=f"(nothing found at {experience_uri})",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert events == []
+
+
+async def test_memory_usage_extractor_ignores_short_user_read_not_found_result():
+ short_uri = "viking://user/memories/experiences/missing.md"
+ messages = [
+ Message(
+ id="msg-missing-short-read",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="call-read",
+ tool_name="mcp__openviking__read",
+ tool_status="completed",
+ tool_input={"uris": short_uri},
+ tool_output=f"(nothing found at {short_uri})",
+ )
+ ],
+ )
+ ]
+
+ events = await MemoryUsageExtractor().extract(messages=messages, context=_context())
+
+ assert events == []
@pytest.mark.asyncio
@@ -90,7 +486,7 @@ async def test_memory_usage_extractor_uses_message_time_for_event_time():
parts=[
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": experience_uri},
)
@@ -112,7 +508,7 @@ async def test_memory_usage_extractor_ignores_non_experience_memory_uris():
parts=[
ToolPart(
tool_id="call-search",
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_output={
"results": [
@@ -123,7 +519,7 @@ async def test_memory_usage_extractor_ignores_non_experience_memory_uris():
),
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": "viking://user/default/memories/trajectories/a.md"},
),
@@ -147,13 +543,13 @@ async def test_memory_usage_extractor_ignores_other_users_experience_uris():
parts=[
ToolPart(
tool_id="call-search",
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_output={"results": [{"uri": own_uri}, {"uri": other_uri}]},
),
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": other_uri},
),
@@ -178,7 +574,7 @@ async def test_memory_usage_extractor_ignores_noncanonical_experience_uris():
parts=[
ToolPart(
tool_id="call-search",
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_output={
"results": [
@@ -190,13 +586,13 @@ async def test_memory_usage_extractor_ignores_noncanonical_experience_uris():
),
ToolPart(
tool_id="call-read-query",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": query_alias},
),
ToolPart(
tool_id="call-read-fragment",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": fragment_alias},
),
@@ -219,7 +615,7 @@ async def test_memory_usage_extractor_ignores_internal_experience_sidecars():
parts=[
ToolPart(
tool_id="call-search",
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_output={
"results": [
@@ -231,7 +627,7 @@ async def test_memory_usage_extractor_ignores_internal_experience_sidecars():
),
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": "viking://user/test/memories/experiences/.abstract.md"},
),
@@ -254,7 +650,7 @@ async def test_memory_usage_extractor_correlates_read_input_by_tool_id():
parts=[
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="running",
tool_input={"uri": experience_uri},
)
@@ -266,7 +662,7 @@ async def test_memory_usage_extractor_correlates_read_input_by_tool_id():
parts=[
ToolPart(
tool_id="call-read",
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_output='{"uri":"truncated',
)
@@ -291,9 +687,9 @@ async def test_memory_usage_extractor_replay_uses_stable_event_id():
parts=[
ToolPart(
tool_id="call-replay",
- tool_name="read_experience",
+ tool_name="mcp__openviking__read",
tool_status="completed",
- tool_input={"uri": experience_uri},
+ tool_input={"uris": experience_uri},
)
],
)
@@ -327,12 +723,12 @@ async def test_memory_usage_extractor_ignores_completed_tools_without_tool_id():
role="user",
parts=[
ToolPart(
- tool_name="search_experience",
+ tool_name="find",
tool_status="completed",
tool_output={"results": [{"uri": experience_uri}]},
),
ToolPart(
- tool_name="read_experience",
+ tool_name="read",
tool_status="completed",
tool_input={"uri": experience_uri},
),