Skip to content

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

fix(agent-hook-plugin): commit turns Stop already sent at session end (#6598)

t0saki376aa806392c
diff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.md
index ad76de0d1..45dd3dba2 100644
--- a/docs/en/agent-integrations/08-community-plugins.md
+++ b/docs/en/agent-integrations/08-community-plugins.md
@@ -84,7 +84,7 @@ The CodeBuddy Code integration is an `agent-hook-plugin` host adapter. It reuses
- **SessionStart** injects the user profile and replays anything the offline queue is holding.
- **UserPromptSubmit** recalls relevant memories and injects them as an `<openviking-context>` block in `additionalContext`. Host-generated continuation turns are skipped, so a turn the host produced on its own never triggers a search.
- **PreToolUse** denies reading or writing a `viking://` URI as a local path and points the Agent at the OpenViking MCP tools. Shell commands are not checked, so `ov` invocations and literal `viking://` arguments still work.
-- **Stop**, **PreCompact**, and **SessionEnd** capture new transcript turns incrementally in a detached worker. `Stop` commits the OpenViking session every 8 captured messages (`commitTurnThreshold`); `PreCompact` and `SessionEnd` commit when they capture new messages.
+- **Stop**, **PreCompact**, and **SessionEnd** capture new transcript turns incrementally in a detached worker. `Stop` commits the OpenViking session every 8 captured messages (`commitTurnThreshold`); `PreCompact` and `SessionEnd` commit everything not yet committed, including messages `Stop` already sent.
The plugin manifest also exposes the OpenViking MCP server as a stdio proxy onto the same resolved configuration, and ships the `openviking-memory`, `openviking-skills`, and `ov-experience-memory` skills. Hooks and MCP read the same credentials, so they cannot disagree about the server, account, or user. Subagent capture is not supported in v1, as on the other community adapters: the host fires `SubagentStart`/`SubagentStop`, but the shared dispatcher has no subagent stage yet.
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index a10388fc7..9b76554e9 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -53,8 +53,8 @@ Long-term memories are extracted from a session only after a **commit**. Capture
| Cursor | Yes, session-aware | Profile, memory index, skills | Every 8 captured messages | No | Commits, then the host summarizes |
| TRAE, TRAE CN | Yes, session-aware | Profile, memory index, skills | Every turn | No exit event; turns are already committed | No pre-compaction event |
| ZCode | Yes, session-aware | Profile, memory index, skills | Every turn | No exit event; turns are already committed | No pre-compaction event |
-| Kimi Code | Yes, session-aware | Profile, memory index, skills, at the first prompt | Every 8 captured messages | Only when `SessionEnd` captures new messages | Commits newly captured messages |
-| CodeBuddy Code | Yes, session-aware, in the interactive TUI only | Profile, memory index, skills | Every 8 captured messages | Only when `SessionEnd` captures new messages, in the interactive TUI only | Commits newly captured messages |
+| Kimi Code | Yes, session-aware | Profile, memory index, skills, at the first prompt | Every 8 captured messages | Yes | Commits uncommitted messages |
+| CodeBuddy Code | Yes, session-aware, in the interactive TUI only | Profile, memory index, skills | Every 8 captured messages | Yes, in the interactive TUI only | Commits uncommitted messages |
| OpenCode | Yes, session-aware | Profile, memory index, skills, indexed repositories | At 20,000 pending tokens, when idle | Yes, within the host's cleanup time | Commits around compaction |
| DSH | Yes, session-aware | Profile, memory index, skills, once per session | At 20,000 pending tokens | Yes, with a 3-second budget | Commits, then the host summarizes |
| pi | Yes, session-aware | Profile, memory index, skills, every turn | Takeover on: about 30,000 tokens; off: 20,000 | Takeover on: no; off: yes | Takeover replaces pi's summary |
@@ -322,8 +322,8 @@ Thresholds in this table are client-side. They read the server's pending-token c
| Cursor | `stop` after 8 captured messages since the last commit (`commitTurnThreshold`), counted locally | `sessionEnd` is registered but does not run in practice | `preCompact` always commits |
| TRAE, TRAE CN | Every `Stop` that captured content | None | No pre-compaction event |
| ZCode | Every `Stop`; turns a missed `Stop` skipped are caught up from the rollout file at the next `Stop` | None | No pre-compaction event |
-| Kimi Code | `Stop` after 8 captured messages since the last commit | `SessionEnd` and `Interrupt` commit when they capture new messages | `PreCompact` commits when it captures new messages |
-| CodeBuddy Code | `Stop` after 8 captured messages since the last commit | `SessionEnd` (interactive TUI only) commits when it captures new messages; `SessionStart` replays queued writes | `PreCompact` commits when it captures new messages |
+| Kimi Code | `Stop` after 8 captured messages since the last commit | `SessionEnd` and `Interrupt` commit everything not yet committed, including messages `Stop` already sent | `PreCompact` commits everything not yet committed |
+| CodeBuddy Code | `Stop` after 8 captured messages since the last commit | `SessionEnd` (interactive TUI only) commits everything not yet committed, including messages `Stop` already sent; `SessionStart` replays queued writes | `PreCompact` commits everything not yet committed |
| OpenCode | v1 `session.idle`, v2 end of execution: at 20,000 pending tokens | Session deletion, v1 `session.error`, v1 dispose, and v2 cleanup force a commit | v1 before and after compaction; v2 once after compaction ends |
| DSH | `turn/end` at 20,000 pending tokens | Cordis teardown commits each session | `compaction/start` commits without the threshold check |
| pi, takeover on (default) | Locally estimated 30,000 tokens with more than 3 user turns | `/viking commit` | `session_before_compact` |
@@ -346,8 +346,8 @@ Thresholds in this table are client-side. They read the server's pending-token c
| Cursor | No | No | No | No | No | Closing or switching a chat fires no event. `sessionEnd` fires only on window close, after the host has already stopped running hook commands. Messages below the 8-message threshold wait for later messages in the same session |
| TRAE, TRAE CN | No | No | No | No | No | Every `Stop` already committed, so at most the turn in progress is lost |
| ZCode | No | Conditional | No | No | No | Ctrl+C after that turn's `Stop` fired lets the detached worker finish. Every `Stop` commits, and missed turns are caught up at the next `Stop` |
-| Kimi Code | Conditional | Conditional | Not verified | Not verified | No | `SessionEnd` and `Interrupt` commit only when they capture new messages; a tail already captured by `Stop` waits for the next commit |
-| CodeBuddy Code | Conditional | No | No | No | No | `SessionEnd` fires only in the interactive TUI and commits only when it captures new messages, so a headless run relies on the threshold or `/compact`. The capture runs in a detached worker that the hook's own timeout does not reach |
+| Kimi Code | Commits | Conditional | Not verified | Not verified | No | `SessionEnd` and `Interrupt` commit everything not yet committed, including messages `Stop` already sent. `Interrupt` shares a 2-second request budget between capture and commit, so a slow capture leaves the commit to the next commit of the same session |
+| CodeBuddy Code | Conditional | No | No | No | No | `SessionEnd` fires only in the interactive TUI, where it commits everything not yet committed, including messages `Stop` already sent; a headless run relies on the threshold or `/compact`. The capture runs in a detached worker that the hook's own timeout does not reach |
| OpenCode | Conditional | Conditional | Conditional | Conditional | No | v1 1.15.11+ `dispose` and v2 cleanup commit every session, but host cleanup time is limited, so slow requests or many sessions can be cut off. v2 cleanup also runs after 60 minutes idle and on plugin hot reload |
| DSH | Commits | Commits | Commits | No | No | Teardown gives each session one 3-second commit, queued behind any slow write, inside a 5-second process grace period. A second Ctrl+C force-quits without it. Closing a browser tab in the web form does not tear down |
| pi, takeover on | No | No | No | No | No | `session_shutdown` saves takeover state but does not commit. The next run that reaches the threshold, or `/viking commit` |
@@ -401,9 +401,9 @@ When the host shortens its context, most integrations make sure the dropped mess
| Claude Code | Host summarizes | `PreCompact` commits synchronously; this is the one write that never runs in the background, because the host rewrites the transcript right after | `SessionStart` with `source="compact"` injects the archive overview and up to 5 summaries |
| Codex, TraeCode CLI 2.0 | Host summarizes | `PreCompact` catches up uncaptured turns, commits everything, and starts a new OpenViking session. If the catch-up is incomplete, it does not commit and retries later | The archive summary is injected on resume |
| Cursor | Host summarizes | `preCompact` commits | Nothing |
-| CodeBuddy Code | Host summarizes | `PreCompact` commits newly captured messages | Nothing |
+| CodeBuddy Code | Host summarizes | `PreCompact` commits | Nothing |
| TRAE, TRAE CN, ZCode | Host summarizes | No pre-compaction event | Nothing |
-| Kimi Code | Host summarizes | `PreCompact` commits newly captured messages | Nothing |
+| Kimi Code | Host summarizes | `PreCompact` commits | Nothing |
| OpenCode | Host summarizes | v1 flushes and commits; v2 captures the transcript | v1 commits again on `session.compacted`; v2 commits after `session.compaction.ended` |
| DSH | Host summarizes | `compaction/start` commits regardless of the token threshold. Injected context is a user message and shrinks with the host's compaction; the profile is not sent again | Nothing |
| pi | Takeover, on by default | Commits and waits for the archive overview | The overview replaces pi's summary; on failure pi compacts as usual |
diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.md
index 37fd0731b..e47008525 100644
--- a/docs/zh/agent-integrations/08-community-plugins.md
+++ b/docs/zh/agent-integrations/08-community-plugins.md
@@ -81,7 +81,7 @@ CodeBuddy Code 集成是 `agent-hook-plugin` 的宿主适配器:复用共享
- **SessionStart** 注入用户画像,并重放离线队列中暂存的写入。
- **UserPromptSubmit** 召回相关记忆,以 `additionalContext` 中的 `<openviking-context>` 块注入。宿主自动生成的续写轮次会被跳过,因此宿主自己产生的轮次不会触发检索。
- **PreToolUse** 拒绝把 `viking://` URI 当本地路径读写,并引导 Agent 改用 OpenViking MCP 工具。Shell 命令不做检查,`ov` 调用与字面量 `viking://` 参数照常可用。
-- **Stop**、**PreCompact** 和 **SessionEnd** 在分离的 worker 中增量捕获 transcript 中的新轮次。`Stop` 每捕获 8 条消息(`commitTurnThreshold`)提交一次 OpenViking session;`PreCompact` 和 `SessionEnd` 捕获到新消息时提交。
+- **Stop**、**PreCompact** 和 **SessionEnd** 在分离的 worker 中增量捕获 transcript 中的新轮次。`Stop` 每捕获 8 条消息(`commitTurnThreshold`)提交一次 OpenViking session;`PreCompact` 和 `SessionEnd` 提交所有尚未提交的消息,包括 `Stop` 已经发送的。
插件 manifest 还把 OpenViking MCP 服务以 stdio 代理的形式暴露出来,走同一份解析后的配置,并附带 `openviking-memory`、`openviking-skills`、`ov-experience-memory` 三个 skill。hook 与 MCP 读取同一份凭据,不会在服务端、账号或用户上各说各话。与其他社区适配器一致,v1 不支持子代理采集:宿主会触发 `SubagentStart`/`SubagentStop`,但共享 dispatcher 目前还没有子代理阶段。
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index 2c80d99f6..510697d12 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -53,8 +53,8 @@
| Cursor | 是,带会话 | profile、记忆索引、skill | 每捕获 8 条消息 | 否 | 先提交,再由宿主摘要 |
| TRAE、TRAE CN | 是,带会话 | profile、记忆索引、skill | 每轮 | 没有退出事件;每轮已提交 | 没有压缩前事件 |
| ZCode | 是,带会话 | profile、记忆索引、skill | 每轮 | 没有退出事件;每轮已提交 | 没有压缩前事件 |
-| Kimi Code | 是,带会话 | profile、记忆索引、skill,在首次提问时 | 每捕获 8 条消息 | 仅当 `SessionEnd` 捕获到新消息 | 提交新捕获的消息 |
-| CodeBuddy Code | 是,带会话,仅限交互式 TUI | profile、记忆索引、skill | 每捕获 8 条消息 | 仅当 `SessionEnd` 捕获到新消息,且仅限交互式 TUI | 提交新捕获的消息 |
+| Kimi Code | 是,带会话 | profile、记忆索引、skill,在首次提问时 | 每捕获 8 条消息 | 是 | 提交尚未提交的消息 |
+| CodeBuddy Code | 是,带会话,仅限交互式 TUI | profile、记忆索引、skill | 每捕获 8 条消息 | 是,仅限交互式 TUI | 提交尚未提交的消息 |
| OpenCode | 是,带会话 | profile、记忆索引、skill、已索引的仓库 | 空闲时,待提交 token 达到 20,000 | 是,在宿主的清理时限内 | 在压缩前后提交 |
| DSH | 是,带会话 | profile、记忆索引、skill,每个会话一次 | 待提交 token 达到 20,000 | 是,预算 3 秒 | 先提交,再由宿主摘要 |
| pi | 是,带会话 | profile、记忆索引、skill,每轮 | takeover 开:约 30,000 token;关:20,000 | takeover 开:否;关:是 | takeover 替换 pi 的摘要 |
@@ -321,8 +321,8 @@ Claude Code 和 Codex 默认 `auto`,其他集成默认 `off`。支持服务端
| Cursor | 距上次提交捕获满 8 条消息时,在 `stop` 提交(`commitTurnThreshold`),本地计数 | `sessionEnd` 已注册,但实际不会运行 | `preCompact` 总是提交 |
| TRAE、TRAE CN | 每个捕获到内容的 `Stop` | 无 | 没有压缩前事件 |
| ZCode | 每个 `Stop`;漏掉的 `Stop` 对应的轮次,在下一个 `Stop` 从 rollout 文件补齐 | 无 | 没有压缩前事件 |
-| Kimi Code | 距上次提交捕获满 8 条消息时,在 `Stop` 提交 | `SessionEnd` 和 `Interrupt` 捕获到新消息时提交 | `PreCompact` 捕获到新消息时提交 |
-| CodeBuddy Code | 距上次提交捕获满 8 条消息时,在 `Stop` 提交 | `SessionEnd`(仅交互式 TUI)捕获到新消息时提交;`SessionStart` 重放排队的写入 | `PreCompact` 捕获到新消息时提交 |
+| Kimi Code | 距上次提交捕获满 8 条消息时,在 `Stop` 提交 | `SessionEnd` 和 `Interrupt` 提交所有尚未提交的消息,包括 `Stop` 已经发送的 | `PreCompact` 提交所有尚未提交的消息 |
+| CodeBuddy Code | 距上次提交捕获满 8 条消息时,在 `Stop` 提交 | `SessionEnd`(仅交互式 TUI)提交所有尚未提交的消息,包括 `Stop` 已经发送的;`SessionStart` 重放排队的写入 | `PreCompact` 提交所有尚未提交的消息 |
| OpenCode | v1 `session.idle`、v2 执行结束时:待提交 token 达到 20,000 | 删除会话、v1 `session.error`、v1 dispose 和 v2 cleanup 强制提交 | v1 在压缩前后各一次;v2 在压缩结束后一次 |
| DSH | `turn/end` 时待提交 token 达到 20,000 | Cordis teardown 提交每个会话 | `compaction/start` 提交,跳过阈值检查 |
| pi,takeover 开(默认) | 本地估算达到 30,000 token,且用户轮多于 3 个 | `/viking commit` | `session_before_compact` |
@@ -345,8 +345,8 @@ Claude Code 和 Codex 默认 `auto`,其他集成默认 `off`。支持服务端
| Cursor | 否 | 否 | 否 | 否 | 否 | 关闭或切换对话不触发任何事件。`sessionEnd` 只在关闭窗口时触发,而此时宿主已停止执行 hook 命令。不足 8 条消息阈值的部分要等同一会话的后续消息 |
| TRAE、TRAE CN | 否 | 否 | 否 | 否 | 否 | 每个 `Stop` 已经提交,最多丢失正在进行的那一轮 |
| ZCode | 否 | 视情况 | 否 | 否 | 否 | 按 Ctrl+C 时如果该轮的 `Stop` 已触发,分离的 worker 会写完。每个 `Stop` 都提交,漏掉的轮次在下一个 `Stop` 补齐 |
-| Kimi Code | 视情况 | 视情况 | 未验证 | 未验证 | 否 | `SessionEnd` 和 `Interrupt` 只在捕获到新消息时提交;已被 `Stop` 捕获的尾部等待下一次提交 |
-| CodeBuddy Code | 视情况 | 否 | 否 | 否 | 否 | `SessionEnd` 只在交互式 TUI 触发,且只在捕获到新消息时提交,因此 headless 运行依赖阈值或 `/compact`。捕获由分离的 worker 完成,hook 自身的超时不会波及它 |
+| Kimi Code | 提交 | 视情况 | 未验证 | 未验证 | 否 | `SessionEnd` 和 `Interrupt` 提交所有尚未提交的消息,包括 `Stop` 已经发送的。`Interrupt` 的捕获和提交共用 2 秒请求预算,捕获慢时提交留给同一会话的下一次提交 |
+| CodeBuddy Code | 视情况 | 否 | 否 | 否 | 否 | `SessionEnd` 只在交互式 TUI 触发,会提交所有尚未提交的消息,包括 `Stop` 已经发送的;headless 运行依赖阈值或 `/compact`。捕获由分离的 worker 完成,hook 自身的超时不会波及它 |
| OpenCode | 视情况 | 视情况 | 视情况 | 视情况 | 否 | v1 1.15.11+ 的 `dispose` 和 v2 cleanup 会提交所有会话,但宿主留给清理的时间有限,慢请求或会话较多时可能被截断。v2 cleanup 还会在空闲 60 分钟和插件热重载时运行 |
| DSH | 提交 | 提交 | 提交 | 否 | 否 | teardown 给每个会话一次 3 秒的提交,排在慢写入之后,整体处于 5 秒的进程宽限期内。第二次 Ctrl+C 会强制退出,跳过提交。Web 形态下关闭浏览器标签页不会触发 teardown |
| pi,takeover 开 | 否 | 否 | 否 | 否 | 否 | `session_shutdown` 保存 takeover 状态但不提交。等下次运行达到阈值,或执行 `/viking commit` |
@@ -400,9 +400,9 @@ Claude Code 和 Codex 默认 `auto`,其他集成默认 `off`。支持服务端
| Claude Code | 宿主摘要 | `PreCompact` 同步提交;这是唯一不在后台运行的写入,因为宿主紧接着就会重写 transcript | `source="compact"` 的 `SessionStart` 注入归档概览和最多 5 条摘要 |
| Codex、TraeCode CLI 2.0 | 宿主摘要 | `PreCompact` 补齐未捕获的轮次,提交全部内容,并开始一个新的 OpenViking 会话。补齐不完整时不提交,稍后重试 | resume 时注入归档摘要 |
| Cursor | 宿主摘要 | `preCompact` 提交 | 无 |
-| CodeBuddy Code | 宿主摘要 | `PreCompact` 提交新捕获的消息 | 无 |
+| CodeBuddy Code | 宿主摘要 | `PreCompact` 提交 | 无 |
| TRAE、TRAE CN、ZCode | 宿主摘要 | 没有压缩前事件 | 无 |
-| Kimi Code | 宿主摘要 | `PreCompact` 提交新捕获的消息 | 无 |
+| Kimi Code | 宿主摘要 | `PreCompact` 提交 | 无 |
| OpenCode | 宿主摘要 | v1 刷新并提交;v2 捕获 transcript | v1 在 `session.compacted` 时再提交一次;v2 在 `session.compaction.ended` 后提交 |
| DSH | 宿主摘要 | `compaction/start` 无论 token 阈值如何都会提交。注入的上下文是一条用户消息,随宿主压缩一起缩减;profile 不再发送 | 无 |
| pi | takeover,默认开启 | 提交并等待归档概览 | 用概览替换 pi 的摘要;失败时 pi 照常压缩 |
diff --git a/examples/agent-hook-plugin/hosts/codebuddy.mjs b/examples/agent-hook-plugin/hosts/codebuddy.mjs
index 2ad9b7da4..b8b798154 100644
--- a/examples/agent-hook-plugin/hosts/codebuddy.mjs
+++ b/examples/agent-hook-plugin/hosts/codebuddy.mjs
@@ -7,10 +7,11 @@ import {
import { buildCodebuddyTurns, cleanCodebuddyText } from "./codebuddy-turns.mjs";
export function shouldCommitCodebuddyCapture(event, cfg = {}, previous = 0, captured = 0) {
- if (captured <= 0) return false;
+ const uncommitted = Number(previous || 0) + captured;
+ if (uncommitted <= 0) return false;
if (event === "session-end") return true;
if (event === "pre-compact") return cfg.autoCommitOnCompact !== false;
- return Number(previous || 0) + captured >= Number(cfg.commitTurnThreshold || Infinity);
+ return uncommitted >= Number(cfg.commitTurnThreshold || Infinity);
}
export const codebuddy = {
@@ -76,14 +77,21 @@ export const codebuddy = {
return null;
}
const plan = buildIncrementalCapturePlan(transcript.turns, state, ctx.cfg);
- if (plan.toSend.length === 0) return null;
-
- const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads, ctx.peerId);
- const next = applyIncrementalCaptureResult(state, plan, result, cleanCodebuddyText);
+ let next;
+ if (plan.toSend.length > 0) {
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads, ctx.peerId);
+ next = applyIncrementalCaptureResult(state, plan, result, cleanCodebuddyText);
+ } else if (shouldCommitCodebuddyCapture(event, ctx.cfg, state.capturedSinceCommit, 0)) {
+ // Nothing new to send, but turns sent earlier are still uncommitted; a
+ // session end or compaction may be their last chance.
+ next = { ...state, captured: 0 };
+ } else {
+ return null;
+ }
let capturedSinceCommit = Number(state.capturedSinceCommit || 0) + next.captured;
if (shouldCommitCodebuddyCapture(event, ctx.cfg, state.capturedSinceCommit, next.captured)) {
const committed = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
- if (committed.ok) capturedSinceCommit = 0;
+ if (committed.ok || committed.pendingQueued) capturedSinceCommit = 0;
}
const { captured, ...persisted } = next;
return { ...persisted, capturedSinceCommit };
diff --git a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
index 8d39f1fb0..eabf22e55 100644
--- a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
+++ b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.5.27",
+ "version": "0.5.28",
"description": "Long-term semantic memory for the CodeBuddy Code CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.",
"author": {
"name": "OpenViking",
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
index e3b6b9ddf..9af7c1e37 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.27",
+ "version": "0.5.28",
"clients": [
"cursor"
],
diff --git a/examples/agent-hook-plugin/hosts/kimicode.mjs b/examples/agent-hook-plugin/hosts/kimicode.mjs
index 3402c65c0..1ce6bbbb2 100644
--- a/examples/agent-hook-plugin/hosts/kimicode.mjs
+++ b/examples/agent-hook-plugin/hosts/kimicode.mjs
@@ -7,10 +7,11 @@ import {
import { buildKimicodeTurns, cleanKimicodeText } from "./kimicode-turns.mjs";
export function shouldCommitKimicodeCapture(event, cfg = {}, previous = 0, captured = 0) {
- if (captured <= 0) return false;
+ const uncommitted = Number(previous || 0) + captured;
+ if (uncommitted <= 0) return false;
if (event === "interrupt" || event === "session-end") return true;
if (event === "pre-compact") return cfg.autoCommitOnCompact !== false;
- return Number(previous || 0) + captured >= Number(cfg.commitTurnThreshold || Infinity);
+ return uncommitted >= Number(cfg.commitTurnThreshold || Infinity);
}
function promptParts(input) {
@@ -63,14 +64,21 @@ export const kimicode = {
return null;
}
const plan = buildIncrementalCapturePlan(transcript.turns, state, ctx.cfg);
- if (plan.toSend.length === 0) return null;
-
- const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads, ctx.peerId);
- const next = applyIncrementalCaptureResult(state, plan, result, cleanKimicodeText);
+ let next;
+ if (plan.toSend.length > 0) {
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads, ctx.peerId);
+ next = applyIncrementalCaptureResult(state, plan, result, cleanKimicodeText);
+ } else if (shouldCommitKimicodeCapture(event, ctx.cfg, state.capturedSinceCommit, 0)) {
+ // Nothing new to send, but turns sent earlier are still uncommitted; a
+ // session end, interrupt or compaction may be their last chance.
+ next = { ...state, captured: 0 };
+ } else {
+ return null;
+ }
let capturedSinceCommit = Number(state.capturedSinceCommit || 0) + next.captured;
if (shouldCommitKimicodeCapture(event, ctx.cfg, state.capturedSinceCommit, next.captured)) {
const committed = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
- if (committed.ok) capturedSinceCommit = 0;
+ if (committed.ok || committed.pendingQueued) capturedSinceCommit = 0;
}
const { captured, ...persisted } = next;
return { ...persisted, capturedSinceCommit };
diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json
index 825f9fec1..7f2715935 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.27",
+ "version": "0.5.28",
"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 0cf1ff3e3..7aafef4ed 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.27",
+ "version": "0.5.28",
"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 18663daab..4535d4714 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.27",
+ "version": "0.5.28",
"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 5034f473d..476f1d97a 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.27",
+ "version": "0.5.28",
"clients": [
"zcode"
],
diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
index a612b83be..48f8a70aa 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.27",
+ "version": "0.5.28",
"description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode, Kimi Code and CodeBuddy 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/tests/codebuddy.test.mjs b/examples/agent-hook-plugin/tests/codebuddy.test.mjs
index 0464c03eb..aa1e1ebf0 100644
--- a/examples/agent-hook-plugin/tests/codebuddy.test.mjs
+++ b/examples/agent-hook-plugin/tests/codebuddy.test.mjs
@@ -135,6 +135,10 @@ test("both injection events answer the Claude Code envelope, write-path events s
test("the commit policy commits at session end and on compact, else by turn count", () => {
assert.equal(shouldCommitCodebuddyCapture("session-end", {}, 0, 1), true);
assert.equal(shouldCommitCodebuddyCapture("session-end", {}, 0, 0), false);
+ // Turns a Stop already sent are still uncommitted at session end.
+ assert.equal(shouldCommitCodebuddyCapture("session-end", {}, 3, 0), true);
+ assert.equal(shouldCommitCodebuddyCapture("pre-compact", {}, 3, 0), true);
+ assert.equal(shouldCommitCodebuddyCapture("stop", { commitTurnThreshold: 8 }, 3, 0), false);
assert.equal(shouldCommitCodebuddyCapture("pre-compact", {}, 0, 1), true);
assert.equal(shouldCommitCodebuddyCapture("pre-compact", { autoCommitOnCompact: false }, 0, 1), false);
assert.equal(shouldCommitCodebuddyCapture("stop", { commitTurnThreshold: 2 }, 1, 1), true);
@@ -290,6 +294,39 @@ test("a second Stop on the same session sends nothing — the cursor is idempote
}
});
+test("SessionEnd commits turns a Stop already sent below the commit threshold", async () => {
+ const restoreEnv = scrubOpenVikingEnv();
+ const box = await sandbox();
+ const seen = { batches: [], commit: 0 };
+ try {
+ await withMockOpenViking(healthyMock(seen), async (url) => {
+ const files = await writeCredentialFiles("ov-cb-capture-url-", {
+ ovcli: { url, api_key: "k" },
+ ov: {},
+ });
+ try {
+ const env = { ...files.env, ...box.env };
+ const input = stopPayload(box.transcript, box.files.dir);
+ const run = async (event) =>
+ expectExit(await runHookScript(HOOK, { argv: [event, "codebuddy"], input, cwd: box.files.dir, env }), 0);
+ await run("stop");
+ assert.equal(seen.batches.length, 1);
+ assert.equal(seen.commit, 0, "Stop stays below the commit threshold");
+ await run("session-end");
+ assert.equal(seen.batches.length, 1, "SessionEnd has nothing new to send");
+ assert.equal(seen.commit, 1, "SessionEnd commits what Stop already sent");
+ await run("session-end");
+ assert.equal(seen.commit, 1, "nothing is left to commit");
+ } finally {
+ await rmSync(files.dir, { recursive: true, force: true });
+ }
+ });
+ } finally {
+ await rmSync(box.files.dir, { recursive: true, force: true });
+ restoreEnv();
+ }
+});
+
test("a downed server queues the turns durably instead of losing them", async () => {
const restoreEnv = scrubOpenVikingEnv();
const box = await sandbox();
diff --git a/examples/agent-hook-plugin/tests/kimicode.test.mjs b/examples/agent-hook-plugin/tests/kimicode.test.mjs
index ebef9a637..b42c6bf24 100644
--- a/examples/agent-hook-plugin/tests/kimicode.test.mjs
+++ b/examples/agent-hook-plugin/tests/kimicode.test.mjs
@@ -128,3 +128,44 @@ test("Interrupt shares one two-second request budget across capture and commit",
assert.ok(elapsed < 2100, `Interrupt took ${elapsed}ms`);
assert.equal(requests, 1, "commit started after the remaining budget was below one request quantum");
});
+
+test("SessionEnd commits turns a Stop already sent below the commit threshold", async (t) => {
+ const paths = [];
+ const server = createServer((request, response) => {
+ paths.push(new URL(request.url, "http://localhost").pathname);
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end('{"result":{}}');
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+
+ const home = mkdtempSync(join(tmpdir(), "ov-kimi-session-end-"));
+ const sessionId = "session-end";
+ const sessionDir = join(home, "sessions", "wd", sessionId);
+ mkdirSync(join(sessionDir, "agents", "main"), { recursive: true });
+ writeFileSync(join(home, "session_index.jsonl"), `${JSON.stringify({ sessionId, sessionDir })}\n`);
+ writeFileSync(join(sessionDir, "agents", "main", "wire.jsonl"), [
+ JSON.stringify({ type: "turn.prompt", input: [{ type: "text", text: "question" }] }),
+ JSON.stringify({ type: "context.append_loop_event", event: { type: "content.part", turnId: "1", part: { type: "text", text: "answer" } } }),
+ ].join("\n") + "\n");
+ const env = {
+ HOME: home,
+ KIMI_CODE_HOME: home,
+ OPENVIKING_HOOK_STATE_DIR: join(home, "state"),
+ OPENVIKING_PENDING_DIR: join(home, "pending"),
+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
+ OPENVIKING_WRITE_PATH_ASYNC: "0",
+ };
+ const run = async (event) => {
+ paths.length = 0;
+ const result = await runHook([event, "kimicode"], { session_id: sessionId, cwd: home }, env);
+ assert.equal(result.status, 0, result.stderr);
+ return paths.filter((path) => path.includes("/sessions/"));
+ };
+
+ const stop = await run("stop");
+ assert.ok(stop.some((path) => path.endsWith("/messages/batch")), stop.join(", "));
+ assert.ok(!stop.some((path) => path.endsWith("/commit")), stop.join(", "));
+ assert.deepEqual(await run("session-end"), [`/api/v1/sessions/kc-${sessionId}/commit`]);
+ assert.deepEqual(await run("session-end"), []);
+});