Skip to content

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

feat(integrations): add ZCode memory plugin (#3678)

阿舟的AI小站(超级个体)2c374e79d9ad
diff --git a/.gitignore b/.gitignore
index a327a779f..1e510435a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -226,3 +226,6 @@ tests/integration/.tmp_*/
# all node_modules folders
node_modules/
+
+# Local scratch / working notes
+.scratch/
diff --git a/docs/design/zcode-memory-plugin-design.md b/docs/design/zcode-memory-plugin-design.md
new file mode 100644
index 000000000..ab9220255
--- /dev/null
+++ b/docs/design/zcode-memory-plugin-design.md
@@ -0,0 +1,288 @@
+# 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 21ecef86d..8d5d9f1a3 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -11,6 +11,7 @@ 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 |
diff --git a/docs/en/agent-integrations/15-zcode.md b/docs/en/agent-integrations/15-zcode.md
new file mode 100644
index 000000000..1dbfd233a
--- /dev/null
+++ b/docs/en/agent-integrations/15-zcode.md
@@ -0,0 +1,58 @@
+# 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 d7e5adf1f..6797fac3f 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -11,6 +11,7 @@ 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 |
diff --git a/docs/zh/agent-integrations/15-zcode.md b/docs/zh/agent-integrations/15-zcode.md
new file mode 100644
index 000000000..18105bf01
--- /dev/null
+++ b/docs/zh/agent-integrations/15-zcode.md
@@ -0,0 +1,57 @@
+# 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/install.sh b/examples/memory-plugin-shared/install.sh
index b5054d936..500abb269 100644
--- a/examples/memory-plugin-shared/install.sh
+++ b/examples/memory-plugin-shared/install.sh
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
#
# OpenViking Memory Plugin shared installer for Claude Code, Codex, Cursor,
-# TRAE / TRAE CN, OpenCode, and pi.
+# TRAE / TRAE CN, ZCode, OpenCode, and pi.
#
# One-liner (GitHub):
# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)
# One-liner (TOS mirror, for regions where GitHub is unreachable):
# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos
# Non-interactive:
-# bash install.sh --harness claude,codex,cursor,trae,trae-cn,opencode,pi --dist github --lang en --url http://127.0.0.1:1933 --api-key ''
+# bash install.sh --harness claude,codex,cursor,trae,trae-cn,zcode,opencode,pi --dist github --lang en --url http://127.0.0.1:1933 --api-key ''
# Format-compatible CLI aliases:
# bash install.sh --harness codex --codex-bin codex,traex
# bash install.sh --harness claude --claude-bin claude,seed
@@ -143,7 +143,7 @@ usage() {
Usage: install.sh [options]
Options:
- --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, opencode, pi.
+ --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, zcode, opencode, pi.
--claude-bin LIST Comma-separated Claude-format CLI commands (default: claude).
--codex-bin LIST Comma-separated Codex-format CLI commands (default: codex).
--dist CHANNEL github (default) | tos (mirror for GitHub-blocked regions).
@@ -369,7 +369,7 @@ EOF
}
refresh_available_harnesses() {
- HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0
+ HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0
has_available_bin "$CLAUDE_BINS" && HAVE_CLAUDE=1
has_available_bin "$CODEX_BINS" && HAVE_CODEX=1
{ command -v cursor >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1 || [ -d "/Applications/Cursor.app" ] || [ -d "$HOME/.cursor" ]; } && HAVE_CURSOR=1
@@ -377,6 +377,7 @@ refresh_available_harnesses() {
{ [ -d "/Applications/Trae CN.app" ] || [ -d "/Applications/TRAE SOLO CN.app" ] || [ -d "$HOME/.trae-cn" ]; } && HAVE_TRAE_CN=1
command -v opencode >/dev/null 2>&1 && HAVE_OPENCODE=1
command -v pi >/dev/null 2>&1 && HAVE_PI=1
+ { command -v zcode >/dev/null 2>&1 || [ -d "$HOME/.zcode" ]; } && HAVE_ZCODE=1
return 0
}
@@ -443,7 +444,7 @@ NODE
CLAUDE_BINS="$(normalize_bin_list "$CLAUDE_BINS_ARG" claude)"
CODEX_BINS="$(normalize_bin_list "$CODEX_BINS_ARG" codex)"
-HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0
+HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0
refresh_available_harnesses
TUI_CLAUDE_BINS="$CLAUDE_BINS"
@@ -455,6 +456,7 @@ SEL_PI=0
SEL_CURSOR_APP=0
SEL_TRAE=0
SEL_TRAE_CN=0
+SEL_ZCODE=0
TUI_CURSOR=0; TUI_LINES=0
list_count() {
@@ -468,7 +470,7 @@ EOF
}
tui_selectable_count() {
- printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 5 ))
+ printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 6 ))
}
tui_total_count() {
@@ -500,6 +502,8 @@ EOF
if [ "$i" -eq "$idx" ]; then printf 'trae|trae'; return 0; fi
i=$((i + 1))
if [ "$i" -eq "$idx" ]; then printf 'trae-cn|trae-cn'; return 0; fi
+ i=$((i + 1))
+ if [ "$i" -eq "$idx" ]; then printf 'zcode|zcode'; return 0; fi
printf 'add|'
}
@@ -529,6 +533,7 @@ tui_bin_label() {
cursor:*) printf 'Cursor' ;;
trae:*) printf 'TRAE' ;;
trae-cn:*) printf 'TRAE CN' ;;
+ zcode:*) printf 'ZCode' ;;
claude:*) printf '%s %s' "$bin" "$(t '(Claude-format)' '(Claude 格式)')" ;;
codex:*) printf '%s %s' "$bin" "$(t '(Codex-format)' '(Codex 格式)')" ;;
esac
@@ -548,6 +553,8 @@ tui_bin_selected() {
[ "$SEL_CURSOR_APP" -eq 1 ]
elif [ "$kind" = "trae" ]; then
[ "$SEL_TRAE" -eq 1 ]
+ elif [ "$kind" = "zcode" ]; then
+ [ "$SEL_ZCODE" -eq 1 ]
else
[ "$SEL_TRAE_CN" -eq 1 ]
fi
@@ -558,6 +565,7 @@ tui_bin_detected() { # tui_bin_detected <kind> <bin>
cursor) [ "$HAVE_CURSOR" -eq 1 ] ;;
trae) [ "$HAVE_TRAE" -eq 1 ] ;;
trae-cn) [ "$HAVE_TRAE_CN" -eq 1 ] ;;
+ zcode) [ "$HAVE_ZCODE" -eq 1 ] ;;
*) command -v "$2" >/dev/null 2>&1 ;;
esac
}
@@ -570,6 +578,7 @@ tui_set_all_bins() {
SEL_CURSOR_APP=1
SEL_TRAE=1
SEL_TRAE_CN=1
+ SEL_ZCODE=1
}
tui_toggle_bin() {
@@ -588,6 +597,8 @@ tui_toggle_bin() {
SEL_CURSOR_APP=$((1 - SEL_CURSOR_APP)); return 0
elif [ "$kind" = "trae" ]; then
SEL_TRAE=$((1 - SEL_TRAE)); return 0
+ elif [ "$kind" = "zcode" ]; then
+ SEL_ZCODE=$((1 - SEL_ZCODE)); return 0
else
SEL_TRAE_CN=$((1 - SEL_TRAE_CN)); return 0
fi
@@ -658,6 +669,7 @@ tui_reset_bin_selection() {
SEL_CURSOR_APP=0
SEL_TRAE=0
SEL_TRAE_CN=0
+ SEL_ZCODE=0
while IFS= read -r bin; do
[ -n "$bin" ] || continue
if command -v "$bin" >/dev/null 2>&1; then
@@ -681,6 +693,7 @@ EOF
if [ "$HAVE_CURSOR" -eq 1 ]; then SEL_CURSOR_APP=1; any=1; fi
if [ "$HAVE_TRAE" -eq 1 ]; then SEL_TRAE=1; any=1; fi
if [ "$HAVE_TRAE_CN" -eq 1 ]; then SEL_TRAE_CN=1; any=1; fi
+ if [ "$HAVE_ZCODE" -eq 1 ]; then SEL_ZCODE=1; any=1; fi
if [ "$any" -ne 1 ]; then
SEL_CLAUDE_BINS="$TUI_CLAUDE_BINS"
SEL_CODEX_BINS="$TUI_CODEX_BINS"
@@ -768,7 +781,7 @@ tui_add_compatible_cli() {
tui_has_selection() {
[ -n "$(list_words "$SEL_CLAUDE_BINS")" ] || [ -n "$(list_words "$SEL_CODEX_BINS")" ] \
|| [ "$SEL_OPENCODE" -eq 1 ] || [ "$SEL_PI" -eq 1 ] || [ "$SEL_CURSOR_APP" -eq 1 ] \
- || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ]
+ || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ] || [ "$SEL_ZCODE" -eq 1 ]
}
tui_finish_selection() {
@@ -782,6 +795,7 @@ tui_finish_selection() {
[ "$SEL_CURSOR_APP" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}cursor"
[ "$SEL_TRAE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae"
[ "$SEL_TRAE_CN" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae-cn"
+ [ "$SEL_ZCODE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}zcode"
return 0
}
@@ -852,6 +866,7 @@ select_harnesses() {
[ "$HAVE_TRAE_CN" -eq 1 ] && detected="${detected:+$detected,}trae-cn"
[ "$HAVE_OPENCODE" -eq 1 ] && detected="${detected:+$detected,}opencode"
[ "$HAVE_PI" -eq 1 ] && detected="${detected:+$detected,}pi"
+ [ "$HAVE_ZCODE" -eq 1 ] && detected="${detected:+$detected,}zcode"
if [ -n "$REQUESTED_HARNESSES" ]; then
SELECTED_HARNESSES="$REQUESTED_HARNESSES"
@@ -897,7 +912,7 @@ validate_selected_harnesses() {
local h bad=0
while IFS= read -r h; do
case "$h" in
- claude|codex|cursor|trae|trae-cn|opencode|pi) ;;
+ claude|codex|cursor|trae|trae-cn|opencode|pi|zcode) ;;
*) err "Unsupported harness: $h"; bad=1 ;;
esac
done <<EOF
@@ -936,7 +951,7 @@ EOF
if contains_harness pi && command -v pi >/dev/null 2>&1; then ok=1; fi
# Cursor and TRAE are config-driven integrations. They may be installed
# before the desktop app itself, so a CLI in PATH is not required.
- if contains_harness cursor || contains_harness trae || contains_harness trae-cn; then ok=1; fi
+ if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness zcode; then ok=1; fi
if [ "$ok" -ne 1 ]; then
err "$(t 'No selected compatible CLI command was found in PATH.' '未在 PATH 中找到任何已选择的兼容 CLI 命令。')"
exit 2
@@ -1793,6 +1808,7 @@ function isOpenVikingHook(value) {
return text.includes("OPENVIKING_INTEGRATION_ID") || (text.includes("openviking") && [
"cursor-hook.mjs",
"trae-hook.mjs",
+ "zcode-hook.mjs",
"session-start.mjs",
"auto-recall.mjs",
"auto-capture.mjs",
@@ -1824,10 +1840,15 @@ function renderHookCommand(command) {
if (cursorMatch) {
rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, cursorMatch[1]))}`;
} else {
- const traeMatch = /^node\s+__OPENVIKING_TRAE_ROOT__\/(\S+)\s+(.+)$/u.exec(rendered);
- if (!traeMatch) throw new Error(`Unsupported ${clientId} hook command template: ${command}`);
- rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, traeMatch[1]))} ${traeMatch[2]
- .replaceAll("__OPENVIKING_CLIENT_ID__", clientId)}`;
+ const pluginRootMatch = /^node\s+"?\$\{(?:CLAUDE_PLUGIN_ROOT|ZCODE_PLUGIN_ROOT)\}"?\/(.+?)"?$/u.exec(rendered);
+ if (pluginRootMatch) {
+ rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, pluginRootMatch[1]))}`;
+ } else {
+ const traeMatch = /^node\s+__OPENVIKING_TRAE_ROOT__\/(\S+)\s+(.+)$/u.exec(rendered);
+ if (!traeMatch) throw new Error(`Unsupported ${clientId} hook command template: ${command}`);
+ rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, traeMatch[1]))} ${traeMatch[2]
+ .replaceAll("__OPENVIKING_CLIENT_ID__", clientId)}`;
+ }
}
return `${envPrefix} ${rendered} # openviking-memory`;
}
@@ -1955,6 +1976,7 @@ function ownsHook(value) {
return text.includes("openviking") && [
"cursor-hook.mjs",
"trae-hook.mjs",
+ "zcode-hook.mjs",
"session-start.mjs",
"auto-recall.mjs",
"auto-capture.mjs",
@@ -2003,9 +2025,53 @@ uninstall_agent_integrations() {
rm -rf "$OV_HOME/agent-integrations/trae-cn"
info "$(t 'Removed TRAE CN OpenViking hooks and MCP config.' '已移除 TRAE CN OpenViking hooks 与 MCP 配置。')"
fi
+ if contains_harness zcode; then
+ # ZCode reads hooks/MCP from config.json, not standalone files.
+ # Use a node script to strip openviking entries from config.json.
+ # Safe read: ENOENT → skip; parse error → skip (do NOT overwrite user data).
+ "$NODE_BIN" - "$HOME/.zcode/cli/config.json" <<'CLEAN_NODE' 2>/dev/null || true
+const fs = require("node:fs");
+const configPath = process.argv[2];
+if (!fs.existsSync(configPath)) process.exit(0);
+let config;
+try {
+ config = JSON.parse(fs.readFileSync(configPath, "utf8"));
+} catch {
+ // Malformed config — do NOT overwrite; skip cleanup silently.
+ process.exit(0);
+}
+if (typeof config !== "object" || config === null || Array.isArray(config)) process.exit(0);
+// Remove openviking hooks from each event
+if (config.hooks?.events) {
+ for (const [event, handlers] of Object.entries(config.hooks.events)) {
+ config.hooks.events[event] = (Array.isArray(handlers) ? handlers : []).filter(
+ (group) => !JSON.stringify(group).includes("openviking-memory"),
+ );
+ if (config.hooks.events[event].length === 0) delete config.hooks.events[event];
+ }
+ if (Object.keys(config.hooks.events).length === 0) delete config.hooks.events;
+}
+// Remove openviking MCP server — ONLY if it's managed by us (contains openviking-memory tag)
+if (config.mcp?.servers?.openviking) {
+ if (JSON.stringify(config.mcp.servers.openviking).includes("openviking-memory")) {
+ delete config.mcp.servers.openviking;
+ if (Object.keys(config.mcp.servers).length === 0) delete config.mcp.servers;
+ if (Object.keys(config.mcp).length === 0) delete config.mcp;
+ }
+}
+const tmp = `${configPath}.${process.pid}.tmp`;
+fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n");
+fs.renameSync(tmp, configPath);
+CLEAN_NODE
+ # Clean up intermediate files generated by agent_write_json_configs
+ rm -f "$HOME/.zcode/hooks.json" "$HOME/.zcode/mcp.json" 2>/dev/null
+ rm -rf "$OV_HOME/agent-integrations/zcode"
+ info "$(t 'Removed ZCode OpenViking hooks and MCP config.' '已移除 ZCode OpenViking hooks 与 MCP 配置。')"
+ fi
if [ ! -d "$OV_HOME/agent-integrations/cursor" ] \
&& [ ! -d "$OV_HOME/agent-integrations/trae" ] \
- && [ ! -d "$OV_HOME/agent-integrations/trae-cn" ]; then
+ && [ ! -d "$OV_HOME/agent-integrations/trae-cn" ] \
+ && [ ! -d "$OV_HOME/agent-integrations/zcode" ]; then
rm -rf "$OV_HOME/agent-integrations/memory-plugin-shared"
fi
}
@@ -2065,6 +2131,101 @@ install_cursor() {
fi
}
+zcode_mcp_path() {
+ printf '%s' "$HOME/.zcode/mcp.json"
+}
+
+zcode_merge_config() { # zcode_merge_config <config_path> <hooks_path> <mcp_path>
+ "$NODE_BIN" - "$1" "$2" "$3" <<'ZCODE_MERGE_NODE'
+const fs = require("node:fs");
+const path = require("node:path");
+const [configPath, hooksPath, mcpPath] = process.argv.slice(2);
+
+// --- Safe read: ENOENT → empty config; parse error → abort, do NOT overwrite ---
+let config = {};
+const exists = fs.existsSync(configPath);
+if (exists) {
+ let raw;
+ try {
+ raw = fs.readFileSync(configPath, "utf8");
+ } catch (e) {
+ process.stderr.write(`Cannot read ${configPath}: ${e.message}\n`);
+ process.exit(1);
+ }
+ try {
+ config = JSON.parse(raw);
+ } catch (e) {
+ process.stderr.write(`${configPath} is malformed and will NOT be overwritten: ${e.message}\n`);
+ process.exit(1);
+ }
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
+ process.stderr.write(`${configPath} top-level value is not an object; refusing to overwrite\n`);
+ process.exit(1);
+ }
+}
+
+// --- Merge hooks ---
+if (fs.existsSync(hooksPath)) {
+ const hooks = JSON.parse(fs.readFileSync(hooksPath, "utf8"));
+ config.hooks = config.hooks || {};
+ config.hooks.enabled = true;
+ config.hooks.events = config.hooks.events || {};
+ if (hooks.hooks) {
+ for (const [event, handlers] of Object.entries(hooks.hooks)) {
+ const existing = (config.hooks.events[event] || []).filter(
+ (group) => !JSON.stringify(group).includes("openviking-memory"),
+ );
+ config.hooks.events[event] = [...existing, ...handlers];
+ }
+ }
+}
+
+// --- Merge MCP: only manage entries tagged as openviking-memory ---
+if (fs.existsSync(mcpPath)) {
+ const stat = fs.statSync(mcpPath);
+ if (stat.size > 0) {
+ const mcp = JSON.parse(fs.readFileSync(mcpPath, "utf8"));
+ config.mcp = config.mcp || {};
+ config.mcp.servers = config.mcp.servers || {};
+ const incoming = mcp.mcpServers || {};
+ if (mcp.openviking) incoming.openviking = mcp.openviking;
+ for (const [name, server] of Object.entries(incoming)) {
+ const existing = config.mcp.servers[name];
+ // Only replace if the entry doesn't exist OR is already managed by us
+ if (existing && !JSON.stringify(existing).includes("openviking-memory")) {
+ process.stderr.write(`Skipping ${name} MCP server: already exists and is not managed by OpenViking\n`);
+ continue;
+ }
+ config.mcp.servers[name] = server;
+ }
+ }
+}
+
+// --- Atomic write: backup + tmp + rename ---
+if (exists) fs.copyFileSync(configPath, `${configPath}.bak`);
+const tmp = `${configPath}.${process.pid}.tmp`;
+fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n");
+fs.renameSync(tmp, configPath);
+ZCODE_MERGE_NODE
+}
+
+install_zcode() {
+ heading "$(t 'ZCode integration' 'ZCode 集成')"
+ local root hooks_path mcp_path config_path
+ root="$(assemble_agent_integration zcode-memory-plugin zcode)" || return 1
+ hooks_path="$HOME/.zcode/hooks.json"
+ mcp_path="$(zcode_mcp_path)"
+ config_path="$HOME/.zcode/cli/config.json"
+ mkdir -p "$HOME/.zcode/cli"
+ agent_write_json_configs zcode "$hooks_path" "$mcp_path" "$root" zcode "$NODE_BIN"
+ # ZCode reads hooks from config.json → hooks.events, not a standalone hooks.json.
+ # Merge the generated hooks.json and mcp.json into config.json so ZCode picks them up.
+ zcode_merge_config "$config_path" "$hooks_path" "$mcp_path" \
+ || { warn "$(t 'Failed to merge ZCode config' 'ZCode 配置合并失败')"; return 1; }
+ info "$(t 'ZCode hooks installed:' 'ZCode hooks 已安装:') $config_path (hooks.events)"
+ info "$(t 'ZCode MCP installed:' 'ZCode MCP 已安装:') $config_path (mcp.servers)"
+}
+
install_trae_variant() { # install_trae_variant <trae|trae-cn>
local client_id="$1" root hooks_path mcp_path
root="$(assemble_agent_integration trae-memory-hooks "$client_id")" || return 1
@@ -2655,6 +2816,32 @@ EOF
ok=0; agent_fatal=1
fi
fi
+ if contains_harness zcode; then
+ local zcode_config="$HOME/.zcode/cli/config.json"
+ if grep -q 'scripts/session-start.mjs' "$zcode_config" 2>/dev/null \
+ && grep -q 'scripts/auto-recall.mjs' "$zcode_config" 2>/dev/null \
+ && grep -q 'scripts/auto-capture.mjs' "$zcode_config" 2>/dev/null \
+ && grep -q 'scripts/uri-guard.mjs' "$zcode_config" 2>/dev/null \
+ && grep -q 'OPENVIKING_INTEGRATION_ID' "$zcode_config" 2>/dev/null \
+ && grep -q 'mcp-proxy.mjs' "$zcode_config" 2>/dev/null \
+ && [ -f "$OV_HOME/agent-integrations/zcode/scripts/zcode-hook.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/zcode/scripts/uri-guard.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/zcode/integration.json" ]; then
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/zcode/scripts/zcode-hook.mjs" \
+ || { ok=0; agent_fatal=1; }
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/zcode/scripts/uri-guard.mjs" \
+ || { ok=0; agent_fatal=1; }
+ if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \
+ "$NODE_BIN" "$OV_HOME/agent-integrations/zcode/scripts/session-start.mjs" >/dev/null; then
+ warn "zcode: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
+ ok=0; agent_fatal=1
+ fi
+ info "zcode: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"
+ else
+ warn "zcode: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"
+ ok=0; agent_fatal=1
+ fi
+ fi
if contains_harness opencode; then
local ocfg="$HOME/.config/opencode/opencode.json"
local ocfgc="$HOME/.config/opencode/opencode.jsonc"
@@ -2773,6 +2960,7 @@ fi
if contains_harness cursor; then install_cursor; fi
if contains_harness trae; then install_trae_variant trae; fi
if contains_harness trae-cn; then install_trae_variant trae-cn; fi
+if contains_harness zcode; then install_zcode; fi
if contains_harness opencode; then install_opencode; fi
if contains_harness pi; then install_pi; fi
validate_install
@@ -2788,5 +2976,6 @@ if contains_harness codex; then info "Codex-format: $(list_words "$CODEX_BINS")
if contains_harness cursor; then info "Cursor: Hooks + MCP + Rule + Skill"; fi
if contains_harness trae; then info "TRAE: ~/.trae/hooks.json + MCP"; fi
if contains_harness trae-cn; then info "TRAE CN: ~/.trae-cn/hooks.json + MCP"; fi
+if contains_harness zcode; then info "ZCode: ~/.zcode/cli/config.json (hooks + MCP)"; fi
if contains_harness opencode; then info "OpenCode: @openviking/opencode-plugin"; fi
if contains_harness pi; then info "pi: ~/.pi/agent/extensions/openviking"; fi
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index 19344baa2..04a454590 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -24,6 +24,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
+ { dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjs
index e3abc7c77..91363016e 100644
--- a/examples/memory-plugin-shared/sync.test.mjs
+++ b/examples/memory-plugin-shared/sync.test.mjs
@@ -24,6 +24,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
+ { dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
diff --git a/examples/zcode-memory-plugin/.mcp.json b/examples/zcode-memory-plugin/.mcp.json
new file mode 100644
index 000000000..1845bf92f
--- /dev/null
+++ b/examples/zcode-memory-plugin/.mcp.json
@@ -0,0 +1,10 @@
+{
+ "mcpServers": {
+ "openviking": {
+ "command": "node",
+ "args": [
+ "${ZCODE_PLUGIN_ROOT}/servers/mcp-proxy.mjs"
+ ]
+ }
+ }
+}
diff --git a/examples/zcode-memory-plugin/.zcode-plugin/plugin.json b/examples/zcode-memory-plugin/.zcode-plugin/plugin.json
new file mode 100644
index 000000000..8ea5f3604
--- /dev/null
+++ b/examples/zcode-memory-plugin/.zcode-plugin/plugin.json
@@ -0,0 +1,19 @@
+{
+ "name": "openviking-memory",
+ "version": "0.1.0",
+ "description": "Long-term semantic memory for ZCode, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
+ "author": {
+ "name": "OpenViking",
+ "url": "https://github.com/volcengine/OpenViking"
+ },
+ "repository": "https://github.com/volcengine/OpenViking",
+ "license": "Apache-2.0",
+ "keywords": [
+ "memory",
+ "openviking",
+ "semantic-search",
+ "long-term-memory",
+ "context-engine"
+ ],
+ "mcpServers": "./.mcp.json"
+}
diff --git a/examples/zcode-memory-plugin/DESIGN.md b/examples/zcode-memory-plugin/DESIGN.md
new file mode 100644
index 000000000..fb31d4e3e
--- /dev/null
+++ b/examples/zcode-memory-plugin/DESIGN.md
@@ -0,0 +1,63 @@
+# DESIGN: ZCode Memory Plugin
+
+## Verified ZCode extension surface
+
+These facts were verified against a live ZCode installation (built-in `zcode-guide` plugin docs + actual `~/.zcode/cli/config.json` + 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 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 |
+
+## Key design decisions
+
+### 1. Vendor shared runtime (not relative path)
+
+Unlike TRAE/Cursor (which import shared lib via cross-directory relative paths), the ZCode plugin **vendors** the shared runtime into `scripts/shared/` — the same pattern as Claude Code and Codex. This makes the plugin self-contained and relocatable.
+
+**Provenance**: Adversarial review B1 — vendor and relative-path are mutually inconsistent; pure vendor was chosen because ZCode's config-driven install model copies files to `~/.openviking/agent-integrations/`.
+
+### 2. Config-file hooks (not plugin-manifest hooks)
+
+`install_zcode()` writes hooks and MCP config into `~/.zcode/cli/config.json` (the config-file scope), not via plugin marketplace registration. This mirrors the Cursor/TRAE install pattern.
+
+`${ZCODE_PLUGIN_ROOT}` in the source `hooks/hooks.json` is replaced by absolute paths at install time by `renderHookCommand()` in `install.sh`, so the config-file "no template expansion" limitation does not apply.
+
+**Provenance**: Adversarial review R4 — config-file hooks require `hooks.enabled: true`; the merge script sets this automatically.
+
+### 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`.
+
+**Provenance**: Adversarial review R1 — confirmed all 4 event names valid; R4 — unsupported events silently dropped.
+
+### 4. Output schema: ZCode-canonical keys only
+
+ZCode's strict JSON schema rejects unrecognized keys. The dispatcher emits ONLY `{ hookSpecificOutput: { hookEventName, additionalContext } }` for context injection, and `{ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason } }` for URI guard. No `decision: "approve"` (Claude-Code-ism).
+
+**Provenance**: Adversarial review R1-F1, R4-V1 — the #1 silent-failure mode.
+
+### 5. `.zcode-plugin/plugin.json` (preferred manifest form)
+
+**Provenance**: Adversarial review R1 — `.claude-plugin/` works but `.zcode-plugin/` is the documented preferred location.
+
+## Primary unknowns
+
+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).
+
+## 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.
diff --git a/examples/zcode-memory-plugin/README.md b/examples/zcode-memory-plugin/README.md
new file mode 100644
index 000000000..5e27910ed
--- /dev/null
+++ b/examples/zcode-memory-plugin/README.md
@@ -0,0 +1,34 @@
+# OpenViking Memory Plugin for ZCode
+
+This package provides a ZCode lifecycle adapter for OpenViking long-term memory. It reuses the shared `memory-plugin-shared` runtime — no memory logic is duplicated. Only a thin ZCode adapter is new.
+
+## What it does
+
+- **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.
+
+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.
+
+## Install
+
+Use the shared installer:
+
+```bash
+bash examples/memory-plugin-shared/install.sh --harness zcode
+```
+
+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`.
+
+## 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.
+
+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
+```
diff --git a/examples/zcode-memory-plugin/README_CN.md b/examples/zcode-memory-plugin/README_CN.md
new file mode 100644
index 000000000..590049b8f
--- /dev/null
+++ b/examples/zcode-memory-plugin/README_CN.md
@@ -0,0 +1,34 @@
+# OpenViking ZCode 记忆插件
+
+本包为 ZCode 提供 OpenViking 长期记忆的生命周期适配器。复用 `memory-plugin-shared` 共享运行时——不重复任何记忆逻辑,仅新增一个 ZCode 薄适配层。
+
+## 功能
+
+- **SessionStart** — 注入用户画像和偏好/实体到上下文。
+- **UserPromptSubmit** — 搜索 OpenViking 相关记忆并注入。
+- **PreToolUse**(`Read|Glob|Grep`)— 拦截 `viking://` 虚拟路径的直接访问,引导使用 MCP 工具。
+- **Stop** — 捕获增量用户/助手对话并提交 OpenViking 会话。
+
+ZCode 不支持 `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`,因此采用 commit-on-`Stop` 策略(同 TRAE 和 Codex),补偿缺少 compact/会话结束信号的不足。
+
+## 安装
+
+使用共享安装脚本:
+
+```bash
+bash examples/memory-plugin-shared/install.sh --harness zcode
+```
+
+安装脚本通过 `~/.zcode/` 或 `zcode` 二进制检测 ZCode,将 hooks 和 MCP 配置合并到 `~/.zcode/cli/config.json`,并将 OpenViking 凭据写入 `~/.openviking/ovcli.conf`。
+
+## 架构
+
+插件通过 `sync.mjs` 将共享运行时 vendor 到 `scripts/shared/`。调度器(`zcode-hook.mjs`)按事件名分支;四个薄 shim 脚本设置环境变量后导入调度器。所有记忆逻辑(召回、捕获、提交、去重、待处理队列、凭据解析、MCP 代理)由共享运行时提供。
+
+详见 [DESIGN.md](./DESIGN.md) 了解已验证的 ZCode 扩展面事实和设计决策来源。
+
+## 测试
+
+```bash
+node --test scripts/zcode-turns.test.mjs scripts/zcode-hooks.test.mjs
+```
diff --git a/examples/zcode-memory-plugin/hooks/hooks.json b/examples/zcode-memory-plugin/hooks/hooks.json
new file mode 100644
index 000000000..ebcb12539
--- /dev/null
+++ b/examples/zcode-memory-plugin/hooks/hooks.json
@@ -0,0 +1,51 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/session-start.mjs\"",
+ "timeout": 30
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/auto-recall.mjs\"",
+ "timeout": 20
+ }
+ ]
+ }
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "Read|Glob|Grep",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/uri-guard.mjs\"",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "Stop": [
+ {
+ "matcher": "",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/auto-capture.mjs\"",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/examples/zcode-memory-plugin/openviking.integration.json b/examples/zcode-memory-plugin/openviking.integration.json
new file mode 100644
index 000000000..f1febf7ed
--- /dev/null
+++ b/examples/zcode-memory-plugin/openviking.integration.json
@@ -0,0 +1,7 @@
+{
+ "schemaVersion": 1,
+ "id": "openviking-memory",
+ "version": "0.1.0",
+ "clients": ["zcode"],
+ "capabilities": ["hooks", "mcp"]
+}
diff --git a/examples/zcode-memory-plugin/scripts/auto-capture.mjs b/examples/zcode-memory-plugin/scripts/auto-capture.mjs
new file mode 100644
index 000000000..b753af31b
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/auto-capture.mjs
@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+
+process.env.OPENVIKING_HOOK_EVENT = "stop";
+await import("./zcode-hook.mjs");
diff --git a/examples/zcode-memory-plugin/scripts/auto-recall.mjs b/examples/zcode-memory-plugin/scripts/auto-recall.mjs
new file mode 100644
index 000000000..d9cc9c2ed
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/auto-recall.mjs
@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+
+process.env.OPENVIKING_HOOK_EVENT = "user-prompt-submit";
+await import("./zcode-hook.mjs");
diff --git a/examples/zcode-memory-plugin/scripts/session-start.mjs b/examples/zcode-memory-plugin/scripts/session-start.mjs
new file mode 100644
index 000000000..6c8bb3c5b
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/session-start.mjs
@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+
+process.env.OPENVIKING_HOOK_EVENT = "session-start";
+await import("./zcode-hook.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
new file mode 100644
index 000000000..848dea82b
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -0,0 +1,241 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { buildUserAgent, resolveOpenVikingCredentials } from "./credentials.mjs";
+import { createLogger } from "./debug-log.mjs";
+import { sendSessionMessages } from "./batch-send.mjs";
+import { enqueue, replayPending } from "./pending-queue.mjs";
+import { buildProfileBlock } from "./profile-inject.mjs";
+import { buildRecallBlock } from "./recall-core.mjs";
+import { deriveHarnessSessionId, isBypassed } from "./session-model.mjs";
+import { resolveEffectivePeerId } from "./workspace-peer.mjs";
+
+const STATE_VERSION = 1;
+const STATE_DIR_MODE = 0o700;
+const STATE_FILE_MODE = 0o600;
+
+function envBool(name, fallback) {
+ const value = process.env[name];
+ if (value == null || value === "") return fallback;
+ return !["0", "false", "no", "off"].includes(value.trim().toLowerCase());
+}
+
+function envNumber(name, fallback, minimum = 0) {
+ const value = Number(process.env[name]);
+ return Number.isFinite(value) ? Math.max(minimum, value) : fallback;
+}
+
+function safePart(value) {
+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, "-");
+}
+
+export function stableHash(...values) {
+ return createHash("sha256")
+ .update(values.map((value) => String(value ?? "")).join("\n"))
+ .digest("hex");
+}
+
+export function loadAgentHookConfig(clientId) {
+ const credentials = resolveOpenVikingCredentials();
+ const debugLogPath = process.env.OPENVIKING_DEBUG_LOG
+ || join(homedir(), ".openviking", "logs", `${clientId}-hooks.log`);
+ return {
+ ...credentials,
+ clientId,
+ userAgent: buildUserAgent(clientId, process.env.OPENVIKING_INTEGRATION_VERSION),
+ enabled: envBool("OPENVIKING_MEMORY_ENABLED", true),
+ autoRecall: envBool("OPENVIKING_AUTO_RECALL", true),
+ autoCapture: envBool("OPENVIKING_AUTO_CAPTURE", true),
+ workspacePeer: envBool("OPENVIKING_WORKSPACE_PEER", true),
+ bypassSession: envBool("OPENVIKING_BYPASS_SESSION", false),
+ bypassSessionPatterns: String(process.env.OPENVIKING_BYPASS_SESSION_PATTERNS || "")
+ .split(",").map((item) => item.trim()).filter(Boolean),
+ recallLimit: envNumber("OPENVIKING_RECALL_LIMIT", 6, 1),
+ recallTokenBudget: envNumber("OPENVIKING_RECALL_TOKEN_BUDGET", 2000, 200),
+ recallMaxContentChars: envNumber("OPENVIKING_RECALL_MAX_CONTENT_CHARS", 500, 50),
+ scoreThreshold: envNumber("OPENVIKING_SCORE_THRESHOLD", 0.35, 0),
+ recallPreferAbstract: envBool("OPENVIKING_RECALL_PREFER_ABSTRACT", true),
+ recallPeerScope: process.env.OPENVIKING_RECALL_PEER_SCOPE === "actor" ? "actor" : "all",
+ timeoutMs: envNumber("OPENVIKING_TIMEOUT_MS", 15000, 1000),
+ profileTokenBudget: envNumber("OPENVIKING_PROFILE_TOKEN_BUDGET", 6000, 500),
+ commitTurnThreshold: envNumber("OPENVIKING_COMMIT_TURN_THRESHOLD", 8, 1),
+ debug: envBool("OPENVIKING_DEBUG", false),
+ debugLogPath,
+ };
+}
+
+export function createAgentLogger(clientId, hookName, cfg) {
+ return createLogger(`${clientId}:${hookName}`, cfg);
+}
+
+export async function readHookInput() {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ const raw = Buffer.concat(chunks).toString();
+ if (!raw.trim()) return {};
+ try { return JSON.parse(raw); } catch { return {}; }
+}
+
+export function resolveAgentCwd(input = {}) {
+ const workspaceRoots = Array.isArray(input.workspace_roots)
+ ? input.workspace_roots
+ : Array.isArray(input.workspaceRoots) ? input.workspaceRoots : [];
+ return String(
+ input.cwd
+ || workspaceRoots.find((value) => typeof value === "string" && value.trim())
+ || process.env.CURSOR_PROJECT_DIR
+ || process.cwd(),
+ );
+}
+
+export function resolveNativeSessionId(input = {}) {
+ const direct = input.conversation_id || input.session_id || input.sessionId || input.generation_id;
+ if (direct) return safePart(direct);
+ const transcript = input.transcript_path || input.transcriptPath;
+ if (transcript) {
+ const match = String(transcript).match(/([0-9a-f]{8}-[0-9a-f-]{20,})/i);
+ return safePart(match?.[1] || stableHash(transcript).slice(0, 24));
+ }
+ const cwd = resolveAgentCwd(input);
+ return `cwd-${stableHash(cwd).slice(0, 20)}`;
+}
+
+export function deriveAgentSessionId(prefix, input = {}) {
+ return deriveHarnessSessionId(prefix, resolveNativeSessionId(input));
+}
+
+function statePath(clientId, nativeSessionId) {
+ const root = process.env.OPENVIKING_HOOK_STATE_DIR
+ || join(homedir(), ".openviking", "hook-state");
+ return join(root, safePart(clientId), `${safePart(nativeSessionId)}.json`);
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export async function withAgentHookLock(clientId, nativeSessionId, callback) {
+ const file = statePath(clientId, nativeSessionId);
+ const lock = `${file}.lock`;
+ await mkdir(dirname(file), { recursive: true, mode: STATE_DIR_MODE });
+ const deadline = Date.now() + 5000;
+ while (true) {
+ try {
+ await mkdir(lock, { mode: STATE_DIR_MODE });
+ break;
+ } catch (error) {
+ if (error?.code !== "EEXIST") throw error;
+ try {
+ if (Date.now() - (await stat(lock)).mtimeMs > 60_000) {
+ await rm(lock, { recursive: true, force: true });
+ continue;
+ }
+ } catch {}
+ if (Date.now() >= deadline) return null;
+ await sleep(50);
+ }
+ }
+ try {
+ return await callback();
+ } finally {
+ await rm(lock, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
+export async function readHookState(clientId, nativeSessionId) {
+ try {
+ const parsed = JSON.parse(await readFile(statePath(clientId, nativeSessionId), "utf8"));
+ return parsed && typeof parsed === "object" ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
+export async function writeHookState(clientId, nativeSessionId, value) {
+ const file = statePath(clientId, nativeSessionId);
+ await mkdir(dirname(file), { recursive: true, mode: STATE_DIR_MODE });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify({ version: STATE_VERSION, ...value }, null, 2)}\n`, {
+ encoding: "utf8",
+ mode: STATE_FILE_MODE,
+ });
+ await rename(tmp, file);
+}
+
+export function makeAgentFetchJSON(cfg, cwd = process.cwd()) {
+ const effectivePeer = resolveEffectivePeerId({ cfg, cwd });
+ const fetchJSON = async (path, init = {}, options = {}) => {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);
+ try {
+ const headers = { "Content-Type": "application/json", ...(init.headers || {}) };
+ if (cfg.apiKey) headers.Authorization = `Bearer ${cfg.apiKey}`;
+ if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ const peerId = options.actorPeerId ?? effectivePeer.peerId;
+ if (peerId) headers["X-OpenViking-Actor-Peer"] = peerId;
+ if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ const response = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok || body.status === "error") {
+ return { ok: false, status: response.status, error: body.error || body };
+ }
+ return { ok: true, result: body.result ?? body };
+ } catch (error) {
+ return { ok: false, status: 0, error: { message: error?.message || String(error) } };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+ return { fetchJSON, effectivePeer };
+}
+
+function retryable(result) {
+ const status = Number(result?.status || 0);
+ return !status || status === 408 || status === 429 || status >= 500;
+}
+
+export async function addAgentMessage(fetchJSON, sessionId, payload) {
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ if (!result.ok && retryable(result)) await enqueue("addMessage", sessionId, payload);
+ return result;
+}
+
+export async function addAgentMessages(fetchJSON, sessionId, payloads) {
+ return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });
+}
+
+export async function commitAgentSession(fetchJSON, sessionId) {
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
+ method: "POST",
+ body: "{}",
+ });
+ if (!result.ok && retryable(result)) await enqueue("commitSession", sessionId, {});
+ return result;
+}
+
+export async function replayAgentPending(fetchJSON, log = () => {}) {
+ return replayPending(fetchJSON, log);
+}
+
+export async function recallForPrompt(fetchJSON, cfg, prompt, cwd, log = () => {}) {
+ if (!cfg.autoRecall || !String(prompt || "").trim()) return null;
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ return buildRecallBlock(fetchJSON, cfg, prompt, { actorPeerId: peer.peerId, log });
+}
+
+export async function buildAgentProfile(fetchJSON, cfg, cwd) {
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ const profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget, peer.peerId);
+ return profile?.block || null;
+}
+
+export function shouldBypassAgent(cfg, input = {}) {
+ return isBypassed(cfg, { sessionId: resolveNativeSessionId(input), cwd: resolveAgentCwd(input) });
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/agent-uri-guard.mjs b/examples/zcode-memory-plugin/scripts/shared/agent-uri-guard.mjs
new file mode 100644
index 000000000..d0dada027
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/agent-uri-guard.mjs
@@ -0,0 +1,47 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { buildGuardMessage, findVikingUri, normalizeToolName } from "./uri-guard.mjs";
+
+const TOOL_HINTS = {
+ read: {
+ tool: "OpenViking MCP read",
+ example: (uri) => `read(uris="${uri}")`,
+ },
+ glob: {
+ tool: "OpenViking MCP glob or list",
+ example: (uri, input = {}) => (
+ `glob(pattern="${String(input.pattern ?? "**/*").replaceAll('"', '\\"')}", uri="${uri}")`
+ ),
+ },
+ grep: {
+ tool: "OpenViking MCP grep or search",
+ example: (uri, input = {}) => (
+ `grep(uri="${uri}", pattern="${String(input.pattern ?? "").replaceAll('"', '\\"')}")`
+ ),
+ },
+ bash: {
+ tool: "OpenViking MCP read or search",
+ example: (uri) => `read(uris="${uri}")`,
+ },
+ runcommand: {
+ tool: "OpenViking MCP read or search",
+ example: (uri) => `read(uris="${uri}")`,
+ },
+ shell: {
+ tool: "OpenViking MCP read or search",
+ example: (uri) => `read(uris="${uri}")`,
+ },
+};
+
+export function evaluateAgentUriGuard(toolName, input = {}) {
+ const hint = TOOL_HINTS[normalizeToolName(toolName)];
+ if (!hint) return null;
+ const uri = findVikingUri(input);
+ if (!uri) return null;
+ return {
+ uri,
+ reason: buildGuardMessage(uri, {
+ tool: hint.tool,
+ example: hint.example(uri, input),
+ }),
+ };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/async-writer.mjs b/examples/zcode-memory-plugin/scripts/shared/async-writer.mjs
new file mode 100644
index 000000000..8ffc71468
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/async-writer.mjs
@@ -0,0 +1,78 @@
+// 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/zcode-memory-plugin/scripts/shared/batch-send.mjs b/examples/zcode-memory-plugin/scripts/shared/batch-send.mjs
new file mode 100644
index 000000000..6d929d6bf
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/batch-send.mjs
@@ -0,0 +1,122 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { enqueue } from "./pending-queue.mjs";
+
+export const BATCH_LIMIT = 100;
+
+export function isRetryableSendFailure(res) {
+ if (!res || res.ok) return false;
+ const status = Number(res.status || 0);
+ return !status || status === 408 || status === 429 || status >= 500;
+}
+
+function makeResult() {
+ return {
+ sent: 0,
+ queued: 0,
+ enqueueFailed: 0,
+ failed: 0,
+ retryable: false,
+ usedBatch: true,
+ lastError: null,
+ };
+}
+
+async function enqueueRemainder(sessionId, payloads, startIndex, result, retryable, lastError) {
+ result.retryable = retryable;
+ result.lastError = lastError ?? null;
+
+ if (!retryable) {
+ result.failed += Math.max(0, payloads.length - startIndex);
+ return result;
+ }
+
+ const baseCreatedAt = Date.now();
+ for (let i = startIndex; i < payloads.length; i++) {
+ const queued = await enqueue("addMessage", sessionId, payloads[i], {
+ createdAt: baseCreatedAt + (i - startIndex),
+ });
+ if (!queued.ok) {
+ // Stop at the first enqueue failure so queued entries stay a contiguous
+ // prefix: consumers mark the first sent+queued payloads as captured, so
+ // skipping a payload here and queueing a later one would silently drop it.
+ result.enqueueFailed += payloads.length - i;
+ return result;
+ }
+ result.queued++;
+ }
+ return result;
+}
+
+async function sendSerial(fetchJSON, sessionId, payloads, startIndex, opts, result) {
+ result.usedBatch = false;
+ const encodedSid = encodeURIComponent(sessionId);
+ for (let i = startIndex; i < payloads.length; i++) {
+ const res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {
+ method: "POST",
+ body: JSON.stringify(payloads[i]),
+ });
+ if (res?.ok) {
+ result.sent++;
+ await opts.onSent?.(1);
+ continue;
+ }
+
+ const retryable = isRetryableSendFailure(res);
+ if (opts.enqueueOnRetryable) {
+ return enqueueRemainder(sessionId, payloads, i, result, retryable, res?.error ?? res);
+ }
+ result.retryable = retryable;
+ result.lastError = res?.error ?? res ?? null;
+ result.failed += payloads.length - i;
+ return result;
+ }
+ return result;
+}
+
+/**
+ * Send add-message payloads in server-sized batches with serial fallback.
+ *
+ * @param {Function} fetchJSON - (path, init) => { ok, status, result?, error? }
+ * @param {string} sessionId - OpenViking session id
+ * @param {Array<object>} payloads - sanitized add-message request bodies
+ * @param {object} opts
+ * @param {boolean} opts.enqueueOnRetryable - enqueue unsent payloads after a retryable failure
+ * @param {Function} opts.onSent - called with the number of messages durably sent after each success
+ * @returns {Promise<{sent:number,queued:number,enqueueFailed:number,failed:number,retryable:boolean,usedBatch:boolean,lastError:any}>}
+ */
+export async function sendSessionMessages(fetchJSON, sessionId, payloads, opts = {}) {
+ const result = makeResult();
+ const messages = Array.isArray(payloads) ? payloads : [];
+ if (messages.length === 0) return result;
+
+ const encodedSid = encodeURIComponent(sessionId);
+ for (let start = 0; start < messages.length; start += BATCH_LIMIT) {
+ const chunk = messages.slice(start, start + BATCH_LIMIT);
+ const res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages/batch`, {
+ method: "POST",
+ body: JSON.stringify({ messages: chunk }),
+ });
+
+ if (res?.ok) {
+ result.sent += chunk.length;
+ await opts.onSent?.(chunk.length);
+ continue;
+ }
+
+ const status = Number(res?.status || 0);
+ if (status === 404 || status === 405) {
+ return sendSerial(fetchJSON, sessionId, messages, start, opts, result);
+ }
+
+ const retryable = isRetryableSendFailure(res);
+ if (opts.enqueueOnRetryable) {
+ return enqueueRemainder(sessionId, messages, start, result, retryable, res?.error ?? res);
+ }
+ result.retryable = retryable;
+ result.lastError = res?.error ?? res ?? null;
+ result.failed += messages.length - start;
+ return result;
+ }
+
+ return result;
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
new file mode 100644
index 000000000..c28d9ffd9
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
@@ -0,0 +1,499 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+const TEXT_BLOCK_TYPES = new Set(["text", "input_text", "output_text"]);
+const TOOL_CALL_TYPES = new Set([
+ "tool_call",
+ "toolcall",
+ "tool_use",
+ "tooluse",
+ "function_call",
+ "functioncall",
+]);
+const TOOL_RESULT_TYPES = new Set([
+ "tool_result",
+ "toolresult",
+ "tool_output",
+ "tooloutput",
+ "function_call_output",
+ "functioncalloutput",
+]);
+
+const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
+const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
+const METADATA_KEYS = [
+ "session_id",
+ "sessionid",
+ "sessionkey",
+ "conversation_id",
+ "conversationid",
+ "channel",
+ "sender",
+ "user_id",
+ "userid",
+ "agent_id",
+ "agentid",
+ "timestamp",
+ "timezone",
+ "cwd",
+ "model",
+ "permission_mode",
+];
+
+function normalizeType(value) {
+ return String(value || "").toLowerCase().replace(/[-\s]/g, "_");
+}
+
+function isToolCallBlock(block) {
+ const type = normalizeType(block?.type || block?.kind || block?.role);
+ return TOOL_CALL_TYPES.has(type) || Boolean(block?.tool_calls) || Boolean(block?.function?.name);
+}
+
+function isToolResultBlock(block) {
+ const type = normalizeType(block?.type || block?.kind || block?.role);
+ return TOOL_RESULT_TYPES.has(type) || type === "tool" || type === "function";
+}
+
+function oneLine(text) {
+ return String(text || "").replace(/\s+/g, " ").trim();
+}
+
+export function truncateCaptureText(text, maxChars = 2000) {
+ const value = String(text || "").trim();
+ if (!Number.isFinite(maxChars) || maxChars <= 0 || value.length <= maxChars) return value;
+ return `${value.slice(0, Math.max(0, maxChars - 20)).trimEnd()}\n[truncated]`;
+}
+
+function stringifyCompact(value, maxChars) {
+ if (value == null) return "";
+ if (typeof value === "string") return truncateCaptureText(value, maxChars);
+ try {
+ return truncateCaptureText(JSON.stringify(value), maxChars);
+ } catch {
+ return truncateCaptureText(String(value), maxChars);
+ }
+}
+
+function parseMaybeJson(value) {
+ if (value == null || typeof value !== "string") return value;
+ const trimmed = value.trim();
+ if (!trimmed) return value;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return value;
+ }
+}
+
+function blockText(block) {
+ if (!block || typeof block !== "object") return "";
+ if (typeof block.text === "string") return block.text;
+ if (typeof block.output_text === "string") return block.output_text;
+ if (typeof block.input_text === "string") return block.input_text;
+ if (typeof block.content === "string") return block.content;
+ return "";
+}
+
+function toolName(block) {
+ return oneLine(
+ block?.name ||
+ block?.tool_name ||
+ block?.toolName ||
+ block?.function?.name ||
+ block?.call?.name ||
+ "",
+ );
+}
+
+function toolPayload(block, kind) {
+ if (!block || typeof block !== "object") return "";
+ if (kind === "call") {
+ return block.input ??
+ block.arguments ??
+ block.args ??
+ block.params ??
+ block.function?.arguments ??
+ block.command ??
+ block.call?.input ??
+ block.call?.arguments ??
+ "";
+ }
+ return block.output ??
+ block.result ??
+ block.error ??
+ block.data ??
+ block.content ??
+ block.text ??
+ "";
+}
+
+function toolId(block) {
+ return oneLine(
+ block?.call_id ||
+ block?.callId ||
+ block?.tool_call_id ||
+ block?.toolCallId ||
+ block?.tool_use_id ||
+ block?.toolUseId ||
+ block?.function_call_id ||
+ block?.functionCallId ||
+ block?.id ||
+ "",
+ );
+}
+
+function toolStatus(block, kind) {
+ if (kind === "call") return "running";
+ if (block?.is_error || block?.error) return "error";
+ const status = oneLine(block?.status || "");
+ return status || "completed";
+}
+
+function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+ const id = toolId(block);
+ const name = toolName(block) || (id ? toolNameById[id] : "");
+ const payload = toolPayload(block, kind);
+ const part = {
+ type: "tool",
+ tool_id: id || undefined,
+ tool_name: name || undefined,
+ tool_status: toolStatus(block, kind),
+ };
+ if (kind === "call") {
+ const input = parseMaybeJson(payload);
+ if (input !== "" && input != null) {
+ part.tool_input = typeof input === "object" && !Array.isArray(input)
+ ? input
+ : { value: input };
+ }
+ } else {
+ part.tool_output = stringifyCompact(payload, toolMaxChars);
+ }
+ return part;
+}
+
+function formatToolBlock(block, kind, maxChars) {
+ const name = toolName(block);
+ const payload = toolPayload(block, kind);
+ const body = oneLine(stringifyCompact(payload, maxChars));
+ const label = kind === "call" ? "tool-call" : "tool-result";
+ return body
+ ? `[${label}${name ? ` ${name}` : ""}] ${body}`
+ : `[${label}${name ? ` ${name}` : ""}]`;
+}
+
+function blockToText(block, options) {
+ if (!block) return "";
+ if (typeof block === "string") return block;
+ if (Array.isArray(block)) return extractTextFromContent(block, options);
+ if (typeof block !== "object") return "";
+
+ if (block.item && typeof block.item === "object") {
+ const itemText = blockToText(block.item, options);
+ if (itemText) return itemText;
+ }
+
+ const type = normalizeType(block.type || block.kind || block.role);
+ if (TEXT_BLOCK_TYPES.has(type)) return blockText(block);
+ if (isToolCallBlock(block)) return formatToolBlock(block, "call", options.toolMaxChars);
+ if (isToolResultBlock(block)) return formatToolBlock(block, "result", options.toolMaxChars);
+ if (Array.isArray(block.content)) return extractTextFromContent(block.content, options);
+ if (!type) return blockText(block);
+ return "";
+}
+
+export function extractTextFromContent(content, options = {}) {
+ const opts = { toolMaxChars: 2000, ...options };
+ if (!content) return "";
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ return content
+ .map((block) => blockToText(block, opts))
+ .filter(Boolean)
+ .join("\n\n");
+ }
+ if (typeof content === "object") {
+ return blockToText(content, opts) || stringifyCompact(content, opts.toolMaxChars);
+ }
+ return "";
+}
+
+export function extractTextFromPayload(payload, options = {}) {
+ if (!payload || typeof payload !== "object") return "";
+ const chunks = [];
+ const directType = normalizeType(payload.type || payload.kind || payload.role);
+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ if (direct) return direct;
+ }
+
+ if (payload.message && typeof payload.message === "object") {
+ const messageText = extractTextFromPayload(payload.message, options);
+ if (messageText) chunks.push(messageText);
+ } else if (payload.content !== undefined) {
+ const contentText = extractTextFromContent(payload.content, options);
+ if (contentText) chunks.push(contentText);
+ }
+
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ const toolText = extractTextFromContent(value, options);
+ if (toolText) chunks.push(toolText);
+ }
+
+ if (chunks.length === 0) {
+ const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ if (direct) chunks.push(direct);
+ }
+
+ return chunks.join("\n\n");
+}
+
+function collectToolNamesByIdFromEntries(entries) {
+ const map = {};
+ for (const entry of entries || []) {
+ const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;
+ collectToolNamesByIdFromPayload(payload, map);
+ }
+ return map;
+}
+
+function collectToolNamesByIdFromPayload(payload, out) {
+ if (!payload || typeof payload !== "object") return;
+ if (payload.message && typeof payload.message === "object") {
+ collectToolNamesByIdFromPayload(payload.message, out);
+ }
+ const candidates = [];
+ if (Array.isArray(payload.content)) candidates.push(...payload.content);
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ if (Array.isArray(value)) candidates.push(...value);
+ else candidates.push(value);
+ }
+ if (isToolCallBlock(payload)) candidates.push(payload);
+ for (const block of candidates) {
+ if (!block || typeof block !== "object") continue;
+ if (!isToolCallBlock(block)) continue;
+ const id = toolId(block);
+ const name = toolName(block);
+ if (id && name) out[id] = name;
+ }
+}
+
+function extractPartsFromContent(content, options = {}) {
+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const parts = [];
+ if (!content) return parts;
+ if (typeof content === "string") {
+ if (content.trim()) parts.push({ type: "text", text: content });
+ return parts;
+ }
+ if (!Array.isArray(content)) {
+ const text = blockToText(content, opts);
+ if (text.trim()) parts.push({ type: "text", text });
+ return parts;
+ }
+ for (const block of content) {
+ if (!block || typeof block !== "object") continue;
+ if (isToolCallBlock(block)) {
+ parts.push(buildToolPart(block, "call", opts));
+ } else if (isToolResultBlock(block)) {
+ parts.push(buildToolPart(block, "result", opts));
+ } else {
+ const text = blockToText(block, opts);
+ if (text.trim()) parts.push({ type: "text", text });
+ }
+ }
+ return parts;
+}
+
+export function extractPartsFromPayload(payload, options = {}) {
+ if (!payload || typeof payload !== "object") return [];
+ const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ if (payload.message && typeof payload.message === "object") {
+ return extractPartsFromPayload(payload.message, opts);
+ }
+
+ const directType = normalizeType(payload.type || payload.kind || payload.role);
+ if (TOOL_CALL_TYPES.has(directType) || isToolCallBlock(payload)) {
+ return [buildToolPart(payload, "call", opts)];
+ }
+ if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || directType === "function") {
+ return [buildToolPart(payload, "result", opts)];
+ }
+
+ const parts = [];
+ if (payload.content !== undefined) {
+ parts.push(...extractPartsFromContent(payload.content, opts));
+ }
+ for (const key of ["tool_calls", "toolCalls", "function_call", "functionCall", "tool_call", "toolCall"]) {
+ const value = payload[key];
+ if (!value) continue;
+ if (Array.isArray(value)) {
+ for (const block of value) parts.push(...extractPartsFromPayload(block, opts));
+ } else {
+ parts.push(...extractPartsFromPayload(value, opts));
+ }
+ }
+ return parts;
+}
+
+export function extractCaptureTurns(rolloutEntries, cfg = {}) {
+ const toolNameById = collectToolNamesByIdFromEntries(rolloutEntries);
+ const turns = [];
+ for (const entry of rolloutEntries || []) {
+ if (!entry || typeof entry !== "object") continue;
+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : entry;
+ const message = payload.message && typeof payload.message === "object" ? payload.message : null;
+ const rawRole = message?.role || payload.role || payload.type || payload.kind;
+ const role = normalizeCaptureRole(rawRole);
+ if (!role) continue;
+ if (isAssistantSideCaptureRole(rawRole) && !cfg.captureAssistantTurns) continue;
+
+ const rawText = extractTextFromPayload(payload, { toolMaxChars: cfg.captureToolMaxChars });
+ const parts = extractPartsFromPayload(payload, {
+ toolMaxChars: cfg.captureToolMaxChars,
+ toolNameById,
+ });
+ const decision = shouldCaptureText(rawText, role, cfg);
+ if (!decision.shouldCapture && parts.length === 0) continue;
+ const text = decision.shouldCapture ? decision.text : "";
+ turns.push({ role, text, parts });
+ }
+ return turns;
+}
+
+export function normalizeCaptureRole(role) {
+ const value = normalizeType(role);
+ if (value === "user") return "user";
+ if (value === "assistant") return "assistant";
+ if (value === "tool" || value === "tool_result" || value === "function" || value === "function_call_output") {
+ return "user";
+ }
+ if (value === "tool_call" || value === "function_call") return "assistant";
+ return null;
+}
+
+export function isAssistantSideCaptureRole(role) {
+ const value = normalizeType(role);
+ return value === "assistant" ||
+ value === "tool" ||
+ value === "tool_result" ||
+ value === "tool_call" ||
+ value === "function" ||
+ value === "function_call" ||
+ value === "function_call_output";
+}
+
+function stripMetadataFences(text) {
+ return String(text || "").replace(/```(?:json)?\s*([\s\S]*?)```/gi, (match, body) => {
+ const lower = body.toLowerCase();
+ let hits = 0;
+ for (const key of METADATA_KEYS) {
+ const re = new RegExp(`["']?${key}["']?\\s*:`, "i");
+ if (re.test(lower)) hits += 1;
+ }
+ return hits >= 3 ? "" : match;
+ });
+}
+
+function stripInjectedDigestBlocks(text) {
+ const lines = String(text || "").split(/\r?\n/);
+ const out = [];
+ let skipping = false;
+ let skipUntilMcpHint = false;
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (/^OpenViking session archive digest:/i.test(trimmed)) {
+ skipping = true;
+ skipUntilMcpHint = true;
+ continue;
+ }
+ if (/^OpenViking memory digest:/i.test(trimmed)) {
+ skipping = true;
+ skipUntilMcpHint = false;
+ continue;
+ }
+ if (skipping) {
+ if (skipUntilMcpHint) {
+ if (/^More detail: use the OpenViking MCP /i.test(trimmed)) {
+ skipping = false;
+ skipUntilMcpHint = false;
+ }
+ continue;
+ }
+ if (!trimmed) {
+ skipping = false;
+ continue;
+ }
+ if (
+ /^(?:[-*]\s+|#{1,6}\s+|More detail:|Use OpenViking MCP|Latest committed archive|Resume continuity|viking:\/\/)/i.test(trimmed) ||
+ /^\s{2,}\S/.test(line)
+ ) {
+ continue;
+ }
+ skipping = false;
+ }
+ out.push(line);
+ }
+
+ return out.join("\n");
+}
+
+export function sanitizeCapturedText(text) {
+ let value = String(text || "");
+ value = value
+ .replace(/\u0000/g, "")
+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, " ")
+ .replace(/<relevant-memor(?:y|ies)\b[^>]*>[\s\S]*?<\/relevant-memor(?:y|ies)>/gi, " ")
+ .replace(/^\s*Sender\s*\([^)]+\)\s*```[\s\S]*?```\s*/gim, " ")
+ .replace(/^\s*Conversation (?:metadata|info):\s*```[\s\S]*?```\s*/gim, " ")
+ .replace(/^\s*\[?\d{4}-\d{2}-\d{2}[T ][^\]\n]{3,80}\]?\s*/gm, "")
+ .replace(/^\s*\d{10,13}\s+/gm, "");
+ value = stripMetadataFences(value);
+ value = stripInjectedDigestBlocks(value);
+ value = value.replace(/^\s*More detail: use the OpenViking MCP .*$/gim, " ");
+ return value
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+function hasEnoughSignal(text) {
+ const cjk = text.match(/[\u3400-\u9fff]/g)?.length || 0;
+ const alnum = text.match(/[a-z0-9]/gi)?.length || 0;
+ return cjk >= 4 || alnum >= 6 || text.length >= 12;
+}
+
+function isPunctuationOnly(text) {
+ return !/[a-z0-9\u3400-\u9fff]/i.test(text);
+}
+
+export function shouldCaptureText(text, role, cfg = {}) {
+ const maxLength = cfg.captureMaxLength || 24000;
+ const sanitized = sanitizeCapturedText(text);
+ if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
+
+ const capped = truncateCaptureText(sanitized, maxLength);
+ const compact = oneLine(capped);
+ const isToolSummary = /^\[tool-(?:call|result)\b/i.test(compact);
+
+ if (!isToolSummary && role === "user" && SLASH_COMMAND_RE.test(compact)) {
+ return { shouldCapture: false, reason: "slash_command", text: "" };
+ }
+ if (!isToolSummary && ACK_RE.test(compact)) {
+ return { shouldCapture: false, reason: "ack", text: "" };
+ }
+ if (!isToolSummary && isPunctuationOnly(compact)) {
+ return { shouldCapture: false, reason: "punctuation", text: "" };
+ }
+ if (!isToolSummary && !hasEnoughSignal(compact)) {
+ return { shouldCapture: false, reason: "too_short", text: "" };
+ }
+ if (/^\[openviking-memory\]/i.test(compact)) {
+ return { shouldCapture: false, reason: "plugin_status", text: "" };
+ }
+
+ return { shouldCapture: true, reason: "ok", text: capped };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/credentials.mjs b/examples/zcode-memory-plugin/scripts/shared/credentials.mjs
new file mode 100644
index 000000000..30d5401f2
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/credentials.mjs
@@ -0,0 +1,228 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve as resolvePath } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
+const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
+const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
+
+function str(val, fallback = "") {
+ if (typeof val === "string" && val.trim()) return val.trim();
+ return fallback;
+}
+
+function normalizePath(value) {
+ const raw = str(value, "");
+ if (!raw) return "";
+ if (raw === "~") return homedir();
+ if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
+ return resolvePath(raw);
+}
+
+function tryLoadJson(path) {
+ if (!path) return null;
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Build the User-Agent every harness plugin sends on OpenViking-bound requests.
+ * Shape is `name/semver` so downstream stats layers can parse it as one token.
+ */
+export function buildUserAgent(harness, version) {
+ return `openviking-memory-${harness}/${str(version, "") || "0.0.0"}`;
+}
+
+/**
+ * Read a plugin manifest's `version` field. Accepts a path or a URL (so callers
+ * can resolve relative to import.meta.url). Returns "" when unreadable so the
+ * User-Agent falls back to 0.0.0 instead of throwing inside a short-lived hook.
+ */
+export function readManifestVersion(manifest) {
+ try {
+ return str(JSON.parse(readFileSync(manifest, "utf-8")).version, "");
+ } catch {
+ return "";
+ }
+}
+
+function looksLikeOvcli(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ if (obj.server && typeof obj.server === "object") return false;
+ return Boolean(
+ typeof obj.url === "string" ||
+ typeof obj.api_key === "string" ||
+ typeof obj.account === "string" ||
+ typeof obj.account_id === "string" ||
+ typeof obj.user === "string" ||
+ typeof obj.user_id === "string" ||
+ typeof obj.actor_peer_id === "string",
+ );
+}
+
+function hasCredentialFields(obj) {
+ if (!obj || typeof obj !== "object") return false;
+ return [
+ "url",
+ "api_key",
+ "account",
+ "account_id",
+ "user",
+ "user_id",
+ "actor_peer_id",
+ "peer_id",
+ ].some((key) => typeof obj[key] === "string");
+}
+
+export function loadCredentialFiles(env = process.env) {
+ const cliPathCandidate = normalizePath(env.OPENVIKING_CLI_CONFIG_FILE) || DEFAULT_OVCLI_CONF_PATH;
+ const ovPathCandidate = normalizePath(env.OPENVIKING_CONFIG_FILE) || DEFAULT_OV_CONF_PATH;
+ const cliPathEnv = Boolean(str(env.OPENVIKING_CLI_CONFIG_FILE, ""));
+ const ovPathEnv = Boolean(str(env.OPENVIKING_CONFIG_FILE, ""));
+
+ let cliFile = tryLoadJson(cliPathCandidate);
+ let cliPath = cliFile ? cliPathCandidate : "";
+ let ovFile = tryLoadJson(ovPathCandidate);
+ let ovPath = ovFile ? ovPathCandidate : "";
+
+ // Backward compat: older plugin installs used OPENVIKING_CONFIG_FILE for
+ // both ov.conf and ovcli.conf. Preserve that when the file is ovcli-shaped.
+ if (ovPathEnv && !cliPathEnv && looksLikeOvcli(ovFile)) {
+ cliFile = ovFile;
+ cliPath = ovPath;
+ ovFile = null;
+ ovPath = "";
+ }
+
+ return {
+ cliFile: cliFile || {},
+ cliPath,
+ cliPathCandidate,
+ ovFile: ovFile || {},
+ ovPath,
+ };
+}
+
+function sourceMode(env) {
+ const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
+ .toLowerCase();
+ if (raw === "env" || raw === "environment") return "env";
+ if (raw === "cli" || raw === "ovcli" || raw === "file" || raw === "config") return "cli";
+ return "auto";
+}
+
+function hasEnvCredentialFields(env) {
+ return Boolean(
+ str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, "")) ||
+ str(env.OPENVIKING_MCP_URL, "") ||
+ str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, "")) ||
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(env.OPENVIKING_USER, "") ||
+ str(env.OPENVIKING_PEER_ID, ""),
+ );
+}
+
+function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
+ const envUrl = str(env.OPENVIKING_URL, str(env.OPENVIKING_BASE_URL, ""));
+ const cliUrl = str(cliFile.url, "");
+
+ if (mode !== "cli" && envUrl) return envUrl.replace(/\/+$/, "");
+ if (useCli && cliUrl) return cliUrl.replace(/\/+$/, "");
+ if (mode !== "env" && cliUrl) return cliUrl.replace(/\/+$/, "");
+
+ const server = ovFile.server || {};
+ const ovUrl = str(server.url, "");
+ if (ovUrl) return ovUrl.replace(/\/+$/, "");
+
+ const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
+ const port = Number.isFinite(Number(server.port)) ? Math.floor(Number(server.port)) : 1933;
+ return `http://${host}:${port}`;
+}
+
+export function resolveOpenVikingCredentials(env = process.env) {
+ const files = loadCredentialFiles(env);
+ const mode = sourceMode(env);
+ const envHasCredentials = hasEnvCredentialFields(env);
+ const useCli = mode === "cli" ||
+ (mode === "auto" && !envHasCredentials && files.cliPath && hasCredentialFields(files.cliFile));
+ const cx = files.ovFile.codex || {};
+ const server = files.ovFile.server || {};
+
+ const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+
+ const apiKey = useCli
+ ? str(files.cliFile.api_key, "")
+ : (
+ str(env.OPENVIKING_BEARER_TOKEN, "") ||
+ str(env.OPENVIKING_API_KEY, "") ||
+ str(files.cliFile.api_key, "") ||
+ str(cx.apiKey, "") ||
+ str(server.root_api_key, "")
+ );
+
+ const account = useCli
+ ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ : (
+ str(env.OPENVIKING_ACCOUNT, "") ||
+ str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ str(cx.accountId, "")
+ );
+
+ const user = useCli
+ ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ : (
+ str(env.OPENVIKING_USER, "") ||
+ str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ str(cx.userId, "")
+ );
+
+ const peerId = useCli
+ ? str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, ""))
+ : (
+ str(env.OPENVIKING_PEER_ID, "") ||
+ str(files.cliFile.actor_peer_id, str(files.cliFile.peer_id, "")) ||
+ str(cx.peerId, str(cx.peer_id, ""))
+ );
+
+ const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
+ const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
+
+ return {
+ ...files,
+ credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ baseUrl,
+ mcpUrl,
+ apiKey,
+ account,
+ user,
+ peerId,
+ hasApiKey: Boolean(apiKey),
+ };
+}
+
+function main() {
+ const cmd = process.argv[2] || "";
+ if (cmd === "mcp-url") {
+ process.stdout.write(resolveOpenVikingCredentials().mcpUrl);
+ return;
+ }
+ if (cmd === "has-api-key") {
+ process.stdout.write(resolveOpenVikingCredentials().hasApiKey ? "1" : "0");
+ return;
+ }
+ if (cmd === "has-peer-id") {
+ process.stdout.write(resolveOpenVikingCredentials().peerId ? "1" : "0");
+ return;
+ }
+ process.stderr.write("usage: ov-credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
+ process.exitCode = 2;
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+ main();
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/debug-log.mjs b/examples/zcode-memory-plugin/scripts/shared/debug-log.mjs
new file mode 100644
index 000000000..73855cf6d
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/debug-log.mjs
@@ -0,0 +1,58 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared structured debug logger for OpenViking memory plugin hook scripts.
+ *
+ * Harness-specific wrappers load config and pass {debug, debugLogPath}. This
+ * module stays path-agnostic so it can be vendored into each plugin snapshot.
+ */
+
+import { appendFileSync, mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+function ensureDir(filePath) {
+ try {
+ mkdirSync(dirname(filePath), { recursive: true });
+ } catch { /* best effort */ }
+}
+
+function writeLine(filePath, obj) {
+ try {
+ appendFileSync(filePath, JSON.stringify(obj) + "\n");
+ } catch { /* best effort */ }
+}
+
+function localISO() {
+ const d = new Date();
+ const off = d.getTimezoneOffset();
+ const sign = off <= 0 ? "+" : "-";
+ const abs = Math.abs(off);
+ const local = new Date(d.getTime() - off * 60000);
+ return local.toISOString().replace(
+ "Z",
+ `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`,
+ );
+}
+
+const noop = () => {};
+
+export function createLogger(hookName, overrideCfg) {
+ const c = overrideCfg || {};
+ if (!c.debug) return { log: noop, logError: noop };
+
+ const logPath = c.debugLogPath;
+ if (!logPath) return { log: noop, logError: noop };
+ ensureDir(logPath);
+
+ function log(stage, data) {
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, data });
+ }
+
+ function logError(stage, err) {
+ const error = err instanceof Error
+ ? { message: err.message, stack: err.stack }
+ : String(err);
+ writeLine(logPath, { ts: localISO(), hook: hookName, stage, error });
+ }
+
+ return { log, logError };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs
new file mode 100644
index 000000000..70b1a4539
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs
@@ -0,0 +1,504 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared stdio -> streamable-HTTP MCP proxy core for OpenViking memory plugins.
+ *
+ * Harness-specific entrypoints provide credential/config loading; this module
+ * owns only transport, session retry, SSE parsing, and protocol-clean stdio.
+ */
+
+import { statSync } from "node:fs";
+import { createInterface } from "node:readline";
+
+const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
+const DELETE_TIMEOUT_MS = 2000;
+const MAX_CONCURRENT_REQUESTS = 16;
+
+class HttpStatusError extends Error {
+ constructor(status, statusText, bodyText, messages = []) {
+ super(`HTTP ${status}${statusText ? ` ${statusText}` : ""}`);
+ this.name = "HttpStatusError";
+ this.status = status;
+ this.statusText = statusText;
+ this.bodyText = bodyText;
+ this.messages = messages;
+ }
+}
+
+function snapshotPaths(paths) {
+ const out = new Map();
+ for (const path of paths || []) {
+ try {
+ const st = statSync(path);
+ out.set(path, `${st.mtimeMs}:${st.size}`);
+ } catch {
+ out.set(path, "missing");
+ }
+ }
+ return out;
+}
+
+function snapshotsDiffer(a, b) {
+ if (a.size !== b.size) return true;
+ for (const [key, value] of a.entries()) {
+ if (b.get(key) !== value) return true;
+ }
+ return false;
+}
+
+function createSemaphore(limit) {
+ let active = 0;
+ const queue = [];
+ return async function acquire() {
+ if (active >= limit) {
+ await new Promise((resolve) => queue.push(resolve));
+ }
+ active += 1;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ active -= 1;
+ const next = queue.shift();
+ if (next) next();
+ };
+ };
+}
+
+function isRequest(message) {
+ return Object.prototype.hasOwnProperty.call(message || {}, "id");
+}
+
+function messageId(message) {
+ return isRequest(message) ? message.id : undefined;
+}
+
+function errorResponse(id, code, message, data) {
+ const error = { code, message };
+ if (data !== undefined) error.data = data;
+ return { jsonrpc: "2.0", id: id ?? null, error };
+}
+
+function parseMaybeJson(text) {
+ const trimmed = String(text || "").trim();
+ if (!trimmed) return null;
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return null;
+ }
+}
+
+function parseSseMessages(text) {
+ const messages = [];
+ let dataLines = [];
+
+ function flush() {
+ if (dataLines.length === 0) return;
+ const data = dataLines.join("\n").trim();
+ dataLines = [];
+ if (!data || data === "[DONE]") return;
+ messages.push(JSON.parse(data));
+ }
+
+ for (const rawLine of String(text || "").split(/\r?\n/)) {
+ if (rawLine === "") {
+ flush();
+ continue;
+ }
+ if (rawLine.startsWith(":")) continue;
+ const colon = rawLine.indexOf(":");
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
+ let value = colon === -1 ? "" : rawLine.slice(colon + 1);
+ if (value.startsWith(" ")) value = value.slice(1);
+ if (field === "data") dataLines.push(value);
+ }
+ flush();
+ return messages;
+}
+
+function parseHttpBody(contentType, text) {
+ const ctype = String(contentType || "").toLowerCase();
+ if (!String(text || "").trim()) return [];
+ if (ctype.includes("text/event-stream")) return parseSseMessages(text);
+ const json = parseMaybeJson(text);
+ return json == null ? [] : [json];
+}
+
+function serializeBodyForError(bodyText) {
+ const parsed = parseMaybeJson(bodyText);
+ if (parsed?.error?.message) return parsed.error.message;
+ if (parsed?.detail) return typeof parsed.detail === "string" ? parsed.detail : JSON.stringify(parsed.detail);
+ const compact = String(bodyText || "").replace(/\s+/g, " ").trim();
+ return compact.slice(0, 500);
+}
+
+function cloneMessage(message) {
+ return JSON.parse(JSON.stringify(message));
+}
+
+export function createOpenVikingMcpProxy({
+ stdin = process.stdin,
+ stdout = process.stdout,
+ readConfig,
+ loggerFactory,
+ fetchImpl = globalThis.fetch,
+ localToolProvider = null,
+} = {}) {
+ if (typeof fetchImpl !== "function") {
+ throw new Error("global fetch is required; use Node.js 18 or newer");
+ }
+ if (typeof readConfig !== "function") {
+ throw new Error("readConfig function is required");
+ }
+ if (typeof loggerFactory !== "function") {
+ throw new Error("loggerFactory function is required");
+ }
+
+ let proxyConfig = readConfig();
+ let logger = loggerFactory("mcp-proxy", proxyConfig);
+ let watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);
+ let sessionId = "";
+ let initializeRequest = null;
+ let initializedNotification = null;
+ let protocolVersion = DEFAULT_PROTOCOL_VERSION;
+ let initializeInFlight = null;
+ let reinitializeInFlight = null;
+ let stdoutChain = Promise.resolve();
+ let shuttingDown = false;
+ let reinitCounter = 0;
+ const acquire = createSemaphore(MAX_CONCURRENT_REQUESTS);
+
+ function log(stage, data) {
+ try {
+ logger.log(stage, data);
+ } catch { /* debug logging must never affect protocol IO */ }
+ }
+
+ function logError(stage, err) {
+ try {
+ logger.logError(stage, err);
+ } catch { /* debug logging must never affect protocol IO */ }
+ }
+
+ function localTools() {
+ if (!localToolProvider || typeof localToolProvider.listTools !== "function") return [];
+ const tools = localToolProvider.listTools();
+ return Array.isArray(tools) ? tools : [];
+ }
+
+ function appendLocalTools(message, outbound) {
+ if (message.method !== "tools/list" || !Array.isArray(outbound?.result?.tools)) {
+ return outbound;
+ }
+ const additions = localTools().filter((tool) => tool?.name);
+ if (additions.length === 0) return outbound;
+ const localNames = new Set(additions.map((tool) => tool.name));
+ const upstreamTools = outbound.result.tools.filter((tool) => !localNames.has(tool?.name));
+ return {
+ ...outbound,
+ result: {
+ ...outbound.result,
+ tools: [...upstreamTools, ...additions],
+ },
+ };
+ }
+
+ async function callLocalTool(message) {
+ if (
+ message.method !== "tools/call"
+ || !localToolProvider
+ || typeof localToolProvider.callTool !== "function"
+ ) {
+ return null;
+ }
+ const name = message.params?.name;
+ if (!localTools().some((tool) => tool?.name === name)) return null;
+ reloadIfCredentialFilesChanged("local_tool_call");
+ return localToolProvider.callTool(message.params, { config: proxyConfig });
+ }
+
+ function reloadConfig(reason) {
+ proxyConfig = readConfig();
+ logger = loggerFactory("mcp-proxy", proxyConfig);
+ watchedSnapshot = snapshotPaths(proxyConfig.watchedPaths);
+ log("credentials_reloaded", {
+ reason,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath,
+ mcpUrl: proxyConfig.mcpUrl,
+ hasApiKey: Boolean(proxyConfig.apiKey),
+ hasIdentity: Boolean(proxyConfig.account || proxyConfig.user),
+ hasPeer: Boolean(proxyConfig.peerId),
+ });
+ }
+
+ function reloadIfCredentialFilesChanged(reason) {
+ const next = snapshotPaths(proxyConfig.watchedPaths);
+ if (!snapshotsDiffer(watchedSnapshot, next)) return false;
+ reloadConfig(reason);
+ return true;
+ }
+
+ function headersForRequest(includeSession = true) {
+ const headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ // Always the proxy's current version (default, then server-negotiated) —
+ // never the client's un-negotiated ask, which strict upstreams reject
+ // with HTTP 400 before initialize negotiation can run.
+ "MCP-Protocol-Version": protocolVersion,
+ };
+ if (includeSession && sessionId) headers["Mcp-Session-Id"] = sessionId;
+ if (proxyConfig.apiKey) headers.Authorization = `Bearer ${proxyConfig.apiKey}`;
+ if (proxyConfig.account) headers["X-OpenViking-Account"] = proxyConfig.account;
+ if (proxyConfig.user) headers["X-OpenViking-User"] = proxyConfig.user;
+ if (proxyConfig.peerId) headers["X-OpenViking-Actor-Peer"] = proxyConfig.peerId;
+ if (proxyConfig.userAgent) headers["User-Agent"] = proxyConfig.userAgent;
+ return headers;
+ }
+
+ function writeMessage(obj) {
+ const line = `${JSON.stringify(obj)}\n`;
+ stdoutChain = stdoutChain
+ .then(() => new Promise((resolve) => stdout.write(line, resolve)))
+ .catch(() => {});
+ return stdoutChain;
+ }
+
+ function mapError(message, err) {
+ const id = messageId(message);
+ if (err instanceof HttpStatusError) {
+ if (err.status === 401 || err.status === 403) {
+ return errorResponse(
+ id,
+ -32001,
+ `OpenViking MCP authentication failed (HTTP ${err.status}). Check ~/.openviking/ovcli.conf or OPENVIKING_API_KEY, and verify the configured account/user for trusted mode.`,
+ {
+ status: err.status,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath || undefined,
+ serverMessage: serializeBodyForError(err.bodyText) || undefined,
+ },
+ );
+ }
+ return errorResponse(
+ id,
+ -32002,
+ `OpenViking MCP upstream returned HTTP ${err.status}.`,
+ {
+ status: err.status,
+ serverMessage: serializeBodyForError(err.bodyText) || undefined,
+ },
+ );
+ }
+ const msg = err instanceof Error ? err.message : String(err);
+ return errorResponse(
+ id,
+ -32001,
+ `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that 'ov serve' is running.`,
+ { cause: msg },
+ );
+ }
+
+ async function postToMcp(message, { includeSession = true, timeoutMs = proxyConfig.timeoutMs } = {}) {
+ const release = await acquire();
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const res = await fetchImpl(proxyConfig.mcpUrl, {
+ method: "POST",
+ headers: headersForRequest(includeSession),
+ body: JSON.stringify(message),
+ signal: controller.signal,
+ });
+ const text = await res.text();
+ const messages = parseHttpBody(res.headers.get("content-type"), text);
+ const nextSessionId = res.headers.get("mcp-session-id");
+ if (nextSessionId) sessionId = nextSessionId;
+ if (message?.method === "initialize" && res.ok) {
+ const negotiated = messages.find((m) => typeof m?.result?.protocolVersion === "string")?.result.protocolVersion;
+ if (negotiated) protocolVersion = negotiated;
+ }
+ if (!res.ok) {
+ throw new HttpStatusError(res.status, res.statusText, text, messages);
+ }
+ return { status: res.status, messages };
+ } finally {
+ clearTimeout(timer);
+ release();
+ }
+ }
+
+ async function deleteSession() {
+ if (!sessionId || shuttingDown) return;
+ shuttingDown = true;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), DELETE_TIMEOUT_MS);
+ try {
+ await fetchImpl(proxyConfig.mcpUrl, {
+ method: "DELETE",
+ headers: headersForRequest(true),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ logError("delete_session_failed", err);
+ } finally {
+ clearTimeout(timer);
+ sessionId = "";
+ }
+ }
+
+ async function reinitialize(failedSessionId) {
+ if (!initializeRequest) {
+ throw new Error("MCP session expired before initialize parameters were cached");
+ }
+ if (reinitializeInFlight) return reinitializeInFlight;
+ reinitializeInFlight = (async () => {
+ if (failedSessionId && sessionId && sessionId !== failedSessionId) return;
+ const reinit = cloneMessage(initializeRequest);
+ reinit.id = `openviking-proxy-reinit-${Date.now()}-${++reinitCounter}`;
+ sessionId = "";
+ const result = await postToMcp(reinit, { includeSession: false });
+ if (initializedNotification) {
+ await postToMcp(cloneMessage(initializedNotification), { includeSession: true });
+ }
+ log("reinitialized", { mcpUrl: proxyConfig.mcpUrl, status: result.status, sessionId: Boolean(sessionId) });
+ })().finally(() => {
+ reinitializeInFlight = null;
+ });
+ return reinitializeInFlight;
+ }
+
+ async function sendWithRetry(message, { expectsResponse }) {
+ if (message.method !== "initialize" && initializeInFlight) {
+ await initializeInFlight.catch(() => {});
+ }
+
+ const failedSessionId = sessionId;
+ try {
+ return await postToMcp(message, { includeSession: message.method !== "initialize" });
+ } catch (err) {
+ if (err instanceof HttpStatusError && (err.status === 401 || err.status === 403)) {
+ if (reloadIfCredentialFilesChanged("auth_failure")) {
+ sessionId = "";
+ if (message.method !== "initialize" && initializeRequest) {
+ await reinitialize(failedSessionId);
+ }
+ return await postToMcp(message, { includeSession: message.method !== "initialize" });
+ }
+ }
+ if (
+ err instanceof HttpStatusError
+ && (err.status === 400 || err.status === 404)
+ && message.method !== "initialize"
+ && initializeRequest
+ ) {
+ await reinitialize(failedSessionId);
+ return await postToMcp(message, { includeSession: true });
+ }
+ if (!expectsResponse) {
+ logError("notification_failed", err);
+ }
+ throw err;
+ }
+ }
+
+ async function handleMessage(message) {
+ if (!message || typeof message !== "object" || message.jsonrpc !== "2.0") {
+ await writeMessage(errorResponse(null, -32600, "Invalid JSON-RPC message"));
+ return;
+ }
+
+ const expectsResponse = isRequest(message);
+ if (message.method === "initialize") {
+ initializeRequest = cloneMessage(message);
+ protocolVersion = DEFAULT_PROTOCOL_VERSION;
+ sessionId = "";
+ }
+ if (message.method === "notifications/initialized") {
+ initializedNotification = cloneMessage(message);
+ }
+
+ try {
+ const localResult = await callLocalTool(message);
+ if (localResult !== null) {
+ if (expectsResponse) {
+ await writeMessage({ jsonrpc: "2.0", id: message.id, result: localResult });
+ }
+ return;
+ }
+ const send = sendWithRetry(message, { expectsResponse });
+ if (message.method === "initialize") {
+ initializeInFlight = send
+ .catch(() => {})
+ .finally(() => {
+ initializeInFlight = null;
+ });
+ }
+ const result = await send;
+ if (!expectsResponse) return;
+ if (result.messages.length === 0) {
+ await writeMessage(errorResponse(message.id, -32003, "OpenViking MCP upstream returned an empty response"));
+ return;
+ }
+ for (const outbound of result.messages) {
+ await writeMessage(appendLocalTools(message, outbound));
+ }
+ } catch (err) {
+ if (expectsResponse) {
+ await writeMessage(mapError(message, err));
+ } else {
+ logError("notification_unhandled", err);
+ }
+ }
+ }
+
+ async function handleLine(line) {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let message;
+ try {
+ message = JSON.parse(trimmed);
+ } catch {
+ await writeMessage(errorResponse(null, -32700, "Parse error"));
+ return;
+ }
+ await handleMessage(message);
+ }
+
+ async function closeAndExit(code = 0) {
+ await deleteSession();
+ await stdoutChain;
+ process.exit(code);
+ }
+
+ async function closeSession() {
+ await deleteSession();
+ await stdoutChain;
+ }
+
+ function start() {
+ log("start", {
+ mcpUrl: proxyConfig.mcpUrl,
+ credentialSource: proxyConfig.credentialSource,
+ credentialPath: proxyConfig.credentialPath,
+ hasApiKey: Boolean(proxyConfig.apiKey),
+ });
+ const rl = createInterface({ input: stdin, crlfDelay: Infinity, terminal: false });
+ rl.on("line", (line) => {
+ void handleLine(line);
+ });
+ rl.on("close", () => {
+ void closeAndExit(0);
+ });
+ process.on("SIGINT", () => {
+ void closeAndExit(130);
+ });
+ process.on("SIGTERM", () => {
+ void closeAndExit(143);
+ });
+ return { close: () => closeAndExit(0) };
+ }
+
+ return { start, handleMessage, parseSseMessages, closeSession };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs b/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs
new file mode 100644
index 000000000..16e4da0dc
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs
@@ -0,0 +1,441 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Local pending queue for offline resilience.
+ *
+ * When the OpenViking server is temporarily unreachable, write operations
+ * (addMessage, commitSession) serialize their payloads to
+ * `~/.openviking/pending/` as JSON files. On the next session-start, the
+ * queue is replayed in small batches. This is a session-start-triggered retry
+ * path with maxRetries/TTL, not a long-running background worker.
+ *
+ * Each file contains: { type, sessionId, payload, createdAt, retries, dedupKey }
+ *
+ * Config (env vars):
+ * OPENVIKING_PENDING_DIR pending queue directory
+ * (default: ~/.openviking/pending)
+ * OPENVIKING_PENDING_MAX_RETRIES max retry attempts per item (default: 3)
+ * OPENVIKING_PENDING_TTL_DAYS max age in days before stale cleanup
+ * (default: 7)
+ * OPENVIKING_PENDING_REPLAY_LIMIT max items replayed per session-start
+ * (default: 50)
+ */
+
+import { mkdir, readdir, readFile, rename, writeFile, unlink, stat, chmod } from "node:fs/promises";
+import { createHash } from "node:crypto";
+import { join } from "node:path";
+import { homedir } from "node:os";
+
+const DEFAULT_MAX_RETRIES = 3;
+const DEFAULT_TTL_DAYS = 7;
+const DEFAULT_REPLAY_LIMIT = 50;
+const PROCESSING_STALE_MS = 10 * 60 * 1000;
+const DEFAULT_PENDING_DIR = () => join(homedir(), ".openviking", "pending");
+
+// Pending queue files may contain raw memory payload / transcript content.
+// Use restrictive permissions explicitly so we don't depend on umask.
+// - dir: 0o700 (owner: rwx; group/other: none)
+// - file: 0o600 (owner: rw; group/other: none)
+const PENDING_DIR_MODE = 0o700;
+const PENDING_FILE_MODE = 0o600;
+
+/**
+ * Ensure the pending directory exists with 0o700 permissions. If the
+ * directory was created by a previous version of this code (or by hand)
+ * with looser permissions, best-effort chmod it on first use.
+ */
+async function ensurePendingDir(dir) {
+ await mkdir(dir, { recursive: true, mode: PENDING_DIR_MODE });
+ try {
+ await chmod(dir, PENDING_DIR_MODE);
+ } catch {
+ // Best effort: chmod may fail on some platforms (e.g. Windows); not fatal.
+ }
+}
+
+function getPendingDir() {
+ return process.env.OPENVIKING_PENDING_DIR || DEFAULT_PENDING_DIR();
+}
+
+function getMaxRetries() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_MAX_RETRIES || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_MAX_RETRIES;
+}
+
+function getTTLDays() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_TTL_DAYS || "", 10);
+ return Number.isFinite(v) && v >= 0 ? v : DEFAULT_TTL_DAYS;
+}
+
+function getReplayLimit() {
+ const v = parseInt(process.env.OPENVIKING_PENDING_REPLAY_LIMIT || "", 10);
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_REPLAY_LIMIT;
+}
+
+function stableStringify(value) {
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
+}
+
+function makeDedupKey(type, sessionId, payload) {
+ return createHash("sha256")
+ .update(type)
+ .update("\n")
+ .update(sessionId)
+ .update("\n")
+ .update(stableStringify(payload))
+ .digest("hex");
+}
+
+function pendingFilename(dedupKey, retries = 0) {
+ return `${dedupKey}_${Math.max(0, Number(retries) || 0)}.json`;
+}
+
+function retryFilename(filename, retries) {
+ const bare = filename.replace(/\.(json|processing)$/, "");
+ const nextBare = /_\d+$/.test(bare)
+ ? bare.replace(/_\d+$/, `_${retries}`)
+ : `${bare}_${retries}`;
+ return `${nextBare}.json`;
+}
+
+function processingFilename(filename) {
+ return filename.replace(/\.json$/, ".processing");
+}
+
+function pendingFromProcessingFilename(filename) {
+ return filename.replace(/\.processing$/, ".json");
+}
+
+function isRetryableReplayFailure(res) {
+ if (!res || res.ok) return false;
+ const status = Number(res.status || 0);
+ return !status || status >= 500 || status === 408 || status === 429;
+}
+
+async function readEntry(dir, filename) {
+ const raw = await readFile(join(dir, filename), "utf-8");
+ return JSON.parse(raw);
+}
+
+async function findExistingByDedupKey(dir, dedupKey) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return null;
+ }
+
+ // Fast path: filenames are `${dedupKey}_${retries}.json` (or
+ // .processing). `dedupKey` is a sha256 hex produced by makeDedupKey
+ // (no underscores), so `${dedupKey}_` is a unique prefix per key.
+ // Filter on prefix BEFORE opening the file to avoid readFile +
+ // JSON.parse on every entry in the directory on every enqueue call —
+ // the previous implementation was O(n²) in queue size. Worst case here
+ // is O(n) readdir entries, but only the (typically single) prefix
+ // match actually gets opened and parsed.
+ const prefix = `${dedupKey}_`;
+
+ for (const f of files) {
+ if (!f.startsWith(prefix)) continue;
+ if (!f.endsWith(".json") && !f.endsWith(".processing")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ if (entry?.dedupKey === dedupKey) return { filename: f, entry };
+ } catch {
+ // Corrupted file - ignore for dedup lookup.
+ }
+ }
+ return null;
+}
+
+async function recoverStaleProcessing(dir) {
+ let files;
+ try {
+ files = await readdir(dir);
+ } catch {
+ return 0;
+ }
+
+ const now = Date.now();
+ let recovered = 0;
+ for (const f of files) {
+ if (!f.endsWith(".processing")) continue;
+ const from = join(dir, f);
+ try {
+ const s = await stat(from);
+ if (now - s.mtimeMs < PROCESSING_STALE_MS) continue;
+ const to = join(dir, pendingFromProcessingFilename(f));
+ await rename(from, to);
+ recovered++;
+ } catch {
+ // Best effort. A concurrent process may have already handled it.
+ }
+ }
+ return recovered;
+}
+
+/**
+ * Enqueue a failed operation to local disk.
+ *
+ * @param {string} type - "addMessage" or "commitSession"
+ * @param {string} sessionId - OV session ID
+ * @param {object} payload - the data that failed to send
+ * @param {object} options
+ * @param {number} options.createdAt - optional queue timestamp override
+ */
+export async function enqueue(type, sessionId, payload, options = {}) {
+ const dir = getPendingDir();
+ const now = Number.isFinite(options.createdAt) ? options.createdAt : Date.now();
+ const dedupKey = makeDedupKey(type, sessionId, payload);
+ const filename = pendingFilename(dedupKey, 0);
+ const entry = {
+ type,
+ sessionId,
+ payload,
+ createdAt: now,
+ retries: 0,
+ dedupKey,
+ };
+
+ try {
+ await ensurePendingDir(dir);
+ } catch (err) {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+
+ const existing = await findExistingByDedupKey(dir, dedupKey);
+ if (existing) {
+ return { ok: true, path: existing.filename, deduped: true, dedupKey };
+ }
+
+ try {
+ await writeFile(join(dir, filename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ return { ok: true, path: filename, dedupKey };
+ } catch (err) {
+ if (err?.code !== "EEXIST") {
+ return { ok: false, error: err?.message || String(err), dedupKey };
+ }
+ }
+
+ const duplicate = await findExistingByDedupKey(dir, dedupKey);
+ if (duplicate) {
+ return { ok: true, path: duplicate.filename, deduped: true, dedupKey };
+ }
+ return { ok: false, error: `pending file exists but dedup entry was not readable: ${filename}`, dedupKey };
+}
+
+/**
+ * List all pending queue entries.
+ * Returns array of { filename, entry } sorted by createdAt ascending.
+ */
+export async function listPending() {
+ const dir = getPendingDir();
+ let files;
+ try {
+ await recoverStaleProcessing(dir);
+ files = await readdir(dir);
+ } catch {
+ return [];
+ }
+
+ const entries = [];
+ for (const f of files) {
+ if (!f.endsWith(".json")) continue;
+ try {
+ const entry = await readEntry(dir, f);
+ entries.push({ filename: f, entry });
+ } catch {
+ // Corrupted file - skip.
+ }
+ }
+
+ entries.sort((a, b) => (a.entry.createdAt || 0) - (b.entry.createdAt || 0));
+ return entries;
+}
+
+/**
+ * Atomically claim a pending file for replay. Only the process that successfully
+ * renames the file may send the HTTP replay.
+ */
+export async function claimForReplay(filename) {
+ if (!filename.endsWith(".json")) return null;
+ const dir = getPendingDir();
+ const claimed = processingFilename(filename);
+ try {
+ await rename(join(dir, filename), join(dir, claimed));
+ return claimed;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Remove a pending entry after successful replay.
+ */
+export async function dequeue(filename) {
+ const dir = getPendingDir();
+ try {
+ await unlink(join(dir, filename));
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Increment retry count on a pending entry. Returns false if max retries exceeded.
+ */
+export async function incrementRetry(filename, entry) {
+ const dir = getPendingDir();
+ const maxRetries = getMaxRetries();
+ entry.retries = (entry.retries || 0) + 1;
+
+ if (entry.retries > maxRetries) {
+ try {
+ await unlink(join(dir, filename));
+ } catch {
+ // Best effort.
+ }
+ return false;
+ }
+
+ const newFilename = retryFilename(filename, entry.retries);
+ // Atomic write: write to a unique temp file in the same directory, then
+ // rename into place. Avoids leaving a half-written JSON if the process
+ // crashes mid-write.
+ const tmpFilename = `${newFilename}.tmp.${process.pid}.${Date.now()}`;
+ try {
+ await writeFile(join(dir, tmpFilename), JSON.stringify(entry), {
+ encoding: "utf-8",
+ flag: "wx",
+ mode: PENDING_FILE_MODE,
+ });
+ await rename(join(dir, tmpFilename), join(dir, newFilename));
+ await unlink(join(dir, filename)).catch(() => {});
+ return true;
+ } catch {
+ await unlink(join(dir, tmpFilename)).catch(() => {});
+ return false;
+ }
+}
+
+/**
+ * Clean up stale entries older than TTL.
+ */
+export async function cleanStale() {
+ const ttlMs = getTTLDays() * 24 * 60 * 60 * 1000;
+ const now = Date.now();
+ const pending = await listPending();
+ let cleaned = 0;
+
+ for (const { filename, entry } of pending) {
+ const age = now - (entry.createdAt || 0);
+ if (age > ttlMs) {
+ await dequeue(filename);
+ cleaned++;
+ }
+ }
+ return cleaned;
+}
+
+/**
+ * Replay pending entries. Call this during session-start when the server is
+ * healthy. Each run processes at most OPENVIKING_PENDING_REPLAY_LIMIT items so
+ * a just-recovered server is not hit with an unbounded replay burst.
+ *
+ * @param {Function} fetchJSON - the configured fetchJSON from makeFetchJSON
+ * @param {Function} log - logger function
+ * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
+ */
+export async function replayPending(fetchJSON, log) {
+ const pending = await listPending();
+
+ if (pending.length === 0) {
+ return { replayed: 0, failed: 0, skipped: 0, deferred: 0 };
+ }
+
+ const replayLimit = getReplayLimit();
+ log("pending-queue", { count: pending.length, replayLimit, action: "replay-start" });
+
+ let replayed = 0;
+ let failed = 0;
+ let skipped = 0;
+ let deferred = 0;
+ let processed = 0;
+
+ for (const { filename, entry } of pending) {
+ if (processed >= replayLimit) {
+ deferred++;
+ continue;
+ }
+
+ if ((entry.retries || 0) >= getMaxRetries()) {
+ await dequeue(filename);
+ skipped++;
+ continue;
+ }
+
+ const claimedFilename = await claimForReplay(filename);
+ if (!claimedFilename) {
+ skipped++;
+ continue;
+ }
+ processed++;
+
+ let res;
+ try {
+ const encodedSid = encodeURIComponent(entry.sessionId);
+ if (entry.type === "addMessage") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/messages`, {
+ method: "POST",
+ body: JSON.stringify(entry.payload),
+ });
+ } else if (entry.type === "commitSession") {
+ res = await fetchJSON(`/api/v1/sessions/${encodedSid}/commit`, {
+ method: "POST",
+ body: JSON.stringify(entry.payload || {}),
+ });
+ } else {
+ await dequeue(claimedFilename);
+ skipped++;
+ continue;
+ }
+ } catch {
+ res = { ok: false };
+ }
+
+ if (res?.ok) {
+ await dequeue(claimedFilename);
+ replayed++;
+ } else if (!isRetryableReplayFailure(res)) {
+ await dequeue(claimedFilename);
+ skipped++;
+ } else {
+ await incrementRetry(claimedFilename, entry);
+ failed++;
+ if (entry.type === "addMessage") {
+ deferred += Math.max(0, pending.length - processed);
+ break;
+ }
+ }
+ }
+
+ const cleaned = await cleanStale();
+
+ log("pending-queue", {
+ action: "replay-done",
+ replayed,
+ failed,
+ skipped,
+ deferred,
+ cleaned,
+ });
+
+ return { replayed, failed, skipped, deferred };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/profile-inject.mjs b/examples/zcode-memory-plugin/scripts/shared/profile-inject.mjs
new file mode 100644
index 000000000..3f601844a
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/profile-inject.mjs
@@ -0,0 +1,294 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Session-start profile injection helper.
+ *
+ * Builds a <user-profile> + <available-memories> block from
+ * viking://user/<space>/memories/profile.md
+ * viking://user/<space>/memories/preferences/ (ls with abstracts)
+ * viking://user/<space>/memories/entities/ (ls with abstracts)
+ *
+ * Budget enforced via the CJK-aware estimateTokens() below — codepoint >=
+ * 0x3000 counts at 1.5 tokens, else chars/4. The estimator is exported so
+ * callers (e.g. session-start.mjs) can log token counts that match what
+ * the budget logic actually sees.
+ *
+ * Returned block is the *inner* content only (no outer <openviking-context>);
+ * session-start.mjs composes the outer wrapper so the archive block can sit
+ * alongside in a single context envelope.
+ */
+
+const USER_RESERVED_DIRS = new Set(["memories"]);
+let _userSpaceCache = null;
+
+/**
+ * Mirrors auto-recall.mjs resolveScopeSpace for scope="user" (lines 123-147).
+ * Duplicated rather than imported to avoid coupling session-start to
+ * auto-recall's module-level fetchJSON closure.
+ */
+async function resolveUserSpace(fetchJSON, actorPeerId = "") {
+ if (_userSpaceCache) return _userSpaceCache;
+
+ let fallbackSpace = "default";
+ const status = await fetchJSON("/api/v1/system/status");
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
+ fallbackSpace = status.result.user.trim();
+ }
+
+ const lsRes = await fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
+ const spaces = lsRes.result
+ .filter((e) => e?.isDir)
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
+ if (spaces.length > 0) {
+ if (spaces.includes(fallbackSpace)) { _userSpaceCache = fallbackSpace; return fallbackSpace; }
+ if (spaces.includes("default")) { _userSpaceCache = "default"; return "default"; }
+ if (spaces.length === 1) { _userSpaceCache = spaces[0]; return spaces[0]; }
+ }
+ }
+ _userSpaceCache = fallbackSpace;
+ return fallbackSpace;
+}
+
+/**
+ * Token estimate that splits CJK from the rest. The rest of the plugin uses a
+ * flat chars/4 heuristic, which silently undercounts CJK content by 4-6× and
+ * makes a "5000 token budget" really worth ~1k real tokens for Chinese text.
+ *
+ * Rule:
+ * - codepoint >= 0x3000 → CJK / Hiragana / Katakana / Hangul / CJK
+ * punctuation / fullwidth ASCII; counted at 1.5 tokens/char (empirical
+ * average for cl100k_base on Chinese; Claude's tokenizer is in the same
+ * ballpark).
+ * - everything else → chars/4 (the standard English-ish heuristic).
+ *
+ * Single linear pass, no dependencies. Errs on the side of overcounting CJK
+ * by ~10-20% in the worst case (some common Chinese phrases compress better
+ * than 1.5 tokens/char), which is the safe direction for budget enforcement.
+ */
+export function estimateTokens(text) {
+ if (!text) return 0;
+ let cjk = 0;
+ for (let i = 0; i < text.length; i++) {
+ if (text.charCodeAt(i) >= 0x3000) cjk++;
+ }
+ const other = text.length - cjk;
+ return Math.ceil(cjk * 1.5 + other / 4);
+}
+
+/**
+ * Convert a token budget to a max-chars budget that respects this content's
+ * actual CJK density. Avoids the chars/4 trap where a "5000 token" sub-cap
+ * yields 20000 chars of pure-CJK text → 30000 actual tokens (6× over).
+ *
+ * For an empty/missing string, returns 0.
+ */
+function tokensToCharsBudget(content, maxTokens) {
+ if (!content) return 0;
+ let cjk = 0;
+ for (let i = 0; i < content.length; i++) {
+ if (content.charCodeAt(i) >= 0x3000) cjk++;
+ }
+ const ratio = cjk / content.length;
+ const tokensPerChar = ratio * 1.5 + (1 - ratio) * 0.25;
+ return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));
+}
+
+async function readProfile(fetchJSON, profileUri, actorPeerId = "") {
+ const res = await fetchJSON(
+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,
+ {},
+ { actorPeerId },
+ );
+ if (!res.ok || typeof res.result !== "string") return null;
+ const trimmed = res.result.trim();
+ return trimmed || null;
+}
+
+/**
+ * Recursive ls of a memory directory, flattening to .md leaves.
+ *
+ * Memory layout under preferences/ and entities/ is two-level:
+ * <dir>/<owner_name>/<topic>.md
+ * so we use the server's recursive=true flag and filter to leaf .md files.
+ * `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name
+ * to keep owner-namespacing visible and unambiguous when multiple owners exist.
+ */
+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {
+ const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;
+ const res = await fetchJSON(url, {}, { actorPeerId });
+ if (!res.ok || !Array.isArray(res.result)) return [];
+ return res.result
+ .filter((e) => !e.isDir)
+ .map((e) => {
+ const rel = typeof e.rel_path === "string" && e.rel_path
+ ? e.rel_path
+ : (typeof e.name === "string" ? e.name : "");
+ return {
+ name: rel,
+ abstract: typeof e.abstract === "string" ? e.abstract.trim() : "",
+ };
+ })
+ .filter((e) => e.name && e.name.endsWith(".md"))
+ .sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/**
+ * When profile exceeds its sub-cap, keep the head (identity block + first
+ * timeline events) and the tail (most-recent events), drop the middle. This
+ * preserves both stable identity facts (top of file) and most-recent activity
+ * (bottom of file) — only the noisy middle timeline is sacrificed.
+ *
+ * Layout:
+ * <first HEAD_LINES lines>
+ * ... [profile middle elided] ...
+ * <as many trailing lines as fit in remaining budget>
+ *
+ * Falls back to head-only truncate when the file is too short to elide
+ * meaningfully (<HEAD_LINES + 4 lines) or the budget is too tight to fit
+ * both head and a useful tail.
+ */
+function elideProfile(content, maxTokens) {
+ // Compute char budget from token budget using *this* content's CJK density,
+ // not chars/4 — otherwise the truncated string can still blow the token cap
+ // for CJK-heavy profiles (Copilot review point).
+ const maxChars = Math.max(400, tokensToCharsBudget(content, maxTokens));
+ if (estimateTokens(content) <= maxTokens) return content;
+
+ const HEAD_LINES = 8;
+ const ELLIPSIS = "\n... [profile middle elided] ...\n";
+ const lines = content.split("\n");
+
+ const fallbackHeadTruncate = () =>
+ content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]";
+
+ if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate();
+
+ const head = lines.slice(0, HEAD_LINES).join("\n");
+ const reserveForTail = maxChars - head.length - ELLIPSIS.length;
+ if (reserveForTail < 200) return fallbackHeadTruncate();
+
+ let tailChars = 0;
+ let tailStart = lines.length;
+ for (let i = lines.length - 1; i > HEAD_LINES; i--) {
+ const lineLen = lines[i].length + 1;
+ if (tailChars + lineLen > reserveForTail) break;
+ tailChars += lineLen;
+ tailStart = i;
+ }
+ if (tailStart >= lines.length - 1) return fallbackHeadTruncate();
+
+ return `${head}${ELLIPSIS}${lines.slice(tailStart).join("\n")}`;
+}
+
+function formatListing(headerUri, entries, budgetTokens) {
+ if (entries.length === 0) return { lines: [], used: 0, dropped: 0 };
+ // Header is the full directory URI; child lines are relative paths so the
+ // agent can reconstruct each leaf's full URI by concatenation while the
+ // listing itself stays compact.
+ const header = ` ${headerUri}/`;
+ const headerTokens = estimateTokens(header);
+ // If the header alone busts the budget, emit just a one-line stub instead
+ // of silently violating the cap (Copilot review point).
+ if (headerTokens > budgetTokens) {
+ const stub = ` ${headerUri}/ (${entries.length} entries, budget too tight; use \`memory_recall\`)`;
+ return { lines: [stub], used: estimateTokens(stub), dropped: entries.length };
+ }
+ const lines = [header];
+ let used = headerTokens;
+ for (let i = 0; i < entries.length; i++) {
+ const e = entries[i];
+ const desc = e.abstract
+ ? ` — ${e.abstract.replace(/\s+/g, " ").slice(0, 200)}`
+ : "";
+ const line = ` - ${e.name}${desc}`;
+ const tokens = estimateTokens(line);
+ if (used + tokens > budgetTokens) {
+ const remaining = entries.length - i;
+ const tail = ` ... +${remaining} more, use \`memory_recall\``;
+ const tailTokens = estimateTokens(tail);
+ // Only emit the tail if it fits; otherwise the listing closes silently
+ // rather than violating the cap to advertise its own truncation.
+ if (used + tailTokens <= budgetTokens) {
+ lines.push(tail);
+ return { lines, used: used + tailTokens, dropped: remaining };
+ }
+ return { lines, used, dropped: remaining };
+ }
+ lines.push(line);
+ used += tokens;
+ }
+ return { lines, used, dropped: 0 };
+}
+
+/**
+ * Build the profile injection block.
+ *
+ * Returns null when neither profile.md nor either listing has any content.
+ * The returned `block` is just the inner <user-profile>/<available-memories>
+ * payload — the caller wraps it in <openviking-context source="...">.
+ *
+ * @param {Function} fetchJSON ov-session.mjs:makeFetchJSON closure
+ * @param {number} totalBudgetTokens chars/4 budget, total for the whole block
+ * @returns {Promise<null | {
+ * block: string, chars: number, tokens: number, profileUri: string,
+ * profileChars: number, prefCount: number, entCount: number,
+ * droppedPref: number, droppedEnt: number,
+ * }>}
+ */
+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
+ const profileUri = `viking://user/${space}/memories/profile.md`;
+ const prefUri = `viking://user/${space}/memories/preferences`;
+ const entUri = `viking://user/${space}/memories/entities`;
+
+ const [profile, prefs, ents] = await Promise.all([
+ readProfile(fetchJSON, profileUri, actorPeerId),
+ lsDir(fetchJSON, prefUri, actorPeerId),
+ lsDir(fetchJSON, entUri, actorPeerId),
+ ]);
+
+ if (!profile && prefs.length === 0 && ents.length === 0) return null;
+
+ // Profile gets up to half the total budget; listings split the rest.
+ // Sub-cap protects against a runaway profile blowing the listing budget.
+ const profileBudget = Math.floor(totalBudgetTokens / 2);
+ const profileTrunc = profile ? elideProfile(profile, profileBudget) : null;
+ const profileTokens = estimateTokens(profileTrunc || "");
+
+ const listingBudget = Math.max(0, totalBudgetTokens - profileTokens);
+ const halfListing = Math.floor(listingBudget / 2);
+ const prefBlock = formatListing(prefUri, prefs, halfListing);
+ const entBudget = Math.max(0, listingBudget - prefBlock.used);
+ const entBlock = formatListing(entUri, ents, entBudget);
+
+ const lines = [];
+ if (profileTrunc) {
+ lines.push(`<user-profile uri="${profileUri}">`);
+ lines.push(profileTrunc);
+ lines.push(`</user-profile>`);
+ }
+ if (prefBlock.lines.length > 0 || entBlock.lines.length > 0) {
+ lines.push(`<available-memories>`);
+ lines.push(...prefBlock.lines);
+ lines.push(...entBlock.lines);
+ lines.push(`</available-memories>`);
+ }
+
+ const block = lines.join("\n");
+ return {
+ block,
+ chars: block.length,
+ tokens: estimateTokens(block),
+ profileUri,
+ profileChars: profile?.length ?? 0,
+ prefCount: prefs.length,
+ entCount: ents.length,
+ droppedPref: prefBlock.dropped,
+ droppedEnt: entBlock.dropped,
+ };
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs b/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
new file mode 100644
index 000000000..d65f62ba9
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
@@ -0,0 +1,302 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;
+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;
+const STOPWORDS = new Set([
+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",
+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",
+]);
+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
+const SOURCES = [
+ { type: "memory", uri: "viking://user/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://user/skills", bucket: "skills" },
+];
+
+let userSpaceCache = "";
+
+export function estimateTokens(text) {
+ return text ? Math.ceil(String(text).length / 4) : 0;
+}
+
+export function buildRecallEndpointBody(cfg = {}) {
+ const limit = Math.max(Number(cfg.recallLimit || 0), 1);
+ const body = {
+ query: "",
+ quotas: {
+ events: limit,
+ entities: limit,
+ preferences: Math.max(1, Math.min(limit, 3)),
+ experiences: 0,
+ },
+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),
+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
+ render: true,
+ };
+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
+ return body;
+}
+
+function clampScore(v) {
+ if (typeof v !== "number" || Number.isNaN(v)) return 0;
+ return Math.max(0, Math.min(1, v));
+}
+
+function buildQueryProfile(query) {
+ const text = query.trim();
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
+ return {
+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
+ };
+}
+
+function lexicalOverlapBoost(tokens, text) {
+ if (tokens.length === 0 || !text) return 0;
+ const haystack = ` ${text.toLowerCase()} `;
+ let matched = 0;
+ for (const token of tokens.slice(0, 8)) {
+ if (haystack.includes(token)) matched += 1;
+ }
+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
+}
+
+function rankItem(item, profile) {
+ const base = clampScore(item.score);
+ const abstract = (item.abstract || item.overview || "").trim();
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;
+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;
+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;
+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);
+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;
+}
+
+function isEventOrCaseItem(item) {
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");
+}
+
+function dedupeItems(items) {
+ const seen = new Set();
+ const out = [];
+ for (const item of items) {
+ const key = isEventOrCaseItem(item)
+ ? `uri:${item.uri}`
+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(item);
+ }
+ return out;
+}
+
+async function resolveUserSpace(fetchJSON, actorPeerId = "") {
+ if (userSpaceCache) return userSpaceCache;
+
+ let fallbackSpace = "default";
+ const status = await fetchJSON("/api/v1/system/status");
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
+ fallbackSpace = status.result.user.trim();
+ }
+
+ const lsRes = await fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
+ const spaces = lsRes.result
+ .filter((e) => e?.isDir)
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
+ if (spaces.length > 0) {
+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }
+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }
+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }
+ }
+ }
+ userSpaceCache = fallbackSpace;
+ return fallbackSpace;
+}
+
+async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
+ const trimmed = targetUri.trim().replace(/\/+$/, "");
+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
+ if (!m) return trimmed;
+ const rawRest = (m[1] ?? "").trim();
+ if (!rawRest) return trimmed;
+ const parts = rawRest.split("/").filter(Boolean);
+ if (parts.length === 0) return trimmed;
+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
+ return `viking://user/${space}/${parts.join("/")}`;
+}
+
+async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {
+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);
+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };
+ const res = await fetchJSON("/api/v1/search/find", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId });
+ if (!res.ok) return [];
+ const items = res.result?.[source.bucket] || [];
+ return items.map((item) => ({ ...item, _sourceType: source.type }));
+}
+
+async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {
+ const results = await Promise.all(
+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),
+ );
+ const all = results.flat();
+ log("recall_search_summary", {
+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),
+ total: all.length,
+ });
+ return all;
+}
+
+async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
+ let content;
+
+ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {
+ content = (item.abstract || item.overview).trim();
+ } else if (item.level === 2) {
+ try {
+ const res = await fetchJSON(
+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,
+ {},
+ { actorPeerId },
+ );
+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";
+ content = body || (item.abstract || item.overview || "").trim() || item.uri;
+ } catch {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+ } else {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+
+ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));
+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;
+ return content;
+}
+
+async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
+ if (items.length === 0) return null;
+
+ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const lines = [
+ "<openviking-context>",
+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
+ ];
+ let contentCount = 0;
+ let hintCount = 0;
+
+ for (const item of items) {
+ const score = (clampScore(item.score) * 100).toFixed(0);
+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;
+
+ if (budgetRemaining > 0) {
+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);
+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;
+ const lineTokens = estimateTokens(contentLine);
+
+ if (lineTokens > budgetRemaining && contentCount > 0) {
+ lines.push(uriLine);
+ hintCount++;
+ } else {
+ lines.push(contentLine);
+ budgetRemaining -= lineTokens;
+ contentCount++;
+ }
+ } else {
+ lines.push(uriLine);
+ hintCount++;
+ }
+ }
+
+ lines.push("</openviking-context>");
+
+ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ log("recall_injection_built", {
+ contentItems: contentCount,
+ hintItems: hintCount,
+ budgetUsed,
+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ });
+
+ return lines.join("\n");
+}
+
+async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {
+ const body = buildRecallEndpointBody(cfg);
+ body.query = query;
+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });
+ if (!res.ok) {
+ log("recall_endpoint_fallback", { status: res.status || 0 });
+ return null;
+ }
+ const rendered = String(res.result?.rendered || "").trim();
+ if (!rendered) return "";
+ return [
+ "<openviking-context>",
+ "Relevant memory from OpenViking. Use the recall/read MCP tools to expand URIs.",
+ rendered,
+ "</openviking-context>",
+ ].join("\n");
+}
+
+export async function postRecall(fetchJSON, body, opts = {}) {
+ const actorPeerId = opts.actorPeerId || "";
+ const log = opts.log || (() => {});
+ const request = { ...body };
+ const res = await fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(request),
+ }, { actorPeerId });
+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {
+ return res;
+ }
+
+ const downgraded = { ...request };
+ delete downgraded.peer_scope;
+ log("recall_peer_scope_downgrade", { status: res.status || 0 });
+ return fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(downgraded),
+ }, { actorPeerId });
+}
+
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
+ const log = options.log || (() => {});
+ const trimmed = String(query || "").trim();
+ if (!trimmed) return null;
+
+ const endpointBlock = await recallViaEndpoint(fetchJSON, cfg, trimmed, actorPeerId, log);
+ if (endpointBlock !== null) return endpointBlock || null;
+
+ const recallLimit = Math.max(1, Number(cfg.recallLimit || 6));
+ const perSourceLimit = Math.max(recallLimit * 2, 8);
+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
+ if (raw.length === 0) return null;
+
+ const profile = buildQueryProfile(trimmed);
+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);
+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));
+ const picked = dedupeItems(filtered).slice(0, recallLimit);
+ log("recall_picked", {
+ rawCount: raw.length,
+ filteredCount: filtered.length,
+ pickedCount: picked.length,
+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
+ });
+
+ if (picked.length === 0) return null;
+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/session-model.mjs b/examples/zcode-memory-plugin/scripts/shared/session-model.mjs
new file mode 100644
index 000000000..b6496a113
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/session-model.mjs
@@ -0,0 +1,57 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Shared OpenViking session-id helpers for memory plugin harnesses.
+ */
+
+/**
+ * Glob -> RegExp. Minimal implementation: supports `*`, `**`, and literals.
+ */
+function globToRe(glob) {
+ let re = "^";
+ for (let i = 0; i < glob.length; i++) {
+ const c = glob[i];
+ if (c === "*") {
+ if (glob[i + 1] === "*") { re += ".*"; i++; }
+ else re += "[^/]*";
+ } else if (/[.+?^${}()|[\]\\]/.test(c)) {
+ re += "\\" + c;
+ } else {
+ re += c;
+ }
+ }
+ re += "$";
+ return new RegExp(re);
+}
+
+export function isBypassed(cfg, { sessionId, cwd } = {}) {
+ if (cfg.bypassSession) return true;
+ const patterns = cfg.bypassSessionPatterns || [];
+ if (patterns.length === 0) return false;
+ const haystacks = [sessionId, cwd].filter(Boolean);
+ for (const pat of patterns) {
+ const re = globToRe(pat);
+ if (haystacks.some((h) => re.test(h))) return true;
+ }
+ return false;
+}
+
+function safeId(value, replacement = "_") {
+ return String(value || "unknown").replace(/[^A-Za-z0-9._-]/g, replacement);
+}
+
+export function deriveHarnessSessionId(prefix, sessionId, suffix = "") {
+ if (!prefix || typeof prefix !== "string") {
+ throw new Error("deriveHarnessSessionId requires a non-empty prefix");
+ }
+ if (!sessionId || typeof sessionId !== "string") {
+ throw new Error("deriveHarnessSessionId requires a non-empty sessionId");
+ }
+ const base = `${prefix}${sessionId}`;
+ if (!suffix) return base;
+ const normalized = String(suffix).replace(/:/g, "-").replace(/[^A-Za-z0-9._-]/g, "-");
+ return `${base}__${normalized}`;
+}
+
+export function deriveCodexSessionId(codexSessionId) {
+ return `cx-${safeId(codexSessionId, "_")}`;
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjs b/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjs
new file mode 100644
index 000000000..5108f5f2b
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/setup-wizard.mjs
@@ -0,0 +1,111 @@
+// 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,
+} = {}) {
+ const { cliPath } = loadCredentialFiles(env);
+ const current = readJsonSafe(cliPath);
+ const rl = createInterface({ input, output });
+ const say = (line = "") => output.write(`${line}\n`);
+
+ try {
+ say("OpenViking memory plugin setup");
+ say(`Config file: ${cliPath}`);
+ 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: cliPath };
+ }
+
+ mkdirSync(dirname(cliPath), { recursive: true });
+ if (existsSync(cliPath)) {
+ copyFileSync(cliPath, `${cliPath}.bak.${Date.now()}`);
+ }
+ writeFileSync(cliPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
+ try {
+ chmodSync(cliPath, 0o600);
+ } catch {
+ /* best effort on platforms without chmod semantics */
+ }
+ say(`Written: ${cliPath}`);
+ say("The stdio MCP proxy and hooks pick this up on the next harness start.");
+ return { written: true, path: cliPath };
+ } finally {
+ rl.close();
+ }
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/uri-guard.mjs b/examples/zcode-memory-plugin/scripts/shared/uri-guard.mjs
new file mode 100644
index 000000000..9505ddb5e
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/uri-guard.mjs
@@ -0,0 +1,56 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+const DEFAULT_URI_KEYS = [
+ "filePath",
+ "file_path",
+ "filepath",
+ "path",
+ "uri",
+ "target_uri",
+ "targetUri",
+ "pattern",
+];
+
+export function normalizeToolName(value) {
+ return String(value || "").trim().toLowerCase();
+}
+
+export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS) {
+ if (!args || typeof args !== "object") return null;
+ for (const key of keys) {
+ const uri = findVikingUriInValue(args[key]);
+ if (uri) return uri;
+ }
+ return findVikingUriInValue(args);
+}
+
+export function findVikingUriInValue(value) {
+ if (typeof value === "string") {
+ const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i);
+ return match?.[0] || null;
+ }
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const uri = findVikingUriInValue(item);
+ if (uri) return uri;
+ }
+ return null;
+ }
+ if (value && typeof value === "object") {
+ for (const item of Object.values(value)) {
+ const uri = findVikingUriInValue(item);
+ if (uri) return uri;
+ }
+ }
+ return null;
+}
+
+export function buildGuardMessage(uri, hint = {}) {
+ const tool = hint.tool || "the OpenViking MCP tools";
+ const example = typeof hint.example === "function" ? hint.example(uri) : hint.example;
+ const lines = [
+ "viking:// URIs are OpenViking virtual paths, not local filesystem paths.",
+ `Use ${tool} instead.`,
+ ];
+ if (example) lines.push(`Example: ${example}`);
+ return lines.join("\n");
+}
diff --git a/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs
new file mode 100644
index 000000000..6b5cd45ec
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs
@@ -0,0 +1,16 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+export function deriveWorkspacePeerId(cwd) {
+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");
+}
+
+export function resolveEffectivePeerId({ cfg = {}, cwd = "" } = {}) {
+ const explicit = String(cfg.peerId || "").trim();
+ if (explicit) return { peerId: explicit, source: "explicit" };
+
+ if (cfg.workspacePeer !== false) {
+ const peerId = deriveWorkspacePeerId(cwd);
+ if (peerId) return { peerId, source: "workspace" };
+ }
+
+ return { peerId: "", source: "none" };
+}
diff --git a/examples/zcode-memory-plugin/scripts/uri-guard.mjs b/examples/zcode-memory-plugin/scripts/uri-guard.mjs
new file mode 100644
index 000000000..a415c537f
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/uri-guard.mjs
@@ -0,0 +1,51 @@
+#!/usr/bin/env node
+
+/**
+ * URI guard for ZCode (PreToolUse event).
+ *
+ * Denies direct Read/Glob/Grep of viking:// URIs and redirects the agent to
+ * OpenViking MCP tools. Uses the shared agent-uri-guard runtime for detection
+ * and message formatting.
+ *
+ * Output contract: ZCode strict JSON — emits ONLY recognized keys:
+ * { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: "..." } }
+ * Pass-through (no viking:// URI): empty output + implicit exit 0.
+ */
+
+import { readFileSync, realpathSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { evaluateAgentUriGuard } from "./shared/agent-uri-guard.mjs";
+
+function readInput() {
+ try {
+ const raw = readFileSync(0, "utf8").trim();
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+export function evaluateZcodeUriGuard(input = {}) {
+ const toolName =
+ input.tool_name ?? input.toolName ?? input.name ?? input.tool;
+ const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};
+ const decision = evaluateAgentUriGuard(toolName, toolInput);
+ if (!decision) return {};
+ return {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: decision.reason,
+ },
+ };
+}
+
+const isEntrypoint =
+ process.argv[1] &&
+ realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
+if (isEntrypoint) {
+ const output = evaluateZcodeUriGuard(readInput());
+ if (Object.keys(output).length > 0) {
+ process.stdout.write(`${JSON.stringify(output)}\n`);
+ }
+}
diff --git a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
new file mode 100644
index 000000000..5cf4827f1
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
@@ -0,0 +1,203 @@
+#!/usr/bin/env node
+
+/**
+ * ZCode hook dispatcher.
+ *
+ * Mirrors the TRAE adapter pattern: a single entry point branched on
+ * OPENVIKING_HOOK_EVENT. Four thin shim scripts set the event env var and
+ * import this module.
+ *
+ * Output contract: ZCode parses hook stdout as strict JSON — any unrecognized
+ * key causes the entire output to be silently discarded. Therefore we NEVER
+ * emit Claude-Code-isms like { "decision": "approve" }. Instead:
+ * - Context injection: { hookSpecificOutput: { hookEventName, additionalContext } }
+ * - Pass-through: empty output (stdout = "") + exit 0
+ *
+ * The deny path (PreToolUse) is handled separately by uri-guard.mjs, which
+ * emits { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", ... } }.
+ */
+
+import {
+ addAgentMessages,
+ buildAgentProfile,
+ commitAgentSession,
+ createAgentLogger,
+ deriveAgentSessionId,
+ loadAgentHookConfig,
+ makeAgentFetchJSON,
+ readHookInput,
+ readHookState,
+ recallForPrompt,
+ replayAgentPending,
+ resolveAgentCwd,
+ resolveNativeSessionId,
+ shouldBypassAgent,
+ stableHash,
+ withAgentHookLock,
+ writeHookState,
+} from "./shared/agent-hook-runtime.mjs";
+import { buildZcodeTurns, cleanZcodeText } from "./zcode-turns.mjs";
+
+const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
+const cfg = loadAgentHookConfig("zcode");
+const { log, logError } = createAgentLogger("zcode", eventName, cfg);
+
+/**
+ * Emit context injection output for SessionStart / UserPromptSubmit.
+ * Uses ONLY ZCode-recognized keys: hookSpecificOutput with hookEventName + additionalContext.
+ * No `decision` field — that is a Claude-Code-ism that ZCode's strict schema rejects.
+ */
+function outputContext(additionalContext, hookEventName) {
+ if (!additionalContext) {
+ // Pass-through: empty output + implicit exit 0
+ return;
+ }
+ process.stdout.write(
+ JSON.stringify({
+ hookSpecificOutput: {
+ hookEventName,
+ additionalContext,
+ },
+ }) + "\n",
+ );
+}
+
+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);
+
+async function main() {
+ if (!cfg.enabled || shouldBypassAgent(cfg, input)) {
+ return;
+ }
+ let state = await readHookState("zcode", nativeSessionId);
+
+ // --- SessionStart: inject user profile + replay pending ---
+ if (eventName === "session-start") {
+ const profile = await withAgentHookLock("zcode", nativeSessionId, async () => {
+ state = await readHookState("zcode", nativeSessionId);
+ const now = Date.now();
+ if (now - Number(state.lastSessionStartAt || 0) < 2000) return null;
+ state = { ...state, lastSessionStartAt: now };
+ await writeHookState("zcode", nativeSessionId, state);
+ await replayAgentPending(fetchJSON, log).catch((error) => logError("pending", error));
+ return buildAgentProfile(fetchJSON, cfg, cwd).catch((error) => {
+ logError("profile", error);
+ return null;
+ });
+ });
+ outputContext(
+ profile ? `<openviking-context source="session-start">\n${profile}\n</openviking-context>` : "",
+ "SessionStart",
+ );
+ return;
+ }
+
+ // --- UserPromptSubmit: recall relevant memories ---
+ if (eventName === "user-prompt-submit") {
+ const prompt = cleanZcodeText(
+ input.prompt || input.user_prompt || input.userMessage || input.user_message || input.message || "",
+ );
+ if (!prompt) return;
+ const recallBlock = await withAgentHookLock("zcode", nativeSessionId, async () => {
+ state = await readHookState("zcode", nativeSessionId);
+ const promptHash = stableHash(prompt);
+ const now = Date.now();
+ const promptEventId =
+ input.generation_id || input.request_id || input.message_id || input.prompt_id || "";
+ const duplicateEvent = promptEventId
+ ? state.promptEventId === promptEventId
+ : state.promptHash === promptHash && now - Number(state.promptAt || 0) < 500;
+ if (duplicateEvent) return null;
+ const block =
+ state.promptHash === promptHash && state.recallBlock
+ ? state.recallBlock
+ : await recallForPrompt(fetchJSON, cfg, prompt, cwd, log).catch((error) => {
+ logError("recall", error);
+ return null;
+ });
+ await writeHookState("zcode", nativeSessionId, {
+ ...state,
+ promptHash,
+ promptEventId,
+ promptAt: now,
+ recallBlock: block,
+ pendingPrompt: { prompt, hash: promptHash, at: now },
+ });
+ return block;
+ });
+ outputContext(recallBlock || "", "UserPromptSubmit");
+ return;
+ }
+
+ // --- Stop: capture incremental turns + commit ---
+ if (eventName === "stop") {
+ 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;
+ }
+ }
+
+ // 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);
+ }
+ }
+ 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),
+ capturedSinceCommit: nextCount,
+ pendingPrompt: null,
+ lastTurnId: newLastTurnId,
+ });
+ });
+ // Stop: no output needed (pass-through)
+ return;
+ }
+
+ // Unknown event: pass-through silently
+}
+
+main().catch((error) => {
+ logError("uncaught", error);
+ // Pass-through on error — never block the session
+});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs b/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
new file mode 100644
index 000000000..6e79c022a
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
@@ -0,0 +1,119 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+import { evaluateZcodeUriGuard } from "./uri-guard.mjs";
+
+const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
+
+// ---------------------------------------------------------------------------
+// URI Guard output schema (the #1 silent-failure mode in the adversarial review)
+// ZCode's strict JSON schema rejects any unrecognized key. These tests assert
+// the output contains ONLY ZCode-recognized keys.
+// ---------------------------------------------------------------------------
+
+test("uri guard deny output contains only recognized keys", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Read",
+ tool_input: { file_path: "viking://user/memories/profile.md" },
+ });
+ assert.ok(output.hookSpecificOutput);
+ assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");
+ assert.equal(output.hookSpecificOutput.permissionDecision, "deny");
+ assert.ok(output.hookSpecificOutput.permissionDecisionReason);
+ // Must NOT contain Claude-Code-isms
+ assert.equal(output.decision, undefined);
+ assert.equal(output.hookSpecificOutput.decision, undefined);
+});
+
+test("uri guard deny reason includes MCP redirect", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Read",
+ tool_input: { file_path: "viking://resources/myproject/docs.md" },
+ });
+ const reason = output.hookSpecificOutput?.permissionDecisionReason || "";
+ assert.ok(reason.includes("MCP"), "reason should mention MCP");
+});
+
+test("uri guard pass-through for non-viking URIs returns empty", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Read",
+ tool_input: { file_path: "/tmp/local-file.txt" },
+ });
+ assert.equal(Object.keys(output).length, 0);
+});
+
+test("uri guard pass-through for Glob with local pattern", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Glob",
+ tool_input: { pattern: "**/*.ts" },
+ });
+ assert.equal(Object.keys(output).length, 0);
+});
+
+test("uri guard deny for Glob with viking URI", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Glob",
+ tool_input: { pattern: "viking://user/memories/**" },
+ });
+ assert.equal(output.hookSpecificOutput.permissionDecision, "deny");
+});
+
+test("uri guard handles alternative tool_input field names", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Read",
+ toolInput: { file_path: "viking://user/test.md" },
+ });
+ assert.equal(output.hookSpecificOutput?.permissionDecision, "deny");
+});
+
+test("uri guard handles alternative tool_name field names", () => {
+ const output = evaluateZcodeUriGuard({
+ toolName: "Read",
+ tool_input: { file_path: "viking://user/test.md" },
+ });
+ assert.equal(output.hookSpecificOutput?.permissionDecision, "deny");
+});
+
+test("uri guard returns empty for unmatched tool name", () => {
+ const output = evaluateZcodeUriGuard({
+ tool_name: "Bash",
+ tool_input: { command: "cat viking://user/test.md" },
+ });
+ // Bash is not in the Read|Glob|Grep matcher — but evaluateAgentUriGuard
+ // may still detect viking:// in certain fields. The important assertion is
+ // that the output shape is valid (either empty or correct deny).
+ if (Object.keys(output).length > 0) {
+ assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Source-file conventions: hooks.json and .mcp.json must use ZCODE_PLUGIN_ROOT
+// (not CLAUDE_PLUGIN_ROOT) in a .zcode-plugin/ plugin for naming consistency.
+// ---------------------------------------------------------------------------
+
+test("hooks.json uses ZCODE_PLUGIN_ROOT, not CLAUDE_PLUGIN_ROOT", () => {
+ const hooksJson = readFileSync(join(PLUGIN_ROOT, "hooks", "hooks.json"), "utf8");
+ assert.ok(
+ !hooksJson.includes("CLAUDE_PLUGIN_ROOT"),
+ "hooks.json should use ${ZCODE_PLUGIN_ROOT}, not ${CLAUDE_PLUGIN_ROOT}",
+ );
+ assert.ok(
+ hooksJson.includes("ZCODE_PLUGIN_ROOT"),
+ "hooks.json should reference ${ZCODE_PLUGIN_ROOT}",
+ );
+});
+
+test(".mcp.json uses ZCODE_PLUGIN_ROOT, not CLAUDE_PLUGIN_ROOT", () => {
+ const mcpJson = readFileSync(join(PLUGIN_ROOT, ".mcp.json"), "utf8");
+ assert.ok(
+ !mcpJson.includes("CLAUDE_PLUGIN_ROOT"),
+ ".mcp.json should use ${ZCODE_PLUGIN_ROOT}, not ${CLAUDE_PLUGIN_ROOT}",
+ );
+ assert.ok(
+ mcpJson.includes("ZCODE_PLUGIN_ROOT"),
+ ".mcp.json should reference ${ZCODE_PLUGIN_ROOT}",
+ );
+});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-turns.mjs b/examples/zcode-memory-plugin/scripts/zcode-turns.mjs
new file mode 100644
index 000000000..ca98b4626
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-turns.mjs
@@ -0,0 +1,186 @@
+/**
+ * Pure transcript parser for ZCode hook events.
+ *
+ * ZCode's Stop hook stdin payload is not fully documented. Based on
+ * reverse-engineering (#3127 by @quinn-zenith) and rollout file analysis,
+ * the Stop payload contains at least:
+ * - session_id / sessionId
+ * - cwd
+ * - transcript_path (points to a TEMP file with only the LAST assistant
+ * message — NOT a complete conversation)
+ * - responseText / responsePreview (the last assistant response text)
+ *
+ * The rollout files at ~/.zcode/cli/rollout/model-io-*.jsonl contain
+ * the COMPLETE conversation with this structure per line:
+ * { sessionId, turnId, type: "model_io",
+ * request: { messages: [{ role, content }] },
+ * 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
+ */
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+const INJECTED_BLOCK_RE = /<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi;
+const RELEVANT_MEMORIES_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;
+const SYSTEM_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
+
+/**
+ * Strip plugin-injected blocks and trim whitespace.
+ */
+export function cleanZcodeText(value) {
+ return String(value || "")
+ .replace(INJECTED_BLOCK_RE, "")
+ .replace(RELEVANT_MEMORIES_RE, "")
+ .replace(SYSTEM_REMINDER_RE, "")
+ .trim();
+}
+
+/**
+ * Resolve the rollout file path for a given session ID.
+ * ZCode stores rollout at ~/.zcode/cli/rollout/model-io-<sessionId>.jsonl
+ */
+function resolveRolloutPath(input = {}) {
+ const sessionId =
+ input.session_id || input.sessionId || input.conversation_id || "";
+ if (!sessionId) return null;
+ const home = process.env.HOME || process.env.USERPROFILE || "";
+ // ZCode rollout files are named: model-io-<sessionId>.jsonl
+ // sessionId already includes the "sess_" prefix, so no extra "sess-" needed.
+ return join(home, ".zcode", "cli", "rollout", `model-io-${sessionId}.jsonl`);
+}
+
+/**
+ * Extract the user message from a rollout entry's request.messages.
+ * Finds the last user-role message in the array.
+ */
+function extractUserFromMessages(messages) {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.role === "user") {
+ const content = typeof msg.content === "string"
+ ? msg.content
+ : Array.isArray(msg.content)
+ ? msg.content.filter((b) => b?.type === "text").map((b) => b.text).join("\n")
+ : "";
+ const cleaned = cleanZcodeText(content);
+ if (cleaned) return cleaned;
+ break;
+ }
+ }
+ return "";
+}
+
+/**
+ * Read ALL unseen turns from a ZCode rollout file since lastKnownTurnId.
+ * Each rollout line is a JSON object with turnId, request.messages, response.text.
+ *
+ * @param {string} rolloutPath - Path to the rollout JSONL file.
+ * @param {string} lastKnownTurnId - The last processed turnId (exclusive bound).
+ * @returns {Array<{role: string, content: string, turnId: string}>} Unseen turns.
+ */
+export function extractUnseenRolloutTurns(rolloutPath, lastKnownTurnId = null) {
+ if (!rolloutPath) return [];
+ let raw;
+ try {
+ raw = readFileSync(rolloutPath, "utf8");
+ } catch {
+ return [];
+ }
+
+ const lines = raw.trim().split("\n").filter(Boolean);
+ if (lines.length === 0) return [];
+
+ // If we have a lastKnownTurnId, find its position and return everything after.
+ // If not, return only the last entry (first-time capture).
+ let startIndex = 0;
+ if (lastKnownTurnId) {
+ const foundIndex = lines.findIndex((line) => {
+ try {
+ return JSON.parse(line).turnId === lastKnownTurnId;
+ } catch {
+ return false;
+ }
+ });
+ if (foundIndex >= 0) startIndex = foundIndex + 1;
+ }
+ // No lastKnownTurnId → capture ALL entries (first-time capture should not
+ // lose prior turns). Previously only returned the last entry.
+
+ const turns = [];
+ for (let i = startIndex; i < lines.length; i++) {
+ let entry;
+ try {
+ entry = JSON.parse(lines[i]);
+ } catch {
+ continue;
+ }
+ const turnId = entry.turnId || "";
+ const userContent = extractUserFromMessages(entry?.request?.messages || []);
+ const assistantContent = cleanZcodeText(entry?.response?.text || "");
+ if (userContent) {
+ turns.push({ role: "user", content: userContent, turnId });
+ }
+ if (assistantContent) {
+ turns.push({ role: "assistant", content: assistantContent, turnId });
+ }
+ }
+
+ return 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.
+ *
+ * @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 = {}) {
+ // Assistant content: try documented and reverse-engineered field names
+ const assistantContent =
+ input.responseText ||
+ input.responsePreview ||
+ input.last_assistant_message ||
+ input.assistantMessage ||
+ input.assistant_message ||
+ input.text_content ||
+ input.response ||
+ "";
+
+ // User content: try multiple field names
+ const userContent =
+ input.prompt ||
+ input.user_prompt ||
+ input.userMessage ||
+ input.user_message ||
+ input.last_user_message ||
+ input.message ||
+ state.pendingPrompt?.prompt ||
+ "";
+
+ // Build turns from stdin payload
+ let turns = [
+ { 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
new file mode 100644
index 000000000..7521b4f67
--- /dev/null
+++ b/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
@@ -0,0 +1,336 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { buildZcodeTurns, cleanZcodeText, extractUnseenRolloutTurns } from "./zcode-turns.mjs";
+
+test("cleanZcodeText strips openviking-context blocks", () => {
+ const input = "hello <openviking-context source=\"test\">secret</openviking-context> world";
+ assert.equal(cleanZcodeText(input), "hello world");
+});
+
+test("cleanZcodeText strips relevant-memories blocks", () => {
+ const input = "text <relevant-memories>old</relevant-memories> here";
+ assert.equal(cleanZcodeText(input), "text here");
+});
+
+test("cleanZcodeText strips system-reminder blocks", () => {
+ const input = "msg <system-reminder>warn</system-reminder> end";
+ assert.equal(cleanZcodeText(input), "msg end");
+});
+
+test("cleanZcodeText returns empty string for undefined/null", () => {
+ assert.equal(cleanZcodeText(undefined), "");
+ assert.equal(cleanZcodeText(null), "");
+});
+
+test("cleanZcodeText trims whitespace", () => {
+ assert.equal(cleanZcodeText(" hello "), "hello");
+});
+
+test("buildZcodeTurns extracts user + assistant from prompt/responseText", () => {
+ const turns = buildZcodeTurns({
+ prompt: "what is my name?",
+ responseText: "Your name is Alice.",
+ });
+ assert.equal(turns.length, 2);
+ assert.equal(turns[0].role, "user");
+ assert.equal(turns[0].content, "what is my name?");
+ assert.equal(turns[1].role, "assistant");
+ assert.equal(turns[1].content, "Your name is Alice.");
+});
+
+test("buildZcodeTurns probes responsePreview field", () => {
+ const turns = buildZcodeTurns({
+ prompt: "hello",
+ responsePreview: "hi there",
+ });
+ assert.equal(turns.length, 2);
+ assert.equal(turns[1].content, "hi there");
+});
+
+test("buildZcodeTurns returns only assistant turn when no prompt", () => {
+ const turns = buildZcodeTurns({ responseText: "hi there" });
+ assert.equal(turns.length, 1);
+ assert.equal(turns[0].role, "assistant");
+ assert.equal(turns[0].content, "hi there");
+});
+
+test("buildZcodeTurns returns empty array when both empty", () => {
+ const turns = buildZcodeTurns({});
+ assert.equal(turns.length, 0);
+});
+
+test("buildZcodeTurns falls back to state.pendingPrompt", () => {
+ const turns = buildZcodeTurns(
+ { responseText: "answer" },
+ { pendingPrompt: { prompt: "cached question" } },
+ );
+ assert.equal(turns.length, 2);
+ assert.equal(turns[0].role, "user");
+ assert.equal(turns[0].content, "cached question");
+});
+
+test("buildZcodeTurns strips injected blocks from content", () => {
+ const turns = buildZcodeTurns({
+ prompt: "real question <openviking-context>injected</openviking-context>",
+ responseText: "answer <relevant-memories>old</relevant-memories>",
+ });
+ assert.equal(turns[0].content, "real question");
+ assert.equal(turns[1].content, "answer");
+});
+
+test("buildZcodeTurns probes alternative field names", () => {
+ const turns = buildZcodeTurns({
+ user_prompt: "alt prompt",
+ assistantMessage: "alt response",
+ });
+ assert.equal(turns.length, 2);
+ assert.equal(turns[0].content, "alt prompt");
+ assert.equal(turns[1].content, "alt response");
+});
+
+// ---------------------------------------------------------------------------
+// Rollout fallback + turnId tests
+// ---------------------------------------------------------------------------
+
+function createFakeRolloutHome(entries) {
+ const sessionId = "test-sess-rollout";
+ const fakeHome = mkdtempSync(join(tmpdir(), "zcode-home-"));
+ const rolloutDir = join(fakeHome, ".zcode", "cli", "rollout");
+ mkdirSync(rolloutDir, { recursive: true });
+ const lines = entries.map((e) => JSON.stringify(e)).join("\n");
+ writeFileSync(join(rolloutDir, `model-io-${sessionId}.jsonl`), lines + "\n");
+ return { fakeHome, sessionId };
+}
+
+test("extractUnseenRolloutTurns returns ALL entries when no lastKnownTurnId", () => {
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "first q" }] }, response: { text: "first a" } },
+ { turnId: "turn-002", request: { messages: [{ role: "user", content: "second q" }] }, response: { text: "second a" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = extractUnseenRolloutTurns(
+ join(fakeHome, ".zcode", "cli", "rollout", `model-io-${sessionId}.jsonl`),
+ null,
+ );
+ process.env.HOME = originalHome;
+ // No lastKnownTurnId → returns ALL entries (first-time capture should not lose prior turns)
+ assert.equal(turns.length, 4); // user+assistant × 2 entries
+ assert.equal(turns[0].content, "first q");
+ assert.equal(turns[0].turnId, "turn-001");
+ assert.equal(turns[1].content, "first a");
+ assert.equal(turns[1].turnId, "turn-001");
+ assert.equal(turns[2].content, "second q");
+ assert.equal(turns[2].turnId, "turn-002");
+});
+
+test("extractUnseenRolloutTurns returns all entries after lastKnownTurnId", () => {
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "q1" }] }, response: { text: "a1" } },
+ { turnId: "turn-002", request: { messages: [{ role: "user", content: "q2" }] }, response: { text: "a2" } },
+ { turnId: "turn-003", request: { messages: [{ role: "user", content: "q3" }] }, response: { text: "a3" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = extractUnseenRolloutTurns(
+ join(fakeHome, ".zcode", "cli", "rollout", `model-io-${sessionId}.jsonl`),
+ "turn-001",
+ );
+ process.env.HOME = originalHome;
+ // Should return turn-002 and turn-003 (4 turns: user+assistant × 2)
+ assert.equal(turns.length, 4);
+ assert.equal(turns[0].content, "q2");
+ assert.equal(turns[0].turnId, "turn-002");
+ assert.equal(turns[2].content, "q3");
+ assert.equal(turns[2].turnId, "turn-003");
+});
+
+test("buildZcodeTurns falls back to rollout when user content missing", () => {
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "rollout question" }] }, response: { text: "rollout answer" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = buildZcodeTurns({
+ session_id: sessionId,
+ responseText: "stdin assistant only",
+ });
+ process.env.HOME = originalHome;
+ assert.ok(turns.length >= 2);
+ assert.equal(turns[0].role, "user");
+ assert.ok(turns[0].content.includes("rollout"));
+ assert.ok(turns[0].turnId, "turn from rollout should carry turnId");
+});
+
+test("buildZcodeTurns handles missing rollout file gracefully", () => {
+ const turns = buildZcodeTurns({
+ session_id: "nonexistent-session",
+ responseText: "assistant only",
+ });
+ assert.equal(turns.length, 1);
+ assert.equal(turns[0].role, "assistant");
+ assert.equal(turns[0].content, "assistant only");
+});
+
+test("buildZcodeTurns respects lastTurnId in state for incremental capture", () => {
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "old q" }] }, response: { text: "old a" } },
+ { turnId: "turn-002", request: { messages: [{ role: "user", content: "new q" }] }, response: { text: "new a" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ // Pass state with lastTurnId = turn-001 → should only get turn-002
+ const turns = buildZcodeTurns(
+ { session_id: sessionId, responseText: "ignored" },
+ { lastTurnId: "turn-001" },
+ );
+ process.env.HOME = originalHome;
+ assert.equal(turns.length, 2); // user + assistant from turn-002
+ assert.equal(turns[0].content, "new q");
+ assert.equal(turns[0].turnId, "turn-002");
+});
+
+// ---------------------------------------------------------------------------
+// Lifecycle tests: duplicate Stop, missed Stop, repeated content on distinct turns
+// ---------------------------------------------------------------------------
+
+test("lifecycle: missed Stop recovers all unseen turns on next fire", () => {
+ // Simulate: Stop fires after turn-001, then hook fails, then Stop fires again
+ // after turn-003. With lastTurnId=turn-001, should get turn-002 AND turn-003.
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "q1" }] }, response: { text: "a1" } },
+ { turnId: "turn-002", request: { messages: [{ role: "user", content: "q2" }] }, response: { text: "a2" } },
+ { turnId: "turn-003", request: { messages: [{ role: "user", content: "q3" }] }, response: { text: "a3" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = buildZcodeTurns(
+ { session_id: sessionId, responseText: "ignored" },
+ { lastTurnId: "turn-001" },
+ );
+ process.env.HOME = originalHome;
+ assert.equal(turns.length, 4); // turn-002 (user+assistant) + turn-003 (user+assistant)
+ assert.equal(turns[0].turnId, "turn-002");
+ assert.equal(turns[2].turnId, "turn-003");
+});
+
+test("lifecycle: user and assistant from same rollout entry both captured", () => {
+ // This is the regression test for the dedup bug where user and assistant
+ // shared the same turnId and the assistant was silently dropped.
+ const { fakeHome, sessionId } = createFakeRolloutHome([
+ { turnId: "turn-001", request: { messages: [{ role: "user", content: "user msg" }] }, response: { text: "assistant msg" } },
+ ]);
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+ const turns = buildZcodeTurns({
+ session_id: sessionId,
+ responseText: "ignored", // triggers rollout fallback (no user content in stdin)
+ });
+ process.env.HOME = originalHome;
+ assert.equal(turns.length, 2);
+ assert.equal(turns[0].role, "user");
+ assert.equal(turns[0].content, "user msg");
+ assert.equal(turns[1].role, "assistant");
+ assert.equal(turns[1].content, "assistant msg");
+ assert.equal(turns[0].turnId, turns[1].turnId); // same turnId, different role
+});
+
+// ---------------------------------------------------------------------------
+// Concurrent session isolation: two sessions in the same workspace must not
+// cross-read each other's rollout data
+// ---------------------------------------------------------------------------
+
+test("isolation: two sessions read their own rollout files, not each other's", () => {
+ const fakeHome = mkdtempSync(join(tmpdir(), "zcode-iso-"));
+ const rolloutDir = join(fakeHome, ".zcode", "cli", "rollout");
+ mkdirSync(rolloutDir, { recursive: true });
+
+ const sessA = "sess-isolation-AAA";
+ const sessB = "sess-isolation-BBB";
+
+ // Each session has its own rollout file with distinct sentinel content
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessA}.jsonl`),
+ JSON.stringify({ turnId: "turn-A1", request: { messages: [{ role: "user", content: "amber-sentinel-A" }] }, response: { text: "response-A" } }) + "\n",
+ );
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessB}.jsonl`),
+ JSON.stringify({ turnId: "turn-B1", request: { messages: [{ role: "user", content: "sapphire-sentinel-B" }] }, response: { text: "response-B" } }) + "\n",
+ );
+
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+
+ // Session A reads its own rollout
+ const turnsA = buildZcodeTurns({ session_id: sessA, responseText: "ignored" });
+ // Session B reads its own rollout
+ const turnsB = buildZcodeTurns({ session_id: sessB, responseText: "ignored" });
+
+ process.env.HOME = originalHome;
+
+ // Session A must NOT contain session B's content
+ const aContents = turnsA.map((t) => t.content).join(" ");
+ assert.ok(aContents.includes("amber-sentinel-A"), "session A should see its own content");
+ assert.ok(!aContents.includes("sapphire-sentinel-B"), "session A must NOT see session B's content");
+
+ // Session B must NOT contain session A's content
+ const bContents = turnsB.map((t) => t.content).join(" ");
+ assert.ok(bContents.includes("sapphire-sentinel-B"), "session B should see its own content");
+ assert.ok(!bContents.includes("amber-sentinel-A"), "session B must NOT see session A's content");
+
+ // Turn IDs must not cross
+ assert.equal(turnsA[0].turnId, "turn-A1");
+ assert.equal(turnsB[0].turnId, "turn-B1");
+});
+
+test("isolation: independent lastTurnId state per session", () => {
+ const fakeHome = mkdtempSync(join(tmpdir(), "zcode-iso-state-"));
+ const rolloutDir = join(fakeHome, ".zcode", "cli", "rollout");
+ mkdirSync(rolloutDir, { recursive: true });
+
+ const sessA = "sess-state-AAA";
+ const sessB = "sess-state-BBB";
+
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessA}.jsonl`),
+ [
+ JSON.stringify({ turnId: "A-001", request: { messages: [{ role: "user", content: "A1" }] }, response: { text: "a1" } }),
+ JSON.stringify({ turnId: "A-002", request: { messages: [{ role: "user", content: "A2" }] }, response: { text: "a2" } }),
+ ].join("\n") + "\n",
+ );
+ writeFileSync(
+ join(rolloutDir, `model-io-${sessB}.jsonl`),
+ [
+ JSON.stringify({ turnId: "B-001", request: { messages: [{ role: "user", content: "B1" }] }, response: { text: "b1" } }),
+ JSON.stringify({ turnId: "B-002", request: { messages: [{ role: "user", content: "B2" }] }, response: { text: "b2" } }),
+ ].join("\n") + "\n",
+ );
+
+ const originalHome = process.env.HOME;
+ process.env.HOME = fakeHome;
+
+ // Session A processed turn A-001 first; now reads A-002 only
+ const turnsA = buildZcodeTurns(
+ { session_id: sessA, responseText: "ignored" },
+ { lastTurnId: "A-001" },
+ );
+ // Session B is fresh — reads ALL its entries
+ const turnsB = buildZcodeTurns(
+ { session_id: sessB, responseText: "ignored" },
+ {}, // no lastTurnId — first capture
+ );
+
+ process.env.HOME = originalHome;
+
+ // Session A: only A-002 (2 turns: user+assistant)
+ assert.equal(turnsA.length, 2);
+ assert.equal(turnsA[0].turnId, "A-002");
+
+ // Session B: both entries (4 turns: user+assistant × 2)
+ assert.equal(turnsB.length, 4);
+ assert.equal(turnsB[0].turnId, "B-001");
+ assert.equal(turnsB[2].turnId, "B-002");
+});
diff --git a/examples/zcode-memory-plugin/servers/mcp-proxy.mjs b/examples/zcode-memory-plugin/servers/mcp-proxy.mjs
new file mode 100644
index 000000000..3699d140a
--- /dev/null
+++ b/examples/zcode-memory-plugin/servers/mcp-proxy.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+
+import { fileURLToPath } from "node:url";
+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 { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
+
+function readConfig() {
+ const cfg = loadAgentHookConfig("zcode");
+ return {
+ mcpUrl: cfg.mcpUrl,
+ apiKey: cfg.apiKey,
+ account: cfg.account,
+ user: cfg.user,
+ peerId: cfg.peerId,
+ userAgent: cfg.userAgent,
+ timeoutMs: cfg.timeoutMs,
+ debug: cfg.debug,
+ debugLogPath: cfg.debugLogPath,
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.cliPath || cfg.ovPath || "",
+ watchedPaths: [cfg.cliPath, cfg.ovPath].filter(Boolean),
+ };
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
+ createOpenVikingMcpProxy({ readConfig, loggerFactory: createLogger }).start();
+}