Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
refactor(plugins): converge the harness forks back onto the shared library (#4594)
t0saki37ef554bb2a1
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.ymlindex 4d29e30c6..fa4a80025 100644--- a/.github/workflows/pr.yml+++ b/.github/workflows/pr.yml@@ -44,14 +44,17 @@ jobs:examples/codex-memory-plugin/scripts/session-end.test.mjs \examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs \examples/codex-memory-plugin/scripts/session-state.test.mjs \+ examples/codex-memory-plugin/scripts/config.test.mjs \examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs \examples/claude-code-memory-plugin/scripts/config.test.mjs \examples/claude-code-memory-plugin/scripts/marketplace.test.mjs \examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs \examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs \examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs \+ examples/claude-code-memory-plugin/scripts/lib/recall-core-timeout.test.mjs \examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs \examples/trae-memory-hooks/scripts/trae-hooks.test.mjs \+ examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs \examples/zcode-memory-plugin/scripts/zcode-async.test.mjs \examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs \examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs \diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.mdindex db3ed63d1..2491333c0 100644--- a/docs/en/agent-integrations/11-pi.md+++ b/docs/en/agent-integrations/11-pi.md@@ -86,7 +86,7 @@ An explicit peer from `OPENVIKING_PEER_ID`, `ovcli.conf`, or `ov.conf` takes pre`peerSource` decides how that workspace peer is derived. The default `"git"` uses the repository's normalized `origin` URL (`[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`), falling back to the repository root path, so every clone, worktree, and subdirectory of one repository shares a single peer; outside a repository no peer is sent at all, and what is remembered there goes to your user-level space at `viking://user/<you>/memories`. `"cwd"` restores the earlier behavior — the working directory with every non-alphanumeric character replaced by `-` — `"none"` (like `OPENVIKING_WORKSPACE_PEER=0`) sends no peer at all, and a template such as `"team-{dir}"`, or a list of templates tried in order, builds your own. To give a directory outside a repository its own memory, set `OPENVIKING_PEER_ID` for it ([Give a Directory Its Own Peer](../configuration/02-client.md#give-a-directory-its-own-peer)).-Takeover is fail-open: if pending writes cannot flush, commit fails, the archive overview is not ready, or the branch fingerprint no longer matches, pi keeps full local history or falls back to its default compaction. Set `OV_DEBUG_LOG=/tmp/ov-pi.log` when validating boundary advances.+Takeover is fail-open: if pending writes cannot flush, commit fails, the archive overview is not ready, or the branch fingerprint no longer matches, pi keeps full local history or falls back to its default compaction. Set `OPENVIKING_DEBUG_LOG=/tmp/ov-pi.log` when validating boundary advances; the log is JSON Lines, one record per event. `OV_DEBUG_LOG` is a deprecated alias that still works.## Verifydiff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.mdindex 551300f9a..ce7002dd4 100644--- a/docs/en/agent-integrations/16-capability-reference.md+++ b/docs/en/agent-integrations/16-capability-reference.md@@ -112,7 +112,7 @@ Supporting mechanisms:The `examples/memory-plugin-shared/lib/` directory contains 23 `.mjs` modules and serves as the single source of truth for all JS-based harnesses. These are consumed in two ways:-1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source (keep this in mind when cross-referencing line numbers). Every target ships exactly the modules it imports, so the breakdown follows the import graph rather than the harness. Over the 13-module hook set (`HOOK_SHARED_FILES` in `sync.mjs`) that every hook-driven plugin takes: pi takes it alone (13); dsh adds the two `mcp-proxy-*` modules it needs for the stdio proxy (15); opencode adds those two plus `async-writer` and `batch-send` (17); zcode adds those four plus `agent-hook-runtime` and `agent-uri-guard` (19); claude-code and codex add those four plus `plugin-config`, `workspace-config`, `workspace-registry`, and `doctor-core` (21 each). agent-plugins takes none of the hook set — it has no hooks — only `credentials`, `debug-log`, and the two `mcp-proxy-*` (4). At the current HEAD, every target has zero drift from the original library source.+1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source (keep this in mind when cross-referencing line numbers). Every target ships exactly the modules it imports, so the breakdown follows the import graph rather than the harness. Over the 12-module hook set (`HOOK_SHARED_FILES` in `sync.mjs`) that every hook-driven plugin takes: pi adds `setup-wizard` (13); dsh adds the two `mcp-proxy-*` modules it needs for the stdio proxy (14); opencode adds `setup-wizard`, the two `mcp-proxy-*`, and `batch-send` (16); zcode adds the two `mcp-proxy-*`, `batch-send`, `async-writer`, `agent-hook-runtime`, and `agent-uri-guard` (18); claude-code and codex add `setup-wizard`, the two `mcp-proxy-*`, `batch-send`, `async-writer`, `plugin-config`, `workspace-config`, `workspace-registry`, and `doctor-core` (21 each). agent-plugins takes none of the hook set — it has no hooks — only `credentials`, `debug-log`, and the two `mcp-proxy-*` (4). At the current HEAD, every target has zero drift from the original library source.2. **Direct import via relative path (no copying)**: Integrations like cursor, trae, and trae-cn directly `import "../../memory-plugin-shared/lib/..."`. To ensure this works, the installer copies the package alongside the 15 shared modules those hooks transitively import into `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`, preserving the relative folder layout. That installed set is closed under imports and excludes the workspace configuration layer, which no hook runtime reaches. At runtime, these harnesses share this directory, meaning reinstalling any one of them will overwrite the shared directory wholesale.Core modules at a glance (detailed further in the per-dimension sections):@@ -126,7 +126,7 @@ Core modules at a glance (detailed further in the per-dimension sections):| `batch-send.mjs` | Executes writes in batches of 100, handles per-message degradation on 404/405 errors, and queues the leading contiguous prefix | cc / codex / opencode + the agent-hook family || `profile-inject.mjs` | Injects the profile and available-memory index at session start | 9 harnesses (all but openclaw / hermes) || `recall-compress-core.mjs` | Manages the recall compression prompt, URI edit-distance repair, and caching | claude-code |-| `capture-utils.mjs` | Handles message normalization, injection back-flow guarding, and capture filtering | codex / opencode / dsh / pi |+| `capture-utils.mjs` | Handles message normalization, injection back-flow guarding, and capture filtering | codex / opencode / dsh / pi / zcode || `credentials.mjs` | Credential resolution chain (see [§3.1.3](#_3-1-3-credential-systems)) | All JS-based || `session-model.mjs` | Session ID prefix derivation and bypass globbing | All JS-based || `async-writer.mjs` | Detaches the write path (drains stdin → spawn → approve → write → unref). Falls back to synchronous writing if spawn fails | cc / codex / zcode |@@ -561,7 +561,7 @@ Each card serves as a quick-reference entry point. It records only the facts and## zcode- **Integration docs**: [Community Integrations → ZCode](./08-community-plugins.md)-- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors 19 shared modules, and is the only harness that vendors the `agent-hook-runtime` pair instead of importing it by relative path. Version 0.1.1.+- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors 18 shared modules, and is the only harness that vendors the `agent-hook-runtime` pair instead of importing it by relative path. Version 0.1.2.- **Capability highlights**: The rollout file `~/.zcode/cli/rollout/model-io-<sid>.jsonl` serves as the source of truth for increments (a `lastTurnId` diff backfills any missed Stop events). Stop detaches by default, meaning Ctrl+C does not result in lost writes.- **Behavior notes**: Commits on every Stop (keep 0). The capture path only strips the three types of injection blocks without performing any further text cleanup ([§3.2.6](#_3-2-6-injection-backflow-protection)). The initial capture reads the entire rollout at once, meaning that installing it into a long-running session will produce a single large push.- **Configuration**: Environment variables only; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.diff --git a/docs/en/agent-integrations/17-dsh.md b/docs/en/agent-integrations/17-dsh.mdindex 8b01a9b20..de680c108 100644--- a/docs/en/agent-integrations/17-dsh.md+++ b/docs/en/agent-integrations/17-dsh.md@@ -99,6 +99,8 @@ Behavior knobs live in the profile's Cordis patch entry:commitTokenThreshold: 20000```+`syncTurns: false`, in that same block, makes the integration read-only: it still injects your profile and recalls memories, but sends nothing back — no captured turns, no commits, and no replay of writes an earlier session queued, which stay on the queue until a session that still writes drains them.+`peerSource`, in that same `config` block, decides how the workspace peer is derived. The default `"git"` uses the repository's normalized `origin` URL (`[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`), falling back to the repository root path, so every clone, worktree, and subdirectory of one repository shares a single peer; outside a repository no peer is sent at all, and what is remembered there goes to your user-level space at `viking://user/<you>/memories`. `"cwd"` restores the earlier behavior — the working directory with every non-alphanumeric character replaced by `-` — and `"none"` sends no peer at all. To give a directory outside a repository its own memory, set `OPENVIKING_PEER_ID` for it ([Give a Directory Its Own Peer](../configuration/02-client.md#give-a-directory-its-own-peer)).Credentials given in the patch win over the environment; behavior toggles read the environment first. The full list is documented in the [bundle README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin).diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.mdindex 789edffe0..963f89262 100644--- a/docs/zh/agent-integrations/11-pi.md+++ b/docs/zh/agent-integrations/11-pi.md@@ -86,7 +86,7 @@ node ~/.pi/agent/extensions/openviking/scripts/setup.mjs`peerSource` 决定 workspace peer 的派生方式。默认的 `"git"` 取仓库归一化后的 `origin` URL(`[email protected]:volcengine/OpenViking.git` 得到 `github.com-volcengine-openviking`),其次是仓库根路径,因此同一个仓库的每个 clone、worktree 和子目录共用同一个 peer;不在仓库中则完全不发送 peer,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。`"cwd"` 恢复此前的行为——把工作目录路径中的非字母数字字符全部替换成 `-`;`"none"`(等同于 `OPENVIKING_WORKSPACE_PEER=0`)完全不发送 peer;也可以用 `"team-{dir}"` 这样的模板,或按顺序尝试的模板列表自定义。要让仓库之外的目录拥有独立记忆,请为它设置 `OPENVIKING_PEER_ID`(见[让一个目录拥有独立记忆](../configuration/02-client.md#让一个目录拥有独立记忆))。-Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、archive overview 尚未生成,或 branch 指纹不匹配,pi 会继续保留完整本地历史,或回退到默认 compaction。验证边界推进时可设置 `OV_DEBUG_LOG=/tmp/ov-pi.log`。+Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、archive overview 尚未生成,或 branch 指纹不匹配,pi 会继续保留完整本地历史,或回退到默认 compaction。验证边界推进时可设置 `OPENVIKING_DEBUG_LOG=/tmp/ov-pi.log`,日志按 JSON Lines 写入,每个事件一行。`OV_DEBUG_LOG` 是已弃用的别名,仍然可用。## 验证diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.mdindex e2031fa0a..7aecd4884 100644--- a/docs/zh/agent-integrations/16-capability-reference.md+++ b/docs/zh/agent-integrations/16-capability-reference.md@@ -113,7 +113,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章`examples/memory-plugin-shared/lib/` 下共 23 个 `.mjs` 模块,是 JS 系 harness 的唯一事实源。两种消费形态:-1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1,交叉读行号引用时要换算)。每个目标只发它真正 import 的模块,因此分发清单跟的是 import 图而不是 harness。在每个 hook 型插件都会拿的 13 个 hook 模块(`sync.mjs` 里的 `HOOK_SHARED_FILES`)之上:pi 只拿这一组(13 个);dsh 加 stdio 代理需要的两个 mcp-proxy-*(15 个);opencode 再加 async-writer 与 batch-send(17 个);zcode 在这四个之外再加 agent-hook-runtime 与 agent-uri-guard(19 个);claude-code / codex 在这四个之外再加 plugin-config、workspace-config、workspace-registry 与 doctor-core(各 21 个)。agent-plugins 没有 hook,因此一个 hook 模块都不拿,只有 credentials、debug-log 与两个 mcp-proxy-*(4 个)。当前 HEAD 各目标与 lib 源零漂移。+1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1,交叉读行号引用时要换算)。每个目标只发它真正 import 的模块,因此分发清单跟的是 import 图而不是 harness。在每个 hook 型插件都会拿的 12 个 hook 模块(`sync.mjs` 里的 `HOOK_SHARED_FILES`)之上:pi 加 setup-wizard(13 个);dsh 加 stdio 代理需要的两个 mcp-proxy-*(14 个);opencode 加 setup-wizard、两个 mcp-proxy-* 与 batch-send(16 个);zcode 加两个 mcp-proxy-*、batch-send、async-writer、agent-hook-runtime 与 agent-uri-guard(18 个);claude-code / codex 加 setup-wizard、两个 mcp-proxy-*、batch-send、async-writer、plugin-config、workspace-config、workspace-registry 与 doctor-core(各 21 个)。agent-plugins 没有 hook,因此一个 hook 模块都不拿,只有 credentials、debug-log 与两个 mcp-proxy-*(4 个)。当前 HEAD 各目标与 lib 源零漂移。2. **相对路径直接 import(不复制)**:cursor / trae / trae-cn 直接 `import "../../memory-plugin-shared/lib/..."`;安装器把包与这些 hook 传递 import 到的 15 个共享模块一起复制到 `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`,使相对层级成立。这份安装集合对 import 闭合,不含任何 hook 运行时都够不到的 workspace 配置层。运行期这个共享目录被这几个 harness 共用,任一重装都会整体覆盖。核心模块速览(细节在各维度章展开):@@ -127,7 +127,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章| `batch-send.mjs` | 100 条/批写入 + 404/405 逐条降级 + 连续前缀入队 | cc / codex / opencode + agent-hook 系 || `profile-inject.mjs` | session-start 的 profile + 可用记忆清单注入 | 9 个 harness(openclaw / hermes 除外) || `recall-compress-core.mjs` | 召回压缩 prompt + URI 编辑距离修复 + 缓存 | claude-code |-| `capture-utils.mjs` | 消息归一 + 注入回流防护 + 捕获过滤 | codex / opencode / dsh / pi |+| `capture-utils.mjs` | 消息归一 + 注入回流防护 + 捕获过滤 | codex / opencode / dsh / pi / zcode || `credentials.mjs` | 凭据解析链(详见 [§3.1.3](#_3-1-3-凭据体系)) | 全部 JS 系 || `session-model.mjs` | 会话 id 前缀派生 + bypass glob | 全部 JS 系 || `async-writer.mjs` | 写路径 detach(drain stdin → spawn → approve → write → unref;spawn 失败回落同步) | cc / codex / zcode |@@ -543,7 +543,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可## zcode- **集成文档**:[社区插件 → ZCode](./08-community-plugins.md)-- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。共 vendoring 19 个共享模块,也是唯一 vendoring `agent-hook-runtime` 那一对、而不是相对 import 的 harness。版本 0.1.1。+- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。共 vendoring 18 个共享模块,也是唯一 vendoring `agent-hook-runtime` 那一对、而不是相对 import 的 harness。版本 0.1.2。- **能力亮点**:以 rollout 文件 `~/.zcode/cli/rollout/model-io-<sid>.jsonl` 为增量真相源(`lastTurnId` 差集补齐漏掉的 Stop);Stop 默认 detach(Ctrl+C 不丢写入)。- **行为要点**:每 Stop commit(keep 0);捕获路径仅剥离三类注入块(不做额外文本清洗,[§3.2.6](#_3-2-6-注入回流防护));首次捕获会一次性读取整个 rollout(长会话首装时单次推送量大)。- **配置**:仅 env;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。diff --git a/docs/zh/agent-integrations/17-dsh.md b/docs/zh/agent-integrations/17-dsh.mdindex 99b033e8b..7b0c9243c 100644--- a/docs/zh/agent-integrations/17-dsh.md+++ b/docs/zh/agent-integrations/17-dsh.md@@ -99,6 +99,8 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-sharcommitTokenThreshold: 20000```+同一个 `config` 块里的 `syncTurns: false` 让该集成变成只读:画像注入和记忆召回照常,但什么都不再写回——不捕获对话、不 commit,也不重放此前会话排入队列的写入,那些写入会一直留在队列里,直到某个仍在写入的会话把它们排空。+同一个 `config` 块里的 `peerSource` 决定工作区 peer 的派生方式。默认的 `"git"` 取仓库归一化后的 `origin` URL(`[email protected]:volcengine/OpenViking.git` 得到 `github.com-volcengine-openviking`),其次是仓库根路径,因此同一个仓库的每个 clone、worktree 和子目录共用同一个 peer;不在仓库中则完全不发送 peer,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。`"cwd"` 恢复此前的行为——把工作目录路径中的非字母数字字符全部替换成 `-`;`"none"` 则完全不发送 peer。要让仓库之外的目录拥有独立记忆,请为它设置 `OPENVIKING_PEER_ID`(见[让一个目录拥有独立记忆](../configuration/02-client.md#让一个目录拥有独立记忆))。patch 中写的凭证优先于环境变量;行为开关则优先读环境变量。完整参数列表见[插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin)。diff --git a/examples/dsh-memory-plugin/README.md b/examples/dsh-memory-plugin/README.mdindex 10019ded6..08b560766 100644--- a/examples/dsh-memory-plugin/README.md+++ b/examples/dsh-memory-plugin/README.md@@ -150,6 +150,7 @@ The patch can also carry plugin config:- `session/event` captures user, assistant, and optionally tool-result messages without scraping a transcript.- `turn/end` checks the OpenViking pending-token threshold and commits when required.- `skipSubagentSessions: true` excludes sessions marked with `header.origin: subagent` from automatic profile, recall, capture, and commit; it defaults to `false`.+- `syncTurns: false` stops every write: no captured messages, no threshold or shutdown commit, and no replay of writes an earlier session queued — those stay queued for a session that still writes. Profile injection and recall are unaffected; it defaults to `true`.- Failed writes enter the shared OpenViking pending queue for replay at the next session start.- `tools/pre-execute` blocks DSH filesystem and shell tools from treating `viking://` URIs as local paths, pointing the model at the bridged `mcp__openviking__*` tools instead.diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.jsonindex 3666a7365..fb573980e 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.3.0",+ "version": "0.3.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@openviking/dsh-memory-plugin",- "version": "0.3.0",+ "version": "0.3.1","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.jsonindex 3683ab9dc..b1f230bb3 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.3.0",+ "version": "0.3.1","description": "OpenViking memory and context bundle for DeepSeek Harness","type": "module","main": "index.mjs",diff --git a/examples/dsh-memory-plugin/runtime.mjs b/examples/dsh-memory-plugin/runtime.mjsindex 2dd5dfdca..1dc9f8137 100644--- a/examples/dsh-memory-plugin/runtime.mjs+++ b/examples/dsh-memory-plugin/runtime.mjs@@ -87,10 +87,14 @@ export class OpenVikingRuntime {state.initializationRetryable = isRetryableFailure(ensured);return state;}- await replayPending(- (path, init) => this.client.fetchJSON(path, init),- (stage, data) => this.log(stage, data),- );+ // Replay is a write, so it stays behind the same toggle: a backlog queued+ // while capture was on waits for a session that still writes.+ if (state.config.syncTurns) {+ await replayPending(+ (path, init) => this.client.fetchJSON(path, init),+ (stage, data) => this.log(stage, data),+ );+ }await this.refreshPendingState(state);const profile = await buildProfileBlock((path, init, options) => this.client.fetchJSON(path, init, options),@@ -172,6 +176,7 @@ export class OpenVikingRuntime {maybeCommit(session, event) {if (event.type !== "turn/end") return;const state = this.stateFor(session);+ if (!state.config.syncTurns) return;this.enqueueWrite(state, async () => {if (state.hasPendingWrites) return;if (!state.ready && !(await this.ensureState(state)).ready) return;@@ -204,6 +209,7 @@ export class OpenVikingRuntime {if (state.disposing) return state.disposing;state.disposing = (async () => {this.enqueueWrite(state, async () => {+ if (!state.config.syncTurns) return;const commitPayload = {keep_recent_count: state.config.commitKeepRecentCount,};diff --git a/examples/dsh-memory-plugin/runtime.test.mjs b/examples/dsh-memory-plugin/runtime.test.mjsindex 7f913c8db..517a089d4 100644--- a/examples/dsh-memory-plugin/runtime.test.mjs+++ b/examples/dsh-memory-plugin/runtime.test.mjs@@ -287,6 +287,52 @@ test("disposeAll drains every live session", async () => {assert.equal(runtime.states.size, 0);});+test("syncTurns false sends nothing: no capture, no commit, no dispose flush, no replay", async () => {+ const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-sync-off-"));+ tempDirs.push(pendingDir);+ process.env.OPENVIKING_PENDING_DIR = pendingDir;+ await enqueue("addMessage", "dsh-earlier", { content: "queued while capture was on" });++ const writes = [];+ const runtime = new OpenVikingRuntime({+ async healthResult() {+ return { ok: true };+ },+ async ensureSessionResult() {+ return { ok: true };+ },+ async fetchJSON(path, init) {+ if (init?.method === "POST" && /\/(messages|commit)$/.test(path)) writes.push(path);+ return { ok: false, status: 503, error: { code: "UNAVAILABLE" } };+ },+ async addMessage() {+ writes.push("addMessage");+ return { ok: true };+ },+ async getSession() {+ return { pending_tokens: 1000000 };+ },+ async commitSession() {+ writes.push("commitSession");+ return { ok: true };+ },+ }, { ...config(), syncTurns: false }, { debug() {} });+ const session = { id: "sync-off", header: { cwd: "/workspace" } };++ runtime.capture(session, userEvent("Never sent."));+ runtime.maybeCommit(session, { type: "turn/end" });+ // The recall path reaches initialization even when nothing is captured, and+ // the toggle takes the replay out of it without taking the reads with it.+ assert.equal((await runtime.initialize({ session })).ready, true);+ await runtime.flush(session);+ await runtime.dispose(session);++ assert.deepEqual(writes, []);+ const pending = await listPending();+ assert.deepEqual(pending.map(item => item.entry.sessionId), ["dsh-earlier"]);+ assert.ok(!pending[0].entry.retries);+});+test("the per-session peer honors peerSource", async () => {const root = realpathSync(await mkdtemp(join(tmpdir(), "dsh-memory-peer-")));tempDirs.push(root);diff --git a/examples/dsh-memory-plugin/shared/setup-wizard.mjs b/examples/dsh-memory-plugin/shared/setup-wizard.mjsdeleted file mode 100644index a49dbe7db..000000000--- a/examples/dsh-memory-plugin/shared/setup-wizard.mjs+++ /dev/null@@ -1,114 +0,0 @@-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.-/**- * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.- *- * Lets a pure-marketplace install (no installer script) configure the server- * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:- *- * node <plugin>/scripts/setup.mjs- *- * Conventions: show current values, keep existing secrets on empty input,- * merge-write (never drop unknown fields), back up the previous file, 0600.- */--import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";-import { dirname } from "node:path";-import { createInterface } from "node:readline/promises";-import { loadCredentialFiles } from "./credentials.mjs";--const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";-const LOCAL_URL = "http://127.0.0.1:1933";--function maskSecret(value) {- const s = String(value || "");- if (!s) return "(not set)";- if (s.length <= 8) return "****";- return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;-}--function readJsonSafe(path) {- try {- return JSON.parse(readFileSync(path, "utf-8"));- } catch {- return {};- }-}--export async function runSetupWizard({- input = process.stdin,- output = process.stdout,- env = process.env,-} = {}) {- // cliPath is empty until the file exists; first-run writes go to the candidate- // path (OPENVIKING_CLI_CONFIG_FILE, else ~/.openviking/ovcli.conf).- const { cliPath, cliPathCandidate } = loadCredentialFiles(env);- const targetPath = cliPath || cliPathCandidate;- const current = readJsonSafe(targetPath);- const rl = createInterface({ input, output });- const say = (line = "") => output.write(`${line}\n`);-- try {- say("OpenViking memory plugin setup");- say(`Config file: ${targetPath}`);- say("");- say("Current values:");- say(` url: ${current.url || "(not set)"}`);- say(` api_key: ${maskSecret(current.api_key)}`);- if (current.account) say(` account: ${current.account}`);- if (current.user) say(` user: ${current.user}`);- say("");-- const defaultUrl = current.url || LOCAL_URL;- say("Where do you connect to OpenViking?");- say(` 1) Self-hosted / local [${LOCAL_URL}]`);- say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);- say(` 3) Custom URL / keep current [${defaultUrl}]`);- const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();- let url = defaultUrl;- if (mode === "1") {- url = LOCAL_URL;- } else if (mode === "2") {- url = CLOUD_URL;- } else {- const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();- if (answer) url = answer;- }-- const keyPrompt = current.api_key- ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `- : "API key (leave empty for unauthenticated local mode): ";- const keyAnswer = await rl.question(keyPrompt);- let apiKey = current.api_key || "";- if (keyAnswer === "-") apiKey = "";- else if (keyAnswer.trim()) apiKey = keyAnswer.trim();- else if (!current.api_key) apiKey = "";-- const next = { ...current, url, api_key: apiKey };-- say("");- say("Changes:");- say(` url: ${current.url || "(not set)"} -> ${next.url}`);- say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);- const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();- if (confirm === "n" || confirm === "no") {- say("Aborted; nothing written.");- return { written: false, path: targetPath };- }-- mkdirSync(dirname(targetPath), { recursive: true });- if (existsSync(targetPath)) {- copyFileSync(targetPath, `${targetPath}.bak.${Date.now()}`);- }- writeFileSync(targetPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });- try {- chmodSync(targetPath, 0o600);- } catch {- /* best effort on platforms without chmod semantics */- }- say(`Written: ${targetPath}`);- say("The stdio MCP proxy and hooks pick this up on the next harness start.");- return { written: true, path: targetPath };- } finally {- rl.close();- }-}diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex 7b2fe9cbc..c3e3f5601 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -1320,7 +1320,9 @@ resolve_self_checkout() {local src dirsrc="${BASH_SOURCE[0]}"dir="$(cd "$(dirname "$src")" >/dev/null 2>&1 && pwd -P)" || return 0- if [ -d "$dir/../../.git" ] && [ -d "$dir/../claude-code-memory-plugin" ]; then+ # A linked worktree keeps `.git` as a file pointing at the real gitdir, so+ # test for existence rather than for a directory.+ if [ -e "$dir/../../.git" ] && [ -d "$dir/../claude-code-memory-plugin" ]; thenCHECKOUT_DIR="$(cd "$dir/../.." >/dev/null 2>&1 && pwd -P)"fi}diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjsindex 383fcce25..72d46423b 100644--- a/examples/memory-plugin-shared/sync.mjs+++ b/examples/memory-plugin-shared/sync.mjs@@ -18,7 +18,6 @@ const HOOK_SHARED_FILES = ["session-model.mjs","pending-queue.mjs","debug-log.mjs",- "setup-wizard.mjs","recall-compress-core.mjs","recall-core.mjs","retryable.mjs",@@ -27,24 +26,33 @@ const HOOK_SHARED_FILES = ["profile-inject.mjs","uri-guard.mjs",];+/** The interactive installer, for the plugins that ship a `scripts/setup.mjs`. */+const SETUP_WIZARD_SHARED_FILES = ["setup-wizard.mjs"];/** The stdio MCP proxy, for the plugins that bundle one. */const MCP_PROXY_SHARED_FILES = ["mcp-proxy-core.mjs", "mcp-proxy-config.mjs"];/** Batched session sends, for the plugins that flush off the hook's hot path. */-const BATCH_SHARED_FILES = ["async-writer.mjs", "batch-send.mjs"];+const BATCH_SHARED_FILES = ["batch-send.mjs"];+/** The detached write path, for the plugins whose hooks are short-lived subprocesses. */+const ASYNC_WRITE_SHARED_FILES = ["async-writer.mjs"];/** The layered workspace config, its per-machine registry, and the loader over both. */const WORKSPACE_CONFIG_SHARED_FILES = ["plugin-config.mjs", "workspace-config.mjs", "workspace-registry.mjs"];const DOCTOR_SHARED_FILES = [...HOOK_SHARED_FILES,+ ...SETUP_WIZARD_SHARED_FILES,...MCP_PROXY_SHARED_FILES,...BATCH_SHARED_FILES,+ ...ASYNC_WRITE_SHARED_FILES,...WORKSPACE_CONFIG_SHARED_FILES,"doctor-core.mjs",];-const OPENCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES];-const ZCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES, "agent-hook-runtime.mjs", "agent-uri-guard.mjs"];+// opencode is imported in-process by its host, so it has no hook subprocess to+// detach from: it takes the batch sender without the async write path.+const OPENCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...SETUP_WIZARD_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES];+// dsh and zcode ship no setup entry point, so nothing there calls the wizard.+const ZCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES, ...ASYNC_WRITE_SHARED_FILES, "agent-hook-runtime.mjs", "agent-uri-guard.mjs"];const DSH_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES];-const PI_SHARED_FILES = [...HOOK_SHARED_FILES];+const PI_SHARED_FILES = [...HOOK_SHARED_FILES, ...SETUP_WIZARD_SHARED_FILES];// Agent Plugins 1.0 has no hooks: it is the proxy and nothing else.const AGENT_PLUGINS_SHARED_FILES = ["credentials.mjs", "debug-log.mjs", ...MCP_PROXY_SHARED_FILES];// openclaw assembles recall server-side, so it takes the recall pair alone.diff --git a/examples/opencode-plugin/lib/shared/async-writer.mjs b/examples/opencode-plugin/lib/shared/async-writer.mjsdeleted file mode 100644index 8ffc71468..000000000--- a/examples/opencode-plugin/lib/shared/async-writer.mjs+++ /dev/null@@ -1,78 +0,0 @@-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.-/**- * Async write-path helper for hook-based memory plugins.- *- * When `cfg.writePathAsync` is true and we're not already the worker, we:- * 1. Drain the parent's stdin (the hook payload)- * 2. Emit the harness-specific approve/no-op response on stdout immediately- * 3. Spawn a detached clone of ourselves with env OV_HOOK_WORKER=1- * 4. Feed the drained payload to the worker's stdin, unref, and exit- *- * The worker re-enters the same script, maybeDetach returns false (because- * OV_HOOK_WORKER=1), and the hook's normal synchronous code path reads its- * own stdin and runs the OV HTTP work with nobody waiting.- *- * Call this BEFORE the hook reads stdin itself. When it returns true, the- * caller must `return` out of main() immediately.- */--import { spawn } from "node:child_process";--const WORKER_ENV = "OV_HOOK_WORKER";--export async function maybeDetach(cfg, { approve }) {- if (!cfg.writePathAsync) return false;- if (process.env[WORKER_ENV] === "1") return false;-- // Drain parent stdin so we can forward to the worker.- let raw;- try {- const chunks = [];- for await (const chunk of process.stdin) chunks.push(chunk);- raw = Buffer.concat(chunks);- } catch {- // stdin read failed - let the synchronous path handle it.- return false;- }-- let child;- try {- child = spawn(process.execPath, [process.argv[1]], {- detached: true,- stdio: ["pipe", "ignore", "ignore"],- env: { ...process.env, [WORKER_ENV]: "1" },- });- } catch {- // spawn failed - fall through to sync mode, but we've already drained- // stdin so hand the payload back via env var path below.- process.env.OPENVIKING_HOOK_STDIN_CACHE = raw.toString();- return false;- }-- // Approve first, then write to the detached child. Ordering matters for- // harnesses that read stdout before waiting for the hook process to exit.- approve();-- try {- child.stdin.write(raw);- child.stdin.end();- } catch { /* worker may have already exited; nothing useful to recover */ }- child.unref();- return true;-}--/**- * Fallback stdin reader used when the async path drained stdin but spawn- * failed; hooks should call this instead of reading stdin directly when- * possible so the sync fallback still works after a failed detach.- */-export async function readHookStdin() {- if (process.env.OPENVIKING_HOOK_STDIN_CACHE) {- const cached = process.env.OPENVIKING_HOOK_STDIN_CACHE;- delete process.env.OPENVIKING_HOOK_STDIN_CACHE;- return cached;- }- const chunks = [];- for await (const chunk of process.stdin) chunks.push(chunk);- return Buffer.concat(chunks).toString();-}diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.mdindex 74b6dc924..12e605fba 100644--- a/examples/pi-coding-agent-extension/README.md+++ b/examples/pi-coding-agent-extension/README.md@@ -81,6 +81,7 @@ Credential environment variables:| `OPENVIKING_PEER_ID` | Actor peer id || `OPENVIKING_WORKSPACE_PEER` | Derive an actor peer from the workspace's git identity by default; set `0` to send no peer || `OPENVIKING_RECALL_PEER_SCOPE` | `all` recalls other project memories with a score penalty; `actor` only sees global plus the current project |+| `OPENVIKING_DEBUG_LOG` | Write JSON Lines debug records to this path. `OV_DEBUG_LOG` is a deprecated alias kept for existing setups |Recall asks the server to assemble the context block in one request(`POST /api/v1/search/search` with `mode="context"`), so token budgeting, detail@@ -193,6 +194,7 @@ recent live tail.|--------------------------|------------|--------------------------------------------------------------------------|| `bypassPatterns` | `[]` | Glob patterns to skip extension processing || `logLevel` | `"error"` | `"silent"`, `"error"`, or `"info"` |+| `debugLogPath` | `""` | Write JSON Lines debug records to this path; empty disables the log |## Architecture@@ -322,7 +324,7 @@ All TypeScript files are loaded directly by pi's built-in `jiti` transpiler —| Tools not showing after `pi -c` resume | Known pi issue (tools not re-registered on resume) | Workaround built in — tools register in `before_agent_start`|| Extension crashes on load | Wrong OV server URL or network issue | Check `logLevel` and server accessibility || No memories extracted | Wrong embedding/extraction model in OV config | Check OV's `embedding` / `vlm` configuration |-| Takeover never advances | Pending addMessage replay, commit, or overview polling failed | Set `OV_DEBUG_LOG=/tmp/ov-pi.log` and retry `/viking commit` |+| Takeover never advances | Pending addMessage replay, commit, or overview polling failed | Set `OPENVIKING_DEBUG_LOG=/tmp/ov-pi.log` and retry `/viking commit` |## Licensediff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.tsindex a23367c2a..5d5fa432e 100644--- a/examples/pi-coding-agent-extension/config.ts+++ b/examples/pi-coding-agent-extension/config.ts@@ -46,6 +46,7 @@ export interface OVConfig {captureAssistantTurns: boolean;bypassPatterns: string[];logLevel: "silent" | "error" | "info";+ debugLogPath: string;}const DEFAULT_CONFIG: OVConfig = {@@ -91,6 +92,7 @@ const DEFAULT_CONFIG: OVConfig = {captureAssistantTurns: true,bypassPatterns: [],logLevel: "error",+ debugLogPath: "",};export function loadConfigFromModuleUrl(moduleUrl: string): OVConfig {@@ -154,6 +156,10 @@ export function loadConfig(extensionDir: string): OVConfig {if (process.env.OPENVIKING_RECALL_LEDGER !== undefined) {config.recallLedger = envBool(process.env.OPENVIKING_RECALL_LEDGER, config.recallLedger);}+ // OPENVIKING_DEBUG_LOG is the shared spelling; OV_DEBUG_LOG is pi's older+ // name, kept working so existing setups still log.+ const debugLogEnv = process.env.OPENVIKING_DEBUG_LOG || process.env.OV_DEBUG_LOG;+ if (debugLogEnv) config.debugLogPath = debugLogEnv;config.recallLimit = clampInt(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);config.recallMaxContentChars = clampInt(config.recallMaxContentChars, 100, 5000, DEFAULT_CONFIG.recallMaxContentChars);@@ -177,6 +183,7 @@ export function loadConfig(extensionDir: string): OVConfig {config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto";config.recallLedger = config.recallLedger !== false;if (!Array.isArray(config.bypassPatterns)) config.bypassPatterns = [];+ config.debugLogPath = typeof config.debugLogPath === "string" ? config.debugLogPath.trim() : "";config.peerId = resolveEffectivePeerId({ cfg: config as any, cwd: process.cwd() }).peerId;return config;}diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.tsindex 618220991..0c6222d50 100644--- a/examples/pi-coding-agent-extension/index.ts+++ b/examples/pi-coding-agent-extension/index.ts@@ -10,8 +10,7 @@* (most mature, production-hardened), Hermes (anti-pattern: stale prefetch).*/import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";-import { appendFileSync, mkdirSync } from "node:fs";-import { dirname } from "node:path";+import { createLogger } from "./shared/debug-log.mjs";import { loadConfigFromModuleUrl, type OVConfig } from "./config.js";import { OVClient } from "./client.js";import { RecallManager } from "./recall.js";@@ -40,17 +39,14 @@ export default async function (pi: ExtensionAPI) {// caches (#4137); it is per pi session and opened once the id is known.config.recallLedger ? new RecallLedger() : null,);- const debugLog = (message: string) => {- const file = process.env.OV_DEBUG_LOG;- if (!file) return;- try {- mkdirSync(dirname(file), { recursive: true });- appendFileSync(file, `${new Date().toISOString()} ${message}\n`);- } catch {- // Best effort; logging must never affect pi.- }- };- const takeover = createTakeoverManager({ pi, client, sync, config, log: debugLog });+ const logger = createLogger("pi", {+ debug: Boolean(config.debugLogPath),+ debugLogPath: config.debugLogPath,+ });+ const takeover = createTakeoverManager({+ pi, client, sync, config,+ log: (message: string) => logger.log("takeover", message),+ });// Session statelet connected = false;@@ -142,7 +138,7 @@ export default async function (pi: ExtensionAPI) {// before_agent_start awaits the same in-flight chain before the first// provider request — the first turn still gets profile + recall.void start(ctx).catch((error) => {- debugLog(`session_start: ${error instanceof Error ? error.message : String(error)}`);+ logger.logError("session_start", error);});});@@ -236,7 +232,7 @@ export default async function (pi: ExtensionAPI) {const branch = ctx.sessionManager.getBranch();const result = await sync.syncBranch(branch);- debugLog(`turn_end: synced ${result.added} entries, ~${result.tokens} tokens`);+ logger.log("turn_end", { added: result.added, tokens: result.tokens });await takeover.onTurnSynced(result.tokens);updateStatus(ctx, connected, result.added, sync.sessionId, config, takeover.state);});diff --git a/examples/pi-coding-agent-extension/shared/debug-log.d.mts b/examples/pi-coding-agent-extension/shared/debug-log.d.mtsnew file mode 100644index 000000000..7c44ca656--- /dev/null+++ b/examples/pi-coding-agent-extension/shared/debug-log.d.mts@@ -0,0 +1,7 @@+export declare function createLogger(+ hookName: string,+ overrideCfg?: { debug?: boolean; debugLogPath?: string },+): {+ log(stage: string, data?: unknown): void;+ logError(stage: string, err: unknown): void;+};diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.tsindex 296f6b405..fc754ea07 100644--- a/examples/pi-coding-agent-extension/sync.ts+++ b/examples/pi-coding-agent-extension/sync.ts@@ -1,6 +1,5 @@import type { OVClient } from "./client.js";-import { appendFileSync, mkdirSync } from "node:fs";-import { dirname } from "node:path";+import { createLogger } from "./shared/debug-log.mjs";import type { OVConfig } from "./config.js";import { deriveHarnessSessionId } from "./shared/session-model.mjs";import { enqueue, listPending, replayPending } from "./shared/pending-queue.mjs";@@ -20,26 +19,20 @@ export interface SyncBranchResult {allDelivered: boolean;}-function debugLog(message: string): void {- const file = process.env.OV_DEBUG_LOG;- if (!file) return;- try {- mkdirSync(dirname(file), { recursive: true });- appendFileSync(file, `${new Date().toISOString()} ${message}\n`);- } catch {- // Best effort; logging must never affect pi.- }-}-export class SyncManager {private client: OVClient;private config: OVConfig;+ private logger: ReturnType<typeof createLogger>;private ovSessionId: string | null = null;private syncedEntryCount = 0;constructor(client: OVClient, config: OVConfig) {this.client = client;this.config = config;+ this.logger = createLogger("pi", {+ debug: Boolean(config.debugLogPath),+ debugLogPath: config.debugLogPath,+ });}get sessionId(): string | null { return this.ovSessionId; }@@ -62,8 +55,7 @@ export class SyncManager {if (!this.client.connected) return;await replayPending((path: string, init?: any) => this.client.fetchJSON(path, init, 10000),- (stage: string, data: unknown) =>- debugLog(`${stage}: ${JSON.stringify(data)}`),+ (stage: string, data: unknown) => this.logger.log(stage, data),);}@@ -123,11 +115,13 @@ export class SyncManager {);const result = response.result;if (!result) {- debugLog(- `commit: session=${this.ovSessionId} ok=false status=${response.status ?? 0} ` +- `trace_id=${response.traceId || "none"} ` +- `error=${response.error?.message || response.error?.code || "unknown"}`,- );+ this.logger.log("commit", {+ session: this.ovSessionId,+ ok: false,+ status: response.status ?? 0,+ trace_id: response.traceId || "none",+ error: response.error?.message || response.error?.code || "unknown",+ });if (opts.queueOnFailure !== false) {await enqueue("commitSession", this.ovSessionId, {keep_recent_count: opts.keepRecentCount ?? this.config.commitKeepRecentCount,@@ -135,9 +129,11 @@ export class SyncManager {}return null;}- debugLog(- `commit: session=${this.ovSessionId} ok=true trace_id=${result.trace_id || "none"}`,- );+ this.logger.log("commit", {+ session: this.ovSessionId,+ ok: true,+ trace_id: result.trace_id || "none",+ });return result;}diff --git a/examples/pi-coding-agent-extension/tests/config.test.mjs b/examples/pi-coding-agent-extension/tests/config.test.mjsindex e2ad5fe00..1fbd66d2a 100644--- a/examples/pi-coding-agent-extension/tests/config.test.mjs+++ b/examples/pi-coding-agent-extension/tests/config.test.mjs@@ -19,6 +19,8 @@ async function withConfigFile(body, fn, env = {}, cliConfig = null) {OPENVIKING_CREDENTIAL_SOURCE: process.env.OPENVIKING_CREDENTIAL_SOURCE,OPENVIKING_CLI_CONFIG_FILE: process.env.OPENVIKING_CLI_CONFIG_FILE,OPENVIKING_CONFIG_FILE: process.env.OPENVIKING_CONFIG_FILE,+ OPENVIKING_DEBUG_LOG: process.env.OPENVIKING_DEBUG_LOG,+ OV_DEBUG_LOG: process.env.OV_DEBUG_LOG,};process.env.OPENVIKING_CREDENTIAL_SOURCE = "env";process.env.OPENVIKING_URL = "http://127.0.0.1:1933";@@ -30,6 +32,8 @@ async function withConfigFile(body, fn, env = {}, cliConfig = null) {delete process.env.OPENVIKING_PEER_ID;delete process.env.OPENVIKING_WORKSPACE_PEER;delete process.env.OPENVIKING_RECALL_PEER_SCOPE;+ delete process.env.OPENVIKING_DEBUG_LOG;+ delete process.env.OV_DEBUG_LOG;for (const [key, value] of Object.entries(env)) {if (value === undefined) delete process.env[key];else process.env[key] = value;@@ -167,6 +171,39 @@ test("loadConfig gives environment peer precedence over config peer", async () =}, { OPENVIKING_PEER_ID: "explicit-peer" });});+test("loadConfig leaves the debug log off when nothing asks for it", async () => {+ await withConfigFile({}, (cfg) => {+ assert.equal(cfg.debugLogPath, "");+ });+});++test("loadConfig reads the debug log path from OPENVIKING_DEBUG_LOG", async () => {+ await withConfigFile({}, (cfg) => {+ assert.equal(cfg.debugLogPath, "/tmp/ov-pi-shared.log");+ }, { OPENVIKING_DEBUG_LOG: "/tmp/ov-pi-shared.log" });+});++test("loadConfig still honours the deprecated OV_DEBUG_LOG", async () => {+ await withConfigFile({}, (cfg) => {+ assert.equal(cfg.debugLogPath, "/tmp/ov-pi-legacy.log");+ }, { OV_DEBUG_LOG: "/tmp/ov-pi-legacy.log" });+});++test("loadConfig prefers OPENVIKING_DEBUG_LOG over the deprecated alias", async () => {+ await withConfigFile({ debugLogPath: "/tmp/ov-pi-file.log" }, (cfg) => {+ assert.equal(cfg.debugLogPath, "/tmp/ov-pi-shared.log");+ }, {+ OPENVIKING_DEBUG_LOG: "/tmp/ov-pi-shared.log",+ OV_DEBUG_LOG: "/tmp/ov-pi-legacy.log",+ });+});++test("loadConfig falls back to the config file debug log path", async () => {+ await withConfigFile({ debugLogPath: " /tmp/ov-pi-file.log " }, (cfg) => {+ assert.equal(cfg.debugLogPath, "/tmp/ov-pi-file.log");+ });+});+test("loadConfig gives ovcli peer precedence over config peer", async () => {await withConfigFile({peerId: "config-peer",diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjsindex 150c450e3..b3a5db4ee 100644--- a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs@@ -62,60 +62,57 @@ test("syncBranch returns added token accounting and delivered status", async ()});});+async function readLastRecord(path) {+ const lines = (await readFile(path, "utf8")).trim().split("\n");+ return JSON.parse(lines[lines.length - 1]);+}+test("commit writes success trace_id to the pi debug log", async () => {await withPendingDir(async (dir) => {- const previous = process.env.OV_DEBUG_LOG;const debugLogPath = join(dir, "pi-debug.log");- process.env.OV_DEBUG_LOG = debugLogPath;- try {- const c = client({- commitSessionResponse: async () => ({- result: {- task_id: "t-trace",- archive_uri: "viking://archive/trace",- trace_id: "trace-pi-commit",- },- traceId: "trace-pi-commit",- }),- });- const sync = new SyncManager(c, config());- await sync.ensureSession("pi-trace-session");-- const result = await sync.commit();- assert.equal(result.trace_id, "trace-pi-commit");- assert.match(await readFile(debugLogPath, "utf8"), /trace_id=trace-pi-commit/);- } finally {- if (previous === undefined) delete process.env.OV_DEBUG_LOG;- else process.env.OV_DEBUG_LOG = previous;- }+ const c = client({+ commitSessionResponse: async () => ({+ result: {+ task_id: "t-trace",+ archive_uri: "viking://archive/trace",+ trace_id: "trace-pi-commit",+ },+ traceId: "trace-pi-commit",+ }),+ });+ const sync = new SyncManager(c, config({ debugLogPath }));+ await sync.ensureSession("pi-trace-session");++ const result = await sync.commit();+ assert.equal(result.trace_id, "trace-pi-commit");+ const record = await readLastRecord(debugLogPath);+ assert.equal(record.hook, "pi");+ assert.equal(record.stage, "commit");+ assert.equal(record.data.ok, true);+ assert.equal(record.data.trace_id, "trace-pi-commit");});});test("commit writes failure trace_id to the pi debug log", async () => {await withPendingDir(async (dir) => {- const previous = process.env.OV_DEBUG_LOG;const debugLogPath = join(dir, "pi-debug-error.log");- process.env.OV_DEBUG_LOG = debugLogPath;- try {- const c = client({- commitSessionResponse: async () => ({- result: null,- status: 500,- traceId: "trace-pi-error",- error: { message: "commit failed" },- }),- });- const sync = new SyncManager(c, config());- await sync.ensureSession("pi-trace-error");-- assert.equal(await sync.commit({ queueOnFailure: false }), null);- const raw = await readFile(debugLogPath, "utf8");- assert.match(raw, /trace_id=trace-pi-error/);- assert.match(raw, /error=commit failed/);- } finally {- if (previous === undefined) delete process.env.OV_DEBUG_LOG;- else process.env.OV_DEBUG_LOG = previous;- }+ const c = client({+ commitSessionResponse: async () => ({+ result: null,+ status: 500,+ traceId: "trace-pi-error",+ error: { message: "commit failed" },+ }),+ });+ const sync = new SyncManager(c, config({ debugLogPath }));+ await sync.ensureSession("pi-trace-error");++ assert.equal(await sync.commit({ queueOnFailure: false }), null);+ const record = await readLastRecord(debugLogPath);+ assert.equal(record.stage, "commit");+ assert.equal(record.data.ok, false);+ assert.equal(record.data.trace_id, "trace-pi-error");+ assert.equal(record.data.error, "commit failed");});});diff --git a/examples/zcode-memory-plugin/openviking.integration.json b/examples/zcode-memory-plugin/openviking.integration.jsonindex 1b9170959..5bd99e47a 100644--- a/examples/zcode-memory-plugin/openviking.integration.json+++ b/examples/zcode-memory-plugin/openviking.integration.json@@ -1,7 +1,7 @@{"schemaVersion": 1,"id": "openviking-memory",- "version": "0.1.1",+ "version": "0.1.2","clients": ["zcode"],"capabilities": ["hooks", "mcp"]}diff --git a/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjs b/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjsdeleted file mode 100644index a49dbe7db..000000000--- a/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjs+++ /dev/null@@ -1,114 +0,0 @@-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.-/**- * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.- *- * Lets a pure-marketplace install (no installer script) configure the server- * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:- *- * node <plugin>/scripts/setup.mjs- *- * Conventions: show current values, keep existing secrets on empty input,- * merge-write (never drop unknown fields), back up the previous file, 0600.- */--import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";-import { dirname } from "node:path";-import { createInterface } from "node:readline/promises";-import { loadCredentialFiles } from "./credentials.mjs";--const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";-const LOCAL_URL = "http://127.0.0.1:1933";--function maskSecret(value) {- const s = String(value || "");- if (!s) return "(not set)";- if (s.length <= 8) return "****";- return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;-}--function readJsonSafe(path) {- try {- return JSON.parse(readFileSync(path, "utf-8"));- } catch {- return {};- }-}--export async function runSetupWizard({- input = process.stdin,- output = process.stdout,- env = process.env,-} = {}) {- // cliPath is empty until the file exists; first-run writes go to the candidate- // path (OPENVIKING_CLI_CONFIG_FILE, else ~/.openviking/ovcli.conf).- const { cliPath, cliPathCandidate } = loadCredentialFiles(env);- const targetPath = cliPath || cliPathCandidate;- const current = readJsonSafe(targetPath);- const rl = createInterface({ input, output });- const say = (line = "") => output.write(`${line}\n`);-- try {- say("OpenViking memory plugin setup");- say(`Config file: ${targetPath}`);- say("");- say("Current values:");- say(` url: ${current.url || "(not set)"}`);- say(` api_key: ${maskSecret(current.api_key)}`);- if (current.account) say(` account: ${current.account}`);- if (current.user) say(` user: ${current.user}`);- say("");-- const defaultUrl = current.url || LOCAL_URL;- say("Where do you connect to OpenViking?");- say(` 1) Self-hosted / local [${LOCAL_URL}]`);- say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);- say(` 3) Custom URL / keep current [${defaultUrl}]`);- const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();- let url = defaultUrl;- if (mode === "1") {- url = LOCAL_URL;- } else if (mode === "2") {- url = CLOUD_URL;- } else {- const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();- if (answer) url = answer;- }-- const keyPrompt = current.api_key- ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `- : "API key (leave empty for unauthenticated local mode): ";- const keyAnswer = await rl.question(keyPrompt);- let apiKey = current.api_key || "";- if (keyAnswer === "-") apiKey = "";- else if (keyAnswer.trim()) apiKey = keyAnswer.trim();- else if (!current.api_key) apiKey = "";-- const next = { ...current, url, api_key: apiKey };-- say("");- say("Changes:");- say(` url: ${current.url || "(not set)"} -> ${next.url}`);- say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);- const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();- if (confirm === "n" || confirm === "no") {- say("Aborted; nothing written.");- return { written: false, path: targetPath };- }-- mkdirSync(dirname(targetPath), { recursive: true });- if (existsSync(targetPath)) {- copyFileSync(targetPath, `${targetPath}.bak.${Date.now()}`);- }- writeFileSync(targetPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });- try {- chmodSync(targetPath, 0o600);- } catch {- /* best effort on platforms without chmod semantics */- }- say(`Written: ${targetPath}`);- say("The stdio MCP proxy and hooks pick this up on the next harness start.");- return { written: true, path: targetPath };- } finally {- rl.close();- }-}diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.mjs b/examples/zcode-memory-plugin/scripts/zcode-capture.mjsindex 29ca5fea0..13efb2e48 100644--- a/examples/zcode-memory-plugin/scripts/zcode-capture.mjs+++ b/examples/zcode-memory-plugin/scripts/zcode-capture.mjs@@ -1,4 +1,5 @@import { stableHash } from "./shared/agent-hook-runtime.mjs";+import { shouldCaptureText } from "./shared/capture-utils.mjs";import { cleanZcodeText } from "./zcode-turns.mjs";export function zcodeTurnDedupKey(turn) {@@ -7,18 +8,22 @@ export function zcodeTurnDedupKey(turn) {: stableHash(turn.role, turn.content);}-export function buildZcodeCapturePlan(turns, state = {}) {+export function buildZcodeCapturePlan(turns, state = {}, cfg = {}) {const capturedTurnIds = new Set(Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],);- const candidates = turns.map((turn) => ({- dedupKey: zcodeTurnDedupKey(turn),- turn,- }));+ const candidates = [];+ for (const turn of turns) {+ const decision = shouldCaptureText(turn.content, turn.role, cfg);+ if (!decision.shouldCapture) continue;+ // The dedup key stays keyed on the raw turn so raising captureMaxLength+ // never resends a turn the server already holds in truncated form.+ candidates.push({ dedupKey: zcodeTurnDedupKey(turn), turn, content: decision.text });+ }const toSend = candidates.filter((item) => !capturedTurnIds.has(item.dedupKey));- const payloads = toSend.map(({ turn }) => ({+ const payloads = toSend.map(({ turn, content }) => ({role: turn.role,- content: turn.content,+ content,...(turn.turnId ? { turn_id: turn.turnId } : {}),}));return { candidates, toSend, payloads };diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjsindex 15d4b0487..1e1bd7fb7 100644--- a/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs+++ b/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs@@ -20,6 +20,59 @@ test("capture plan maps host identity to the OpenViking turn_id contract", () =>assert.equal(plan.payloads[0].turnId, undefined);});+test("acknowledgements and slash commands never reach the server", () => {+ const plan = buildZcodeCapturePlan([+ { role: "user", content: "/compact", turnId: "turn-001" },+ { role: "assistant", content: "好的", turnId: "turn-001" },+ { role: "user", content: "real question", turnId: "turn-002" },+ { role: "assistant", content: "real answer", turnId: "turn-002" },+ ], {});+ assert.deepEqual(plan.payloads, [+ { role: "user", content: "real question", turn_id: "turn-002" },+ { role: "assistant", content: "real answer", turn_id: "turn-002" },+ ]);+});++test("injected blocks cleanZcodeText does not know are stripped before sending", () => {+ const plan = buildZcodeCapturePlan([{+ role: "assistant",+ content: "answer body <relevant-memory score=\"0.9\">recalled</relevant-memory>",+ turnId: "turn-001",+ }], {});+ assert.ok(!plan.payloads[0].content.includes("recalled"));+ assert.ok(plan.payloads[0].content.startsWith("answer body"));+});++test("a fully filtered turn still lets the cursor advance past it", () => {+ const turnsWithNoise = [+ { role: "user", content: "ok", turnId: "turn-001" },+ { role: "user", content: "real question", turnId: "turn-002" },+ { role: "assistant", content: "real answer", turnId: "turn-002" },+ ];+ const plan = buildZcodeCapturePlan(turnsWithNoise, {});+ const next = applyZcodeCaptureResult({}, plan, { sent: 2, queued: 0, failed: 0 });+ assert.equal(next.lastTurnId, "turn-002");+});++test("oversized turns are truncated to captureMaxLength before they are sent", () => {+ const long = "a question that repeats. ".repeat(100);+ const plan = buildZcodeCapturePlan(+ [{ role: "user", content: long, turnId: "turn-001" }],+ {},+ { captureMaxLength: 200 },+ );+ assert.equal(plan.payloads.length, 1);+ assert.ok(plan.payloads[0].content.length <= 200);+ assert.ok(plan.payloads[0].content.endsWith("[truncated]"));+ // Without a host turn id the key is hashed from the turn itself, so it must+ // follow the raw text: a later captureMaxLength cannot make the turn look new.+ const hashed = [{ role: "user", content: long }];+ const narrow = buildZcodeCapturePlan(hashed, {}, { captureMaxLength: 200 });+ const wider = buildZcodeCapturePlan(hashed, {}, { captureMaxLength: 24000 });+ assert.equal(wider.candidates[0].dedupKey, narrow.candidates[0].dedupKey);+ assert.equal(wider.payloads[0].content, long.trim());+});+test("non-retryable failure keeps cursor, dedup, and pending prompt unchanged", () => {const state = {lastTurnId: "turn-000",diff --git a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs b/examples/zcode-memory-plugin/scripts/zcode-hook.mjsindex 328115555..f6f14c9c3 100644--- a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs+++ b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs@@ -138,7 +138,7 @@ async function main() {if (!cfg.autoCapture) return;await withAgentHookLock("zcode", nativeSessionId, async () => {state = await readHookState("zcode", nativeSessionId);- const plan = buildZcodeCapturePlan(buildZcodeTurns(input, state), state);+ const plan = buildZcodeCapturePlan(buildZcodeTurns(input, state), state, cfg);// Fail-closed: if no turns and no dedup keys, skip silently (not an error —// could be a Stop with no new content, or a race with UserPromptSubmit).diff --git a/examples/zcode-memory-plugin/servers/mcp-proxy.mjs b/examples/zcode-memory-plugin/servers/mcp-proxy.mjsindex 69cce31e8..3e4f508a2 100644--- a/examples/zcode-memory-plugin/servers/mcp-proxy.mjs+++ b/examples/zcode-memory-plugin/servers/mcp-proxy.mjs@@ -5,12 +5,12 @@ import { resolve as resolvePath } from "node:path";import { loadAgentHookConfig } from "../scripts/shared/agent-hook-runtime.mjs";import { createLogger } from "../scripts/shared/debug-log.mjs";-import { resolveMcpActorPeerId } from "../scripts/shared/mcp-proxy-config.mjs";+import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../scripts/shared/mcp-proxy-config.mjs";import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";function readConfig() {const cfg = loadAgentHookConfig("zcode");- return {+ return buildMcpProxyConfig({mcpUrl: cfg.mcpUrl,apiKey: cfg.apiKey,account: cfg.account,@@ -22,8 +22,8 @@ function readConfig() {debugLogPath: cfg.debugLogPath,credentialSource: cfg.credentialSource,credentialPath: cfg.cliPath || cfg.ovPath || "",- watchedPaths: [cfg.cliPath, cfg.ovPath].filter(Boolean),- };+ watchedPaths: [cfg.cliPath, cfg.ovPath],+ });}if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {