Skip to content

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

fix(zcode): make memory capture reliable (#3728)

t0sakif08293411d2c
diff --git a/.github/scripts/stage-memory-plugin-marketplace.sh b/.github/scripts/stage-memory-plugin-marketplace.sh
new file mode 100644
index 000000000..af0e9f4a8
--- /dev/null
+++ b/.github/scripts/stage-memory-plugin-marketplace.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
+STAGE="${1:?usage: stage-memory-plugin-marketplace.sh <stage-dir>}"
+
+rm -rf "${STAGE}"
+mkdir -p "${STAGE}"
+cp -R \
+ "${ROOT}/examples/.claude-plugin" \
+ "${ROOT}/examples/.agents" \
+ "${ROOT}/examples/claude-code-memory-plugin" \
+ "${ROOT}/examples/codex-memory-plugin" \
+ "${ROOT}/examples/cursor-memory-plugin" \
+ "${ROOT}/examples/trae-memory-hooks" \
+ "${ROOT}/examples/zcode-memory-plugin" \
+ "${ROOT}/examples/opencode-plugin" \
+ "${ROOT}/examples/pi-coding-agent-extension" \
+ "${ROOT}/examples/memory-plugin-shared" \
+ "${STAGE}/"
+
+for required in \
+ cursor-memory-plugin/.cursor-plugin/plugin.json \
+ cursor-memory-plugin/hooks/hooks.json \
+ cursor-memory-plugin/.mcp.json \
+ cursor-memory-plugin/openviking.integration.json \
+ cursor-memory-plugin/scripts/cursor-hook.mjs \
+ cursor-memory-plugin/scripts/session-start.mjs \
+ cursor-memory-plugin/scripts/auto-recall.mjs \
+ cursor-memory-plugin/scripts/auto-capture.mjs \
+ cursor-memory-plugin/scripts/pre-compact.mjs \
+ cursor-memory-plugin/scripts/session-end.mjs \
+ cursor-memory-plugin/scripts/cursor-transcript.mjs \
+ cursor-memory-plugin/scripts/uri-guard.mjs \
+ cursor-memory-plugin/servers/mcp-proxy.mjs \
+ cursor-memory-plugin/rules/openviking-memory.mdc \
+ cursor-memory-plugin/skills/openviking-memory/SKILL.md \
+ trae-memory-hooks/hooks/hooks.json \
+ trae-memory-hooks/.mcp.json \
+ trae-memory-hooks/openviking.integration.json \
+ trae-memory-hooks/scripts/trae-hook.mjs \
+ trae-memory-hooks/scripts/session-start.mjs \
+ trae-memory-hooks/scripts/auto-recall.mjs \
+ trae-memory-hooks/scripts/auto-capture.mjs \
+ trae-memory-hooks/scripts/trae-turns.mjs \
+ trae-memory-hooks/scripts/uri-guard.mjs \
+ trae-memory-hooks/servers/mcp-proxy.mjs \
+ zcode-memory-plugin/.zcode-plugin/plugin.json \
+ zcode-memory-plugin/hooks/hooks.json \
+ zcode-memory-plugin/.mcp.json \
+ zcode-memory-plugin/openviking.integration.json \
+ zcode-memory-plugin/scripts/zcode-hook.mjs \
+ zcode-memory-plugin/scripts/zcode-capture.mjs \
+ zcode-memory-plugin/scripts/zcode-turns.mjs \
+ zcode-memory-plugin/scripts/shared/async-writer.mjs \
+ zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs \
+ zcode-memory-plugin/scripts/shared/batch-send.mjs \
+ zcode-memory-plugin/servers/mcp-proxy.mjs \
+ memory-plugin-shared/lib/agent-hook-runtime.mjs \
+ memory-plugin-shared/lib/agent-uri-guard.mjs \
+ memory-plugin-shared/lib/async-writer.mjs \
+ memory-plugin-shared/lib/uri-guard.mjs \
+ memory-plugin-shared/lib/mcp-proxy-core.mjs; do
+ test -f "${STAGE}/${required}" || {
+ echo "Marketplace archive is missing ${required}" >&2
+ exit 1
+ }
+done
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 319c3c1db..926c59098 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -43,10 +43,15 @@ jobs:
examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs \
examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs \
examples/trae-memory-hooks/scripts/trae-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 \
+ examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs \
examples/memory-plugin-shared/batch-send.test.mjs \
examples/memory-plugin-shared/install-agent-hooks.test.mjs \
examples/memory-plugin-shared/install-opencode-jsonc.test.mjs \
examples/memory-plugin-shared/install-tui.test.mjs \
+ examples/memory-plugin-shared/release-marketplace.test.mjs \
examples/memory-plugin-shared/sync.test.mjs \
examples/memory-plugin-shared/recall-core.test.mjs \
examples/memory-plugin-shared/workspace-peer.test.mjs \
@@ -57,6 +62,7 @@ jobs:
- name: Check installer scripts parse
run: |
+ bash -n .github/scripts/stage-memory-plugin-marketplace.sh
bash -n examples/memory-plugin-shared/install.sh
bash -n examples/claude-code-memory-plugin/setup-helper/install.sh
bash -n examples/claude-code-memory-plugin/setup-helper/tos-install.sh
diff --git a/.github/workflows/release-tos.yml b/.github/workflows/release-tos.yml
index 9ce9fdd19..32d095b09 100644
--- a/.github/workflows/release-tos.yml
+++ b/.github/workflows/release-tos.yml
@@ -82,48 +82,7 @@ jobs:
# The shared installer registers the unzipped directory as a local
# marketplace for both Claude Code and Codex (GitHub-free path).
STAGE=/tmp/memory-plugin-marketplace
- rm -rf "${STAGE}"
- mkdir -p "${STAGE}"
- cp -R examples/.claude-plugin examples/.agents \
- examples/claude-code-memory-plugin examples/codex-memory-plugin \
- examples/cursor-memory-plugin examples/trae-memory-hooks \
- examples/opencode-plugin examples/pi-coding-agent-extension \
- examples/memory-plugin-shared "${STAGE}/"
- for required in \
- cursor-memory-plugin/.cursor-plugin/plugin.json \
- cursor-memory-plugin/hooks/hooks.json \
- cursor-memory-plugin/.mcp.json \
- cursor-memory-plugin/openviking.integration.json \
- cursor-memory-plugin/scripts/cursor-hook.mjs \
- cursor-memory-plugin/scripts/session-start.mjs \
- cursor-memory-plugin/scripts/auto-recall.mjs \
- cursor-memory-plugin/scripts/auto-capture.mjs \
- cursor-memory-plugin/scripts/pre-compact.mjs \
- cursor-memory-plugin/scripts/session-end.mjs \
- cursor-memory-plugin/scripts/cursor-transcript.mjs \
- cursor-memory-plugin/scripts/uri-guard.mjs \
- cursor-memory-plugin/servers/mcp-proxy.mjs \
- cursor-memory-plugin/rules/openviking-memory.mdc \
- cursor-memory-plugin/skills/openviking-memory/SKILL.md \
- trae-memory-hooks/hooks/hooks.json \
- trae-memory-hooks/.mcp.json \
- trae-memory-hooks/openviking.integration.json \
- trae-memory-hooks/scripts/trae-hook.mjs \
- trae-memory-hooks/scripts/session-start.mjs \
- trae-memory-hooks/scripts/auto-recall.mjs \
- trae-memory-hooks/scripts/auto-capture.mjs \
- trae-memory-hooks/scripts/trae-turns.mjs \
- trae-memory-hooks/scripts/uri-guard.mjs \
- trae-memory-hooks/servers/mcp-proxy.mjs \
- memory-plugin-shared/lib/agent-hook-runtime.mjs \
- memory-plugin-shared/lib/agent-uri-guard.mjs \
- memory-plugin-shared/lib/uri-guard.mjs \
- memory-plugin-shared/lib/mcp-proxy-core.mjs; do
- test -f "${STAGE}/${required}" || {
- echo "::error::Marketplace archive is missing ${required}"
- exit 1
- }
- done
+ bash .github/scripts/stage-memory-plugin-marketplace.sh "${STAGE}"
(cd /tmp && zip -rq "memory-plugin-marketplace-${RELEASE_TAG}.zip" memory-plugin-marketplace)
- name: Build marketplace git repo (dumb HTTP)
diff --git a/docs/design/zcode-memory-plugin-design.md b/docs/design/zcode-memory-plugin-design.md
deleted file mode 100644
index ab9220255..000000000
--- a/docs/design/zcode-memory-plugin-design.md
+++ /dev/null
@@ -1,288 +0,0 @@
-# Spec: ZCode Memory Plugin for OpenViking
-
-> **Status**: Draft — pending local verification on a live ZCode install.
-> **Related**: Closes [#3127](https://github.com/volcengine/OpenViking/issues/3127), [#3442](https://github.com/volcengine/OpenViking/issues/3442); supersedes draft PR [#3544](https://github.com/volcengine/OpenViking/pull/3544) with verified ZCode extension-surface facts.
-> **Authored against**: upstream `main` @ `c4d2b27c` (2026-07-31).
-
----
-
-## Problem Statement
-
-ZCode is an AI coding agent (the one shipped with the GLM model family) that has no OpenViking memory integration. Users who run OpenViking as their context database get automatic recall and capture in Claude Code, Codex, Cursor, TRAE, OpenCode, and pi — but not in ZCode. Every ZCode conversation starts with zero memory, and every session's content evaporates when the session ends. A user who switches between ZCode and Claude Code has a fractured memory: half their context lives in OpenViking, half doesn't.
-
-## Solution
-
-A `zcode-memory-plugin` under `examples/` that reuses the existing `memory-plugin-shared` runtime (no memory logic is duplicated). The plugin is a thin adapter that wires four ZCode lifecycle events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `Stop`) into the shared recall/capture/commit pipeline. It ships as a self-contained plugin directory discoverable by ZCode's plugin marketplace, and is installable via the shared `install.sh` one-liner.
-
-## User Stories
-
-### Installation & lifecycle
-
-1. As a ZCode user, I want to install the OpenViking memory plugin with a single command, so that I don't have to manually edit configuration files.
-2. As a ZCode user, I want the installer to detect whether ZCode is installed on my machine, so that the `--harness zcode` option only appears when relevant.
-3. As a ZCode user, I want the plugin to be distributed via ZCode's plugin marketplace, so that I can install and update it through the standard mechanism.
-4. As a ZCode user, I want the plugin to connect to my local OpenViking server automatically (reading `~/.openviking/ovcli.conf`), so that I don't have to configure credentials manually for a local setup.
-5. As a ZCode user who also uses Claude Code or Codex, I want the same OpenViking server and data store to serve all my agents, so that memory is shared across tools — not siloed per agent.
-
-### Recall (reading memory)
-
-6. As a ZCode user, when I start a new session, I want the plugin to inject my user profile and relevant preferences/entities into the context, so that the agent knows my preferences from prior sessions.
-7. As a ZCode user, when I type a prompt, I want the plugin to search OpenViking for relevant memories and inject them as context, so that the agent can recall facts from past conversations.
-8. As a ZCode user, I want recall to be fast (under 8 seconds), so that it doesn't noticeably delay my prompt processing.
-9. As a ZCode user, I want recall to degrade gracefully when the OpenViking server is offline, so that my session isn't blocked by a memory system that's down.
-10. As a ZCode user, I want recall to skip empty or too-short prompts, so that trivial inputs don't waste server resources.
-
-### Capture (writing memory)
-
-11. As a ZCode user, when a conversation turn completes (Stop event), I want the plugin to capture the user and assistant messages into an OpenViking session, so that the content is available for future recall.
-12. As a ZCode user, I want capture to happen asynchronously (without blocking the session), so that I don't experience latency from memory writes.
-13. As a ZCode user, I want the plugin to avoid re-capturing turns that were already captured (deduplication), so that the memory store doesn't fill with duplicates.
-14. As a ZCode user, I want the plugin to commit the OpenViking session periodically (when enough turns accumulate), so that the memory extractor can produce archived long-term memories.
-15. As a ZCode user, I want capture to enqueue writes to a persistent pending queue when the server is unreachable, so that no conversation content is lost during outages.
-16. As a ZCode user, I want the plugin to strip its own injected `<openviking-context>` blocks from captured text, so that recall output doesn't pollute the memory store in a self-referential loop.
-
-### URI guard (safety)
-
-17. As a ZCode user, when the agent attempts to `Read`, `Glob`, or `Grep` a `viking://` URI directly, I want the plugin to deny the operation and redirect the agent to the OpenViking MCP tools, so that virtual filesystem paths are never passed to local file/shell tools.
-18. As a ZCode user, I want the deny message to include the correct MCP tool invocation example, so that the agent knows exactly how to access the content properly.
-
-### MCP tools
-
-19. As a ZCode user, I want the OpenViking MCP server to connect automatically at session start, so that I can use `find`, `search`, `recall`, `read`, `remember` tools without manual setup.
-20. As a ZCode user, I want to see the MCP server status (connected, tool count > 0) in Settings → MCP, so that I can verify the integration is healthy.
-21. As a ZCode user, I want the MCP tool names to follow the `mcp__plugin:openviking:openviking__*` namespace (ZCode's plugin MCP naming), so that tool calls resolve correctly.
-
-### Configuration & debugging
-
-22. As a ZCode user, I want to enable debug logging via `ov.conf` (`claude_code.debug: true` or an equivalent zcode section), so that I can troubleshoot hook behavior without relying on shell environment variables that don't propagate to desktop-spawned processes.
-23. As a ZCode user, I want the debug log to be written to `~/.openviking/logs/zcode-hooks.log`, so that I can find ZCode-specific hook traces separate from other agents.
-24. As a ZCode user, I want to be able to disable the plugin via environment variable (`OPENVIKING_MEMORY_ENABLED=0`) or config, so that I can temporarily turn off memory without uninstalling.
-25. As a ZCode user, I want to bypass memory for specific sessions via glob patterns (`OPENVIKING_BYPASS_SESSION_PATTERNS`), so that scratch or sensitive sessions don't contaminate the shared store.
-
-## Implementation Decisions
-
-### Architecture: thin adapter over shared runtime
-
-The ZCode adapter mirrors the TRAE plugin's architecture (the closest analogue — another IDE-style coding agent without `PreCompact`/`SessionEnd` events). A single dispatcher script (`zcode-hook.mjs`) branches on event name; four thin shim scripts (3 lines each) set an environment variable and import the dispatcher. All memory logic (recall, capture, commit, dedup, pending queue, credential resolution, MCP proxy) is provided by the shared runtime — zero duplication.
-
-### Shared runtime reference: vendored copy (not relative path)
-
-Unlike TRAE/Cursor (which import the shared lib via cross-directory relative paths resolved at install time by `assemble_agent_integration()`), the ZCode plugin **vendors** the shared runtime into `scripts/shared/` — the same pattern used by Claude Code and Codex. Rationale:
-
-- ZCode plugins are self-contained directories distributed via marketplace; cross-directory relative imports are not guaranteed to resolve after installation.
-- The vendor mechanism (`examples/memory-plugin-shared/sync.mjs`) is mature and already used by four consumers.
-- A vendored copy makes the plugin relocatable and marketplace-distributable.
-
-The `TARGETS` array in `sync.mjs` gains one entry:
-```
-{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES }
-```
-
-The dispatcher imports from the vendored path (`./shared/agent-hook-runtime.mjs`), not the source path (`../../memory-plugin-shared/lib/...`).
-
-> **Decision provenance**: Adversarial review finding B1 — the original plan mixed vendor + TRAE-style relative imports, which are mutually inconsistent. Pure vendor (Claude Code pattern) was chosen because ZCode's marketplace distribution model requires self-contained plugin directories.
-
-### Manifest: `.zcode-plugin/plugin.json` (preferred form)
-
-ZCode probes manifest locations in order: `.zcode-plugin/` (preferred) → `.claude-plugin/` → `.codex-plugin/`. Although `.claude-plugin/` is recognized (confirmed by the OMC plugin running under ZCode), the plugin uses `.zcode-plugin/plugin.json` as the first-class ZCode citizen form. The manifest is minimal: `name`, `version`, `description`, and `mcpServers` pointing to `./.mcp.json`.
-
-> **Decision provenance**: Adversarial review R1 — `.claude-plugin/` works but is a compatibility name that may be deprecated; `.zcode-plugin/` is the documented preferred location.
-
-### Hook events: exactly four (the ZCode-supported subset)
-
-ZCode supports exactly seven lifecycle events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `PostToolUseFailure`, `Stop`. It does **not** support `PreCompact`, `SessionEnd`, `SubagentStart`, or `SubagentStop`. The plugin wires four events:
-
-| Event | Script | Purpose |
-|-------|--------|---------|
-| `SessionStart` | `session-start.mjs` | Inject user profile + preferences/entities; replay pending queue |
-| `UserPromptSubmit` | `auto-recall.mjs` | Search OpenViking, inject `<openviking-context>` recall block |
-| `PreToolUse` (matcher `Read\|Glob\|Grep`) | `uri-guard.mjs` | Deny direct access to `viking://` URIs, redirect to MCP tools |
-| `Stop` | `auto-capture.mjs` | Capture incremental turns + commit session |
-
-The commit-on-`Stop` strategy (committing after every capture, not waiting for `PreCompact`/`SessionEnd`) mirrors the TRAE and Codex patterns. This is necessary because ZCode offers no compact/end-of-session lifecycle signal.
-
-> **Decision provenance**: Adversarial review R1 — confirmed all four event names are valid; R4 — confirmed `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop` are silently dropped by ZCode, so including them creates dead hooks (as seen in the OMC plugin's `hooks.json`).
-
-### Hook output schema: ZCode-canonical keys only
-
-ZCode parses hook stdout as JSON with a **strict schema — any extra key fails validation and the entire output is silently discarded**. The Claude Code plugin emits `{ "decision": "approve", "hookSpecificOutput": { ... } }`, which contains Claude-specific keys. The ZCode adapter must emit only ZCode-recognized output:
-
-- **Context injection** (`SessionStart`, `UserPromptSubmit`): `{ "hookSpecificOutput": { "hookEventName": "<Event>", "additionalContext": "..." } }` — or verify whether ZCode accepts a top-level `additionalContext` without the `decision` wrapper. This is the single highest-risk unknown and must be resolved by manual testing before any live verification.
-- **URI guard deny** (`PreToolUse`): `{ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..." } }` — ZCode documents `allow`/`ask`/`deny` as valid permission decisions.
-- **Pass-through** (all events when no action needed): empty output + exit code 0.
-
-The `approve()` helper in the dispatcher must NOT emit `decision: "approve"` (a Claude-Code-ism). If ZCode requires a decision field, use `exit 0` with no JSON output as the pass-through path.
-
-> **Decision provenance**: Adversarial review R1 (F1) and R4 (V1) — the #1 silent-failure mode. A hook that "fires successfully" and logs `injection_built` but whose output is discarded by strict validation produces zero visible effect.
-
-### Template variables: `${CLAUDE_PLUGIN_ROOT}` (braced form)
-
-ZCode expands `${CLAUDE_PLUGIN_ROOT}` and `${ZCODE_PLUGIN_ROOT}` for plugin hooks (confirmed by docs and by real plugins: OMC, android-emulator, ios-simulator). The braced form `${CLAUDE_PLUGIN_ROOT}` is used (not the bare `$CLAUDE_PLUGIN_ROOT`, which breaks on paths with spaces). Template expansion is plugin-only — configuration-file hooks do not expand templates, so this is only safe in the plugin's `hooks/hooks.json`.
-
-### MCP: single `.mcp.json`, no manifest-inline duplication
-
-The plugin provides a single `.mcp.json` at the plugin root (referenced from the manifest via `"mcpServers": "./.mcp.json"`). The manifest does NOT inline an `mcpServers` object — only one source of truth, to avoid the precedence ambiguity seen in the android-emulator plugin (which ships both and they disagree). The MCP server is namespaced by ZCode as `plugin:openviking:openviking`, producing tool names like `mcp__plugin:openviking:openviking__find`.
-
-### Timeout units: seconds (not milliseconds)
-
-For `type: "command"` hooks, ZCode's `timeout` field is in **seconds** (not ms). The plan uses conservative values: `SessionStart: 30s`, `UserPromptSubmit: 20s`, `PreToolUse: 5s`, `Stop: 30s`. These match TRAE's timeouts. No `async: true` field is used (it has no runtime effect in ZCode — hooks always run inline).
-
-> **Decision provenance**: Adversarial review R1 (F2, F10) — timeout unit confusion and useless `async` are common pitfalls.
-
-### Session ID derivation
-
-The adapter derives a stable OpenViking session ID from the ZCode session identifier, prefixed `zc-` (analogous to TRAE's `tr-` and Codex's prefix). The shared runtime's `deriveAgentSessionId("zc-", input)` handles this. The native session ID is resolved from whichever field ZCode provides (`session_id`, `conversation_id`, `generation_id`, or derived from `transcript_path`).
-
-### Debug logging path
-
-The adapter configures the logger with `clientId: "zcode"`, which writes to `~/.openviking/logs/zcode-hooks.log` (not `cc-hooks.log`). Debug is activated via the shared runtime's `OPENVIKING_DEBUG` env var, but since desktop-spawned hook processes may not inherit shell env vars, the plugin should also support activation via an `ov.conf` flag.
-
-### Shared installer wiring (`install.sh`)
-
-The `install.sh` shared installer gains `zcode` as a recognized harness:
-
-- `validate_selected_harnesses()`: add `zcode` to the case whitelist.
-- `refresh_available_harnesses()`: detect ZCode via `~/.zcode/cli/` directory existence or a `zcode` CLI command.
-- TUI variables: add `HAVE_ZCODE`, `SEL_ZCODE`.
-- A `install_zcode()` function (or `install_zcode_variant()` analogous to `install_trae_variant()`) that registers the plugin in ZCode's marketplace and writes `ovcli.conf` credentials.
-- Since ZCode supports the standard plugin manifest + marketplace model, the install path resembles Claude Code's (marketplace add + install) more than TRAE's (write hooks into a config file).
-
-> **Decision provenance**: Adversarial review R2 (B2) — without `install.sh` wiring, `bash install.sh --harness zcode` hard-fails with exit code 2. Every other IDE plugin (cursor, trae, trae-cn) is fully wired.
-
-### Transcript parsing
-
-The adapter includes a `zcode-turns.mjs` module (analogous to `trae-turns.mjs`) that extracts user/assistant turns from the ZCode Stop-event payload. The exact field names in ZCode's hook stdin are **the primary unknown** — the shared runtime's `readHookInput()` handles multiple field name conventions as a fallback, but the adapter must be validated against real ZCode payloads before assuming correctness. The parser strips injected blocks (`<openviking-context>`, `<relevant-memories>`, `<system-reminder>`) to prevent self-referential pollution.
-
-### Contribution strategy: collaborate first, not compete
-
-An open draft PR (#3544 by `now-ing`) already exists for this feature, and a maintainer (`@huangruiteng`) has a substantive technical comment on the linked issue (#3127) requesting a "ZCode contract." The correct first action is to **comment on PR #3544 and Issue #3127** with the verified ZCode extension-surface information (hook events, output schema, template variables, config paths) gathered during this research. Only if the PR author is unresponsive for 2-4 weeks does a new PR become appropriate.
-
-> **Decision provenance**: Adversarial review R3 — submitting a competing PR for a feature with an active draft PR by a high-output contributor, with a maintainer already engaged, is the highest-avoidance-risk category of open-source conflict.
-
-## Testing Decisions
-
-### Seam 1: Pure transcript parser (unit test — primary)
-
-**What**: `scripts/zcode-turns.test.mjs` using `node:test`.
-
-**Prior art**: `examples/trae-memory-hooks/scripts/trae-hooks.test.mjs` — tests `buildTraeTurns(input, state)` with mock inputs covering: tag stripping, turn building, empty-turn dropping, state fallback.
-
-**Test cases for ZCode**:
-- Input with `prompt` + `responseText` → produces `[user, assistant]` turns
-- Input with `prompt` + `responsePreview` → produces `[user, assistant]` turns
-- Input with only `responseText` → produces `[assistant]` turn (no user)
-- Input with empty prompt + state fallback → uses `state.pendingPrompt`
-- Input with `<openviking-context>` tags in content → tags stripped
-- Input with `<relevant-memories>` tags → tags stripped
-- Empty input → produces `[]`
-- Rollout fallback: stdin lacks user content → reads rollout file for complete conversation
-- Rollout incremental: `state.lastTurnId` set → returns only unseen entries
-- Rollout turnId propagation: turns from rollout carry `turnId` for dedup
-
-**Why this seam**: The transcript parser is pure (no I/O, no network, no filesystem), making it the highest-value, lowest-cost test. It validates the only ZCode-specific logic that can break silently — if the field names don't match ZCode's actual payload, turns are empty and capture silently no-ops.
-
-### Seam 2: Hook output schema conformance (unit test — secondary)
-
-**What**: `scripts/zcode-hooks.test.mjs` using `node:test`.
-
-**Prior art**: `examples/trae-memory-hooks/scripts/trae-hooks.test.mjs` — asserts hook contract shape.
-
-**Test cases**:
-- `SessionStart` output contains only recognized keys (no `decision: "approve"`)
-- `UserPromptSubmit` output's `additionalContext` is a string or absent
-- `PreToolUse` deny output uses `permissionDecision: "deny"` (not `"approve"`)
-- `Stop` output is empty or contains only recognized keys
-- Plugin disabled state → output is empty + exit 0
-
-**Why this seam**: ZCode's strict JSON schema is the #1 silent-failure mode (adversarial review R1-F1, R4-V1). A hook that emits an unrecognized key has its entire output discarded — the plugin appears "installed but doing nothing." This seam catches that regression at unit-test time before it reaches manual verification.
-
-### What is NOT tested automatically (out of seam scope)
-
-- End-to-end hook triggering (requires a live ZCode process)
-- MCP tool exposure (requires a running OpenViking backend)
-- Recall/capture correctness against a live server (integration test)
-- Template variable expansion (requires the ZCode plugin loader)
-
-These are covered by a manual verification SOP (documented in the plugin README, modeled on `examples/codex-memory-plugin/VERIFICATION.md`) that accounts for the seven false-positive/negative scenarios identified in the adversarial review.
-
-### CI compatibility
-
-Both test files use `node:test` (Node.js built-in test runner), runnable via:
-```bash
-node --test scripts/zcode-turns.test.mjs scripts/zcode-hooks.test.mjs
-```
-No external dependencies, no `npm install` required. Matches the pattern used by TRAE, Claude Code, and the shared runtime tests.
-
-## Out of Scope
-
-- **Competing PR submission**: The first action is commenting on PR #3544 / Issue #3127 with verified info, not opening a new PR. A new PR is a fallback only if collaboration fails.
-- **`PreCompact` / `SessionEnd` / `SubagentStart` / `SubagentStop` hooks**: ZCode does not support these events. The commit-on-`Stop` strategy compensates for the absence of `PreCompact`/`SessionEnd`. Subagent isolation is not possible without `SubagentStart`/`SubagentStop`.
-- **`PostToolUse` skill-experience injection**: The Claude Code plugin injects skill/experience context on `PostToolUse(Read)`. This is a nice-to-have enhancement, not part of the initial plugin. ZCode supports `PostToolUse`, so it can be added later.
-- **Statusline**: ZCode may or may not have a statusline mechanism equivalent to Claude Code's `.statusLine` settings entry. Statusline integration is deferred until the core hook/MCP functionality is verified.
-- **ZCode desktop app vs CLI divergence**: Some MCP field-name migrations (`environment` → `env`) are handled by the CLI config parser but may not be by the desktop app's session creation path. The plugin uses canonical field names (`env`, `command`, `args`) but does not attempt to work around desktop-specific parsing quirks.
-- **Cross-session memory attribution**: Multiple agents (ZCode, Claude Code, Codex) share one OpenViking data store. Distinguishing which agent captured a given memory is handled by `peer_id` / session prefixing, but a UI for per-agent memory filtering is out of scope.
-
-## Further Notes
-
-### Verified ZCode extension surface (ground truth)
-
-These facts were verified against the live ZCode installation on the development machine (docs from the built-in `zcode-guide` plugin + actual `~/.zcode/cli/config.json` + 4 real installed plugins with hooks):
-
-| Aspect | Verified fact |
-|--------|--------------|
-| Supported hook events | `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `PostToolUseFailure`, `Stop` (exactly 7) |
-| Unsupported events | `PreCompact`, `SessionEnd`, `Notification`, `SubagentStart`, `SubagentStop` |
-| Manifest probe order | `.zcode-plugin/plugin.json` → `.claude-plugin/plugin.json` → `.codex-plugin/plugin.json` |
-| Template vars (plugin hooks) | `${CLAUDE_PLUGIN_ROOT}`, `${ZCODE_PLUGIN_ROOT}`, `${CLAUDE_PROJECT_DIR}`, `${ZCODE_PROJECT_DIR}`, `${CLAUDE_SESSION_ID}` |
-| Template vars (config hooks) | None — config-file hooks do NOT expand templates |
-| Hook output schema | Strict JSON — any extra key fails validation, output discarded |
-| MCP config location | `~/.zcode/cli/config.json` → `mcp.servers` (user scope) |
-| Plugin MCP namespacing | `plugin:<plugin>:<server>` |
-| MCP auto-connect | All scopes (user, workspace, plugin, env, CLI) auto-connect at session start |
-| Hook runner enablement | Auto-enabled when any plugin contributes a hook |
-| Timeout units | `command` type: `timeout` in **seconds**; `process` type: `timeoutMs` in milliseconds |
-| `async` field | No runtime effect — hooks always run inline |
-| Third-party plugin trust | All plugin hooks are runnable (no trust gate) |
-
-### Primary unknowns to resolve during implementation
-
-1. **Exact hook stdin field names**: ZCode's `Stop` payload field names for prompt text, assistant response, and transcript path. The shared runtime has multi-field fallbacks, but the adapter must be validated against real payloads.
-2. **Output schema acceptance**: Whether `{ "hookSpecificOutput": { "hookEventName": "...", "additionalContext": "..." } }` is accepted as-is, or whether ZCode requires a different wrapper (e.g., top-level `additionalContext`). Must be tested by running the script manually and checking the ZCode log for validation failures.
-3. **MCP tool name format**: Whether the namespaced form `mcp__plugin:openviking:openviking__find` is the exact tool name the model sees, and whether existing prompt examples that reference `mcp__openviking__find` need updating.
-
-### Adversarial review artifacts
-
-This spec incorporates findings from a four-reviewer adversarial review:
-- **R1 (ZCode extension surface)**: 12 concrete runtime failure scenarios; confirmed 5/6 technical claims; refuted the "vendor is a recognized mechanism" framing.
-- **R2 (codebase conventions)**: 2 blockers (vendor/relative-path inconsistency, missing install.sh wiring), 5 majors (missing tests, docs, sync.test.mjs, manifest format).
-- **R3 (PR strategy)**: 4 high-risk findings; recommended collaboration over competition.
-- **R4 (verification realism)**: 7 false-positive/negative scenarios in the original verification plan.
-
-### Files to be created/modified
-
-Created:
-- `examples/zcode-memory-plugin/.zcode-plugin/plugin.json`
-- `examples/zcode-memory-plugin/hooks/hooks.json`
-- `examples/zcode-memory-plugin/.mcp.json`
-- `examples/zcode-memory-plugin/scripts/zcode-hook.mjs`
-- `examples/zcode-memory-plugin/scripts/zcode-turns.mjs`
-- `examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs`
-- `examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs`
-- `examples/zcode-memory-plugin/scripts/session-start.mjs`
-- `examples/zcode-memory-plugin/scripts/auto-recall.mjs`
-- `examples/zcode-memory-plugin/scripts/auto-capture.mjs`
-- `examples/zcode-memory-plugin/scripts/uri-guard.mjs`
-- `examples/zcode-memory-plugin/servers/mcp-proxy.mjs`
-- `examples/zcode-memory-plugin/scripts/shared/*.mjs` (generated by sync.mjs)
-- `examples/zcode-memory-plugin/README.md`
-- `examples/zcode-memory-plugin/README_CN.md`
-- `examples/zcode-memory-plugin/DESIGN.md`
-- `docs/en/agent-integrations/15-zcode.md`
-- `docs/zh/agent-integrations/15-zcode.md`
-
-Modified:
-- `examples/memory-plugin-shared/sync.mjs` (add zcode to TARGETS)
-- `examples/memory-plugin-shared/sync.test.mjs` (mirror TARGETS change)
-- `examples/memory-plugin-shared/install.sh` (add zcode harness: detection, validation, TUI, install function)
-- `docs/en/agent-integrations/01-overview.md` (add zcode row)
-- `docs/zh/agent-integrations/01-overview.md` (add zcode row)
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index 8d5d9f1a3..3cb1f5e0b 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -11,14 +11,13 @@ OpenViking can act as the long-term memory and context backend for many agent ru
| **Codex** | [Codex Memory Plugin](./04-codex.md) — lifecycle hooks for auto-recall and incremental capture |
| **Cursor** | [Cursor Memory Integration](./12-cursor.md) — one command installs lifecycle hooks, MCP tools, rules, and skills |
| **TRAE / TRAE CN** | [TRAE Memory Integration](./13-trae.md) — one installer configures prompt-time recall, turn capture, and OpenViking tools |
-| **ZCode** | [ZCode Memory Integration](./15-zcode.md) — config-driven hooks for auto-recall, turn capture, and URI guard |
| **Hermes Agent** | [Hermes Agent](./05-hermes.md) — built-in OpenViking memory provider, no plugin install needed |
| **OpenCode** | [OpenCode Plugin](./10-opencode.md) — MCP tools plus lifecycle hooks for repo context, auto-recall, and capture |
| **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, and threshold commit |
| **LangChain / LangGraph** | [LangChain and LangGraph](./07-langchain-langgraph.md) — retriever, tools, context backend, store, and middleware |
| **Multiple local coding agents / a desktop UI** | [OpenViking Helper](./14-openviking-helper.md) — visual agent setup, session inspection, and memory management |
| **Manus / Claude Desktop / ChatGPT / other MCP clients** | [MCP Clients](./06-mcp-clients.md) — point any MCP-compatible client at the built-in `/mcp` endpoint |
-| **AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |
+| **ZCode / AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |
## Prerequisite for all integrations
diff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.md
index 8005d0cc5..5dc3934a2 100644
--- a/docs/en/agent-integrations/08-community-plugins.md
+++ b/docs/en/agent-integrations/08-community-plugins.md
@@ -2,6 +2,51 @@
Community-maintained integrations for various agent runtimes. Each differs in target platform, integration depth, and maintenance status — check the linked README before adopting.
+## ZCode memory integration
+
+Source: [examples/zcode-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
+
+The ZCode community integration adds cross-project, cross-session memory through config-driven lifecycle hooks and an OpenViking MCP server:
+
+- **SessionStart** injects the user profile.
+- **UserPromptSubmit** recalls relevant memories.
+- **PreToolUse** redirects direct `viking://` reads to MCP tools.
+- **Stop** captures unseen rollout turns in a detached worker, then commits the OpenViking session.
+
+ZCode does not expose `PreCompact`, `SessionEnd`, or subagent lifecycle hooks. The adapter therefore commits on `Stop`, uses ZCode rollout files as the authoritative incremental transcript, and falls back to hook stdin only when no rollout file is available.
+
+### Install
+
+Prerequisites: Node.js 18+, a running OpenViking server, and ZCode.
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
+ --harness zcode
+```
+
+Use the TOS mirror where GitHub is unavailable:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+ --harness zcode --dist tos
+```
+
+The installer detects `~/.zcode/` or the `zcode` binary, installs the runtime under `~/.openviking/agent-integrations/zcode/`, and merges hooks and MCP configuration into `~/.zcode/cli/config.json`.
+
+After restarting ZCode, verify that:
+
+- `~/.zcode/cli/config.json` contains `hooks.enabled: true`, OpenViking entries under `hooks.events`, and `mcp.servers.openviking`.
+- `OPENVIKING_DEBUG=1` produces diagnostics in `~/.openviking/logs/zcode-hooks.log`.
+
+| Symptom | Cause | Fix |
+|---------|-------|-----|
+| Hooks not firing | Hook configuration is disabled or stale | Re-run the installer and restart ZCode |
+| Recall returns nothing | OpenViking is unavailable or has not extracted memories yet | Check `curl http://127.0.0.1:1933/health` and wait for extraction |
+| MCP tools not appearing | The MCP proxy failed to start | Check the absolute `mcp.servers.openviking` command in `~/.zcode/cli/config.json` |
+| Duplicate captures | An older installation left duplicate hook entries | Run `install.sh --harness zcode --uninstall`, then reinstall |
+
+Implementation details and currently verified ZCode assumptions are documented in the plugin's [README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin) and [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/zcode-memory-plugin/DESIGN.md).
+
## AstrBot plugin
[AstrBot](https://github.com/AstrBotDevs/AstrBot) is a multi-platform IM bot framework supporting QQ, Telegram, Discord, Lark, and 20+ other platforms.
diff --git a/docs/en/agent-integrations/15-zcode.md b/docs/en/agent-integrations/15-zcode.md
deleted file mode 100644
index 1dbfd233a..000000000
--- a/docs/en/agent-integrations/15-zcode.md
+++ /dev/null
@@ -1,58 +0,0 @@
-# ZCode Memory Integration
-
-Adds cross-project, cross-session long-term memory to ZCode. After installation, OpenViking hooks automatically inject relevant context at session start, recall memories on each prompt, and capture conversation turns for the memory extractor. MCP tools enable manual search, read, and management of memories.
-
-## Install
-
-Prerequisites: Node.js 18+, an OpenViking server running locally or remotely, and ZCode installed on your machine.
-
-```bash
-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
- --harness zcode
-```
-
-For regions where GitHub is unreachable, use the TOS mirror:
-
-```bash
-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
- --harness zcode --dist tos
-```
-
-The installer detects ZCode via `~/.zcode/` or a `zcode` binary, merges hooks and MCP config into `~/.zcode/cli/config.json`, and writes OpenViking credentials to `~/.openviking/ovcli.conf`.
-
-## Verification
-
-After install, restart ZCode. Then:
-
-- **Settings → Plugin Management** — not applicable (ZCode uses config-file hooks, not plugin marketplace for this integration).
-- Check `~/.zcode/cli/config.json` for `hooks.events` entries containing `openviking-memory` and `mcp.servers.openviking`.
-- Set `OPENVIKING_DEBUG=1` in the ZCode process environment (or `claude_code.debug: true` in `~/.openviking/ov.conf`) and check `~/.openviking/logs/zcode-hooks.log`.
-
-## How it works
-
-The plugin mounts into ZCode's lifecycle at four points:
-
-- **SessionStart** — injects user profile and preferences/entities into context.
-- **UserPromptSubmit** — searches OpenViking for relevant memories and injects them as `<openviking-context>`.
-- **PreToolUse** (`Read|Glob|Grep`) — denies direct access to `viking://` URIs, redirecting to OpenViking MCP tools.
-- **Stop** — captures incremental user/assistant turns and commits the OpenViking session.
-
-ZCode does not support `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`, so the commit-on-`Stop` strategy compensates for the absence of compact/end-of-session signals.
-
-All data writes are asynchronous and do not block the conversation.
-
-## Troubleshooting
-
-| Symptom | Cause | Fix |
-|---------|-------|-----|
-| Hooks not firing | `hooks.enabled` not set in config.json | Re-run the installer, or manually set `"hooks": { "enabled": true }` in `~/.zcode/cli/config.json` |
-| Recall returns nothing | OpenViking server not running or no memories extracted yet | Check `curl http://127.0.0.1:1933/health`; wait for memory extractor to process captured turns |
-| MCP tools not appearing | MCP server failed to start | Check `~/.zcode/cli/config.json` → `mcp.servers.openviking` has correct absolute path to `mcp-proxy.mjs` |
-| Duplicate captures | Re-installed without uninstalling | Run `install.sh --harness zcode --uninstall` first, then reinstall |
-
-## See also
-
-- [Plugin README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
-- [DESIGN.md](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin/DESIGN.md) — verified ZCode extension-surface facts
-- [MCP clients](./06-mcp-clients.md)
-- [Deployment guide → CLI](../guides/03-deployment.md#cli)
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 6797fac3f..179a22fb3 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -11,14 +11,13 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
| **Codex** | [Codex 记忆插件](./04-codex.md) — 生命周期 hooks 自动召回与增量捕获 |
| **Cursor** | [Cursor 记忆集成](./12-cursor.md) — 一条命令安装生命周期 Hook、MCP 工具、Rules 与 Skills |
| **TRAE / TRAE CN** | [TRAE 记忆集成](./13-trae.md) — 一个安装器完成 prompt 召回、回合捕获与 OpenViking 工具接入 |
-| **ZCode** | [ZCode 记忆集成](./15-zcode.md) — 配置驱动 Hook 实现自动召回、对话捕获与 URI 守卫 |
| **Hermes Agent** | [Hermes Agent](./05-hermes.md) — 内置 OpenViking 记忆提供方,无需安装插件 |
| **OpenCode** | [OpenCode 插件](./10-opencode.md) — MCP 工具 + 生命周期 hooks,覆盖仓库上下文、自动召回与捕获 |
| **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获与阈值 commit |
| **LangChain / LangGraph** | [LangChain 和 LangGraph](./07-langchain-langgraph.md) — retriever、tools、context backend、store 和 middleware |
| **多个本地开发 Agent / 希望使用桌面界面** | [OpenViking Helper](./14-openviking-helper.md) — 可视化完成 Agent 接入、会话分析和记忆管理 |
| **Manus / Claude Desktop / ChatGPT / 其他 MCP 客户端** | [MCP 客户端](./06-mcp-clients.md) — 任何兼容 MCP 的客户端直接对接内置 `/mcp` 端点 |
-| **AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |
+| **ZCode / AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |
## 所有集成的共同前置
diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.md
index 8e2bceaa2..beaa7dfb5 100644
--- a/docs/zh/agent-integrations/08-community-plugins.md
+++ b/docs/zh/agent-integrations/08-community-plugins.md
@@ -2,6 +2,51 @@
社区维护的各运行时集成。各插件在目标平台、集成深度和维护状态上各有差异,使用前请先阅读各自的 README。
+## ZCode 记忆集成
+
+源码:[examples/zcode-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
+
+ZCode 社区集成通过配置驱动的生命周期 Hook 和 OpenViking MCP 服务提供跨项目、跨会话记忆:
+
+- **SessionStart** 注入用户画像。
+- **UserPromptSubmit** 召回相关记忆。
+- **PreToolUse** 将直接读取 `viking://` 的操作引导至 MCP 工具。
+- **Stop** 在 detached worker 中捕获 rollout 里的未处理回合,并 commit OpenViking session。
+
+ZCode 不提供 `PreCompact`、`SessionEnd` 和 subagent 生命周期 Hook。因此该适配器在 `Stop` 时 commit,以 ZCode rollout 文件作为权威增量对话源,只有 rollout 文件不可用时才回退到 Hook stdin。
+
+### 安装
+
+前置条件:Node.js 18+、正在运行的 OpenViking 服务,以及 ZCode。
+
+```bash
+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
+ --harness zcode
+```
+
+GitHub 不可用的地区可使用 TOS 镜像:
+
+```bash
+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
+ --harness zcode --dist tos
+```
+
+安装器通过 `~/.zcode/` 或 `zcode` 二进制检测 ZCode,将运行时安装到 `~/.openviking/agent-integrations/zcode/`,并把 Hook 与 MCP 配置合并到 `~/.zcode/cli/config.json`。
+
+重启 ZCode 后,请确认:
+
+- `~/.zcode/cli/config.json` 包含 `hooks.enabled: true`、`hooks.events` 下的 OpenViking 条目,以及 `mcp.servers.openviking`。
+- 设置 `OPENVIKING_DEBUG=1` 后,可在 `~/.openviking/logs/zcode-hooks.log` 查看诊断日志。
+
+| 现象 | 原因 | 处理方式 |
+|------|------|----------|
+| Hook 未执行 | Hook 配置被禁用或已过期 | 重跑安装器并重启 ZCode |
+| 召回为空 | OpenViking 不可用或记忆尚未提取 | 检查 `curl http://127.0.0.1:1933/health`,并等待提取完成 |
+| MCP 工具未出现 | MCP proxy 启动失败 | 检查 `~/.zcode/cli/config.json` 中 `mcp.servers.openviking` 的绝对路径命令 |
+| 重复捕获 | 旧安装留下了重复 Hook 条目 | 先运行 `install.sh --harness zcode --uninstall`,再重新安装 |
+
+实现细节与当前已验证的 ZCode 假设见插件目录中的 [README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin) 和 [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/zcode-memory-plugin/DESIGN.md)。
+
## AstrBot 插件
[AstrBot](https://github.com/AstrBotDevs/AstrBot) 是一个多平台 IM Bot 框架,支持 QQ、Telegram、Discord、飞书等 20+ 平台。
diff --git a/docs/zh/agent-integrations/15-zcode.md b/docs/zh/agent-integrations/15-zcode.md
deleted file mode 100644
index 18105bf01..000000000
--- a/docs/zh/agent-integrations/15-zcode.md
+++ /dev/null
@@ -1,57 +0,0 @@
-# ZCode 记忆集成
-
-为 ZCode 添加跨项目、跨会话的长期记忆。安装后,OpenViking Hook 会自动在会话启动时注入相关上下文、在每次输入时召回记忆、并在对话结束时捕获内容。MCP 工具用于主动搜索、读取和管理记忆。
-
-## 安装
-
-前置条件:Node.js 18+、本地或远程运行的 OpenViking 服务、以及已安装的 ZCode。
-
-```bash
-bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \
- --harness zcode
-```
-
-GitHub 访问受限时使用 TOS 镜像:
-
-```bash
-bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \
- --harness zcode --dist tos
-```
-
-安装脚本通过 `~/.zcode/` 或 `zcode` 二进制检测 ZCode,将 hooks 和 MCP 配置合并到 `~/.zcode/cli/config.json`,并将 OpenViking 凭据写入 `~/.openviking/ovcli.conf`。
-
-## 验证
-
-安装后重启 ZCode,然后:
-
-- 检查 `~/.zcode/cli/config.json` 中 `hooks.events` 是否包含 `openviking-memory` 条目,以及 `mcp.servers.openviking` 是否存在。
-- 设置 `OPENVIKING_DEBUG=1`(ZCode 进程环境变量)或 `~/.openviking/ov.conf` 中的 `claude_code.debug: true`,查看 `~/.openviking/logs/zcode-hooks.log`。
-
-## 工作原理
-
-插件挂载到 ZCode 生命周期的四个节点:
-
-- **SessionStart** — 注入用户画像和偏好/实体到上下文。
-- **UserPromptSubmit** — 搜索 OpenViking 相关记忆并注入 `<openviking-context>`。
-- **PreToolUse**(`Read|Glob|Grep`)— 拦截 `viking://` 虚拟路径的直接访问,引导使用 OpenViking MCP 工具。
-- **Stop** — 捕获增量用户/助手对话并提交 OpenViking 会话。
-
-ZCode 不支持 `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`,因此采用 commit-on-`Stop` 策略补偿缺少 compact/会话结束信号的不足。
-
-所有数据写入均为异步执行,不会阻塞当前对话。
-
-## 故障排查
-
-| 现象 | 原因 | 修复 |
-|------|------|------|
-| Hook 未触发 | config.json 中 `hooks.enabled` 未设置 | 重跑安装脚本,或手动设置 `"hooks": { "enabled": true }` |
-| 召回返回空 | OpenViking 服务未运行或记忆尚未提取 | 检查 `curl http://127.0.0.1:1933/health`;等待记忆提取器处理捕获的对话 |
-| MCP 工具未出现 | MCP 服务启动失败 | 检查 `~/.zcode/cli/config.json` → `mcp.servers.openviking` 的 `mcp-proxy.mjs` 绝对路径是否正确 |
-| 重复捕获 | 未卸载就重装 | 先运行 `install.sh --harness zcode --uninstall`,再重新安装 |
-
-## 参见
-
-- [插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
-- [DESIGN.md](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin/DESIGN.md) — 已验证的 ZCode 扩展面事实
-- [MCP 客户端](./06-mcp-clients.md)
-- [部署指南 → CLI](../guides/03-deployment.md#cli)
diff --git a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
index 41969efa9..ff92d2a9c 100644
--- a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
+++ b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
@@ -61,6 +61,7 @@ export function loadAgentHookConfig(clientId) {
timeoutMs: envNumber("OPENVIKING_TIMEOUT_MS", 15000, 1000),
profileTokenBudget: envNumber("OPENVIKING_PROFILE_TOKEN_BUDGET", 6000, 500),
commitTurnThreshold: envNumber("OPENVIKING_COMMIT_TURN_THRESHOLD", 8, 1),
+ writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC", true),
debug: envBool("OPENVIKING_DEBUG", false),
debugLogPath,
};
diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjs
new file mode 100644
index 000000000..caa3e7e9d
--- /dev/null
+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const installer = join(ROOT, "examples", "memory-plugin-shared", "install.sh");
+const stageScript = join(ROOT, ".github", "scripts", "stage-memory-plugin-marketplace.sh");
+
+function run(command, args, options = {}) {
+ return spawnSync(command, args, {
+ cwd: ROOT,
+ encoding: "utf8",
+ ...options,
+ });
+}
+
+test("release marketplace archive supports a ZCode TOS install", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-zcode-release-"));
+ try {
+ const stage = join(tmp, "memory-plugin-marketplace");
+ const staged = run("bash", [stageScript, stage]);
+ assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);
+
+ const zipped = run("zip", ["-rq", join(tmp, "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], {
+ cwd: tmp,
+ });
+ assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+
+ const home = join(tmp, "home");
+ mkdirSync(home, { recursive: true });
+ const installed = run("bash", [
+ installer,
+ "--harness", "zcode",
+ "--dist", "tos",
+ "--source", "archive",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:1933",
+ "--api-key", "",
+ "--yes",
+ ], {
+ env: {
+ ...process.env,
+ HOME: home,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(tmp, "memory-plugin-marketplace.zip")}`,
+ },
+ });
+ assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);
+
+ const integrationRoot = join(home, ".openviking", "agent-integrations", "zcode");
+ assert.ok(existsSync(join(integrationRoot, "scripts", "zcode-hook.mjs")));
+ assert.ok(existsSync(join(integrationRoot, "scripts", "zcode-capture.mjs")));
+ assert.ok(existsSync(join(integrationRoot, "scripts", "shared", "async-writer.mjs")));
+
+ const config = JSON.parse(readFileSync(join(home, ".zcode", "cli", "config.json"), "utf8"));
+ assert.equal(config.hooks.enabled, true);
+ assert.deepEqual(Object.keys(config.hooks.events), [
+ "SessionStart",
+ "UserPromptSubmit",
+ "PreToolUse",
+ "Stop",
+ ]);
+ assert.ok(config.mcp.servers.openviking);
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/examples/zcode-memory-plugin/DESIGN.md b/examples/zcode-memory-plugin/DESIGN.md
index fb31d4e3e..875772345 100644
--- a/examples/zcode-memory-plugin/DESIGN.md
+++ b/examples/zcode-memory-plugin/DESIGN.md
@@ -37,7 +37,7 @@ Unlike TRAE/Cursor (which import shared lib via cross-directory relative paths),
### 3. Four events only (ZCode-supported subset)
-ZCode supports 7 events but NOT `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`. The plugin wires 4 events. The commit-on-`Stop` strategy compensates for the absence of `PreCompact`/`SessionEnd`.
+ZCode supports 7 events but NOT `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`. The plugin wires 4 events. The commit-on-`Stop` strategy compensates for the absence of `PreCompact`/`SessionEnd`; the Stop parent detaches before reading stdin so network writes do not block ZCode.
**Provenance**: Adversarial review R1 — confirmed all 4 event names valid; R4 — unsupported events silently dropped.
@@ -56,8 +56,8 @@ ZCode's strict JSON schema rejects unrecognized keys. The dispatcher emits ONLY
1. **Hook stdin field names**: Verified via ZCode source reverse-engineering (#3127 by @quinn-zenith). The Stop hook exposes `responseText`/`responsePreview` for assistant content. User content is NOT in stdin — the parser falls back to ZCode's rollout file (`~/.zcode/cli/rollout/model-io-<sessionId>.jsonl`) which contains the complete conversation per line: `{ sessionId, turnId, request: { messages: [...] }, response: { text } }`.
2. **Output schema acceptance**: Whether `hookSpecificOutput` wrapper is accepted as-is. Must be tested against a live ZCode session.
3. **MCP tool name format**: Namespaced as `plugin:openviking:openviking` — verify tool names match expectations.
-4. **Turn identity**: Rollout entries carry a monotonic `turnId` — the adapter uses it for deduplication (`capturedTurnIds` set in hook state) and incremental capture (`lastTurnId` tracks the last processed entry). This satisfies the maintainer's contract option 2 (`session_id` + monotonic `turn_id` + per-turn content).
+4. **Turn identity**: Rollout entries carry a monotonic `turnId`. The rollout is the authoritative incremental source whenever it is readable; stdin is a compatibility fallback only. The adapter sends this identity as OpenViking's `turn_id`, records both role-specific dedup keys only after messages are sent or durably queued, and advances `lastTurnId` only through complete acknowledged rollout entries.
## Adversarial review incorporation
-This design incorporates findings from a 4-reviewer adversarial review (R1: ZCode surface, R2: conventions, R3: PR strategy, R4: verification). See `docs/design/zcode-memory-plugin-design.md` for the full spec with provenance citations.
+The focused regression suite covers rollout-first recovery, acknowledgement and cursor state, duplicate Stop delivery, detached slow writes, and installation from the same marketplace staging script used by the TOS release workflow.
diff --git a/examples/zcode-memory-plugin/README.md b/examples/zcode-memory-plugin/README.md
index 5e27910ed..766c7fb0f 100644
--- a/examples/zcode-memory-plugin/README.md
+++ b/examples/zcode-memory-plugin/README.md
@@ -7,9 +7,9 @@ This package provides a ZCode lifecycle adapter for OpenViking long-term memory.
- **SessionStart** — injects user profile and preferences/entities into context.
- **UserPromptSubmit** — searches OpenViking for relevant memories and injects them.
- **PreToolUse** (`Read|Glob|Grep`) — denies direct access to `viking://` URIs, redirects to MCP tools.
-- **Stop** — captures incremental user/assistant turns and commits the OpenViking session.
+- **Stop** — returns immediately, then captures incremental user/assistant turns and commits the OpenViking session in a detached worker.
-ZCode does not support `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`, so the commit-on-`Stop` strategy (mirroring TRAE and Codex) compensates for the absence of compact/end-of-session signals.
+ZCode does not support `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`, so the commit-on-`Stop` strategy compensates for the absence of compact/end-of-session signals. The rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and allow a later Stop to recover missed turns. Hook stdin is only a fallback when the rollout file is unavailable.
## Install
@@ -23,12 +23,12 @@ The installer detects ZCode via `~/.zcode/` or a `zcode` binary, merges hooks an
## Architecture
-The plugin vendors the shared runtime into `scripts/shared/` via `sync.mjs`. The dispatcher (`zcode-hook.mjs`) branches on event name; four thin shim scripts set an environment variable and import the dispatcher. All memory logic (recall, capture, commit, dedup, pending queue, credential resolution, MCP proxy) is provided by the shared runtime.
+The plugin vendors the shared runtime into `scripts/shared/` via `sync.mjs`. The dispatcher (`zcode-hook.mjs`) branches on event name; three thin shim scripts set an environment variable and import the dispatcher, while the URI guard has its own entry point. Shared runtime modules provide recall, batching, pending queue, credential resolution, and MCP proxying; `zcode-capture.mjs` owns the ZCode-specific acknowledgement and cursor state transition.
See [DESIGN.md](./DESIGN.md) for verified ZCode extension-surface facts and decision provenance.
## Tests
```bash
-node --test scripts/zcode-turns.test.mjs scripts/zcode-hooks.test.mjs
+node --test scripts/*.test.mjs
```
diff --git a/examples/zcode-memory-plugin/README_CN.md b/examples/zcode-memory-plugin/README_CN.md
index 590049b8f..40381da9d 100644
--- a/examples/zcode-memory-plugin/README_CN.md
+++ b/examples/zcode-memory-plugin/README_CN.md
@@ -7,9 +7,9 @@
- **SessionStart** — 注入用户画像和偏好/实体到上下文。
- **UserPromptSubmit** — 搜索 OpenViking 相关记忆并注入。
- **PreToolUse**(`Read|Glob|Grep`)— 拦截 `viking://` 虚拟路径的直接访问,引导使用 MCP 工具。
-- **Stop** — 捕获增量用户/助手对话并提交 OpenViking 会话。
+- **Stop** — 立即返回,并在 detached worker 中捕获增量用户/助手对话、提交 OpenViking 会话。
-ZCode 不支持 `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`,因此采用 commit-on-`Stop` 策略(同 TRAE 和 Codex),补偿缺少 compact/会话结束信号的不足。
+ZCode 不支持 `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`,因此通过 Stop 时 commit 补足 compact/会话结束信号。Rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能恢复漏掉的回合;只有 rollout 文件不可用时才回退到 Hook stdin。
## 安装
@@ -23,12 +23,12 @@ bash examples/memory-plugin-shared/install.sh --harness zcode
## 架构
-插件通过 `sync.mjs` 将共享运行时 vendor 到 `scripts/shared/`。调度器(`zcode-hook.mjs`)按事件名分支;四个薄 shim 脚本设置环境变量后导入调度器。所有记忆逻辑(召回、捕获、提交、去重、待处理队列、凭据解析、MCP 代理)由共享运行时提供。
+插件通过 `sync.mjs` 将共享运行时 vendor 到 `scripts/shared/`。调度器(`zcode-hook.mjs`)按事件名分支;三个轻量 shim 设置环境变量并导入调度器,URI guard 使用独立入口。共享运行时提供召回、批量写入、待处理队列、凭据解析和 MCP 代理;`zcode-capture.mjs` 负责 ZCode 特有的确认与游标状态转换。
详见 [DESIGN.md](./DESIGN.md) 了解已验证的 ZCode 扩展面事实和设计决策来源。
## 测试
```bash
-node --test scripts/zcode-turns.test.mjs scripts/zcode-hooks.test.mjs
+node --test scripts/*.test.mjs
```
diff --git a/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs
index 848dea82b..28f95a63e 100644
--- a/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ b/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -62,6 +62,7 @@ export function loadAgentHookConfig(clientId) {
timeoutMs: envNumber("OPENVIKING_TIMEOUT_MS", 15000, 1000),
profileTokenBudget: envNumber("OPENVIKING_PROFILE_TOKEN_BUDGET", 6000, 500),
commitTurnThreshold: envNumber("OPENVIKING_COMMIT_TURN_THRESHOLD", 8, 1),
+ writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC", true),
debug: envBool("OPENVIKING_DEBUG", false),
debugLogPath,
};
diff --git a/examples/zcode-memory-plugin/scripts/zcode-async.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-async.test.mjs
new file mode 100644
index 000000000..772a62818
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-async.test.mjs
@@ -0,0 +1,204 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createServer } from "node:http";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const hook = fileURLToPath(new URL("./auto-capture.mjs", import.meta.url));
+
+function waitFor(predicate, timeoutMs = 5000) {
+ const deadline = Date.now() + timeoutMs;
+ return new Promise((resolve, reject) => {
+ const poll = () => {
+ if (predicate()) {
+ resolve();
+ return;
+ }
+ if (Date.now() >= deadline) {
+ reject(new Error("timed out waiting for detached ZCode worker"));
+ return;
+ }
+ setTimeout(poll, 25);
+ };
+ poll();
+ });
+}
+
+function runHook(input, env) {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [hook], {
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ child.stdin.end(JSON.stringify(input));
+ });
+}
+
+test("Stop returns before slow writes while detached worker finishes capture", async (t) => {
+ const requests = [];
+ let completedResponses = 0;
+ const server = createServer((request, response) => {
+ const chunks = [];
+ request.on("data", (chunk) => chunks.push(chunk));
+ request.on("end", () => {
+ requests.push({
+ url: request.url,
+ body: Buffer.concat(chunks).toString(),
+ });
+ setTimeout(() => {
+ response.writeHead(200, { "Content-Type": "application/json" });
+ response.end('{"result":{}}');
+ completedResponses++;
+ }, 700);
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+
+ const home = mkdtempSync(join(tmpdir(), "zcode-async-"));
+ t.after(() => rmSync(home, { recursive: true, force: true }));
+ const sessionId = "sess-async-test";
+ const rolloutDir = join(home, ".zcode", "cli", "rollout");
+ mkdirSync(rolloutDir, { recursive: true });
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessionId}.jsonl`),
+ `${JSON.stringify({
+ turnId: "turn-001",
+ request: { messages: [{ role: "user", content: "slow question" }] },
+ response: { text: "slow answer" },
+ })}\n`,
+ );
+
+ const startedAt = Date.now();
+ const child = spawn(process.execPath, [hook], {
+ env: {
+ ...process.env,
+ HOME: home,
+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
+ OPENVIKING_WRITE_PATH_ASYNC: "1",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ child.stdin.end(JSON.stringify({ session_id: sessionId, cwd: home }));
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ const exitCode = await new Promise((resolve) => child.on("close", resolve));
+ const elapsedMs = Date.now() - startedAt;
+
+ assert.equal(exitCode, 0, stderr);
+ assert.equal(stdout, "");
+ assert.equal(completedResponses, 0, "parent waited for a network response");
+ assert.ok(elapsedMs < 650, `parent hook took ${elapsedMs}ms`);
+
+ await waitFor(() => requests.some(({ url }) => url?.endsWith("/commit")));
+ assert.equal(requests.length, 2);
+ const batch = requests.find(({ url }) => url?.endsWith("/messages/batch"));
+ assert.ok(batch);
+ assert.deepEqual(JSON.parse(batch.body), {
+ messages: [
+ { role: "user", content: "slow question", turn_id: "turn-001" },
+ { role: "assistant", content: "slow answer", turn_id: "turn-001" },
+ ],
+ });
+
+ const statePath = join(home, ".openviking", "hook-state", "zcode", `${sessionId}.json`);
+ await waitFor(() => existsSync(statePath));
+ const state = JSON.parse(readFileSync(statePath, "utf8"));
+ assert.equal(state.lastTurnId, "turn-001");
+ assert.deepEqual(state.capturedTurnIds, [
+ "turn-001:user",
+ "turn-001:assistant",
+ ]);
+ assert.equal(state.captured, undefined);
+});
+
+test("400 failure does not advance state and successful retry prevents duplicate Stop", async (t) => {
+ let batchAttempts = 0;
+ const requests = [];
+ const server = createServer((request, response) => {
+ const chunks = [];
+ request.on("data", (chunk) => chunks.push(chunk));
+ request.on("end", () => {
+ requests.push({
+ url: request.url,
+ body: Buffer.concat(chunks).toString(),
+ });
+ const isBatch = request.url?.endsWith("/messages/batch");
+ if (isBatch) batchAttempts++;
+ const status = isBatch && batchAttempts === 1 ? 400 : 200;
+ response.writeHead(status, { "Content-Type": "application/json" });
+ response.end(status === 400
+ ? '{"status":"error","error":{"message":"invalid request"}}'
+ : '{"result":{}}');
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ t.after(() => server.close());
+
+ const home = mkdtempSync(join(tmpdir(), "zcode-retry-"));
+ t.after(() => rmSync(home, { recursive: true, force: true }));
+ const sessionId = "sess-retry-test";
+ const rolloutDir = join(home, ".zcode", "cli", "rollout");
+ const stateDir = join(home, ".openviking", "hook-state", "zcode");
+ mkdirSync(rolloutDir, { recursive: true });
+ mkdirSync(stateDir, { recursive: true });
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessionId}.jsonl`),
+ `${JSON.stringify({
+ turnId: "turn-001",
+ request: { messages: [{ role: "user", content: "retry question" }] },
+ response: { text: "retry answer" },
+ })}\n`,
+ );
+ const statePath = join(stateDir, `${sessionId}.json`);
+ const pendingPrompt = { prompt: "retry question", hash: "prompt-hash", at: 123 };
+ writeFileSync(statePath, `${JSON.stringify({ version: 1, pendingPrompt })}\n`);
+ const env = {
+ HOME: home,
+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
+ OPENVIKING_WRITE_PATH_ASYNC: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ };
+
+ const first = await runHook({ session_id: sessionId, cwd: home }, env);
+ assert.equal(first.status, 0, first.stderr);
+ const failedState = JSON.parse(readFileSync(statePath, "utf8"));
+ assert.equal(failedState.lastTurnId ?? null, null);
+ assert.deepEqual(failedState.capturedTurnIds, []);
+ assert.deepEqual(failedState.pendingPrompt, pendingPrompt);
+ assert.equal(requests.length, 1);
+
+ const second = await runHook({ session_id: sessionId, cwd: home }, env);
+ assert.equal(second.status, 0, second.stderr);
+ const retriedBatch = requests.filter(({ url }) => url?.endsWith("/messages/batch"))[1];
+ assert.deepEqual(JSON.parse(retriedBatch.body), {
+ messages: [
+ { role: "user", content: "retry question", turn_id: "turn-001" },
+ { role: "assistant", content: "retry answer", turn_id: "turn-001" },
+ ],
+ });
+ const successfulState = JSON.parse(readFileSync(statePath, "utf8"));
+ assert.equal(successfulState.lastTurnId, "turn-001");
+ assert.deepEqual(successfulState.capturedTurnIds, [
+ "turn-001:user",
+ "turn-001:assistant",
+ ]);
+ assert.equal(successfulState.pendingPrompt, null);
+ assert.equal(successfulState.captured, undefined);
+
+ const requestCountAfterSuccess = requests.length;
+ const third = await runHook({ session_id: sessionId, cwd: home }, env);
+ assert.equal(third.status, 0, third.stderr);
+ assert.equal(requests.length, requestCountAfterSuccess);
+});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.mjs b/examples/zcode-memory-plugin/scripts/zcode-capture.mjs
new file mode 100644
index 000000000..29ca5fea0
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-capture.mjs
@@ -0,0 +1,82 @@
+import { stableHash } from "./shared/agent-hook-runtime.mjs";
+import { cleanZcodeText } from "./zcode-turns.mjs";
+
+export function zcodeTurnDedupKey(turn) {
+ return turn.turnId
+ ? `${turn.turnId}:${turn.role}`
+ : stableHash(turn.role, turn.content);
+}
+
+export function buildZcodeCapturePlan(turns, state = {}) {
+ const capturedTurnIds = new Set(
+ Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
+ );
+ const candidates = turns.map((turn) => ({
+ dedupKey: zcodeTurnDedupKey(turn),
+ turn,
+ }));
+ const toSend = candidates.filter((item) => !capturedTurnIds.has(item.dedupKey));
+ const payloads = toSend.map(({ turn }) => ({
+ role: turn.role,
+ content: turn.content,
+ ...(turn.turnId ? { turn_id: turn.turnId } : {}),
+ }));
+ return { candidates, toSend, payloads };
+}
+
+function acknowledgedCursor(candidates, acknowledged) {
+ let cursor = null;
+ let currentTurnId = null;
+ let currentComplete = true;
+
+ for (const item of candidates) {
+ const turnId = item.turn.turnId || null;
+ if (!turnId) continue;
+ if (currentTurnId !== turnId) {
+ if (currentTurnId && currentComplete) cursor = currentTurnId;
+ if (currentTurnId && !currentComplete) return cursor;
+ currentTurnId = turnId;
+ currentComplete = true;
+ }
+ if (!acknowledged.has(item.dedupKey)) currentComplete = false;
+ }
+
+ if (currentTurnId && currentComplete) cursor = currentTurnId;
+ return cursor;
+}
+
+export function applyZcodeCaptureResult(state, plan, result) {
+ const acknowledged = new Set(
+ Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : [],
+ );
+ const captured = Math.min(
+ plan.toSend.length,
+ Math.max(0, Number(result?.sent || 0) + Number(result?.queued || 0)),
+ );
+ const newlyAcknowledged = plan.toSend.slice(0, captured);
+ for (const item of newlyAcknowledged) acknowledged.add(item.dedupKey);
+
+ const cursor = acknowledgedCursor(plan.candidates, acknowledged);
+ const pendingPrompt = cleanZcodeText(state.pendingPrompt?.prompt || "");
+ let pendingPromptItem = null;
+ if (pendingPrompt) {
+ for (let index = plan.candidates.length - 1; index >= 0; index--) {
+ const item = plan.candidates[index];
+ if (item.turn.role === "user" && cleanZcodeText(item.turn.content) === pendingPrompt) {
+ pendingPromptItem = item;
+ break;
+ }
+ }
+ }
+ const pendingPromptAcknowledged = pendingPromptItem
+ ? acknowledged.has(pendingPromptItem.dedupKey)
+ : false;
+
+ return {
+ ...state,
+ capturedTurnIds: [...acknowledged].slice(-1000),
+ pendingPrompt: pendingPromptAcknowledged ? null : state.pendingPrompt,
+ lastTurnId: cursor || state.lastTurnId || null,
+ captured,
+ };
+}
diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs
new file mode 100644
index 000000000..15d4b0487
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs
@@ -0,0 +1,128 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ applyZcodeCaptureResult,
+ buildZcodeCapturePlan,
+} from "./zcode-capture.mjs";
+
+const turns = [
+ { role: "user", content: "question", turnId: "turn-001" },
+ { role: "assistant", content: "answer", turnId: "turn-001" },
+];
+
+test("capture plan maps host identity to the OpenViking turn_id contract", () => {
+ const plan = buildZcodeCapturePlan(turns, {});
+ assert.deepEqual(plan.payloads, [
+ { role: "user", content: "question", turn_id: "turn-001" },
+ { role: "assistant", content: "answer", turn_id: "turn-001" },
+ ]);
+ assert.equal(plan.payloads[0].turnId, undefined);
+});
+
+test("non-retryable failure keeps cursor, dedup, and pending prompt unchanged", () => {
+ const state = {
+ lastTurnId: "turn-000",
+ capturedTurnIds: [],
+ pendingPrompt: { prompt: "question", hash: "prompt-hash" },
+ };
+ const plan = buildZcodeCapturePlan(turns, state);
+ const next = applyZcodeCaptureResult(state, plan, {
+ sent: 0,
+ queued: 0,
+ failed: 2,
+ });
+
+ assert.equal(next.lastTurnId, "turn-000");
+ assert.deepEqual(next.capturedTurnIds, []);
+ assert.deepEqual(next.pendingPrompt, state.pendingPrompt);
+ assert.equal(next.captured, 0);
+});
+
+test("only the acknowledged contiguous prefix updates dedup and cursor state", () => {
+ const state = {
+ lastTurnId: "turn-000",
+ capturedTurnIds: [],
+ pendingPrompt: { prompt: "question" },
+ };
+ const plan = buildZcodeCapturePlan(turns, state);
+ const next = applyZcodeCaptureResult(state, plan, {
+ sent: 1,
+ queued: 0,
+ failed: 1,
+ });
+
+ assert.deepEqual(next.capturedTurnIds, ["turn-001:user"]);
+ assert.equal(next.lastTurnId, "turn-000");
+ assert.equal(next.pendingPrompt, null);
+});
+
+test("successful capture records every dedup key and suppresses repeated Stop", () => {
+ const state = {
+ capturedTurnIds: [],
+ pendingPrompt: { prompt: "question" },
+ };
+ const firstPlan = buildZcodeCapturePlan(turns, state);
+ const next = applyZcodeCaptureResult(state, firstPlan, {
+ sent: 2,
+ queued: 0,
+ failed: 0,
+ });
+
+ assert.deepEqual(next.capturedTurnIds, [
+ "turn-001:user",
+ "turn-001:assistant",
+ ]);
+ assert.equal(next.lastTurnId, "turn-001");
+ assert.equal(next.pendingPrompt, null);
+
+ const repeatedPlan = buildZcodeCapturePlan(turns, next);
+ assert.equal(repeatedPlan.toSend.length, 0);
+ assert.equal(repeatedPlan.payloads.length, 0);
+});
+
+test("queued messages are acknowledged like sent messages", () => {
+ const plan = buildZcodeCapturePlan(turns, {});
+ const next = applyZcodeCaptureResult({}, plan, {
+ sent: 0,
+ queued: 2,
+ failed: 0,
+ });
+
+ assert.equal(next.lastTurnId, "turn-001");
+ assert.deepEqual(next.capturedTurnIds, [
+ "turn-001:user",
+ "turn-001:assistant",
+ ]);
+});
+
+test("repeated prompt text clears only after the latest matching user is acknowledged", () => {
+ const repeatedTurns = [
+ { role: "user", content: "same question", turnId: "turn-001" },
+ { role: "assistant", content: "first answer", turnId: "turn-001" },
+ { role: "user", content: "same question", turnId: "turn-002" },
+ { role: "assistant", content: "second answer", turnId: "turn-002" },
+ ];
+ const state = {
+ capturedTurnIds: [],
+ pendingPrompt: { prompt: "same question" },
+ };
+ const plan = buildZcodeCapturePlan(repeatedTurns, state);
+ const partial = applyZcodeCaptureResult(state, plan, {
+ sent: 2,
+ queued: 0,
+ failed: 2,
+ });
+
+ assert.equal(partial.lastTurnId, "turn-001");
+ assert.deepEqual(partial.pendingPrompt, state.pendingPrompt);
+
+ const retryPlan = buildZcodeCapturePlan(repeatedTurns.slice(2), partial);
+ const complete = applyZcodeCaptureResult(partial, retryPlan, {
+ sent: 2,
+ queued: 0,
+ failed: 0,
+ });
+ assert.equal(complete.lastTurnId, "turn-002");
+ assert.equal(complete.pendingPrompt, null);
+});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
index 5cf4827f1..5d71a286a 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
+++ b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
@@ -25,7 +25,6 @@ import {
deriveAgentSessionId,
loadAgentHookConfig,
makeAgentFetchJSON,
- readHookInput,
readHookState,
recallForPrompt,
replayAgentPending,
@@ -36,6 +35,8 @@ import {
withAgentHookLock,
writeHookState,
} from "./shared/agent-hook-runtime.mjs";
+import { maybeDetach, readHookStdin } from "./shared/async-writer.mjs";
+import { applyZcodeCaptureResult, buildZcodeCapturePlan } from "./zcode-capture.mjs";
import { buildZcodeTurns, cleanZcodeText } from "./zcode-turns.mjs";
const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
@@ -62,17 +63,11 @@ function outputContext(additionalContext, hookEventName) {
);
}
-const input = await readHookInput();
-
-// ZCode may pass sessionId in camelCase or snake_case. Ensure both are present
-// so resolveNativeSessionId() finds it via the direct lookup path — avoids the
-// cwd fallback that would collide for two windows in the same directory.
-if (!input.session_id && input.sessionId) input.session_id = input.sessionId;
-
-const nativeSessionId = resolveNativeSessionId(input);
-const sessionId = deriveAgentSessionId("zc-", input);
-const cwd = resolveAgentCwd(input);
-const { fetchJSON } = makeAgentFetchJSON(cfg, cwd);
+let input = {};
+let nativeSessionId = "";
+let sessionId = "";
+let cwd = "";
+let fetchJSON;
async function main() {
if (!cfg.enabled || shouldBypassAgent(cfg, input)) {
@@ -143,51 +138,22 @@ async function main() {
if (!cfg.autoCapture) return;
await withAgentHookLock("zcode", nativeSessionId, async () => {
state = await readHookState("zcode", nativeSessionId);
- const capturedTurnIds = new Set(Array.isArray(state.capturedTurnIds) ? state.capturedTurnIds : []);
- const toSend = [];
- let newLastTurnId = state.lastTurnId || null;
-
- for (const turn of buildZcodeTurns(input, state)) {
- // Dedup key: turnId + role ensures user and assistant from the same
- // rollout entry (which share a turnId) are treated as distinct turns.
- // For stdin-only turns without turnId, fall back to stableHash.
- const dedupKey = turn.turnId
- ? `${turn.turnId}:${turn.role}`
- : stableHash(turn.role, turn.content);
- if (capturedTurnIds.has(dedupKey)) continue;
- toSend.push({ dedupKey, turn });
- if (turn.turnId) {
- newLastTurnId = turn.turnId;
- }
- }
+ const plan = buildZcodeCapturePlan(buildZcodeTurns(input, state), state);
// 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).
- if (toSend.length === 0) return;
-
- const result = await addAgentMessages(
- fetchJSON,
- sessionId,
- toSend.map((item) => item.turn),
- );
- const captured = result.sent + result.queued;
- // Only record dedup keys for successfully sent turns
- for (const item of toSend.slice(0, captured)) {
- if (!item.turn.turnId) {
- capturedTurnIds.add(item.dedupKey);
- }
- }
+ if (plan.toSend.length === 0) return;
+
+ const result = await addAgentMessages(fetchJSON, sessionId, plan.payloads);
+ const { captured, ...nextState } = applyZcodeCaptureResult(state, plan, result);
let nextCount = Number(state.capturedSinceCommit || 0) + captured;
if (captured > 0) {
const committed = await commitAgentSession(fetchJSON, sessionId);
if (committed.ok) nextCount = 0;
}
await writeHookState("zcode", nativeSessionId, {
- ...state,
- capturedTurnIds: [...capturedTurnIds].slice(-1000),
+ ...nextState,
capturedSinceCommit: nextCount,
- pendingPrompt: null,
- lastTurnId: newLastTurnId,
});
});
// Stop: no output needed (pass-through)
@@ -197,7 +163,31 @@ async function main() {
// Unknown event: pass-through silently
}
-main().catch((error) => {
+async function run() {
+ if (eventName === "stop" && cfg.enabled && cfg.autoCapture) {
+ const detached = await maybeDetach(cfg, { approve: () => {} });
+ if (detached) return;
+ }
+
+ try {
+ input = JSON.parse(await readHookStdin());
+ } catch {
+ input = {};
+ }
+
+ // ZCode may pass sessionId in camelCase or snake_case. Ensure both are present
+ // so resolveNativeSessionId() finds it via the direct lookup path — avoids the
+ // cwd fallback that would collide for two windows in the same directory.
+ if (!input.session_id && input.sessionId) input.session_id = input.sessionId;
+
+ nativeSessionId = resolveNativeSessionId(input);
+ sessionId = deriveAgentSessionId("zc-", input);
+ cwd = resolveAgentCwd(input);
+ ({ fetchJSON } = makeAgentFetchJSON(cfg, cwd));
+ await main();
+}
+
+run().catch((error) => {
logError("uncaught", error);
// Pass-through on error — never block the session
});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-turns.mjs b/examples/zcode-memory-plugin/scripts/zcode-turns.mjs
index ca98b4626..ab257d010 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-turns.mjs
+++ b/examples/zcode-memory-plugin/scripts/zcode-turns.mjs
@@ -17,9 +17,9 @@
* response: { text, toolCalls, finishReason } }
*
* Strategy:
- * 1. Try stdin payload fields for per-turn user/assistant content
- * 2. If stdin lacks user content, read the rollout file for the session
- * and extract ALL unseen turns since the last known turnId
+ * 1. Use the rollout file as the authoritative incremental transcript and
+ * extract ALL unseen turns since the last acknowledged turnId.
+ * 2. Use stdin + pendingPrompt only when the rollout file is unavailable.
*/
import { readFileSync } from "node:fs";
@@ -84,16 +84,20 @@ function extractUserFromMessages(messages) {
* @returns {Array<{role: string, content: string, turnId: string}>} Unseen turns.
*/
export function extractUnseenRolloutTurns(rolloutPath, lastKnownTurnId = null) {
- if (!rolloutPath) return [];
+ return readUnseenRolloutTurns(rolloutPath, lastKnownTurnId).turns;
+}
+
+function readUnseenRolloutTurns(rolloutPath, lastKnownTurnId = null) {
+ if (!rolloutPath) return { available: false, turns: [] };
let raw;
try {
raw = readFileSync(rolloutPath, "utf8");
} catch {
- return [];
+ return { available: false, turns: [] };
}
const lines = raw.trim().split("\n").filter(Boolean);
- if (lines.length === 0) return [];
+ if (lines.length === 0) return { available: true, turns: [] };
// If we have a lastKnownTurnId, find its position and return everything after.
// If not, return only the last entry (first-time capture).
@@ -130,20 +134,25 @@ export function extractUnseenRolloutTurns(rolloutPath, lastKnownTurnId = null) {
}
}
- return turns;
+ return { available: true, turns };
}
/**
* Extract user/assistant turns from a ZCode Stop-event payload.
*
- * Tries stdin payload fields first. Falls back to rollout file for complete
- * conversation when stdin lacks user content.
+ * Uses the rollout file first so every normal Stop observes stable host turn
+ * IDs and can recover missed Stop events. Stdin is only a compatibility
+ * fallback for environments where no rollout file can be read.
*
* @param {object} input - Raw hook stdin JSON.
* @param {object} state - Persistent hook state (may contain pendingPrompt, lastTurnId).
* @returns {Array<{role: string, content: string, turnId?: string}>} Non-empty turns.
*/
export function buildZcodeTurns(input = {}, state = {}) {
+ const rolloutPath = resolveRolloutPath(input);
+ const rollout = readUnseenRolloutTurns(rolloutPath, state.lastTurnId || null);
+ if (rollout.available) return rollout.turns;
+
// Assistant content: try documented and reverse-engineered field names
const assistantContent =
input.responseText ||
@@ -166,21 +175,8 @@ export function buildZcodeTurns(input = {}, state = {}) {
state.pendingPrompt?.prompt ||
"";
- // Build turns from stdin payload
- let turns = [
+ return [
{ role: "user", content: cleanZcodeText(userContent) },
{ role: "assistant", content: cleanZcodeText(assistantContent) },
].filter((turn) => turn.content);
-
- // If user content is missing from stdin (the known ZCode limitation),
- // use rollout file to extract ALL unseen turns with turnId.
- if (turns.length < 2 || turns[0]?.role !== "user") {
- const rolloutPath = resolveRolloutPath(input);
- const rolloutTurns = extractUnseenRolloutTurns(rolloutPath, state.lastTurnId || null);
- if (rolloutTurns.length > 0) {
- turns = rolloutTurns;
- }
- }
-
- return turns;
}
diff --git a/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
index 7521b4f67..8d5bbd518 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
+++ b/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
@@ -72,6 +72,35 @@ test("buildZcodeTurns falls back to state.pendingPrompt", () => {
assert.equal(turns[0].content, "cached question");
});
+test("buildZcodeTurns prefers rollout and recovers missed turns even with pendingPrompt", () => {
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "missed q" }] }, response: { text: "missed a" } },
+ { turnId: "turn-002", request: { messages: [{ role: "user", content: "current q" }] }, response: { text: "current a" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = buildZcodeTurns(
+ {
+ session_id: sessionId,
+ responseText: "stdin current a",
+ },
+ {
+ pendingPrompt: { prompt: "current q" },
+ },
+ );
+ process.env.HOME = originalHome;
+
+ assert.deepEqual(
+ turns.map(({ role, content, turnId }) => ({ role, content, turnId })),
+ [
+ { role: "user", content: "missed q", turnId: "turn-001" },
+ { role: "assistant", content: "missed a", turnId: "turn-001" },
+ { role: "user", content: "current q", turnId: "turn-002" },
+ { role: "assistant", content: "current a", turnId: "turn-002" },
+ ],
+ );
+});
+
test("buildZcodeTurns strips injected blocks from content", () => {
const turns = buildZcodeTurns({
prompt: "real question <openviking-context>injected</openviking-context>",