Skip to content

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

fix(agent-evolution): preserve explicit Experience read attribution (#6365)

bot-of-qin-ctxa07c02cd25f5
diff --git a/docs/en/agent-integrations/12-cursor.md b/docs/en/agent-integrations/12-cursor.md
index 574975bc5..98384aca3 100644
--- a/docs/en/agent-integrations/12-cursor.md
+++ b/docs/en/agent-integrations/12-cursor.md
@@ -20,7 +20,7 @@ Quit Cursor completely and restart it after installation.
- Lifecycle Hooks for profile loading, prompt recall, conversation capture, session commit, and `viking://` URI protection.
- The OpenViking MCP server with tools such as `search`, `read`, `remember`, and `add_skill`; `search` with `mode="context"` returns assembled context.
- An always-on Rule and the `openviking-memory` Skill, which tell the Agent how to use injected context and memory tools, plus the `openviking-skills` Skill for finding, using, creating (`add_skill`), sharing, and migrating skills stored in OpenViking.
-- The `ov-experience-memory` Skill, which has the Agent search and apply prior task Experience before executable work. Cursor captures text only, so here the Skill only retrieves and applies Experience; its reads are not linked back to the Experience they used.
+- The `ov-experience-memory` Skill, which has the Agent search and apply prior task Experience before executable work. Successful OpenViking MCP `read` calls are captured with the conversation. When the `session commit` containing the read produces trajectories, those trajectories can be queried for the Experience.
## Verify
@@ -35,9 +35,14 @@ Quit Cursor completely and restart it after installation.
- `sessionStart` loads your profile, the current project's memory index, and an `<available-skills>` catalog of your OpenViking skills.
- `beforeSubmitPrompt` recalls context for the current request, including your own skills and those shared with your account under `viking://agent/skills`, and injects it through `additional_context`.
- `beforeReadFile` denies reading a `viking://` path as a local file and points the Agent to OpenViking MCP tools. Shell commands are not checked.
-- `stop` incrementally captures new user and assistant messages.
+- `afterMCPExecution` appends completed calls to the `openviking` MCP server to a local tool log, preserving the native call ID, input, output, and success or failure status. It does not upload messages or rewrite earlier results.
+- `stop` uploads new conversation turns and locally recorded tool results through `add message`. Capture progress advances only after upload succeeds, and `session commit` follows the existing message threshold. Tool records do not add to that threshold's message count.
- `preCompact` and `sessionEnd` commit pending messages for memory extraction.
+Tool capture requires `afterMCPExecution` to provide `tool_use_id`, `mcp_server_name`, `tool_name`, `tool_input`, and `result_json`. Events without an identity or result are skipped, never inferred to be successful. Failed uploads remain local for the same conversation's next capture attempt; incomplete capture prevents a commit.
+
+The tool log stays beside the session checkpoint. Stop reads only the unacknowledged tail; the checkpoint keeps the byte position and accepted call IDs so repeated events do not require rereading old result bodies. Progress advances only after acknowledgement, and tool calls do not consume the text deduplication window.
+
The skill catalog lists your own skills first, then those shared with your account, leaving out a shared skill whose name you also own; each description is cut to about 40 tokens. It has its own token budget, `skillCatalogTokenBudget` (default `1200`), separate from the profile budget. When not every description fits, the catalog lists names only (with a `... +N more` tail if even the names do not all fit), and when not even one name fits, it shrinks to a one-line skill count. Set `skillCatalog` to `false` or the budget to `0` to turn it off, either in the `plugin` or `plugin.cursor` section of `~/.openviking/ovcli.conf` ([Plugin Settings](../configuration/02-client.md#plugin-settings)) or through `OPENVIKING_SKILL_CATALOG` and `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`. Without any skills, or on a server without `GET /api/v1/skills`, the catalog is left out.
Project identity uses Cursor's `workspace_roots`, keeping workspace peers separate. Hooks and MCP share credentials from `~/.openviking/ovcli.conf`.
@@ -60,6 +65,7 @@ Uninstall removes only OpenViking-managed Cursor Hooks, MCP, Rule, Skills, and r
| Recall appears in Hook output but not in the answer | Upgrade to the latest stable Cursor; older releases may not support `beforeSubmitPrompt.additional_context`. |
| The same event runs multiple OpenViking Hooks | Cursor may be importing an older Claude Code plugin. Upgrade or remove the legacy OpenViking plugin ids reported by the installer, then restart Cursor. |
| MCP does not connect | Check the URL/API key in `~/.openviking/ovcli.conf`, then restart Cursor. |
+| An Experience was read but has no application trajectories | Check that `afterMCPExecution` is installed and provides the fields above, and that `session commit` finished extracting trajectories. Upgrade older Cursor builds that omit the call ID. Automatic injection alone does not count as a read. |
| Detailed diagnostics are needed | Start Cursor with `OPENVIKING_DEBUG=1` and inspect `~/.openviking/logs/cursor-hooks.log`. |
## See also
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index ab03fe6a8..c63553d98 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -361,7 +361,8 @@ What this means in practice:
| Integration | What happens when a write fails |
|---|---|
-| Claude Code, Cursor, TRAE, TRAE CN, ZCode, Kimi Code, OpenCode, DSH, pi | Retryable failures go to an on-disk queue under `~/.openviking/pending`. It is replayed at session start: up to 50 entries per run and 3 attempts per entry, kept for 7 days. Network errors, 408, 429, and 5xx are retryable; other 4xx responses, including 401 and 403, are not queued. A failed message stops the replay so order is kept |
+| Claude Code, TRAE, TRAE CN, ZCode, Kimi Code, OpenCode, DSH, pi | Retryable failures go to an on-disk queue under `~/.openviking/pending`. It is replayed at session start: up to 50 entries per run and 3 attempts per entry, kept for 7 days. Network errors, 408, 429, and 5xx are retryable; other 4xx responses, including 401 and 403, are not queued. A failed message stops the replay so order is kept |
+| Cursor | New captures are not queued. The text transcript and local tool records retain unsent content; progress advances only after server acknowledgement. Later capture in the same conversation retries it, and incomplete capture prevents a commit. `SessionStart` still replays legacy queued writes |
| Codex, TraeCode CLI 2.0 | New captures are not queued. The transcript cursor moves only past messages the server accepted, so the next capture or start-up sweep resends the rest. `SessionStart` still replays queued entries |
| OpenClaw | No queue. A failed turn is not sent again |
| Hermes (bundled) | Uploads run in in-process threads and are not replayed from disk. Pending-commit markers under `$HERMES_HOME/openviking/pending_sessions/` let a later start commit sessions left by a dead run (POSIX only) |
@@ -580,10 +581,10 @@ Each note covers what is specific to one integration. Shared behavior is in the
### Cursor
-[Cursor Memory Integration](./12-cursor.md). Hook and MCP configuration with 6 hooks (`sessionStart`, `beforeSubmitPrompt`, `beforeReadFile`, `stop`, `preCompact`, `sessionEnd`), an always-on rule, and 3 skills.
+[Cursor Memory Integration](./12-cursor.md). Hook and MCP configuration with 7 hooks (`sessionStart`, `beforeSubmitPrompt`, `beforeReadFile`, `afterMCPExecution`, `stop`, `preCompact`, `sessionEnd`), an always-on rule, and 3 skills.
- The URI guard runs on `beforeReadFile` only, independent of the plugin switch. Shell commands are not checked, and an upgrade removes the `beforeShellExecution` entry older installs registered.
-- Capture is text-only, so `ov-experience-memory` can find and apply Experience but cannot link its reads back to the Experience used.
+- `afterMCPExecution` retains completed OpenViking tool calls, uploaded with the conversation at Stop. Successful Experience reads can link to trajectories produced by that commit; failed or unfinished calls and automatic injection do not count as successful reads.
- `sessionEnd` fires only on window close, after Cursor has stopped running hook commands, so it does not commit in practice.
- With the server unreachable, every turn waits out the 15-second recall timeout.
diff --git a/docs/en/api/19-agent-evolution.md b/docs/en/api/19-agent-evolution.md
index af6950f66..dd4947c15 100644
--- a/docs/en/api/19-agent-evolution.md
+++ b/docs/en/api/19-agent-evolution.md
@@ -2,6 +2,8 @@
The Agent Evolution API reports trajectories linked to a successful read of a specific Experience and their outcome distribution. These operations are currently available through HTTP only. A read establishes the link; it does not prove that the Agent followed the Experience or that the Experience caused an outcome.
+The plugin must use `add message` to record a successful OpenViking `read` in the Session, and the `session commit` containing that record must produce a trajectory. `viking://~/memories/experiences/...` resolves to the Session owner's space. Automatic recall and hook injection do not count as explicit reads. A commit that produces no trajectories does not increase the application trajectory count. Accordingly, `total` counts linked trajectories, not `read` calls.
+
## API Reference
### List Experience application trajectories
diff --git a/docs/zh/agent-integrations/12-cursor.md b/docs/zh/agent-integrations/12-cursor.md
index 90f1c0061..996fd7520 100644
--- a/docs/zh/agent-integrations/12-cursor.md
+++ b/docs/zh/agent-integrations/12-cursor.md
@@ -20,7 +20,7 @@ curl -fsSL https://openviking.ai/install | bash
- 生命周期 Hook:自动加载画像、按问题召回、捕获对话、提交会话并保护 `viking://` URI。
- OpenViking MCP Server:提供 `search`、`read`、`remember`、`add_skill` 等工具;`search` 的 `mode="context"` 可返回组装后的上下文。
- always-on Rule 和 `openviking-memory` Skill:告诉 Agent 如何使用已注入的上下文和记忆工具;另有 `openviking-skills` Skill,讲如何查找、使用、创建(`add_skill`)、共享和迁移存放在 OpenViking 里的 skill。
-- `ov-experience-memory` Skill:让 Agent 在执行类任务前检索并应用以往任务的 Experience。Cursor 只捕获文本,所以这里该 Skill 只负责检索和应用 Experience,它的读取不会关联回所用的 Experience。
+- `ov-experience-memory` Skill:让 Agent 在执行类任务前检索并应用以往任务的 Experience。成功的 OpenViking MCP `read` 会与对话一起上报;包含该读取记录的 `session commit` 生成轨迹后,可查询经验的应用轨迹。
## 验证
@@ -35,9 +35,14 @@ curl -fsSL https://openviking.ai/install | bash
- `sessionStart`:加载用户画像、当前项目的记忆索引,以及 OpenViking skill 清单 `<available-skills>`。
- `beforeSubmitPrompt`:根据当前问题召回上下文并通过 `additional_context` 注入,召回范围包括你自己的 skill 和账号内共享在 `viking://agent/skills` 下的 skill。
- `beforeReadFile`:阻止把 `viking://` 虚拟路径当作本地文件读取,并提示改用 OpenViking MCP 工具;shell 命令不做检查。
-- `stop`:增量捕获本轮新增的用户与助手消息。
+- `afterMCPExecution`:将 `openviking` MCP 服务的工具完成记录追加到本地工具日志,保留真实调用 ID、输入、输出和成功或失败状态;此时不向服务端写入消息,也不重写此前的结果。
+- `stop`:将新增对话与本地工具记录一起通过 `add message` 上报;成功后才推进捕获位置,达到原有消息阈值时执行 `session commit`。工具记录不额外增加该阈值的消息计数。
- `preCompact` / `sessionEnd`:提交尚未处理的消息,触发记忆抽取。
+工具采集要求 `afterMCPExecution` 提供 `tool_use_id`、`mcp_server_name`、`tool_name`、`tool_input` 和 `result_json`。缺少身份或结果的事件会跳过,不会推断为成功。上传失败时保留本地记录,等待同一会话的后续采集重试;消息未传完整时不提交。
+
+工具日志与会话状态文件放在同一目录。Stop 只读取尚未确认的日志尾部;状态文件保留字节位置和已确认的调用 ID,去重时不需要重读旧结果正文。收到确认后才推进上传位置,工具调用不占用文本的去重额度。
+
skill 清单先列你自己的 skill,再列账号内共享的 skill;共享 skill 与你自己的 skill 重名时不列出。每条描述截到约 40 token。清单有独立的 token 预算 `skillCatalogTokenBudget`(默认 `1200`),不占用画像预算。描述放不下时只列名称,名称也列不全时末尾附 `... +N more`;连一个名称都放不下时,只写一行 skill 数量。把 `skillCatalog` 设为 `false` 或把预算设为 `0` 即可关闭,既可以写在 `~/.openviking/ovcli.conf` 的 `plugin` 或 `plugin.cursor` 段(见[插件配置](../configuration/02-client.md#插件配置)),也可以用环境变量 `OPENVIKING_SKILL_CATALOG` 和 `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`。没有任何 skill,或服务端不提供 `GET /api/v1/skills` 时,不注入这份清单。
项目身份优先使用 Cursor 提供的 `workspace_roots`,因此不同项目会使用不同的 workspace peer。连接信息统一读取 `~/.openviking/ovcli.conf`。
@@ -60,6 +65,7 @@ curl -fsSL https://openviking.ai/install | bash -s -- --uninstall --yes --harnes
| Hook 返回召回内容,但回答未使用 | 更新到最新稳定版 Cursor;旧版本可能不支持 `beforeSubmitPrompt.additional_context`。 |
| 同一事件出现多个 OpenViking Hook | Cursor 可能导入了旧 Claude Code 插件。升级或移除安装器列出的旧 OpenViking plugin id,然后重启 Cursor。 |
| MCP 未连接 | 检查 `~/.openviking/ovcli.conf` 中的 URL/API Key,并重启 Cursor。 |
+| 经验已读取,但应用轨迹为空 | 检查 `afterMCPExecution` 是否已安装且提供上述字段,并确认 `session commit` 已完成轨迹提取。旧版 Cursor 缺少调用 ID 时需升级;自动注入本身不计为读取。 |
| 需要详细日志 | 设置 `OPENVIKING_DEBUG=1` 后启动 Cursor,查看 `~/.openviking/logs/cursor-hooks.log`。 |
## 参见
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 3550d4dba..0dfeb7d3a 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -360,7 +360,8 @@ Claude Code 和 Codex 默认 `auto`,其他集成默认 `off`。支持服务端
| 集成 | 写入失败时 |
|---|---|
-| Claude Code、Cursor、TRAE、TRAE CN、ZCode、Kimi Code、OpenCode、DSH、pi | 可重试的失败进入 `~/.openviking/pending` 下的磁盘队列,在会话开始时重放:每次最多 50 条,每条最多 3 次,保留 7 天。网络错误、408、429 和 5xx 可重试;其他 4xx(含 401 和 403)不入队。某条消息重放失败时停止,以保证顺序 |
+| Claude Code、TRAE、TRAE CN、ZCode、Kimi Code、OpenCode、DSH、pi | 可重试的失败进入 `~/.openviking/pending` 下的磁盘队列,在会话开始时重放:每次最多 50 条,每条最多 3 次,保留 7 天。网络错误、408、429 和 5xx 可重试;其他 4xx(含 401 和 403)不入队。某条消息重放失败时停止,以保证顺序 |
+| Cursor | 新捕获不入离线队列。文本 transcript 与本地工具记录保留未上报内容,服务端确认后才推进进度;同一会话后续采集重试。消息未传完整时不提交。`SessionStart` 仍重放旧队列中的写入 |
| Codex、TraeCode CLI 2.0 | 新捕获的内容不入队。transcript 游标只越过服务端已接受的消息,下次捕获或启动扫描会重发剩余部分。`SessionStart` 仍会重放已排队的条目 |
| OpenClaw | 没有队列,失败的轮次不会重发 |
| Hermes(内置) | 上传在进程内线程中运行,不从磁盘重放。`$HERMES_HOME/openviking/pending_sessions/` 下的待提交标记让之后的启动能提交已退出进程留下的会话(仅 POSIX) |
@@ -579,10 +580,10 @@ Claude Code、Codex、Cursor、TRAE、ZCode、Kimi Code、DSH 和 pi 还会安
### Cursor
-[Cursor](./12-cursor.md)。hook 与 MCP 配置,包含 6 个 hook(`sessionStart`、`beforeSubmitPrompt`、`beforeReadFile`、`stop`、`preCompact`、`sessionEnd`)、一条常驻 rule 和 3 个 skill。
+[Cursor](./12-cursor.md)。hook 与 MCP 配置,包含 7 个 hook(`sessionStart`、`beforeSubmitPrompt`、`beforeReadFile`、`afterMCPExecution`、`stop`、`preCompact`、`sessionEnd`)、一条常驻 rule 和 3 个 skill。
- URI guard 只在 `beforeReadFile` 运行,不受插件开关影响。shell 命令不检查,升级会移除旧版本注册的 `beforeShellExecution` 条目。
-- 只捕获文本,所以 `ov-experience-memory` 能检索和应用 Experience,但无法把读取关联回所用的 Experience。
+- `afterMCPExecution` 保留 OpenViking 工具完成记录,Stop 与对话一起上报。成功读取的 Experience 可关联到同次提交生成的轨迹;失败、未完成调用和自动注入不计为成功读取。
- `sessionEnd` 只在关闭窗口时触发,此时 Cursor 已停止执行 hook 命令,因此实际不会提交。
- 服务端不可达时,每轮都要等满 15 秒召回超时。
diff --git a/docs/zh/api/19-agent-evolution.md b/docs/zh/api/19-agent-evolution.md
index ccc0204dd..d74472bbd 100644
--- a/docs/zh/api/19-agent-evolution.md
+++ b/docs/zh/api/19-agent-evolution.md
@@ -2,6 +2,8 @@
Agent Evolution API 用于查询与某条 Experience 成功读取记录关联的 Trajectory 及结果分布。当前仅提供 HTTP API。读取记录用于建立关联,不能据此认定 Agent 遵循了这条经验,或结果由该经验造成。
+关联要求:插件通过 `add message` 将成功的 OpenViking `read` 工具记录写入 Session,再由包含该记录的 `session commit` 提取出 Trajectory。`viking://~/memories/experiences/...` 按 Session 所属用户解析。自动召回或 hook 注入不等于显式读取;没有生成 Trajectory 的提交也不会增加应用轨迹数量。因此 `total` 表示关联的轨迹数,而非 `read` 调用次数。
+
## API 参考
### 查询 Experience 应用轨迹
diff --git a/examples/agent-hook-plugin/README.md b/examples/agent-hook-plugin/README.md
index cd07b31e3..dd1291abc 100644
--- a/examples/agent-hook-plugin/README.md
+++ b/examples/agent-hook-plugin/README.md
@@ -29,11 +29,13 @@ The memory logic itself is not here: recall, batching, the pending queue, creden
## Host notes
-- **Cursor** — six events, including the `preCompact` and `sessionEnd` no other host in this plugin has. Commits on Stop once `capturedSinceCommit` reaches the threshold, and unconditionally before a compaction. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).
+- **Cursor** — seven events. `afterMCPExecution` appends OpenViking tool results to a local JSONL log; Stop uploads them with the text transcript. Text deduplication and the tool-upload position are separate. Only accepted messages advance capture progress, and the source records own retries. Commits when `capturedSinceCommit` reaches the threshold, or before compaction after capture completes. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).
- **TRAE / TRAE CN** — capture reads `prompt`, `text_content` and `last_assistant_message` off the Stop event rather than parsing a transcript. Every Stop that carries content commits. Sessions are `tr-` and `trcn-`. See the [TRAE guide](../../docs/en/agent-integrations/13-trae.md).
- **ZCode** — the rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and let a later Stop recover missed turns, and hook stdin is only the fallback. ZCode supports neither `PreCompact` nor `SessionEnd`, so committing on every Stop stands in for both. Its output schema is strict, so a pass-through writes nothing at all. Sessions are `zc-`. [DESIGN.md](./DESIGN.md) records the verified extension surface.
- **Kimi Code** — `wire.jsonl` is the authoritative transcript. UserPromptSubmit emits raw context text, while Stop, PreCompact and SessionEnd may detach; Interrupt remains synchronous under a two-second OpenViking request budget. The installer creates a self-contained native plugin without editing legacy `config.toml` or `mcp.json`. Sessions are `kc-`. [Host contract](./hosts/kimicode/DESIGN.md).
+Cursor tool capture follows the [Hooks contract](https://cursor.com/docs/hooks) and the MCP executor in [`@cursor/sdk` 1.0.38](https://registry.npmjs.org/@cursor/sdk/-/sdk-1.0.38.tgz), which supplies `tool_use_id` on `afterMCPExecution`. Older events without that native identity retain text capture only; the adapter does not invent call IDs or completion evidence.
+
## Diagnostics
```bash
diff --git a/examples/agent-hook-plugin/README_CN.md b/examples/agent-hook-plugin/README_CN.md
index c14be7f9d..16ca2ff5e 100644
--- a/examples/agent-hook-plugin/README_CN.md
+++ b/examples/agent-hook-plugin/README_CN.md
@@ -29,11 +29,13 @@ curl -fsSL https://openviking.ai/install | bash
## 各宿主差异
-- **Cursor** — 六个事件,其中 `preCompact` 与 `sessionEnd` 是本插件里独有的。Stop 时 `capturedSinceCommit` 达到阈值才 commit,压缩前无条件 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。
+- **Cursor** — 七个事件。`afterMCPExecution` 将 OpenViking 工具结果追加到本地 JSONL 日志,Stop 时与文本 transcript 一起上报;文本去重与工具上传位置分别管理,成功后推进捕获位置,失败由原记录重试。`capturedSinceCommit` 达到阈值才 commit,压缩前在消息完整上报后 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。
- **TRAE / TRAE CN** — 采集直接读 Stop 事件的 `prompt`、`text_content`、`last_assistant_message`,不解析 transcript;每次带内容的 Stop 都 commit。会话前缀 `tr-` 与 `trcn-`。见 [TRAE 接入文档](../../docs/zh/agent-integrations/13-trae.md)。
- **ZCode** — rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能补回漏掉的回合,hook stdin 只是兜底。ZCode 不支持 `PreCompact` 与 `SessionEnd`,因此每次 Stop 都 commit 来补足这两个信号。它的输出 schema 是严格的,所以放行时不写任何内容。会话前缀 `zc-`。已验证的扩展面记录在 [DESIGN.md](./DESIGN.md)。
- **Kimi Code** — `wire.jsonl` 是权威 transcript;UserPromptSubmit 输出原始上下文文本。Stop、PreCompact、SessionEnd 可后台写入,Interrupt 保持同步并共享 2 秒的 OpenViking 请求预算。安装脚本生成自包含原生插件,不修改旧的 `config.toml` 或 `mcp.json`。会话前缀 `kc-`。
+Cursor 工具采集依据 [Hooks 契约](https://cursor.com/docs/hooks) 和 [`@cursor/sdk` 1.0.38](https://registry.npmjs.org/@cursor/sdk/-/sdk-1.0.38.tgz) 的 MCP 执行器实现,后者在 `afterMCPExecution` 中提供 `tool_use_id`。旧事件若没有原生调用 ID,只保留文本采集;适配器不生成调用 ID 或推断完成状态。
+
## 体检
```bash
diff --git a/examples/agent-hook-plugin/hosts/cursor.mjs b/examples/agent-hook-plugin/hosts/cursor.mjs
index bcb108910..e3f6c833f 100644
--- a/examples/agent-hook-plugin/hosts/cursor.mjs
+++ b/examples/agent-hook-plugin/hosts/cursor.mjs
@@ -1,20 +1,104 @@
-import { readFile } from "node:fs/promises";
+import { appendFile, open, readFile } from "node:fs/promises";
import {
- addAgentMessages,
commitAgentSession,
stableHash,
} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { filterCaptureTurns, isCaptureEnabled } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import {
+ extractPartsFromPayload,
+ filterCaptureTurns,
+ isCaptureEnabled,
+ shapeCaptureParts,
+} from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import { sendSessionMessages } from "../../memory-plugin-shared/lib/batch-send.mjs";
import { denyCursorPermission, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";
import { parseCursorTranscript } from "./cursor-transcript.mjs";
-async function captureTranscript(ctx, state) {
- if (!isCaptureEnabled(ctx.cfg)) return { state, captured: 0 };
+async function readTranscript(ctx) {
const transcriptPath = ctx.input.transcript_path || ctx.input.transcriptPath;
- if (!transcriptPath) return { state, captured: 0 };
- let turns = [];
- try { turns = parseCursorTranscript(await readFile(transcriptPath, "utf8")); } catch { return { state, captured: 0 }; }
+ if (!transcriptPath) return null;
+ try { return parseCursorTranscript(await readFile(transcriptPath, "utf8")); } catch { return null; }
+}
+
+async function recordMcpResult(ctx) {
+ const input = ctx.input;
+ // The managed installation registers this exact server key. A tool named
+ // "read" on another MCP server must never become an OpenViking read.
+ if (input.mcp_server_name !== "openviking") return;
+ if (typeof input.tool_use_id !== "string" || !input.tool_use_id.trim()
+ || typeof input.tool_name !== "string" || !input.tool_name.trim()) {
+ ctx.log("capture_skip", { reason: "missing_mcp_tool_identity" });
+ return;
+ }
+ let toolInput, result;
+ try {
+ toolInput = JSON.parse(input.tool_input);
+ result = JSON.parse(input.result_json);
+ } catch {
+ ctx.log("capture_skip", { reason: "invalid_mcp_tool_json" });
+ return;
+ }
+ if (!toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)
+ || !result || typeof result !== "object" || Array.isArray(result)) {
+ ctx.log("capture_skip", { reason: "invalid_mcp_tool_payload" });
+ return;
+ }
+ const failed = Boolean(result.isError || result.error || result.rejected || result.permissionDenied);
+ if (!failed && !Array.isArray(result.content)) {
+ ctx.log("capture_skip", { reason: "missing_mcp_tool_result" });
+ return;
+ }
+ const [part] = shapeCaptureParts(extractPartsFromPayload({
+ type: "tool_result",
+ tool_use_id: input.tool_use_id,
+ name: `mcp__openviking__${input.tool_name}`,
+ state: { input: toolInput, output: result },
+ is_error: failed,
+ }, { toolMaxChars: ctx.cfg.captureToolMaxChars }), "assistant", ctx.cfg).parts;
+ // The hook's session lock also serializes this append. Keep result bodies
+ // out of the checkpoint: each completion writes only its own record.
+ const record = { afterTurn: (await readTranscript(ctx))?.length ?? null, part };
+ await appendFile(`${ctx.stateFile}.tools.jsonl`, `${JSON.stringify(record)}\n`, { mode: 0o600 });
+}
+
+async function readToolRecords(ctx, offset) {
+ let file;
+ let tail;
+ try {
+ file = await open(`${ctx.stateFile}.tools.jsonl`, "r");
+ const { size } = await file.stat();
+ if (offset > size) throw new Error("Cursor tool log is shorter than its capture checkpoint");
+ tail = Buffer.alloc(size - offset);
+ for (let position = 0; position < tail.length;) {
+ const { bytesRead } = await file.read(tail, position, tail.length - position, offset + position);
+ if (!bytesRead) throw new Error("Cursor tool log ended before its recorded size");
+ position += bytesRead;
+ }
+ } catch (error) {
+ if (error.code === "ENOENT" && offset === 0) return [];
+ throw error;
+ } finally {
+ await file?.close();
+ }
+ if (tail.length && tail.at(-1) !== 10) throw new Error("Cursor tool log has an incomplete record");
+ return tail.toString("utf8").split("\n").slice(0, -1).map((line) => {
+ offset += Buffer.byteLength(line, "utf8") + 1;
+ return { ...JSON.parse(line), endOffset: offset };
+ });
+}
+
+async function captureTranscript(ctx, state) {
+ const turns = await readTranscript(ctx);
+ if (!turns) {
+ ctx.log("capture_skip", { reason: "unreadable_transcript" });
+ return { state, complete: false };
+ }
+ let capturedToolOffset = state.capturedToolOffset || 0;
+ const toolRecords = await readToolRecords(ctx, capturedToolOffset);
+ // Keep acknowledgement identities in the checkpoint, so an old completion
+ // can be deduplicated without rereading its result body.
+ const acceptedToolIds = new Set(state.capturedToolIds || []);
+ const seenToolIds = new Set(acceptedToolIds);
const capturedHashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
const toSend = [];
for (const [index, turn] of turns.entries()) {
@@ -31,17 +115,48 @@ async function captureTranscript(ctx, state) {
capturedHashes.add(hash);
continue;
}
- toSend.push({ hash, turn: kept[0] });
+ toSend.push({ hash, position: index * 2, turn: kept[0] });
+ }
+ let toolPosition = -1;
+ for (const item of toolRecords) {
+ if (seenToolIds.has(item.part.tool_id)) continue;
+ seenToolIds.add(item.part.tool_id);
+ // Preserve tool-log order even when compaction shortened the text source.
+ toolPosition = Math.max(toolPosition, (item.afterTurn ?? turns.length) * 2 - 1);
+ toSend.push({
+ toolId: item.part.tool_id,
+ position: toolPosition,
+ turn: { role: "assistant", parts: [item.part] },
+ });
+ }
+ toSend.sort((a, b) => a.position - b.position);
+ // Both local sources own retries. Advance only after upload, without a
+ // second copy in the offline queue.
+ const payloads = toSend.map(({ turn }) => ({
+ ...turn,
+ ...(ctx.peerId ? { peer_id: ctx.peerId } : {}),
+ }));
+ const result = await sendSessionMessages(ctx.fetchJSON, ctx.sessionId, payloads);
+ const captured = result.sent;
+ const acknowledged = toSend.slice(0, captured);
+ for (const item of acknowledged) {
+ if (item.toolId) acceptedToolIds.add(item.toolId);
+ else capturedHashes.add(item.hash);
+ }
+ for (const item of toolRecords) {
+ if (!acceptedToolIds.has(item.part.tool_id)) break;
+ capturedToolOffset = item.endOffset;
}
- const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, toSend.map((item) => item.turn), ctx.peerId);
- const captured = result.sent + result.queued;
- for (const item of toSend.slice(0, captured)) capturedHashes.add(item.hash);
return {
captured,
+ complete: captured === toSend.length,
state: {
...state,
capturedHashes: [...capturedHashes].slice(-1000),
- capturedSinceCommit: Number(state.capturedSinceCommit || 0) + captured,
+ capturedToolOffset,
+ capturedToolIds: [...acceptedToolIds],
+ capturedSinceCommit: Number(state.capturedSinceCommit || 0)
+ + acknowledged.filter((item) => typeof item.turn.content === "string").length,
},
};
}
@@ -51,6 +166,7 @@ export const cursor = {
requestBudgets: {
sessionStart: 25_000,
beforeSubmitPrompt: 17_000,
+ afterMCPExecution: 2_000,
stop: 25_000,
preCompact: 25_000,
sessionEnd: 25_000,
@@ -58,6 +174,7 @@ export const cursor = {
stages: {
sessionStart: "start",
beforeSubmitPrompt: "prompt",
+ afterMCPExecution: "capture",
stop: "capture",
preCompact: "capture",
sessionEnd: "capture",
@@ -78,13 +195,16 @@ export const cursor = {
},
prompt: (input) => (typeof input.prompt === "string" ? input.prompt.trim() : ""),
async capture(ctx, state, event) {
- const { state: next } = await captureTranscript(ctx, state);
+ if (!isCaptureEnabled(ctx.cfg)) return state;
+ if (event === "afterMCPExecution") return recordMcpResult(ctx);
+ const { state: next, complete } = await captureTranscript(ctx, state);
+ if (!complete) return next;
// Only a plain Stop waits for the threshold: a compaction or a session end
// is the last chance this transcript has to reach the server.
const shouldCommit = event !== "stop" || next.capturedSinceCommit >= ctx.cfg.commitTurnThreshold;
if (shouldCommit) {
const result = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
- if (result.ok) next.capturedSinceCommit = 0;
+ if (result.ok || result.pendingQueued) next.capturedSinceCommit = 0;
}
return next;
},
diff --git a/examples/agent-hook-plugin/hosts/cursor/hooks.json b/examples/agent-hook-plugin/hosts/cursor/hooks.json
index 080fd768f..85b40ddd3 100644
--- a/examples/agent-hook-plugin/hosts/cursor/hooks.json
+++ b/examples/agent-hook-plugin/hosts/cursor/hooks.json
@@ -19,6 +19,12 @@
"timeout": 5
}
],
+ "afterMCPExecution": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs afterMCPExecution __OPENVIKING_CLIENT_ID__",
+ "timeout": 10
+ }
+ ],
"stop": [
{
"command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs stop __OPENVIKING_CLIENT_ID__",
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index fafb4a819..1c0e7fd90 100644
--- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.21",
+ "version": "0.5.22",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
index 51dd05c72..bf972471f 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.21",
+ "version": "0.5.22",
"description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
index 1f64e3255..3f064589b 100644
--- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.21",
+ "version": "0.5.22",
"clients": [
"kimicode"
],
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
index e7685b2b2..7d658d58a 100644
--- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.21",
+ "version": "0.5.22",
"clients": [
"trae",
"trae-cn"
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
index 5e1609b52..6aa60ae14 100644
--- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "openviking-memory",
- "version": "0.5.21",
+ "version": "0.5.22",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index 3f4167a8e..46e0a7a4e 100644
--- a/examples/agent-hook-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agent-hook-plugin",
- "version": "0.5.21",
+ "version": "0.5.22",
"description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode and Kimi Code — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/scripts/hook.mjs b/examples/agent-hook-plugin/scripts/hook.mjs
index d26a675c2..1e69ab34c 100644
--- a/examples/agent-hook-plugin/scripts/hook.mjs
+++ b/examples/agent-hook-plugin/scripts/hook.mjs
@@ -125,8 +125,9 @@ async function promptSubmit(ctx) {
async function capture(ctx) {
if (host.capturesOnlyWhenEnabled && !isCaptureEnabled(ctx.cfg)) return "";
- await withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
+ await withAgentHookLock(clientId, ctx.nativeSessionId, async (stateFile) => {
const state = await readHookState(clientId, ctx.nativeSessionId);
+ ctx.stateFile = stateFile;
const next = await host.capture(ctx, state, event);
if (next) await writeHookState(clientId, ctx.nativeSessionId, next);
});
diff --git a/examples/agent-hook-plugin/tests/cursor.test.mjs b/examples/agent-hook-plugin/tests/cursor.test.mjs
index 3ae0d3b42..044b7192e 100644
--- a/examples/agent-hook-plugin/tests/cursor.test.mjs
+++ b/examples/agent-hook-plugin/tests/cursor.test.mjs
@@ -1,13 +1,15 @@
import assert from "node:assert/strict";
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import fs from "node:fs/promises";
import { createServer } from "node:http";
+import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { expectExit, runHookScript } from "../../memory-plugin-shared/testing/support.mjs";
-import { parseCursorTranscript } from "../hosts/cursor-transcript.mjs";
+import { cursor } from "../hosts/cursor.mjs";
import { evaluateHostUriGuard } from "../scripts/uri-guard.mjs";
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -44,6 +46,7 @@ test("Cursor command-installed integration contains Hook, Rule, Skill, and MCP e
"sessionStart",
"beforeSubmitPrompt",
"beforeReadFile",
+ "afterMCPExecution",
"stop",
"preCompact",
"sessionEnd",
@@ -68,21 +71,98 @@ test("Cursor URI guard lets a shell command routed by an older install run", ()
}), {});
});
-test("Cursor transcript parser keeps only user and assistant text", () => {
- const raw = [
- JSON.stringify({ role: "user", message: { content: [{ type: "text", text: "question" }] } }),
- JSON.stringify({ role: "assistant", message: { content: [{ type: "text", text: "answer [REDACTED]" }, { type: "tool_use", name: "Read" }] } }),
- JSON.stringify({ type: "turn_ended", status: "success" }),
- ].join("\n");
- assert.deepEqual(parseCursorTranscript(raw), [
- { role: "user", content: "question" },
- { role: "assistant", content: "answer" },
- ]);
+test("Cursor captures a busy session without replaying text or rereading uploaded tool bodies", async () => {
+ const root = mkdtempSync(join(tmpdir(), "openviking-cursor-history-"));
+ const transcript = join(root, "transcript.jsonl");
+ const messages = [];
+ let commits = 0;
+ let toolReadBytes = 0;
+ const originalReadFile = fs.readFile;
+ const originalOpen = fs.open;
+ fs.readFile = async (path, ...args) => {
+ const data = await originalReadFile(path, ...args);
+ if (String(path).endsWith(".tools.jsonl")) toolReadBytes += Buffer.byteLength(data);
+ return data;
+ };
+ fs.open = async (path, ...args) => {
+ const file = await originalOpen(path, ...args);
+ if (String(path).endsWith(".tools.jsonl")) {
+ const read = file.read.bind(file);
+ file.read = async (...args) => {
+ const result = await read(...args);
+ toolReadBytes += result.bytesRead;
+ return result;
+ };
+ }
+ return file;
+ };
+ syncBuiltinESMExports();
+ const ctx = {
+ cfg: { enabled: true, autoCapture: true, commitTurnThreshold: 8 },
+ sessionId: "cu-history",
+ stateFile: join(root, "state.json"),
+ peerId: "",
+ log: () => {},
+ fetchJSON: async (path, request) => {
+ if (path.endsWith("/messages/batch")) messages.push(...JSON.parse(request.body).messages);
+ if (path.endsWith("/commit")) commits++;
+ return { ok: true };
+ },
+ };
+ const tool = {
+ transcript_path: transcript,
+ mcp_server_name: "openviking",
+ tool_name: "read",
+ tool_input: JSON.stringify({ uris: "viking://~/memories/experiences/example.md" }),
+ result_json: JSON.stringify({ content: [{ type: "text", text: `${"x".repeat(19996)}部署经验` }], isError: false }),
+ };
+ let state = {};
+ const lines = [];
+ try {
+ for (let round = 0; round < 60; round++) {
+ lines.push(
+ JSON.stringify({ role: "user", content: `Question in round ${round}` }),
+ JSON.stringify({ role: "assistant", content: `Answer in round ${round}` }),
+ );
+ writeFileSync(transcript, lines.join("\n"));
+ for (let call = 0; call < 15; call++) {
+ ctx.input = { ...tool, tool_use_id: `${round}-${call}` };
+ await cursor.capture(ctx, state, "afterMCPExecution");
+ }
+ ctx.input = { transcript_path: transcript };
+ state = await cursor.capture(ctx, state, "stop");
+ }
+ assert.equal(messages.filter((message) => typeof message.content === "string").length, 120);
+ assert.equal(messages.filter((message) => message.parts).length, 900);
+ assert.equal(commits, 15);
+ const readBeforeEmptyStop = toolReadBytes;
+ assert.equal(toolReadBytes, statSync(`${ctx.stateFile}.tools.jsonl`).size,
+ "each tool-result byte should be read once across all rounds");
+ state = await cursor.capture(ctx, state, "stop");
+ assert.equal(toolReadBytes, readBeforeEmptyStop, "empty Stop must not read tool-result bodies");
+
+ // An old completion can be delivered again after its result was accepted.
+ ctx.input = { ...tool, tool_use_id: "0-0" };
+ await cursor.capture(ctx, state, "afterMCPExecution");
+ ctx.input = { transcript_path: transcript };
+ state = await cursor.capture(ctx, state, "stop");
+ await cursor.capture(ctx, state, "stop");
+ assert.equal(messages.length, 1020, "empty Stop must not resend accepted text or tools");
+ assert.equal(commits, 15, "duplicate capture must not advance the commit threshold");
+ assert.equal(toolReadBytes, statSync(`${ctx.stateFile}.tools.jsonl`).size,
+ "a repeated completion only reads the newly appended record");
+ } finally {
+ fs.readFile = originalReadFile;
+ fs.open = originalOpen;
+ syncBuiltinESMExports();
+ rmSync(root, { recursive: true, force: true });
+ }
});
-test("Cursor injects recall before the request and Stop captures transcript deltas", async () => {
+test("Cursor captures text and completed OpenViking tools together before commit", async () => {
const messages = [];
const actorPeers = [];
+ const archives = [];
const server = createServer((request, response) => {
let body = "";
request.on("data", (chunk) => { body += chunk; });
@@ -97,6 +177,7 @@ test("Cursor injects recall before the request and Stop captures transcript delt
messages.push(...(parsed.messages ?? [parsed]));
response.end(JSON.stringify({ result: { ok: true } }));
} else if (request.url?.endsWith("/commit")) {
+ archives.push([...messages]);
response.end(JSON.stringify({ result: { ok: true } }));
} else {
response.statusCode = 404;
@@ -110,6 +191,7 @@ test("Cursor injects recall before the request and Stop captures transcript delt
HOME: root,
OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
OPENVIKING_HOOK_STATE_DIR: join(root, "state"),
+ OPENVIKING_PENDING_DIR: join(root, "pending"),
OPENVIKING_MEMORY_ENABLED: "1",
};
try {
@@ -131,6 +213,34 @@ test("Cursor injects recall before the request and Stop captures transcript delt
JSON.stringify({ role: "user", message: { content: [{ type: "text", text: "question" }] } }),
JSON.stringify({ role: "assistant", message: { content: [{ type: "text", text: "answer" }] } }),
].join("\n"));
+ const experienceUri = "viking://~/memories/experiences/example.md";
+ const read = {
+ ...base,
+ transcript_path: transcript,
+ tool_use_id: "read-1",
+ mcp_server_name: "openviking",
+ tool_name: "read",
+ tool_input: JSON.stringify({ uris: experienceUri }),
+ result_json: JSON.stringify({ content: [{ type: "text", text: "experience body" }], isError: false }),
+ };
+ await Promise.all([
+ runHook("afterMCPExecution", read, env),
+ runHook("afterMCPExecution", read, env),
+ ]);
+ await runHook("afterMCPExecution", {
+ ...read, tool_use_id: "read-failed",
+ result_json: JSON.stringify({ content: [{ type: "text", text: "NOT_FOUND: missing" }], isError: true }),
+ }, env);
+ await runHook("afterMCPExecution", { ...read, tool_use_id: "other-server", mcp_server_name: "other" }, env);
+ await runHook("afterMCPExecution", { ...read, tool_use_id: "" }, env);
+ await runHook("afterMCPExecution", { ...read, tool_use_id: "no-result", result_json: "{}" }, env);
+ await runHook("afterMCPExecution", { ...read, tool_use_id: "disabled" }, { ...env, OPENVIKING_AUTO_CAPTURE: "0" });
+ await runHook("preCompact", { ...base, transcript_path: join(root, "missing.jsonl") }, env);
+ assert.equal(messages.length, 0, "tool completion only records locally");
+ assert.equal(archives.length, 0);
+ writeFileSync(transcript, `${readFileSync(transcript, "utf8")}\n${JSON.stringify({
+ role: "assistant", content: "Task finished after reading the experience.",
+ })}`);
await Promise.all([
runHook("stop", { ...base, transcript_path: transcript }, env),
runHook("stop", { ...base, transcript_path: transcript }, env),
@@ -139,28 +249,56 @@ test("Cursor injects recall before the request and Stop captures transcript delt
assert.deepEqual(messages, [
{ role: "user", content: "question", peer_id: "github.com-acme-cursor-project" },
{ role: "assistant", content: "answer", peer_id: "github.com-acme-cursor-project" },
+ {
+ role: "assistant", peer_id: "github.com-acme-cursor-project",
+ parts: [{
+ type: "tool", tool_id: "read-1", tool_name: "mcp__openviking__read",
+ tool_status: "completed", tool_input: { uris: experienceUri }, tool_output: read.result_json,
+ }],
+ },
+ {
+ role: "assistant", peer_id: "github.com-acme-cursor-project",
+ parts: [{
+ type: "tool", tool_id: "read-failed", tool_name: "mcp__openviking__read",
+ tool_status: "error", tool_input: { uris: experienceUri },
+ tool_output: JSON.stringify({ content: [{ type: "text", text: "NOT_FOUND: missing" }], isError: true }),
+ }],
+ },
+ { role: "assistant", content: "Task finished after reading the experience.", peer_id: "github.com-acme-cursor-project" },
]);
+ await runHook("afterMCPExecution", read, env);
+ await runHook("sessionEnd", { ...base, transcript_path: transcript }, env);
+ assert.equal(messages.length, 5, "a repeated completion after Stop is not captured twice");
+ assert.deepEqual(archives.at(-1), messages);
} finally {
server.close();
rmSync(root, { recursive: true, force: true });
}
});
-test("Cursor replays offline capture on the next SessionStart", async () => {
+test("Cursor retries the unreported tail after a partial capture before committing", async () => {
const messages = [];
+ const archives = [];
let offline = true;
const server = createServer((request, response) => {
let body = "";
request.on("data", (chunk) => { body += chunk; });
request.on("end", () => {
if (request.url?.includes("/messages")) {
- if (offline) {
+ if (offline && request.url.endsWith("/messages/batch")) {
+ response.statusCode = 404;
+ response.end(JSON.stringify({ status: "error" }));
+ return;
+ }
+ if (offline && messages.length >= 3) {
response.statusCode = 503;
response.end(JSON.stringify({ status: "error", error: "offline" }));
return;
}
const parsed = JSON.parse(body);
messages.push(...(parsed.messages ?? [parsed]));
+ } else if (request.url?.endsWith("/commit")) {
+ archives.push([...messages]);
}
response.end(JSON.stringify({ result: { ok: true } }));
});
@@ -183,19 +321,48 @@ test("Cursor replays offline capture on the next SessionStart", async () => {
].join("\n"));
const input = { conversation_id: "cursor-offline", cwd: "/workspace", transcript_path: transcript };
- await runHook("stop", input, env);
- assert.equal(readdirSync(pendingDir).filter((name) => name.endsWith(".json")).length, 2);
+ const tool = {
+ ...input,
+ tool_use_id: "offline-read",
+ mcp_server_name: "openviking",
+ tool_name: "read",
+ tool_input: JSON.stringify({ uris: "viking://~/memories/experiences/offline.md" }),
+ result_json: JSON.stringify({ content: [{ type: "text", text: "offline experience" }], isError: false }),
+ };
+ await runHook("afterMCPExecution", tool, env);
+ await runHook("afterMCPExecution", tool, env);
+ await runHook("afterMCPExecution", { ...tool, tool_use_id: "offline-read-2" }, env);
+ await runHook("preCompact", input, env);
+ assert.equal(archives.length, 0, "commit must not overtake unreported messages");
+ assert.equal(messages.length, 3);
+ assert.equal(messages[2].parts[0].tool_id, "offline-read");
+ assert.equal(existsSync(pendingDir), false, "the local capture source owns retries");
offline = false;
- await runHook("sessionStart", input, env);
+ await runHook("preCompact", input, env);
assert.deepEqual(messages, [
{ role: "user", content: "offline question" },
{ role: "assistant", content: "offline answer" },
+ {
+ role: "assistant",
+ parts: [{
+ type: "tool", tool_id: "offline-read", tool_name: "mcp__openviking__read",
+ tool_status: "completed", tool_input: JSON.parse(tool.tool_input), tool_output: tool.result_json,
+ }],
+ },
+ {
+ role: "assistant",
+ parts: [{
+ type: "tool", tool_id: "offline-read-2", tool_name: "mcp__openviking__read",
+ tool_status: "completed", tool_input: JSON.parse(tool.tool_input), tool_output: tool.result_json,
+ }],
+ },
]);
- assert.equal(readdirSync(pendingDir).filter((name) => name.endsWith(".json")).length, 0);
+ assert.deepEqual(archives, [messages]);
+ assert.equal(existsSync(pendingDir), false);
await runHook("stop", input, env);
- assert.equal(messages.length, 2, "captured hashes prevent replayed turns from being stored twice");
+ assert.equal(messages.length, 4, "acknowledged turns are not stored twice");
} finally {
server.close();
rmSync(root, { recursive: true, force: true });
diff --git a/examples/agent-hook-plugin/tests/request-budget.test.mjs b/examples/agent-hook-plugin/tests/request-budget.test.mjs
index 424bde0fa..bbf61a23c 100644
--- a/examples/agent-hook-plugin/tests/request-budget.test.mjs
+++ b/examples/agent-hook-plugin/tests/request-budget.test.mjs
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
-import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -83,7 +83,7 @@ test("recall stops falling back once the prompt budget is spent", async (t) => {
assert.deepEqual(server.requests, ["POST /api/v1/search/search", "POST /api/v1/search/recall"]);
});
-test("a capture keeps each request to the request timeout and queues what the stop budget cannot fit", async (t) => {
+test("a capture timeout retains its cursor and does not commit incomplete capture", async (t) => {
const server = await silentServer(t);
const cfg = config(server.port);
const transcript = join(dir, "transcript.jsonl");
@@ -96,17 +96,17 @@ test("a capture keeps each request to the request timeout and queues what the st
cfg,
input: { transcript_path: transcript },
sessionId: "cu-budget",
+ stateFile: join(dir, "budget.json"),
fetchJSON: withRequestBudget(fetchJSON, 1500, cfg.timeoutMs),
peerId: "",
log: () => {},
};
const started = Date.now();
- await HOSTS.cursor.capture(ctx, {}, "preCompact");
+ const state = await HOSTS.cursor.capture(ctx, {}, "preCompact");
const elapsed = Date.now() - started;
assert.ok(elapsed < 1500, `capture took ${elapsed}ms`);
assert.deepEqual(server.requests, ["POST /api/v1/sessions/cu-budget/messages/batch"]);
- const queued = readdirSync(process.env.OPENVIKING_PENDING_DIR)
- .map((name) => JSON.parse(readFileSync(join(process.env.OPENVIKING_PENDING_DIR, name), "utf8")).type)
- .sort();
- assert.deepEqual(queued, ["addMessage", "addMessage", "commitSession"]);
+ assert.deepEqual(state.capturedHashes, []);
+ assert.equal(state.capturedSinceCommit, 0);
+ assert.equal(existsSync(process.env.OPENVIKING_PENDING_DIR), false);
});
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index 572c1b823..8de36eaa6 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.7.13",
+ "version": "0.7.14",
"description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index ff5896dce..56f30ec0f 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.7.13",
+ "version": "0.7.14",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
index 2e1d04421..6018494cf 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -132,7 +132,7 @@ export async function withAgentHookLock(clientId, nativeSessionId, callback) {
}
}
try {
- return await callback();
+ return await callback(file);
} finally {
await rm(lock, { recursive: true, force: true }).catch(() => {});
}
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index 6be7f2873..979ba3be5 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.11.11",
+ "version": "0.11.12",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
index 2e1d04421..6018494cf 100644
--- a/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -132,7 +132,7 @@ export async function withAgentHookLock(clientId, nativeSessionId, callback) {
}
}
try {
- return await callback();
+ return await callback(file);
} finally {
await rm(lock, { recursive: true, force: true }).catch(() => {});
}
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
index da778a7bf..cd74aea44 100644
--- a/examples/dsh-memory-plugin/config.mjs
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -1,7 +1,7 @@
import { buildPluginConfig } from "./shared/plugin-config.mjs";
-import { loadCredentialFiles } from "./shared/credentials.mjs";
+import { loadCredentialFiles, readManifestVersion } from "./shared/credentials.mjs";
-export const PLUGIN_VERSION = "0.5.26";
+export const PLUGIN_VERSION = readManifestVersion(new URL("./package.json", import.meta.url));
/**
* Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index a1b38dee3..37272624e 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.26",
+ "version": "0.5.27",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.26",
+ "version": "0.5.27",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index 699aa5255..c95a02c8a 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.5.26",
+ "version": "0.5.27",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"icon": "./icon.svg",
"type": "module",
diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
index cc11e4ab0..dcc4df110 100644
--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs
+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
@@ -361,6 +361,7 @@ test("combined hook-host install preserves unrelated hooks and is idempotent", (
assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes("OPENVIKING_INTEGRATION_ID='openviking-memory'")));
assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes("OPENVIKING_HOOK_SOURCE='cursor'")));
assert.equal(cursor.hooks.beforeReadFile.filter((entry) => entry.command.includes("uri-guard.mjs")).length, 1);
+ assert.equal(cursor.hooks.afterMCPExecution.filter((entry) => entry.command.includes("scripts/hook.mjs")).length, 1);
assert.deepEqual(cursor.hooks.beforeShellExecution, [thirdPartyShellHook]);
assert.equal(Boolean(cursor.hooks.postToolUse), false);
diff --git a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
index ad6471951..200a5d864 100644
--- a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
+++ b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
@@ -131,7 +131,7 @@ export async function withAgentHookLock(clientId, nativeSessionId, callback) {
}
}
try {
- return await callback();
+ return await callback(file);
} finally {
await rm(lock, { recursive: true, force: true }).catch(() => {});
}
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index a2a9f96b3..f18a47ca3 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.5.17",
+ "version": "0.5.18",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json
index ab36959e2..25af49a13 100644
--- a/examples/pi-coding-agent-extension/package-lock.json
+++ b/examples/pi-coding-agent-extension/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.20",
+ "version": "0.4.21",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openviking-pi-extension",
- "version": "0.4.20",
+ "version": "0.4.21",
"dependencies": {
"@modelcontextprotocol/client": "2.0.0"
},
diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json
index 67c307f4f..c187ea515 100644
--- a/examples/pi-coding-agent-extension/package.json
+++ b/examples/pi-coding-agent-extension/package.json
@@ -1,6 +1,6 @@
{
"name": "openviking-pi-extension",
- "version": "0.4.20",
+ "version": "0.4.21",
"description": "OpenViking memory and context extension for the pi coding agent",
"private": true,
"type": "module",
diff --git a/openviking/session/memory/experience_lineage.py b/openviking/session/memory/experience_lineage.py
index 146e9b4fe..319bc4828 100644
--- a/openviking/session/memory/experience_lineage.py
+++ b/openviking/session/memory/experience_lineage.py
@@ -8,7 +8,7 @@ import json
import re
from typing import Any, Iterable
-from openviking.core.namespace import uri_parts
+from openviking.core.namespace import resolve_request_uri, uri_parts
from openviking.message import Message, ToolPart
from openviking.server.identity import RequestContext
from openviking.utils.tags import normalize_search_tag
@@ -138,7 +138,12 @@ def collect_read_experience_uris(
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 "?" in uri or "#" in uri:
+ continue
+ try:
+ canonical_uri = canonical_experience_uri(resolve_request_uri(uri, ctx), ctx)
+ except ValueError:
+ continue
if (
not canonical_uri
or canonical_uri in seen
diff --git a/tests/session/train/test_trajectory_analyzer_component.py b/tests/session/train/test_trajectory_analyzer_component.py
index 7deb471e2..dbfe0b6f2 100644
--- a/tests/session/train/test_trajectory_analyzer_component.py
+++ b/tests/session/train/test_trajectory_analyzer_component.py
@@ -9,6 +9,7 @@ from types import SimpleNamespace
import pytest
from openviking.message import Message, TextPart, ToolPart
+from openviking.server.identity import RequestContext, Role
from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOperations
from openviking.session.memory.utils import generate_uri
from openviking.session.train import (
@@ -22,6 +23,7 @@ from openviking.session.train.components.trajectory_analyzer import (
TrajectoryAnalyzerContext,
TrajectoryRolloutAnalyzer,
)
+from openviking_cli.session.user_id import UserIdentifier
def _patch_runtime_defaults(monkeypatch):
@@ -206,10 +208,7 @@ async def test_trajectory_rollout_analyzer_extracts_and_persists_trajectory(monk
analyzer = TrajectoryRolloutAnalyzer(viking_fs=fs, vlm_resolver=FakeResolver())
context = TrajectoryAnalyzerContext(
- request_context=SimpleNamespace(
- user=SimpleNamespace(account_id="default", user_id="u"),
- account_id="default",
- ),
+ request_context=RequestContext(user=UserIdentifier("default", "u"), role=Role.USER),
source_archive_uri="viking://user/u/sessions/s1/history/archive_001",
)
@@ -222,7 +221,7 @@ async def test_trajectory_rollout_analyzer_extracts_and_persists_trajectory(monk
ToolPart(
tool_id="read-1",
tool_name="read",
- tool_input={"uri": "viking://user/u/memories/experiences/exchange.md"},
+ tool_input={"uris": "viking://~/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 f5317438a..c03b74852 100644
--- a/tests/unit/session/memory/test_experience_lineage.py
+++ b/tests/unit/session/memory/test_experience_lineage.py
@@ -34,7 +34,7 @@ def test_collect_read_experience_uris_supports_generic_openviking_reads():
ToolPart(
tool_id="read-1",
tool_name="mcp__openviking__read",
- tool_input={"uri": uri},
+ tool_input={"uris": "viking://~/memories/experiences/order-exchange.md"},
tool_status="pending",
),
ToolPart(
@@ -54,7 +54,7 @@ def test_collect_read_experience_uris_supports_generic_openviking_reads():
tool_id="read-1",
tool_name="mcp__openviking__read",
tool_status="completed",
- tool_output='{"uri":"%s"}' % uri,
+ tool_output="Experience body without a URI.",
),
ToolPart(
tool_id="read-2",
@@ -71,9 +71,36 @@ def test_collect_read_experience_uris_supports_generic_openviking_reads():
ToolPart(
tool_id="read-3",
tool_name="read",
- tool_input={"uri": uri},
+ tool_input={"uris": "viking://~/memories/experiences/failed.md"},
tool_status="error",
),
+ ToolPart(
+ tool_id="read-4",
+ tool_name="read",
+ tool_input={"uris": uri},
+ tool_status="completed",
+ tool_output="The same experience read through its canonical URI.",
+ ),
+ ToolPart(
+ tool_id="read-5",
+ tool_name="read",
+ tool_input={"uris": "viking://~/memories/experiences/unfinished.md"},
+ tool_status="running",
+ ),
+ ToolPart(
+ tool_id="read-6",
+ tool_name="read",
+ tool_input={
+ "uris": [
+ "file:///tmp/experience.md",
+ "viking://~/memories/experiences/.abstract.md",
+ "viking://~/memories/experiences/../other.md",
+ "viking://~/memories/experiences/example.md?offset=1",
+ "viking://~/memories/experiences/example.md#section",
+ ]
+ },
+ tool_status="completed",
+ ),
],
),
]