Skip to content

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

refactor(plugins): resolve every harness's knobs from one declaration, and generate the packaged copies at pack time (#4773)

t0sakiaa3ee2f4315f
diff --git a/.gitattributes b/.gitattributes
index 1eaf140f3..41e30e234 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,14 +1,6 @@
# Shared runtime copies generated by examples/memory-plugin-shared/sync.mjs.
+# Only the plugins a host installs by pointing at a directory in this repository
+# keep their copies in git; the rest are built at pack time and gitignored.
examples/claude-code-memory-plugin/scripts/shared/*.mjs linguist-generated=true
examples/codex-memory-plugin/scripts/shared/*.mjs linguist-generated=true
-examples/opencode-plugin/lib/shared/*.mjs linguist-generated=true
-examples/dsh-memory-plugin/shared/*.mjs linguist-generated=true
-examples/pi-coding-agent-extension/shared/*.mjs linguist-generated=true
-examples/zcode-memory-plugin/scripts/shared/*.mjs linguist-generated=true
agent-plugins/servers/shared/*.mjs linguist-generated=true
-
-# Pi owns this module; sync.mjs does not generate it.
-examples/pi-coding-agent-extension/shared/recall-ledger.mjs -linguist-generated
-
-# The openclaw target sync.mjs gained in #4450.
-examples/openclaw-plugin/shared/*.mjs linguist-generated=true
diff --git a/.github/scripts/check-marketplace-archive.mjs b/.github/scripts/check-marketplace-archive.mjs
new file mode 100644
index 000000000..76b2c8426
--- /dev/null
+++ b/.github/scripts/check-marketplace-archive.mjs
@@ -0,0 +1,226 @@
+#!/usr/bin/env node
+
+// What the marketplace archive must contain is not a list anybody keeps: it is
+// what each plugin's manifests name, what those entrypoints import, and what the
+// shared-module sync generates. The hand-typed list this replaced was a second
+// copy of all three and had drifted from every one of them — it named eleven of
+// the twenty-two modules the installer assembles and four of the thirty-eight
+// copies the sync generates.
+
+import { readdir, readFile, stat } from "node:fs/promises";
+import { dirname, join, relative, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ MANIFEST_PATH,
+ ROOT,
+ assembledClosure,
+ importSpecifiers,
+ resolveTargets,
+} from "../../examples/memory-plugin-shared/sync.mjs";
+
+const EXAMPLES = join(ROOT, "examples");
+
+// Manifests a host reads by name to find everything else.
+const HOST_MANIFESTS = ["openviking.integration.json", ".mcp.json", "hooks.json", join("hooks", "hooks.json")];
+const PACKAGE_MANIFESTS = ["plugin.json"];
+
+// Directories a host loads whole; what is inside them is named nowhere.
+const CONTENT_DIRS = ["skills", "rules", "commands"];
+
+const SCRIPT_RE = /[^\s"'`]+\.(?:mjs|cjs|js)\b/g;
+
+async function isFile(path) {
+ return stat(path)
+ .then((info) => info.isFile())
+ .catch(() => false);
+}
+
+async function isDirectory(path) {
+ return stat(path)
+ .then((info) => info.isDirectory())
+ .catch(() => false);
+}
+
+async function filesUnder(dir, out = []) {
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
+ for (const entry of entries) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) await filesUnder(path, out);
+ else if (entry.isFile()) out.push(path);
+ }
+ return out;
+}
+
+/** Every string a JSON document holds, at any depth. */
+function jsonStrings(value, out = []) {
+ if (typeof value === "string") out.push(value);
+ else if (Array.isArray(value)) for (const item of value) jsonStrings(item, out);
+ else if (value && typeof value === "object") for (const item of Object.values(value)) jsonStrings(item, out);
+ return out;
+}
+
+/**
+ * The file a host-templated command names, if the plugin has it.
+ *
+ * Each host writes its plugin root differently — `${CLAUDE_PLUGIN_ROOT}`,
+ * `__OPENVIKING_PLUGIN_ROOT__`, `$PLUGIN_DIR`, or nothing at all — so the
+ * prefix is dropped a segment at a time until what is left is a file in the
+ * plugin, which may be one the plugin reaches across its own boundary.
+ */
+async function resolveInPlugin(root, token) {
+ const parts = token.split("/").filter((part) => part && part !== ".");
+ for (let i = 0; i < parts.length; i += 1) {
+ const candidate = join(root, ...parts.slice(i));
+ if (await isFile(candidate)) return candidate;
+ }
+ return null;
+}
+
+async function namedScripts(root, text) {
+ const found = [];
+ for (const token of text.match(SCRIPT_RE) || []) {
+ const path = await resolveInPlugin(root, token);
+ if (path) found.push(path);
+ }
+ return found;
+}
+
+/** Every module reachable from `entries` by relative import, entries included. */
+async function importClosure(entries) {
+ const reached = new Set();
+ const pending = [...entries];
+ while (pending.length) {
+ const file = pending.pop();
+ if (reached.has(file) || !(await isFile(file))) continue;
+ reached.add(file);
+ const source = await readFile(file, "utf-8");
+ for (const spec of importSpecifiers(source)) {
+ if (spec.startsWith(".")) pending.push(resolve(dirname(file), spec));
+ }
+ }
+ return reached;
+}
+
+/**
+ * Where one plugin's host manifests sit: its own root, plus a directory per host
+ * for a plugin that serves several of them.
+ */
+async function manifestRoots(root) {
+ const roots = [root];
+ for (const entry of await readdir(join(root, "hosts"), { withFileTypes: true }).catch(() => [])) {
+ if (entry.isDirectory()) roots.push(join(root, "hosts", entry.name));
+ }
+ return roots;
+}
+
+/** The manifests, entrypoints and content one staged plugin directory owes. */
+async function pluginRequirements(root) {
+ const required = new Set();
+ const entrypoints = new Set();
+ for (const manifest of PACKAGE_MANIFESTS) {
+ if (await isFile(join(root, manifest))) required.add(join(root, manifest));
+ }
+
+ for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
+ // `.claude-plugin/`, `.codex-plugin/`: the host's own manifest directory,
+ // always small and always shipped whole.
+ if (entry.isDirectory() && entry.name.startsWith(".")) {
+ for (const file of await filesUnder(join(root, entry.name))) required.add(file);
+ }
+ }
+ for (const host of await manifestRoots(root)) {
+ for (const manifest of HOST_MANIFESTS) {
+ if (await isFile(join(host, manifest))) required.add(join(host, manifest));
+ }
+ for (const dir of CONTENT_DIRS) {
+ for (const file of await filesUnder(join(host, dir))) required.add(file);
+ }
+ }
+
+ for (const file of [...required]) {
+ if (file.endsWith(".json")) {
+ for (const value of jsonStrings(JSON.parse(await readFile(file, "utf-8")))) {
+ for (const script of await namedScripts(root, value)) entrypoints.add(script);
+ }
+ } else if (file.endsWith(".md")) {
+ // A skill's own document is its manifest: the command it tells the agent
+ // to run has to be in the archive too.
+ for (const script of await namedScripts(root, await readFile(file, "utf-8"))) {
+ entrypoints.add(script);
+ }
+ }
+ }
+
+ for (const file of await importClosure([...entrypoints])) required.add(file);
+ return required;
+}
+
+/** Every file the staged marketplace tree must hold, relative to its root. */
+export async function requiredArchiveFiles(stagedNames) {
+ const staged = new Set(stagedNames);
+ const required = new Set();
+ // The config-driven hook hosts import the shared runtime across the plugin
+ // boundary; anything outside the staged tree is not this archive's.
+ const addIfStaged = (path) => {
+ const name = relative(EXAMPLES, path);
+ if (!name.startsWith("..") && staged.has(name.split(sep)[0])) required.add(name);
+ };
+
+ for (const name of staged) {
+ if (name === "memory-plugin-shared") continue;
+ const root = join(EXAMPLES, name);
+ if (!(await isDirectory(root))) continue;
+ // `.claude-plugin/` and `.agents/` are the marketplace manifests the
+ // installer registers the unzipped directory with, not plugins.
+ if (name.startsWith(".")) {
+ for (const file of await filesUnder(root)) addIfStaged(file);
+ continue;
+ }
+ for (const file of await pluginRequirements(root)) addIfStaged(file);
+ }
+
+ // The plugins that vendor a copy of the shared runtime ship what the sync put
+ // there, and the harnesses that vendor nothing ship the closure the installer
+ // assembles for them, named by the manifest the installer reads.
+ for (const target of await resolveTargets()) {
+ const dir = relative(EXAMPLES, target.dir);
+ if (dir.startsWith("..") || !staged.has(dir.split(sep)[0])) continue;
+ for (const file of target.files) required.add(join(dir, file));
+ }
+ if (staged.has("memory-plugin-shared")) {
+ addIfStaged(MANIFEST_PATH);
+ for (const file of await assembledClosure()) addIfStaged(join(dirname(MANIFEST_PATH), file));
+ }
+
+ return [...required].sort();
+}
+
+async function main(stage, expected) {
+ const missing = [];
+ for (const name of expected) {
+ if (!(await isDirectory(join(stage, name)))) missing.push(`${name}/`);
+ }
+ for (const file of await requiredArchiveFiles(expected)) {
+ if (!(await isFile(join(stage, file)))) missing.push(file);
+ }
+ if (missing.length) {
+ for (const file of missing) process.stderr.write(`Marketplace archive is missing ${file}\n`);
+ process.exit(1);
+ }
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+ const [stage, ...expected] = process.argv.slice(2);
+ // The expected directories are the caller's list, not the stage's own: a name
+ // dropped from it would otherwise leave both this check and the staging script
+ // agreeing that whatever happens to be there is complete.
+ if (!stage || !expected.length) {
+ process.stderr.write("usage: check-marketplace-archive.mjs <stage-dir> <plugin-dir>...\n");
+ process.exit(2);
+ }
+ main(stage, expected).catch((err) => {
+ process.stderr.write(`${err?.stack || err}\n`);
+ process.exit(1);
+ });
+}
diff --git a/.github/scripts/check-plugin-version-bumps.sh b/.github/scripts/check-plugin-version-bumps.sh
new file mode 100755
index 000000000..e9b92524c
--- /dev/null
+++ b/.github/scripts/check-plugin-version-bumps.sh
@@ -0,0 +1,100 @@
+#!/usr/bin/env bash
+# Fail when a distributed plugin changed without its version string.
+#
+# Claude Code resolves an installed plugin by the `version` in its manifest
+# rather than by the commit the marketplace ref points at, so a frozen version
+# string means users keep running the build they already have no matter how
+# many fixes land on main. Other entries use their package or installer manifest;
+# pi is copied wholesale and reports its manifest version on the wire.
+#
+# Usage: check-plugin-version-bumps.sh <base-ref>
+set -euo pipefail
+
+BASE_REF="${1:-}"
+if [ -z "$BASE_REF" ]; then
+ echo "usage: $0 <base-ref>" >&2
+ exit 2
+fi
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+cd "$ROOT"
+
+# <plugin directory>:<manifest holding the version>
+PLUGINS=(
+ "examples/claude-code-memory-plugin:examples/claude-code-memory-plugin/.claude-plugin/plugin.json"
+ "examples/codex-memory-plugin:examples/codex-memory-plugin/.codex-plugin/plugin.json"
+ "examples/agent-hook-plugin:examples/agent-hook-plugin/plugin.json"
+ "examples/opencode-plugin:examples/opencode-plugin/package.json"
+ "examples/dsh-memory-plugin:examples/dsh-memory-plugin/package.json"
+ "examples/pi-coding-agent-extension:examples/pi-coding-agent-extension/package.json"
+)
+
+# A change to the shared library reaches every plugin, and it no longer reaches
+# them through a vendored copy inside their directory: the config-driven hook
+# hosts have the runtime assembled at install time, and the packaged plugins
+# build their copies at pack time. So the library counts as a change to all.
+SHARED_LIB="examples/memory-plugin-shared/lib"
+
+read_version() { # read_version <ref-or-empty> <path>
+ local ref="$1" path="$2" json
+ if [ -n "$ref" ]; then
+ json="$(git show "$ref:$path" 2>/dev/null)" || return 1
+ else
+ json="$(cat "$path")"
+ fi
+ printf '%s' "$json" | node -e '
+let raw = "";
+process.stdin.on("data", (c) => { raw += c; });
+process.stdin.on("end", () => {
+ try { process.stdout.write(String(JSON.parse(raw).version || "")); }
+ catch { process.exit(1); }
+});
+'
+}
+
+# A plugin that carries both a host manifest and an installer manifest has to
+# say the same version in both: the host installs by one and the installer
+# decides "nothing changed" by the other, so a mismatch means a plugin that
+# reports upgraded and behaves like it did not.
+PAIRED=(
+ "examples/agent-hook-plugin/plugin.json:examples/agent-hook-plugin/hosts/cursor/openviking.integration.json"
+ "examples/agent-hook-plugin/plugin.json:examples/agent-hook-plugin/hosts/trae/openviking.integration.json"
+ "examples/agent-hook-plugin/plugin.json:examples/agent-hook-plugin/hosts/zcode/openviking.integration.json"
+)
+
+failed=0
+for entry in "${PAIRED[@]}"; do
+ host="${entry%%:*}"
+ integration="${entry#*:}"
+ [ -f "$host" ] && [ -f "$integration" ] || continue
+ host_version="$(read_version "" "$host")"
+ integration_version="$(read_version "" "$integration")"
+ if [ "$host_version" != "$integration_version" ]; then
+ echo "::error file=$host::$host says $host_version and $integration says $integration_version."
+ failed=1
+ fi
+done
+
+for entry in "${PLUGINS[@]}"; do
+ dir="${entry%%:*}"
+ manifest="${entry#*:}"
+
+ changed="$(git diff --name-only "$BASE_REF...HEAD" -- "$dir" "$SHARED_LIB" | grep -v '/node_modules/' || true)"
+ [ -n "$changed" ] || continue
+
+ # A plugin added in this branch has no baseline version to compare against.
+ before="$(read_version "$BASE_REF" "$manifest")" || continue
+ after="$(read_version "" "$manifest")"
+
+ if [ "$before" = "$after" ]; then
+ echo "::error file=$manifest::$dir changed but its version is still $after."
+ echo " Hosts install by this string, so users receive nothing until it moves."
+ echo " Files changed:"
+ printf ' %s\n' $changed
+ failed=1
+ else
+ echo "ok: $dir $before -> $after"
+ fi
+done
+
+exit "$failed"
diff --git a/.github/scripts/stage-memory-plugin-marketplace.sh b/.github/scripts/stage-memory-plugin-marketplace.sh
index 96b9f151e..944a54b15 100644
--- a/.github/scripts/stage-memory-plugin-marketplace.sh
+++ b/.github/scripts/stage-memory-plugin-marketplace.sh
@@ -5,86 +5,41 @@ set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
STAGE="${1:?usage: stage-memory-plugin-marketplace.sh <stage-dir>}"
+# The plugins published as packages build their shared copies at pack time and
+# keep none in git, so the archive is only complete once the generator has run.
+node "${ROOT}/examples/memory-plugin-shared/sync.mjs" >/dev/null
+
rm -rf "${STAGE}"
mkdir -p "${STAGE}"
-cp -R \
- "${ROOT}/examples/.claude-plugin" \
- "${ROOT}/examples/.agents" \
- "${ROOT}/examples/claude-code-memory-plugin" \
- "${ROOT}/examples/codex-memory-plugin" \
- "${ROOT}/examples/cursor-memory-plugin" \
- "${ROOT}/examples/trae-memory-hooks" \
- "${ROOT}/examples/trae-cli-memory-hooks" \
- "${ROOT}/examples/zcode-memory-plugin" \
- "${ROOT}/examples/opencode-plugin" \
- "${ROOT}/examples/pi-coding-agent-extension" \
- "${ROOT}/examples/memory-plugin-shared" \
- "${STAGE}/"
-for required in \
- claude-code-memory-plugin/skills/ov-experience-memory/SKILL.md \
- codex-memory-plugin/skills/ov-experience-memory/SKILL.md \
- cursor-memory-plugin/.cursor-plugin/plugin.json \
- cursor-memory-plugin/hooks/hooks.json \
- cursor-memory-plugin/.mcp.json \
- cursor-memory-plugin/openviking.integration.json \
- cursor-memory-plugin/scripts/cursor-hook.mjs \
- cursor-memory-plugin/scripts/session-start.mjs \
- cursor-memory-plugin/scripts/auto-recall.mjs \
- cursor-memory-plugin/scripts/auto-capture.mjs \
- cursor-memory-plugin/scripts/pre-compact.mjs \
- cursor-memory-plugin/scripts/session-end.mjs \
- cursor-memory-plugin/scripts/cursor-transcript.mjs \
- cursor-memory-plugin/scripts/uri-guard.mjs \
- cursor-memory-plugin/servers/mcp-proxy.mjs \
- cursor-memory-plugin/rules/openviking-memory.mdc \
- cursor-memory-plugin/skills/openviking-memory/SKILL.md \
- claude-code-memory-plugin/skills/openviking-memory/SKILL.md \
- claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md \
- claude-code-memory-plugin/scripts/ov-memory-doctor.mjs \
- codex-memory-plugin/skills/openviking-memory/SKILL.md \
- codex-memory-plugin/skills/ov-memory-doctor/SKILL.md \
- codex-memory-plugin/scripts/ov-memory-doctor.mjs \
- trae-memory-hooks/hooks/hooks.json \
- trae-memory-hooks/.mcp.json \
- trae-memory-hooks/openviking.integration.json \
- trae-memory-hooks/scripts/trae-hook.mjs \
- trae-memory-hooks/scripts/session-start.mjs \
- trae-memory-hooks/scripts/auto-recall.mjs \
- trae-memory-hooks/scripts/auto-capture.mjs \
- trae-memory-hooks/scripts/trae-turns.mjs \
- trae-memory-hooks/scripts/uri-guard.mjs \
- trae-memory-hooks/servers/mcp-proxy.mjs \
- trae-cli-memory-hooks/hooks/hooks.json \
- trae-cli-memory-hooks/.mcp.json \
- trae-cli-memory-hooks/openviking.integration.json \
- trae-cli-memory-hooks/scripts/trae-cli-hook.mjs \
- trae-cli-memory-hooks/scripts/session-start.mjs \
- trae-cli-memory-hooks/scripts/auto-recall.mjs \
- trae-cli-memory-hooks/scripts/auto-capture.mjs \
- trae-cli-memory-hooks/scripts/trae-cli-turns.mjs \
- trae-cli-memory-hooks/scripts/uri-guard.mjs \
- trae-cli-memory-hooks/servers/mcp-proxy.mjs \
- zcode-memory-plugin/.zcode-plugin/plugin.json \
- zcode-memory-plugin/hooks/hooks.json \
- zcode-memory-plugin/.mcp.json \
- zcode-memory-plugin/openviking.integration.json \
- zcode-memory-plugin/scripts/zcode-hook.mjs \
- zcode-memory-plugin/scripts/zcode-capture.mjs \
- zcode-memory-plugin/scripts/zcode-turns.mjs \
- zcode-memory-plugin/scripts/shared/async-writer.mjs \
- zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs \
- zcode-memory-plugin/scripts/shared/batch-send.mjs \
- zcode-memory-plugin/scripts/shared/retryable.mjs \
- zcode-memory-plugin/servers/mcp-proxy.mjs \
- memory-plugin-shared/lib/agent-hook-runtime.mjs \
- memory-plugin-shared/lib/agent-uri-guard.mjs \
- memory-plugin-shared/lib/async-writer.mjs \
- memory-plugin-shared/lib/retryable.mjs \
- memory-plugin-shared/lib/uri-guard.mjs \
- memory-plugin-shared/lib/mcp-proxy-core.mjs; do
- test -f "${STAGE}/${required}" || {
- echo "Marketplace archive is missing ${required}" >&2
+# The archive ships these directories whole. What each of them has to contain is
+# derived below, not listed here.
+DIRS=(
+ .claude-plugin
+ .agents
+ claude-code-memory-plugin
+ codex-memory-plugin
+ agent-hook-plugin
+ opencode-plugin
+ pi-coding-agent-extension
+ memory-plugin-shared
+)
+
+# Tar drops the plugins' node_modules on the way through, over a hundred
+# megabytes the archive has no use for. Copying only tracked files would drop
+# the generated shared copies the archive does need.
+tar -cf - \
+ --exclude=node_modules \
+ --exclude=.git \
+ -C "${ROOT}/examples" \
+ "${DIRS[@]}" \
+ | tar -xf - -C "${STAGE}"
+
+for dir in "${DIRS[@]}"; do
+ test -d "${STAGE}/${dir}" || {
+ echo "Marketplace archive is missing ${dir}/" >&2
exit 1
}
done
+
+node "${ROOT}/.github/scripts/check-marketplace-archive.mjs" "${STAGE}" "${DIRS[@]}"
diff --git a/.github/workflows/clawhub-dev-release.yml b/.github/workflows/clawhub-dev-release.yml
index c8807a4a5..787368ccd 100644
--- a/.github/workflows/clawhub-dev-release.yml
+++ b/.github/workflows/clawhub-dev-release.yml
@@ -12,6 +12,9 @@ on:
- main
paths:
- "examples/openclaw-plugin/**"
+ - "examples/memory-plugin-shared/lib/**"
+ - "examples/memory-plugin-shared/sync.mjs"
+ - ".github/workflows/clawhub-dev-release.yml"
workflow_dispatch:
inputs:
version:
diff --git a/.github/workflows/dsh-plugin-release.yml b/.github/workflows/dsh-plugin-release.yml
deleted file mode 100644
index 7d24d1013..000000000
--- a/.github/workflows/dsh-plugin-release.yml
+++ /dev/null
@@ -1,80 +0,0 @@
-name: DSH Memory Plugin Release
-
-on:
- push:
- branches: [main]
- paths:
- - "examples/dsh-memory-plugin/**"
- - ".github/workflows/dsh-plugin-release.yml"
- workflow_dispatch:
-
-permissions:
- contents: read
- id-token: write
-
-concurrency:
- group: dsh-plugin-release
- cancel-in-progress: false
-
-jobs:
- publish:
- name: Publish @openviking/dsh-memory-plugin
- runs-on: ubuntu-24.04
- defaults:
- run:
- working-directory: examples/dsh-memory-plugin
- steps:
- - name: Checkout repository
- uses: actions/checkout@v6
-
- - name: Setup Node.js
- uses: actions/setup-node@v6
- with:
- node-version: "24"
- registry-url: "https://registry.npmjs.org"
-
- - name: Install dependencies
- run: npm ci
-
- - name: Validate package
- run: |
- npm run check
- npm test
- npm pack --dry-run
-
- - name: Resolve package version
- id: package
- run: |
- node -e "
- const pkg = require('./package.json')
- if (pkg.name !== '@openviking/dsh-memory-plugin') {
- throw new Error('Unexpected package name: ' + pkg.name)
- }
- console.log('name=' + pkg.name)
- console.log('version=' + pkg.version)
- " >> "$GITHUB_OUTPUT"
-
- - name: Check whether version already exists
- id: published
- env:
- PACKAGE_NAME: ${{ steps.package.outputs.name }}
- PACKAGE_VERSION: ${{ steps.package.outputs.version }}
- run: |
- if npm view "$PACKAGE_NAME@$PACKAGE_VERSION" version --registry=https://registry.npmjs.org >/dev/null 2>&1; then
- echo "exists=true" >> "$GITHUB_OUTPUT"
- echo "::notice::$PACKAGE_NAME@$PACKAGE_VERSION is already published; skipping."
- else
- echo "exists=false" >> "$GITHUB_OUTPUT"
- fi
-
- - name: Publish package
- if: steps.published.outputs.exists == 'false'
- env:
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: |
- if [ -n "${NPM_TOKEN:-}" ]; then
- npm config set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
- else
- echo "::notice::NPM_TOKEN is not set; npm publish will use Trusted Publishing/OIDC. For first-time packages, publish once with an npm token or configure npm trusted publishing after the package exists."
- fi
- npm publish --access public --provenance
diff --git a/.github/workflows/opencode-plugin-release.yml b/.github/workflows/opencode-plugin-release.yml
deleted file mode 100644
index f4e1b2f1f..000000000
--- a/.github/workflows/opencode-plugin-release.yml
+++ /dev/null
@@ -1,73 +0,0 @@
-name: OpenCode Plugin Release
-
-on:
- push:
- branches: [main]
- paths:
- - "examples/opencode-plugin/**"
- - ".github/workflows/opencode-plugin-release.yml"
- - ".github/scripts/opencode-release-version*.mjs"
- workflow_dispatch:
-
-permissions:
- contents: read
- id-token: write
-
-concurrency:
- group: opencode-plugin-release
- cancel-in-progress: false
-
-jobs:
- publish:
- # Forks must not publish the official package.
- if: github.repository == 'volcengine/OpenViking' && github.ref == 'refs/heads/main'
- name: Publish @openviking/opencode-plugin
- runs-on: ubuntu-24.04
- defaults:
- run:
- working-directory: examples/opencode-plugin
- steps:
- - name: Checkout repository
- uses: actions/checkout@v6
- with:
- # Queued runs package current main, never an older event snapshot.
- ref: main
-
- - name: Setup Node.js
- uses: actions/setup-node@v6
- with:
- node-version: "24"
- registry-url: "https://registry.npmjs.org"
-
- - name: Install dependencies
- run: npm install
-
- - name: Validate package
- run: |
- npm run check
- npm test
- npm pack --dry-run
-
- - name: Resolve release version
- id: package
- working-directory: .
- run: |
- node --test .github/scripts/opencode-release-version.test.mjs
- export SOURCE_COMMIT="$(git rev-parse HEAD)"
- node .github/scripts/opencode-release-version.mjs
-
- - name: Validate versioned artifact
- if: steps.package.outputs.published == 'false'
- run: npm pack --dry-run
-
- - name: Publish package
- if: steps.package.outputs.published == 'false'
- env:
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: |
- if [ -n "${NPM_TOKEN:-}" ]; then
- npm config set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
- else
- echo "::notice::NPM_TOKEN is not set; npm publish will use Trusted Publishing/OIDC. For first-time packages, publish once with an npm token or configure npm trusted publishing after the package exists."
- fi
- npm publish --access public --provenance --tag latest
diff --git a/.github/workflows/plugin-npm-release.yml b/.github/workflows/plugin-npm-release.yml
new file mode 100644
index 000000000..dcf667a6b
--- /dev/null
+++ b/.github/workflows/plugin-npm-release.yml
@@ -0,0 +1,110 @@
+name: Plugin npm Release
+
+# Publishes the memory plugins that ship as npm packages. One push filter covers
+# every package in the matrix, so a change to one of them also starts the other
+# legs; those legs stop at the already-published check instead of republishing.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "examples/dsh-memory-plugin/**"
+ - "examples/opencode-plugin/**"
+ - "examples/memory-plugin-shared/lib/**"
+ - "examples/memory-plugin-shared/sync.mjs"
+ - ".github/workflows/plugin-npm-release.yml"
+ - ".github/scripts/opencode-release-version*.mjs"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ # Forks must not publish the official packages.
+ if: github.repository == 'volcengine/OpenViking' && github.ref == 'refs/heads/main'
+ name: Publish ${{ matrix.package }}
+ runs-on: ubuntu-24.04
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - package: "@openviking/dsh-memory-plugin"
+ directory: examples/dsh-memory-plugin
+ install: npm ci
+ - package: "@openviking/opencode-plugin"
+ directory: examples/opencode-plugin
+ # No lockfile in this package, so npm ci cannot run here.
+ install: npm install
+ concurrency:
+ group: plugin-npm-release-${{ matrix.directory }}
+ cancel-in-progress: false
+ defaults:
+ run:
+ working-directory: ${{ matrix.directory }}
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v6
+ with:
+ # Queued runs package current main, never an older event snapshot.
+ ref: main
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v6
+ with:
+ node-version: "24"
+ registry-url: "https://registry.npmjs.org"
+
+ - name: Install dependencies
+ run: ${{ matrix.install }}
+
+ - name: Validate package
+ run: |
+ node ../memory-plugin-shared/sync.mjs
+ npm run check
+ npm test
+ npm pack --dry-run
+
+ - name: Resolve release version
+ id: package
+ env:
+ EXPECTED_NAME: ${{ matrix.package }}
+ run: |
+ if [ "$EXPECTED_NAME" = "@openviking/opencode-plugin" ]; then
+ node --test "$GITHUB_WORKSPACE/.github/scripts/opencode-release-version.test.mjs"
+ SOURCE_COMMIT="$(git rev-parse HEAD)"
+ export SOURCE_COMMIT
+ cd "$GITHUB_WORKSPACE"
+ node .github/scripts/opencode-release-version.mjs
+ exit 0
+ fi
+ package_name=$(node -p "require('./package.json').name")
+ package_version=$(node -p "require('./package.json').version")
+ if [ "$package_name" != "$EXPECTED_NAME" ]; then
+ echo "Unexpected package name: $package_name" >&2
+ exit 1
+ fi
+ echo "version=$package_version" >> "$GITHUB_OUTPUT"
+ if npm view "$package_name@$package_version" version --registry=https://registry.npmjs.org >/dev/null 2>&1; then
+ echo "published=true" >> "$GITHUB_OUTPUT"
+ echo "::notice::$package_name@$package_version is already published; skipping."
+ else
+ echo "published=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Validate versioned artifact
+ if: steps.package.outputs.published == 'false'
+ run: npm pack --dry-run
+
+ - name: Publish package
+ if: steps.package.outputs.published == 'false'
+ env:
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+ run: |
+ if [ -n "${NPM_TOKEN:-}" ]; then
+ npm config set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
+ else
+ echo "::notice::NPM_TOKEN is not set; npm publish will use Trusted Publishing/OIDC. For first-time packages, publish once with an npm token or configure npm trusted publishing after the package exists."
+ fi
+ npm publish --access public --provenance --tag latest
diff --git a/.github/workflows/plugin-shared-sync.yml b/.github/workflows/plugin-shared-sync.yml
new file mode 100644
index 000000000..39b5c091a
--- /dev/null
+++ b/.github/workflows/plugin-shared-sync.yml
@@ -0,0 +1,54 @@
+name: Plugin Shared Runtime Sync
+
+# The plugins a host installs by pointing at a directory in this repository —
+# Claude Code, Codex, and the Agent Plugins package — can only load files git
+# holds, so their copies of the shared runtime have to be committed. Generating
+# them by hand is what let a copy go stale on main while the pull request that
+# changed the library looked complete. This regenerates them after the merge.
+#
+# The plugins published as an npm package or assembled into a tarball build
+# their copies at pack time and keep none in git; nothing here touches them.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "examples/memory-plugin-shared/lib/**"
+ - "examples/memory-plugin-shared/sync.mjs"
+ - "examples/skills/**"
+ - "examples/claude-code-memory-plugin/**"
+ - "examples/codex-memory-plugin/**"
+ - "agent-plugins/**"
+ workflow_dispatch:
+
+permissions:
+ contents: write
+
+concurrency:
+ group: plugin-shared-sync
+ cancel-in-progress: false
+
+jobs:
+ sync:
+ name: Regenerate the committed shared copies
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: "24"
+
+ - run: node examples/memory-plugin-shared/sync.mjs
+
+ - name: Commit what changed
+ run: |
+ git add -A
+ if git diff --cached --quiet; then
+ echo "the committed copies already match the library"
+ exit 0
+ fi
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git commit -m "chore(plugins): regenerate the committed shared runtime copies"
+ git push
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 31e48ac29..61a3f21e5 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -20,6 +20,13 @@ on:
jobs:
plugin-tests:
runs-on: ubuntu-24.04
+ env:
+ # The tests that fork whole installs, named once: the step below runs
+ # exactly what the parallel run subtracts, so renaming one cannot leave
+ # it in both.
+ INSTALLER_TESTS: >-
+ examples/memory-plugin-shared/install-agent-hooks.test.mjs
+ examples/memory-plugin-shared/release-marketplace.test.mjs
steps:
- uses: actions/checkout@v6
@@ -30,66 +37,42 @@ jobs:
- run: npm ci --prefix examples/dsh-memory-plugin
+ # The plugins published as packages keep no shared copies in git; they are
+ # built on the way out, and the tests import them like the package would.
+ - name: Generate the shared runtime copies
+ run: node examples/memory-plugin-shared/sync.mjs
+
+ - name: Committed generator output must be up to date
+ run: |
+ # A module the closure grew reaches the committed lanes as an
+ # untracked file, which `git diff` does not see at all.
+ status=$(git status --porcelain --untracked-files=normal -- examples agent-plugins)
+ if [ -n "$status" ]; then
+ printf '%s\n' "$status"
+ exit 1
+ fi
+ git diff --exit-code
+
- name: Run memory plugin tests
run: |
- node --test \
- examples/codex-memory-plugin/servers/mcp-proxy.test.mjs \
- examples/codex-memory-plugin/scripts/auto-capture.test.mjs \
- examples/codex-memory-plugin/scripts/capture-utils.test.mjs \
- examples/codex-memory-plugin/scripts/marketplace.test.mjs \
- examples/codex-memory-plugin/scripts/ov-credentials.test.mjs \
- examples/codex-memory-plugin/scripts/ov-memory-doctor.test.mjs \
- examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjs \
- examples/codex-memory-plugin/scripts/auto-recall.test.mjs \
- examples/codex-memory-plugin/scripts/session-start-commit.test.mjs \
- examples/codex-memory-plugin/scripts/session-end.test.mjs \
- examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs \
- examples/codex-memory-plugin/scripts/session-state.test.mjs \
- examples/codex-memory-plugin/scripts/config.test.mjs \
- examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs \
- examples/claude-code-memory-plugin/scripts/auto-recall-filters.test.mjs \
- examples/claude-code-memory-plugin/scripts/config.test.mjs \
- examples/claude-code-memory-plugin/scripts/marketplace.test.mjs \
- examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs \
- examples/claude-code-memory-plugin/scripts/uri-guard.test.mjs \
- examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs \
- examples/claude-code-memory-plugin/scripts/lib/recall-core-timeout.test.mjs \
- examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs \
- examples/trae-memory-hooks/scripts/trae-hooks.test.mjs \
- examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs \
- examples/zcode-memory-plugin/scripts/zcode-async.test.mjs \
- examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs \
- examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs \
- examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs \
- examples/memory-plugin-shared/agent-hook-runtime.test.mjs \
- examples/memory-plugin-shared/batch-send.test.mjs \
- examples/memory-plugin-shared/doctor-core.test.mjs \
- examples/memory-plugin-shared/install-agent-hooks.test.mjs \
- examples/memory-plugin-shared/install-lib-closure.test.mjs \
- examples/memory-plugin-shared/install-opencode-jsonc.test.mjs \
- examples/memory-plugin-shared/install-tui.test.mjs \
- examples/memory-plugin-shared/release-marketplace.test.mjs \
- examples/memory-plugin-shared/setup-wizard.test.mjs \
- examples/memory-plugin-shared/sync.test.mjs \
- examples/memory-plugin-shared/mcp-proxy-config.test.mjs \
- examples/memory-plugin-shared/mcp-proxy-core.test.mjs \
- examples/memory-plugin-shared/recall-compress-core.test.mjs \
- examples/memory-plugin-shared/recall-core.test.mjs \
- examples/memory-plugin-shared/recall-session-wiring.test.mjs \
- examples/memory-plugin-shared/workspace-peer.test.mjs \
- examples/memory-plugin-shared/peer-guidance.test.mjs \
- examples/memory-plugin-shared/workspace-identity.test.mjs \
- examples/memory-plugin-shared/workspace-config.test.mjs \
- examples/memory-plugin-shared/workspace-registry.test.mjs \
- examples/memory-plugin-shared/plugin-known-keys.test.mjs \
- examples/memory-plugin-shared/uri-guard.test.mjs \
- examples/memory-plugin-shared/capture-utils.test.mjs \
- examples/memory-plugin-shared/input-filters.test.mjs \
- examples/dsh-memory-plugin/*.test.mjs \
- examples/opencode-plugin/tests/*.test.mjs \
- examples/opencode-plugin/servers/mcp-proxy.test.mjs \
- examples/pi-coding-agent-extension/tests/*.test.mjs \
- agent-plugins/plugin.test.mjs
+ # A pattern no plugin matches yet contributes nothing rather than
+ # reaching node as a literal.
+ shopt -s nullglob
+ files=$(printf '%s\n' \
+ examples/*/scripts/*.test.mjs \
+ examples/*/scripts/lib/*.test.mjs \
+ examples/*/servers/*.test.mjs \
+ examples/*/tests/*.test.mjs \
+ examples/*-plugin/*.test.mjs \
+ examples/memory-plugin-shared/*.test.mjs \
+ agent-plugins/*.test.mjs \
+ | grep -vFxf <(printf '%s\n' $INSTALLER_TESTS))
+ node --test $files
+
+ # Staging the marketplace regenerates the shared copies the rest of the
+ # suite imports, and both tests fork whole installs, so they run alone.
+ - name: Run the installer tests
+ run: node --test --test-concurrency=1 $INSTALLER_TESTS
- name: Check installer scripts parse
run: |
@@ -114,15 +97,18 @@ jobs:
with:
node-version: '24'
+ - name: Generate the shared runtime copies
+ run: node ../memory-plugin-shared/sync.mjs
+
- name: Install plugin dependencies
run: npm ci --ignore-scripts
- name: Run the OpenClaw plugin Vitest suite
# The suite is otherwise never exercised by CI, so regressions in
# examples/openclaw-plugin only surface in user installs.
- # tests/ut/architecture-boundaries.test.ts is excluded until its 4
- # pre-existing main failures are resolved (see #4720 / #4731 / #4732);
- # every other file passes on main (44 files / 690 tests).
+ # tests/ut/architecture-boundaries.test.ts is excluded until its 2
+ # pre-existing failures are resolved (see #4720 / #4731 / #4732);
+ # every other file passes (42 files / 675 tests).
# The node_modules exclude restores vitest's default filters, which a
# custom --exclude replaces.
run: >
@@ -130,6 +116,23 @@ jobs:
--exclude "tests/ut/architecture-boundaries.test.ts"
--exclude "**/node_modules/**"
+ plugin-versions:
+ runs-on: ubuntu-24.04
+ if: ${{ github.event_name == 'pull_request' }}
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: '24'
+
+ - name: Plugins that changed must move their version string
+ run: |
+ git fetch --quiet origin ${{ github.base_ref }}
+ bash .github/scripts/check-plugin-version-bumps.sh "origin/${{ github.base_ref }}"
+
check-deps:
runs-on: ubuntu-24.04
outputs:
@@ -188,7 +191,7 @@ jobs:
echo "langchain_changed=false" >> $GITHUB_OUTPUT
fi
- OPENCLAW_PATTERN="examples/openclaw-plugin/|\.github/workflows/pr\.yml"
+ OPENCLAW_PATTERN="examples/openclaw-plugin/|examples/memory-plugin-shared/(lib/|sync\.mjs)|\.github/workflows/pr\.yml"
OPENCLAW_CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }} HEAD | grep -E "$OPENCLAW_PATTERN" || true)
if [ -n "$OPENCLAW_CHANGED_FILES" ]; then
diff --git a/.gitignore b/.gitignore
index 599987ebf..110d53d6e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,6 +30,8 @@ share/python-wheels/
*.egg
.ttadk
MANIFEST
+# The shared memory-plugin installer's module list — not a Python sdist manifest.
+!examples/memory-plugin-shared/lib/MANIFEST
openviking.egg-info/
data/
@@ -238,3 +240,12 @@ node_modules/
# Local scratch / working notes
.scratch/
+
+# Shared runtime copies built at pack time by examples/memory-plugin-shared/sync.mjs.
+# The plugins that publish as an npm package or as a tarball generate these on
+# the way out; only the plugins a host installs by pointing at a directory in
+# this repository keep their copies in git.
+examples/opencode-plugin/lib/shared/
+examples/dsh-memory-plugin/shared/
+examples/pi-coding-agent-extension/shared/
+examples/openclaw-plugin/shared/
diff --git a/RELEASE.md b/RELEASE.md
index 693b47586..762e6282f 100644
--- a/RELEASE.md
+++ b/RELEASE.md
@@ -146,9 +146,7 @@ Recommended usage:
- **TypeScript SDK Release** (`typescript-sdk-release.yml`): triggered by pushing a
`[email protected]` tag, or manually. Publishes `@openviking/sdk` to npm.
-- **OpenCode Plugin Release** (`opencode-plugin-release.yml`): runs automatically on
- pushes to `main` that touch `examples/opencode-plugin/**`, or manually. Publishes
- `@openviking/opencode-plugin` to npm and skips versions that already exist.
+- **Plugin npm Release** (`plugin-npm-release.yml`): runs automatically on pushes to `main` that touch `examples/dsh-memory-plugin/**`, `examples/opencode-plugin/**`, or the shared plugin library `examples/memory-plugin-shared/lib/**`, or manually. Publishes `@openviking/dsh-memory-plugin` and `@openviking/opencode-plugin` to npm, one matrix job per package, and skips versions that already exist.
- **Controlplane MCP Release** (`controlplane-mcp-release.yml`): manual only. Publishes
`mcp-server-openviking-controlplane`, including the `ov-cp` CLI.
diff --git a/agent-plugins/README.md b/agent-plugins/README.md
index 5237a6d28..6e9e10a61 100644
--- a/agent-plugins/README.md
+++ b/agent-plugins/README.md
@@ -10,7 +10,6 @@ Agent Plugins 1.0 is a vendor-neutral packaging format for extending AI coding a
plugin.json # Agent Plugins 1.0 manifest
mcp.json # stdio MCP server: "openviking"
servers/mcp-proxy.mjs # stdio -> streamable-HTTP proxy to the OV server's /mcp
-servers/config.mjs, debug-log.mjs # credential/config resolution (adapted from claude-code-memory-plugin)
servers/shared/ # generated from examples/memory-plugin-shared/lib (do not edit)
skills/openviking-memory/SKILL.md # teaches the model the recall + persist loop
skills/ov-memory-troubleshoot/ # read-only extraction troubleshooting
@@ -59,7 +58,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
- [claude-code-memory-plugin](../examples/claude-code-memory-plugin/) (Claude Code)
- [codex-memory-plugin](../examples/codex-memory-plugin/) (Codex)
- [opencode-plugin](../examples/opencode-plugin/) (OpenCode)
-- [cursor-memory-plugin](../examples/cursor-memory-plugin/), [trae-memory-hooks](../examples/trae-memory-hooks/), [zcode-memory-plugin](../examples/zcode-memory-plugin/), ...
+- [agent-hook-plugin](../examples/agent-hook-plugin/) (Cursor, TRAE, TRAE CN, ZCode), ...
Use this Agent Plugins package for harnesses with no hooks, or when you want one package that loads across many clients.
@@ -77,6 +76,6 @@ node --test agent-plugins/plugin.test.mjs
node examples/memory-plugin-shared/sync.mjs
```
-`examples/memory-plugin-shared/sync.test.mjs` fails if they drift. `servers/config.mjs`, `servers/debug-log.mjs`, and `servers/mcp-proxy.mjs` are adapted from `examples/claude-code-memory-plugin` (connection fields only — the hook-tuning knobs are dropped, since this spec has no hooks); when changing proxy behavior there, mirror it here.
+`examples/memory-plugin-shared/sync.test.mjs` fails if they drift, and pins this package to the connection half of the shared runtime: `servers/mcp-proxy.mjs` resolves everything through `buildProxyConnection()` in `shared/credentials.mjs`, so the hook-tuning knobs — which this spec has no hooks to run — never enter the bundle.
Both test files run in CI via `.github/workflows/pr.yml`.
diff --git a/agent-plugins/servers/config.mjs b/agent-plugins/servers/config.mjs
deleted file mode 100644
index 6abe73e47..000000000
--- a/agent-plugins/servers/config.mjs
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Connection config loader for the OpenViking Agent Plugins 1.0 package.
- *
- * VENDORED (adapted) from examples/claude-code-memory-plugin/scripts/config.mjs —
- * keep the resolution semantics in sync with that file. This copy is trimmed to
- * the fields consumed by servers/mcp-proxy.mjs: Agent Plugins 1.0 has no hooks,
- * so all of the hook-tuning knobs (recall/capture/commit/profile) are dropped,
- * as is the Claude-Code-specific `claude_code` section of ov.conf.
- *
- * Resolution priority (highest → lowest):
- * 1. Environment variables (OPENVIKING_*)
- * 2. ovcli.conf (CLI client config: url, api_key, account, user)
- * 3. ov.conf `server` section (local server config; url/host/port/root_api_key)
- * 4. Built-in defaults (http://127.0.0.1:1933)
- *
- * Env vars covered:
- * Connection / identity:
- * OPENVIKING_URL / OPENVIKING_BASE_URL, OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN,
- * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID
- * Config file overrides:
- * OPENVIKING_CONFIG_FILE (ov.conf), OPENVIKING_CLI_CONFIG_FILE (ovcli.conf)
- * Misc:
- * OPENVIKING_TIMEOUT_MS, OPENVIKING_DEBUG, OPENVIKING_DEBUG_LOG
- */
-
-import { readFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { resolve as resolvePath, join } from "node:path";
-
-import { buildUserAgent, readManifestVersion } from "./shared/credentials.mjs";
-
-const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
-const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
-const USER_AGENT = buildUserAgent(
- "agent-plugins",
- readManifestVersion(new URL("../plugin.json", import.meta.url)),
-);
-
-function num(val, fallback) {
- if (typeof val === "number" && Number.isFinite(val)) return val;
- if (typeof val === "string" && val.trim()) {
- const n = Number(val);
- if (Number.isFinite(n)) return n;
- }
- return fallback;
-}
-
-function str(val, fallback) {
- if (typeof val === "string" && val.trim()) return val.trim();
- return fallback;
-}
-
-function envBool(name) {
- const v = process.env[name];
- if (v == null || v === "") return undefined;
- const lower = v.trim().toLowerCase();
- if (lower === "0" || lower === "false" || lower === "no") return false;
- if (lower === "1" || lower === "true" || lower === "yes") return true;
- return undefined;
-}
-
-/**
- * Try to load and parse a JSON config file. Returns { configPath, file } or null.
- */
-function tryLoadJsonFile(envVar, defaultPath) {
- const configPath = resolvePath(
- (process.env[envVar] || defaultPath).replace(/^~/, homedir()),
- );
-
- let raw;
- try {
- raw = readFileSync(configPath, "utf-8");
- } catch {
- return null;
- }
-
- try {
- return { configPath, file: JSON.parse(raw) };
- } catch {
- return null;
- }
-}
-
-/**
- * Load the connection configuration for the stdio MCP proxy.
- *
- * Resolution: env vars → ovcli.conf → ov.conf → defaults.
- */
-export function loadConfig() {
- const ovConf = tryLoadJsonFile("OPENVIKING_CONFIG_FILE", DEFAULT_OV_CONF_PATH);
- const cliConf = tryLoadJsonFile("OPENVIKING_CLI_CONFIG_FILE", DEFAULT_OVCLI_CONF_PATH);
-
- const ovFile = ovConf?.file || {};
- const cliFile = cliConf?.file || {};
- const configPath = cliConf?.configPath || ovConf?.configPath || null;
-
- const server = ovFile.server || {};
-
- // baseUrl: env → ovcli.url → ov.server.url → http://{host}:{port}
- const envUrl = str(process.env.OPENVIKING_URL, null) || str(process.env.OPENVIKING_BASE_URL, null);
- let baseUrl;
- if (envUrl) {
- baseUrl = envUrl.replace(/\/+$/, "");
- } else if (cliFile.url) {
- baseUrl = str(cliFile.url, "").replace(/\/+$/, "");
- } else if (server.url) {
- baseUrl = str(server.url, "").replace(/\/+$/, "");
- } else {
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Math.floor(num(server.port, 1933));
- baseUrl = `http://${host}:${port}`;
- }
-
- // apiKey: env → ovcli.api_key → ov.server.root_api_key
- // Accepts OPENVIKING_BEARER_TOKEN or OPENVIKING_API_KEY (sent as Bearer either way).
- const apiKey = str(process.env.OPENVIKING_BEARER_TOKEN, null)
- || str(process.env.OPENVIKING_API_KEY, null)
- || str(cliFile.api_key, null)
- || str(server.root_api_key, "");
-
- const accountId = str(process.env.OPENVIKING_ACCOUNT, null)
- || str(cliFile.account, "");
-
- const userId = str(process.env.OPENVIKING_USER, null)
- || str(cliFile.user, "");
-
- const peerId = str(process.env.OPENVIKING_PEER_ID, "");
-
- const timeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_TIMEOUT_MS,
- 15000,
- )));
-
- const debug = envBool("OPENVIKING_DEBUG") ?? false;
- const defaultLogPath = join(homedir(), ".openviking", "logs", "agent-plugins.log");
- const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);
-
- return {
- configPath,
- baseUrl,
- apiKey,
- accountId,
- userId,
- peerId,
- timeoutMs,
- userAgent: USER_AGENT,
- debug,
- debugLogPath,
- };
-}
diff --git a/agent-plugins/servers/debug-log.mjs b/agent-plugins/servers/debug-log.mjs
deleted file mode 100644
index f6210e4d0..000000000
--- a/agent-plugins/servers/debug-log.mjs
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Structured debug logger for the OpenViking Agent Plugins 1.0 package.
- *
- * VENDORED (adapted) from examples/claude-code-memory-plugin/scripts/debug-log.mjs —
- * keep in sync with that file.
- *
- * Activation: OPENVIKING_DEBUG=1 env var.
- * Log path: OPENVIKING_DEBUG_LOG env var OR ~/.openviking/logs/agent-plugins.log.
- * Format: JSON Lines — { ts, hook, stage, data } | { ts, hook, stage, error }.
- *
- * When inactive, log() and logError() are zero-cost no-ops.
- */
-
-import { loadConfig } from "./config.mjs";
-import { createLogger as createSharedLogger } from "./shared/debug-log.mjs";
-
-let _cfg;
-function cfg() {
- if (!_cfg) _cfg = loadConfig();
- return _cfg;
-}
-
-/**
- * @param {string} hookName — e.g. "mcp-proxy"
- * @param {{ debug?: boolean, debugLogPath?: string }} [overrideCfg]
- * Pass a config object directly (avoids re-loading config in tests).
- * @returns {{ log: (stage: string, data: any) => void, logError: (stage: string, err: any) => void }}
- */
-export function createLogger(hookName, overrideCfg) {
- return createSharedLogger(hookName, overrideCfg || cfg());
-}
diff --git a/agent-plugins/servers/mcp-proxy.mjs b/agent-plugins/servers/mcp-proxy.mjs
index 1ccb134c6..ac80a0e52 100644
--- a/agent-plugins/servers/mcp-proxy.mjs
+++ b/agent-plugins/servers/mcp-proxy.mjs
@@ -3,41 +3,43 @@
/**
* stdio -> streamable-HTTP MCP proxy for the OpenViking Agent Plugins 1.0 package.
*
- * VENDORED (adapted) from examples/claude-code-memory-plugin/servers/mcp-proxy.mjs —
- * keep in sync with that file. Only the import paths and doc comments differ;
- * the proxy behavior is identical. The shared modules under ./shared/ are
- * generated by `node examples/memory-plugin-shared/sync.mjs` (this directory is
- * one of its TARGETS) — edit them in examples/memory-plugin-shared/lib, never here.
- *
* A conforming Agent Plugins client starts this process as a local stdio MCP
* server (see ../mcp.json). The proxy reads the same OpenViking credential
* sources as the ov CLI (OPENVIKING_* env → ~/.openviking/ovcli.conf →
* ~/.openviking/ov.conf), forwards JSON-RPC requests to the server's /mcp
* endpoint, and keeps stdout protocol-clean.
+ *
+ * The modules under ./shared/ are generated by `node
+ * examples/memory-plugin-shared/sync.mjs` (this directory is one of its
+ * TARGETS) — edit them in examples/memory-plugin-shared/lib, never here.
*/
import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
-import { loadConfig } from "./config.mjs";
-import { createLogger } from "./debug-log.mjs";
+import { buildProxyConnection } from "./shared/credentials.mjs";
+import { createLogger } from "./shared/debug-log.mjs";
import { buildMcpProxyConfig, resolveMcpActorPeerId } from "./shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "./shared/mcp-proxy-core.mjs";
function readProxyConfig() {
- const cfg = loadConfig();
+ const cfg = buildProxyConnection("agent-plugins", {
+ manifestUrl: new URL("../plugin.json", import.meta.url),
+ });
return buildMcpProxyConfig({
baseUrl: cfg.baseUrl,
+ mcpUrl: cfg.mcpUrl,
apiKey: cfg.apiKey,
- account: cfg.accountId,
- user: cfg.userId,
+ account: cfg.account,
+ user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
peerId: resolveMcpActorPeerId(cfg),
userAgent: cfg.userAgent,
timeoutMs: cfg.timeoutMs,
debug: cfg.debug,
debugLogPath: cfg.debugLogPath,
- credentialSource: cfg.configPath?.endsWith("ovcli.conf") ? "ovcli" : "auto",
- credentialPath: cfg.configPath,
- watchedPaths: [cfg.configPath],
+ credentialSource: cfg.credentialSource,
+ credentialPath: cfg.credentialPath,
+ watchedPaths: cfg.watchedPaths,
});
}
diff --git a/agent-plugins/servers/shared/credentials.mjs b/agent-plugins/servers/shared/credentials.mjs
index ba26a84dc..0ab2d984d 100644
--- a/agent-plugins/servers/shared/credentials.mjs
+++ b/agent-plugins/servers/shared/credentials.mjs
@@ -7,6 +7,8 @@ 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";
+const DEFAULT_TIMEOUT_MS = 15000;
+const MIN_TIMEOUT_MS = 1000;
function str(val, fallback = "") {
if (typeof val === "string" && val.trim()) return val.trim();
@@ -108,6 +110,45 @@ export function loadCredentialFiles(env = process.env) {
};
}
+/**
+ * The calling harness's own section of ov.conf.
+ *
+ * ov.conf spells its sections snake_case while a host may call itself
+ * `claude-code` or `trae-cn`, so both spellings land on the same block. The
+ * normalization stays inline rather than importing `config-schema.mjs`, which
+ * the portable agent-plugins bundle would then have to ship as well.
+ */
+function harnessSection(ovFile, harness) {
+ const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+ const section = key ? ovFile[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+const AUTH_MODES = ["trusted", "api_key"];
+
+function normalizeAuthMode(value) {
+ const mode = str(value, "").toLowerCase();
+ return AUTH_MODES.includes(mode) ? mode : "";
+}
+
+/**
+ * Which auth mode the server is in, and with it whether the identity headers
+ * may go on the wire.
+ *
+ * An `api_key` server reads the account and the user out of the key and ignores
+ * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
+ * every proxy on the path who the operator is and buys nothing. A named mode
+ * wins; ov.conf's server block answers next; failing both, a credential layer
+ * that supplied an identity at all means the deployment expects one.
+ */
+export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
+ const server = ovFile.server || {};
+ const authMode = normalizeAuthMode(settings.authMode)
+ || normalizeAuthMode(server.auth_mode)
+ || ((account || user) ? "trusted" : "api_key");
+ return { authMode, sendIdentityHeaders: authMode === "trusted" };
+}
+
function sourceMode(env) {
const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
.toLowerCase();
@@ -144,40 +185,58 @@ function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
return `http://${host}:${port}`;
}
-export function resolveOpenVikingCredentials(env = process.env) {
+/**
+ * `harness` names whose ov.conf section supplies the legacy fallback. It sits
+ * where it always did — after ovcli.conf, before `server.root_api_key` — but a
+ * harness now reads its own section instead of every one of them reading
+ * codex's. The default keeps codex, the only caller that never passes one.
+ *
+ * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
+ * section named, which this module cannot read for itself: resolving that
+ * section needs the knob schema, and the portable bundles would then have to
+ * ship it. All three rank where the file they come from ranks — under
+ * ovcli.conf's own fields, over ov.conf.
+ */
+export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
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 cx = harnessSection(files.ovFile, harness);
const server = files.ovFile.server || {};
const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+ const pluginApiKey = str(plugin?.apiKey, "");
const apiKey = useCli
- ? str(files.cliFile.api_key, "")
+ ? (str(files.cliFile.api_key, "") || pluginApiKey)
: (
str(env.OPENVIKING_BEARER_TOKEN, "") ||
str(env.OPENVIKING_API_KEY, "") ||
str(files.cliFile.api_key, "") ||
+ pluginApiKey ||
str(cx.apiKey, "") ||
str(server.root_api_key, "")
);
+ const pluginAccount = str(plugin?.accountId, "");
const account = useCli
- ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
: (
str(env.OPENVIKING_ACCOUNT, "") ||
str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ pluginAccount ||
str(cx.accountId, "")
);
+ const pluginUser = str(plugin?.userId, "");
const user = useCli
- ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
: (
str(env.OPENVIKING_USER, "") ||
str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ pluginUser ||
str(cx.userId, "")
);
@@ -192,19 +251,31 @@ export function resolveOpenVikingCredentials(env = process.env) {
const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
+ // Which layer actually supplied the api_key, following the same chain, and
+ // the file behind it — empty when the key came from the environment or was
+ // never found. `apiKeySource` is what a doctor and a 401 hint report; the
+ // credential *source* beside it is the mode the chain ran in, not a file.
+ let apiKeySource = "none";
let credentialPath = "";
if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
+ if (useCli) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
+ apiKeySource = "env";
+ } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else {
+ apiKeySource = "ov";
+ credentialPath = files.ovPath;
+ }
}
return {
...files,
credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ apiKeySource,
credentialPath,
baseUrl,
mcpUrl,
@@ -216,6 +287,71 @@ export function resolveOpenVikingCredentials(env = process.env) {
};
}
+function envFlag(env, name) {
+ const raw = str(env[name], "").toLowerCase();
+ return raw === "1" || raw === "true" || raw === "yes";
+}
+
+function clampTimeout(value) {
+ const raw = str(value, "");
+ const parsed = raw ? Number(raw) : NaN;
+ return Math.max(MIN_TIMEOUT_MS, Math.floor(Number.isFinite(parsed) ? parsed : DEFAULT_TIMEOUT_MS));
+}
+
+/**
+ * Everything a stdio MCP proxy needs, for a package that ships no hooks.
+ *
+ * `buildPluginConfig` answers the same question one layer up, but reaching it
+ * means vendoring the knob schema and the workspace layers — a closure the
+ * portable agent-plugins bundle would carry in git to send one HTTP header.
+ * This is the connection half alone: the credential chain, the auth mode that
+ * decides whether the identity headers may go on the wire, the User-Agent, the
+ * request timeout, and the debug log.
+ *
+ * The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
+ * chain to itself. A portable package has no installer to migrate anyone, so
+ * an install that names only a `url` there keeps the key it has always used.
+ */
+export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
+ const name = str(harness);
+ const credentials = resolveOpenVikingCredentials(env, name);
+
+ let { apiKey, apiKeySource, credentialPath } = credentials;
+ if (!apiKey) {
+ apiKey = str(credentials.ovFile?.server?.root_api_key);
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+
+ return {
+ harness: name,
+ userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
+ baseUrl: credentials.baseUrl,
+ mcpUrl: credentials.mcpUrl,
+ apiKey,
+ account: credentials.account,
+ user: credentials.user,
+ peerId: credentials.peerId,
+ ...resolveAuthMode({
+ settings: { authMode: env.OPENVIKING_AUTH_MODE },
+ ovFile: credentials.ovFile,
+ account: credentials.account,
+ user: credentials.user,
+ }),
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
+ debug: envFlag(env, "OPENVIKING_DEBUG"),
+ debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
+ || join(homedir(), ".openviking", "logs", `${name}.log`),
+ };
+}
+
function main() {
const cmd = process.argv[2] || "";
if (cmd === "mcp-url") {
@@ -230,7 +366,7 @@ function main() {
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.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
process.exitCode = 2;
}
diff --git a/agent-plugins/servers/shared/mcp-proxy-config.mjs b/agent-plugins/servers/shared/mcp-proxy-config.mjs
index 24d33d9fb..dd11897ee 100644
--- a/agent-plugins/servers/shared/mcp-proxy-config.mjs
+++ b/agent-plugins/servers/shared/mcp-proxy-config.mjs
@@ -86,7 +86,9 @@ function uniq(values) {
* `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
* user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
* harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
+ * deduplicated. `sendIdentityHeaders` carries the harness's resolved auth mode
+ * so an `api_key` server, which reads the identity out of the key and ignores
+ * the headers, never sees the operator's account and user on the wire.
*/
export function buildMcpProxyConfig({
baseUrl = "",
@@ -94,6 +96,7 @@ export function buildMcpProxyConfig({
apiKey = "",
account = "",
user = "",
+ sendIdentityHeaders = false,
peerId = "",
userAgent = "",
timeoutMs,
@@ -109,6 +112,7 @@ export function buildMcpProxyConfig({
apiKey: apiKey || "",
account: account || "",
user: user || "",
+ sendIdentityHeaders: sendIdentityHeaders === true,
peerId: peerId || "",
userAgent: userAgent || "",
timeoutMs: Math.max(
diff --git a/agent-plugins/servers/shared/mcp-proxy-core.mjs b/agent-plugins/servers/shared/mcp-proxy-core.mjs
index 9a8f5ba26..de11c2879 100644
--- a/agent-plugins/servers/shared/mcp-proxy-core.mjs
+++ b/agent-plugins/servers/shared/mcp-proxy-core.mjs
@@ -9,6 +9,8 @@
import { statSync } from "node:fs";
import { createInterface } from "node:readline";
+import { buildOvHeaders } from "./ov-http.mjs";
+
const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
const DELETE_TIMEOUT_MS = 2000;
const MAX_CONCURRENT_REQUESTS = 16;
@@ -240,21 +242,17 @@ export function createOpenVikingMcpProxy({
}
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;
+ return buildOvHeaders(proxyConfig, {
+ actorPeerId: proxyConfig.peerId,
+ extraHeaders: {
+ "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,
+ ...(includeSession && sessionId ? { "Mcp-Session-Id": sessionId } : {}),
+ },
+ });
}
function writeMessage(obj) {
diff --git a/agent-plugins/servers/shared/ov-http.mjs b/agent-plugins/servers/shared/ov-http.mjs
new file mode 100644
index 000000000..e02f5316e
--- /dev/null
+++ b/agent-plugins/servers/shared/ov-http.mjs
@@ -0,0 +1,112 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * The one path from a hook to the OpenViking server.
+ *
+ * Every harness used to own its own AbortController, header block and envelope
+ * parser, and they drifted: one sent the api key twice, one named the operator
+ * to every proxy on the path whether or not the server was trusted with it, one
+ * read a different field for the same account. A server-side change now lands
+ * in one place instead of eight.
+ *
+ * `X-API-Key` is deliberately absent. The server takes `Authorization: Bearer`,
+ * and the identity headers go out only when the resolved config says this
+ * server is trusted with the operator's name.
+ */
+
+// A request that aborts the instant it starts reads as a dead server. A config
+// that asks for less than a second gets a second.
+const MIN_TIMEOUT_MS = 1000;
+
+/**
+ * The headers every harness puts on every OpenViking request.
+ *
+ * `identityHeaders` overrides `cfg.sendIdentityHeaders` for the callers that
+ * decide per request rather than per config — the doctor probes both ways.
+ */
+export function buildOvHeaders(cfg = {}, { actorPeerId = "", identityHeaders, extraHeaders } = {}) {
+ const identity = identityHeaders === undefined ? Boolean(cfg.sendIdentityHeaders) : Boolean(identityHeaders);
+ const headers = { "Content-Type": "application/json" };
+ if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
+ if (identity && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (identity && cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
+ if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ return { ...headers, ...extraHeaders };
+}
+
+function responseTraceId(body) {
+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
+}
+
+/**
+ * Build the `fetchJSON(path, init, { timeoutMs, actorPeerId })` a harness talks
+ * through. It resolves to `{ ok, status, result, error, traceId }` and never
+ * throws: a hook that crashes on a closed port would take its host's turn with
+ * it, so a network error is `{ ok: false, status: 0 }` and the retry rules in
+ * `retryable.mjs` decide what happens next.
+ *
+ * `resolveActorPeerId` is a callback because Codex only knows its peer after
+ * loading session state under the lock, well after the client is built.
+ * `requireJsonBody` is for the capture hooks, which would rather retry a body
+ * they cannot parse than record the turn as sent.
+ */
+export function createOvHttp(cfg = {}, {
+ defaultTimeoutMs = 0,
+ resolveActorPeerId = () => "",
+ identityHeaders,
+ extraHeaders,
+ requireJsonBody = false,
+} = {}) {
+ // dsh and pi name this field `endpoint`; every other harness names it `baseUrl`.
+ const baseUrl = cfg.baseUrl || cfg.endpoint || "";
+ return async function fetchJSON(path, init = {}, options = {}) {
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0);
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ try {
+ const headers = {
+ ...buildOvHeaders(cfg, {
+ actorPeerId: options.actorPeerId ?? resolveActorPeerId(),
+ identityHeaders,
+ extraHeaders,
+ }),
+ ...(init.headers || {}),
+ };
+ const response = await fetch(`${baseUrl}${path}`, { ...init, headers, signal: controller.signal });
+ const body = await response.json().catch(() => null);
+ if (requireJsonBody && !body) {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: { message: "empty or invalid JSON response" },
+ };
+ }
+ const traceId = responseTraceId(body);
+ if (!response.ok || body?.status === "error") {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: body?.error || { message: `HTTP ${response.status}` },
+ traceId,
+ };
+ }
+ return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId };
+ } catch (error) {
+ const message = error?.message || String(error);
+ // This module owns the controller, so it says a timeout was a timeout
+ // rather than leaving callers to guess it from whatever fetch threw.
+ const failure = timedOut
+ ? { name: "AbortError", aborted: true, message }
+ : { message };
+ return { ok: false, status: 0, result: null, error: failure };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+}
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index c9c9905b0..e25ab1ccf 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -125,7 +125,10 @@ const gettingStartedSidebar = {
const agentIntegrationSidebar = {
en: {
overview: 'Integration Overview',
- topItems: [['16-capability-reference.md', 'Capability Reference']],
+ topItems: [
+ ['16-capability-reference.md', 'Capability Reference'],
+ ['18-plugin-development.md', 'Plugin Development']
+ ],
groups: [
{
text: 'Developer Tools',
@@ -161,7 +164,10 @@ const agentIntegrationSidebar = {
},
zh: {
overview: '集成概览',
- topItems: [['16-capability-reference.md', '集成能力参考']],
+ topItems: [
+ ['16-capability-reference.md', '集成能力参考'],
+ ['18-plugin-development.md', '插件开发与维护']
+ ],
groups: [
{
text: '开发工具',
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index 732f64f07..60e5b264a 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -25,6 +25,10 @@ OpenViking can act as the long-term memory and context backend for many agent ru
For the concrete differences between integrations — tool surface, automatic recall, session and commit behaviour, compaction takeover, degradation and fault tolerance — see the [Capability Reference](./16-capability-reference.md), a cross-integration comparison matrix.
+## Developing and maintaining plugins
+
+To add or maintain an integration, follow the [Hook + MCP Agent Plugin Development and Maintenance Standard](./18-plugin-development.md). When using VibeCoding, require your coding agent to read and follow it before making changes, using Claude Code, Codex, and other existing plugins as implementation references.
+
## Prerequisite for all integrations
Every integration on this page connects to a running OpenViking server. If you don't have one yet, follow the [Quickstart Guide](../getting-started/02-quickstart.md). The default endpoint is `http://localhost:1933`; remote use requires an API key (see [Authentication](../guides/04-authentication.md)).
@@ -33,7 +37,7 @@ Every integration on this page connects to a running OpenViking server. If you d
Query expansion and recall-result compression are two independent, optional model calls. Disable both in the Agent plugin when response latency matters most; semantic retrieval, budgeting, tier degradation, and cross-turn dedup continue to work.
-The same environment variables apply to both the Claude Code and Codex memory plugins. Query expansion is also switchable in OpenCode and pi; compression is Claude Code and Codex only.
+The same environment variables apply to both the Claude Code and Codex memory plugins. Query expansion is switchable in every memory plugin that resolves its settings through the shared loader; compression is Claude Code and Codex only.
```bash
export OPENVIKING_RECALL_QUERY_EXPANSION=off
@@ -62,6 +66,6 @@ The same settings can live in `~/.openviking/ovcli.conf`:
Environment variables take precedence over `ovcli.conf`. Restart the Agent after changing these settings so its hook processes reload the configuration. These are plugin-client settings; the server's `ov.conf` does not need to change.
-The `plugin` section is read by the Claude Code and Codex plugins, so a `plugin` entry named after another harness is currently inert. OpenCode and pi read `OPENVIKING_RECALL_QUERY_EXPANSION` from the environment (or `recallQueryExpansion` in their own config file) but not `OPENVIKING_RECALL_COMPRESS`, since neither requests a server digest.
+The `plugin` section is read by every memory plugin — claude-code, codex, cursor, trae, trae-cn, zcode, opencode, dsh and pi — and a `plugin.<harness>` object overrides the shared keys for one of them, under either spelling (`claude_code` or `claude-code`, `trae_cn` or `trae-cn`). Compression is the exception: the other harnesses honour `recallQueryExpansion` but ignore `recallCompress` and its companions, since none of them requests a server digest.
A context request waits longer than an ordinary request, because aborting it client-side discards the whole response rather than just the stage that ran long. The server pipeline is serial and each optional stage has its own fuse: query expansion (`retrieval.recall_intent_timeout_s`, 5s) runs first, then retrieval, body reads and budgeting, and only then the digest rewrite (`retrieval.recall_rewrite_timeout_s`, 30s). The deadline therefore follows what the request actually asks for — 15s once it carries a session and can spend the expansion fuse, 45s when it also asks for a digest, and the plugin's ordinary timeout when it asks for neither. Set `OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS` (or `plugin.recallContextTimeoutMs`) to pin it — keep it above the fuses the request will spend and below the Agent's own hook timeout.
diff --git a/docs/en/agent-integrations/08-community-plugins.md b/docs/en/agent-integrations/08-community-plugins.md
index b5b18d11e..ce8e4165c 100644
--- a/docs/en/agent-integrations/08-community-plugins.md
+++ b/docs/en/agent-integrations/08-community-plugins.md
@@ -4,7 +4,7 @@ Community-maintained integrations for various agent runtimes. Each differs in ta
## ZCode memory integration
-Source: [examples/zcode-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
+Source: [examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
The ZCode community integration adds cross-project, cross-session memory through config-driven lifecycle hooks and an OpenViking MCP server:
@@ -45,7 +45,7 @@ After restarting ZCode, verify that:
| MCP tools not appearing | The MCP proxy failed to start | Check the absolute `mcp.servers.openviking` command in `~/.zcode/cli/config.json` |
| Duplicate captures | An older installation left duplicate hook entries | Run `install.sh --harness zcode --uninstall`, then reinstall |
-Implementation details and currently verified ZCode assumptions are documented in the plugin's [README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin) and [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/zcode-memory-plugin/DESIGN.md).
+Implementation details and currently verified ZCode assumptions are documented in the plugin's [README](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin) and [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md).
## AstrBot plugin
diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.md
index 6ae314978..a1316e3b6 100644
--- a/docs/en/agent-integrations/10-opencode.md
+++ b/docs/en/agent-integrations/10-opencode.md
@@ -97,29 +97,32 @@ Credentials are shared with the Claude Code and Codex memory plugins. Run the se
node examples/opencode-plugin/scripts/setup.mjs
```
-`~/.config/opencode/openviking-config.json` is now for behavior knobs only:
+Behavior knobs live in the `plugin` section of `~/.openviking/ovcli.conf`, beside the connection fields the wizard writes. Shared keys apply to every memory plugin; keys under `plugin.opencode` apply to this one and override them:
```json
{
- "enabled": true,
- "timeoutMs": 30000,
- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },
- "autoRecall": {
- "enabled": true,
- "limit": 6,
+ "plugin": {
+ "recallLimit": 6,
"scoreThreshold": 0.35,
- "maxContentChars": 500,
- "preferAbstract": true,
- "tokenBudget": 2000,
- "minQueryLength": 3
- },
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000
+ "recallMaxContentChars": 500,
+ "recallPreferAbstract": true,
+ "recallTokenBudget": 2000,
+ "minQueryLength": 3,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000,
+ "opencode": {
+ "timeoutMs": 30000,
+ "repoContext": true,
+ "repoContextCacheTtlMs": 60000
+ }
+ }
}
```
+Settings resolve highest priority first: `OPENVIKING_*` environment variables, the workspace's `.openviking/config.json` and `config.local.json`, `plugin.opencode`, `plugin`, then the built-in defaults. `autoRecall: false` turns automatic recall off, and `autoCapture: false` stops the plugin sending turns back.
+
Environment variables override `ovcli.conf`:
```bash
@@ -129,7 +132,7 @@ export OPENVIKING_USER="opencode" # optional, trusted-mode deployments only
export OPENVIKING_PEER_ID="opencode" # optional, peer-scoped memory routing
```
-API keys are sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode headers; `peerId` is sent as `X-OpenViking-Actor-Peer` and as `peer_id` on captured session messages. Existing `openviking-config.json` credential fields are still read as a migration fallback, but new installs should use `ovcli.conf` or env vars.
+API keys are sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode headers; `peerId` is sent as `X-OpenViking-Actor-Peer` and as `peer_id` on captured session messages.
## Verify
@@ -152,9 +155,9 @@ Ask OpenCode to search or browse OpenViking memory. Runtime state and errors are
| Issue | What to check |
|-------|---------------|
| Plugin does not load | Confirm `~/.config/opencode/opencode.json` references `@openviking/opencode-plugin`, or that `~/.config/opencode/plugins/openviking.js` exists for source installs |
-| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_PLUGIN_CONFIG` to the intended config path |
+| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars; `OPENVIKING_CLI_CONFIG_FILE` points the plugin at a different ovcli.conf |
| 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |
-| Recall is empty | Confirm the OpenViking server has indexed memories/resources and that `autoRecall.enabled` is `true` |
+| Recall is empty | Confirm the OpenViking server has indexed memories/resources and that `autoRecall` is not set to `false` |
| Local `openviking_add_resource` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |
For all available tools, configuration fields, and runtime file details, see the [plugin README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin).
diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.md
index 2491333c0..e1fda917e 100644
--- a/docs/en/agent-integrations/11-pi.md
+++ b/docs/en/agent-integrations/11-pi.md
@@ -35,7 +35,7 @@ In regions where GitHub is hard to reach, run the same installer from the Volcen
bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
```
-The installer copies the extension into `~/.pi/agent/extensions/openviking` (preserving an existing `config.json`), registers it with `pi install`, and configures `~/.openviking/ovcli.conf`.
+The installer copies the extension into `~/.pi/agent/extensions/openviking`, registers it with `pi install`, and configures `~/.openviking/ovcli.conf`.
Manual copy from a repo checkout also works:
@@ -55,34 +55,37 @@ Credentials resolve from `OPENVIKING_*` environment variables, then `~/.openviki
node ~/.pi/agent/extensions/openviking/scripts/setup.mjs
```
-`~/.pi/agent/extensions/openviking/config.json` holds behavior and peer-scoping knobs, and reinstalls preserve your edits. Connection and authentication credentials still come from the shared sources above:
+Behavior and peer-scoping knobs live in the `plugin` section of `~/.openviking/ovcli.conf`, shared with the other memory plugins. Keys under `plugin.pi` apply to this extension only and override the shared ones; connection and authentication credentials still come from the sources above:
```json
{
- "peerId": "",
- "workspacePeer": true,
- "peerSource": "git",
- "recallPeerScope": "all",
- "scoreThreshold": 0.35,
- "recallTokenBudget": 2000,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000,
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "takeover": {
- "enabled": true,
- "tokenThreshold": 30000,
- "keepRecentTurns": 3,
- "overviewBudget": 3000,
- "overviewPollMs": 2000,
- "overviewPollMax": 15
- },
- "captureAssistantTurns": true,
- "bypassPatterns": []
+ "plugin": {
+ "recallPeerScope": "all",
+ "scoreThreshold": 0.35,
+ "recallTokenBudget": 2000,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "captureAssistantTurns": true,
+ "pi": {
+ "workspacePeer": true,
+ "peerSource": "git",
+ "takeoverEnabled": true,
+ "takeoverTokenThreshold": 30000,
+ "takeoverKeepRecentTurns": 3,
+ "takeoverOverviewBudget": 3000,
+ "takeoverOverviewPollMs": 2000,
+ "takeoverOverviewPollMax": 15,
+ "bypassSessionPatterns": []
+ }
+ }
}
```
-An explicit peer from `OPENVIKING_PEER_ID`, `ovcli.conf`, or `ov.conf` takes precedence over `config.json`'s `peerId`. The local `peerId` takes precedence over the workspace-derived peer, which is used only when `workspacePeer` is enabled and neither explicit source provides a peer.
+Settings resolve highest priority first: `OPENVIKING_*` environment variables, the workspace's `.openviking/config.json` and `config.local.json`, `plugin.pi`, `plugin`, then the built-in defaults. `autoCapture: false` — the extension's older spelling is `syncTurns` — stops it sending turns back, and `autoRecall: false` stops it retrieving.
+
+`OPENVIKING_PEER_ID` outranks every file. Below it the more specific layer wins, so a workspace `peer.id` or a `peerId` set in the `plugin` section takes precedence over `ovcli.conf`'s `actor_peer_id` and `ov.conf`'s `pi.peerId`. Any peer named by one of those layers takes precedence over the workspace-derived peer, which is used only when `workspacePeer` is enabled and no layer names one.
`peerSource` decides how that workspace peer is derived. The default `"git"` uses the repository's normalized `origin` URL (`[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`), falling back to the repository root path, so every clone, worktree, and subdirectory of one repository shares a single peer; outside a repository no peer is sent at all, and what is remembered there goes to your user-level space at `viking://user/<you>/memories`. `"cwd"` restores the earlier behavior — the working directory with every non-alphanumeric character replaced by `-` — `"none"` (like `OPENVIKING_WORKSPACE_PEER=0`) sends no peer at all, and a template such as `"team-{dir}"`, or a list of templates tried in order, builds your own. To give a directory outside a repository its own memory, set `OPENVIKING_PEER_ID` for it ([Give a Directory Its Own Peer](../configuration/02-client.md#give-a-directory-its-own-peer)).
diff --git a/docs/en/agent-integrations/12-cursor.md b/docs/en/agent-integrations/12-cursor.md
index e2270fc88..e0bc90b6d 100644
--- a/docs/en/agent-integrations/12-cursor.md
+++ b/docs/en/agent-integrations/12-cursor.md
@@ -31,7 +31,7 @@ Quit Cursor completely and restart it after installation.
## Verify
1. Restart Cursor and create a new Agent session.
-2. Open **Cursor Settings → Hooks** and confirm that the OpenViking lifecycle Hooks execute `cursor-hook.mjs` and its URI protection Hooks execute `uri-guard.mjs`.
+2. Open **Cursor Settings → Hooks** and confirm that the OpenViking lifecycle Hooks execute `scripts/hook.mjs` and its URI protection Hooks execute `scripts/uri-guard.mjs`.
3. Check that the `beforeSubmitPrompt` output contains `additional_context`. This confirms that recall reaches the Agent without requiring an MCP call first.
4. Open **Cursor Settings → Tools & MCPs** and confirm that `openviking` is connected.
5. Tell Cursor a temporary preference, wait for the response to finish, then create a new session and ask for that preference to verify capture and cross-session recall.
diff --git a/docs/en/agent-integrations/15-agent-plugins.md b/docs/en/agent-integrations/15-agent-plugins.md
index a56f20ae1..279fce91a 100644
--- a/docs/en/agent-integrations/15-agent-plugins.md
+++ b/docs/en/agent-integrations/15-agent-plugins.md
@@ -12,7 +12,6 @@ agent-plugins/
├── mcp.json # one stdio MCP server: "openviking"
├── servers/
│ ├── mcp-proxy.mjs # stdio -> streamable-HTTP proxy to the server's /mcp
-│ ├── config.mjs, debug-log.mjs # credential / config resolution
│ └── shared/ # generated from examples/memory-plugin-shared/lib
├── skills/openviking-memory/SKILL.md # teaches the model the recall + persist loop
└── plugin.test.mjs # node --test conformance checks
@@ -36,10 +35,15 @@ OpenViking already speaks streamable HTTP at `/mcp`, but a `streamable-http` ent
Highest to lowest priority — the same chain as the `ov` CLI and the other OpenViking plugins:
-1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
-2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account`, `user`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
-3. `~/.openviking/ov.conf`, `server` section (`url`, or `host` / `port`, and `root_api_key`) — override the path with `OPENVIKING_CONFIG_FILE`
-4. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
+1. Environment variables: `OPENVIKING_URL` (or `OPENVIKING_BASE_URL`), `OPENVIKING_MCP_URL`, `OPENVIKING_API_KEY` (or `OPENVIKING_BEARER_TOKEN`), `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_PEER_ID`
+2. `~/.openviking/ovcli.conf` (`url`, `api_key`, `account` / `account_id`, `user` / `user_id`, `actor_peer_id` / `peer_id`) — override the path with `OPENVIKING_CLI_CONFIG_FILE`
+3. `~/.openviking/ov.conf`, `agent_plugins` section (`apiKey`, `accountId`, `userId`, `peerId`) — override the path with `OPENVIKING_CONFIG_FILE`
+4. `~/.openviking/ov.conf`, `server` section (`url`, or `host` / `port`, and `root_api_key`)
+5. Defaults: `http://127.0.0.1:1933`, no auth (local mode)
+
+`OPENVIKING_MCP_URL` replaces the derived `<url>/mcp` endpoint, not the base URL.
+
+`OPENVIKING_CREDENTIAL_SOURCE` (or `OPENVIKING_CREDENTIALS_SOURCE`) pins the chain to one end: `env` for the environment, `cli` (also `ovcli` / `file` / `config`) for ovcli.conf. The default `auto` pins it to ovcli.conf when that file carries credentials and none of the variables above is set, and runs the whole chain otherwise. While the chain is pinned to ovcli.conf, the environment, `OPENVIKING_MCP_URL` and the `agent_plugins` section are all skipped; `server.root_api_key` still answers when ovcli.conf carries no key of its own, so an install that names only a `url` there keeps the key it has always used.
```json
// ~/.openviking/ovcli.conf
diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md
index d4bbc187d..b447e3995 100644
--- a/docs/en/agent-integrations/16-capability-reference.md
+++ b/docs/en/agent-integrations/16-capability-reference.md
@@ -42,7 +42,7 @@
¹ MCP `write` can target `viking://resources`, `viking://user`, or `viking://agent`. Adding skills via MCP is not yet supported; use the openclaw `add_skill` tool, `ov add-skill` CLI, or the REST API instead.
² MCP `forget` does not differentiate between memory, resource, and skill types. However, the storage layer protects namespace roots: deletion requests for bare `viking://`, `viking://user`, and `viking://agent` are rejected. See [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
³ For `viking_forget` on pi: the `recursive` flag is strictly set to false (directories are never deleted), and deleting by query requires a match score > 0.8.
-⁴ The `pi` harness registers its tools only if the session bypasses `bypassPatterns`, `client.health()` passes, and `ensureSession` succeeds (`index.ts:66-113`). If the health check fails, no tools are registered for that session.
+⁴ The `pi` harness registers its tools only if the session misses `bypassSessionPatterns`, `client.health()` passes, and `ensureSession` succeeds (`index.ts:66-108`). If the health check fails, no tools are registered for that session.
⁵ The `add_resource` tool in openclaw requires a double opt-in before activation.
**Skill addition/deletion boundaries**: Skills can be added via the openclaw `add_skill` tool (enabled by default), the `ov add-skill` CLI command, or the REST API. Deletion operates across four tiers, detailed in [§3.5](#_3-5-type-boundaries-for-writes-and-deletes).
@@ -52,7 +52,7 @@
| harness | how it plugs in | auto-recall | recall carries session_id | digest (client)* | profile injection | takes over host compaction | offline compensation (pending queue) | statusline |
|---|---|---|---|---|---|---|---|---|
| claude-code | 9 hooks + MCP proxy + slash + statusline + skill | ✅ | ✅ | ✅ local `claude -p` / server-side rewrite (auto by default) | ✅ (10000) | ❌ (PreCompact only commits) | ✅ | ✅ |
-| codex / trae-cli | 4 hooks + MCP proxy + skill | ✅ | ✅ | ✅ local `codex exec` (on by default) | ✅ (10000) | ❌ | ❌ no on-disk queue (the cursor stays put and the next turn resends) | ❌ |
+| codex / trae-cli | 5 hooks + MCP proxy + skill | ✅ | ✅ | ✅ local `codex exec` (on by default) | ✅ (10000) | ❌ | ✅ | ❌ |
| cursor | 7 hooks + MCP proxy + rule + skill | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |
| trae / trae-cn | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |
| zcode | 4 hooks + MCP proxy | ✅ | ✅ | ❌ | ✅ (6000) | ❌ | ✅ | ❌ |
@@ -110,33 +110,35 @@ Supporting mechanisms:
## 2.2 The memory-plugin-shared layer
-The `examples/memory-plugin-shared/lib/` directory contains 24 `.mjs` modules and serves as the single source of truth for all JS-based harnesses. These are consumed in two ways:
+The `examples/memory-plugin-shared/lib/` directory contains 25 `.mjs` modules and serves as the single source of truth for all JS-based harnesses. These are consumed in two ways:
-1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source (keep this in mind when cross-referencing line numbers). Every target ships exactly the modules it imports, so the breakdown follows the import graph rather than the harness. Over the 13-module hook set (`HOOK_SHARED_FILES` in `sync.mjs`) that every hook-driven plugin takes: pi adds `setup-wizard` and `batch-send` (15); dsh adds the two `mcp-proxy-*` modules it needs for the stdio proxy (15); opencode adds `setup-wizard`, the two `mcp-proxy-*`, and `batch-send` (17); zcode adds the two `mcp-proxy-*`, `batch-send`, `async-writer`, `agent-hook-runtime`, and `agent-uri-guard` (19); claude-code and codex add `setup-wizard`, the two `mcp-proxy-*`, `batch-send`, `async-writer`, `plugin-config`, `workspace-config`, `workspace-registry`, and `doctor-core` (22 each). agent-plugins takes none of the hook set — it has no hooks — only `credentials`, `debug-log`, and the two `mcp-proxy-*` (4). At the current HEAD, every target has zero drift from the original library source.
-2. **Direct import via relative path (no copying)**: Integrations like cursor, trae, and trae-cn directly `import "../../memory-plugin-shared/lib/..."`. To ensure this works, the installer copies the package alongside the 15 shared modules those hooks transitively import into `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`, preserving the relative folder layout. That installed set is closed under imports and excludes the workspace configuration layer, which no hook runtime reaches. At runtime, these harnesses share this directory, meaning reinstalling any one of them will overwrite the shared directory wholesale.
+1. **Vendoring (copying)**: The `sync.mjs` script distributes these modules to 7 targets, prefixing every file with `// GENERATED FROM ... DO NOT EDIT.`. Because of this added line, a vendored copy's line number will be exactly one line greater than the library source. There is no hand-kept file list: each target gets the transitive closure of the modules its own code imports. Claude Code, Codex and agent-plugins are installed by pointing a host at a directory in this repository, so their generated copies are committed and a push to main regenerates them. OpenCode, DSH and OpenClaw publish as npm packages and pi is tarred by the installer, so those four generate their copies at pack time and keep none in git.
+2. **Direct import via relative path (no copying)**: cursor, trae, trae-cn and zcode directly `import "../../memory-plugin-shared/lib/..."`. The installer copies the package alongside the shared modules those hooks transitively import into `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`, preserving the relative folder layout. That installed set is closed under imports, including the workspace configuration layer the hook runtime reaches. At runtime, these harnesses share this directory, so reinstalling any one of them overwrites the shared directory wholesale.
Core modules at a glance (detailed further in the per-dimension sections):
| Module | Responsibility | Consumers |
|---|---|---|
| `recall-core.mjs` | Handles recall request construction, three-tier degradation, and local fallback ranking/injection | All JS-based harnesses |
-| `agent-hook-runtime.mjs` | All-in-one "thin hook" runtime handling 19 configuration environment variables, session ID derivation, cross-process locking, fetching, and commits | cursor / trae / trae-cn / zcode |
+| `agent-hook-runtime.mjs` | All-in-one "thin hook" runtime handling configuration resolution through the shared schema, session ID derivation, cross-process locking, fetching, and commits | cc / codex / cursor / trae / trae-cn / zcode |
| `mcp-proxy-core.mjs` | stdio ↔ streamable-HTTP MCP proxy core | All MCP-based integrations + agent-plugins |
-| `pending-queue.mjs` | On-disk offline queueing and replay at session start | cc / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `ov-http.mjs` | The one path from a hook to the OpenViking server: headers, AbortController, envelope | All JS-based + agent-plugins |
+| `pending-queue.mjs` | On-disk offline queueing and replay at session start | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
| `batch-send.mjs` | Executes writes in batches of 100, handles per-message degradation on 404/405 errors, and queues the leading contiguous prefix | cc / codex / opencode + the agent-hook family |
| `profile-inject.mjs` | Injects the profile and available-memory index at session start | 9 harnesses (all but openclaw / hermes) |
| `recall-compress-core.mjs` | Manages the recall compression prompt, URI edit-distance repair, and caching | claude-code |
-| `capture-utils.mjs` | Handles message normalization, injection back-flow guarding, and the built-in capture heuristics (acks, slash commands, signal floor) | codex / opencode / dsh / pi / zcode |
-| `input-filters.mjs` | Compiles and applies the operator's own sed-style rules — `s` substitute, `d` drop, `k` keep-only, optionally scoped to one role — over the recall query and every captured turn. A rule that fails to parse is reported and skipped, never thrown ([grammar](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#input-filters)) | Vendored by every hook plugin; the `recallQueryFilters` / `captureFilters` knobs are supplied by claude-code / codex |
+| `capture-utils.mjs` | Handles message normalization, injection back-flow guarding, and the built-in capture heuristics (acks, slash commands, signal floor) | cc / codex / opencode / dsh / pi / zcode / cursor / trae×2 |
+| `input-filters.mjs` | Compiles and applies the operator's own sed-style rules — `s` substitute, `d` drop, `k` keep-only, optionally scoped to one role — over the recall query and every captured turn. A rule that fails to parse is reported and skipped, never thrown ([grammar](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#input-filters)) | All hook plugins; the `recallQueryFilters` / `captureFilters` knobs are supplied by claude-code / codex |
| `credentials.mjs` | Credential resolution chain (see [§3.1.3](#_3-1-3-credential-systems)) | All JS-based |
| `session-model.mjs` | Session ID prefix derivation and bypass globbing | All JS-based |
| `async-writer.mjs` | Detaches the write path (drains stdin → spawn → approve → write → unref). Falls back to synchronous writing if spawn fails | cc / codex / zcode |
| `workspace-peer.mjs` | Resolves the actor peer from `peer.source` — presets, templates, and the pre-git id kept for dual-read ([§3.1.3](#_3-1-3-credential-systems)) | All JS-based |
| `workspace-identity.mjs` | Workspace root + git identity (normalized `origin`, root path, worktree/submodule kind), derived by walking the filesystem with no `git` subprocess and cached per cwd | All JS-based |
-| `workspace-config.mjs` | The layered workspace config: reads `<root>/.openviking/config.json` and `config.local.json`, merges layers with provenance, strips connection and credential keys | claude-code / codex |
-| `workspace-registry.mjs` | The per-machine registry `~/.openviking/workspaces/<slot>.json` — one file per workspace, hand-created and read-only for the plugins, the layer that outranks any committed file | claude-code / codex |
-| `uri-guard.mjs` / `agent-uri-guard.mjs` | Intercepts cases where `viking://` is incorrectly treated as a local path | Used in each harness's `PreToolUse` or `tool.execute.before`-style hooks |
-| `plugin-config.mjs` | Reads the `plugin` section of `ovcli.conf` | claude-code / codex |
+| `workspace-config.mjs` | The layered workspace config: reads `<root>/.openviking/config.json` and `config.local.json`, merges layers with provenance, strips connection and credential keys | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `workspace-registry.mjs` | The per-machine registry `~/.openviking/workspaces/<slot>.json` — one file per workspace, hand-created and read-only for the plugins, the layer that outranks any committed file | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `uri-guard.mjs` | Intercepts cases where `viking://` is incorrectly treated as a local path | Used in each harness's `PreToolUse` or `tool.execute.before`-style hooks |
+| `config-schema.mjs` | The single declaration of every knob: canonical name, type, default, range, `OPENVIKING_*` variable, accepted aliases, and workspace key. The doctor's known-key set and the workspace file's dotted-key map are projections of it | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `plugin-config.mjs` | Resolves every declared knob through the layers: env → the workspace layers → `ovcli.conf` `plugin.<harness>` → `ovcli.conf` `plugin` → ov.conf's harness section → defaults | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
| `setup-wizard.mjs` | Interactively writes to `ovcli.conf` | cc, codex, opencode, and pi expose an entry point for this |
| `retryable.mjs` | Handles retryability checks: allows status codes 0, 408, 429, and ≥500, as well as 409 if `error.details.retryable===true`. Standard 4xx errors (including 401/403) are not retried | All JS-based |
@@ -165,19 +167,19 @@ Core modules at a glance (detailed further in the per-dimension sections):
| claude-code | CC plugin (marketplace): 9 hooks + MCP proxy + slash + statusline + skill | One-line `install.sh --harness claude` (supports both the modern plugin path and the legacy `claude mcp add` compatibility path) / manual marketplace / TOS mirror | `cc-<CC session_id verbatim>`; subagents use `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
| codex | Codex plugin (marketplace): 4 hooks + MCP proxy + skill | One-line `--harness codex` / `codex plugin marketplace add` (the TOS channel uses dumb-HTTP git to ensure remote updates continue working) | `cx-<safeId>` (deterministically derived, without reading state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |
| trae-cli | **Installed as a codex plugin alias** (TraeCode CLI 2.0, 2.0 only; a Codex-family CLI: uses the `traecli` binary and `~/.trae/traecli.toml` config; its capability surface is identical to codex) | One-line `--harness trae-cli` (reuses the codex install flow; marketplace commands run against the targeted binary, e.g., `traecli plugin marketplace add`) | Same derivation rule as codex | Same as codex (env + ovcli.conf `plugin.codex` + ov.conf) | ✅ (same as codex) |
-| cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env only | ❌ (shares the installer TUI) |
-| trae / trae-cn | Config-driven (`~/.trae{,-cn}/hooks.json` + platform-specific mcp.json) | One-line `--harness trae,trae-cn` | `tr-` / `trcn-` | env only | ❌ |
-| zcode | Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) | One-line `--harness zcode` | `zc-<sess_…>` | env only | ❌ |
-| opencode | npm plugin `@openviking/opencode-plugin` (its config hook dynamically injects the MCP entry) | One-line `--harness opencode` (uses npm registration with a proxy snapshot fallback) / manual npm / from source | `oc-<id>`; subagents use `oc-<parent>__subagent-<child>` | `openviking-config.json` (searched at 4 levels) + env | ✅ |
-| dsh | In-process Cordis plugin (`cordis.patch.yml` plugin group) | Unified installer (asks for the profile, default `web`), or `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id as-is>`; each subagent is assigned its own session | cordis patch config + 4 env vars (credentials: patch > env; behavior toggles: env > patch) | ❌ |
-| pi | Native pi extension (loaded from a directory, with TypeScript transpiled on the fly via jiti) | One-line `--harness pi` (including `pi install` registration) | `pi-<piSessionId>` | `config.json` (credential fields are resolved via the shared credential chain) + env | ✅ |
+| cursor | Config-driven (writes `~/.cursor/hooks.json`+`mcp.json`) + rule + skill | One-line `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌ (shares the installer TUI) |
+| trae / trae-cn | Config-driven (`~/.trae{,-cn}/hooks.json` + platform-specific mcp.json) | One-line `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |
+| zcode | Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) | One-line `--harness zcode` | `zc-<sess_…>` | env + ovcli.conf `plugin.zcode` | ❌ |
+| opencode | npm plugin `@openviking/opencode-plugin` (its config hook dynamically injects the MCP entry) | One-line `--harness opencode` (uses npm registration with a proxy snapshot fallback) / manual npm / from source | `oc-<id>`; subagents use `oc-<parent>__subagent-<child>` | env + ovcli.conf `plugin.opencode` | ✅ |
+| dsh | In-process Cordis plugin (`cordis.patch.yml` plugin group) | Unified installer (asks for the profile, default `web`), or `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id as-is>`; each subagent is assigned its own session | env + ovcli.conf `plugin.dsh` + the cordis patch config, which is the lowest behavior layer (credentials still come from the patch first) | ❌ |
+| pi | Native pi extension (loaded from a directory, with TypeScript transpiled on the fly via jiti) | One-line `--harness pi` (including `pi install` registration) | `pi-<piSessionId>` | env + ovcli.conf `plugin.pi` (credential fields are resolved via the shared credential chain) | ✅ |
| openclaw | context-engine plugin (`ownsCompaction:true`) + 15 tools + 5 slash + 4 hooks + HTTP routes | ClawHub: run `openclaw plugins install clawhub:@openviking/openclaw-plugin` alongside `openclaw openviking setup` / npm installer / TOS offline bundle | A UUID is lowercased as-is, otherwise `sha256(sessionKey)`; `memory_store` temporary sessions use `memory-store-<ts>-<rand>` | `plugins.entries.openviking.config` in `openclaw.json` (strictly validated: unknown keys or invalid values force the plugin into setup-only mode) + a few env vars | ✅ `openclaw openviking setup` (interactive/non-interactive + key role probing + version compatibility check) |
| hermes | Hermes bundled MemoryProvider (ships with Hermes; no plugin installation required) | Run `hermes memory setup openviking` (interactive curses wizard), or manually run `config set memory.provider openviking` + `.env` | Hermes generates `%Y%m%d_%H%M%S_<hex6>`; the plugin uses it verbatim | `.env` (`OPENVIKING_*`) or linked ovcli.conf (`use_ovcli_config` mode clears the 5 corresponding variables from .env) + config.yaml | ✅ (multi-level menu) |
| ov CLI | Native Rust binary | npm `@openviking/cli` / `uv tool install openviking` / cargo / GitHub Releases | Does not manage its own session (`ov chat` defaults to the machine-uid) | `ovcli.conf` (multiple profiles) + a few env vars | ✅ `ov config` (TUI wizard) |
### 3.1.2 Unified installer
-The unified install script (`examples/memory-plugin-shared/install.sh`, 3424 lines) supports ten harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`. (Note that `openclaw` uses its own distribution channel, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:
+The unified install script (`examples/memory-plugin-shared/install.sh`) supports ten harness IDs: `claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`. (Note that `openclaw` uses its own distribution channel, while `trae-cli` reuses the `codex` install flow, as detailed in [§3.1.1](#_3-1-1-decision-matrix)). Key highlights:
- **Interactive prompts:** Two distributions (`--dist github|tos`) and three sources (`--source remote|archive|dev`) are available. When executed via `bash <(curl …)`, it reads input directly from `/dev/tty` to ensure prompts remain interactive.
- **Usage:** In the official documentation, the canonical one-line command omits the `--harness` flag, which launches a TUI multi-select menu. However, the setup-helper forwarding scripts bundled with each plugin append the `--harness` flag automatically.
@@ -193,7 +195,7 @@ Four parallel credential-resolution systems coexist within the codebase, each ut
| Family | Consumers | URL Env | Key Env | Identity Env | Auth Header |
|---|---|---|---|---|---|
-| **A. Shared JS core** (`credentials.mjs`) | claude-code / codex (including trae-cli) / cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | `Authorization: Bearer`. Note: codex's four hook scripts also send an `X-API-Key` compatibility header. |
+| **A. Shared JS core** (`credentials.mjs`) | claude-code / codex (including trae-cli) / cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | `Authorization: Bearer` alone; no harness in this family sends `X-API-Key`. |
| **B. openclaw** (its own `config.ts`) | openclaw | `OPENVIKING_BASE_URL` → `OPENVIKING_URL` | `OPENVIKING_API_KEY` (supports SecretRef env/file) | `OPENVIKING_ACCOUNT_ID` / `OPENVIKING_USER_ID` (note the `_ID` suffix here) | `X-API-Key`. (When pointing to OV Cloud, note that it actually authenticates using Bearer). |
| **C. hermes** (Python) | hermes | `OPENVIKING_ENDPOINT` | `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_AGENT` (= actor peer) | Sends both `X-API-Key` and `Bearer`. When a key is present, it omits tenant headers by default (if the server rejects the call with a trusted error, it appends them and retries once). |
| **D. ov CLI** (Rust) | ov | Primarily the conf file | conf | `--account/--user/--actor-peer-id` | `X-API-Key`. Toggles between LDAP Basic and OIDC Bearer based on `auth_mode`; an `api_key` containing two or more `.` characters automatically receives a Bearer header as well (JWT fallback). |
@@ -203,11 +205,11 @@ Family A resolves credentials in the following order (refer to individual profil
1. The resolution mode is controlled by `OPENVIKING_CREDENTIAL_SOURCE` (aliased as `_CREDENTIALS_SOURCE`), accepting values of `env|cli|auto` (defaults to `auto`).
2. **`auto` prioritizes environment variables**: If any environment credential field is present, the entire resolution process relies on the environment. Only when all environment fields are empty, and an `ovcli.conf` file exists with credential fields, does the system fall back to the configuration file (meaning the key, account, user, and peer are then exclusively sourced from the file).
3. **baseUrl**: Resolves via environment variables → `ovcli` `url` → `ov.conf` `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}` (where `0.0.0.0` normalizes to `127.0.0.1`), with a final fallback to `http://127.0.0.1:1933`.
-4. **apiKey**: Resolves via `BEARER_TOKEN` → `API_KEY` → `ovcli` `api_key` → `ov.conf` `codex.apiKey` → `server.root_api_key`.
+4. **apiKey**: Resolves via `BEARER_TOKEN` → `API_KEY` → `ovcli` `api_key` → `ovcli` `plugin.<harness>.apiKey` → `ovcli` `plugin.apiKey` → `ov.conf` `<harness>.apiKey` → `server.root_api_key`. The `<harness>` block is the one named after the calling harness (snake_case, so `trae_cn`; `claude-code` and `claude_code` reach the same block), and `account` / `user` / `peerId` read that same block at the same position in their own chains.
5. **mcpUrl**: Resolves via `OPENVIKING_MCP_URL` (when outside CLI mode) → `${baseUrl}/mcp`.
-6. **Common request headers**: `Authorization: Bearer` + `X-OpenViking-Account/User/Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`.
+6. **Common request headers**: `Authorization: Bearer` + `X-OpenViking-Account/User` (trusted mode only) + `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`. An `api_key` server reads the identity out of the key and ignores those two headers, so they are withheld there rather than named to every proxy on the path. The mode resolves via `ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → trusted whenever an account or user resolved at all.
-**Workspace peer** (applies to every Family A harness; the agent-plugins package derives nothing and sends only an explicit `OPENVIKING_PEER_ID`): If no explicit `peerId` is provided and `OPENVIKING_WORKSPACE_PEER≠0`, the peer is derived from the workspace and sent as the `X-OpenViking-Actor-Peer` (the server validates this header and returns a `400` error if it contains `/` or `\`). The derivation rule is `peer.source`, which **defaults to `git`**: the normalized `origin` URL first, falling back to the repository root. Outside a repository nothing is sent, and what is remembered there goes to the user-level space `viking://user/<you>/memories` instead. In `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` with an origin of `[email protected]:volcengine/OpenViking.git`, the peer is `github.com-volcengine-openviking` — the same value from any subdirectory, any worktree, any machine, and any clone. `peer.source` is read from the env var `OPENVIKING_PEER_SOURCE`, the ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource` keys, and the workspace file's `peer.source`; only claude-code and codex read those layers, so every other Family A harness always runs on the default.
+**Workspace peer** (applies to every Family A harness; the agent-plugins package derives no workspace peer and forwards none — it has no knob layer that could set `recallPeerScope` to `actor`, so its proxy never sends the header): If no explicit `peerId` is provided and `OPENVIKING_WORKSPACE_PEER≠0`, the peer is derived from the workspace and sent as the `X-OpenViking-Actor-Peer` (the server validates this header and returns a `400` error if it contains `/` or `\`). The derivation rule is `peer.source`, which **defaults to `git`**: the normalized `origin` URL first, falling back to the repository root. Outside a repository nothing is sent, and what is remembered there goes to the user-level space `viking://user/<you>/memories` instead. In `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` with an origin of `[email protected]:volcengine/OpenViking.git`, the peer is `github.com-volcengine-openviking` — the same value from any subdirectory, any worktree, any machine, and any clone. `peer.source` is read from the env var `OPENVIKING_PEER_SOURCE`, the ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource` keys, and the workspace file's `peer.source`; every Family A harness reads those layers.
| `peer.source` | Expands to | Resulting peer |
|---|---|---|
@@ -224,7 +226,7 @@ Family A resolves credentials in the following order (refer to individual profil
| `{dir}` | The workspace root's directory name: the repository root, or the directory holding `.openviking/config.json` | The directory is not a workspace |
| `{harness}` | The name of the agent running, the same one the User-Agent carries | Never — but the MCP proxy takes no part in derivation (its cwd is not a reliable identity), so a read path that goes only through it cannot resolve it |
-To give a directory that is not a repository its own peer under claude-code or codex, create `.openviking/config.json` there holding `{"version": 1, "peer": {"id": "my-project"}}`; every other harness needs an explicit `OPENVIKING_PEER_ID` instead.
+To give a directory that is not a repository its own peer, create `.openviking/config.json` there holding `{"version": 1, "peer": {"id": "my-project"}}`, or set an explicit `OPENVIKING_PEER_ID` for it.
**Identity semantics**: Every clone of one repository shares one peer, so project memory follows the project rather than the checkout. A fork carries a different `origin` and is therefore a separate peer by default; reviewing an external PR via `gh pr checkout` does not change `origin`, so it does not change identity either. Derivation is pure filesystem work (`workspace-identity.mjs`) with no `git` subprocess, which keeps it inside the tightest hook budget and keeps it working where `git` is absent from `PATH` or would refuse the repo over dubious ownership. Worktrees converge onto the main repository via `commondir`, a submodule keeps its own identity, and `$HOME` and `/` are never treated as workspace roots.
@@ -237,19 +239,17 @@ For `openclaw`, the peer is derived from `peer_role`/`peer_prefix` (note that if
| Config Layer | Applies To | Notes |
|---|---|---|
| env `OPENVIKING_*` | Per family, see above; behavior knobs are listed on each profile card | The only layer that spans every JS-based integration. |
-| Workspace layers: the per-machine registry `~/.openviking/workspaces/<slot>.json` > `<repo-root>/.openviking/config.local.json` (private, gitignored) > `<repo-root>/.openviking/config.json` (committed, shared by the team) | claude-code / codex | Schema v1; `version: 1` is required and a file declaring another version is skipped with a warning. Keys: `peer.source`, `peer.id`, `recall.{enabled,peer_scope,dedup_turns,max_items,score_threshold}`, `capture.{enabled,commit_token_threshold}`, `bypass.session_patterns`, `labels`. Lists union across layers, and a leading `"!reset"` clears what was inherited; unknown keys are kept and ignored. These files are trusted without a prompt because a hook is non-interactive, so the refusals are structural instead: connection and credential keys (`url`, `api_key`, `account`, `user`, `extra_headers`, …) are stripped with a warning and `${VAR}` is never expanded. Nothing writes the registry today: an entry is created by hand, and `ov-memory-doctor` prints the slot path to put it at. What a committed file switches off is announced in `ov-memory-doctor` rather than blocked. |
-| ovcli.conf `plugin` section (`plugin.claude_code` / `plugin.codex` / shared scalars) | claude-code / codex | `plugin.<x>` entries named after any other harness are ignored. Note: `ov config add/edit` rewrites the entire file from the Rust Config struct, thereby dropping any `plugin` sections it does not recognize; however, `ov config switch` simply copies bytes and remains unaffected. |
-| ov.conf harness sections (`claude_code.*` / `codex.*`) | claude-code / codex (legacy fallback) | |
-| The harness's own config file | opencode `openviking-config.json`, pi `config.json`, dsh cordis patch, openclaw `openclaw.json`, hermes `config.yaml`+`.env` | |
+| Workspace layers: the per-machine registry `~/.openviking/workspaces/<slot>.json` > `<repo-root>/.openviking/config.local.json` (private, gitignored) > `<repo-root>/.openviking/config.json` (committed, shared by the team) | claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi | Schema v1; `version: 1` is required and a file declaring another version is skipped with a warning. Keys: `peer.source`, `peer.id`, `recall.{enabled,peer_scope,dedup_turns,max_items,score_threshold}`, `capture.{enabled,commit_token_threshold}`, `bypass.session_patterns`, `labels`. Lists union across layers, and a leading `"!reset"` clears what was inherited; unknown keys are kept and ignored. These files are trusted without a prompt because a hook is non-interactive, so the refusals are structural instead: connection and credential keys (`url`, `api_key`, `account`, `user`, `extra_headers`, …) are stripped with a warning and `${VAR}` is never expanded. Nothing writes the registry today: an entry is created by hand, and `ov-memory-doctor` prints the slot path to put it at. What a committed file switches off is announced in `ov-memory-doctor` rather than blocked. |
+| ovcli.conf `plugin` section (shared scalars, overridden by a `plugin.<harness>` object) | claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi | A per-harness key takes either spelling — `claude_code` or `claude-code`, `trae_cn` or `trae-cn`. Note: `ov config add/edit` rewrites the entire file from the Rust Config struct, thereby dropping any `plugin` sections it does not recognize; however, `ov config switch` simply copies bytes and remains unaffected. |
+| ov.conf harness sections (`<harness>.*`, legacy) | Every harness, for the section named after it | Both the credential fields (`apiKey`, `accountId`, `userId`, `peerId`) and the tuning knobs resolve from the calling harness's own section. Either spelling of the name reaches the same block. |
+| The harness's own config file | dsh cordis patch (which the `plugin` section outranks), openclaw `openclaw.json`, hermes `config.yaml`+`.env` | |
**Quick scope reference** (these settings only take effect on the specified harnesses):
- `OPENVIKING_COMMIT_TURN_THRESHOLD`: cursor only (`trae`, `trae-cn`, and `zcode` commit on every Stop and ignore this threshold).
- `OPENVIKING_WRITE_PATH_ASYNC`: claude-code / codex / zcode.
- Recall digest settings (`OPENVIKING_RECALL_COMPRESS`, `OPENVIKING_RECALL_REWRITE`, and their companions): claude-code / codex (note that the server-side `rewrite` parameter is available to all callers, see [§3.2.5](#_3-2-5-recall-digest)).
-- `OPENVIKING_RECALL_DEDUP_TURNS`, `OPENVIKING_RECALL_QUERY_EXPANSION`: claude-code / codex.
-- `OPENVIKING_PEER_SOURCE` and the workspace config files: claude-code / codex (every other Family A harness derives its peer with the default `git` rule and still honors `OPENVIKING_PEER_ID` and `OPENVIKING_WORKSPACE_PEER`).
-- ovcli.conf `plugin` section: claude-code / codex.
+- `OPENVIKING_RECALL_DEDUP_TURNS`, `OPENVIKING_RECALL_QUERY_EXPANSION`, `OPENVIKING_PEER_SOURCE`, the workspace config files and the ovcli.conf `plugin` section: every harness that resolves through the shared loader — claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi. openclaw and hermes have configuration systems of their own.
## 3.2 Automatic recall and injection
### 3.2.1 Mechanism foundation: one shared pipeline, two server-side paths
@@ -268,7 +268,7 @@ On the server side, `session_id` handling diverges into two distinct execution p
**Three key notes on `dedup_turns`:**
① **Server default:** The server default for the context face is **0**. The familiar default of "5" actually originates from the `recall-core.mjs` client fallback and the `/recall` preset (the latter applying only when a `session_id` is present). Therefore, a third-party application hitting the API directly without the shared library must explicitly send `dedup_turns` to enable cross-turn deduplication, even if a `session_id` is provided.
② **Turn counting:** A "turn" counts individual messages, not full conversation rounds (since `_resolve_turn` relies on `total_message_count`). For a harness that pushes user and assistant messages simultaneously, the default of 5 roughly equals 1-2 actual conversation rounds.
-③ **Edge cases with auto-settings:** If `autoCapture=0` and `autoRecall=1`, the message count remains at 0, meaning the ledger clock never advances. As a result, URIs whose bodies were previously sent remain cooled down for the entire session. To disable deduplication entirely (e.g., for claude-code or codex), use `OPENVIKING_RECALL_DEDUP_TURNS=0`.
+③ **Edge cases with auto-settings:** If `autoCapture=0` and `autoRecall=1`, the message count remains at 0, meaning the ledger clock never advances. As a result, URIs whose bodies were previously sent remain cooled down for the entire session. To disable deduplication entirely, use `OPENVIKING_RECALL_DEDUP_TURNS=0`.
### 3.2.2 Decision matrix
@@ -299,7 +299,7 @@ On the server side, `session_id` handling diverges into two distinct execution p
- **pi**: Injected into the `systemPrompt`, re-assembled for every prompt (10000 budget, always resident).
- *Note:* `openclaw` and `hermes` do not perform profile injection.
- **Archive injection** (pulls the previous archive summary back upon resume):
- - **claude-code**: `source=resume/compact`, `token_budget=32000`, ≤5 `pre_archive_abstracts`.
+ - **claude-code**: `source=resume/compact`, `token_budget=32000`.
- **codex**: On resume, when the local `ovSessionId` has already been cleared (32000 budget / truncated to 6000 characters).
- **opencode**: Executed as part B of the opening injection (32000 budget).
- **pi**: Active in non-takeover mode (32000 budget).
@@ -395,8 +395,7 @@ Legend: **C** = commits; **C\*** = commits, with a precondition (see notes); **
| harness | mechanism | notes |
|---|---|---|
-| cc / cursor / trae×2 / zcode / opencode / dsh / pi | On-disk queue `~/.openviking/pending` (0700/0600) | Only retryable failures are queued (4xx errors, including 401/403, are considered non-retryable and are not queued, though they appear in debug logs); replay runs at session start: ≤50 entries per run, ≤3 attempts per entry, TTL 7 days; `.processing` claims entries atomically, with a 10min stale reclaim; an addMessage failure breaks execution immediately to preserve order |
-| codex / trae-cli | No on-disk queue | When the server is unreachable, compensation occurs because the `capturedTurnCount` cursor does not advance, prompting the next Stop to resend the same batch. This works provided the process survives and a subsequent turn occurs |
+| cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi | On-disk queue `~/.openviking/pending` (0700/0600) | Only retryable failures are queued (4xx errors, including 401/403, are considered non-retryable and are not queued, though they appear in debug logs); replay runs at session start: ≤50 entries per run, ≤3 attempts per entry, TTL 7 days; `.processing` claims entries atomically, with a 10min stale reclaim; an addMessage failure breaks execution immediately to preserve order |
| openclaw | No local queue | An addSessionMessage failure is caught, and that turn's messages are not replayed |
| hermes | In-process daemon-thread queue | The drain operates on a strict budget (10s/65s); nothing is written to disk |
| LangChain | In-process `_pending_commit_sessions` set | A failed commit is retried automatically during the next record; nothing is written to disk. On partial success, it raises an `OpenVikingPartialWriteError` (carrying `messages_written`, `input_messages_consumed`, and `context_attached`, allowing the caller to slice by position and retry the suffix) — making this the only protocol across all integrations that reports partial success |
@@ -481,7 +480,7 @@ There are three primary guards on MCP `write` and REST `content/write` (`content
| harness | When the server is unreachable | Negative cache | HTTP retry | Failure blocks the host |
|---|---|---|---|---|
| claude-code | All hooks catch exceptions → approve (never blocks); at session-start, even pending replays are skipped | context-face 6h + host-cli probe 7d + health 5s | None (relies on pending replay); `peer_scope` degrades once; batch falls back to sequential | No (`uri-guard` deny is by design) |
-| codex / trae-cli | All hooks catch exceptions → noop | context-face 6h + compressor runtime_failed (until the next startup) | Same as above (no on-disk pending; resends from the cursor) | No |
+| codex / trae-cli | All hooks catch exceptions → noop | context-face 6h + compressor runtime_failed (until the next startup) | Same as above (pending replay, triggered at SessionStart) | No |
| cursor/trae×2/zcode | Fetch errors are swallowed as `status:0`, and catch returns an empty injection; silently skips if the lock isn't acquired within 5s | context-face 6h (no negative cache for unreachable servers; every turn waits the full 15s) | None | No |
| opencode | All paths catch exceptions → WARN; the `event`/`dispose` hooks lack try/catch blocks (non-retryable commit failures bubble up to the host) | context-face 6h only; `/health` is uncached (one round trip per turn) | No synchronous retry; the MCP proxy retries once each for 401/403 and 400/404 | Mostly no (except `event`/`dispose`) |
| dsh | The client swallows all exceptions; `ensureState` failures are not cached (when the server is unreachable, each pre-step makes two 5s health calls) | context-face 6h + an in-process user-space cache that never expires | None; pending queue replays 3 times across processes | Yes (pre-step runs profile+recall serially; session/flush blocks) |
@@ -498,8 +497,8 @@ General HTTP timeouts are 15000ms (with a 1000ms floor). MCP proxy requests time
| harness | statusline | slash command | rule/skill | setup wizard | other |
|---|---|---|---|---|---|
-| claude-code | ✅ A separate process writes to `settings.json` (rich segments, 1-min TTL) | ✅ `/openviking-memory:ov` (server status + identity + injection provenance) | 1 experience skill | ✅ Line-based Q&A | Diagnostic scripts (`debug-recall`/`debug-capture`); `uri-guard` is not gated by the plugin toggle |
-| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | 8-step SOP in `VERIFICATION.md` |
+| claude-code | ✅ A separate process writes to `settings.json` (rich segments, 1-min TTL) | ✅ `/openviking-memory:ov` (server status + identity + injection provenance) | 1 experience skill | ✅ Line-based Q&A | `uri-guard` is not gated by the plugin toggle |
+| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | Live checks in `README.md`'s Testing section |
| cursor | ❌ | ❌ | Rule (`alwaysApply`) + skill | ❌ (Shares the installer TUI) | Standalone `uri-guard`, independent of the plugin toggle |
| trae/trae-cn | ❌ | ❌ | None | ❌ | — |
| zcode | ❌ | ❌ | None | ❌ | — |
@@ -519,19 +518,19 @@ Each card serves as a quick-reference entry point. It records only the facts and
## claude-code
- **Integration docs**: [Claude Code Memory Plugin](./02-claude-code.md)
-- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.4.4.
+- **Form**: A Claude Code plugin (marketplace) featuring a four-in-one architecture: 9 hooks, an MCP proxy (passing through 15 tools), a slash command, a statusline, and 1 experience skill. Version 0.5.0.
- **Capability highlights**: The harness with the broadest hook coverage — `SessionStart` (120s) / `UserPromptSubmit` (60s) / `PostToolUse:Read` (5s, the skill-experience hook, off by default) / `PreToolUse:Read|Glob|Grep` (5s, `uri-guard`) / `Stop` (45s) / `PreCompact` (30s) / `SessionEnd` (30s) / `SubagentStart` (10s) / `SubagentStop` (45s). Recall digesting is enabled by default (local `claude -p`, falling back to the server-side rewrite automatically when the local CLI is unavailable, [§3.2.5](#_3-2-5-recall-digest)). Provides full sub-session isolation via `SubagentStart`/`Stop` ([§3.3.5](#_3-3-5-subagent-session-comparison)), along with a statusline, slash command, and `uri-guard`. All shutdown paths except `kill -9` trigger a commit ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: The session ID format is `cc-<raw_CC_session_id>`, while subagents use `…__subagent-<agent_id>`. `Stop` commits at a threshold of 20000 (keep 10), and `PreCompact` commits synchronously. Automatic recall excludes resources ([§3.2.1](#_3-2-1-mechanism-foundation-one-shared-pipeline-two-server-side-paths)). The incremental cursor is stored in `/tmp` (if cleared by the system, the entire session is pushed again).
-- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 40 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.claude_code`), and `ov.conf` (`claude_code` as per [§3.1.4](#_3-1-4-configuration-layers)), offering roughly 70 tunable parameters. The compressor command and model are hardcoded to `claude`/`sonnet`/`low`/30s.
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | compaction [§3.4](#_3-4-compaction-takeover) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance) | UX [§3.7](#_3-7-additional-ux-comparison).
## codex
- **Integration docs**: [Codex Memory Plugin](./04-codex.md)
-- **Form**: A Codex plugin (marketplace). Features 5 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s), an MCP proxy, and 1 experience skill. Version 0.8.0.
+- **Form**: A Codex plugin (marketplace). Features 5 hooks (`SessionStart` 70s / `UserPromptSubmit` 130s / `Stop` 30s / `SessionEnd` 3s / `PreCompact` 60s), an MCP proxy, and 1 experience skill. Version 0.9.0.
- **Capability highlights**: A local recall-compression pipeline (`codex exec`, [§3.2.5](#_3-2-5-recall-digest)). `SessionEnd` (Codex ≥ 0.145) commits the session on a graceful exit, catching up any turns `Stop` missed, and a `SessionStart` fallback sweep reclaims messages left unarchived by exits that never fired it ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: The session ID format is `cx-<safeId>` (derived deterministically without reading state). `SessionEnd` fires only on a graceful exit and only on Codex 0.145+, so signals, crashes, older builds and `codex app-server` deferral fall to the sweep. Has no on-disk pending queue (while offline, the cursor simply doesn't advance, and the next turn resends to compensate, [§3.3.4](#_3-3-4-pending-queue-offline-compensation-comparison)). Idle-TTL is 1800000ms, lock wait 120000ms (configured via env). `Stop` and `SessionEnd` detach by default (the `appended N turn(s)` notice is hidden by default); a per-session mkdir lock serializes the Stop worker, PreCompact, the SessionEnd worker and the sweep. A newly registered hook event has no Codex trust record, so `/hooks` must approve `SessionEnd` after an upgrade.
-- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.codex`), and `ov.conf` (`codex`). Hooks transmit both `Bearer` and the `X-API-Key` compatibility headers ([§3.1.3](#_3-1-3-credential-systems)).
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.codex`), and `ov.conf` (`codex`). Hooks authenticate with `Authorization: Bearer` alone ([§3.1.3](#_3-1-3-credential-systems)).
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).
## trae-cli (TraeCode CLI 2.0)
@@ -539,59 +538,59 @@ Each card serves as a quick-reference entry point. It records only the facts and
- **Integration docs**: [TRAE Memory Integration](./13-trae.md)
- **Form**: TraeCode CLI 2.0 is a Codex-family CLI (binary `traecli`, user config `~/.trae/traecli.toml`, TUI support for `/plugins`, `/skills`, and `/mcp`). OpenViking integrates via a **codex plugin alias install**: using `--harness trae-cli` reuses the Codex installation flow, redirecting only the install parameters (binary, home, and config paths) to TraeCode CLI.
- **Capability surface**: Same plugin as Codex: 5 registered hooks, an MCP proxy, an experience skill, local recall compression, idle-TTL commit reclamation, and resume-archive injection. Refer to the Codex profile card. If the TraeCode CLI build lacks `SessionEnd`, the registration is ignored and every commit at shutdown goes through the idle-TTL sweep.
-- **Version support**: TraeCode CLI 2.0 only. 1.0 and 2.0 are not the same CLI — only 2.0 is Codex-family, and only 2.0 can use the codex plugin alias install. The earlier standalone plugin for 1.0, `examples/trae-cli-memory-hooks` (the `~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` approach), is deprecated.
+- **Version support**: TraeCode CLI 2.0 only. 1.0 and 2.0 are not the same CLI — only 2.0 is Codex-family, and only 2.0 can use the codex plugin alias install. The earlier standalone plugin for 1.0 (the `~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` approach) has been removed from the repository. The installer still accepts `--harness trae-cli --uninstall` to clean up a copy an old install left on disk.
- **Dimension index**: Same as the Codex card.
## cursor
- **Integration docs**: [Cursor Memory Integration](./12-cursor.md)
-- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and a skill. Includes 7 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `beforeShellExecution` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring).
+- **Form**: Config-driven (modifies `~/.cursor/hooks.json` and `mcp.json`), featuring an MCP proxy, an always-on rule, and a skill. Includes 7 hooks: `sessionStart` (30s) / `beforeSubmitPrompt` (20s) / `beforeReadFile` (5s) / `beforeShellExecution` (5s) / `stop` (30s) / `preCompact` (30s) / `sessionEnd` (30s). The shared library is loaded via relative imports (no vendoring). Version 0.3.0.
- **Capability highlights**: Features a dual `uri-guard` on `beforeReadFile` and `beforeShellExecution` (independent of the plugin toggle). The rule and skill are installed alongside it.
- **Behavior notes**: The session ID format is `cu-<conversation_id>`. `stop` commits every 8 messages (`commitTurnThreshold=8`, counted in messages, keep 0). `sessionEnd` only fires on `window_close`. By then, the host has already destroyed the shell-exec host, so it practically never runs ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)) — sessions ending below the 8-message watermark leave their tail to be archived by a later message in the same session ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). If the server is unreachable, every turn waits out the full 15s recall timeout.
-- **Configuration**: Configured strictly via environment variables (the `plugin` section is ignored).
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.cursor`), and the workspace files ([§3.1.4](#_3-1-4-configuration-layers)).
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).
## trae / trae-cn (IDE editions)
- **Integration docs**: [TRAE Memory Integration](./13-trae.md)
-- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). The shared library is introduced via relative imports, and the MCP server is named `openviking`.
+- **Form**: Config-driven (`~/.trae{,-cn}/hooks.json` + a platform-specific mcp.json) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s). The shared library is introduced via relative imports, and the MCP server is named `openviking`. Version 0.3.0.
- **Capability highlights**: Features the simplest and most direct behavior of the group. Every Stop that carries content is committed (keep 0). Consequently, upon shutdown, the largest possible backlog is merely the last in-flight turn ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)).
- **Behavior notes**: trae and trae-cn differ only in their session ID prefixes (`tr-` vs. `trcn-`) and installation paths. The same workload lands in two separate sets of sessions across the two clients, and cross-client sharing occurs via the server-side memory space after extraction rather than by reusing sessions. Note that there is no handling for PreCompact, status lines, skills, or subagents.
-- **Configuration**: Environment variables only.
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.trae` / `plugin.trae_cn`), and the workspace files.
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).
## zcode
- **Integration docs**: [Community Integrations → ZCode](./08-community-plugins.md)
-- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors 18 shared modules, and is the only harness that vendors the `agent-hook-runtime` pair instead of importing it by relative path. Version 0.1.2.
+- **Form**: Config-driven (merged into `~/.zcode/cli/config.json`, forcing `hooks.enabled=true`) utilizing an MCP proxy. It features 4 hooks: SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s). It vendors nothing: the installer assembles its shared runtime the same way it does for cursor and trae. Version 0.3.0.
- **Capability highlights**: The rollout file `~/.zcode/cli/rollout/model-io-<sid>.jsonl` serves as the source of truth for increments (a `lastTurnId` diff backfills any missed Stop events). Stop detaches by default, meaning Ctrl+C does not result in lost writes.
- **Behavior notes**: Commits on every Stop (keep 0). The capture path only strips the three types of injection blocks without performing any further text cleanup ([§3.2.6](#_3-2-6-injection-backflow-protection)). The initial capture reads the entire rollout at once, meaning that installing it into a long-running session will produce a single large push.
-- **Configuration**: Environment variables only; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.zcode`), and the workspace files; `OPENVIKING_WRITE_PATH_ASYNC` takes effect for zcode.
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).
## opencode
- **Integration docs**: [OpenCode Plugin](./10-opencode.md)
-- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 7 plugin hooks: config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. Version 0.2.4.
+- **Form**: Provided as the npm plugin `@openviking/opencode-plugin`, featuring a config hook that injects the MCP entry itself (tools carry the `openviking_` prefix). It exposes 7 plugin hooks: config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose. Version 0.3.0.
- **Capability highlights**: The `dispose` hook covers all four standard shutdown paths (on hosts ≥1.15.11). The repository list is injected into the system prompt ([§3.2.3](#_3-2-3-profile-opening-injection)). It boasts the richest host event surface of any integration, with `session.idle`, `compacted`, `deleted`, and `error` each carrying their own specific semantics.
- **Behavior notes**: Features a `commitTokenThreshold` of 20000 (positive values only; 0 falls back to the default) and a commit timeout of 30000ms. A single host compaction equates to two commits. Within the `dispose` hook's 5-second host budget, a slow commit spanning several sessions might be cut short, and the pending queue does not cover this scenario ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). On host versions below 1.15.11, the `dispose` hook is unavailable, meaning shutdowns do not trigger a commit. Leftover sessions are not flushed upon restart. The opening injection is attempted once per session ([§3.2.3](#_3-2-3-profile-opening-injection)). Finally, directory matching in `bypassSessionPatterns` does not apply to opencode, as the input does not carry a current working directory (cwd).
-- **Configuration**: Handled via `openviking-config.json` (searched at 4 levels) + environment variables.
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.opencode`), and the workspace files.
- **Dimension index**: tool surface [§2.1](#_2-1-server-side-mcp-tool-surface) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | subagent [§3.3.5](#_3-3-5-subagent-session-comparison).
## dsh (DeepSeek Harness)
-- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). It natively registers 7 `viking_*` tools (`viking_search/read/browse/remember/forget/add_resource/archive_expand`) and communicates directly via REST. It features 4 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush. Version 0.1.0.
+- **Form**: This is the only in-process, native Cordis plugin (`export function apply`). It natively registers 7 `viking_*` tools (`viking_search/read/browse/remember/forget/add_resource/archive_expand`) and communicates directly via REST. It features 4 events: agent/session-start (emit) / agent/pre-step (waterfall) / session/event / session/flush. Version 0.4.0.
- **Capability highlights**: `ctx.provide("openvikingMemory")` allows other Cordis plugins to build upon it. Pre-step injection is transmitted as a user message, aligning with the `complete:true` rendering mode of the DSH persona.
- **Behavior notes**: The unified installer covers dsh and asks which profile to install into (default `web`, overridable with `--dsh-profile`); npm is the bundle's only distribution channel, so the github/tos choice does not apply and every mode except `dev` installs the published package; `dev` packs the checkout first, because `dsh plugin` forwards to pnpm and a linked source tree cannot resolve the dsh peers the bundle imports. The teardown commit is allocated 3 seconds with no threshold, and it does not trigger on SIGHUP or a consecutive Ctrl+C ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). Compaction remains invisible to the plugin: injected content shrinks alongside the host's compaction, and the profile is not re-injected. Each subagent is assigned its own session ([§3.3.5](#_3-3-5-subagent-session-comparison)). The tool surface is the server's own MCP surface, reached through the same stdio proxy the other integrations use and published under `mcp__openviking__*`, so a server upgrade adds tools without a bundle release; the trade-off is that the proxy runs once per profile, so tool calls carry a process-level actor peer and `remember` is not session-scoped (recall, capture, and commit still resolve a peer per session). The bundle also ships the shared `openviking-memory` skill. Additionally, `uri-guard` matches tool names without normalizing case.
-- **Configuration**: Configured via cordis patch + 4 environment variables. For credentials, the patch overrides env vars; for behavior toggles, env vars override the patch.
+- **Configuration**: Configured via environment variables, `ovcli.conf` (`plugin.dsh`), the workspace files, and the cordis patch, which is the lowest layer for behavior knobs. Credentials are the exception: an endpoint, key, account, user, or peer named in the patch overrides the credential chain.
- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix) | degradation [§3.6](#_3-6-degradation-and-fault-tolerance).
## pi (pi Coding Agent Extension)
- **Integration docs**: [pi Coding Agent Extension](./11-pi.md)
-- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). It registers 7 native `viking_*` tools and uses direct REST communication (since pi lacks MCP support). It features 8 events + a `/viking` command. Version 0.1.0.
+- **Form**: Operates as a native pi extension (loaded from a directory and dynamically transpiled from TS by jiti). It registers 7 native `viking_*` tools and uses direct REST communication (since pi lacks MCP support). It features 8 events + a `/viking` command. Version 0.3.0.
- **Highlights**: Features takeover compaction (enabled by default, [§3.4.2](#_3-4-2-pi-takeover)). Employs a two-stage recall system: it queues at `before_agent_start` and performs synchronous retrieval during the context event, ensuring the current turn's prompt receives its corresponding memories. It also includes a status line. The `session_shutdown` event triggers across all shutdown paths and is properly awaited.
- **Behavior**: When takeover is enabled, exiting does not trigger a commit. Instead, the handler persists local state, and archiving waits either for the next resumed run to hit the threshold or for a manual `/viking commit` command ([§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix)). The takeover threshold is set to 30000 tokens while keeping the last 3 turns (keep 3, which the server interprets as a message count). When takeover is disabled, the threshold is 20000 tokens (keep 10), and exiting triggers an unconditional commit. Tool registration requires `health` and `ensureSession` to be established first ([§1.1](#_1-1-active-tool-surface-agentic-calls)). The `viking_add_resource` tool exclusively accepts HTTP URLs (the guard resides on the server). If takeover is off, resuming via `pi -c` will re-report the entire branch.
-- **Config**: Behavior toggles are managed in `config.json` + environment variables (credentials always pass through the credential chain, [§3.1.3](#_3-1-3-credential-systems)). Note that `bypassPatterns` uses prefix matching rather than globs.
+- **Config**: Configured via environment variables, `ovcli.conf` (`plugin.pi`), and the workspace files (credentials always pass through the credential chain, [§3.1.3](#_3-1-3-credential-systems)). Bypass goes through the shared `isBypassed` glob matcher under the key `bypassSessionPatterns`; the older `bypassPatterns` still reads.
- **Dimension index**: tool surface [§1.1](#_1-1-active-tool-surface-agentic-calls) | recall [§3.2](#_3-2-automatic-recall-and-injection) | takeover [§3.4.2](#_3-4-2-pi-takeover) | commit [§3.3.2](#_3-3-2-regular-commit-triggers)/[§3.3.3](#_3-3-3-shutdown-method-×-harness-outcome-matrix).
## openclaw
diff --git a/docs/en/agent-integrations/17-dsh.md b/docs/en/agent-integrations/17-dsh.md
index de680c108..39357ef45 100644
--- a/docs/en/agent-integrations/17-dsh.md
+++ b/docs/en/agent-integrations/17-dsh.md
@@ -103,7 +103,7 @@ Behavior knobs live in the profile's Cordis patch entry:
`peerSource`, in that same `config` block, decides how the workspace peer is derived. The default `"git"` uses the repository's normalized `origin` URL (`[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`), falling back to the repository root path, so every clone, worktree, and subdirectory of one repository shares a single peer; outside a repository no peer is sent at all, and what is remembered there goes to your user-level space at `viking://user/<you>/memories`. `"cwd"` restores the earlier behavior — the working directory with every non-alphanumeric character replaced by `-` — and `"none"` sends no peer at all. To give a directory outside a repository its own memory, set `OPENVIKING_PEER_ID` for it ([Give a Directory Its Own Peer](../configuration/02-client.md#give-a-directory-its-own-peer)).
-Credentials given in the patch win over the environment; behavior toggles read the environment first. The full list is documented in the [bundle README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin).
+Credentials given in the patch win over the environment. Behavior knobs resolve highest priority first: `OPENVIKING_*` environment variables, the workspace's `.openviking/config.json` and `config.local.json`, `ovcli.conf`'s `plugin.dsh`, `ovcli.conf`'s `plugin`, then this patch block. The full list is documented in the [bundle README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin).
</details>
diff --git a/docs/en/agent-integrations/18-plugin-development.md b/docs/en/agent-integrations/18-plugin-development.md
new file mode 100644
index 000000000..51c6ef129
--- /dev/null
+++ b/docs/en/agent-integrations/18-plugin-development.md
@@ -0,0 +1,498 @@
+# Hook + MCP Agent Plugin Development and Maintenance Standard
+
+This guide defines how to add and maintain OpenViking agent plugins that automatically read and write memory through lifecycle hooks and expose tools through MCP. It covers module responsibilities, protocols, state handling, installation, testing, and releases. A host is the client or runtime that runs the agent; the code also calls it a harness.
+
+A new host should primarily add its event, message-format, context-injection, and installation differences. Reuse shared implementations for configuration resolution, authentication, recall, capture filtering, HTTP requests, and offline retries. Claude Code, Codex, and other plugins are useful references, but verify the target host's actual contract. MCP-only and native-tool integrations can adopt relevant rules without adding hooks that do not apply.
+
+## Developing plugins with VibeCoding
+
+When using VibeCoding or other AI-assisted development to add, fix, or refactor an agent plugin, **require the coding agent to read this entire document and follow it before making changes**. Provide the document path with the task. Require the agent to verify the host contract first, implement the change, and report results against the acceptance checklist. Generated code and passing tests do not replace protocol, recovery, and installed-artifact verification.
+
+Start with the [Claude Code](./02-claude-code.md) and [Codex](./04-codex.md) plugins to understand how shared capabilities connect to native hooks and MCP. For hosts configured through hook files, refer to `agent-hook-plugin`; for persistent extensions, refer to OpenCode, DSH, and other plugins. Follow their separation of responsibilities and verified behavior. Do not ask the agent to copy an entire plugin or force every host to use the same events.
+
+Copy the following prompt into your coding agent and replace the final line with the specific task:
+
+```text
+Before changing any OpenViking agent plugin, read and follow
+docs/en/agent-integrations/18-plugin-development.md
+(Chinese: docs/zh/agent-integrations/18-plugin-development.md).
+
+Inspect examples/memory-plugin-shared/lib/ and the Claude Code and Codex
+plugins. Also inspect agent-hook-plugin, OpenCode, DSH, or another existing
+integration when its host model matches the task. Verify the target host's
+events, payloads, output schema, time limits, and installation contract.
+
+Keep shared behavior in the shared modules and host differences in the
+adapter. Do not copy a whole plugin or edit generated shared files. Cover
+configuration, hook/MCP identity, capture acknowledgements, commit recovery,
+installation, versioning, and bilingual documentation as applicable.
+
+Before finishing, use the guide's acceptance checklist and report what was
+changed, what was verified, and any remaining limitations.
+
+Task: <describe the plugin addition, fix, or maintenance change>
+```
+
+## 1. Design principles
+
+A shared library does not, by itself, make plugins share behavior. Configuration stays consistent only when the same execution path resolves and consumes it. Interpreting switches separately in each host leads to different names, defaults, and settings that are accepted but do nothing. Distribution files should likewise be derived from dependencies, so code that passes in the source tree does not fail after installation because an imported file is missing.
+
+The requirements are:
+
+1. **One authoritative implementation per behavior.** Shared modules own rules; adapters supply host facts. Do not copy a slightly different version of a rule into an adapter.
+2. **Reuse must happen in the execution path.** Call `buildPluginConfig()`, `buildRecallBlockDetailed()`, or the shared sender. Copied files, identically named exports, and agreements to keep implementations aligned do not prevent divergence.
+3. **Derive lists when possible.** Configuration keys, diagnostic keys, and workspace mappings come from the schema; runtime files come from the import closure; required archive contents come from entrypoints and manifests.
+4. **Preserve real differences.** Claude Code's subagent events, Codex's exit recovery, and ZCode's strict output format each have a reason. Share common capabilities without forcing identical lifecycles.
+5. **Distribution determines when files are generated.** A host that loads a repository directory needs that directory to be complete. A host that installs a built artifact needs dependencies generated before packaging. Keep installations complete and commit only the generated files that distribution requires.
+6. **Every abstraction should reduce maintenance points.** A new interface should let a future fix touch fewer places. Reconsider it if it only adds forwarding layers, boolean options, or another configuration table.
+
+These principles match the repository's [ownership and design guidelines](https://github.com/volcengine/OpenViking/blob/main/CONTRIBUTING.md#ownership-and-design). A new maintainer should be able to follow calls, locate the rule, explain a failure, and deliver a fix. Line and file counts are outcomes, not the goal.
+
+## 2. Establish the host contract before implementation
+
+Before development, record the following in the plugin README or, where needed, its design document. Cite host documentation, versioned source, or observed behavior. Do not fill gaps with assumptions about another agent.
+
+| Area | What must be established |
+| --- | --- |
+| Versions and platforms | Minimum host and Node.js versions, verified operating systems, and behavior on older versions |
+| Installation | Native plugin, marketplace, configuration-file hooks, or npm extension; directories the host actually loads |
+| Events | Availability of startup, prompt submission, turn completion, pre-compaction, session end, and subagent events |
+| Input | Whether stdin is JSON; session, cwd, transcript, and turn fields, including when they can be absent |
+| Output | Context injection, allow/deny fields, empty response, exit codes, and whether unknown keys invalidate the whole output |
+| Time limits | Units, upper bounds, whether the host clamps values, and whether timeouts kill one process or a process group |
+| Message source | Transcript/rollout format, flush timing, stable message IDs, and tool call/result association |
+| Processes | Hook process reuse, detached worker survival, and concurrency across windows and sessions |
+| MCP | Configuration format, stdio support, root variables, startup cwd, inherited environment, and tool namespaces |
+| Recovery | Identity and state retained across resume, clear, abnormal exit, compaction, and transcript truncation |
+
+Mark each capability as verified, supported with a fallback, or unsupported, and state the verified version. Do not describe `Stop` as session end or claim a capability by registering an event the host never emits. The minimum server version follows the APIs and URI capabilities actually used. For example, shared recall currently requires `viking://~` support; a fallback for one older API does not imply compatibility with every older server.
+
+### 2.1 Choose the smallest suitable integration form
+
+| Host constraints | Preferred form | Reference |
+| --- | --- | --- |
+| Hooks and MCP are installed through configuration files; the common dispatcher can express the lifecycle | Add an adapter and host configuration under `agent-hook-plugin/hosts/` | [agent-hook-plugin](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md) |
+| A native plugin needs its own manifest, directory, and lifecycle entrypoints | A separate plugin directory whose entrypoints call the shared runtime | [Claude Code](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md), [Codex](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) |
+| Host SDK callbacks require persistent state or dispose/idle callbacks | A host extension package using shared capabilities and explicit session scheduling | [OpenCode](https://github.com/volcengine/OpenViking/blob/main/examples/opencode-plugin/README.md), [DSH](https://github.com/volcengine/OpenViking/blob/main/examples/dsh-memory-plugin/README.md) |
+| MCP is available, but automatic injection or complete session records are not | An MCP-only integration with documented limits | [Agent Plugins](https://github.com/volcengine/OpenViking/blob/main/agent-plugins/README.md) |
+
+A new host name does not justify copying the Claude Code or Codex directory. Conversely, a host with a distinct session state machine should not be forced into the common dispatcher through accumulating `isFoo` or `specialStop` flags.
+
+## 3. Module responsibilities and dependency direction
+
+```text
+Host events / transcript Host MCP client
+ ↓ ↓ stdio
+Event, message, and output adapter Thin MCP entrypoint
+ ↓ ↓
+runHookStage + host lifecycle buildMcpProxyConfig
+ ↓ createOpenVikingMcpProxy
+Shared recall / capture / session ↓
+ ↓ createOvHttp Shared MCP transport
+ └────────── buildOvHeaders ─────────────┘
+ ↓
+ OpenViking Server
+
+buildPluginConfig / credentials configure both paths and their identity
+sync / install / pack deliver the complete dependency graph
+```
+
+Authoritative capability sources live in [`examples/memory-plugin-shared/lib/`](https://github.com/volcengine/OpenViking/tree/main/examples/memory-plugin-shared/lib/). The following table helps locate rules; it is not a template to recreate inside every plugin.
+
+| Responsibility | Authoritative module | What a host may supply |
+| --- | --- | --- |
+| Configuration declarations, defaults, aliases, ranges | [config-schema.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/config-schema.mjs) | Justified host-specific defaults, still declared in the schema |
+| Layered resolution and the complete config object | [plugin-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/plugin-config.mjs) | Harness ID, manifest, log filename, native host parameters |
+| Credentials and authentication mode | [credentials.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/credentials.mjs) | Existing compatibility requirements; no separate fallback chain |
+| Workspace and peer identity | [workspace-peer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-peer.mjs), [workspace-identity.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-identity.mjs) | Actual session cwd and an explicitly provided peer |
+| Hook initialization, bypass, single output | [agent-hook-runtime.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs) | Input reader, session ID resolver, enablement predicate, output envelope |
+| HTTP headers, timeouts, error results | [ov-http.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/ov-http.mjs) | Request path and body, time budget, current actor peer |
+| Recall and context construction | [recall-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/recall-core.mjs), [profile-inject.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/profile-inject.mjs) | Query, session identity, local compressor callback, host presentation |
+| Message sanitation, roles, structured content | [capture-utils.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/capture-utils.mjs), [input-filters.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/input-filters.mjs) | Transcript decoding and native tool event normalization |
+| Batch sending, offline replay, retry classification | [batch-send.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/batch-send.mjs), [pending-queue.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/pending-queue.mjs), [retryable.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/retryable.mjs) | When to call them and how acknowledgements advance the host cursor |
+| Background writes | [async-writer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/async-writer.mjs) | Host-supported detach timing and recovery measures |
+| MCP configuration and protocol | [mcp-proxy-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs), [mcp-proxy-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs) | Configuration projection, logger factory, necessary local tools |
+| Virtual URI checks and diagnostics | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs), [doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | Tool names, denial format, host installation/state checks |
+
+Dependencies must point from host adapters to shared capabilities. Shared code must not import a host directory. Pass a small, explicit callback when a capability needs a host action. Do not introduce a plugin container, service locator, or inheritance hierarchy for a single file read. Shared runtime modules must not depend on installers, tests, or user interfaces.
+
+### 3.1 How thin should an adapter be?
+
+Thin means owning only host differences; it is not a line-count limit. For example, [cc-transcript.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/scripts/cc-transcript.mjs) converts Claude message blocks and nested `tool_result` content. [Codex capture-utils.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/scripts/capture-utils.mjs) also expands nested tool activity and removes duplicate representations of the same call, so it can be longer. Both should delegate common content processing to shared code.
+
+For a new thin host, prefer the existing [`HOSTS`](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/hosts/index.mjs) registry and dispatcher interfaces: `stages`, `envelope`, `prompt`, `normalizeInput`, `capture`, and `guard`. Before adding an interface, identify the host fact that cannot be expressed. Do not design an adapter DSL for every hypothetical future agent.
+
+The existing `hosts/cursor.mjs`, `hosts/trae.mjs`, and `hosts/zcode.mjs` demonstrate the separation: event mappings are data, message conversion fits pure functions, and asynchronous capture needs explicit callbacks. Do not combine them into a configuration-object builder that also performs network requests.
+
+## 4. Configuration, credentials, and identity
+
+### 4.1 Declare once and resolve consistently
+
+Declare new behavior settings in `config-schema.mjs`: canonical name, type, default, range, owning capability, and applicable environment variable, legacy aliases, and workspace key. Resolve through `buildPluginConfig(harness, options)`; adapters only project fields needed by their host. Do not add a private plugin `config.json` that repeats shared defaults or maintain separate doctor/workspace key tables.
+
+Behavior settings resolve in this order, highest precedence first:
+
+1. `OPENVIKING_*` environment variables.
+2. The machine's workspace registry.
+3. Workspace `.openviking/config.local.json`.
+4. Workspace `.openviking/config.json`.
+5. `ovcli.conf` `plugin.<harness>`.
+6. `ovcli.conf` `plugin`.
+7. The legacy host section in `ov.conf`.
+8. Schema defaults.
+
+Pass host SDK inputs through explicit shared builder parameters and document their precedence. DSH host settings currently participate in the compatibility layer, and `hostInput` can pin connection or peer values. These specific interfaces do not authorize arbitrary overrides of the resolved configuration.
+
+Keep examples minimal. This `ovcli.conf` fragment supplies shared recall defaults and disables automatic capture for Codex; higher-priority environment or workspace settings can still override it:
+
+```json
+{
+ "plugin": {
+ "autoRecall": true,
+ "codex": {
+ "autoCapture": false
+ }
+ }
+}
+```
+
+Register the canonical host ID in `HARNESS_KEYS` and verify hyphen/underscore aliases follow existing conventions. The shared resolver decides conflicts between canonical names and aliases; within a layer, the canonical name wins. Do not add a second, conflicting alias conversion in the adapter.
+
+Distinguish an absent value, explicit `false`, and a resolved value equal to the default. Fields marked `sendOnlyWhenConfigured` are sent only when actually configured, so client defaults do not override server defaults. Do not use `value || default` for fields that allow `false`, `0`, or an empty string; validity follows the field's semantics.
+
+Switches must govern actual behavior. Disabling recall prevents automatic recall requests; disabling capture prevents new automatic capture and its associated commits for the session. Decide and verify separately whether previously queued writes are still recovered. Shared `isRecallEnabled()` and `isCaptureEnabled()` checks provide the final guard; adapters may exit early but must not be the only place enforcing switches. Advertise settings such as `mcpEnabled` for a host only when that host actually consumes them.
+
+### 4.2 Credentials are not ordinary workspace settings
+
+Resolve connections and identity through `credentials.mjs` and `buildPluginConfig()`. The `auto`, `cli`, and `env` modes of `OPENVIKING_CREDENTIAL_SOURCE` select credential sources; they do not simply follow the behavior-setting precedence above. Verify custom configuration paths, `plugin.<harness>` overrides, and hook/MCP behavior after `ov config switch`. Comparing a few default loader fields is insufficient.
+
+Workspace files must not contain forbidden connection or credential fields such as URLs, API keys, and user credentials, and must not interpolate environment variables. [`workspace-config.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-config.mjs) owns this rule; do not add a separate allowlist per host. Installers must not write resolved API keys into `.mcp.json` or replace the user's selected cloud connection.
+
+Build request headers with `buildOvHeaders()`. Send API keys as `Authorization: Bearer`, without a duplicate `X-API-Key`; send account/user headers only when the resolved `sendIdentityHeaders` is true. Preserve `User-Agent` and error `traceId` values to identify the running version and trace requests. Health checks, status lines, and diagnostic probes must not reimplement authentication.
+
+In diagnostics, `credentialSource` identifies the resolution mode, while `apiKeySource` identifies the key's actual origin. Keep these meanings distinct. `rootKeyFallback` exists for older installations; a new host must not copy that option unconditionally just because a reference plugin enables it.
+
+### 4.3 Separate session identity from peer identity
+
+A native session ID identifies a conversation; a peer identifies project memory ownership. They are not interchangeable. Writes use a stable native session ID and an explicit host prefix. Separate windows, sessions in the same cwd, and main/subagents must not accidentally share a capture cursor. Prefixes and session ID algorithms are data compatibility contracts; explain how old state remains readable when changing them.
+
+Use shared peer resolution. The current default derives identity from Git; ordinary non-Git directories receive no automatic peer, while marker files can specify one. See the [shared library's workspace notes](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/README.md#workspace-peers) for worktrees, subdirectories, and forks. Hooks must reload workspace settings using the payload's actual cwd, not the plugin installation directory.
+
+A persistent MCP proxy cannot infer the active project from its startup cwd. Use `resolveMcpActorPeerId()`: broad reads omit the actor peer header; actor-scoped reads require an explicit peer. The shared implementation currently warns and falls back to broad reads when that peer is absent. Document this behavior accurately. Peer scopes organize memory and retrieval within an authenticated user; do not present them as authorization isolation between different users.
+
+## 5. Hook lifecycle and reliable writes
+
+### 5.1 Map common stages to host events
+
+| Stage | Shared responsibility | Claude Code today | Codex today |
+| --- | --- | --- | --- |
+| Session start | Profile injection and necessary recovery | `SessionStart` | `SessionStart`, distinguishing startup, clear, and resume |
+| Prompt submission | Filter the query, recall, inject context | `UserPromptSubmit` | `UserPromptSubmit` |
+| Turn completion | Catch up new messages from a reliable source and persist progress | `Stop`, plus threshold-based commits | `Stop`, normally appending rather than ending the session |
+| Before compaction | Ensure preceding messages were written, then commit as appropriate | `PreCompact` commits existing messages; this entrypoint does not catch up the transcript | `PreCompact` catches up the transcript and commits |
+| Session end | Finish outstanding writes and commit | `SessionEnd` commits existing messages; this entrypoint does not catch up the transcript | `SessionEnd` catches up and commits in a worker, with startup recovery retained |
+| Subagents | Preserve identity and parent relationships without duplicates | `SubagentStart`, `SubagentStop` | Neither event is registered in the current hook manifest |
+| Local tool checks | Prevent treating virtual URIs as local paths | `PreToolUse` URI guard | No URI guard is registered in the current hook manifest |
+
+Use [Claude Code hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json) and [Codex hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/hooks/hooks.json) as the event registration references. Identical event names do not guarantee identical payloads or outputs. A host without an end event must choose and document an alternative commit point, such as ZCode's Stop commits, rather than register an unreachable SessionEnd handler.
+
+### 5.2 Hook entrypoint responsibilities
+
+Use `runHookStage()` for stdin parsing, configuration reload against the session cwd, enablement and bypass gates, and a single response. Supply a resolver for host-specific session fields instead of disabling bypass to accommodate a field name. Output must match the host's current event protocol: `decision: "approve"` is not universal, and Cursor's `additional_context` is not interchangeable with `hookSpecificOutput.additionalContext`.
+
+Keep stdout reserved for the host's protocol. Write logs to stderr or the shared log file. No results, disabled features, unavailable configuration, and network errors should produce a valid empty result for that event, so a memory service failure does not block normal interaction. An explicit URI guard denial must retain its denial semantics; generic error handling must not turn it into approval.
+
+Ordinary module imports must not read stdin, spawn processes, access the network, or exit the process. Put those effects in entrypoints or explicitly called functions. Shared functions must not call `process.exit()` for convenience. Reusable entrypoints need a testable main function and an explicit startup condition.
+
+### 5.3 Recall and profile injection
+
+Use `buildProfileBlock()` for profiles and `buildRecallBlock()` / `buildRecallBlockDetailed()` for per-turn recall. Hosts may supply compressors, presentation, and statistics, but must not reimplement retrieval targets, ranking, token budgets, or server compatibility fallbacks. A status line should consume shared results and the final injected content, rather than issue another recall to calculate counts.
+
+Automatic recall must carry the correct session and peer, and honor input filters, bypass, and switches. Keep empty results empty instead of injecting a server's no-relevant-memory sentinel. Compression failure may fall back to the existing uncompressed result, but must not invent a digest. Compressed `viking://` URIs must remain readable. Capture must distinguish the user's input, recalled context, and host wrappers so injected old memories are not captured again.
+
+When using a host CLI for compression, isolate that auxiliary invocation from automatic memory hooks, bound its execution time, and reuse the existing compressor interface. Do not launch an agent that recursively invokes the same recall/capture hooks. Model selection and invocation belong to the host adapter; common compression result handling belongs to shared code.
+
+### 5.4 Capture data and acknowledgement rules
+
+Prefer a complete host transcript or rollout. Use stdin as a fallback only when the complete source is verified to be unavailable. A Stop payload may lack the user input; do not manufacture a complete turn from the last assistant response. An unreadable file and no new messages must be distinguishable results.
+
+Decode host records into the shared capture model before applying shared filtering and sending. Preserve text separately from structured tool content. Tool names, call IDs, inputs, outputs, status, and available turn IDs must come from actual records. Do not record a native event, MCP result, and nested representation of one tool call as several calls. Do not retain only final assistant prose and lose tool activity. Text filtering must not discard valid records that contain only tools.
+
+Use `capture-utils.mjs` and `input-filters.mjs` for filtering and truncation. A text summary of tool output and structured `tool_output` are different fields. The current implementation delegates large-output externalization to the server while retaining a client limit for pathological payloads. Shortening text summaries must not also remove structured evidence.
+
+Write in this order:
+
+```text
+Read new records → decode and filter → send in order
+ ├─ server acknowledgement: advance sent progress
+ ├─ durable pending entry: handoff progress may advance; not yet delivered
+ └─ send and enqueue both fail: keep progress for recovery
+```
+
+Preserve these invariants:
+
+- Advance cursors only through a contiguous acknowledged prefix. The shared sender returns `sent` and `queued`. An adapter that advances by both must establish that queued entries are durable and retain responsibility for replay. Attempts are not successes.
+- Prefer stable message IDs, turn IDs, or transcript positions for deduplication. Identical text can belong to two legitimate turns; do not permanently deduplicate solely by text hash.
+- Use session locking when multiple processes update the same state, and write state through a temporary file and atomic rename. Lock wait limits, stale-lock recovery, and task duration must agree. Long tasks need demonstrable ownership and liveness, not a stale TTL shorter than their execution.
+- Define how replay handles messages sent successfully before a failed state save. Do not claim exactly-once delivery without server-side idempotency guarantees.
+- Transcript shrinkage, resume, and compaction must not leave the cursor permanently beyond new records. Explain how these changes are detected and recovered.
+- Give subagent capture a clear owner. If the main transcript already contains subagent records, a separate subagent hook must not import them again.
+
+### 5.5 Commits, retries, and exit
+
+A commit requests server archiving and processing; it does not mean long-term memory extraction has finished. Report HTTP success, task acceptance, archive completion, and extraction completion separately. A `task_id` is not proof that all processing is complete.
+
+Catch up a session's messages before committing. On partial failure, retain its active session and unfinished state. Implementations that hand messages to the pending queue must also prove a commit cannot overtake unreplayed messages. **Using the pending queue does not automatically provide transactional ordering between messages and commits.** Verify complete failure sequences and choose deferred commits or replay with enforced ordering as appropriate for the host.
+
+Shared retry classification currently permits retries for network failures, 408, 429, and 5xx. A 409 is retryable only when `error.details.retryable` explicitly says so. Do not repeatedly enqueue 401/403 responses or ordinary parameter errors. `sendSessionMessages()` handles batches of at most 100 messages and falls back to serial sends when the batch endpoint returns 404/405. Hosts must not maintain separate status-code lists or batching loops.
+
+Preserve the original payload when enqueueing, including commit parameters such as `keep_recent_count`; replay must execute the original operation. A failed commit must not clear the active ID, end marker, or missing messages prematurely. Pending queues have retry, replay-batch, and TTL limits. They provide bounded recovery, not indefinite offline retention.
+
+Set exit budgets from verified host behavior. Codex currently caps SessionEnd at 3 seconds. Its parent writes an `.ended` marker before launching a worker; a later SessionStart scans unfinished or expired active sessions. Resume does not imply an ended session, and an old worker must not commit a newly resumed session, so markers and cleanup must refer to the same exit event. See the [Codex commit design](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md).
+
+Use `maybeDetach()` and `readHookStdin()` for background writes and correctly transfer already-consumed stdin. Avoid losing the payload when parent and worker each try to read it. A successful detach means only that a worker started. Verify whether it survives host exit and how transcript data, pending entries, or end markers recover failures. A valid empty hook response is not a write acknowledgement.
+
+Synchronous shutdown needs one total budget covering lock waits, catch-up, and commit. Each step uses the remaining time instead of receiving the full hook timeout again. Background workers must also be bounded; a stuck request must not hold a lock indefinitely.
+
+A server field, configuration echo, or API's existence does not prove automatic commits execute in the actual message path. Before transferring commit responsibility from a plugin to the server, verify runtime behavior, older-server fallback, and duplicate-commit prevention. Do not remove reliable plugin commit points solely because an `auto_commit` setting exists.
+
+## 6. MCP and model-visible tools
+
+Hooks automate lifecycle behavior; MCP exposes tools the model chooses to call. Both connect through the same configuration and identity, but have separate responsibilities. Document what is injected automatically, which operations require model calls, and which MCP tools remain usable when automatic behavior is disabled.
+
+Hosts with stdio MCP support should use the shared proxy employed by Claude Code and Codex: resolve configuration, shape it with `buildMcpProxyConfig()`, and pass it to `createOpenVikingMcpProxy()`. MCP transport owns its own sessions, SSE, and protocol negotiation, so a REST JSON helper is not a substitute. Common authentication headers still come from `buildOvHeaders()`.
+
+Proxy entrypoints must not own separate tool schemas, API clients, SSE parsers, or retry state machines. Treat server `tools/list` and `tools/call` as authoritative instead of maintaining a second memory-tool catalog to customize descriptions. Necessary local tools use the shared `localToolProvider` interface with explicit scope, and must not accidentally shadow server tools.
+
+For each new host, verify:
+
+- Startup from the host's actual working directory, including relative paths, root variables, and environment allowlists. Codex's `.mcp.json` `env_vars` is a host-specific requirement, not evidence that other hosts inherit the same variables.
+- `initialize` negotiation, notifications without ordinary responses, JSON/SSE handling, concurrent response IDs, and protocol-clean stdout.
+- Shared recovery for expired MCP sessions and changed credential files. Do not blindly retry arbitrary tool calls after network failures, especially calls with write effects.
+- Expected hook and MCP URLs and identities across environment configuration, default/custom files, and profile switching. Observe request targets and headers rather than only configuration contents.
+- Tool names in diagnostics and documentation match what the host exposes. Do not rename `remember` to `store` in documentation or copy another host's namespace.
+
+Use direct remote MCP connections only when the host has suitable credential and configuration support, and document how it stays consistent with hooks. Do not add wrappers, environment files, or installation-time rewrites to work around a problem the shared proxy already solves.
+
+## 7. URI guards, skills, and diagnostics
+
+`viking://` is a virtual URI and must not be passed to local file or shell tools. Where the host supports checks before tool execution, use `evaluateUriGuard()` and keep only tool-parameter mapping and denial envelopes in the adapter. Do not expand the guard into a general command interceptor; ordinary file paths retain their behavior. Without the required event, document the limitation and guide models through a skill, without claiming equivalent interception.
+
+Shared skill sources live in [`examples/skills/`](https://github.com/volcengine/OpenViking/tree/main/examples/skills/) and are shipped through `SKILL_TARGETS`. Do not edit the same guidance separately in several plugin copies. Skills must describe tools that can actually be called and capabilities that exist. Do not instruct the model to repeat capture or commits each turn when hooks already own them. Distinct tool surfaces may need distinct skills; explain why. Generated skill files must not receive a banner before their YAML frontmatter.
+
+Use `runDoctor(hostSpec)` for diagnostics. Hosts supply installation paths, manifests, hook registrations, and state checks; `doctor-core.mjs` owns common configuration, credential, network, and output handling. Diagnostics must make it possible to inspect the installed version, configuration sources and effective values, peer, MCP entrypoint, hook budgets, and pending/session state. Prefer offline and JSON modes; offline checks must not silently access the network.
+
+Diagnostics should distinguish disabled, bypassed, no results, timeout, authentication failure, queued, enqueue failure, and commit failure. Logs retain host, stage, session association, latency, and trace IDs. They must not log API keys, full Authorization headers, or whole user transcripts by default. Doctor recommendations must use commands valid for the current installation form, not removed debug scripts.
+
+## 8. Layout, generation, and installation
+
+### 8.1 Recommended layout
+
+These are placement conventions, not a requirement to create every file. Angle brackets represent names supplied during implementation.
+
+```text
+examples/memory-plugin-shared/
+ lib/<capability>.mjs Authoritative shared behavior
+ lib/<capability>.d.mts Types when needed; maintained with implementation
+ lib/install/ Installer-only code, outside hook dependency closures
+ testing/support.mjs Test helpers, not shipped as runtime
+ sync.mjs Distribution targets and closure generation
+
+examples/agent-hook-plugin/
+ hosts/<host>.mjs Host adapter
+ hosts/<host>/ Host declarations, hook/MCP config, required assets
+ scripts/hook.mjs Common dispatcher
+ servers/mcp-proxy.mjs Common MCP entrypoint
+
+examples/<host>-memory-plugin/ Create only when a separate native plugin is needed
+ <host manifest directory>/
+ hooks/
+ scripts/ Host entrypoints, state, transcript adaptation
+ scripts/shared/ Generated; do not edit
+ servers/
+ skills/
+```
+
+Use explicit relative imports. Where shared modules have TypeScript consumers, keep `.d.mts` beside the authoritative `.mjs` and generate both together. Do not hand-maintain declarations in each artifact directory. List re-exports explicitly when needed to avoid `export *` collisions with adapter implementations.
+
+### 8.2 Choose generation strategy by distribution
+
+| Distribution | Current examples | Requirement |
+| --- | --- | --- |
+| Host loads a plugin directory directly from Git | Claude Code, Codex, `agent-plugins` | Commit shared copies so a checkout is loadable |
+| npm package or installation archive | OpenCode, DSH, OpenClaw, Pi | Generate during prepack or staging; do not commit runtime copies |
+| Installer assembles an adjacent runtime directory | Cursor, TRAE, TRAE CN, ZCode | Derive `lib/MANIFEST` from `ASSEMBLED_ROOTS` and copy runtime modules from it |
+
+Register these targets in [`sync.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs). For separate plugins, add the source root, output directory, and `committed` policy to `TARGETS`. Extend `ASSEMBLED_ROOTS` only for a new assembled root; ordinary thin hosts are usually covered already. Register skill delivery separately in `SKILL_TARGETS`. Do not maintain a manual list of runtime modules to copy.
+
+After changing shared source, run:
+
+```bash
+node examples/memory-plugin-shared/sync.mjs
+```
+
+The generator analyzes static imports and literal dynamic imports. Keep required dependencies discoverable; do not hide them behind constructed strings. Preserve relative layout after installation so the same import works in the source tree and on the user's machine. Do not rely on absolute development paths, temporary symlinks, or `NODE_PATH` to make local tests pass.
+
+Pull requests must include current generated files where the delivery policy requires them to be committed, including newly generated untracked files. The main-branch [`plugin-shared-sync.yml`](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/plugin-shared-sync.yml) is an additional safeguard, not a replacement for a complete change. Documentation-only edits that do not affect generation sources need not regenerate unrelated copies.
+
+### 8.3 Installation and removal contracts
+
+Reuse [`install.sh`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/install.sh). Keep JSON/JSONC merge logic in [`lib/install/`](https://github.com/volcengine/OpenViking/tree/main/examples/memory-plugin-shared/lib/install/) instead of adding large JavaScript programs inside shell heredocs. Installers should:
+
+1. Parse, validate, and prepare required files before changing user configuration. Invalid JSON/JSONC must produce an error and preserve the original file, not be treated as empty configuration.
+2. Be idempotent, without duplicate hook/MCP entries. Preserve other plugins, user settings, and meaningful comments in formats that support them.
+3. Handle spaces in paths, hosts without variable expansion, and custom configuration paths. Write only fields the host supports.
+4. Remove only entries owned by this plugin, including URI guards. Preserve other integrations, credentials, memory, and session data. Uninstalling should not require downloading source again.
+5. Keep shared runtime files available to other clients after removing one client. Failures must not leave configuration split between old and new installation directories.
+
+Validate archives with [`stage-memory-plugin-marketplace.sh`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/stage-memory-plugin-marketplace.sh) and [`check-marketplace-archive.mjs`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-marketplace-archive.mjs). Entrypoints, transitive dependencies, and scripts referenced by skills must exist. Exclude `node_modules`, `.git`, and local secrets. Validation must also detect an omitted distribution target, rather than merely trusting the staging directory list.
+
+Before release, extract the final archive or tarball and smoke-test entrypoints and installation. Successful source-tree imports prove only that the source tree is complete, not the package users receive.
+
+## 9. Reviewing code smells and maintainability
+
+Review the path from host input through the normalized model, shared capability, acknowledgement state, and installed artifact. Each rule should have one implementation and each side effect an explicit caller. Address the following issues in relevant changes or document a concrete compatibility reason. A promise to unify code later does not justify new duplication.
+
+| Signal | Problem | Preferred treatment |
+| --- | --- | --- |
+| Copied and renamed clients, recall implementations, or doctors | Fixes require multiple edits and behavior diverges | Move rules into the existing capability module; pass host parameters |
+| A field appears in several default tables | Configuration, diagnostics, and execution disagree | Declare it in the schema and derive other views |
+| A setting is read but never consumed | User changes have no effect | Trace actual execution; do not advertise unsupported behavior |
+| Shared functions repeatedly branch on harness names | Shared code is taking ownership of host protocols | Move event, format, and policy differences into adapters |
+| Several boolean options eliminate only a few repeated lines | Callers must understand incompatible modes and invalid combinations | Use small callbacks or retain short, direct host code |
+| One `utils.mjs` handles parsing, networking, and commits | Rules lack ownership and tests are hard to isolate | Split by capability and keep parsing mostly pure |
+| A loader writes files or starts services while reading config | Calling it again changes the system | Move actions into explicit installation or lifecycle entrypoints |
+| An ambiguous `true` means handled | Delivery, queueing, and skipping cannot be distinguished | Return explicit results with errors and acknowledgement counts |
+| A catch returns success or an empty array | Unreadable files and authentication failures look like no data | Preserve failure categories and let the host entrypoint choose a valid fallback |
+| Global state represents the current session | Concurrent windows and subagents overwrite each other | Key state by session and pass the current identity |
+| `export *` and multiple layers of same-name forwarding | The implementation being called is unclear | Use explicit imports/exports and remove wrappers without compatibility value |
+| Comments promise reliable commits while code only calls `spawn()` | Documentation hides unacknowledged effects | Document recovery conditions and verify completion through state |
+| Shared copies or generated type declarations are edited manually | The next sync overwrites the fix | Edit the authoritative source and regenerate |
+| Release scripts list every shared file manually | New dependencies are missed until installation | Validate dependency closures and manifests |
+| Stale designs, unused scripts, and copied tests remain | Search results mislead maintainers and duplicated tests inflate coverage | Remove obsolete references and files; keep history in Git |
+
+Name functions and variables after actions and states: `parseTranscript`, `sent`, `queued`, and `commitAccepted` are useful; `handleEverything`, `done`, and `successLike` hide meaning. Comments should explain host constraints, data invariants, and tradeoffs rather than repeat the next line. Document why a wrapper exists if it only supports logging or compatibility.
+
+Similar code is not necessarily equivalent. Calling the same builder does not prove hooks and MCP use identical credential projections. Verify observable behavior before fixing or preserving a difference. Do not turn every line of a reference plugin into a requirement.
+
+## 10. Implementation sequence for a new plugin
+
+1. **Record the host contract.** Establish the facts in section 2, the support matrix, minimum versions, substitutes for absent events, session IDs, and commit timing.
+2. **Choose the integration form.** Prefer adding a thin-host adapter. Create a separate package only for actual distribution or lifecycle requirements, and document the choice.
+3. **Connect configuration and MCP first.** Register the host ID, use the shared builder and proxy, verify paths, environment, and authentication under real startup conditions, and drive hooks from the same configuration.
+4. **Connect automatic reads.** Adapt startup profile and per-turn recall events and outputs. Verify disabled, bypass, empty-result, and network-failure behavior.
+5. **Connect reliable writes.** Implement transcript decoding, stable identity, incremental cursors, acknowledgement updates, commits, and recovery. Prioritize disconnections, duplicate events, and missing tail messages.
+6. **Add supported host features.** Add URI guards, skills, and diagnostics where supported. Do not add empty handlers for events that do not exist.
+7. **Complete installation and distribution.** Register generation targets, installers, archives/marketplaces, version checks, and release workflows. Package entrypoints must run directly.
+8. **Verify and document.** Reuse existing contract tests, verify host differences, smoke-test final artifacts, and record tested versions, platforms, and limits.
+
+Each step needs an inspectable result. A created directory or working tool list is not a complete integration. Work may be split into independent commits, but each commit should have explainable behavior and preserve existing integrations.
+
+## 11. Testing and acceptance evidence
+
+Test observable contracts and major failure cases. Follow the contribution guidelines: prefer extending existing high-value tests instead of mechanically adding unit tests for forwarding code, new files, or configuration lines. Test shared capabilities once; host tests cover wiring and differences. Do not copy entire recall, pending, or MCP suites.
+
+Put common helpers in [`testing/support.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/testing/support.mjs). Do not import helpers from other test files or place them in the runtime `lib/`. Use private temporary directories, isolated configuration and pending paths, and dynamic ports. Installation tests must not modify developers' live agent configuration or share a directory that another test's generator rewrites.
+
+| Area | Behavior to verify | Existing entrypoints |
+| --- | --- | --- |
+| Configuration and switches | Layer precedence, alias conflicts, invalid values, configured flags, no new network effects when disabled | `plugin-config.test.mjs`, `plugin-known-keys.test.mjs`, host config tests |
+| Credentials and peers | Matching hook/MCP request identity; custom paths, profile switching, multiple workspaces | `credentials.test.mjs`, `wire-headers.test.mjs`, `mcp-proxy-config.test.mjs` |
+| Hook output | Real payloads, one valid response, empty results, missing/unknown fields, failures | `agent-hook-runtime.test.mjs`, host event tests |
+| Recall | Switches, bypass, empty results, server compatibility, compression failure, readable URIs | `recall-core.test.mjs`, host recall tests |
+| Capture | Complete text/tools, repeated events and text, nested tools, partial success, truncation recovery | `capture-utils.test.mjs`, `batch-send.test.mjs`, host transcript tests |
+| State and commits | Concurrent Stop/End, failed workers, resume versus old end markers, unreadable tails, enqueue failure, retained commit parameters | `pending-queue.test.mjs`, Codex session tests, host recovery tests |
+| MCP | Initialize, protocol versions, notifications, SSE, expired-session recovery, error semantics, stdout | `mcp-proxy-core.test.mjs`, plus host startup smoke tests |
+| Installed artifacts | Fresh/repeated installs, preserved third-party config, invalid config not overwritten, complete uninstall, dependency closures | `install-agent-hooks.test.mjs`, `release-marketplace.test.mjs`, `sync.test.mjs` |
+| Maintenance constraints | One header implementation, matching schema/consumers, correct generated-file tracking | `one-header-builder.test.mjs`, `plugin-known-keys.test.mjs`, `sync.test.mjs` |
+
+Filenames are relative to the shared library unless a host is specified. Use [PR CI](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/pr.yml) and each package's scripts for complete commands; do not create another manually maintained repository-wide test inventory. Source-structure checks protect important single-implementation constraints, but do not replace behavioral tests or justify pinning unrelated helper names or line counts.
+
+For example, after changing shared configuration and MCP contracts, run focused checks from the repository root, followed by affected host tests:
+
+```bash
+node examples/memory-plugin-shared/sync.mjs
+node --test \
+ examples/memory-plugin-shared/plugin-config.test.mjs \
+ examples/memory-plugin-shared/credentials.test.mjs \
+ examples/memory-plugin-shared/mcp-proxy-config.test.mjs \
+ examples/memory-plugin-shared/mcp-proxy-core.test.mjs
+```
+
+Installer and marketplace tests generate runtime files and assemble installations. Run them separately and serially, as CI does:
+
+```bash
+node --test --test-concurrency=1 \
+ examples/memory-plugin-shared/install-agent-hooks.test.mjs \
+ examples/memory-plugin-shared/release-marketplace.test.mjs
+```
+
+CI currently uses Node.js 24, and some TypeScript tests rely on native type stripping. Document the test environment separately from the minimum plugin runtime version. Passing Node.js tests does not establish that Windows detach behavior, path quoting, or process cleanup works. State untested platforms rather than substituting an overall green test count for verification scope.
+
+Acceptance evidence should identify the artifact, host version, scenario, and observation. For writes, confirm complete tail messages and the corresponding commit reached the server. For installation, confirm extracted entrypoints can resolve their dependencies. Documentation-only changes need syntax, relative-link, symbol-reference, and example checks; they do not require the entire plugin suite.
+
+## 12. Maintenance, releases, and documentation
+
+### 12.1 Follow through by change type
+
+| Change | Required follow-up |
+| --- | --- |
+| Shared behavior fix | Edit the authoritative module, verify affected hosts, generate copies, inspect relevant artifacts and versions |
+| Host payload or event update | Update adapter, real-format fixtures, minimum-version/fallback notes; preserve other hosts' defaults |
+| New setting | Schema, actual consumer, configured semantics, diagnostic source, user documentation; parsing alone is insufficient |
+| New shared dependency | Colocated types where needed, sync closure, `lib/MANIFEST`, archive and offline installation validation |
+| Directory or package rename | Imports, manifests, installer, marketplace, CI path filters, skills, links, uninstall identification |
+| Compatibility removal | Supported versions and migration notes; preserve configuration aliases still promised to users |
+| Documentation only | Accuracy and working links; do not change unrelated behavior to update prose |
+
+Start a fix from the failing behavior and its owning module. A shared defect exposed by one host still belongs in shared source; a payload change unique to one host belongs in that adapter. Split large refactors into independently verifiable, reversible steps rather than combining behavior changes, historical cleanup, and distribution changes into one replacement with unclear causes.
+
+### 12.2 Versions and releases
+
+Versions determine whether users receive updates. A new plugin must join the applicable version checks and release workflow, not merely add a directory. [`check-plugin-version-bumps.sh`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-plugin-version-bumps.sh) counts shared `lib/` changes for every plugin it registers. That is not proof that all distribution targets are covered automatically. Check registration whenever adding or changing a target.
+
+Keep host manifests, `package.json`, root package versions in existing lockfiles, installation manifests, and installer version checks consistent. Use the package manager's versioning workflow without rewriting unrelated dependencies. `User-Agent` and doctor output should report the actual artifact version, so an apparently upgraded installation does not run old code.
+
+npm/archive builds must generate shared files from clean source before packaging. The current [`plugin-npm-release.yml`](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/plugin-npm-release.yml) matrix covers DSH and OpenCode. Check other packages' release paths individually; sharing a prepack command does not mean they are in that matrix. Release triggers must include shared source changes rather than depend on diffs in generated copies that are no longer committed.
+
+Before merge, check versions against the actual base. For example, when local `origin/main` is current and is the target branch:
+
+```bash
+bash .github/scripts/check-plugin-version-bumps.sh origin/main
+git diff --check
+git status --short --untracked-files=normal -- examples agent-plugins
+```
+
+The version check identifies changes through committed `base...HEAD`; it does not treat uncommitted work as a complete pull request. Run the final check against the final commit. Inspect generated untracked files as well as `git diff`. After release, verify the package and version users actually download; a started CI run is not completion.
+
+### 12.3 Documentation is part of the interface
+
+A plugin README should include supported capabilities and versions, the quickest usable installation method, credential sources, automatic behavior versus MCP, core switches, limitations, upgrade/removal, diagnostics, and test entrypoints. Start user installation instructions with a directly usable one-command option. Keep GUI steps separate rather than mixing CLI commands or TOML configuration into a GUI procedure.
+
+User integration guides and this standard live in `docs/{en,zh}/agent-integrations/`; maintain corresponding English and Chinese pages together. If a host also has mirrored instructions in `docs/images/agents/{en,zh}/`, check those too, without creating mirrors that do not otherwise exist. Link to the shared README for complete common configuration details and keep host pages focused on differences and common examples.
+
+Design documents should retain constraints, decisions, and recovery invariants that reading the code alone does not explain. Update support matrices, commands, and entrypoints when they change, and remove contradictory old guidance. Temporary investigations, one-off validation reports, and stale test counts are not long-term design documentation.
+
+## 13. Pre-merge checklist
+
+- [ ] Host versions, input/output formats, time limits, message sources, and end semantics have evidence; unsupported capabilities are explicit.
+- [ ] The integration form fits the host; new code mainly describes host differences, with no shared-to-host dependencies.
+- [ ] Configuration is declared once, switches affect execution, and actual hook/MCP connections and identity are verified.
+- [ ] Session and peer identities are distinct; multiple windows, resume, subagents, and cwd changes do not misuse state.
+- [ ] Capture preserves text and tool evidence; partial failure, offline queueing, duplicate events, and tail recovery do not advance cursors incorrectly.
+- [ ] Commit ordering and recovery ownership are clear, including a verified recovery path when exit workers fail.
+- [ ] Hook/MCP output is valid; URI guards, skills, and diagnostics promise only supported behavior.
+- [ ] Generation targets, installation, removal, archives, types, and release triggers are complete; the final artifact was tested.
+- [ ] Versions and related manifests agree; checks match the change and untested platforms/scenarios are documented.
+- [ ] Documentation and migration notes describe the final behavior, without new duplicate settings, old paths, or unused helper scripts.
+
+## 14. Maintainer reading guide
+
+Choose an entrypoint by the problem, instead of starting from generated plugin copies:
+
+- Supported behavior across integrations: [Capability Reference](./16-capability-reference.md).
+- Configuration, peers, and generation strategy: [Memory Plugin Shared README](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/README.md).
+- Claude Code event wiring: [hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json); recall adaptation: [auto-recall.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/scripts/auto-recall.mjs).
+- Codex commits, abnormal exits, and recovery: [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md); implementation: [session-end.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/scripts/session-end.mjs).
+- New configuration-file hosts: [agent-hook-plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md); strict protocol example: [ZCode DESIGN](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md).
+- CI and delivery checks: [pr.yml](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/pr.yml), [sync.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs), [marketplace archive checker](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-marketplace-archive.mjs).
diff --git a/docs/images/agents/en/cursor.md b/docs/images/agents/en/cursor.md
index 71d0c4063..6e0f2f457 100644
--- a/docs/images/agents/en/cursor.md
+++ b/docs/images/agents/en/cursor.md
@@ -28,4 +28,4 @@
## Reference
- Docs on Manual Settings: [Cursor](https://docs.openviking.net/en/agent-integrations/12-cursor)
-- Code: [examples/cursor-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/cursor-memory-plugin)
+- Code: [examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
diff --git a/docs/images/agents/en/trae.md b/docs/images/agents/en/trae.md
index f29f8a9a3..f3750a59b 100644
--- a/docs/images/agents/en/trae.md
+++ b/docs/images/agents/en/trae.md
@@ -35,4 +35,4 @@ Open **Settings → MCP → Configured MCP Servers** and confirm that the `openv
## Reference
- Docs on Manual Settings: [TRAE](https://docs.openviking.net/en/agent-integrations/13-trae)
-- Code: [examples/trae-memory-hooks](https://github.com/volcengine/OpenViking/tree/main/examples/trae-memory-hooks)
+- Code: [examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
diff --git a/docs/images/agents/zh/cursor.md b/docs/images/agents/zh/cursor.md
index 55f230f25..8e32162a2 100644
--- a/docs/images/agents/zh/cursor.md
+++ b/docs/images/agents/zh/cursor.md
@@ -28,4 +28,4 @@
## 参考
- 手动配置文档:[Cursor](https://docs.openviking.net/zh/agent-integrations/12-cursor)
-- 源码:[examples/cursor-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/cursor-memory-plugin)
+- 源码:[examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
diff --git a/docs/images/agents/zh/trae.md b/docs/images/agents/zh/trae.md
index 5b2a6847a..08081d5e5 100644
--- a/docs/images/agents/zh/trae.md
+++ b/docs/images/agents/zh/trae.md
@@ -35,4 +35,4 @@
## 参考
- 手动配置文档:[TRAE](https://docs.openviking.net/zh/agent-integrations/13-trae)
-- 源码:[examples/trae-memory-hooks](https://github.com/volcengine/OpenViking/tree/main/examples/trae-memory-hooks)
+- 源码:[examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 79fa671a7..e1591a0b7 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -25,6 +25,10 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
想知道各个集成在工具面、自动召回、会话与 commit、压缩接管、降级容错上的具体差异,见 [集成能力参考](./16-capability-reference.md)——一份覆盖全部集成的横向对照矩阵。
+## 开发与维护插件
+
+新增或维护集成时,请遵循 [Hook + MCP Agent 插件开发与维护规范](./18-plugin-development.md)。使用 VibeCoding 时,务必让 coding agent 在修改前阅读并遵循该规范;实现可以参考 Claude Code、Codex 和其他现有插件。
+
## 所有集成的共同前置
本页所有集成都需要连接到一个正在运行的 OpenViking 服务。如果你还没有,请先按 [快速开始](../getting-started/02-quickstart.md) 部署。默认端点是 `http://localhost:1933`;远程使用需要 API Key(参见 [鉴权](../guides/04-authentication.md))。
@@ -33,7 +37,7 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
查询扩展和召回结果压缩是两个独立的可选模型调用。需要优先保证响应速度时,可以在 Agent 插件端同时关闭它们;语义检索、预算控制、档位降级和跨轮去重仍会正常工作。
-下面这组环境变量同时适用于 Claude Code 和 Codex。查询扩展在 OpenCode 和 pi 上同样可以关闭;压缩只有 Claude Code 和 Codex 支持。
+下面这组环境变量同时适用于 Claude Code 和 Codex。查询扩展在所有经共享加载器解析配置的记忆插件上都可以关闭;压缩只有 Claude Code 和 Codex 支持。
```bash
export OPENVIKING_RECALL_QUERY_EXPANSION=off
@@ -62,6 +66,6 @@ export OPENVIKING_RECALL_COMPRESS=off
环境变量优先于 `ovcli.conf`。修改后重启对应的 Agent,让 hook 进程重新加载配置。上述设置属于插件客户端,不需要修改服务端的 `ov.conf`。
-`plugin` 段目前由 Claude Code 和 Codex 插件读取,因此以其他 harness 命名的 `plugin` 条目当前不生效。OpenCode 和 pi 支持用环境变量 `OPENVIKING_RECALL_QUERY_EXPANSION`(或各自配置文件里的 `recallQueryExpansion`)关闭查询扩展,但不支持 `OPENVIKING_RECALL_COMPRESS`——这两个 harness 不会请求服务端 digest。
+`plugin` 段由每个记忆插件读取——claude-code、codex、cursor、trae、trae-cn、zcode、opencode、dsh 和 pi;`plugin.<harness>` 对象只覆盖其中某一个 harness 的共享键,两种写法都认(`claude_code` 或 `claude-code`、`trae_cn` 或 `trae-cn`)。压缩是例外:其余 harness 认 `recallQueryExpansion`,但忽略 `recallCompress` 及其配套项——它们都不会请求服务端 digest。
context 请求的等待时间比普通请求更长,因为客户端提前中断会丢掉整个响应,而不只是超时的那一段。服务端流水线是串行的,每个可选阶段各有保险丝:先是查询扩展(`retrieval.recall_intent_timeout_s`,5 秒),然后是检索、正文读取和预算规划,最后才是 digest 重写(`retrieval.recall_rewrite_timeout_s`,30 秒)。因此这个上限按请求实际启用的阶段决定——带 session、会走查询扩展时取 15 秒,同时还要 digest 时取 45 秒,两者都不涉及时沿用插件自身的普通超时。可以用 `OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS`(或 `plugin.recallContextTimeoutMs`)指定这个上限,取值应高于该请求会用到的保险丝、低于 Agent 自身的 hook 超时。
diff --git a/docs/zh/agent-integrations/08-community-plugins.md b/docs/zh/agent-integrations/08-community-plugins.md
index e2d3186ce..48e187995 100644
--- a/docs/zh/agent-integrations/08-community-plugins.md
+++ b/docs/zh/agent-integrations/08-community-plugins.md
@@ -4,7 +4,7 @@
## ZCode 记忆集成
-源码:[examples/zcode-memory-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin)
+源码:[examples/agent-hook-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin)
ZCode 社区集成通过配置驱动的生命周期 Hook 和 OpenViking MCP 服务提供跨项目、跨会话记忆:
@@ -45,7 +45,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
| MCP 工具未出现 | MCP proxy 启动失败 | 检查 `~/.zcode/cli/config.json` 中 `mcp.servers.openviking` 的绝对路径命令 |
| 重复捕获 | 旧安装留下了重复 Hook 条目 | 先运行 `install.sh --harness zcode --uninstall`,再重新安装 |
-实现细节与当前已验证的 ZCode 假设见插件目录中的 [README](https://github.com/volcengine/OpenViking/tree/main/examples/zcode-memory-plugin) 和 [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/zcode-memory-plugin/DESIGN.md)。
+实现细节与当前已验证的 ZCode 假设见插件目录中的 [README](https://github.com/volcengine/OpenViking/tree/main/examples/agent-hook-plugin) 和 [DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md)。
## AstrBot 插件
diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.md
index 461bfb9ee..93518bf6a 100644
--- a/docs/zh/agent-integrations/10-opencode.md
+++ b/docs/zh/agent-integrations/10-opencode.md
@@ -97,29 +97,32 @@ cp -r examples/opencode-plugin/servers ~/.config/opencode/plugins/openviking/
node examples/opencode-plugin/scripts/setup.mjs
```
-`~/.config/opencode/openviking-config.json` 现在只放行为旋钮:
+行为旋钮写在 `~/.openviking/ovcli.conf` 的 `plugin` 段,与向导写入的连接字段同一个文件。共享键对所有记忆插件生效;`plugin.opencode` 下的键只对本插件生效,并覆盖共享键:
```json
{
- "enabled": true,
- "timeoutMs": 30000,
- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },
- "autoRecall": {
- "enabled": true,
- "limit": 6,
+ "plugin": {
+ "recallLimit": 6,
"scoreThreshold": 0.35,
- "maxContentChars": 500,
- "preferAbstract": true,
- "tokenBudget": 2000,
- "minQueryLength": 3
- },
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000
+ "recallMaxContentChars": 500,
+ "recallPreferAbstract": true,
+ "recallTokenBudget": 2000,
+ "minQueryLength": 3,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000,
+ "opencode": {
+ "timeoutMs": 30000,
+ "repoContext": true,
+ "repoContextCacheTtlMs": 60000
+ }
+ }
}
```
+配置项按优先级从高到低解析:`OPENVIKING_*` 环境变量、工作区的 `.openviking/config.json` 与 `config.local.json`、`plugin.opencode`、`plugin`,最后是内置默认值。`autoRecall: false` 关闭自动召回,`autoCapture: false` 让插件不再回写对话。
+
环境变量优先级高于 `ovcli.conf`:
```bash
@@ -129,7 +132,7 @@ export OPENVIKING_USER="opencode" # 可选,仅 trusted-mode 部署需要
export OPENVIKING_PEER_ID="opencode" # 可选,peer 维度记忆路由需要
```
-API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`account` 和 `user` 是 trusted-mode headers;`peerId` 会作为 `X-OpenViking-Actor-Peer` 和捕获 session message 的 `peer_id` 使用。旧版 `openviking-config.json` 里的凭据字段仍会作为迁移 fallback 读取,但新安装建议使用 `ovcli.conf` 或环境变量。
+API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`account` 和 `user` 是 trusted-mode headers;`peerId` 会作为 `X-OpenViking-Actor-Peer` 和捕获 session message 的 `peer_id` 使用。
## 验证
@@ -152,9 +155,9 @@ API key 会由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送;`
| 问题 | 排查方向 |
|------|----------|
| 插件没有加载 | 确认 `~/.config/opencode/opencode.json` 引用了 `@openviking/opencode-plugin`;源码安装时确认 `~/.config/opencode/plugins/openviking.js` 存在 |
-| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量 / `OPENVIKING_PLUGIN_CONFIG` 指向正确配置 |
+| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量;`OPENVIKING_CLI_CONFIG_FILE` 可让插件改读另一份 ovcli.conf |
| OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |
-| recall 为空 | 确认 OpenViking server 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |
+| recall 为空 | 确认 OpenViking server 中已有 memories/resources,且 `autoRecall` 没有被设成 `false` |
| 本地 `openviking_add_resource` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |
完整 tools、配置字段和运行时文件说明见 [插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)。
diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.md
index 963f89262..d8cbb7f49 100644
--- a/docs/zh/agent-integrations/11-pi.md
+++ b/docs/zh/agent-integrations/11-pi.md
@@ -35,7 +35,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/e
bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh)
```
-安装器会把扩展复制到 `~/.pi/agent/extensions/openviking`(保留已有的 `config.json`),用 `pi install` 完成注册,并配置 `~/.openviking/ovcli.conf`。
+安装器会把扩展复制到 `~/.pi/agent/extensions/openviking`,用 `pi install` 完成注册,并配置 `~/.openviking/ovcli.conf`。
也可以从仓库 checkout 手动复制:
@@ -55,34 +55,37 @@ pi install ~/.pi/agent/extensions/openviking
node ~/.pi/agent/extensions/openviking/scripts/setup.mjs
```
-`~/.pi/agent/extensions/openviking/config.json` 保存行为与 peer 作用域配置,重装时会保留你的修改。连接和认证凭据仍来自上面的共享配置源:
+行为与 peer 作用域旋钮写在 `~/.openviking/ovcli.conf` 的 `plugin` 段,与其他记忆插件共用。`plugin.pi` 下的键只对本扩展生效,并覆盖共享键;连接和认证凭据仍来自上面的配置源:
```json
{
- "peerId": "",
- "workspacePeer": true,
- "peerSource": "git",
- "recallPeerScope": "all",
- "scoreThreshold": 0.35,
- "recallTokenBudget": 2000,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000,
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "takeover": {
- "enabled": true,
- "tokenThreshold": 30000,
- "keepRecentTurns": 3,
- "overviewBudget": 3000,
- "overviewPollMs": 2000,
- "overviewPollMax": 15
- },
- "captureAssistantTurns": true,
- "bypassPatterns": []
+ "plugin": {
+ "recallPeerScope": "all",
+ "scoreThreshold": 0.35,
+ "recallTokenBudget": 2000,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "captureAssistantTurns": true,
+ "pi": {
+ "workspacePeer": true,
+ "peerSource": "git",
+ "takeoverEnabled": true,
+ "takeoverTokenThreshold": 30000,
+ "takeoverKeepRecentTurns": 3,
+ "takeoverOverviewBudget": 3000,
+ "takeoverOverviewPollMs": 2000,
+ "takeoverOverviewPollMax": 15,
+ "bypassSessionPatterns": []
+ }
+ }
}
```
-`OPENVIKING_PEER_ID`、`ovcli.conf` 或 `ov.conf` 中的显式 peer 优先于 `config.json` 的 `peerId`;本地 `peerId` 又优先于 workspace 派生值。只有启用 `workspacePeer` 且所有显式来源都未提供 peer 时,才会从工作区派生。
+配置项按优先级从高到低解析:`OPENVIKING_*` 环境变量、工作区的 `.openviking/config.json` 与 `config.local.json`、`plugin.pi`、`plugin`,最后是内置默认值。`autoCapture: false`(本扩展的旧拼写是 `syncTurns`)让它不再回写对话,`autoRecall: false` 让它不再检索。
+
+`OPENVIKING_PEER_ID` 优先于所有配置文件。在它之下,更具体的一层胜出:workspace 的 `peer.id` 和 `plugin` 段里写的 `peerId` 都优先于 `ovcli.conf` 的 `actor_peer_id` 和 `ov.conf` 的 `pi.peerId`。任何一层给出的显式 peer 又都优先于 workspace 派生值。只有启用 `workspacePeer` 且所有层都未给出 peer 时,才会从工作区派生。
`peerSource` 决定 workspace peer 的派生方式。默认的 `"git"` 取仓库归一化后的 `origin` URL(`[email protected]:volcengine/OpenViking.git` 得到 `github.com-volcengine-openviking`),其次是仓库根路径,因此同一个仓库的每个 clone、worktree 和子目录共用同一个 peer;不在仓库中则完全不发送 peer,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。`"cwd"` 恢复此前的行为——把工作目录路径中的非字母数字字符全部替换成 `-`;`"none"`(等同于 `OPENVIKING_WORKSPACE_PEER=0`)完全不发送 peer;也可以用 `"team-{dir}"` 这样的模板,或按顺序尝试的模板列表自定义。要让仓库之外的目录拥有独立记忆,请为它设置 `OPENVIKING_PEER_ID`(见[让一个目录拥有独立记忆](../configuration/02-client.md#让一个目录拥有独立记忆))。
diff --git a/docs/zh/agent-integrations/12-cursor.md b/docs/zh/agent-integrations/12-cursor.md
index cb0a6766c..edaf9d506 100644
--- a/docs/zh/agent-integrations/12-cursor.md
+++ b/docs/zh/agent-integrations/12-cursor.md
@@ -31,7 +31,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
## 验证
1. 重启 Cursor 并新建 Agent 会话。
-2. 打开 **Cursor Settings → Hooks**,确认 OpenViking 生命周期 Hook 执行了 `cursor-hook.mjs`,URI 保护 Hook 执行了 `uri-guard.mjs`。
+2. 打开 **Cursor Settings → Hooks**,确认 OpenViking 生命周期 Hook 执行了 `scripts/hook.mjs`,URI 保护 Hook 执行了 `scripts/uri-guard.mjs`。
3. 查看 `beforeSubmitPrompt` 输出,确认存在 `additional_context`;这表示当前问题的召回结果已直接交给 Agent,无需先调用 MCP。
4. 打开 **Cursor Settings → Tools & MCPs**,确认 `openviking` 已连接。
5. 告诉 Cursor 一个临时偏好,等待本轮回复完成;新建会话后询问该偏好,确认捕获和跨会话召回均生效。
diff --git a/docs/zh/agent-integrations/15-agent-plugins.md b/docs/zh/agent-integrations/15-agent-plugins.md
index f47b7ff67..a9a837550 100644
--- a/docs/zh/agent-integrations/15-agent-plugins.md
+++ b/docs/zh/agent-integrations/15-agent-plugins.md
@@ -12,7 +12,6 @@ agent-plugins/
├── mcp.json # 一个 stdio MCP server:"openviking"
├── servers/
│ ├── mcp-proxy.mjs # stdio -> streamable-HTTP 代理,转发到服务端 /mcp
-│ ├── config.mjs, debug-log.mjs # 凭据 / 配置解析
│ └── shared/ # 由 examples/memory-plugin-shared/lib 生成
├── skills/openviking-memory/SKILL.md # 教模型完成「召回 + 沉淀」闭环
└── plugin.test.mjs # node --test 规范一致性校验
@@ -36,10 +35,15 @@ OpenViking 服务端本身在 `/mcp` 上就是 streamable HTTP,但 `mcp.json`
从高到低 —— 与 `ov` CLI 及其他 OpenViking 插件完全一致:
-1. 环境变量:`OPENVIKING_URL`(或 `OPENVIKING_BASE_URL`)、`OPENVIKING_API_KEY`(或 `OPENVIKING_BEARER_TOKEN`)、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`
-2. `~/.openviking/ovcli.conf`(`url`、`api_key`、`account`、`user`)—— 可用 `OPENVIKING_CLI_CONFIG_FILE` 覆盖路径
-3. `~/.openviking/ov.conf` 的 `server` 段(`url`,或 `host` / `port`,以及 `root_api_key`)—— 可用 `OPENVIKING_CONFIG_FILE` 覆盖路径
-4. 默认值:`http://127.0.0.1:1933`,不鉴权(本地模式)
+1. 环境变量:`OPENVIKING_URL`(或 `OPENVIKING_BASE_URL`)、`OPENVIKING_MCP_URL`、`OPENVIKING_API_KEY`(或 `OPENVIKING_BEARER_TOKEN`)、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`
+2. `~/.openviking/ovcli.conf`(`url`、`api_key`、`account` / `account_id`、`user` / `user_id`、`actor_peer_id` / `peer_id`)—— 可用 `OPENVIKING_CLI_CONFIG_FILE` 覆盖路径
+3. `~/.openviking/ov.conf` 的 `agent_plugins` 段(`apiKey`、`accountId`、`userId`、`peerId`)—— 可用 `OPENVIKING_CONFIG_FILE` 覆盖路径
+4. `~/.openviking/ov.conf` 的 `server` 段(`url`,或 `host` / `port`,以及 `root_api_key`)
+5. 默认值:`http://127.0.0.1:1933`,不鉴权(本地模式)
+
+`OPENVIKING_MCP_URL` 覆盖的是推导出的 `<url>/mcp` 端点,而不是 base URL。
+
+`OPENVIKING_CREDENTIAL_SOURCE`(或 `OPENVIKING_CREDENTIALS_SOURCE`)把整条链钉在某一端:`env` 只认环境变量,`cli`(同义写法还有 `ovcli` / `file` / `config`)只认 ovcli.conf。默认的 `auto` 在 ovcli.conf 带凭据、且上面这些环境变量一个都没设时钉向 ovcli.conf,否则按整条链解析。钉在 ovcli.conf 时,环境变量、`OPENVIKING_MCP_URL` 和 `agent_plugins` 段都会被跳过;只有 `server.root_api_key` 仍然生效——ovcli.conf 自己没有 api_key 时由它兜底,这样一份只写了 `url` 的旧安装仍然能用原来的 key。
```json
// ~/.openviking/ovcli.conf
diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md
index f83033d43..9366429aa 100644
--- a/docs/zh/agent-integrations/16-capability-reference.md
+++ b/docs/zh/agent-integrations/16-capability-reference.md
@@ -42,7 +42,7 @@
¹ MCP `write` 的可写域是 `viking://resources|user|agent`,暂不支持 MCP 新增 skill;新增 skill 的入口是 openclaw `add_skill`、`ov add-skill` 与 REST。
² MCP `forget` 不区分 memory/resource/skill 类型;存储层保留了命名空间根保护机制(裸 `viking://`、`viking://user`、`viking://agent` 根拒删),详见 [§3.5](#_3-5-写入与删除的类型边界)。
³ pi 的 `viking_forget`:其 `recursive` 参数固定为 false(不删除目录),按 query 删除要求匹配分 >0.8。
-⁴ pi 工具注册前置:需未命中 bypassPatterns、`client.health()` 通过、`ensureSession` 成功(`index.ts:66-113`);health 未通过时本轮不注册工具面。
+⁴ pi 工具注册前置:需未命中 `bypassSessionPatterns`、`client.health()` 通过、`ensureSession` 成功(`index.ts:66-108`);health 未通过时本轮不注册工具面。
⁵ openclaw 的 `add_resource` 需经过双重 opt-in 后方可开启。
**skill 的增删边界**:新增入口包含 openclaw `add_skill`(默认开)、`ov add-skill` 与 REST;删除边界分四档,详见 [§3.5](#_3-5-写入与删除的类型边界)。
@@ -52,7 +52,7 @@
| harness | 接入方式 | 自动召回 | 召回带 session_id | 再摘要(客户端)* | profile 注入 | 接管宿主压缩 | 离线补偿(pending queue) | statusline |
|---|---|---|---|---|---|---|---|---|
| claude-code | 9 hook + MCP 代理 + slash + statusline + skill | ✅ | ✅ | ✅ 本地 `claude -p` / 服务端 rewrite(默认 auto) | ✅(10000) | ❌(PreCompact 只 commit) | ✅ | ✅ |
-| codex / trae-cli | 4 hook + MCP 代理 + skill | ✅ | ✅ | ✅ 本地 `codex exec`(默认开) | ✅(10000) | ❌ | ❌ 无磁盘队列(靠游标不推进、下一轮重发补偿) | ❌ |
+| codex / trae-cli | 5 hook + MCP 代理 + skill | ✅ | ✅ | ✅ 本地 `codex exec`(默认开) | ✅(10000) | ❌ | ✅ | ❌ |
| cursor | 7 hook + MCP 代理 + rule + skill | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |
| trae / trae-cn | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |
| zcode | 4 hook + MCP 代理 | ✅ | ✅ | ❌ | ✅(6000) | ❌ | ✅ | ❌ |
@@ -111,33 +111,35 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
## 2.2 memory-plugin-shared 共享层
-`examples/memory-plugin-shared/lib/` 下共 24 个 `.mjs` 模块,是 JS 系 harness 的唯一事实源。两种消费形态:
+`examples/memory-plugin-shared/lib/` 下共 25 个 `.mjs` 模块,是 JS 系 harness 的唯一事实源。两种消费形态:
-1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1,交叉读行号引用时要换算)。每个目标只发它真正 import 的模块,因此分发清单跟的是 import 图而不是 harness。在每个 hook 型插件都会拿的 13 个 hook 模块(`sync.mjs` 里的 `HOOK_SHARED_FILES`)之上:pi 加 setup-wizard 与 batch-send(15 个);dsh 加 stdio 代理需要的两个 mcp-proxy-*(15 个);opencode 加 setup-wizard、两个 mcp-proxy-* 与 batch-send(17 个);zcode 加两个 mcp-proxy-*、batch-send、async-writer、agent-hook-runtime 与 agent-uri-guard(19 个);claude-code / codex 加 setup-wizard、两个 mcp-proxy-*、batch-send、async-writer、plugin-config、workspace-config、workspace-registry 与 doctor-core(各 22 个)。agent-plugins 没有 hook,因此一个 hook 模块都不拿,只有 credentials、debug-log 与两个 mcp-proxy-*(4 个)。当前 HEAD 各目标与 lib 源零漂移。
-2. **相对路径直接 import(不复制)**:cursor / trae / trae-cn 直接 `import "../../memory-plugin-shared/lib/..."`;安装器把包与这些 hook 传递 import 到的 15 个共享模块一起复制到 `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`,使相对层级成立。这份安装集合对 import 闭合,不含任何 hook 运行时都够不到的 workspace 配置层。运行期这个共享目录被这几个 harness 共用,任一重装都会整体覆盖。
+1. **Vendoring(复制)**:由 `sync.mjs` 分发到 7 个目标,每个文件首行加 `// GENERATED FROM ... DO NOT EDIT.`(因此 vendored 副本行号 = lib 源行号 + 1)。分发清单不再手写:每个目标拿的是自身代码实际 import 的传递闭包。claude-code、codex、agent-plugins 由宿主直接指向仓库目录安装,所以生成副本提交进 git,并由 main 上的推送重新生成;opencode、dsh、openclaw 以 npm 包发布,pi 由安装脚本打包,这四个在打包时生成副本,git 中不保留。
+2. **相对路径直接 import(不复制)**:cursor / trae / trae-cn / zcode 直接 `import "../../memory-plugin-shared/lib/..."`;安装器把包与这些 hook 传递 import 到的共享模块一起复制到 `~/.openviking/agent-integrations/{<client>,memory-plugin-shared}/`,保持相对层级。这份安装集合对 import 闭合,包括 hook 运行时所需的 workspace 配置层。运行期几个 harness 共用该目录,任一重装都会整体覆盖。
核心模块速览(细节在各维度章展开):
| 模块 | 职责 | 消费方 |
|---|---|---|
| `recall-core.mjs` | 召回请求构造 + 三级降级 + 本地兜底排序注入 | 全部 JS 系 harness |
-| `agent-hook-runtime.mjs` | "瘦 hook"一体化运行时(配置面 19 个 env、session id 派生、跨进程锁、fetch、commit) | cursor / trae / trae-cn / zcode |
+| `agent-hook-runtime.mjs` | "瘦 hook"一体化运行时(配置经共享 schema 解析、session id 派生、跨进程锁、fetch、commit) | cc / codex / cursor / trae / trae-cn / zcode |
| `mcp-proxy-core.mjs` | stdio↔streamable-HTTP MCP 代理内核 | 全部 MCP 型 + agent-plugins |
-| `pending-queue.mjs` | 磁盘离线队列 + 会话启动重放 | cc / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `ov-http.mjs` | hook 到 OpenViking 服务端的唯一出网路径:请求头、AbortController、信封解析 | 全部 JS 系 + agent-plugins |
+| `pending-queue.mjs` | 磁盘离线队列 + 会话启动重放 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
| `batch-send.mjs` | 100 条/批写入 + 404/405 逐条降级 + 连续前缀入队 | cc / codex / opencode + agent-hook 系 |
| `profile-inject.mjs` | session-start 的 profile + 可用记忆清单注入 | 9 个 harness(openclaw / hermes 除外) |
| `recall-compress-core.mjs` | 召回压缩 prompt + URI 编辑距离修复 + 缓存 | claude-code |
-| `capture-utils.mjs` | 消息归一 + 注入回流防护 + 内置捕获启发式(应答语、slash 命令、信息量下限) | codex / opencode / dsh / pi / zcode |
-| `input-filters.mjs` | 编译并执行操作员自己配的 sed 风格规则 —— `s` 替换、`d` 丢弃、`k` 仅保留,可限定角色 —— 作用于召回 query 与每个被捕获的回合;解析失败的规则会被报告并跳过,不抛异常([语法](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#输入过滤器)) | 每个 hook 插件都会 vendoring;`recallQueryFilters` / `captureFilters` 两个 knob 目前由 claude-code / codex 提供 |
+| `capture-utils.mjs` | 消息归一 + 注入回流防护 + 内置捕获启发式(应答语、slash 命令、信息量下限) | cc / codex / opencode / dsh / pi / zcode / cursor / trae×2 |
+| `input-filters.mjs` | 编译并执行操作员自己配的 sed 风格规则 —— `s` 替换、`d` 丢弃、`k` 仅保留,可限定角色 —— 作用于召回 query 与每个被捕获的回合;解析失败的规则会被报告并跳过,不抛异常([语法](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#输入过滤器)) | 所有 hook 插件;`recallQueryFilters` / `captureFilters` 两个 knob 目前由 claude-code / codex 提供 |
| `credentials.mjs` | 凭据解析链(详见 [§3.1.3](#_3-1-3-凭据体系)) | 全部 JS 系 |
| `session-model.mjs` | 会话 id 前缀派生 + bypass glob | 全部 JS 系 |
| `async-writer.mjs` | 写路径 detach(drain stdin → spawn → approve → write → unref;spawn 失败回落同步) | cc / codex / zcode |
| `workspace-peer.mjs` | 按 `peer.source` 解析 actor peer(预设 / 模板 / 保留用于双读的旧 peer id,详见 [§3.1.3](#_3-1-3-凭据体系)) | 全部 JS 系 |
| `workspace-identity.mjs` | workspace 根目录 + git 身份(归一化 `origin`、仓库根路径、worktree/submodule 类型),纯文件系统上溯、不起 `git` 子进程,按 cwd 缓存 | 全部 JS 系 |
-| `workspace-config.mjs` | 分层 workspace 配置:读 `<root>/.openviking/config.json` 与 `config.local.json`,带来源(provenance)合并各层,剥离连接与凭据类 key | claude-code / codex |
-| `workspace-registry.mjs` | 每机注册表 `~/.openviking/workspaces/<slot>.json`——一个 workspace 一个文件,由人工创建、插件只读,优先级高于任何已提交的文件 | claude-code / codex |
-| `uri-guard.mjs` / `agent-uri-guard.mjs` | 拦截 `viking://` 被误当成本地路径的情况 | 各 harness 的 PreToolUse/tool.execute.before 类 hook |
-| `plugin-config.mjs` | ovcli.conf `plugin` 段读取 | claude-code / codex |
+| `workspace-config.mjs` | 分层 workspace 配置:读 `<root>/.openviking/config.json` 与 `config.local.json`,带来源(provenance)合并各层,剥离连接与凭据类 key | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `workspace-registry.mjs` | 每机注册表 `~/.openviking/workspaces/<slot>.json`——一个 workspace 一个文件,由人工创建、插件只读,优先级高于任何已提交的文件 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `uri-guard.mjs` | 拦截 `viking://` 被误当成本地路径的情况 | 各 harness 的 PreToolUse/tool.execute.before 类 hook |
+| `config-schema.mjs` | 全部旋钮的唯一声明:规范名、类型、默认值、取值范围、`OPENVIKING_*` 变量、可接受的旧拼写、workspace 键。doctor 的已知键集合与 workspace 文件的点分键映射都是它的投影 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
+| `plugin-config.mjs` | 按层解析全部已声明旋钮:env → workspace 各层 → ovcli.conf `plugin.<harness>` → ovcli.conf `plugin` → ov.conf 的 harness 段 → 默认值 | cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi |
| `setup-wizard.mjs` | 交互式写 ovcli.conf | cc / codex / opencode / pi 暴露入口 |
| `retryable.mjs` | 可重试判定:status 0/408/429/≥500,或 409 且 `error.details.retryable===true`;4xx(含 401/403)不重试 | 全部 JS 系 |
@@ -167,19 +169,19 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| claude-code | CC 插件(marketplace):包含 9 hook + MCP 代理 + slash + statusline + skill | 一键 `install.sh --harness claude`(支持现代 plugin 路径与 legacy `claude mcp add` 兼容路径)/ 手动 marketplace / TOS 镜像 | `cc-<CC session_id 原文>`;subagent 格式为 `…__subagent-<agent_id>` | env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code` | ✅ `scripts/setup.mjs` |
| codex | Codex 插件(marketplace):包含 4 hook + MCP 代理 + skill | 一键 `--harness codex` / `codex plugin marketplace add`(TOS 走 dumb-HTTP git 以保留远程更新能力) | `cx-<safeId>`(确定性推导,不读取 state) | env + ovcli.conf `plugin.codex` + ov.conf `codex` | ✅ |
| trae-cli | **codex 插件别名安装**(TraeCode CLI 2.0,仅支持 2.0;Codex 系:binary `traecli`、配置 `~/.trae/traecli.toml`;能力面与 codex 一致) | 一键 `--harness trae-cli`(复用 codex 安装流程;marketplace 命令会随指向的 binary 执行,如 `traecli plugin marketplace add`) | 与 codex 的派生规则一致 | 与 codex 一致(env + ovcli.conf `plugin.codex` + ov.conf) | ✅(同 codex) |
-| cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | 仅 env | ❌(共用安装器 TUI) |
-| trae / trae-cn | 配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json) | 一键 `--harness trae,trae-cn` | `tr-` / `trcn-` | 仅 env | ❌ |
-| zcode | 配置驱动(合并进 `~/.zcode/cli/config.json`,并强制 `hooks.enabled=true`) | 一键 `--harness zcode` | `zc-<sess_…>` | 仅 env | ❌ |
-| opencode | npm 插件 `@openviking/opencode-plugin`(config hook 自注入 MCP 条目) | 一键 `--harness opencode`(npm 注册 + 代理快照兜底)/ 手动 npm / 源码 | `oc-<id>`;subagent 格式为 `oc-<parent>__subagent-<child>` | `openviking-config.json`(4 级搜索)+ env | ✅ |
-| dsh | Cordis 同进程插件(`cordis.patch.yml` plugin group) | 统一安装器(会询问 profile,默认 `web`),或执行 `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id 原样>`;subagent 各自独立会话 | cordis patch config + 4 个 env(凭据优先级 patch>env,行为开关优先级 env>patch) | ❌ |
-| pi | pi 原生扩展(目录装载,jiti 直译 TS) | 一键 `--harness pi`(含 `pi install` 注册) | `pi-<piSessionId>` | `config.json`(凭据字段由凭据链统一解析)+ env | ✅ |
+| cursor | 配置驱动(写入 `~/.cursor/hooks.json`+`mcp.json`)+ rule + skill | 一键 `--harness cursor` | `cu-<conversation_id>` | env + ovcli.conf `plugin.cursor` | ❌(共用安装器 TUI) |
+| trae / trae-cn | 配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json) | 一键 `--harness trae,trae-cn` | `tr-` / `trcn-` | env + ovcli.conf `plugin.trae` / `plugin.trae_cn` | ❌ |
+| zcode | 配置驱动(合并进 `~/.zcode/cli/config.json`,并强制 `hooks.enabled=true`) | 一键 `--harness zcode` | `zc-<sess_…>` | env + ovcli.conf `plugin.zcode` | ❌ |
+| opencode | npm 插件 `@openviking/opencode-plugin`(config hook 自注入 MCP 条目) | 一键 `--harness opencode`(npm 注册 + 代理快照兜底)/ 手动 npm / 源码 | `oc-<id>`;subagent 格式为 `oc-<parent>__subagent-<child>` | env + ovcli.conf `plugin.opencode` | ✅ |
+| dsh | Cordis 同进程插件(`cordis.patch.yml` plugin group) | 统一安装器(会询问 profile,默认 `web`),或执行 `dsh plugin --profile web add @openviking/dsh-memory-plugin` | `dsh-<session.id 原样>`;subagent 各自独立会话 | env + ovcli.conf `plugin.dsh` + cordis patch config(行为旋钮的最低层;凭据仍以 patch 优先) | ❌ |
+| pi | pi 原生扩展(目录装载,jiti 直译 TS) | 一键 `--harness pi`(含 `pi install` 注册) | `pi-<piSessionId>` | env + ovcli.conf `plugin.pi`(凭据字段由凭据链统一解析) | ✅ |
| openclaw | context-engine 插件(`ownsCompaction:true`)+ 15 工具 + 5 slash + 4 hook + HTTP 路由 | ClawHub 执行 `openclaw plugins install clawhub:@openviking/openclaw-plugin` 搭配 `openclaw openviking setup` / npm 安装器 / TOS 离线包 | UUID 原样小写,否则 `sha256(sessionKey)`;`memory_store` 临时会话 `memory-store-<ts>-<rand>` | `openclaw.json` 的 `plugins.entries.openviking.config`(严格校验:存在未知键/非法值时插件进入 setup-only 模式)+ 少量 env | ✅ `openclaw openviking setup`(交互/非交互 + key 角色探测 + 版本兼容检查) |
| hermes | Hermes bundled MemoryProvider(随 Hermes 发布,无需装插件) | 执行 `hermes memory setup openviking`(curses 向导)或手动 `config set memory.provider openviking` + `.env` | 由 Hermes 生成 `%Y%m%d_%H%M%S_<hex6>`,插件原样使用 | `.env`(`OPENVIKING_*`)或 ovcli.conf 联动(`use_ovcli_config` 模式会清空 .env 里的 5 个对应变量)+ config.yaml | ✅(多层菜单) |
| ov CLI | Rust 原生二进制 | npm `@openviking/cli` / `uv tool install openviking` / cargo / GitHub Releases | 无自有会话(`ov chat` 默认使用 machine-uid) | `ovcli.conf`(多 profile)+ 少量 env | ✅ `ov config`(TUI 向导) |
### 3.1.2 统一安装器
-统一安装脚本 `examples/memory-plugin-shared/install.sh`(3424 行)覆盖 10 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`(其中 openclaw 走自有渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:
+统一安装脚本 `examples/memory-plugin-shared/install.sh` 覆盖 10 个 harness id:`claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi, dsh`(其中 openclaw 走自有渠道;`trae-cli` 则复用 codex 安装流程,[§3.1.1](#_3-1-1-判定矩阵))。要点如下:
- 双分发:`--dist github|tos`;三源:`--source remote|archive|dev`。以 `bash <(curl …)` 方式执行时会从 `/dev/tty` 读取输入,从而保留交互。
- 官方 docs 的规范一键命令是不带 `--harness` 的裸命令(执行后进入 TUI 多选);而各插件自带的 setup-helper 转发脚本在调用时会自动补 `--harness`。
@@ -195,7 +197,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| 家族 | 消费者 | URL env | Key env | 身份 env | 认证头 |
|---|---|---|---|---|---|
-| **A. JS 共享核**(`credentials.mjs`) | claude-code / codex(含 trae-cli)/ cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | `Authorization: Bearer`;注意 codex 的 4 个 hook 脚本会额外发送 `X-API-Key` 兼容头 |
+| **A. JS 共享核**(`credentials.mjs`) | claude-code / codex(含 trae-cli)/ cursor / trae×2 / zcode / opencode / pi / dsh / agent-plugins | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_PEER_ID` | 只发 `Authorization: Bearer`;本家族任何 harness 都不发 `X-API-Key` |
| **B. openclaw**(自有 `config.ts`) | openclaw | `OPENVIKING_BASE_URL` → `OPENVIKING_URL` | `OPENVIKING_API_KEY`(支持 SecretRef env/file) | `OPENVIKING_ACCOUNT_ID` / `OPENVIKING_USER_ID`(注意此处带 `_ID`) | `X-API-Key`(指向 OV Cloud 时注意其实际采用 Bearer 认证) |
| **C. hermes**(Python) | hermes | `OPENVIKING_ENDPOINT` | `OPENVIKING_API_KEY` | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` / `OPENVIKING_AGENT`(=actor peer) | `X-API-Key` + `Bearer` 双发;有 key 时默认不发租户头(被服务端以 trusted 报错拒绝时会自动补头重试一次) |
| **D. ov CLI**(Rust) | ov | conf 文件为主 | conf | `--account/--user/--actor-peer-id` | `X-API-Key`;LDAP Basic / OIDC Bearer 按 `auth_mode` 切换;api_key 含 ≥2 个 `.` 时自动附加 Bearer(JWT 兜底) |
@@ -205,11 +207,11 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
1. 模式由 `OPENVIKING_CREDENTIAL_SOURCE`(别名 `_CREDENTIALS_SOURCE`)控制,取值 ∈ `env|cli|auto`(默认 auto)。
2. **auto 语义是 env 优先**:只要任一 env 凭据字段存在,整体就走 env;只有 env 全空、且 ovcli.conf 存在并含凭据字段时,才整体切换到文件(此时 key/account/user/peer 全部只从文件取)。
3. baseUrl:env → ovcli `url` → ov.conf `server.url` → `http://{server.host|127.0.0.1}:{server.port|1933}`(其中 `0.0.0.0` 归一为 `127.0.0.1`);兜底 `http://127.0.0.1:1933`。
-4. apiKey:`BEARER_TOKEN` → `API_KEY` → ovcli `api_key` → ov.conf `codex.apiKey` → `server.root_api_key`。
+4. apiKey:`BEARER_TOKEN` → `API_KEY` → ovcli `api_key` → ovcli `plugin.<harness>.apiKey` → ovcli `plugin.apiKey` → ov.conf `<harness>.apiKey` → `server.root_api_key`。`<harness>` 是调用方 harness 自己的那段(snake_case,如 `trae_cn`;`claude-code` 与 `claude_code` 指向同一段);account / user / peerId 在各自链条的同一位置读同一段。
5. mcpUrl:`OPENVIKING_MCP_URL`(非 cli 模式)→ `${baseUrl}/mcp`。
-6. 统一请求头:`Authorization: Bearer` + `X-OpenViking-Account/User/Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`。
+6. 统一请求头:`Authorization: Bearer` + `X-OpenViking-Account/User`(仅 trusted 模式)+ `X-OpenViking-Actor-Peer` + `User-Agent: openviking-memory-<harness>/<version>`。`api_key` 模式的服务端从 key 里取身份、忽略这两个头,所以那里不发,免得把身份报给链路上的每一层代理。模式解析顺序:`ovcli` `plugin.<harness>.authMode` → `plugin.authMode` → `ov.conf` `<harness>.authMode` → `ov.conf` `server.auth_mode` → 只要解析出了 account 或 user 就算 trusted。
-**workspace peer**(家族 A 各 harness 均适用;agent-plugins 包不做派生,只发显式 `OPENVIKING_PEER_ID`):无显式 peerId 且 `OPENVIKING_WORKSPACE_PEER≠0` 时由 workspace 派生,随 `X-OpenViking-Actor-Peer` 发送(服务端会对该头校验,含 `/` 或 `\` 返回 400)。派生规则由 `peer.source` 决定,**默认 `git`**:先取归一化后的 `origin` URL,取不到回落到仓库根路径;不在仓库中则什么都不发送,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。例如在 `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` 下、origin 为 `[email protected]:volcengine/OpenViking.git` 时,peer 是 `github.com-volcengine-openviking`——任意子目录、任意 worktree、任意机器、任意 clone 都是同一个值。`peer.source` 的读取层为 env `OPENVIKING_PEER_SOURCE`、ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource`、workspace 文件的 `peer.source`;只有 claude-code 和 codex 读这几层,其余家族 A harness 一律走默认值。
+**workspace peer**(家族 A 各 harness 均适用;agent-plugins 包既不派生 workspace peer,也不转发任何 peer——它没有能把 `recallPeerScope` 设成 `actor` 的旋钮层,代理始终不发这个头):无显式 peerId 且 `OPENVIKING_WORKSPACE_PEER≠0` 时由 workspace 派生,随 `X-OpenViking-Actor-Peer` 发送(服务端会对该头校验,含 `/` 或 `\` 返回 400)。派生规则由 `peer.source` 决定,**默认 `git`**:先取归一化后的 `origin` URL,取不到回落到仓库根路径;不在仓库中则什么都不发送,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。例如在 `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` 下、origin 为 `[email protected]:volcengine/OpenViking.git` 时,peer 是 `github.com-volcengine-openviking`——任意子目录、任意 worktree、任意机器、任意 clone 都是同一个值。`peer.source` 的读取层为 env `OPENVIKING_PEER_SOURCE`、ovcli.conf `plugin.peerSource` / `plugin.<harness>.peerSource`、workspace 文件的 `peer.source`;家族 A 的每个 harness 都会读这几层。
| `peer.source` | 展开为 | 得到的 peer |
|---|---|---|
@@ -226,7 +228,7 @@ per-harness 章节(档案卡)只写差异;所有共享事实均在本章
| `{dir}` | 工作区根目录的目录名:仓库根,或放着 `.openviking/config.json` 的那个目录 | 该目录不是工作区 |
| `{harness}` | 当前 agent 的名字,与 User-Agent 里那个一致 | 从不为空——但 MCP proxy 不参与推导(它的 cwd 不是可靠身份),只走 proxy 的读路径解析不出它 |
-在 claude-code 和 codex 下,要让一个不是仓库的目录拥有独立 peer,在该目录下创建 `.openviking/config.json`,写上 `{"version": 1, "peer": {"id": "my-project"}}`;其余 harness 只能改用显式的 `OPENVIKING_PEER_ID`。
+要让一个不是仓库的目录拥有独立 peer,在该目录下创建 `.openviking/config.json`,写上 `{"version": 1, "peer": {"id": "my-project"}}`,或者为它设置显式的 `OPENVIKING_PEER_ID`。
**身份语义**:同一仓库的所有 clone 共用一个 peer,项目记忆跟着项目走而非跟着 checkout 走。fork 的 `origin` 不同,因此默认就是另一个 peer;用 `gh pr checkout` 评审外部 PR 不改 `origin`,身份也就不受影响。派生是纯文件系统操作(`workspace-identity.mjs`),不起 `git` 子进程,因此能塞进最紧的 hook 预算,也能在 `git` 不在 `PATH` 上、或因 dubious ownership 拒绝该仓库时照常工作。worktree 经 `commondir` 收敛回主仓库,submodule 保留自己的身份,`$HOME` 与 `/` 永远不会被当作 workspace 根。
@@ -239,19 +241,17 @@ openclaw 的 peer 由 `peer_role`/`peer_prefix` 推导(`peer_role=sender` 时
| 配置层 | 生效范围 | 备注 |
|---|---|---|
| env `OPENVIKING_*` | 各家族见上;行为旋钮见各档案卡 | 唯一横跨所有 JS 系的层 |
-| workspace 层:每机注册表 `~/.openviking/workspaces/<slot>.json` > `<repo-root>/.openviking/config.local.json`(私有,gitignore)> `<repo-root>/.openviking/config.json`(提交进仓库、团队共享) | claude-code / codex | schema v1,必须写 `version: 1`,声明其他版本的文件会被跳过并告警。可用 key:`peer.source`、`peer.id`、`recall.{enabled,peer_scope,dedup_turns,max_items,score_threshold}`、`capture.{enabled,commit_token_threshold}`、`bypass.session_patterns`、`labels`。列表类跨层取并集,首元素写 `"!reset"` 可清空继承来的内容;不认识的 key 原样保留但不生效。hook 是非交互的,这些文件因此无提示直接信任,换来的是结构性的拒绝:连接与凭据类 key(`url`、`api_key`、`account`、`user`、`extra_headers` 等)一律剥离并告警,这些文件里的 `${VAR}` 永不展开。注册表目前没有写入方:条目由人工创建,`ov-memory-doctor` 会打印该放到哪个 slot 路径。提交进仓库的文件关掉了什么,由 `ov-memory-doctor` 播报而不是拦截 |
-| ovcli.conf `plugin` 段(`plugin.claude_code` / `plugin.codex` / 共享标量) | claude-code / codex | 其余 harness 名下的 `plugin.<x>` 条目不参与解析。注意:`ov config add/edit` 会以 Rust Config 结构重写整个文件,从而丢弃其不识别的 `plugin` 段;而 `ov config switch` 为字节复制,不受影响 |
-| ov.conf harness 段(`claude_code.*` / `codex.*`) | claude-code / codex(legacy 回落) | |
-| harness 自有配置文件 | opencode `openviking-config.json`、pi `config.json`、dsh cordis patch、openclaw `openclaw.json`、hermes `config.yaml`+`.env` | |
+| workspace 层:每机注册表 `~/.openviking/workspaces/<slot>.json` > `<repo-root>/.openviking/config.local.json`(私有,gitignore)> `<repo-root>/.openviking/config.json`(提交进仓库、团队共享) | claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi | schema v1,必须写 `version: 1`,声明其他版本的文件会被跳过并告警。可用 key:`peer.source`、`peer.id`、`recall.{enabled,peer_scope,dedup_turns,max_items,score_threshold}`、`capture.{enabled,commit_token_threshold}`、`bypass.session_patterns`、`labels`。列表类跨层取并集,首元素写 `"!reset"` 可清空继承来的内容;不认识的 key 原样保留但不生效。hook 是非交互的,这些文件因此无提示直接信任,换来的是结构性的拒绝:连接与凭据类 key(`url`、`api_key`、`account`、`user`、`extra_headers` 等)一律剥离并告警,这些文件里的 `${VAR}` 永不展开。注册表目前没有写入方:条目由人工创建,`ov-memory-doctor` 会打印该放到哪个 slot 路径。提交进仓库的文件关掉了什么,由 `ov-memory-doctor` 播报而不是拦截 |
+| ovcli.conf `plugin` 段(共享标量,可被 `plugin.<harness>` 对象覆盖) | claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi | 每个 harness 键两种写法都认——`claude_code` 或 `claude-code`、`trae_cn` 或 `trae-cn`。注意:`ov config add/edit` 会以 Rust Config 结构重写整个文件,从而丢弃其不识别的 `plugin` 段;而 `ov config switch` 为字节复制,不受影响 |
+| ov.conf harness 段(`<harness>.*`,legacy) | 每个 harness 读与自己同名的那段 | 凭据字段(`apiKey`/`accountId`/`userId`/`peerId`)与调优旋钮都按调用方 harness 取自己的段。两种写法指向同一段 |
+| harness 自有配置文件 | dsh cordis patch(会被 `plugin` 段压过)、openclaw `openclaw.json`、hermes `config.yaml`+`.env` | |
**配置项生效范围速查**(这些旋钮只在列出的 harness 上生效):
- `OPENVIKING_COMMIT_TURN_THRESHOLD`:仅 cursor(trae×2/zcode 每 Stop 必 commit,不走该阈值)。
- `OPENVIKING_WRITE_PATH_ASYNC`:claude-code / codex / zcode。
- 召回再摘要相关(`OPENVIKING_RECALL_COMPRESS` / `OPENVIKING_RECALL_REWRITE` 及配套项):claude-code / codex(服务端 `rewrite` 参数本身对所有调用方可用,[§3.2.5](#_3-2-5-召回再摘要))。
-- `OPENVIKING_RECALL_DEDUP_TURNS`、`OPENVIKING_RECALL_QUERY_EXPANSION`:claude-code / codex。
-- `OPENVIKING_PEER_SOURCE` 与 workspace 配置文件:claude-code / codex(其余家族 A harness 一律按默认 `git` 规则派生 peer,`OPENVIKING_PEER_ID` 与 `OPENVIKING_WORKSPACE_PEER` 仍然生效)。
-- ovcli.conf `plugin` 段:claude-code / codex。
+- `OPENVIKING_RECALL_DEDUP_TURNS`、`OPENVIKING_RECALL_QUERY_EXPANSION`、`OPENVIKING_PEER_SOURCE`、workspace 配置文件与 ovcli.conf `plugin` 段:经共享加载器解析配置的每个 harness——claude-code / codex / cursor / trae / trae-cn / zcode / opencode / dsh / pi;openclaw 与 hermes 各有自己的配置体系。
## 3.2 自动召回与注入
@@ -268,7 +268,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处
- **路径 A:`mode="context"`**(适用于 context face 与 `/recall` preset)。此路径负责 query expansion 与跨轮去重台账。expansion 设有三重闸门:`retrieval.enable_intent` 需开启(默认 true) → 会话必须已物化(即 `messages.jsonl` 文件存在) → `latest_archive_overview` 或 `current_messages` 不能为空。扩写后原 query 永远排第一,追加的 planned queries 上限为 3。台账(`.recall_log.json`)按 `dedup_turns` 冷却已发正文的 URI;若"当轮只发了 URI 没发正文",该记录则不参与冷却;digest 判定 no_relevant 时亦不记账。
- **路径 B:`mode="list"`**(不写 mode 时的默认行为)。此路径下,IntentAnalyzer 会整体替换 typed_queries(原 query 不保证保留),无台账、无原-query 保底。实际落在这条路径上的调用方包括:codex 的第二级降级 `searchScope`、hermes 的 `viking_search(mode="deep")` 以及 prefetch 的首选路径。尽管它们带了 session_id,但拿不到 context 面的 expansion 与去重机制。
-**`dedup_turns` 的三点说明**:① 服务端 context 面的默认值是 **0**,常见的"5"实则源自客户端 `recall-core.mjs` 兜底与 `/recall` preset(后者仅当带 session_id)——不经共享库直接打 API 的第三方即使带了 session_id,也要显式发 `dedup_turns` 才有跨轮去重;② "turn"的计数单位是消息条数而非对话轮(`_resolve_turn` 用 `total_message_count`),对同时推 user+assistant 的 harness,默认 5 ≈ 1-2 个真实对话轮;③ 注意:`autoCapture=0` 且 `autoRecall=1` 时消息数恒 0 → 台账时钟不走 → 已发过正文的 URI 在本会话内持续冷却;可用 `OPENVIKING_RECALL_DEDUP_TURNS=0` 关闭去重(claude-code / codex)。
+**`dedup_turns` 的三点说明**:① 服务端 context 面的默认值是 **0**,常见的"5"实则源自客户端 `recall-core.mjs` 兜底与 `/recall` preset(后者仅当带 session_id)——不经共享库直接打 API 的第三方即使带了 session_id,也要显式发 `dedup_turns` 才有跨轮去重;② "turn"的计数单位是消息条数而非对话轮(`_resolve_turn` 用 `total_message_count`),对同时推 user+assistant 的 harness,默认 5 ≈ 1-2 个真实对话轮;③ 注意:`autoCapture=0` 且 `autoRecall=1` 时消息数恒 0 → 台账时钟不走 → 已发过正文的 URI 在本会话内持续冷却;可用 `OPENVIKING_RECALL_DEDUP_TURNS=0` 关闭去重。
### 3.2.2 判定矩阵
@@ -291,7 +291,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处
- **实现**:`profile-inject.mjs`——读 `viking://user/<space>/memories/profile.md` 全文 + `preferences/`、`entities/` 递归清单(abs_limit=512)。预算估算引入 CJK 感知(≥U+3000 记 1.5 token/字,其余 chars/4);profile 占一半预算,超限则采用"头 8 行 + 尾部"的中段省略;清单超限则追加 `... +N more` 提示。
- **谁注入、何时、预算**:claude-code(SessionStart 全部 source,10000);codex(SessionStart startup/clear/resume,10000);cursor/trae×2/zcode(SessionStart,6000,2s 去抖);opencode(每会话首条 chat.message 一次,10000,进程内 Set 去重,subagent 会话跳过;注意开场注入每会话只尝试一次,失败后本进程内不重试);dsh(每 session 投一次 `profileDelivered`,10000;compaction 之后不重投);pi(进 systemPrompt,每个 prompt 重拼,10000 常驻)。openclaw、hermes 无 profile 注入。
-- **archive 注入**(resume 场景把上次归档摘要拉回来):claude-code(source=resume/compact,`token_budget=32000`,≤5 条 pre_archive_abstracts);codex(resume 且本地 ovSessionId 已清时,32000/截 6000 字符);opencode(开场注入 B 部分,32000);pi 非 takeover 模式(32000)。
+- **archive 注入**(resume 场景把上次归档摘要拉回来):claude-code(source=resume/compact,`token_budget=32000`);codex(resume 且本地 ovSessionId 已清时,32000/截 6000 字符);opencode(开场注入 B 部分,32000);pi 非 takeover 模式(32000)。
- **repo 上下文注入**:opencode 独有——通过 `experimental.chat.system.transform` 把已索引仓库列表放进 system prompt。
### 3.2.4 超时与预算链
@@ -374,8 +374,7 @@ JS 系 harness 的召回逻辑均由 `recall-core.mjs` 中的三级降级链处
| harness | 机制 | 要点 |
|---|---|---|
-| cc / cursor / trae×2 / zcode / opencode / dsh / pi | 磁盘队列 `~/.openviking/pending`(0700/0600) | 仅可重试的失败入队(4xx 含 401/403 判为不可重试,不入队,debug 日志可见);重放在会话启动时执行:≤50 条/次、≤3 次/条、TTL 7 天;`.processing` 原子认领,10min 陈旧回收;addMessage 失败即 break 保序 |
-| codex / trae-cli | 无磁盘队列 | 服务端不可达时,靠 `capturedTurnCount` 游标不推进、下一轮 Stop 重发同批实现补偿(进程存活且有下一轮时生效) |
+| cc / codex / cursor / trae×2 / zcode / opencode / dsh / pi | 磁盘队列 `~/.openviking/pending`(0700/0600) | 仅可重试的失败入队(4xx 含 401/403 判为不可重试,不入队,debug 日志可见);重放在会话启动时执行:≤50 条/次、≤3 次/条、TTL 7 天;`.processing` 原子认领,10min 陈旧回收;addMessage 失败即 break 保序 |
| openclaw | 无本地队列 | addSessionMessage 失败被 catch,该轮消息不重放 |
| hermes | 进程内 daemon 线程队列 | drain 有预算(10s/65s);不落盘 |
| LangChain | 进程内 `_pending_commit_sessions` 集合 | commit 失败下次 record 自动重试;不落盘。部分成功时抛 `OpenVikingPartialWriteError`(携带 `messages_written`、`input_messages_consumed`、`context_attached`,调用方可按位置切片重试后缀)——全部集成里唯一的部分成功上报协议 |
@@ -462,7 +461,7 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
| harness | 服务端不可达时 | 负缓存 | HTTP 重试 | 失败阻塞宿主 |
|---|---|---|---|---|
| claude-code | 各 hook catch→approve,不阻塞;session-start 时连 pending 重放都跳过 | context-face 6h + host-cli 探测 7d + health 5s | 无(靠 pending 重放);peer_scope 降级 1 次;batch→逐条 | 否(uri-guard deny 是设计意图) |
-| codex / trae-cli | 各 hook catch→noop | context-face 6h + 压缩器 runtime_failed(至下次启动) | 同上(无磁盘 pending,靠游标重发) | 否 |
+| codex / trae-cli | 各 hook catch→noop | context-face 6h + 压缩器 runtime_failed(至下次启动) | 同上(靠 pending 重放,SessionStart 触发) | 否 |
| cursor/trae×2/zcode | fetch 吞成 status:0,catch 返回空注入;锁 5s 拿不到则静默跳过 | context-face 6h(服务端整体不可达时无负缓存,每轮等满 15s) | 无 | 否 |
| opencode | 各路径 catch→WARN;`event`/`dispose` hook 无 try/catch(不可重试的 commit 失败会冒泡宿主) | 仅 context-face 6h;`/health` 无缓存(每轮一次往返) | 无同步重试;MCP 代理 401/403、400/404 各一次 | 基本否(event/dispose 例外) |
| dsh | client 全吞异常;`ensureState` 失败不缓存(服务端不可达时每 pre-step 两次 health 各 5s) | context-face 6h + user-space 缓存进程内不过期 | 无;pending 跨进程重放 3 次 | 是(pre-step 串行 profile+recall;session/flush 阻塞) |
@@ -479,8 +478,8 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
| harness | statusline | slash command | rule/skill | setup 向导 | 其他 |
|---|---|---|---|---|---|
-| claude-code | ✅ 独立进程写 settings.json(段位丰富,1min TTL) | ✅ `/openviking-memory:ov`(服务状态 + 身份 + 注入溯源) | 1 experience skill | ✅ 行式问答 | debug-recall/debug-capture 诊断脚本;uri-guard 不受插件开关门控 |
-| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | VERIFICATION.md 8 步 SOP |
+| claude-code | ✅ 独立进程写 settings.json(段位丰富,1min TTL) | ✅ `/openviking-memory:ov`(服务状态 + 身份 + 注入溯源) | 1 experience skill | ✅ 行式问答 | uri-guard 不受插件开关门控 |
+| codex / trae-cli | ❌ | ❌ | 1 experience skill | ✅ | README.md Testing 一节的 live 检查 |
| cursor | ❌ | ❌ | rule(alwaysApply)+ skill | ❌(共用安装器 TUI) | 独立 uri-guard,不受插件开关控制 |
| trae/trae-cn | ❌ | ❌ | 无 | ❌ | — |
| zcode | ❌ | ❌ | 无 | ❌ | — |
@@ -500,19 +499,19 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
## claude-code
- **集成文档**:[Claude Code 记忆插件](./02-claude-code.md)
-- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.4.4。
+- **形态**:CC 插件(marketplace),采用四合一架构:9 hook + MCP 代理(15 工具透传)+ slash command + statusline + 1 experience skill。版本 0.5.0。
- **能力亮点**:hook 覆盖最全的 harness——SessionStart(120s) / UserPromptSubmit(60s) / PostToolUse:Read(5s,默认关的 skill-experience) / PreToolUse:Read\|Glob\|Grep(5s,uri-guard) / Stop(45s) / PreCompact(30s) / SessionEnd(30s) / SubagentStart(10s) / SubagentStop(45s);默认启用召回再摘要(本地 `claude -p`,本地不可用时自动回落服务端 rewrite,[§3.2.5](#_3-2-5-召回再摘要));支持 SubagentStart/Stop 的完整子会话隔离([§3.3.5](#_3-3-5-subagent-会话对照));statusline + slash + uri-guard;关闭链路除 kill -9 外全部 commit([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:session id 为 `cc-<CC session_id 原文>`,subagent 为 `…__subagent-<agent_id>`;Stop 阈值 commit 20000/keep 10,PreCompact 同步 commit;自动召回排除 resources([§3.2.1](#_3-2-1-机制底座-一条共享管线-两条服务端路径));增量游标存于 `/tmp`(被系统清理后,同一会话会整段重推)。
-- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 40 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。
+- **配置**:env + ovcli.conf `plugin.claude_code` + ov.conf `claude_code`([§3.1.4](#_3-1-4-配置体系分层)),约 70 个旋钮;压缩器命令与模型固定为 `claude`/`sonnet`/`low`/30s。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |压缩 [§3.4](#_3-4-压缩-compaction-接管) |降级 [§3.6](#_3-6-降级与容错) |UX [§3.7](#_3-7-附加-ux-对照)。
## codex
- **集成文档**:[Codex 记忆插件](./04-codex.md)
-- **形态**:Codex 插件(marketplace),5 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s)+ MCP 代理 + 1 experience skill。版本 0.8.0。
+- **形态**:Codex 插件(marketplace),5 hook(SessionStart 70s / UserPromptSubmit 130s / Stop 30s / SessionEnd 3s / PreCompact 60s)+ MCP 代理 + 1 experience skill。版本 0.9.0。
- **能力亮点**:本地召回压缩管线(`codex exec`,[§3.2.5](#_3-2-5-召回再摘要));SessionEnd(Codex ≥ 0.145)在正常退出时补齐 Stop 漏掉的轮次并 commit,SessionStart 的兜底扫描回收那些没触发 SessionEnd 的退出所遗留的未归档消息([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:session id 为 `cx-<safeId>`(确定性推导,不读 state);SessionEnd 只在正常退出、且 Codex 0.145+ 时触发,信号、崩溃、旧版本以及 `codex app-server` 延后的场景都落到扫描路径;不使用磁盘 pending queue(离线靠游标不推进、下一轮重发补偿,[§3.3.4](#_3-3-4-pending-queue-离线补偿对照));idle-TTL 1800000ms、锁等待 120000ms(env 配置);Stop 与 SessionEnd 默认 detach(`appended N turn(s)` 提示默认不展示);单会话 mkdir 锁串行化 Stop worker、PreCompact、SessionEnd worker 与扫描。新增的 hook 事件在 Codex 侧没有信任记录,升级后需在 `/hooks` 中批准 SessionEnd。
-- **配置**:env + ovcli.conf `plugin.codex` + ov.conf `codex`;hooks 同时发送 Bearer 与 `X-API-Key` 兼容头([§3.1.3](#_3-1-3-凭据体系))。
+- **配置**:env + ovcli.conf `plugin.codex` + ov.conf `codex`;hooks 只用 `Authorization: Bearer` 认证([§3.1.3](#_3-1-3-凭据体系))。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。
## trae-cli(TraeCode CLI 2.0)
@@ -520,60 +519,60 @@ MCP `write` / REST `content/write` 的三道 guard(`content_write.py`):可
- **集成文档**:[TRAE 记忆集成](./13-trae.md)
- **形态**:TraeCode CLI 2.0 是 Codex 系 CLI(binary `traecli`,用户配置 `~/.trae/traecli.toml`,TUI 支持 `/plugins` `/skills` `/mcp`)。OpenViking 经 **codex 插件别名安装**接入:`--harness trae-cli` 复用 codex 安装流程,仅安装参数(binary / home / 配置路径)指向 TraeCode CLI。
- **能力面**:与 codex 同一套插件——5 个已注册 hook + MCP 代理 + experience skill、本地召回压缩、idle-TTL commit 回收、resume archive 注入等,详见 codex 档案卡。若 TraeCode CLI 所基于的 Codex 版本没有 `SessionEnd`,该 hook 会被忽略,关闭时的 commit 全部依赖 idle-TTL 扫描。
-- **版本支持**:仅支持 TraeCode CLI 2.0。1.0 与 2.0 不是同一套 CLI,2.0 才是 Codex 系、才能走 codex 插件别名安装;早期面向 1.0 的独立插件 `examples/trae-cli-memory-hooks`(`~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` 方案)已废弃。
+- **版本支持**:仅支持 TraeCode CLI 2.0。1.0 与 2.0 不是同一套 CLI,2.0 才是 Codex 系、才能走 codex 插件别名安装;早期面向 1.0 的独立插件(`~/.trae/cli/hooks.json` + `[mcp_servers."openviking-memory"]` 方案)已随仓库移除;安装器仍保留 `--harness trae-cli --uninstall`,用于清掉旧安装留在磁盘上的那份。
- **维度索引**:同 codex 卡。
## cursor
- **集成文档**:[Cursor 记忆集成](./12-cursor.md)
-- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + skill。7 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / beforeShellExecution(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。
+- **形态**:配置驱动(写 `~/.cursor/hooks.json`+`mcp.json`)+ MCP 代理 + always-on rule + skill。7 hook:sessionStart(30s) / beforeSubmitPrompt(20s) / beforeReadFile(5s) / beforeShellExecution(5s) / stop(30s) / preCompact(30s) / sessionEnd(30s)。相对 import 共享 lib(不 vendoring)。版本 0.3.0。
- **能力亮点**:beforeReadFile/beforeShellExecution 双 uri-guard(不受插件开关控制);rule + skill 随装。
- **行为要点**:session id 为 `cu-<conversation_id>`;stop 每 8 条消息 commit(`commitTurnThreshold=8`,消息条数计数,keep 0);`sessionEnd` 仅 window_close 触发,且此时宿主已销毁 shell-exec host,实践中不执行([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))——结束在 <8 条消息水位的会话,尾部依赖后续同会话消息触发归档([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));服务端不可达时,每轮等满 15s 召回超时。
-- **配置**:仅 env(`plugin` 段不参与解析)。
+- **配置**:env + ovcli.conf `plugin.cursor` + workspace 文件([§3.1.4](#_3-1-4-配置体系分层))。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。
## trae / trae-cn(IDE 版)
- **集成文档**:[TRAE 记忆集成](./13-trae.md)
-- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。相对 import 共享 lib。MCP server 名为 `openviking`。
+- **形态**:配置驱动(`~/.trae{,-cn}/hooks.json` + 平台相关 mcp.json)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep\|Bash\|RunCommand(5s) / Stop(30s)。相对 import 共享 lib。MCP server 名为 `openviking`。版本 0.3.0。
- **能力亮点**:行为最简单直接的一档——每个有内容的 Stop 都 commit(keep 0),关闭场景下最大待归档量只有最后一轮 in-flight([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵))。
- **行为要点**:trae 与 trae-cn 的差异是 session id 前缀 `tr-` / `trcn-` 与安装路径——同一份记忆在两个客户端落到两组不同 session,跨客户端共享靠服务端抽取后的记忆空间而非 session 复用;无 PreCompact/statusline/skill/subagent 处理。
-- **配置**:仅 env。
+- **配置**:env + ovcli.conf `plugin.trae` / `plugin.trae_cn` + workspace 文件。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。
## zcode
- **集成文档**:[社区插件 → ZCode](./08-community-plugins.md)
-- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。共 vendoring 18 个共享模块,也是唯一 vendoring `agent-hook-runtime` 那一对、而不是相对 import 的 harness。版本 0.1.2。
+- **形态**:配置驱动(合并进 `~/.zcode/cli/config.json`,强制 `hooks.enabled=true`)+ MCP 代理。4 hook:SessionStart(30s) / UserPromptSubmit(20s) / PreToolUse:Read\|Glob\|Grep(5s) / Stop(30s)。自身不 vendoring 任何共享模块:安装器按 cursor / trae 同样的方式为它拼装共享运行时。版本 0.3.0。
- **能力亮点**:以 rollout 文件 `~/.zcode/cli/rollout/model-io-<sid>.jsonl` 为增量真相源(`lastTurnId` 差集补齐漏掉的 Stop);Stop 默认 detach(Ctrl+C 不丢写入)。
- **行为要点**:每 Stop commit(keep 0);捕获路径仅剥离三类注入块(不做额外文本清洗,[§3.2.6](#_3-2-6-注入回流防护));首次捕获会一次性读取整个 rollout(长会话首装时单次推送量大)。
-- **配置**:仅 env;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。
+- **配置**:env + ovcli.conf `plugin.zcode` + workspace 文件;`OPENVIKING_WRITE_PATH_ASYNC` 对 zcode 生效。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。
## opencode
- **集成文档**:[OpenCode 插件](./10-opencode.md)
-- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。7 个 plugin hook:config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。版本 0.2.4。
+- **形态**:npm 插件 `@openviking/opencode-plugin`,config hook 自注入 MCP 条目(工具带 `openviking_` 前缀)。7 个 plugin hook:config / event / tool.execute.before / experimental.chat.system.transform / chat.message / experimental.session.compacting / dispose。版本 0.3.0。
- **能力亮点**:`dispose` hook 覆盖全部四种常规关闭方式(宿主 ≥1.15.11);repo 列表进 system prompt([§3.2.3](#_3-2-3-profile-开场注入));宿主事件面最丰富(session.idle/compacted/deleted/error 各有语义)。
- **行为要点**:`commitTokenThreshold=20000`(取正数,0 回落默认值);commit 超时 30000ms;一次宿主压缩 = 两次 commit;dispose 的 5s 宿主预算下,多会话慢 commit 可能被截断,且 pending queue 不覆盖此场景([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));<1.15.11 无 dispose 时关闭不 commit;重启后不主动 flush 遗留会话;开场注入每会话尝试一次([§3.2.3](#_3-2-3-profile-开场注入));`bypassSessionPatterns` 的目录匹配在 opencode 上不适用(input 无 cwd)。
-- **配置**:`openviking-config.json`(4 级搜索)+ env。
+- **配置**:env + ovcli.conf `plugin.opencode` + workspace 文件。
- **维度索引**:工具面 [§2.1](#_2-1-服务端-mcp-工具面) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |subagent [§3.3.5](#_3-3-5-subagent-会话对照)。
## dsh(DeepSeek Harness)
-- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),原生注册 7 个 `viking_*` 工具(`viking_search/read/browse/remember/forget/add_resource/archive_expand`),REST 直连。4 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush。版本 0.1.0。
+- **形态**:唯一同进程 Cordis 原生插件(`export function apply`),原生注册 7 个 `viking_*` 工具(`viking_search/read/browse/remember/forget/add_resource/archive_expand`),REST 直连。4 事件:agent/session-start(emit)/ agent/pre-step(waterfall)/ session/event / session/flush。版本 0.4.0。
- **能力亮点**:`ctx.provide("openvikingMemory")` 供其他 Cordis 插件二次开发;pre-step 注入走 user 消息,适配 DSH persona 的 `complete:true` 渲染模式。
- **行为要点**:统一安装器已覆盖 dsh,会询问装到哪个 profile(默认 `web`,可用 `--dsh-profile` 指定);npm 是该插件唯一的分发渠道,因此 github/tos 选择对它不适用,除 `dev` 外的模式一律装已发布的包;`dev` 会先把 checkout 打包再装——`dsh plugin` 转发给 pnpm,link 一个源码目录无法解析插件 import 的 dsh peer;teardown commit 3s 无阈值,SIGHUP/二次 Ctrl+C 不触发([§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));compaction 不感知(注入内容随宿主压缩收缩,profile 不重投);subagent 各自独立会话([§3.3.5](#_3-3-5-subagent-会话对照));工具面即服务端自身的 MCP 面,经与其他集成同一个 stdio 代理接入、以 `mcp__openviking__*` 发布,服务端升级即可增加工具而无需发版;代价是代理每个 profile 只起一个进程,因此工具调用带的是进程级 actor peer、`remember` 也不绑当前会话(召回/捕获/commit 仍按会话解析 peer);另随包附带共享的 `openviking-memory` 技能;uri-guard 匹配工具名不做大小写归一化。
-- **配置**:cordis patch + 4 个 env;凭据 patch>env,行为开关 env>patch。
+- **配置**:env + ovcli.conf `plugin.dsh` + workspace 文件 + cordis patch(行为旋钮的最低层);凭据是例外,patch 里写的 endpoint / key / account / user / peer 仍然压过凭据链。
- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵) |降级 [§3.6](#_3-6-降级与容错)。
## pi(pi Coding Agent Extension)
- **集成文档**:[pi Coding Agent 扩展](./11-pi.md)
-- **形态**:pi 原生扩展(目录装载,jiti 直译 TS),原生注册 7 个 `viking_*` 工具,REST 直连(pi 无 MCP 支持)。8 事件 + `/viking` 命令。版本 0.1.0。
+- **形态**:pi 原生扩展(目录装载,jiti 直译 TS),原生注册 7 个 `viking_*` 工具,REST 直连(pi 无 MCP 支持)。8 事件 + `/viking` 命令。版本 0.3.0。
- **能力亮点**:takeover 压缩接管(默认开,[§3.4.2](#_3-4-2-pi-takeover));两段式召回(before_agent_start 排队 + context 事件同步检索,当前轮 prompt 拿当前轮记忆);statusline;`session_shutdown` 在所有关闭方式下都触发且被 await。
- **行为要点**:默认 takeover 下退出不 commit(handler 持久化本地状态,归档靠下次续跑攒满阈值或 `/viking commit`,[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵));takeover 阈值 30000 token + 保留 3 轮(keep 3,服务端按消息条数解释);非 takeover 阈值 20000/keep 10、退出无条件 commit;工具注册需 health+ensureSession 前置([§1.1](#_1-1-主动工具面-agentic-调用能力));`viking_add_resource` 仅 HTTP URL(guard 在服务端);非 takeover 模式下 `pi -c` 续跑会重新上报整条 branch。
-- **配置**:`config.json` 行为旋钮 + env(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));`bypassPatterns` 为前缀匹配(非 glob)。
+- **配置**:env + ovcli.conf `plugin.pi` + workspace 文件(凭据统一走凭据链,[§3.1.3](#_3-1-3-凭据体系));bypass 走共享 `isBypassed` 的 glob 匹配,键名 `bypassSessionPatterns`(旧名 `bypassPatterns` 仍可读)。
- **维度索引**:工具面 [§1.1](#_1-1-主动工具面-agentic-调用能力) |召回 [§3.2](#_3-2-自动召回与注入) |takeover [§3.4.2](#_3-4-2-pi-takeover) |commit [§3.3.2](#_3-3-2-常规-commit-触发条件)/[§3.3.3](#_3-3-3-关闭方式-×-harness-终局矩阵)。
## openclaw
diff --git a/docs/zh/agent-integrations/17-dsh.md b/docs/zh/agent-integrations/17-dsh.md
index 7b0c9243c..6b930c5d8 100644
--- a/docs/zh/agent-integrations/17-dsh.md
+++ b/docs/zh/agent-integrations/17-dsh.md
@@ -103,7 +103,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
同一个 `config` 块里的 `peerSource` 决定工作区 peer 的派生方式。默认的 `"git"` 取仓库归一化后的 `origin` URL(`[email protected]:volcengine/OpenViking.git` 得到 `github.com-volcengine-openviking`),其次是仓库根路径,因此同一个仓库的每个 clone、worktree 和子目录共用同一个 peer;不在仓库中则完全不发送 peer,在那里记下的内容进入用户级空间 `viking://user/<you>/memories`。`"cwd"` 恢复此前的行为——把工作目录路径中的非字母数字字符全部替换成 `-`;`"none"` 则完全不发送 peer。要让仓库之外的目录拥有独立记忆,请为它设置 `OPENVIKING_PEER_ID`(见[让一个目录拥有独立记忆](../configuration/02-client.md#让一个目录拥有独立记忆))。
-patch 中写的凭证优先于环境变量;行为开关则优先读环境变量。完整参数列表见[插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin)。
+patch 中写的凭证优先于环境变量。行为旋钮按优先级从高到低解析:`OPENVIKING_*` 环境变量、工作区的 `.openviking/config.json` 与 `config.local.json`、`ovcli.conf` 的 `plugin.dsh`、`ovcli.conf` 的 `plugin`,最后才是这个 patch 块。完整参数列表见[插件 README](https://github.com/volcengine/OpenViking/tree/main/examples/dsh-memory-plugin)。
</details>
diff --git a/docs/zh/agent-integrations/18-plugin-development.md b/docs/zh/agent-integrations/18-plugin-development.md
new file mode 100644
index 000000000..541f088d2
--- /dev/null
+++ b/docs/zh/agent-integrations/18-plugin-development.md
@@ -0,0 +1,498 @@
+# Hook + MCP Agent 插件开发与维护规范
+
+本文规定如何新增和维护通过生命周期 hook 自动读写记忆、通过 MCP 提供工具的 OpenViking Agent 插件,涵盖模块职责、协议、状态、安装、测试和发布。宿主是指承载 Agent 的客户端或运行时,代码中也称 harness。
+
+新增宿主时,应主要实现事件、消息格式、上下文注入和安装方式的差异。配置解析、鉴权、召回、捕获过滤、网络请求和离线重试应复用共享实现。Claude Code、Codex 和其他插件可作为参考,但仍需核对目标宿主的实际契约。MCP-only 或原生工具集成可采用相关规则,不必补齐不适用的 hook 能力。
+
+## 使用 VibeCoding 开发插件
+
+使用 VibeCoding 或其他 AI 辅助编程方式新增、修复、重构 Agent 插件时,**必须让 coding agent 在修改前完整阅读并遵循本文**。将文档路径和具体任务一起交给 Agent,要求它先核实宿主契约,再实施,并按验收检查单报告结果。生成了代码或测试通过,都不能替代对协议、恢复和安装产物的验证。
+
+优先参考 [Claude Code](./02-claude-code.md) 和 [Codex](./04-codex.md) 插件,了解共享能力如何接入原生 hook 与 MCP;配置文件式宿主可参考 `agent-hook-plugin`,常驻扩展可参考 OpenCode、DSH 和其他插件。参考其职责划分和已验证行为,不要让 Agent 整目录复制,也不要要求所有宿主照搬同一套事件。
+
+下面的提示词可以直接交给 coding agent;把最后一行替换为具体任务:
+
+```text
+Before changing any OpenViking agent plugin, read and follow
+docs/en/agent-integrations/18-plugin-development.md
+(Chinese: docs/zh/agent-integrations/18-plugin-development.md).
+
+Inspect examples/memory-plugin-shared/lib/ and the Claude Code and Codex
+plugins. Also inspect agent-hook-plugin, OpenCode, DSH, or another existing
+integration when its host model matches the task. Verify the target host's
+events, payloads, output schema, time limits, and installation contract.
+
+Keep shared behavior in the shared modules and host differences in the
+adapter. Do not copy a whole plugin or edit generated shared files. Cover
+configuration, hook/MCP identity, capture acknowledgements, commit recovery,
+installation, versioning, and bilingual documentation as applicable.
+
+Before finishing, use the guide's acceptance checklist and report what was
+changed, what was verified, and any remaining limitations.
+
+Task: <describe the plugin addition, fix, or maintenance change>
+```
+
+## 1. 设计原则
+
+共享库存在,并不代表各插件真正共享行为。配置只有在共同的执行链上解析和消费,才能保持一致;各宿主分别解释开关,会导致不同拼写、不同默认值,甚至配置能读到却不起作用。分发文件也应从依赖关系推导,避免源码通过测试,安装后却缺少 import 所需文件。
+
+因此,本规范要求:
+
+1. **同一行为有一个权威实现**。共享模块拥有规则,适配器提供宿主事实;不允许在适配器中复制一套“略有不同”的规则。
+2. **统一必须发生在执行链上**。调用 `buildPluginConfig()`、`buildRecallBlockDetailed()` 或共享发送器,才构成复用。复制文件、导出同名函数、约定大家保持一致,都不足以防止分叉。
+3. **能推导的清单不手写**。配置键、诊断键、workspace 映射来自 schema;运行时文件集合来自 import 闭包;安装包必需文件来自入口和 manifest。
+4. **保留真实差异**。Claude Code 的子代理事件、Codex 的退出补偿、ZCode 的严格输出格式,各有明确原因。统一它们的公共能力,不强迫它们拥有相同的生命周期。
+5. **交付方式决定生成时机**。用户直接加载仓库目录时,目录必须已经完整;用户安装构建产物时,在打包前生成依赖。不为减少 diff 破坏安装,也不为方便开发提交不需要的生成物。
+6. **每次抽象都减少维护点**。新接口应让后续修复少改一个地方。若只是多了一层转发、更多布尔参数或第二套配置表,应重新考虑。
+
+这些原则与仓库[贡献指南的职责与设计要求](https://github.com/volcengine/OpenViking/blob/main/CONTRIBUTING_CN.md#职责与设计)一致。衡量改动是否合理,要看一个新维护者能否沿调用关系找到规则、解释失败、完成交付。代码行数和文件数量只是结果。
+
+## 2. 接入前先确定宿主契约
+
+开发前必须完成以下接入记录,放在插件 README 或必要的 DESIGN 文档中。记录应引用宿主文档、对应版本源码或实测结果,不能用另一款 Agent 的行为补全空白。
+
+| 要确认的内容 | 必须写清的问题 |
+| --- | --- |
+| 版本与平台 | 最低宿主版本、Node.js 版本、已验证操作系统;较旧版本如何降级 |
+| 安装方式 | 原生插件、marketplace、配置文件 hook 或 npm 扩展;宿主实际加载哪些目录 |
+| 事件 | 启动、提交用户输入、轮次结束、压缩前、会话结束、子代理事件分别是否存在 |
+| 输入 | stdin 是 JSON 还是其他格式;session、cwd、transcript、turn 的字段名及缺失条件 |
+| 输出 | 注入字段、允许/拒绝字段、空结果形式、退出码;未知字段是否导致整份输出被丢弃 |
+| 时间限制 | 单位、最大值、宿主是否截断配置值;超时后杀单进程还是整个进程组 |
+| 消息来源 | transcript 或 rollout 的格式、写盘时机、稳定消息 ID、工具调用与结果如何关联 |
+| 进程模型 | 是否复用 hook 进程;后台进程能否存活;多个窗口和会话是否并发 |
+| MCP | 配置格式、stdio 支持、根路径变量、启动 cwd、环境变量继承、工具命名空间 |
+| 恢复 | resume、clear、异常退出、压缩和 transcript 截短后,哪些身份与状态仍然有效 |
+
+每项能力标记为“已验证”“有降级实现”或“不支持”,并说明验证版本。不能把 `Stop` 写成“会话结束”,也不能注册一个宿主不会触发的事件后宣称能力完整。最低服务端版本由实际使用的 API 和 URI 能力决定;例如当前共享召回要求服务端支持 `viking://~`,局部的旧接口回退不代表任意旧版本都兼容。
+
+### 2.1 选择最小的接入形态
+
+| 宿主条件 | 应采用的形态 | 参考 |
+| --- | --- | --- |
+| 通过配置文件安装 hook 和 MCP;公共调度足够表达生命周期 | 在 `agent-hook-plugin/hosts/` 增加适配器及宿主配置 | [agent-hook-plugin](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md) |
+| 原生插件要求独立 manifest、目录和生命周期入口 | 独立插件目录,入口调用共享运行时 | [Claude Code](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md)、[Codex](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/README.md) |
+| 以宿主 SDK 回调运行,需要常驻状态或 dispose/idle 回调 | 使用宿主扩展包,复用共享能力,明确自己的会话调度 | [OpenCode](https://github.com/volcengine/OpenViking/blob/main/examples/opencode-plugin/README.md)、[DSH](https://github.com/volcengine/OpenViking/blob/main/examples/dsh-memory-plugin/README.md) |
+| 只有 MCP,没有自动注入或完整会话记录 | 交付 MCP-only 集成,明确能力范围 | [Agent Plugins](https://github.com/volcengine/OpenViking/blob/main/agent-plugins/README.md) |
+
+只因新增宿主名称,不应复制 Claude Code 或 Codex 的整个目录。反过来,如果宿主有独立的会话状态机,也不应不断往公共 dispatcher 加 `isFoo`、`specialStop` 一类开关来容纳它。
+
+## 3. 模块职责与依赖方向
+
+```text
+宿主事件 / transcript 宿主 MCP 客户端
+ ↓ ↓ stdio
+事件、消息、输出适配器 薄 MCP 入口
+ ↓ ↓
+runHookStage + 宿主生命周期调度 buildMcpProxyConfig
+ ↓ createOpenVikingMcpProxy
+共享 recall / capture / session 能力 ↓
+ ↓ createOvHttp 共享 MCP transport
+ └────────── buildOvHeaders ────────────┘
+ ↓
+ OpenViking Server
+
+buildPluginConfig / credentials 为两条链提供配置和身份
+sync / install / pack 负责把这张依赖图完整交付到机器上
+```
+
+共享能力的源文件位于 [`examples/memory-plugin-shared/lib/`](https://github.com/volcengine/OpenViking/tree/main/examples/memory-plugin-shared/lib/)。下表是定位规则的入口,不是需要在每个插件重建的目录模板。
+
+| 责任 | 权威模块 | 宿主可以提供的差异 |
+| --- | --- | --- |
+| 配置声明、默认值、别名、范围 | [config-schema.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/config-schema.mjs) | 有证据的宿主默认值差异,仍在 schema 声明 |
+| 分层配置、完整配置对象 | [plugin-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/plugin-config.mjs) | harness ID、manifest、日志文件名、宿主原生参数 |
+| 凭据和鉴权模式 | [credentials.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/credentials.mjs) | 已有兼容要求;不得再写 fallback 链 |
+| workspace、peer 身份 | [workspace-peer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-peer.mjs)、[workspace-identity.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-identity.mjs) | 当前会话的真实 cwd、宿主明确传入的 peer |
+| hook 初始化、bypass、单次输出 | [agent-hook-runtime.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs) | 输入读取、session ID 解析、启用谓词、输出 envelope |
+| HTTP 头、超时、错误结果 | [ov-http.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/ov-http.mjs) | 请求路径、正文、调用预算、当前 actor peer |
+| 召回和上下文构建 | [recall-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/recall-core.mjs)、[profile-inject.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/profile-inject.mjs) | 查询、会话身份、本地压缩器回调、宿主显示 |
+| 消息清洗、角色和结构化内容 | [capture-utils.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/capture-utils.mjs)、[input-filters.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/input-filters.mjs) | transcript 格式解码、原生工具事件归一化 |
+| 批量发送、离线重放、重试分类 | [batch-send.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/batch-send.mjs)、[pending-queue.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/pending-queue.mjs)、[retryable.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/retryable.mjs) | 何时调用、发送成功后如何推进宿主游标 |
+| 后台写入 | [async-writer.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/async-writer.mjs) | 宿主允许的 detach 时机和恢复措施 |
+| MCP 配置与协议 | [mcp-proxy-config.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs)、[mcp-proxy-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs) | 配置投影、日志工厂、确有必要的本地工具 |
+| 虚拟 URI 检查、诊断 | [uri-guard.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/uri-guard.mjs)、[doctor-core.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/doctor-core.mjs) | 工具名、拒绝格式、宿主安装与状态检查 |
+
+依赖必须从宿主适配器指向共享能力。共享能力不能 import 某个宿主目录;需要宿主动作时,由调用者传入小而明确的回调。不要为一次文件读取引入通用插件容器、服务定位器或继承体系。共享模块也不能反向依赖安装器、测试代码或用户界面。
+
+### 3.1 适配器应该有多薄
+
+“薄”指它只拥有宿主差异,不设行数上限。例如 [cc-transcript.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/scripts/cc-transcript.mjs) 负责 Claude 消息块和嵌套 `tool_result` 的转换;[Codex capture-utils.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/scripts/capture-utils.mjs) 还要展开嵌套工具活动并消除同一调用的重复表示,因此可以更长。两者都应把通用内容处理交给共享代码。
+
+新增薄宿主时,优先使用现有 [`HOSTS`](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/hosts/index.mjs) 和 dispatcher 支持的 `stages`、`envelope`、`prompt`、`normalizeInput`、`capture`、`guard`。需要新增接口时,先说明哪一个宿主事实无法表达,再决定是否扩展;不要预先设计覆盖所有未来 Agent 的适配器 DSL。
+
+现有 `hosts/cursor.mjs`、`hosts/trae.mjs` 和 `hosts/zcode.mjs` 表明,事件映射适合数据,消息转换适合纯函数,异步捕获适合显式回调。不要把这三种东西压进一个包含网络访问的“配置对象生成器”。
+
+## 4. 配置、凭据和身份
+
+### 4.1 一次声明,统一解析
+
+新行为配置必须先在 `config-schema.mjs` 声明规范名称、类型、默认值、范围、所属能力,以及适用的环境变量、旧别名、workspace 键。解析入口使用 `buildPluginConfig(harness, options)`;适配器只投影宿主需要的字段。禁止新增插件私有的 `config.json` 来重复保存共享默认值,也禁止另写 doctor 已知键表或 workspace 键表。
+
+普通行为配置从高到低按以下顺序解析:
+
+1. `OPENVIKING_*` 环境变量。
+2. 本机 workspace registry。
+3. workspace 的 `.openviking/config.local.json`。
+4. workspace 的 `.openviking/config.json`。
+5. `ovcli.conf` 的 `plugin.<harness>`。
+6. `ovcli.conf` 的 `plugin`。
+7. 旧 `ov.conf` 中对应宿主的配置段。
+8. schema 默认值。
+
+宿主 SDK 直接提供参数时,通过共享 builder 的显式参数表达,记录优先级。现有 DSH 的宿主配置参与兼容层,`hostInput` 还能固定连接或 peer;这些有具体含义的入口,不能被解释为适配器可以任意覆盖最终配置。
+
+配置示例只放必要值。例如下面的 `ovcli.conf` 片段为共享 resolver 提供召回默认值,并对 Codex 关闭自动捕获;环境变量和 workspace 等更高优先级配置仍可覆盖:
+
+```json
+{
+ "plugin": {
+ "autoRecall": true,
+ "codex": {
+ "autoCapture": false
+ }
+ }
+}
+```
+
+新增宿主应在 `HARNESS_KEYS` 注册规范 ID,并验证连字符与下划线别名是否按现有约定解析。规范名称与旧别名同时出现时,由共享 resolver 决定结果;同一层规范名称优先。不要在适配器里再做一轮互相冲突的别名转换。
+
+必须区分“未设置”“显式设置为 false”和“最终值等于默认值”。schema 中 `sendOnlyWhenConfigured` 控制的字段,只有实际配置后才发送,避免客户端默认值覆盖服务端默认值。不要用 `value || default` 处理允许 `false`、`0` 或空字符串的字段;是否允许这些值由字段语义决定。
+
+开关必须控制对应的真实行为:关闭 recall 后不发起自动召回,关闭 capture 后不新增本会话的自动捕获和由它触发的提交。历史 pending 的恢复是否继续,要单独定义并验证,不能混为“新采集”。共享能力中的 `isRecallEnabled()`、`isCaptureEnabled()` 是最终保护;适配器可以提前退出,但不能成为唯一检查点。`mcpEnabled` 等配置只有宿主真正消费后,才可以在该宿主文档中宣称支持。
+
+### 4.2 凭据不是普通 workspace 配置
+
+连接和身份必须走 `credentials.mjs` 与 `buildPluginConfig()`。`OPENVIKING_CREDENTIAL_SOURCE` 的 `auto`、`cli`、`env` 控制凭据来源,不能简单套用行为配置优先级。必须验证自定义配置路径、`plugin.<harness>` 覆盖和 `ov config switch` 后 hook 与 MCP 的结果,不能只比较 loader 返回的几个默认字段。
+
+workspace 文件不得包含 URL、API key、用户凭据等禁止字段,也不做环境变量插值。规则由 [`workspace-config.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/lib/workspace-config.mjs) 执行,不在每个宿主增加自己的白名单。安装器不得把解析后的 API key 固化到 `.mcp.json`,也不得替换用户已选择的云端连接。
+
+请求头由 `buildOvHeaders()` 构造:API key 使用 `Authorization: Bearer`,不再另发 `X-API-Key`;只有解析结果 `sendIdentityHeaders` 为真时才发送 account/user 头。保留 `User-Agent` 和错误中的 `traceId`,便于确认实际运行版本和追踪请求。不要在健康检查、状态栏或诊断探针里另写鉴权。
+
+诊断中的 `credentialSource` 表示凭据解析模式,`apiKeySource` 表示 key 的实际来源;两者不能混用。源码中存在为旧安装保留的 `rootKeyFallback`,新宿主不得因为参考插件启用了它,就无条件复制这个选项。
+
+### 4.3 会话身份与 peer 分开处理
+
+原生 session ID 标识一次会话,peer 标识项目记忆归属,二者不能互换。写入使用稳定的宿主 session ID 和明确的宿主前缀;多个窗口、两个相同 cwd 的会话、主代理和子代理不能意外共用写游标。前缀和现有会话 ID 算法属于数据兼容约定,改名时必须说明旧状态如何继续读取。
+
+peer 解析使用共享实现。现状默认从 Git 身份推导,普通非 Git 目录不自动分配 peer;标记文件可显式指定。worktree、子目录和 fork 的行为见[共享库说明](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/README.md#workspace-peers)。hook 必须以 payload 中的真实 cwd 重新解析 workspace 配置,不能把插件安装目录当作项目。
+
+长期运行的 MCP proxy 不能从启动 cwd 推导当前项目。必须使用 `resolveMcpActorPeerId()`:默认宽范围读取不发 actor peer 头,actor 范围需要显式 peer。现有共享实现在缺少显式 peer 时发出警告并退回宽范围,文档必须如实说明。peer 是已认证用户内部的记忆归属和检索范围,不能把它宣称为不同用户之间的授权隔离。
+
+## 5. Hook 生命周期与可靠写入
+
+### 5.1 通用阶段和宿主事件的对应关系
+
+| 阶段 | 通用责任 | Claude Code 现状 | Codex 现状 |
+| --- | --- | --- | --- |
+| 会话启动 | profile 注入、必要的恢复工作 | `SessionStart` | `SessionStart`;区分 startup、clear、resume |
+| 用户提交 | 过滤查询、召回、注入上下文 | `UserPromptSubmit` | `UserPromptSubmit` |
+| 轮次结束 | 从可靠来源补齐新消息,保存进度 | `Stop`;另有阈值提交 | `Stop`;通常追加,不等同会话结束 |
+| 压缩前 | 确认压缩前消息已写入,再执行相应提交 | `PreCompact` 提交已有消息;本入口不补采 transcript | `PreCompact` 补齐 transcript 后提交 |
+| 会话结束 | 完成尚未完成的写入与提交 | `SessionEnd` 提交已有消息;本入口不补采 transcript | `SessionEnd` 后台补齐并提交,保留启动补偿 |
+| 子代理 | 保留身份和父子关系,避免重复 | `SubagentStart`、`SubagentStop` | 当前 hook manifest 没有这两个事件 |
+| 本地工具检查 | 阻止把虚拟 URI 当本地路径 | `PreToolUse` URI guard | 当前 hook manifest 未注册 URI guard |
+
+以两份 [Claude Code hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json) 和 [Codex hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/hooks/hooks.json) 为事件注册依据。相同事件名称不保证 payload 或输出格式相同。没有结束事件的宿主必须选择并说明替代提交点,例如 ZCode 在 Stop 提交;不能假装存在一个永远不会执行的 SessionEnd。
+
+### 5.2 Hook 入口的固定职责
+
+入口使用 `runHookStage()` 处理 stdin、按会话 cwd 重载配置、启用和 bypass 判断,并保证只输出一次。宿主特有 session 字段通过 resolver 传入,不能为兼容一个字段名而关闭 bypass。输出必须严格符合当前事件的宿主协议:`decision: "approve"` 不是通用格式,Cursor 的 `additional_context` 与其他宿主的 `hookSpecificOutput.additionalContext` 也不能混用。
+
+stdout 只承载宿主约定的结果,日志写 stderr 或共享日志文件。无结果、禁用、配置不可用、网络失败时,都应产生该事件合法的空结果,避免让记忆服务故障阻断用户正常交互。URI guard 的明确拒绝则应保留拒绝语义,不能被统一异常处理改成允许。
+
+不要在普通模块 import 时读 stdin、启动子进程、联网或退出进程。这些副作用属于入口或显式调用的函数。共享函数不能为了方便调用者直接 `process.exit()`;可复用入口需要可测试的主函数和明确的启动条件。
+
+### 5.3 Recall 与 profile 注入
+
+profile 与逐轮召回分别使用 `buildProfileBlock()` 和 `buildRecallBlock()` / `buildRecallBlockDetailed()`。宿主可提供压缩器、显示结果和统计信息,不能重写检索目标、排序、token 预算和服务端兼容回退。状态栏需要计数时,应消费共享结果和最终注入内容,不能再跑一次召回推算。
+
+自动召回必须携带正确会话身份和 peer,并遵守 input filter、bypass 和开关。空结果应保持为空,不把服务端的“无相关记忆”占位文本当成记忆注入。压缩失败可退回已有的未压缩结果;不得凭空补写摘要。压缩后的 `viking://` URI 必须仍可读取,原始用户问题、召回块与宿主包装也必须能在 capture 时区分,避免重复写入注入的旧记忆。
+
+如果使用宿主 CLI 压缩内容,必须隔离这次辅助调用的自动记忆 hook,限制执行时间,并复用已有压缩接口。不得启动一个再次触发自身 recall/capture 的递归 Agent。模型选择和调用方式属于宿主适配,通用压缩结果处理属于共享层。
+
+### 5.4 Capture 的数据与确认规则
+
+优先读取宿主提供的完整 transcript/rollout,stdin 只在已验证缺少完整来源时作为补偿。Stop payload 不一定有用户输入,不得用最后一条助手输出伪造一轮完整对话。文件暂时不可读和“没有新消息”必须是不同结果。
+
+宿主解析器先把外部记录转换成共享捕获模型,再调用共享清洗和发送逻辑。文本与结构化工具内容分开保留:工具名、调用 ID、输入、输出、状态以及可取得的 turn ID,应来自真实记录。不要把同一次工具调用的原生事件、MCP 结果和嵌套表示重复记成几次调用;也不要仅保留最终助手文本而丢掉工具活动。正文过滤不能意外删除仅包含工具的有效记录。
+
+过滤与截断策略使用 `capture-utils.mjs` 和 `input-filters.mjs`。工具输出的正文摘要与结构化 `tool_output` 不是同一个字段;当前实现把大输出交给服务端外置,客户端保留防止异常载荷的上限。不要为了压缩文本摘要把结构化证据一起截掉。
+
+写入遵守以下顺序:
+
+```text
+读取新记录 → 解码与过滤 → 按顺序发送
+ ├─ 服务端确认:推进已发送进度
+ ├─ 已持久化到 pending:可推进交接进度,仍未送达服务端
+ └─ 发送与入队均失败:保留原进度,等待恢复
+```
+
+必须保留以下不变量:
+
+- 游标只推进到连续确认的位置。共享发送器返回 `sent` 与 `queued`;允许按两者推进的适配器,必须确认 `queued` 表示已落盘,并保留后续重放责任。不能把尝试次数当成功次数。
+- 去重优先使用稳定消息 ID、turn ID 或 transcript 位置。相同文本可能是两个合法轮次,不能只按文本 hash 永久去重。
+- 多进程更新同一状态时必须加会话锁;状态写入使用临时文件和原子 rename。锁等待、陈旧锁回收和持有时间必须相容。长任务需要能证明所有权与存活的锁,不能直接套用更短的 stale TTL。
+- 消息发送成功但状态保存失败后的重放,应有可解释的重复处理策略。没有服务端幂等保证,就不能宣称 exactly-once。
+- transcript 截短、resume 或 compaction 不能让游标永久越过新记录;必须说明如何识别并恢复。
+- 子代理记录由明确的一方采集。若主 transcript 已包含子代理内容,单独的子代理 hook 不得重复导入同一记录。
+
+### 5.5 Commit、重试和退出
+
+Commit 表示请求服务端归档并触发处理,不代表长期记忆已经提取完毕。HTTP 成功、任务已受理、归档完成和提取完成要分别报告,不能把 `task_id` 的出现解释成所有工作已完成。
+
+同一会话应先补齐消息,再提交。部分消息失败时,应保留活动 session 和未完成状态;采用 pending 交接的实现,还必须证明 commit 不会越过未重放的消息。**复用 pending queue 本身,不等于自动获得消息与 commit 的事务顺序**。接入时要验证完整失败序列,并按宿主实际情况选择延后 commit 或受顺序约束的重放。
+
+共享重试分类的现状是:网络失败、408、429、5xx 可重试;409 只有明确标记 `error.details.retryable` 时才可重试。401/403 和普通参数错误不能不断入队。批量发送由 `sendSessionMessages()` 控制,每批最多 100 条,批量接口返回 404/405 时回退串行发送。宿主不得另写一套状态码列表或分批循环。
+
+入队时必须保留原始 payload,包括 `keep_recent_count` 等提交参数;重放仍执行原操作。提交失败不能提前清除活动 ID、结束标记或待补消息。pending 有重试次数、重放批量和 TTL 限制,属于有界恢复能力,不能向用户承诺离线数据永久保留。
+
+退出预算按宿主实测设置。当前 Codex SessionEnd 的上限为 3 秒,入口先写 `.ended` 标记,再启动 worker;下次 SessionStart 扫描未完成或过期活动会话。resume 不等于结束,旧 worker 也不能提交已经恢复的新会话,因此标记与清理需要对应同一次结束事件。详细依据见 [Codex commit design](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md)。
+
+后台写入使用 `maybeDetach()` 和 `readHookStdin()`,必须正确转交已经读取的 stdin,防止父子进程各读一次后丢失 payload。detach 成功只表示 worker 已启动;还要验证 worker 在宿主退出后能否存活,失败时如何通过 transcript、pending 或结束标记恢复。不能把返回合法空结果当成写入成功。
+
+同步收尾要给锁等待、消息补齐和 commit 一个总体时间预算,各步骤使用剩余时间。不得让每一步重新获得整个 hook timeout。后台 worker 也必须有界,不能让卡住的网络请求永久持有锁。
+
+服务端字段、配置回显或 API 存在,不足以证明自动提交会在实际消息路径触发。若要把提交职责从插件交给服务端,必须验证运行行为、旧服务端降级和不会重复提交;不能仅凭一个 `auto_commit` 配置删掉插件的可靠提交点。
+
+## 6. MCP 与模型可见工具
+
+Hook 提供自动生命周期行为,MCP 提供模型主动调用的工具。两者通过同一套配置和身份连接 OpenViking,但职责独立。插件启动时应能回答:哪些内容自动注入,哪些操作必须由模型调用,哪些行为禁用后仍可使用 MCP。
+
+支持 stdio MCP 的宿主,应采用 Claude Code、Codex 已使用的共享 proxy:入口解析配置,经 `buildMcpProxyConfig()` 整理,再交给 `createOpenVikingMcpProxy()`。HTTP transport 有 MCP 自身的 session、SSE 和协议协商,不能简单用 REST 的 JSON helper 替换;公共鉴权头仍由 `buildOvHeaders()` 生成。
+
+proxy 入口不得拥有自己的工具 schema、副本 API client、SSE parser 或重试状态机。`tools/list` 和 `tools/call` 应以服务端为准,不能为了改工具描述而维护第二套内存工具目录。确需本地工具时,使用共享 `localToolProvider` 接口并限定范围,工具名不得意外覆盖服务端工具。
+
+新增宿主必须验证:
+
+- 从宿主实际工作目录启动,所有相对路径、根路径变量和环境变量白名单都有效。Codex `.mcp.json` 的 `env_vars` 是具体宿主要求,不能推断其他宿主会同样继承。
+- `initialize` 的协议协商、通知无普通响应、JSON 与 SSE 响应、并发响应 ID 均正确,stdout 无日志污染。
+- MCP session 过期和凭据文件变更使用共享恢复逻辑;未经限定的工具调用不得在网络错误后盲目重试,尤其是有写副作用的操作。
+- hooks 与 MCP 在环境变量、默认文件、自定义文件和 profile 切换后仍使用预期的 URL 和身份。用实际请求头和请求目标验证,不能只看配置文件内容。
+- 诊断和文档列出的工具名与宿主实际显示一致;`remember` 不能随意写成 `store`,工具命名空间也不能照抄另一宿主。
+
+直接连接远程 MCP 只有在宿主确有合适的凭据和配置能力时才采用,并记录与 hook 保持一致的办法。不要增加 wrapper、环境文件或安装时重写来绕过已经能解决问题的共享 proxy。
+
+## 7. URI guard、Skill 和诊断
+
+`viking://` 是虚拟 URI,不能交给本地文件或 shell 工具。宿主支持工具执行前检查时,应使用 `evaluateUriGuard()`,只在适配器中定义工具参数和拒绝 envelope。检查器不能扩展成一般命令拦截器;普通文件路径应保持原有行为。宿主不支持该事件时,明确限制并通过 Skill 指引模型使用 MCP,不得宣称具备等效拦截。
+
+共享 Skill 的源文件放在 [`examples/skills/`](https://github.com/volcengine/OpenViking/tree/main/examples/skills/),通过 `SKILL_TARGETS` 交付,禁止在多个插件副本里分别修改同一段指导。Skill 只描述真实可调用工具和实际能力;自动 hook 已处理的捕获、提交不应再要求模型每轮手动重复执行。不同工具集确有不同操作语义时,可以保留独立 Skill,并说明理由。生成 Skill 时不能在 YAML frontmatter 前插入生成标记。
+
+doctor 使用 `runDoctor(hostSpec)`,宿主只补充安装位置、manifest、hook 注册、状态文件等检查。公共配置、凭据、网络和输出格式由 `doctor-core.mjs` 负责。必须能够检查安装版本、配置来源、生效值、peer、MCP 入口、hook 时间限制和 pending/会话状态。优先提供离线模式和 JSON 输出,离线检查不应偷偷发起网络请求。
+
+排障信息至少能区分禁用、bypass、无结果、超时、鉴权失败、已入队、入队失败与提交失败。日志保留宿主、阶段、会话关联、耗时和 trace ID;默认不写 API key、完整 Authorization 或整份用户 transcript。doctor 的建议必须是适用于当前安装形态的真实命令,不能指向已经删除的 debug 脚本。
+
+## 8. 文件布局、生成与安装
+
+### 8.1 推荐布局
+
+以下是位置约定,尖括号表示接入时填写的名称,不要求创建所有文件:
+
+```text
+examples/memory-plugin-shared/
+ lib/<capability>.mjs 共享行为源文件
+ lib/<capability>.d.mts 需要时提供,与实现一同维护
+ lib/install/ 安装器专用逻辑,不进入 hook 依赖闭包
+ testing/support.mjs 测试辅助,不随运行时交付
+ sync.mjs 分发目标与闭包生成
+
+examples/agent-hook-plugin/
+ hosts/<host>.mjs 宿主适配器
+ hosts/<host>/ 宿主声明、hook/MCP 配置和必要资源
+ scripts/hook.mjs 共用调度入口
+ servers/mcp-proxy.mjs 共用 MCP 入口
+
+examples/<host>-memory-plugin/ 独立原生插件需要时才创建
+ <宿主 manifest 目录>/
+ hooks/
+ scripts/ 宿主入口、状态与 transcript 适配
+ scripts/shared/ 生成物,不手改
+ servers/
+ skills/
+```
+
+模块通过明确的相对 import 连接。公共模块有 TypeScript 消费者时,`.d.mts` 与 `.mjs` 放在同一个权威目录并一起生成。不要在每个产物目录手写一份类型声明。需要显式 re-export 时列出名称,避免 `export *` 与适配器的同名实现冲突。
+
+### 8.2 按交付方式选择生成策略
+
+| 交付方式 | 当前例子 | 生成要求 |
+| --- | --- | --- |
+| 宿主直接加载 Git 中的插件目录 | Claude Code、Codex、`agent-plugins` | 共享副本提交到 Git,checkout 后即可加载 |
+| npm 包或安装归档 | OpenCode、DSH、OpenClaw、Pi | 在 prepack 或 staging 时生成;运行时副本不提交 Git |
+| 安装器组装相邻运行时目录 | Cursor、TRAE、TRAE CN、ZCode | 使用 `ASSEMBLED_ROOTS` 推导 `lib/MANIFEST`,按 manifest 复制共享运行时 |
+
+[`sync.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs) 是上述目标的登记处。新增独立插件登记 `TARGETS` 的 source root、目标目录和 `committed`;新增组装根才扩展 `ASSEMBLED_ROOTS`,普通薄宿主通常已被现有根覆盖。是否交付 Skill 另外登记 `SKILL_TARGETS`。不要维护一份“需要复制的 20 个模块”清单。
+
+修改共享源码后运行:
+
+```bash
+node examples/memory-plugin-shared/sync.mjs
+```
+
+生成器分析静态 import 和字面量动态 import;依赖路径必须可分析,不能用字符串拼接隐藏必需模块。组装后的相对目录关系必须与源码一致,让同一个 import 在仓库和安装目录都成立。不要用绝对开发路径、临时 symlink 或 `NODE_PATH` 让本机测试侥幸通过。
+
+PR 必须包含应提交的最新生成物,并检查新出现但未跟踪的文件。主线的 [`plugin-shared-sync.yml`](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/plugin-shared-sync.yml) 是额外保障,不能代替 PR 中的完整交付。只修改文档且未改变生成源时,无需为了走流程生成无关副本。
+
+### 8.3 安装与卸载的行为要求
+
+安装复用 [`install.sh`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/install.sh),JSON/JSONC 合并放在 [`lib/install/`](https://github.com/volcengine/OpenViking/tree/main/examples/memory-plugin-shared/lib/install/),不要在 shell heredoc 内继续堆放大型 JavaScript。安装器应做到:
+
+1. 在修改用户配置前完成解析、校验和所需文件准备。坏 JSON/JSONC 必须报错并保留原文件,不能将解析失败当作空配置。
+2. 重复安装幂等,不增加重复 hook/MCP 条目;保留其他插件和用户配置,保留格式中有意义的注释。
+3. 路径有空格、宿主不展开变量、自定义配置路径等情况都能正确处理;只向宿主写入它实际支持的字段。
+4. 卸载按本插件拥有的条目删除,包括 URI guard;保留其他集成、凭据、记忆和会话数据。卸载不应要求重新下载源码。
+5. 单个客户端卸载后,其他客户端依赖的共享运行时仍可用;失败时不能留下一半指向旧目录、一半指向新目录的配置。
+
+安装包校验使用 [`stage-memory-plugin-marketplace.sh`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/stage-memory-plugin-marketplace.sh) 和 [`check-marketplace-archive.mjs`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-marketplace-archive.mjs)。必需入口、传递依赖、Skill 中调用的脚本都必须存在;归档排除 `node_modules`、`.git` 和本机秘密。检查工具不能只相信 staging 提供的目录列表,还必须验证预期分发目标没有整项遗漏。
+
+发布前至少从最终归档或 tarball 解包后执行一次入口和安装 smoke test。源码 import 成功,只能证明源码树完整,不能证明用户拿到的包完整。
+
+## 9. Code smell 与可维护性评审
+
+评审时应沿“宿主输入 → 规范模型 → 共享能力 → 状态确认 → 安装产物”阅读。每条规则要能找到唯一实现,每个副作用要能找到明确调用者。以下问题应在本次相关修改中解决,或给出具体的兼容理由;不能用“以后统一”解释新增重复。
+
+| 信号 | 具体问题 | 应采用的处理 |
+| --- | --- | --- |
+| 复制后改名的 client、recall、doctor | 后续修复必须修改多份,行为逐渐分叉 | 将规则放回现有能力模块,宿主只传参数 |
+| 一个字段出现在多个默认值表 | 配置、诊断与实际执行不一致 | 在 schema 声明,其他视图推导 |
+| 配置被读取但没有消费者 | 用户修改开关却没有效果 | 沿真实调用验证,缺能力就不宣称支持 |
+| 共享函数中密集判断 harness 名 | 共享层正在承担宿主协议 | 将事件、格式和策略移到适配器 |
+| 为消除几行重复增加一组布尔开关 | 调用者必须理解多个互斥模式,非法组合增加 | 使用小回调或保留短而直接的宿主代码 |
+| `utils.mjs` 同时处理解析、联网和提交 | 规则没有归属,测试也难以隔离 | 按能力拆分,解析尽量纯函数化 |
+| loader 读配置同时写文件或启动服务 | 调用次数改变系统行为 | 将动作放在显式安装或生命周期入口 |
+| 返回一个含糊的 `true` 表示“处理过” | 无法区分送达、入队和跳过 | 返回明确结果,保留错误与确认数量 |
+| catch 后返回成功或空数组 | 文件不可读、鉴权失败被伪装成无数据 | 保留失败类别,在宿主入口决定合法降级 |
+| 用全局变量表示“当前会话” | 并发窗口与子代理相互覆盖 | 以 session 为键持有状态,传入当前身份 |
+| `export *`、多层同名转发 | 无法判断实际调用的是哪份实现 | 显式导入导出,删除无兼容价值的薄壳 |
+| 注释承诺可靠提交,代码只 `spawn()` | 文案掩盖未确认的副作用 | 写清恢复条件,用实际状态证明完成 |
+| 手动编辑 shared 副本或类型声明 | 下次 sync 覆盖修复 | 修改权威源并生成 |
+| 在发布脚本手列所有共享文件 | 新依赖遗漏只在用户机器暴露 | 从依赖闭包与 manifest 校验 |
+| 旧设计、未调用脚本和测试副本长期保留 | 搜索结果误导维护者,重复测试制造假覆盖 | 删除引用后移除;必要历史留在 Git |
+
+函数名和变量名要反映动作和状态,例如 `parseTranscript`、`sent`、`queued`、`commitAccepted`,避免 `handleEverything`、`done`、`successLike`。注释解释宿主限制、数据不变量和取舍,不复述下一行代码。只为日志或兼容保留的 wrapper 应写清理由。
+
+相似不等于相同。源码中调用同一个共享 builder 也不自动证明 hook 与 MCP 采用完全相同的凭据投影。遇到这种差异,先验证其公开行为,再决定修复或保留;不要把当前参考实现的每一行提升为规范。
+
+## 10. 新增一个插件的实施顺序
+
+1. **完成接入记录**。确认第 2 节的宿主事实,定义支持矩阵、最低版本、缺失事件的替代方案,以及会话 ID 和 commit 时机。
+2. **选择接入形态**。优先增加现有薄宿主适配器;只有分发或生命周期确有要求才新增独立包。把决定写在 README/设计说明中。
+3. **先接通配置与 MCP**。注册 harness ID,使用共享 builder 和 proxy,验证真实启动方式下的路径、环境和鉴权,并用同一配置驱动 hook。
+4. **接入自动读取**。实现启动 profile 和逐轮 recall 的事件/输出转换,验证禁用、bypass、空结果和网络失败。
+5. **接入可靠写入**。实现 transcript 解码、稳定身份、增量游标、确认更新、commit 和恢复。优先覆盖掉线、重复事件和尾部消息补齐。
+6. **接入宿主辅助能力**。按支持情况增加 URI guard、Skill、doctor;不要为不存在的事件放空入口。
+7. **完成安装和分发**。登记生成目标、安装器、归档/marketplace、版本检查和发布工作流,确保包里的入口可直接运行。
+8. **验证并更新文档**。复用现有契约测试,补足宿主差异的验证,执行最终产物 smoke test,记录已测版本、平台与限制。
+
+每一步应有可检查的产物,不以“目录已建好”或“工具列表能返回”作为全部完成。过程可以分成独立提交,但每个提交都应能解释其行为并保持已有接入可用。
+
+## 11. 测试与验收证据
+
+测试验证用户可观察的契约和主要失败情况。遵循贡献指南,优先扩展现有高价值测试,不为简单转发、新文件或几行配置机械地增加单测。共享能力测一次,宿主测试只验证接线和差异;不要复制整套 recall、pending 或 MCP 测试。
+
+公共辅助函数放在 [`testing/support.mjs`](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/testing/support.mjs),不要从另一个测试文件 import helper,也不要放进随插件交付的 `lib/`。测试使用独立临时目录、隔离的配置和 pending 路径、动态端口;安装测试不得修改开发者正在使用的 Agent 配置或与其他测试共享被生成器改写的目录。
+
+| 验证范围 | 至少覆盖的真实行为 | 现有入口 |
+| --- | --- | --- |
+| 配置与开关 | 分层覆盖、别名冲突、非法值、未配置标记、关闭后无新网络副作用 | `plugin-config.test.mjs`、`plugin-known-keys.test.mjs`、宿主 config 测试 |
+| 凭据与 peer | hook/MCP 的请求身份一致;自定义路径、profile 切换、多 workspace | `credentials.test.mjs`、`wire-headers.test.mjs`、`mcp-proxy-config.test.mjs` |
+| Hook 输出 | 真实 payload、单次合法输出、空结果、未知/缺失字段、错误路径 | `agent-hook-runtime.test.mjs`、宿主事件测试 |
+| Recall | 开关、bypass、空结果、服务端兼容、压缩失败、可读 URI | `recall-core.test.mjs`、宿主 recall 测试 |
+| Capture | 完整文本和工具记录、重复事件、重复文本、嵌套工具、部分成功、截短恢复 | `capture-utils.test.mjs`、`batch-send.test.mjs`、宿主 transcript 测试 |
+| 状态与提交 | 并发 Stop/End、worker 失败、resume 与旧结束标记、不可读尾部、入队失败、提交参数保留 | `pending-queue.test.mjs`、Codex session 测试、宿主恢复测试 |
+| MCP | initialize、协议版本、通知、SSE、过期恢复、错误语义、stdout | `mcp-proxy-core.test.mjs`,另加宿主启动 smoke test |
+| 安装产物 | 冷安装、重复安装、保留第三方配置、坏配置不覆盖、卸载不残留、完整依赖闭包 | `install-agent-hooks.test.mjs`、`release-marketplace.test.mjs`、`sync.test.mjs` |
+| 维护约束 | 请求头不再分叉、schema 与消费者匹配、生成物跟踪策略正确 | `one-header-builder.test.mjs`、`plugin-known-keys.test.mjs`、`sync.test.mjs` |
+
+这些文件名均相对于共享库,除非注明宿主。完整命令以 [PR CI](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/pr.yml) 和各插件 package scripts 为准;不要在新插件再维护一份容易过期的全仓库测试清单。源码结构检查用于保护关键的单一实现约束,不能代替行为测试,也不应锁死无关 helper 名称或行数。
+
+例如,修改配置与 MCP 公共契约后,可先在仓库根运行以下聚焦检查,再运行受影响宿主的测试:
+
+```bash
+node examples/memory-plugin-shared/sync.mjs
+node --test \
+ examples/memory-plugin-shared/plugin-config.test.mjs \
+ examples/memory-plugin-shared/credentials.test.mjs \
+ examples/memory-plugin-shared/mcp-proxy-config.test.mjs \
+ examples/memory-plugin-shared/mcp-proxy-core.test.mjs
+```
+
+安装和 marketplace 测试会生成运行时和组装安装目录,按 CI 单独串行执行:
+
+```bash
+node --test --test-concurrency=1 \
+ examples/memory-plugin-shared/install-agent-hooks.test.mjs \
+ examples/memory-plugin-shared/release-marketplace.test.mjs
+```
+
+当前 CI 使用 Node.js 24,其中部分 TypeScript 测试依赖原生类型剥离;测试环境版本和插件运行时最低版本必须分别说明。Node.js 下通过不代表 Windows 上的 detach、路径引用和进程回收已经验证。缺少实测的平台要明示,不用一个全绿数字替代验证范围。
+
+验收报告应记录“用哪个产物、在什么宿主版本、执行什么场景、观察到什么”。对于写入,至少能确认服务端收到完整尾部消息和对应提交;对于安装,至少能确认解包后的入口可以找到依赖。只有文档修改时,检查语法、相对链接、引用符号和示例即可,无需自动运行整套插件测试。
+
+## 12. 维护、发布和文档同步
+
+### 12.1 按改动类型完成维护
+
+| 改动 | 必须跟进的内容 |
+| --- | --- |
+| 共享行为修复 | 修改权威模块、验证受影响宿主、生成副本、检查所有相关分发产物和版本 |
+| 宿主 payload 或事件升级 | 更新适配器、真实格式 fixture、最低版本/降级说明;不修改其他宿主的默认行为 |
+| 新增配置项 | schema、真实消费者、configured 语义、诊断来源、用户文档;不得只加解析 |
+| 增加公共模块依赖 | 同目录类型声明、sync 闭包、`lib/MANIFEST`、归档和离线安装验证 |
+| 目录或包名变更 | import、manifest、installer、marketplace、CI path filter、Skill、链接与卸载识别 |
+| 删除兼容逻辑 | 明确支持版本与迁移说明;不能顺手删除仍承诺支持的配置别名 |
+| 纯文档改动 | 校验与现状一致、相对链接有效;不为说明文字改动无关行为 |
+
+修复应从失败行为和负责的模块出发。若共享问题在单一宿主暴露,仍应在共享源修复;若只有一个宿主 payload 变化,就保持在该适配器内。大型重构按可独立验证、可回退的步骤推进,避免把行为变更、历史清理和分发调整混成无法归因的一次替换。
+
+### 12.2 版本与发布链
+
+版本号决定用户是否能拿到更新。新增插件必须接入适用的版本检查和发布工作流,不能只新增目录。现有 [`check-plugin-version-bumps.sh`](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-plugin-version-bumps.sh) 会把共享 `lib/` 变化计入其登记的每个插件;它不是所有分发目标都已自动覆盖的证明。增加或改变目标时,必须检查登记范围。
+
+宿主 manifest、`package.json`、存在的 lockfile 根包版本、安装 manifest 和安装器判定版本必须一致。修改版本时使用相应包管理流程,不为一个版本数字重写无关依赖。`User-Agent` 和 doctor 应报告实际产物版本,避免用户显示已升级而代码仍旧。
+
+npm/归档目标的构建必须从干净源码生成共享文件,再打包。当前 [`plugin-npm-release.yml`](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/plugin-npm-release.yml) 的矩阵覆盖 DSH 和 OpenCode;其他包要核对各自发布流程,不能因使用相同 prepack 就推断已接入这个矩阵。发布触发条件必须关注共享源变化,不能依赖已经不提交的 shared 副本发生 diff 才触发。
+
+合并前按实际 base 检查版本,例如在本地 `origin/main` 已更新且确为目标分支时:
+
+```bash
+bash .github/scripts/check-plugin-version-bumps.sh origin/main
+git diff --check
+git status --short --untracked-files=normal -- examples agent-plugins
+```
+
+版本检查按已提交的 `base...HEAD` 识别变更,不会把未提交工作区当作完整 PR;最后一次检查应针对最终提交。生成器运行后的未跟踪文件也要审查,不能仅依赖 `git diff`。发布后的验证应检查用户实际下载到的包及版本,不以 CI 已启动作为完成依据。
+
+### 12.3 文档是接口的一部分
+
+插件 README 至少包含:支持范围和版本、最快可用的安装方式、凭据来源、自动行为与 MCP 的分工、核心开关、限制、升级/卸载、诊断与测试入口。面向用户的安装章节优先写可直接使用的一键命令;GUI 步骤独立成段,不把 CLI 命令和 TOML 配置混成 GUI 操作。
+
+用户集成文档与本规范放在 `docs/{en,zh}/agent-integrations/`,英文和中文对应页同步维护。如果该宿主还存在 `docs/images/agents/{en,zh}/` 的镜像说明,也要同步核对;不需要为不存在的镜像机械创建多份相同文本。共享配置的完整解释链接到共享 README,宿主页只说明差异和常用示例。
+
+设计文档只保留读代码无法直接回答的约束、选择理由和恢复不变量。支持矩阵、真实命令和入口变化后及时更新,删除互相矛盾的旧说明。不要把临时排查记录、一次性验证报告或过期测试数字当作长期设计文档。
+
+## 13. 合入前检查单
+
+- [ ] 宿主版本、输入输出、时间限制、消息来源和结束语义均有证据;不支持的能力已注明。
+- [ ] 选择了合理的接入形态,新增代码主要描述宿主差异,共享层不反向依赖宿主。
+- [ ] 配置只有一处声明,开关在执行链生效,hook 与 MCP 的实际连接和身份经过验证。
+- [ ] session 与 peer 不混用;多窗口、resume、子代理和 cwd 变化不会误用状态。
+- [ ] capture 保留文本与工具证据;部分失败、离线入队、重复事件和尾部补齐不会错误推进游标。
+- [ ] commit 顺序与恢复责任明确;退出后 worker 失败也有可验证的补偿办法。
+- [ ] Hook/MCP 输出合法,URI guard、Skill 和 doctor 只承诺真实能力。
+- [ ] 生成目标、安装、卸载、归档、类型声明和发布触发条件完整;最终产物已验证。
+- [ ] 版本与相关 manifest 一致;运行了与改动相称的检查,并记录未验证的平台或场景。
+- [ ] 文档和迁移说明与最终行为一致,没有新增重复配置、旧路径引用或无人使用的辅助脚本。
+
+## 14. 维护者阅读入口
+
+按问题选择入口,避免从各插件生成副本开始追踪:
+
+- 已有集成的支持范围:[集成能力参考](./16-capability-reference.md)。
+- 配置、peer、生成策略:[Memory Plugin Shared README](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/README.md)。
+- Claude Code 的事件接线:[hooks.json](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/hooks/hooks.json);召回适配:[auto-recall.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/scripts/auto-recall.mjs)。
+- Codex 的提交、异常退出与恢复:[DESIGN.md](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/DESIGN.md);实现:[session-end.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/codex-memory-plugin/scripts/session-end.mjs)。
+- 新增配置文件式宿主:[agent-hook-plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/README.md);严格协议实例:[ZCode DESIGN](https://github.com/volcengine/OpenViking/blob/main/examples/agent-hook-plugin/DESIGN.md)。
+- CI 和交付检查:[pr.yml](https://github.com/volcengine/OpenViking/blob/main/.github/workflows/pr.yml)、[sync.mjs](https://github.com/volcengine/OpenViking/blob/main/examples/memory-plugin-shared/sync.mjs)、[marketplace archive checker](https://github.com/volcengine/OpenViking/blob/main/.github/scripts/check-marketplace-archive.mjs)。
diff --git a/examples/zcode-memory-plugin/DESIGN.md b/examples/agent-hook-plugin/DESIGN.md
similarity index 61%
rename from examples/zcode-memory-plugin/DESIGN.md
rename to examples/agent-hook-plugin/DESIGN.md
index 875772345..188e675ac 100644
--- a/examples/zcode-memory-plugin/DESIGN.md
+++ b/examples/agent-hook-plugin/DESIGN.md
@@ -1,4 +1,6 @@
-# DESIGN: ZCode Memory Plugin
+# DESIGN: the ZCode host
+
+The ZCode adapter is the one host in this plugin whose extension surface had to be established by inspection rather than from documentation. What was verified, and what the adapter decided because of it, is recorded here.
## Verified ZCode extension surface
@@ -21,35 +23,38 @@ These facts were verified against a live ZCode installation (built-in `zcode-gui
## 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.
+### 1. Assemble the shared runtime at install time (no vendored copy)
-**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/`.
+ZCode imports the shared runtime across the plugin boundary, the way Cursor and TRAE do. The installer copies the modules `lib/MANIFEST` names to `~/.openviking/agent-integrations/memory-plugin-shared/lib`, which is exactly where `../../memory-plugin-shared/lib` resolves from an installed `hosts/` or `scripts/` file — so the same relative path works in this repository and on a user's machine, and no generated copy has to be kept in git.
### 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.
+`__OPENVIKING_PLUGIN_ROOT__` in the source `hosts/zcode/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`; the Stop parent detaches before reading stdin so network writes do not block ZCode.
+ZCode supports 7 events but NOT `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`. The host wires 4 events. The commit-on-`Stop` strategy compensates for the absence of `PreCompact`/`SessionEnd`; the Stop parent detaches before reading stdin so network writes do not block ZCode.
**Provenance**: Adversarial review R1 — confirmed all 4 event names valid; R4 — unsupported events silently dropped.
### 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).
+ZCode's strict JSON schema rejects unrecognized keys. The adapter's envelope 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)
+### 5. No ZCode host plugin manifest
+
+ZCode probes `.zcode-plugin/plugin.json`, then `.claude-plugin/plugin.json`, then `.codex-plugin/plugin.json` — but nothing here is registered with its plugin system. The installer writes hooks and MCP config straight into `~/.zcode/cli/config.json`, so the host-consumed manifest is `hosts/zcode/openviking.integration.json`, which the installer reads.
-**Provenance**: Adversarial review R1 — `.claude-plugin/` works but `.zcode-plugin/` is the documented preferred location.
+The root `plugin.json` is host-neutral package metadata. The installer copies it
+with the integration, the doctor reads its version, and repository checks keep
+that version aligned with each host's `openviking.integration.json`. No host
+probes or loads it as a native plugin manifest.
## Primary unknowns
diff --git a/examples/agent-hook-plugin/README.md b/examples/agent-hook-plugin/README.md
new file mode 100644
index 000000000..be1cbccdd
--- /dev/null
+++ b/examples/agent-hook-plugin/README.md
@@ -0,0 +1,48 @@
+# OpenViking Memory for the config-driven hook hosts
+
+Cursor, TRAE, TRAE CN and ZCode all install the same way: the shared installer writes lifecycle hooks and an MCP server entry into the host's own configuration files, and assembles the OpenViking runtime beside the integration. None of them has a marketplace listing to register or a separate MCP setup to do.
+
+```bash
+bash examples/memory-plugin-shared/install.sh --harness cursor
+bash examples/memory-plugin-shared/install.sh --harness trae,trae-cn
+bash examples/memory-plugin-shared/install.sh --harness zcode
+```
+
+> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less `viking://user/memories` shorthand is rejected by newer servers.
+
+## What the hooks do
+
+- **Session start** — injects the user profile and preferences into context, and replays anything an offline session queued.
+- **Prompt submit** — searches OpenViking for memories relevant to the prompt and injects them, deduplicated by event id and a 500ms window.
+- **Tool use** — denies `viking://` virtual paths to local file and shell tools, and points the agent back at the OpenViking MCP tools.
+- **Stop** — captures the finished turn and commits the OpenViking session. Cursor also runs this before a compaction and at session end; ZCode answers first and finishes the writes in a detached worker.
+
+## Layout
+
+`scripts/hook.mjs` is the single entry every hook command runs. It owns the state machine all four clients share — the debounce, the prompt dedup, the recall cache, the cross-process lock — and asks the adapter under `hosts/` for the four things that differ: the event vocabulary, the response envelope, how a prompt is read out of the payload, and how a finished turn is captured. `scripts/uri-guard.mjs` and `servers/mcp-proxy.mjs` are likewise one file each, with the host chosen from the client id the installer passes.
+
+The root `plugin.json` is host-neutral package metadata used for version checks and diagnostics. It is not a Claude Code, Cursor, TRAE, or ZCode native plugin manifest.
+
+`hosts/<host>/` holds only what a host reads as configuration — `hooks.json`, `.mcp.json`, `openviking.integration.json`, plus Cursor's rule and skill. Everything executable stays one level up, because `../../memory-plugin-shared/lib` is the path that resolves both in this repository and in an installed `~/.openviking/agent-integrations/<client>/`.
+
+The memory logic itself is not here: recall, batching, the pending queue, credential resolution and the MCP proxy all come from `examples/memory-plugin-shared/lib`, which the installer copies to `~/.openviking/agent-integrations/memory-plugin-shared/lib`.
+
+## Host notes
+
+- **Cursor** — seven events, including the `preCompact` and `sessionEnd` no other host in this plugin has. Commits on Stop once `capturedSinceCommit` reaches the threshold, and unconditionally before a compaction. Sessions are `cu-`. See the [Cursor guide](../../docs/en/agent-integrations/12-cursor.md).
+- **TRAE / TRAE CN** — capture reads `prompt`, `text_content` and `last_assistant_message` off the Stop event rather than parsing a transcript. Every Stop that carries content commits. Sessions are `tr-` and `trcn-`. See the [TRAE guide](../../docs/en/agent-integrations/13-trae.md).
+- **ZCode** — the rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and let a later Stop recover missed turns, and hook stdin is only the fallback. ZCode supports neither `PreCompact` nor `SessionEnd`, so committing on every Stop stands in for both. Its output schema is strict, so a pass-through writes nothing at all. Sessions are `zc-`. [DESIGN.md](./DESIGN.md) records the verified extension surface.
+
+## Diagnostics
+
+```bash
+node ~/.openviking/agent-integrations/<client>/scripts/ov-memory-doctor.mjs --offline
+```
+
+The client defaults to the one this copy was installed for; pass `cursor`, `trae`, `trae-cn` or `zcode` as an argument to override it, drop `--offline` to probe the server as well, and add `--json` for a machine-readable report.
+
+## Tests
+
+```bash
+node --test examples/agent-hook-plugin/tests/*.test.mjs
+```
diff --git a/examples/agent-hook-plugin/README_CN.md b/examples/agent-hook-plugin/README_CN.md
new file mode 100644
index 000000000..8e581e9fa
--- /dev/null
+++ b/examples/agent-hook-plugin/README_CN.md
@@ -0,0 +1,48 @@
+# OpenViking 记忆:配置驱动的 Hook 宿主
+
+Cursor、TRAE、TRAE CN 与 ZCode 的安装方式相同:共享安装脚本把生命周期 hook 与 MCP server 条目写进宿主自己的配置文件,并在集成目录旁装配 OpenViking 运行时。四家都不需要注册 marketplace,也不需要单独配置 MCP。
+
+```bash
+bash examples/memory-plugin-shared/install.sh --harness cursor
+bash examples/memory-plugin-shared/install.sh --harness trae,trae-cn
+bash examples/memory-plugin-shared/install.sh --harness zcode
+```
+
+> **需要支持 `viking://~` home alias 的 OpenViking 服务端。** 召回通过 `viking://~/memories` 与 `viking://~/skills` 指向调用者自己的上下文空间;不带 uid 的 `viking://user/memories` 简写会被较新的服务端拒绝。
+
+## Hook 做什么
+
+- **会话开始** — 注入用户画像与偏好,并重放离线会话排队的写入。
+- **提交 prompt** — 搜索与 prompt 相关的记忆并注入,按事件 id 与 500ms 窗口去重。
+- **工具调用前** — 拦截本地文件与 shell 工具对 `viking://` 虚拟路径的访问,引导回 OpenViking MCP 工具。
+- **Stop** — 捕获完成的回合并提交 OpenViking 会话。Cursor 另外在压缩前与会话结束时执行;ZCode 先应答,再在 detached worker 里完成写入。
+
+## 目录结构
+
+`scripts/hook.mjs` 是所有 hook 命令的唯一入口,持有四家共用的状态机——防抖、prompt 去重、召回缓存、跨进程锁——差异部分向 `hosts/` 下的适配器索取:事件词汇、响应信封、如何从 payload 读出 prompt、如何采集完成的回合。`scripts/uri-guard.mjs` 与 `servers/mcp-proxy.mjs` 同样各只有一份,按安装器传入的 client id 选择宿主。
+
+根目录的 `plugin.json` 是宿主无关的包元数据,只用于版本检查和诊断,不是 Claude Code、Cursor、TRAE 或 ZCode 的原生插件 manifest。
+
+`hosts/<host>/` 只放宿主当作配置读取的东西——`hooks.json`、`.mcp.json`、`openviking.integration.json`,以及 Cursor 的 rule 与 skill。可执行文件一律放在上一层,因为 `../../memory-plugin-shared/lib` 这条相对路径要在本仓库和安装后的 `~/.openviking/agent-integrations/<client>/` 两处同时成立。
+
+记忆逻辑本身不在这里:召回、批量写入、待处理队列、凭据解析与 MCP 代理都来自 `examples/memory-plugin-shared/lib`,由安装脚本复制到 `~/.openviking/agent-integrations/memory-plugin-shared/lib`。
+
+## 各宿主差异
+
+- **Cursor** — 七个事件,其中 `preCompact` 与 `sessionEnd` 是本插件里独有的。Stop 时 `capturedSinceCommit` 达到阈值才 commit,压缩前无条件 commit。会话前缀 `cu-`。见 [Cursor 接入文档](../../docs/zh/agent-integrations/12-cursor.md)。
+- **TRAE / TRAE CN** — 采集直接读 Stop 事件的 `prompt`、`text_content`、`last_assistant_message`,不解析 transcript;每次带内容的 Stop 都 commit。会话前缀 `tr-` 与 `trcn-`。见 [TRAE 接入文档](../../docs/zh/agent-integrations/13-trae.md)。
+- **ZCode** — rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能补回漏掉的回合,hook stdin 只是兜底。ZCode 不支持 `PreCompact` 与 `SessionEnd`,因此每次 Stop 都 commit 来补足这两个信号。它的输出 schema 是严格的,所以放行时不写任何内容。会话前缀 `zc-`。已验证的扩展面记录在 [DESIGN.md](./DESIGN.md)。
+
+## 体检
+
+```bash
+node ~/.openviking/agent-integrations/<client>/scripts/ov-memory-doctor.mjs --offline
+```
+
+client 默认取这份副本安装时对应的那个;传 `cursor`、`trae`、`trae-cn` 或 `zcode` 可以覆盖,去掉 `--offline` 会连带探测服务端,加 `--json` 输出机器可读的报告。
+
+## 测试
+
+```bash
+node --test examples/agent-hook-plugin/tests/*.test.mjs
+```
diff --git a/examples/cursor-memory-plugin/scripts/cursor-transcript.mjs b/examples/agent-hook-plugin/hosts/cursor-transcript.mjs
similarity index 100%
rename from examples/cursor-memory-plugin/scripts/cursor-transcript.mjs
rename to examples/agent-hook-plugin/hosts/cursor-transcript.mjs
diff --git a/examples/agent-hook-plugin/hosts/cursor.mjs b/examples/agent-hook-plugin/hosts/cursor.mjs
new file mode 100644
index 000000000..acc0a3fa2
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/cursor.mjs
@@ -0,0 +1,83 @@
+import { readFile } from "node:fs/promises";
+
+import {
+ addAgentMessages,
+ commitAgentSession,
+ stableHash,
+} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { filterCaptureTurns, isCaptureEnabled } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import { denyCursorPermission, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";
+import { parseCursorTranscript } from "./cursor-transcript.mjs";
+
+async function captureTranscript(ctx, state) {
+ if (!isCaptureEnabled(ctx.cfg)) return { state, captured: 0 };
+ const transcriptPath = ctx.input.transcript_path || ctx.input.transcriptPath;
+ if (!transcriptPath) return { state, captured: 0 };
+ let turns = [];
+ try { turns = parseCursorTranscript(await readFile(transcriptPath, "utf8")); } catch { return { state, captured: 0 }; }
+ const capturedHashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
+ const toSend = [];
+ for (const [index, turn] of turns.entries()) {
+ // Cursor transcripts do not expose a stable message id. Include the
+ // transcript position so two legitimate identical turns are retained,
+ // while duplicate Hook executions over the same transcript still dedupe.
+ // Hash the raw turn, not the filtered text, so raising captureMaxLength
+ // never resends a turn the server already holds in truncated form.
+ const hash = stableHash(index, turn.role, turn.content);
+ if (capturedHashes.has(hash)) continue;
+ const { kept, dropped } = filterCaptureTurns([turn], ctx.cfg);
+ if (!kept.length) {
+ ctx.log("capture_skip", dropped[0]);
+ capturedHashes.add(hash);
+ continue;
+ }
+ toSend.push({ hash, turn: kept[0] });
+ }
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, toSend.map((item) => item.turn));
+ const captured = result.sent + result.queued;
+ for (const item of toSend.slice(0, captured)) capturedHashes.add(item.hash);
+ return {
+ captured,
+ state: {
+ ...state,
+ capturedHashes: [...capturedHashes].slice(-1000),
+ capturedSinceCommit: Number(state.capturedSinceCommit || 0) + captured,
+ },
+ };
+}
+
+export const cursor = {
+ prefix: "cu-",
+ stages: {
+ sessionStart: "start",
+ beforeSubmitPrompt: "prompt",
+ stop: "capture",
+ preCompact: "capture",
+ sessionEnd: "capture",
+ },
+ envelope(event, block) {
+ if (event === "beforeSubmitPrompt") {
+ return block ? { continue: true, additional_context: block } : { continue: true };
+ }
+ if (event === "sessionStart" && block) return { additional_context: block };
+ return {};
+ },
+ guard(input = {}) {
+ const isShell = typeof input.command === "string";
+ const decision = evaluateUriGuard(isShell ? "bash" : "read", input);
+ if (!decision) return {};
+ return denyCursorPermission(decision.reason, { agentMessage: isShell });
+ },
+ prompt: (input) => (typeof input.prompt === "string" ? input.prompt.trim() : ""),
+ async capture(ctx, state, event) {
+ const { state: next } = await captureTranscript(ctx, state);
+ // Only a plain Stop waits for the threshold: a compaction or a session end
+ // is the last chance this transcript has to reach the server.
+ const shouldCommit = event !== "stop" || next.capturedSinceCommit >= ctx.cfg.commitTurnThreshold;
+ if (shouldCommit) {
+ const result = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
+ if (result.ok) next.capturedSinceCommit = 0;
+ }
+ return next;
+ },
+};
diff --git a/examples/zcode-memory-plugin/.mcp.json b/examples/agent-hook-plugin/hosts/cursor/.mcp.json
similarity index 63%
rename from examples/zcode-memory-plugin/.mcp.json
rename to examples/agent-hook-plugin/hosts/cursor/.mcp.json
index 1845bf92f..755d8c0e6 100644
--- a/examples/zcode-memory-plugin/.mcp.json
+++ b/examples/agent-hook-plugin/hosts/cursor/.mcp.json
@@ -3,7 +3,7 @@
"openviking": {
"command": "node",
"args": [
- "${ZCODE_PLUGIN_ROOT}/servers/mcp-proxy.mjs"
+ "__OPENVIKING_PLUGIN_ROOT__/servers/mcp-proxy.mjs"
]
}
}
diff --git a/examples/agent-hook-plugin/hosts/cursor/hooks.json b/examples/agent-hook-plugin/hosts/cursor/hooks.json
new file mode 100644
index 000000000..6bfe6cb5d
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/cursor/hooks.json
@@ -0,0 +1,47 @@
+{
+ "version": 1,
+ "hooks": {
+ "sessionStart": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs sessionStart __OPENVIKING_CLIENT_ID__",
+ "timeout": 30
+ }
+ ],
+ "beforeSubmitPrompt": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs beforeSubmitPrompt __OPENVIKING_CLIENT_ID__",
+ "timeout": 20
+ }
+ ],
+ "beforeReadFile": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",
+ "timeout": 5
+ }
+ ],
+ "beforeShellExecution": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",
+ "timeout": 5
+ }
+ ],
+ "stop": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs stop __OPENVIKING_CLIENT_ID__",
+ "timeout": 30
+ }
+ ],
+ "preCompact": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs preCompact __OPENVIKING_CLIENT_ID__",
+ "timeout": 30
+ }
+ ],
+ "sessionEnd": [
+ {
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs sessionEnd __OPENVIKING_CLIENT_ID__",
+ "timeout": 30
+ }
+ ]
+ }
+}
diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
new file mode 100644
index 000000000..f8f111a71
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json
@@ -0,0 +1,14 @@
+{
+ "schemaVersion": 1,
+ "id": "openviking-memory",
+ "version": "0.3.0",
+ "clients": [
+ "cursor"
+ ],
+ "capabilities": [
+ "hooks",
+ "mcp",
+ "rules",
+ "skills"
+ ]
+}
diff --git a/examples/cursor-memory-plugin/rules/openviking-memory.mdc b/examples/agent-hook-plugin/hosts/cursor/rules/openviking-memory.mdc
similarity index 100%
rename from examples/cursor-memory-plugin/rules/openviking-memory.mdc
rename to examples/agent-hook-plugin/hosts/cursor/rules/openviking-memory.mdc
diff --git a/examples/cursor-memory-plugin/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md
similarity index 100%
rename from examples/cursor-memory-plugin/skills/openviking-memory/SKILL.md
rename to examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md
diff --git a/examples/agent-hook-plugin/hosts/index.mjs b/examples/agent-hook-plugin/hosts/index.mjs
new file mode 100644
index 000000000..a09b505af
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/index.mjs
@@ -0,0 +1,6 @@
+import { cursor } from "./cursor.mjs";
+import { trae, traeCn } from "./trae.mjs";
+import { zcode } from "./zcode.mjs";
+
+/** Every client id the installer can configure, keyed the way it names them. */
+export const HOSTS = { cursor, trae, "trae-cn": traeCn, zcode };
diff --git a/examples/trae-memory-hooks/scripts/trae-turns.mjs b/examples/agent-hook-plugin/hosts/trae-turns.mjs
similarity index 100%
rename from examples/trae-memory-hooks/scripts/trae-turns.mjs
rename to examples/agent-hook-plugin/hosts/trae-turns.mjs
diff --git a/examples/agent-hook-plugin/hosts/trae.mjs b/examples/agent-hook-plugin/hosts/trae.mjs
new file mode 100644
index 000000000..75f8a3a49
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/trae.mjs
@@ -0,0 +1,69 @@
+import {
+ addAgentMessages,
+ commitAgentSession,
+ stableHash,
+} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { filterCaptureTurns } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import { denyHookSpecificOutput, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";
+import { buildTraeTurns, cleanTraeText } from "./trae-turns.mjs";
+
+export const trae = {
+ prefix: "tr-",
+ tracksPendingPrompt: true,
+ capturesOnlyWhenEnabled: true,
+ stages: { "session-start": "start", "user-prompt-submit": "prompt", stop: "capture" },
+ envelope(event, block) {
+ const value = { decision: "approve" };
+ if (block) {
+ value.hookSpecificOutput = {
+ hookEventName: event === "session-start" ? "SessionStart" : "UserPromptSubmit",
+ additionalContext: block,
+ };
+ }
+ return value;
+ },
+ guard(input = {}) {
+ const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;
+ const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};
+ const decision = evaluateUriGuard(toolName, toolInput);
+ return decision ? denyHookSpecificOutput(decision.reason) : {};
+ },
+ prompt: (input) => cleanTraeText(input.prompt),
+ async capture(ctx, state) {
+ const hashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
+ const turnKey = state.pendingPrompt?.at || state.lastTurnKey || state.promptHash || "unknown-turn";
+ const toSend = [];
+ for (const turn of buildTraeTurns(ctx.input, state)) {
+ // Hash the raw turn, not the filtered text, so raising
+ // captureMaxLength never resends one the server already holds
+ // in truncated form.
+ const hash = stableHash(turnKey, turn.role, turn.content);
+ if (hashes.has(hash)) continue;
+ const { kept, dropped } = filterCaptureTurns([turn], ctx.cfg);
+ if (!kept.length) {
+ ctx.log("capture_skip", dropped[0]);
+ hashes.add(hash);
+ continue;
+ }
+ toSend.push({ hash, turn: kept[0] });
+ }
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, toSend.map((item) => item.turn));
+ const captured = result.sent + result.queued;
+ for (const item of toSend.slice(0, captured)) hashes.add(item.hash);
+ let nextCount = Number(state.capturedSinceCommit || 0) + captured;
+ if (captured > 0) {
+ const committed = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
+ if (committed.ok) nextCount = 0;
+ }
+ return {
+ ...state,
+ capturedHashes: [...hashes].slice(-1000),
+ capturedSinceCommit: nextCount,
+ pendingPrompt: null,
+ lastTurnKey: turnKey,
+ };
+ },
+};
+
+// TRAE CN is the same host with its own configuration key and session prefix.
+export const traeCn = { ...trae, prefix: "trcn-" };
diff --git a/examples/agent-hook-plugin/hosts/trae/.mcp.json b/examples/agent-hook-plugin/hosts/trae/.mcp.json
new file mode 100644
index 000000000..755d8c0e6
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/trae/.mcp.json
@@ -0,0 +1,10 @@
+{
+ "mcpServers": {
+ "openviking": {
+ "command": "node",
+ "args": [
+ "__OPENVIKING_PLUGIN_ROOT__/servers/mcp-proxy.mjs"
+ ]
+ }
+ }
+}
diff --git a/examples/trae-memory-hooks/hooks/hooks.json b/examples/agent-hook-plugin/hosts/trae/hooks.json
similarity index 62%
rename from examples/trae-memory-hooks/hooks/hooks.json
rename to examples/agent-hook-plugin/hosts/trae/hooks.json
index dcee7ca46..1c1a7fc2d 100644
--- a/examples/trae-memory-hooks/hooks/hooks.json
+++ b/examples/agent-hook-plugin/hosts/trae/hooks.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_TRAE_ROOT__/scripts/session-start.mjs __OPENVIKING_CLIENT_ID__",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs session-start __OPENVIKING_CLIENT_ID__",
"timeout": 30
}
]
@@ -18,7 +18,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_TRAE_ROOT__/scripts/auto-recall.mjs __OPENVIKING_CLIENT_ID__",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs user-prompt-submit __OPENVIKING_CLIENT_ID__",
"timeout": 20
}
]
@@ -30,7 +30,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_TRAE_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",
"timeout": 5
}
]
@@ -41,7 +41,7 @@
"hooks": [
{
"type": "command",
- "command": "node __OPENVIKING_TRAE_ROOT__/scripts/auto-capture.mjs __OPENVIKING_CLIENT_ID__",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs stop __OPENVIKING_CLIENT_ID__",
"timeout": 30
}
]
diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
new file mode 100644
index 000000000..65758b85c
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json
@@ -0,0 +1,13 @@
+{
+ "schemaVersion": 1,
+ "id": "openviking-memory",
+ "version": "0.3.0",
+ "clients": [
+ "trae",
+ "trae-cn"
+ ],
+ "capabilities": [
+ "hooks",
+ "mcp"
+ ]
+}
diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.mjs b/examples/agent-hook-plugin/hosts/zcode-capture.mjs
similarity index 94%
rename from examples/zcode-memory-plugin/scripts/zcode-capture.mjs
rename to examples/agent-hook-plugin/hosts/zcode-capture.mjs
index 13efb2e48..61f416c6b 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-capture.mjs
+++ b/examples/agent-hook-plugin/hosts/zcode-capture.mjs
@@ -1,5 +1,5 @@
-import { stableHash } from "./shared/agent-hook-runtime.mjs";
-import { shouldCaptureText } from "./shared/capture-utils.mjs";
+import { stableHash } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { shouldCaptureText } from "../../memory-plugin-shared/lib/capture-utils.mjs";
import { cleanZcodeText } from "./zcode-turns.mjs";
export function zcodeTurnDedupKey(turn) {
diff --git a/examples/zcode-memory-plugin/scripts/zcode-turns.mjs b/examples/agent-hook-plugin/hosts/zcode-turns.mjs
similarity index 100%
rename from examples/zcode-memory-plugin/scripts/zcode-turns.mjs
rename to examples/agent-hook-plugin/hosts/zcode-turns.mjs
diff --git a/examples/agent-hook-plugin/hosts/zcode.mjs b/examples/agent-hook-plugin/hosts/zcode.mjs
new file mode 100644
index 000000000..c9bb4ccbf
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/zcode.mjs
@@ -0,0 +1,60 @@
+/**
+ * ZCode adapter.
+ *
+ * Output contract: ZCode validates hook stdout against a strict JSON schema and
+ * silently discards the whole document when it meets a key it does not know, so
+ * the envelope never carries a Claude-Code-ism such as `{ "decision": "approve" }`
+ * and a pass-through writes nothing at all.
+ */
+
+import { addAgentMessages, commitAgentSession } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { denyHookSpecificOutput, evaluateUriGuard } from "../../memory-plugin-shared/lib/uri-guard.mjs";
+import { applyZcodeCaptureResult, buildZcodeCapturePlan } from "./zcode-capture.mjs";
+import { buildZcodeTurns, cleanZcodeText } from "./zcode-turns.mjs";
+
+export const zcode = {
+ prefix: "zc-",
+ tracksPendingPrompt: true,
+ capturesOnlyWhenEnabled: true,
+ detachesCapture: true,
+ stages: { "session-start": "start", "user-prompt-submit": "prompt", stop: "capture" },
+ envelope(event, block) {
+ if (!block) return null;
+ return {
+ hookSpecificOutput: {
+ hookEventName: event === "session-start" ? "SessionStart" : "UserPromptSubmit",
+ additionalContext: block,
+ },
+ };
+ },
+ guard(input = {}) {
+ const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;
+ const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};
+ const decision = evaluateUriGuard(toolName, toolInput);
+ return decision ? denyHookSpecificOutput(decision.reason) : {};
+ },
+ // 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.
+ normalizeInput: (input) => (
+ !input.session_id && input.sessionId ? { ...input, session_id: input.sessionId } : input
+ ),
+ prompt: (input) => cleanZcodeText(
+ input.prompt || input.user_prompt || input.userMessage || input.user_message || input.message || "",
+ ),
+ async capture(ctx, state) {
+ const plan = buildZcodeCapturePlan(buildZcodeTurns(ctx.input, state), state, ctx.cfg);
+ // Fail-closed: if no turns and no dedup keys, skip silently (not an error —
+ // could be a Stop with no new content, or a race with UserPromptSubmit).
+ if (plan.toSend.length === 0) return null;
+
+ const result = await addAgentMessages(ctx.fetchJSON, ctx.sessionId, plan.payloads);
+ const { captured, ...nextState } = applyZcodeCaptureResult(state, plan, result);
+ let nextCount = Number(state.capturedSinceCommit || 0) + captured;
+ if (captured > 0) {
+ const committed = await commitAgentSession(ctx.fetchJSON, ctx.sessionId, ctx.log);
+ if (committed.ok) nextCount = 0;
+ }
+ return { ...nextState, capturedSinceCommit: nextCount };
+ },
+};
diff --git a/examples/agent-hook-plugin/hosts/zcode/.mcp.json b/examples/agent-hook-plugin/hosts/zcode/.mcp.json
new file mode 100644
index 000000000..755d8c0e6
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/zcode/.mcp.json
@@ -0,0 +1,10 @@
+{
+ "mcpServers": {
+ "openviking": {
+ "command": "node",
+ "args": [
+ "__OPENVIKING_PLUGIN_ROOT__/servers/mcp-proxy.mjs"
+ ]
+ }
+ }
+}
diff --git a/examples/zcode-memory-plugin/hooks/hooks.json b/examples/agent-hook-plugin/hosts/zcode/hooks.json
similarity index 60%
rename from examples/zcode-memory-plugin/hooks/hooks.json
rename to examples/agent-hook-plugin/hosts/zcode/hooks.json
index a6f674c56..44c897a04 100644
--- a/examples/zcode-memory-plugin/hooks/hooks.json
+++ b/examples/agent-hook-plugin/hosts/zcode/hooks.json
@@ -5,7 +5,7 @@
"hooks": [
{
"type": "command",
- "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/session-start.mjs\"",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs session-start __OPENVIKING_CLIENT_ID__",
"timeout": 30
}
]
@@ -16,7 +16,7 @@
"hooks": [
{
"type": "command",
- "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/auto-recall.mjs\"",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs user-prompt-submit __OPENVIKING_CLIENT_ID__",
"timeout": 20
}
]
@@ -28,7 +28,7 @@
"hooks": [
{
"type": "command",
- "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/uri-guard.mjs\"",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/uri-guard.mjs __OPENVIKING_CLIENT_ID__",
"timeout": 5
}
]
@@ -39,7 +39,7 @@
"hooks": [
{
"type": "command",
- "command": "node \"${ZCODE_PLUGIN_ROOT}/scripts/auto-capture.mjs\"",
+ "command": "node __OPENVIKING_PLUGIN_ROOT__/scripts/hook.mjs stop __OPENVIKING_CLIENT_ID__",
"timeout": 30
}
]
diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
new file mode 100644
index 000000000..b4a7b08b5
--- /dev/null
+++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json
@@ -0,0 +1,12 @@
+{
+ "schemaVersion": 1,
+ "id": "openviking-memory",
+ "version": "0.3.0",
+ "clients": [
+ "zcode"
+ ],
+ "capabilities": [
+ "hooks",
+ "mcp"
+ ]
+}
diff --git a/examples/zcode-memory-plugin/.zcode-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json
similarity index 51%
rename from examples/zcode-memory-plugin/.zcode-plugin/plugin.json
rename to examples/agent-hook-plugin/plugin.json
index edd2e936f..01568e668 100644
--- a/examples/zcode-memory-plugin/.zcode-plugin/plugin.json
+++ b/examples/agent-hook-plugin/plugin.json
@@ -1,7 +1,7 @@
{
- "name": "openviking-memory",
- "version": "0.1.1",
- "description": "Long-term semantic memory for ZCode, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
+ "name": "agent-hook-plugin",
+ "version": "0.3.0",
+ "description": "Long-term semantic memory for the config-driven hook hosts — Cursor, TRAE, TRAE CN and ZCode — powered by OpenViking. Auto-recall relevant memories at session start and capture the conversation as it happens.",
"author": {
"name": "OpenViking",
"url": "https://github.com/volcengine/OpenViking"
@@ -14,6 +14,5 @@
"semantic-search",
"long-term-memory",
"context-engine"
- ],
- "mcpServers": "./.mcp.json"
+ ]
}
diff --git a/examples/agent-hook-plugin/scripts/hook.mjs b/examples/agent-hook-plugin/scripts/hook.mjs
new file mode 100644
index 000000000..ac581a461
--- /dev/null
+++ b/examples/agent-hook-plugin/scripts/hook.mjs
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+
+/**
+ * The one hook entry cursor, TRAE and ZCode all run.
+ *
+ * Each host names it from its own hooks.json, passing the event and the client
+ * id as arguments; the adapter under `hosts/` supplies everything that differs
+ * — the event vocabulary, the response envelope, how a prompt is read out of
+ * the payload, and how a finished turn is captured. The state machine around
+ * those four things is the same in all three, so it lives here.
+ */
+
+import {
+ buildAgentProfile,
+ createAgentLogger,
+ deriveAgentSessionId,
+ loadAgentHookConfig,
+ makeAgentFetchJSON,
+ recallForPrompt,
+ readHookState,
+ replayAgentPending,
+ resolveNativeSessionId,
+ runHookStage,
+ stableHash,
+ withAgentHookLock,
+ writeHookState,
+} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import { maybeDetach, readHookStdin } from "../../memory-plugin-shared/lib/async-writer.mjs";
+import { isCaptureEnabled } from "../../memory-plugin-shared/lib/capture-utils.mjs";
+import { HOSTS } from "../hosts/index.mjs";
+
+// ZCode's detached writer re-enters this file with no arguments at all, so what
+// the first run put in the environment is what tells the worker what it is.
+const event = process.argv[2] || process.env.OPENVIKING_HOOK_EVENT || "";
+const clientId = process.argv[3] || process.env.OPENVIKING_HOOK_SOURCE || "";
+const host = HOSTS[clientId];
+
+if (!host) {
+ process.stderr.write(`openviking: no hook adapter for ${clientId || "?"}\n`);
+ process.exit(0);
+}
+
+process.env.OPENVIKING_HOOK_EVENT = event;
+process.env.OPENVIKING_HOOK_SOURCE = clientId;
+
+const stageName = host.stages[event] || "";
+let cfg = loadAgentHookConfig(clientId);
+const { log, logError } = createAgentLogger(clientId, event, cfg);
+
+let emitted = false;
+function emit(block) {
+ if (emitted) return;
+ emitted = true;
+ const value = host.envelope(event, block || "");
+ if (value) process.stdout.write(`${JSON.stringify(value)}\n`);
+}
+
+const normalize = (input) => (host.normalizeInput ? host.normalizeInput(input) : input);
+
+const contextBlock = (source, body) => (
+ body ? `<openviking-context source="${source}">\n${body}\n</openviking-context>` : ""
+);
+
+async function sessionStart(ctx) {
+ return withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
+ const state = await readHookState(clientId, ctx.nativeSessionId);
+ const now = Date.now();
+ if (now - Number(state.lastSessionStartAt || 0) < 2000) return "";
+ await writeHookState(clientId, ctx.nativeSessionId, { ...state, lastSessionStartAt: now });
+ await replayAgentPending(ctx.fetchJSON, log).catch((error) => logError("pending", error));
+ const profile = await buildAgentProfile(ctx.fetchJSON, ctx.cfg, ctx.cwd).catch((error) => {
+ logError("profile", error);
+ return null;
+ });
+ return contextBlock("session-start", profile);
+ });
+}
+
+async function promptSubmit(ctx) {
+ const prompt = host.prompt(ctx.input);
+ if (!prompt) return "";
+ return withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
+ const state = await readHookState(clientId, ctx.nativeSessionId);
+ const promptHash = stableHash(prompt);
+ const now = Date.now();
+ const { input } = ctx;
+ 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 "";
+ const recallBlock = state.promptHash === promptHash && state.recallBlock
+ ? state.recallBlock
+ : await recallForPrompt(ctx.fetchJSON, ctx.cfg, prompt, ctx.cwd, log, { sessionId: ctx.sessionId })
+ .catch((error) => {
+ logError("recall", error);
+ return null;
+ });
+ await writeHookState(clientId, ctx.nativeSessionId, {
+ ...state,
+ promptHash,
+ promptEventId,
+ promptAt: now,
+ recallBlock,
+ ...(host.tracksPendingPrompt ? { pendingPrompt: { prompt, hash: promptHash, at: now } } : {}),
+ });
+ return recallBlock || "";
+ });
+}
+
+async function capture(ctx) {
+ if (host.capturesOnlyWhenEnabled && !isCaptureEnabled(ctx.cfg)) return "";
+ await withAgentHookLock(clientId, ctx.nativeSessionId, async () => {
+ const state = await readHookState(clientId, ctx.nativeSessionId);
+ const next = await host.capture(ctx, state, event);
+ if (next) await writeHookState(clientId, ctx.nativeSessionId, next);
+ });
+ return "";
+}
+
+async function main() {
+ // The write path answers before it works, so the detach decision is taken
+ // against this process's directory, before stdin is consumed.
+ if (host.detachesCapture && stageName === "capture" && isCaptureEnabled(cfg)
+ && await maybeDetach(cfg, { approve: () => emit() })) {
+ return;
+ }
+ await runHookStage({
+ clientId,
+ input: { read: readHookStdin, tolerant: true },
+ // These harnesses spell the session id in more ways than a payload key, so
+ // the gate is given the same resolver the hook's own state files use.
+ sessionId: (payload) => resolveNativeSessionId(normalize(payload)),
+ gates: { enabled: (value) => value.enabled },
+ envelope: emit,
+ onSkip: (reason) => log("skip", { reason }),
+ }, async ({ cfg: resolved, cwd, input }) => {
+ cfg = resolved;
+ const payload = normalize(input);
+ if (!stageName) return "";
+ const ctx = {
+ cfg,
+ cwd,
+ input: payload,
+ nativeSessionId: resolveNativeSessionId(payload),
+ sessionId: deriveAgentSessionId(host.prefix, payload),
+ fetchJSON: makeAgentFetchJSON(cfg, cwd).fetchJSON,
+ log,
+ logError,
+ };
+ if (stageName === "start") return sessionStart(ctx);
+ if (stageName === "prompt") return promptSubmit(ctx);
+ return capture(ctx);
+ });
+}
+
+main().catch((error) => {
+ logError("uncaught", error);
+ emit();
+});
diff --git a/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs b/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs
new file mode 100644
index 000000000..e60a1aed5
--- /dev/null
+++ b/examples/agent-hook-plugin/scripts/ov-memory-doctor.mjs
@@ -0,0 +1,257 @@
+#!/usr/bin/env node
+
+/**
+ * Client-side diagnostics for the config-driven hook hosts.
+ *
+ * Cursor, TRAE, TRAE CN and ZCode are installed by writing into the host's own
+ * configuration files rather than through a plugin marketplace, so what can go
+ * wrong is different from Claude Code's and Codex's: the host config may have
+ * lost the OpenViking entries, the assembled runtime beside the integration may
+ * be missing or stale, or the client may simply never have been installed. The
+ * configuration and connection sections are the ones every harness shares.
+ *
+ * Usage:
+ * node ov-memory-doctor.mjs [<client>] [--json] [--offline] [--timeout <ms>] [--no-color]
+ *
+ * The client defaults to the one this copy was installed for. Exit code 1 when
+ * any check fails, 0 otherwise. Never prints a full api key.
+ */
+
+import { readdirSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join, resolve as resolvePath } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
+import {
+ credentialSources,
+ existsPath,
+ fmtAge,
+ fmtBytes,
+ homeShort,
+ inspectConfigFiles,
+ inspectJsonFile,
+ reportCredentials,
+ reportPeer,
+ reportTimeouts,
+ reportToggles,
+ runDoctor,
+ scanDebugLog,
+ sweepEnv,
+ tryJson,
+} from "../../memory-plugin-shared/lib/doctor-core.mjs";
+
+const PLUGIN_ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), "..");
+const REQUIRED_PLUGIN_FILES = ["plugin.json", "scripts/hook.mjs", "scripts/uri-guard.mjs", "servers/mcp-proxy.mjs", "hosts/index.mjs"];
+
+/**
+ * Where each client keeps the two things the installer writes.
+ *
+ * ZCode reads both out of one config file; the rest keep hooks and MCP apart,
+ * and TRAE's MCP path is the editor's platform-specific user directory.
+ */
+const CLIENTS = {
+ cursor: {
+ cliName: "cursor",
+ launcherHint: "Cursor",
+ hooks: () => join(homedir(), ".cursor", "hooks.json"),
+ mcp: () => join(homedir(), ".cursor", "mcp.json"),
+ extras: () => [
+ join(homedir(), ".cursor", "rules", "openviking-memory.mdc"),
+ join(homedir(), ".cursor", "skills", "openviking-memory", "SKILL.md"),
+ ],
+ timeoutBudgets: { beforeSubmitPrompt: "recallTimeoutMs", stop: "captureTimeoutMs" },
+ },
+ trae: {
+ cliName: "trae",
+ launcherHint: "TRAE",
+ hooks: () => join(homedir(), ".trae", "hooks.json"),
+ mcp: () => (process.platform === "darwin"
+ ? join(homedir(), "Library", "Application Support", "Trae", "User", "mcp.json")
+ : join(homedir(), ".trae", "mcp.json")),
+ timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
+ },
+ "trae-cn": {
+ cliName: "trae",
+ launcherHint: "TRAE CN",
+ hooks: () => join(homedir(), ".trae-cn", "hooks.json"),
+ mcp: () => (process.platform === "darwin"
+ ? join(homedir(), "Library", "Application Support", "Trae CN", "User", "mcp.json")
+ : join(homedir(), ".trae-cn", "mcp.json")),
+ timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
+ },
+ zcode: {
+ cliName: "zcode",
+ launcherHint: "ZCode",
+ hooks: () => join(homedir(), ".zcode", "cli", "config.json"),
+ mcp: () => join(homedir(), ".zcode", "cli", "config.json"),
+ timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
+ },
+};
+
+/** The client this copy serves: the argument, the install manifest, or cursor. */
+function resolveClient(argv) {
+ const named = argv.find((arg) => CLIENTS[arg]);
+ if (named) return named;
+ const installed = tryJson(join(PLUGIN_ROOT, "integration.json"));
+ return CLIENTS[installed?.client] ? installed.client : "cursor";
+}
+
+const CLIENT = resolveClient(process.argv.slice(2));
+const SPEC = CLIENTS[CLIENT];
+// TRAE CN is served by the TRAE host directory.
+const HOST_DIR = CLIENT === "trae-cn" ? "trae" : CLIENT;
+
+function hookStateDir() {
+ const root = process.env.OPENVIKING_HOOK_STATE_DIR || join(homedir(), ".openviking", "hook-state");
+ return join(root, CLIENT);
+}
+
+function checkInstall(report) {
+ report.section("Plugin install");
+ const manifest = tryJson(join(PLUGIN_ROOT, "plugin.json"));
+ const installed = tryJson(join(PLUGIN_ROOT, "integration.json"));
+ report.info(`running from ${homeShort(PLUGIN_ROOT)} (version ${manifest?.version || "?"}, client ${CLIENT})`);
+ if (installed?.client && installed.client !== CLIENT) {
+ report.warn(`this copy was installed for ${installed.client}, not ${CLIENT}`, "", `run the ${installed.client} copy, or pass the client name as an argument`);
+ }
+
+ const missing = REQUIRED_PLUGIN_FILES.filter((rel) => !existsPath(join(PLUGIN_ROOT, rel)));
+ if (missing.length) report.fail("plugin files missing", missing.join(", "), `bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness ${CLIENT}`);
+ else report.ok("plugin files present (hook entry, URI guard, MCP proxy, host adapters)");
+
+ // The runtime is not vendored: it sits beside the integration, assembled from
+ // lib/MANIFEST at install time. A stale or absent copy is ERR_MODULE_NOT_FOUND
+ // on the first hook, which the host reports as nothing at all.
+ const shared = resolvePath(PLUGIN_ROOT, "..", "memory-plugin-shared", "lib");
+ const modules = existsPath(shared) ? readdirSync(shared).filter((name) => name.endsWith(".mjs")) : [];
+ if (!modules.length) report.fail("the shared runtime is not assembled beside this integration", homeShort(shared), `re-run the installer with --harness ${CLIENT}`);
+ else report.ok(`shared runtime: ${modules.length} modules in ${homeShort(shared)}`);
+ if (!existsPath(join(PLUGIN_ROOT, "hosts", HOST_DIR, "hooks.json"))) {
+ report.fail(`no hooks template for ${CLIENT}`, "", "re-run the installer");
+ }
+
+ const hooksPath = SPEC.hooks();
+ const hooks = inspectJsonFile(hooksPath);
+ if (!hooks.exists) report.fail(`${homeShort(hooksPath)} not found`, `${SPEC.launcherHint} has no hook configuration on this machine`, `re-run the installer with --harness ${CLIENT}`);
+ else if (!hooks.ok) report.fail(`${homeShort(hooksPath)} cannot be parsed`, hooks.error, "fix the JSON; the installer refuses to overwrite a file it cannot read");
+ else {
+ const text = JSON.stringify(hooks.data);
+ const events = Object.keys(hooks.data.hooks?.events || hooks.data.hooks || {});
+ if (!text.includes("OPENVIKING_INTEGRATION_ID")) report.fail(`${homeShort(hooksPath)} has no OpenViking hooks`, `events present: ${events.join(", ") || "(none)"}`, `re-run the installer with --harness ${CLIENT}`);
+ else {
+ report.ok(`hooks in ${homeShort(hooksPath)}: ${events.join(", ")}`);
+ if (!text.includes("scripts/hook.mjs")) report.warn("the installed hook commands do not name scripts/hook.mjs", "they were written by an older installer", "re-run the installer");
+ if (CLIENT === "zcode" && hooks.data.hooks?.enabled !== true) report.fail("ZCode's hook runner is off", "config.json has hooks.enabled != true, so no hook fires", "re-run the installer, or set hooks.enabled = true");
+ }
+ for (const command of String(text).match(/'([^']*\.mjs)'/gu) || []) {
+ const script = command.slice(1, -1);
+ if (!existsPath(script)) report.fail("an installed hook names a script that is not on disk", script, "re-run the installer");
+ }
+ }
+
+ const mcpPath = SPEC.mcp();
+ const mcp = inspectJsonFile(mcpPath);
+ const server = mcp.ok ? (mcp.data.mcpServers?.openviking || mcp.data.mcp?.servers?.openviking) : null;
+ if (!mcp.exists) report.warn(`${homeShort(mcpPath)} not found`, "the MCP memory tools are not wired up", `re-run the installer with --harness ${CLIENT}`);
+ else if (!mcp.ok) report.fail(`${homeShort(mcpPath)} cannot be parsed`, mcp.error, "fix the JSON");
+ else if (!server) report.fail(`no 'openviking' MCP server in ${homeShort(mcpPath)}`, "", `re-run the installer with --harness ${CLIENT}`);
+ else {
+ report.ok(`MCP server 'openviking' in ${homeShort(mcpPath)}`);
+ const proxy = Array.isArray(server.args) ? server.args.find((arg) => String(arg).endsWith("mcp-proxy.mjs")) : "";
+ if (proxy && !existsPath(proxy)) report.fail("the MCP server points at a proxy that is not on disk", proxy, "re-run the installer");
+ if (server.env?.OPENVIKING_HOOK_SOURCE && server.env.OPENVIKING_HOOK_SOURCE !== CLIENT) {
+ report.warn(`the MCP server is tagged for ${server.env.OPENVIKING_HOOK_SOURCE}`, `this copy serves ${CLIENT}; the proxy reads its configuration under the tagged client`, "re-run the installer");
+ }
+ }
+
+ for (const extra of SPEC.extras?.() || []) {
+ if (!existsPath(extra)) report.warn(`${homeShort(extra)} is missing`, "", `re-run the installer with --harness ${CLIENT}`);
+ }
+}
+
+function checkConfig(report, cfg, host) {
+ report.section("Configuration");
+ const { cliConf, ovConf } = inspectConfigFiles(report, host);
+ if (!cliConf.ok && !ovConf.ok && !(process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL)) {
+ report.fail("no usable config — the plugin falls back to http://127.0.0.1:1933 with no key", "", "create ~/.openviking/ovcli.conf with url + api_key (chmod 600)");
+ }
+ const keyInfo = reportCredentials(report, cfg, credentialSources(cfg, cliConf, ovConf), { account: cfg.account, user: cfg.user });
+ report.info(`auth mode ${cfg.authMode} (identity headers ${cfg.sendIdentityHeaders ? "sent" : "not sent"})`);
+ const peer = reportPeer(report, cfg);
+ reportTimeouts(report, cfg, host);
+
+ const toggles = [
+ `auto-recall ${cfg.autoRecall ? "on" : "OFF"}`,
+ `auto-capture ${cfg.autoCapture ? "on" : "OFF"}`,
+ `write path ${cfg.writePathAsync ? "async" : "sync"}`,
+ ];
+ if (CLIENT === "cursor") toggles.push(`commit threshold ${cfg.commitTurnThreshold}`);
+ reportToggles(report, cfg, host, toggles);
+
+ sweepEnv(report, cfg, host);
+ return { keyInfo, peer, ovConf };
+}
+
+function checkActivity(report, cfg, connection) {
+ report.section("Recent activity");
+ const dir = hookStateDir();
+ let states = [];
+ try {
+ states = readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => {
+ const path = join(dir, name);
+ return { name, mtimeMs: statSync(path).mtimeMs, data: tryJson(path) };
+ }).sort((a, b) => b.mtimeMs - a.mtimeMs);
+ } catch {
+ report.info(`no hook state in ${homeShort(dir)} yet — no ${SPEC.launcherHint} hook has run (or OPENVIKING_HOOK_STATE_DIR points elsewhere)`);
+ }
+ if (states.length) {
+ const newest = states[0];
+ report.info(`${states.length} session state file(s) in ${homeShort(dir)}; newest ${fmtAge(newest.mtimeMs)}`);
+ const captured = states.filter((state) => (state.data?.capturedHashes?.length || state.data?.capturedTurnIds?.length || 0) > 0);
+ if (states.length > 3 && !captured.length) {
+ report.warn("no session has ever captured a turn", "the Stop hook runs but never appends messages", "check the Connection section; set OPENVIKING_DEBUG=1 and read the hook log");
+ }
+ if (newest.data?.recallBlock === null) report.info("the last prompt recalled nothing — an empty context space, or a failed request the log will name");
+ }
+
+ const log = scanDebugLog(cfg.debugLogPath);
+ if (!log.exists) {
+ report.info(`no hook log at ${homeShort(cfg.debugLogPath)}${cfg.debug ? ` — debug is on but no hook has run since; if a ${SPEC.launcherHint} turn ran, hooks are not being spawned` : ""}`);
+ } else {
+ report.info(`hook log ${homeShort(log.path)} — ${fmtBytes(log.size)}, last write ${fmtAge(log.mtimeMs)}, hooks seen: ${log.hooks.join(", ") || "(none)"}`);
+ if (log.recentErrors.length) report.warn(`hook errors in the last day of logging (${log.recentErrors.length} shown)`, log.recentErrors.map((e) => `${e.ts} ${e.hook}/${e.stage}: ${e.message}`).join("\n"));
+ }
+ if (connection?.summary?.reachable === false) report.info("captures that fail are queued on disk and replayed at the next session start");
+}
+
+const HOST = {
+ harness: CLIENT,
+ pluginRoot: PLUGIN_ROOT,
+ hooksTemplate: join(PLUGIN_ROOT, "hosts", HOST_DIR, "hooks.json"),
+ cliName: SPEC.cliName,
+ launcherHint: SPEC.launcherHint,
+ timeoutBudgets: SPEC.timeoutBudgets,
+ loadConfig: () => loadAgentHookConfig(CLIENT),
+ checkInstall,
+ checkConfig,
+ checkActivity,
+ resolveIdentity: (cfg) => ({ account: cfg.account, user: cfg.user }),
+ extraResolved: (cfg) => ({ client: CLIENT, credentialSource: cfg.credentialSource, authMode: cfg.authMode }),
+};
+
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
+ }
+}
+
+if (isDirectRun()) {
+ runDoctor(HOST).catch((err) => {
+ console.error("ov-memory-doctor failed:", err?.stack || err?.message || err);
+ process.exit(2);
+ });
+}
diff --git a/examples/agent-hook-plugin/scripts/uri-guard.mjs b/examples/agent-hook-plugin/scripts/uri-guard.mjs
new file mode 100644
index 000000000..dd7f63844
--- /dev/null
+++ b/examples/agent-hook-plugin/scripts/uri-guard.mjs
@@ -0,0 +1,13 @@
+#!/usr/bin/env node
+
+import { runUriGuardHook } from "../../memory-plugin-shared/lib/uri-guard.mjs";
+import { HOSTS } from "../hosts/index.mjs";
+
+// The deny envelope is the host's: Cursor answers its own permission shape,
+// TRAE and ZCode the PreToolUse one.
+export function evaluateHostUriGuard(clientId, input = {}) {
+ return HOSTS[clientId] ? HOSTS[clientId].guard(input) : {};
+}
+
+const client = process.argv[2] || process.env.OPENVIKING_HOOK_SOURCE || "";
+runUriGuardHook(import.meta.url, (input) => evaluateHostUriGuard(client, input));
diff --git a/examples/trae-cli-memory-hooks/servers/mcp-proxy.mjs b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
old mode 100755
new mode 100644
similarity index 53%
rename from examples/trae-cli-memory-hooks/servers/mcp-proxy.mjs
rename to examples/agent-hook-plugin/servers/mcp-proxy.mjs
index ba1165404..f0f4e8188
--- a/examples/trae-cli-memory-hooks/servers/mcp-proxy.mjs
+++ b/examples/agent-hook-plugin/servers/mcp-proxy.mjs
@@ -5,24 +5,32 @@ import { resolve as resolvePath } from "node:path";
import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
import { createLogger } from "../../memory-plugin-shared/lib/debug-log.mjs";
+import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../../memory-plugin-shared/lib/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../../memory-plugin-shared/lib/mcp-proxy-core.mjs";
+import { HOSTS } from "../hosts/index.mjs";
function readConfig() {
- const cfg = loadAgentHookConfig("trae-cli");
- return {
+ // The installer writes the client id into the MCP server's environment; it is
+ // the only thing that tells this proxy which harness launched it. A hand-written
+ // entry that names none resolves through the layers every harness shares rather
+ // than borrowing another client's `plugin.<harness>` section.
+ const requested = process.env.OPENVIKING_HOOK_SOURCE || "";
+ const cfg = loadAgentHookConfig(HOSTS[requested] ? requested : "agent-hook");
+ return buildMcpProxyConfig({
mcpUrl: cfg.mcpUrl,
apiKey: cfg.apiKey,
account: cfg.account,
user: cfg.user,
- peerId: cfg.peerId,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
+ peerId: resolveMcpActorPeerId(cfg),
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),
- };
+ watchedPaths: [cfg.cliPath, cfg.ovPath],
+ });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
diff --git a/examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs b/examples/agent-hook-plugin/tests/cursor.test.mjs
similarity index 79%
rename from examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs
rename to examples/agent-hook-plugin/tests/cursor.test.mjs
index 5b7f15355..6a3fe2f4f 100644
--- a/examples/cursor-memory-plugin/scripts/cursor-plugin.test.mjs
+++ b/examples/agent-hook-plugin/tests/cursor.test.mjs
@@ -1,67 +1,42 @@
import assert from "node:assert/strict";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
-import { parseCursorTranscript } from "./cursor-transcript.mjs";
-import { evaluateCursorUriGuard } from "./uri-guard.mjs";
+import { expectExit, runHookScript } from "../../memory-plugin-shared/testing/support.mjs";
+import { parseCursorTranscript } from "../hosts/cursor-transcript.mjs";
+import { evaluateHostUriGuard } from "../scripts/uri-guard.mjs";
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const hookEntry = resolve(pluginRoot, "scripts", "hook.mjs");
-function runHook(event, input, env) {
- const entrypoint = {
- sessionStart: "session-start.mjs",
- beforeSubmitPrompt: "auto-recall.mjs",
- stop: "auto-capture.mjs",
- preCompact: "pre-compact.mjs",
- sessionEnd: "session-end.mjs",
- }[event];
- return new Promise((resolveRun, reject) => {
- const child = spawn(process.execPath, [join(pluginRoot, "scripts", entrypoint)], {
- env: { ...process.env, ...env },
- stdio: ["pipe", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => { stdout += chunk; });
- child.stderr.on("data", (chunk) => { stderr += chunk; });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code !== 0) reject(new Error(stderr || `hook exited ${code}`));
- else resolveRun(JSON.parse(stdout.trim() || "{}"));
- });
- child.stdin.end(JSON.stringify(input));
- });
+async function runHook(event, input, env) {
+ const run = expectExit(await runHookScript(hookEntry, { argv: [event, "cursor"], input, env }));
+ return JSON.parse(run.stdout.trim() || "{}");
}
test("Cursor command-installed integration contains Hook, Rule, Skill, and MCP entrypoints", () => {
for (const file of [
- ".cursor-plugin/plugin.json",
- "hooks/hooks.json",
- ".mcp.json",
- "openviking.integration.json",
- "scripts/cursor-hook.mjs",
- "scripts/session-start.mjs",
- "scripts/auto-recall.mjs",
- "scripts/auto-capture.mjs",
- "scripts/pre-compact.mjs",
- "scripts/session-end.mjs",
- "scripts/cursor-transcript.mjs",
+ "plugin.json",
+ "hosts/cursor/hooks.json",
+ "hosts/cursor/.mcp.json",
+ "hosts/cursor/openviking.integration.json",
+ "hosts/cursor.mjs",
+ "hosts/cursor-transcript.mjs",
+ "scripts/hook.mjs",
"scripts/uri-guard.mjs",
"servers/mcp-proxy.mjs",
- "rules/openviking-memory.mdc",
- "skills/openviking-memory/SKILL.md",
+ "hosts/cursor/rules/openviking-memory.mdc",
+ "hosts/cursor/skills/openviking-memory/SKILL.md",
]) {
assert.ok(existsSync(join(pluginRoot, file)), `${file} must exist`);
}
- const plugin = JSON.parse(readFileSync(join(pluginRoot, ".cursor-plugin", "plugin.json"), "utf8"));
- const integration = JSON.parse(readFileSync(join(pluginRoot, "openviking.integration.json"), "utf8"));
- const hooks = JSON.parse(readFileSync(join(pluginRoot, "hooks", "hooks.json"), "utf8"));
- assert.equal(plugin.name, integration.id);
+ const plugin = JSON.parse(readFileSync(join(pluginRoot, "plugin.json"), "utf8"));
+ const integration = JSON.parse(readFileSync(join(pluginRoot, "hosts", "cursor", "openviking.integration.json"), "utf8"));
+ const hooks = JSON.parse(readFileSync(join(pluginRoot, "hosts", "cursor", "hooks.json"), "utf8"));
assert.equal(plugin.version, integration.version);
assert.deepEqual(Object.keys(hooks.hooks), [
"sessionStart",
@@ -75,19 +50,19 @@ test("Cursor command-installed integration contains Hook, Rule, Skill, and MCP e
});
test("Cursor URI guard redirects virtual paths to OpenViking MCP tools", () => {
- const readDecision = evaluateCursorUriGuard({
+ const readDecision = evaluateHostUriGuard("cursor", {
file_path: "viking://resources/project/file.md",
});
assert.equal(readDecision.permission, "deny");
assert.match(readDecision.user_message, /OpenViking MCP read/);
- const shellDecision = evaluateCursorUriGuard({
+ const shellDecision = evaluateHostUriGuard("cursor", {
command: "cat viking://resources/project/file.md",
});
assert.equal(shellDecision.permission, "deny");
assert.match(shellDecision.agent_message, /OpenViking MCP read or search/);
- assert.deepEqual(evaluateCursorUriGuard({ file_path: "/tmp/file.md" }), {});
+ assert.deepEqual(evaluateHostUriGuard("cursor", { file_path: "/tmp/file.md" }), {});
});
test("Cursor transcript parser keeps only user and assistant text", () => {
diff --git a/examples/trae-memory-hooks/scripts/trae-hooks.test.mjs b/examples/agent-hook-plugin/tests/trae.test.mjs
similarity index 75%
rename from examples/trae-memory-hooks/scripts/trae-hooks.test.mjs
rename to examples/agent-hook-plugin/tests/trae.test.mjs
index 8f88c4b24..1d5849ee3 100644
--- a/examples/trae-memory-hooks/scripts/trae-hooks.test.mjs
+++ b/examples/agent-hook-plugin/tests/trae.test.mjs
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -7,26 +6,25 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
-import { buildTraeTurns, cleanTraeText } from "./trae-turns.mjs";
-import { evaluateTraeUriGuard } from "./uri-guard.mjs";
+import { expectExit, runHookScript } from "../../memory-plugin-shared/testing/support.mjs";
+import { buildTraeTurns, cleanTraeText } from "../hosts/trae-turns.mjs";
+import { evaluateHostUriGuard } from "../scripts/uri-guard.mjs";
const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
+const hookEntry = join(pluginRoot, "scripts", "hook.mjs");
test("TRAE integration contains native Hook and MCP declarations", () => {
for (const file of [
- "hooks/hooks.json",
- ".mcp.json",
- "openviking.integration.json",
- "scripts/trae-hook.mjs",
- "scripts/session-start.mjs",
- "scripts/auto-recall.mjs",
- "scripts/auto-capture.mjs",
+ "hosts/trae/hooks.json",
+ "hosts/trae/.mcp.json",
+ "hosts/trae/openviking.integration.json",
+ "hosts/trae.mjs",
"scripts/uri-guard.mjs",
]) {
assert.ok(existsSync(join(pluginRoot, file)), `${file} must exist`);
}
- const integration = JSON.parse(readFileSync(join(pluginRoot, "openviking.integration.json"), "utf8"));
- const hooks = JSON.parse(readFileSync(join(pluginRoot, "hooks", "hooks.json"), "utf8"));
+ const integration = JSON.parse(readFileSync(join(pluginRoot, "hosts", "trae", "openviking.integration.json"), "utf8"));
+ const hooks = JSON.parse(readFileSync(join(pluginRoot, "hosts", "trae", "hooks.json"), "utf8"));
assert.deepEqual(integration.clients, ["trae", "trae-cn"]);
assert.deepEqual(Object.keys(hooks.hooks), [
"SessionStart",
@@ -37,7 +35,7 @@ test("TRAE integration contains native Hook and MCP declarations", () => {
});
test("TRAE URI guard follows the Claude Code PreToolUse response contract", () => {
- const denied = evaluateTraeUriGuard({
+ const denied = evaluateHostUriGuard("trae", {
tool_name: "Read",
tool_input: { file_path: "viking://resources/project/file.md" },
});
@@ -47,34 +45,15 @@ test("TRAE URI guard follows the Claude Code PreToolUse response contract", () =
denied.hookSpecificOutput?.permissionDecisionReason ?? "",
/OpenViking MCP read/,
);
- assert.deepEqual(evaluateTraeUriGuard({
+ assert.deepEqual(evaluateHostUriGuard("trae", {
tool_name: "Read",
tool_input: { file_path: "/tmp/file.md" },
}), {});
});
-function runHook(event, client, input, env) {
- const entrypoint = {
- "session-start": "session-start.mjs",
- "user-prompt-submit": "auto-recall.mjs",
- stop: "auto-capture.mjs",
- }[event];
- return new Promise((resolveRun, reject) => {
- const child = spawn(process.execPath, [join(pluginRoot, "scripts", entrypoint), client], {
- env: { ...process.env, ...env },
- stdio: ["pipe", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => { stdout += chunk; });
- child.stderr.on("data", (chunk) => { stderr += chunk; });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code !== 0) reject(new Error(stderr || `hook exited ${code}`));
- else resolveRun(JSON.parse(stdout.trim() || "{}"));
- });
- child.stdin.end(JSON.stringify(input));
- });
+async function runHook(event, client, input, env) {
+ const run = expectExit(await runHookScript(hookEntry, { argv: [event, client], input, env }));
+ return JSON.parse(run.stdout.trim() || "{}");
}
test("TRAE capture uses event fields rather than a transcript path", () => {
@@ -129,15 +108,15 @@ test("TRAE prompt hook injects recall and Stop captures dedicated event fields",
]);
assert.equal(recalled.filter((item) => /trae memory/.test(item.hookSpecificOutput?.additionalContext || "")).length, 1);
await Promise.all([
- runHook("stop", "trae-cn", { ...base, last_assistant_message: "done" }, env),
- runHook("stop", "trae-cn", { ...base, last_assistant_message: "done" }, env),
+ runHook("stop", "trae-cn", { ...base, last_assistant_message: "the retry budget is three attempts" }, env),
+ runHook("stop", "trae-cn", { ...base, last_assistant_message: "the retry budget is three attempts" }, env),
]);
assert.equal(messages.length, 2);
assert.equal(commits.length, 1, "the completed TRAE turn must be committed immediately");
assert.ok(messages.every((item) => item.url.includes("trcn-same-session")));
await runHook("user-prompt-submit", "trae-cn", { ...base, prompt: "remember this", generation_id: "prompt-2" }, env);
- await runHook("stop", "trae-cn", { ...base, last_assistant_message: "done" }, env);
+ await runHook("stop", "trae-cn", { ...base, last_assistant_message: "the retry budget is three attempts" }, env);
assert.equal(messages.length, 4, "a later identical turn must not be mistaken for a duplicate Hook run");
assert.equal(commits.length, 2);
} finally {
diff --git a/examples/zcode-memory-plugin/scripts/zcode-async.test.mjs b/examples/agent-hook-plugin/tests/zcode-async.test.mjs
similarity index 83%
rename from examples/zcode-memory-plugin/scripts/zcode-async.test.mjs
rename to examples/agent-hook-plugin/tests/zcode-async.test.mjs
index 1c9429617..6674f2f46 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-async.test.mjs
+++ b/examples/agent-hook-plugin/tests/zcode-async.test.mjs
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -7,7 +6,9 @@ import { join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-const hook = fileURLToPath(new URL("./auto-capture.mjs", import.meta.url));
+import { expectExit, runHookScript } from "../../memory-plugin-shared/testing/support.mjs";
+
+const hook = fileURLToPath(new URL("../scripts/hook.mjs", import.meta.url));
// Mirrors OPENVIKING_TIMEOUT_MS below: the parent must never stall this long.
const HOOK_TIMEOUT_MS = 5000;
@@ -34,18 +35,7 @@ function waitFor(predicate, timeoutMs = 5000) {
}
function runHook(input, env) {
- return new Promise((resolve) => {
- const child = spawn(process.execPath, [hook], {
- env: { ...process.env, ...env },
- stdio: ["pipe", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => { stdout += chunk; });
- child.stderr.on("data", (chunk) => { stderr += chunk; });
- child.on("close", (status) => resolve({ status, stdout, stderr }));
- child.stdin.end(JSON.stringify(input));
- });
+ return runHookScript(hook, { argv: ["stop", "zcode"], input, env });
}
test("Stop returns before slow writes while detached worker finishes capture", async (t) => {
@@ -84,26 +74,20 @@ test("Stop returns before slow writes while detached worker finishes capture", a
);
const startedAt = Date.now();
- const child = spawn(process.execPath, [hook], {
+ const run = await runHookScript(hook, {
+ argv: ["stop", "zcode"],
+ input: { session_id: sessionId, cwd: home },
env: {
- ...process.env,
HOME: home,
OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
OPENVIKING_WRITE_PATH_ASYNC: "1",
OPENVIKING_TIMEOUT_MS: String(HOOK_TIMEOUT_MS),
},
- stdio: ["pipe", "pipe", "pipe"],
});
- child.stdin.end(JSON.stringify({ session_id: sessionId, cwd: home }));
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => { stdout += chunk; });
- child.stderr.on("data", (chunk) => { stderr += chunk; });
- const exitCode = await new Promise((resolve) => child.on("close", resolve));
const elapsedMs = Date.now() - startedAt;
- assert.equal(exitCode, 0, stderr);
- assert.equal(stdout, "");
+ expectExit(run);
+ assert.equal(run.stdout, "");
// Core async-path guarantee, independent of wall-clock speed: every server
// response is delayed 700ms, so a parent that exits with zero completed
// responses provably never awaited the network. A synchronous fallback
@@ -184,16 +168,14 @@ test("400 failure does not advance state and successful retry prevents duplicate
OPENVIKING_TIMEOUT_MS: String(HOOK_TIMEOUT_MS),
};
- const first = await runHook({ session_id: sessionId, cwd: home }, env);
- assert.equal(first.status, 0, first.stderr);
+ expectExit(await runHook({ session_id: sessionId, cwd: home }, env));
const failedState = JSON.parse(readFileSync(statePath, "utf8"));
assert.equal(failedState.lastTurnId ?? null, null);
assert.deepEqual(failedState.capturedTurnIds, []);
assert.deepEqual(failedState.pendingPrompt, pendingPrompt);
assert.equal(requests.length, 1);
- const second = await runHook({ session_id: sessionId, cwd: home }, env);
- assert.equal(second.status, 0, second.stderr);
+ expectExit(await runHook({ session_id: sessionId, cwd: home }, env));
const retriedBatch = requests.filter(({ url }) => url?.endsWith("/messages/batch"))[1];
assert.deepEqual(JSON.parse(retriedBatch.body), {
messages: [
@@ -211,7 +193,6 @@ test("400 failure does not advance state and successful retry prevents duplicate
assert.equal(successfulState.captured, undefined);
const requestCountAfterSuccess = requests.length;
- const third = await runHook({ session_id: sessionId, cwd: home }, env);
- assert.equal(third.status, 0, third.stderr);
+ expectExit(await runHook({ session_id: sessionId, cwd: home }, env));
assert.equal(requests.length, requestCountAfterSuccess);
});
diff --git a/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs b/examples/agent-hook-plugin/tests/zcode-capture.test.mjs
similarity index 99%
rename from examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs
rename to examples/agent-hook-plugin/tests/zcode-capture.test.mjs
index 1e1bd7fb7..97a44c4e2 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-capture.test.mjs
+++ b/examples/agent-hook-plugin/tests/zcode-capture.test.mjs
@@ -4,7 +4,7 @@ import test from "node:test";
import {
applyZcodeCaptureResult,
buildZcodeCapturePlan,
-} from "./zcode-capture.mjs";
+} from "../hosts/zcode-capture.mjs";
const turns = [
{ role: "user", content: "question", turnId: "turn-001" },
diff --git a/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs b/examples/agent-hook-plugin/tests/zcode-turns.test.mjs
similarity index 99%
rename from examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
rename to examples/agent-hook-plugin/tests/zcode-turns.test.mjs
index 8d5bbd518..97ffa8830 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-turns.test.mjs
+++ b/examples/agent-hook-plugin/tests/zcode-turns.test.mjs
@@ -3,7 +3,7 @@ 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";
+import { buildZcodeTurns, cleanZcodeText, extractUnseenRolloutTurns } from "../hosts/zcode-turns.mjs";
test("cleanZcodeText strips openviking-context blocks", () => {
const input = "hello <openviking-context source=\"test\">secret</openviking-context> world";
diff --git a/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs b/examples/agent-hook-plugin/tests/zcode.test.mjs
similarity index 67%
rename from examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
rename to examples/agent-hook-plugin/tests/zcode.test.mjs
index 3efe14d4e..a4318074d 100644
--- a/examples/zcode-memory-plugin/scripts/zcode-hooks.test.mjs
+++ b/examples/agent-hook-plugin/tests/zcode.test.mjs
@@ -3,7 +3,7 @@ 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";
+import { evaluateHostUriGuard } from "../scripts/uri-guard.mjs";
const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
@@ -14,7 +14,7 @@ const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
// ---------------------------------------------------------------------------
test("uri guard deny output contains only recognized keys", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Read",
tool_input: { file_path: "viking://~/memories/profile.md" },
});
@@ -28,7 +28,7 @@ test("uri guard deny output contains only recognized keys", () => {
});
test("uri guard deny reason includes MCP redirect", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Read",
tool_input: { file_path: "viking://resources/myproject/docs.md" },
});
@@ -37,7 +37,7 @@ test("uri guard deny reason includes MCP redirect", () => {
});
test("uri guard pass-through for non-viking URIs returns empty", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Read",
tool_input: { file_path: "/tmp/local-file.txt" },
});
@@ -45,7 +45,7 @@ test("uri guard pass-through for non-viking URIs returns empty", () => {
});
test("uri guard pass-through for Glob with local pattern", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Glob",
tool_input: { pattern: "**/*.ts" },
});
@@ -53,7 +53,7 @@ test("uri guard pass-through for Glob with local pattern", () => {
});
test("uri guard deny for Glob with viking URI", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Glob",
tool_input: { pattern: "viking://user/memories/**" },
});
@@ -61,7 +61,7 @@ test("uri guard deny for Glob with viking URI", () => {
});
test("uri guard handles alternative tool_input field names", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Read",
toolInput: { file_path: "viking://user/test.md" },
});
@@ -69,7 +69,7 @@ test("uri guard handles alternative tool_input field names", () => {
});
test("uri guard handles alternative tool_name field names", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
toolName: "Read",
tool_input: { file_path: "viking://user/test.md" },
});
@@ -77,11 +77,11 @@ test("uri guard handles alternative tool_name field names", () => {
});
test("uri guard returns empty for unmatched tool name", () => {
- const output = evaluateZcodeUriGuard({
+ const output = evaluateHostUriGuard("zcode", {
tool_name: "Bash",
tool_input: { command: "cat viking://user/test.md" },
});
- // Bash is not in the Read|Glob|Grep matcher — but evaluateAgentUriGuard
+ // Bash is not in the Read|Glob|Grep matcher — but evaluateUriGuard
// 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) {
@@ -90,30 +90,33 @@ test("uri guard returns empty for unmatched tool name", () => {
});
// ---------------------------------------------------------------------------
-// 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.
+// Source-file conventions: the installer expands the plugin root, and it knows
+// one spelling of it. A host-specific spelling reaches ZCode verbatim, where
+// nothing expands it.
// ---------------------------------------------------------------------------
-test("hooks.json uses ZCODE_PLUGIN_ROOT, not CLAUDE_PLUGIN_ROOT", () => {
- const hooksJson = readFileSync(join(PLUGIN_ROOT, "hooks", "hooks.json"), "utf8");
+const HOST_ROOT_VARIABLE = /(?:CLAUDE|CURSOR|ZCODE)_PLUGIN_ROOT/u;
+
+test("hooks.json templates the plugin root the installer expands", () => {
+ const hooksJson = readFileSync(join(PLUGIN_ROOT, "hosts", "zcode", "hooks.json"), "utf8");
assert.ok(
- !hooksJson.includes("CLAUDE_PLUGIN_ROOT"),
- "hooks.json should use ${ZCODE_PLUGIN_ROOT}, not ${CLAUDE_PLUGIN_ROOT}",
+ !HOST_ROOT_VARIABLE.test(hooksJson),
+ "hooks.json should use __OPENVIKING_PLUGIN_ROOT__, not a host-specific root variable",
);
assert.ok(
- hooksJson.includes("ZCODE_PLUGIN_ROOT"),
- "hooks.json should reference ${ZCODE_PLUGIN_ROOT}",
+ hooksJson.includes("__OPENVIKING_PLUGIN_ROOT__"),
+ "hooks.json should reference __OPENVIKING_PLUGIN_ROOT__",
);
});
-test(".mcp.json uses ZCODE_PLUGIN_ROOT, not CLAUDE_PLUGIN_ROOT", () => {
- const mcpJson = readFileSync(join(PLUGIN_ROOT, ".mcp.json"), "utf8");
+test(".mcp.json templates the plugin root the installer expands", () => {
+ const mcpJson = readFileSync(join(PLUGIN_ROOT, "hosts", "zcode", ".mcp.json"), "utf8");
assert.ok(
- !mcpJson.includes("CLAUDE_PLUGIN_ROOT"),
- ".mcp.json should use ${ZCODE_PLUGIN_ROOT}, not ${CLAUDE_PLUGIN_ROOT}",
+ !HOST_ROOT_VARIABLE.test(mcpJson),
+ ".mcp.json should use __OPENVIKING_PLUGIN_ROOT__, not a host-specific root variable",
);
assert.ok(
- mcpJson.includes("ZCODE_PLUGIN_ROOT"),
- ".mcp.json should reference ${ZCODE_PLUGIN_ROOT}",
+ mcpJson.includes("__OPENVIKING_PLUGIN_ROOT__"),
+ ".mcp.json should reference __OPENVIKING_PLUGIN_ROOT__",
);
});
diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
index f0c3f5acb..a14b19be3 100644
--- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
+++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.4.7",
+ "version": "0.5.0",
"description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.",
"author": {
"name": "OpenViking",
diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.md
index 9ab12e5f0..b1f0f8ab6 100644
--- a/examples/claude-code-memory-plugin/README.md
+++ b/examples/claude-code-memory-plugin/README.md
@@ -392,7 +392,6 @@ Set `claude_code.debug: true` in `ov.conf` or `OPENVIKING_DEBUG=1` to write hook
- `auto-recall` logs key stages plus a compact `ranking_summary` by default.
- Set `claude_code.logRankingDetails: true` only when investigating per-candidate scoring; output is verbose.
-- For deep diagnosis, run the standalone scripts `scripts/debug-recall.mjs` and `scripts/debug-capture.mjs` against a sample input rather than leaving the hook log on permanently.
## Troubleshooting
@@ -413,7 +412,7 @@ Or just ask Claude to check the plugin: the `ov-memory-doctor` skill runs the sa
| Remote auth 401 / 403 | API key / account / user header mismatch | Verify `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER` (or their `ov.conf` counterparts) |
| `Stop` hook times out | Server slow + sync write path | Leave `writePathAsync: true` (default), or raise the `Stop` timeout in `hooks/hooks.json` |
| Old context keeps re-appearing in OV | Pre-fix versions captured the recall block back into OV | Update to current version — `auto-capture` now strips `<openviking-context>` before pushing |
-| Logs are noisy | `logRankingDetails: true` left on | Set `false`; use `debug-recall.mjs` / `debug-capture.mjs` for one-off inspection |
+| Logs are noisy | `logRankingDetails: true` left on | Set `false`; the compact `ranking_summary` stays in the log |
## Compared to Claude Code's built-in memory
@@ -514,8 +513,6 @@ claude-code-memory-plugin/
│ ├── pre-compact.mjs # PreCompact
│ ├── subagent-start.mjs # SubagentStart
│ ├── subagent-stop.mjs # SubagentStop
-│ ├── debug-recall.mjs # standalone diagnostic for recall
-│ ├── debug-capture.mjs # standalone diagnostic for capture
│ ├── ov-status.mjs # /ov status report
│ ├── ov-memory-doctor.mjs # diagnostics script (ov-memory-doctor skill)
│ └── lib/
diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.md
index 78a88f1a2..fc5f76e3c 100644
--- a/examples/claude-code-memory-plugin/README_CN.md
+++ b/examples/claude-code-memory-plugin/README_CN.md
@@ -342,7 +342,6 @@ OV ✓ │ 🔗 resumed │ +3 today session 已恢复上下文;
- `auto-recall` 默认输出关键阶段 + 紧凑的 `ranking_summary`
- 仅在排查每候选打分时才把 `claude_code.logRankingDetails` 设为 `true`,否则非常啰嗦
-- 深度排查请用 `scripts/debug-recall.mjs` / `scripts/debug-capture.mjs` 单跑示例输入,不要长期开 hook 日志
## 故障排除
@@ -363,7 +362,7 @@ node "$(jq -r '.plugins["openviking-memory@openviking"][0].installPath' ~/.claud
| 远程鉴权 401 / 403 | API key / account / user 头错配 | 核对 `OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`(或 `ov.conf` 对应字段) |
| `Stop` hook 超时 | 服务器慢 + 同步写路径 | 保持 `writePathAsync: true`(默认),或调大 `hooks/hooks.json` 里的 `Stop` 超时 |
| 旧上下文反复出现在 OV 里 | 早期版本把召回块当成用户消息回写了 | 升级到当前版本——`auto-capture` 现在推送前会剥离 `<openviking-context>` |
-| 日志太吵 | `logRankingDetails: true` 没关 | 设为 `false`;按需用 `debug-recall.mjs` / `debug-capture.mjs` |
+| 日志太吵 | `logRankingDetails: true` 没关 | 设为 `false`;日志里仍保留紧凑的 `ranking_summary` |
## 与 Claude Code 内置记忆的对比
@@ -464,8 +463,6 @@ claude-code-memory-plugin/
│ ├── pre-compact.mjs # PreCompact
│ ├── subagent-start.mjs # SubagentStart
│ ├── subagent-stop.mjs # SubagentStop
-│ ├── debug-recall.mjs # 召回独立诊断
-│ ├── debug-capture.mjs # 捕获独立诊断
│ ├── ov-status.mjs # /ov 状态报告
│ ├── ov-memory-doctor.mjs # 体检脚本(ov-memory-doctor skill)
│ └── lib/
diff --git a/examples/claude-code-memory-plugin/package-lock.json b/examples/claude-code-memory-plugin/package-lock.json
deleted file mode 100644
index 6771592ec..000000000
--- a/examples/claude-code-memory-plugin/package-lock.json
+++ /dev/null
@@ -1,1174 +0,0 @@
-{
- "name": "claude-code-openviking-memory",
- "version": "0.4.4",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "claude-code-openviking-memory",
- "version": "0.4.4",
- "dependencies": {
- "@modelcontextprotocol/sdk": "^1.12.1",
- "zod": "^4.3.6"
- },
- "devDependencies": {
- "@types/node": "^22.0.0",
- "typescript": "^5.7.0"
- }
- },
- "node_modules/@hono/node-server": {
- "version": "1.19.11",
- "resolved": "https://registry.npmmirror.com/@hono/node-server/-/node-server-1.19.11.tgz",
- "integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==",
- "license": "MIT",
- "engines": {
- "node": ">=18.14.1"
- },
- "peerDependencies": {
- "hono": "^4"
- }
- },
- "node_modules/@modelcontextprotocol/sdk": {
- "version": "1.27.1",
- "resolved": "https://registry.npmmirror.com/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz",
- "integrity": "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA==",
- "license": "MIT",
- "dependencies": {
- "@hono/node-server": "^1.19.9",
- "ajv": "^8.17.1",
- "ajv-formats": "^3.0.1",
- "content-type": "^1.0.5",
- "cors": "^2.8.5",
- "cross-spawn": "^7.0.5",
- "eventsource": "^3.0.2",
- "eventsource-parser": "^3.0.0",
- "express": "^5.2.1",
- "express-rate-limit": "^8.2.1",
- "hono": "^4.11.4",
- "jose": "^6.1.3",
- "json-schema-typed": "^8.0.2",
- "pkce-challenge": "^5.0.0",
- "raw-body": "^3.0.0",
- "zod": "^3.25 || ^4.0",
- "zod-to-json-schema": "^3.25.1"
- },
- "engines": {
- "node": ">=18"
- },
- "peerDependencies": {
- "@cfworker/json-schema": "^4.1.1",
- "zod": "^3.25 || ^4.0"
- },
- "peerDependenciesMeta": {
- "@cfworker/json-schema": {
- "optional": true
- },
- "zod": {
- "optional": false
- }
- }
- },
- "node_modules/@types/node": {
- "version": "22.19.15",
- "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.19.15.tgz",
- "integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "undici-types": "~6.21.0"
- }
- },
- "node_modules/accepts": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/accepts/-/accepts-2.0.0.tgz",
- "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
- "license": "MIT",
- "dependencies": {
- "mime-types": "^3.0.0",
- "negotiator": "^1.0.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/ajv": {
- "version": "8.18.0",
- "resolved": "https://registry.npmmirror.com/ajv/-/ajv-8.18.0.tgz",
- "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
- "license": "MIT",
- "dependencies": {
- "fast-deep-equal": "^3.1.3",
- "fast-uri": "^3.0.1",
- "json-schema-traverse": "^1.0.0",
- "require-from-string": "^2.0.2"
- },
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/epoberezkin"
- }
- },
- "node_modules/ajv-formats": {
- "version": "3.0.1",
- "resolved": "https://registry.npmmirror.com/ajv-formats/-/ajv-formats-3.0.1.tgz",
- "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
- "license": "MIT",
- "dependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependencies": {
- "ajv": "^8.0.0"
- },
- "peerDependenciesMeta": {
- "ajv": {
- "optional": true
- }
- }
- },
- "node_modules/body-parser": {
- "version": "2.2.2",
- "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-2.2.2.tgz",
- "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",
- "license": "MIT",
- "dependencies": {
- "bytes": "^3.1.2",
- "content-type": "^1.0.5",
- "debug": "^4.4.3",
- "http-errors": "^2.0.0",
- "iconv-lite": "^0.7.0",
- "on-finished": "^2.4.1",
- "qs": "^6.14.1",
- "raw-body": "^3.0.1",
- "type-is": "^2.0.1"
- },
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/bytes": {
- "version": "3.1.2",
- "resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz",
- "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/call-bind-apply-helpers": {
- "version": "1.0.2",
- "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
- "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0",
- "function-bind": "^1.1.2"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/call-bound": {
- "version": "1.0.4",
- "resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz",
- "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
- "license": "MIT",
- "dependencies": {
- "call-bind-apply-helpers": "^1.0.2",
- "get-intrinsic": "^1.3.0"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/content-disposition": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-1.0.1.tgz",
- "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==",
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/content-type": {
- "version": "1.0.5",
- "resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz",
- "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/cookie": {
- "version": "0.7.2",
- "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz",
- "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/cookie-signature": {
- "version": "1.2.2",
- "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.2.2.tgz",
- "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
- "license": "MIT",
- "engines": {
- "node": ">=6.6.0"
- }
- },
- "node_modules/cors": {
- "version": "2.8.6",
- "resolved": "https://registry.npmmirror.com/cors/-/cors-2.8.6.tgz",
- "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
- "license": "MIT",
- "dependencies": {
- "object-assign": "^4",
- "vary": "^1"
- },
- "engines": {
- "node": ">= 0.10"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/cross-spawn": {
- "version": "7.0.6",
- "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz",
- "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
- "license": "MIT",
- "dependencies": {
- "path-key": "^3.1.0",
- "shebang-command": "^2.0.0",
- "which": "^2.0.1"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/debug": {
- "version": "4.4.3",
- "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz",
- "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "license": "MIT",
- "dependencies": {
- "ms": "^2.1.3"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
- "node_modules/depd": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/depd/-/depd-2.0.0.tgz",
- "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/dunder-proto": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz",
- "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
- "license": "MIT",
- "dependencies": {
- "call-bind-apply-helpers": "^1.0.1",
- "es-errors": "^1.3.0",
- "gopd": "^1.2.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/ee-first": {
- "version": "1.1.1",
- "resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz",
- "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
- "license": "MIT"
- },
- "node_modules/encodeurl": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-2.0.0.tgz",
- "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/es-define-property": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz",
- "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-errors": {
- "version": "1.3.0",
- "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz",
- "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-object-atoms": {
- "version": "1.1.1",
- "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
- "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/escape-html": {
- "version": "1.0.3",
- "resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz",
- "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
- "license": "MIT"
- },
- "node_modules/etag": {
- "version": "1.8.1",
- "resolved": "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz",
- "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/eventsource": {
- "version": "3.0.7",
- "resolved": "https://registry.npmmirror.com/eventsource/-/eventsource-3.0.7.tgz",
- "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
- "license": "MIT",
- "dependencies": {
- "eventsource-parser": "^3.0.1"
- },
- "engines": {
- "node": ">=18.0.0"
- }
- },
- "node_modules/eventsource-parser": {
- "version": "3.0.6",
- "resolved": "https://registry.npmmirror.com/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
- "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
- "license": "MIT",
- "engines": {
- "node": ">=18.0.0"
- }
- },
- "node_modules/express": {
- "version": "5.2.1",
- "resolved": "https://registry.npmmirror.com/express/-/express-5.2.1.tgz",
- "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
- "license": "MIT",
- "dependencies": {
- "accepts": "^2.0.0",
- "body-parser": "^2.2.1",
- "content-disposition": "^1.0.0",
- "content-type": "^1.0.5",
- "cookie": "^0.7.1",
- "cookie-signature": "^1.2.1",
- "debug": "^4.4.0",
- "depd": "^2.0.0",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "etag": "^1.8.1",
- "finalhandler": "^2.1.0",
- "fresh": "^2.0.0",
- "http-errors": "^2.0.0",
- "merge-descriptors": "^2.0.0",
- "mime-types": "^3.0.0",
- "on-finished": "^2.4.1",
- "once": "^1.4.0",
- "parseurl": "^1.3.3",
- "proxy-addr": "^2.0.7",
- "qs": "^6.14.0",
- "range-parser": "^1.2.1",
- "router": "^2.2.0",
- "send": "^1.1.0",
- "serve-static": "^2.2.0",
- "statuses": "^2.0.1",
- "type-is": "^2.0.1",
- "vary": "^1.1.2"
- },
- "engines": {
- "node": ">= 18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/express-rate-limit": {
- "version": "8.3.1",
- "resolved": "https://registry.npmmirror.com/express-rate-limit/-/express-rate-limit-8.3.1.tgz",
- "integrity": "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw==",
- "license": "MIT",
- "dependencies": {
- "ip-address": "10.1.0"
- },
- "engines": {
- "node": ">= 16"
- },
- "funding": {
- "url": "https://github.com/sponsors/express-rate-limit"
- },
- "peerDependencies": {
- "express": ">= 4.11"
- }
- },
- "node_modules/fast-deep-equal": {
- "version": "3.1.3",
- "resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
- "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
- "license": "MIT"
- },
- "node_modules/fast-uri": {
- "version": "3.1.0",
- "resolved": "https://registry.npmmirror.com/fast-uri/-/fast-uri-3.1.0.tgz",
- "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/fastify"
- },
- {
- "type": "opencollective",
- "url": "https://opencollective.com/fastify"
- }
- ],
- "license": "BSD-3-Clause"
- },
- "node_modules/finalhandler": {
- "version": "2.1.1",
- "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-2.1.1.tgz",
- "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.4.0",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "on-finished": "^2.4.1",
- "parseurl": "^1.3.3",
- "statuses": "^2.0.1"
- },
- "engines": {
- "node": ">= 18.0.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/forwarded": {
- "version": "0.2.0",
- "resolved": "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz",
- "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/fresh": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/fresh/-/fresh-2.0.0.tgz",
- "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/function-bind": {
- "version": "1.1.2",
- "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz",
- "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/get-intrinsic": {
- "version": "1.3.0",
- "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
- "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
- "license": "MIT",
- "dependencies": {
- "call-bind-apply-helpers": "^1.0.2",
- "es-define-property": "^1.0.1",
- "es-errors": "^1.3.0",
- "es-object-atoms": "^1.1.1",
- "function-bind": "^1.1.2",
- "get-proto": "^1.0.1",
- "gopd": "^1.2.0",
- "has-symbols": "^1.1.0",
- "hasown": "^2.0.2",
- "math-intrinsics": "^1.1.0"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/get-proto": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz",
- "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
- "license": "MIT",
- "dependencies": {
- "dunder-proto": "^1.0.1",
- "es-object-atoms": "^1.0.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/gopd": {
- "version": "1.2.0",
- "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz",
- "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/has-symbols": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz",
- "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/hasown": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz",
- "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
- "license": "MIT",
- "dependencies": {
- "function-bind": "^1.1.2"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/hono": {
- "version": "4.12.8",
- "resolved": "https://registry.npmmirror.com/hono/-/hono-4.12.8.tgz",
- "integrity": "sha512-VJCEvtrezO1IAR+kqEYnxUOoStaQPGrCmX3j4wDTNOcD1uRPFpGlwQUIW8niPuvHXaTUxeOUl5MMDGrl+tmO9A==",
- "license": "MIT",
- "engines": {
- "node": ">=16.9.0"
- }
- },
- "node_modules/http-errors": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz",
- "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
- "license": "MIT",
- "dependencies": {
- "depd": "~2.0.0",
- "inherits": "~2.0.4",
- "setprototypeof": "~1.2.0",
- "statuses": "~2.0.2",
- "toidentifier": "~1.0.1"
- },
- "engines": {
- "node": ">= 0.8"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/iconv-lite": {
- "version": "0.7.2",
- "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.7.2.tgz",
- "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
- "license": "MIT",
- "dependencies": {
- "safer-buffer": ">= 2.1.2 < 3.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/inherits": {
- "version": "2.0.4",
- "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz",
- "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
- "license": "ISC"
- },
- "node_modules/ip-address": {
- "version": "10.1.0",
- "resolved": "https://registry.npmmirror.com/ip-address/-/ip-address-10.1.0.tgz",
- "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
- "license": "MIT",
- "engines": {
- "node": ">= 12"
- }
- },
- "node_modules/ipaddr.js": {
- "version": "1.9.1",
- "resolved": "https://registry.npmmirror.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
- "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.10"
- }
- },
- "node_modules/is-promise": {
- "version": "4.0.0",
- "resolved": "https://registry.npmmirror.com/is-promise/-/is-promise-4.0.0.tgz",
- "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
- "license": "MIT"
- },
- "node_modules/isexe": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz",
- "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
- "license": "ISC"
- },
- "node_modules/jose": {
- "version": "6.2.2",
- "resolved": "https://registry.npmmirror.com/jose/-/jose-6.2.2.tgz",
- "integrity": "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/panva"
- }
- },
- "node_modules/json-schema-traverse": {
- "version": "1.0.0",
- "resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
- "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
- "license": "MIT"
- },
- "node_modules/json-schema-typed": {
- "version": "8.0.2",
- "resolved": "https://registry.npmmirror.com/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
- "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
- "license": "BSD-2-Clause"
- },
- "node_modules/math-intrinsics": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
- "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/media-typer": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-1.1.0.tgz",
- "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/merge-descriptors": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
- "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
- "license": "MIT",
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "url": "https://github.com/sponsors/sindresorhus"
- }
- },
- "node_modules/mime-db": {
- "version": "1.54.0",
- "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.54.0.tgz",
- "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mime-types": {
- "version": "3.0.2",
- "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-3.0.2.tgz",
- "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
- "license": "MIT",
- "dependencies": {
- "mime-db": "^1.54.0"
- },
- "engines": {
- "node": ">=18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/ms": {
- "version": "2.1.3",
- "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "license": "MIT"
- },
- "node_modules/negotiator": {
- "version": "1.0.0",
- "resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-1.0.0.tgz",
- "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/object-assign": {
- "version": "4.1.1",
- "resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz",
- "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/object-inspect": {
- "version": "1.13.4",
- "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz",
- "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/on-finished": {
- "version": "2.4.1",
- "resolved": "https://registry.npmmirror.com/on-finished/-/on-finished-2.4.1.tgz",
- "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
- "license": "MIT",
- "dependencies": {
- "ee-first": "1.1.1"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/once": {
- "version": "1.4.0",
- "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz",
- "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
- "license": "ISC",
- "dependencies": {
- "wrappy": "1"
- }
- },
- "node_modules/parseurl": {
- "version": "1.3.3",
- "resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz",
- "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/path-key": {
- "version": "3.1.1",
- "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz",
- "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/path-to-regexp": {
- "version": "8.3.0",
- "resolved": "https://registry.npmmirror.com/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
- "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
- "license": "MIT",
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/pkce-challenge": {
- "version": "5.0.1",
- "resolved": "https://registry.npmmirror.com/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
- "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
- "license": "MIT",
- "engines": {
- "node": ">=16.20.0"
- }
- },
- "node_modules/proxy-addr": {
- "version": "2.0.7",
- "resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz",
- "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
- "license": "MIT",
- "dependencies": {
- "forwarded": "0.2.0",
- "ipaddr.js": "1.9.1"
- },
- "engines": {
- "node": ">= 0.10"
- }
- },
- "node_modules/qs": {
- "version": "6.15.0",
- "resolved": "https://registry.npmmirror.com/qs/-/qs-6.15.0.tgz",
- "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==",
- "license": "BSD-3-Clause",
- "dependencies": {
- "side-channel": "^1.1.0"
- },
- "engines": {
- "node": ">=0.6"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/range-parser": {
- "version": "1.2.1",
- "resolved": "https://registry.npmmirror.com/range-parser/-/range-parser-1.2.1.tgz",
- "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/raw-body": {
- "version": "3.0.2",
- "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-3.0.2.tgz",
- "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
- "license": "MIT",
- "dependencies": {
- "bytes": "~3.1.2",
- "http-errors": "~2.0.1",
- "iconv-lite": "~0.7.0",
- "unpipe": "~1.0.0"
- },
- "engines": {
- "node": ">= 0.10"
- }
- },
- "node_modules/require-from-string": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/require-from-string/-/require-from-string-2.0.2.tgz",
- "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
- "license": "MIT",
- "engines": {
- "node": ">=0.10.0"
- }
- },
- "node_modules/router": {
- "version": "2.2.0",
- "resolved": "https://registry.npmmirror.com/router/-/router-2.2.0.tgz",
- "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.4.0",
- "depd": "^2.0.0",
- "is-promise": "^4.0.0",
- "parseurl": "^1.3.3",
- "path-to-regexp": "^8.0.0"
- },
- "engines": {
- "node": ">= 18"
- }
- },
- "node_modules/safer-buffer": {
- "version": "2.1.2",
- "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz",
- "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
- "license": "MIT"
- },
- "node_modules/send": {
- "version": "1.2.1",
- "resolved": "https://registry.npmmirror.com/send/-/send-1.2.1.tgz",
- "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
- "license": "MIT",
- "dependencies": {
- "debug": "^4.4.3",
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "etag": "^1.8.1",
- "fresh": "^2.0.0",
- "http-errors": "^2.0.1",
- "mime-types": "^3.0.2",
- "ms": "^2.1.3",
- "on-finished": "^2.4.1",
- "range-parser": "^1.2.1",
- "statuses": "^2.0.2"
- },
- "engines": {
- "node": ">= 18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/serve-static": {
- "version": "2.2.1",
- "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-2.2.1.tgz",
- "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
- "license": "MIT",
- "dependencies": {
- "encodeurl": "^2.0.0",
- "escape-html": "^1.0.3",
- "parseurl": "^1.3.3",
- "send": "^1.2.0"
- },
- "engines": {
- "node": ">= 18"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/express"
- }
- },
- "node_modules/setprototypeof": {
- "version": "1.2.0",
- "resolved": "https://registry.npmmirror.com/setprototypeof/-/setprototypeof-1.2.0.tgz",
- "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
- "license": "ISC"
- },
- "node_modules/shebang-command": {
- "version": "2.0.0",
- "resolved": "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz",
- "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
- "license": "MIT",
- "dependencies": {
- "shebang-regex": "^3.0.0"
- },
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/shebang-regex": {
- "version": "3.0.0",
- "resolved": "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz",
- "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
- "node_modules/side-channel": {
- "version": "1.1.0",
- "resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.0.tgz",
- "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0",
- "object-inspect": "^1.13.3",
- "side-channel-list": "^1.0.0",
- "side-channel-map": "^1.0.1",
- "side-channel-weakmap": "^1.0.2"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/side-channel-list": {
- "version": "1.0.0",
- "resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.0.tgz",
- "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0",
- "object-inspect": "^1.13.3"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/side-channel-map": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz",
- "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
- "license": "MIT",
- "dependencies": {
- "call-bound": "^1.0.2",
- "es-errors": "^1.3.0",
- "get-intrinsic": "^1.2.5",
- "object-inspect": "^1.13.3"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/side-channel-weakmap": {
- "version": "1.0.2",
- "resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
- "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
- "license": "MIT",
- "dependencies": {
- "call-bound": "^1.0.2",
- "es-errors": "^1.3.0",
- "get-intrinsic": "^1.2.5",
- "object-inspect": "^1.13.3",
- "side-channel-map": "^1.0.1"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/statuses": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz",
- "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/toidentifier": {
- "version": "1.0.1",
- "resolved": "https://registry.npmmirror.com/toidentifier/-/toidentifier-1.0.1.tgz",
- "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
- "license": "MIT",
- "engines": {
- "node": ">=0.6"
- }
- },
- "node_modules/type-is": {
- "version": "2.0.1",
- "resolved": "https://registry.npmmirror.com/type-is/-/type-is-2.0.1.tgz",
- "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
- "license": "MIT",
- "dependencies": {
- "content-type": "^1.0.5",
- "media-typer": "^1.1.0",
- "mime-types": "^3.0.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/typescript": {
- "version": "5.9.3",
- "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
- "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
- "license": "Apache-2.0",
- "bin": {
- "tsc": "bin/tsc",
- "tsserver": "bin/tsserver"
- },
- "engines": {
- "node": ">=14.17"
- }
- },
- "node_modules/undici-types": {
- "version": "6.21.0",
- "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
- "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
- "dev": true,
- "license": "MIT"
- },
- "node_modules/unpipe": {
- "version": "1.0.0",
- "resolved": "https://registry.npmmirror.com/unpipe/-/unpipe-1.0.0.tgz",
- "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/vary": {
- "version": "1.1.2",
- "resolved": "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz",
- "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/which": {
- "version": "2.0.2",
- "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz",
- "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
- "license": "ISC",
- "dependencies": {
- "isexe": "^2.0.0"
- },
- "bin": {
- "node-which": "bin/node-which"
- },
- "engines": {
- "node": ">= 8"
- }
- },
- "node_modules/wrappy": {
- "version": "1.0.2",
- "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz",
- "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
- "license": "ISC"
- },
- "node_modules/zod": {
- "version": "4.3.6",
- "resolved": "https://registry.npmmirror.com/zod/-/zod-4.3.6.tgz",
- "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/colinhacks"
- }
- },
- "node_modules/zod-to-json-schema": {
- "version": "3.25.1",
- "resolved": "https://registry.npmmirror.com/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz",
- "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==",
- "license": "ISC",
- "peerDependencies": {
- "zod": "^3.25 || ^4"
- }
- }
- }
-}
diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json
index 9fb3f932a..cc3309675 100644
--- a/examples/claude-code-memory-plugin/package.json
+++ b/examples/claude-code-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-code-openviking-memory",
- "version": "0.4.7",
+ "version": "0.5.0",
"description": "OpenViking memory plugin for Claude Code — semantic long-term memory",
"type": "module",
"scripts": {
diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
index 9e45bbaf1..7733b1955 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
@@ -16,7 +16,7 @@
* Incremental tracking: state file per CC session_id records capturedTurnCount.
*
* Ported from openclaw-plugin/ context-engine.ts + text-utils.ts
- * (sanitize / MEMORY_TRIGGERS / extractNewTurnMessages).
+ * (MEMORY_TRIGGERS / extractNewTurnMessages).
*/
import { readFile, writeFile, mkdir } from "node:fs/promises";
@@ -24,18 +24,19 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
+import { extractCaptureTurns, parseTranscript, sanitizeCapturedText } from "./cc-transcript.mjs";
import {
commitSession,
deriveOvSessionId,
enqueuePendingDirectly,
getSession,
- isBypassed,
isRetryableFailure,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
import { readJsonState, writeJsonState } from "./lib/state.mjs";
import { getEffectivePeerId } from "./lib/workspace-peer.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
import { sendSessionMessages } from "./shared/batch-send.mjs";
import { filterCaptureParts } from "./shared/capture-utils.mjs";
@@ -44,9 +45,9 @@ if (!isPluginEnabled()) {
process.exit(0);
}
-let cfg = loadConfig();
+const baseCfg = loadConfig();
const { log, logError } = createLogger("auto-capture");
-const fetchJSON = makeFetchJSON(cfg, "captureTimeoutMs");
+const fetchJSON = makeFetchJSON(baseCfg, "captureTimeoutMs");
const STATE_DIR = join(tmpdir(), "openviking-cc-capture-state");
@@ -81,7 +82,7 @@ async function saveState(sessionId, state) {
} catch { /* best effort */ }
}
-async function reconcileKnownFailedCapture(sessionId, ovSessionId, state) {
+async function reconcileKnownFailedCapture(cfg, sessionId, ovSessionId, state) {
if (
state.capturedTurnCount <= 0
|| cfg.captureMode !== "semantic"
@@ -127,10 +128,7 @@ async function reconcileKnownFailedCapture(sessionId, ovSessionId, state) {
}
}
-// ---------------------------------------------------------------------------
-// Text processing (ported from openclaw-plugin/text-utils.ts)
-// ---------------------------------------------------------------------------
-
+// Keyword-mode gate (ported from openclaw-plugin/text-utils.ts).
const MEMORY_TRIGGERS = [
/remember|preference|prefer|important|decision|decided|always|never/i,
/记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,
@@ -141,272 +139,14 @@ const MEMORY_TRIGGERS = [
/(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,
];
-const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;
-const OPENVIKING_CTX_BLOCK_RE = /<openviking-context>[\s\S]*?<\/openviking-context>/gi;
-const SYSTEM_REMINDER_BLOCK_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
-const SUBAGENT_CONTEXT_LINE_RE = /^\[Subagent Context\][^\n]*$/gmi;
-const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;
-const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;
-const CJK_CHAR_RE = /[぀-ヿ㐀-鿿豈-﫿가-힯]/;
-// Question-only heuristic (ported from openclaw-plugin/text-utils.ts
-// looksLikeQuestionOnlyText). Pure interrogatives rarely yield memories.
-const QUESTION_ONLY_RE = /^(who|what|when|where|why|how|is|are|does|did|can|could|would|should|may|might|will|谁|什么|何|哪|为什么|怎么|如何|是|会|能|能否)\b.{0,200}[??]$/i;
-
-// Strip plugin-injected blocks (auto-recall context, system reminders,
-// subagent context, relevant-memories) without collapsing whitespace —
-// preserves the user's original formatting (newlines, code blocks) for
-// storage in OV. Without this, the auto-recall block we inject this turn
-// would be captured back into OV next turn, causing a self-referential
-// pollution loop.
-function stripInjectedBlocks(text) {
- return text
- .replace(RELEVANT_MEMORIES_BLOCK_RE, "")
- .replace(OPENVIKING_CTX_BLOCK_RE, "")
- .replace(SYSTEM_REMINDER_BLOCK_RE, "")
- .replace(SUBAGENT_CONTEXT_LINE_RE, "")
- .replace(/\x00/g, "");
-}
-
-function sanitize(text) {
- return stripInjectedBlocks(text)
- .replace(/\s+/g, " ")
- .trim();
-}
-
-function shouldCapture(text) {
- const normalized = sanitize(text);
- if (!normalized) return { capture: false, reason: "empty", text: "" };
-
- const compact = normalized.replace(/\s+/g, "");
- const minLen = CJK_CHAR_RE.test(compact) ? 4 : 10;
- if (compact.length < minLen || normalized.length > cfg.captureMaxLength) {
- return { capture: false, reason: "length_out_of_range", text: normalized };
- }
-
- if (COMMAND_TEXT_RE.test(normalized)) {
- return { capture: false, reason: "command", text: normalized };
- }
-
- if (NON_CONTENT_TEXT_RE.test(normalized)) {
- return { capture: false, reason: "non_content", text: normalized };
- }
-
- if (QUESTION_ONLY_RE.test(normalized)) {
- return { capture: false, reason: "question_only", text: normalized };
- }
-
- if (cfg.captureMode === "keyword") {
- for (const trigger of MEMORY_TRIGGERS) {
- if (trigger.test(normalized)) {
- return { capture: true, reason: `trigger:${trigger}`, text: normalized };
- }
- }
- return { capture: false, reason: "no_trigger", text: normalized };
- }
-
- // semantic mode — always capture
- return { capture: true, reason: "semantic", text: normalized };
-}
-
-// ---------------------------------------------------------------------------
-// Transcript parsing
-// ---------------------------------------------------------------------------
-
-function parseTranscript(content) {
- try {
- const data = JSON.parse(content);
- if (Array.isArray(data)) return data;
- } catch { /* not a JSON array */ }
-
- const lines = content.split("\n").filter(l => l.trim());
- const messages = [];
- for (const line of lines) {
- try { messages.push(JSON.parse(line)); } catch { /* skip */ }
- }
- return messages;
-}
-
-// Tool result (output) retention. 0 = drop tool_result blocks entirely; >0 = keep,
-// truncated to that many chars. Default 0 — memory extraction signal lives in the
-// agent's prose summary of what happened, not in the raw bytes the tool returned
-// (file contents, web pages, command stdout). Operators who want replay-style
-// archives can set this >0 to retain truncated results.
-const TOOL_RESULT_MAX_CHARS = 0;
-
-function formatToolInput(value) {
- // Tool inputs are agent-authored. We keep them verbatim — they're usually short
- // (URLs, file paths, queries) and a pathologically long input is itself signal
- // worth surfacing to the memory extractor.
- if (typeof value === "string") return value;
- try {
- return JSON.stringify(value, null, 2);
- } catch {
- return String(value);
- }
-}
-
-function truncateToolResult(s) {
- if (TOOL_RESULT_MAX_CHARS <= 0) return null; // drop
- if (typeof s !== "string") s = String(s ?? "");
- if (s.length <= TOOL_RESULT_MAX_CHARS) return s;
- return (
- s.slice(0, TOOL_RESULT_MAX_CHARS) +
- `\n... [truncated, ${s.length - TOOL_RESULT_MAX_CHARS} more chars]`
- );
-}
-
-function extractToolResultText(content) {
- if (typeof content === "string") return content;
- if (!Array.isArray(content)) return "";
- return content
- .filter((b) => b && b.type === "text" && typeof b.text === "string")
- .map((b) => b.text)
- .join("\n");
-}
-
-// ---------------------------------------------------------------------------
-// Structured parts (parts-mode capture)
-//
-// Tool calls / results become dedicated `tool` parts (tool_id / tool_name /
-// tool_input / tool_output / tool_status) instead of being inlined into the
-// message content, so the server can process call vs result separately. The
-// `text` field above is kept only to drive the capture heuristics (length /
-// keyword); `parts` is what we actually send. Part shape mirrors openclaw-plugin
-// (examples/openclaw-plugin context-engine.ts afterTurn).
-// ---------------------------------------------------------------------------
-
-// Tool output retention for the part path. Unlike the legacy prose path
-// (TOOL_RESULT_MAX_CHARS, which drops outputs to keep the extractor's text
-// clean), results here land in a separable tool_output field and are reported
-// verbatim — the server externalizes anything oversized and leaves a stub plus
-// tool_output_ref, so truncating here would only destroy what it stores.
-function truncateToolOutput(s) {
- if (typeof s !== "string") s = String(s ?? "");
- const max = cfg.captureToolMaxChars;
- if (s.length <= max) return s;
- return s.slice(0, max) + `\n... [truncated, ${s.length - max} more chars]`;
-}
-
-// tool_result blocks carry only tool_use_id, not the tool name. Pre-scan all
-// messages so result parts can be labelled with the matching call's name.
-function collectToolNamesById(messages) {
- const map = {};
- for (const msg of messages) {
- const content = msg?.content ?? msg?.message?.content;
- if (!Array.isArray(content)) continue;
- for (const block of content) {
- if (
- block?.type === "tool_use" &&
- typeof block.id === "string" &&
- typeof block.name === "string"
- ) {
- map[block.id] = block.name;
- }
- }
- }
- return map;
-}
-
-function buildParts(content, toolNameById) {
- const out = [];
- if (typeof content === "string") {
- if (content.trim()) out.push({ type: "text", text: content });
- return out;
- }
- if (!Array.isArray(content)) return out;
- for (const block of content) {
- if (!block || typeof block !== "object") continue;
- if (block.type === "text" && typeof block.text === "string") {
- if (block.text.trim()) out.push({ type: "text", text: block.text });
- } else if (block.type === "tool_use" && typeof block.name === "string") {
- out.push({
- type: "tool",
- tool_id: typeof block.id === "string" ? block.id : undefined,
- tool_name: block.name,
- tool_input:
- block.input && typeof block.input === "object" ? block.input : undefined,
- tool_status: "running",
- });
- } else if (block.type === "tool_result") {
- const id = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined;
- out.push({
- type: "tool",
- tool_id: id,
- tool_name: id ? toolNameById[id] : undefined,
- tool_output: truncateToolOutput(extractToolResultText(block.content)),
- tool_status: block.is_error ? "error" : "completed",
- });
- }
- }
- return out;
-}
-
-/**
- * Extract user/assistant turns. Captures plain text + tool_use input (verbatim) and,
- * if TOOL_RESULT_MAX_CHARS > 0, tool_result output (truncated). Tool blocks are inlined
- * into the per-turn text so the OV memory extractor sees what the agent did with
- * substance, not just tool names.
- */
-function extractAllTurns(messages) {
- const toolNameById = collectToolNamesById(messages);
- const turns = [];
- for (const msg of messages) {
- if (!msg || typeof msg !== "object") continue;
-
- let role = msg.role;
- let text = "";
- let toolNames = [];
- let parts = [];
-
- const harvestContent = (content) => {
- if (typeof content === "string") {
- text = content;
- } else if (Array.isArray(content)) {
- const parts = [];
- for (const block of content) {
- if (!block || typeof block !== "object") continue;
- if (block.type === "text" && typeof block.text === "string") {
- parts.push(block.text);
- } else if (block.type === "tool_use" && typeof block.name === "string") {
- toolNames.push(block.name);
- parts.push(`[tool: ${block.name}]\n${formatToolInput(block.input)}`);
- } else if (block.type === "tool_result") {
- const resultText = extractToolResultText(block.content);
- const truncated = resultText ? truncateToolResult(resultText) : null;
- if (truncated) {
- parts.push(`[tool result]\n${truncated}`);
- }
- }
- }
- text = parts.join("\n\n");
- }
- };
-
- let rawContent;
- if (msg.content !== undefined) {
- rawContent = msg.content;
- } else if (typeof msg.message === "object" && msg.message) {
- role = msg.message.role || role;
- rawContent = msg.message.content;
- }
- harvestContent(rawContent);
- parts = buildParts(rawContent, toolNameById);
-
- if (role !== "user" && role !== "assistant") continue;
- // Keep turns that carry any structured part. This also retains tool_result-
- // only user turns (previously dropped because their inlined `text` was empty
- // once TOOL_RESULT_MAX_CHARS=0), so tool outputs reach OV as tool parts.
- if (parts.length === 0) continue;
- turns.push({ role, text: text.trim(), toolNames, parts });
- }
- return turns;
-}
-
function formatTurnsAsText(turns) {
const lines = [];
for (const t of turns) {
- if (t.role === "assistant" && t.toolNames.length > 0) {
- const uniq = Array.from(new Set(t.toolNames)).join(", ");
+ const toolNames = t.parts
+ .filter((p) => p.type === "tool" && p.tool_status === "running" && p.tool_name)
+ .map((p) => p.tool_name);
+ if (t.role === "assistant" && toolNames.length > 0) {
+ const uniq = Array.from(new Set(toolNames)).join(", ");
if (t.text) lines.push(`[assistant]: ${t.text}`);
lines.push(`[assistant used tools: ${uniq}]`);
} else if (t.text) {
@@ -425,11 +165,11 @@ function formatTurnsAsText(turns) {
// + trim, but per text part so tool I/O is never collapsed. The configured
// capture filters run last, here at the send site rather than in the extractor,
// because the cursor CC advances is an index into the extracted turn list.
-function sanitizePartsForSend(parts, role = "") {
+function sanitizePartsForSend(parts, role = "", cfg = {}) {
const out = [];
for (const p of parts || []) {
if (p.type === "text") {
- const t = stripInjectedBlocks(p.text).trim();
+ const t = sanitizeCapturedText(p.text);
if (t) out.push({ type: "text", text: t });
} else {
out.push(p);
@@ -439,12 +179,12 @@ function sanitizePartsForSend(parts, role = "") {
return shaped.dropped ? [] : shaped.parts;
}
-async function pushTurnsToOv(ovSessionId, turns, peerId = "") {
+async function pushTurnsToOv(ovSessionId, turns, peerId = "", cfg = {}) {
const payloads = [];
for (const turn of turns) {
// Send structured parts: tool calls/results are dedicated `tool` parts, not
// inlined into content, so the server can process them separately.
- const parts = sanitizePartsForSend(turn.parts, turn.role);
+ const parts = sanitizePartsForSend(turn.parts, turn.role, cfg);
if (parts.length === 0) continue;
const payload = { role: turn.role, parts };
@@ -463,11 +203,11 @@ async function pushTurnsToOv(ovSessionId, turns, peerId = "") {
};
}
-async function enqueueTurnsToPending(ovSessionId, turns, peerId = "") {
+async function enqueueTurnsToPending(ovSessionId, turns, peerId = "", cfg = {}) {
let queued = 0;
let failed = 0;
for (const turn of turns) {
- const parts = sanitizePartsForSend(turn.parts, turn.role);
+ const parts = sanitizePartsForSend(turn.parts, turn.role, cfg);
if (parts.length === 0) continue;
const payload = { role: turn.role, parts };
@@ -488,51 +228,16 @@ function isMissingSessionState(error) {
// Main
// ---------------------------------------------------------------------------
-async function main() {
- if (!cfg.autoCapture) {
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- approve();
- return;
- }
-
- // Async write path: parent detaches and returns, worker continues below.
- if (await maybeDetach(cfg, { approve })) return;
-
- let input;
- try {
- input = JSON.parse(await readHookStdin());
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- approve();
- return;
- }
-
+async function main({ cfg, input, cwd }) {
const transcriptPath = input.transcript_path;
const sessionId = input.session_id || "unknown";
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
- if (!cfg.autoCapture) {
- // The gate above ran against this process's directory, not the session's.
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- approve();
- return;
- }
const ovSessionId = sessionId !== "unknown" ? deriveOvSessionId(sessionId) : null;
const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
log("start", { sessionId, ovSessionId, transcriptPath, peerSource: effectivePeer.source });
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
- return;
- }
-
if (!transcriptPath || !ovSessionId) {
log("skip", { stage: "input_check", reason: "no transcript_path or session_id" });
- approve();
return;
}
@@ -541,26 +246,23 @@ async function main() {
transcriptContent = await readFile(transcriptPath, "utf-8");
} catch (err) {
logError("transcript_read", err);
- approve();
return;
}
if (!transcriptContent.trim()) {
log("skip", { stage: "transcript_read", reason: "empty transcript" });
- approve();
return;
}
const messages = parseTranscript(transcriptContent);
- const allTurns = extractAllTurns(messages);
+ const allTurns = extractCaptureTurns(messages, cfg);
if (allTurns.length === 0) {
log("skip", { stage: "transcript_parse", reason: "no user/assistant turns found" });
- approve();
return;
}
const state = await loadState(sessionId);
- await reconcileKnownFailedCapture(sessionId, ovSessionId, state);
+ await reconcileKnownFailedCapture(cfg, sessionId, ovSessionId, state);
const newTurns = allTurns.slice(state.capturedTurnCount);
const captureTurns = cfg.captureAssistantTurns
? newTurns
@@ -575,7 +277,6 @@ async function main() {
if (newTurns.length === 0) {
log("skip", { stage: "incremental_check", reason: "no new turns" });
- approve();
return;
}
@@ -585,30 +286,27 @@ async function main() {
capturedTurnCount: allTurns.length,
});
log("state_update", { newCapturedTurnCount: allTurns.length, reason: "assistant_only_increment" });
- approve();
return;
}
- // Batch-level capture decision. shouldCapture() is designed to evaluate a *single
- // user message* (length bounds, command/punctuation/question-only filters, keyword
- // trigger). Applied to a multi-turn batch concatenated by formatTurnsAsText(), it
- // misfires:
+ // Batch-level capture decision. A per-message filter (length bounds,
+ // command/punctuation/question-only) misfires on a multi-turn batch
+ // concatenated by formatTurnsAsText():
// - tool I/O inlining easily pushes combined text over captureMaxLength → entire
// batch silently dropped + state advanced → permanent data loss
- // - JSON-shaped tool I/O can match the punctuation-only regex → non_content drop
+ // - JSON-shaped tool I/O can match a punctuation-only rule → non_content drop
// - a leading `/cmd` user turn flips the whole batch to `command` → drop
// - a question-shaped user turn ("why?") tags the whole batch as question_only
// For batches we only need: skip empty batches, and (keyword mode) require *some*
// user turn to carry a trigger phrase. Per-turn substance is already bounded by
- // TOOL_BLOCK_MAX_CHARS during harvest.
+ // captureToolMaxChars during harvest.
const combined = formatTurnsAsText(captureTurns);
- if (!sanitize(combined)) {
+ if (!sanitizeCapturedText(combined)) {
log("skip", { stage: "batch_empty" });
await saveState(sessionId, {
...state,
capturedTurnCount: allTurns.length,
});
- approve();
return;
}
@@ -616,7 +314,7 @@ async function main() {
const hasTrigger = captureTurns.some(
(t) =>
t.role === "user" &&
- MEMORY_TRIGGERS.some((re) => re.test(sanitize(t.text))),
+ MEMORY_TRIGGERS.some((re) => re.test(sanitizeCapturedText(t.text))),
);
if (!hasTrigger) {
log("skip", { stage: "keyword_mode_no_trigger", turns: captureTurns.length });
@@ -624,7 +322,6 @@ async function main() {
...state,
capturedTurnCount: allTurns.length,
});
- approve();
return;
}
}
@@ -638,10 +335,10 @@ async function main() {
const health = await fetchJSON("/health");
let result;
if (health.ok) {
- result = await pushTurnsToOv(ovSessionId, captureTurns, effectivePeer.peerId);
+ result = await pushTurnsToOv(ovSessionId, captureTurns, effectivePeer.peerId, cfg);
} else if (isRetryableFailure(health)) {
logError("health_check", "server unreachable or unhealthy; enqueuing capture");
- result = await enqueueTurnsToPending(ovSessionId, captureTurns, effectivePeer.peerId);
+ result = await enqueueTurnsToPending(ovSessionId, captureTurns, effectivePeer.peerId, cfg);
log("push_turns", {
ovSessionId,
ok: result.ok,
@@ -650,7 +347,6 @@ async function main() {
});
if (result.failed > 0) {
logError("pending_enqueue", "some turns failed to enqueue; state not advanced");
- approve();
return;
}
await saveState(sessionId, {
@@ -670,11 +366,9 @@ async function main() {
ov_session_id: ovSessionId,
cc_session_id: sessionId,
});
- approve(result.queued > 0 ? `queued ${result.queued} turns to pending queue` : undefined);
- return;
+ return result.queued > 0 ? `queued ${result.queued} turns to pending queue` : undefined;
} else {
logError("health_check", `non-retryable status ${health.status || "unknown"}`);
- approve();
return;
}
log("push_turns", {
@@ -707,7 +401,6 @@ async function main() {
ov_session_id: ovSessionId,
cc_session_id: sessionId,
});
- approve();
return;
}
@@ -778,16 +471,33 @@ async function main() {
writeJsonState("daily-stats.json", { date: today, archives });
}
- if (result.ok > 0) {
- approve(
- `captured ${result.ok} turns to ov session ${ovSessionId}` +
- (committed
- ? ` (committed${commitTraceId ? `; trace_id=${commitTraceId}` : ""})`
- : ""),
- );
- } else {
+ if (result.ok === 0) return undefined;
+ return `captured ${result.ok} turns to ov session ${ovSessionId}`
+ + (committed
+ ? ` (committed${commitTraceId ? `; trace_id=${commitTraceId}` : ""})`
+ : "");
+}
+
+async function start() {
+ // Write-path hook: gated by autoCapture so that disabling capture also stops
+ // the transcript push. This runs against the hook's own directory, before the
+ // payload names the session's.
+ if (!baseCfg.autoCapture) {
+ log("skip", { stage: "init", reason: "disabled" });
approve();
+ return;
}
+
+ // Async write path: parent detaches and returns, worker continues below.
+ if (await maybeDetach(baseCfg, { approve })) return;
+
+ await runHookStage({
+ loadConfig,
+ input: { read: readHookStdin },
+ gates: { enabled: (cfg) => cfg.autoCapture },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+ }, main);
}
-main().catch((err) => { logError("uncaught", err); approve(); });
+start().catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
index e9db0a09a..9838a3389 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
@@ -1,49 +1,14 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
-
-function writeJson(res, statusCode, value) {
- res.writeHead(statusCode, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try {
- resolve(raw ? JSON.parse(raw) : null);
- } catch (err) {
- reject(err);
- }
- });
- req.on("error", reject);
- });
-}
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- handler(req, res).catch((err) => {
- writeJson(res, 500, { status: "error", error: String(err?.stack || err) });
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
function runAutoCapture(input, env) {
return new Promise((resolve, reject) => {
@@ -107,38 +72,38 @@ test("failed non-retryable capture keeps the cursor for a later retry", async ()
await withMockOpenViking(async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/health") {
- writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ writeJson(res, { status: "ok", result: { healthy: true } });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
const body = await readRequestBody(req);
if (rejectWrites) {
- writeJson(res, 404, {
+ writeJson(res, {
status: "error",
error: { code: "NOT_FOUND", message: "Resource not found" },
- });
+ }, 404);
return;
}
batches.push(body);
- writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ writeJson(res, { status: "ok", result: { added: body.messages.length } });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/messages")) {
await readRequestBody(req);
- writeJson(res, 404, {
+ writeJson(res, {
status: "error",
error: { code: "NOT_FOUND", message: "Resource not found" },
- });
+ }, 404);
return;
}
if (req.method === "GET" && url.pathname === "/api/v1/sessions/cc-capture-retry") {
- writeJson(res, 200, {
+ writeJson(res, {
status: "ok",
result: { message_count: 2, pending_tokens: 10, commit_count: 0 },
});
return;
}
- writeJson(res, 404, { status: "error", error: { code: "NOT_FOUND" } });
+ writeJson(res, { status: "error", error: { code: "NOT_FOUND" } }, 404);
}, async (baseUrl) => {
const input = { session_id: sessionId, transcript_path: transcriptPath, cwd: root };
await runAutoCapture(input, hookEnv(root, baseUrl));
@@ -187,11 +152,11 @@ test("legacy advanced cursor rewinds when the server session is empty", async ()
await withMockOpenViking(async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/health") {
- writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ writeJson(res, { status: "ok", result: { healthy: true } });
return;
}
if (req.method === "GET" && url.pathname === "/api/v1/sessions/cc-legacy-empty-session") {
- writeJson(res, 200, {
+ writeJson(res, {
status: "ok",
result: {
message_count: captured ? 2 : 0,
@@ -206,10 +171,10 @@ test("legacy advanced cursor rewinds when the server session is empty", async ()
const body = await readRequestBody(req);
batches.push(body);
captured = true;
- writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ writeJson(res, { status: "ok", result: { added: body.messages.length } });
return;
}
- writeJson(res, 404, { status: "error", error: { code: "NOT_FOUND" } });
+ writeJson(res, { status: "error", error: { code: "NOT_FOUND" } }, 404);
}, async (baseUrl) => {
await runAutoCapture(
{ session_id: sessionId, transcript_path: transcriptPath, cwd: root },
@@ -233,23 +198,23 @@ async function captureToolResult(root, transcriptPath, sessionId, extraEnv = {})
await withMockOpenViking(async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/health") {
- writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ writeJson(res, { status: "ok", result: { healthy: true } });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
const body = await readRequestBody(req);
batches.push(body);
- writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ writeJson(res, { status: "ok", result: { added: body.messages.length } });
return;
}
if (req.method === "GET" && url.pathname === `/api/v1/sessions/cc-${sessionId}`) {
- writeJson(res, 200, {
+ writeJson(res, {
status: "ok",
result: { message_count: 2, pending_tokens: 10, commit_count: 0 },
});
return;
}
- writeJson(res, 404, { status: "error", error: { code: "NOT_FOUND" } });
+ writeJson(res, { status: "error", error: { code: "NOT_FOUND" } }, 404);
}, async (baseUrl) => {
await runAutoCapture(
{ session_id: sessionId, transcript_path: transcriptPath, cwd: root },
@@ -348,22 +313,22 @@ test("the workspace that decides capture is the payload's, not the hook process'
const url = new URL(req.url, "http://127.0.0.1");
paths.push(url.pathname);
if (req.method === "GET" && url.pathname === "/health") {
- writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ writeJson(res, { status: "ok", result: { healthy: true } });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
const body = await readRequestBody(req);
- writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ writeJson(res, { status: "ok", result: { added: body.messages.length } });
return;
}
if (req.method === "GET" && url.pathname.startsWith("/api/v1/sessions/")) {
- writeJson(res, 200, {
+ writeJson(res, {
status: "ok",
result: { message_count: 0, pending_tokens: 10, commit_count: 0 },
});
return;
}
- writeJson(res, 404, { status: "error", error: { code: "NOT_FOUND" } });
+ writeJson(res, { status: "error", error: { code: "NOT_FOUND" } }, 404);
}, async (baseUrl) => {
await runAutoCapture(
{ session_id: "ws-off", transcript_path: transcriptPath, cwd: workspaceDir },
@@ -403,16 +368,16 @@ test("capture filters rewrite and drop turns at the send site", async () => {
await withMockOpenViking(async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
if (req.method === "GET" && url.pathname === "/health") {
- writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ writeJson(res, { status: "ok", result: { healthy: true } });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
const body = await readRequestBody(req);
batches.push(body);
- writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ writeJson(res, { status: "ok", result: { added: body.messages.length } });
return;
}
- writeJson(res, 200, { status: "ok", result: {} });
+ writeJson(res, { status: "ok", result: {} });
}, async (baseUrl) => {
await runAutoCapture({ session_id: sessionId, transcript_path: transcriptPath, cwd: root }, {
...hookEnv(root, baseUrl),
diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
index 184c2c9a0..efb0a3e20 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs
@@ -4,23 +4,19 @@
* Auto-Recall Hook Script for Claude Code (UserPromptSubmit).
*
* Searches OpenViking for relevant context and injects an
- * <openviking-context> block. High-score items within the token budget
- * include resolved content; remaining items degrade to URI + score.
- *
- * Ranking: ported from openclaw-plugin/memory-ranking.ts (query profile
- * + boosts). Content resolution + budget: ported from
- * openclaw-plugin/index.ts resolveMemoryContent / buildMemoryLinesWithBudget,
- * modified so items beyond the budget are degraded (URI-only) instead of
- * dropped.
+ * <openviking-context> block. Retrieval, ranking and the token budget are the
+ * shared recall core's; this hook owns the CC envelope and the statusline
+ * snapshot it leaves behind.
*/
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
-import { deriveOvSessionId, isBypassed, makeFetchJSON } from "./lib/ov-session.mjs";
+import { deriveOvSessionId, makeFetchJSON } from "./lib/ov-session.mjs";
import { writeJsonState } from "./lib/state.mjs";
import { createHostCompressor } from "./lib/host-compressor.mjs";
import { getEffectivePeerId } from "./lib/workspace-peer.mjs";
-import { buildServerAssembledBlock } from "./shared/recall-core.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
+import { buildRecallBlockDetailed } from "./shared/recall-core.mjs";
import { applyInputFilters, compileInputFilters } from "./shared/input-filters.mjs";
if (!isPluginEnabled()) {
@@ -28,9 +24,9 @@ if (!isPluginEnabled()) {
process.exit(0);
}
-let cfg = loadConfig();
+const baseCfg = loadConfig();
const { log, logError } = createLogger("auto-recall");
-const fetchJSON = makeFetchJSON(cfg);
+const fetchJSON = makeFetchJSON(baseCfg);
function output(obj) {
process.stdout.write(JSON.stringify(obj) + "\n");
@@ -42,328 +38,46 @@ function approve(msg) {
output(out);
}
-// ---------------------------------------------------------------------------
-// Ranking (ported from openclaw-plugin/memory-ranking.ts)
-// ---------------------------------------------------------------------------
-
-function clampScore(v) {
- if (typeof v !== "number" || Number.isNaN(v)) return 0;
- return Math.max(0, Math.min(1, v));
-}
-
-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",
-]);
-
-function buildQueryProfile(query) {
- const text = query.trim();
- const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
- const tokens = allTokens.filter(t => !STOPWORDS.has(t));
- return {
- tokens,
- 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;
-}
-
-/**
- * events/cases specialization (ported from openclaw-plugin/memory-ranking.ts
- * isEventOrCaseMemory): dedupe by URI instead of abstract.
- */
-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;
-}
-
-// ---------------------------------------------------------------------------
-// User URI space resolution
-// ---------------------------------------------------------------------------
-
-const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
-let _userSpaceCache = "";
-
-async function resolveUserSpace(actorPeerId = "") {
- if (_userSpaceCache) return _userSpaceCache;
+const URI_RE = /viking:\/\/[^\s<>"')\]]+/g;
- 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(targetUri, actorPeerId = "") {
- const trimmed = targetUri.trim().replace(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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(actorPeerId);
- return `viking://user/${space}/${parts.join("/")}`;
-}
-
-// ---------------------------------------------------------------------------
-// Multi-source search (scoped sources only — resources excluded to prevent
-// cross-namespace leakage; use MCP search(scope="resources") explicitly)
-// ---------------------------------------------------------------------------
-
-const SOURCES = [
- { type: "memory", uri: "viking://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-
-async function searchOneSource(query, source, limit, actorPeerId = "") {
- const resolvedUri = await resolveTargetUri(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(query, perSourceLimit, actorPeerId = "") {
- const results = await Promise.all(SOURCES.map(src => searchOneSource(query, src, perSourceLimit, actorPeerId)));
- const all = results.flat();
- log("search_summary", {
- counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),
- total: all.length,
- });
- return all;
-}
-
-// ---------------------------------------------------------------------------
-// Content resolution + budget formatting
-// Ported from openclaw-plugin/index.ts resolveMemoryContent (line 1822-1850)
-// and buildMemoryLinesWithBudget (line 1878-1907).
-// Key difference: items beyond token budget are degraded to URI+score
-// instead of being dropped entirely.
-// ---------------------------------------------------------------------------
-
-/** chars/4 heuristic (openclaw-plugin/index.ts:1812) */
-function estimateTokens(text) {
- return text ? Math.ceil(text.length / 4) : 0;
-}
-
-/**
- * Resolve display content for a single item.
- * Ported from openclaw-plugin/index.ts:1822 resolveMemoryContent.
- */
-async function resolveItemContent(item, 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;
- }
-
- if (content.length > cfg.recallMaxContentChars) {
- content = content.slice(0, cfg.recallMaxContentChars) + "...";
- }
-
- return content;
-}
-
-/**
- * Build the injection block with token budget.
- * Front items (within budget) get full content lines.
- * Remaining items (beyond budget) degrade to URI + score only.
- */
-async function buildInjectionBlock(items, actorPeerId = "") {
- if (items.length === 0) return null;
-
- let budgetRemaining = cfg.recallTokenBudget;
- 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(item, actorPeerId);
- const contentLine = `- [${item._sourceType} ${score}%] ${content}`;
- const lineTokens = estimateTokens(contentLine);
-
- // First item always included even if over budget (openclaw spec §6.2)
- 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 = cfg.recallTokenBudget - budgetRemaining;
- log("injection_built", {
- contentItems: contentCount,
- hintItems: hintCount,
- budgetUsed,
- budgetTotal: cfg.recallTokenBudget,
- });
-
- return { block: lines.join("\n"), contentCount, hintCount, budgetUsed };
-}
-
-async function recallViaServerAssembly(query, actorPeerId = "", sessionId = "", legacyPeerId = "") {
+async function recall(cfg, query, peer, sessionId) {
const runCompressor = await createHostCompressor(cfg, log);
- const assemble = (peerId) => buildServerAssembledBlock(fetchJSON, cfg, query, {
- actorPeerId: peerId,
+ return buildRecallBlockDetailed(fetchJSON, cfg, query, {
+ actorPeerId: peer.peerId,
+ legacyPeerId: peer.legacyPeerId,
sessionId,
log,
runCompressor,
localCompressorAvailable: Boolean(runCompressor),
});
-
- const block = await assemble(actorPeerId);
- // `peer_scope: "all"` already sweeps every peer under this user, so the peer
- // this workspace used before the identity rule changed needs asking only
- // when that sweep is off.
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return block;
-
- const legacy = await assemble(legacyPeerId);
- if (!legacy) return block;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return block ? `${block}\n${legacy}` : legacy;
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
-async function main() {
- const t0 = Date.now();
- // Snapshot state for the statusline. Always written, even on early-exit
- // branches, so the indicator reflects the latest turn rather than stale
- // data from the previous run.
- const writeRecallState = (extra) => writeJsonState("last-recall.json", {
- server_url: cfg.baseUrl,
+const t0 = Date.now();
+// Snapshot state for the statusline. Always written, even on early-exit
+// branches, so the indicator reflects the latest turn rather than stale
+// data from the previous run.
+function writeRecallState(extra) {
+ writeJsonState("last-recall.json", {
+ server_url: baseCfg.baseUrl,
latency_ms: Date.now() - t0,
...extra,
});
+}
- let input;
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString());
- } catch {
- log("skip", { reason: "invalid stdin" });
- writeRecallState({ count: 0, reason: "bad_stdin" });
- approve();
- return;
- }
-
+runHookStage({
+ loadConfig,
+ gates: { enabled: (cfg) => cfg.autoRecall },
+ envelope: approve,
+ onSkip: (reason, { cfg, sessionId }) => {
+ log("skip", { reason });
+ if (cfg.enabled !== false) writeRecallState({ count: 0, reason, cc_session_id: sessionId });
+ },
+}, async ({ cfg, input, cwd, sessionId }) => {
let userPrompt = (input.prompt || "").trim();
- const sessionId = input.session_id;
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- // Everything gated below — recall.enabled included — reads the reload.
- cfg = loadConfig(cwd);
-
- if (!cfg.autoRecall) {
- log("skip", { reason: "autoRecall disabled" });
- writeRecallState({ count: 0, reason: "disabled" });
- approve();
- return;
- }
-
const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
log("start", {
query: userPrompt.slice(0, 200),
@@ -378,13 +92,6 @@ async function main() {
},
});
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- writeRecallState({ count: 0, reason: "bypass", cc_session_id: sessionId });
- approve();
- return;
- }
-
// Filters run before the length gate, so a prompt whose only content was a
// stripped prefix is short_query rather than a search for the empty string.
const queryFilters = compileInputFilters(cfg.recallQueryFilters);
@@ -393,18 +100,15 @@ async function main() {
if (verdict.dropped) {
log("skip", { reason: "query_filter", rule: verdict.ruleIndex, op: verdict.op });
writeRecallState({ count: 0, reason: "query_filtered", cc_session_id: sessionId });
- approve();
return;
}
if (verdict.changed) log("query_filter", { rawLength: userPrompt.length, length: verdict.text.length });
userPrompt = verdict.text;
}
if (queryFilters.errors.length) log("query_filter_errors", queryFilters.errors);
-
if (!userPrompt || userPrompt.length < cfg.minQueryLength) {
log("skip", { reason: "query too short or empty" });
writeRecallState({ count: 0, reason: "short_query", cc_session_id: sessionId });
- approve();
return;
}
@@ -412,78 +116,31 @@ async function main() {
if (!health.ok) {
logError("health_check", "server unreachable");
writeRecallState({ count: 0, reason: "offline", cc_session_id: sessionId });
- approve();
return;
}
// The OV session id is what unlocks server-side query expansion and the
// cross-turn dedup ledger; it must match the id auto-capture writes to.
const ovSessionId = sessionId && sessionId !== "unknown" ? deriveOvSessionId(sessionId) : "";
- const endpointBlock = await recallViaServerAssembly(
- userPrompt,
- effectivePeer.peerId,
- ovSessionId,
- effectivePeer.legacyPeerId,
- );
- if (endpointBlock !== null) {
- if (!endpointBlock) {
- log("skip", { reason: "recall_endpoint_no_results" });
- writeRecallState({ count: 0, reason: "no_results", cc_session_id: sessionId });
- approve();
- return;
- }
- writeRecallState({
- count: new Set(endpointBlock.match(/viking:\/\/[^\s<>"')\]]+/g) || []).size,
- content_items: 1,
- hint_items: 0,
- tokens_used: estimateTokens(endpointBlock),
- tokens_budget: cfg.recallTokenBudget,
- cc_session_id: sessionId,
- reason: "ok",
- });
- approve(endpointBlock);
- return;
- }
-
- const perSourceLimit = Math.max(cfg.recallLimit * 2, 8);
- const raw = await searchAllSources(userPrompt, perSourceLimit, effectivePeer.peerId);
- if (raw.length === 0) {
- log("skip", { reason: "no results" });
- writeRecallState({ count: 0, reason: "no_results", cc_session_id: sessionId });
- approve();
- return;
- }
-
- const profile = buildQueryProfile(userPrompt);
- const filtered = raw.filter(it => clampScore(it.score) >= cfg.scoreThreshold);
- filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));
- const deduped = dedupeItems(filtered);
- const picked = deduped.slice(0, cfg.recallLimit);
- log("picked", {
- rawCount: raw.length,
- filteredCount: filtered.length,
- dedupedCount: deduped.length,
- pickedCount: picked.length,
- items: picked.map(it => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
- });
-
- if (picked.length === 0) {
- writeRecallState({ count: 0, reason: "filtered_out", cc_session_id: sessionId });
- approve();
+ const recalled = await recall(cfg, userPrompt, effectivePeer, ovSessionId);
+ if (!recalled.block) {
+ log("skip", { reason: recalled.stage });
+ writeRecallState({ count: 0, reason: recalled.stage, cc_session_id: sessionId });
return;
}
- const built = await buildInjectionBlock(picked, effectivePeer.peerId);
writeRecallState({
- count: picked.length,
- content_items: built?.contentCount ?? 0,
- hint_items: built?.hintCount ?? 0,
- tokens_used: built?.budgetUsed ?? 0,
+ // A server-assembled block is one rendered unit whatever it holds, so the
+ // count the statusline shows comes from the URIs it cites.
+ count: recalled.stage === "server_assembled"
+ ? new Set(recalled.block.match(URI_RE) || []).size
+ : recalled.contentCount + recalled.hintCount,
+ content_items: recalled.contentCount,
+ hint_items: recalled.hintCount,
+ tokens_used: recalled.budgetUsed,
tokens_budget: cfg.recallTokenBudget,
cc_session_id: sessionId,
reason: "ok",
});
- approve(built?.block);
-}
-
-main().catch((err) => { logError("uncaught", err); approve(); });
+ return recalled.block;
+}).catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.test.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.test.mjs
new file mode 100644
index 000000000..97b4faa3b
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.test.mjs
@@ -0,0 +1,309 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, readFile, readdir, rm } from "node:fs/promises";
+import http from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
+const PLUGIN_DIR = dirname(SCRIPT_DIR);
+const SESSION_ID = "recall-branch-session";
+
+function writeJson(res, statusCode, value) {
+ res.writeHead(statusCode, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(value));
+}
+
+async function withMockOpenViking(handler, fn) {
+ const server = http.createServer((req, res) => {
+ Promise.resolve(handler(req, res)).catch((err) => {
+ writeJson(res, 500, { status: "error", error: String(err?.stack || err) });
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const { port } = server.address();
+ return await fn(`http://127.0.0.1:${port}`);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+function runAutoRecall(stdin, env) {
+ return new Promise((resolve, reject) => {
+ const cleanEnv = { ...process.env };
+ for (const key of Object.keys(cleanEnv)) {
+ if (key.startsWith("OPENVIKING_")) delete cleanEnv[key];
+ }
+ const child = spawn(process.execPath, [join(SCRIPT_DIR, "auto-recall.mjs")], {
+ env: { ...cleanEnv, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk.toString(); });
+ child.stderr.on("data", (chunk) => { stderr += chunk.toString(); });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ if (code !== 0) {
+ reject(new Error(`auto-recall exited ${code}: ${stderr}`));
+ return;
+ }
+ resolve({ stdout, stderr });
+ });
+ child.stdin.end(stdin);
+ });
+}
+
+function hookEnv(root, baseUrl, extra = {}) {
+ return {
+ HOME: root,
+ TMPDIR: root,
+ OPENVIKING_HOME: join(root, ".openviking"),
+ OPENVIKING_MEMORY_ENABLED: "1",
+ OPENVIKING_AUTO_RECALL: "1",
+ OPENVIKING_RECALL_COMPRESS: "off",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_URL: baseUrl,
+ ...extra,
+ };
+}
+
+async function readRecallState(root) {
+ const raw = await readFile(join(root, ".openviking", "state", "last-recall.json"), "utf-8");
+ return JSON.parse(raw);
+}
+
+function injectedContext(stdout) {
+ const out = JSON.parse(stdout.trim());
+ assert.equal(out.decision, "approve");
+ return out.hookSpecificOutput?.additionalContext ?? null;
+}
+
+/**
+ * One turn against a stubbed server: `routes` maps "METHOD /path" to a handler
+ * returning the JSON body, so each test only spells out the endpoints its own
+ * branch reaches.
+ */
+async function recallTurn({ routes = {}, env = {}, input = {} } = {}) {
+ const root = await mkdtemp(join(tmpdir(), "ov-cc-recall-"));
+ try {
+ return await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ const route = routes[`${req.method} ${url.pathname}`];
+ if (!route) {
+ writeJson(res, 404, { status: "error", error: { message: "no route" } });
+ return;
+ }
+ const { status = 200, body } = await route(req);
+ writeJson(res, status, body);
+ }, async (baseUrl) => {
+ const stdin = typeof input === "string" ? input : JSON.stringify({
+ prompt: "remember the ranking pipeline please",
+ session_id: SESSION_ID,
+ cwd: root,
+ ...input,
+ });
+ const run = await runAutoRecall(stdin, hookEnv(root, baseUrl, env));
+ return { ...run, state: await readRecallState(root), root };
+ });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const HEALTHY = { "GET /health": () => ({ body: { status: "ok", result: { healthy: true } } }) };
+const NO_SERVER_ASSEMBLY = {
+ ...HEALTHY,
+ "POST /api/v1/search/search": () => ({ status: 503, body: { status: "error", error: { message: "unavailable" } } }),
+ "POST /api/v1/search/recall": () => ({ status: 404, body: { status: "error", error: { message: "gone" } } }),
+};
+
+function memory(uri, score, abstract) {
+ return { uri, score, abstract, level: 1, category: "entities" };
+}
+
+test("unparseable stdin is recorded as bad_stdin", async () => {
+ const { state } = await recallTurn({ routes: HEALTHY, input: "{not json" });
+
+ assert.equal(state.reason, "bad_stdin");
+ assert.equal(state.count, 0);
+});
+
+test("a disabled recall switch is recorded as disabled", async () => {
+ const { stdout, state } = await recallTurn({
+ routes: HEALTHY,
+ env: { OPENVIKING_AUTO_RECALL: "0" },
+ });
+
+ assert.equal(state.reason, "disabled");
+ assert.equal(state.count, 0);
+ assert.equal(injectedContext(stdout), null);
+});
+
+test("a bypassed session is recorded as bypass", async () => {
+ const { state } = await recallTurn({
+ routes: HEALTHY,
+ env: { OPENVIKING_BYPASS_SESSION: "1" },
+ });
+
+ assert.equal(state.reason, "bypass");
+ assert.equal(state.count, 0);
+ assert.equal(state.cc_session_id, SESSION_ID);
+});
+
+test("a prompt below the minimum length is recorded as short_query", async () => {
+ const { state } = await recallTurn({ routes: HEALTHY, input: { prompt: "hi" } });
+
+ assert.equal(state.reason, "short_query");
+ assert.equal(state.count, 0);
+ assert.equal(state.cc_session_id, SESSION_ID);
+});
+
+test("an unreachable server is recorded as offline", async () => {
+ const { state } = await recallTurn({
+ routes: { "GET /health": () => ({ status: 503, body: { status: "error", error: { message: "down" } } }) },
+ });
+
+ assert.equal(state.reason, "offline");
+ assert.equal(state.count, 0);
+});
+
+test("an empty server-assembled context is recorded as no_results", async () => {
+ const { stdout, state } = await recallTurn({
+ routes: {
+ ...HEALTHY,
+ "POST /api/v1/search/search": () => ({ body: { status: "ok", result: { rendered: "", entries: [], stats: {} } } }),
+ },
+ });
+
+ assert.equal(state.reason, "no_results");
+ assert.equal(state.count, 0);
+ assert.equal(injectedContext(stdout), null);
+});
+
+test("a server-assembled block counts its URIs and its own token cost", async () => {
+ const rendered = [
+ "- viking://user/default/memories/entities/plugin.md — the shared recall core",
+ "- viking://user/default/memories/events/rollout.md — shipped last week",
+ ].join("\n");
+ const { stdout, state } = await recallTurn({
+ routes: {
+ ...HEALTHY,
+ "POST /api/v1/search/search": () => ({
+ body: { status: "ok", result: { rendered, entries: [], stats: { used_tokens: 40 } } },
+ }),
+ },
+ });
+
+ const block = injectedContext(stdout);
+ assert.match(block, /^<openviking-context>/);
+ assert.ok(block.includes(rendered));
+ assert.equal(state.reason, "ok");
+ assert.equal(state.count, 2);
+ assert.equal(state.content_items, 1);
+ assert.equal(state.hint_items, 0);
+ assert.equal(state.tokens_used, Math.ceil(block.length / 4));
+ assert.equal(state.tokens_budget, 2000);
+ assert.equal(state.cc_session_id, SESSION_ID);
+});
+
+test("no search hits at all are recorded as no_results", async () => {
+ const { stdout, state } = await recallTurn({
+ routes: {
+ ...NO_SERVER_ASSEMBLY,
+ "POST /api/v1/search/find": () => ({ body: { status: "ok", result: { memories: [], skills: [] } } }),
+ },
+ });
+
+ assert.equal(state.reason, "no_results");
+ assert.equal(state.count, 0);
+ assert.equal(injectedContext(stdout), null);
+});
+
+test("hits that all fall under the score threshold are recorded as filtered_out", async () => {
+ const { stdout, state } = await recallTurn({
+ routes: {
+ ...NO_SERVER_ASSEMBLY,
+ "POST /api/v1/search/find": () => ({
+ body: {
+ status: "ok",
+ result: {
+ memories: [memory("viking://user/default/memories/entities/a.md", 0.1, "barely related")],
+ skills: [],
+ },
+ },
+ }),
+ },
+ });
+
+ assert.equal(state.reason, "filtered_out");
+ assert.equal(state.count, 0);
+ assert.equal(injectedContext(stdout), null);
+});
+
+test("the client-ranked fallback degrades past the budget to URI hints", async () => {
+ const first = "x".repeat(500);
+ const second = "y".repeat(500);
+ const { stdout, state } = await recallTurn({
+ env: { OPENVIKING_RECALL_TOKEN_BUDGET: "200" },
+ routes: {
+ ...NO_SERVER_ASSEMBLY,
+ "POST /api/v1/search/find": () => ({
+ body: {
+ status: "ok",
+ result: {
+ memories: [
+ memory("viking://user/default/memories/entities/a.md", 0.9, first),
+ memory("viking://user/default/memories/entities/b.md", 0.9, second),
+ ],
+ skills: [],
+ },
+ },
+ }),
+ },
+ });
+
+ const block = injectedContext(stdout);
+ assert.ok(block.includes(`- [memory 90%] ${first}`));
+ assert.ok(block.includes("- [memory 90%] viking://user/default/memories/entities/b.md"));
+ assert.equal(state.reason, "ok");
+ assert.equal(state.count, 2);
+ assert.equal(state.content_items, 1);
+ assert.equal(state.hint_items, 1);
+ assert.equal(state.tokens_used, Math.ceil(`- [memory 90%] ${first}`.length / 4));
+ assert.equal(state.tokens_budget, 200);
+});
+
+// The ranking pipeline lives in the shared recall core and the transcript walk
+// in the shared capture utilities. A second copy of either here is what this
+// plugin spent a release drifting away from.
+const SHARED_ONLY_SYMBOLS = [
+ "buildQueryProfile",
+ "lexicalOverlapBoost",
+ "rankItem",
+ "extractAllTurns",
+];
+
+async function ownSourceFiles(dir) {
+ const out = [];
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
+ if (entry.name === "node_modules" || entry.name === "shared" || entry.name.startsWith(".")) continue;
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...await ownSourceFiles(full));
+ else if (entry.name.endsWith(".mjs")) out.push(full);
+ }
+ return out;
+}
+
+test("the plugin keeps no ranking or transcript copy of its own", async () => {
+ const pattern = new RegExp(`function\\s+(${SHARED_ONLY_SYMBOLS.join("|")})\\b`);
+ const hits = [];
+ for (const file of await ownSourceFiles(PLUGIN_DIR)) {
+ if (pattern.test(await readFile(file, "utf-8"))) hits.push(file.slice(PLUGIN_DIR.length + 1));
+ }
+
+ assert.deepEqual(hits, []);
+});
diff --git a/examples/claude-code-memory-plugin/scripts/cc-transcript.mjs b/examples/claude-code-memory-plugin/scripts/cc-transcript.mjs
new file mode 100644
index 000000000..251c346a7
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/cc-transcript.mjs
@@ -0,0 +1,146 @@
+/**
+ * Claude Code transcript reading, on top of the shared capture utilities.
+ *
+ * Claude writes JSONL of Anthropic messages, whose blocks differ from the shape
+ * `capture-utils` walks in one way that matters: a `tool_result` nests its
+ * output in a content array of text blocks and names the call it answers by id
+ * rather than by name. Normalising that is all this harness needs of its own —
+ * the block walking, the part building and the capture filter are shared.
+ */
+
+import {
+ collectToolNamesByIdFromEntries,
+ extractPartsFromPayload,
+ normalizeCaptureRole,
+} from "./shared/capture-utils.mjs";
+
+// Named one by one rather than re-exported wholesale: this module has an
+// `extractCaptureTurns` of its own, and `export *` would let the shared one
+// through under the same name with nothing to say which a caller holds.
+export { sanitizeCapturedText } from "./shared/capture-utils.mjs";
+
+// Tool output retention in the per-turn *text*. 0 = drop it: the extraction
+// signal lives in the agent's prose about what happened, not in the raw bytes a
+// tool returned (file contents, web pages, command stdout), and the output
+// still travels verbatim in the turn's tool part. Operators who want
+// replay-style archives can set this above zero.
+const TOOL_RESULT_MAX_CHARS = 0;
+
+/** Claude's transcript is JSONL; older ones are a single JSON array. */
+export function parseTranscript(content) {
+ try {
+ const data = JSON.parse(content);
+ if (Array.isArray(data)) return data;
+ } catch { /* not a JSON array */ }
+
+ const messages = [];
+ for (const line of String(content || "").split("\n")) {
+ if (!line.trim()) continue;
+ try { messages.push(JSON.parse(line)); } catch { /* skip */ }
+ }
+ return messages;
+}
+
+function extractToolResultText(content) {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .filter((block) => block && block.type === "text" && typeof block.text === "string")
+ .map((block) => block.text)
+ .join("\n");
+}
+
+// Results land in a separable tool_output field and are reported verbatim — the
+// server externalizes anything oversized and leaves a stub plus tool_output_ref,
+// so this cap only guards against pathological payloads.
+function truncateToolOutput(text, cfg) {
+ const value = typeof text === "string" ? text : String(text ?? "");
+ const max = cfg.captureToolMaxChars;
+ if (!(max > 0) || value.length <= max) return value;
+ return `${value.slice(0, max)}\n... [truncated, ${value.length - max} more chars]`;
+}
+
+function truncateToolResult(text) {
+ if (TOOL_RESULT_MAX_CHARS <= 0) return null;
+ const value = typeof text === "string" ? text : String(text ?? "");
+ if (value.length <= TOOL_RESULT_MAX_CHARS) return value;
+ return `${value.slice(0, TOOL_RESULT_MAX_CHARS)}\n... [truncated, ${value.length - TOOL_RESULT_MAX_CHARS} more chars]`;
+}
+
+// Tool inputs are agent-authored. They stay verbatim — usually short (URLs,
+// paths, queries), and a pathologically long one is itself signal.
+function formatToolInput(value) {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+function normalizeBlock(block, cfg) {
+ if (!block || typeof block !== "object" || block.type !== "tool_result") return block;
+ return {
+ type: "tool_result",
+ tool_use_id: block.tool_use_id,
+ output: truncateToolOutput(extractToolResultText(block.content), cfg),
+ is_error: Boolean(block.is_error),
+ };
+}
+
+function normalizeMessage(message, cfg) {
+ if (!message || typeof message !== "object") return null;
+ let role = message.role;
+ let content;
+ if (message.content !== undefined) {
+ content = message.content;
+ } else if (message.message && typeof message.message === "object") {
+ role = message.message.role || role;
+ content = message.message.content;
+ }
+ return {
+ role,
+ content: Array.isArray(content)
+ ? content.map((block) => normalizeBlock(block, cfg))
+ : content,
+ };
+}
+
+// The text the capture heuristics read: tool calls inlined with their input,
+// tool results per TOOL_RESULT_MAX_CHARS.
+function textFromParts(parts) {
+ const chunks = [];
+ for (const part of parts) {
+ if (part.type !== "tool") {
+ chunks.push(part.text);
+ } else if (part.tool_status === "running") {
+ chunks.push(`[tool: ${part.tool_name || "unknown"}]\n${formatToolInput(part.tool_input)}`);
+ } else {
+ const retained = truncateToolResult(part.tool_output);
+ if (retained) chunks.push(`[tool result]\n${retained}`);
+ }
+ }
+ return chunks.join("\n\n").trim();
+}
+
+/**
+ * Every user/assistant turn in the transcript, in order.
+ *
+ * Turns carrying no structured part are dropped; the rest keep their index, so
+ * a caller can treat the position of a turn as a durable cursor.
+ */
+export function extractCaptureTurns(messages, cfg = {}) {
+ const payloads = (messages || []).map((message) => normalizeMessage(message, cfg));
+ const toolNameById = collectToolNamesByIdFromEntries(payloads.filter(Boolean));
+ const turns = [];
+ for (const payload of payloads) {
+ const role = payload && normalizeCaptureRole(payload.role);
+ if (!role) continue;
+ // Output was capped in normalizeBlock; capping it again here would eat the
+ // "[truncated, N more chars]" note that cap just appended.
+ const parts = extractPartsFromPayload(payload, { toolMaxChars: Infinity, toolNameById });
+ if (parts.length === 0) continue;
+ turns.push({ role, text: textFromParts(parts), parts });
+ }
+ return turns;
+}
diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjs
index e3bd76a82..dcbcfddc9 100644
--- a/examples/claude-code-memory-plugin/scripts/config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/config.mjs
@@ -1,76 +1,38 @@
/**
- * Shared configuration loader for the Claude Code OpenViking memory plugin.
+ * Configuration for the Claude Code OpenViking memory plugin.
*
- * Resolution priority (highest → lowest):
- * 1. Environment variables (OPENVIKING_*)
- * 2. ovcli.conf (CLI client config: url, api_key, account, user) — connection only
- * 3. ov.conf fields (server section + claude_code section) — legacy; new deployments should
- * prefer env vars. Tuning fields under claude_code.* are still honored for backward compat.
- * 4. Built-in defaults
+ * Every knob is declared once in `shared/config-schema.mjs` and the whole
+ * configuration is assembled by `buildPluginConfig()`, which reads the layers
+ * in this order:
+ *
+ * env (OPENVIKING_*) → workspace `.openviking/config*.json` and the machine
+ * registry → ovcli.conf `plugin.claude_code` → ovcli.conf `plugin` →
+ * ov.conf's `claude_code` section (legacy) → the schema's defaults
+ *
+ * What stays here is what only this harness knows: whether the plugin is
+ * enabled at all, the file `configPath` has always named, and the tri-state
+ * digest mode.
*
* Enable/disable:
* - OPENVIKING_MEMORY_ENABLED env var (0/false/no = off, 1/true/yes = on)
* - claude_code.enabled field in ov.conf (false = off)
* - Fallback: enabled when ov.conf or ovcli.conf exists, disabled otherwise
*
- * Env vars covered (full list):
- * Connection / identity:
- * OPENVIKING_URL / OPENVIKING_BASE_URL, OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN,
- * OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID
- * Recall tuning:
- * OPENVIKING_AUTO_RECALL, OPENVIKING_RECALL_LIMIT, OPENVIKING_RECALL_TOKEN_BUDGET,
- * OPENVIKING_RECALL_MAX_CONTENT_CHARS, OPENVIKING_RECALL_PREFER_ABSTRACT,
- * OPENVIKING_SCORE_THRESHOLD, OPENVIKING_MIN_QUERY_LENGTH, OPENVIKING_LOG_RANKING_DETAILS,
- * OPENVIKING_RECALL_PEER_SCOPE, OPENVIKING_RECALL_COMPRESS,
- * OPENVIKING_RECALL_QUERY_FILTERS (CSV)
- * Capture tuning:
- * OPENVIKING_AUTO_CAPTURE, OPENVIKING_CAPTURE_MODE, OPENVIKING_CAPTURE_MAX_LENGTH,
- * OPENVIKING_CAPTURE_ASSISTANT_TURNS, OPENVIKING_COMMIT_TOKEN_THRESHOLD,
- * OPENVIKING_RESUME_CONTEXT_BUDGET, OPENVIKING_CAPTURE_FILTERS (CSV)
- * Lifecycle / behavior:
- * OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS, OPENVIKING_WRITE_PATH_ASYNC,
- * OPENVIKING_BYPASS_SESSION, OPENVIKING_BYPASS_SESSION_PATTERNS (CSV),
- * OPENVIKING_WORKSPACE_PEER
- * Profile injection (session_start):
- * OPENVIKING_NO_AUTO_INJECT, OPENVIKING_PROFILE_TOKEN_BUDGET
- * Skill experience injection (PostToolUse Read):
- * OPENVIKING_SKILL_EXPERIENCE, OPENVIKING_SKILL_EXPERIENCE_LIMIT
- * Misc:
- * OPENVIKING_MEMORY_ENABLED, OPENVIKING_DEBUG, OPENVIKING_DEBUG_LOG,
- * OPENVIKING_CONFIG_FILE, OPENVIKING_CLI_CONFIG_FILE
+ * Connection and credentials are not knobs and never come from a workspace
+ * file: OPENVIKING_URL / OPENVIKING_BASE_URL, OPENVIKING_API_KEY /
+ * OPENVIKING_BEARER_TOKEN, OPENVIKING_ACCOUNT, OPENVIKING_USER, then
+ * ovcli.conf, then ov.conf's server section.
*/
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve as resolvePath } from "node:path";
-import { buildUserAgent, readManifestVersion } from "./shared/credentials.mjs";
-import { HARNESS_KEYS, loadPluginSettings, normalizeRewriteMode } from "./shared/plugin-config.mjs";
+import { buildPluginConfig, normalizeRewriteMode } from "./shared/plugin-config.mjs";
const DEFAULT_OV_CONF_PATH = join(homedir(), ".openviking", "ov.conf");
const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
-const USER_AGENT = buildUserAgent(
- "claude-code",
- readManifestVersion(new URL("../.claude-plugin/plugin.json", import.meta.url)),
-);
-
-function num(val, fallback) {
- if (typeof val === "number" && Number.isFinite(val)) return val;
- if (typeof val === "string" && val.trim()) {
- const n = Number(val);
- if (Number.isFinite(n)) return n;
- }
- return fallback;
-}
-
-function str(val, fallback) {
- if (typeof val === "string" && val.trim()) return val.trim();
- return fallback;
-}
-
-function hasOwn(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj || {}, key);
-}
+const MANIFEST_URL = new URL("../.claude-plugin/plugin.json", import.meta.url);
function envBool(name) {
const v = process.env[name];
@@ -135,8 +97,6 @@ export function isPluginEnabled() {
/**
* Load the full plugin configuration.
*
- * Resolution: env vars → ovcli.conf → ov.conf → defaults.
- *
* `cwd` selects the workspace layer (`.openviking/config.json` and the
* registry entry for that directory). It defaults to this process's directory,
* which is all a hook knows at module load; a hook whose payload names the
@@ -146,295 +106,31 @@ export function isPluginEnabled() {
* load stay valid.
*/
export function loadConfig(cwd = process.cwd()) {
- const workspaceCwd = str(cwd, "") || process.cwd();
- const ovConf = tryLoadJsonFile("OPENVIKING_CONFIG_FILE", DEFAULT_OV_CONF_PATH);
- const cliConf = tryLoadJsonFile("OPENVIKING_CLI_CONFIG_FILE", DEFAULT_OVCLI_CONF_PATH);
-
- const ovFile = ovConf?.file || {};
- const cliFile = cliConf?.file || {};
- const configPath = ovConf?.configPath || cliConf?.configPath || null;
-
- const server = ovFile.server || {};
- // ovcli.conf plugin.<harness> overrides plugin.* which overrides ov.conf's
- // claude_code section, so client-side tuning no longer needs a server config.
- const pluginSettings = loadPluginSettings(HARNESS_KEYS.claudeCode, process.env, { cwd: workspaceCwd });
- const cc = { ...(ovFile.claude_code || {}), ...pluginSettings };
-
- // baseUrl: env → ovcli.url → ov.server.url → http://{host}:{port}
- const envUrl = str(process.env.OPENVIKING_URL, null) || str(process.env.OPENVIKING_BASE_URL, null);
- let baseUrl;
- if (envUrl) {
- baseUrl = envUrl.replace(/\/+$/, "");
- } else if (cliFile.url) {
- baseUrl = str(cliFile.url, "").replace(/\/+$/, "");
- } else if (server.url) {
- baseUrl = str(server.url, "").replace(/\/+$/, "");
- } else {
- const host = str(server.host, "127.0.0.1").replace("0.0.0.0", "127.0.0.1");
- const port = Math.floor(num(server.port, 1933));
- baseUrl = `http://${host}:${port}`;
- }
-
- // apiKey: env → ovcli.api_key → cc.apiKey → server.root_api_key
- // Accepts OPENVIKING_BEARER_TOKEN or OPENVIKING_API_KEY (sent as Bearer either way).
- const envApiKey = str(process.env.OPENVIKING_BEARER_TOKEN, null)
- || str(process.env.OPENVIKING_API_KEY, null);
- const apiKey = envApiKey
- || str(cliFile.api_key, null)
- || str(cc.apiKey, null)
- || str(server.root_api_key, "");
-
- // Which source actually supplied the api_key. `configPath` only reports the
- // file that parsed, so debug logs and 401 hints pointed at the wrong file
- // whenever both configs existed.
- const ccApiKeyFromCli = hasOwn(pluginSettings, "apiKey");
- let credentialSource = "none";
- let credentialPath = null;
- if (envApiKey) {
- credentialSource = "env";
- } else if (str(cliFile.api_key, null)) {
- credentialSource = "ovcli";
- credentialPath = cliConf?.configPath || null;
- } else if (str(cc.apiKey, null)) {
- credentialSource = ccApiKeyFromCli ? "ovcli" : "ov";
- credentialPath = (ccApiKeyFromCli ? cliConf?.configPath : ovConf?.configPath) || null;
- } else if (str(server.root_api_key, null)) {
- credentialSource = "ov";
- credentialPath = ovConf?.configPath || null;
- }
-
- // accountId: env → ovcli.account → cc.accountId → ""
- const accountId = str(process.env.OPENVIKING_ACCOUNT, null)
- || str(cliFile.account, null)
- || str(cc.accountId, "");
-
- // userId: env → ovcli.user → cc.userId → ""
- const userId = str(process.env.OPENVIKING_USER, null)
- || str(cliFile.user, null)
- || str(cc.userId, "");
-
- const peerId = str(process.env.OPENVIKING_PEER_ID, null)
- || str(cc.peerId, null)
- || str(cc.peer_id, "");
- const workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? (cc.workspacePeer !== false);
- const recallPeerScopeRaw = str(
- process.env.OPENVIKING_RECALL_PEER_SCOPE,
- str(cc.recallPeerScope, "all"),
- );
- const recallPeerScope = recallPeerScopeRaw === "actor" ? "actor" : "all";
-
- // Each tuning field follows env > ovcli.conf is N/A (CLI doesn't carry tuning) >
- // ov.conf cc.* > built-in default. Env var names are flat OPENVIKING_* (no CC
- // namespace) to match the existing connection-field convention; they are only
- // read by this plugin's hooks.
-
- const debug = envBool("OPENVIKING_DEBUG") ?? (cc.debug === true);
- const defaultLogPath = join(homedir(), ".openviking", "logs", "cc-hooks.log");
- const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);
-
- const timeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_TIMEOUT_MS,
- num(cc.timeoutMs, 15000),
- )));
- const captureTimeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_TIMEOUT_MS,
- num(cc.captureTimeoutMs, Math.max(timeoutMs * 2, 30000)),
- )));
-
- // captureMode whitelist: env or cc, only "keyword" flips it; anything else → "semantic"
- const captureModeRaw = str(process.env.OPENVIKING_CAPTURE_MODE, str(cc.captureMode, "semantic"));
- const captureMode = captureModeRaw === "keyword" ? "keyword" : "semantic";
-
- // bypassSessionPatterns: env CSV overrides ov.conf array entirely
- const envPatterns = str(process.env.OPENVIKING_BYPASS_SESSION_PATTERNS, null);
- const bypassSessionPatterns = envPatterns
- ? envPatterns.split(",").map((s) => s.trim()).filter(Boolean)
- : (Array.isArray(cc.bypassSessionPatterns)
- ? cc.bypassSessionPatterns.filter((p) => typeof p === "string" && p.trim())
- : []);
-
- // Input filter rule lists: env CSV overrides the configured array entirely,
- // same shape as bypassSessionPatterns. Both paths trim, so a rule reads the
- // same however it was configured — and a rule that needs a literal comma has
- // to come from the array, since the env value is split on it.
- const filterList = (envName, configured) => {
- const raw = str(process.env[envName], null);
- const list = raw !== null ? raw.split(",") : (Array.isArray(configured) ? configured : []);
- return list.filter((r) => typeof r === "string").map((r) => r.trim()).filter(Boolean);
- };
- const recallQueryFilters = filterList("OPENVIKING_RECALL_QUERY_FILTERS", cc.recallQueryFilters);
- const captureFilters = filterList("OPENVIKING_CAPTURE_FILTERS", cc.captureFilters);
+ const config = buildPluginConfig("claude-code", {
+ cwd,
+ manifestUrl: MANIFEST_URL,
+ logFile: "cc-hooks.log",
+ rootKeyFallback: true,
+ });
return {
- configPath,
- credentialSource,
- credentialPath,
- baseUrl,
- apiKey,
- accountId,
- userId,
- peerId,
- workspacePeer,
- peerSource: str(process.env.OPENVIKING_PEER_SOURCE, null) ?? cc.peerSource,
- harness: "claude-code",
- timeoutMs,
- userAgent: USER_AGENT,
+ ...config,
+ // `configPath` reports whichever file parsed, ov.conf first, and predates
+ // the pair of paths beside it.
+ configPath: config.ovPath || config.cliPath || null,
+ credentialPath: config.credentialPath || null,
- // Recall
- autoRecall: envBool("OPENVIKING_AUTO_RECALL") ?? (cc.autoRecall !== false),
- recallLimit: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_RECALL_LIMIT,
- num(cc.recallLimit, 10),
- ))),
- recallLimitConfigured: Boolean(process.env.OPENVIKING_RECALL_LIMIT) ||
- hasOwn(cc, "recallLimit"),
- scoreThreshold: Math.min(1, Math.max(0, num(
- process.env.OPENVIKING_SCORE_THRESHOLD,
- num(cc.scoreThreshold, 0.35),
- ))),
- minQueryLength: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_MIN_QUERY_LENGTH,
- num(cc.minQueryLength, 3),
- ))),
- logRankingDetails: envBool("OPENVIKING_LOG_RANKING_DETAILS") ?? (cc.logRankingDetails === true),
- // Ported from openclaw DEFAULT_RECALL_MAX_CONTENT_CHARS / DEFAULT_RECALL_TOKEN_BUDGET /
- // DEFAULT_RECALL_PREFER_ABSTRACT (openclaw-plugin/config.ts:44-47).
- recallMaxContentChars: Math.max(50, Math.floor(num(
- process.env.OPENVIKING_RECALL_MAX_CONTENT_CHARS,
- num(cc.recallMaxContentChars, 500),
- ))),
- recallTokenBudget: Math.max(200, Math.floor(num(
- process.env.OPENVIKING_RECALL_TOKEN_BUDGET,
- num(cc.recallTokenBudget, 2000),
- ))),
- recallPreferAbstract: envBool("OPENVIKING_RECALL_PREFER_ABSTRACT") ?? (cc.recallPreferAbstract !== false),
- recallPeerScope,
-
- // Server-side context assembly (/search mode="context").
- recallMaxTokens: Math.max(64, Math.floor(num(
- process.env.OPENVIKING_RECALL_MAX_TOKENS,
- num(cc.recallMaxTokens, 1600),
- ))),
- recallMaxTokensConfigured: Boolean(process.env.OPENVIKING_RECALL_MAX_TOKENS) ||
- hasOwn(cc, "recallMaxTokens"),
- recallDedupTurns: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_DEDUP_TURNS,
- num(cc.recallDedupTurns, 5),
- ))),
- recallQueryExpansion: str(
- process.env.OPENVIKING_RECALL_QUERY_EXPANSION,
- str(cc.recallQueryExpansion, "auto"),
- ) === "off" ? "off" : "auto",
- recallQueryExpansionConfigured: Boolean(process.env.OPENVIKING_RECALL_QUERY_EXPANSION) ||
- hasOwn(cc, "recallQueryExpansion"),
// Digest compression defaults to auto: prefer the local host CLI and fall
// back to the server when it is unavailable. A failed digest still falls
- // back to the uncompressed context block.
- // OPENVIKING_RECALL_REWRITE / recallRewrite are legacy aliases. Keep the
+ // back to the uncompressed context block. `recallRewrite` keeps the
// internal field name because the shared core maps this mode to the
- // server's `rewrite` request field.
+ // server's `rewrite` request field; OPENVIKING_RECALL_REWRITE is the older
+ // env spelling and still works.
recallRewrite: normalizeRewriteMode(
process.env.OPENVIKING_RECALL_COMPRESS
?? process.env.OPENVIKING_RECALL_REWRITE
- ?? cc.recallCompress
- ?? cc.recallRewrite,
+ ?? config.recallCompress,
"auto",
),
- // 0 keeps the built-in default, which outlasts the server's rewrite fuse.
- recallContextTimeoutMs: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS,
- num(cc.recallContextTimeoutMs, 0),
- ))),
- recallCompressMinInputChars: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS,
- num(cc.recallCompressMinInputChars, 1500),
- ))),
- recallCompressMaxInputChars: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS,
- num(cc.recallCompressMaxInputChars, 18000),
- ))),
- recallCompressMaxBullets: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MAX_BULLETS,
- num(cc.recallCompressMaxBullets, 6),
- ))),
- recallCompressMaxBulletsConfigured:
- Boolean(process.env.OPENVIKING_RECALL_COMPRESS_MAX_BULLETS) ||
- hasOwn(cc, "recallCompressMaxBullets"),
-
- // Capture
- autoCapture: envBool("OPENVIKING_AUTO_CAPTURE") ?? (cc.autoCapture !== false),
- captureMode,
- captureMaxLength: Math.max(200, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_MAX_LENGTH,
- num(cc.captureMaxLength, 24000),
- ))),
- // Tool output is reported verbatim; the server owns truncation via
- // tool_output_externalization (threshold_chars, default 20000). This cap only
- // guards against pathological payloads.
- captureToolMaxChars: Math.max(200, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS,
- num(cc.captureToolMaxChars, 1000000),
- ))),
- captureTimeoutMs,
- // Default true: a "memory plugin" without assistant-side capture only sees half the
- // conversation, which makes extraction noticeably worse. Subagent capture has always
- // pushed both sides (subagent-stop.mjs); this aligns the main-session path with that
- // behavior. Operators who want the old user-only behavior can still set
- // OPENVIKING_CAPTURE_ASSISTANT_TURNS=0 or claude_code.captureAssistantTurns=false.
- captureAssistantTurns: envBool("OPENVIKING_CAPTURE_ASSISTANT_TURNS") ?? (cc.captureAssistantTurns !== false),
- // P0-2: client-driven commit threshold (ported from openclaw afterTurn).
- // Default 20000 aligns with openclaw; lower values produce archives faster.
- commitTokenThreshold: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD,
- num(cc.commitTokenThreshold, 20000),
- ))),
- commitKeepRecentCount: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT,
- num(cc.commitKeepRecentCount, 10),
- ))),
-
- // P0-3b: token budget for session-start archive-overview fetch
- resumeContextBudget: Math.max(1024, Math.floor(num(
- process.env.OPENVIKING_RESUME_CONTEXT_BUDGET,
- num(cc.resumeContextBudget, 32000),
- ))),
-
- // Session-start profile injection: pull profile.md + ls of preferences/
- // and entities/ on every session_start (startup/clear/resume/compact),
- // independent of UserPromptSubmit auto-recall. Subagents skip entirely
- // (handled by subagent-start.mjs not invoking buildProfileBlock).
- noAutoInject: envBool("OPENVIKING_NO_AUTO_INJECT") ?? (cc.noAutoInject === true),
- profileTokenBudget: Math.max(500, Math.floor(num(
- process.env.OPENVIKING_PROFILE_TOKEN_BUDGET,
- num(cc.profileTokenBudget, 10000),
- ))),
-
- skillExperience: envBool("OPENVIKING_SKILL_EXPERIENCE") ?? (cc.skillExperience === true),
- skillExperienceLimit: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_SKILL_EXPERIENCE_LIMIT,
- num(cc.skillExperienceLimit, 3),
- ))),
-
- // P1-15: bypass patterns (glob) — when the CC session_id or cwd matches,
- // skip capture/recall entirely. Useful for one-off scratch sessions that
- // should not contaminate OV.
- bypassSessionPatterns,
- bypassSession: envBool("OPENVIKING_BYPASS_SESSION") ?? false,
-
- // Ordered sed-style rules over the text the plugin sends: the recall query
- // on UserPromptSubmit, and every captured turn on the write path.
- recallQueryFilters,
- captureFilters,
-
- // Write-path async: auto-capture / session-end / subagent-stop fire-and-
- // forget via a detached child process, so the hook returns to CC instantly.
- // pre-compact stays sync regardless (CC rewrites transcript right after).
- // Default on — OV commit is already half-async server-side, so eventual
- // consistency matches the sync path.
- writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC") ?? (cc.writePathAsync !== false),
-
- // Debug
- debug,
- debugLogPath,
};
}
diff --git a/examples/claude-code-memory-plugin/scripts/config.test.mjs b/examples/claude-code-memory-plugin/scripts/config.test.mjs
index f7fc0115f..0228b3cbd 100644
--- a/examples/claude-code-memory-plugin/scripts/config.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/config.test.mjs
@@ -1,19 +1,23 @@
import assert from "node:assert/strict";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { loadConfig } from "./config.mjs";
+// The layers, the knobs and the peer are the shared loader's, and
+// memory-plugin-shared/plugin-config.test.mjs holds this harness to them. What
+// is left here is what this harness answers itself: which file the credential
+// came from, and the tri-state digest mode.
const OVERRIDES = [
"OPENVIKING_CONFIG_FILE",
"OPENVIKING_CLI_CONFIG_FILE",
"OPENVIKING_HOME",
"OPENVIKING_STATE_DIR",
- "OPENVIKING_PEER_ID",
- "OPENVIKING_AUTO_CAPTURE",
"OPENVIKING_API_KEY",
"OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_RECALL_COMPRESS",
+ "OPENVIKING_RECALL_REWRITE",
"OPENVIKING_RECALL_QUERY_FILTERS",
"OPENVIKING_CAPTURE_FILTERS",
];
@@ -21,34 +25,22 @@ const OVERRIDES = [
/**
* Run loadConfig() against a throwaway ~/.openviking pair, with the env vars
* that feed the credential chain reset to exactly what the case needs.
- *
- * `workspace` is written to `workspace/.openviking/config.json`; the bare
- * `.git` beside it is what makes that directory a workspace root, and
- * `other/` is a second directory with neither.
*/
-function withConfigs({ ov, cli, workspace, env = {} }, fn) {
+function withConfigs({ ov, cli, env = {} }, fn) {
const dir = mkdtempSync(join(tmpdir(), "cc-config-"));
const ovPath = join(dir, "ov.conf");
const cliPath = join(dir, "ovcli.conf");
- const workspaceDir = join(dir, "workspace");
- const otherDir = join(dir, "other");
const saved = Object.fromEntries(OVERRIDES.map((key) => [key, process.env[key]]));
try {
for (const key of OVERRIDES) delete process.env[key];
if (ov) writeFileSync(ovPath, JSON.stringify(ov));
if (cli) writeFileSync(cliPath, JSON.stringify(cli));
- mkdirSync(join(workspaceDir, ".openviking"), { recursive: true });
- mkdirSync(join(workspaceDir, ".git"), { recursive: true });
- mkdirSync(otherDir, { recursive: true });
- if (workspace) {
- writeFileSync(join(workspaceDir, ".openviking", "config.json"), JSON.stringify(workspace));
- }
process.env.OPENVIKING_CONFIG_FILE = ovPath;
process.env.OPENVIKING_CLI_CONFIG_FILE = cliPath;
// Keeps the identity cache and the workspace registry out of the real home.
process.env.OPENVIKING_HOME = join(dir, "home");
Object.assign(process.env, env);
- return fn({ ovPath, cliPath, workspaceDir, otherDir });
+ return fn({ ovPath, cliPath });
} finally {
for (const [key, value] of Object.entries(saved)) {
if (value === undefined) delete process.env[key];
@@ -65,7 +57,7 @@ test("an ovcli.conf api_key is reported as the credential source", () => {
}, ({ ovPath, cliPath }) => {
const cfg = loadConfig();
assert.equal(cfg.apiKey, "sk-cli");
- assert.equal(cfg.credentialSource, "ovcli");
+ assert.equal(cfg.apiKeySource, "ovcli");
assert.equal(cfg.credentialPath, cliPath);
// configPath stays "whichever file parsed" for backward compat.
assert.equal(cfg.configPath, ovPath);
@@ -79,35 +71,11 @@ test("an ov.conf root_api_key is reported even when ovcli.conf exists", () => {
}, ({ ovPath }) => {
const cfg = loadConfig();
assert.equal(cfg.apiKey, "sk-root");
- assert.equal(cfg.credentialSource, "ov");
+ assert.equal(cfg.apiKeySource, "ov");
assert.equal(cfg.credentialPath, ovPath);
});
});
-test("an ov.conf claude_code.apiKey is reported as ov.conf", () => {
- withConfigs({
- ov: { claude_code: { apiKey: "sk-cc" } },
- cli: { url: "http://127.0.0.1:1933" },
- }, ({ ovPath }) => {
- const cfg = loadConfig();
- assert.equal(cfg.apiKey, "sk-cc");
- assert.equal(cfg.credentialSource, "ov");
- assert.equal(cfg.credentialPath, ovPath);
- });
-});
-
-test("an ovcli.conf plugin.claude_code.apiKey is reported as ovcli.conf", () => {
- withConfigs({
- ov: { server: {} },
- cli: { url: "http://127.0.0.1:1933", plugin: { claude_code: { apiKey: "sk-plugin" } } },
- }, ({ cliPath }) => {
- const cfg = loadConfig();
- assert.equal(cfg.apiKey, "sk-plugin");
- assert.equal(cfg.credentialSource, "ovcli");
- assert.equal(cfg.credentialPath, cliPath);
- });
-});
-
test("an env api_key wins and carries no path", () => {
withConfigs({
ov: { server: { root_api_key: "sk-root" } },
@@ -116,53 +84,46 @@ test("an env api_key wins and carries no path", () => {
}, () => {
const cfg = loadConfig();
assert.equal(cfg.apiKey, "sk-env");
- assert.equal(cfg.credentialSource, "env");
+ assert.equal(cfg.apiKeySource, "env");
assert.equal(cfg.credentialPath, null);
});
});
-test("the workspace layer follows the cwd it is handed, not the process's", () => {
+test("no api_key anywhere reports no source", () => {
withConfigs({
- ov: { server: {} },
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
- workspace: { version: 1, peer: { id: "team-a" }, capture: { enabled: false } },
- }, ({ workspaceDir, otherDir }) => {
- const inside = loadConfig(workspaceDir);
- assert.equal(inside.peerId, "team-a");
- assert.equal(inside.autoCapture, false);
-
- const outside = loadConfig(otherDir);
- assert.equal(outside.peerId, "");
- assert.equal(outside.autoCapture, true);
+ ov: { server: { host: "127.0.0.1" } },
+ cli: { url: "http://127.0.0.1:1933" },
+ }, () => {
+ const cfg = loadConfig();
+ assert.equal(cfg.apiKey, "");
+ assert.equal(cfg.apiKeySource, "none");
+ assert.equal(cfg.credentialPath, null);
});
});
-test("an omitted cwd falls back to this process's directory", () => {
+// `recallRewrite` is a tri-state this harness reads from the shared on/off
+// switch, so a mode the switch cannot express still has to survive the trip.
+test("the digest mode is this harness's own tri-state, under either env name", () => {
withConfigs({
ov: { server: {} },
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
- workspace: { version: 1, capture: { enabled: false } },
- }, ({ workspaceDir }) => {
- const origin = process.cwd();
- try {
- process.chdir(workspaceDir);
- assert.equal(loadConfig().autoCapture, false);
- assert.equal(loadConfig("").autoCapture, false);
- } finally {
- process.chdir(origin);
- }
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { recallCompress: "server" } },
+ }, () => {
+ assert.equal(loadConfig().recallRewrite, "server");
});
-});
-test("no api_key anywhere reports no source", () => {
withConfigs({
- ov: { server: { host: "127.0.0.1" } },
- cli: { url: "http://127.0.0.1:1933" },
+ ov: { server: {} },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { recallCompress: "louder" } },
}, () => {
- const cfg = loadConfig();
- assert.equal(cfg.apiKey, "");
- assert.equal(cfg.credentialSource, "none");
- assert.equal(cfg.credentialPath, null);
+ assert.equal(loadConfig().recallRewrite, "auto", "an unreadable mode falls back to auto");
+ });
+
+ withConfigs({
+ ov: { server: {} },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { recallCompress: "off" } },
+ env: { OPENVIKING_RECALL_REWRITE: "client" },
+ }, () => {
+ assert.equal(loadConfig().recallRewrite, "client", "the older env spelling still works");
});
});
diff --git a/examples/claude-code-memory-plugin/scripts/debug-capture.mjs b/examples/claude-code-memory-plugin/scripts/debug-capture.mjs
deleted file mode 100755
index 5663757a3..000000000
--- a/examples/claude-code-memory-plugin/scripts/debug-capture.mjs
+++ /dev/null
@@ -1,488 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Debug Capture Pipeline — standalone test script.
- *
- * Usage:
- * node scripts/debug-capture.mjs /path/to/transcript.jsonl [session-id]
- * echo "remember I like Rust" | node scripts/debug-capture.mjs --stdin
- *
- * Runs the same capture pipeline as auto-capture.mjs but prints every
- * intermediate stage to stdout in a human-readable format instead of
- * silently returning a hook decision.
- */
-
-import { readFile, writeFile, mkdir } from "node:fs/promises";
-import { join } from "node:path";
-import { tmpdir } from "node:os";
-import { loadConfig } from "./config.mjs";
-
-// ---------------------------------------------------------------------------
-// ANSI helpers
-// ---------------------------------------------------------------------------
-
-const C = {
- reset: "\x1b[0m",
- dim: "\x1b[2m",
- bold: "\x1b[1m",
- red: "\x1b[31m",
- green: "\x1b[32m",
- yellow: "\x1b[33m",
- cyan: "\x1b[36m",
-};
-
-function header(title) {
- console.log(`\n${C.cyan}${C.bold}═══ ${title} ═══${C.reset}\n`);
-}
-
-function ok(msg) { console.log(`${C.green}\u2713${C.reset} ${msg}`); }
-function warn(msg) { console.log(`${C.yellow}\u26A0${C.reset} ${msg}`); }
-function fail(msg) { console.log(`${C.red}\u2717${C.reset} ${msg}`); }
-function dim(msg) { console.log(`${C.dim}${msg}${C.reset}`); }
-
-function preview(text, maxLen) {
- if (text.length <= maxLen) return text;
- return text.slice(0, maxLen) + "...";
-}
-
-// ---------------------------------------------------------------------------
-// State directory for incremental tracking
-// ---------------------------------------------------------------------------
-
-const STATE_DIR = join(tmpdir(), "openviking-cc-capture-state");
-
-function stateFilePath(sessionId) {
- const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
- return join(STATE_DIR, `${safe}.json`);
-}
-
-async function loadState(sessionId) {
- try {
- const data = await readFile(stateFilePath(sessionId), "utf-8");
- return JSON.parse(data);
- } catch {
- return { capturedTurnCount: 0 };
- }
-}
-
-async function saveState(sessionId, state) {
- try {
- await mkdir(STATE_DIR, { recursive: true });
- await writeFile(stateFilePath(sessionId), JSON.stringify(state));
- } catch { /* best effort */ }
-}
-
-// ---------------------------------------------------------------------------
-// Text processing (copied from auto-capture.mjs)
-// ---------------------------------------------------------------------------
-
-const MEMORY_TRIGGERS = [
- /remember|preference|prefer|important|decision|decided|always|never/i,
- /记住|偏好|喜欢|喜爱|崇拜|讨厌|害怕|重要|决定|总是|永远|优先|习惯|爱好|擅长|最爱|不喜欢/i,
- /[\w.-]+@[\w.-]+\.\w+/,
- /\+\d{10,}/,
- /(?:我|my)\s*(?:是|叫|名字|name|住在|live|来自|from|生日|birthday|电话|phone|邮箱|email)/i,
- /(?:我|i)\s*(?:喜欢|崇拜|讨厌|害怕|擅长|不会|爱|恨|想要|需要|希望|觉得|认为|相信)/i,
- /(?:favorite|favourite|love|hate|enjoy|dislike|admire|idol|fan of)/i,
-];
-
-const RELEVANT_MEMORIES_BLOCK_RE = /<relevant-memories>[\s\S]*?<\/relevant-memories>/gi;
-const COMMAND_TEXT_RE = /^\/[a-z0-9_-]{1,64}\b/i;
-const NON_CONTENT_TEXT_RE = /^[\p{P}\p{S}\s]+$/u;
-const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
-
-function sanitize(text) {
- return text
- .replace(RELEVANT_MEMORIES_BLOCK_RE, " ")
- .replace(/\u0000/g, "")
- .replace(/\s+/g, " ")
- .trim();
-}
-
-function shouldCapture(text) {
- const normalized = sanitize(text);
- if (!normalized) return { capture: false, reason: "empty", text: "" };
-
- const compact = normalized.replace(/\s+/g, "");
- const minLen = CJK_CHAR_RE.test(compact) ? 4 : 10;
- if (compact.length < minLen || normalized.length > cfg.captureMaxLength) {
- return { capture: false, reason: "length_out_of_range", text: normalized };
- }
-
- if (COMMAND_TEXT_RE.test(normalized)) {
- return { capture: false, reason: "command", text: normalized };
- }
-
- if (NON_CONTENT_TEXT_RE.test(normalized)) {
- return { capture: false, reason: "non_content", text: normalized };
- }
-
- if (cfg.captureMode === "keyword") {
- for (const trigger of MEMORY_TRIGGERS) {
- if (trigger.test(normalized)) {
- return { capture: true, reason: `trigger:${trigger}`, text: normalized };
- }
- }
- return { capture: false, reason: "no_trigger", text: normalized };
- }
-
- // semantic mode — always capture
- return { capture: true, reason: "semantic", text: normalized };
-}
-
-// ---------------------------------------------------------------------------
-// Transcript parsing (copied from auto-capture.mjs)
-// ---------------------------------------------------------------------------
-
-function parseTranscript(content) {
- try {
- const data = JSON.parse(content);
- if (Array.isArray(data)) return { messages: data, format: "JSON array" };
- } catch { /* not a JSON array */ }
-
- const lines = content.split("\n").filter(l => l.trim());
- const messages = [];
- for (const line of lines) {
- try { messages.push(JSON.parse(line)); } catch { /* skip */ }
- }
- return { messages, format: "JSONL" };
-}
-
-function extractAllTurns(messages) {
- const turns = [];
- for (const msg of messages) {
- if (!msg || typeof msg !== "object") continue;
-
- let role = msg.role;
- let text = "";
-
- if (typeof msg.content === "string") {
- text = msg.content;
- } else if (Array.isArray(msg.content)) {
- const textParts = msg.content
- .filter(b => b && b.type === "text" && typeof b.text === "string")
- .map(b => b.text);
- text = textParts.join("\n");
- } else if (typeof msg.message === "object" && msg.message) {
- const inner = msg.message;
- role = inner.role || role;
- if (typeof inner.content === "string") {
- text = inner.content;
- } else if (Array.isArray(inner.content)) {
- const textParts = inner.content
- .filter(b => b && b.type === "text" && typeof b.text === "string")
- .map(b => b.text);
- text = textParts.join("\n");
- }
- }
-
- if (role !== "user" && role !== "assistant") continue;
- if (text.trim()) {
- turns.push({ role, text: text.trim() });
- }
- }
- return turns;
-}
-
-// ---------------------------------------------------------------------------
-// fetchJSON — verbose version for debugging
-// ---------------------------------------------------------------------------
-
-async function fetchJSON(path, init = {}) {
- const url = `${cfg.baseUrl}${path}`;
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);
- try {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;
- if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- const res = await fetch(url, { ...init, headers, signal: controller.signal });
- const body = await res.json();
- dim(` ${init.method || "GET"} ${path} -> ${res.status}`);
- if (!res.ok || body.status === "error") {
- fail(` Response error: ${JSON.stringify(body).slice(0, 300)}`);
- return null;
- }
- const result = body.result ?? body;
- dim(` Response: ${JSON.stringify(result).slice(0, 300)}`);
- return result;
- } catch (err) {
- fail(` Fetch failed: ${url} — ${err?.message || err}`);
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
-
-// ---------------------------------------------------------------------------
-// captureToOpenViking — verbose version showing each step
-// ---------------------------------------------------------------------------
-
-async function captureToOpenViking(text) {
- header("Session Pipeline");
-
- // Step 1: Create session
- console.log("Step 1: Creating session...");
- const sessionResult = await fetchJSON("/api/v1/sessions", {
- method: "POST",
- body: JSON.stringify({}),
- });
- if (!sessionResult?.session_id) {
- fail("Session creation failed — no session_id returned");
- return { ok: false, reason: "session_create_failed" };
- }
- ok(`Session created: ${sessionResult.session_id}`);
-
- const sessionId = sessionResult.session_id;
- try {
- // Step 2: Add message
- console.log("\nStep 2: Adding message...");
- const body = { role: "user", content: text };
- if (cfg.peerId) body.peer_id = cfg.peerId;
- const addResult = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
- method: "POST",
- body: JSON.stringify(body),
- });
- if (addResult) {
- ok("Message added to session");
- } else {
- warn("addMessage returned null (may still work)");
- }
-
- // Step 3: Extract
- console.log("\nStep 3: Extracting memories...");
- const extracted = await fetchJSON(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/extract`,
- { method: "POST", body: JSON.stringify({}) },
- );
-
- if (extracted) {
- ok("Extraction completed");
- } else {
- fail("Extraction returned null");
- }
-
- // Show extracted memories
- header("Extracted Memories");
- const memories = Array.isArray(extracted) ? extracted : [];
- if (memories.length === 0) {
- warn("No memories extracted");
- } else {
- ok(`${memories.length} memor${memories.length === 1 ? "y" : "ies"} extracted:`);
- for (let i = 0; i < memories.length; i++) {
- const m = memories[i];
- console.log(`\n ${C.green}[${i + 1}]${C.reset}`);
- if (m.id) dim(` id: ${m.id}`);
- if (m.content) console.log(` content: ${preview(String(m.content), 200)}`);
- if (m.category) dim(` category: ${m.category}`);
- if (m.score != null) dim(` score: ${m.score}`);
- // Print any other fields
- for (const key of Object.keys(m)) {
- if (!["id", "content", "category", "score"].includes(key)) {
- dim(` ${key}: ${JSON.stringify(m[key]).slice(0, 150)}`);
- }
- }
- }
- }
-
- return { ok: true, count: memories.length };
- } finally {
- // Cleanup session
- dim("\nCleaning up session...");
- await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, {
- method: "DELETE",
- }).catch(() => {});
- }
-}
-
-// ---------------------------------------------------------------------------
-// stdin reader
-// ---------------------------------------------------------------------------
-
-async function readStdin() {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- return Buffer.concat(chunks).toString();
-}
-
-// ---------------------------------------------------------------------------
-// Config (loaded at module level like auto-capture.mjs)
-// ---------------------------------------------------------------------------
-
-const cfg = loadConfig();
-
-// ---------------------------------------------------------------------------
-// Main
-// ---------------------------------------------------------------------------
-
-async function main() {
- const args = process.argv.slice(2);
- const isStdin = args.includes("--stdin");
-
- if (args.length === 0 && !isStdin) {
- console.error(`Usage:
- node scripts/debug-capture.mjs /path/to/transcript.jsonl [session-id]
- echo "remember I like Rust" | node scripts/debug-capture.mjs --stdin`);
- process.exit(1);
- }
-
- // ── Stage 1: Config summary ──
- header("Config Summary");
- console.log(` baseUrl: ${cfg.baseUrl}`);
- console.log(` captureMode: ${cfg.captureMode}`);
- console.log(` captureMaxLength: ${cfg.captureMaxLength}`);
- console.log(` captureTimeoutMs: ${cfg.captureTimeoutMs}`);
- console.log(` captureAssistant: ${cfg.captureAssistantTurns}`);
- console.log(` debug: ${cfg.debug}`);
- console.log(` timeoutMs: ${cfg.timeoutMs}`);
-
- let allTurns;
- let sessionId;
- let skipIncremental = false;
- let transcriptFormat;
-
- if (isStdin) {
- // ── stdin mode ──
- header("Transcript Parsing");
- const stdinText = await readStdin();
- if (!stdinText.trim()) {
- fail("No input received on stdin");
- process.exit(1);
- }
- allTurns = [{ role: "user", text: stdinText.trim() }];
- sessionId = "stdin-debug";
- skipIncremental = true;
- transcriptFormat = "stdin text";
- ok(`Format: ${transcriptFormat}`);
- ok(`Total turns: ${allTurns.length}`);
- dim(` Text: ${preview(stdinText.trim(), 100)}`);
- } else {
- // ── file mode ──
- const transcriptPath = args[0];
- sessionId = args[1] || "debug-" + Date.now();
-
- header("Transcript Parsing");
- let transcriptContent;
- try {
- transcriptContent = await readFile(transcriptPath, "utf-8");
- } catch (err) {
- fail(`Failed to read transcript: ${transcriptPath} — ${err?.message || err}`);
- process.exit(1);
- }
-
- if (!transcriptContent.trim()) {
- fail("Transcript file is empty");
- process.exit(1);
- }
-
- const { messages, format } = parseTranscript(transcriptContent);
- transcriptFormat = format;
- allTurns = extractAllTurns(messages);
-
- ok(`Format: ${transcriptFormat}`);
- ok(`Total messages parsed: ${messages.length}`);
- ok(`Total turns extracted: ${allTurns.length}`);
- dim(` Session ID: ${sessionId}`);
- }
-
- if (allTurns.length === 0) {
- warn("No turns to process");
- process.exit(0);
- }
-
- // ── Stage 3: Incremental state ──
- header("Incremental State");
- let newTurns;
- let captureTurns;
- if (skipIncremental) {
- dim(" Skipped (stdin mode)");
- newTurns = allTurns;
- ok(`New turns to process: ${newTurns.length}`);
- } else {
- const state = await loadState(sessionId);
- dim(` State file: ${stateFilePath(sessionId)}`);
- console.log(` Previously captured: ${state.capturedTurnCount}`);
- newTurns = allTurns.slice(state.capturedTurnCount);
- ok(`New turns to process: ${newTurns.length}`);
- if (newTurns.length === 0) {
- warn("All turns already captured — nothing to do");
- process.exit(0);
- }
- }
- captureTurns = cfg.captureAssistantTurns
- ? newTurns
- : newTurns.filter(turn => turn.role === "user");
- ok(`Turns selected for capture: ${captureTurns.length}`);
- if (!cfg.captureAssistantTurns) {
- dim(` Assistant turns skipped: ${newTurns.length - captureTurns.length}`);
- }
- if (captureTurns.length === 0) {
- warn("No user turns in the new incremental slice — nothing will be sent");
- if (!skipIncremental) {
- await saveState(sessionId, { capturedTurnCount: allTurns.length });
- dim(" State updated (assistant-only turns marked as seen)");
- }
- process.exit(0);
- }
-
- // ── Stage 4: shouldCapture decisions ──
- header("shouldCapture Decisions");
- for (let i = 0; i < captureTurns.length; i++) {
- const turn = captureTurns[i];
- const decision = shouldCapture(turn.text);
- const captureLabel = decision.capture
- ? `${C.green}true${C.reset}`
- : `${C.dim}false${C.reset}`;
- console.log(` [${i}] ${C.dim}(${turn.role})${C.reset} capture=${captureLabel} reason=${decision.reason}`);
- dim(` ${preview(decision.text || turn.text, 100)}`);
- }
-
- // Build combined text from capturable turns (same logic as auto-capture.mjs)
- const turnText = captureTurns.map(t => `[${t.role}]: ${t.text}`).join("\n");
- const combinedDecision = shouldCapture(turnText);
-
- header("Combined Capture Decision");
- if (combinedDecision.capture) {
- ok(`capture=true reason=${combinedDecision.reason}`);
- } else {
- fail(`capture=false reason=${combinedDecision.reason}`);
- // Save state even on skip so next run doesn't re-examine these turns
- if (!skipIncremental) {
- await saveState(sessionId, { capturedTurnCount: allTurns.length });
- dim(" State updated (turns marked as seen)");
- }
- console.log("\nPipeline stopped — combined text did not pass shouldCapture.");
- process.exit(0);
- }
-
- // ── Stage 5: Text sent to OpenViking ──
- header("Text Sent to OpenViking");
- console.log(preview(combinedDecision.text, 500));
- dim(`\n (total length: ${combinedDecision.text.length} chars)`);
-
- // ── Stage 6 + 7: Session pipeline + extracted memories ──
- const result = await captureToOpenViking(combinedDecision.text);
-
- // Update state
- if (!skipIncremental) {
- await saveState(sessionId, { capturedTurnCount: allTurns.length });
- dim("\nState updated (turns marked as captured)");
- }
-
- // Final summary
- header("Summary");
- if (result.ok) {
- ok(`Pipeline completed — ${result.count} memor${result.count === 1 ? "y" : "ies"} extracted from ${captureTurns.length} captured turn${captureTurns.length === 1 ? "" : "s"}`);
- } else {
- fail(`Pipeline failed: ${result.reason}`);
- process.exit(1);
- }
-}
-
-main().catch(err => {
- fail(`Unhandled error: ${err?.message || err}`);
- if (err?.stack) dim(err.stack);
- process.exit(1);
-});
diff --git a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs
deleted file mode 100755
index f48367009..000000000
--- a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs
+++ /dev/null
@@ -1,451 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Debug Recall Pipeline — standalone test script.
- *
- * Usage: node scripts/debug-recall.mjs "我喜欢什么语言"
- *
- * Walks through every stage of the auto-recall pipeline and prints
- * human-readable output so you can see exactly what OpenViking returns,
- * how scoring/ranking works, and what the final injected message looks like.
- */
-
-import { loadConfig } from "./config.mjs";
-
-// ---------------------------------------------------------------------------
-// ANSI helpers
-// ---------------------------------------------------------------------------
-
-const C = {
- reset: "\x1b[0m",
- dim: "\x1b[2m",
- bold: "\x1b[1m",
- red: "\x1b[31m",
- green: "\x1b[32m",
- yellow: "\x1b[33m",
- cyan: "\x1b[36m",
-};
-
-function header(title) {
- console.log(`\n${C.cyan}${C.bold}═══ ${title} ═══${C.reset}\n`);
-}
-
-function ok(msg) { console.log(`${C.green}${msg}${C.reset}`); }
-function warn(msg) { console.log(`${C.yellow}${msg}${C.reset}`); }
-function fail(msg) { console.log(`${C.red}${msg}${C.reset}`); }
-function dim(msg) { console.log(`${C.dim}${msg}${C.reset}`); }
-
-// ---------------------------------------------------------------------------
-// CLI validation
-// ---------------------------------------------------------------------------
-
-const query = process.argv[2];
-if (!query || !query.trim()) {
- fail("Usage: node scripts/debug-recall.mjs \"<query>\"");
- fail(" e.g. node scripts/debug-recall.mjs \"我喜欢什么语言\"");
- process.exit(1);
-}
-
-// ---------------------------------------------------------------------------
-// Config
-// ---------------------------------------------------------------------------
-
-let cfg;
-try {
- cfg = loadConfig();
-} catch (err) {
- fail(`Config loading failed: ${err?.message || err}`);
- process.exit(1);
-}
-
-// ---------------------------------------------------------------------------
-// fetchJSON (verbose version — shows response details on error)
-// ---------------------------------------------------------------------------
-
-async function fetchJSON(path, init = {}, options = {}) {
- const url = `${cfg.baseUrl}${path}`;
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);
- try {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;
- if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;
- const actorPeerId = options.actorPeerId ?? "";
- if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- const res = await fetch(url, { ...init, headers, signal: controller.signal });
- const body = await res.json();
- if (!res.ok || body.status === "error") {
- warn(` HTTP ${res.status} from ${path}`);
- dim(` Response: ${JSON.stringify(body).slice(0, 500)}`);
- return null;
- }
- return body.result ?? body;
- } catch (err) {
- if (err?.name === "AbortError") {
- fail(` Request timed out after ${cfg.timeoutMs}ms: ${path}`);
- } else {
- fail(` Fetch error for ${path}: ${err?.message || err}`);
- }
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
-
-// ---------------------------------------------------------------------------
-// Pure functions — copied from auto-recall.mjs
-// ---------------------------------------------------------------------------
-
-function clampScore(v) {
- if (typeof v !== "number" || Number.isNaN(v)) return 0;
- return Math.max(0, Math.min(1, v));
-}
-
-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\u4e00-\u9fa5]{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",
-]);
-
-function buildQueryProfile(queryText) {
- const text = queryText.trim();
- const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
- const tokens = allTokens.filter(t => !STOPWORDS.has(t));
- return {
- tokens,
- 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 rankForInjection(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 dedupeByAbstract(items) {
- const seen = new Set();
- return items.filter(item => {
- const key = (item.abstract || item.overview || "").trim().toLowerCase() || item.uri;
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- });
-}
-
-function pickMemories(items, limit, queryText) {
- if (items.length === 0 || limit <= 0) return [];
- const profile = buildQueryProfile(queryText);
- const sorted = [...items].sort((a, b) => rankForInjection(b, profile) - rankForInjection(a, profile));
- const deduped = dedupeByAbstract(sorted);
- const leaves = deduped.filter(m => m.level === 2 || m.uri.endsWith(".md"));
- if (leaves.length >= limit) return leaves.slice(0, limit);
- const picked = [...leaves];
- const used = new Set(picked.map(m => m.uri));
- for (const item of deduped) {
- if (picked.length >= limit) break;
- if (used.has(item.uri)) continue;
- picked.push(item);
- }
- return picked;
-}
-
-function postProcess(items, limit, threshold) {
- const seen = new Set();
- const sorted = [...items].sort((a, b) => clampScore(b.score) - clampScore(a.score));
- const result = [];
- for (const item of sorted) {
- if (item.level !== 2) continue;
- if (clampScore(item.score) < threshold) continue;
- const cat = (item.category || "").toLowerCase() || "unknown";
- const abs = (item.abstract || item.overview || "").trim().toLowerCase();
- const key = abs ? `${cat}:${abs}` : `uri:${item.uri}`;
- if (seen.has(key)) continue;
- seen.add(key);
- result.push(item);
- if (result.length >= limit) break;
- }
- return result;
-}
-
-// ---------------------------------------------------------------------------
-// URI space resolution — copied from auto-recall.mjs
-// ---------------------------------------------------------------------------
-
-const USER_RESERVED_DIRS = new Set(["memories"]);
-const AGENT_RESERVED_DIRS = new Set(["memories", "skills"]);
-const _spaceCache = {};
-
-async function resolveScopeSpace(scope) {
- if (_spaceCache[scope]) return _spaceCache[scope];
-
- let fallbackSpace = "default";
- try {
- const status = await fetchJSON("/api/v1/system/status");
- if (status && typeof status.user === "string" && status.user.trim()) {
- fallbackSpace = status.user.trim();
- }
- } catch { /* use fallback */ }
-
- const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;
- try {
- const entries = await fetchJSON(
- `/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`,
- {},
- { actorPeerId: cfg.peerId },
- );
- if (Array.isArray(entries)) {
- const spaces = entries
- .filter(e => e?.isDir)
- .map(e => (typeof e.name === "string" ? e.name.trim() : ""))
- .filter(n => n && !n.startsWith(".") && !reservedDirs.has(n));
- if (spaces.length > 0) {
- if (spaces.includes(fallbackSpace)) { _spaceCache[scope] = fallbackSpace; return fallbackSpace; }
- if (scope === "user" && spaces.includes("default")) { _spaceCache[scope] = "default"; return "default"; }
- if (spaces.length === 1) { _spaceCache[scope] = spaces[0]; return spaces[0]; }
- }
- }
- } catch { /* use fallback */ }
-
- _spaceCache[scope] = fallbackSpace;
- return fallbackSpace;
-}
-
-async function resolveTargetUri(targetUri) {
- const trimmed = targetUri.trim().replace(/\/+$/, "");
- const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);
- if (!m) return trimmed;
- const scope = m[1];
- const rawRest = (m[2] ?? "").trim();
- if (!rawRest) return trimmed;
- const parts = rawRest.split("/").filter(Boolean);
- if (parts.length === 0) return trimmed;
- const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;
- if (!reservedDirs.has(parts[0])) return trimmed;
- const space = await resolveScopeSpace(scope);
- return `viking://${scope}/${space}/${parts.join("/")}`;
-}
-
-// ---------------------------------------------------------------------------
-// Search — adapted from auto-recall.mjs (verbose on error)
-// ---------------------------------------------------------------------------
-
-async function searchScope(queryText, targetUri, limit) {
- const resolvedUri = await resolveTargetUri(targetUri);
- dim(` target: ${targetUri} -> ${resolvedUri}`);
- const body = { query: queryText, target_uri: resolvedUri, limit, score_threshold: 0 };
- const result = await fetchJSON("/api/v1/search/find", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId: cfg.peerId });
- return result?.memories || [];
-}
-
-async function searchUserScope(queryText, limit) {
- console.log(`${C.dim}Searching user scope...${C.reset}`);
- const userMems = await searchScope(queryText, "viking://~/memories", limit);
-
- const uriSet = new Set();
- return {
- userMems,
- combined: userMems.filter(m => {
- if (uriSet.has(m.uri)) return false;
- uriSet.add(m.uri);
- return true;
- }),
- };
-}
-
-async function readMemoryContent(uri) {
- try {
- const result = await fetchJSON(
- `/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
- {},
- { actorPeerId: cfg.peerId },
- );
- if (result && typeof result === "string" && result.trim()) return result.trim();
- } catch (err) {
- warn(` Failed to read content for ${uri}: ${err?.message || err}`);
- }
- return null;
-}
-
-// ---------------------------------------------------------------------------
-// Print helpers
-// ---------------------------------------------------------------------------
-
-function printSearchResults(label, items) {
- console.log(`${C.bold}${label}${C.reset} (${items.length} result${items.length === 1 ? "" : "s"}):`);
- if (items.length === 0) {
- dim(" (none)");
- return;
- }
- for (const item of items) {
- const score = clampScore(item.score).toFixed(4);
- console.log(` ${C.bold}${item.uri}${C.reset}`);
- dim(` score=${score} level=${item.level} category=${item.category || "(none)"}`);
- dim(` abstract: ${(item.abstract || item.overview || "(none)").trim().slice(0, 120)}`);
- }
-}
-
-// ---------------------------------------------------------------------------
-// Main pipeline
-// ---------------------------------------------------------------------------
-
-async function main() {
- // ── Stage 1: Config ──
- header("Config Summary");
- console.log(` baseUrl: ${C.bold}${cfg.baseUrl}${C.reset}`);
- console.log(` recallLimit: ${cfg.recallLimit}`);
- console.log(` scoreThreshold: ${cfg.scoreThreshold}`);
- console.log(` timeoutMs: ${cfg.timeoutMs}`);
- console.log(` debug: ${cfg.debug}`);
- console.log(` configPath: ${C.dim}${cfg.configPath}${C.reset}`);
- console.log(`\n Query: ${C.bold}${query}${C.reset}`);
-
- // Query profile
- const profile = buildQueryProfile(query);
- dim(` tokens: [${profile.tokens.join(", ")}]`);
- dim(` wantsPreference: ${profile.wantsPreference}`);
- dim(` wantsTemporal: ${profile.wantsTemporal}`);
-
- // ── Stage 2: Health check ──
- header("Health Check");
- const health = await fetchJSON("/health");
- if (health) {
- ok(` OK`);
- dim(` ${JSON.stringify(health).slice(0, 300)}`);
- } else {
- fail(` FAILED — OpenViking is not reachable at ${cfg.baseUrl}`);
- fail(" The search stages below will likely fail as well.");
- }
-
- // ── Stage 3: Raw search results ──
- header("Raw Search Results");
- const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
- dim(` candidateLimit: ${candidateLimit}`);
-
- const { userMems, combined } = await searchUserScope(query, candidateLimit);
-
- console.log();
- printSearchResults("User scope (viking://~/memories)", userMems);
- console.log();
- dim(` Combined (deduplicated): ${combined.length} result${combined.length === 1 ? "" : "s"}`);
-
- if (combined.length === 0) {
- warn("\n No search results found. Pipeline ends here.");
- return;
- }
-
- // ── Stage 4: PostProcess ──
- header("PostProcess Results");
- const processed = postProcess(combined, candidateLimit, cfg.scoreThreshold);
- console.log(` Raw count: ${combined.length}`);
- console.log(` Filtered count: ${processed.length}`);
- const dropped = combined.length - processed.length;
- if (dropped > 0) {
- dim(` Dropped ${dropped} item${dropped === 1 ? "" : "s"} (non-leaf, below threshold, or duplicate)`);
- }
-
- if (processed.length === 0) {
- warn("\n All candidates were filtered out. Pipeline ends here.");
- return;
- }
-
- // ── Stage 5: Ranking details ──
- header("Ranking Details");
- const rankedItems = [...processed].sort((a, b) => rankForInjection(b, profile) - rankForInjection(a, profile));
-
- for (const item of rankedItems) {
- 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}`);
- const finalScore = base + leafBoost + eventBoost + prefBoost + overlapBoost;
-
- console.log(` ${C.bold}${item.uri}${C.reset}`);
- dim(` baseScore: ${base.toFixed(4)}`);
- dim(` leafBoost: ${leafBoost > 0 ? C.reset + C.green + "+" + leafBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);
- dim(` eventBoost: ${eventBoost > 0 ? C.reset + C.green + "+" + eventBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);
- dim(` prefBoost: ${prefBoost > 0 ? C.reset + C.green + "+" + prefBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);
- dim(` overlapBoost: ${overlapBoost > 0 ? C.reset + C.green + "+" + overlapBoost.toFixed(4) + C.reset + C.dim : "+0.0000"}`);
- console.log(` ${C.bold}finalScore: ${finalScore.toFixed(4)}${C.reset}`);
- }
-
- // ── Stage 6: Final picks ──
- header("Final Picks");
- const memories = pickMemories(processed, cfg.recallLimit, query);
-
- if (memories.length === 0) {
- warn(" No memories selected after pick stage.");
- return;
- }
-
- console.log(` Selected ${C.bold}${memories.length}${C.reset} of ${processed.length} candidates (limit: ${cfg.recallLimit})\n`);
-
- const lines = [];
- for (const item of memories) {
- console.log(` ${C.green}*${C.reset} ${C.bold}${item.uri}${C.reset}`);
- dim(` score=${clampScore(item.score).toFixed(4)} level=${item.level} category=${item.category || "(none)"}`);
-
- let lineText;
- if (item.level === 2) {
- const content = await readMemoryContent(item.uri);
- if (content) {
- ok(` content: ${content.slice(0, 200)}${content.length > 200 ? "..." : ""}`);
- lineText = `- [${item.category || "memory"}] ${content}`;
- } else {
- warn(" content: (could not read)");
- lineText = `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;
- }
- } else {
- lineText = `- [${item.category || "memory"}] ${(item.abstract || item.overview || item.uri).trim()}`;
- dim(` abstract: ${(item.abstract || item.overview || "(none)").trim().slice(0, 200)}`);
- }
- lines.push(lineText);
- }
-
- // ── Stage 7: Generated system message ──
- header("Generated System Message");
- const memoryContext =
- "<relevant-memories>\n" +
- "The following long-term memories from OpenViking may be relevant to this conversation:\n" +
- lines.join("\n") + "\n" +
- "</relevant-memories>";
-
- console.log(memoryContext);
- console.log();
- dim(` (${Buffer.byteLength(memoryContext, "utf-8")} bytes)`);
-}
-
-main().catch((err) => {
- fail(`\nUnexpected error: ${err?.message || err}`);
- if (err?.stack) dim(err.stack);
- process.exit(1);
-});
diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
index 894d7df05..479e33db1 100644
--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs
@@ -13,24 +13,36 @@
* The CC session_id is preserved verbatim so the OV id is human-readable and
* the parent/subagent lineage is visible at a glance.
*
- * Works with endpoints in openviking/server/routers/sessions.py:
- * - POST /api/v1/sessions/{id}/messages (auto_create=true by default)
- * - POST /api/v1/sessions/{id}/commit
- * - GET /api/v1/sessions/{id}?auto_create=true
- * - GET /api/v1/sessions/{id}/context?token_budget=N
+ * Everything past that derivation is the shared hook runtime under the names
+ * these scripts already call it by.
*/
+import {
+ addAgentMessage,
+ commitAgentSession,
+ enqueueAgentPending,
+ getAgentSession,
+ getAgentSessionContext,
+ makeAgentFetchJSON,
+} from "../shared/agent-hook-runtime.mjs";
+import { isRetryableFailure } from "../shared/retryable.mjs";
import {
deriveHarnessSessionId,
isBypassed,
} from "../shared/session-model.mjs";
-import { isRetryableFailure as isSharedRetryableFailure } from "../shared/retryable.mjs";
/**
* Check whether a CC session_id or cwd matches any bypass pattern.
* Also honours OPENVIKING_BYPASS_SESSION env var (via cfg.bypassSession).
*/
-export { isBypassed };
+export { isBypassed, isRetryableFailure };
+
+export {
+ addAgentMessage as addMessage,
+ enqueueAgentPending as enqueuePendingDirectly,
+ getAgentSession as getSession,
+ getAgentSessionContext as getSessionContext,
+};
/**
* Derive a stable OV session ID from a CC session_id.
@@ -43,134 +55,23 @@ export function deriveOvSessionId(ccSessionId, suffix = "") {
return deriveHarnessSessionId("cc-", ccSessionId, suffix);
}
-function responseTraceId(body) {
- return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
-}
-
/**
* Build a fetchJSON closure tied to a given config. Callers pass their own cfg
* (from scripts/config.mjs loadConfig()) so the timeout can vary per hook.
*/
export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {
- const defaultTimeoutMs = Math.max(1000, cfg[timeoutKey] || cfg.timeoutMs || 10000);
- return async function fetchJSON(path, init = {}, options = {}) {
- const timeoutMs = Math.max(1000, Number(options.timeoutMs) || defaultTimeoutMs);
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- try {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;
- if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;
- const actorPeerId = options.actorPeerId ?? "";
- if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
- const body = await res.json().catch(() => ({}));
- const traceId = responseTraceId(body);
- if (!res.ok || body.status === "error") {
- return {
- ok: false,
- status: res.status,
- error: body.error || { message: `HTTP ${res.status}` },
- traceId,
- };
- }
- return { ok: true, result: body.result ?? body, traceId };
- } catch (err) {
- return { ok: false, error: { message: err?.message || String(err) } };
- } finally {
- clearTimeout(timer);
- }
- };
-}
-
-export function isRetryableFailure(res) {
- return isSharedRetryableFailure(res);
-}
-
-function warnNonRetryable(operation, res) {
- const status = res?.status || "unknown";
- const msg = res?.error?.message || res?.error?.code || "";
- process.stderr.write(
- `[ov] ${operation} failed with non-retryable status ${status}; not enqueuing pending retry` +
- (msg ? ` (${msg})` : "") +
- "\n",
- );
-}
-
-export async function enqueuePendingDirectly(type, sessionId, payload = {}) {
- try {
- const { enqueue } = await import("./pending-queue.mjs");
- return await enqueue(type, sessionId, payload);
- } catch {
- return { ok: false };
- }
-}
-
-/**
- * Add a message to the persistent OV session. The server auto-creates the
- * session on first message via /sessions/{id}/messages (see add_message in
- * openviking/server/routers/sessions.py).
- *
- * `payload` accepts either { role, content } (simple string) or
- * { role, parts: [...] } (parts-mode, for tier-1 structured capture).
- */
-export async function addMessage(fetchJSON, sessionId, payload) {
- const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
- method: "POST",
- body: JSON.stringify(payload),
- });
- if (!res.ok) {
- if (isRetryableFailure(res)) {
- const queued = await enqueuePendingDirectly("addMessage", sessionId, payload);
- if (queued.ok) res.pendingQueued = true;
- else res.pendingEnqueueFailed = true;
- } else {
- warnNonRetryable("addMessage", res);
- }
- }
- return res;
+ return makeAgentFetchJSON(cfg, process.cwd(), {
+ defaultTimeoutMs: cfg[timeoutKey] || cfg.timeoutMs || 10000,
+ // Every call on this stack names the peer it wants, so nothing here may put
+ // one on a request that asked for none.
+ getActorPeerId: () => "",
+ }).fetchJSON;
}
/**
* Commit the persistent OV session (archive + background extract). Safe to
* call repeatedly: if there are no pending messages the server is a no-op.
*/
-export async function commitSession(fetchJSON, sessionId, payload = {}) {
- const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
- method: "POST",
- body: JSON.stringify(payload || {}),
- });
- if (!res.ok) {
- if (isRetryableFailure(res)) {
- const queued = await enqueuePendingDirectly("commitSession", sessionId, payload || {});
- if (queued.ok) res.pendingQueued = true;
- else res.pendingEnqueueFailed = true;
- } else {
- warnNonRetryable("commitSession", res);
- }
- }
- return res;
-}
-
-/**
- * Get assembled session context (includes latest_archive_overview).
- * Returns null when the session does not exist or the request fails.
- */
-export async function getSessionContext(fetchJSON, sessionId, tokenBudget = 128000) {
- const res = await fetchJSON(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,
- );
- return res.ok ? res.result : null;
-}
-
-/**
- * Fetch session meta. Returns null if the session does not exist (unless
- * autoCreate=true).
- */
-export async function getSession(fetchJSON, sessionId, { autoCreate = false } = {}) {
- const q = autoCreate ? "?auto_create=true" : "";
- const res = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}${q}`);
- return res.ok ? res.result : null;
+export function commitSession(fetchJSON, sessionId, payload = {}) {
+ return commitAgentSession(fetchJSON, sessionId, undefined, payload);
}
diff --git a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs
index 3c93fd5bf..a208c8bed 100644
--- a/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/lib/pending-queue.test.mjs
@@ -1,44 +1,9 @@
import assert from "node:assert/strict";
-import { mkdtemp, readdir, rm } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
import test from "node:test";
import { addMessage, commitSession, makeFetchJSON } from "./ov-session.mjs";
-import {
- claimForReplay,
- enqueue,
- listPending,
- replayPending,
-} from "./pending-queue.mjs";
-
-const originalEnv = {
- dir: process.env.OPENVIKING_PENDING_DIR,
- maxRetries: process.env.OPENVIKING_PENDING_MAX_RETRIES,
- replayLimit: process.env.OPENVIKING_PENDING_REPLAY_LIMIT,
- ttlDays: process.env.OPENVIKING_PENDING_TTL_DAYS,
-};
-
-async function withPendingDir(fn) {
- const dir = await mkdtemp(join(tmpdir(), "openviking-pending-test-"));
- process.env.OPENVIKING_PENDING_DIR = dir;
- delete process.env.OPENVIKING_PENDING_MAX_RETRIES;
- delete process.env.OPENVIKING_PENDING_REPLAY_LIMIT;
- delete process.env.OPENVIKING_PENDING_TTL_DAYS;
- try {
- return await fn(dir);
- } finally {
- if (originalEnv.dir === undefined) delete process.env.OPENVIKING_PENDING_DIR;
- else process.env.OPENVIKING_PENDING_DIR = originalEnv.dir;
- if (originalEnv.maxRetries === undefined) delete process.env.OPENVIKING_PENDING_MAX_RETRIES;
- else process.env.OPENVIKING_PENDING_MAX_RETRIES = originalEnv.maxRetries;
- if (originalEnv.replayLimit === undefined) delete process.env.OPENVIKING_PENDING_REPLAY_LIMIT;
- else process.env.OPENVIKING_PENDING_REPLAY_LIMIT = originalEnv.replayLimit;
- if (originalEnv.ttlDays === undefined) delete process.env.OPENVIKING_PENDING_TTL_DAYS;
- else process.env.OPENVIKING_PENDING_TTL_DAYS = originalEnv.ttlDays;
- await rm(dir, { recursive: true, force: true });
- }
-}
+import { listPending, replayPending } from "./pending-queue.mjs";
+import { withPendingDir } from "../../../memory-plugin-shared/testing/support.mjs";
test("addMessage queues retryable failures", async () => {
await withPendingDir(async () => {
@@ -193,68 +158,3 @@ test("makeFetchJSON preserves commit trace_id on success and failure", async (t)
assert.equal(failure.traceId, "trace-error");
assert.equal(failure.error.trace_id, "trace-error");
});
-
-test("replayPending sends queued entries and removes them after success", async () => {
- await withPendingDir(async () => {
- const payload = { role: "assistant", content: "queued response" };
- await enqueue("addMessage", "cc-replay", payload);
-
- const calls = [];
- const result = await replayPending(async (path, init) => {
- calls.push({ path, init });
- return { ok: true };
- }, () => {});
-
- assert.deepEqual(result, { replayed: 1, failed: 0, skipped: 0, deferred: 0 });
- assert.equal(calls.length, 1);
- assert.equal(calls[0].path, "/api/v1/sessions/cc-replay/messages");
- assert.deepEqual(JSON.parse(calls[0].init.body), payload);
- assert.deepEqual(await listPending(), []);
- });
-});
-
-test("enqueue deduplicates identical payloads", async () => {
- await withPendingDir(async () => {
- const payload = { role: "user", parts: [{ type: "text", text: "same" }] };
- const first = await enqueue("addMessage", "cc-dedup", payload);
- const second = await enqueue("addMessage", "cc-dedup", payload);
-
- assert.equal(first.ok, true);
- assert.equal(second.ok, true);
- assert.equal(second.deduped, true);
- assert.equal((await listPending()).length, 1);
- });
-});
-
-test("replayPending honors the per-run replay limit", async () => {
- await withPendingDir(async () => {
- process.env.OPENVIKING_PENDING_REPLAY_LIMIT = "1";
- await enqueue("addMessage", "cc-limit", { role: "user", content: "one" });
- await enqueue("addMessage", "cc-limit", { role: "user", content: "two" });
-
- const calls = [];
- const result = await replayPending(async (path, init) => {
- calls.push({ path, init });
- return { ok: true };
- }, () => {});
-
- assert.equal(result.replayed, 1);
- assert.equal(result.deferred, 1);
- assert.equal(calls.length, 1);
- assert.equal((await listPending()).length, 1);
- });
-});
-
-test("claimForReplay atomically claims a file only once", async () => {
- await withPendingDir(async (dir) => {
- await enqueue("commitSession", "cc-claim", {});
- const [{ filename }] = await listPending();
-
- const firstClaim = await claimForReplay(filename);
- const secondClaim = await claimForReplay(filename);
-
- assert.match(firstClaim, /\.processing$/);
- assert.equal(secondClaim, null);
- assert.deepEqual(await readdir(dir), [firstClaim]);
- });
-});
diff --git a/examples/claude-code-memory-plugin/scripts/lib/recall-core-timeout.test.mjs b/examples/claude-code-memory-plugin/scripts/lib/recall-core-timeout.test.mjs
deleted file mode 100644
index 84a6c77b8..000000000
--- a/examples/claude-code-memory-plugin/scripts/lib/recall-core-timeout.test.mjs
+++ /dev/null
@@ -1,14 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { contextRequestTimeoutMs } from "../shared/recall-core.mjs";
-
-test("explicit recall context timeout applies without rewrite or expansion", () => {
- const timeout = contextRequestTimeoutMs(
- { recallContextTimeoutMs: 25000, timeoutMs: 15000 },
- { session_id: "s1", query_expansion: "off" },
- );
-
- assert.equal(timeout, 25000);
-});
-
diff --git a/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs
index dd9d14d1c..d4a6c2878 100644
--- a/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs
+++ b/examples/claude-code-memory-plugin/scripts/lib/server-probe.mjs
@@ -14,6 +14,7 @@
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
+import { buildOvHeaders } from "../shared/ov-http.mjs";
import { STATE_DIR } from "./state.mjs";
const CACHE_FILE = join(STATE_DIR, "server-probe.json");
@@ -62,11 +63,9 @@ export async function probeServer(cfg, { ttlMs = DEFAULT_TTL_MS } = {}) {
if (cached.base_url === cfg.baseUrl) return cached;
}
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;
- if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ // No actor peer: /health is not scoped to one, and the statusline probe is
+ // shared across every session on this machine.
+ const headers = buildOvHeaders(cfg);
const t0 = Date.now();
let healthy = false;
diff --git a/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
index dbed4fedc..90e220989 100644
--- a/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
+++ b/examples/claude-code-memory-plugin/scripts/ov-memory-doctor.mjs
@@ -17,7 +17,7 @@
* Exit code 1 when any check fails, 0 otherwise. Never prints a full api key.
*/
-import { readFileSync } from "node:fs";
+import { realpathSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
@@ -25,36 +25,30 @@ import { fileURLToPath } from "node:url";
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { STATE_DIR } from "./lib/state.mjs";
import {
- assessProbes,
- checkServerHealth,
- collectEnv,
countDirEntries,
- createReport,
- describeApiKey,
existsPath,
+ expandHome,
fileInfo,
fmtAge,
fmtBytes,
+ credentialSources,
homeShort,
+ inspectConfigFiles,
inspectJsonFile,
- isLoopbackUrl,
- lintBaseUrl,
- parseNodeMajor,
- probeOpenViking,
readStateFiles,
+ reportCredentials,
+ reportPeer,
+ reportTimeouts,
+ reportToggles,
runCommand,
+ runDoctor,
scanDebugLog,
scanRcFiles,
- unknownOvcliKeys,
- unknownPluginKeys,
- whichCommand,
- checkWorkspace,
- lintPeerScopeDowngrade,
- WORKSPACE_PEER_HINT,
+ sweepEnv,
+ tryJson,
} from "./shared/doctor-core.mjs";
import { describeInputFilters } from "./shared/input-filters.mjs";
import { isBypassed } from "./shared/session-model.mjs";
-import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
const PLUGIN_ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), "..");
const PLUGIN_ID = "openviking-memory@openviking";
@@ -62,39 +56,9 @@ const PLUGIN_NAME = "openviking-memory";
const MARKETPLACE = "openviking";
const LEGACY_MARKETPLACE = "openviking-plugins-local";
const CLAUDE_DIR = join(homedir(), ".claude");
-const RC_MARKERS = ["# >>> openviking claude-code memory plugin >>>", "# >>> openviking-codex-plugin >>>"];
const STATE_FILES = ["last-recall.json", "last-capture.json", "last-session-event.json", "daily-stats.json", "server-probe.json", "host-cli-probe.json", "context-face.json"];
const REQUIRED_PLUGIN_FILES = [".claude-plugin/plugin.json", "hooks/hooks.json", ".mcp.json", "servers/mcp-proxy.mjs", "scripts/config.mjs", "scripts/auto-recall.mjs", "scripts/auto-capture.mjs"];
-function parseArgs(argv) {
- const opts = { json: false, offline: false, timeoutMs: 5000, color: process.stdout.isTTY && !process.env.NO_COLOR };
- for (let i = 0; i < argv.length; i += 1) {
- const arg = argv[i];
- if (arg === "--json") opts.json = true;
- else if (arg === "--offline" || arg === "--no-network") opts.offline = true;
- else if (arg === "--no-color") opts.color = false;
- else if (arg === "--timeout") opts.timeoutMs = Math.max(1000, Number(argv[++i]) || 5000);
- else if (arg === "-h" || arg === "--help") {
- console.log("usage: ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]");
- process.exit(0);
- }
- }
- if (opts.json) opts.color = false;
- return opts;
-}
-
-function expandHome(p) {
- return p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p;
-}
-
-function tryJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return null;
- }
-}
-
function envBoolValue(name) {
const v = process.env[name];
if (v == null || v === "") return undefined;
@@ -108,33 +72,7 @@ function envBoolValue(name) {
// Sections
// ---------------------------------------------------------------------------
-function checkEnvironment(report) {
- report.section("Environment");
- const nodeMajor = parseNodeMajor(process.version);
- const nodePath = process.execPath;
- if (nodeMajor >= 18) report.ok(`node ${process.version} (${nodePath})`);
- else report.fail(`node ${process.version} is too old`, "hooks and the MCP proxy need Node.js 18+ (global fetch)", "install Node.js 18 or newer and make sure it is first on PATH");
- const nodeOnPath = whichCommand("node");
- if (!nodeOnPath) {
- report.warn("`node` is not on PATH for this process", "hooks and .mcp.json invoke the bare command `node`; if Claude Code was launched without your shell profile (nvm/volta/fnm), hooks never start",
- "put node on PATH for the environment that launches Claude Code, or set PATH in the `env` block of ~/.claude/settings.json");
- } else if (resolvePath(nodeOnPath) !== resolvePath(nodePath)) {
- report.info(`PATH resolves node to ${nodeOnPath} (this run used ${nodePath})`);
- }
-
- const claude = runCommand("claude", ["--version"], { timeoutMs: 15000 });
- if (claude.ok) {
- report.ok(`claude ${claude.stdout.split("\n")[0]}`);
- const plugin = runCommand("claude", ["plugin", "--help"], { timeoutMs: 15000 });
- if (!plugin.ok) report.warn("`claude plugin` subcommand unavailable", "this Claude Code build predates the plugin system; only the legacy settings.json hook install works", "upgrade Claude Code to 2.0+");
- } else {
- report.info(`claude CLI not found on PATH (${claude.error || "?"}) — install checks that need it are skipped`);
- }
- report.info(`platform ${process.platform} ${process.arch}, cwd ${homeShort(process.cwd())}`);
- return { claudeOnPath: claude.ok };
-}
-
-function checkInstall(report, { claudeOnPath }) {
+function checkInstall(report, { cliOnPath }) {
report.section("Plugin install");
const manifest = tryJson(join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"));
const version = manifest?.version || "?";
@@ -264,12 +202,7 @@ function checkInstall(report, { claudeOnPath }) {
report.warn("a user-scope MCP server named 'openviking' is registered besides the plugin's", JSON.stringify(userMcp).slice(0, 160),
"claude mcp remove openviking -s user (the plugin ships its own MCP server)");
}
- const rc = scanRcFiles(RC_MARKERS);
- const blocks = rc.filter((h) => h.kind === "block");
- if (blocks.length) {
- report.warn("shell rc files still carry a legacy openviking wrapper block", blocks.map((h) => `${h.file}: ${h.detail}`).join("\n"),
- "delete the block between the >>> and <<< markers; it exports stale OPENVIKING_* values that override ovcli.conf");
- }
+ const rc = scanRcFiles([]);
const CONNECTION_VARS = /^OPENVIKING_(URL|BASE_URL|API_KEY|BEARER_TOKEN|ACCOUNT|USER|MEMORY_ENABLED|CONFIG_FILE|CLI_CONFIG_FILE|HOME)$/;
for (const h of rc.filter((h) => h.kind === "export")) {
const conn = h.vars.filter((v) => CONNECTION_VARS.test(v));
@@ -277,7 +210,7 @@ function checkInstall(report, { claudeOnPath }) {
else report.info(`${h.file} exports ${h.detail}`);
}
- if (claudeOnPath) {
+ if (cliOnPath) {
const list = runCommand("claude", ["plugin", "list", "--json"], { timeoutMs: 30000 });
if (list.ok) {
let rows = [];
@@ -298,51 +231,9 @@ function checkInstall(report, { claudeOnPath }) {
report.info("MCP wiring: `claude mcp list` shows the plugin server as plugin:openviking-memory:openviking (slow; run it when MCP tools are missing)");
}
-function credentialSources(cliConf, ovConf) {
- const env = process.env;
- const cliShort = homeShort(cliConf.path);
- const ovShort = homeShort(ovConf.path);
- const cli = cliConf.ok ? cliConf.data : {};
- const ov = ovConf.ok ? ovConf.data : {};
- const cc = ov.claude_code || {};
- const server = ov.server || {};
- const url = (env.OPENVIKING_URL || env.OPENVIKING_BASE_URL) ? "env" : cli.url ? cliShort : server.url ? ovShort : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
- const apiKey = env.OPENVIKING_BEARER_TOKEN ? "env OPENVIKING_BEARER_TOKEN" : env.OPENVIKING_API_KEY ? "env OPENVIKING_API_KEY" : cli.api_key ? cliShort : cc.apiKey ? `${ovShort} claude_code.apiKey` : server.root_api_key ? `${ovShort} server.root_api_key` : "(none)";
- const account = env.OPENVIKING_ACCOUNT ? "env" : cli.account ? cliShort : cc.accountId ? `${ovShort} claude_code.accountId` : "(unset)";
- const user = env.OPENVIKING_USER ? "env" : cli.user ? cliShort : cc.userId ? `${ovShort} claude_code.userId` : "(unset)";
- return { url, apiKey, account, user };
-}
-
-function checkConfig(report, cfg) {
+function checkConfig(report, cfg, host) {
report.section("Configuration");
- const cliPath = expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf"));
- const ovPath = expandHome(process.env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf"));
- const cliConf = inspectJsonFile(cliPath);
- const ovConf = inspectJsonFile(ovPath);
-
- for (const [label, conf] of [["ovcli.conf", cliConf], ["ov.conf", ovConf]]) {
- if (!conf.exists) {
- report.info(`${label}: ${homeShort(conf.path)} not present`);
- } else if (!conf.ok) {
- report.fail(`${label} cannot be parsed — the plugin treats it as absent`, `${homeShort(conf.path)}: ${conf.error}`, "fix the JSON (a trailing comma or comment is enough to break it)");
- } else {
- report.ok(`${label}: ${homeShort(conf.path)} (mode ${conf.mode}, ${fmtBytes(conf.size)})`);
- if (label === "ovcli.conf") {
- if (conf.mode !== "600" && conf.mode !== "400") report.warn("ovcli.conf is not private", `mode ${conf.mode}; it holds the api key`, `chmod 600 ${homeShort(conf.path)}`);
- const unknown = unknownOvcliKeys(conf.data);
- if (unknown.length) report.warn("ovcli.conf has keys nobody reads", unknown.join(", "), "typos such as apiKey/base_url/token are silently ignored — use url, api_key, account, user");
- // `plugin` is on the allowlist above, so until now nothing inside it
- // was ever checked and a misspelled knob just sat there doing nothing.
- for (const { key, suggestion } of unknownPluginKeys(conf.data.plugin)) {
- report.warn(`ovcli.conf ${key} is not a knob any plugin reads`, "", suggestion ? `did you mean ${suggestion}?` : "remove it, or check the plugin README for the knob you meant");
- }
- if (conf.data.extra_headers && Object.keys(conf.data.extra_headers).some((h) => /^x-api-key$/i.test(h))) {
- report.warn("ovcli.conf extra_headers sets X-API-Key", "the server prefers X-API-Key over Authorization: Bearer, so it shadows api_key");
- }
- }
- if (label === "ov.conf" && conf.data.claude_code) report.info("ov.conf has a legacy claude_code block (still honoured; prefer ovcli.conf plugin.claude_code or env vars)");
- }
- }
+ const { cliConf, ovConf } = inspectConfigFiles(report, host);
// Enable verdict
const enabled = isPluginEnabled();
@@ -357,54 +248,12 @@ function checkConfig(report, cfg) {
else report.fail(`plugin disabled — every hook exits immediately (${reason})`, "", envEnabled === false ? "unset OPENVIKING_MEMORY_ENABLED" : "create ~/.openviking/ovcli.conf with url + api_key, or set OPENVIKING_MEMORY_ENABLED=1 plus OPENVIKING_URL/OPENVIKING_API_KEY");
// Resolved values + sources
- const src = credentialSources(cliConf, ovConf);
- report.info(`url ${cfg.baseUrl} ← ${src.url}`);
- for (const p of lintBaseUrl(cfg.baseUrl)) report[p.level](p.message, "", p.fix);
- if (src.url.startsWith("default") && !isLoopbackUrl(cfg.baseUrl)) report.info("url fell back to the built-in default");
- else if (src.url.startsWith("default")) report.warn("no url configured — using the built-in default http://127.0.0.1:1933", "only right when the server runs on this machine", "set url in ovcli.conf or OPENVIKING_URL");
-
- const keyInfo = describeApiKey(cfg.apiKey);
- report.info(`api_key ${keyInfo.display} ← ${src.apiKey}`);
- for (const p of keyInfo.problems) report.warn(`api key ${p}`, "", "re-copy the key exactly as issued");
- if (src.apiKey.includes("root_api_key")) {
- report.warn("api key falls back to ov.conf server.root_api_key", "the root key is refused on tenant data APIs and /mcp in api_key mode; against a remote server it is simply the wrong key",
- "put a user/admin key in ovcli.conf api_key (or OPENVIKING_API_KEY)");
- }
- if (!keyInfo.present && !isLoopbackUrl(cfg.baseUrl)) report.warn("no api key configured for a non-local server", "", "set api_key in ovcli.conf or OPENVIKING_API_KEY");
- report.info(`account ${cfg.accountId || "(unset)"} ← ${src.account}`);
- report.info(`user ${cfg.userId || "(unset)"} ← ${src.user}`);
- if (keyInfo.format === "v2") {
- if (cfg.accountId && keyInfo.account && cfg.accountId !== keyInfo.account) report.warn(`configured account '${cfg.accountId}' differs from the key's account '${keyInfo.account}'`, "in api_key mode the key wins");
- if (cfg.userId && keyInfo.user && cfg.userId !== keyInfo.user) report.warn(`configured user '${cfg.userId}' differs from the key's user '${keyInfo.user}'`, "in api_key mode the key wins");
- }
- const peer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });
- report.info(`peer ${peer.peerId || "(none)"} ← ${peer.source} (${peer.origin})`);
- if (peer.origin === "unresolved") {
- report.info(
- "no peer is sent: this directory is in no git repository, so its memories go to your user-level space",
- `to give it a memory of its own, create .openviking/config.json here with ${WORKSPACE_PEER_HINT}`,
- );
- } else if (peer.source === "none") {
- report.warn(
- "no peer is sent, so recall defaults to every memory under this user",
- "sending a peer narrows the search to this workspace",
- 'unset OPENVIKING_WORKSPACE_PEER, or set peer.source to "git"',
- );
- }
- if (peer.legacyPeerId) {
- report.info(
- `previous peer ${peer.legacyPeerId}`,
- cfg.recallPeerScope === "actor"
- ? "recall asks it separately, because peer_scope actor turns off the server's cross-peer sweep"
- : "already covered by the server's cross-peer sweep under peer_scope all",
- );
- }
- for (const p of lintPeerScopeDowngrade()) report[p.level](p.message, p.detail, p.fix);
- report.info(`timeouts ${cfg.timeoutMs}ms request, ${cfg.captureTimeoutMs}ms capture; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);
+ const keyInfo = reportCredentials(report, cfg, credentialSources(cfg, cliConf, ovConf), { account: cfg.accountId, user: cfg.userId });
+ const peer = reportPeer(report, cfg);
+ reportTimeouts(report, cfg, host);
const toggles = [`auto-inject ${cfg.noAutoInject ? "OFF" : "on"}`, `auto-recall ${cfg.autoRecall ? "on" : "OFF"}`, `auto-capture ${cfg.autoCapture ? "on" : "OFF"}`, `recall compress ${cfg.recallRewrite}`, `write path ${cfg.writePathAsync ? "async" : "sync"}`];
- report.info(`toggles ${toggles.join(", ")}`);
- if (!cfg.autoRecall || !cfg.autoCapture || cfg.noAutoInject) report.warn("one or more injection paths are switched off", toggles.join(", "), "check OPENVIKING_AUTO_RECALL / OPENVIKING_AUTO_CAPTURE / OPENVIKING_NO_AUTO_INJECT and ovcli.conf plugin.claude_code");
+ reportToggles(report, cfg, host, toggles);
if (cfg.bypassSession) report.warn("OPENVIKING_BYPASS_SESSION is on — every hook skips the server", "", "unset it");
if (cfg.bypassSessionPatterns?.length) {
const hit = isBypassed(cfg, { cwd: process.cwd() });
@@ -426,39 +275,16 @@ function checkConfig(report, cfg) {
}
report.info(`debug log ${cfg.debug ? "on" : "off"} → ${homeShort(cfg.debugLogPath)}${cfg.debug ? "" : " (set OPENVIKING_DEBUG=1 in Claude Code's environment to record hook errors)"}`);
- // Environment sweep
- const env = collectEnv();
- if (env.openviking.length) {
- report.info("OPENVIKING_* in this environment", env.openviking.map((e) => `${e.name}=${e.value}`).join("\n"));
- if (env.openviking.some((e) => e.name === "OPENVIKING_MCP_URL")) report.warn("OPENVIKING_MCP_URL has no effect on this plugin", "the proxy always targets <url>/mcp", "unset it and fix url instead");
+ sweepEnv(report, cfg, host, (r, env) => {
+ if (env.openviking.some((e) => e.name === "OPENVIKING_MCP_URL")) r.warn("OPENVIKING_MCP_URL has no effect on this plugin", "the proxy always targets <url>/mcp", "unset it and fix url instead");
if (env.openviking.some((e) => ["OPENVIKING_URL", "OPENVIKING_BASE_URL", "OPENVIKING_API_KEY", "OPENVIKING_BEARER_TOKEN"].includes(e.name)) && cliConf.ok && (cliConf.data.url || cliConf.data.api_key)) {
- report.info("env vars override the url/api_key in ovcli.conf — edits to the file do not take effect while they are set");
+ r.info("env vars override the url/api_key in ovcli.conf — edits to the file do not take effect while they are set");
}
- } else {
- report.info("no OPENVIKING_* environment variables set");
- }
- if (env.proxy.length) {
- report.warn(`proxy variables set: ${env.proxy.map((e) => e.name).join(", ")}`, "Node's fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY=1 (Node 24+); curl honours them, so curl may succeed while hooks fail",
- isLoopbackUrl(cfg.baseUrl) ? "harmless for a local server" : "set NODE_USE_ENV_PROXY=1 (or reach the server without the proxy) in the environment that launches Claude Code");
- }
- if (env.node.length) report.info(`node TLS/proxy env: ${env.node.map((e) => `${e.name}=${e.value}`).join(", ")}`);
- if (/^https:/i.test(cfg.baseUrl) && env.node.some((e) => e.name === "NODE_TLS_REJECT_UNAUTHORIZED" && e.value === "0")) report.warn("NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate checks", "", "prefer NODE_EXTRA_CA_CERTS=<ca.pem>");
+ });
return { keyInfo, cliConf, ovConf, peer };
}
-async function checkConnection(report, cfg, { keyInfo, peer }, opts) {
- report.section("Connection");
- if (opts.offline) {
- report.info("skipped (--offline)");
- return null;
- }
- const conn = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, account: cfg.accountId, user: cfg.userId, peerId: peer.peerId, userAgent: cfg.userAgent };
- const probes = await probeOpenViking(conn, { timeoutMs: opts.timeoutMs });
- const summary = assessProbes(report, probes, conn, keyInfo);
- return { probes, summary };
-}
-
function checkActivity(report, cfg, connection) {
report.section("Recent activity");
const inject = fileInfo(join(homedir(), ".openviking", "last_inject.md"));
@@ -518,44 +344,38 @@ function checkActivity(report, cfg, connection) {
// ---------------------------------------------------------------------------
-async function main() {
- const opts = parseArgs(process.argv.slice(2));
- const report = createReport({ color: opts.color });
- const envInfo = checkEnvironment(report);
- checkInstall(report, envInfo);
- const cfg = loadConfig();
- const configInfo = checkConfig(report, cfg);
- const workspace = checkWorkspace(report);
- const connection = await checkConnection(report, cfg, configInfo, opts);
- const serverHealth = await checkServerHealth(report, { baseUrl: cfg.baseUrl, ovConf: configInfo.ovConf, health: connection?.probes?.health, offline: opts.offline, timeoutMs: opts.timeoutMs });
- checkActivity(report, cfg, connection);
-
- if (opts.json) {
- const out = {
- harness: "claude-code",
- pluginRoot: PLUGIN_ROOT,
- generatedAt: new Date().toISOString(),
- resolved: {
- baseUrl: cfg.baseUrl,
- apiKey: configInfo.keyInfo.display,
- apiKeyFormat: configInfo.keyInfo.format,
- account: cfg.accountId,
- user: cfg.userId,
- peerId: configInfo.peer.peerId,
- },
- workspace,
- server: connection?.summary || null,
- serverHealth,
- ...report.toJSON(),
- };
- console.log(JSON.stringify(out, null, 2));
- } else {
- console.log(report.render());
+const HOST = {
+ harness: "claude-code",
+ pluginRoot: PLUGIN_ROOT,
+ cliName: "claude",
+ launcherHint: "Claude Code",
+ nodePathFix: "put node on PATH for the environment that launches Claude Code, or set PATH in the `env` block of ~/.claude/settings.json",
+ // Recall runs on the plain request timeout here; only Codex gives it its own.
+ timeoutBudgets: { UserPromptSubmit: "timeoutMs", Stop: "captureTimeoutMs" },
+ onCliFound(report, cli) {
+ report.ok(`claude ${cli.stdout.split("\n")[0]}`);
+ const plugin = runCommand("claude", ["plugin", "--help"], { timeoutMs: 15000 });
+ if (!plugin.ok) report.warn("`claude plugin` subcommand unavailable", "this Claude Code build predates the plugin system; only the legacy settings.json hook install works", "upgrade Claude Code to 2.0+");
+ },
+ loadConfig,
+ checkInstall,
+ checkConfig,
+ checkActivity,
+ resolveIdentity: (cfg) => ({ account: cfg.accountId, user: cfg.userId }),
+};
+
+function isDirectRun() {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
+ } catch {
+ return resolvePath(process.argv[1]) === fileURLToPath(import.meta.url);
}
- process.exitCode = report.exitCode();
}
-main().catch((err) => {
- console.error("ov-memory-doctor failed:", err?.stack || err?.message || err);
- process.exit(2);
-});
+if (isDirectRun()) {
+ runDoctor(HOST).catch((err) => {
+ console.error("ov-memory-doctor failed:", err?.stack || err?.message || err);
+ process.exit(2);
+ });
+}
diff --git a/examples/claude-code-memory-plugin/scripts/ov-status.mjs b/examples/claude-code-memory-plugin/scripts/ov-status.mjs
index 4ba09a231..74ec5564d 100644
--- a/examples/claude-code-memory-plugin/scripts/ov-status.mjs
+++ b/examples/claude-code-memory-plugin/scripts/ov-status.mjs
@@ -135,7 +135,7 @@ async function main() {
: "default";
// Taken from loadConfig() so this line and the MCP proxy always name the
// same file.
- const keySrc = cfg.credentialSource === "env" ? "env"
+ const keySrc = cfg.apiKeySource === "env" ? "env"
: cfg.credentialPath ? homeShort(cfg.credentialPath)
: "(none)";
console.log(`Auth: url from ${urlSrc}, api_key from ${keySrc}`);
diff --git a/examples/claude-code-memory-plugin/scripts/pre-compact.mjs b/examples/claude-code-memory-plugin/scripts/pre-compact.mjs
index 2a93dda71..4d4955271 100644
--- a/examples/claude-code-memory-plugin/scripts/pre-compact.mjs
+++ b/examples/claude-code-memory-plugin/scripts/pre-compact.mjs
@@ -12,52 +12,32 @@
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
-import { commitSession, deriveOvSessionId, isBypassed, makeFetchJSON } from "./lib/ov-session.mjs";
+import { commitSession, deriveOvSessionId, makeFetchJSON } from "./lib/ov-session.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
if (!isPluginEnabled()) {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
process.exit(0);
}
-let cfg = loadConfig();
const { log, logError } = createLogger("pre-compact");
-const fetchJSON = makeFetchJSON(cfg);
+const fetchJSON = makeFetchJSON(loadConfig());
function approve() {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
}
-async function main() {
- let input = {};
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString() || "{}");
- } catch { /* best effort */ }
-
- const sessionId = input.session_id;
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
-
+runHookStage({
+ loadConfig,
+ input: { tolerant: true },
// Write-path hook: gated by autoCapture so that disabling capture also
// disables the pending-message commits triggered here.
- if (!cfg.autoCapture) {
- log("skip", { reason: "autoCapture disabled" });
- approve();
- return;
- }
-
+ gates: { enabled: (cfg) => cfg.autoCapture },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+}, async ({ sessionId }) => {
if (!sessionId) {
log("skip", { reason: "no session_id" });
- approve();
- return;
- }
-
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
return;
}
@@ -65,7 +45,6 @@ async function main() {
const health = await fetchJSON("/health");
if (!health.ok) {
logError("health_check", "server unreachable");
- approve();
return;
}
@@ -76,7 +55,4 @@ async function main() {
trace_id: res.traceId || res.result?.trace_id,
error: res.ok ? undefined : res.error?.message,
});
- approve();
-}
-
-main().catch((err) => { logError("uncaught", err); approve(); });
+}).catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/session-end.mjs b/examples/claude-code-memory-plugin/scripts/session-end.mjs
index 11bd5103d..0e8de5775 100644
--- a/examples/claude-code-memory-plugin/scripts/session-end.mjs
+++ b/examples/claude-code-memory-plugin/scripts/session-end.mjs
@@ -15,20 +15,20 @@ import {
commitSession,
deriveOvSessionId,
enqueuePendingDirectly,
- isBypassed,
isRetryableFailure,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
if (!isPluginEnabled()) {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
process.exit(0);
}
-let cfg = loadConfig();
+const baseCfg = loadConfig();
const { log, logError } = createLogger("session-end");
-const fetchJSON = makeFetchJSON(cfg);
+const fetchJSON = makeFetchJSON(baseCfg);
function approve() {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
@@ -36,68 +36,50 @@ function approve() {
async function main() {
// Write-path hook: gated by autoCapture so that disabling capture also
- // disables the final-commit triggered here.
- if (!cfg.autoCapture) {
- log("skip", { reason: "autoCapture disabled" });
+ // disables the final-commit triggered here. This runs against the hook's own
+ // directory, before the payload names the session's.
+ if (!baseCfg.autoCapture) {
+ log("skip", { reason: "disabled" });
approve();
return;
}
- if (await maybeDetach(cfg, { approve })) return;
+ if (await maybeDetach(baseCfg, { approve })) return;
- let input = {};
- try {
- input = JSON.parse((await readHookStdin()) || "{}");
- } catch { /* best effort */ }
+ await runHookStage({
+ loadConfig,
+ input: { read: readHookStdin, tolerant: true },
+ gates: { enabled: (cfg) => cfg.autoCapture },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+ }, async ({ sessionId }) => {
+ if (!sessionId) {
+ log("skip", { reason: "no session_id" });
+ return;
+ }
- const sessionId = input.session_id;
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
- if (!cfg.autoCapture) {
- // The gate above ran against this process's directory, not the session's.
- log("skip", { reason: "autoCapture disabled" });
- approve();
- return;
- }
-
- if (!sessionId) {
- log("skip", { reason: "no session_id" });
- approve();
- return;
- }
-
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
- return;
- }
-
- const ovSessionId = deriveOvSessionId(sessionId);
- const health = await fetchJSON("/health");
- if (!health.ok && isRetryableFailure(health)) {
- const queued = await enqueuePendingDirectly("commitSession", ovSessionId, {});
- log("commit", { ovSessionId, ok: false, queued: queued.ok, reason: "health_retryable" });
- approve();
- return;
- }
- if (!health.ok) {
- logError("health_check", `non-retryable status ${health.status || "unknown"}`);
- approve();
- return;
- }
+ const ovSessionId = deriveOvSessionId(sessionId);
+ const health = await fetchJSON("/health");
+ if (!health.ok && isRetryableFailure(health)) {
+ const queued = await enqueuePendingDirectly("commitSession", ovSessionId, {});
+ log("commit", { ovSessionId, ok: false, queued: queued.ok, reason: "health_retryable" });
+ return;
+ }
+ if (!health.ok) {
+ logError("health_check", `non-retryable status ${health.status || "unknown"}`);
+ return;
+ }
- const res = await commitSession(fetchJSON, ovSessionId);
- log("commit", {
- ovSessionId,
- ok: res.ok,
- trace_id: res.traceId || res.result?.trace_id,
- queued: Boolean(res.pendingQueued),
- enqueueFailed: Boolean(res.pendingEnqueueFailed),
- error: res.ok ? undefined : res.error?.message,
+ const res = await commitSession(fetchJSON, ovSessionId);
+ log("commit", {
+ ovSessionId,
+ ok: res.ok,
+ trace_id: res.traceId || res.result?.trace_id,
+ queued: Boolean(res.pendingQueued),
+ enqueueFailed: Boolean(res.pendingEnqueueFailed),
+ error: res.ok ? undefined : res.error?.message,
+ });
});
- approve();
}
main().catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjs
index a23d7c111..36ef29fdf 100644
--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs
+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs
@@ -12,10 +12,10 @@
* OPENVIKING_PROFILE_TOKEN_BUDGET (default 10000 tokens, CJK-aware).
*
* 2. Archive injection (resume/compact only): OV's persistent session's
- * latest_archive_overview + pre-archive abstracts, fetched at
- * OPENVIKING_RESUME_CONTEXT_BUDGET tokens. For "compact" this is OV's
- * canonical long-term record alongside CC's own compact summary; for
- * "resume" it re-hydrates context lost when CC restarted.
+ * latest_archive_overview, fetched at OPENVIKING_RESUME_CONTEXT_BUDGET
+ * tokens. For "compact" this is OV's canonical long-term record alongside
+ * CC's own compact summary; for "resume" it re-hydrates context lost when
+ * CC restarted.
*
* The composed payload is mirrored to ~/.openviking/last_inject.md for audit.
*/
@@ -29,22 +29,21 @@ import { createLogger } from "./debug-log.mjs";
import {
deriveOvSessionId,
getSessionContext,
- isBypassed,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { replayPending } from "./lib/pending-queue.mjs";
import { buildProfileBlock, estimateTokens } from "./lib/profile-inject.mjs";
import { writeJsonState } from "./lib/state.mjs";
import { getEffectivePeerId } from "./lib/workspace-peer.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
if (!isPluginEnabled()) {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
process.exit(0);
}
-let cfg = loadConfig();
const { log, logError } = createLogger("session-start");
-const fetchJSON = makeFetchJSON(cfg);
+const fetchJSON = makeFetchJSON(loadConfig());
function output(obj) {
process.stdout.write(JSON.stringify(obj) + "\n");
@@ -70,19 +69,11 @@ function formatArchiveSection(sessionCtx) {
const overview = (sessionCtx.latest_archive_overview || "").trim();
if (!overview) return null;
- const abstracts = Array.isArray(sessionCtx.pre_archive_abstracts)
- ? sessionCtx.pre_archive_abstracts.filter((a) => typeof a === "string" && a.trim())
- : [];
-
- const lines = [
+ return [
"<session-archive>",
` <archive-overview>${overview}</archive-overview>`,
- ];
- for (const abs of abstracts.slice(0, 5)) {
- lines.push(` <archive-abstract>${abs.trim()}</archive-abstract>`);
- }
- lines.push("</session-archive>");
- return lines.join("\n");
+ "</session-archive>",
+ ].join("\n");
}
function writeLastInject(content) {
@@ -95,36 +86,22 @@ function writeLastInject(content) {
}
}
-async function main() {
- let input = {};
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString() || "{}");
- } catch { /* best effort */ }
-
+runHookStage({
+ loadConfig,
+ input: { tolerant: true },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+}, async ({ cfg, input, cwd, sessionId }) => {
const source = input.source || "startup";
- const sessionId = input.session_id;
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
log("start", { source, sessionId, peerSource: effectivePeer.source });
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
- return;
- }
-
const willInjectProfile = !cfg.noAutoInject;
const willInjectArchive = (source === "resume" || source === "compact") && !!sessionId;
const health = await fetchJSON("/health");
if (!health.ok) {
logError("health_check", "server unreachable");
- approve();
return;
}
@@ -142,7 +119,6 @@ async function main() {
if (!willInjectProfile && !willInjectArchive) {
log("skip", { reason: "no_injection_planned", source, noAutoInject: cfg.noAutoInject });
- approve();
return;
}
@@ -184,7 +160,6 @@ async function main() {
if (sections.length === 0) {
log("no_inject", { source, profile: !!profile, archive: !!archiveSection });
- approve();
return;
}
@@ -214,7 +189,5 @@ async function main() {
},
archive: Boolean(archiveSection),
});
- approve(composed);
-}
-
-main().catch((err) => { logError("uncaught", err); approve(); });
+ return composed;
+}).catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
new file mode 100644
index 000000000..745bfaece
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -0,0 +1,367 @@
+// 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 { createLogger } from "./debug-log.mjs";
+import { sendSessionMessages } from "./batch-send.mjs";
+import { createOvHttp } from "./ov-http.mjs";
+import { enqueue, replayPending } from "./pending-queue.mjs";
+import { buildProfileBlock } from "./profile-inject.mjs";
+import { buildRecallBlock, isRecallEnabled } from "./recall-core.mjs";
+import { buildPluginConfig } from "./plugin-config.mjs";
+import { isRetryableFailure } from "./retryable.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 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");
+}
+
+/**
+ * The config for one of the thin hook harnesses.
+ *
+ * These four used to read the environment and nothing else, so `ov config
+ * switch` moved their credentials and left their behaviour behind, and an
+ * `ovcli.conf` `plugin` entry named after them was inert. They resolve through
+ * the same layers as every other harness now; only the client's own name for
+ * itself stays local.
+ *
+ * `cwd` selects the workspace layer. It defaults to this process's directory,
+ * which is all a hook knows before the payload on stdin names the session's
+ * own — the caller re-resolves once it has it. That is safe because a workspace
+ * file may not carry connection or credential keys, so the base URL and API key
+ * cannot move under a logger or fetch helper already built from the first load.
+ */
+export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
+ return {
+ ...buildPluginConfig(clientId, {
+ cwd,
+ version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ logFile: `${clientId}-hooks.log`,
+ }),
+ clientId,
+ };
+}
+
+export function createAgentLogger(clientId, hookName, cfg) {
+ return createLogger(`${clientId}:${hookName}`, cfg);
+}
+
+export async function readRawHookInput() {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ return Buffer.concat(chunks).toString();
+}
+
+export async function readHookInput() {
+ const raw = await readRawHookInput();
+ 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);
+}
+
+/**
+ * The `fetchJSON` a hook talks through.
+ *
+ * `getActorPeerId` is a getter rather than a value because Codex only knows its
+ * peer after loading session state under the session lock, and because a stack
+ * whose every call names its own peer answers with the empty string. The
+ * workspace peer behind the default is resolved on demand so those callers do
+ * not pay for a lookup they never read.
+ */
+export function makeAgentFetchJSON(cfg, cwd = process.cwd(), {
+ defaultTimeoutMs,
+ getActorPeerId,
+ requireJsonBody = false,
+} = {}) {
+ let resolved = null;
+ const workspacePeer = () => (resolved ??= resolveEffectivePeerId({ cfg, cwd }));
+ const fetchJSON = createOvHttp(cfg, {
+ defaultTimeoutMs: defaultTimeoutMs ?? cfg.timeoutMs,
+ resolveActorPeerId: getActorPeerId || (() => workspacePeer().peerId),
+ requireJsonBody,
+ });
+ return { fetchJSON, get effectivePeer() { return workspacePeer(); } };
+}
+
+/** Park a write for the next hook to replay. Never throws: the caller is a hook. */
+export async function enqueueAgentPending(type, sessionId, payload = {}) {
+ try {
+ return await enqueue(type, sessionId, payload);
+ } catch {
+ return { ok: false };
+ }
+}
+
+/**
+ * What became of a write that failed: parked for replay, or reported once on
+ * stderr when no retry can help. `pendingQueued` / `pendingEnqueueFailed` are
+ * what the capture hooks log and what decides whether a turn is lost.
+ */
+async function notePendingWrite(type, sessionId, payload, result) {
+ if (result.ok) return result;
+ if (!isRetryableFailure(result)) {
+ const detail = result.error?.message || result.error?.code || "";
+ process.stderr.write(
+ `[ov] ${type} failed with non-retryable status ${result.status || "unknown"};`
+ + ` not enqueuing pending retry${detail ? ` (${detail})` : ""}\n`,
+ );
+ return result;
+ }
+ const pending = await enqueueAgentPending(type, sessionId, payload);
+ if (pending.ok) result.pendingQueued = true;
+ else result.pendingEnqueueFailed = true;
+ return result;
+}
+
+export async function addAgentMessage(fetchJSON, sessionId, payload) {
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ return notePendingWrite("addMessage", sessionId, payload, result);
+}
+
+export async function addAgentMessages(fetchJSON, sessionId, payloads) {
+ return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });
+}
+
+export async function commitAgentSession(fetchJSON, sessionId, log = () => {}, payload = {}) {
+ const body = payload || {};
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ await notePendingWrite("commitSession", sessionId, body, result);
+ log("commit", {
+ sessionId,
+ ok: result.ok,
+ status: result.result?.status || result.status,
+ trace_id: result.traceId || result.result?.trace_id,
+ queued: Boolean(result.pendingQueued),
+ error: result.ok ? undefined : result.error?.message || result.error?.code,
+ });
+ return result;
+}
+
+/** Session meta, or null when the session does not exist and `autoCreate` is off. */
+export async function getAgentSession(fetchJSON, sessionId, { autoCreate = false } = {}) {
+ const query = autoCreate ? "?auto_create=true" : "";
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}${query}`);
+ return result.ok ? result.result : null;
+}
+
+/** Assembled session context (includes latest_archive_overview), or null. */
+export async function getAgentSessionContext(fetchJSON, sessionId, tokenBudget = 128000) {
+ const result = await fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,
+ );
+ return result.ok ? result.result : null;
+}
+
+export async function replayAgentPending(fetchJSON, log = () => {}) {
+ return replayPending(fetchJSON, log);
+}
+
+export async function recallForPrompt(fetchJSON, cfg, prompt, cwd, log = () => {}, options = {}) {
+ if (!isRecallEnabled(cfg) || !String(prompt || "").trim()) return null;
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ return buildRecallBlock(fetchJSON, cfg, prompt, {
+ actorPeerId: peer.peerId,
+ legacyPeerId: peer.legacyPeerId,
+ // Passing the OV session id is what turns on server-side query expansion
+ // and the cross-turn dedup ledger for these thin harnesses.
+ sessionId: options.sessionId || "",
+ 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) });
+}
+
+/**
+ * The opening every hook entry shares: read the payload, re-resolve the config
+ * against the session's directory, answer the two gates, then run the hook's
+ * own work and emit one envelope.
+ *
+ * `run` receives the resolved stage and returns the envelope's payload — a
+ * systemMessage, a context block, or nothing. A closed gate calls
+ * `onSkip(reason, stage)` with `"bad_stdin"`, `"disabled"` or `"bypass"`, emits
+ * an empty envelope and never runs the callback. `run` may emit early through
+ * `stage.emit` (a detaching hook has to answer before its worker starts); the
+ * envelope is written once.
+ *
+ * Both gates are predicates over `(cfg, stage)`: `enabled` says whether this
+ * hook runs at all, `bypass` whether this session is one the plugin stays out
+ * of. `sessionId` reads the session out of the payload — the default is the key
+ * Claude Code and Codex send, and a host that spells it differently, or derives
+ * it, hands over its own resolver rather than turning the gate off.
+ *
+ * The write-path preamble — the enabled gate against this process's directory,
+ * then `maybeDetach` — stays in the entry. A worker has to be spawned before
+ * stdin is consumed, and its response is the host's own.
+ */
+export async function runHookStage({
+ clientId,
+ loadConfig = (cwd) => loadAgentHookConfig(clientId, cwd),
+ input: { read = readRawHookInput, tolerant = false } = {},
+ sessionId: resolveSessionId = (payload) => payload.session_id ?? payload.sessionId,
+ gates: { enabled = null, bypass = (cfg, stage) => stage.bypassed } = {},
+ envelope = () => {},
+ onSkip = () => {},
+} = {}, run = () => undefined) {
+ let emitted = false;
+ const emit = (value) => {
+ if (emitted) return;
+ emitted = true;
+ envelope(value);
+ };
+
+ let badStdin = false;
+ const raw = await read();
+ let payload;
+ try {
+ payload = JSON.parse(tolerant ? raw || "{}" : raw);
+ } catch {
+ badStdin = !tolerant;
+ payload = {};
+ }
+ if (!payload || typeof payload !== "object") payload = {};
+
+ const cwd = resolveAgentCwd(payload);
+ const cfg = loadConfig(cwd);
+ const sessionId = resolveSessionId(payload);
+ const stage = {
+ cfg,
+ input: payload,
+ raw,
+ cwd,
+ sessionId,
+ bypassed: isBypassed(cfg, { sessionId, cwd }),
+ emit,
+ };
+
+ if (badStdin) {
+ onSkip("bad_stdin", stage);
+ emit();
+ return undefined;
+ }
+ if (cfg.enabled === false || (enabled && !enabled(cfg, stage))) {
+ onSkip("disabled", stage);
+ emit();
+ return undefined;
+ }
+ if (bypass && bypass(cfg, stage)) {
+ onSkip("bypass", stage);
+ emit();
+ return undefined;
+ }
+
+ const result = await run(stage);
+ emit(result);
+ return result;
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
index 22bc1b63c..777913f74 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
@@ -266,7 +266,13 @@ export function extractTextFromPayload(payload, options = {}) {
return chunks.join("\n\n");
}
-function collectToolNamesByIdFromEntries(entries) {
+/**
+ * Map every tool call id in a transcript to the name of the tool it invoked.
+ *
+ * A result block names the call by id only, so the name has to come from the
+ * call that preceded it. Pass the map as `toolNameById` to the extractors.
+ */
+export function collectToolNamesByIdFromEntries(entries) {
const map = {};
for (const entry of entries || []) {
const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;
@@ -433,6 +439,24 @@ export function extractCaptureTurns(rolloutEntries, cfg = {}) {
return turns;
}
+/**
+ * Index of the last turn that came from a human prompt, or -1.
+ *
+ * `role === "user"` alone is not enough: normalizeCaptureRole() maps tool
+ * results onto the user role too, and those carry `tool` parts rather than
+ * `text` parts. Used by the post-compact shrink path to find where the current
+ * interaction starts.
+ */
+export function findLastHumanTurnIndex(turns) {
+ const list = Array.isArray(turns) ? turns : [];
+ for (let i = list.length - 1; i >= 0; i -= 1) {
+ const turn = list[i];
+ if (turn?.role !== "user") continue;
+ if (turn.parts?.some((part) => part?.type === "text")) return i;
+ }
+ return -1;
+}
+
export function normalizeCaptureRole(role) {
const value = normalizeType(role);
if (value === "user") return "user";
@@ -511,12 +535,24 @@ function stripInjectedDigestBlocks(text) {
return out.join("\n");
}
+/**
+ * Drop everything in a turn that the conversation did not put there.
+ *
+ * Recall injects a context block into the prompt, and the host adds notes of
+ * its own; captured back unchanged, this turn's injection becomes next turn's
+ * memory and the loop feeds on itself. Formatting the conversation did author
+ * — newlines, code fences — survives.
+ */
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, " ")
+ // Claude Code wraps its own out-of-band notes to the model in these two
+ // shapes. They are the host talking to itself, not the conversation.
+ .replace(/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi, " ")
+ .replace(/^[ \t]*\[Subagent Context\][^\n]*$/gim, " ")
.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, "")
@@ -540,6 +576,23 @@ function isPunctuationOnly(text) {
return !/[a-z0-9\u3400-\u9fff]/i.test(text);
}
+/**
+ * Is capture on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoCapture`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables capture under an older name still disables it.
+ */
+export function isCaptureEnabled(cfg = {}) {
+ for (const value of [cfg.enabled, cfg.autoCapture, cfg.capture, cfg.syncTurns]) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {}) {
const maxLength = cfg.captureMaxLength || 24000;
const sanitized = sanitizeCapturedText(text);
@@ -576,3 +629,26 @@ export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {})
return { shouldCapture: true, reason: "ok", text: capped };
}
+
+/**
+ * Apply the capture filter to a list of `{ role, content }` turns.
+ *
+ * The harnesses that compose `agent-hook-runtime` used to send whatever their
+ * transcript parser produced: an acknowledgement, a slash command, a stray
+ * `ok`, or a turn far past `captureMaxLength` all reached the extractor
+ * verbatim. This is the same decision every other harness makes, in one place,
+ * so a thin harness gets it by calling rather than by reimplementing it.
+ *
+ * Returns the surviving turns with `content` replaced by the sanitized and
+ * capped text, and the dropped ones with the reason, for the debug log.
+ */
+export function filterCaptureTurns(turns, cfg = {}) {
+ const kept = [];
+ const dropped = [];
+ for (const turn of Array.isArray(turns) ? turns : []) {
+ const decision = shouldCaptureText(turn?.content, turn?.role, cfg);
+ if (decision.shouldCapture) kept.push({ ...turn, content: decision.text });
+ else dropped.push({ role: turn?.role, reason: decision.reason });
+ }
+ return { kept, dropped };
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs
new file mode 100644
index 000000000..4a1a7c9c4
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs
@@ -0,0 +1,359 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Every knob a memory plugin reads, declared once.
+ *
+ * A setting stayed uniform across harnesses only when a shared module read it
+ * on the hot path: `recallLimit`, `scoreThreshold` and `captureMaxLength` agree
+ * everywhere because `recall-core` and `capture-utils` read them. Everything
+ * else drifted — the same switch is `autoRecall` in three loaders, an
+ * `autoRecall` *object* in opencode, `syncTurns` in dsh and pi, and absent from
+ * the thin hook runtime — because each loader hand-wrote its own list and the
+ * author picked a name. Three more lists then had to be kept in step by hand:
+ * the doctor's known-knob set, the workspace file's dotted-key map, and the
+ * implicit inventory inside `loadAgentHookConfig`.
+ *
+ * This module is the one list. The others are projections of it:
+ * `pluginConfigKeys()` for the doctor, `WORKSPACE_KNOB_MAP` for the workspace
+ * file, and `resolveKnobs()` for every loader. A knob added here reaches all of
+ * them; a knob spelled wrong reaches none.
+ *
+ * Declaration fields:
+ * name canonical key, and the property the loaders read
+ * type bool | int | number | enum | string | list
+ * default value when no layer supplies one
+ * harness per-harness default, where one genuinely differs
+ * min/max clamped, not rejected: a config file must not kill a hook
+ * values the enum's members; anything else falls back to the default
+ * env OPENVIKING_* variable, the highest-priority layer
+ * aliases older spellings, honoured forever; the doctor names them
+ * workspace dotted key in `.openviking/config.json`
+ * capability which capability owns it, for the switches in recall/capture
+ * sendOnlyWhenConfigured
+ * the request omits this field unless a layer actually set it,
+ * so the server's own default stands. Loaders project the flag
+ * as `<name>Configured` and `recall-core` reads it from there.
+ */
+
+export const CAPABILITIES = ["connection", "peer", "recall", "capture", "session", "debug"];
+
+/** @type {ReadonlyArray<object>} */
+export const KNOBS = [
+ // ── connection and identity ────────────────────────────────────────────
+ // Credentials resolve through `credentials.mjs`; these entries exist so the
+ // doctor recognises them inside `plugin` and so ov.conf's harness section
+ // keeps working.
+ { name: "enabled", type: "bool", default: true, env: "OPENVIKING_MEMORY_ENABLED", capability: "connection" },
+ { name: "apiKey", type: "string", default: "", capability: "connection" },
+ { name: "accountId", type: "string", default: "", capability: "connection" },
+ { name: "userId", type: "string", default: "", capability: "connection" },
+ { name: "authMode", type: "enum", values: ["trusted", "api_key"], default: "", env: "OPENVIKING_AUTH_MODE", aliases: ["auth_mode"], capability: "connection" },
+ {
+ name: "timeoutMs",
+ type: "int",
+ default: 15000,
+ // opencode drives an editor session that tolerates a slower call; dsh runs
+ // inside a chat host that does not.
+ harness: { opencode: 30000, dsh: 10000 },
+ min: 1000,
+ max: 300000,
+ env: "OPENVIKING_TIMEOUT_MS",
+ aliases: ["requestTimeoutMs"],
+ capability: "connection",
+ },
+ { name: "mcpEnabled", type: "bool", default: true, capability: "connection" },
+ { name: "mcpToolCallTimeoutMs", type: "int", default: 60000, min: 1000, max: 600000, capability: "connection" },
+ { name: "dataDir", type: "string", default: "", capability: "connection" },
+
+ { name: "peerId", type: "string", default: "", env: "OPENVIKING_PEER_ID", aliases: ["peer_id"], workspace: "peer.id", capability: "peer" },
+ { name: "peerSource", type: "template", default: "", env: "OPENVIKING_PEER_SOURCE", workspace: "peer.source", capability: "peer" },
+ { name: "workspacePeer", type: "bool", default: true, env: "OPENVIKING_WORKSPACE_PEER", capability: "peer" },
+
+ // ── recall ────────────────────────────────────────────────────────────
+ {
+ name: "autoRecall",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_RECALL",
+ workspace: "recall.enabled",
+ capability: "recall",
+ },
+ { name: "recallLimit", type: "int", default: 10, min: 1, max: 50, env: "OPENVIKING_RECALL_LIMIT", workspace: "recall.max_items", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "scoreThreshold", type: "number", default: 0.35, min: 0, max: 1, env: "OPENVIKING_SCORE_THRESHOLD", aliases: ["recallScoreThreshold"], workspace: "recall.score_threshold", capability: "recall" },
+ { name: "minQueryLength", type: "int", default: 3, min: 1, max: 64, env: "OPENVIKING_MIN_QUERY_LENGTH", aliases: ["recallMinQueryLength"], capability: "recall" },
+ { name: "recallTokenBudget", type: "int", default: 2000, min: 200, max: 50000, env: "OPENVIKING_RECALL_TOKEN_BUDGET", aliases: ["recallBudget"], capability: "recall" },
+ { name: "recallMaxContentChars", type: "int", default: 500, min: 100, max: 5000, env: "OPENVIKING_RECALL_MAX_CONTENT_CHARS", capability: "recall" },
+ { name: "recallPreferAbstract", type: "bool", default: true, env: "OPENVIKING_RECALL_PREFER_ABSTRACT", capability: "recall" },
+ { name: "recallPeerScope", type: "enum", values: ["all", "actor"], default: "all", env: "OPENVIKING_RECALL_PEER_SCOPE", workspace: "recall.peer_scope", capability: "recall" },
+ { name: "recallDedupTurns", type: "int", default: 5, min: 0, max: 20, env: "OPENVIKING_RECALL_DEDUP_TURNS", workspace: "recall.dedup_turns", capability: "recall" },
+ { name: "recallMaxTokens", type: "int", default: 1600, min: 64, max: 200000, env: "OPENVIKING_RECALL_MAX_TOKENS", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallQueryExpansion", type: "enum", values: ["auto", "off"], default: "auto", env: "OPENVIKING_RECALL_QUERY_EXPANSION", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallTimeoutMs", type: "int", default: 120000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_TIMEOUT_MS", capability: "recall" },
+ // 0 keeps the built-in default, which outlasts the server's rewrite fuse.
+ { name: "recallContextTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS", capability: "recall" },
+ { name: "logRankingDetails", type: "bool", default: false, env: "OPENVIKING_LOG_RANKING_DETAILS", capability: "recall" },
+ { name: "recallLedger", type: "bool", default: true, env: "OPENVIKING_RECALL_LEDGER", capability: "recall" },
+ { name: "recallQueryFilters", type: "list", default: [], env: "OPENVIKING_RECALL_QUERY_FILTERS", capability: "recall" },
+
+ // Digest compression. Claude Code reads this as the tri-state
+ // off/client/server/auto through `normalizeRewriteMode`; Codex reads the same
+ // key as on/off. Both spellings stay declared so neither harness's users are
+ // told their config is a typo.
+ { name: "recallCompress", type: "string", default: "auto", env: "OPENVIKING_RECALL_COMPRESS", aliases: ["recallRewrite"], capability: "recall" },
+ { name: "recallCompressModel", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_MODEL", capability: "recall" },
+ { name: "recallCompressBaseUrl", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_BASE_URL", capability: "recall" },
+ { name: "recallCompressThinking", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_THINKING", aliases: ["recallCompressReasoningEffort"], capability: "recall" },
+ // 0 means "derive from recallTimeoutMs" — the loader that owns the fallback
+ // is the one that knows the request budget it has to fit inside.
+ { name: "recallCompressTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectOnStartup", type: "bool", default: true, env: "OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP", capability: "recall" },
+ { name: "recallCompressDetectTimeoutMs", type: "int", default: 15000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectTtlMs", type: "int", default: 604800000, min: 0, capability: "recall", env: "OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS" },
+ { name: "recallCompressMinInputChars", type: "int", default: 1500, min: 0, max: 100000, env: "OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxInputChars", type: "int", default: 18000, min: 1000, max: 200000, env: "OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxBullets", type: "int", default: 6, min: 1, max: 50, env: "OPENVIKING_RECALL_COMPRESS_MAX_BULLETS", sendOnlyWhenConfigured: true, capability: "recall" },
+
+ // ── capture ───────────────────────────────────────────────────────────
+ // `syncTurns` is dsh and pi's spelling of the same switch. It stays an alias
+ // rather than a second knob so `ov config switch` moves both.
+ {
+ name: "autoCapture",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_CAPTURE",
+ aliases: ["syncTurns"],
+ workspace: "capture.enabled",
+ capability: "capture",
+ },
+ { name: "captureMode", type: "enum", values: ["semantic", "keyword"], default: "semantic", env: "OPENVIKING_CAPTURE_MODE", capability: "capture" },
+ { name: "captureMaxLength", type: "int", default: 24000, min: 200, max: 100000, env: "OPENVIKING_CAPTURE_MAX_LENGTH", capability: "capture" },
+ // Tool output is reported verbatim; the server owns truncation via
+ // tool_output_externalization. This cap only guards pathological payloads.
+ { name: "captureToolMaxChars", type: "int", default: 1000000, min: 200, max: 1000000, env: "OPENVIKING_CAPTURE_TOOL_MAX_CHARS", capability: "capture" },
+ // Default true: a memory plugin that only sees the user's half of the
+ // conversation extracts noticeably worse.
+ { name: "captureAssistantTurns", type: "bool", default: true, env: "OPENVIKING_CAPTURE_ASSISTANT_TURNS", capability: "capture" },
+ { name: "captureLastAssistantOnStop", type: "bool", default: true, env: "OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP", capability: "capture" },
+ { name: "captureToolResults", type: "bool", default: false, env: "OPENVIKING_CAPTURE_TOOL_RESULTS", capability: "capture" },
+ { name: "captureFilters", type: "list", default: [], env: "OPENVIKING_CAPTURE_FILTERS", capability: "capture" },
+ // 0 means "derive from timeoutMs": a write gets a longer budget than a read.
+ { name: "captureTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_CAPTURE_TIMEOUT_MS", capability: "capture" },
+ { name: "commitTokenThreshold", type: "int", default: 20000, min: 1000, max: 1000000, env: "OPENVIKING_COMMIT_TOKEN_THRESHOLD", workspace: "capture.commit_token_threshold", capability: "capture" },
+ { name: "commitKeepRecentCount", type: "int", default: 10, min: 0, max: 1000, env: "OPENVIKING_COMMIT_KEEP_RECENT_COUNT", capability: "capture" },
+ { name: "commitTurnThreshold", type: "int", default: 8, min: 1, max: 1000, env: "OPENVIKING_COMMIT_TURN_THRESHOLD", capability: "capture" },
+ { name: "autoCommitOnCompact", type: "bool", default: true, env: "OPENVIKING_AUTO_COMMIT_ON_COMPACT", capability: "capture" },
+ { name: "writePathAsync", type: "bool", default: true, env: "OPENVIKING_WRITE_PATH_ASYNC", capability: "capture" },
+
+ // ── session lifecycle ─────────────────────────────────────────────────
+ { name: "noAutoInject", type: "bool", default: false, env: "OPENVIKING_NO_AUTO_INJECT", capability: "session" },
+ { name: "profileTokenBudget", type: "int", default: 10000, min: 500, max: 50000, env: "OPENVIKING_PROFILE_TOKEN_BUDGET", aliases: ["profileBudget"], capability: "session" },
+ { name: "resumeContextBudget", type: "int", default: 32000, min: 1024, max: 128000, env: "OPENVIKING_RESUME_CONTEXT_BUDGET", capability: "session" },
+ { name: "resumeArchiveInject", type: "bool", default: true, env: "OPENVIKING_RESUME_ARCHIVE_INJECT", capability: "session" },
+ { name: "resumeArchiveTokenBudget", type: "int", default: 32000, min: 0, max: 128000, env: "OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET", capability: "session" },
+ { name: "resumeArchiveMaxChars", type: "int", default: 6000, min: 1000, max: 200000, env: "OPENVIKING_RESUME_ARCHIVE_MAX_CHARS", capability: "session" },
+ { name: "skillExperience", type: "bool", default: false, env: "OPENVIKING_SKILL_EXPERIENCE", capability: "session" },
+ { name: "skillExperienceLimit", type: "int", default: 3, min: 1, max: 50, env: "OPENVIKING_SKILL_EXPERIENCE_LIMIT", capability: "session" },
+ { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" },
+ { name: "repoContext", type: "bool", default: true, capability: "session" },
+ { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" },
+
+ { name: "takeoverEnabled", type: "bool", default: true, env: "OPENVIKING_TAKEOVER", capability: "session" },
+ { name: "takeoverTokenThreshold", type: "int", default: 30000, min: 1, max: 1000000, capability: "session" },
+ { name: "takeoverKeepRecentTurns", type: "int", default: 3, min: 0, max: 100, capability: "session" },
+ { name: "takeoverOverviewBudget", type: "int", default: 3000, min: 100, max: 50000, capability: "session" },
+ { name: "takeoverOverviewPollMs", type: "int", default: 2000, min: 0, max: 60000, capability: "session" },
+ { name: "takeoverOverviewPollMax", type: "int", default: 15, min: 1, max: 120, capability: "session" },
+
+ { name: "bypassSession", type: "bool", default: false, env: "OPENVIKING_BYPASS_SESSION", capability: "session" },
+ {
+ name: "bypassSessionPatterns",
+ type: "list",
+ default: [],
+ env: "OPENVIKING_BYPASS_SESSION_PATTERNS",
+ // pi shipped this under its own name before the shared matcher existed.
+ aliases: ["bypassPatterns"],
+ workspace: "bypass.session_patterns",
+ capability: "session",
+ },
+
+ // ── debug ─────────────────────────────────────────────────────────────
+ { name: "debug", type: "bool", default: false, env: "OPENVIKING_DEBUG", capability: "debug" },
+ // The default path is per-harness and built from a log directory the loader
+ // owns, so the schema only carries what a user set.
+ { name: "debugLogPath", type: "string", default: "", env: "OPENVIKING_DEBUG_LOG", capability: "debug" },
+ { name: "logLevel", type: "enum", values: ["silent", "error", "info"], default: "error", env: "OPENVIKING_LOG_LEVEL", capability: "debug" },
+];
+
+export const KNOB_BY_NAME = new Map(KNOBS.map((knob) => [knob.name, knob]));
+
+/** Every accepted spelling → the canonical knob it means. */
+export const KNOB_BY_KEY = new Map();
+for (const knob of KNOBS) {
+ KNOB_BY_KEY.set(knob.name, knob);
+ for (const alias of knob.aliases || []) KNOB_BY_KEY.set(alias, knob);
+}
+
+/** Every key a user may legitimately write in `ovcli.conf`'s plugin section. */
+export function pluginConfigKeys() {
+ return new Set(KNOB_BY_KEY.keys());
+}
+
+/** The workspace file's dotted keys → the knob each one sets. */
+export const WORKSPACE_KNOB_MAP = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.name]),
+);
+
+/** The enum members and clamps the workspace validator reports on. */
+export const WORKSPACE_ENUMS = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.values || null]),
+);
+
+export const WORKSPACE_RANGES = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace && knob.min !== undefined && knob.max !== undefined)
+ .map((knob) => [knob.workspace, {
+ min: knob.min,
+ max: knob.max,
+ integer: knob.type === "int",
+ }]),
+);
+
+/**
+ * The harnesses that may appear as a per-harness object inside `plugin`.
+ *
+ * The key is snake_case because that is what ov.conf's own sections use; the
+ * hyphenated spelling a host calls itself (`claude-code`, `trae-cn`) is
+ * accepted too, so a user who copies the harness name out of the installer
+ * lands on the right override instead of on a silent no-op.
+ */
+export const HARNESS_KEYS = {
+ claudeCode: "claude_code",
+ codex: "codex",
+ cursor: "cursor",
+ trae: "trae",
+ traeCn: "trae_cn",
+ zcode: "zcode",
+ opencode: "opencode",
+ dsh: "dsh",
+ pi: "pi",
+ openclaw: "openclaw",
+};
+
+export function harnessKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** Both accepted spellings of every harness, for the `plugin` section. */
+export const HARNESS_CONFIG_KEYS = new Set(
+ Object.values(HARNESS_KEYS).flatMap((key) => [key, key.replace(/_/g, "-")]),
+);
+
+export function knobDefault(knob, harness = "") {
+ if (harness && knob.harness && knob.harness[harness] !== undefined) return knob.harness[harness];
+ return Array.isArray(knob.default) ? [...knob.default] : knob.default;
+}
+
+const TRUE_WORDS = ["1", "true", "yes", "on"];
+const FALSE_WORDS = ["0", "false", "no", "off"];
+
+/**
+ * Coerce one raw value to the knob's type.
+ *
+ * A value out of range is clamped and a value of the wrong shape falls back to
+ * the default: a hook that dies because someone typed a letter into a number
+ * would take the host's session down with it.
+ */
+export function coerceKnobValue(knob, raw, fallback) {
+ if (raw === undefined || raw === null) return fallback;
+ switch (knob.type) {
+ case "bool": {
+ if (typeof raw === "boolean") return raw;
+ const word = String(raw).trim().toLowerCase();
+ if (TRUE_WORDS.includes(word)) return true;
+ if (FALSE_WORDS.includes(word)) return false;
+ return fallback;
+ }
+ case "int":
+ case "number": {
+ if (typeof raw === "string" && !raw.trim()) return fallback;
+ const value = knob.type === "int" ? Math.round(Number(raw)) : Number(raw);
+ if (!Number.isFinite(value)) return fallback;
+ const floored = knob.min === undefined ? value : Math.max(knob.min, value);
+ return knob.max === undefined ? floored : Math.min(knob.max, floored);
+ }
+ case "enum": {
+ const word = String(raw ?? "").trim();
+ return (knob.values || []).includes(word) ? word : fallback;
+ }
+ // A peer template may be one string or an ordered list of fallbacks, and
+ // `String([a, b])` would quietly turn the list into one bogus template.
+ case "template": {
+ if (Array.isArray(raw)) {
+ const items = raw.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ return items.length ? items : fallback;
+ }
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ case "list": {
+ const items = Array.isArray(raw)
+ ? raw
+ : typeof raw === "string" ? raw.split(",") : null;
+ if (!items) return fallback;
+ return items.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ }
+ default: {
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ }
+}
+
+/**
+ * Resolve every knob through the layers, lowest priority first.
+ *
+ * `layers` is `[{ name, data }]`; `env` is the top layer and needs no entry.
+ * Returns the settings plus the names a layer actually supplied, which is what
+ * the `*Configured` flags report — several call sites send a field to the
+ * server only when the user asked for it, and a default must not look asked-for.
+ */
+export function resolveKnobs({ harness = "", layers = [], env = {} } = {}) {
+ const settings = {};
+ const configured = new Set();
+ const sources = {};
+ // A value that would not parse is not a configuration: without this sentinel
+ // `recallLimit: "abc"` would report as configured and send a default to the
+ // server dressed up as the user's choice.
+ const UNPARSEABLE = Symbol("unparseable");
+
+ const take = (knob, raw, source, current) => {
+ const value = coerceKnobValue(knob, raw, UNPARSEABLE);
+ if (value === UNPARSEABLE) return current;
+ configured.add(knob.name);
+ sources[knob.name] = source;
+ return value;
+ };
+
+ for (const knob of KNOBS) {
+ let value = knobDefault(knob, harness);
+ for (const layer of layers) {
+ const data = layer?.data;
+ if (!data || typeof data !== "object") continue;
+ // Aliases first so the canonical name wins when one layer carries both:
+ // a file with `recallCompressThinking` beside its older
+ // `recallCompressReasoningEffort` means the newer one.
+ for (const key of [...(knob.aliases || []), knob.name]) {
+ if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
+ if (data[key] === undefined) continue;
+ value = take(knob, data[key], layer.name || "file", value);
+ }
+ }
+ if (knob.env) {
+ const raw = env[knob.env];
+ if (raw !== undefined && raw !== null && String(raw) !== "") {
+ value = take(knob, raw, "env", value);
+ }
+ }
+ settings[knob.name] = value;
+ }
+
+ return { settings, configured, sources };
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
index ba26a84dc..0ab2d984d 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/credentials.mjs
@@ -7,6 +7,8 @@ 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";
+const DEFAULT_TIMEOUT_MS = 15000;
+const MIN_TIMEOUT_MS = 1000;
function str(val, fallback = "") {
if (typeof val === "string" && val.trim()) return val.trim();
@@ -108,6 +110,45 @@ export function loadCredentialFiles(env = process.env) {
};
}
+/**
+ * The calling harness's own section of ov.conf.
+ *
+ * ov.conf spells its sections snake_case while a host may call itself
+ * `claude-code` or `trae-cn`, so both spellings land on the same block. The
+ * normalization stays inline rather than importing `config-schema.mjs`, which
+ * the portable agent-plugins bundle would then have to ship as well.
+ */
+function harnessSection(ovFile, harness) {
+ const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+ const section = key ? ovFile[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+const AUTH_MODES = ["trusted", "api_key"];
+
+function normalizeAuthMode(value) {
+ const mode = str(value, "").toLowerCase();
+ return AUTH_MODES.includes(mode) ? mode : "";
+}
+
+/**
+ * Which auth mode the server is in, and with it whether the identity headers
+ * may go on the wire.
+ *
+ * An `api_key` server reads the account and the user out of the key and ignores
+ * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
+ * every proxy on the path who the operator is and buys nothing. A named mode
+ * wins; ov.conf's server block answers next; failing both, a credential layer
+ * that supplied an identity at all means the deployment expects one.
+ */
+export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
+ const server = ovFile.server || {};
+ const authMode = normalizeAuthMode(settings.authMode)
+ || normalizeAuthMode(server.auth_mode)
+ || ((account || user) ? "trusted" : "api_key");
+ return { authMode, sendIdentityHeaders: authMode === "trusted" };
+}
+
function sourceMode(env) {
const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
.toLowerCase();
@@ -144,40 +185,58 @@ function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
return `http://${host}:${port}`;
}
-export function resolveOpenVikingCredentials(env = process.env) {
+/**
+ * `harness` names whose ov.conf section supplies the legacy fallback. It sits
+ * where it always did — after ovcli.conf, before `server.root_api_key` — but a
+ * harness now reads its own section instead of every one of them reading
+ * codex's. The default keeps codex, the only caller that never passes one.
+ *
+ * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
+ * section named, which this module cannot read for itself: resolving that
+ * section needs the knob schema, and the portable bundles would then have to
+ * ship it. All three rank where the file they come from ranks — under
+ * ovcli.conf's own fields, over ov.conf.
+ */
+export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
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 cx = harnessSection(files.ovFile, harness);
const server = files.ovFile.server || {};
const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+ const pluginApiKey = str(plugin?.apiKey, "");
const apiKey = useCli
- ? str(files.cliFile.api_key, "")
+ ? (str(files.cliFile.api_key, "") || pluginApiKey)
: (
str(env.OPENVIKING_BEARER_TOKEN, "") ||
str(env.OPENVIKING_API_KEY, "") ||
str(files.cliFile.api_key, "") ||
+ pluginApiKey ||
str(cx.apiKey, "") ||
str(server.root_api_key, "")
);
+ const pluginAccount = str(plugin?.accountId, "");
const account = useCli
- ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
: (
str(env.OPENVIKING_ACCOUNT, "") ||
str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ pluginAccount ||
str(cx.accountId, "")
);
+ const pluginUser = str(plugin?.userId, "");
const user = useCli
- ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
: (
str(env.OPENVIKING_USER, "") ||
str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ pluginUser ||
str(cx.userId, "")
);
@@ -192,19 +251,31 @@ export function resolveOpenVikingCredentials(env = process.env) {
const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
+ // Which layer actually supplied the api_key, following the same chain, and
+ // the file behind it — empty when the key came from the environment or was
+ // never found. `apiKeySource` is what a doctor and a 401 hint report; the
+ // credential *source* beside it is the mode the chain ran in, not a file.
+ let apiKeySource = "none";
let credentialPath = "";
if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
+ if (useCli) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
+ apiKeySource = "env";
+ } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else {
+ apiKeySource = "ov";
+ credentialPath = files.ovPath;
+ }
}
return {
...files,
credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ apiKeySource,
credentialPath,
baseUrl,
mcpUrl,
@@ -216,6 +287,71 @@ export function resolveOpenVikingCredentials(env = process.env) {
};
}
+function envFlag(env, name) {
+ const raw = str(env[name], "").toLowerCase();
+ return raw === "1" || raw === "true" || raw === "yes";
+}
+
+function clampTimeout(value) {
+ const raw = str(value, "");
+ const parsed = raw ? Number(raw) : NaN;
+ return Math.max(MIN_TIMEOUT_MS, Math.floor(Number.isFinite(parsed) ? parsed : DEFAULT_TIMEOUT_MS));
+}
+
+/**
+ * Everything a stdio MCP proxy needs, for a package that ships no hooks.
+ *
+ * `buildPluginConfig` answers the same question one layer up, but reaching it
+ * means vendoring the knob schema and the workspace layers — a closure the
+ * portable agent-plugins bundle would carry in git to send one HTTP header.
+ * This is the connection half alone: the credential chain, the auth mode that
+ * decides whether the identity headers may go on the wire, the User-Agent, the
+ * request timeout, and the debug log.
+ *
+ * The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
+ * chain to itself. A portable package has no installer to migrate anyone, so
+ * an install that names only a `url` there keeps the key it has always used.
+ */
+export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
+ const name = str(harness);
+ const credentials = resolveOpenVikingCredentials(env, name);
+
+ let { apiKey, apiKeySource, credentialPath } = credentials;
+ if (!apiKey) {
+ apiKey = str(credentials.ovFile?.server?.root_api_key);
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+
+ return {
+ harness: name,
+ userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
+ baseUrl: credentials.baseUrl,
+ mcpUrl: credentials.mcpUrl,
+ apiKey,
+ account: credentials.account,
+ user: credentials.user,
+ peerId: credentials.peerId,
+ ...resolveAuthMode({
+ settings: { authMode: env.OPENVIKING_AUTH_MODE },
+ ovFile: credentials.ovFile,
+ account: credentials.account,
+ user: credentials.user,
+ }),
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
+ debug: envFlag(env, "OPENVIKING_DEBUG"),
+ debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
+ || join(homedir(), ".openviking", "logs", `${name}.log`),
+ };
+}
+
function main() {
const cmd = process.argv[2] || "";
if (cmd === "mcp-url") {
@@ -230,7 +366,7 @@ function main() {
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.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
process.exitCode = 2;
}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
index 47887e6e8..7cdd797cf 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/doctor-core.mjs
@@ -7,7 +7,9 @@
* state directory) and delegates everything that is the same everywhere to
* this module: config-file inspection, API key display, base URL linting,
* environment sweep, server probes and their interpretation, state/log
- * inspection, and report rendering.
+ * inspection, and report rendering. `runDoctor(hostSpec)` owns the run itself:
+ * the argument parsing, the section order, the `--json` envelope and the exit
+ * code, calling back into the host for the sections only it can produce.
*
* Nothing here reads harness config; callers pass a resolved connection
* `{ baseUrl, apiKey, account, user, peerId, userAgent }`.
@@ -16,12 +18,15 @@
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { join, resolve as resolvePath } from "node:path";
+import { HARNESS_CONFIG_KEYS, HARNESS_KEYS, harnessKey, KNOB_BY_NAME, pluginConfigKeys } from "./config-schema.mjs";
+import { buildOvHeaders } from "./ov-http.mjs";
import { resolveWorkspaceSettings } from "./plugin-config.mjs";
import { peerScopeMemoPath } from "./recall-core.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE, workspaceConfigPaths } from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId } from "./workspace-peer.mjs";
import { entryPath } from "./workspace-registry.mjs";
/**
@@ -311,32 +316,13 @@ export function unknownOvcliKeys(data) {
*
* `plugin` is on the allowlist above, which used to mean everything inside it
* went unchecked — so `peerSorce` sat there doing nothing with no complaint.
- * `plugin-known-keys.test.mjs` derives this set from the two loaders and fails
- * when they diverge, so it cannot rot into a list that rejects a real knob.
+ * The set is the schema's own key list, aliases included, so it cannot rot into
+ * a list that rejects a real knob.
*/
-export const KNOWN_PLUGIN_KEYS = new Set([
- "apiKey", "accountId", "userId", "auth_mode", "authMode", "enabled", "debug", "timeoutMs",
- "peerId", "peer_id", "peerSource", "workspacePeer",
- "autoRecall", "autoCapture", "noAutoInject", "writePathAsync", "minQueryLength",
- "bypassSessionPatterns",
- "recallLimit", "recallMaxTokens", "recallMaxContentChars", "recallTokenBudget",
- "recallPeerScope", "recallDedupTurns", "recallQueryExpansion", "recallPreferAbstract",
- "recallRewrite", "recallContextTimeoutMs", "recallTimeoutMs", "scoreThreshold",
- "recallCompress", "recallCompressMaxBullets", "recallCompressMaxInputChars",
- "recallCompressMinInputChars", "recallCompressBaseUrl", "recallCompressModel",
- "recallCompressThinking", "recallCompressReasoningEffort", "recallCompressTimeoutMs",
- "recallCompressDetectOnStartup", "recallCompressDetectTimeoutMs", "recallCompressDetectTtlMs",
- "recallQueryFilters", "captureFilters",
- "captureMode", "captureMaxLength", "captureTimeoutMs", "captureToolMaxChars",
- "captureAssistantTurns", "captureLastAssistantOnStop", "logRankingDetails",
- "commitTokenThreshold", "commitKeepRecentCount", "autoCommitOnCompact",
- "profileTokenBudget", "resumeContextBudget", "resumeArchiveInject",
- "resumeArchiveMaxChars", "resumeArchiveTokenBudget",
- "skillExperience", "skillExperienceLimit",
-]);
+export const KNOWN_PLUGIN_KEYS = pluginConfigKeys();
/** Nested objects in `plugin` are per-harness overrides, not knobs. */
-const PLUGIN_HARNESS_KEYS = new Set(["claude_code", "codex"]);
+const PLUGIN_HARNESS_KEYS = HARNESS_CONFIG_KEYS;
function nearestKnownKey(key) {
// Levenshtein would be overkill; a typo that matters is almost always one
@@ -502,14 +488,10 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo
return out;
}
+// A connection record carries no `sendIdentityHeaders`: the doctor asks with
+// the identity and reports whatever the server echoes back.
function authHeaders(conn, { identity = true } = {}) {
- const headers = { "Content-Type": "application/json" };
- if (conn.apiKey) headers["Authorization"] = `Bearer ${conn.apiKey}`;
- if (identity && conn.account) headers["X-OpenViking-Account"] = conn.account;
- if (identity && conn.user) headers["X-OpenViking-User"] = conn.user;
- if (conn.peerId) headers["X-OpenViking-Actor-Peer"] = conn.peerId;
- if (conn.userAgent) headers["User-Agent"] = conn.userAgent;
- return headers;
+ return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity });
}
export function serverErrorMessage(probe) {
@@ -780,7 +762,7 @@ export function gitignoreHidesWorkspaceConfig(root) {
* provenance is how a user finds out which layer actually won, the way
* `git config --show-origin --show-scope` does.
*/
-export function checkWorkspace(report, { cwd = process.cwd(), env = process.env } = {}) {
+export function checkWorkspace(report, { cwd = process.cwd(), env = process.env, clientVersion = "" } = {}) {
report.section("Workspace");
const { root, rootKind, git } = findWorkspaceRoot(cwd, env);
@@ -794,7 +776,7 @@ export function checkWorkspace(report, { cwd = process.cwd(), env = process.env
const foundBy = rootKind === "git" ? git.kind : `${TEAM_FILE}${git ? ` inside ${git.kind}` : ""}`;
report.ok(`workspace ${homeShort(root)} ← ${foundBy}`);
- const resolved = resolveWorkspaceSettings(cwd, env);
+ const resolved = resolveWorkspaceSettings(cwd, env, { clientVersion });
summary.settings = resolved.settings;
summary.provenance = resolved.provenance;
const identity = resolveWorkspaceIdentity({ cwd, env });
@@ -915,7 +897,13 @@ export function existsPath(path) {
// `openviking-server doctor`, which runs in the server's Python environment.
// ---------------------------------------------------------------------------
-const PLUGIN_ONLY_OV_CONF_KEYS = { claude_code: "ovcli.conf plugin.claude_code", codex: "ovcli.conf plugin.codex" };
+// Every harness reads the ov.conf section named after it, so every one of
+// those names is a block a user may have written and the server refuses.
+const PLUGIN_ONLY_OV_CONF_KEYS = Object.fromEntries(
+ Object.values(HARNESS_KEYS)
+ .filter((key) => key !== "openclaw")
+ .map((key) => [key, `ovcli.conf plugin.${key}`]),
+);
const READY_OK_VALUES = new Set(["ok", "not_configured", "not_supported"]);
const READY_FIXES = {
embedding: "the server cannot embed with the configured provider — check embedding.dense.{provider,model,api_key,api_base} in ov.conf; `openviking-server doctor` shows the provider's reply",
@@ -1094,3 +1082,363 @@ export async function checkServerHealth(report, { baseUrl, ovConf, health, offli
else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;
return summary;
}
+
+// ---------------------------------------------------------------------------
+// Configuration segments
+//
+// The "Configuration" section is host-composed: these are the parts every
+// harness reports identically, called in order, with the host slotting its own
+// lines in between (Claude Code's enable verdict, Codex's credential-source
+// block). Each segment takes the harness spec `runDoctor` already carries.
+// ---------------------------------------------------------------------------
+
+/** ovcli.conf and ov.conf: where they are, whether they parse, what sits in them. */
+export function inspectConfigFiles(report, { harness = "", launcherHint = "this harness" } = {}) {
+ const key = harnessKey(harness);
+ const cliConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf")));
+ const ovConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf")));
+
+ for (const [label, conf] of [["ovcli.conf", cliConf], ["ov.conf", ovConf]]) {
+ if (!conf.exists) {
+ report.info(`${label}: ${homeShort(conf.path)} not present`);
+ continue;
+ }
+ if (!conf.ok) {
+ report.fail(`${label} cannot be parsed — the plugin treats it as absent`, `${homeShort(conf.path)}: ${conf.error}`, "fix the JSON (a trailing comma or comment is enough to break it)");
+ continue;
+ }
+ report.ok(`${label}: ${homeShort(conf.path)} (mode ${conf.mode}, ${fmtBytes(conf.size)})`);
+ if (label === "ov.conf") {
+ if (key && conf.data[key]) report.info(`ov.conf has a legacy ${key} block (still honoured; prefer ovcli.conf plugin.${key} or env vars)`);
+ continue;
+ }
+ if (conf.mode !== "600" && conf.mode !== "400") report.warn("ovcli.conf is not private", `mode ${conf.mode}; it holds the api key`, `chmod 600 ${homeShort(conf.path)}`);
+ const unknown = unknownOvcliKeys(conf.data);
+ if (unknown.length) report.warn("ovcli.conf has keys nobody reads", unknown.join(", "), "typos such as apiKey/base_url/token are silently ignored — use url, api_key, account, user");
+ // `plugin` is on the ovcli allowlist, so nothing inside it is checked
+ // there — a misspelled knob would just sit doing nothing.
+ for (const { key: knob, suggestion } of unknownPluginKeys(conf.data.plugin)) {
+ report.warn(`ovcli.conf ${knob} is not a knob any plugin reads`, "", suggestion ? `did you mean ${suggestion}?` : "remove it, or check the plugin README for the knob you meant");
+ }
+ if (conf.data.extra_headers && Object.keys(conf.data.extra_headers).some((h) => /^x-api-key$/i.test(h))) {
+ report.warn("ovcli.conf extra_headers sets X-API-Key", "the server prefers X-API-Key over Authorization: Bearer, so it shadows api_key");
+ }
+ const sections = Object.keys(conf.data.plugin || {}).filter((k) => HARNESS_CONFIG_KEYS.has(k));
+ const others = sections.filter((k) => harnessKey(k) !== key);
+ if (key && others.length && !sections.some((k) => harnessKey(k) === key)) {
+ report.info(`ovcli.conf ${others.map((k) => `plugin.${k}`).join(", ")} settings do not apply to ${launcherHint} (use plugin.${key})`);
+ }
+ }
+ return { cliConf, ovConf };
+}
+
+/**
+ * Where each resolved credential came from, as one label per field.
+ *
+ * The key's layer is not re-derived here: `buildPluginConfig` already answered
+ * it in `apiKeySource`, and three doctors reconstructing that walk by hand is
+ * three chances to describe a chain nobody runs. What the files are still asked
+ * is which field inside the winning layer holds the value, because the layer
+ * alone cannot tell `plugin.<harness>.apiKey` from `api_key`, or a harness
+ * block from `server.root_api_key`.
+ *
+ * The identity has no such answer to read, so account and user follow the chain
+ * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * at that file's `plugin` section, and otherwise the environment wins and
+ * ov.conf's harness block is last.
+ */
+export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(cfg.harness || "") } = {}) {
+ const env = process.env;
+ const cliShort = homeShort(cliConf.path);
+ const ovShort = homeShort(ovConf.path);
+ const cli = cliConf.ok ? cliConf.data : {};
+ const ov = ovConf.ok ? ovConf.data : {};
+ const plugin = cli.plugin || {};
+ const scoped = (section && plugin[section]) || {};
+ const block = (section && ov[section]) || {};
+ const server = ov.server || {};
+ // Pinned to ovcli.conf, the chain never looks at the environment.
+ const pinned = cfg.credentialSource === "ovcli";
+
+ const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
+ const url = (!pinned && envUrl) ? "env"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+
+ let apiKey;
+ if (cfg.apiKeySource === "env") {
+ apiKey = env.OPENVIKING_BEARER_TOKEN ? "env OPENVIKING_BEARER_TOKEN" : "env OPENVIKING_API_KEY";
+ } else if (cfg.apiKeySource === "ovcli") {
+ apiKey = cli.api_key ? cliShort
+ : scoped.apiKey ? `${cliShort} plugin.${section}.apiKey`
+ : plugin.apiKey ? `${cliShort} plugin.apiKey` : cliShort;
+ } else if (cfg.apiKeySource === "ov") {
+ apiKey = block.apiKey ? `${ovShort} ${section}.apiKey`
+ : server.root_api_key ? `${ovShort} server.root_api_key` : ovShort;
+ } else if (cfg.apiKeySource === "host") {
+ apiKey = "the host application";
+ } else {
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ }
+
+ const identity = (envName, cliValue, name) => (
+ (!pinned && env[envName]) ? "env"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ );
+ return {
+ url,
+ apiKey,
+ account: identity("OPENVIKING_ACCOUNT", cli.account || cli.account_id, "accountId"),
+ user: identity("OPENVIKING_USER", cli.user || cli.user_id, "userId"),
+ };
+}
+
+/**
+ * The resolved url, key and identity, each with the source it came from.
+ * `sources` is the host's own credential chain rendered as one label per field.
+ */
+export function reportCredentials(report, cfg, sources, { account = "", user = "" } = {}) {
+ report.info(`url ${cfg.baseUrl} ← ${sources.url}`);
+ for (const p of lintBaseUrl(cfg.baseUrl)) report[p.level](p.message, "", p.fix);
+ if (sources.url.startsWith("default") && !isLoopbackUrl(cfg.baseUrl)) report.info("url fell back to the built-in default");
+ else if (sources.url.startsWith("default")) report.warn("no url configured — using the built-in default http://127.0.0.1:1933", "only right when the server runs on this machine", "set url in ovcli.conf or OPENVIKING_URL");
+
+ const keyInfo = describeApiKey(cfg.apiKey);
+ report.info(`api_key ${keyInfo.display} ← ${sources.apiKey}`);
+ for (const p of keyInfo.problems) report.warn(`api key ${p}`, "", "re-copy the key exactly as issued");
+ if (sources.apiKey.includes("root_api_key")) {
+ report.warn("api key falls back to ov.conf server.root_api_key", "the root key is refused on tenant data APIs and /mcp in api_key mode; against a remote server it is simply the wrong key",
+ "put a user/admin key in ovcli.conf api_key (or OPENVIKING_API_KEY)");
+ }
+ if (!keyInfo.present && !isLoopbackUrl(cfg.baseUrl)) report.warn("no api key configured for a non-local server", "", "set api_key in ovcli.conf or OPENVIKING_API_KEY");
+ report.info(`account ${account || "(unset)"} ← ${sources.account}`);
+ report.info(`user ${user || "(unset)"} ← ${sources.user}`);
+ if (keyInfo.format === "v2") {
+ if (account && keyInfo.account && account !== keyInfo.account) report.warn(`configured account '${account}' differs from the key's account '${keyInfo.account}'`, "in api_key mode the key wins");
+ if (user && keyInfo.user && user !== keyInfo.user) report.warn(`configured user '${user}' differs from the key's user '${keyInfo.user}'`, "in api_key mode the key wins");
+ }
+ return keyInfo;
+}
+
+/** The peer this directory sends, where it came from, and what it costs when there is none. */
+export function reportPeer(report, cfg, { cwd = process.cwd() } = {}) {
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ report.info(`peer ${peer.peerId || "(none)"} ← ${peer.source} (${peer.origin})`);
+ if (peer.origin === "unresolved") {
+ report.info(
+ "no peer is sent: this directory is in no git repository, so its memories go to your user-level space",
+ `to give it a memory of its own, create .openviking/config.json here with ${WORKSPACE_PEER_HINT}`,
+ );
+ } else if (peer.source === "none") {
+ report.warn(
+ "no peer is sent, so recall defaults to every memory under this user",
+ "sending a peer narrows the search to this workspace",
+ 'unset OPENVIKING_WORKSPACE_PEER, or set peer.source to "git"',
+ );
+ }
+ if (peer.legacyPeerId) {
+ report.info(
+ `previous peer ${peer.legacyPeerId}`,
+ cfg.recallPeerScope === "actor"
+ ? "recall asks it separately, because peer_scope actor turns off the server's cross-peer sweep"
+ : "already covered by the server's cross-peer sweep under peer_scope all",
+ );
+ }
+ for (const p of lintPeerScopeDowngrade()) report[p.level](p.message, p.detail, p.fix);
+ return peer;
+}
+
+const TIMEOUT_LABELS = { timeoutMs: "request", recallTimeoutMs: "recall", captureTimeoutMs: "capture" };
+
+/**
+ * The timeouts line and the hook-budget check. `timeoutBudgets` maps a hook
+ * event to the knob that governs the request inside it, so each harness names
+ * the knob its own recall and capture paths actually read — a request that
+ * outlives its hook is killed by the host before it can answer.
+ *
+ * `hooksTemplate` names the template when it does not sit at the plugin root,
+ * and an entry states its timeout either directly or one nesting level down.
+ */
+export function reportTimeouts(report, cfg, { pluginRoot = "", hooksTemplate = "", launcherHint = "the harness", timeoutBudgets = {} } = {}) {
+ const knobs = [...new Set(["timeoutMs", ...Object.values(timeoutBudgets)])];
+ report.info(`timeouts ${knobs.map((knob) => `${cfg[knob]}ms ${TIMEOUT_LABELS[knob] || knob}`).join(", ")}; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);
+
+ const hooks = tryJson(hooksTemplate || join(pluginRoot, "hooks", "hooks.json"))?.hooks || {};
+ for (const [event, knob] of Object.entries(timeoutBudgets)) {
+ const entry = hooks[event]?.[0];
+ const budget = Number(entry?.hooks?.[0]?.timeout ?? entry?.timeout) * 1000 || 0;
+ if (!budget || !(cfg[knob] > budget)) continue;
+ report.warn(`${TIMEOUT_LABELS[knob] || knob} timeout ${cfg[knob]}ms exceeds the ${event} hook budget ${budget}ms`,
+ `${launcherHint} kills the hook before the request can finish`,
+ `lower ${KNOB_BY_NAME.get(knob)?.env || knob}`);
+ }
+}
+
+/** The switches that decide whether anything is injected at all. */
+export function reportToggles(report, cfg, { harness = "" } = {}, toggles = []) {
+ report.info(`toggles ${toggles.join(", ")}`);
+ if (!cfg.autoRecall || !cfg.autoCapture || cfg.noAutoInject) {
+ report.warn("one or more injection paths are switched off", toggles.join(", "),
+ `check OPENVIKING_AUTO_RECALL / OPENVIKING_AUTO_CAPTURE / OPENVIKING_NO_AUTO_INJECT and ovcli.conf plugin.${harnessKey(harness)}`);
+ }
+}
+
+/**
+ * Where the hooks log, and what the environment does to them. `extra` adds the
+ * host's own reading of the OPENVIKING_* vars it found.
+ */
+export function sweepEnv(report, cfg, { launcherHint = "the harness" } = {}, extra) {
+ report.info(`debug log ${cfg.debug ? "on" : "off"} → ${homeShort(cfg.debugLogPath)}${cfg.debug ? "" : ` (set OPENVIKING_DEBUG=1 in ${launcherHint}'s environment to record hook errors)`}`);
+
+ const env = collectEnv();
+ if (env.openviking.length) {
+ report.info("OPENVIKING_* in this environment", env.openviking.map((e) => `${e.name}=${e.value}`).join("\n"));
+ if (extra) extra(report, env);
+ } else {
+ report.info("no OPENVIKING_* environment variables set");
+ }
+ if (env.proxy.length) {
+ report.warn(`proxy variables set: ${env.proxy.map((e) => e.name).join(", ")}`,
+ "Node's fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY=1 (Node 24+); curl honours them, so curl may succeed while hooks fail",
+ isLoopbackUrl(cfg.baseUrl) ? "harmless for a local server" : `set NODE_USE_ENV_PROXY=1 (or reach the server without the proxy) in the environment that launches ${launcherHint}`);
+ }
+ if (env.node.length) report.info(`node TLS/proxy env: ${env.node.map((e) => `${e.name}=${e.value}`).join(", ")}`);
+ if (/^https:/i.test(cfg.baseUrl) && env.node.some((e) => e.name === "NODE_TLS_REJECT_UNAUTHORIZED" && e.value === "0")) {
+ report.warn("NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate checks", "", "prefer NODE_EXTRA_CA_CERTS=<ca.pem>");
+ }
+ return env;
+}
+
+// ---------------------------------------------------------------------------
+// The run
+// ---------------------------------------------------------------------------
+
+export function parseArgs(argv) {
+ const opts = { json: false, offline: false, timeoutMs: 5000, color: process.stdout.isTTY && !process.env.NO_COLOR };
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === "--json") opts.json = true;
+ else if (arg === "--offline" || arg === "--no-network") opts.offline = true;
+ else if (arg === "--no-color") opts.color = false;
+ else if (arg === "--timeout") opts.timeoutMs = Math.max(1000, Number(argv[++i]) || 5000);
+ else if (arg === "-h" || arg === "--help") {
+ console.log("usage: ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]");
+ process.exit(0);
+ }
+ }
+ if (opts.json) opts.color = false;
+ return opts;
+}
+
+export function expandHome(p) {
+ return p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p;
+}
+
+export function tryJson(path) {
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The "Environment" section. `launcherHint` names the host in the prose ("the
+ * environment that launches Claude Code"); `onCliFound` lets a host report its
+ * CLI its own way and add probes of its own between the version line and the
+ * platform line.
+ */
+export function checkEnvironment(report, { cliName, cliVersionArgs = ["--version"], launcherHint, nodePathFix, onCliFound } = {}) {
+ report.section("Environment");
+ const nodeMajor = parseNodeMajor(process.version);
+ const nodePath = process.execPath;
+ if (nodeMajor >= 18) report.ok(`node ${process.version} (${nodePath})`);
+ else report.fail(`node ${process.version} is too old`, "hooks and the MCP proxy need Node.js 18+ (global fetch)", "install Node.js 18 or newer and make sure it is first on PATH");
+ const nodeOnPath = whichCommand("node");
+ if (!nodeOnPath) {
+ report.warn("`node` is not on PATH for this process",
+ `hooks and .mcp.json invoke the bare command \`node\`; if ${launcherHint} was launched without your shell profile (nvm/volta/fnm), hooks never start`,
+ nodePathFix || `put node on PATH for the environment that launches ${launcherHint}`);
+ } else if (resolvePath(nodeOnPath) !== resolvePath(nodePath)) {
+ report.info(`PATH resolves node to ${nodeOnPath} (this run used ${nodePath})`);
+ }
+
+ const cli = runCommand(cliName, cliVersionArgs, { timeoutMs: 15000 });
+ if (cli.ok) {
+ if (onCliFound) onCliFound(report, cli);
+ else report.ok(cli.stdout.split("\n")[0]);
+ } else {
+ report.info(`${cliName} CLI not found on PATH (${cli.error || "?"}) — install checks that need it are skipped`);
+ }
+ report.info(`platform ${process.platform} ${process.arch}, cwd ${homeShort(process.cwd())}`);
+ return { cliOnPath: cli.ok };
+}
+
+/**
+ * The "Connection" section. `account`/`user` are the configured identity: they
+ * only reach the wire when the harness sends identity headers, but the probe
+ * report compares them against what the key claims either way. `onSummary`
+ * carries the host's verdict on the answer (Codex compares auth modes).
+ */
+export async function checkConnection(report, cfg, { keyInfo, peer, account = "", user = "" }, opts, { onSummary } = {}) {
+ report.section("Connection");
+ if (opts.offline) {
+ report.info("skipped (--offline)");
+ return null;
+ }
+ const conn = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, account: cfg.sendIdentityHeaders ? account : "", user: cfg.sendIdentityHeaders ? user : "", peerId: peer.peerId, userAgent: cfg.userAgent };
+ const probes = await probeOpenViking(conn, { timeoutMs: opts.timeoutMs });
+ const summary = assessProbes(report, probes, { ...conn, account, user }, keyInfo);
+ if (onSummary) onSummary(report, summary, cfg);
+ return { probes, summary };
+}
+
+/**
+ * Run one harness's doctor. `host` is the harness spec: the `checkEnvironment`
+ * fields above, `loadConfig()`, the three sections only the host can produce
+ * (`checkInstall`, `checkConfig`, `checkActivity`), `resolveIdentity(cfg)` for
+ * the account/user spelling that harness uses, and optionally `onSummary` and
+ * `extraResolved(cfg)` for extra `--json` fields. `checkConfig` is handed the
+ * spec back, because the configuration segments it composes are driven by it.
+ */
+export async function runDoctor(host) {
+ const opts = parseArgs(process.argv.slice(2));
+ const report = createReport({ color: opts.color });
+ const envInfo = checkEnvironment(report, host);
+ host.checkInstall(report, envInfo);
+ const cfg = host.loadConfig();
+ const configInfo = host.checkConfig(report, cfg, host);
+ const workspace = checkWorkspace(report, { clientVersion: cfg.clientVersion });
+ const identity = host.resolveIdentity(cfg);
+ const connection = await checkConnection(report, cfg, { ...configInfo, ...identity }, opts, host);
+ const serverHealth = await checkServerHealth(report, { baseUrl: cfg.baseUrl, ovConf: configInfo.ovConf, health: connection?.probes?.health, offline: opts.offline, timeoutMs: opts.timeoutMs });
+ host.checkActivity(report, cfg, connection);
+
+ if (opts.json) {
+ console.log(JSON.stringify({
+ harness: host.harness,
+ pluginRoot: host.pluginRoot,
+ generatedAt: new Date().toISOString(),
+ resolved: {
+ baseUrl: cfg.baseUrl,
+ apiKey: configInfo.keyInfo.display,
+ apiKeyFormat: configInfo.keyInfo.format,
+ account: identity.account,
+ user: identity.user,
+ peerId: configInfo.peer.peerId,
+ ...(host.extraResolved ? host.extraResolved(cfg) : {}),
+ },
+ workspace,
+ server: connection?.summary || null,
+ serverHealth,
+ ...report.toJSON(),
+ }, null, 2));
+ } else {
+ console.log(report.render());
+ }
+ process.exitCode = report.exitCode();
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
index 24d33d9fb..dd11897ee 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-config.mjs
@@ -86,7 +86,9 @@ function uniq(values) {
* `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
* user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
* harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
+ * deduplicated. `sendIdentityHeaders` carries the harness's resolved auth mode
+ * so an `api_key` server, which reads the identity out of the key and ignores
+ * the headers, never sees the operator's account and user on the wire.
*/
export function buildMcpProxyConfig({
baseUrl = "",
@@ -94,6 +96,7 @@ export function buildMcpProxyConfig({
apiKey = "",
account = "",
user = "",
+ sendIdentityHeaders = false,
peerId = "",
userAgent = "",
timeoutMs,
@@ -109,6 +112,7 @@ export function buildMcpProxyConfig({
apiKey: apiKey || "",
account: account || "",
user: user || "",
+ sendIdentityHeaders: sendIdentityHeaders === true,
peerId: peerId || "",
userAgent: userAgent || "",
timeoutMs: Math.max(
diff --git a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs
index 9a8f5ba26..de11c2879 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/mcp-proxy-core.mjs
@@ -9,6 +9,8 @@
import { statSync } from "node:fs";
import { createInterface } from "node:readline";
+import { buildOvHeaders } from "./ov-http.mjs";
+
const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
const DELETE_TIMEOUT_MS = 2000;
const MAX_CONCURRENT_REQUESTS = 16;
@@ -240,21 +242,17 @@ export function createOpenVikingMcpProxy({
}
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;
+ return buildOvHeaders(proxyConfig, {
+ actorPeerId: proxyConfig.peerId,
+ extraHeaders: {
+ "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,
+ ...(includeSession && sessionId ? { "Mcp-Session-Id": sessionId } : {}),
+ },
+ });
}
function writeMessage(obj) {
diff --git a/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs b/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs
new file mode 100644
index 000000000..e02f5316e
--- /dev/null
+++ b/examples/claude-code-memory-plugin/scripts/shared/ov-http.mjs
@@ -0,0 +1,112 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * The one path from a hook to the OpenViking server.
+ *
+ * Every harness used to own its own AbortController, header block and envelope
+ * parser, and they drifted: one sent the api key twice, one named the operator
+ * to every proxy on the path whether or not the server was trusted with it, one
+ * read a different field for the same account. A server-side change now lands
+ * in one place instead of eight.
+ *
+ * `X-API-Key` is deliberately absent. The server takes `Authorization: Bearer`,
+ * and the identity headers go out only when the resolved config says this
+ * server is trusted with the operator's name.
+ */
+
+// A request that aborts the instant it starts reads as a dead server. A config
+// that asks for less than a second gets a second.
+const MIN_TIMEOUT_MS = 1000;
+
+/**
+ * The headers every harness puts on every OpenViking request.
+ *
+ * `identityHeaders` overrides `cfg.sendIdentityHeaders` for the callers that
+ * decide per request rather than per config — the doctor probes both ways.
+ */
+export function buildOvHeaders(cfg = {}, { actorPeerId = "", identityHeaders, extraHeaders } = {}) {
+ const identity = identityHeaders === undefined ? Boolean(cfg.sendIdentityHeaders) : Boolean(identityHeaders);
+ const headers = { "Content-Type": "application/json" };
+ if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
+ if (identity && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (identity && cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
+ if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ return { ...headers, ...extraHeaders };
+}
+
+function responseTraceId(body) {
+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
+}
+
+/**
+ * Build the `fetchJSON(path, init, { timeoutMs, actorPeerId })` a harness talks
+ * through. It resolves to `{ ok, status, result, error, traceId }` and never
+ * throws: a hook that crashes on a closed port would take its host's turn with
+ * it, so a network error is `{ ok: false, status: 0 }` and the retry rules in
+ * `retryable.mjs` decide what happens next.
+ *
+ * `resolveActorPeerId` is a callback because Codex only knows its peer after
+ * loading session state under the lock, well after the client is built.
+ * `requireJsonBody` is for the capture hooks, which would rather retry a body
+ * they cannot parse than record the turn as sent.
+ */
+export function createOvHttp(cfg = {}, {
+ defaultTimeoutMs = 0,
+ resolveActorPeerId = () => "",
+ identityHeaders,
+ extraHeaders,
+ requireJsonBody = false,
+} = {}) {
+ // dsh and pi name this field `endpoint`; every other harness names it `baseUrl`.
+ const baseUrl = cfg.baseUrl || cfg.endpoint || "";
+ return async function fetchJSON(path, init = {}, options = {}) {
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0);
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ try {
+ const headers = {
+ ...buildOvHeaders(cfg, {
+ actorPeerId: options.actorPeerId ?? resolveActorPeerId(),
+ identityHeaders,
+ extraHeaders,
+ }),
+ ...(init.headers || {}),
+ };
+ const response = await fetch(`${baseUrl}${path}`, { ...init, headers, signal: controller.signal });
+ const body = await response.json().catch(() => null);
+ if (requireJsonBody && !body) {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: { message: "empty or invalid JSON response" },
+ };
+ }
+ const traceId = responseTraceId(body);
+ if (!response.ok || body?.status === "error") {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: body?.error || { message: `HTTP ${response.status}` },
+ traceId,
+ };
+ }
+ return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId };
+ } catch (error) {
+ const message = error?.message || String(error);
+ // This module owns the controller, so it says a timeout was a timeout
+ // rather than leaving callers to guess it from whatever fetch threw.
+ const failure = timedOut
+ ? { name: "AbortError", aborted: true, message }
+ : { message };
+ return { ok: false, status: 0, result: null, error: failure };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
index 7cbaba5ba..cbae04ab8 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/plugin-config.mjs
@@ -19,18 +19,24 @@
* Resolution stays env → ovcli.conf plugin.<harness> → ovcli.conf plugin →
* ov.conf harness section (legacy) → defaults.
*
- * Consumers: Claude Code and Codex only. The other harnesses ship this module
- * through `sync.mjs` but still read their knobs from the environment, so a
- * `plugin` entry named after them is inert. `HARNESS_KEYS` lists what a harness
- * loader actually consumes today — add a key here as its loader starts calling
- * `loadPluginSettings`, not before, so the section never promises a knob that
- * silently does nothing.
+ * Every harness resolves through `resolveSettings()` below, and assembles its
+ * whole configuration through `buildPluginConfig()`, so one `plugin` section
+ * configures all of them and `ov config switch` moves behaviour along with
+ * credentials. The knobs themselves are declared once in `config-schema.mjs`;
+ * this module decides which files supply them and what is derived from them.
*/
-import { readFileSync } from "node:fs";
import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
+import { join } from "node:path";
+import { HARNESS_KEYS, KNOBS, harnessKey, resolveKnobs } from "./config-schema.mjs";
+import {
+ buildUserAgent,
+ loadCredentialFiles,
+ readManifestVersion,
+ resolveAuthMode,
+ resolveOpenVikingCredentials,
+} from "./credentials.mjs";
import {
announcedOverrides,
loadWorkspaceLayers,
@@ -39,33 +45,27 @@ import {
projectWorkspaceSettings,
} from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId, resolvePluginPeerId } from "./workspace-peer.mjs";
import { readEntry } from "./workspace-registry.mjs";
-const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
-
-export const HARNESS_KEYS = {
- claudeCode: "claude_code",
- codex: "codex",
-};
+const OVCLI_LAYER = "ovcli.conf";
+const OV_CONF_LAYER = "ov.conf";
-function tryLoadJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return null;
- }
-}
+export { HARNESS_KEYS, harnessKey };
/**
* Merge the shared plugin section with the harness-specific override.
* Returns a flat settings object; unknown keys pass through untouched so a
* harness can add its own knobs without touching this module.
+ *
+ * `cliFile` is ovcli.conf already parsed. Callers that have it hand it over so
+ * the file is read once per build and, more importantly, so the `plugin`
+ * section comes out of the same file the credential chain read — an
+ * `OPENVIKING_CONFIG_FILE` that is ovcli-shaped is ovcli.conf, and only
+ * `loadCredentialFiles` knows that.
*/
export function loadPluginSettings(harness, env = process.env, options = {}) {
- const path = resolvePath(
- (env.OPENVIKING_CLI_CONFIG_FILE || DEFAULT_OVCLI_CONF_PATH).replace(/^~/, homedir()),
- );
- const file = tryLoadJson(path);
+ const file = options.cliFile || loadCredentialFiles(env).cliFile;
const plugin = file && typeof file.plugin === "object" && file.plugin ? file.plugin : {};
const shared = {};
@@ -73,9 +73,14 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
if (value && typeof value === "object" && !Array.isArray(value)) continue;
shared[key] = value;
}
- const scoped = harness && plugin[harness] && typeof plugin[harness] === "object"
- ? plugin[harness]
- : {};
+ // Both spellings of the harness name find the same override, so copying
+ // `claude-code` out of the installer is not a silent no-op.
+ const key = harnessKey(harness);
+ const scoped = {};
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ const value = candidate && plugin[candidate];
+ if (value && typeof value === "object" && !Array.isArray(value)) Object.assign(scoped, value);
+ }
const settings = { ...shared, ...scoped };
const cwd = String(options.cwd || "").trim();
@@ -83,6 +88,32 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
return { ...settings, ...resolveWorkspaceSettings(cwd, env, options).settings };
}
+/**
+ * Every knob for one harness, resolved through the whole layer stack.
+ *
+ * `legacy` is that harness's section in ov.conf, which is where tuning used to
+ * live: it stays the lowest configured layer so an existing deployment keeps
+ * working, and everything above it comes from files a client may edit.
+ *
+ * Returns the settings, the names some layer actually supplied (what the
+ * `*Configured` flags report), and the raw ovcli.conf merge — a couple of
+ * callers still need to know a value came from ovcli.conf rather than ov.conf.
+ */
+export function resolveSettings(harness, options = {}) {
+ const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options;
+ const key = harnessKey(harness);
+ const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile });
+ const { settings, configured, sources } = resolveKnobs({
+ harness: key,
+ layers: [
+ { name: OV_CONF_LAYER, data: legacy },
+ { name: OVCLI_LAYER, data: plugin },
+ ],
+ env,
+ });
+ return { settings, configured, sources, plugin };
+}
+
/**
* The workspace layers for one cwd, flattened into harness knobs.
*
@@ -122,6 +153,169 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion
}
}
+const SEND_ONLY_WHEN_CONFIGURED = KNOBS.filter((knob) => knob.sendOnlyWhenConfigured);
+
+function str(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : "";
+}
+
+/** The ov.conf block named after this harness, the lowest layer of every chain. */
+function ovConfSection(ovFile, key) {
+ const section = key ? ovFile?.[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+/**
+ * A connection value ovcli.conf's `plugin` section supplied, as opposed to
+ * ov.conf's harness block or the environment — the credential chain ranks
+ * those two itself, and would rank a `plugin` value wrong.
+ */
+function fromPluginSection(settings, sources, name) {
+ return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
+}
+
+/**
+ * One harness's whole configuration: the files, the knobs, the peer, and the
+ * handful of fields derived from them.
+ *
+ * Every loader used to write this sequence out by hand and each wrote a
+ * slightly different subset, which is how ov.conf's `<harness>.authMode` came
+ * to apply on three harnesses only, and why two of the four knobs the server
+ * defaults for itself were reported as configured on two harnesses and nowhere
+ * else. What is left in a loader after this call is what only that harness
+ * knows.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
+ * host hands it one of its own); `hostInput` is what an embedding host named
+ * for this process, which is the more specific answer and outranks every file;
+ * `logFile` is the log basename this harness has always used, and a harness
+ * that never had a default log path does not get one invented for it;
+ * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * pinning and has always ended at `server.root_api_key`.
+ */
+export function buildPluginConfig(harness, {
+ cwd = "",
+ env = process.env,
+ legacy = null,
+ manifestUrl = "",
+ version = "",
+ hostInput = {},
+ logFile = "",
+ rootKeyFallback = false,
+ deriveEffectivePeer = false,
+} = {}) {
+ const name = String(harness || "");
+ const key = harnessKey(name);
+ const workspaceCwd = str(cwd) || process.cwd();
+ const files = loadCredentialFiles(env);
+ // The version answers two questions: what the User-Agent reports, and whether
+ // a workspace file asking for a newer client gets to say so.
+ const clientVersion = str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "");
+ const { settings, configured, sources } = resolveSettings(key, {
+ env,
+ cwd: workspaceCwd,
+ legacy: legacy || ovConfSection(files.ovFile, key),
+ cliFile: files.cliFile,
+ clientVersion,
+ });
+ const credentials = resolveOpenVikingCredentials(env, key, {
+ apiKey: fromPluginSection(settings, sources, "apiKey"),
+ accountId: fromPluginSection(settings, sources, "accountId"),
+ userId: fromPluginSection(settings, sources, "userId"),
+ });
+
+ // Pinned to ovcli.conf, the credential chain stops at that file. The layers
+ // under it still answer: ov.conf's harness block is where tuning used to
+ // live, and `server.root_api_key` is where a harness that predates the
+ // pinning has always ended its chain.
+ let apiKey = credentials.apiKey;
+ let apiKeySource = credentials.apiKeySource;
+ let credentialPath = credentials.credentialPath;
+ if (!apiKey) {
+ apiKey = sources.apiKey === OV_CONF_LAYER
+ ? str(settings.apiKey)
+ : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+ const hostApiKey = str(hostInput.apiKey);
+ if (hostApiKey) {
+ apiKey = hostApiKey;
+ apiKeySource = "host";
+ credentialPath = "";
+ }
+
+ const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
+ const baseUrl = hostBaseUrl || credentials.baseUrl;
+ const account = str(hostInput.account) || credentials.account;
+ const user = str(hostInput.user) || credentials.user;
+ const timeoutMs = settings.timeoutMs;
+ const peerId = resolvePluginPeerId({
+ settings,
+ configured,
+ sources,
+ credentials,
+ hostInput: hostInput.peerId,
+ env,
+ });
+
+ const config = {
+ ...settings,
+ harness: name,
+ clientVersion,
+ userAgent: buildUserAgent(name, clientVersion),
+
+ baseUrl,
+ mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
+ apiKey,
+ account,
+ user,
+ ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ configPath: credentials.cliPath || credentials.ovPath || null,
+ cliConfigPath: credentials.cliPath,
+ ovConfigPath: credentials.ovPath,
+ cliPath: credentials.cliPath,
+ ovPath: credentials.ovPath,
+
+ peerId,
+ explicitPeerId: peerId,
+
+ // A write gets a longer budget than a read, and a digest has to finish
+ // inside the recall request it belongs to, so both fall back to a knob.
+ captureTimeoutMs: settings.captureTimeoutMs || Math.max(timeoutMs * 2, 30000),
+ recallCompressTimeoutMs: settings.recallCompressTimeoutMs
+ || Math.max(1000, settings.recallTimeoutMs - 10000),
+ debugLogPath: settings.debugLogPath
+ || (logFile ? join(homedir(), ".openviking", "logs", logFile) : ""),
+
+ // The spellings these fields carried before every harness shared a loader.
+ endpoint: baseUrl,
+ accountId: account,
+ userId: user,
+ requestTimeoutMs: timeoutMs,
+ };
+ for (const knob of SEND_ONLY_WHEN_CONFIGURED) {
+ config[`${knob.name}Configured`] = configured.has(knob.name);
+ }
+
+ // Only for the harnesses that resolve the peer once at load. The rest derive
+ // it per session, against the directory the payload names, and an MCP proxy
+ // must not derive one from wherever it happened to be launched.
+ if (deriveEffectivePeer) {
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ config.effectivePeer = effectivePeer;
+ config.legacyPeerId = effectivePeer.legacyPeerId;
+ }
+ return config;
+}
+
const REWRITE_MODES = new Set(["off", "client", "server", "auto"]);
/**
diff --git a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
index 72835de8f..4695a887b 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/recall-core.mjs
@@ -31,6 +31,28 @@ const CODING_QUOTA_WEIGHTS = {
let userSpaceCache = "";
+/**
+ * Is recall on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoRecall`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables recall under an older name still disables it.
+ */
+export function isRecallEnabled(cfg = {}) {
+ return isSwitchOn([cfg.enabled, cfg.autoRecall, cfg.recall, cfg.syncRecall]);
+}
+
+/** Any recognised spelling that says off wins; everything else means on. */
+function isSwitchOn(values) {
+ for (const value of values) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function estimateTokens(text) {
return text ? Math.ceil(String(text).length / 4) : 0;
}
@@ -338,9 +360,8 @@ async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
}
async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
- if (items.length === 0) return null;
-
- let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const budgetTotal = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ let budgetRemaining = budgetTotal;
const lines = [
"<openviking-context>",
"Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
@@ -373,15 +394,15 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =
lines.push("</openviking-context>");
- const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ const budgetUsed = budgetTotal - budgetRemaining;
log("recall_injection_built", {
contentItems: contentCount,
hintItems: hintCount,
budgetUsed,
- budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ budgetTotal,
});
- return lines.join("\n");
+ return { block: lines.join("\n"), contentCount, hintCount, budgetUsed, stage: "ranked" };
}
const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
@@ -626,8 +647,13 @@ export async function postRecall(fetchJSON, body, opts = {}) {
* `"actor"` that sweep is off by definition, so the old peer is asked for
* separately — as itself, which is both cheaper and wider than a bare
* cross-peer read (that would need the user id, and reaches memories only).
+ *
+ * `stage` names the path the block came from, which is what a host needs to
+ * tell "the server had nothing" (`no_results`) from "the score threshold
+ * dropped everything" (`filtered_out`) when the block is empty, and a
+ * `server_assembled` block from a `ranked` one when it is not.
*/
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+export async function buildRecallBlockDetailed(fetchJSON, cfg, query, options = {}) {
const primary = await recallForPeer(fetchJSON, cfg, query, options);
const legacyPeerId = String(options.legacyPeerId || "").trim();
@@ -636,16 +662,32 @@ export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
const log = options.log || (() => {});
const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
+ if (!legacy.block) return primary;
log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
+ return {
+ block: primary.block ? `${primary.block}\n${legacy.block}` : legacy.block,
+ contentCount: primary.contentCount + legacy.contentCount,
+ hintCount: primary.hintCount + legacy.hintCount,
+ budgetUsed: primary.budgetUsed + legacy.budgetUsed,
+ stage: primary.block ? primary.stage : legacy.stage,
+ };
+}
+
+/** The block alone, or null when nothing was injectable. */
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const { block } = await buildRecallBlockDetailed(fetchJSON, cfg, query, options);
+ return block || null;
+}
+
+function emptyRecall(stage) {
+ return { block: "", contentCount: 0, hintCount: 0, budgetUsed: 0, stage };
}
async function recallForPeer(fetchJSON, cfg, query, options = {}) {
const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
const log = options.log || (() => {});
const trimmed = String(query || "").trim();
- if (!trimmed) return null;
+ if (!trimmed) return emptyRecall("no_results");
// Assembly happens server-side when the deployment offers the context face;
// older servers fall through to /recall, then to raw find.
@@ -654,12 +696,23 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
actorPeerId,
log,
});
- if (serverBlock !== null) return serverBlock || null;
+ if (serverBlock !== null) {
+ if (!serverBlock) return emptyRecall("no_results");
+ // The server rendered one budgeted unit, so nothing here degraded to a
+ // URI-only hint and the block's own estimate is what it cost.
+ return {
+ block: serverBlock,
+ contentCount: 1,
+ hintCount: 0,
+ budgetUsed: estimateTokens(serverBlock),
+ stage: "server_assembled",
+ };
+ }
const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
const perSourceLimit = Math.max(recallLimit * 2, 8);
const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
- if (raw.length === 0) return null;
+ if (raw.length === 0) return emptyRecall("no_results");
const profile = buildQueryProfile(trimmed);
const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
@@ -673,6 +726,6 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
});
- if (picked.length === 0) return null;
+ if (picked.length === 0) return emptyRecall("filtered_out");
return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs
index cf57bf406..d90c3d5f3 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs
@@ -1,4 +1,8 @@
// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { readFileSync, realpathSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
const DEFAULT_URI_KEYS = [
"filePath",
"file_path",
@@ -76,3 +80,109 @@ export function buildGuardMessage(uri, hint = {}) {
if (example) lines.push(`Example: ${example}`);
return lines.join("\n");
}
+
+/** The hints a host gets when it names no table of its own. */
+export const DEFAULT_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}")`,
+ },
+};
+
+/**
+ * The guard decision for one tool call, or null when the call may proceed.
+ *
+ * `hints` carries the host's replacement tool names and example calls; `guarded`
+ * narrows which tool names the host guards at all, because the set is not the
+ * same everywhere — claude-code and opencode leave the shell alone (their
+ * matchers never see it), pi guards it.
+ */
+export function evaluateUriGuard(toolName, input = {}, { hints = DEFAULT_TOOL_HINTS, guarded } = {}) {
+ const name = normalizeToolName(toolName);
+ if (guarded && !guarded.has(name)) return null;
+ const hint = hints[name];
+ if (!hint) return null;
+ const uri = findVikingUri(input);
+ if (!uri) return null;
+ return {
+ uri,
+ reason: buildGuardMessage(uri, {
+ tool: hint.tool,
+ example: typeof hint.example === "function" ? hint.example(uri, input) : hint.example,
+ }),
+ };
+}
+
+/** The PreToolUse deny envelope claude-code, trae and zcode all read. */
+export function denyHookSpecificOutput(reason) {
+ return {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: reason,
+ },
+ };
+}
+
+/** Cursor's deny envelope; its shell hook also wants the reason for the agent. */
+export function denyCursorPermission(reason, { agentMessage = false } = {}) {
+ const output = { permission: "deny", user_message: reason };
+ if (agentMessage) output.agent_message = reason;
+ return output;
+}
+
+function readHookInput() {
+ try {
+ const raw = readFileSync(0, "utf8").trim();
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Run a guard as a hook process: read the event off stdin, print the envelope.
+ *
+ * A guard is also imported by its harness tests, so the body only runs when the
+ * module is the process entrypoint. An empty envelope prints nothing — every
+ * host treats unrecognized or empty output as "no opinion", and one of them
+ * rejects any key it does not know.
+ */
+function isEntrypoint(moduleUrl) {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(moduleUrl));
+ } catch {
+ return resolve(process.argv[1]) === fileURLToPath(moduleUrl);
+ }
+}
+
+export function runUriGuardHook(moduleUrl, evaluate) {
+ if (!isEntrypoint(moduleUrl)) return;
+ const output = evaluate(readHookInput());
+ if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);
+}
diff --git a/examples/claude-code-memory-plugin/scripts/shared/workspace-config.mjs b/examples/claude-code-memory-plugin/scripts/shared/workspace-config.mjs
index da741d2f2..1e4b4d9e6 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/workspace-config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/workspace-config.mjs
@@ -24,6 +24,7 @@
import { readFileSync, realpathSync, statSync } from "node:fs";
import { isAbsolute, join, relative } from "node:path";
+import { WORKSPACE_ENUMS, WORKSPACE_KNOB_MAP, WORKSPACE_RANGES } from "./config-schema.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE } from "./workspace-identity.mjs";
/**
@@ -95,37 +96,14 @@ export const FORBIDDEN_KEYS = [
*/
export const FREE_FORM_SECTIONS = ["labels"];
-const ENUMS = {
- "recall.peer_scope": ["all", "actor"],
- "peer.source": null, // free-form: preset name, template, or template array
-};
-
-const RANGES = {
- "recall.dedup_turns": { min: 0, max: 20, integer: true },
- "recall.max_items": { min: 1, max: 100, integer: true },
- "recall.score_threshold": { min: 0, max: 1, integer: false },
- "capture.commit_token_threshold": { min: 1000, max: 1_000_000, integer: true },
-};
-
/**
- * The workspace schema in the vocabulary the harness loaders already speak.
- *
- * Only knobs a loader actually reads appear here — the same rule the ovcli
- * `plugin` section follows, so the schema never advertises a setting that
- * silently does nothing. `labels` is metadata for humans and is not projected.
+ * The workspace schema is a projection of `config-schema.mjs`: the dotted key,
+ * its enum members and its range all come from the one knob declaration, so a
+ * knob cannot be spelled one way here and another way in the loaders.
*/
-const KNOB_MAP = {
- "peer.id": "peerId",
- "peer.source": "peerSource",
- "recall.enabled": "autoRecall",
- "recall.peer_scope": "recallPeerScope",
- "recall.dedup_turns": "recallDedupTurns",
- "recall.max_items": "recallLimit",
- "recall.score_threshold": "scoreThreshold",
- "capture.enabled": "autoCapture",
- "capture.commit_token_threshold": "commitTokenThreshold",
- "bypass.session_patterns": "bypassSessionPatterns",
-};
+const ENUMS = WORKSPACE_ENUMS;
+const RANGES = WORKSPACE_RANGES;
+const KNOB_MAP = WORKSPACE_KNOB_MAP;
export const WORKSPACE_SCHEMA_KEYS = Object.keys(KNOB_MAP);
diff --git a/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs
index 89df30793..7f136f10b 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/workspace-peer.mjs
@@ -40,6 +40,69 @@ export const DEFAULT_PEER_SOURCE = "git";
const VARIABLE_RE = /\{([a-z_]+)\}/g;
+/**
+ * Layers `resolvePluginPeerId` must not read off the merged settings, because
+ * each has a rank of its own: the environment ranks above every file, and
+ * ov.conf's harness block ranks below all of them.
+ */
+const PEER_LAYERS_RANKED_SEPARATELY = new Set(["env", "ov.conf"]);
+
+function trimmed(value) {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+/**
+ * The peer some layer named, in the one order every harness follows.
+ *
+ * Both halves of a loader's configuration carry a peer: `resolveSettings()`
+ * reads the workspace file, the machine registry and ovcli.conf's `plugin`
+ * section, while the credential chain ends in ovcli.conf's `actor_peer_id`. The
+ * more specific layer wins, so a `peerId` written for this harness outranks the
+ * account-wide actor peer — codex resolved it that way and opencode and pi
+ * resolved it the other way round, which meant one ovcli.conf produced two
+ * different peers depending on which host read it.
+ *
+ * ov.conf's harness block, where this tuning used to live, stays at the bottom.
+ * It gets its own rank rather than riding the credential chain, which drops it
+ * entirely once the credentials are pinned to ovcli.conf.
+ *
+ * `OPENVIKING_PEER_ID` still outranks every file, except when the credentials
+ * are pinned to ovcli.conf, where the environment is meant not to apply at all.
+ * A host that names a peer itself (dsh's cordis patch) outranks all of them.
+ *
+ * Returns "" when nobody named one, which is what makes
+ * `resolveEffectivePeerId()` derive one from `peer.source`.
+ */
+export function resolvePluginPeerId({
+ settings = {},
+ configured = null,
+ sources = {},
+ credentials = {},
+ hostInput = "",
+ env = process.env,
+ credentialSource = credentials?.credentialSource || "",
+} = {}) {
+ const host = trimmed(hostInput);
+ if (host) return host;
+
+ if (credentialSource !== "ovcli") {
+ const fromEnv = trimmed(env?.OPENVIKING_PEER_ID);
+ if (fromEnv) return fromEnv;
+ }
+
+ if (configured?.has?.("peerId") && !PEER_LAYERS_RANKED_SEPARATELY.has(sources?.peerId)) {
+ const named = trimmed(settings?.peerId);
+ if (named) return named;
+ }
+
+ const fromCredentials = trimmed(credentials?.peerId);
+ if (fromCredentials) return fromCredentials;
+
+ if (sources?.peerId === "ov.conf") return trimmed(settings?.peerId);
+
+ return "";
+}
+
export function deriveWorkspacePeerId(cwd) {
return legacySanitize(cwd);
}
diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
index eff2e58fa..064ee5366 100644
--- a/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.mjs
@@ -13,15 +13,15 @@ import { basename, normalize, sep } from "node:path";
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
import { makeFetchJSON } from "./lib/ov-session.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
if (!isPluginEnabled()) {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
process.exit(0);
}
-const cfg = loadConfig();
const { log, logError } = createLogger("skill-experience");
-const fetchJSON = makeFetchJSON(cfg);
+const fetchJSON = makeFetchJSON(loadConfig());
function output(obj) {
process.stdout.write(JSON.stringify(obj) + "\n");
@@ -38,16 +38,6 @@ function approve(additionalContext) {
output(out);
}
-async function readStdinJson() {
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- return JSON.parse(Buffer.concat(chunks).toString() || "{}");
- } catch {
- return {};
- }
-}
-
function toolName(input) {
return String(input.tool_name || input.toolName || input.name || input.tool || "").trim();
}
@@ -95,7 +85,7 @@ function clampScore(value) {
return Math.max(0, Math.min(1, num));
}
-async function findExperiences(query) {
+async function findExperiences(cfg, query) {
const res = await fetchJSON("/api/v1/search/find", {
method: "POST",
body: JSON.stringify({
@@ -128,36 +118,30 @@ function buildContext(skillName, items) {
return lines.join("\n");
}
-async function main() {
- if (!cfg.skillExperience) {
- log("skip", { reason: "disabled" });
- approve();
- return;
- }
-
- const input = await readStdinJson();
+runHookStage({
+ loadConfig,
+ input: { tolerant: true },
+ // No bypass gate: this optional per-read hint has never consulted the
+ // session patterns, only its own switch.
+ gates: { enabled: (cfg) => cfg.skillExperience, bypass: () => false },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+}, async ({ cfg, input }) => {
const name = toolName(input);
const path = readPath(input);
if (name && name !== "Read") {
log("skip", { reason: "not_read", toolName: name });
- approve();
return;
}
if (!isSkillFile(path)) {
log("skip", { reason: "not_skill_file", path });
- approve();
return;
}
const skillName = skillNameFromContent(path);
const query = `skill ${skillName} usage experience`;
- const items = await findExperiences(query);
+ const items = await findExperiences(cfg, query);
const context = buildContext(skillName, items);
log("done", { skillName, count: items.length });
- approve(context);
-}
-
-main().catch((err) => {
- logError("uncaught", err);
- approve();
-});
+ return context;
+}).catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
index 520a232d0..f51e64d49 100644
--- a/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/skill-experience.test.mjs
@@ -1,50 +1,14 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
-const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
-
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try {
- resolve(raw ? JSON.parse(raw) : null);
- } catch (err) {
- reject(err);
- }
- });
- req.on("error", reject);
- });
-}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- handler(req, res).catch((err) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
function runSkillExperience(input, env) {
return new Promise((resolve, reject) => {
diff --git a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
index 9b2c9cfd6..7ea364866 100644
--- a/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
+++ b/examples/claude-code-memory-plugin/scripts/subagent-start.mjs
@@ -22,15 +22,15 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
-import { deriveOvSessionId, isBypassed } from "./lib/ov-session.mjs";
+import { deriveOvSessionId } from "./lib/ov-session.mjs";
import { getEffectivePeerId } from "./lib/workspace-peer.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
if (!isPluginEnabled()) {
process.stdout.write(JSON.stringify({ decision: "approve" }) + "\n");
process.exit(0);
}
-let cfg = loadConfig();
const { log, logError } = createLogger("subagent-start");
const STATE_DIR = join(tmpdir(), "openviking-cc-subagent-state");
@@ -44,43 +44,24 @@ function stateFile(subagentId) {
return join(STATE_DIR, `${safe}.json`);
}
-async function main() {
- let input = {};
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString() || "{}");
- } catch { /* best effort */ }
-
- const sessionId = input.session_id;
- const subagentId = input.agent_id;
- const agentType = input.agent_type || "subagent";
- const cwd = input.cwd;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
-
+runHookStage({
+ loadConfig,
+ input: { tolerant: true },
// Paired with subagent-stop.mjs (a write path): when capture is off the
// stop hook will skip, so there's no point stashing start state either.
- if (!cfg.autoCapture) {
- log("skip", { reason: "autoCapture disabled" });
- approve();
- return;
- }
-
- const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
+ gates: { enabled: (cfg) => cfg.autoCapture },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+}, async ({ cfg, input, cwd, sessionId }) => {
+ const subagentId = input.agent_id;
+ const agentType = input.agent_type || "subagent";
if (!sessionId || !subagentId) {
log("skip", { reason: "missing session_id or agent_id" });
- approve();
return;
}
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
- return;
- }
+ const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
// Isolated ovSessionId: append Claude's subagent id so the subagent has its
// own OV session distinct from the parent.
@@ -105,7 +86,4 @@ async function main() {
}
log("start", { subagentId, agentType, ovSessionId, peerSource: effectivePeer.source });
- approve();
-}
-
-main().catch((err) => { logError("uncaught", err); approve(); });
+}).catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
index b237c030a..50d8e5a40 100644
--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
@@ -7,10 +7,10 @@
* { session_id, agent_id, agent_type, agent_transcript_path, ... }
*
* Regular in-subagent hooks never fire, so this is the only place we can
- * capture the subagent's turns. We read its transcript jsonl, extract
- * tier-1 parts (text + tool-use name list), and push to the isolated
- * ovSessionId we created in subagent-start.mjs. An immediate commit runs
- * so the subagent's context is archived before the parent continues.
+ * capture the subagent's turns. We read its transcript jsonl with the same
+ * reader auto-capture uses and push the turns to the isolated ovSessionId we
+ * created in subagent-start.mjs. An immediate commit runs so the subagent's
+ * context is archived before the parent continues.
*
* Each subagent is written to a distinct OpenViking session derived from the
* parent session id and Claude's subagent id.
@@ -21,16 +21,17 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { isPluginEnabled, loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
+import { extractCaptureTurns, parseTranscript } from "./cc-transcript.mjs";
import {
commitSession,
deriveOvSessionId,
enqueuePendingDirectly,
- isBypassed,
isRetryableFailure,
makeFetchJSON,
} from "./lib/ov-session.mjs";
import { maybeDetach, readHookStdin } from "./lib/async-writer.mjs";
import { getEffectivePeerId } from "./lib/workspace-peer.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
import { sendSessionMessages } from "./shared/batch-send.mjs";
import { filterCaptureParts } from "./shared/capture-utils.mjs";
@@ -39,7 +40,7 @@ if (!isPluginEnabled()) {
process.exit(0);
}
-let cfg = loadConfig();
+const baseCfg = loadConfig();
const { log, logError } = createLogger("subagent-stop");
const STATE_DIR = join(tmpdir(), "openviking-cc-subagent-state");
@@ -53,7 +54,7 @@ function stateFile(subagentId) {
return join(STATE_DIR, `${safe}.json`);
}
-function peerIdFromSubagent(subagentId, state, sessionId, cwd) {
+function peerIdFromSubagent(cfg, subagentId, state, sessionId, cwd) {
if (cfg.peerId) return cfg.peerId;
if (state?.peerId) return state.peerId;
const effectivePeer = getEffectivePeerId(cfg, { sessionId, cwd });
@@ -70,168 +71,7 @@ async function loadState(subagentId) {
}
}
-function parseTranscript(content) {
- const lines = content.split("\n").filter(l => l.trim());
- const out = [];
- for (const line of lines) {
- try { out.push(JSON.parse(line)); } catch { /* skip */ }
- }
- return out;
-}
-
-// Tool result (output) retention. 0 = drop tool_result entirely; >0 = keep, truncated.
-// Default 0 — see auto-capture.mjs for rationale. Mirrors auto-capture.mjs.
-const TOOL_RESULT_MAX_CHARS = 0;
-
-function formatToolInput(value) {
- // Tool inputs are agent-authored; we keep them verbatim.
- if (typeof value === "string") return value;
- try {
- return JSON.stringify(value, null, 2);
- } catch {
- return String(value);
- }
-}
-
-function truncateToolResult(s) {
- if (TOOL_RESULT_MAX_CHARS <= 0) return null; // drop
- if (typeof s !== "string") s = String(s ?? "");
- if (s.length <= TOOL_RESULT_MAX_CHARS) return s;
- return (
- s.slice(0, TOOL_RESULT_MAX_CHARS) +
- `\n... [truncated, ${s.length - TOOL_RESULT_MAX_CHARS} more chars]`
- );
-}
-
-function extractToolResultText(content) {
- if (typeof content === "string") return content;
- if (!Array.isArray(content)) return "";
- return content
- .filter((b) => b && b.type === "text" && typeof b.text === "string")
- .map((b) => b.text)
- .join("\n");
-}
-
-// Structured parts (parts-mode capture) — mirrors auto-capture.mjs. Tool calls /
-// results become dedicated `tool` parts instead of being inlined into content,
-// and tool_output is reported verbatim so the server can externalize it.
-function truncateToolOutput(s) {
- if (typeof s !== "string") s = String(s ?? "");
- const max = cfg.captureToolMaxChars;
- if (s.length <= max) return s;
- return s.slice(0, max) + `\n... [truncated, ${s.length - max} more chars]`;
-}
-
-function collectToolNamesById(messages) {
- const map = {};
- for (const msg of messages) {
- const content = msg?.content ?? msg?.message?.content;
- if (!Array.isArray(content)) continue;
- for (const block of content) {
- if (
- block?.type === "tool_use" &&
- typeof block.id === "string" &&
- typeof block.name === "string"
- ) {
- map[block.id] = block.name;
- }
- }
- }
- return map;
-}
-
-function buildParts(content, toolNameById) {
- const out = [];
- if (typeof content === "string") {
- if (content.trim()) out.push({ type: "text", text: content });
- return out;
- }
- if (!Array.isArray(content)) return out;
- for (const block of content) {
- if (!block || typeof block !== "object") continue;
- if (block.type === "text" && typeof block.text === "string") {
- if (block.text.trim()) out.push({ type: "text", text: block.text });
- } else if (block.type === "tool_use" && typeof block.name === "string") {
- out.push({
- type: "tool",
- tool_id: typeof block.id === "string" ? block.id : undefined,
- tool_name: block.name,
- tool_input:
- block.input && typeof block.input === "object" ? block.input : undefined,
- tool_status: "running",
- });
- } else if (block.type === "tool_result") {
- const id = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined;
- out.push({
- type: "tool",
- tool_id: id,
- tool_name: id ? toolNameById[id] : undefined,
- tool_output: truncateToolOutput(extractToolResultText(block.content)),
- tool_status: block.is_error ? "error" : "completed",
- });
- }
- }
- return out;
-}
-
-/**
- * Tier-1 parts extraction — shared shape with auto-capture.mjs.
- * Kept inline here so SubagentStop does not import auto-capture's globals.
- * Inlines tool_use input verbatim; tool_result content is dropped by default
- * (TOOL_RESULT_MAX_CHARS = 0) and retained only if explicitly enabled.
- */
-function extractTurns(messages) {
- const toolNameById = collectToolNamesById(messages);
- const turns = [];
- for (const msg of messages) {
- if (!msg || typeof msg !== "object") continue;
- let role = msg.role;
- let text = "";
- const toolNames = [];
- let parts = [];
-
- const harvestContent = (content) => {
- if (typeof content === "string") {
- text = content;
- } else if (Array.isArray(content)) {
- const parts = [];
- for (const block of content) {
- if (!block || typeof block !== "object") continue;
- if (block.type === "text" && typeof block.text === "string") {
- parts.push(block.text);
- } else if (block.type === "tool_use" && typeof block.name === "string") {
- toolNames.push(block.name);
- parts.push(`[tool: ${block.name}]\n${formatToolInput(block.input)}`);
- } else if (block.type === "tool_result") {
- const resultText = extractToolResultText(block.content);
- const truncated = resultText ? truncateToolResult(resultText) : null;
- if (truncated) {
- parts.push(`[tool result]\n${truncated}`);
- }
- }
- }
- text = parts.join("\n\n");
- }
- };
-
- let rawContent;
- if (msg.content !== undefined) {
- rawContent = msg.content;
- } else if (typeof msg.message === "object" && msg.message) {
- role = msg.message.role || role;
- rawContent = msg.message.content;
- }
- harvestContent(rawContent);
- parts = buildParts(rawContent, toolNameById);
-
- if (role !== "user" && role !== "assistant") continue;
- if (parts.length === 0) continue;
- turns.push({ role, text: text.trim(), toolNames, parts });
- }
- return turns;
-}
-
-async function pushTurns(ovSessionId, turns, { peerId = null, enqueueOnly = false } = {}) {
+async function pushTurns(cfg, ovSessionId, turns, { peerId = null, enqueueOnly = false } = {}) {
const fetchJSON = makeFetchJSON(cfg);
let ok = 0;
let queued = 0;
@@ -291,98 +131,79 @@ async function pushTurns(ovSessionId, turns, { peerId = null, enqueueOnly = fals
async function main() {
// Write-path hook: gated by autoCapture so that disabling capture also
- // suppresses the subagent transcript push + commit.
- if (!cfg.autoCapture) {
- log("skip", { reason: "autoCapture disabled" });
+ // suppresses the subagent transcript push + commit. This runs against the
+ // hook's own directory, before the payload names the session's.
+ if (!baseCfg.autoCapture) {
+ log("skip", { reason: "disabled" });
approve();
return;
}
- if (await maybeDetach(cfg, { approve })) return;
+ if (await maybeDetach(baseCfg, { approve })) return;
- let input = {};
- try {
- input = JSON.parse((await readHookStdin()) || "{}");
- } catch { /* best effort */ }
+ await runHookStage({
+ loadConfig,
+ input: { read: readHookStdin, tolerant: true },
+ gates: { enabled: (cfg) => cfg.autoCapture },
+ envelope: approve,
+ onSkip: (reason) => log("skip", { reason }),
+ }, async ({ cfg, input, cwd, sessionId }) => {
+ const subagentId = input.agent_id;
+ const transcriptPath = input.agent_transcript_path;
- const sessionId = input.session_id;
- const cwd = input.cwd;
- const subagentId = input.agent_id;
- const transcriptPath = input.agent_transcript_path;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
- if (!cfg.autoCapture) {
- // The gate above ran against this process's directory, not the session's.
- log("skip", { reason: "autoCapture disabled" });
- approve();
- return;
- }
+ if (!sessionId || !subagentId || !transcriptPath) {
+ log("skip", { reason: "missing required input fields" });
+ return;
+ }
- if (!sessionId || !subagentId || !transcriptPath) {
- log("skip", { reason: "missing required input fields" });
- approve();
- return;
- }
+ // Prefer state from SubagentStart (may carry ovSessionId from config snapshot);
+ // fall back to live derivation if state file is missing.
+ const state = await loadState(subagentId);
+ const ovSessionId = state?.ovSessionId || deriveOvSessionId(sessionId, `subagent:${subagentId}`);
+
+ let transcript;
+ try {
+ transcript = await readFile(transcriptPath, "utf-8");
+ } catch (err) {
+ logError("transcript_read", err);
+ return;
+ }
- if (isBypassed(cfg, { sessionId, cwd })) {
- log("skip", { reason: "bypass_session_pattern" });
- approve();
- return;
- }
+ const messages = parseTranscript(transcript);
+ const turns = extractCaptureTurns(messages, cfg);
+ log("transcript_parse", {
+ subagentId,
+ ovSessionId,
+ totalTurns: turns.length,
+ });
- // Prefer state from SubagentStart (may carry ovSessionId from config snapshot);
- // fall back to live derivation if state file is missing.
- const state = await loadState(subagentId);
- const ovSessionId = state?.ovSessionId || deriveOvSessionId(sessionId, `subagent:${subagentId}`);
+ if (turns.length === 0) {
+ await unlink(stateFile(subagentId)).catch(() => {});
+ return;
+ }
- let transcript;
- try {
- transcript = await readFile(transcriptPath, "utf-8");
- } catch (err) {
- logError("transcript_read", err);
- approve();
- return;
- }
+ const peerId = peerIdFromSubagent(cfg, subagentId, state, sessionId, cwd);
+ const fetchJSON = makeFetchJSON(cfg);
+ const health = await fetchJSON("/health");
+ let result;
+ if (health.ok) {
+ result = await pushTurns(cfg, ovSessionId, turns, { peerId });
+ } else if (isRetryableFailure(health)) {
+ logError("health_check", "server unreachable; enqueuing subagent capture");
+ result = await pushTurns(cfg, ovSessionId, turns, { peerId, enqueueOnly: true });
+ } else {
+ logError("health_check", `non-retryable status ${health.status || "unknown"}`);
+ return;
+ }
+ log("push_turns", { ovSessionId, ...result });
- const messages = parseTranscript(transcript);
- const turns = extractTurns(messages);
- log("transcript_parse", {
- subagentId,
- ovSessionId,
- totalTurns: turns.length,
- });
+ if (result.enqueueFailed > 0) {
+ logError("pending_enqueue", "some turns failed to enqueue; state file retained");
+ return;
+ }
- if (turns.length === 0) {
await unlink(stateFile(subagentId)).catch(() => {});
- approve();
- return;
- }
-
- const peerId = peerIdFromSubagent(subagentId, state, sessionId, cwd);
- const fetchJSON = makeFetchJSON(cfg);
- const health = await fetchJSON("/health");
- let result;
- if (health.ok) {
- result = await pushTurns(ovSessionId, turns, { peerId });
- } else if (isRetryableFailure(health)) {
- logError("health_check", "server unreachable; enqueuing subagent capture");
- result = await pushTurns(ovSessionId, turns, { peerId, enqueueOnly: true });
- } else {
- logError("health_check", `non-retryable status ${health.status || "unknown"}`);
- approve();
- return;
- }
- log("push_turns", { ovSessionId, ...result });
-
- if (result.enqueueFailed > 0) {
- logError("pending_enqueue", "some turns failed to enqueue; state file retained");
- approve();
- return;
- }
-
- await unlink(stateFile(subagentId)).catch(() => {});
- approve();
+ });
}
main().catch((err) => { logError("uncaught", err); approve(); });
diff --git a/examples/claude-code-memory-plugin/scripts/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/uri-guard.mjs
index c5c89ebc2..0bf14896e 100644
--- a/examples/claude-code-memory-plugin/scripts/uri-guard.mjs
+++ b/examples/claude-code-memory-plugin/scripts/uri-guard.mjs
@@ -1,59 +1,21 @@
#!/usr/bin/env node
-import { readFileSync } from "node:fs";
-import { buildGuardMessage, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs";
+import {
+ denyHookSpecificOutput,
+ evaluateUriGuard,
+ runUriGuardHook,
+} from "./shared/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('"', '\\"')}")`,
- },
-};
+// Claude Code names the same MCP tools as the shared hints, so only the guarded
+// set is host data: Bash is left alone, a viking:// URI inside a shell command
+// reaches the model.
+const GUARDED_TOOLS = new Set(["read", "glob", "grep"]);
export function evaluatePreToolUse(input = {}) {
- const toolName = normalizeToolName(input.tool_name ?? input.toolName ?? input.name ?? input.tool);
- const hint = TOOL_HINTS[toolName];
- if (!hint) return {};
-
+ const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;
const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? {};
- const uri = findVikingUri(toolInput);
- if (!uri) return {};
-
- return {
- hookSpecificOutput: {
- hookEventName: "PreToolUse",
- permissionDecision: "deny",
- permissionDecisionReason: buildGuardMessage(uri, {
- tool: hint.tool,
- example: hint.example(uri, toolInput),
- }),
- },
- };
-}
-
-function main() {
- let payload = {};
- try {
- const raw = readFileSync(0, "utf8").trim();
- if (raw) payload = JSON.parse(raw);
- } catch {
- payload = {};
- }
-
- const out = evaluatePreToolUse(payload);
- if (Object.keys(out).length > 0) {
- process.stdout.write(`${JSON.stringify(out)}\n`);
- }
+ const decision = evaluateUriGuard(toolName, toolInput, { guarded: GUARDED_TOOLS });
+ return decision ? denyHookSpecificOutput(decision.reason) : {};
}
-if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
- main();
-}
+runUriGuardHook(import.meta.url, evaluatePreToolUse);
diff --git a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
index de96174dc..04084e265 100644
--- a/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/claude-code-memory-plugin/servers/mcp-proxy.mjs
@@ -23,6 +23,7 @@ function readProxyConfig() {
apiKey: cfg.apiKey,
account: cfg.accountId,
user: cfg.userId,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
peerId: resolveMcpActorPeerId(cfg),
userAgent: cfg.userAgent,
timeoutMs: cfg.timeoutMs,
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
index 6576ab4ee..275e4c92e 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -31,8 +31,10 @@ three moving parts and each fails silently in its own way:
When the resolved url is loopback, the server runs on this machine and the
doctor adds a **Server health** section: whether anything listens on the
-port, plugin-only keys in `ov.conf` (`claude_code`, `codex`, `server.url`)
-that make the server refuse to start, and `GET /ready` — the server's own
+port, plugin-only keys in `ov.conf` (a top-level block named after any
+harness: `claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`,
+`opencode`, `dsh`, `pi`, plus `server.url`) that make the server refuse to
+start, and `GET /ready` — the server's own
per-subsystem verdict (agfs, vectordb, api keys, embedding, ollama). For a
remote server only `/ready` is probed. Everything else on the server side —
config validation, live embedding probe, native engine, disk — is
@@ -83,6 +85,7 @@ Work top-down; fix the first ✗ and rerun before chasing the next.
| `using the ROOT api key` / `403 ROOT API keys cannot access tenant-scoped data APIs` | `api_key` fell through to `ov.conf server.root_api_key`, or the user pasted the root key | Create a user key (`POST /api/v1/admin/accounts/<account>/users` with the root key) and put it in ovcli.conf. |
| `server is in trusted mode and needs account + user` / 400 `Trusted mode requests must include…` | Server identity comes from headers | Set `account` and `user` in ovcli.conf. |
| `configured account/user differ from the key's identity` | In `api_key` mode the server ignores `X-OpenViking-Account/User`; data lands under the key's identity | Remove them or use a key for that identity. Explains "I changed the account but nothing changed". |
+| `request/capture timeout exceeds the hook budget` | Claude Code kills the hook before the request finishes | Lower `OPENVIKING_TIMEOUT_MS` / `OPENVIKING_CAPTURE_TIMEOUT_MS`. |
| `POST /mcp tools/list → 404/406/502/504` while /health is fine | Reverse proxy not forwarding `/mcp`, rewriting `Accept`, or buffering SSE | Fix the proxy (`proxy_buffering off`, forward `/mcp`, pass `Authorization`). |
| `proxy variables set` + curl works but doctor/hook fails | Node's fetch ignores `HTTP(S)_PROXY`; the plugin ships no proxy/CA handling | `NODE_USE_ENV_PROXY=1` or `NODE_EXTRA_CA_CERTS=<ca.pem>` in the environment that launches Claude Code (`env` block of `~/.claude/settings.json`). |
| `last auto-recall … reason=offline/bypass/disabled/short_query` | The hook ran and chose not to inject | `offline` → connection; `bypass` → `OPENVIKING_BYPASS_SESSION*`; `short_query` → prompt shorter than `minQueryLength`; only `no_results`/`filtered_out` mean the search actually ran. Note that a 401 on the search call also reads as `no_results`. |
@@ -90,7 +93,7 @@ Work top-down; fix the first ✗ and rerun before chasing the next.
| `MCP proxy last started against <other url>` | The proxy is a long-lived process; a changed url only takes effect after restart | Restart Claude Code or `/mcp` → reconnect. Key rotation self-heals after a 401 if ovcli.conf changed on disk. |
| `recall is pinned to the legacy /search/recall endpoint` | One 4xx mentioning "mode" pins recall for 6h | `rm ~/.openviking/state/context-face.json`. |
| `no hook log … debug is on but no hook has run` | Hooks are not being spawned at all | Registration/enablement/node problem, not a server problem. |
-| `ov.conf has a top-level 'claude_code' block` / `'codex' block` / `server.url is rejected` | Plugin-only keys in the server's own config; the server refuses to start at its next restart (`Unknown config field` / `Extra inputs are not permitted`) | Move them to ovcli.conf (`plugin.<harness>`, `url`) and delete them from ov.conf. Ignore only if this ov.conf never starts a server. |
+| `ov.conf has a top-level '<harness>' block` / `server.url is rejected` | Plugin-only keys in the server's own config — a top-level block named after any harness (`claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`, `opencode`, `dsh`, `pi`) plus `server.url`; the server refuses to start at its next restart (`Unknown config field` / `Extra inputs are not permitted`) | Move them to ovcli.conf (`plugin.<harness>`, `url`) and delete them from ov.conf. Ignore only if this ov.conf never starts a server. |
| `nothing listens on port … — the server is not running` | Server down or never started; a stale `.openviking.pid` means it died | Start it (`openviking-server`; first time `openviking-server init`) in a terminal and read the startup output. Ask before restarting a server the user runs. |
| `/ready: embedding → error …` | The running server cannot call its embedding provider: recall searches nothing, commits extract nothing | Fix `embedding.*` (api_key/api_base/model) in ov.conf and restart; `openviking-server doctor` prints the provider's reply. |
| `/ready: vectordb → …` / `/ready: agfs → …` | Storage broken: disk full, two servers on one workspace, corrupted index | Server log; stop the duplicate; free disk. |
@@ -141,10 +144,6 @@ same `~/.openviking/ovcli.conf` (they show account/user/role for the key).
`ov config list` reveals whether a different profile was switched in with
`ov config switch` — that also retargets the plugin.
-Recall corpus probe: `node ${CLAUDE_PLUGIN_ROOT}/scripts/debug-recall.mjs "<query>"`
-prints config, health and raw `/search/find` hits. It is a connectivity and
-corpus check, not a replay of the hook's exact ranking.
-
Server side (only meaningful when the server runs on this machine):
```bash
@@ -185,8 +184,6 @@ ask before stopping or restarting it.
- Never print a full API key or the raw contents of `ovcli.conf`; the
doctor's masked forms are the limit.
-- Never run `scripts/debug-capture.mjs` with a live Claude Code session id —
- it overwrites that session's capture cursor and uses an obsolete API flow.
- `scripts/setup.mjs` needs a TTY and, on older plugin versions, an existing
`ovcli.conf`; on a fresh machine write the file directly or re-run the installer.
- Never pipe `claude plugin list` into `grep -q`; capture the output first
diff --git a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
index e8f7d908f..3ea6c0f42 100644
--- a/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/claude-code-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -31,10 +31,11 @@ and `OPENVIKING_PENDING_DIR` relocate individual pieces.
| Field | Order |
|---|---|
| url | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` → `ovcli.conf url` → `ov.conf server.url` → `http://{server.host\|127.0.0.1}:{server.port\|1933}` |
-| api_key | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` → `ovcli.conf api_key` → `ov.conf claude_code.apiKey` → `ov.conf server.root_api_key` |
-| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/user` → `ov.conf claude_code.accountId/userId` |
-| peer | `OPENVIKING_PEER_ID` → registry → `config.local.json` → `config.json` (`peer.id`) → `ovcli.conf plugin.claude_code.peerId` → `ovcli.conf plugin.peerId` → `ov.conf claude_code.peerId` → derived per `peer.source` unless `OPENVIKING_WORKSPACE_PEER=0` |
+| api_key | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` → `ovcli.conf api_key` → `ovcli.conf plugin.claude_code.apiKey` → `ovcli.conf plugin.apiKey` → `ov.conf claude_code.apiKey` → `ov.conf server.root_api_key` |
+| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/user` → `ovcli.conf plugin.claude_code.accountId/userId` → `ovcli.conf plugin.accountId/userId` → `ov.conf claude_code.accountId/userId` |
+| peer | `OPENVIKING_PEER_ID` → registry → `config.local.json` → `config.json` (`peer.id`) → `ovcli.conf plugin.claude_code.peerId` → `ovcli.conf plugin.peerId` → `ovcli.conf actor_peer_id/peer_id` → `ov.conf claude_code.peerId` → derived per `peer.source` unless `OPENVIKING_WORKSPACE_PEER=0` |
| peer.source | `OPENVIKING_PEER_SOURCE` → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.claude_code.peerSource` → `ovcli.conf plugin.peerSource` → `ov.conf claude_code.peerSource` → `git` |
+| auth mode | `ovcli.conf plugin.claude_code.authMode` → `ovcli.conf plugin.authMode` → `ov.conf claude_code.authMode` → `ov.conf server.auth_mode` → `trusted` when account/user are set, else `api_key` |
| enabled | `OPENVIKING_MEMORY_ENABLED` → `ov.conf claude_code.enabled === false` → "ov.conf or ovcli.conf exists and parses" |
| tuning | env → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.claude_code.*` → `ovcli.conf plugin.*` → `ov.conf claude_code.*` → defaults |
@@ -46,10 +47,13 @@ is a legitimate path prefix; `/api/v1` or `/mcp` suffixes are not.
Peers minted before this need no migration: the old cwd-derived id is recomputed locally, `peer_scope: "all"` already sweeps it, and under `"actor"` recall asks it separately. Doctor prints it as `previous peer`. Across the workspace layers lists union rather than replace, with a leading `"!reset"` dropping what the lower layers contributed; unknown keys are kept and ignored, and a file declaring a version other than `1` is skipped with a warning.
-Sent headers: `Authorization: Bearer <key>`, `X-OpenViking-Account`,
-`X-OpenViking-User`, `X-OpenViking-Actor-Peer`, `User-Agent: openviking-memory-claude-code/<version>`.
-The open-source server also accepts `X-API-Key` (and prefers it when both are
-sent); the Volcengine-hosted OpenViking Service (`https://api.vikingdb.cn-beijing.volces.com/openviking`) accepts Bearer only.
+Hook budgets in `hooks/hooks.json`: SessionStart 120s, UserPromptSubmit 60s, Stop and SubagentStop 45s, PreCompact and SessionEnd 30s, SubagentStart 10s, PreToolUse and PostToolUse 5s. `timeoutMs` (default 15000) must stay below 60s and `captureTimeoutMs` (default 30000, derived as twice `timeoutMs` when it is not set) at or below 45s; doctor warns when either outgrows its hook.
+
+Sent headers: `Authorization: Bearer <key>`, `X-OpenViking-Account/User` (trusted
+mode only), `X-OpenViking-Actor-Peer`, `User-Agent: openviking-memory-claude-code/<version>`.
+The plugin never sends `X-API-Key`. The open-source server still accepts it (and
+prefers it when both are sent), so a gateway that injects one shadows the key
+here; the Volcengine-hosted OpenViking Service (`https://api.vikingdb.cn-beijing.volces.com/openviking`) accepts Bearer only.
## Peer: giving a directory its own memory
@@ -115,7 +119,7 @@ Plugin MCP proxy (what Claude Code shows for a failing tool call):
Hook log (`cc-hooks.log`) stages worth grepping: `health_check`
(connectivity), `push_turns` / `capture_write` / `pending_enqueue` (capture),
-`recall_context_assembled` / `search_summary` / `injection_built` (recall),
+`recall_context_assembled` / `recall_search_summary` / `recall_injection_built` (recall),
`mcp-proxy` `start` (resolved `mcpUrl`, `hasApiKey` = present, not valid),
`uncaught` (crash). Hooks: `session-start`, `auto-recall`, `auto-capture`,
`session-end`, `pre-compact`, `subagent-start`, `subagent-stop`,
@@ -165,7 +169,7 @@ Startup failures (printed by the server; exit 1 unless noted):
| Text | Cause |
|---|---|
| `OpenViking configuration file not found.` | No ov.conf at any resolved path |
-| `Unknown config field '…' in OpenVikingConfig` / `Extra inputs are not permitted` | Unknown key — including `claude_code`, `codex` and `server.url`, which only the plugins read |
+| `Unknown config field '…' in OpenVikingConfig` / `Extra inputs are not permitted` | Unknown key — including a top-level block named after any harness (`claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`, `opencode`, `dsh`, `pi`) and `server.url`, which only the plugins read |
| `SECURITY: server.auth_mode='dev' requires server.host to be localhost` | Dev mode (no `auth_mode`, no `root_api_key`) on a non-loopback bind |
| `Invalid server.root_api_key: empty string is not allowed` | `""` instead of `null` |
| `Another OpenViking process (PID n) is already using the data directory` | Two servers on one workspace (exit 3, `Application startup failed. Exiting.`) |
diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json
index 9c8911ece..59b17d1fc 100644
--- a/examples/codex-memory-plugin/.codex-plugin/plugin.json
+++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openviking-memory",
- "version": "0.8.3",
+ "version": "0.9.0",
"description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.",
"author": {
"name": "OpenViking",
diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.md
index d6f674c75..da8d82da7 100644
--- a/examples/codex-memory-plugin/DESIGN.md
+++ b/examples/codex-memory-plugin/DESIGN.md
@@ -209,7 +209,13 @@ and appends each new user/assistant turn to the OV session for this codex
State is updated:
`{ovSessionId, capturedTurnCount, lastUpdatedAt: now}`.
-After a successful append, Stop reads session meta and commits when
+The transcript and persisted cursor own retries. Failed messages are not also
+put in the shared pending queue: replaying both sources would duplicate them.
+A partial append advances only past confirmed messages; subsequent hooks or
+the SessionStart sweep retry the remaining tail. The transcript must remain
+available until that catch-up succeeds.
+
+After a complete append, Stop reads session meta and commits when
`pending_tokens >= OPENVIKING_COMMIT_TOKEN_THRESHOLD` (default 20000).
The threshold commit passes
`keep_recent_count=OPENVIKING_COMMIT_KEEP_RECENT_COUNT` (default 10) so
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index a6a6f9c81..e2f31c525 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -40,8 +40,7 @@ Claude Code and Codex share this installer (drop `--harness codex` to pick inter
2. Sets up `~/.openviking/ovcli.conf` interactively
3. Registers the `openviking` marketplace — remote git by default (`codex plugin marketplace add https://github.com/volcengine/OpenViking.git`), or this checkout / a TOS archive in dev/archive mode — and enables `openviking-memory@openviking` with `features.plugin_hooks = true`
4. Keeps the checked-in stdio `.mcp.json` intact; `servers/mcp-proxy.mjs` reads your active `ovcli.conf` at runtime
-5. Removes old OpenViking rc wrapper blocks and the pre-unification `openviking-plugins-local` marketplace when found
-6. Runs plugin-list and stdio MCP validation
+5. Runs plugin-list and stdio MCP validation
After install:
@@ -115,7 +114,7 @@ Connection / identity source (applies to hooks, MCP, and `ov` commands run insid
Hooks and the MCP proxy call the same resolver directly, so the model tools and lifecycle hooks follow the same target.
-Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model); the hooks also send the same key as `X-API-Key` for compatibility with older servers.
+Auth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model), and as nothing else — the hooks used to repeat the key as `X-API-Key`, which a gateway of your own can still add if it needs one. `account` and `user` go out as `X-OpenViking-Account` / `X-OpenViking-User` only in trusted mode; an `api_key` server reads both out of the key and ignores the headers.
By default the hooks derive the peer from git rather than from where the repository happens to sit: the normalized `origin` URL, else the repository root path. Outside a repository nothing is sent, and what is remembered there goes to your user-level space at `viking://user/<you>/memories`. In `/Users/x/Dev/OpenViking/examples/codex-memory-plugin` with origin `[email protected]:volcengine/OpenViking.git` the peer is `github.com-volcengine-openviking`, and it stays that from any subdirectory, worktree, machine or clone. Every clone of one repository therefore shares one project memory; a fork has a different origin and stays separate, and `gh pr checkout` of an external PR leaves `origin` alone, so reviewing one does not move the identity. Derivation is pure filesystem work — no `git` subprocess — so it also holds where `git` is missing from `PATH` or would refuse the repository over dubious ownership. Hooks pass the effective peer as `peer_id` for captured session messages and as `X-OpenViking-Actor-Peer` for retrieval and filesystem calls.
@@ -375,6 +374,42 @@ node "$(ls -d ~/.codex/plugins/cache/openviking/openviking-memory/*/ | sort -V |
Or invoke the `$ov-memory-doctor` skill in Codex, which runs the same script and walks the report. When the server runs on the same machine (loopback url) the report adds a Server health section — whether anything listens on the port, plugin-only keys in ov.conf that stop the server from starting, and `GET /ready`; everything else server-side (config validation, live embedding probe, native engine, disk) stays with `openviking-server doctor`.
+## Testing
+
+There is no `package.json` and no build step, so the suite runs straight through Node's own test runner:
+
+```bash
+cd examples/codex-memory-plugin
+node --test scripts/*.test.mjs
+```
+
+CI runs the same files (`.github/workflows/pr.yml`), so a green local run is the same signal. They cover every hook end to end against a stubbed server — the deterministic `cx-<codex_session_id>` derivation, incremental append and idempotent re-runs, the PreCompact and SessionEnd commit paths with their `.ended.<ts>` markers and locks, the SessionStart sweep (idle TTL, cursor retention, `source=resume`), and recall assembly. The MCP proxy is shared code and its contract is tested once, in `examples/memory-plugin-shared/mcp-proxy-core.test.mjs`.
+
+### Live checks
+
+Two legs need a real server and real Codex auth, so they stay manual. Prerequisites: the `ov` CLI installed and reachable, Node.js 22+, and `~/.openviking/ovcli.conf` (or a per-tenant variant like `ovcli.conf.bob`) pointing at the OpenViking server you want to write to. The plugin sends `Authorization: Bearer <api_key>` from this file, and `X-OpenViking-Account` / `X-OpenViking-User` only in trusted mode.
+
+**Memory extraction landed in the user namespace.** After a session commits, wait ~60 s for OV's extractor, then:
+
+```bash
+export OV_CONF=$HOME/.openviking/ovcli.conf.bob # or whichever tenant
+OPENVIKING_CONFIG_FILE=$OV_CONF ov ls viking://user/<your-user>/memories/
+OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/<your-user>/memories/profile.md
+```
+
+Expect new entries describing the preferences the conversation stated, with timestamps from this run.
+
+**Codex CLI smoke test** (requires codex auth):
+
+```bash
+codex plugin marketplace add /path/to/OpenViking-codex-marketplace # if not already
+codex # interactive
+# Have a brief conversation that mentions a clear preference,
+# then /compact (manual PreCompact) to force a commit, then exit.
+```
+
+Then re-run the extraction check above.
+
## Plugin Structure
```
@@ -404,13 +439,11 @@ codex-memory-plugin/
│ ├── pre-compact-capture.mjs # PreCompact hook
│ └── *.test.mjs # node --test suites (session-end, pre-compact, ...)
├── servers/
-│ ├── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge
-│ └── mcp-proxy.test.mjs # proxy contract tests
+│ └── mcp-proxy.mjs # stdio -> OpenViking /mcp bridge
├── setup-helper/
│ └── install.sh # One-line installer
├── .mcp.json # stdio MCP wiring
├── DESIGN.md
-├── VERIFICATION.md
└── README.md
```
diff --git a/examples/codex-memory-plugin/VERIFICATION.md b/examples/codex-memory-plugin/VERIFICATION.md
deleted file mode 100644
index e2e9d82b0..000000000
--- a/examples/codex-memory-plugin/VERIFICATION.md
+++ /dev/null
@@ -1,322 +0,0 @@
-# Verification SOP — codex plugin (v0.6.0)
-
-End-to-end smoke test against a live OpenViking server. Run this whenever the
-hook scripts change. Takes ~3 minutes; the only async wait is OV's memory
-extractor (~30–60 s).
-
-## 0. Prereqs
-
-- `ov` CLI installed and reachable
-- `~/.openviking/ovcli.conf` (or a per-tenant variant like `ovcli.conf.bob`)
- pointing at the OV server you want to write to. The plugin sends
- `X-API-Key`, `X-OpenViking-Account`, `X-OpenViking-User` from this file.
-- Node.js 22+
-
-```bash
-export OV_CONF=$HOME/.openviking/ovcli.conf.bob # or whichever tenant
-export PLUGIN=/path/to/OpenViking/examples/codex-memory-plugin
-export STATE_DIR=/tmp/codex-plugin-verify
-rm -rf "$STATE_DIR" && mkdir -p "$STATE_DIR"
-```
-
-## 1. Stop hook — first turn appends
-
-```bash
-cat > "$STATE_DIR/transcript.jsonl" <<'EOF'
-{"payload":{"role":"user","content":"My favorite color is fuchsia."}}
-{"payload":{"role":"assistant","content":"Got it — fuchsia noted."}}
-EOF
-
-OPENVIKING_CONFIG_FILE=$OV_CONF \
-OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
-CODEX_PLUGIN_ROOT=$PLUGIN \
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl"}' \
- | node $PLUGIN/scripts/auto-capture.mjs
-```
-
-Expect: `{"systemMessage":"appended 2 turn(s) to OpenViking session cx-verify-sess"}`.
-
-State file:
-```bash
-cat $STATE_DIR/state/verify-sess.json
-# {"codexSessionId":"verify-sess","ovSessionId":"cx-verify-sess","capturedTurnCount":2,...}
-```
-
-OV side:
-```bash
-OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/sessions/cx-verify-sess/messages.jsonl
-# 2 JSONL records: user "fuchsia", assistant "noted"
-```
-
-## 2. Stop hook idempotency — re-run without changes is a no-op
-
-```bash
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/auto-capture.mjs
-```
-
-Expect: `{}` (no new turns). `capturedTurnCount` still 2.
-
-## 3. Stop hook — incremental append
-
-Append two more turns to the transcript and re-run:
-
-```bash
-cat >> "$STATE_DIR/transcript.jsonl" <<'EOF'
-{"payload":{"role":"user","content":"Actually, mint green."}}
-{"payload":{"role":"assistant","content":"Updated to mint green."}}
-EOF
-
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/auto-capture.mjs
-```
-
-Expect: `appended 2 turn(s)` (only the new ones). Re-read
-`viking://user/sessions/cx-verify-sess/messages.jsonl` — 4 records now.
-
-## 4. PreCompact — commit + reset
-
-```bash
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl","trigger":"manual"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/pre-compact-capture.mjs
-```
-
-Expect: `OpenViking session cx-verify-sess is committed`.
-
-State file: `ovSessionId` is now `null`, `capturedTurnCount` stays at 4.
-
-OV side:
-```bash
-OPENVIKING_CONFIG_FILE=$OV_CONF ov ls viking://user/sessions/cx-verify-sess
-# messages.jsonl is now size 0 (archived)
-# history/archive_001/ exists with the committed messages
-OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/sessions/cx-verify-sess/history/archive_001/messages.jsonl
-```
-
-## 5. Post-compact Stop — same deterministic OV session id
-
-Append more turns and run Stop. The same OV session id should appear:
-
-```bash
-cat >> "$STATE_DIR/transcript.jsonl" <<'EOF'
-{"payload":{"role":"user","content":"After compaction: I prefer serif fonts."}}
-{"payload":{"role":"assistant","content":"Noted serif preference."}}
-EOF
-
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/auto-capture.mjs
-```
-
-Expect: `appended 2 turn(s) to OpenViking session cx-verify-sess`.
-
-## 6. SessionEnd commit + SessionStart fallback sweep
-
-`SessionEnd` (Codex ≥ 0.145) is the primary commit path; `SessionStart`
-`source=startup|clear` sweeps only what `SessionEnd` could not reach
-(matcher = `clear|startup|resume`). `source=resume` never commits or sweeps;
-all three sources inject the shared profile/background block by default, and
-resume may additionally inject latest archive context if a committed archive
-exists. Set `OPENVIKING_NO_AUTO_INJECT=1` when a cleanup-only smoke test needs
-the historical `{}` output.
-See `DESIGN.md` §2 + §5 for the full decision tree.
-
-### 6a. SessionEnd — catch-up append + commit
-
-After step 5, `verify-sess` has a live `cx-verify-sess` and a cursor of 6.
-Append two more turns that `Stop` never saw, then run the worker path
-directly (`OV_HOOK_WORKER=1` skips the detach, so the run is observable).
-
-```bash
-cat >> "$STATE_DIR/transcript.jsonl" <<'EOF'
-{"payload":{"role":"user","content":"One last thing: I ship on Fridays."}}
-{"payload":{"role":"assistant","content":"Noted — Friday releases."}}
-EOF
-
-echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl","cwd":"/tmp","hook_event_name":"SessionEnd","reason":"other"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- OV_HOOK_WORKER=1 \
- OPENVIKING_DEBUG=1 \
- node $PLUGIN/scripts/session-end.mjs
-```
-
-Expect: `{}` on stdout (SessionEnd output is ignored by Codex). In
-`~/.openviking/logs/codex-hooks.log`: `appended_catchup` with `added: 2`,
-then `commit` with `"reason":"session_end"`.
-
-```bash
-cat $STATE_DIR/state/verify-sess.json
-# ovSessionId is null, capturedTurnCount is 8 (cursor preserved for resume)
-ls $STATE_DIR/state/verify-sess.ended.* # no such file — the marker was cleared
-```
-
-### 6b. SessionEnd parent — marker first, work detached
-
-```bash
-time (echo '{"session_id":"verify-sess","transcript_path":"'"$STATE_DIR"'/transcript.jsonl","cwd":"/tmp","hook_event_name":"SessionEnd","reason":"other"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/session-end.mjs)
-```
-
-Expect: `{}` well under 1 s — the parent only writes
-`$STATE_DIR/state/verify-sess.ended.<timestamp>` and detaches the worker. The worker
-finds nothing live to commit and removes the marker again shortly after.
-
-### 6c. `.ended.<ts>` marker → next SessionStart commits immediately
-
-```bash
-# A live session whose SessionEnd worker never finished: fresh timestamp,
-# so only the marker can make the sweep pick it up.
-NOW=$(node -e 'console.log(Date.now())')
-mkdir -p "$STATE_DIR/state"
-cat > "$STATE_DIR/state/sess-ended.json" <<EOF
-{"codexSessionId":"sess-ended","ovSessionId":"cx-sess-ended","capturedTurnCount":2,"createdAt":$NOW,"lastUpdatedAt":$NOW}
-EOF
-printf '%s' "$NOW" > "$STATE_DIR/state/sess-ended.ended.$NOW"
-
-echo '{"session_id":"sess-ccc","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- OPENVIKING_DEBUG=1 \
- node $PLUGIN/scripts/session-start-commit.mjs
-```
-
-Expect: `systemMessage` reports `cx-sess-ended` committed, and the log shows
-`"reason":"ended_retry"` despite the fresh `lastUpdatedAt`. Afterwards
-`sess-ended.json` has `ovSessionId: null` with `capturedTurnCount: 2`, and
-`sess-ended.ended.$NOW` is gone.
-
-### 6c-2. Held lock → sweep skips instead of racing
-
-```bash
-# Re-arm the same session, then hold its lock as a concurrent worker would.
-cat > "$STATE_DIR/state/sess-ended.json" <<EOF
-{"codexSessionId":"sess-ended","ovSessionId":"cx-sess-ended","capturedTurnCount":2,"createdAt":$NOW,"lastUpdatedAt":$NOW}
-EOF
-printf '%s' "$NOW" > "$STATE_DIR/state/sess-ended.ended.$NOW"
-mkdir "$STATE_DIR/state/sess-ended.lock"
-
-echo '{"session_id":"sess-fff","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- OPENVIKING_DEBUG=1 \
- node $PLUGIN/scripts/session-start-commit.mjs
-
-rmdir "$STATE_DIR/state/sess-ended.lock"
-```
-
-Expect: the log shows `sweep_skip` with `"reason":"locked by another writer"`,
-no `/commit` is issued, and `sess-ended.json` keeps `ovSessionId` and its
-marker. (A lock older than 5 min is treated as stale and taken over instead.)
-
-### 6d. Idle-TTL sweep
-
-```bash
-# A live state with no marker, backdated past IDLE_TTL_MS (default 30 min):
-# the signal/crash/old-Codex path.
-OLD=$(node -e 'console.log(Date.now() - 60*60*1000)') # 1 hour ago
-cat > "$STATE_DIR/state/sess-aaa.json" <<EOF
-{"codexSessionId":"sess-aaa","ovSessionId":"cx-sess-aaa","capturedTurnCount":2,"createdAt":$OLD,"lastUpdatedAt":$OLD}
-EOF
-
-echo '{"session_id":"sess-ddd","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/session-start-commit.mjs
-```
-
-Expect: log shows `sweep` for `sess-aaa` with `"reason":"idle_ttl"`, followed
-by the commit. `sess-aaa.json` is still present, with `ovSessionId: null` and
-`capturedTurnCount: 2` for resume. Any other state file that is both fresh and
-unmarked is left untouched — that is the whole point of dropping the old
-active-window heuristic.
-
-### 6d-2. Cursor retention
-
-```bash
-# sess-aaa is now cursor-only (ovSessionId: null, capturedTurnCount: 2).
-# Re-run the same SessionStart with a 1 s committed TTL.
-echo '{"session_id":"sess-eee","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- OPENVIKING_CODEX_COMMITTED_TTL_MS=1000 \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- OPENVIKING_DEBUG=1 \
- node $PLUGIN/scripts/session-start-commit.mjs
-```
-
-Expect: log shows `state_retire` for `sess-aaa` and the file is gone. With
-the default 30-day TTL it stays, and no `/commit` is issued for it either
-way — a cursor-only state has nothing left to commit.
-
-### 6e. `source=resume` → no commit/sweep; optional archive inject
-
-```bash
-echo '{"session_id":"any","source":"resume","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/session-start-commit.mjs
-# Expect without an existing archive: hookSpecificOutput.additionalContext
-# containing the OpenViking profile block.
-# Expect with an existing archive for cx-any: the same additionalContext also
-# contains "OpenViking session archive digest" and a
-# viking://user/sessions/cx-any/history/ URI.
-```
-
-### 6f. Compressor profile detect can be disabled for hook smoke tests
-
-```bash
-echo '{"session_id":"any","source":"startup","cwd":"/tmp","model":"x","permission_mode":"default","transcript_path":null,"hook_event_name":"SessionStart"}' \
- | OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP=0 \
- OPENVIKING_CONFIG_FILE=$OV_CONF \
- OPENVIKING_CODEX_STATE_DIR=$STATE_DIR/state \
- CODEX_PLUGIN_ROOT=$PLUGIN \
- node $PLUGIN/scripts/session-start-commit.mjs
-# Expect: normal SessionStart behavior without spawning `codex exec` for model probing.
-```
-
-## 7. Memory extraction landed in user namespace
-
-Wait ~60 s for OV's extractor, then:
-
-```bash
-OPENVIKING_CONFIG_FILE=$OV_CONF ov ls viking://user/<your-user>/memories/
-OPENVIKING_CONFIG_FILE=$OV_CONF ov read viking://user/<your-user>/memories/profile.md
-```
-
-Expect new entries describing the captured preferences (favorite color,
-serif fonts, etc.) with timestamps from this run.
-
-## 8. Codex CLI smoke test (requires codex auth)
-
-```bash
-codex plugin marketplace add /path/to/OpenViking-codex-marketplace # if not already
-codex # interactive
-# Have a brief conversation that mentions a clear preference,
-# then /compact (manual PreCompact) to force a commit, then exit.
-```
-
-Verify with steps 4 + 7 above.
-
----
-
-**Cleanup**: `rm -rf $STATE_DIR && rm -rf ~/.openviking/codex-plugin-state/verify-sess.json`
diff --git a/examples/codex-memory-plugin/scripts/auto-capture.mjs b/examples/codex-memory-plugin/scripts/auto-capture.mjs
index 97a21e93e..b0dc82f24 100644
--- a/examples/codex-memory-plugin/scripts/auto-capture.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-capture.mjs
@@ -26,6 +26,7 @@ import { loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
import { catchUpTurns, hasCaptureKeyword, makeFetchJSON } from "./ov-session.mjs";
import { clearEnded, loadState, saveState, withSessionLock } from "./session-state.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
import { maybeDetach, readHookStdin } from "./shared/async-writer.mjs";
import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
@@ -108,7 +109,7 @@ async function capture(sessionId, transcriptPath, cwd, heartbeat) {
return "";
}
- const { added, ovSessionId } = await catchUpTurns({
+ const { newTurns, added, ovSessionId } = await catchUpTurns({
state,
transcriptPath,
fetchJSONRes,
@@ -123,7 +124,7 @@ async function capture(sessionId, transcriptPath, cwd, heartbeat) {
let commitInfo = { committed: false, traceId: "" };
if (added > 0) {
log("appended", { ovSessionId, added });
- commitInfo = await maybeCommitByThreshold(ovSessionId, added);
+ if (added === newTurns.length) commitInfo = await maybeCommitByThreshold(ovSessionId, added);
}
await saveState(state);
@@ -135,39 +136,10 @@ async function capture(sessionId, transcriptPath, cwd, heartbeat) {
: "");
}
-async function main() {
- if (!cfg.autoCapture) {
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- noop();
- return;
- }
-
- // Async write mode returns a no-op response immediately; worker stdout is
- // intentionally discarded, so appended-count systemMessage is sync-only.
- process.env.OPENVIKING_HOOK_STARTED_AT = String(HOOK_STARTED_AT);
- if (await maybeDetach(cfg, { approve: () => output({}) })) return;
-
- let input;
- try {
- input = JSON.parse(await readHookStdin());
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- noop();
- return;
- }
-
- const sessionId = input.session_id || "unknown";
- const transcriptPath = input.transcript_path || null;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- const cwd = typeof input.cwd === "string" && input.cwd.trim() ? input.cwd : process.cwd();
- cfg = loadConfig(cwd);
- if (!cfg.autoCapture) {
- // The gate above ran against this process's directory, not the session's.
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- noop();
- return;
- }
+async function main(stage) {
+ cfg = stage.cfg;
+ const sessionId = stage.input.session_id || "unknown";
+ const transcriptPath = stage.input.transcript_path || null;
// A turn ended for this session, so it is alive again after any resume — but
// only for markers older than this hook run.
@@ -175,15 +147,37 @@ async function main() {
const outcome = await withSessionLock(
sessionId,
- ({ heartbeat }) => capture(sessionId, transcriptPath, cwd, heartbeat),
+ ({ heartbeat }) => capture(sessionId, transcriptPath, stage.cwd, heartbeat),
{ waitMs: LOCK_WAIT_MS },
);
if (outcome.skipped) {
logError("lock_timeout", `another writer holds ${sessionId}; leaving state untouched`);
+ return;
+ }
+ return outcome.value;
+}
+
+async function start() {
+ // Write-path hook: gated by autoCapture against this process's directory,
+ // before the payload names the session's.
+ if (!cfg.autoCapture) {
+ log("skip", { stage: "init", reason: "disabled" });
noop();
return;
}
- noop(outcome.value);
+
+ // Async write mode returns a no-op response immediately; worker stdout is
+ // intentionally discarded, so appended-count systemMessage is sync-only.
+ process.env.OPENVIKING_HOOK_STARTED_AT = String(HOOK_STARTED_AT);
+ if (await maybeDetach(cfg, { approve: () => output({}) })) return;
+
+ await runHookStage({
+ loadConfig,
+ input: { read: readHookStdin },
+ gates: { enabled: (reloaded) => reloaded.autoCapture },
+ envelope: noop,
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+ }, main);
}
-main().catch((err) => { logError("uncaught", err); noop(); });
+start().catch((err) => { logError("uncaught", err); noop(); });
diff --git a/examples/codex-memory-plugin/scripts/auto-capture.test.mjs b/examples/codex-memory-plugin/scripts/auto-capture.test.mjs
index 4a9c7ce4a..e55dca1a4 100644
--- a/examples/codex-memory-plugin/scripts/auto-capture.test.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-capture.test.mjs
@@ -1,12 +1,13 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { expectExit, runHookScript, readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
async function endedMarkerStamps(dir, id) {
@@ -26,44 +27,6 @@ function writeEndedMarker(dir, id, ts) {
return writeFile(join(dir, `${id}.ended.${ts}`), String(ts));
}
-
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try {
- resolve(raw ? JSON.parse(raw) : null);
- } catch (err) {
- reject(err);
- }
- });
- req.on("error", reject);
- });
-}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- handler(req, res).catch((err) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
function runAutoCapture(input, env) {
return new Promise((resolve, reject) => {
const cleanEnv = { ...process.env };
@@ -630,7 +593,6 @@ test("the workspace that decides capture is the payload's, not the hook process'
const transcriptPath = join(stateDir, "transcript.jsonl");
const workspaceDir = join(stateDir, "workspace");
const plainDir = join(stateDir, "plain");
- const calls = [];
try {
// The `.git` is what makes the directory a workspace root; the hook itself
@@ -659,7 +621,6 @@ test("the workspace that decides capture is the payload's, not the hook process'
await withMockOpenViking(async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
- calls.push(url.pathname);
if (req.method === "GET" && url.pathname === "/health") {
writeJson(res, { status: "ok", result: { ok: true } });
return;
@@ -675,21 +636,171 @@ test("the workspace that decides capture is the payload's, not the hook process'
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "error", error: "not found" }));
- }, async (baseUrl) => {
+ }, async (baseUrl, requests) => {
const off = await runAutoCapture(
{ session_id: "ws-off", transcript_path: transcriptPath, cwd: workspaceDir },
env(baseUrl),
);
assert.deepEqual(JSON.parse(off.stdout.trim()), {});
- assert.deepEqual(calls, [], "the workspace file turned capture off for this directory");
+ const paths = () => requests.map(({ path }) => path);
+ assert.deepEqual(paths(), [], "the workspace file turned capture off for this directory");
await runAutoCapture(
{ session_id: "ws-on", transcript_path: transcriptPath, cwd: plainDir },
env(baseUrl),
);
assert.ok(
- calls.some((path) => path.endsWith("/messages/batch")),
- `expected the same env to capture outside that workspace; calls=${JSON.stringify(calls)}`,
+ paths().some((path) => path.endsWith("/messages/batch")),
+ `expected the same env to capture outside that workspace; paths=${JSON.stringify(paths())}`,
+ );
+ });
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
+
+test("failed capture resumes from the transcript once before committing", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-capture-pending-"));
+ const transcriptPath = join(stateDir, "transcript.jsonl");
+ const pendingDir = join(stateDir, "pending");
+ let healthy = false;
+ const delivered = [];
+ let commits = 0;
+ const messages = Array.from({ length: 101 }, (_, i) => ({
+ role: "user", parts: [{ type: "text", text: `this turn must survive the outage ${i}` }],
+ }));
+
+ try {
+ await writeFile(transcriptPath, messages.map((message) => JSON.stringify({
+ payload: { message: { role: message.role, content: message.parts[0].text } },
+ })).join("\n"));
+
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "POST" && /\/messages(?:\/batch)?$/.test(url.pathname)) {
+ const body = await readRequestBody(req);
+ if (healthy || body.messages?.length === 100) {
+ delivered.push(...(body.messages || [body]));
+ writeJson(res, { status: "ok", result: {} });
+ return;
+ }
+ res.writeHead(503, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: { message: "server restarting" } }));
+ return;
+ }
+ if (url.pathname.endsWith("/commit")) commits++;
+ writeJson(res, { status: "ok", result: { pending_tokens: 99999 } });
+ }, async (baseUrl) => {
+ const input = { session_id: "cx-outage", transcript_path: transcriptPath, cwd: stateDir };
+ const env = {
+ HOME: stateDir,
+ OPENVIKING_CODEX_STATE_DIR: stateDir,
+ OPENVIKING_PENDING_DIR: pendingDir,
+ OPENVIKING_HOME: join(stateDir, "home"),
+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_WRITE_PATH_ASYNC: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_URL: baseUrl,
+ OPENVIKING_RECALL_COMPRESS: "off",
+ OPENVIKING_NO_AUTO_INJECT: "1",
+ OV_HOOK_WORKER: "1",
+ };
+ await runAutoCapture(input, env);
+ expectExit(await runHookScript(join(SCRIPT_DIR, "session-end.mjs"), { input, env }));
+ const statePath = join(stateDir, "cx-outage.json");
+ const failed = JSON.parse(await readFile(statePath, "utf-8"));
+ assert.equal(failed.capturedTurnCount, 100);
+ assert.ok(failed.ovSessionId);
+ assert.equal(commits, 0, "failed tail must keep the session live");
+ assert.ok(await endedMarkerExists(stateDir, "cx-outage"));
+
+ healthy = true;
+ expectExit(await runHookScript(join(SCRIPT_DIR, "session-start-commit.mjs"), {
+ input: { source: "startup", session_id: "next", cwd: stateDir }, env,
+ }));
+ await runAutoCapture(input, env);
+ assert.deepEqual(delivered, messages);
+ assert.equal(commits, 1);
+ const recovered = JSON.parse(await readFile(statePath, "utf-8"));
+ assert.equal(recovered.capturedTurnCount, 101);
+ assert.equal(recovered.ovSessionId, null);
+ assert.equal(await endedMarkerExists(stateDir, "cx-outage"), false);
+ assert.deepEqual(await readdir(pendingDir).catch(() => []), []);
+ });
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
+
+test("a bypassed directory captures nothing and leaves no state behind", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-capture-bypass-"));
+ const transcriptPath = join(stateDir, "transcript.jsonl");
+ const scratchDir = join(stateDir, "scratch");
+ const keepDir = join(stateDir, "keep");
+
+ try {
+ await mkdir(scratchDir, { recursive: true });
+ await mkdir(keepDir, { recursive: true });
+ await writeFile(transcriptPath, JSON.stringify({
+ payload: { message: { role: "user", content: "throwaway experiment" } },
+ }));
+
+ const env = (baseUrl) => ({
+ OPENVIKING_CODEX_STATE_DIR: stateDir,
+ OPENVIKING_HOME: join(stateDir, "home"),
+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_WRITE_PATH_ASYNC: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_BYPASS_SESSION_PATTERNS: "**/scratch",
+ OPENVIKING_URL: baseUrl,
+ });
+
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
+ await readRequestBody(req);
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "GET" && url.pathname.startsWith("/api/v1/sessions/")) {
+ writeJson(res, { status: "ok", result: { pending_tokens: 0 } });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
+ }, async (baseUrl, requests) => {
+ const off = await runAutoCapture(
+ { session_id: "cx-bypassed", transcript_path: transcriptPath, cwd: scratchDir },
+ env(baseUrl),
+ );
+ assert.deepEqual(JSON.parse(off.stdout.trim()), {});
+ const paths = () => requests.map(({ path }) => path);
+ assert.deepEqual(paths(), [], "a bypassed directory must not reach the server at all");
+ assert.equal(
+ (await readdir(stateDir)).includes("cx-bypassed.json"),
+ false,
+ "no session state should be written for a bypassed directory",
+ );
+
+ await runAutoCapture(
+ { session_id: "cx-kept", transcript_path: transcriptPath, cwd: keepDir },
+ env(baseUrl),
+ );
+ assert.ok(
+ paths().some((path) => path.endsWith("/messages/batch")),
+ `the same env must still capture outside the pattern; paths=${JSON.stringify(paths())}`,
);
});
} finally {
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjs
index fdceb4342..9e745c482 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs
@@ -32,13 +32,15 @@ import {
normalizeContextEntry,
postRecall,
} from "./shared/recall-core.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
+import { createOvHttp } from "./shared/ov-http.mjs";
import { compressRecallContext } from "./shared/recall-compress-core.mjs";
import { applyInputFilters, compileInputFilters } from "./shared/input-filters.mjs";
import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
let cfg = loadConfig();
const { log, logError } = createLogger("auto-recall");
-let effectivePeer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });
+let effectivePeer = { peerId: "" };
let emitted = false;
let activeCompressor = null;
@@ -95,36 +97,17 @@ recallDeadline = setTimeout(() => {
}, cfg.recallTimeoutMs);
recallDeadline.unref?.();
-async function fetchJSON(path, init = {}, options = {}) {
- const controller = new AbortController();
- const timer = setTimeout(
- () => controller.abort(),
- Math.max(1000, Number(options.timeoutMs) || cfg.timeoutMs),
- );
- try {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) {
- headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- headers["X-API-Key"] = cfg.apiKey;
- }
- if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
- if (effectivePeer.peerId) headers["X-OpenViking-Actor-Peer"] = effectivePeer.peerId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
- const body = await res.json().catch(() => null);
- if (!body) return { ok: false, status: res.status };
- if (!res.ok || body.status === "error") {
- return { ok: false, status: res.status, error: body.error || body };
- }
- return { ok: true, result: body.result ?? body };
- } catch {
- return { ok: false, status: 0 };
- } finally {
- clearTimeout(timer);
- }
+// Rebuilt after the hook reloads config for the payload's directory.
+function makeFetchJSON() {
+ return createOvHttp(cfg, {
+ defaultTimeoutMs: cfg.timeoutMs,
+ resolveActorPeerId: () => effectivePeer.peerId,
+ requireJsonBody: true,
+ });
}
+let fetchJSON = makeFetchJSON();
+
// ---------------------------------------------------------------------------
// Ranking
// ---------------------------------------------------------------------------
@@ -553,29 +536,16 @@ async function compressMemoryContext(userPrompt, rendered, items, shortContext =
}
}
-async function main() {
- let input;
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString());
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- emit();
- return;
- }
-
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- const cwd = typeof input.cwd === "string" && input.cwd.trim() ? input.cwd : process.cwd();
- cfg = loadConfig(cwd);
+runHookStage({
+ loadConfig,
+ gates: { enabled: (reloaded) => reloaded.autoRecall },
+ envelope: emit,
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+}, async (stage) => {
+ const { input, cwd } = stage;
+ cfg = stage.cfg;
effectivePeer = resolveEffectivePeerId({ cfg, cwd });
-
- if (!cfg.autoRecall) {
- log("skip", { stage: "init", reason: "autoRecall disabled" });
- emit();
- return;
- }
+ fetchJSON = makeFetchJSON();
let userPrompt = (input.prompt || "").trim();
const codexSessionId = typeof input.session_id === "string" ? input.session_id.trim() : "";
@@ -610,14 +580,12 @@ async function main() {
if (!userPrompt || userPrompt.length < cfg.minQueryLength) {
log("skip", { stage: "query_check", reason: "query too short or empty" });
- emit();
return;
}
const health = await fetchJSON("/health");
if (!health.ok) {
logError("health_check", "server unreachable or unhealthy");
- emit();
return;
}
@@ -625,7 +593,6 @@ async function main() {
if (endpointRecall !== null) {
if (!endpointRecall.context && endpointRecall.items.length === 0) {
log("skip", { stage: "recall_endpoint", reason: "no results" });
- emit();
return;
}
const compressedContext = endpointRecall.items.length > 0
@@ -639,7 +606,6 @@ async function main() {
: compressedContext;
if (!memoryContext) {
log("skip", { stage: "recall_endpoint", reason: "compressor found no relevant memory" });
- emit();
return;
}
log("recall_endpoint", {
@@ -647,15 +613,13 @@ async function main() {
compressed: compressedContext !== null,
entryCount: endpointRecall.items.length,
});
- emit(memoryContext);
- return;
+ return memoryContext;
}
const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
const allMemories = await searchAll(userPrompt, candidateLimit, recallSessionId);
if (allMemories.length === 0) {
log("skip", { stage: "search", reason: "no results" });
- emit();
return;
}
@@ -681,7 +645,6 @@ async function main() {
const memories = pickMemories(processed, cfg.recallLimit, userPrompt);
if (memories.length === 0) {
log("skip", { stage: "pick", reason: "no memories survived ranking" });
- emit();
return;
}
@@ -710,9 +673,5 @@ async function main() {
memoryItems,
fallbackContext,
);
- const memoryContext = compressedContext === null ? fallbackContext : compressedContext;
-
- emit(memoryContext);
-}
-
-main().catch((err) => { logError("uncaught", err); emit(); });
+ return compressedContext === null ? fallbackContext : compressedContext;
+}).catch((err) => { logError("uncaught", err); emit(); });
diff --git a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
index a6aa7fd5f..a4cbdea6b 100644
--- a/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
+++ b/examples/codex-memory-plugin/scripts/auto-recall.test.mjs
@@ -1,11 +1,12 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { delimiter, dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
import { resolveCodexLaunch, trySpawnCodex } from "./codex-launch.mjs";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
@@ -37,48 +38,11 @@ test("Codex launch converts a synchronous spawn failure into a fallback signal",
assert.equal(result.error, failure);
});
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try {
- resolve(raw ? JSON.parse(raw) : null);
- } catch (err) {
- reject(err);
- }
- });
- req.on("error", reject);
- });
-}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
function writeStatusJson(res, status, value) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(value));
}
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- handler(req, res).catch((err) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
function runAutoRecall(input, env) {
return new Promise((resolve, reject) => {
const cleanEnv = { ...process.env };
@@ -522,6 +486,31 @@ test("auto-recall gives the compressor full content from the raw-search fallback
}
});
+test("auto-recall repairs a mangled viking:// URI in the compressed digest", async () => {
+ const uri = "viking://user/zeus/memories/preferences/editor.md";
+ const result = await runEndpointCompressionCase({
+ prompt: "Which editor do I prefer?",
+ entry: {
+ uri,
+ score: 0.91,
+ type: "preferences",
+ mode: "summary",
+ summary: "Use Vim",
+ },
+ rendered: "<memory_group>Use Vim</memory_group>",
+ compressorOutput: [
+ "OpenViking memory digest:",
+ "- [preferences] Use Vim (viking://user/zeus/memories/preference/edtior.md)",
+ ].join("\n"),
+ extraEnv: { OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS: "0" },
+ });
+
+ const injected = result.output.hookSpecificOutput.additionalContext;
+ assert.ok(injected.includes(`(${uri})`), injected);
+ assert.ok(!injected.includes("edtior"), injected);
+ assert.equal(result.compressorCalls, 1);
+});
+
test("auto-recall passes the configured compressor base URL to Codex", async () => {
const result = await runEndpointCompressionCase({
prompt: "Explain HTTP 429",
@@ -835,6 +824,83 @@ test("the actor peer comes from the workspace named by the payload's cwd", async
}
});
+test("a bypassed directory gets no injected memory and makes no request", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-bypass-"));
+ const scratchDir = join(stateDir, "scratch");
+ const keepDir = join(stateDir, "keep");
+
+ try {
+ await mkdir(scratchDir, { recursive: true });
+ await mkdir(keepDir, { recursive: true });
+
+ const env = (baseUrl) => ({
+ OPENVIKING_AUTO_RECALL: "1",
+ OPENVIKING_CODEX_STATE_DIR: stateDir,
+ OPENVIKING_STATE_DIR: stateDir,
+ OPENVIKING_HOME: join(stateDir, "home"),
+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_RECALL_COMPRESS: "0",
+ OPENVIKING_RECALL_LIMIT: "1",
+ OPENVIKING_RECALL_TIMEOUT_MS: "10000",
+ OPENVIKING_MIN_QUERY_LENGTH: "1",
+ OPENVIKING_SCORE_THRESHOLD: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_BYPASS_SESSION_PATTERNS: "**/scratch",
+ OPENVIKING_URL: baseUrl,
+ });
+
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname === "/api/v1/search/search") {
+ await readRequestBody(req);
+ writeJson(res, {
+ status: "ok",
+ result: {
+ entries: [{
+ uri: "viking://user/zeus/memories/events/leak.md",
+ category: "events",
+ detail: "full",
+ score: 0.9,
+ text: "memory that must not reach a bypassed session",
+ }],
+ rendered: "memory that must not reach a bypassed session",
+ digest: "",
+ stats: { returned: 1, used_tokens: 40 },
+ },
+ });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
+ }, async (baseUrl, requests) => {
+ const off = await runAutoRecall(
+ { prompt: "please use prior context", session_id: "cx-bypassed", cwd: scratchDir },
+ env(baseUrl),
+ );
+ assert.deepEqual(JSON.parse(off.stdout.trim()), {});
+ assert.deepEqual(requests, [], "a bypassed directory must not reach the server at all");
+
+ const on = await runAutoRecall(
+ { prompt: "please use prior context", session_id: "cx-kept", cwd: keepDir },
+ env(baseUrl),
+ );
+ assert.match(
+ JSON.parse(on.stdout.trim()).hookSpecificOutput.additionalContext,
+ /must not reach a bypassed session/,
+ "the same env must still recall outside the pattern",
+ );
+ });
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
+
function filterEnv(stateDir, baseUrl, filters) {
return {
OPENVIKING_AUTO_RECALL: "1",
@@ -917,3 +983,69 @@ test("a query stripped to nothing never reaches the server", async () => {
await rm(stateDir, { recursive: true, force: true });
}
});
+
+test("auto-recall authenticates with Bearer alone and gates the identity headers", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-auto-recall-headers-"));
+ const seen = [];
+
+ const env = (baseUrl, identity) => ({
+ OPENVIKING_AUTO_RECALL: "1",
+ OPENVIKING_CODEX_STATE_DIR: stateDir,
+ OPENVIKING_STATE_DIR: stateDir,
+ OPENVIKING_HOME: join(stateDir, "home"),
+ OPENVIKING_CONFIG_FILE: join(stateDir, "missing-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(stateDir, "missing-ovcli.conf"),
+ OPENVIKING_CREDENTIAL_SOURCE: "env",
+ OPENVIKING_RECALL_COMPRESS: "0",
+ OPENVIKING_RECALL_LIMIT: "1",
+ OPENVIKING_RECALL_TIMEOUT_MS: "10000",
+ OPENVIKING_MIN_QUERY_LENGTH: "1",
+ OPENVIKING_SCORE_THRESHOLD: "0",
+ OPENVIKING_TIMEOUT_MS: "5000",
+ OPENVIKING_API_KEY: "recall-key",
+ OPENVIKING_URL: baseUrl,
+ ...identity,
+ });
+ try {
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname === "/api/v1/search/search") {
+ seen.push(req.headers);
+ await readRequestBody(req);
+ writeJson(res, {
+ status: "ok",
+ result: { entries: [], rendered: "", digest: "", stats: { returned: 0 } },
+ });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
+ }, async (baseUrl) => {
+ await runAutoRecall(
+ { prompt: "please use prior context", session_id: "cx-trusted" },
+ env(baseUrl, { OPENVIKING_ACCOUNT: "acct-a", OPENVIKING_USER: "user-a" }),
+ );
+ await runAutoRecall(
+ { prompt: "please use prior context", session_id: "cx-api-key" },
+ env(baseUrl, {}),
+ );
+ });
+
+ assert.equal(seen.length, 2);
+ const [trusted, apiKey] = seen;
+ assert.equal(trusted.authorization, "Bearer recall-key");
+ assert.equal(trusted["x-api-key"], undefined);
+ assert.equal(trusted["x-openviking-account"], "acct-a");
+ assert.equal(trusted["x-openviking-user"], "user-a");
+ assert.equal(apiKey.authorization, "Bearer recall-key");
+ assert.equal(apiKey["x-api-key"], undefined);
+ assert.equal(apiKey["x-openviking-account"], undefined);
+ assert.equal(apiKey["x-openviking-user"], undefined);
+ } finally {
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/codex-memory-plugin/scripts/capture-utils.mjs b/examples/codex-memory-plugin/scripts/capture-utils.mjs
index 3eff567cb..508907d35 100644
--- a/examples/codex-memory-plugin/scripts/capture-utils.mjs
+++ b/examples/codex-memory-plugin/scripts/capture-utils.mjs
@@ -2,7 +2,10 @@ import {
extractCaptureTurns as extractSharedCaptureTurns,
} from "./shared/capture-utils.mjs";
-export * from "./shared/capture-utils.mjs";
+// Named one by one rather than re-exported wholesale: this module has an
+// `extractCaptureTurns` of its own, and `export *` would let the shared one
+// through under the same name with nothing to say which a caller holds.
+export { findLastHumanTurnIndex } from "./shared/capture-utils.mjs";
function mcpResultText(result) {
let value = result;
@@ -356,21 +359,3 @@ export function extractCaptureTurns(rolloutEntries, cfg = {}) {
const normalized = normalizeCodexNativeToolEvents(deduplicated);
return extractSharedCaptureTurns(normalizeCodexCompletedToolEvents(normalized), cfg);
}
-
-/**
- * Index of the last turn that came from a human prompt, or -1.
- *
- * `role === "user"` alone is not enough: normalizeCaptureRole() maps tool
- * results onto the user role too, and those carry `tool` parts rather than
- * `text` parts. Used by the post-compact shrink path to find where the current
- * interaction starts.
- */
-export function findLastHumanTurnIndex(turns) {
- const list = Array.isArray(turns) ? turns : [];
- for (let i = list.length - 1; i >= 0; i -= 1) {
- const turn = list[i];
- if (turn?.role !== "user") continue;
- if (turn.parts?.some((part) => part?.type === "text")) return i;
- }
- return -1;
-}
diff --git a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
index 040ee91b9..cd09baedb 100644
--- a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
+++ b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { extractCaptureTurns, findLastHumanTurnIndex } from "./capture-utils.mjs";
+import { extractCaptureTurns } from "./capture-utils.mjs";
const CAPTURE_CONFIG = {
captureAssistantTurns: true,
@@ -1033,35 +1033,3 @@ test("captureToolMaxChars still caps tool output when an operator lowers it", ()
assert.ok(completed.tool_output.length <= 1000);
assert.match(completed.tool_output, /\[truncated\]$/);
});
-
-test("findLastHumanTurnIndex skips tool results mapped onto the user role", () => {
- const turns = extractCaptureTurns(
- [
- { payload: { message: { role: "user", content: "compacted historical summary" } } },
- { payload: { message: { role: "user", content: "current user request" } } },
- { payload: { type: "function_call", id: "call-1", name: "shell", arguments: "{}" } },
- { payload: { type: "function_call_output", call_id: "call-1", output: "tool result" } },
- { payload: { message: { role: "assistant", content: "current assistant response" } } },
- ],
- CAPTURE_CONFIG,
- );
-
- const index = findLastHumanTurnIndex(turns);
- assert.equal(turns[index].text, "current user request");
- assert.equal(turns.at(-2).role, "user");
- assert.equal(turns.at(-2).parts[0].type, "tool");
-});
-
-test("findLastHumanTurnIndex reports -1 when no human turn survives", () => {
- const turns = extractCaptureTurns(
- [
- { payload: { type: "function_call", id: "call-1", name: "shell", arguments: "{}" } },
- { payload: { type: "function_call_output", call_id: "call-1", output: "tool result" } },
- { payload: { message: { role: "assistant", content: "assistant only" } } },
- ],
- CAPTURE_CONFIG,
- );
-
- assert.equal(findLastHumanTurnIndex(turns), -1);
- assert.equal(findLastHumanTurnIndex([]), -1);
-});
diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjs
index 72a29ac7b..7a1e36969 100644
--- a/examples/codex-memory-plugin/scripts/config.mjs
+++ b/examples/codex-memory-plugin/scripts/config.mjs
@@ -1,5 +1,16 @@
/**
- * Shared configuration loader for the Codex OpenViking memory plugin.
+ * Configuration for the Codex OpenViking memory plugin.
+ *
+ * Every knob is declared once in `shared/config-schema.mjs` and the whole
+ * configuration is assembled by `buildPluginConfig()`, which reads the layers
+ * in this order:
+ *
+ * env (OPENVIKING_*) → workspace `.openviking/config*.json` and the machine
+ * registry → ovcli.conf `plugin.codex` → ovcli.conf `plugin` → ov.conf's
+ * `codex` section (legacy) → the schema's defaults
+ *
+ * What stays here is what only this harness knows: how it reads the digest
+ * switch, and what counts as having configured a compressor.
*
* Credential source:
* - Default (auto): env-var credentials win when any credential env var is
@@ -9,8 +20,6 @@
* force env-var credentials.
* - Without env vars or ovcli.conf, ov.conf/defaults are used.
*
- * Tuning resolution remains env vars > ov.conf codex.* > built-in defaults.
- *
* The stdio MCP proxy calls the same resolver directly. Aligning the resolver
* prevents identity drift between auto-capture/auto-recall hooks, MCP calls,
* and child `ov` commands launched from inside Codex.
@@ -29,54 +38,11 @@
* OPENVIKING_API_KEY / OPENVIKING_BEARER_TOKEN
* OPENVIKING_AUTH_MODE
* OPENVIKING_ACCOUNT, OPENVIKING_USER, OPENVIKING_PEER_ID
- *
- * Misc env vars:
- * OPENVIKING_TIMEOUT_MS, OPENVIKING_CAPTURE_TIMEOUT_MS
- * OPENVIKING_RECALL_TIMEOUT_MS, OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS
- * OPENVIKING_RECALL_COMPRESS_MODEL, OPENVIKING_RECALL_COMPRESS_THINKING
- * OPENVIKING_RECALL_COMPRESS_BASE_URL
- * OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS
- * OPENVIKING_RECALL_LIMIT, OPENVIKING_SCORE_THRESHOLD
- * OPENVIKING_WORKSPACE_PEER, OPENVIKING_RECALL_PEER_SCOPE
- * OPENVIKING_NO_AUTO_INJECT, OPENVIKING_PROFILE_TOKEN_BUDGET
- * OPENVIKING_RECALL_QUERY_FILTERS (CSV), OPENVIKING_CAPTURE_FILTERS (CSV)
- * OPENVIKING_DEBUG=1, OPENVIKING_DEBUG_LOG
*/
-import { homedir } from "node:os";
-import { join } from "node:path";
-import { resolveOpenVikingCredentials } from "./ov-credentials.mjs";
-import { buildUserAgent, readManifestVersion } from "./shared/credentials.mjs";
-import { HARNESS_KEYS, loadPluginSettings } from "./shared/plugin-config.mjs";
+import { buildPluginConfig } from "./shared/plugin-config.mjs";
-const USER_AGENT = buildUserAgent(
- "codex",
- readManifestVersion(new URL("../.codex-plugin/plugin.json", import.meta.url)),
-);
-
-function num(val, fallback) {
- if (typeof val === "number" && Number.isFinite(val)) return val;
- if (typeof val === "string" && val.trim()) {
- const n = Number(val);
- if (Number.isFinite(n)) return n;
- }
- return fallback;
-}
-
-function str(val, fallback) {
- if (typeof val === "string" && val.trim()) return val.trim();
- return fallback;
-}
-
-function envBool(name) {
- const v = process.env[name];
- if (v == null || v === "") return undefined;
- const lower = v.trim().toLowerCase();
- if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false;
- if (lower === "1" || lower === "true" || lower === "yes" || lower === "on"
- || lower === "auto" || lower === "client") return true;
- return undefined;
-}
+const MANIFEST_URL = new URL("../.codex-plugin/plugin.json", import.meta.url);
function configBool(value, fallback) {
if (typeof value === "boolean") return value;
@@ -87,27 +53,6 @@ function configBool(value, fallback) {
return fallback;
}
-function hasOwn(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj || {}, key);
-}
-
-/**
- * A configured list of input filter rules. An env CSV replaces the configured
- * array entirely; both paths trim, so a rule reads the same however it was
- * configured — and a rule needing a literal comma has to come from the array,
- * since the env value is split on one.
- */
-function filterList(envName, configured) {
- const raw = str(process.env[envName], null);
- const list = raw !== null ? raw.split(",") : (Array.isArray(configured) ? configured : []);
- return list.filter((r) => typeof r === "string").map((r) => r.trim()).filter(Boolean);
-}
-
-function normalizeAuthMode(val) {
- const mode = str(val, "").toLowerCase();
- return ["trusted", "api_key"].includes(mode) ? mode : "";
-}
-
/**
* `cwd` selects the workspace layer (`.openviking/config.json` and the registry
* entry for that directory). It defaults to this process's directory, which is
@@ -117,217 +62,19 @@ function normalizeAuthMode(val) {
* cannot move — loggers and fetch helpers built from the first load stay valid.
*/
export function loadConfig(cwd = process.cwd()) {
- const creds = resolveOpenVikingCredentials();
- const { cliPath, ovFile, ovPath } = creds;
- const configPath = cliPath || ovPath || null;
-
- // ovcli.conf plugin.<harness> overrides plugin.* which overrides ov.conf's
- // codex section, so client-side tuning no longer needs a server config.
- const workspaceCwd = str(cwd, "") || process.cwd();
- const pluginSettings = loadPluginSettings(HARNESS_KEYS.codex, process.env, { cwd: workspaceCwd });
- const cx = { ...(ovFile.codex || {}), ...pluginSettings };
- const server = ovFile.server || {};
- const explicitAuthMode = normalizeAuthMode(process.env.OPENVIKING_AUTH_MODE)
- || normalizeAuthMode(cx.authMode)
- || normalizeAuthMode(cx.auth_mode)
- || normalizeAuthMode(server.auth_mode);
- const authMode = explicitAuthMode || ((creds.account || creds.user) ? "trusted" : "api_key");
-
- // A workspace file's `peer.id` (and ovcli.conf's plugin.codex.peerId) is
- // projected into pluginSettings; reading only the credential chain dropped it.
- // A repository's pin is the more specific answer, so it outranks the file peer
- // that chain ends in — but not OPENVIKING_PEER_ID, and not a credential source
- // pinned to ovcli.conf, where env peers are meant not to apply. ov.conf's
- // codex.peerId stays where it was, behind ovcli.conf, inside creds.peerId.
- const envPeerId = creds.credentialSource === "ovcli"
- ? null
- : str(process.env.OPENVIKING_PEER_ID, null);
- const peerId = envPeerId
- || str(pluginSettings.peerId, null)
- || str(pluginSettings.peer_id, null)
- || creds.peerId;
-
- const debug = envBool("OPENVIKING_DEBUG") ?? (cx.debug === true);
- const defaultLogPath = join(homedir(), ".openviking", "logs", "codex-hooks.log");
- const debugLogPath = str(process.env.OPENVIKING_DEBUG_LOG, defaultLogPath);
- const workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? (cx.workspacePeer !== false);
- const recallPeerScopeRaw = str(
- process.env.OPENVIKING_RECALL_PEER_SCOPE,
- str(cx.recallPeerScope, "all"),
- );
- const recallPeerScope = recallPeerScopeRaw === "actor" ? "actor" : "all";
-
- const timeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_TIMEOUT_MS,
- num(cx.timeoutMs, 15000),
- )));
- const captureTimeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_TIMEOUT_MS,
- num(cx.captureTimeoutMs, Math.max(timeoutMs * 2, 30000)),
- )));
- const recallTimeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RECALL_TIMEOUT_MS,
- num(cx.recallTimeoutMs, 120000),
- )));
- const defaultRecallCompressTimeoutMs = Math.max(1000, recallTimeoutMs - 10000);
- const recallCompressTimeoutMs = Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS,
- num(cx.recallCompressTimeoutMs, defaultRecallCompressTimeoutMs),
- )));
- const recallCompressModel = str(
- process.env.OPENVIKING_RECALL_COMPRESS_MODEL,
- hasOwn(cx, "recallCompressModel") ? str(cx.recallCompressModel, "") : "",
- );
- const recallCompressBaseUrl = str(
- process.env.OPENVIKING_RECALL_COMPRESS_BASE_URL,
- hasOwn(cx, "recallCompressBaseUrl") ? str(cx.recallCompressBaseUrl, "") : "",
- );
- const cxRecallCompressThinking = hasOwn(cx, "recallCompressThinking")
- ? cx.recallCompressThinking
- : (hasOwn(cx, "recallCompressReasoningEffort") ? cx.recallCompressReasoningEffort : "");
- const recallCompressThinking = str(
- process.env.OPENVIKING_RECALL_COMPRESS_THINKING,
- str(
- process.env.OPENVIKING_RECALL_COMPRESS_REASONING_EFFORT,
- str(cxRecallCompressThinking, ""),
- ),
- );
+ const config = buildPluginConfig("codex", {
+ cwd,
+ manifestUrl: MANIFEST_URL,
+ logFile: "codex-hooks.log",
+ });
return {
- configPath,
- cliConfigPath: cliPath,
- ovConfigPath: ovPath,
- credentialSource: creds.credentialSource,
- baseUrl: creds.baseUrl,
- authMode,
- sendIdentityHeaders: authMode === "trusted",
- apiKey: creds.apiKey,
- account: creds.account,
- user: creds.user,
- peerId,
- workspacePeer,
- peerSource: str(process.env.OPENVIKING_PEER_SOURCE, null) ?? cx.peerSource,
- harness: "codex",
- userAgent: USER_AGENT,
- timeoutMs,
- recallTimeoutMs,
-
- autoRecall: envBool("OPENVIKING_AUTO_RECALL") ?? (cx.autoRecall !== false),
- recallLimit: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_RECALL_LIMIT,
- num(cx.recallLimit, 10),
- ))),
- recallLimitConfigured: Boolean(process.env.OPENVIKING_RECALL_LIMIT) ||
- hasOwn(cx, "recallLimit"),
- scoreThreshold: Math.min(1, Math.max(0, num(
- process.env.OPENVIKING_SCORE_THRESHOLD,
- num(cx.scoreThreshold, 0.35),
- ))),
- minQueryLength: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_MIN_QUERY_LENGTH,
- num(cx.minQueryLength, 3),
- ))),
- // Ordered sed-style rules over the text the plugin sends: the recall query
- // on the UserPromptSubmit hook, and every captured turn on the write path.
- recallQueryFilters: filterList("OPENVIKING_RECALL_QUERY_FILTERS", cx.recallQueryFilters),
- captureFilters: filterList("OPENVIKING_CAPTURE_FILTERS", cx.captureFilters),
- logRankingDetails: envBool("OPENVIKING_LOG_RANKING_DETAILS") ?? (cx.logRankingDetails === true),
- recallPeerScope,
- recallCompress: envBool("OPENVIKING_RECALL_COMPRESS") ?? configBool(cx.recallCompress, true),
- recallCompressModel,
- recallCompressBaseUrl,
- recallCompressThinking,
- recallCompressConfigured: Boolean(recallCompressModel || recallCompressThinking),
- recallCompressTimeoutMs,
- recallCompressDetectOnStartup: envBool("OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP") ?? (cx.recallCompressDetectOnStartup !== false),
- recallCompressDetectTimeoutMs: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS,
- num(cx.recallCompressDetectTimeoutMs, 15000),
- ))),
- recallCompressDetectTtlMs: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS,
- num(cx.recallCompressDetectTtlMs, 604800000),
- ))),
- recallCompressMinInputChars: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS,
- num(cx.recallCompressMinInputChars, 1500),
- ))),
- recallCompressMaxInputChars: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS,
- num(cx.recallCompressMaxInputChars, 18000),
- ))),
- recallCompressMaxBullets: Math.max(1, Math.floor(num(
- process.env.OPENVIKING_RECALL_COMPRESS_MAX_BULLETS,
- num(cx.recallCompressMaxBullets, 6),
- ))),
- recallCompressMaxBulletsConfigured:
- Boolean(process.env.OPENVIKING_RECALL_COMPRESS_MAX_BULLETS) ||
- hasOwn(cx, "recallCompressMaxBullets"),
-
- // Server-side context assembly (/search mode="context").
- recallMaxTokens: Math.max(64, Math.floor(num(
- process.env.OPENVIKING_RECALL_MAX_TOKENS,
- num(cx.recallMaxTokens, 1600),
- ))),
- recallMaxTokensConfigured: Boolean(process.env.OPENVIKING_RECALL_MAX_TOKENS) ||
- hasOwn(cx, "recallMaxTokens"),
- recallDedupTurns: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RECALL_DEDUP_TURNS,
- num(cx.recallDedupTurns, 5),
- ))),
- recallQueryExpansion: str(
- process.env.OPENVIKING_RECALL_QUERY_EXPANSION,
- str(cx.recallQueryExpansion, "auto"),
- ) === "off" ? "off" : "auto",
- recallQueryExpansionConfigured: Boolean(process.env.OPENVIKING_RECALL_QUERY_EXPANSION) ||
- hasOwn(cx, "recallQueryExpansion"),
-
- autoCapture: envBool("OPENVIKING_AUTO_CAPTURE") ?? (cx.autoCapture !== false),
- captureMode: (str(process.env.OPENVIKING_CAPTURE_MODE, str(cx.captureMode, "semantic")) === "keyword")
- ? "keyword"
- : "semantic",
- captureMaxLength: Math.max(200, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_MAX_LENGTH,
- num(cx.captureMaxLength, 24000),
- ))),
- captureTimeoutMs,
- captureToolMaxChars: Math.max(200, Math.floor(num(
- process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS,
- num(cx.captureToolMaxChars, 1000000),
- ))),
- writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC") ?? (cx.writePathAsync !== false),
- // Default true: a "memory plugin" without assistant-side capture only sees half the
- // conversation, which makes extraction noticeably worse. Mirrors the claude-code plugin
- // (examples/claude-code-memory-plugin/scripts/config.mjs). Operators who want the old
- // user-only behavior can set OPENVIKING_CAPTURE_ASSISTANT_TURNS=0 or codex.captureAssistantTurns=false.
- captureAssistantTurns: envBool("OPENVIKING_CAPTURE_ASSISTANT_TURNS") ?? (cx.captureAssistantTurns !== false),
- captureLastAssistantOnStop: envBool("OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP") ?? (cx.captureLastAssistantOnStop !== false),
- commitTokenThreshold: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD,
- num(cx.commitTokenThreshold, 20000),
- ))),
- commitKeepRecentCount: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT,
- num(cx.commitKeepRecentCount, 10),
- ))),
-
- autoCommitOnCompact: envBool("OPENVIKING_AUTO_COMMIT_ON_COMPACT") ?? (cx.autoCommitOnCompact !== false),
- noAutoInject: envBool("OPENVIKING_NO_AUTO_INJECT") ?? (cx.noAutoInject === true),
- profileTokenBudget: Math.max(500, Math.floor(num(
- process.env.OPENVIKING_PROFILE_TOKEN_BUDGET,
- num(cx.profileTokenBudget, 10000),
- ))),
- resumeArchiveInject: envBool("OPENVIKING_RESUME_ARCHIVE_INJECT") ?? (cx.resumeArchiveInject !== false),
- resumeArchiveTokenBudget: Math.max(0, Math.floor(num(
- process.env.OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET,
- num(cx.resumeArchiveTokenBudget, 32000),
- ))),
- resumeArchiveMaxChars: Math.max(1000, Math.floor(num(
- process.env.OPENVIKING_RESUME_ARCHIVE_MAX_CHARS,
- num(cx.resumeArchiveMaxChars, 6000),
- ))),
-
- debug,
- debugLogPath,
+ ...config,
+ // Codex reads the compression knob as on/off; "auto" and "client" are the
+ // Claude Code spellings of on, and mean the same thing here.
+ recallCompress: configBool(config.recallCompress, true),
+ // Not `configured.has`: what makes a compressor configured here is having
+ // been told which model to run, not having named the switch.
+ recallCompressConfigured: Boolean(config.recallCompressModel || config.recallCompressThinking),
};
}
diff --git a/examples/codex-memory-plugin/scripts/config.test.mjs b/examples/codex-memory-plugin/scripts/config.test.mjs
index 4032538e7..6f568983a 100644
--- a/examples/codex-memory-plugin/scripts/config.test.mjs
+++ b/examples/codex-memory-plugin/scripts/config.test.mjs
@@ -4,17 +4,22 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { loadConfig } from "./config.mjs";
+import { isBypassed } from "./shared/session-model.mjs";
+// The layers, the knobs and the peer are the shared loader's, and
+// memory-plugin-shared/plugin-config.test.mjs holds this harness to them. What
+// is left here is the compression switch this harness reads as a boolean, and
+// the bypass patterns it is the only harness to resolve from every layer.
const OVERRIDES = [
"OPENVIKING_CONFIG_FILE",
"OPENVIKING_CLI_CONFIG_FILE",
"OPENVIKING_HOME",
"OPENVIKING_STATE_DIR",
- "OPENVIKING_CREDENTIAL_SOURCE",
- "OPENVIKING_CREDENTIALS_SOURCE",
- "OPENVIKING_PEER_ID",
- "OPENVIKING_PEER_SOURCE",
- "OPENVIKING_AUTO_CAPTURE",
+ "OPENVIKING_BYPASS_SESSION",
+ "OPENVIKING_BYPASS_SESSION_PATTERNS",
+ "OPENVIKING_RECALL_COMPRESS",
+ "OPENVIKING_RECALL_COMPRESS_MODEL",
+ "OPENVIKING_RECALL_COMPRESS_THINKING",
"OPENVIKING_URL",
"OPENVIKING_BASE_URL",
"OPENVIKING_API_KEY",
@@ -60,86 +65,73 @@ function withConfigs({ ov, cli, workspace, env = {} }, fn) {
}
}
-test("a workspace file's peer.id is the peer this directory writes under", () => {
+test("a repository can carry the bypass patterns its contributors share", () => {
withConfigs({
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", actor_peer_id: "cli-peer" },
- workspace: { version: 1, peer: { id: "team-a" } },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
+ workspace: { version: 1, bypass: { session_patterns: ["**/workspace"] } },
}, ({ workspaceDir, otherDir }) => {
- assert.equal(loadConfig(workspaceDir).peerId, "team-a");
- // Same process, another directory: the ovcli.conf peer is untouched.
- assert.equal(loadConfig(otherDir).peerId, "cli-peer");
- });
-});
+ const inside = loadConfig(workspaceDir);
+ assert.deepEqual(inside.bypassSessionPatterns, ["**/workspace"]);
+ assert.equal(isBypassed(inside, { cwd: workspaceDir }), true);
-test("OPENVIKING_PEER_ID still outranks a workspace peer.id", () => {
- withConfigs({
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", actor_peer_id: "cli-peer" },
- workspace: { version: 1, peer: { id: "team-a" } },
- env: { OPENVIKING_PEER_ID: "env-peer" },
- }, ({ workspaceDir }) => {
- assert.equal(loadConfig(workspaceDir).peerId, "env-peer");
+ const outside = loadConfig(otherDir);
+ assert.deepEqual(outside.bypassSessionPatterns, []);
+ assert.equal(isBypassed(outside, { cwd: otherDir }), false);
});
});
-test("a credential source pinned to ovcli.conf ignores the env peer", () => {
+test("the bypass env vars override the file, matching every other harness", () => {
withConfigs({
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", actor_peer_id: "cli-peer" },
- env: { OPENVIKING_PEER_ID: "env-peer", OPENVIKING_CREDENTIAL_SOURCE: "cli" },
+ ov: { codex: { bypassSessionPatterns: ["/from/ov-conf"] } },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
+ env: {
+ OPENVIKING_BYPASS_SESSION_PATTERNS: "/from/env, /also/env ,",
+ OPENVIKING_BYPASS_SESSION: "1",
+ },
}, ({ otherDir }) => {
- assert.equal(loadConfig(otherDir).peerId, "cli-peer");
+ const cfg = loadConfig(otherDir);
+ assert.deepEqual(cfg.bypassSessionPatterns, ["/from/env", "/also/env"]);
+ assert.equal(cfg.bypassSession, true);
+ assert.equal(isBypassed(cfg, { cwd: "/anywhere" }), true, "the switch wins regardless of cwd");
});
});
-test("an ovcli.conf plugin.codex.peerId outranks the file's actor peer", () => {
+test("ov.conf's codex section still supplies the patterns when no env var does", () => {
withConfigs({
- cli: {
- url: "http://127.0.0.1:1933",
- api_key: "sk-cli",
- actor_peer_id: "cli-peer",
- plugin: { codex: { peerId: "plugin-peer" } },
- },
+ ov: { codex: { bypassSessionPatterns: ["/scratch/*", 7, " "] } },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
}, ({ otherDir }) => {
- assert.equal(loadConfig(otherDir).peerId, "plugin-peer");
+ const cfg = loadConfig(otherDir);
+ assert.deepEqual(cfg.bypassSessionPatterns, ["/scratch/*"]);
+ assert.equal(cfg.bypassSession, false);
});
});
-test("ov.conf's codex.peerId keeps its place behind ovcli.conf", () => {
+// This harness reads the shared compression knob as a boolean, and calls a
+// compressor configured only once it has been told what to run.
+test("the compression switch is a boolean here, and a model is what configures one", () => {
withConfigs({
- ov: { codex: { peerId: "ov-peer" } },
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", actor_peer_id: "cli-peer" },
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { recallCompress: "auto" } },
}, ({ otherDir }) => {
- assert.equal(loadConfig(otherDir).peerId, "cli-peer");
+ const cfg = loadConfig(otherDir);
+ assert.equal(cfg.recallCompress, true, "\"auto\" is the Claude Code spelling of on");
+ assert.equal(cfg.recallCompressConfigured, false, "naming the switch is not naming a compressor");
});
-});
-test("the workspace layer follows the cwd it is handed, not the process's", () => {
withConfigs({
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
- workspace: { version: 1, capture: { enabled: false }, recall: { max_items: 3 } },
- }, ({ workspaceDir, otherDir }) => {
- const inside = loadConfig(workspaceDir);
- assert.equal(inside.autoCapture, false);
- assert.equal(inside.recallLimit, 3);
-
- const outside = loadConfig(otherDir);
- assert.equal(outside.autoCapture, true);
- assert.equal(outside.recallLimit, 10);
+ cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli", plugin: { recallCompress: "off" } },
+ }, ({ otherDir }) => {
+ assert.equal(loadConfig(otherDir).recallCompress, false);
});
-});
-test("an omitted cwd falls back to this process's directory", () => {
withConfigs({
- cli: { url: "http://127.0.0.1:1933", api_key: "sk-cli" },
- workspace: { version: 1, capture: { enabled: false } },
- }, ({ workspaceDir }) => {
- const origin = process.cwd();
- try {
- process.chdir(workspaceDir);
- assert.equal(loadConfig().autoCapture, false);
- assert.equal(loadConfig("").autoCapture, false);
- } finally {
- process.chdir(origin);
- }
+ cli: {
+ url: "http://127.0.0.1:1933",
+ api_key: "sk-cli",
+ plugin: { codex: { recallCompressModel: "gpt-5.5" } },
+ },
+ }, ({ otherDir }) => {
+ assert.equal(loadConfig(otherDir).recallCompressConfigured, true);
});
});
diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.mjs b/examples/codex-memory-plugin/scripts/ov-credentials.mjs
deleted file mode 100644
index fc495c5c0..000000000
--- a/examples/codex-memory-plugin/scripts/ov-credentials.mjs
+++ /dev/null
@@ -1,30 +0,0 @@
-import { join, resolve as resolvePath } from "node:path";
-import { fileURLToPath } from "node:url";
-import {
- loadCredentialFiles,
- resolveOpenVikingCredentials,
-} from "./shared/credentials.mjs";
-
-export { loadCredentialFiles, resolveOpenVikingCredentials } from "./shared/credentials.mjs";
-
-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/codex-memory-plugin/scripts/ov-memory-doctor.mjs b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
index 1262e90ab..74181b42c 100644
--- a/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
+++ b/examples/codex-memory-plugin/scripts/ov-memory-doctor.mjs
@@ -25,32 +25,24 @@ import { fileURLToPath } from "node:url";
import { loadConfig } from "./config.mjs";
import { getStateDir } from "./session-state.mjs";
import {
- assessProbes,
- checkServerHealth,
- collectEnv,
- createReport,
- describeApiKey,
+ credentialSources,
existsPath,
fmtAge,
fmtBytes,
homeShort,
- inspectJsonFile,
- isLoopbackUrl,
- lintBaseUrl,
- parseNodeMajor,
- probeOpenViking,
+ inspectConfigFiles,
+ reportCredentials,
+ reportPeer,
+ reportTimeouts,
+ reportToggles,
runCommand,
+ runDoctor,
scanDebugLog,
scanRcFiles,
- unknownOvcliKeys,
- unknownPluginKeys,
- whichCommand,
- checkWorkspace,
- lintPeerScopeDowngrade,
- WORKSPACE_PEER_HINT,
+ sweepEnv,
+ tryJson,
} from "./shared/doctor-core.mjs";
import { describeInputFilters } from "./shared/input-filters.mjs";
-import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
const PLUGIN_ROOT = resolvePath(dirname(fileURLToPath(import.meta.url)), "..");
const PLUGIN_ID = "openviking-memory@openviking";
@@ -61,34 +53,8 @@ const CODEX_DIR = join(homedir(), ".codex");
const CODEX_CONFIG = process.env.CODEX_CONFIG_FILE || join(CODEX_DIR, "config.toml");
const CACHE_DIR = join(CODEX_DIR, "plugins", "cache", MARKETPLACE, PLUGIN_NAME);
const HOOK_EVENTS = ["session_start", "user_prompt_submit", "stop", "session_end", "pre_compact"];
-const RC_MARKERS = ["# >>> openviking-codex-plugin >>>", "codex-plugin.rc.sh"];
const REQUIRED_PLUGIN_FILES = [".codex-plugin/plugin.json", "hooks/hooks.json", ".mcp.json", "servers/mcp-proxy.mjs", "scripts/config.mjs", "scripts/auto-recall.mjs", "scripts/auto-capture.mjs", "scripts/session-end.mjs", "scripts/ov-session.mjs"];
-function parseArgs(argv) {
- const opts = { json: false, offline: false, timeoutMs: 5000, color: process.stdout.isTTY && !process.env.NO_COLOR };
- for (let i = 0; i < argv.length; i += 1) {
- const arg = argv[i];
- if (arg === "--json") opts.json = true;
- else if (arg === "--offline" || arg === "--no-network") opts.offline = true;
- else if (arg === "--no-color") opts.color = false;
- else if (arg === "--timeout") opts.timeoutMs = Math.max(1000, Number(argv[++i]) || 5000);
- else if (arg === "-h" || arg === "--help") {
- console.log("usage: ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]");
- process.exit(0);
- }
- }
- if (opts.json) opts.color = false;
- return opts;
-}
-
-function tryJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return null;
- }
-}
-
/**
* Minimal TOML reader — enough for config.toml's [section] headers (including
* quoted dotted names) and scalar `key = value` lines. Values keep their raw
@@ -129,20 +95,6 @@ function readToml(path) {
// Sections
// ---------------------------------------------------------------------------
-function checkEnvironment(report) {
- report.section("Environment");
- const nodeMajor = parseNodeMajor(process.version);
- if (nodeMajor >= 18) report.ok(`node ${process.version} (${process.execPath})`);
- else report.fail(`node ${process.version} is too old`, "hooks and the MCP proxy need Node.js 18+ (global fetch)", "install Node.js 18 or newer");
- if (!whichCommand("node")) report.warn("`node` is not on PATH for this process", "hooks and .mcp.json invoke the bare command `node`", "put node on PATH for the environment that launches Codex");
-
- const codex = runCommand("codex", ["--version"], { timeoutMs: 15000 });
- if (codex.ok) report.ok(codex.stdout.split("\n")[0]);
- else report.info(`codex CLI not found on PATH (${codex.error || "?"}) — install checks that need it are skipped`);
- report.info(`platform ${process.platform} ${process.arch}, cwd ${homeShort(process.cwd())}`);
- return { codexOnPath: codex.ok };
-}
-
export function parseFeaturesList(stdout) {
const map = new Map();
if (typeof stdout !== "string") return map;
@@ -218,7 +170,7 @@ export function assessHooksFeature(features, cliFeatures = null) {
};
}
-function checkInstall(report, { codexOnPath }) {
+function checkInstall(report, { cliOnPath }) {
report.section("Plugin install");
const manifest = tryJson(join(PLUGIN_ROOT, ".codex-plugin", "plugin.json"));
const version = manifest?.version || "?";
@@ -241,7 +193,7 @@ function checkInstall(report, { codexOnPath }) {
// codex CLI view
let listed = null;
- if (codexOnPath) {
+ if (cliOnPath) {
const list = runCommand("codex", ["plugin", "list", "--json"], { timeoutMs: 30000 });
if (list.ok) {
const rows = tryJsonText(list.stdout)?.installed || [];
@@ -287,7 +239,7 @@ function checkInstall(report, { codexOnPath }) {
report.warn(`${homeShort(CODEX_CONFIG)} not found`, "Codex has never been configured on this machine");
} else {
let cliFeatures = null;
- if (codexOnPath) {
+ if (cliOnPath) {
const featRes = runCommand("codex", ["features", "list"], { timeoutMs: 5000 });
if (featRes.ok) cliFeatures = parseFeaturesList(featRes.stdout);
}
@@ -330,9 +282,7 @@ function checkInstall(report, { codexOnPath }) {
}
// Legacy artifacts
- const rc = scanRcFiles(RC_MARKERS);
- const blocks = rc.filter((h) => h.kind === "block");
- if (blocks.length) report.warn("shell rc files still source the legacy codex wrapper", blocks.map((h) => `${h.file}: ${h.detail}`).join("\n"), "remove the block; it exports stale OPENVIKING_* values that override ovcli.conf");
+ const rc = scanRcFiles([]);
const CONNECTION_VARS = /^OPENVIKING_(URL|BASE_URL|API_KEY|BEARER_TOKEN|ACCOUNT|USER|CONFIG_FILE|CLI_CONFIG_FILE|CREDENTIAL_SOURCE|HOME)$/;
for (const h of rc.filter((h) => h.kind === "export")) {
const conn = h.vars.filter((v) => CONNECTION_VARS.test(v));
@@ -351,52 +301,9 @@ function tryJsonText(text) {
}
}
-function credentialSources(cfg, cliConf, ovConf) {
- const env = process.env;
- const cliShort = homeShort(cliConf.path);
- const ovShort = homeShort(ovConf.path);
- const cli = cliConf.ok ? cliConf.data : {};
- const ov = ovConf.ok ? ovConf.data : {};
- const cx = ov.codex || {};
- const server = ov.server || {};
- const cliMode = cfg.credentialSource === "ovcli";
- const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
- const url = (!cliMode && envUrl) ? "env" : cli.url ? cliShort : server.url ? ovShort : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
- const apiKey = cliMode
- ? (cli.api_key ? cliShort : "(none — ovcli.conf mode ignores env and ov.conf)")
- : env.OPENVIKING_BEARER_TOKEN ? "env OPENVIKING_BEARER_TOKEN" : env.OPENVIKING_API_KEY ? "env OPENVIKING_API_KEY" : cli.api_key ? cliShort : cx.apiKey ? `${ovShort} codex.apiKey` : server.root_api_key ? `${ovShort} server.root_api_key` : "(none)";
- const account = (!cliMode && env.OPENVIKING_ACCOUNT) ? "env" : (cli.account || cli.account_id) ? cliShort : (!cliMode && cx.accountId) ? `${ovShort} codex.accountId` : "(unset)";
- const user = (!cliMode && env.OPENVIKING_USER) ? "env" : (cli.user || cli.user_id) ? cliShort : (!cliMode && cx.userId) ? `${ovShort} codex.userId` : "(unset)";
- return { url, apiKey, account, user };
-}
-
-function checkConfig(report, cfg) {
+function checkConfig(report, cfg, host) {
report.section("Configuration");
- const expand = (p) => (p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p);
- const cliPath = expand(process.env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf"));
- const ovPath = expand(process.env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf"));
- const cliConf = inspectJsonFile(cliPath);
- const ovConf = inspectJsonFile(ovPath);
-
- for (const [label, conf] of [["ovcli.conf", cliConf], ["ov.conf", ovConf]]) {
- if (!conf.exists) report.info(`${label}: ${homeShort(conf.path)} not present`);
- else if (!conf.ok) report.fail(`${label} cannot be parsed — the plugin treats it as absent`, `${homeShort(conf.path)}: ${conf.error}`, "fix the JSON (a trailing comma or comment is enough to break it)");
- else {
- report.ok(`${label}: ${homeShort(conf.path)} (mode ${conf.mode}, ${fmtBytes(conf.size)})`);
- if (label === "ovcli.conf") {
- if (conf.mode !== "600" && conf.mode !== "400") report.warn("ovcli.conf is not private", `mode ${conf.mode}; it holds the api key`, `chmod 600 ${homeShort(conf.path)}`);
- const unknown = unknownOvcliKeys(conf.data);
- if (unknown.length) report.warn("ovcli.conf has keys nobody reads", unknown.join(", "), "typos such as apiKey/base_url/token are silently ignored — use url, api_key, account, user");
- // `plugin` is on the allowlist above, so until now nothing inside it
- // was ever checked and a misspelled knob just sat there doing nothing.
- for (const { key, suggestion } of unknownPluginKeys(conf.data.plugin)) {
- report.warn(`ovcli.conf ${key} is not a knob any plugin reads`, "", suggestion ? `did you mean ${suggestion}?` : "remove it, or check the plugin README for the knob you meant");
- }
- if (conf.data.plugin?.claude_code && !conf.data.plugin?.codex) report.info("ovcli.conf plugin.claude_code settings do not apply to Codex (use plugin.codex)");
- }
- if (label === "ov.conf" && conf.data.codex) report.info("ov.conf has a legacy codex block (still honoured; prefer ovcli.conf plugin.codex or env vars)");
- }
- }
+ const { cliConf, ovConf } = inspectConfigFiles(report, host);
if (!cliConf.ok && !ovConf.ok && !(process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL)) {
report.fail("no usable config — the plugin falls back to http://127.0.0.1:1933 with no key", "", "create ~/.openviking/ovcli.conf with url + api_key (chmod 600)");
}
@@ -406,56 +313,18 @@ function checkConfig(report, cfg) {
report.info(`credential source: ${cfg.credentialSource} — ${modeText}${modeEnv ? ` (OPENVIKING_CREDENTIAL_SOURCE=${modeEnv})` : ""}`);
if (modeEnv && !/^(env|environment|cli|ovcli|file|config|auto)$/i.test(modeEnv)) report.warn(`OPENVIKING_CREDENTIAL_SOURCE=${modeEnv} is not a recognised value`, "valid: env, cli (ovcli/file/config), auto", "fix or unset it");
- const src = credentialSources(cfg, cliConf, ovConf);
- report.info(`url ${cfg.baseUrl} ← ${src.url}`);
- for (const p of lintBaseUrl(cfg.baseUrl)) report[p.level](p.message, "", p.fix);
- if (src.url.startsWith("default")) report.warn("no url configured — using the built-in default http://127.0.0.1:1933", "only right when the server runs on this machine", "set url in ovcli.conf or OPENVIKING_URL");
-
- const keyInfo = describeApiKey(cfg.apiKey);
- report.info(`api_key ${keyInfo.display} ← ${src.apiKey}`);
- for (const p of keyInfo.problems) report.warn(`api key ${p}`, "", "re-copy the key exactly as issued");
- if (src.apiKey.includes("root_api_key")) report.warn("api key falls back to ov.conf server.root_api_key", "the root key is refused on tenant data APIs and /mcp in api_key mode; against a remote server it is simply the wrong key", "put a user/admin key in ovcli.conf api_key (or OPENVIKING_API_KEY)");
- if (!keyInfo.present && !isLoopbackUrl(cfg.baseUrl)) report.warn("no api key configured for a non-local server", "", "set api_key in ovcli.conf or OPENVIKING_API_KEY");
- report.info(`account ${cfg.account || "(unset)"} ← ${src.account}`);
- report.info(`user ${cfg.user || "(unset)"} ← ${src.user}`);
- if (keyInfo.format === "v2") {
- if (cfg.account && keyInfo.account && cfg.account !== keyInfo.account) report.warn(`configured account '${cfg.account}' differs from the key's account '${keyInfo.account}'`, "in api_key mode the key wins");
- if (cfg.user && keyInfo.user && cfg.user !== keyInfo.user) report.warn(`configured user '${cfg.user}' differs from the key's user '${keyInfo.user}'`, "in api_key mode the key wins");
- }
+ const keyInfo = reportCredentials(report, cfg, credentialSources(cfg, cliConf, ovConf), { account: cfg.account, user: cfg.user });
report.info(`auth mode ${cfg.authMode} (identity headers ${cfg.sendIdentityHeaders ? "sent" : "not sent"}; trusted is implied when account/user are set)`);
- const peer = resolveEffectivePeerId({ cfg, cwd: process.cwd() });
- report.info(`peer ${peer.peerId || "(none)"} ← ${peer.source} (${peer.origin})`);
- if (peer.origin === "unresolved") {
- report.info(
- "no peer is sent: this directory is in no git repository, so its memories go to your user-level space",
- `to give it a memory of its own, create .openviking/config.json here with ${WORKSPACE_PEER_HINT}`,
- );
- } else if (peer.source === "none") {
- report.warn(
- "no peer is sent, so recall defaults to every memory under this user",
- "sending a peer narrows the search to this workspace",
- 'unset OPENVIKING_WORKSPACE_PEER, or set peer.source to "git"',
- );
- }
- if (peer.legacyPeerId) {
- report.info(
- `previous peer ${peer.legacyPeerId}`,
- cfg.recallPeerScope === "actor"
- ? "recall asks it separately, because peer_scope actor turns off the server's cross-peer sweep"
- : "already covered by the server's cross-peer sweep under peer_scope all",
- );
- }
- for (const p of lintPeerScopeDowngrade()) report[p.level](p.message, p.detail, p.fix);
-
- report.info(`timeouts ${cfg.timeoutMs}ms request, ${cfg.recallTimeoutMs}ms recall, ${cfg.captureTimeoutMs}ms capture; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);
- const hooks = tryJson(join(PLUGIN_ROOT, "hooks", "hooks.json"))?.hooks || {};
- const budget = (event) => Number(hooks[event]?.[0]?.hooks?.[0]?.timeout) * 1000 || 0;
- if (budget("UserPromptSubmit") && cfg.recallTimeoutMs > budget("UserPromptSubmit")) report.warn(`recall timeout ${cfg.recallTimeoutMs}ms exceeds the UserPromptSubmit hook budget ${budget("UserPromptSubmit")}ms`, "Codex kills the hook before the request can finish", "lower OPENVIKING_RECALL_TIMEOUT_MS");
- if (budget("Stop") && cfg.captureTimeoutMs > budget("Stop")) report.warn(`capture timeout ${cfg.captureTimeoutMs}ms exceeds the Stop hook budget ${budget("Stop")}ms`, "Codex kills the hook before the request can finish", "lower OPENVIKING_CAPTURE_TIMEOUT_MS");
+ const peer = reportPeer(report, cfg);
+ reportTimeouts(report, cfg, host);
const toggles = [`auto-inject ${cfg.noAutoInject ? "OFF" : "on"}`, `auto-recall ${cfg.autoRecall ? "on" : "OFF"}`, `auto-capture ${cfg.autoCapture ? "on" : "OFF"}`, `commit on compact ${cfg.autoCommitOnCompact ? "on" : "OFF"}`, `recall compress ${cfg.recallCompress ? "on" : "off"}`, `write path ${cfg.writePathAsync ? "async" : "sync"}`];
- report.info(`toggles ${toggles.join(", ")}`);
- if (!cfg.autoRecall || !cfg.autoCapture || cfg.noAutoInject) report.warn("one or more injection paths are switched off", toggles.join(", "), "check OPENVIKING_AUTO_RECALL / OPENVIKING_AUTO_CAPTURE / OPENVIKING_NO_AUTO_INJECT and ovcli.conf plugin.codex");
+ reportToggles(report, cfg, host, toggles);
+
+ sweepEnv(report, cfg, host, (r, env) => {
+ if (env.openviking.some((e) => e.name === "OPENVIKING_MEMORY_ENABLED")) r.warn("OPENVIKING_MEMORY_ENABLED has no effect on the Codex plugin", "disable it with OPENVIKING_AUTO_RECALL=0 / OPENVIKING_AUTO_CAPTURE=0, or codex plugin remove", "");
+ if (cfg.credentialSource === "env") r.info("credential env vars override ovcli.conf — edits to the file (and `ov config switch`) do not take effect while they are set");
+ });
for (const filters of describeInputFilters(cfg)) {
if (!filters.total) continue;
report.info(`${filters.label} ${filters.summary}`);
@@ -470,36 +339,10 @@ function checkConfig(report, cfg) {
);
}
}
- report.info(`debug log ${cfg.debug ? "on" : "off"} → ${homeShort(cfg.debugLogPath)}${cfg.debug ? "" : " (set OPENVIKING_DEBUG=1 in Codex's environment to record hook errors)"}`);
- const env = collectEnv();
- if (env.openviking.length) {
- report.info("OPENVIKING_* in this environment", env.openviking.map((e) => `${e.name}=${e.value}`).join("\n"));
- if (env.openviking.some((e) => e.name === "OPENVIKING_MEMORY_ENABLED")) report.warn("OPENVIKING_MEMORY_ENABLED has no effect on the Codex plugin", "disable it with OPENVIKING_AUTO_RECALL=0 / OPENVIKING_AUTO_CAPTURE=0, or codex plugin remove", "");
- if (cfg.credentialSource === "env") report.info("credential env vars override ovcli.conf — edits to the file (and `ov config switch`) do not take effect while they are set");
- } else {
- report.info("no OPENVIKING_* environment variables set");
- }
- if (env.proxy.length) report.warn(`proxy variables set: ${env.proxy.map((e) => e.name).join(", ")}`, "Node's fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY=1 (Node 24+); curl honours them, so curl may succeed while hooks fail", isLoopbackUrl(cfg.baseUrl) ? "harmless for a local server" : "set NODE_USE_ENV_PROXY=1 (or reach the server without the proxy) in the environment that launches Codex");
- if (env.node.length) report.info(`node TLS/proxy env: ${env.node.map((e) => `${e.name}=${e.value}`).join(", ")}`);
return { keyInfo, peer, ovConf };
}
-async function checkConnection(report, cfg, { keyInfo, peer }, opts) {
- report.section("Connection");
- if (opts.offline) {
- report.info("skipped (--offline)");
- return null;
- }
- const conn = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, account: cfg.sendIdentityHeaders ? cfg.account : "", user: cfg.sendIdentityHeaders ? cfg.user : "", peerId: peer.peerId, userAgent: cfg.userAgent };
- const probes = await probeOpenViking(conn, { timeoutMs: opts.timeoutMs });
- const summary = assessProbes(report, probes, { ...conn, account: cfg.account, user: cfg.user }, keyInfo);
- if (summary.authMode && summary.authMode !== "dev" && summary.authMode !== cfg.authMode) {
- report.warn(`plugin auth mode '${cfg.authMode}' differs from the server's '${summary.authMode}'`, cfg.authMode === "trusted" ? "identity headers are sent but the server ignores them in api_key mode" : "the server expects X-OpenViking-Account/User headers", "set account/user in ovcli.conf for trusted servers, or remove them (or set OPENVIKING_AUTH_MODE) for api_key servers");
- }
- return { probes, summary };
-}
-
function checkActivity(report, cfg, connection) {
report.section("Recent activity");
const stateDir = getStateDir();
@@ -556,43 +399,25 @@ function checkActivity(report, cfg, connection) {
// ---------------------------------------------------------------------------
-async function main() {
- const opts = parseArgs(process.argv.slice(2));
- const report = createReport({ color: opts.color });
- const envInfo = checkEnvironment(report);
- checkInstall(report, envInfo);
- const cfg = loadConfig();
- const configInfo = checkConfig(report, cfg);
- const workspace = checkWorkspace(report);
- const connection = await checkConnection(report, cfg, configInfo, opts);
- const serverHealth = await checkServerHealth(report, { baseUrl: cfg.baseUrl, ovConf: configInfo.ovConf, health: connection?.probes?.health, offline: opts.offline, timeoutMs: opts.timeoutMs });
- checkActivity(report, cfg, connection);
-
- if (opts.json) {
- console.log(JSON.stringify({
- harness: "codex",
- pluginRoot: PLUGIN_ROOT,
- generatedAt: new Date().toISOString(),
- resolved: {
- baseUrl: cfg.baseUrl,
- apiKey: configInfo.keyInfo.display,
- apiKeyFormat: configInfo.keyInfo.format,
- account: cfg.account,
- user: cfg.user,
- peerId: configInfo.peer.peerId,
- credentialSource: cfg.credentialSource,
- authMode: cfg.authMode,
- },
- workspace,
- server: connection?.summary || null,
- serverHealth,
- ...report.toJSON(),
- }, null, 2));
- } else {
- console.log(report.render());
- }
- process.exitCode = report.exitCode();
-}
+const HOST = {
+ harness: "codex",
+ pluginRoot: PLUGIN_ROOT,
+ cliName: "codex",
+ launcherHint: "Codex",
+ // Recall has a timeout of its own here, so it is the knob the prompt hook spends.
+ timeoutBudgets: { UserPromptSubmit: "recallTimeoutMs", Stop: "captureTimeoutMs" },
+ loadConfig,
+ checkInstall,
+ checkConfig,
+ checkActivity,
+ resolveIdentity: (cfg) => ({ account: cfg.account, user: cfg.user }),
+ extraResolved: (cfg) => ({ credentialSource: cfg.credentialSource, authMode: cfg.authMode }),
+ onSummary(report, summary, cfg) {
+ if (summary.authMode && summary.authMode !== "dev" && summary.authMode !== cfg.authMode) {
+ report.warn(`plugin auth mode '${cfg.authMode}' differs from the server's '${summary.authMode}'`, cfg.authMode === "trusted" ? "identity headers are sent but the server ignores them in api_key mode" : "the server expects X-OpenViking-Account/User headers", "set account/user in ovcli.conf for trusted servers, or remove them (or set OPENVIKING_AUTH_MODE) for api_key servers");
+ }
+ },
+};
function isDirectRun() {
if (!process.argv[1]) return false;
@@ -604,7 +429,7 @@ function isDirectRun() {
}
if (isDirectRun()) {
- main().catch((err) => {
+ runDoctor(HOST).catch((err) => {
console.error("ov-memory-doctor failed:", err?.stack || err?.message || err);
process.exit(2);
});
diff --git a/examples/codex-memory-plugin/scripts/ov-session.mjs b/examples/codex-memory-plugin/scripts/ov-session.mjs
index bc3f94b0b..7872157b9 100644
--- a/examples/codex-memory-plugin/scripts/ov-session.mjs
+++ b/examples/codex-memory-plugin/scripts/ov-session.mjs
@@ -13,54 +13,22 @@
import { readFile } from "node:fs/promises";
import { extractCaptureTurns, findLastHumanTurnIndex } from "./capture-utils.mjs";
import { resolveOvSessionId, saveState } from "./session-state.mjs";
+import { makeAgentFetchJSON } from "./shared/agent-hook-runtime.mjs";
import { sendSessionMessages } from "./shared/batch-send.mjs";
-function responseTraceId(body) {
- return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
-}
-
/**
* Build the `{ fetchJSONRes, fetchJSON }` pair used by every capture hook.
* The peer id is read through a getter because callers only know it after
* loading state (which happens under the session lock).
*/
export function makeFetchJSON(cfg, { getActorPeerId = () => "" } = {}) {
- function makeHeaders() {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) {
- headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- headers["X-API-Key"] = cfg.apiKey;
- }
- if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
- const actorPeerId = getActorPeerId();
- if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- return headers;
- }
-
- async function fetchJSONRes(path, init = {}) {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);
- try {
- const res = await fetch(`${cfg.baseUrl}${path}`, {
- ...init,
- headers: makeHeaders(),
- signal: controller.signal,
- });
- const body = await res.json().catch(() => null);
- if (!body) return { ok: false, status: res.status, error: { message: "empty or invalid JSON response" } };
- const traceId = responseTraceId(body);
- if (!res.ok || body.status === "error") {
- return { ok: false, status: res.status, error: body.error || body, traceId };
- }
- return { ok: true, status: res.status, result: body.result ?? body, traceId };
- } catch (err) {
- return { ok: false, status: 0, error: { message: err?.message || String(err) } };
- } finally {
- clearTimeout(timer);
- }
- }
+ const { fetchJSON: fetchJSONRes } = makeAgentFetchJSON(cfg, process.cwd(), {
+ defaultTimeoutMs: cfg.captureTimeoutMs,
+ getActorPeerId,
+ // A capture hook would rather retry a body it cannot parse than record the
+ // turn as sent.
+ requireJsonBody: true,
+ });
async function fetchJSON(path, init = {}) {
const r = await fetchJSONRes(path, init);
@@ -199,6 +167,8 @@ export async function catchUpTurns({
});
const r = await sendSessionMessages(fetchJSONRes, ovSessionId, payloads, {
+ // The transcript and persisted cursor own retries, including SessionStart
+ // catch-up. Queueing the same tail would create a second retry owner.
onSent: async (n) => {
state.capturedTurnCount += n;
await saveState(state);
diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
index 4269b40a7..4ba71a32d 100644
--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.mjs
@@ -28,6 +28,7 @@ import { loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
import { catchUpTurns, commitOvSession, hasCaptureKeyword, makeFetchJSON } from "./ov-session.mjs";
import { clearEnded, loadState, saveState, withSessionLock } from "./session-state.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
let cfg = loadConfig();
@@ -136,46 +137,28 @@ async function compact(sessionId, transcriptPath, trigger, cwd, heartbeat) {
return `OpenViking session ${liveOvSessionId} is committed` + (traceId ? ` (trace_id=${traceId})` : "");
}
-async function main() {
- if (!cfg.autoCommitOnCompact) {
- log("skip", { stage: "init", reason: "autoCommitOnCompact disabled" });
- noop();
- return;
- }
-
- let input;
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString());
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- noop();
- return;
- }
-
- const sessionId = input.session_id || "unknown";
- const transcriptPath = input.transcript_path || null;
- const trigger = input.trigger || "auto";
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- const cwd = typeof input.cwd === "string" && input.cwd.trim() ? input.cwd : process.cwd();
- cfg = loadConfig(cwd);
+runHookStage({
+ loadConfig,
+ gates: { enabled: (reloaded) => reloaded.autoCommitOnCompact },
+ envelope: noop,
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+}, async (stage) => {
+ cfg = stage.cfg;
+ const sessionId = stage.input.session_id || "unknown";
+ const transcriptPath = stage.input.transcript_path || null;
+ const trigger = stage.input.trigger || "auto";
// Compaction means the thread is running, so any earlier end marker is stale.
await clearEnded(sessionId, { before: HOOK_STARTED_AT });
const outcome = await withSessionLock(
sessionId,
- ({ heartbeat }) => compact(sessionId, transcriptPath, trigger, cwd, heartbeat),
+ ({ heartbeat }) => compact(sessionId, transcriptPath, trigger, stage.cwd, heartbeat),
{ waitMs: LOCK_WAIT_MS },
);
if (outcome.skipped) {
logError("lock_timeout", `another writer holds ${sessionId}; leaving state untouched`);
- noop();
return;
}
- noop(outcome.value);
-}
-
-main().catch((err) => { logError("uncaught", err); noop(); });
+ return outcome.value;
+}).catch((err) => { logError("uncaught", err); noop(); });
diff --git a/examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs b/examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs
index 4ba82a0ad..a3eb32584 100644
--- a/examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs
+++ b/examples/codex-memory-plugin/scripts/pre-compact-capture.test.mjs
@@ -1,12 +1,13 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
async function endedMarkerStamps(dir, id) {
@@ -26,40 +27,6 @@ function writeEndedMarker(dir, id, ts) {
return writeFile(join(dir, `${id}.ended.${ts}`), String(ts));
}
-
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try { resolve(raw ? JSON.parse(raw) : null); } catch (err) { reject(err); }
- });
- req.on("error", reject);
- });
-}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- Promise.resolve(handler(req, res)).catch((err) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
function runPreCompact(input, env) {
return new Promise((resolve, reject) => {
const cleanEnv = { ...process.env };
@@ -214,10 +181,8 @@ test("pre-compact leaves state untouched when the session lock is held", async (
test("pre-compact does not commit when the catch-up append fails entirely", async () => {
const stateDir = await mkdtemp(join(tmpdir(), "ov-pre-compact-fail-"));
const transcriptPath = join(stateDir, "transcript.jsonl");
- const calls = [];
const handler = async (req, res) => {
const url = new URL(req.url, "http://127.0.0.1");
- calls.push({ method: req.method, path: url.pathname });
if (req.method === "GET" && url.pathname === "/health") {
writeJson(res, { status: "ok", result: { ok: true } });
return;
@@ -241,15 +206,18 @@ test("pre-compact does not commit when the catch-up append fails entirely", asyn
turn("assistant", "turn-3"),
].join("\n"));
- await withMockOpenViking(handler, async (baseUrl) => {
+ await withMockOpenViking(handler, async (baseUrl, requests) => {
const { output } = await runPreCompact(
{ session_id: "pc3", transcript_path: transcriptPath, trigger: "manual" },
baseEnv(baseUrl, stateDir),
);
assert.match(output.systemMessage, /catch-up append incomplete for cx-pc3/);
+ assert.ok(
+ !requests.some(({ path }) => path.endsWith("/commit")),
+ "must not commit with turns still unsent",
+ );
});
- assert.ok(!calls.some((c) => c.path.endsWith("/commit")), "must not commit with turns still unsent");
const state = JSON.parse(await readFile(join(stateDir, "pc3.json"), "utf-8"));
assert.equal(state.ovSessionId, "cx-pc3");
assert.equal(state.capturedTurnCount, 2);
diff --git a/examples/codex-memory-plugin/scripts/session-end.mjs b/examples/codex-memory-plugin/scripts/session-end.mjs
index 568b62a41..d70b577f0 100644
--- a/examples/codex-memory-plugin/scripts/session-end.mjs
+++ b/examples/codex-memory-plugin/scripts/session-end.mjs
@@ -31,6 +31,7 @@ import {
saveState,
withSessionLock,
} from "./session-state.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
import { maybeDetach, readHookStdin } from "./shared/async-writer.mjs";
import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
@@ -142,40 +143,21 @@ async function finish(sessionId, transcriptPath, cwd, endToken, heartbeat) {
await clearEnded(sessionId, { before: endToken + 1 });
}
-async function main() {
- if (!cfg.autoCapture) {
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- output({});
- return;
- }
-
- let raw;
- let input;
- try {
- raw = await readHookStdin();
- input = JSON.parse(raw);
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- output({});
- return;
- }
-
- const sessionId = input.session_id;
+runHookStage({
+ loadConfig,
+ input: { read: readHookStdin },
+ // The gates answer before markEnded below: a bypassed session was never
+ // captured, so leaving a marker behind would only make the next SessionStart
+ // sweep chase nothing.
+ gates: { enabled: (reloaded) => reloaded.autoCapture },
+ envelope: () => output({}),
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+}, async ({ cfg: reloaded, input, raw, cwd, sessionId, emit }) => {
+ cfg = reloaded;
const transcriptPath = input.transcript_path || null;
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- const cwd = typeof input.cwd === "string" && input.cwd.trim() ? input.cwd : process.cwd();
- cfg = loadConfig(cwd);
- if (!cfg.autoCapture) {
- // The gate above ran against this process's directory, not the session's.
- log("skip", { stage: "init", reason: "autoCapture disabled" });
- output({});
- return;
- }
if (!sessionId) {
log("skip", { stage: "init", reason: "no session_id" });
- output({});
return;
}
@@ -193,10 +175,7 @@ async function main() {
// stdin is already drained; hand the payload to the worker through the
// shared cache env var.
process.env.OPENVIKING_HOOK_STDIN_CACHE = raw;
- const detached = await maybeDetach(
- { ...cfg, writePathAsync: true },
- { approve: () => output({}) },
- );
+ const detached = await maybeDetach({ ...cfg, writePathAsync: true }, { approve: emit });
if (detached) return;
delete process.env.OPENVIKING_HOOK_STDIN_CACHE;
logError("detach_failed", "running the commit inline; Codex may kill it at the timeout");
@@ -210,7 +189,4 @@ async function main() {
if (outcome.skipped) {
logError("lock_timeout", `another writer holds ${sessionId}; end marker left for the sweep`);
}
- output({});
-}
-
-main().catch((err) => { logError("uncaught", err); output({}); });
+}).catch((err) => { logError("uncaught", err); output({}); });
diff --git a/examples/codex-memory-plugin/scripts/session-end.test.mjs b/examples/codex-memory-plugin/scripts/session-end.test.mjs
index ba18976a3..b3f3775ba 100644
--- a/examples/codex-memory-plugin/scripts/session-end.test.mjs
+++ b/examples/codex-memory-plugin/scripts/session-end.test.mjs
@@ -1,12 +1,13 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
async function endedMarkerStamps(dir, id) {
@@ -26,40 +27,6 @@ function writeEndedMarker(dir, id, ts) {
return writeFile(join(dir, `${id}.ended.${ts}`), String(ts));
}
-
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try { resolve(raw ? JSON.parse(raw) : null); } catch (err) { reject(err); }
- });
- req.on("error", reject);
- });
-}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- Promise.resolve(handler(req, res)).catch((err) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(err?.stack || err) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
function runSessionEnd(input, env) {
return new Promise((resolve, reject) => {
const cleanEnv = { ...process.env };
diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
index e0018a46c..fcecdaa97 100644
--- a/examples/codex-memory-plugin/scripts/session-start-commit.mjs
+++ b/examples/codex-memory-plugin/scripts/session-start-commit.mjs
@@ -46,7 +46,7 @@
import { loadConfig } from "./config.mjs";
import { createLogger } from "./debug-log.mjs";
-import { catchUpTurns, makeFetchJSON } from "./ov-session.mjs";
+import { catchUpTurns, commitOvSession, makeFetchJSON } from "./ov-session.mjs";
import { detectRecallCompressorProfile } from "./recall-compressor-profile.mjs";
import {
clearEnded,
@@ -58,6 +58,8 @@ import {
saveState,
withSessionLock,
} from "./session-state.mjs";
+import { runHookStage } from "./shared/agent-hook-runtime.mjs";
+import { replayPending } from "./shared/pending-queue.mjs";
import { buildProfileBlock } from "./shared/profile-inject.mjs";
import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
@@ -74,7 +76,7 @@ const HOOK_STARTED_AT = Date.now();
// The sweep catches up unsent turns before committing, so it needs the same
// HTTP helper the capture hooks use.
-const { fetchJSONRes } = makeFetchJSON(cfg, { getActorPeerId: () => activePeerId });
+const { fetchJSONRes, fetchJSON } = makeFetchJSON(cfg, { getActorPeerId: () => activePeerId });
const COMMITTED_TTL_MS = (() => {
const v = Number(process.env.OPENVIKING_CODEX_COMMITTED_TTL_MS);
@@ -102,52 +104,23 @@ function emitSessionStartOutput({ contexts = [], systemMessage = "" } = {}) {
output(response);
}
-function responseTraceId(body) {
- return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
-}
-
-async function requestJSON(path, init = {}, options = {}) {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), cfg.captureTimeoutMs);
+/**
+ * Drain writes that an earlier hook queued while the server was unreachable.
+ * SessionStart is the only codex hook that runs after a known-healthy check,
+ * so it is where the queue gets its chance; a bypassed directory still replays,
+ * because the entries were recorded by sessions that were not bypassed.
+ */
+async function replayPendingWrites() {
try {
- const headers = { "Content-Type": "application/json" };
- if (cfg.apiKey) {
- headers["Authorization"] = `Bearer ${cfg.apiKey}`;
- headers["X-API-Key"] = cfg.apiKey;
- }
- if (cfg.sendIdentityHeaders && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
- if (cfg.sendIdentityHeaders && cfg.user) headers["X-OpenViking-User"] = cfg.user;
- const actorPeerId = options.actorPeerId ?? activePeerId;
- if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
- if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
- const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });
- const body = await res.json().catch(() => null);
- if (!body) return { ok: false, status: res.status };
- const traceId = responseTraceId(body);
- if (!res.ok || body.status === "error") {
- return { ok: false, status: res.status, error: body.error || body, traceId };
+ const result = await replayPending(fetchJSONRes, log);
+ if (result.replayed > 0 || result.failed > 0 || result.deferred > 0) {
+ log("pending-replay", result);
}
- return { ok: true, status: res.status, result: body.result ?? body, traceId };
- } catch (error) {
- return { ok: false, status: 0, error: { message: error?.message || String(error) } };
- } finally {
- clearTimeout(timer);
+ } catch (err) {
+ logError("pending-replay", err);
}
}
-async function fetchJSON(path, init = {}, options = {}) {
- const response = await requestJSON(path, init, options);
- return response.ok ? response.result : null;
-}
-
-async function commitOvSession(ovSessionId) {
- if (!ovSessionId) return null;
- return requestJSON(
- `/api/v1/sessions/${encodeURIComponent(ovSessionId)}/commit`,
- { method: "POST", body: JSON.stringify({}) },
- );
-}
-
function truncateText(text, maxChars) {
const value = String(text || "").trim();
if (value.length <= maxChars) return value;
@@ -196,7 +169,7 @@ async function buildSessionProfileContext() {
}
try {
const profile = await buildProfileBlock(
- requestJSON,
+ fetchJSONRes,
cfg.profileTokenBudget,
activePeerId,
);
@@ -263,7 +236,7 @@ async function buildResumeArchiveContext(newSessionId) {
*/
async function commitAndRelease(state, reason, endToken) {
const ovSessionId = state.ovSessionId;
- const commit = await commitOvSession(ovSessionId);
+ const commit = await commitOvSession(fetchJSONRes, ovSessionId);
if (!commit?.ok) {
log("commit", {
reason,
@@ -326,27 +299,24 @@ function describeCommittedSessions(commits) {
(traceIds.length ? ` (trace_ids=${traceIds.join(",")})` : "");
}
-async function main() {
- let input;
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- input = JSON.parse(Buffer.concat(chunks).toString());
- } catch {
- log("skip", { stage: "stdin_parse", reason: "invalid input" });
- noop();
- return;
- }
-
+// A bypassed directory suppresses this session's own memory work — no peer
+// registration, no injection. The sweep and the pending replay still run: they
+// finish sessions recorded elsewhere, and this hook is the only place codex
+// runs either, so skipping them would strand that data for as long as the user
+// keeps working in a bypassed repository.
+runHookStage({
+ loadConfig,
+ gates: { bypass: () => false },
+ envelope: (response) => emitSessionStartOutput(response || {}),
+ onSkip: (reason) => log("skip", { stage: "init", reason }),
+}, async (stage) => {
+ const { input, cwd, bypassed } = stage;
+ cfg = stage.cfg;
const source = input.source || "unknown";
const newSessionId = input.session_id || "unknown";
- const cwd = typeof input.cwd === "string" && input.cwd.trim() ? input.cwd : process.cwd();
- // The workspace layer belongs to the session's directory, which only the
- // payload knows; see loadConfig for why re-resolving this late is safe.
- cfg = loadConfig(cwd);
const effectivePeer = resolveEffectivePeerId({ cfg, cwd });
activePeerId = effectivePeer.peerId;
- if (newSessionId !== "unknown") {
+ if (!bypassed && newSessionId !== "unknown") {
const state = await loadState(newSessionId);
await saveState({
...state,
@@ -358,6 +328,7 @@ async function main() {
newSessionId,
idleTtlMs: IDLE_TTL_MS,
peerSource: effectivePeer.source,
+ bypassed,
});
try {
@@ -373,15 +344,18 @@ async function main() {
const health = await fetchJSON("/health");
if (!health) {
logError("health_check", "server unreachable; skipping profile + archive injection");
- noop();
+ return;
+ }
+ await replayPendingWrites();
+ if (bypassed) {
+ log("skip", { stage: "inject", reason: "bypass_session_pattern" });
return;
}
const [profileContext, archiveContext] = await Promise.all([
buildSessionProfileContext(),
buildResumeArchiveContext(newSessionId),
]);
- emitSessionStartOutput({ contexts: [profileContext, archiveContext] });
- return;
+ return { contexts: [profileContext, archiveContext] };
}
// Other non-startup sources are hard no-ops. We don't sweep there, because
@@ -389,18 +363,18 @@ async function main() {
// session boundary.
if (source !== "startup" && source !== "clear") {
log("skip", { stage: "source_check", reason: `source=${source} (only startup|clear act)` });
- noop();
return;
}
const health = await fetchJSON("/health");
if (!health) {
logError("health_check", "server unreachable; skipping profile injection + commit + sweep");
- noop();
return;
}
- const profileContext = await buildSessionProfileContext();
+ await replayPendingWrites();
+
+ const profileContext = bypassed ? null : await buildSessionProfileContext();
const now = Date.now();
const commits = [];
let retired = 0;
@@ -518,14 +492,8 @@ async function main() {
ovSessionIds,
});
- if (commits.length > 0) {
- emitSessionStartOutput({
- contexts: [profileContext],
- systemMessage: describeCommittedSessions(commits),
- });
- } else {
- emitSessionStartOutput({ contexts: [profileContext] });
- }
-}
-
-main().catch((err) => { logError("uncaught", err); noop(); });
+ return {
+ contexts: [profileContext],
+ systemMessage: commits.length > 0 ? describeCommittedSessions(commits) : "",
+ };
+}).catch((err) => { logError("uncaught", err); noop(); });
diff --git a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
index 291e1b0d9..46a9aaff3 100644
--- a/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
+++ b/examples/codex-memory-plugin/scripts/session-start-commit.test.mjs
@@ -1,12 +1,14 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
-import http from "node:http";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
+import { readRequestBody, withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
+import { enqueue } from "./shared/pending-queue.mjs";
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
async function endedMarkerStamps(dir, id) {
@@ -26,28 +28,6 @@ function writeEndedMarker(dir, id, ts) {
return writeFile(join(dir, `${id}.ended.${ts}`), String(ts));
}
-
-function writeJson(res, value) {
- res.writeHead(200, { "Content-Type": "application/json" });
- res.end(JSON.stringify(value));
-}
-
-async function withMockOpenViking(handler, fn) {
- const server = http.createServer((req, res) => {
- Promise.resolve(handler(req, res)).catch((error) => {
- res.writeHead(500, { "Content-Type": "application/json" });
- res.end(JSON.stringify({ status: "error", error: String(error?.stack || error) }));
- });
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn(`http://127.0.0.1:${port}`);
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
function runSessionStart(input, env) {
return new Promise((resolve, reject) => {
const cleanEnv = { ...process.env };
@@ -472,18 +452,6 @@ test("resume clears a stale SessionEnd marker for the resumed session", async ()
}
});
-function readRequestBody(req) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => {
- const raw = Buffer.concat(chunks).toString("utf-8");
- try { resolve(raw ? JSON.parse(raw) : null); } catch (error) { reject(error); }
- });
- req.on("error", reject);
- });
-}
-
function turn(role, content) {
return JSON.stringify({ payload: { message: { role, content } } });
}
@@ -719,3 +687,50 @@ test("a marker that disappears under the lock falls back to the idle rule", asyn
await rm(stateDir, { recursive: true, force: true });
}
});
+
+test("a turn queued during an outage is replayed at the next SessionStart", async () => {
+ const stateDir = await mkdtemp(join(tmpdir(), "ov-session-start-replay-"));
+ const pendingDir = join(stateDir, "pending");
+ const posted = [];
+
+ const savedPendingDir = process.env.OPENVIKING_PENDING_DIR;
+ try {
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+ const queued = await enqueue("addMessage", "cx-outage", {
+ role: "user",
+ content: "this turn outlived the outage",
+ });
+ assert.ok(queued.ok, `could not seed the queue: ${JSON.stringify(queued)}`);
+
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, { status: "ok", result: { healthy: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname.endsWith("/messages")) {
+ posted.push({ path: url.pathname, body: await readRequestBody(req) });
+ writeJson(res, { status: "ok", result: { ok: true } });
+ return;
+ }
+ res.writeHead(404, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ status: "error", error: "not found" }));
+ }, async (baseUrl) => {
+ await runSessionStart({ source: "startup", session_id: "cx-new", cwd: stateDir }, {
+ ...baseEnv(baseUrl, stateDir),
+ OPENVIKING_PENDING_DIR: pendingDir,
+ OPENVIKING_HOME: join(stateDir, "home"),
+ OPENVIKING_NO_AUTO_INJECT: "1",
+ });
+ });
+
+ assert.equal(posted.length, 1, `expected the queued turn to be replayed; got ${JSON.stringify(posted)}`);
+ assert.match(posted[0].path, /\/cx-outage\/messages$/u);
+ assert.equal(posted[0].body.content, "this turn outlived the outage");
+ assert.deepEqual(await readdir(pendingDir), [], "a replayed entry must be removed from the queue");
+ } finally {
+ if (savedPendingDir === undefined) delete process.env.OPENVIKING_PENDING_DIR;
+ else process.env.OPENVIKING_PENDING_DIR = savedPendingDir;
+ await rm(stateDir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
new file mode 100644
index 000000000..745bfaece
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/shared/agent-hook-runtime.mjs
@@ -0,0 +1,367 @@
+// 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 { createLogger } from "./debug-log.mjs";
+import { sendSessionMessages } from "./batch-send.mjs";
+import { createOvHttp } from "./ov-http.mjs";
+import { enqueue, replayPending } from "./pending-queue.mjs";
+import { buildProfileBlock } from "./profile-inject.mjs";
+import { buildRecallBlock, isRecallEnabled } from "./recall-core.mjs";
+import { buildPluginConfig } from "./plugin-config.mjs";
+import { isRetryableFailure } from "./retryable.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 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");
+}
+
+/**
+ * The config for one of the thin hook harnesses.
+ *
+ * These four used to read the environment and nothing else, so `ov config
+ * switch` moved their credentials and left their behaviour behind, and an
+ * `ovcli.conf` `plugin` entry named after them was inert. They resolve through
+ * the same layers as every other harness now; only the client's own name for
+ * itself stays local.
+ *
+ * `cwd` selects the workspace layer. It defaults to this process's directory,
+ * which is all a hook knows before the payload on stdin names the session's
+ * own — the caller re-resolves once it has it. That is safe because a workspace
+ * file may not carry connection or credential keys, so the base URL and API key
+ * cannot move under a logger or fetch helper already built from the first load.
+ */
+export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
+ return {
+ ...buildPluginConfig(clientId, {
+ cwd,
+ version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ logFile: `${clientId}-hooks.log`,
+ }),
+ clientId,
+ };
+}
+
+export function createAgentLogger(clientId, hookName, cfg) {
+ return createLogger(`${clientId}:${hookName}`, cfg);
+}
+
+export async function readRawHookInput() {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ return Buffer.concat(chunks).toString();
+}
+
+export async function readHookInput() {
+ const raw = await readRawHookInput();
+ 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);
+}
+
+/**
+ * The `fetchJSON` a hook talks through.
+ *
+ * `getActorPeerId` is a getter rather than a value because Codex only knows its
+ * peer after loading session state under the session lock, and because a stack
+ * whose every call names its own peer answers with the empty string. The
+ * workspace peer behind the default is resolved on demand so those callers do
+ * not pay for a lookup they never read.
+ */
+export function makeAgentFetchJSON(cfg, cwd = process.cwd(), {
+ defaultTimeoutMs,
+ getActorPeerId,
+ requireJsonBody = false,
+} = {}) {
+ let resolved = null;
+ const workspacePeer = () => (resolved ??= resolveEffectivePeerId({ cfg, cwd }));
+ const fetchJSON = createOvHttp(cfg, {
+ defaultTimeoutMs: defaultTimeoutMs ?? cfg.timeoutMs,
+ resolveActorPeerId: getActorPeerId || (() => workspacePeer().peerId),
+ requireJsonBody,
+ });
+ return { fetchJSON, get effectivePeer() { return workspacePeer(); } };
+}
+
+/** Park a write for the next hook to replay. Never throws: the caller is a hook. */
+export async function enqueueAgentPending(type, sessionId, payload = {}) {
+ try {
+ return await enqueue(type, sessionId, payload);
+ } catch {
+ return { ok: false };
+ }
+}
+
+/**
+ * What became of a write that failed: parked for replay, or reported once on
+ * stderr when no retry can help. `pendingQueued` / `pendingEnqueueFailed` are
+ * what the capture hooks log and what decides whether a turn is lost.
+ */
+async function notePendingWrite(type, sessionId, payload, result) {
+ if (result.ok) return result;
+ if (!isRetryableFailure(result)) {
+ const detail = result.error?.message || result.error?.code || "";
+ process.stderr.write(
+ `[ov] ${type} failed with non-retryable status ${result.status || "unknown"};`
+ + ` not enqueuing pending retry${detail ? ` (${detail})` : ""}\n`,
+ );
+ return result;
+ }
+ const pending = await enqueueAgentPending(type, sessionId, payload);
+ if (pending.ok) result.pendingQueued = true;
+ else result.pendingEnqueueFailed = true;
+ return result;
+}
+
+export async function addAgentMessage(fetchJSON, sessionId, payload) {
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ });
+ return notePendingWrite("addMessage", sessionId, payload, result);
+}
+
+export async function addAgentMessages(fetchJSON, sessionId, payloads) {
+ return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });
+}
+
+export async function commitAgentSession(fetchJSON, sessionId, log = () => {}, payload = {}) {
+ const body = payload || {};
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+ await notePendingWrite("commitSession", sessionId, body, result);
+ log("commit", {
+ sessionId,
+ ok: result.ok,
+ status: result.result?.status || result.status,
+ trace_id: result.traceId || result.result?.trace_id,
+ queued: Boolean(result.pendingQueued),
+ error: result.ok ? undefined : result.error?.message || result.error?.code,
+ });
+ return result;
+}
+
+/** Session meta, or null when the session does not exist and `autoCreate` is off. */
+export async function getAgentSession(fetchJSON, sessionId, { autoCreate = false } = {}) {
+ const query = autoCreate ? "?auto_create=true" : "";
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}${query}`);
+ return result.ok ? result.result : null;
+}
+
+/** Assembled session context (includes latest_archive_overview), or null. */
+export async function getAgentSessionContext(fetchJSON, sessionId, tokenBudget = 128000) {
+ const result = await fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,
+ );
+ return result.ok ? result.result : null;
+}
+
+export async function replayAgentPending(fetchJSON, log = () => {}) {
+ return replayPending(fetchJSON, log);
+}
+
+export async function recallForPrompt(fetchJSON, cfg, prompt, cwd, log = () => {}, options = {}) {
+ if (!isRecallEnabled(cfg) || !String(prompt || "").trim()) return null;
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ return buildRecallBlock(fetchJSON, cfg, prompt, {
+ actorPeerId: peer.peerId,
+ legacyPeerId: peer.legacyPeerId,
+ // Passing the OV session id is what turns on server-side query expansion
+ // and the cross-turn dedup ledger for these thin harnesses.
+ sessionId: options.sessionId || "",
+ 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) });
+}
+
+/**
+ * The opening every hook entry shares: read the payload, re-resolve the config
+ * against the session's directory, answer the two gates, then run the hook's
+ * own work and emit one envelope.
+ *
+ * `run` receives the resolved stage and returns the envelope's payload — a
+ * systemMessage, a context block, or nothing. A closed gate calls
+ * `onSkip(reason, stage)` with `"bad_stdin"`, `"disabled"` or `"bypass"`, emits
+ * an empty envelope and never runs the callback. `run` may emit early through
+ * `stage.emit` (a detaching hook has to answer before its worker starts); the
+ * envelope is written once.
+ *
+ * Both gates are predicates over `(cfg, stage)`: `enabled` says whether this
+ * hook runs at all, `bypass` whether this session is one the plugin stays out
+ * of. `sessionId` reads the session out of the payload — the default is the key
+ * Claude Code and Codex send, and a host that spells it differently, or derives
+ * it, hands over its own resolver rather than turning the gate off.
+ *
+ * The write-path preamble — the enabled gate against this process's directory,
+ * then `maybeDetach` — stays in the entry. A worker has to be spawned before
+ * stdin is consumed, and its response is the host's own.
+ */
+export async function runHookStage({
+ clientId,
+ loadConfig = (cwd) => loadAgentHookConfig(clientId, cwd),
+ input: { read = readRawHookInput, tolerant = false } = {},
+ sessionId: resolveSessionId = (payload) => payload.session_id ?? payload.sessionId,
+ gates: { enabled = null, bypass = (cfg, stage) => stage.bypassed } = {},
+ envelope = () => {},
+ onSkip = () => {},
+} = {}, run = () => undefined) {
+ let emitted = false;
+ const emit = (value) => {
+ if (emitted) return;
+ emitted = true;
+ envelope(value);
+ };
+
+ let badStdin = false;
+ const raw = await read();
+ let payload;
+ try {
+ payload = JSON.parse(tolerant ? raw || "{}" : raw);
+ } catch {
+ badStdin = !tolerant;
+ payload = {};
+ }
+ if (!payload || typeof payload !== "object") payload = {};
+
+ const cwd = resolveAgentCwd(payload);
+ const cfg = loadConfig(cwd);
+ const sessionId = resolveSessionId(payload);
+ const stage = {
+ cfg,
+ input: payload,
+ raw,
+ cwd,
+ sessionId,
+ bypassed: isBypassed(cfg, { sessionId, cwd }),
+ emit,
+ };
+
+ if (badStdin) {
+ onSkip("bad_stdin", stage);
+ emit();
+ return undefined;
+ }
+ if (cfg.enabled === false || (enabled && !enabled(cfg, stage))) {
+ onSkip("disabled", stage);
+ emit();
+ return undefined;
+ }
+ if (bypass && bypass(cfg, stage)) {
+ onSkip("bypass", stage);
+ emit();
+ return undefined;
+ }
+
+ const result = await run(stage);
+ emit(result);
+ return result;
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
index 22bc1b63c..777913f74 100644
--- a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
@@ -266,7 +266,13 @@ export function extractTextFromPayload(payload, options = {}) {
return chunks.join("\n\n");
}
-function collectToolNamesByIdFromEntries(entries) {
+/**
+ * Map every tool call id in a transcript to the name of the tool it invoked.
+ *
+ * A result block names the call by id only, so the name has to come from the
+ * call that preceded it. Pass the map as `toolNameById` to the extractors.
+ */
+export function collectToolNamesByIdFromEntries(entries) {
const map = {};
for (const entry of entries || []) {
const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;
@@ -433,6 +439,24 @@ export function extractCaptureTurns(rolloutEntries, cfg = {}) {
return turns;
}
+/**
+ * Index of the last turn that came from a human prompt, or -1.
+ *
+ * `role === "user"` alone is not enough: normalizeCaptureRole() maps tool
+ * results onto the user role too, and those carry `tool` parts rather than
+ * `text` parts. Used by the post-compact shrink path to find where the current
+ * interaction starts.
+ */
+export function findLastHumanTurnIndex(turns) {
+ const list = Array.isArray(turns) ? turns : [];
+ for (let i = list.length - 1; i >= 0; i -= 1) {
+ const turn = list[i];
+ if (turn?.role !== "user") continue;
+ if (turn.parts?.some((part) => part?.type === "text")) return i;
+ }
+ return -1;
+}
+
export function normalizeCaptureRole(role) {
const value = normalizeType(role);
if (value === "user") return "user";
@@ -511,12 +535,24 @@ function stripInjectedDigestBlocks(text) {
return out.join("\n");
}
+/**
+ * Drop everything in a turn that the conversation did not put there.
+ *
+ * Recall injects a context block into the prompt, and the host adds notes of
+ * its own; captured back unchanged, this turn's injection becomes next turn's
+ * memory and the loop feeds on itself. Formatting the conversation did author
+ * — newlines, code fences — survives.
+ */
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, " ")
+ // Claude Code wraps its own out-of-band notes to the model in these two
+ // shapes. They are the host talking to itself, not the conversation.
+ .replace(/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi, " ")
+ .replace(/^[ \t]*\[Subagent Context\][^\n]*$/gim, " ")
.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, "")
@@ -540,6 +576,23 @@ function isPunctuationOnly(text) {
return !/[a-z0-9\u3400-\u9fff]/i.test(text);
}
+/**
+ * Is capture on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoCapture`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables capture under an older name still disables it.
+ */
+export function isCaptureEnabled(cfg = {}) {
+ for (const value of [cfg.enabled, cfg.autoCapture, cfg.capture, cfg.syncTurns]) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {}) {
const maxLength = cfg.captureMaxLength || 24000;
const sanitized = sanitizeCapturedText(text);
@@ -576,3 +629,26 @@ export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {})
return { shouldCapture: true, reason: "ok", text: capped };
}
+
+/**
+ * Apply the capture filter to a list of `{ role, content }` turns.
+ *
+ * The harnesses that compose `agent-hook-runtime` used to send whatever their
+ * transcript parser produced: an acknowledgement, a slash command, a stray
+ * `ok`, or a turn far past `captureMaxLength` all reached the extractor
+ * verbatim. This is the same decision every other harness makes, in one place,
+ * so a thin harness gets it by calling rather than by reimplementing it.
+ *
+ * Returns the surviving turns with `content` replaced by the sanitized and
+ * capped text, and the dropped ones with the reason, for the debug log.
+ */
+export function filterCaptureTurns(turns, cfg = {}) {
+ const kept = [];
+ const dropped = [];
+ for (const turn of Array.isArray(turns) ? turns : []) {
+ const decision = shouldCaptureText(turn?.content, turn?.role, cfg);
+ if (decision.shouldCapture) kept.push({ ...turn, content: decision.text });
+ else dropped.push({ role: turn?.role, reason: decision.reason });
+ }
+ return { kept, dropped };
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/config-schema.mjs b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs
new file mode 100644
index 000000000..4a1a7c9c4
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs
@@ -0,0 +1,359 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * Every knob a memory plugin reads, declared once.
+ *
+ * A setting stayed uniform across harnesses only when a shared module read it
+ * on the hot path: `recallLimit`, `scoreThreshold` and `captureMaxLength` agree
+ * everywhere because `recall-core` and `capture-utils` read them. Everything
+ * else drifted — the same switch is `autoRecall` in three loaders, an
+ * `autoRecall` *object* in opencode, `syncTurns` in dsh and pi, and absent from
+ * the thin hook runtime — because each loader hand-wrote its own list and the
+ * author picked a name. Three more lists then had to be kept in step by hand:
+ * the doctor's known-knob set, the workspace file's dotted-key map, and the
+ * implicit inventory inside `loadAgentHookConfig`.
+ *
+ * This module is the one list. The others are projections of it:
+ * `pluginConfigKeys()` for the doctor, `WORKSPACE_KNOB_MAP` for the workspace
+ * file, and `resolveKnobs()` for every loader. A knob added here reaches all of
+ * them; a knob spelled wrong reaches none.
+ *
+ * Declaration fields:
+ * name canonical key, and the property the loaders read
+ * type bool | int | number | enum | string | list
+ * default value when no layer supplies one
+ * harness per-harness default, where one genuinely differs
+ * min/max clamped, not rejected: a config file must not kill a hook
+ * values the enum's members; anything else falls back to the default
+ * env OPENVIKING_* variable, the highest-priority layer
+ * aliases older spellings, honoured forever; the doctor names them
+ * workspace dotted key in `.openviking/config.json`
+ * capability which capability owns it, for the switches in recall/capture
+ * sendOnlyWhenConfigured
+ * the request omits this field unless a layer actually set it,
+ * so the server's own default stands. Loaders project the flag
+ * as `<name>Configured` and `recall-core` reads it from there.
+ */
+
+export const CAPABILITIES = ["connection", "peer", "recall", "capture", "session", "debug"];
+
+/** @type {ReadonlyArray<object>} */
+export const KNOBS = [
+ // ── connection and identity ────────────────────────────────────────────
+ // Credentials resolve through `credentials.mjs`; these entries exist so the
+ // doctor recognises them inside `plugin` and so ov.conf's harness section
+ // keeps working.
+ { name: "enabled", type: "bool", default: true, env: "OPENVIKING_MEMORY_ENABLED", capability: "connection" },
+ { name: "apiKey", type: "string", default: "", capability: "connection" },
+ { name: "accountId", type: "string", default: "", capability: "connection" },
+ { name: "userId", type: "string", default: "", capability: "connection" },
+ { name: "authMode", type: "enum", values: ["trusted", "api_key"], default: "", env: "OPENVIKING_AUTH_MODE", aliases: ["auth_mode"], capability: "connection" },
+ {
+ name: "timeoutMs",
+ type: "int",
+ default: 15000,
+ // opencode drives an editor session that tolerates a slower call; dsh runs
+ // inside a chat host that does not.
+ harness: { opencode: 30000, dsh: 10000 },
+ min: 1000,
+ max: 300000,
+ env: "OPENVIKING_TIMEOUT_MS",
+ aliases: ["requestTimeoutMs"],
+ capability: "connection",
+ },
+ { name: "mcpEnabled", type: "bool", default: true, capability: "connection" },
+ { name: "mcpToolCallTimeoutMs", type: "int", default: 60000, min: 1000, max: 600000, capability: "connection" },
+ { name: "dataDir", type: "string", default: "", capability: "connection" },
+
+ { name: "peerId", type: "string", default: "", env: "OPENVIKING_PEER_ID", aliases: ["peer_id"], workspace: "peer.id", capability: "peer" },
+ { name: "peerSource", type: "template", default: "", env: "OPENVIKING_PEER_SOURCE", workspace: "peer.source", capability: "peer" },
+ { name: "workspacePeer", type: "bool", default: true, env: "OPENVIKING_WORKSPACE_PEER", capability: "peer" },
+
+ // ── recall ────────────────────────────────────────────────────────────
+ {
+ name: "autoRecall",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_RECALL",
+ workspace: "recall.enabled",
+ capability: "recall",
+ },
+ { name: "recallLimit", type: "int", default: 10, min: 1, max: 50, env: "OPENVIKING_RECALL_LIMIT", workspace: "recall.max_items", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "scoreThreshold", type: "number", default: 0.35, min: 0, max: 1, env: "OPENVIKING_SCORE_THRESHOLD", aliases: ["recallScoreThreshold"], workspace: "recall.score_threshold", capability: "recall" },
+ { name: "minQueryLength", type: "int", default: 3, min: 1, max: 64, env: "OPENVIKING_MIN_QUERY_LENGTH", aliases: ["recallMinQueryLength"], capability: "recall" },
+ { name: "recallTokenBudget", type: "int", default: 2000, min: 200, max: 50000, env: "OPENVIKING_RECALL_TOKEN_BUDGET", aliases: ["recallBudget"], capability: "recall" },
+ { name: "recallMaxContentChars", type: "int", default: 500, min: 100, max: 5000, env: "OPENVIKING_RECALL_MAX_CONTENT_CHARS", capability: "recall" },
+ { name: "recallPreferAbstract", type: "bool", default: true, env: "OPENVIKING_RECALL_PREFER_ABSTRACT", capability: "recall" },
+ { name: "recallPeerScope", type: "enum", values: ["all", "actor"], default: "all", env: "OPENVIKING_RECALL_PEER_SCOPE", workspace: "recall.peer_scope", capability: "recall" },
+ { name: "recallDedupTurns", type: "int", default: 5, min: 0, max: 20, env: "OPENVIKING_RECALL_DEDUP_TURNS", workspace: "recall.dedup_turns", capability: "recall" },
+ { name: "recallMaxTokens", type: "int", default: 1600, min: 64, max: 200000, env: "OPENVIKING_RECALL_MAX_TOKENS", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallQueryExpansion", type: "enum", values: ["auto", "off"], default: "auto", env: "OPENVIKING_RECALL_QUERY_EXPANSION", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallTimeoutMs", type: "int", default: 120000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_TIMEOUT_MS", capability: "recall" },
+ // 0 keeps the built-in default, which outlasts the server's rewrite fuse.
+ { name: "recallContextTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS", capability: "recall" },
+ { name: "logRankingDetails", type: "bool", default: false, env: "OPENVIKING_LOG_RANKING_DETAILS", capability: "recall" },
+ { name: "recallLedger", type: "bool", default: true, env: "OPENVIKING_RECALL_LEDGER", capability: "recall" },
+ { name: "recallQueryFilters", type: "list", default: [], env: "OPENVIKING_RECALL_QUERY_FILTERS", capability: "recall" },
+
+ // Digest compression. Claude Code reads this as the tri-state
+ // off/client/server/auto through `normalizeRewriteMode`; Codex reads the same
+ // key as on/off. Both spellings stay declared so neither harness's users are
+ // told their config is a typo.
+ { name: "recallCompress", type: "string", default: "auto", env: "OPENVIKING_RECALL_COMPRESS", aliases: ["recallRewrite"], capability: "recall" },
+ { name: "recallCompressModel", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_MODEL", capability: "recall" },
+ { name: "recallCompressBaseUrl", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_BASE_URL", capability: "recall" },
+ { name: "recallCompressThinking", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_THINKING", aliases: ["recallCompressReasoningEffort"], capability: "recall" },
+ // 0 means "derive from recallTimeoutMs" — the loader that owns the fallback
+ // is the one that knows the request budget it has to fit inside.
+ { name: "recallCompressTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectOnStartup", type: "bool", default: true, env: "OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP", capability: "recall" },
+ { name: "recallCompressDetectTimeoutMs", type: "int", default: 15000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectTtlMs", type: "int", default: 604800000, min: 0, capability: "recall", env: "OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS" },
+ { name: "recallCompressMinInputChars", type: "int", default: 1500, min: 0, max: 100000, env: "OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxInputChars", type: "int", default: 18000, min: 1000, max: 200000, env: "OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxBullets", type: "int", default: 6, min: 1, max: 50, env: "OPENVIKING_RECALL_COMPRESS_MAX_BULLETS", sendOnlyWhenConfigured: true, capability: "recall" },
+
+ // ── capture ───────────────────────────────────────────────────────────
+ // `syncTurns` is dsh and pi's spelling of the same switch. It stays an alias
+ // rather than a second knob so `ov config switch` moves both.
+ {
+ name: "autoCapture",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_CAPTURE",
+ aliases: ["syncTurns"],
+ workspace: "capture.enabled",
+ capability: "capture",
+ },
+ { name: "captureMode", type: "enum", values: ["semantic", "keyword"], default: "semantic", env: "OPENVIKING_CAPTURE_MODE", capability: "capture" },
+ { name: "captureMaxLength", type: "int", default: 24000, min: 200, max: 100000, env: "OPENVIKING_CAPTURE_MAX_LENGTH", capability: "capture" },
+ // Tool output is reported verbatim; the server owns truncation via
+ // tool_output_externalization. This cap only guards pathological payloads.
+ { name: "captureToolMaxChars", type: "int", default: 1000000, min: 200, max: 1000000, env: "OPENVIKING_CAPTURE_TOOL_MAX_CHARS", capability: "capture" },
+ // Default true: a memory plugin that only sees the user's half of the
+ // conversation extracts noticeably worse.
+ { name: "captureAssistantTurns", type: "bool", default: true, env: "OPENVIKING_CAPTURE_ASSISTANT_TURNS", capability: "capture" },
+ { name: "captureLastAssistantOnStop", type: "bool", default: true, env: "OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP", capability: "capture" },
+ { name: "captureToolResults", type: "bool", default: false, env: "OPENVIKING_CAPTURE_TOOL_RESULTS", capability: "capture" },
+ { name: "captureFilters", type: "list", default: [], env: "OPENVIKING_CAPTURE_FILTERS", capability: "capture" },
+ // 0 means "derive from timeoutMs": a write gets a longer budget than a read.
+ { name: "captureTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_CAPTURE_TIMEOUT_MS", capability: "capture" },
+ { name: "commitTokenThreshold", type: "int", default: 20000, min: 1000, max: 1000000, env: "OPENVIKING_COMMIT_TOKEN_THRESHOLD", workspace: "capture.commit_token_threshold", capability: "capture" },
+ { name: "commitKeepRecentCount", type: "int", default: 10, min: 0, max: 1000, env: "OPENVIKING_COMMIT_KEEP_RECENT_COUNT", capability: "capture" },
+ { name: "commitTurnThreshold", type: "int", default: 8, min: 1, max: 1000, env: "OPENVIKING_COMMIT_TURN_THRESHOLD", capability: "capture" },
+ { name: "autoCommitOnCompact", type: "bool", default: true, env: "OPENVIKING_AUTO_COMMIT_ON_COMPACT", capability: "capture" },
+ { name: "writePathAsync", type: "bool", default: true, env: "OPENVIKING_WRITE_PATH_ASYNC", capability: "capture" },
+
+ // ── session lifecycle ─────────────────────────────────────────────────
+ { name: "noAutoInject", type: "bool", default: false, env: "OPENVIKING_NO_AUTO_INJECT", capability: "session" },
+ { name: "profileTokenBudget", type: "int", default: 10000, min: 500, max: 50000, env: "OPENVIKING_PROFILE_TOKEN_BUDGET", aliases: ["profileBudget"], capability: "session" },
+ { name: "resumeContextBudget", type: "int", default: 32000, min: 1024, max: 128000, env: "OPENVIKING_RESUME_CONTEXT_BUDGET", capability: "session" },
+ { name: "resumeArchiveInject", type: "bool", default: true, env: "OPENVIKING_RESUME_ARCHIVE_INJECT", capability: "session" },
+ { name: "resumeArchiveTokenBudget", type: "int", default: 32000, min: 0, max: 128000, env: "OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET", capability: "session" },
+ { name: "resumeArchiveMaxChars", type: "int", default: 6000, min: 1000, max: 200000, env: "OPENVIKING_RESUME_ARCHIVE_MAX_CHARS", capability: "session" },
+ { name: "skillExperience", type: "bool", default: false, env: "OPENVIKING_SKILL_EXPERIENCE", capability: "session" },
+ { name: "skillExperienceLimit", type: "int", default: 3, min: 1, max: 50, env: "OPENVIKING_SKILL_EXPERIENCE_LIMIT", capability: "session" },
+ { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" },
+ { name: "repoContext", type: "bool", default: true, capability: "session" },
+ { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" },
+
+ { name: "takeoverEnabled", type: "bool", default: true, env: "OPENVIKING_TAKEOVER", capability: "session" },
+ { name: "takeoverTokenThreshold", type: "int", default: 30000, min: 1, max: 1000000, capability: "session" },
+ { name: "takeoverKeepRecentTurns", type: "int", default: 3, min: 0, max: 100, capability: "session" },
+ { name: "takeoverOverviewBudget", type: "int", default: 3000, min: 100, max: 50000, capability: "session" },
+ { name: "takeoverOverviewPollMs", type: "int", default: 2000, min: 0, max: 60000, capability: "session" },
+ { name: "takeoverOverviewPollMax", type: "int", default: 15, min: 1, max: 120, capability: "session" },
+
+ { name: "bypassSession", type: "bool", default: false, env: "OPENVIKING_BYPASS_SESSION", capability: "session" },
+ {
+ name: "bypassSessionPatterns",
+ type: "list",
+ default: [],
+ env: "OPENVIKING_BYPASS_SESSION_PATTERNS",
+ // pi shipped this under its own name before the shared matcher existed.
+ aliases: ["bypassPatterns"],
+ workspace: "bypass.session_patterns",
+ capability: "session",
+ },
+
+ // ── debug ─────────────────────────────────────────────────────────────
+ { name: "debug", type: "bool", default: false, env: "OPENVIKING_DEBUG", capability: "debug" },
+ // The default path is per-harness and built from a log directory the loader
+ // owns, so the schema only carries what a user set.
+ { name: "debugLogPath", type: "string", default: "", env: "OPENVIKING_DEBUG_LOG", capability: "debug" },
+ { name: "logLevel", type: "enum", values: ["silent", "error", "info"], default: "error", env: "OPENVIKING_LOG_LEVEL", capability: "debug" },
+];
+
+export const KNOB_BY_NAME = new Map(KNOBS.map((knob) => [knob.name, knob]));
+
+/** Every accepted spelling → the canonical knob it means. */
+export const KNOB_BY_KEY = new Map();
+for (const knob of KNOBS) {
+ KNOB_BY_KEY.set(knob.name, knob);
+ for (const alias of knob.aliases || []) KNOB_BY_KEY.set(alias, knob);
+}
+
+/** Every key a user may legitimately write in `ovcli.conf`'s plugin section. */
+export function pluginConfigKeys() {
+ return new Set(KNOB_BY_KEY.keys());
+}
+
+/** The workspace file's dotted keys → the knob each one sets. */
+export const WORKSPACE_KNOB_MAP = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.name]),
+);
+
+/** The enum members and clamps the workspace validator reports on. */
+export const WORKSPACE_ENUMS = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.values || null]),
+);
+
+export const WORKSPACE_RANGES = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace && knob.min !== undefined && knob.max !== undefined)
+ .map((knob) => [knob.workspace, {
+ min: knob.min,
+ max: knob.max,
+ integer: knob.type === "int",
+ }]),
+);
+
+/**
+ * The harnesses that may appear as a per-harness object inside `plugin`.
+ *
+ * The key is snake_case because that is what ov.conf's own sections use; the
+ * hyphenated spelling a host calls itself (`claude-code`, `trae-cn`) is
+ * accepted too, so a user who copies the harness name out of the installer
+ * lands on the right override instead of on a silent no-op.
+ */
+export const HARNESS_KEYS = {
+ claudeCode: "claude_code",
+ codex: "codex",
+ cursor: "cursor",
+ trae: "trae",
+ traeCn: "trae_cn",
+ zcode: "zcode",
+ opencode: "opencode",
+ dsh: "dsh",
+ pi: "pi",
+ openclaw: "openclaw",
+};
+
+export function harnessKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** Both accepted spellings of every harness, for the `plugin` section. */
+export const HARNESS_CONFIG_KEYS = new Set(
+ Object.values(HARNESS_KEYS).flatMap((key) => [key, key.replace(/_/g, "-")]),
+);
+
+export function knobDefault(knob, harness = "") {
+ if (harness && knob.harness && knob.harness[harness] !== undefined) return knob.harness[harness];
+ return Array.isArray(knob.default) ? [...knob.default] : knob.default;
+}
+
+const TRUE_WORDS = ["1", "true", "yes", "on"];
+const FALSE_WORDS = ["0", "false", "no", "off"];
+
+/**
+ * Coerce one raw value to the knob's type.
+ *
+ * A value out of range is clamped and a value of the wrong shape falls back to
+ * the default: a hook that dies because someone typed a letter into a number
+ * would take the host's session down with it.
+ */
+export function coerceKnobValue(knob, raw, fallback) {
+ if (raw === undefined || raw === null) return fallback;
+ switch (knob.type) {
+ case "bool": {
+ if (typeof raw === "boolean") return raw;
+ const word = String(raw).trim().toLowerCase();
+ if (TRUE_WORDS.includes(word)) return true;
+ if (FALSE_WORDS.includes(word)) return false;
+ return fallback;
+ }
+ case "int":
+ case "number": {
+ if (typeof raw === "string" && !raw.trim()) return fallback;
+ const value = knob.type === "int" ? Math.round(Number(raw)) : Number(raw);
+ if (!Number.isFinite(value)) return fallback;
+ const floored = knob.min === undefined ? value : Math.max(knob.min, value);
+ return knob.max === undefined ? floored : Math.min(knob.max, floored);
+ }
+ case "enum": {
+ const word = String(raw ?? "").trim();
+ return (knob.values || []).includes(word) ? word : fallback;
+ }
+ // A peer template may be one string or an ordered list of fallbacks, and
+ // `String([a, b])` would quietly turn the list into one bogus template.
+ case "template": {
+ if (Array.isArray(raw)) {
+ const items = raw.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ return items.length ? items : fallback;
+ }
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ case "list": {
+ const items = Array.isArray(raw)
+ ? raw
+ : typeof raw === "string" ? raw.split(",") : null;
+ if (!items) return fallback;
+ return items.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ }
+ default: {
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ }
+}
+
+/**
+ * Resolve every knob through the layers, lowest priority first.
+ *
+ * `layers` is `[{ name, data }]`; `env` is the top layer and needs no entry.
+ * Returns the settings plus the names a layer actually supplied, which is what
+ * the `*Configured` flags report — several call sites send a field to the
+ * server only when the user asked for it, and a default must not look asked-for.
+ */
+export function resolveKnobs({ harness = "", layers = [], env = {} } = {}) {
+ const settings = {};
+ const configured = new Set();
+ const sources = {};
+ // A value that would not parse is not a configuration: without this sentinel
+ // `recallLimit: "abc"` would report as configured and send a default to the
+ // server dressed up as the user's choice.
+ const UNPARSEABLE = Symbol("unparseable");
+
+ const take = (knob, raw, source, current) => {
+ const value = coerceKnobValue(knob, raw, UNPARSEABLE);
+ if (value === UNPARSEABLE) return current;
+ configured.add(knob.name);
+ sources[knob.name] = source;
+ return value;
+ };
+
+ for (const knob of KNOBS) {
+ let value = knobDefault(knob, harness);
+ for (const layer of layers) {
+ const data = layer?.data;
+ if (!data || typeof data !== "object") continue;
+ // Aliases first so the canonical name wins when one layer carries both:
+ // a file with `recallCompressThinking` beside its older
+ // `recallCompressReasoningEffort` means the newer one.
+ for (const key of [...(knob.aliases || []), knob.name]) {
+ if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
+ if (data[key] === undefined) continue;
+ value = take(knob, data[key], layer.name || "file", value);
+ }
+ }
+ if (knob.env) {
+ const raw = env[knob.env];
+ if (raw !== undefined && raw !== null && String(raw) !== "") {
+ value = take(knob, raw, "env", value);
+ }
+ }
+ settings[knob.name] = value;
+ }
+
+ return { settings, configured, sources };
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/credentials.mjs b/examples/codex-memory-plugin/scripts/shared/credentials.mjs
index ba26a84dc..0ab2d984d 100644
--- a/examples/codex-memory-plugin/scripts/shared/credentials.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/credentials.mjs
@@ -7,6 +7,8 @@ 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";
+const DEFAULT_TIMEOUT_MS = 15000;
+const MIN_TIMEOUT_MS = 1000;
function str(val, fallback = "") {
if (typeof val === "string" && val.trim()) return val.trim();
@@ -108,6 +110,45 @@ export function loadCredentialFiles(env = process.env) {
};
}
+/**
+ * The calling harness's own section of ov.conf.
+ *
+ * ov.conf spells its sections snake_case while a host may call itself
+ * `claude-code` or `trae-cn`, so both spellings land on the same block. The
+ * normalization stays inline rather than importing `config-schema.mjs`, which
+ * the portable agent-plugins bundle would then have to ship as well.
+ */
+function harnessSection(ovFile, harness) {
+ const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+ const section = key ? ovFile[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+const AUTH_MODES = ["trusted", "api_key"];
+
+function normalizeAuthMode(value) {
+ const mode = str(value, "").toLowerCase();
+ return AUTH_MODES.includes(mode) ? mode : "";
+}
+
+/**
+ * Which auth mode the server is in, and with it whether the identity headers
+ * may go on the wire.
+ *
+ * An `api_key` server reads the account and the user out of the key and ignores
+ * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
+ * every proxy on the path who the operator is and buys nothing. A named mode
+ * wins; ov.conf's server block answers next; failing both, a credential layer
+ * that supplied an identity at all means the deployment expects one.
+ */
+export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
+ const server = ovFile.server || {};
+ const authMode = normalizeAuthMode(settings.authMode)
+ || normalizeAuthMode(server.auth_mode)
+ || ((account || user) ? "trusted" : "api_key");
+ return { authMode, sendIdentityHeaders: authMode === "trusted" };
+}
+
function sourceMode(env) {
const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
.toLowerCase();
@@ -144,40 +185,58 @@ function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
return `http://${host}:${port}`;
}
-export function resolveOpenVikingCredentials(env = process.env) {
+/**
+ * `harness` names whose ov.conf section supplies the legacy fallback. It sits
+ * where it always did — after ovcli.conf, before `server.root_api_key` — but a
+ * harness now reads its own section instead of every one of them reading
+ * codex's. The default keeps codex, the only caller that never passes one.
+ *
+ * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
+ * section named, which this module cannot read for itself: resolving that
+ * section needs the knob schema, and the portable bundles would then have to
+ * ship it. All three rank where the file they come from ranks — under
+ * ovcli.conf's own fields, over ov.conf.
+ */
+export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
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 cx = harnessSection(files.ovFile, harness);
const server = files.ovFile.server || {};
const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+ const pluginApiKey = str(plugin?.apiKey, "");
const apiKey = useCli
- ? str(files.cliFile.api_key, "")
+ ? (str(files.cliFile.api_key, "") || pluginApiKey)
: (
str(env.OPENVIKING_BEARER_TOKEN, "") ||
str(env.OPENVIKING_API_KEY, "") ||
str(files.cliFile.api_key, "") ||
+ pluginApiKey ||
str(cx.apiKey, "") ||
str(server.root_api_key, "")
);
+ const pluginAccount = str(plugin?.accountId, "");
const account = useCli
- ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
: (
str(env.OPENVIKING_ACCOUNT, "") ||
str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ pluginAccount ||
str(cx.accountId, "")
);
+ const pluginUser = str(plugin?.userId, "");
const user = useCli
- ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
: (
str(env.OPENVIKING_USER, "") ||
str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ pluginUser ||
str(cx.userId, "")
);
@@ -192,19 +251,31 @@ export function resolveOpenVikingCredentials(env = process.env) {
const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
+ // Which layer actually supplied the api_key, following the same chain, and
+ // the file behind it — empty when the key came from the environment or was
+ // never found. `apiKeySource` is what a doctor and a 401 hint report; the
+ // credential *source* beside it is the mode the chain ran in, not a file.
+ let apiKeySource = "none";
let credentialPath = "";
if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
+ if (useCli) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
+ apiKeySource = "env";
+ } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else {
+ apiKeySource = "ov";
+ credentialPath = files.ovPath;
+ }
}
return {
...files,
credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ apiKeySource,
credentialPath,
baseUrl,
mcpUrl,
@@ -216,6 +287,71 @@ export function resolveOpenVikingCredentials(env = process.env) {
};
}
+function envFlag(env, name) {
+ const raw = str(env[name], "").toLowerCase();
+ return raw === "1" || raw === "true" || raw === "yes";
+}
+
+function clampTimeout(value) {
+ const raw = str(value, "");
+ const parsed = raw ? Number(raw) : NaN;
+ return Math.max(MIN_TIMEOUT_MS, Math.floor(Number.isFinite(parsed) ? parsed : DEFAULT_TIMEOUT_MS));
+}
+
+/**
+ * Everything a stdio MCP proxy needs, for a package that ships no hooks.
+ *
+ * `buildPluginConfig` answers the same question one layer up, but reaching it
+ * means vendoring the knob schema and the workspace layers — a closure the
+ * portable agent-plugins bundle would carry in git to send one HTTP header.
+ * This is the connection half alone: the credential chain, the auth mode that
+ * decides whether the identity headers may go on the wire, the User-Agent, the
+ * request timeout, and the debug log.
+ *
+ * The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
+ * chain to itself. A portable package has no installer to migrate anyone, so
+ * an install that names only a `url` there keeps the key it has always used.
+ */
+export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
+ const name = str(harness);
+ const credentials = resolveOpenVikingCredentials(env, name);
+
+ let { apiKey, apiKeySource, credentialPath } = credentials;
+ if (!apiKey) {
+ apiKey = str(credentials.ovFile?.server?.root_api_key);
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+
+ return {
+ harness: name,
+ userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
+ baseUrl: credentials.baseUrl,
+ mcpUrl: credentials.mcpUrl,
+ apiKey,
+ account: credentials.account,
+ user: credentials.user,
+ peerId: credentials.peerId,
+ ...resolveAuthMode({
+ settings: { authMode: env.OPENVIKING_AUTH_MODE },
+ ovFile: credentials.ovFile,
+ account: credentials.account,
+ user: credentials.user,
+ }),
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
+ debug: envFlag(env, "OPENVIKING_DEBUG"),
+ debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
+ || join(homedir(), ".openviking", "logs", `${name}.log`),
+ };
+}
+
function main() {
const cmd = process.argv[2] || "";
if (cmd === "mcp-url") {
@@ -230,7 +366,7 @@ function main() {
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.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
process.exitCode = 2;
}
diff --git a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
index 47887e6e8..7cdd797cf 100644
--- a/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/doctor-core.mjs
@@ -7,7 +7,9 @@
* state directory) and delegates everything that is the same everywhere to
* this module: config-file inspection, API key display, base URL linting,
* environment sweep, server probes and their interpretation, state/log
- * inspection, and report rendering.
+ * inspection, and report rendering. `runDoctor(hostSpec)` owns the run itself:
+ * the argument parsing, the section order, the `--json` envelope and the exit
+ * code, calling back into the host for the sections only it can produce.
*
* Nothing here reads harness config; callers pass a resolved connection
* `{ baseUrl, apiKey, account, user, peerId, userAgent }`.
@@ -16,12 +18,15 @@
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { join, resolve as resolvePath } from "node:path";
+import { HARNESS_CONFIG_KEYS, HARNESS_KEYS, harnessKey, KNOB_BY_NAME, pluginConfigKeys } from "./config-schema.mjs";
+import { buildOvHeaders } from "./ov-http.mjs";
import { resolveWorkspaceSettings } from "./plugin-config.mjs";
import { peerScopeMemoPath } from "./recall-core.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE, workspaceConfigPaths } from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId } from "./workspace-peer.mjs";
import { entryPath } from "./workspace-registry.mjs";
/**
@@ -311,32 +316,13 @@ export function unknownOvcliKeys(data) {
*
* `plugin` is on the allowlist above, which used to mean everything inside it
* went unchecked — so `peerSorce` sat there doing nothing with no complaint.
- * `plugin-known-keys.test.mjs` derives this set from the two loaders and fails
- * when they diverge, so it cannot rot into a list that rejects a real knob.
+ * The set is the schema's own key list, aliases included, so it cannot rot into
+ * a list that rejects a real knob.
*/
-export const KNOWN_PLUGIN_KEYS = new Set([
- "apiKey", "accountId", "userId", "auth_mode", "authMode", "enabled", "debug", "timeoutMs",
- "peerId", "peer_id", "peerSource", "workspacePeer",
- "autoRecall", "autoCapture", "noAutoInject", "writePathAsync", "minQueryLength",
- "bypassSessionPatterns",
- "recallLimit", "recallMaxTokens", "recallMaxContentChars", "recallTokenBudget",
- "recallPeerScope", "recallDedupTurns", "recallQueryExpansion", "recallPreferAbstract",
- "recallRewrite", "recallContextTimeoutMs", "recallTimeoutMs", "scoreThreshold",
- "recallCompress", "recallCompressMaxBullets", "recallCompressMaxInputChars",
- "recallCompressMinInputChars", "recallCompressBaseUrl", "recallCompressModel",
- "recallCompressThinking", "recallCompressReasoningEffort", "recallCompressTimeoutMs",
- "recallCompressDetectOnStartup", "recallCompressDetectTimeoutMs", "recallCompressDetectTtlMs",
- "recallQueryFilters", "captureFilters",
- "captureMode", "captureMaxLength", "captureTimeoutMs", "captureToolMaxChars",
- "captureAssistantTurns", "captureLastAssistantOnStop", "logRankingDetails",
- "commitTokenThreshold", "commitKeepRecentCount", "autoCommitOnCompact",
- "profileTokenBudget", "resumeContextBudget", "resumeArchiveInject",
- "resumeArchiveMaxChars", "resumeArchiveTokenBudget",
- "skillExperience", "skillExperienceLimit",
-]);
+export const KNOWN_PLUGIN_KEYS = pluginConfigKeys();
/** Nested objects in `plugin` are per-harness overrides, not knobs. */
-const PLUGIN_HARNESS_KEYS = new Set(["claude_code", "codex"]);
+const PLUGIN_HARNESS_KEYS = HARNESS_CONFIG_KEYS;
function nearestKnownKey(key) {
// Levenshtein would be overkill; a typo that matters is almost always one
@@ -502,14 +488,10 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo
return out;
}
+// A connection record carries no `sendIdentityHeaders`: the doctor asks with
+// the identity and reports whatever the server echoes back.
function authHeaders(conn, { identity = true } = {}) {
- const headers = { "Content-Type": "application/json" };
- if (conn.apiKey) headers["Authorization"] = `Bearer ${conn.apiKey}`;
- if (identity && conn.account) headers["X-OpenViking-Account"] = conn.account;
- if (identity && conn.user) headers["X-OpenViking-User"] = conn.user;
- if (conn.peerId) headers["X-OpenViking-Actor-Peer"] = conn.peerId;
- if (conn.userAgent) headers["User-Agent"] = conn.userAgent;
- return headers;
+ return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity });
}
export function serverErrorMessage(probe) {
@@ -780,7 +762,7 @@ export function gitignoreHidesWorkspaceConfig(root) {
* provenance is how a user finds out which layer actually won, the way
* `git config --show-origin --show-scope` does.
*/
-export function checkWorkspace(report, { cwd = process.cwd(), env = process.env } = {}) {
+export function checkWorkspace(report, { cwd = process.cwd(), env = process.env, clientVersion = "" } = {}) {
report.section("Workspace");
const { root, rootKind, git } = findWorkspaceRoot(cwd, env);
@@ -794,7 +776,7 @@ export function checkWorkspace(report, { cwd = process.cwd(), env = process.env
const foundBy = rootKind === "git" ? git.kind : `${TEAM_FILE}${git ? ` inside ${git.kind}` : ""}`;
report.ok(`workspace ${homeShort(root)} ← ${foundBy}`);
- const resolved = resolveWorkspaceSettings(cwd, env);
+ const resolved = resolveWorkspaceSettings(cwd, env, { clientVersion });
summary.settings = resolved.settings;
summary.provenance = resolved.provenance;
const identity = resolveWorkspaceIdentity({ cwd, env });
@@ -915,7 +897,13 @@ export function existsPath(path) {
// `openviking-server doctor`, which runs in the server's Python environment.
// ---------------------------------------------------------------------------
-const PLUGIN_ONLY_OV_CONF_KEYS = { claude_code: "ovcli.conf plugin.claude_code", codex: "ovcli.conf plugin.codex" };
+// Every harness reads the ov.conf section named after it, so every one of
+// those names is a block a user may have written and the server refuses.
+const PLUGIN_ONLY_OV_CONF_KEYS = Object.fromEntries(
+ Object.values(HARNESS_KEYS)
+ .filter((key) => key !== "openclaw")
+ .map((key) => [key, `ovcli.conf plugin.${key}`]),
+);
const READY_OK_VALUES = new Set(["ok", "not_configured", "not_supported"]);
const READY_FIXES = {
embedding: "the server cannot embed with the configured provider — check embedding.dense.{provider,model,api_key,api_base} in ov.conf; `openviking-server doctor` shows the provider's reply",
@@ -1094,3 +1082,363 @@ export async function checkServerHealth(report, { baseUrl, ovConf, health, offli
else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;
return summary;
}
+
+// ---------------------------------------------------------------------------
+// Configuration segments
+//
+// The "Configuration" section is host-composed: these are the parts every
+// harness reports identically, called in order, with the host slotting its own
+// lines in between (Claude Code's enable verdict, Codex's credential-source
+// block). Each segment takes the harness spec `runDoctor` already carries.
+// ---------------------------------------------------------------------------
+
+/** ovcli.conf and ov.conf: where they are, whether they parse, what sits in them. */
+export function inspectConfigFiles(report, { harness = "", launcherHint = "this harness" } = {}) {
+ const key = harnessKey(harness);
+ const cliConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf")));
+ const ovConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf")));
+
+ for (const [label, conf] of [["ovcli.conf", cliConf], ["ov.conf", ovConf]]) {
+ if (!conf.exists) {
+ report.info(`${label}: ${homeShort(conf.path)} not present`);
+ continue;
+ }
+ if (!conf.ok) {
+ report.fail(`${label} cannot be parsed — the plugin treats it as absent`, `${homeShort(conf.path)}: ${conf.error}`, "fix the JSON (a trailing comma or comment is enough to break it)");
+ continue;
+ }
+ report.ok(`${label}: ${homeShort(conf.path)} (mode ${conf.mode}, ${fmtBytes(conf.size)})`);
+ if (label === "ov.conf") {
+ if (key && conf.data[key]) report.info(`ov.conf has a legacy ${key} block (still honoured; prefer ovcli.conf plugin.${key} or env vars)`);
+ continue;
+ }
+ if (conf.mode !== "600" && conf.mode !== "400") report.warn("ovcli.conf is not private", `mode ${conf.mode}; it holds the api key`, `chmod 600 ${homeShort(conf.path)}`);
+ const unknown = unknownOvcliKeys(conf.data);
+ if (unknown.length) report.warn("ovcli.conf has keys nobody reads", unknown.join(", "), "typos such as apiKey/base_url/token are silently ignored — use url, api_key, account, user");
+ // `plugin` is on the ovcli allowlist, so nothing inside it is checked
+ // there — a misspelled knob would just sit doing nothing.
+ for (const { key: knob, suggestion } of unknownPluginKeys(conf.data.plugin)) {
+ report.warn(`ovcli.conf ${knob} is not a knob any plugin reads`, "", suggestion ? `did you mean ${suggestion}?` : "remove it, or check the plugin README for the knob you meant");
+ }
+ if (conf.data.extra_headers && Object.keys(conf.data.extra_headers).some((h) => /^x-api-key$/i.test(h))) {
+ report.warn("ovcli.conf extra_headers sets X-API-Key", "the server prefers X-API-Key over Authorization: Bearer, so it shadows api_key");
+ }
+ const sections = Object.keys(conf.data.plugin || {}).filter((k) => HARNESS_CONFIG_KEYS.has(k));
+ const others = sections.filter((k) => harnessKey(k) !== key);
+ if (key && others.length && !sections.some((k) => harnessKey(k) === key)) {
+ report.info(`ovcli.conf ${others.map((k) => `plugin.${k}`).join(", ")} settings do not apply to ${launcherHint} (use plugin.${key})`);
+ }
+ }
+ return { cliConf, ovConf };
+}
+
+/**
+ * Where each resolved credential came from, as one label per field.
+ *
+ * The key's layer is not re-derived here: `buildPluginConfig` already answered
+ * it in `apiKeySource`, and three doctors reconstructing that walk by hand is
+ * three chances to describe a chain nobody runs. What the files are still asked
+ * is which field inside the winning layer holds the value, because the layer
+ * alone cannot tell `plugin.<harness>.apiKey` from `api_key`, or a harness
+ * block from `server.root_api_key`.
+ *
+ * The identity has no such answer to read, so account and user follow the chain
+ * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * at that file's `plugin` section, and otherwise the environment wins and
+ * ov.conf's harness block is last.
+ */
+export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(cfg.harness || "") } = {}) {
+ const env = process.env;
+ const cliShort = homeShort(cliConf.path);
+ const ovShort = homeShort(ovConf.path);
+ const cli = cliConf.ok ? cliConf.data : {};
+ const ov = ovConf.ok ? ovConf.data : {};
+ const plugin = cli.plugin || {};
+ const scoped = (section && plugin[section]) || {};
+ const block = (section && ov[section]) || {};
+ const server = ov.server || {};
+ // Pinned to ovcli.conf, the chain never looks at the environment.
+ const pinned = cfg.credentialSource === "ovcli";
+
+ const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
+ const url = (!pinned && envUrl) ? "env"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+
+ let apiKey;
+ if (cfg.apiKeySource === "env") {
+ apiKey = env.OPENVIKING_BEARER_TOKEN ? "env OPENVIKING_BEARER_TOKEN" : "env OPENVIKING_API_KEY";
+ } else if (cfg.apiKeySource === "ovcli") {
+ apiKey = cli.api_key ? cliShort
+ : scoped.apiKey ? `${cliShort} plugin.${section}.apiKey`
+ : plugin.apiKey ? `${cliShort} plugin.apiKey` : cliShort;
+ } else if (cfg.apiKeySource === "ov") {
+ apiKey = block.apiKey ? `${ovShort} ${section}.apiKey`
+ : server.root_api_key ? `${ovShort} server.root_api_key` : ovShort;
+ } else if (cfg.apiKeySource === "host") {
+ apiKey = "the host application";
+ } else {
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ }
+
+ const identity = (envName, cliValue, name) => (
+ (!pinned && env[envName]) ? "env"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ );
+ return {
+ url,
+ apiKey,
+ account: identity("OPENVIKING_ACCOUNT", cli.account || cli.account_id, "accountId"),
+ user: identity("OPENVIKING_USER", cli.user || cli.user_id, "userId"),
+ };
+}
+
+/**
+ * The resolved url, key and identity, each with the source it came from.
+ * `sources` is the host's own credential chain rendered as one label per field.
+ */
+export function reportCredentials(report, cfg, sources, { account = "", user = "" } = {}) {
+ report.info(`url ${cfg.baseUrl} ← ${sources.url}`);
+ for (const p of lintBaseUrl(cfg.baseUrl)) report[p.level](p.message, "", p.fix);
+ if (sources.url.startsWith("default") && !isLoopbackUrl(cfg.baseUrl)) report.info("url fell back to the built-in default");
+ else if (sources.url.startsWith("default")) report.warn("no url configured — using the built-in default http://127.0.0.1:1933", "only right when the server runs on this machine", "set url in ovcli.conf or OPENVIKING_URL");
+
+ const keyInfo = describeApiKey(cfg.apiKey);
+ report.info(`api_key ${keyInfo.display} ← ${sources.apiKey}`);
+ for (const p of keyInfo.problems) report.warn(`api key ${p}`, "", "re-copy the key exactly as issued");
+ if (sources.apiKey.includes("root_api_key")) {
+ report.warn("api key falls back to ov.conf server.root_api_key", "the root key is refused on tenant data APIs and /mcp in api_key mode; against a remote server it is simply the wrong key",
+ "put a user/admin key in ovcli.conf api_key (or OPENVIKING_API_KEY)");
+ }
+ if (!keyInfo.present && !isLoopbackUrl(cfg.baseUrl)) report.warn("no api key configured for a non-local server", "", "set api_key in ovcli.conf or OPENVIKING_API_KEY");
+ report.info(`account ${account || "(unset)"} ← ${sources.account}`);
+ report.info(`user ${user || "(unset)"} ← ${sources.user}`);
+ if (keyInfo.format === "v2") {
+ if (account && keyInfo.account && account !== keyInfo.account) report.warn(`configured account '${account}' differs from the key's account '${keyInfo.account}'`, "in api_key mode the key wins");
+ if (user && keyInfo.user && user !== keyInfo.user) report.warn(`configured user '${user}' differs from the key's user '${keyInfo.user}'`, "in api_key mode the key wins");
+ }
+ return keyInfo;
+}
+
+/** The peer this directory sends, where it came from, and what it costs when there is none. */
+export function reportPeer(report, cfg, { cwd = process.cwd() } = {}) {
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ report.info(`peer ${peer.peerId || "(none)"} ← ${peer.source} (${peer.origin})`);
+ if (peer.origin === "unresolved") {
+ report.info(
+ "no peer is sent: this directory is in no git repository, so its memories go to your user-level space",
+ `to give it a memory of its own, create .openviking/config.json here with ${WORKSPACE_PEER_HINT}`,
+ );
+ } else if (peer.source === "none") {
+ report.warn(
+ "no peer is sent, so recall defaults to every memory under this user",
+ "sending a peer narrows the search to this workspace",
+ 'unset OPENVIKING_WORKSPACE_PEER, or set peer.source to "git"',
+ );
+ }
+ if (peer.legacyPeerId) {
+ report.info(
+ `previous peer ${peer.legacyPeerId}`,
+ cfg.recallPeerScope === "actor"
+ ? "recall asks it separately, because peer_scope actor turns off the server's cross-peer sweep"
+ : "already covered by the server's cross-peer sweep under peer_scope all",
+ );
+ }
+ for (const p of lintPeerScopeDowngrade()) report[p.level](p.message, p.detail, p.fix);
+ return peer;
+}
+
+const TIMEOUT_LABELS = { timeoutMs: "request", recallTimeoutMs: "recall", captureTimeoutMs: "capture" };
+
+/**
+ * The timeouts line and the hook-budget check. `timeoutBudgets` maps a hook
+ * event to the knob that governs the request inside it, so each harness names
+ * the knob its own recall and capture paths actually read — a request that
+ * outlives its hook is killed by the host before it can answer.
+ *
+ * `hooksTemplate` names the template when it does not sit at the plugin root,
+ * and an entry states its timeout either directly or one nesting level down.
+ */
+export function reportTimeouts(report, cfg, { pluginRoot = "", hooksTemplate = "", launcherHint = "the harness", timeoutBudgets = {} } = {}) {
+ const knobs = [...new Set(["timeoutMs", ...Object.values(timeoutBudgets)])];
+ report.info(`timeouts ${knobs.map((knob) => `${cfg[knob]}ms ${TIMEOUT_LABELS[knob] || knob}`).join(", ")}; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);
+
+ const hooks = tryJson(hooksTemplate || join(pluginRoot, "hooks", "hooks.json"))?.hooks || {};
+ for (const [event, knob] of Object.entries(timeoutBudgets)) {
+ const entry = hooks[event]?.[0];
+ const budget = Number(entry?.hooks?.[0]?.timeout ?? entry?.timeout) * 1000 || 0;
+ if (!budget || !(cfg[knob] > budget)) continue;
+ report.warn(`${TIMEOUT_LABELS[knob] || knob} timeout ${cfg[knob]}ms exceeds the ${event} hook budget ${budget}ms`,
+ `${launcherHint} kills the hook before the request can finish`,
+ `lower ${KNOB_BY_NAME.get(knob)?.env || knob}`);
+ }
+}
+
+/** The switches that decide whether anything is injected at all. */
+export function reportToggles(report, cfg, { harness = "" } = {}, toggles = []) {
+ report.info(`toggles ${toggles.join(", ")}`);
+ if (!cfg.autoRecall || !cfg.autoCapture || cfg.noAutoInject) {
+ report.warn("one or more injection paths are switched off", toggles.join(", "),
+ `check OPENVIKING_AUTO_RECALL / OPENVIKING_AUTO_CAPTURE / OPENVIKING_NO_AUTO_INJECT and ovcli.conf plugin.${harnessKey(harness)}`);
+ }
+}
+
+/**
+ * Where the hooks log, and what the environment does to them. `extra` adds the
+ * host's own reading of the OPENVIKING_* vars it found.
+ */
+export function sweepEnv(report, cfg, { launcherHint = "the harness" } = {}, extra) {
+ report.info(`debug log ${cfg.debug ? "on" : "off"} → ${homeShort(cfg.debugLogPath)}${cfg.debug ? "" : ` (set OPENVIKING_DEBUG=1 in ${launcherHint}'s environment to record hook errors)`}`);
+
+ const env = collectEnv();
+ if (env.openviking.length) {
+ report.info("OPENVIKING_* in this environment", env.openviking.map((e) => `${e.name}=${e.value}`).join("\n"));
+ if (extra) extra(report, env);
+ } else {
+ report.info("no OPENVIKING_* environment variables set");
+ }
+ if (env.proxy.length) {
+ report.warn(`proxy variables set: ${env.proxy.map((e) => e.name).join(", ")}`,
+ "Node's fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY=1 (Node 24+); curl honours them, so curl may succeed while hooks fail",
+ isLoopbackUrl(cfg.baseUrl) ? "harmless for a local server" : `set NODE_USE_ENV_PROXY=1 (or reach the server without the proxy) in the environment that launches ${launcherHint}`);
+ }
+ if (env.node.length) report.info(`node TLS/proxy env: ${env.node.map((e) => `${e.name}=${e.value}`).join(", ")}`);
+ if (/^https:/i.test(cfg.baseUrl) && env.node.some((e) => e.name === "NODE_TLS_REJECT_UNAUTHORIZED" && e.value === "0")) {
+ report.warn("NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate checks", "", "prefer NODE_EXTRA_CA_CERTS=<ca.pem>");
+ }
+ return env;
+}
+
+// ---------------------------------------------------------------------------
+// The run
+// ---------------------------------------------------------------------------
+
+export function parseArgs(argv) {
+ const opts = { json: false, offline: false, timeoutMs: 5000, color: process.stdout.isTTY && !process.env.NO_COLOR };
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === "--json") opts.json = true;
+ else if (arg === "--offline" || arg === "--no-network") opts.offline = true;
+ else if (arg === "--no-color") opts.color = false;
+ else if (arg === "--timeout") opts.timeoutMs = Math.max(1000, Number(argv[++i]) || 5000);
+ else if (arg === "-h" || arg === "--help") {
+ console.log("usage: ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]");
+ process.exit(0);
+ }
+ }
+ if (opts.json) opts.color = false;
+ return opts;
+}
+
+export function expandHome(p) {
+ return p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p;
+}
+
+export function tryJson(path) {
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The "Environment" section. `launcherHint` names the host in the prose ("the
+ * environment that launches Claude Code"); `onCliFound` lets a host report its
+ * CLI its own way and add probes of its own between the version line and the
+ * platform line.
+ */
+export function checkEnvironment(report, { cliName, cliVersionArgs = ["--version"], launcherHint, nodePathFix, onCliFound } = {}) {
+ report.section("Environment");
+ const nodeMajor = parseNodeMajor(process.version);
+ const nodePath = process.execPath;
+ if (nodeMajor >= 18) report.ok(`node ${process.version} (${nodePath})`);
+ else report.fail(`node ${process.version} is too old`, "hooks and the MCP proxy need Node.js 18+ (global fetch)", "install Node.js 18 or newer and make sure it is first on PATH");
+ const nodeOnPath = whichCommand("node");
+ if (!nodeOnPath) {
+ report.warn("`node` is not on PATH for this process",
+ `hooks and .mcp.json invoke the bare command \`node\`; if ${launcherHint} was launched without your shell profile (nvm/volta/fnm), hooks never start`,
+ nodePathFix || `put node on PATH for the environment that launches ${launcherHint}`);
+ } else if (resolvePath(nodeOnPath) !== resolvePath(nodePath)) {
+ report.info(`PATH resolves node to ${nodeOnPath} (this run used ${nodePath})`);
+ }
+
+ const cli = runCommand(cliName, cliVersionArgs, { timeoutMs: 15000 });
+ if (cli.ok) {
+ if (onCliFound) onCliFound(report, cli);
+ else report.ok(cli.stdout.split("\n")[0]);
+ } else {
+ report.info(`${cliName} CLI not found on PATH (${cli.error || "?"}) — install checks that need it are skipped`);
+ }
+ report.info(`platform ${process.platform} ${process.arch}, cwd ${homeShort(process.cwd())}`);
+ return { cliOnPath: cli.ok };
+}
+
+/**
+ * The "Connection" section. `account`/`user` are the configured identity: they
+ * only reach the wire when the harness sends identity headers, but the probe
+ * report compares them against what the key claims either way. `onSummary`
+ * carries the host's verdict on the answer (Codex compares auth modes).
+ */
+export async function checkConnection(report, cfg, { keyInfo, peer, account = "", user = "" }, opts, { onSummary } = {}) {
+ report.section("Connection");
+ if (opts.offline) {
+ report.info("skipped (--offline)");
+ return null;
+ }
+ const conn = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, account: cfg.sendIdentityHeaders ? account : "", user: cfg.sendIdentityHeaders ? user : "", peerId: peer.peerId, userAgent: cfg.userAgent };
+ const probes = await probeOpenViking(conn, { timeoutMs: opts.timeoutMs });
+ const summary = assessProbes(report, probes, { ...conn, account, user }, keyInfo);
+ if (onSummary) onSummary(report, summary, cfg);
+ return { probes, summary };
+}
+
+/**
+ * Run one harness's doctor. `host` is the harness spec: the `checkEnvironment`
+ * fields above, `loadConfig()`, the three sections only the host can produce
+ * (`checkInstall`, `checkConfig`, `checkActivity`), `resolveIdentity(cfg)` for
+ * the account/user spelling that harness uses, and optionally `onSummary` and
+ * `extraResolved(cfg)` for extra `--json` fields. `checkConfig` is handed the
+ * spec back, because the configuration segments it composes are driven by it.
+ */
+export async function runDoctor(host) {
+ const opts = parseArgs(process.argv.slice(2));
+ const report = createReport({ color: opts.color });
+ const envInfo = checkEnvironment(report, host);
+ host.checkInstall(report, envInfo);
+ const cfg = host.loadConfig();
+ const configInfo = host.checkConfig(report, cfg, host);
+ const workspace = checkWorkspace(report, { clientVersion: cfg.clientVersion });
+ const identity = host.resolveIdentity(cfg);
+ const connection = await checkConnection(report, cfg, { ...configInfo, ...identity }, opts, host);
+ const serverHealth = await checkServerHealth(report, { baseUrl: cfg.baseUrl, ovConf: configInfo.ovConf, health: connection?.probes?.health, offline: opts.offline, timeoutMs: opts.timeoutMs });
+ host.checkActivity(report, cfg, connection);
+
+ if (opts.json) {
+ console.log(JSON.stringify({
+ harness: host.harness,
+ pluginRoot: host.pluginRoot,
+ generatedAt: new Date().toISOString(),
+ resolved: {
+ baseUrl: cfg.baseUrl,
+ apiKey: configInfo.keyInfo.display,
+ apiKeyFormat: configInfo.keyInfo.format,
+ account: identity.account,
+ user: identity.user,
+ peerId: configInfo.peer.peerId,
+ ...(host.extraResolved ? host.extraResolved(cfg) : {}),
+ },
+ workspace,
+ server: connection?.summary || null,
+ serverHealth,
+ ...report.toJSON(),
+ }, null, 2));
+ } else {
+ console.log(report.render());
+ }
+ process.exitCode = report.exitCode();
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
index 24d33d9fb..dd11897ee 100644
--- a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-config.mjs
@@ -86,7 +86,9 @@ function uniq(values) {
* `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
* user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
* harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
+ * deduplicated. `sendIdentityHeaders` carries the harness's resolved auth mode
+ * so an `api_key` server, which reads the identity out of the key and ignores
+ * the headers, never sees the operator's account and user on the wire.
*/
export function buildMcpProxyConfig({
baseUrl = "",
@@ -94,6 +96,7 @@ export function buildMcpProxyConfig({
apiKey = "",
account = "",
user = "",
+ sendIdentityHeaders = false,
peerId = "",
userAgent = "",
timeoutMs,
@@ -109,6 +112,7 @@ export function buildMcpProxyConfig({
apiKey: apiKey || "",
account: account || "",
user: user || "",
+ sendIdentityHeaders: sendIdentityHeaders === true,
peerId: peerId || "",
userAgent: userAgent || "",
timeoutMs: Math.max(
diff --git a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs
index 9a8f5ba26..de11c2879 100644
--- a/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/mcp-proxy-core.mjs
@@ -9,6 +9,8 @@
import { statSync } from "node:fs";
import { createInterface } from "node:readline";
+import { buildOvHeaders } from "./ov-http.mjs";
+
const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
const DELETE_TIMEOUT_MS = 2000;
const MAX_CONCURRENT_REQUESTS = 16;
@@ -240,21 +242,17 @@ export function createOpenVikingMcpProxy({
}
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;
+ return buildOvHeaders(proxyConfig, {
+ actorPeerId: proxyConfig.peerId,
+ extraHeaders: {
+ "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,
+ ...(includeSession && sessionId ? { "Mcp-Session-Id": sessionId } : {}),
+ },
+ });
}
function writeMessage(obj) {
diff --git a/examples/codex-memory-plugin/scripts/shared/ov-http.mjs b/examples/codex-memory-plugin/scripts/shared/ov-http.mjs
new file mode 100644
index 000000000..e02f5316e
--- /dev/null
+++ b/examples/codex-memory-plugin/scripts/shared/ov-http.mjs
@@ -0,0 +1,112 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+/**
+ * The one path from a hook to the OpenViking server.
+ *
+ * Every harness used to own its own AbortController, header block and envelope
+ * parser, and they drifted: one sent the api key twice, one named the operator
+ * to every proxy on the path whether or not the server was trusted with it, one
+ * read a different field for the same account. A server-side change now lands
+ * in one place instead of eight.
+ *
+ * `X-API-Key` is deliberately absent. The server takes `Authorization: Bearer`,
+ * and the identity headers go out only when the resolved config says this
+ * server is trusted with the operator's name.
+ */
+
+// A request that aborts the instant it starts reads as a dead server. A config
+// that asks for less than a second gets a second.
+const MIN_TIMEOUT_MS = 1000;
+
+/**
+ * The headers every harness puts on every OpenViking request.
+ *
+ * `identityHeaders` overrides `cfg.sendIdentityHeaders` for the callers that
+ * decide per request rather than per config — the doctor probes both ways.
+ */
+export function buildOvHeaders(cfg = {}, { actorPeerId = "", identityHeaders, extraHeaders } = {}) {
+ const identity = identityHeaders === undefined ? Boolean(cfg.sendIdentityHeaders) : Boolean(identityHeaders);
+ const headers = { "Content-Type": "application/json" };
+ if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
+ if (identity && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (identity && cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
+ if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ return { ...headers, ...extraHeaders };
+}
+
+function responseTraceId(body) {
+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
+}
+
+/**
+ * Build the `fetchJSON(path, init, { timeoutMs, actorPeerId })` a harness talks
+ * through. It resolves to `{ ok, status, result, error, traceId }` and never
+ * throws: a hook that crashes on a closed port would take its host's turn with
+ * it, so a network error is `{ ok: false, status: 0 }` and the retry rules in
+ * `retryable.mjs` decide what happens next.
+ *
+ * `resolveActorPeerId` is a callback because Codex only knows its peer after
+ * loading session state under the lock, well after the client is built.
+ * `requireJsonBody` is for the capture hooks, which would rather retry a body
+ * they cannot parse than record the turn as sent.
+ */
+export function createOvHttp(cfg = {}, {
+ defaultTimeoutMs = 0,
+ resolveActorPeerId = () => "",
+ identityHeaders,
+ extraHeaders,
+ requireJsonBody = false,
+} = {}) {
+ // dsh and pi name this field `endpoint`; every other harness names it `baseUrl`.
+ const baseUrl = cfg.baseUrl || cfg.endpoint || "";
+ return async function fetchJSON(path, init = {}, options = {}) {
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0);
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ try {
+ const headers = {
+ ...buildOvHeaders(cfg, {
+ actorPeerId: options.actorPeerId ?? resolveActorPeerId(),
+ identityHeaders,
+ extraHeaders,
+ }),
+ ...(init.headers || {}),
+ };
+ const response = await fetch(`${baseUrl}${path}`, { ...init, headers, signal: controller.signal });
+ const body = await response.json().catch(() => null);
+ if (requireJsonBody && !body) {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: { message: "empty or invalid JSON response" },
+ };
+ }
+ const traceId = responseTraceId(body);
+ if (!response.ok || body?.status === "error") {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: body?.error || { message: `HTTP ${response.status}` },
+ traceId,
+ };
+ }
+ return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId };
+ } catch (error) {
+ const message = error?.message || String(error);
+ // This module owns the controller, so it says a timeout was a timeout
+ // rather than leaving callers to guess it from whatever fetch threw.
+ const failure = timedOut
+ ? { name: "AbortError", aborted: true, message }
+ : { message };
+ return { ok: false, status: 0, result: null, error: failure };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+}
diff --git a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
index 7cbaba5ba..cbae04ab8 100644
--- a/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/plugin-config.mjs
@@ -19,18 +19,24 @@
* Resolution stays env → ovcli.conf plugin.<harness> → ovcli.conf plugin →
* ov.conf harness section (legacy) → defaults.
*
- * Consumers: Claude Code and Codex only. The other harnesses ship this module
- * through `sync.mjs` but still read their knobs from the environment, so a
- * `plugin` entry named after them is inert. `HARNESS_KEYS` lists what a harness
- * loader actually consumes today — add a key here as its loader starts calling
- * `loadPluginSettings`, not before, so the section never promises a knob that
- * silently does nothing.
+ * Every harness resolves through `resolveSettings()` below, and assembles its
+ * whole configuration through `buildPluginConfig()`, so one `plugin` section
+ * configures all of them and `ov config switch` moves behaviour along with
+ * credentials. The knobs themselves are declared once in `config-schema.mjs`;
+ * this module decides which files supply them and what is derived from them.
*/
-import { readFileSync } from "node:fs";
import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
+import { join } from "node:path";
+import { HARNESS_KEYS, KNOBS, harnessKey, resolveKnobs } from "./config-schema.mjs";
+import {
+ buildUserAgent,
+ loadCredentialFiles,
+ readManifestVersion,
+ resolveAuthMode,
+ resolveOpenVikingCredentials,
+} from "./credentials.mjs";
import {
announcedOverrides,
loadWorkspaceLayers,
@@ -39,33 +45,27 @@ import {
projectWorkspaceSettings,
} from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId, resolvePluginPeerId } from "./workspace-peer.mjs";
import { readEntry } from "./workspace-registry.mjs";
-const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
-
-export const HARNESS_KEYS = {
- claudeCode: "claude_code",
- codex: "codex",
-};
+const OVCLI_LAYER = "ovcli.conf";
+const OV_CONF_LAYER = "ov.conf";
-function tryLoadJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return null;
- }
-}
+export { HARNESS_KEYS, harnessKey };
/**
* Merge the shared plugin section with the harness-specific override.
* Returns a flat settings object; unknown keys pass through untouched so a
* harness can add its own knobs without touching this module.
+ *
+ * `cliFile` is ovcli.conf already parsed. Callers that have it hand it over so
+ * the file is read once per build and, more importantly, so the `plugin`
+ * section comes out of the same file the credential chain read — an
+ * `OPENVIKING_CONFIG_FILE` that is ovcli-shaped is ovcli.conf, and only
+ * `loadCredentialFiles` knows that.
*/
export function loadPluginSettings(harness, env = process.env, options = {}) {
- const path = resolvePath(
- (env.OPENVIKING_CLI_CONFIG_FILE || DEFAULT_OVCLI_CONF_PATH).replace(/^~/, homedir()),
- );
- const file = tryLoadJson(path);
+ const file = options.cliFile || loadCredentialFiles(env).cliFile;
const plugin = file && typeof file.plugin === "object" && file.plugin ? file.plugin : {};
const shared = {};
@@ -73,9 +73,14 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
if (value && typeof value === "object" && !Array.isArray(value)) continue;
shared[key] = value;
}
- const scoped = harness && plugin[harness] && typeof plugin[harness] === "object"
- ? plugin[harness]
- : {};
+ // Both spellings of the harness name find the same override, so copying
+ // `claude-code` out of the installer is not a silent no-op.
+ const key = harnessKey(harness);
+ const scoped = {};
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ const value = candidate && plugin[candidate];
+ if (value && typeof value === "object" && !Array.isArray(value)) Object.assign(scoped, value);
+ }
const settings = { ...shared, ...scoped };
const cwd = String(options.cwd || "").trim();
@@ -83,6 +88,32 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
return { ...settings, ...resolveWorkspaceSettings(cwd, env, options).settings };
}
+/**
+ * Every knob for one harness, resolved through the whole layer stack.
+ *
+ * `legacy` is that harness's section in ov.conf, which is where tuning used to
+ * live: it stays the lowest configured layer so an existing deployment keeps
+ * working, and everything above it comes from files a client may edit.
+ *
+ * Returns the settings, the names some layer actually supplied (what the
+ * `*Configured` flags report), and the raw ovcli.conf merge — a couple of
+ * callers still need to know a value came from ovcli.conf rather than ov.conf.
+ */
+export function resolveSettings(harness, options = {}) {
+ const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options;
+ const key = harnessKey(harness);
+ const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile });
+ const { settings, configured, sources } = resolveKnobs({
+ harness: key,
+ layers: [
+ { name: OV_CONF_LAYER, data: legacy },
+ { name: OVCLI_LAYER, data: plugin },
+ ],
+ env,
+ });
+ return { settings, configured, sources, plugin };
+}
+
/**
* The workspace layers for one cwd, flattened into harness knobs.
*
@@ -122,6 +153,169 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion
}
}
+const SEND_ONLY_WHEN_CONFIGURED = KNOBS.filter((knob) => knob.sendOnlyWhenConfigured);
+
+function str(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : "";
+}
+
+/** The ov.conf block named after this harness, the lowest layer of every chain. */
+function ovConfSection(ovFile, key) {
+ const section = key ? ovFile?.[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+/**
+ * A connection value ovcli.conf's `plugin` section supplied, as opposed to
+ * ov.conf's harness block or the environment — the credential chain ranks
+ * those two itself, and would rank a `plugin` value wrong.
+ */
+function fromPluginSection(settings, sources, name) {
+ return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
+}
+
+/**
+ * One harness's whole configuration: the files, the knobs, the peer, and the
+ * handful of fields derived from them.
+ *
+ * Every loader used to write this sequence out by hand and each wrote a
+ * slightly different subset, which is how ov.conf's `<harness>.authMode` came
+ * to apply on three harnesses only, and why two of the four knobs the server
+ * defaults for itself were reported as configured on two harnesses and nowhere
+ * else. What is left in a loader after this call is what only that harness
+ * knows.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
+ * host hands it one of its own); `hostInput` is what an embedding host named
+ * for this process, which is the more specific answer and outranks every file;
+ * `logFile` is the log basename this harness has always used, and a harness
+ * that never had a default log path does not get one invented for it;
+ * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * pinning and has always ended at `server.root_api_key`.
+ */
+export function buildPluginConfig(harness, {
+ cwd = "",
+ env = process.env,
+ legacy = null,
+ manifestUrl = "",
+ version = "",
+ hostInput = {},
+ logFile = "",
+ rootKeyFallback = false,
+ deriveEffectivePeer = false,
+} = {}) {
+ const name = String(harness || "");
+ const key = harnessKey(name);
+ const workspaceCwd = str(cwd) || process.cwd();
+ const files = loadCredentialFiles(env);
+ // The version answers two questions: what the User-Agent reports, and whether
+ // a workspace file asking for a newer client gets to say so.
+ const clientVersion = str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "");
+ const { settings, configured, sources } = resolveSettings(key, {
+ env,
+ cwd: workspaceCwd,
+ legacy: legacy || ovConfSection(files.ovFile, key),
+ cliFile: files.cliFile,
+ clientVersion,
+ });
+ const credentials = resolveOpenVikingCredentials(env, key, {
+ apiKey: fromPluginSection(settings, sources, "apiKey"),
+ accountId: fromPluginSection(settings, sources, "accountId"),
+ userId: fromPluginSection(settings, sources, "userId"),
+ });
+
+ // Pinned to ovcli.conf, the credential chain stops at that file. The layers
+ // under it still answer: ov.conf's harness block is where tuning used to
+ // live, and `server.root_api_key` is where a harness that predates the
+ // pinning has always ended its chain.
+ let apiKey = credentials.apiKey;
+ let apiKeySource = credentials.apiKeySource;
+ let credentialPath = credentials.credentialPath;
+ if (!apiKey) {
+ apiKey = sources.apiKey === OV_CONF_LAYER
+ ? str(settings.apiKey)
+ : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+ const hostApiKey = str(hostInput.apiKey);
+ if (hostApiKey) {
+ apiKey = hostApiKey;
+ apiKeySource = "host";
+ credentialPath = "";
+ }
+
+ const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
+ const baseUrl = hostBaseUrl || credentials.baseUrl;
+ const account = str(hostInput.account) || credentials.account;
+ const user = str(hostInput.user) || credentials.user;
+ const timeoutMs = settings.timeoutMs;
+ const peerId = resolvePluginPeerId({
+ settings,
+ configured,
+ sources,
+ credentials,
+ hostInput: hostInput.peerId,
+ env,
+ });
+
+ const config = {
+ ...settings,
+ harness: name,
+ clientVersion,
+ userAgent: buildUserAgent(name, clientVersion),
+
+ baseUrl,
+ mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
+ apiKey,
+ account,
+ user,
+ ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ configPath: credentials.cliPath || credentials.ovPath || null,
+ cliConfigPath: credentials.cliPath,
+ ovConfigPath: credentials.ovPath,
+ cliPath: credentials.cliPath,
+ ovPath: credentials.ovPath,
+
+ peerId,
+ explicitPeerId: peerId,
+
+ // A write gets a longer budget than a read, and a digest has to finish
+ // inside the recall request it belongs to, so both fall back to a knob.
+ captureTimeoutMs: settings.captureTimeoutMs || Math.max(timeoutMs * 2, 30000),
+ recallCompressTimeoutMs: settings.recallCompressTimeoutMs
+ || Math.max(1000, settings.recallTimeoutMs - 10000),
+ debugLogPath: settings.debugLogPath
+ || (logFile ? join(homedir(), ".openviking", "logs", logFile) : ""),
+
+ // The spellings these fields carried before every harness shared a loader.
+ endpoint: baseUrl,
+ accountId: account,
+ userId: user,
+ requestTimeoutMs: timeoutMs,
+ };
+ for (const knob of SEND_ONLY_WHEN_CONFIGURED) {
+ config[`${knob.name}Configured`] = configured.has(knob.name);
+ }
+
+ // Only for the harnesses that resolve the peer once at load. The rest derive
+ // it per session, against the directory the payload names, and an MCP proxy
+ // must not derive one from wherever it happened to be launched.
+ if (deriveEffectivePeer) {
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ config.effectivePeer = effectivePeer;
+ config.legacyPeerId = effectivePeer.legacyPeerId;
+ }
+ return config;
+}
+
const REWRITE_MODES = new Set(["off", "client", "server", "auto"]);
/**
diff --git a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
index 72835de8f..4695a887b 100644
--- a/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/recall-core.mjs
@@ -31,6 +31,28 @@ const CODING_QUOTA_WEIGHTS = {
let userSpaceCache = "";
+/**
+ * Is recall on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoRecall`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables recall under an older name still disables it.
+ */
+export function isRecallEnabled(cfg = {}) {
+ return isSwitchOn([cfg.enabled, cfg.autoRecall, cfg.recall, cfg.syncRecall]);
+}
+
+/** Any recognised spelling that says off wins; everything else means on. */
+function isSwitchOn(values) {
+ for (const value of values) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function estimateTokens(text) {
return text ? Math.ceil(String(text).length / 4) : 0;
}
@@ -338,9 +360,8 @@ async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
}
async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
- if (items.length === 0) return null;
-
- let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const budgetTotal = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ let budgetRemaining = budgetTotal;
const lines = [
"<openviking-context>",
"Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
@@ -373,15 +394,15 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =
lines.push("</openviking-context>");
- const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ const budgetUsed = budgetTotal - budgetRemaining;
log("recall_injection_built", {
contentItems: contentCount,
hintItems: hintCount,
budgetUsed,
- budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ budgetTotal,
});
- return lines.join("\n");
+ return { block: lines.join("\n"), contentCount, hintCount, budgetUsed, stage: "ranked" };
}
const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
@@ -626,8 +647,13 @@ export async function postRecall(fetchJSON, body, opts = {}) {
* `"actor"` that sweep is off by definition, so the old peer is asked for
* separately — as itself, which is both cheaper and wider than a bare
* cross-peer read (that would need the user id, and reaches memories only).
+ *
+ * `stage` names the path the block came from, which is what a host needs to
+ * tell "the server had nothing" (`no_results`) from "the score threshold
+ * dropped everything" (`filtered_out`) when the block is empty, and a
+ * `server_assembled` block from a `ranked` one when it is not.
*/
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+export async function buildRecallBlockDetailed(fetchJSON, cfg, query, options = {}) {
const primary = await recallForPeer(fetchJSON, cfg, query, options);
const legacyPeerId = String(options.legacyPeerId || "").trim();
@@ -636,16 +662,32 @@ export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
const log = options.log || (() => {});
const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
+ if (!legacy.block) return primary;
log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
+ return {
+ block: primary.block ? `${primary.block}\n${legacy.block}` : legacy.block,
+ contentCount: primary.contentCount + legacy.contentCount,
+ hintCount: primary.hintCount + legacy.hintCount,
+ budgetUsed: primary.budgetUsed + legacy.budgetUsed,
+ stage: primary.block ? primary.stage : legacy.stage,
+ };
+}
+
+/** The block alone, or null when nothing was injectable. */
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const { block } = await buildRecallBlockDetailed(fetchJSON, cfg, query, options);
+ return block || null;
+}
+
+function emptyRecall(stage) {
+ return { block: "", contentCount: 0, hintCount: 0, budgetUsed: 0, stage };
}
async function recallForPeer(fetchJSON, cfg, query, options = {}) {
const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
const log = options.log || (() => {});
const trimmed = String(query || "").trim();
- if (!trimmed) return null;
+ if (!trimmed) return emptyRecall("no_results");
// Assembly happens server-side when the deployment offers the context face;
// older servers fall through to /recall, then to raw find.
@@ -654,12 +696,23 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
actorPeerId,
log,
});
- if (serverBlock !== null) return serverBlock || null;
+ if (serverBlock !== null) {
+ if (!serverBlock) return emptyRecall("no_results");
+ // The server rendered one budgeted unit, so nothing here degraded to a
+ // URI-only hint and the block's own estimate is what it cost.
+ return {
+ block: serverBlock,
+ contentCount: 1,
+ hintCount: 0,
+ budgetUsed: estimateTokens(serverBlock),
+ stage: "server_assembled",
+ };
+ }
const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
const perSourceLimit = Math.max(recallLimit * 2, 8);
const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
- if (raw.length === 0) return null;
+ if (raw.length === 0) return emptyRecall("no_results");
const profile = buildQueryProfile(trimmed);
const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
@@ -673,6 +726,6 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
});
- if (picked.length === 0) return null;
+ if (picked.length === 0) return emptyRecall("filtered_out");
return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
}
diff --git a/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs b/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs
deleted file mode 100644
index cf57bf406..000000000
--- a/examples/codex-memory-plugin/scripts/shared/uri-guard.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// 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();
-}
-
-// Arguments that carry file CONTENT rather than a location. The sweep below
-// looks past the known path keys so an unusual one (`paths`, a nested target)
-// is still caught, but text a tool is asked to WRITE is not a path: a local
-// `write` whose body merely mentions viking://user/default/ was denied, and no
-// file was created. Skipped by name at any depth.
-const DEFAULT_CONTENT_KEYS = [
- "content",
- "contents",
- "text",
- "body",
- "old_string",
- "oldString",
- "new_string",
- "newString",
- "old_str",
- "new_str",
- "file_text",
- "insert_line",
- "replacement",
-];
-
-export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_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, new Set(contentKeys));
-}
-
-export function findVikingUriInValue(value, skipKeys) {
- 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, skipKeys);
- if (uri) return uri;
- }
- return null;
- }
- if (value && typeof value === "object") {
- for (const [key, item] of Object.entries(value)) {
- if (skipKeys?.has(key)) continue;
- const uri = findVikingUriInValue(item, skipKeys);
- 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/codex-memory-plugin/scripts/shared/workspace-config.mjs b/examples/codex-memory-plugin/scripts/shared/workspace-config.mjs
index da741d2f2..1e4b4d9e6 100644
--- a/examples/codex-memory-plugin/scripts/shared/workspace-config.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/workspace-config.mjs
@@ -24,6 +24,7 @@
import { readFileSync, realpathSync, statSync } from "node:fs";
import { isAbsolute, join, relative } from "node:path";
+import { WORKSPACE_ENUMS, WORKSPACE_KNOB_MAP, WORKSPACE_RANGES } from "./config-schema.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE } from "./workspace-identity.mjs";
/**
@@ -95,37 +96,14 @@ export const FORBIDDEN_KEYS = [
*/
export const FREE_FORM_SECTIONS = ["labels"];
-const ENUMS = {
- "recall.peer_scope": ["all", "actor"],
- "peer.source": null, // free-form: preset name, template, or template array
-};
-
-const RANGES = {
- "recall.dedup_turns": { min: 0, max: 20, integer: true },
- "recall.max_items": { min: 1, max: 100, integer: true },
- "recall.score_threshold": { min: 0, max: 1, integer: false },
- "capture.commit_token_threshold": { min: 1000, max: 1_000_000, integer: true },
-};
-
/**
- * The workspace schema in the vocabulary the harness loaders already speak.
- *
- * Only knobs a loader actually reads appear here — the same rule the ovcli
- * `plugin` section follows, so the schema never advertises a setting that
- * silently does nothing. `labels` is metadata for humans and is not projected.
+ * The workspace schema is a projection of `config-schema.mjs`: the dotted key,
+ * its enum members and its range all come from the one knob declaration, so a
+ * knob cannot be spelled one way here and another way in the loaders.
*/
-const KNOB_MAP = {
- "peer.id": "peerId",
- "peer.source": "peerSource",
- "recall.enabled": "autoRecall",
- "recall.peer_scope": "recallPeerScope",
- "recall.dedup_turns": "recallDedupTurns",
- "recall.max_items": "recallLimit",
- "recall.score_threshold": "scoreThreshold",
- "capture.enabled": "autoCapture",
- "capture.commit_token_threshold": "commitTokenThreshold",
- "bypass.session_patterns": "bypassSessionPatterns",
-};
+const ENUMS = WORKSPACE_ENUMS;
+const RANGES = WORKSPACE_RANGES;
+const KNOB_MAP = WORKSPACE_KNOB_MAP;
export const WORKSPACE_SCHEMA_KEYS = Object.keys(KNOB_MAP);
diff --git a/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs
index 89df30793..7f136f10b 100644
--- a/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/workspace-peer.mjs
@@ -40,6 +40,69 @@ export const DEFAULT_PEER_SOURCE = "git";
const VARIABLE_RE = /\{([a-z_]+)\}/g;
+/**
+ * Layers `resolvePluginPeerId` must not read off the merged settings, because
+ * each has a rank of its own: the environment ranks above every file, and
+ * ov.conf's harness block ranks below all of them.
+ */
+const PEER_LAYERS_RANKED_SEPARATELY = new Set(["env", "ov.conf"]);
+
+function trimmed(value) {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+/**
+ * The peer some layer named, in the one order every harness follows.
+ *
+ * Both halves of a loader's configuration carry a peer: `resolveSettings()`
+ * reads the workspace file, the machine registry and ovcli.conf's `plugin`
+ * section, while the credential chain ends in ovcli.conf's `actor_peer_id`. The
+ * more specific layer wins, so a `peerId` written for this harness outranks the
+ * account-wide actor peer — codex resolved it that way and opencode and pi
+ * resolved it the other way round, which meant one ovcli.conf produced two
+ * different peers depending on which host read it.
+ *
+ * ov.conf's harness block, where this tuning used to live, stays at the bottom.
+ * It gets its own rank rather than riding the credential chain, which drops it
+ * entirely once the credentials are pinned to ovcli.conf.
+ *
+ * `OPENVIKING_PEER_ID` still outranks every file, except when the credentials
+ * are pinned to ovcli.conf, where the environment is meant not to apply at all.
+ * A host that names a peer itself (dsh's cordis patch) outranks all of them.
+ *
+ * Returns "" when nobody named one, which is what makes
+ * `resolveEffectivePeerId()` derive one from `peer.source`.
+ */
+export function resolvePluginPeerId({
+ settings = {},
+ configured = null,
+ sources = {},
+ credentials = {},
+ hostInput = "",
+ env = process.env,
+ credentialSource = credentials?.credentialSource || "",
+} = {}) {
+ const host = trimmed(hostInput);
+ if (host) return host;
+
+ if (credentialSource !== "ovcli") {
+ const fromEnv = trimmed(env?.OPENVIKING_PEER_ID);
+ if (fromEnv) return fromEnv;
+ }
+
+ if (configured?.has?.("peerId") && !PEER_LAYERS_RANKED_SEPARATELY.has(sources?.peerId)) {
+ const named = trimmed(settings?.peerId);
+ if (named) return named;
+ }
+
+ const fromCredentials = trimmed(credentials?.peerId);
+ if (fromCredentials) return fromCredentials;
+
+ if (sources?.peerId === "ov.conf") return trimmed(settings?.peerId);
+
+ return "";
+}
+
export function deriveWorkspacePeerId(cwd) {
return legacySanitize(cwd);
}
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
index f340036c6..162dbf1d7 100644
--- a/examples/codex-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/codex-memory-plugin/servers/mcp-proxy.mjs
@@ -12,15 +12,13 @@ import { resolve as resolvePath } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../scripts/config.mjs";
import { createLogger } from "../scripts/debug-log.mjs";
-import { resolveOpenVikingCredentials } from "../scripts/ov-credentials.mjs";
+import { resolveOpenVikingCredentials } from "../scripts/shared/credentials.mjs";
import {
buildMcpProxyConfig,
resolveMcpActorPeerId,
} from "../scripts/shared/mcp-proxy-config.mjs";
import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
-export { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
-
function readProxyConfig() {
const creds = resolveOpenVikingCredentials();
const cfg = loadConfig();
@@ -30,6 +28,7 @@ function readProxyConfig() {
apiKey: creds.apiKey,
account: creds.account,
user: creds.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
peerId: resolveMcpActorPeerId(cfg),
userAgent: cfg.userAgent,
timeoutMs: cfg.timeoutMs,
diff --git a/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs b/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs
deleted file mode 100644
index fa96275f0..000000000
--- a/examples/codex-memory-plugin/servers/mcp-proxy.test.mjs
+++ /dev/null
@@ -1,416 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { createServer } from "node:http";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { Writable } from "node:stream";
-import test from "node:test";
-import { createOpenVikingMcpProxy } from "./mcp-proxy.mjs";
-
-function jsonRpc(id, result = {}) {
- return { jsonrpc: "2.0", id, result };
-}
-
-function sseMessage(obj) {
- return `event: message\r\ndata: ${JSON.stringify(obj)}\r\n\r\n`;
-}
-
-async function readBody(req) {
- const chunks = [];
- for await (const chunk of req) chunks.push(chunk);
- return Buffer.concat(chunks).toString("utf-8");
-}
-
-async function withServer(handler, fn) {
- const requests = [];
- const server = createServer(async (req, res) => {
- const body = await readBody(req);
- let parsed = null;
- try {
- parsed = body ? JSON.parse(body) : null;
- } catch { /* test handler may inspect raw body */ }
- const entry = { method: req.method, url: req.url, headers: req.headers, body: parsed, rawBody: body };
- requests.push(entry);
- await handler(req, res, entry, requests);
- });
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
- try {
- const { port } = server.address();
- return await fn({ url: `http://127.0.0.1:${port}/mcp`, requests });
- } finally {
- await new Promise((resolve) => server.close(resolve));
- }
-}
-
-function makeProxy({ url, configOverrides = {}, stdout, localToolProvider, readConfig } = {}) {
- const out = [];
- const writable = stdout || new Writable({
- write(chunk, _encoding, callback) {
- out.push(chunk.toString("utf-8"));
- callback();
- },
- });
- const proxy = createOpenVikingMcpProxy({
- stdout: writable,
- readConfig: readConfig || (() => ({
- mcpUrl: url,
- apiKey: "test-key",
- account: "default",
- user: "zeus",
- peerId: "peer-a",
- userAgent: "openviking-memory-codex/9.9.9",
- timeoutMs: 5000,
- debug: false,
- debugLogPath: "",
- credentialSource: "test",
- credentialPath: "",
- watchedPaths: [],
- ...configOverrides,
- })),
- loggerFactory: () => ({ log() {}, logError() {} }),
- localToolProvider,
- });
- return {
- proxy,
- out,
- async messages() {
- await new Promise((resolve) => setImmediate(resolve));
- return out.join("").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
- },
- };
-}
-
-test("captures initialize session id and forwards SSE JSON-RPC response", async () => {
- await withServer((_req, res, entry) => {
- assert.equal(entry.method, "POST");
- assert.equal(entry.headers.authorization, "Bearer test-key");
- assert.equal(entry.headers["x-openviking-account"], "default");
- assert.equal(entry.headers["x-openviking-user"], "zeus");
- assert.equal(entry.headers["x-openviking-actor-peer"], "peer-a");
- assert.equal(entry.headers["user-agent"], "openviking-memory-codex/9.9.9");
- assert.equal(entry.headers["mcp-protocol-version"], "2025-06-18");
- assert.equal(entry.headers["mcp-session-id"], undefined);
- res.writeHead(200, {
- "content-type": "text/event-stream",
- "mcp-session-id": "sid-1",
- });
- res.end(`: keepalive\r\n${sseMessage(jsonRpc(1, { protocolVersion: "2025-06-18" }))}`);
- }, async ({ url, requests }) => {
- const { proxy, messages } = makeProxy({ url });
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: { protocolVersion: "2025-06-18" },
- });
- assert.deepEqual(await messages(), [jsonRpc(1, { protocolVersion: "2025-06-18" })]);
- assert.equal(requests.length, 1);
- });
-});
-
-test("never forwards the client's un-negotiated protocol version header", async () => {
- await withServer((_req, res, entry) => {
- // Strict upstreams 400 on unsupported MCP-Protocol-Version before
- // negotiation runs, so the header must stay on a proxy-known version
- // even when the client asks for a newer spec (Trae sends 2025-11-25).
- assert.equal(entry.headers["mcp-protocol-version"], "2025-06-18");
- res.writeHead(200, {
- "content-type": "application/json",
- "mcp-session-id": "sid-np",
- });
- if (entry.body.method === "initialize") {
- res.end(JSON.stringify(jsonRpc(entry.body.id, { protocolVersion: "2025-06-18" })));
- return;
- }
- res.end(JSON.stringify(jsonRpc(entry.body.id, { tools: [] })));
- }, async ({ url, requests }) => {
- const { proxy } = makeProxy({ url });
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: { protocolVersion: "2025-11-25" },
- });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
- assert.equal(requests.length, 2);
- // The initialize body still carries the client's ask end-to-end; only the
- // transport header is pinned until the server negotiates.
- assert.equal(requests[0].body.params.protocolVersion, "2025-11-25");
- });
-});
-
-test("adopts the server-negotiated protocol version for subsequent requests", async () => {
- await withServer((_req, res, entry) => {
- if (entry.body.method === "initialize") {
- res.writeHead(200, {
- "content-type": "application/json",
- "mcp-session-id": "sid-nv",
- });
- res.end(JSON.stringify(jsonRpc(entry.body.id, { protocolVersion: "2025-03-26" })));
- return;
- }
- assert.equal(entry.headers["mcp-protocol-version"], "2025-03-26");
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify(jsonRpc(entry.body.id, { tools: [] })));
- }, async ({ url, requests }) => {
- const { proxy } = makeProxy({ url });
- // Client asks 2025-06-18 but the server negotiates down: follow-up
- // requests must carry the response's version, not the request's.
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: { protocolVersion: "2025-06-18" },
- });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
- assert.equal(requests.length, 2);
- });
-});
-
-test("forwards notifications and writes no stdout for HTTP 202", async () => {
- await withServer((_req, res, entry) => {
- assert.equal(entry.body.method, "notifications/initialized");
- res.writeHead(202, { "content-type": "application/json" });
- res.end("");
- }, async ({ url }) => {
- const { proxy, messages } = makeProxy({ url });
- await proxy.handleMessage({ jsonrpc: "2.0", method: "notifications/initialized" });
- assert.deepEqual(await messages(), []);
- });
-});
-
-test("uses independent POST requests for concurrent calls", async () => {
- await withServer(async (_req, res, entry) => {
- const delay = entry.body.id === 1 ? 50 : 5;
- await new Promise((resolve) => setTimeout(resolve, delay));
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify(jsonRpc(entry.body.id, { name: entry.body.method })));
- }, async ({ url, requests }) => {
- const { proxy, messages } = makeProxy({ url });
- await Promise.all([
- proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
- proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/call" }),
- ]);
- const ids = (await messages()).map((m) => m.id).sort();
- assert.deepEqual(ids, [1, 2]);
- assert.equal(requests.length, 2);
- });
-});
-
-test("appends local tools to the upstream tools/list result", async () => {
- const localTools = [
- { name: "local_probe", description: "Probe locally", inputSchema: { type: "object" } },
- { name: "local_echo", description: "Echo locally", inputSchema: { type: "object" } },
- ];
- await withServer((_req, res, entry) => {
- assert.equal(entry.body.method, "tools/list");
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify(jsonRpc(entry.body.id, {
- tools: [{ name: "find", description: "Find context", inputSchema: { type: "object" } }],
- })));
- }, async ({ url, requests }) => {
- const { proxy, messages } = makeProxy({
- url,
- localToolProvider: {
- listTools: () => localTools,
- async callTool() { return null; },
- },
- });
-
- await proxy.handleMessage({ jsonrpc: "2.0", id: 20, method: "tools/list" });
-
- const [response] = await messages();
- assert.deepEqual(response.result.tools.map((tool) => tool.name), [
- "find",
- "local_probe",
- "local_echo",
- ]);
- assert.equal(requests.length, 1);
- });
-});
-
-test("replaces an upstream tool definition when the local tool has the same name", async () => {
- const localTool = {
- name: "local_probe",
- description: "Local probe",
- inputSchema: { type: "object", required: ["query"] },
- };
- await withServer((_req, res, entry) => {
- assert.equal(entry.body.method, "tools/list");
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify(jsonRpc(entry.body.id, {
- tools: [
- { name: "find", description: "Find context", inputSchema: { type: "object" } },
- {
- name: "local_probe",
- description: "Upstream probe",
- inputSchema: { type: "object", required: ["text"] },
- },
- ],
- })));
- }, async ({ url }) => {
- const { proxy, messages } = makeProxy({
- url,
- localToolProvider: {
- listTools: () => [localTool],
- async callTool() { return null; },
- },
- });
-
- await proxy.handleMessage({ jsonrpc: "2.0", id: 22, method: "tools/list" });
-
- const [response] = await messages();
- assert.deepEqual(response.result.tools, [
- { name: "find", description: "Find context", inputSchema: { type: "object" } },
- localTool,
- ]);
- });
-});
-
-test("handles local tools without forwarding tools/call upstream", async () => {
- const calls = [];
- const { proxy, messages } = makeProxy({
- url: "http://127.0.0.1:1/mcp",
- localToolProvider: {
- listTools: () => [{ name: "local_probe" }],
- async callTool(params, context) {
- calls.push({ params, context });
- return { content: [{ type: "text", text: '{"results":[]}' }] };
- },
- },
- });
-
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 21,
- method: "tools/call",
- params: { name: "local_probe", arguments: { query: "test" } },
- });
-
- assert.equal(calls.length, 1);
- assert.deepEqual(calls[0].params, {
- name: "local_probe",
- arguments: { query: "test" },
- });
- assert.equal(calls[0].context.config.user, "zeus");
- assert.deepEqual(await messages(), [
- jsonRpc(21, { content: [{ type: "text", text: '{"results":[]}' }] }),
- ]);
-});
-
-test("reloads changed credential files before calling a local tool", async (t) => {
- const dir = mkdtempSync(join(tmpdir(), "openviking-mcp-proxy-"));
- const credentialPath = join(dir, "ovcli.conf");
- writeFileSync(credentialPath, "old-key", "utf-8");
- t.after(() => rmSync(dir, { recursive: true, force: true }));
-
- let apiKey = "old-key";
- const receivedKeys = [];
- const readConfig = () => ({
- mcpUrl: "http://127.0.0.1:1/mcp",
- apiKey,
- account: "default",
- user: "zeus",
- peerId: "peer-a",
- timeoutMs: 5000,
- debug: false,
- debugLogPath: "",
- credentialSource: "ovcli",
- credentialPath,
- watchedPaths: [credentialPath],
- });
- const { proxy, messages } = makeProxy({
- readConfig,
- localToolProvider: {
- listTools: () => [{ name: "local_probe" }],
- async callTool(_params, context) {
- receivedKeys.push(context.config.apiKey);
- return { content: [{ type: "text", text: '{"results":[]}' }] };
- },
- },
- });
-
- apiKey = "new-key";
- writeFileSync(credentialPath, "new-key-with-different-size", "utf-8");
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 22,
- method: "tools/call",
- params: { name: "local_probe", arguments: { query: "test" } },
- });
-
- assert.deepEqual(receivedKeys, ["new-key"]);
- assert.equal((await messages())[0].id, 22);
-});
-
-test("reinitializes after 404 and retries the original request once", async () => {
- let call = 0;
- await withServer((_req, res, entry) => {
- call += 1;
- if (call === 1) {
- res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-old" });
- res.end(JSON.stringify(jsonRpc(1, {})));
- return;
- }
- if (call === 2) {
- assert.equal(entry.headers["mcp-session-id"], "sid-old");
- res.writeHead(404, { "content-type": "application/json" });
- res.end(JSON.stringify({ jsonrpc: "2.0", id: entry.body.id, error: { code: -32000, message: "session missing" } }));
- return;
- }
- if (call === 3) {
- assert.equal(entry.body.method, "initialize");
- assert.match(String(entry.body.id), /^openviking-proxy-reinit-/);
- assert.equal(entry.headers["mcp-session-id"], undefined);
- res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-new" });
- res.end(JSON.stringify(jsonRpc(entry.body.id, {})));
- return;
- }
- assert.equal(entry.headers["mcp-session-id"], "sid-new");
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify(jsonRpc(2, { ok: true })));
- }, async ({ url, requests }) => {
- const { proxy, messages } = makeProxy({ url });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
- const responses = await messages();
- assert.equal(responses.at(-1).id, 2);
- assert.deepEqual(responses.at(-1).result, { ok: true });
- assert.equal(requests.length, 4);
- });
-});
-
-test("maps 401/403 to actionable JSON-RPC auth errors", async () => {
- await withServer((_req, res) => {
- res.writeHead(401, { "content-type": "application/json" });
- res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32001, message: "bad token" } }));
- }, async ({ url }) => {
- const { proxy, messages } = makeProxy({ url });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 7, method: "tools/list" });
- const [msg] = await messages();
- assert.equal(msg.id, 7);
- assert.equal(msg.error.code, -32001);
- assert.match(msg.error.message, /authentication failed/i);
- assert.equal(msg.error.data.status, 401);
- assert.equal(msg.error.data.serverMessage, "bad token");
- });
-});
-
-test("DELETEs the upstream MCP session on close", async () => {
- await withServer((_req, res, entry) => {
- if (entry.method === "POST") {
- res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-close" });
- res.end(JSON.stringify(jsonRpc(1, {})));
- return;
- }
- assert.equal(entry.method, "DELETE");
- assert.equal(entry.headers["mcp-session-id"], "sid-close");
- res.writeHead(204);
- res.end("");
- }, async ({ url, requests }) => {
- const { proxy } = makeProxy({ url });
- await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
- await proxy.closeSession();
- assert.equal(requests.at(-1).method, "DELETE");
- });
-});
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
index a6ebb537a..c2276e994 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/SKILL.md
@@ -31,8 +31,10 @@ wrong on a user's machine, each silently:
When the resolved url is loopback, the server runs on this machine and the
doctor adds a **Server health** section: whether anything listens on the
-port, plugin-only keys in `ov.conf` (`claude_code`, `codex`, `server.url`)
-that make the server refuse to start, and `GET /ready` — the server's own
+port, plugin-only keys in `ov.conf` (a top-level block named after any
+harness: `claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`,
+`opencode`, `dsh`, `pi`, plus `server.url`) that make the server refuse to
+start, and `GET /ready` — the server's own
per-subsystem verdict (agfs, vectordb, api keys, embedding, ollama). For a
remote server only `/ready` is probed. Everything else on the server side —
config validation, live embedding probe, native engine, disk — is
@@ -98,7 +100,7 @@ Work top-down; fix the first ✗ and rerun before chasing the next.
| `proxy variables set` + curl works but hooks fail | Node's fetch ignores `HTTP(S)_PROXY`; no CA handling | `NODE_USE_ENV_PROXY=1` or `NODE_EXTRA_CA_CERTS=<ca.pem>` in the environment that launches Codex. |
| `no session has ever captured a turn` / idle sessions piling up | Stop hook runs but writes fail, or commits fail | Fix the Connection findings; state files are kept and replay when the server is back. |
| `MCP proxy last started against <other url>` | The proxy is a long-lived process; a changed url only takes effect after restart | Restart Codex. |
-| `ov.conf has a top-level 'claude_code' block` / `'codex' block` / `server.url is rejected` | Plugin-only keys in the server's own config; the server refuses to start at its next restart (`Unknown config field` / `Extra inputs are not permitted`) | Move them to ovcli.conf (`plugin.<harness>`, `url`) and delete them from ov.conf. Ignore only if this ov.conf never starts a server. |
+| `ov.conf has a top-level '<harness>' block` / `server.url is rejected` | Plugin-only keys in the server's own config — a top-level block named after any harness (`claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`, `opencode`, `dsh`, `pi`) plus `server.url`; the server refuses to start at its next restart (`Unknown config field` / `Extra inputs are not permitted`) | Move them to ovcli.conf (`plugin.<harness>`, `url`) and delete them from ov.conf. Ignore only if this ov.conf never starts a server. |
| `nothing listens on port … — the server is not running` | Server down or never started; a stale `.openviking.pid` means it died | Start it (`openviking-server`; first time `openviking-server init`) in a terminal and read the startup output. Ask before restarting a server the user runs. |
| `/ready: embedding → error …` | The running server cannot call its embedding provider: recall searches nothing, commits extract nothing | Fix `embedding.*` (api_key/api_base/model) in ov.conf and restart; `openviking-server doctor` prints the provider's reply. |
| `/ready: vectordb → …` / `/ready: agfs → …` | Storage broken: disk full, two servers on one workspace, corrupted index | Server log; stop the duplicate; free disk. |
diff --git a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
index d972be84d..fd8c646a1 100644
--- a/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
+++ b/examples/codex-memory-plugin/skills/ov-memory-doctor/reference.md
@@ -33,8 +33,8 @@ doctor prints the effective mode as `credential source`.
| Field | Order (auto mode) |
|---|---|
| url | `OPENVIKING_URL` → `OPENVIKING_BASE_URL` → `ovcli.conf url` → `ov.conf server.url` → `http://{server.host\|127.0.0.1}:{server.port\|1933}` |
-| api_key | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` → `ovcli.conf api_key` → `ov.conf codex.apiKey` → `ov.conf server.root_api_key` |
-| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/account_id`, `user/user_id` → `ov.conf codex.accountId/userId` |
+| api_key | `OPENVIKING_BEARER_TOKEN` → `OPENVIKING_API_KEY` → `ovcli.conf api_key` → `ovcli.conf plugin.codex.apiKey` → `ovcli.conf plugin.apiKey` → `ov.conf codex.apiKey` → `ov.conf server.root_api_key` |
+| account / user | `OPENVIKING_ACCOUNT` / `OPENVIKING_USER` → `ovcli.conf account/account_id`, `user/user_id` → `ovcli.conf plugin.codex.accountId/userId` → `ovcli.conf plugin.accountId/userId` → `ov.conf codex.accountId/userId` |
| peer | `OPENVIKING_PEER_ID` → registry → `config.local.json` → `config.json` (`peer.id`) → `ovcli.conf plugin.codex.peerId` → `ovcli.conf plugin.peerId` → `ovcli.conf actor_peer_id/peer_id` → `ov.conf codex.peerId` → derived per `peer.source` unless `OPENVIKING_WORKSPACE_PEER=0` |
| peer.source | `OPENVIKING_PEER_SOURCE` → registry → `config.local.json` → `config.json` → `ovcli.conf plugin.codex.peerSource` → `ovcli.conf plugin.peerSource` → `ov.conf codex.peerSource` → `git` |
| auth mode | `OPENVIKING_AUTH_MODE` → `codex.authMode` → `server.auth_mode` → `trusted` when account/user are set, else `api_key` |
@@ -56,8 +56,9 @@ PreCompact 60s. `recallTimeoutMs` (default 120000) must stay below
Sent headers: `Authorization: Bearer <key>`, `X-OpenViking-Account/User` (trusted
mode only), `X-OpenViking-Actor-Peer`, `User-Agent: openviking-memory-codex/<version>`.
-The open-source server also accepts `X-API-Key` (and prefers it when both are
-sent); the Volcengine-hosted OpenViking Service (`https://api.vikingdb.cn-beijing.volces.com/openviking`) accepts Bearer only.
+The plugin never sends `X-API-Key`. The open-source server still accepts it (and
+prefers it when both are sent), so a gateway that injects one shadows the key
+here; the Volcengine-hosted OpenViking Service (`https://api.vikingdb.cn-beijing.volces.com/openviking`) accepts Bearer only.
The doctor checks explicit `features.hooks` first, then the live `hooks` entry
from `codex features list`. Legacy `plugin_hooks` only decides the result when
@@ -160,7 +161,7 @@ Startup failures (printed by the server; exit 1 unless noted):
| Text | Cause |
|---|---|
| `OpenViking configuration file not found.` | No ov.conf at any resolved path |
-| `Unknown config field '…' in OpenVikingConfig` / `Extra inputs are not permitted` | Unknown key — including `claude_code`, `codex` and `server.url`, which only the plugins read |
+| `Unknown config field '…' in OpenVikingConfig` / `Extra inputs are not permitted` | Unknown key — including a top-level block named after any harness (`claude_code`, `codex`, `cursor`, `trae`, `trae_cn`, `zcode`, `opencode`, `dsh`, `pi`) and `server.url`, which only the plugins read |
| `SECURITY: server.auth_mode='dev' requires server.host to be localhost` | Dev mode (no `auth_mode`, no `root_api_key`) on a non-loopback bind |
| `Invalid server.root_api_key: empty string is not allowed` | `""` instead of `null` |
| `Another OpenViking process (PID n) is already using the data directory` | Two servers on one workspace (exit 3, `Application startup failed. Exiting.`) |
diff --git a/examples/cursor-memory-plugin/.cursor-plugin/plugin.json b/examples/cursor-memory-plugin/.cursor-plugin/plugin.json
deleted file mode 100644
index 70080c4da..000000000
--- a/examples/cursor-memory-plugin/.cursor-plugin/plugin.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "name": "openviking-memory",
- "displayName": "OpenViking Memory",
- "version": "0.1.3",
- "description": "Automatic long-term memory recall and conversation capture for Cursor",
- "author": {
- "name": "OpenViking"
- },
- "publisher": "OpenViking",
- "homepage": "https://openviking.ai",
- "repository": "https://github.com/volcengine/OpenViking",
- "license": "Apache-2.0",
- "keywords": ["memory", "context", "mcp", "hooks", "openviking"],
- "category": "developer-tools",
- "tags": ["memory", "productivity", "context"],
- "rules": "./rules/",
- "skills": "./skills/",
- "hooks": "./hooks/hooks.json",
- "mcpServers": "./.mcp.json"
-}
diff --git a/examples/cursor-memory-plugin/.mcp.json b/examples/cursor-memory-plugin/.mcp.json
deleted file mode 100644
index 8f2e6f605..000000000
--- a/examples/cursor-memory-plugin/.mcp.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "mcpServers": {
- "openviking": {
- "command": "node",
- "args": ["${CURSOR_PLUGIN_ROOT}/servers/mcp-proxy.mjs"]
- }
- }
-}
diff --git a/examples/cursor-memory-plugin/README.md b/examples/cursor-memory-plugin/README.md
deleted file mode 100644
index fb5bb2c95..000000000
--- a/examples/cursor-memory-plugin/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# OpenViking Memory Integration for Cursor
-
-One command installs lifecycle hooks, an always-on rule, a memory skill, and the OpenViking MCP server. No marketplace listing or separate MCP setup is required. See the [Cursor integration guide](../../docs/en/agent-integrations/12-cursor.md) for installation and verification.
-
-The hooks inject baseline context on session start and prompt-specific memory before each request, capture transcript deltas on stop, and commit before compaction or session end. They also prevent `viking://` virtual paths from being passed to local file or shell tools.
diff --git a/examples/cursor-memory-plugin/hooks/hooks.json b/examples/cursor-memory-plugin/hooks/hooks.json
deleted file mode 100644
index c0679236e..000000000
--- a/examples/cursor-memory-plugin/hooks/hooks.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "version": 1,
- "hooks": {
- "sessionStart": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/session-start.mjs",
- "timeout": 30
- }
- ],
- "beforeSubmitPrompt": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/auto-recall.mjs",
- "timeout": 20
- }
- ],
- "beforeReadFile": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/uri-guard.mjs",
- "timeout": 5
- }
- ],
- "beforeShellExecution": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/uri-guard.mjs",
- "timeout": 5
- }
- ],
- "stop": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/auto-capture.mjs",
- "timeout": 30
- }
- ],
- "preCompact": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/pre-compact.mjs",
- "timeout": 30
- }
- ],
- "sessionEnd": [
- {
- "command": "node ${CURSOR_PLUGIN_ROOT}/scripts/session-end.mjs",
- "timeout": 30
- }
- ]
- }
-}
diff --git a/examples/cursor-memory-plugin/openviking.integration.json b/examples/cursor-memory-plugin/openviking.integration.json
deleted file mode 100644
index b98703465..000000000
--- a/examples/cursor-memory-plugin/openviking.integration.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "schemaVersion": 1,
- "id": "openviking-memory",
- "version": "0.1.3",
- "clients": ["cursor"],
- "capabilities": ["hooks", "mcp", "rules", "skills"]
-}
diff --git a/examples/cursor-memory-plugin/scripts/auto-capture.mjs b/examples/cursor-memory-plugin/scripts/auto-capture.mjs
deleted file mode 100644
index cbf712037..000000000
--- a/examples/cursor-memory-plugin/scripts/auto-capture.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "stop";
-await import("./cursor-hook.mjs");
diff --git a/examples/cursor-memory-plugin/scripts/auto-recall.mjs b/examples/cursor-memory-plugin/scripts/auto-recall.mjs
deleted file mode 100644
index 89a58b24c..000000000
--- a/examples/cursor-memory-plugin/scripts/auto-recall.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "beforeSubmitPrompt";
-await import("./cursor-hook.mjs");
diff --git a/examples/cursor-memory-plugin/scripts/cursor-hook.mjs b/examples/cursor-memory-plugin/scripts/cursor-hook.mjs
deleted file mode 100644
index 4ad4d7d66..000000000
--- a/examples/cursor-memory-plugin/scripts/cursor-hook.mjs
+++ /dev/null
@@ -1,147 +0,0 @@
-#!/usr/bin/env node
-
-import { readFile } from "node:fs/promises";
-import { parseCursorTranscript } from "./cursor-transcript.mjs";
-
-import {
- addAgentMessages,
- buildAgentProfile,
- commitAgentSession,
- createAgentLogger,
- deriveAgentSessionId,
- loadAgentHookConfig,
- makeAgentFetchJSON,
- readHookInput,
- readHookState,
- recallForPrompt,
- replayAgentPending,
- resolveAgentCwd,
- resolveNativeSessionId,
- shouldBypassAgent,
- stableHash,
- withAgentHookLock,
- writeHookState,
-} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-
-const CLIENT_ID = "cursor";
-const PREFIX = "cu-";
-const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
-const cfg = loadAgentHookConfig(CLIENT_ID);
-const { log, logError } = createAgentLogger(CLIENT_ID, eventName, cfg);
-
-function output(value = {}) {
- process.stdout.write(`${JSON.stringify(value)}\n`);
-}
-
-async function captureTranscript(input, state, sessionId) {
- if (!cfg.autoCapture) return { state, captured: 0 };
- const transcriptPath = input.transcript_path || input.transcriptPath;
- if (!transcriptPath) return { state, captured: 0 };
- let turns = [];
- try { turns = parseCursorTranscript(await readFile(transcriptPath, "utf8")); } catch { return { state, captured: 0 }; }
- const capturedHashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
- const toSend = [];
- for (const [index, turn] of turns.entries()) {
- // Cursor transcripts do not expose a stable message id. Include the
- // transcript position so two legitimate identical turns are retained,
- // while duplicate Hook executions over the same transcript still dedupe.
- const hash = stableHash(index, turn.role, turn.content);
- if (capturedHashes.has(hash)) continue;
- toSend.push({ hash, turn });
- }
- const result = await addAgentMessages(fetchJSON, sessionId, toSend.map((item) => item.turn));
- const captured = result.sent + result.queued;
- for (const item of toSend.slice(0, captured)) capturedHashes.add(item.hash);
- return {
- captured,
- state: {
- ...state,
- capturedHashes: [...capturedHashes].slice(-1000),
- capturedSinceCommit: Number(state.capturedSinceCommit || 0) + captured,
- },
- };
-}
-
-const input = await readHookInput();
-const nativeSessionId = resolveNativeSessionId(input);
-const sessionId = deriveAgentSessionId(PREFIX, input);
-const cwd = resolveAgentCwd(input);
-const { fetchJSON } = makeAgentFetchJSON(cfg, cwd);
-
-async function main() {
- if (!cfg.enabled || shouldBypassAgent(cfg, input)) {
- output(eventName === "beforeSubmitPrompt" ? { continue: true } : {});
- return;
- }
-
- let state = await readHookState(CLIENT_ID, nativeSessionId);
- if (eventName === "sessionStart") {
- const response = await withAgentHookLock(CLIENT_ID, nativeSessionId, async () => {
- state = await readHookState(CLIENT_ID, nativeSessionId);
- const now = Date.now();
- if (now - Number(state.lastSessionStartAt || 0) < 2000) return {};
- state = { ...state, lastSessionStartAt: now };
- await writeHookState(CLIENT_ID, nativeSessionId, state);
- await replayAgentPending(fetchJSON, log).catch((error) => logError("pending", error));
- const profile = await buildAgentProfile(fetchJSON, cfg, cwd).catch((error) => {
- logError("profile", error);
- return null;
- });
- return profile ? { additional_context: `<openviking-context source="session-start">\n${profile}\n</openviking-context>` } : {};
- });
- output(response || {});
- return;
- }
-
- if (eventName === "beforeSubmitPrompt") {
- const response = await withAgentHookLock(CLIENT_ID, nativeSessionId, async () => {
- state = await readHookState(CLIENT_ID, nativeSessionId);
- const prompt = typeof input.prompt === "string" ? input.prompt.trim() : "";
- const promptHash = stableHash(prompt);
- if (!prompt) return { continue: true };
- 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 { continue: true };
- if (state.promptHash !== promptHash || !state.recallBlock) {
- const recallBlock = await recallForPrompt(fetchJSON, cfg, prompt, cwd, log, { sessionId }).catch((error) => {
- logError("recall", error);
- return null;
- });
- state = { ...state, promptHash, recallBlock };
- }
- state = { ...state, promptEventId, promptAt: now };
- await writeHookState(CLIENT_ID, nativeSessionId, state);
- return state.recallBlock
- ? { continue: true, additional_context: state.recallBlock }
- : { continue: true };
- });
- output(response || { continue: true });
- return;
- }
-
- if (["stop", "preCompact", "sessionEnd"].includes(eventName)) {
- await withAgentHookLock(CLIENT_ID, nativeSessionId, async () => {
- state = await readHookState(CLIENT_ID, nativeSessionId);
- const captured = await captureTranscript(input, state, sessionId);
- state = captured.state;
- const shouldCommit = eventName !== "stop" || state.capturedSinceCommit >= cfg.commitTurnThreshold;
- if (shouldCommit) {
- const result = await commitAgentSession(fetchJSON, sessionId, log);
- if (result.ok) state.capturedSinceCommit = 0;
- }
- await writeHookState(CLIENT_ID, nativeSessionId, state);
- });
- output({});
- return;
- }
-
- output({});
-}
-
-main().catch((error) => {
- logError("uncaught", error);
- output(eventName === "beforeSubmitPrompt" ? { continue: true } : {});
-});
diff --git a/examples/cursor-memory-plugin/scripts/pre-compact.mjs b/examples/cursor-memory-plugin/scripts/pre-compact.mjs
deleted file mode 100644
index f307cb847..000000000
--- a/examples/cursor-memory-plugin/scripts/pre-compact.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "preCompact";
-await import("./cursor-hook.mjs");
diff --git a/examples/cursor-memory-plugin/scripts/session-end.mjs b/examples/cursor-memory-plugin/scripts/session-end.mjs
deleted file mode 100644
index 3d5e88112..000000000
--- a/examples/cursor-memory-plugin/scripts/session-end.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "sessionEnd";
-await import("./cursor-hook.mjs");
diff --git a/examples/cursor-memory-plugin/scripts/session-start.mjs b/examples/cursor-memory-plugin/scripts/session-start.mjs
deleted file mode 100644
index e8216517f..000000000
--- a/examples/cursor-memory-plugin/scripts/session-start.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "sessionStart";
-await import("./cursor-hook.mjs");
diff --git a/examples/cursor-memory-plugin/scripts/uri-guard.mjs b/examples/cursor-memory-plugin/scripts/uri-guard.mjs
deleted file mode 100644
index 5cb8758c9..000000000
--- a/examples/cursor-memory-plugin/scripts/uri-guard.mjs
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/env node
-
-import { readFileSync, realpathSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import {
- evaluateAgentUriGuard,
-} from "../../memory-plugin-shared/lib/agent-uri-guard.mjs";
-
-function readInput() {
- try {
- const raw = readFileSync(0, "utf8").trim();
- return raw ? JSON.parse(raw) : {};
- } catch {
- return {};
- }
-}
-
-export function evaluateCursorUriGuard(input = {}) {
- const isShell = typeof input.command === "string";
- const toolName = isShell ? "bash" : "read";
- const decision = evaluateAgentUriGuard(toolName, input);
- if (!decision) return {};
- const output = {
- permission: "deny",
- user_message: decision.reason,
- };
- if (isShell) output.agent_message = decision.reason;
- return output;
-}
-
-const isEntrypoint = process.argv[1]
- && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
-if (isEntrypoint) {
- const output = evaluateCursorUriGuard(readInput());
- if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);
-}
diff --git a/examples/cursor-memory-plugin/servers/mcp-proxy.mjs b/examples/cursor-memory-plugin/servers/mcp-proxy.mjs
deleted file mode 100644
index f8a43ae77..000000000
--- a/examples/cursor-memory-plugin/servers/mcp-proxy.mjs
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env node
-
-import { fileURLToPath } from "node:url";
-import { resolve as resolvePath } from "node:path";
-
-import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { createLogger } from "../../memory-plugin-shared/lib/debug-log.mjs";
-import { createOpenVikingMcpProxy } from "../../memory-plugin-shared/lib/mcp-proxy-core.mjs";
-
-function readConfig() {
- const cfg = loadAgentHookConfig("cursor");
- 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();
-}
diff --git a/examples/dsh-memory-plugin/client.mjs b/examples/dsh-memory-plugin/client.mjs
index 78b5dc3c7..329972da0 100644
--- a/examples/dsh-memory-plugin/client.mjs
+++ b/examples/dsh-memory-plugin/client.mjs
@@ -1,67 +1,13 @@
+import { createOvHttp } from "./shared/ov-http.mjs";
+
export class OpenVikingClient {
constructor(config) {
this.config = config;
this.connected = false;
- }
-
- headers(options = {}) {
- const headers = { "Content-Type": "application/json" };
- if (this.config.apiKey) headers.Authorization = `Bearer ${this.config.apiKey}`;
- if (this.config.account) headers["X-OpenViking-Account"] = this.config.account;
- if (this.config.user) headers["X-OpenViking-User"] = this.config.user;
- const actorPeerId = options.actorPeerId ?? this.config.peerId;
- if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
- if (this.config.userAgent) headers["User-Agent"] = this.config.userAgent;
- return headers;
- }
-
- async fetchJSON(path, init = {}, options = {}) {
- const timeoutMs = options.timeoutMs ?? this.config.requestTimeoutMs;
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- try {
- const response = await fetch(`${this.config.endpoint}${path}`, {
- ...init,
- headers: {
- ...this.headers(options),
- ...(init.headers || {}),
- },
- signal: controller.signal,
- });
- const body = await response.json().catch(() => ({}));
- const traceId = body?.result?.trace_id
- || body?.error?.trace_id
- || body?.trace_id
- || undefined;
- if (!response.ok || body?.status === "error") {
- return {
- ok: false,
- result: null,
- status: response.status,
- error: body?.error || { message: `HTTP ${response.status}` },
- traceId,
- };
- }
- return {
- ok: true,
- result: body?.result ?? body,
- status: response.status,
- traceId,
- };
- } catch (error) {
- return {
- ok: false,
- result: null,
- status: 0,
- error: { message: error instanceof Error ? error.message : String(error) },
- };
- } finally {
- clearTimeout(timer);
- }
- }
-
- async health() {
- return (await this.healthResult()).ok;
+ this.fetchJSON = createOvHttp(config, {
+ defaultTimeoutMs: config.requestTimeoutMs,
+ resolveActorPeerId: () => this.config.peerId,
+ });
}
async healthResult() {
@@ -70,12 +16,6 @@ export class OpenVikingClient {
return response;
}
- async ensureSession(sessionId, actorPeerId) {
- const response = await this.ensureSessionResult(sessionId, actorPeerId);
- return response.ok
- || (response.status === 409 && response.error?.code === "ALREADY_EXISTS");
- }
-
async ensureSessionResult(sessionId, actorPeerId) {
const response = await this.fetchJSON("/api/v1/sessions", {
method: "POST",
@@ -93,15 +33,6 @@ export class OpenVikingClient {
return response.ok ? response.result : null;
}
- async getSessionArchive(sessionId, archiveId, actorPeerId) {
- const response = await this.fetchJSON(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/archives/${encodeURIComponent(archiveId)}`,
- {},
- { actorPeerId },
- );
- return response.ok ? response.result : null;
- }
-
async addMessage(sessionId, payload, actorPeerId) {
return this.fetchJSON(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
@@ -123,84 +54,4 @@ export class OpenVikingClient {
{ timeoutMs: options.timeoutMs ?? 30000, actorPeerId },
);
}
-
- async find(query, options = {}) {
- const body = { query };
- if (options.targetUri) body.target_uri = options.targetUri;
- if (options.limit) body.limit = options.limit;
- if (options.scoreThreshold !== undefined) body.score_threshold = options.scoreThreshold;
- const response = await this.fetchJSON("/api/v1/search/find", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId: options.actorPeerId });
- if (!response.ok || !response.result) return [];
-
- const results = [];
- for (const bucket of ["memories", "resources", "skills"]) {
- const entries = response.result[bucket];
- if (!Array.isArray(entries)) continue;
- for (const entry of entries) {
- results.push({
- uri: entry?.uri || "",
- contextType: entry?.context_type
- || (bucket === "memories" ? "memory" : bucket === "skills" ? "skill" : "resource"),
- score: Number(entry?.score || 0),
- abstract: entry?.abstract || "",
- overview: entry?.overview || null,
- });
- }
- }
- return results;
- }
-
- async read(uri, level, actorPeerId) {
- const endpoint = level === "abstract"
- ? "abstract"
- : level === "overview"
- ? "overview"
- : "read";
- const response = await this.fetchJSON(
- `/api/v1/content/${endpoint}?uri=${encodeURIComponent(uri)}`,
- {},
- { actorPeerId },
- );
- return response.ok ? response.result : null;
- }
-
- async list(uri, actorPeerId) {
- const response = await this.fetchJSON(
- `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,
- {},
- { actorPeerId },
- );
- return response.ok && Array.isArray(response.result) ? response.result : [];
- }
-
- async stat(uri, actorPeerId) {
- const response = await this.fetchJSON(
- `/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,
- {},
- { actorPeerId },
- );
- return response.ok ? response.result : null;
- }
-
- async forget(uri, recursive = false, actorPeerId) {
- const response = await this.fetchJSON(
- `/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=${recursive}`,
- { method: "DELETE" },
- { actorPeerId },
- );
- return response.ok;
- }
-
- async addResource(path, reason, actorPeerId) {
- const body = { path };
- if (reason) body.reason = reason;
- const response = await this.fetchJSON("/api/v1/resources", {
- method: "POST",
- body: JSON.stringify(body),
- }, { timeoutMs: 30000, actorPeerId });
- return response.ok ? response.result : null;
- }
}
diff --git a/examples/dsh-memory-plugin/client.test.mjs b/examples/dsh-memory-plugin/client.test.mjs
index b427eef4b..bdea87908 100644
--- a/examples/dsh-memory-plugin/client.test.mjs
+++ b/examples/dsh-memory-plugin/client.test.mjs
@@ -26,6 +26,7 @@ test("client sends OpenViking identity headers and preserves response trace ids"
apiKey: "secret",
account: "account-a",
user: "user-a",
+ sendIdentityHeaders: true,
peerId: "peer-a",
userAgent: "openviking-memory-dsh/0.1.0",
requestTimeoutMs: 1000,
@@ -62,97 +63,10 @@ test("per-session actor peer overrides the process default", async () => {
commitKeepRecentCount: 10,
});
- await client.ensureSession("dsh-2", "workspace-peer");
+ await client.ensureSessionResult("dsh-2", "workspace-peer");
assert.equal(headers["X-OpenViking-Actor-Peer"], "workspace-peer");
});
-test("existing OpenViking sessions are reusable on DSH resume", async () => {
- globalThis.fetch = async () => new Response(JSON.stringify({
- status: "error",
- error: { code: "ALREADY_EXISTS", message: "session exists" },
- }), {
- status: 409,
- headers: { "Content-Type": "application/json" },
- });
- const client = new OpenVikingClient({
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- userAgent: "",
- requestTimeoutMs: 1000,
- commitKeepRecentCount: 10,
- });
-
- assert.equal(await client.ensureSession("dsh-resume"), true);
-});
-
-test("directory listing requests the raw array contract", async () => {
- let seenUrl;
- globalThis.fetch = async (url) => {
- seenUrl = url;
- return new Response(JSON.stringify({
- status: "ok",
- result: [{ name: "notes.md", isDir: false }],
- }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- };
- const client = new OpenVikingClient({
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- userAgent: "",
- requestTimeoutMs: 1000,
- commitKeepRecentCount: 10,
- });
-
- assert.deepEqual(await client.list("viking://resources"), [
- { name: "notes.md", isDir: false },
- ]);
- assert.equal(
- seenUrl,
- "http://127.0.0.1:1933/api/v1/fs/ls?uri=viking%3A%2F%2Fresources&output=original",
- );
-});
-
-test("archive lookup uses the dedicated session archive endpoint", async () => {
- let seenUrl;
- globalThis.fetch = async (url) => {
- seenUrl = url;
- return new Response(JSON.stringify({
- status: "ok",
- result: { archive_id: "archive_001", messages: [] },
- }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- };
- const client = new OpenVikingClient({
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- userAgent: "",
- requestTimeoutMs: 1000,
- commitKeepRecentCount: 10,
- });
-
- assert.deepEqual(
- await client.getSessionArchive("dsh session", "archive/001"),
- { archive_id: "archive_001", messages: [] },
- );
- assert.equal(
- seenUrl,
- "http://127.0.0.1:1933/api/v1/sessions/dsh%20session/archives/archive%2F001",
- );
-});
-
test("client normalizes non-2xx OpenViking envelopes", async () => {
globalThis.fetch = async () => new Response(JSON.stringify({
status: "error",
diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs
index 0c70462f8..a4d7123a8 100644
--- a/examples/dsh-memory-plugin/config.mjs
+++ b/examples/dsh-memory-plugin/config.mjs
@@ -1,7 +1,7 @@
-import { buildUserAgent, resolveOpenVikingCredentials } from "./shared/credentials.mjs";
-import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
+import { buildPluginConfig } from "./shared/plugin-config.mjs";
+import { loadCredentialFiles } from "./shared/credentials.mjs";
-export const PLUGIN_VERSION = "0.3.2";
+export const PLUGIN_VERSION = "0.4.0";
/**
* Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool
@@ -10,172 +10,35 @@ export const PLUGIN_VERSION = "0.3.2";
*/
export const MCP_SERVER_NAME = "openviking";
-const DEFAULT_CONFIG = Object.freeze({
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- userAgent: "",
- workspacePeer: true,
- peerSource: "",
- recallPeerScope: "all",
- recallQueryExpansion: "auto",
- recallQueryExpansionConfigured: false,
- syncTurns: true,
- recallTokenBudget: 2000,
- recallMaxContentChars: 500,
- recallPreferAbstract: true,
- recallLimit: 10,
- recallLimitConfigured: false,
- scoreThreshold: 0.35,
- minQueryLength: 3,
- profileTokenBudget: 10000,
- commitTokenThreshold: 20000,
- commitKeepRecentCount: 10,
- captureToolResults: false,
- captureMode: "semantic",
- captureMaxLength: 24000,
- captureToolMaxChars: 1000000,
- captureAssistantTurns: true,
- skipSubagentSessions: false,
- requestTimeoutMs: 10000,
- mcpToolCallTimeoutMs: 60000,
-});
-
+/**
+ * Resolve the plugin's configuration.
+ *
+ * `input` is what the cordis host hands the plugin — this harness has no config
+ * file of its own. Every knob is declared in `shared/config-schema.mjs`, and
+ * `ovcli.conf`'s `plugin` section outranks the host's input so one file
+ * configures every harness and `ov config switch` moves them together.
+ * Connection fields are the exception: an endpoint or key named by the host is
+ * the more specific answer and stays ahead of the credential chain.
+ */
export function resolveConfig(input = {}, env = process.env, cwd = process.cwd()) {
- const credentials = resolveOpenVikingCredentials(env);
- const explicitPeerId = input.peerId || credentials.peerId;
- const config = {
- ...DEFAULT_CONFIG,
- ...input,
- endpoint: input.endpoint || credentials.baseUrl || DEFAULT_CONFIG.endpoint,
- apiKey: input.apiKey || credentials.apiKey,
- account: input.account || credentials.account,
- user: input.user || credentials.user,
- peerId: explicitPeerId,
- explicitPeerId,
- userAgent: buildUserAgent("dsh", PLUGIN_VERSION),
- harness: "dsh",
- recallLimitConfigured: Object.prototype.hasOwnProperty.call(input, "recallLimit"),
- recallQueryExpansionConfigured: Object.prototype.hasOwnProperty.call(input, "recallQueryExpansion"),
- };
-
- if (env.OPENVIKING_WORKSPACE_PEER !== undefined) {
- config.workspacePeer = environmentBoolean(
- env.OPENVIKING_WORKSPACE_PEER,
- config.workspacePeer,
- );
- }
- if (env.OPENVIKING_RECALL_PEER_SCOPE) {
- config.recallPeerScope = env.OPENVIKING_RECALL_PEER_SCOPE;
- }
- if (env.OPENVIKING_RECALL_QUERY_EXPANSION) {
- config.recallQueryExpansion = env.OPENVIKING_RECALL_QUERY_EXPANSION;
- config.recallQueryExpansionConfigured = true;
- }
- if (env.OPENVIKING_RECALL_LIMIT) {
- config.recallLimit = env.OPENVIKING_RECALL_LIMIT;
- config.recallLimitConfigured = true;
- }
-
- config.endpoint = String(config.endpoint || DEFAULT_CONFIG.endpoint).replace(/\/+$/, "");
- config.workspacePeer = config.workspacePeer !== false;
- const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd });
- config.peerId = effectivePeer.peerId;
- config.legacyPeerId = effectivePeer.legacyPeerId;
- config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all";
- config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto";
- config.recallLimit = clampInteger(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);
- config.recallMaxContentChars = clampInteger(
- config.recallMaxContentChars,
- 100,
- 5000,
- DEFAULT_CONFIG.recallMaxContentChars,
- );
- config.recallTokenBudget = clampInteger(
- config.recallTokenBudget,
- 200,
- 50000,
- DEFAULT_CONFIG.recallTokenBudget,
- );
- config.scoreThreshold = clampNumber(
- config.scoreThreshold,
- 0,
- 1,
- DEFAULT_CONFIG.scoreThreshold,
- );
- config.minQueryLength = clampInteger(
- config.minQueryLength,
- 1,
- 64,
- DEFAULT_CONFIG.minQueryLength,
- );
- config.profileTokenBudget = clampInteger(
- config.profileTokenBudget,
- 500,
- 50000,
- DEFAULT_CONFIG.profileTokenBudget,
- );
- config.commitTokenThreshold = clampInteger(
- config.commitTokenThreshold,
- 1000,
- 1000000,
- DEFAULT_CONFIG.commitTokenThreshold,
- );
- config.commitKeepRecentCount = clampInteger(
- config.commitKeepRecentCount,
- 0,
- 1000,
- DEFAULT_CONFIG.commitKeepRecentCount,
- );
- config.captureMaxLength = clampInteger(
- config.captureMaxLength,
- 200,
- 100000,
- DEFAULT_CONFIG.captureMaxLength,
- );
- config.captureToolMaxChars = clampInteger(
- config.captureToolMaxChars,
- 200,
- 1000000,
- DEFAULT_CONFIG.captureToolMaxChars,
- );
- config.requestTimeoutMs = clampInteger(
- config.requestTimeoutMs,
- 1000,
- 120000,
- DEFAULT_CONFIG.requestTimeoutMs,
- );
- config.mcpToolCallTimeoutMs = clampInteger(
- config.mcpToolCallTimeoutMs,
- 1000,
- 600000,
- DEFAULT_CONFIG.mcpToolCallTimeoutMs,
- );
- config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";
- config.syncTurns = config.syncTurns !== false;
- config.captureAssistantTurns = config.captureAssistantTurns !== false;
- config.captureToolResults = config.captureToolResults === true;
- config.skipSubagentSessions = config.skipSubagentSessions === true;
- return config;
-}
-
-function environmentBoolean(value, fallback) {
- const normalized = String(value || "").trim().toLowerCase();
- if (["0", "false", "no", "off"].includes(normalized)) return false;
- if (["1", "true", "yes", "on"].includes(normalized)) return true;
- return fallback;
-}
-
-function clampInteger(value, minimum, maximum, fallback) {
- const number = Math.round(Number(value));
- if (!Number.isFinite(number)) return fallback;
- return Math.max(minimum, Math.min(maximum, number));
-}
-
-function clampNumber(value, minimum, maximum, fallback) {
- const number = Number(value);
- if (!Number.isFinite(number)) return fallback;
- return Math.max(minimum, Math.min(maximum, number));
+ // ov.conf's `dsh` section is the legacy layer here as everywhere else, but
+ // the cordis patch shares that slot; the host named this process's settings,
+ // so it wins the overlap.
+ const ovSection = loadCredentialFiles(env).ovFile.dsh;
+ const config = buildPluginConfig("dsh", {
+ env,
+ cwd,
+ legacy: { ...(ovSection && typeof ovSection === "object" ? ovSection : {}), ...input },
+ version: PLUGIN_VERSION,
+ hostInput: {
+ peerId: input.peerId,
+ account: input.account,
+ user: input.user,
+ apiKey: input.apiKey,
+ baseUrl: input.endpoint,
+ },
+ deriveEffectivePeer: true,
+ });
+
+ return { ...config, peerId: config.effectivePeer.peerId };
}
diff --git a/examples/dsh-memory-plugin/config.test.mjs b/examples/dsh-memory-plugin/config.test.mjs
index 9daabbbcf..40ecc5e8b 100644
--- a/examples/dsh-memory-plugin/config.test.mjs
+++ b/examples/dsh-memory-plugin/config.test.mjs
@@ -2,8 +2,14 @@ import assert from "node:assert/strict";
import test from "node:test";
import { resolveConfig } from "./config.mjs";
+// The layers, the knobs and the peer are the shared loader's, and
+// memory-plugin-shared/plugin-config.test.mjs holds this harness to them. What
+// is left here is the cordis input: the host hands this plugin its environment
+// and its settings, and no other harness has a layer like it.
+
test("behavior environment overrides are applied and normalized", () => {
const config = resolveConfig({}, {
+ OPENVIKING_CLI_CONFIG_FILE: "/nonexistent/ovcli.conf",
OPENVIKING_URL: "http://127.0.0.1:19464/",
OPENVIKING_WORKSPACE_PEER: "0",
OPENVIKING_RECALL_PEER_SCOPE: "actor",
@@ -29,6 +35,7 @@ test("explicit plugin config overrides credential files", () => {
user: "plugin-user",
peerId: "plugin-peer",
}, {
+ OPENVIKING_CLI_CONFIG_FILE: "/nonexistent/ovcli.conf",
OPENVIKING_URL: "http://env.local",
OPENVIKING_API_KEY: "env-key",
OPENVIKING_ACCOUNT: "env-account",
@@ -42,3 +49,70 @@ test("explicit plugin config overrides credential files", () => {
assert.equal(config.user, "plugin-user");
assert.equal(config.peerId, "plugin-peer");
});
+
+// A knob set once in ovcli.conf reaches this harness like any other, and the
+// host's own input is the lower layer.
+test("the ovcli.conf plugin section outranks the cordis input", async () => {
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { join } = await import("node:path");
+ const dir = mkdtempSync(join(tmpdir(), "dsh-plugin-conf-"));
+ const cliPath = join(dir, "ovcli.conf");
+ writeFileSync(cliPath, JSON.stringify({
+ url: "http://127.0.0.1:1933",
+ plugin: { recallLimit: 5, dsh: { captureMode: "keyword" } },
+ }));
+
+ const config = resolveConfig({ recallLimit: 3, captureMode: "semantic" }, {
+ OPENVIKING_CLI_CONFIG_FILE: cliPath,
+ }, "/workspace/project");
+
+ assert.equal(config.recallLimit, 5);
+ assert.equal(config.captureMode, "keyword");
+});
+
+// This harness has no ov.conf section of its own in the layer stack — the
+// cordis input occupies it — so the section is merged in explicitly.
+test("ov.conf's dsh section is the lowest layer, under the cordis input", async () => {
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { join } = await import("node:path");
+ const dir = mkdtempSync(join(tmpdir(), "dsh-ov-conf-"));
+ const ovPath = join(dir, "ov.conf");
+ writeFileSync(ovPath, JSON.stringify({
+ server: { root_api_key: "root-key" },
+ codex: { apiKey: "sk-codex", recallLimit: 9 },
+ dsh: { apiKey: "sk-dsh", recallLimit: 4, scoreThreshold: 0.6 },
+ }));
+ const env = {
+ OPENVIKING_CONFIG_FILE: ovPath,
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "absent-ovcli.conf"),
+ };
+
+ const config = resolveConfig({ recallLimit: 3 }, env, "/workspace/project");
+ assert.equal(config.apiKey, "sk-dsh");
+ assert.equal(config.recallLimit, 3);
+ assert.equal(config.scoreThreshold, 0.6);
+});
+
+// The credential chain used to overwrite the peer rather than supply it, so an
+// ovcli.conf naming no actor peer erased one configured for this harness.
+test("a configured peer survives an empty credential peer", async () => {
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { join } = await import("node:path");
+ const dir = mkdtempSync(join(tmpdir(), "dsh-peer-"));
+ const cliPath = join(dir, "ovcli.conf");
+ writeFileSync(cliPath, JSON.stringify({
+ url: "http://127.0.0.1:1933",
+ plugin: { dsh: { peerId: "dsh-peer" } },
+ }));
+
+ const config = resolveConfig({}, {
+ OPENVIKING_CONFIG_FILE: join(dir, "absent-ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: cliPath,
+ }, "/workspace/project");
+
+ assert.equal(config.peerId, "dsh-peer");
+ assert.equal(config.explicitPeerId, "dsh-peer");
+});
diff --git a/examples/dsh-memory-plugin/live-recall.test.mjs b/examples/dsh-memory-plugin/live-recall.test.mjs
index ecd2d8973..548094530 100644
--- a/examples/dsh-memory-plugin/live-recall.test.mjs
+++ b/examples/dsh-memory-plugin/live-recall.test.mjs
@@ -18,11 +18,11 @@ test("live recall returns a hit for a memory stored by this test", { skip: !enab
// its whole tail verbatim and extraction has nothing to mine.
const config = resolveConfig({ workspacePeer: false, scoreThreshold: 0.1, commitKeepRecentCount: 0 });
const client = new OpenVikingClient(config);
- assert.equal(await client.health(), true, "OpenViking server must be reachable");
+ assert.equal((await client.healthResult()).ok, true, "OpenViking server must be reachable");
const sentinel = `live-e2e-${randomUUID()}`;
const sessionId = `dsh-live-e2e-${Date.now()}`;
- assert.equal(await client.ensureSession(sessionId), true);
+ assert.equal((await client.ensureSessionResult(sessionId)).ok, true, "session creation must succeed");
const added = await client.addMessage(sessionId, {
role: "user",
content: `Remember this fact: the deployment codename is ${sentinel}. It unlocks the staging cluster.`,
diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json
index 77057e810..92207b835 100644
--- a/examples/dsh-memory-plugin/package-lock.json
+++ b/examples/dsh-memory-plugin/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.3.2",
+ "version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openviking/dsh-memory-plugin",
- "version": "0.3.2",
+ "version": "0.4.0",
"license": "Apache-2.0",
"devDependencies": {
"@deepseek-ai/dsh-llm": "0.1.0-rc.6",
diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json
index d0a026fb3..6c5353c45 100644
--- a/examples/dsh-memory-plugin/package.json
+++ b/examples/dsh-memory-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/dsh-memory-plugin",
- "version": "0.3.2",
+ "version": "0.4.0",
"description": "OpenViking memory and context bundle for DeepSeek Harness",
"type": "module",
"main": "index.mjs",
@@ -29,10 +29,11 @@
}
},
"scripts": {
+ "prepack": "node ../memory-plugin-shared/sync.mjs",
"check": "for f in *.mjs shared/*.mjs; do node --check \"$f\" || exit 1; done && npm run check:version",
"check:version": "node --input-type=module -e \"import {readFileSync} from 'node:fs'; const {PLUGIN_VERSION} = await import('./config.mjs'); const v = JSON.parse(readFileSync('package.json','utf8')).version; if (PLUGIN_VERSION !== v) throw new Error('PLUGIN_VERSION ' + PLUGIN_VERSION + ' does not match package.json version ' + v);\"",
"test": "node --test *.test.mjs",
- "prepublishOnly": "npm run check && npm test"
+ "prepublishOnly": "npm run prepack && npm run check && npm test"
},
"peerDependencies": {
"@deepseek-ai/dsh-llm": ">=0.1.0-rc.6 <0.2.0 || ^0.1.5-rc.1",
diff --git a/examples/dsh-memory-plugin/runtime.mjs b/examples/dsh-memory-plugin/runtime.mjs
index 8f1b428bf..ff8c99491 100644
--- a/examples/dsh-memory-plugin/runtime.mjs
+++ b/examples/dsh-memory-plugin/runtime.mjs
@@ -1,6 +1,7 @@
import { createUserMessage } from "@deepseek-ai/dsh-llm";
+import { isCaptureEnabled } from "./shared/capture-utils.mjs";
import { buildProfileBlock } from "./shared/profile-inject.mjs";
-import { buildRecallBlock } from "./shared/recall-core.mjs";
+import { buildRecallBlock, isRecallEnabled } from "./shared/recall-core.mjs";
import { deriveHarnessSessionId } from "./shared/session-model.mjs";
import {
dequeue,
@@ -93,7 +94,7 @@ export class OpenVikingRuntime {
}
// Replay is a write, so it stays behind the same toggle: a backlog queued
// while capture was on waits for a session that still writes.
- if (state.config.syncTurns) {
+ if (isCaptureEnabled(state.config)) {
await this.replayPendingQueue();
}
await this.refreshPendingState(state);
@@ -126,7 +127,7 @@ export class OpenVikingRuntime {
async recallMessage(agent, messages) {
const state = await this.initialize(agent);
- if (!state.ready) return null;
+ if (!state.ready || !isRecallEnabled(state.config)) return null;
const query = promptText(messages);
if (query.length < state.config.minQueryLength) return null;
const block = await buildRecallBlock(
@@ -145,7 +146,7 @@ export class OpenVikingRuntime {
capture(session, event) {
const state = this.stateFor(session);
- if (!state.config.syncTurns) return;
+ if (!isCaptureEnabled(state.config)) return;
const payload = captureEvent(event, state.config, state.toolNames);
if (!payload) return;
this.enqueueWrite(state, async () => {
@@ -177,7 +178,7 @@ export class OpenVikingRuntime {
maybeCommit(session, event) {
if (event.type !== "turn/end") return;
const state = this.stateFor(session);
- if (!state.config.syncTurns) return;
+ if (!isCaptureEnabled(state.config)) return;
this.enqueueWrite(state, async () => {
if (state.hasPendingWrites) return;
if (!state.ready && !(await this.ensureState(state)).ready) return;
@@ -210,7 +211,7 @@ export class OpenVikingRuntime {
if (state.disposing) return state.disposing;
state.disposing = (async () => {
this.enqueueWrite(state, async () => {
- if (!state.config.syncTurns) return;
+ if (!isCaptureEnabled(state.config)) return;
const commitPayload = {
keep_recent_count: state.config.commitKeepRecentCount,
};
diff --git a/examples/dsh-memory-plugin/runtime.test.mjs b/examples/dsh-memory-plugin/runtime.test.mjs
index 52ac9faeb..6d3726f8c 100644
--- a/examples/dsh-memory-plugin/runtime.test.mjs
+++ b/examples/dsh-memory-plugin/runtime.test.mjs
@@ -61,6 +61,35 @@ test("initialization queues capture only when the failure is retryable", async (
}
});
+test("existing OpenViking sessions are reusable on DSH resume", async () => {
+ const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-resume-"));
+ tempDirs.push(pendingDir);
+ process.env.OPENVIKING_PENDING_DIR = pendingDir;
+
+ const runtime = new OpenVikingRuntime({
+ async healthResult() {
+ return { ok: true };
+ },
+ async ensureSessionResult() {
+ return {
+ ok: false,
+ status: 409,
+ error: { code: "ALREADY_EXISTS", message: "session exists" },
+ };
+ },
+ async fetchJSON() {
+ return { ok: false, status: 503, error: { code: "UNAVAILABLE" } };
+ },
+ }, config(), { debug() {} });
+
+ const state = await runtime.initialize({
+ session: { id: "resume", header: { cwd: "/workspace" } },
+ });
+
+ assert.equal(state.ready, true);
+ assert.equal(state.initializationRetryable, false);
+});
+
test("a retryable threshold commit failure is queued", async () => {
const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-commit-"));
tempDirs.push(pendingDir);
@@ -324,6 +353,19 @@ test("disposeAll drains every live session", async () => {
assert.equal(runtime.states.size, 0);
});
+// dsh and pi had no recall switch at all: every other harness could turn recall
+// off and these two retrieved on every prompt regardless.
+test("autoRecall false stops the recall request", async () => {
+ const runtime = new OpenVikingRuntime({
+ async fetchJSON() {
+ throw new Error("recall must not reach the server when it is switched off");
+ },
+ }, { ...config(), autoRecall: false }, { debug() {} });
+ runtime.initialize = async () => ({ ready: true, config: { ...config(), autoRecall: false } });
+
+ assert.equal(await runtime.recallMessage({}, [{ role: "user", content: "what did we decide" }]), null);
+});
+
test("syncTurns false sends nothing: no capture, no commit, no dispose flush, no replay", async () => {
const pendingDir = await mkdtemp(join(tmpdir(), "dsh-memory-sync-off-"));
tempDirs.push(pendingDir);
diff --git a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
index 86c714caa..8bcd4deec 100644
--- a/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
+++ b/examples/dsh-memory-plugin/servers/mcp-proxy.mjs
@@ -19,12 +19,13 @@ import { createOpenVikingMcpProxy } from "../shared/mcp-proxy-core.mjs";
export function readProxyConfig(env = process.env, cwd = process.cwd()) {
const cfg = resolveConfig({}, env, cwd);
- const creds = resolveOpenVikingCredentials(env);
+ const creds = resolveOpenVikingCredentials(env, "dsh");
return buildMcpProxyConfig({
baseUrl: cfg.endpoint,
apiKey: cfg.apiKey,
account: cfg.account,
user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
// Not gated through `resolveMcpActorPeerId` like the other proxies: DSH's
// parent process resolves the peer per session and hands it over in the
// child env (`mcp.mjs` `buildMcpConfig`), so this one is not a guess at the
diff --git a/examples/dsh-memory-plugin/shared/capture-utils.mjs b/examples/dsh-memory-plugin/shared/capture-utils.mjs
deleted file mode 100644
index 22bc1b63c..000000000
--- a/examples/dsh-memory-plugin/shared/capture-utils.mjs
+++ /dev/null
@@ -1,578 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { applyInputFilters, compileInputFilters } from "./input-filters.mjs";
-
-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",
-]);
-
-// Tool output is reported verbatim; the server owns truncation via
-// tool_output_externalization (threshold_chars, default 20000). This cap only
-// guards against pathological payloads.
-const DEFAULT_TOOL_MAX_CHARS = 1000000;
-
-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?.tool ||
- block?.function?.name ||
- block?.call?.name ||
- "",
- );
-}
-
-function toolPayload(block, kind) {
- if (!block || typeof block !== "object") return "";
- if (kind === "call") {
- return block.input ??
- block.state?.input ??
- block.arguments ??
- block.args ??
- block.params ??
- block.function?.arguments ??
- block.command ??
- block.call?.input ??
- block.call?.arguments ??
- "";
- }
- return block.output ??
- block.state?.output ??
- block.result ??
- block.error ??
- block.state?.error ??
- block.data ??
- block.content ??
- block.text ??
- "";
-}
-
-function toolId(block) {
- return oneLine(
- block?.call_id ||
- block?.callId ||
- 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?.isError || block?.state?.isError || block?.error || block?.state?.error) return "error";
- const status = oneLine(block?.status || block?.state?.status || "");
- return status || "completed";
-}
-
-function setToolInput(part, payload) {
- const input = parseMaybeJson(payload);
- if (input === "" || input == null) return;
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
-}
-
-function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, 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") {
- setToolInput(part, payload);
- } else {
- if (block?.state?.input !== undefined) {
- setToolInput(part, block.state.input);
- }
- 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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, 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: DEFAULT_TOOL_MAX_CHARS, 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;
-}
-
-/**
- * Prune blank text parts and run `cfg.captureFilters` over the ones that remain.
- *
- * One drop verdict is taken per turn, on the aggregate of its text parts; the
- * individual parts are then rewritten with the substitutions only, so a rule can
- * never both keep and drop the same turn. Tool call/result parts are carried
- * through untouched — filters match conversation text, not tool payloads — but a
- * turn dropped on its text takes its tool parts with it.
- */
-export function filterCaptureParts(parts, role, cfg = {}) {
- const kept = [];
- for (const part of parts || []) {
- if (!part) continue;
- if (part.type !== "text") {
- kept.push(part);
- continue;
- }
- const text = typeof part.text === "string" ? part.text.trim() : "";
- if (!text) continue;
- kept.push(text === part.text ? part : { ...part, text });
- }
-
- const blank = { parts: kept, dropped: false };
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (!compiled.rules.length || kept.length === 0) return blank;
-
- const textParts = kept.filter((part) => part.type === "text");
- if (textParts.length === 0) return blank;
-
- const verdict = applyInputFilters(textParts.map((part) => part.text).join("\n\n"), compiled.rules, {
- role,
- });
- if (verdict.dropped) return { parts: [], dropped: true };
-
- const out = [];
- for (const part of kept) {
- if (part.type !== "text") {
- out.push(part);
- continue;
- }
- const shaped = applyInputFilters(part.text, compiled.rules, { role, substituteOnly: true });
- if (!shaped.text) continue;
- out.push(shaped.text === part.text ? part : { ...part, text: shaped.text });
- }
- return { parts: out, dropped: out.length === 0 };
-}
-
-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 shaped = filterCaptureParts(parts, role, cfg);
- if (shaped.dropped) continue;
- // With parts on the wire the drop decision was already taken above, so the
- // text path only runs the filters for the `content` fallback. That also
- // keeps `turn.text` faithful for callers that scan it for trigger words.
- const decision = shouldCaptureText(rawText, role, cfg, { filters: shaped.parts.length === 0 });
- if (!decision.shouldCapture && shaped.parts.length === 0) continue;
- const text = decision.shouldCapture ? decision.text : "";
- turns.push({ role, text, parts: shaped.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 = {}, { filters = true } = {}) {
- const maxLength = cfg.captureMaxLength || 24000;
- const sanitized = sanitizeCapturedText(text);
- if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
-
- let capped = truncateCaptureText(sanitized, maxLength);
- if (filters) {
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (compiled.rules.length) {
- const verdict = applyInputFilters(capped, compiled.rules, { role });
- if (verdict.dropped) return { shouldCapture: false, reason: "filtered", text: "" };
- capped = verdict.text;
- if (!capped) return { shouldCapture: false, reason: "empty", text: "" };
- }
- }
- 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/dsh-memory-plugin/shared/credentials.mjs b/examples/dsh-memory-plugin/shared/credentials.mjs
deleted file mode 100644
index ba26a84dc..000000000
--- a/examples/dsh-memory-plugin/shared/credentials.mjs
+++ /dev/null
@@ -1,239 +0,0 @@
-// 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`;
-
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
- let credentialPath = "";
- if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
- }
-
- return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- credentialPath,
- 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/dsh-memory-plugin/shared/debug-log.mjs b/examples/dsh-memory-plugin/shared/debug-log.mjs
deleted file mode 100644
index 73855cf6d..000000000
--- a/examples/dsh-memory-plugin/shared/debug-log.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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/dsh-memory-plugin/shared/input-filters.mjs b/examples/dsh-memory-plugin/shared/input-filters.mjs
deleted file mode 100644
index e20bb03a7..000000000
--- a/examples/dsh-memory-plugin/shared/input-filters.mjs
+++ /dev/null
@@ -1,219 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Ordered, operator-configured regex filters for memory plugin input.
- *
- * Rules are sed-style strings, applied in order to a single piece of text:
- * s/^\s*ultrathink\s+//i substitute (add `g` to replace every match)
- * d|^\s*[/!]| drop the text when the pattern matches
- * k/^\?ov\b/ keep the text only when the pattern matches
- * user:d/^\s*\/clear\b/ apply to one role only
- *
- * A malformed rule becomes an entry in `errors` and is skipped rather than
- * throwing, so a typo in a config file cannot take a hook down.
- */
-
-const OPS = new Set(["s", "d", "k"]);
-const SCOPES = ["user", "assistant"];
-const ALLOWED_FLAGS = "imsug";
-
-export const INPUT_FILTER_KNOBS = [
- {
- key: "recallQueryFilters",
- env: "OPENVIKING_RECALL_QUERY_FILTERS",
- label: "recall query filters",
- },
- {
- key: "captureFilters",
- env: "OPENVIKING_CAPTURE_FILTERS",
- label: "capture filters",
- },
-];
-
-/**
- * Read one delimited field. `\` always consumes the next character, and only
- * `\<delim>` is un-escaped, so `\d` / `\b` / `\x2c` reach RegExp verbatim.
- * Returns the index of the closing delimiter, or -1 when it is missing.
- */
-function scanField(source, start, delim) {
- let out = "";
- let i = start;
- while (i < source.length) {
- const c = source[i];
- if (c === "\\") {
- const next = source[i + 1];
- if (next === undefined) {
- out += "\\";
- i += 1;
- continue;
- }
- out += next === delim ? next : "\\" + next;
- i += 2;
- continue;
- }
- if (c === delim) return { value: out, end: i };
- out += c;
- i += 1;
- }
- return { value: out, end: -1 };
-}
-
-export function parseInputFilterRule(source) {
- if (typeof source !== "string") {
- return { source: String(source ?? ""), error: "rule must be a string" };
- }
- const raw = source.trim();
- if (!raw) return { source: raw, error: "rule is empty" };
-
- let scope = "";
- let rest = raw;
- for (const candidate of SCOPES) {
- if (rest.startsWith(`${candidate}:`)) {
- scope = candidate;
- rest = rest.slice(candidate.length + 1);
- break;
- }
- }
-
- const op = rest[0] || "";
- if (!OPS.has(op)) {
- return {
- source: raw,
- error: `unknown operation "${op}" — expected s (substitute), d (drop) or k (keep)`,
- };
- }
- const delim = rest[1];
- if (delim === undefined) {
- return { source: raw, error: `missing delimiter after "${op}"` };
- }
- if (/[A-Za-z0-9\s\\]/.test(delim)) {
- return {
- source: raw,
- error: `invalid delimiter ${JSON.stringify(delim)} — use punctuation such as / | # or :`,
- };
- }
-
- const first = scanField(rest, 2, delim);
- const pattern = first.value;
- let replacement = null;
- let flagsRaw = "";
- if (op === "s") {
- if (first.end < 0) {
- return { source: raw, error: `missing ${JSON.stringify(delim)} after the pattern` };
- }
- const second = scanField(rest, first.end + 1, delim);
- if (second.end < 0) {
- return {
- source: raw,
- error: `missing ${JSON.stringify(delim)} after the replacement — write s${delim}pattern${delim}replacement${delim}`,
- };
- }
- replacement = second.value;
- flagsRaw = rest.slice(second.end + 1);
- } else {
- flagsRaw = first.end < 0 ? "" : rest.slice(first.end + 1);
- }
-
- if (!pattern) return { source: raw, error: "pattern is empty" };
-
- const flags = new Set();
- for (const flag of flagsRaw) {
- if (!ALLOWED_FLAGS.includes(flag)) {
- return { source: raw, error: `unknown flag "${flag}" — allowed flags are i, m, s, u, g` };
- }
- if (flags.has(flag)) return { source: raw, error: `duplicate flag "${flag}"` };
- flags.add(flag);
- }
- // d/k decide with .test(), which advances lastIndex on a global regex and
- // would then alternate between calls. `g` means nothing there, so drop it.
- if (op !== "s") flags.delete("g");
-
- let re;
- try {
- re = new RegExp(pattern, [...flags].join(""));
- } catch (err) {
- // V8 already says "Invalid regular expression: <pattern>: <why>"; keep that
- // detail without stuttering the prefix the doctors key off.
- const message = err?.message || String(err);
- return {
- source: raw,
- error: /^invalid regular expression/i.test(message)
- ? `invalid${message.slice("Invalid".length)}`
- : `invalid regular expression: ${message}`,
- };
- }
-
- return { op, scope, re, replacement, source: raw };
-}
-
-export function compileInputFilters(rules) {
- const compiled = [];
- const errors = [];
- const list = Array.isArray(rules) ? rules : [];
- list.forEach((entry, index) => {
- if (typeof entry !== "string") {
- errors.push({ index, source: String(entry ?? ""), message: "rule must be a string" });
- return;
- }
- if (!entry.trim()) return;
- const parsed = parseInputFilterRule(entry);
- if (parsed.error) errors.push({ index, source: parsed.source, message: parsed.error });
- else compiled.push({ ...parsed, index });
- });
- return { rules: compiled, errors };
-}
-
-/**
- * Run compiled rules over `text`.
- *
- * `substituteOnly` skips the d/k operations, so a caller that already took one
- * drop decision for a turn can rewrite its individual pieces without taking a
- * second, possibly contradictory one.
- */
-export function applyInputFilters(text, compiled, { role = "", substituteOnly = false } = {}) {
- const original = typeof text === "string" ? text : String(text ?? "");
- let current = original;
- for (const rule of Array.isArray(compiled) ? compiled : []) {
- if (rule.scope && rule.scope !== role) continue;
- if (rule.op === "s") {
- current = current.replace(rule.re, rule.replacement);
- continue;
- }
- if (substituteOnly) continue;
- const matched = rule.re.test(current);
- if ((rule.op === "d" && matched) || (rule.op === "k" && !matched)) {
- return { text: "", changed: false, dropped: true, ruleIndex: rule.index, op: rule.op };
- }
- }
- const finalText = current.trim();
- return {
- text: finalText,
- changed: finalText !== original,
- dropped: false,
- ruleIndex: -1,
- op: "",
- };
-}
-
-/** Doctor-facing summary of both filter knobs on a resolved plugin config. */
-export function describeInputFilters(cfg = {}) {
- return INPUT_FILTER_KNOBS.map(({ key, env, label }) => {
- const configured = Array.isArray(cfg?.[key]) ? cfg[key] : [];
- const compiled = compileInputFilters(configured);
- const ops = { s: 0, d: 0, k: 0 };
- for (const rule of compiled.rules) ops[rule.op] += 1;
- const bits = [];
- if (ops.s) bits.push(`${ops.s} substitute`);
- if (ops.d) bits.push(`${ops.d} drop`);
- if (ops.k) bits.push(`${ops.k} keep-only`);
- const active = compiled.rules.length;
- return {
- key,
- env,
- label,
- total: configured.length,
- active,
- summary: `${active} rule${active === 1 ? "" : "s"}${bits.length ? ` (${bits.join(", ")})` : ""}`,
- errors: compiled.errors,
- };
- });
-}
diff --git a/examples/dsh-memory-plugin/shared/mcp-proxy-config.mjs b/examples/dsh-memory-plugin/shared/mcp-proxy-config.mjs
deleted file mode 100644
index 24d33d9fb..000000000
--- a/examples/dsh-memory-plugin/shared/mcp-proxy-config.mjs
+++ /dev/null
@@ -1,124 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Shared config shaping for the stdio MCP proxy entrypoints.
- *
- * Every harness loads its credentials differently, but the shape
- * `createOpenVikingMcpProxy` consumes is identical everywhere, and so is the
- * set of files whose changes must trigger a credential reload. Keeping that
- * here stops each entrypoint from re-deriving `~` expansion, URL trimming,
- * timeout clamping, and the watch list.
- */
-
-import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
-
-export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
-const MIN_PROXY_TIMEOUT_MS = 1000;
-
-export function trimSlash(value) {
- return String(value || "").replace(/\/+$/, "");
-}
-
-/** Expand a leading `~` and resolve to an absolute path; "" stays "". */
-export function normalizeConfigPath(value) {
- const raw = String(value || "").trim();
- if (!raw) return "";
- if (raw === "~") return homedir();
- if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
- return resolvePath(raw);
-}
-
-/**
- * The credential files every harness must watch: the two `OPENVIKING_*_FILE`
- * overrides and the two default locations under `~/.openviking`.
- */
-export function defaultCredentialPaths(env = process.env) {
- return [
- normalizeConfigPath(env.OPENVIKING_CLI_CONFIG_FILE),
- normalizeConfigPath(env.OPENVIKING_CONFIG_FILE),
- join(homedir(), ".openviking", "ovcli.conf"),
- join(homedir(), ".openviking", "ov.conf"),
- ].filter(Boolean);
-}
-
-/**
- * Resolve the actor peer header for a long-lived MCP proxy process.
- *
- * MCP servers may start in the plugin directory rather than the active
- * workspace, so their process cwd is not a reliable peer identity — and unlike
- * a hook, a long-lived proxy cannot re-derive one per turn. Broad recall
- * intentionally spans the authenticated user's peer workspaces and therefore
- * leaves the actor header unset. Actor-scoped recall needs an explicit peer so
- * isolation never depends on the proxy's launch directory.
- *
- * A missing one degrades to broad recall with a warning rather than refusing to
- * start: the proxy is what carries every memory tool, and taking those away
- * because a scope preference cannot be honoured costs the user far more than
- * the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
- */
-export function resolveMcpActorPeerId({
- peerId = "",
- recallPeerScope = "all",
- onWarn = null,
-} = {}) {
- if (recallPeerScope !== "actor") return "";
-
- const explicitPeerId = String(peerId || "").trim();
- if (explicitPeerId) return explicitPeerId;
-
- const message = "OpenViking MCP: actor-scoped recall needs an explicit peer id, which an MCP proxy cannot "
- + "derive from its launch directory. Falling back to broad recall across every peer under this user. "
- + "Set actor_peer_id in ovcli.conf, or OPENVIKING_PEER_ID in the MCP server environment, to scope it.";
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return "";
-}
-
-function uniq(values) {
- return [...new Set(values.filter(Boolean))];
-}
-
-/**
- * Shape a harness's loaded config into the object `createOpenVikingMcpProxy`
- * expects.
- *
- * `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
- * user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
- * harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
- */
-export function buildMcpProxyConfig({
- baseUrl = "",
- mcpUrl = "",
- apiKey = "",
- account = "",
- user = "",
- peerId = "",
- userAgent = "",
- timeoutMs,
- debug = false,
- debugLogPath = "",
- credentialSource = "auto",
- credentialPath = "",
- watchedPaths = [],
- env = process.env,
-} = {}) {
- return {
- mcpUrl: mcpUrl || `${trimSlash(baseUrl)}/mcp`,
- apiKey: apiKey || "",
- account: account || "",
- user: user || "",
- peerId: peerId || "",
- userAgent: userAgent || "",
- timeoutMs: Math.max(
- MIN_PROXY_TIMEOUT_MS,
- Number(timeoutMs) || DEFAULT_PROXY_TIMEOUT_MS,
- ),
- debug: debug === true,
- debugLogPath,
- credentialSource: credentialSource || "auto",
- credentialPath: credentialPath || "",
- watchedPaths: uniq([...watchedPaths, ...defaultCredentialPaths(env)]),
- };
-}
diff --git a/examples/dsh-memory-plugin/shared/mcp-proxy-core.mjs b/examples/dsh-memory-plugin/shared/mcp-proxy-core.mjs
deleted file mode 100644
index 9a8f5ba26..000000000
--- a/examples/dsh-memory-plugin/shared/mcp-proxy-core.mjs
+++ /dev/null
@@ -1,516 +0,0 @@
-// 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);
- if (err && err.name === "AbortError") {
- // Client-side timeout, not an outage: the server may be healthy and
- // still computing (rerank-inclusive find/search can legitimately take
- // longer than the default budget). Keep -32001 for genuine
- // connection failures so the two are not misdiagnosed as each other.
- return errorResponse(
- id,
- -32004,
- `OpenViking MCP request timed out after ${proxyConfig.timeoutMs}ms (${proxyConfig.mcpUrl}). The server may still be processing (rerank can be slow) — check /health or raise OPENVIKING_TIMEOUT_MS.`,
- { timeoutMs: proxyConfig.timeoutMs, mcpUrl: proxyConfig.mcpUrl, cause: msg },
- );
- }
- return errorResponse(
- id,
- -32001,
- `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that the OpenViking server (\`openviking-server\`) is reachable.`,
- { 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/dsh-memory-plugin/shared/pending-queue.mjs b/examples/dsh-memory-plugin/shared/pending-queue.mjs
deleted file mode 100644
index 38dccb1c8..000000000
--- a/examples/dsh-memory-plugin/shared/pending-queue.mjs
+++ /dev/null
@@ -1,487 +0,0 @@
-// 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. The queue is replayed in small
- * batches, either at session-start (consuming retry budgets, with
- * maxRetries/TTL) or by a long-running drainer that passes
- * `consumeRetries: false` so transient failures stay retryable.
- *
- * 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";
-import { isRetryableFailure } from "./retryable.mjs";
-
-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) {
- return isRetryableFailure(res);
-}
-
-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;
- }
-}
-
-/**
- * Release a claimed file back to the queue without consuming a retry. The
- * entry keeps its original filename, retry count, and createdAt position, so a
- * later run retries it as if this attempt never happened.
- */
-export async function releaseClaim(claimedFilename) {
- if (!claimedFilename.endsWith(".processing")) return null;
- const dir = getPendingDir();
- const restored = pendingFromProcessingFilename(claimedFilename);
- try {
- await rename(join(dir, claimedFilename), join(dir, restored));
- return restored;
- } 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
- * @param {object} [options]
- * @param {boolean} [options.consumeRetries=true] - when false, retryable
- * failures release their claim instead of incrementing the retry count, so
- * a background drainer can keep retrying a transient failure without
- * burning the session-start retry budget. Exhausted and non-retryable
- * entries are deleted exactly as in the default mode.
- * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
- */
-export async function replayPending(fetchJSON, log, options = {}) {
- const consumeRetries = options.consumeRetries !== false;
- 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 (entry.type === "commitSession") {
- log("pending-queue", {
- action: "commit-replay",
- sessionId: entry.sessionId,
- ok: Boolean(res?.ok),
- status: res?.result?.status || res?.status,
- trace_id: res?.traceId || res?.result?.trace_id,
- error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
- });
- }
-
- if (res?.ok) {
- await dequeue(claimedFilename);
- replayed++;
- } else if (!isRetryableReplayFailure(res)) {
- await dequeue(claimedFilename);
- skipped++;
- } else {
- if (consumeRetries) {
- await incrementRetry(claimedFilename, entry);
- } else {
- const released = await releaseClaim(claimedFilename);
- log("pending-queue", {
- action: released ? "replay-deferred" : "release-failed",
- sessionId: entry.sessionId,
- type: entry.type,
- status: res?.result?.status || res?.status,
- retries: entry.retries || 0,
- });
- }
- 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/dsh-memory-plugin/shared/profile-inject.mjs b/examples/dsh-memory-plugin/shared/profile-inject.mjs
deleted file mode 100644
index 3f601844a..000000000
--- a/examples/dsh-memory-plugin/shared/profile-inject.mjs
+++ /dev/null
@@ -1,294 +0,0 @@
-// 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/dsh-memory-plugin/shared/recall-compress-core.mjs b/examples/dsh-memory-plugin/shared/recall-compress-core.mjs
deleted file mode 100644
index 1ced4cf4d..000000000
--- a/examples/dsh-memory-plugin/shared/recall-compress-core.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
-
-export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
-export const DIGEST_HEADER = "OpenViking memory digest:";
-const COMPRESS_OK = "ok";
-const COMPRESS_EMPTY = "empty";
-const COMPRESS_FAILED = "failed";
-
-// Medium-constraint prompt: state the goal and two structural floors, but no hard
-// bullet-length contract. Hard per-bullet limits pin the digest to headline
-// density; leaving it unconstrained lets small models rewrite long URIs into dead
-// links, which the URI repair below cleans up.
-export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
- return `You are a memory relevance compressor utility.
-Do not use any tools. Do not investigate. Only transform the given text.
-
-User query:
-${query}
-
-Retrieved OpenViking context fragments:
-${rendered}
-
-Write a memory digest for a coding agent about to answer that query. Keep the
-concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
-and conversational filler.
-
-Format rules:
-- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
-- Start every bullet with "- ".
-- End every bullet with its source, copied verbatim from the fragments above:
- "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
-- Output the digest body only. No preamble, no closing remark.
-
-If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
-}
-
-function editDistance(a, b) {
- if (a === b) return 0;
- const rows = a.length + 1;
- const cols = b.length + 1;
- let prev = Array.from({ length: cols }, (_, i) => i);
- for (let i = 1; i < rows; i += 1) {
- const cur = [i];
- for (let j = 1; j < cols; j += 1) {
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
- cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
- }
- prev = cur;
- }
- return prev[cols - 1];
-}
-
-function nearestUri(candidate, validUris) {
- let best = "";
- let bestDistance = Infinity;
- for (const uri of validUris) {
- const distance = editDistance(candidate, uri);
- if (distance < bestDistance) {
- best = uri;
- bestDistance = distance;
- }
- }
- // Only repair near-misses; an unrelated hallucination is dropped instead.
- const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
- return bestDistance <= tolerance ? best : "";
-}
-
-/**
- * Small models occasionally mangle long URIs. Snap every cited URI back onto the
- * set the server actually returned, and drop bullets whose citation cannot be
- * recovered so the digest never carries a dead link.
- */
-export function repairDigestUris(digest, validUris = []) {
- const text = String(digest || "");
- if (!text) return "";
- const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
- if (!valid.length) return text;
- const validSet = new Set(valid);
-
- const lines = [];
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim().startsWith("- ")) {
- lines.push(line);
- continue;
- }
- let tokenized = line;
- for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
- if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
- }
- let dropped = false;
- const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
- let decoded = uri;
- try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
- if (validSet.has(decoded)) return decoded;
- const nearest = nearestUri(decoded, valid);
- if (nearest) return nearest;
- dropped = true;
- return uri;
- });
- if (!dropped) lines.push(repaired);
- }
- return lines.join("\n").trim();
-}
-
-export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
- const text = String(raw || "").trim();
- if (!text) return null;
- if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
- const bullets = text.split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
- .slice(0, Math.max(1, maxBullets))
- .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
- if (!bullets.length) return null;
- return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
-}
-
-export function recallDigestCacheKey({
- query = "",
- rendered = "",
- entries = [],
- maxInputChars = 18000,
- maxBullets = 6,
-} = {}) {
- const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
- const source = JSON.stringify({
- version: 2,
- query: String(query),
- rendered: String(rendered).slice(0, maxInputChars),
- uris,
- maxInputChars,
- maxBullets,
- });
- return createHash("sha256").update(source).digest("hex");
-}
-
-async function readCache(path) {
- if (!path) return null;
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeCache(path, value) {
- if (!path) return;
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-export async function compressRecallContext({
- query,
- rendered,
- shortContext = rendered,
- entries = [],
- cfg = {},
- runCompressor,
- cachePath = "",
- now = 0,
-}) {
- const input = String(rendered || "").trim();
- if (!input) return { status: COMPRESS_EMPTY, context: "" };
- const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
- if (input.length < minChars) {
- return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
- }
-
- const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
- const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
- const key = recallDigestCacheKey({
- query,
- rendered: input,
- entries,
- maxInputChars,
- maxBullets,
- });
- const cached = await readCache(cachePath);
- if (cached?.key === key && typeof cached.digest === "string") {
- const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
- if (digest) return { status: COMPRESS_OK, context: digest };
- }
-
- const prompt = buildRecallCompressionPrompt({
- query,
- rendered: input.slice(0, maxInputChars),
- maxBullets,
- });
- const raw = await runCompressor(prompt);
- const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
- if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
- if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
-
- const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
- const repaired = repairDigestUris(normalized, validUris.length
- ? validUris
- : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
- const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
- if (!digest) return { status: COMPRESS_FAILED, context: "" };
-
- await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
- return { status: COMPRESS_OK, context: digest };
-}
diff --git a/examples/dsh-memory-plugin/shared/recall-core.mjs b/examples/dsh-memory-plugin/shared/recall-core.mjs
deleted file mode 100644
index 72835de8f..000000000
--- a/examples/dsh-memory-plugin/shared/recall-core.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-
-import { compressRecallContext } from "./recall-compress-core.mjs";
-
-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://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-const DEFAULT_CONTEXT_LIMIT = 10;
-const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
-const DEFAULT_REWRITE_MAX_BULLETS = 6;
-const CODING_QUOTA_WEIGHTS = {
- events: 1,
- entities: 2,
- preferences: 1,
- experiences: 1,
- resources: 3,
- skills: 2,
-};
-
-let userSpaceCache = "";
-
-export function estimateTokens(text) {
- return text ? Math.ceil(String(text).length / 4) : 0;
-}
-
-function scaleQuotas(limit, weights) {
- const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
- const order = Object.keys(weights);
- const quotas = Object.fromEntries(order.map((key) => [key, 0]));
- if (slots < order.length) {
- for (const key of order) quotas[key] = 1;
- return quotas;
- }
-
- for (const key of order) quotas[key] = 1;
- const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
- const ideals = Object.fromEntries(
- order.map((key) => [key, slots * weights[key] / totalWeight]),
- );
- while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
- const key = order.reduce((best, candidate) => (
- ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
- ? candidate
- : best
- ));
- quotas[key] += 1;
- }
- return quotas;
-}
-
-function legacyMemoryQuotas(limit) {
- return {
- ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
- experiences: 0,
- };
-}
-
-function codingQuotas(limit) {
- return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
-}
-
-export function buildRecallEndpointBody(cfg = {}) {
- const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
- const body = {
- query: "",
- quotas: legacyMemoryQuotas(limit),
- 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;
-}
-
-/**
- * Body for the server-side context face. The plugin declares intent (coding
- * purpose, budget, session) and leaves the mechanics — quota ratios, tier
- * degradation, cross-turn dedup — to the server's defaults.
- */
-export function buildContextSearchBody(cfg = {}, options = {}) {
- const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
- const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
- const maxTokens = Math.max(
- 64,
- Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
- );
- const body = {
- query: "",
- mode: "context",
- purpose: "coding",
- score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
- };
- const limitConfigured = cfg.recallLimitConfigured === true;
- const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
- if (limitConfigured) body.quotas = codingQuotas(limit);
- if (maxTokensConfigured) body.max_tokens = maxTokens;
- if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
-
- const sessionId = String(options.sessionId || "").trim();
- if (sessionId) {
- body.session_id = sessionId;
- const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
- if (queryExpansionConfigured) {
- body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
- }
- const dedupTurns = Number(cfg.recallDedupTurns);
- const resolvedDedupTurns = Number.isFinite(dedupTurns)
- ? Math.max(0, Math.floor(dedupTurns))
- : 5;
- if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
- }
-
- const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
- if (excludeUris.length) body.exclude_uris = excludeUris;
-
- if (rewriteMode === "server") body.rewrite = true;
- else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
- const rewriteMaxBullets = Math.max(
- 1,
- Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
- );
- const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
- if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
- body.rewrite_max_bullets = rewriteMaxBullets;
- }
- return body;
-}
-
-// The server pipeline is serial and each optional stage has its own fuse. A
-// request is aborted client-side unless its deadline covers every stage it
-// asked for, and aborting discards the whole response rather than just the
-// stage that ran long.
-//
-// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
-// always -> retrieval, body reads, budget planning
-// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
-//
-// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
-// a quarter to spare.
-const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
-const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
-
-/**
- * HTTP deadline for one context request, or undefined to keep the caller's own.
- *
- * Derived from the request body, because the body is what states which server
- * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
- * that also spends the expansion or rewrite fuse.
- */
-export function contextRequestTimeoutMs(cfg = {}, body = {}) {
- const wantsRewrite = body.rewrite !== undefined;
- // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
- // takes the expansion fuse back out of the budget.
- const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
- const configured = Number(cfg.recallContextTimeoutMs);
- if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
- if (!wantsRewrite && !wantsExpansion) return undefined;
- const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
- return Math.max(Number(cfg.timeoutMs) || 0, floor);
-}
-
-/**
- * Strip the context-face fields a pre-context server rejects, converting the
- * token budget back to v1's character budget.
- */
-export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
- const body = buildRecallEndpointBody(cfg);
- body.query = contextBody.query || "";
- body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
- if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
- 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(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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");
-}
-
-const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
-
-function stateFile(name) {
- const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
- return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
-}
-
-async function readJsonFile(path) {
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeJsonFile(path, value) {
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Hooks are one-shot processes, so "this server has no context face" has to be
- * remembered on disk or every turn pays for a rejected request.
- */
-export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- const cached = await readJsonFile(path);
- return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
-}
-
-export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
-}
-
-/**
- * A `peer_scope` the server rejects is remembered the same way, but unlike the
- * context face this one is not a silent capability probe: dropping the field
- * widens recall from the caller's own peer to the whole user root, so doctor
- * reads this file back and warns.
- */
-export function peerScopeMemoPath() {
- return stateFile("peer-scope.json");
-}
-
-export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
- const cached = await readJsonFile(path);
- if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
- return cached;
-}
-
-export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
- await writeJsonFile(path, {
- legacyUntil: now + LEGACY_CACHE_TTL_MS,
- scope: String(scope || ""),
- status: Number(status) || 0,
- at: now,
- });
-}
-
-function looksLikeUnknownField(res) {
- const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
- return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
-}
-
-function wrapContext(body) {
- return [
- "<openviking-context>",
- "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
- body,
- "</openviking-context>",
- ].join("\n");
-}
-
-/**
- * Server-assembled context: the context face when the deployment has it, else
- * the deprecated /recall preset. Returns the injection block, "" when there was
- * nothing relevant, or null when no server-side path was usable at all.
- */
-export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
-
- const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
- if (block !== null) return block;
- return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
-}
-
-/**
- * Raw server-assembled context, or null when the deployment has no context face.
- * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
- * (their own compression, their own envelope) use this instead of the block
- * builders below.
- */
-export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId || "";
- const log = options.log || (() => {});
- if (await isContextFaceLegacy(options.legacyCachePath)) return null;
-
- const body = buildContextSearchBody(cfg, options);
- body.query = query;
- const res = await fetchJSON("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
-
- if (!res.ok) {
- const status = res.status || 0;
- if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
- await markContextFaceLegacy(options.legacyCachePath);
- log("recall_context_face_unsupported", { status });
- } else {
- log("recall_context_face_error", { status });
- }
- return null;
- }
-
- const result = res.result || {};
- const stats = result.stats || {};
- log("recall_context_assembled", {
- entries: Array.isArray(result.entries) ? result.entries.length : 0,
- usedTokens: stats.used_tokens || 0,
- tiers: stats.tier_counts || {},
- rewrite: stats.rewrite || "off",
- });
- return {
- rendered: String(result.rendered || "").trim(),
- entries: Array.isArray(result.entries) ? result.entries : [],
- digest: String(result.digest || "").trim(),
- stats,
- };
-}
-
-/**
- * Entry field compatibility: the context face returns `category`/`text`, while
- * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
- */
-export function normalizeContextEntry(entry = {}) {
- return {
- uri: String(entry.uri || "").trim(),
- category: String(entry.category || entry.type || "memory").trim() || "memory",
- detail: String(entry.detail || entry.mode || "").trim(),
- score: Number(entry.score) || 0,
- text: String(
- entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
- ).trim(),
- };
-}
-
-async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
- const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
- if (assembled === null) return null;
-
- const { rendered, entries } = assembled;
- let digest = assembled.digest;
- const mode = String(cfg.recallRewrite || "off").toLowerCase();
- if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
- log("recall_server_compression", { status: "empty" });
- return "";
- }
- const wantsLocal = mode === "client" || (mode === "auto" && !digest);
- if (wantsLocal && rendered && typeof options.runCompressor === "function") {
- try {
- const compression = await compressRecallContext({
- query,
- rendered,
- entries,
- cfg,
- runCompressor: options.runCompressor,
- cachePath: options.digestCachePath || stateFile("recall-digest.json"),
- now: Date.now(),
- });
- log("recall_local_compression", { status: compression.status });
- if (compression.status === "ok") digest = compression.context;
- if (compression.status === "empty") return "";
- } catch (err) {
- log("recall_local_compression_failed", { error: String(err?.message || err) });
- }
- }
-
- const injected = digest || rendered;
- if (!injected) return "";
- return wrapContext(injected);
-}
-
-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 wrapContext(rendered);
-}
-
-export async function postRecall(fetchJSON, body, opts = {}) {
- const actorPeerId = opts.actorPeerId || "";
- const log = opts.log || (() => {});
- const memoPath = opts.peerScopeMemoPath;
- const request = { ...body };
-
- // A remembered downgrade is still a downgrade: recall runs wider than the
- // caller asked for, so the memo doubles as the doctor's evidence.
- if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
- delete request.peer_scope;
- }
-
- 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;
- }
- // Only an unknown-field rejection means "this server predates peer_scope".
- // Retrying every other 400/422 without it silently widens the search from
- // the caller's own peer to the whole user root.
- if (!looksLikeUnknownField(res)) {
- log("recall_peer_scope_error", { status: res.status || 0 });
- return res;
- }
-
- const downgraded = { ...request };
- delete downgraded.peer_scope;
- await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
- log("recall_peer_scope_downgrade", { status: res.status || 0 });
- return fetchJSON("/api/v1/search/recall", {
- method: "POST",
- body: JSON.stringify(downgraded),
- }, { actorPeerId });
-}
-
-/**
- * Recall, plus whatever is still filed under the peer this workspace used
- * before the identity rule changed.
- *
- * Under the default `peer_scope: "all"` this costs nothing: the server's own
- * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
- * `"actor"` that sweep is off by definition, so the old peer is asked for
- * separately — as itself, which is both cheaper and wider than a bare
- * cross-peer read (that would need the user id, and reaches memories only).
- */
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
- const primary = await recallForPeer(fetchJSON, cfg, query, options);
-
- const legacyPeerId = String(options.legacyPeerId || "").trim();
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
-
- const log = options.log || (() => {});
- const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
-}
-
-async function recallForPeer(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
- const trimmed = String(query || "").trim();
- if (!trimmed) return null;
-
- // Assembly happens server-side when the deployment offers the context face;
- // older servers fall through to /recall, then to raw find.
- const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
- ...options,
- actorPeerId,
- log,
- });
- if (serverBlock !== null) return serverBlock || null;
-
- const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
- 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/dsh-memory-plugin/shared/retryable.mjs b/examples/dsh-memory-plugin/shared/retryable.mjs
deleted file mode 100644
index 8be4b14e8..000000000
--- a/examples/dsh-memory-plugin/shared/retryable.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-export function isRetryableFailure(result) {
- if (!result || result.ok) return false;
- const status = Number(result.status || 0);
- if (!status || status === 408 || status === 429 || status >= 500) {
- return true;
- }
- return status === 409 && result.error?.details?.retryable === true;
-}
diff --git a/examples/dsh-memory-plugin/shared/session-model.mjs b/examples/dsh-memory-plugin/shared/session-model.mjs
deleted file mode 100644
index b6496a113..000000000
--- a/examples/dsh-memory-plugin/shared/session-model.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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/dsh-memory-plugin/shared/uri-guard.mjs b/examples/dsh-memory-plugin/shared/uri-guard.mjs
deleted file mode 100644
index cf57bf406..000000000
--- a/examples/dsh-memory-plugin/shared/uri-guard.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// 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();
-}
-
-// Arguments that carry file CONTENT rather than a location. The sweep below
-// looks past the known path keys so an unusual one (`paths`, a nested target)
-// is still caught, but text a tool is asked to WRITE is not a path: a local
-// `write` whose body merely mentions viking://user/default/ was denied, and no
-// file was created. Skipped by name at any depth.
-const DEFAULT_CONTENT_KEYS = [
- "content",
- "contents",
- "text",
- "body",
- "old_string",
- "oldString",
- "new_string",
- "newString",
- "old_str",
- "new_str",
- "file_text",
- "insert_line",
- "replacement",
-];
-
-export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_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, new Set(contentKeys));
-}
-
-export function findVikingUriInValue(value, skipKeys) {
- 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, skipKeys);
- if (uri) return uri;
- }
- return null;
- }
- if (value && typeof value === "object") {
- for (const [key, item] of Object.entries(value)) {
- if (skipKeys?.has(key)) continue;
- const uri = findVikingUriInValue(item, skipKeys);
- 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/dsh-memory-plugin/shared/workspace-identity.mjs b/examples/dsh-memory-plugin/shared/workspace-identity.mjs
deleted file mode 100644
index 76922cb03..000000000
--- a/examples/dsh-memory-plugin/shared/workspace-identity.mjs
+++ /dev/null
@@ -1,334 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Workspace identity: where the workspace root is, and what git calls it.
- *
- * Every hook is a fresh Node process and this runs on prompt-level paths, so
- * the derivation is pure filesystem work — no `git` subprocess. That keeps it
- * inside the tightest hook budget (Codex allows SessionEnd 3s against
- * SessionStart's 70s), and it keeps working where git is absent from PATH or
- * would refuse the repo over dubious ownership.
- *
- * The result is cached per cwd under the state dir so the several hooks of one
- * turn pay for the walk once.
- */
-
-import { createHash } from "node:crypto";
-import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
-
-// The workspace config file names live here, and `workspace-config.mjs`
-// re-exports them: the walk below needs the filenames to recognise a directory
-// someone marked as a workspace, and it must not pull in the config layer to
-// learn them.
-export const CONFIG_DIR_NAME = ".openviking";
-export const TEAM_FILE = "config.json";
-export const LOCAL_FILE = "config.local.json";
-
-const IDENTITY_CACHE_TTL_MS = 60_000;
-// 255 is the AGFS path-segment limit; stopping well short leaves room for the
-// hash suffix and for anything that later prefixes a peer id.
-const MAX_PEER_ID_LENGTH = 100;
-
-export function stateDir(env = process.env) {
- const explicit = String(env.OPENVIKING_STATE_DIR || "").trim();
- if (explicit) return explicit;
- const home = String(env.OPENVIKING_HOME || "").trim();
- const base = home ? home.replace(/^~(?=$|\/)/, homedir()) : join(homedir(), ".openviking");
- return join(base, "state");
-}
-
-function shortHash(value) {
- return createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
-}
-
-/**
- * Legacy peer sanitation: one byte in, one byte out, no collapsing and no
- * trimming, so a leading `/` still becomes a leading `-`. Kept byte-exact
- * because `peer.source: "cwd"` and the legacy id that dual-read recomputes both
- * depend on it — do not "improve" it.
- */
-export function legacySanitize(value) {
- return String(value || "").replace(/[^A-Za-z0-9]/g, "-");
-}
-
-/**
- * Readable sanitation for values that were never path-shaped — a normalized
- * remote, a directory name. Mirrors the server's own `_sanitize_component`
- * (`openviking/ingest/peer.py:32`) so both languages agree on the id, then
- * enforces what `validate_identifier_part` additionally requires.
- */
-export function sanitizePeerId(value) {
- const raw = String(value || "").trim();
- let cleaned = raw.replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
- if (!cleaned) return "";
- // The server accepts at most one `@` in an identifier part.
- const at = cleaned.indexOf("@");
- if (at !== -1) cleaned = cleaned.slice(0, at + 1) + cleaned.slice(at + 1).replace(/@/g, "-");
- // `ext-` is the server's namespace for base64-encoded external identities,
- // and `__self` its operation-target sentinel. Neither is ours to occupy.
- if (cleaned.startsWith("ext-")) cleaned = `x-${cleaned}`;
- if (cleaned === "__self") cleaned = "self";
- if (cleaned === "." || cleaned === "..") return "";
- if (cleaned.length > MAX_PEER_ID_LENGTH) {
- cleaned = `${cleaned.slice(0, MAX_PEER_ID_LENGTH - 13).replace(/[-.]+$/, "")}-${shortHash(raw)}`;
- }
- return cleaned;
-}
-
-/**
- * Normalize a remote URL to `host/path`, lowercased.
- *
- * Both spellings of the same repo converge, and userinfo is dropped — so a
- * remote with an embedded token cannot leak it into a peer id. The cost of
- * case folding is that two repos differing only in case share one namespace on
- * the rare case-sensitive forge.
- */
-export function normalizeGitRemote(url) {
- const raw = String(url || "").trim();
- if (!raw) return "";
-
- // `C:\src\repo` and `C:/src/repo` are one machine's directory, not a shared
- // identity — and the scp pattern would happily read the drive as a host.
- if (/^[A-Za-z]:[\\/]/.test(raw)) return "";
-
- let host = "";
- let path = "";
- const scp = /^(?:[^@/\\]+@)?([^:/\\]+):(?!\/)(.+)$/.exec(raw);
- if (scp && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {
- host = scp[1];
- path = scp[2];
- } else {
- let parsed;
- try {
- parsed = new URL(raw);
- } catch {
- return "";
- }
- // A local clone has no stable shared identity — fall through to the path
- // rules instead of minting one from `file://` or a bare directory.
- if (parsed.protocol === "file:" || !parsed.hostname) return "";
- host = parsed.hostname;
- path = parsed.pathname;
- }
-
- host = host.toLowerCase().replace(/^\[|\]$/g, "");
- path = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
- if (!host || !path) return "";
- return `${host}/${path}`;
-}
-
-function readFileOrEmpty(path) {
- try {
- return readFileSync(path, "utf-8");
- } catch {
- return "";
- }
-}
-
-/**
- * Read `[remote "origin"] url` out of a git config with a minimal INI parse.
- *
- * `include` / `includeIf` are deliberately not followed: resolving them means
- * more filesystem walking for a value the fallback chain already covers, so an
- * unreadable remote just falls through to the next template.
- */
-export function readGitRemoteUrl(commonDir, remote = "origin") {
- const text = readFileOrEmpty(join(commonDir, "config"));
- if (!text) return "";
-
- let inSection = false;
- for (const line of text.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;
- const section = /^\[([^\]]+)\]/.exec(trimmed);
- if (section) {
- const header = section[1].trim();
- // git folds section and key names to lower case but keeps a quoted
- // subsection exact, so `[Remote "origin"]` is the same section and
- // `[remote "Origin"]` is not.
- const quoted = /^remote\s+"(.*)"$/i.exec(header);
- inSection = Boolean(quoted && quoted[1] === remote);
- continue;
- }
- if (!inSection) continue;
- const pair = /^url\s*=\s*(.*)$/i.exec(trimmed);
- // git treats an unquoted `#` or `;` as starting a comment anywhere on the
- // line, so a trailing note is not part of the URL.
- if (pair) return pair[1].split(/[#;]/)[0].trim().replace(/^["']|["']$/g, "");
- }
- return "";
-}
-
-function resolveGitDir(root) {
- const dotGit = join(root, ".git");
- let stat;
- try {
- stat = statSync(dotGit);
- } catch {
- return null;
- }
- if (stat.isDirectory()) return { gitDir: dotGit, commonDir: dotGit, kind: "repo" };
- if (!stat.isFile()) return null;
-
- const pointer = /^gitdir:\s*(.+)$/m.exec(readFileOrEmpty(dotGit));
- if (!pointer) return null;
- const gitDir = resolve(root, pointer[1].trim());
-
- // `commondir` is the worktree signal, so it is read first — a repository
- // that merely lives under a directory called `modules` is not a submodule.
- const commonRef = readFileOrEmpty(join(gitDir, "commondir")).trim();
- const commonDir = commonRef
- ? (isAbsolute(commonRef) ? commonRef : resolve(gitDir, commonRef))
- : gitDir;
-
- // A submodule keeps its own remote under the superproject's
- // `.git/modules/<name>`; converging it onto the superproject would merge two
- // repositories that release, and are reviewed, separately. Only the segment
- // right after a `.git` directory means that, which is also why a worktree of
- // a submodule resolves here through its own commondir.
- const kind = /[/\\]\.git[/\\]modules[/\\]/.test(`${commonDir}${sep}`)
- ? "submodule"
- : (commonRef ? "worktree" : "repo");
- return { gitDir, commonDir, kind };
-}
-
-/** A directory the user made a workspace on purpose, by giving it a config file. */
-function hasWorkspaceMarker(dir) {
- for (const name of [TEAM_FILE, LOCAL_FILE]) {
- try {
- if (statSync(join(dir, CONFIG_DIR_NAME, name)).isFile()) return true;
- } catch { /* not marked here */ }
- }
- return false;
-}
-
-const NO_ROOT = Object.freeze({ root: "", rootKind: "", git: null, gitRoot: "" });
-
-/**
- * Walk up from `cwd` to the nearest workspace root.
- *
- * A workspace is a git repository, or a directory someone marked as one by
- * creating `.openviking/config.json` (or `config.local.json`) in it. Nearest
- * wins. Above a marked directory the walk continues to the enclosing
- * repository, if any, so the git-shaped variables still resolve there.
- * Anything else — a scratch folder, a download, an app's per-task directory —
- * is not a workspace and gets no peer of its own.
- *
- * `$HOME` and the filesystem root are never workspace roots: a stray `.git`
- * in either would silently make every unrelated directory one workspace.
- */
-export function findWorkspaceRoot(cwd, env = process.env) {
- const start = String(cwd || "").trim();
- if (!start) return NO_ROOT;
-
- let absolute;
- try {
- // A relative `start` makes `resolve` read process.cwd(), which throws when
- // the directory is gone — the very case the catch below is meant to cover.
- absolute = resolve(start);
- } catch {
- return NO_ROOT;
- }
-
- // `current` and `stopAt` are compared as strings, so they must be
- // canonicalized together. A `$HOME` reached through a symlink plus an
- // unresolvable cwd would otherwise walk straight past the guard.
- const home = String(env.HOME || "").trim() || homedir();
- let current;
- let stopAt;
- try {
- current = realpathSync(absolute);
- stopAt = realpathSync(home);
- } catch {
- current = absolute;
- stopAt = home;
- }
- const filesystemRoot = parse(current).root;
- if (current === stopAt || current === filesystemRoot) return NO_ROOT;
-
- let root = "";
- let rootKind = "";
- while (current && current !== filesystemRoot && current !== stopAt) {
- const git = resolveGitDir(current);
- if (git) return { root: root || current, rootKind: rootKind || "git", git, gitRoot: current };
- if (!root && hasWorkspaceMarker(current)) {
- root = current;
- rootKind = "config";
- }
- const parent = dirname(current);
- if (parent === current) break;
- current = parent;
- }
- return root ? { root, rootKind, git: null, gitRoot: "" } : NO_ROOT;
-}
-
-function cachePath(cwd, env) {
- return join(stateDir(env), `ws-identity-${shortHash(cwd)}.json`);
-}
-
-function readCache(path, now) {
- try {
- const cached = JSON.parse(readFileSync(path, "utf-8"));
- // Bounded on both sides: an entry stamped in the future — a clock that ran
- // fast, or `Infinity` — would otherwise pin a stale identity indefinitely.
- if (typeof cached?.ts !== "number" || cached.ts > now || now - cached.ts > IDENTITY_CACHE_TTL_MS) return null;
- const identity = cached.identity;
- if (identity && typeof identity === "object" && identity.vars && typeof identity.vars === "object") {
- return identity;
- }
- } catch { /* a cold or corrupt cache just costs one walk */ }
- return null;
-}
-
-function writeCache(path, identity, now) {
- try {
- mkdirSync(dirname(path), { recursive: true });
- const tmp = `${path}.${process.pid}.tmp`;
- writeFileSync(tmp, JSON.stringify({ ts: now, identity }), { mode: 0o600 });
- renameSync(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Everything the peer templates can substitute, for one cwd.
- *
- * `git_remote` and `dir` are already sanitized; `git_root` and `cwd` carry the
- * legacy byte-for-byte rule, because they are the two that must reproduce a
- * peer minted before any of this existed.
- */
-export function resolveWorkspaceIdentity({ cwd = "", env = process.env, cache = true, now = Date.now() } = {}) {
- const key = String(cwd || "");
- const path = cachePath(key, env);
- if (cache) {
- const hit = readCache(path, now);
- if (hit) return hit;
- }
-
- const { root, rootKind, git, gitRoot } = findWorkspaceRoot(key, env);
- // Only the normalized form is kept. The raw URL may carry a token, and this
- // file outlives the process — writing it here would undo the care
- // `normalizeGitRemote` takes to drop userinfo.
- const remote = git ? normalizeGitRemote(readGitRemoteUrl(git.commonDir)) : "";
- const identity = {
- cwd: key,
- root,
- rootKind,
- isGit: Boolean(git),
- gitKind: git?.kind || "",
- gitCommonDir: git?.commonDir || "",
- gitRoot,
- remote,
- vars: {
- git_remote: sanitizePeerId(remote),
- // The enclosing repository's root, which is not the workspace root when a
- // marker file below it won. Empty outside a repository, so the `git`
- // preset resolves to nothing there rather than to a bare path.
- git_root: git ? legacySanitize(gitRoot) : "",
- cwd: legacySanitize(key),
- dir: root ? sanitizePeerId(root.split(/[/\\]/).filter(Boolean).pop() || "") : "",
- },
- };
- if (cache) writeCache(path, identity, now);
- return identity;
-}
diff --git a/examples/dsh-memory-plugin/shared/workspace-peer.mjs b/examples/dsh-memory-plugin/shared/workspace-peer.mjs
deleted file mode 100644
index 89df30793..000000000
--- a/examples/dsh-memory-plugin/shared/workspace-peer.mjs
+++ /dev/null
@@ -1,134 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Which peer a workspace writes its memories under.
- *
- * The peer used to be the working directory with every non-alphanumeric byte
- * turned into a dash, which made the identity an accident of where the
- * repository happened to sit: a clone on another machine, a rename, a worktree
- * or simply `cd examples/` each minted a separate, empty namespace. The default
- * is now git's own idea of the repository, so one project keeps one memory
- * wherever it is checked out.
- *
- * `peer.source` decides the rule. Presets cover the three answers most people
- * want; a template — or a list of templates tried in order — covers the rest.
- * The old behaviour is still one word away, byte for byte.
- */
-
-import { legacySanitize, resolveWorkspaceIdentity, sanitizePeerId } from "./workspace-identity.mjs";
-
-/**
- * `git` is the default, and it resolves only inside a repository: the remote
- * first, because that is the one name every clone agrees on, then the
- * repository root for a repo that has none. Anywhere else it resolves to
- * nothing and no peer is sent — a scratch folder or an app's per-task
- * directory would otherwise mint a fresh, empty namespace each time, so those
- * memories go to the user-level space instead. Naming such a directory is what
- * `peer.id` is for, and deriving one from a bare path is what `cwd` is for;
- * both are opt-in.
- *
- * No preset adds a prefix. A path-derived id starts with `-` on POSIX, so it
- * cannot collide with a remote-derived one; anyone who wants a prefix writes
- * their own template.
- */
-export const PEER_SOURCE_PRESETS = {
- git: ["{git_remote}", "{git_root}"],
- cwd: ["{cwd}"],
- none: [],
-};
-
-export const DEFAULT_PEER_SOURCE = "git";
-
-const VARIABLE_RE = /\{([a-z_]+)\}/g;
-
-export function deriveWorkspacePeerId(cwd) {
- return legacySanitize(cwd);
-}
-
-/**
- * Normalize `peer.source` — a preset name, a template, or a list — to templates.
- *
- * A bare string with no `{` is a misspelled preset, not a template: `Git` or
- * `gti` would otherwise become a peer literally named `Git`, quietly stranding
- * the workspace's memories in a namespace nobody meant to create. Such a value
- * warns and falls back to the default chain. An array is left alone — writing a
- * list is explicit enough to mean the constant it contains.
- */
-export function peerSourceTemplates(source, onWarn = null) {
- if (Array.isArray(source)) return source.map(String).filter(Boolean);
- const raw = String(source ?? "").trim();
- if (!raw) return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
- if (Object.hasOwn(PEER_SOURCE_PRESETS, raw)) return PEER_SOURCE_PRESETS[raw];
- if (raw.includes("{")) return [raw];
-
- const message = `OpenViking: ignored peer.source ${JSON.stringify(raw)}: it is neither a preset `
- + `(${Object.keys(PEER_SOURCE_PRESETS).join(", ")}) nor a template such as "team-{dir}". `
- + `Falling back to ${DEFAULT_PEER_SOURCE}.`;
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
-}
-
-/**
- * Substitute one template, or return "" when any variable it names is empty.
- *
- * All-or-nothing on purpose: a half-resolved template like `git-` would be a
- * silently shared identity, so an empty variable falls through to the next
- * template instead.
- */
-export function renderPeerTemplate(template, vars) {
- const text = String(template || "");
- if (!text) return "";
- let empty = false;
- const rendered = text.replace(VARIABLE_RE, (match, name) => {
- if (!Object.hasOwn(vars, name)) {
- empty = true;
- return "";
- }
- const value = String(vars[name] ?? "");
- if (!value) empty = true;
- return value;
- });
- return empty ? "" : rendered;
-}
-
-/**
- * The peer this process should send, and where it came from.
- *
- * `source` keeps its three values — call sites compare it against the literal
- * `"workspace"` to decide whether a session pin may be reused — while `origin`
- * names the template that actually produced the id, and `legacyPeerId` carries
- * the pre-git id whenever it differs, so recall can still reach memories
- * written under it.
- */
-export function resolveEffectivePeerId({ cfg = {}, cwd = "", identity = null, env = process.env, onWarn = null } = {}) {
- const explicit = String(cfg.peerId || "").trim();
- if (explicit) return { peerId: explicit, source: "explicit", origin: "explicit", legacyPeerId: "" };
-
- // `OPENVIKING_WORKSPACE_PEER=0` predates `peer.source` and still means "none".
- if (cfg.workspacePeer === false) return { peerId: "", source: "none", origin: "disabled", legacyPeerId: "" };
-
- const templates = peerSourceTemplates(cfg.peerSource, onWarn);
- if (!templates.length) return { peerId: "", source: "none", origin: "none", legacyPeerId: "" };
-
- // `harness` is composed here rather than in the identity, whose result is
- // cached on disk under a cwd-only key — two harnesses in one directory would
- // otherwise read each other's peer back out of that cache.
- const vars = {
- ...((identity || resolveWorkspaceIdentity({ cwd, env })).vars || {}),
- harness: sanitizePeerId(cfg.harness || cfg.clientId || ""),
- };
- const legacyPeerId = deriveWorkspacePeerId(cwd);
- for (const template of templates) {
- const peerId = renderPeerTemplate(template, vars);
- if (!peerId) continue;
- return {
- peerId,
- source: "workspace",
- origin: template,
- legacyPeerId: peerId === legacyPeerId ? "" : legacyPeerId,
- };
- }
- // No peer, but the pre-git id is still what earlier sessions in this
- // directory wrote under, so recall keeps reaching it.
- return { peerId: "", source: "none", origin: "unresolved", legacyPeerId };
-}
diff --git a/examples/dsh-memory-plugin/uri-guard.mjs b/examples/dsh-memory-plugin/uri-guard.mjs
index 145a969cc..701dc88c4 100644
--- a/examples/dsh-memory-plugin/uri-guard.mjs
+++ b/examples/dsh-memory-plugin/uri-guard.mjs
@@ -1,5 +1,5 @@
import { MCP_SERVER_NAME } from "./config.mjs";
-import { buildGuardMessage, findVikingUri } from "./shared/uri-guard.mjs";
+import { evaluateUriGuard } from "./shared/uri-guard.mjs";
/** Model-facing name of a bridged OpenViking MCP tool. */
const mcp = rawName => `mcp__${MCP_SERVER_NAME}__${rawName}`;
@@ -37,17 +37,9 @@ const GUARDED_TOOLS = {
};
export async function guardVikingUri(exec, next) {
- const hint = GUARDED_TOOLS[exec.name];
- if (!hint) return next();
- const uri = findVikingUri(exec.arguments);
- if (!uri) return next();
- return {
- kind: "deny",
- reason: buildGuardMessage(uri, {
- tool: hint.tool,
- example: hint.example(uri, exec.arguments),
- }),
- };
+ const decision = evaluateUriGuard(exec.name, exec.arguments, { hints: GUARDED_TOOLS });
+ if (!decision) return next();
+ return { kind: "deny", reason: decision.reason };
}
function escapeText(value) {
diff --git a/examples/memory-plugin-shared/README.md b/examples/memory-plugin-shared/README.md
index 7afde5000..e33b04908 100644
--- a/examples/memory-plugin-shared/README.md
+++ b/examples/memory-plugin-shared/README.md
@@ -1,7 +1,12 @@
# Memory Plugin Shared Library
-This directory contains shared JavaScript modules that are vendored into the
-Claude Code, Codex, OpenCode, and pi memory plugins by `sync.mjs`.
+For contributor guidance on adding and maintaining hook + MCP integrations, see the [Agent plugin development and maintenance standard](../../docs/en/agent-integrations/18-plugin-development.md) ([中文](../../docs/zh/agent-integrations/18-plugin-development.md)). When using a coding agent, have it read and follow this standard before making changes.
+
+This directory contains shared JavaScript modules. `sync.mjs` vendors each module into the plugins whose code imports it — Claude Code, Codex, OpenCode, dsh, pi, openclaw and the bundled `agent-plugins` servers — together with the matching `lib/*.d.mts` declaration for the targets written in TypeScript. cursor, trae, trae-cn and zcode vendor nothing: the installer copies the modules `lib/MANIFEST` names — the same sync writes it — to `$OV_HOME/agent-integrations/memory-plugin-shared/lib`, and they import it from there.
+
+`lib/install/` is the exception: it holds the installer's own JavaScript — the JSONC editor OpenCode's config needs and the hooks/mcp merge cursor, trae, trae-cn and zcode install through — which runs from `install.sh` and never from a hook. No shared module imports it, so it stays out of every closure and out of `lib/MANIFEST`.
+
+When the copies are made follows how the plugin is delivered. Claude Code, Codex and `agent-plugins` are installed by pointing a host at a directory in this repository, so their copies are committed and a push to main regenerates them. OpenCode, dsh and openclaw publish as npm packages and pi is tarred by the installer, so those build their copies at pack time and keep none in git — run `node examples/memory-plugin-shared/sync.mjs` once in a fresh checkout before running their tests.
> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
@@ -36,7 +41,7 @@ Every clone of one repository therefore shares one peer: project memory follows
Resolution order is:
-1. Explicit peer: `OPENVIKING_PEER_ID`, `peer.id` in a workspace layer, `actor_peer_id` / `peer_id` in `ovcli.conf`, or the harness-specific legacy peer config.
+1. Explicit peer: `OPENVIKING_PEER_ID`, then `peer.id` in a workspace layer or `peerId` in `ovcli.conf`'s `plugin` section, then `actor_peer_id` / `peer_id` in `ovcli.conf`, then the harness's own section of `ov.conf`.
2. The peer derived by `peer.source`, when `workspacePeer` is not `false`.
3. No peer.
@@ -68,9 +73,13 @@ mode so one person's memories are not recalled into another person's session.
4. `.openviking/config.json`
5. `ovcli.conf` `plugin.<harness>`
6. `ovcli.conf` `plugin`
-7. the harness block in `ov.conf` (legacy)
+7. the block in `ov.conf` named after the harness (legacy). Both its credential fields and its tuning knobs reach every harness, and for dsh it sits under the settings the cordis host hands the plugin
8. built-in defaults
+Every harness resolves every knob through that order: claude-code, codex, cursor, trae, trae-cn, zcode, opencode, dsh and pi. One `plugin` section therefore configures all of them, and `ov config switch` moves behaviour along with credentials. Inside `plugin`, a per-harness override is found under either spelling of the harness name, so `claude_code` and `claude-code`, `trae_cn` and `trae-cn` both reach the same object.
+
+The knobs themselves are declared once in `lib/config-schema.mjs`, with each one's type, default, range, `OPENVIKING_*` variable and older spellings. An older spelling keeps working: `syncTurns` sets `autoCapture`, `bypassPatterns` sets `bypassSessionPatterns`, `recallRewrite` sets `recallCompress`, `requestTimeoutMs` sets `timeoutMs`, `recallBudget` sets `recallTokenBudget`, `recallScoreThreshold` sets `scoreThreshold`, `recallMinQueryLength` sets `minQueryLength`, `profileBudget` sets `profileTokenBudget`, `recallCompressReasoningEffort` sets `recallCompressThinking`, `auth_mode` sets `authMode`, and `peer_id` sets `peerId`.
+
Every file declares `version: 1`; one declaring another version is skipped with a warning. Schema v1 is `peer.source`, `peer.id`, `recall.enabled`, `recall.peer_scope`, `recall.dedup_turns`, `recall.max_items`, `recall.score_threshold`, `capture.enabled`, `capture.commit_token_threshold`, `bypass.session_patterns`, and `labels`. Lists union across layers, and a leading `"!reset"` clears what was inherited. Unknown keys are kept and ignored.
Workspace files are trusted without a prompt: a hook is non-interactive, and an approval gate would degrade into one command per workspace. What is refused instead is structural — connection and credential keys (`url`, `api_key`, `account`, `user`, `extra_headers`, …) are stripped with a warning and `${VAR}` is never expanded in these files. What a committed file switches off is announced in `ov-memory-doctor` rather than blocked.
diff --git a/examples/memory-plugin-shared/agent-hook-runtime.test.mjs b/examples/memory-plugin-shared/agent-hook-runtime.test.mjs
index 8845403eb..e1bae1338 100644
--- a/examples/memory-plugin-shared/agent-hook-runtime.test.mjs
+++ b/examples/memory-plugin-shared/agent-hook-runtime.test.mjs
@@ -1,11 +1,66 @@
import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { filterCaptureTurns } from "./lib/capture-utils.mjs";
+import { expectExit, runHookScript, withMockOpenViking, writeJson } from "./testing/support.mjs";
import {
commitAgentSession,
+ loadAgentHookConfig,
makeAgentFetchJSON,
+ resolveNativeSessionId,
+ runHookStage,
} from "./lib/agent-hook-runtime.mjs";
+test("disabled Claude Code and Codex hooks make no requests or session writes", async (t) => {
+ const home = mkdtempSync(join(tmpdir(), "ov-disabled-hooks-"));
+ try {
+ const cli = join(home, "ovcli.conf");
+ writeFileSync(cli, JSON.stringify({ plugin: { enabled: false, skillExperience: true } }));
+ const transcript = join(home, "transcript.jsonl");
+ writeFileSync(transcript, JSON.stringify({ payload: { message: { role: "user", content: "remember disabled hooks" } } }));
+ await withMockOpenViking((_req, res) => writeJson(res, { status: "ok", result: {} }), async (baseUrl, requests) => {
+ for (const plugin of ["claude-code-memory-plugin", "codex-memory-plugin"]) {
+ const root = new URL(`../${plugin}/`, import.meta.url);
+ const manifest = JSON.parse(readFileSync(new URL("hooks/hooks.json", root), "utf-8"));
+ for (const [event, entries] of Object.entries(manifest.hooks)) {
+ if (event === "PreToolUse") continue; // URI guard has no memory I/O.
+ const script = entries[0].hooks[0].command.split("scripts/")[1].replaceAll('"', '');
+ await t.test(`${plugin} ${event}`, async () => {
+ requests.length = 0;
+ const before = readdirSync(home, { recursive: true }).sort();
+ const result = expectExit(await runHookScript(fileURLToPath(new URL(`scripts/${script}`, root)), {
+ cwd: home,
+ input: { session_id: "disabled", agent_id: "child", source: "startup", cwd: home, prompt: "remember disabled hooks", transcript_path: transcript },
+ env: {
+ ...Object.fromEntries(Object.keys(process.env).filter((key) => key.startsWith("OPENVIKING_")).map((key) => [key, undefined])),
+ HOME: home,
+ TMPDIR: home,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_CLI_CONFIG_FILE: cli,
+ OPENVIKING_CONFIG_FILE: join(home, "missing.conf"),
+ OPENVIKING_URL: baseUrl,
+ OPENVIKING_WRITE_PATH_ASYNC: "0",
+ OPENVIKING_RECALL_COMPRESS: "off",
+ OV_HOOK_WORKER: "1",
+ },
+ }));
+ assert.doesNotThrow(() => JSON.parse(result.stdout));
+ assert.deepEqual(requests, []);
+ assert.deepEqual(readdirSync(home, { recursive: true }).sort(), before);
+ });
+ }
+ }
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+});
+
function jsonResponse(status, value) {
return new Response(JSON.stringify(value), {
status,
@@ -78,3 +133,303 @@ test("agent fetch and commit logging preserve response trace_id", async (t) => {
},
});
});
+
+/**
+ * Reporting a write no retry can fix used to be Claude Code's alone; the
+ * harnesses on this runtime inherited it along with the write path, so what
+ * they say and when they say it is pinned here rather than in one host.
+ */
+test("a failed write is parked when a retry can help and reported once when it cannot", async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-agent-hook-pending-"));
+ const savedPendingDir = process.env.OPENVIKING_PENDING_DIR;
+ const warnings = [];
+ try {
+ process.env.OPENVIKING_PENDING_DIR = join(dir, "pending");
+ const responses = [
+ jsonResponse(503, { status: "error", error: { code: "UNAVAILABLE", message: "restarting" } }),
+ jsonResponse(400, { status: "error", error: { code: "INVALID", message: "bad payload" } }),
+ ];
+ t.mock.method(globalThis, "fetch", async () => responses.shift());
+ t.mock.method(process.stderr, "write", (chunk) => {
+ warnings.push(String(chunk));
+ return true;
+ });
+ const { fetchJSON } = makeAgentFetchJSON({
+ baseUrl: "http://127.0.0.1:1933",
+ timeoutMs: 5000,
+ });
+
+ const retryable = await commitAgentSession(fetchJSON, "agent-pending-retryable");
+ assert.equal(retryable.pendingQueued, true, "a retryable failure is parked for replay");
+ assert.deepEqual(warnings, [], "a parked write is not something to warn about");
+
+ const fatal = await commitAgentSession(fetchJSON, "agent-pending-fatal");
+ assert.equal(fatal.pendingQueued, undefined);
+ assert.equal(fatal.pendingEnqueueFailed, undefined);
+ assert.deepEqual(warnings, [
+ "[ov] commitSession failed with non-retryable status 400;"
+ + " not enqueuing pending retry (bad payload)\n",
+ ]);
+ } finally {
+ if (savedPendingDir === undefined) delete process.env.OPENVIKING_PENDING_DIR;
+ else process.env.OPENVIKING_PENDING_DIR = savedPendingDir;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// The thin harnesses composed on this runtime used to send whatever their
+// transcript parser produced. Every other harness runs the same filter, so it
+// belongs beside the runtime rather than reimplemented in each hook.
+test("the shared capture filter drops the turns no harness wants to remember", () => {
+ const { kept, dropped } = filterCaptureTurns([
+ { role: "user", content: "/compact" },
+ { role: "assistant", content: "ok" },
+ { role: "user", content: "..." },
+ { role: "assistant", content: "[openviking-memory] recalled 3 items" },
+ { role: "user", content: "the retry budget is three attempts" },
+ ], { captureMaxLength: 24000 });
+
+ assert.deepEqual(kept.map((turn) => turn.content), ["the retry budget is three attempts"]);
+ assert.deepEqual(dropped.map((turn) => turn.reason), [
+ "slash_command", "ack", "punctuation", "plugin_status",
+ ]);
+});
+
+test("a turn past captureMaxLength is capped rather than dropped", () => {
+ const long = "remember this detail. ".repeat(200);
+ const { kept, dropped } = filterCaptureTurns(
+ [{ role: "user", content: long }],
+ { captureMaxLength: 200 },
+ );
+
+ assert.equal(dropped.length, 0);
+ assert.ok(kept[0].content.length < long.length, "the turn must reach the extractor capped");
+ assert.ok(kept[0].content.startsWith("remember this detail."));
+});
+
+test("filterCaptureTurns tolerates a missing or malformed turn list", () => {
+ for (const input of [undefined, null, "text", 3, {}]) {
+ assert.deepEqual(filterCaptureTurns(input), { kept: [], dropped: [] });
+ }
+});
+
+/**
+ * cursor, trae, trae-cn and zcode read the environment and nothing else before
+ * this: an `ovcli.conf` `plugin` entry named after them was inert, and a
+ * workspace file could not reach them at all. Assert the whole stack lands,
+ * because none of these four has a config test of its own.
+ */
+test("the thin harnesses resolve the same layers as everyone else", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-agent-hook-config-"));
+ const workspace = join(dir, "workspace");
+ const saved = {
+ cli: process.env.OPENVIKING_CLI_CONFIG_FILE,
+ home: process.env.OPENVIKING_HOME,
+ limit: process.env.OPENVIKING_RECALL_LIMIT,
+ };
+ try {
+ mkdirSync(join(workspace, ".openviking"), { recursive: true });
+ mkdirSync(join(workspace, ".git"), { recursive: true });
+ writeFileSync(join(dir, "ovcli.conf"), JSON.stringify({
+ url: "http://127.0.0.1:1933",
+ plugin: {
+ recallLimit: 7,
+ cursor: { captureMode: "keyword" },
+ "trae-cn": { scoreThreshold: 0.8 },
+ zcode: { autoRecall: false },
+ },
+ }));
+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf");
+ // Keeps the identity cache and the workspace registry out of the real home.
+ process.env.OPENVIKING_HOME = join(dir, "home");
+ delete process.env.OPENVIKING_RECALL_LIMIT;
+
+ const cursor = loadAgentHookConfig("cursor", workspace);
+ assert.equal(cursor.recallLimit, 7, "the shared plugin section applies");
+ assert.equal(cursor.captureMode, "keyword", "the per-harness override applies");
+ assert.equal(cursor.autoRecall, true, "another harness's override does not");
+ assert.equal(loadAgentHookConfig("zcode", workspace).autoRecall, false);
+ // The hyphenated spelling of a harness finds the same override.
+ assert.equal(loadAgentHookConfig("trae-cn", workspace).scoreThreshold, 0.8);
+ assert.equal(loadAgentHookConfig("trae", workspace).scoreThreshold, 0.35);
+
+ // A workspace file outranks ovcli.conf, and the environment outranks both.
+ writeFileSync(
+ join(workspace, ".openviking", "config.json"),
+ JSON.stringify({ version: 1, recall: { max_items: 4 }, capture: { enabled: false } }),
+ );
+ const pinned = loadAgentHookConfig("cursor", workspace);
+ assert.equal(pinned.recallLimit, 4);
+ assert.equal(pinned.autoCapture, false);
+
+ process.env.OPENVIKING_RECALL_LIMIT = "2";
+ assert.equal(loadAgentHookConfig("cursor", workspace).recallLimit, 2);
+
+ // And a directory with neither file keeps the ovcli.conf answer.
+ assert.equal(loadAgentHookConfig("cursor", dir).recallLimit, 2);
+ } finally {
+ for (const [key, value] of [
+ ["OPENVIKING_CLI_CONFIG_FILE", saved.cli],
+ ["OPENVIKING_HOME", saved.home],
+ ["OPENVIKING_RECALL_LIMIT", saved.limit],
+ ]) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+/**
+ * `plugin.<harness>.apiKey` was inert on these four: the credential chain never
+ * reads the `plugin` section, so its empty answer used to overwrite the one the
+ * settings layers had already found.
+ */
+test("an ovcli.conf plugin key reaches a thin harness when nothing else supplies one", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-agent-hook-key-"));
+ const overrides = [
+ "OPENVIKING_CLI_CONFIG_FILE",
+ "OPENVIKING_CONFIG_FILE",
+ "OPENVIKING_HOME",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_CREDENTIAL_SOURCE",
+ "OPENVIKING_CREDENTIALS_SOURCE",
+ ];
+ const saved = Object.fromEntries(overrides.map((key) => [key, process.env[key]]));
+ try {
+ for (const key of overrides) delete process.env[key];
+ writeFileSync(join(dir, "ovcli.conf"), JSON.stringify({
+ url: "http://127.0.0.1:1933",
+ plugin: { cursor: { apiKey: "sk-plugin-cursor" } },
+ }));
+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf");
+ process.env.OPENVIKING_CONFIG_FILE = join(dir, "ov.conf");
+ process.env.OPENVIKING_HOME = join(dir, "home");
+
+ assert.equal(loadAgentHookConfig("cursor", dir).apiKey, "sk-plugin-cursor");
+ assert.equal(loadAgentHookConfig("trae", dir).apiKey, "", "another harness's key stays its own");
+ } finally {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+/**
+ * Every Claude Code and Codex hook entry opens the same way, and the copies
+ * drifted: some re-read the config for the payload's directory, some gated
+ * against the hook process's own. `runHookStage` is that opening.
+ */
+async function stageRun({ raw = "{}", cfg = {}, input = {}, ...rest } = {}, run = () => undefined) {
+ const seen = { cwds: [], skips: [], skipStages: [], envelopes: [] };
+ const value = await runHookStage({
+ loadConfig: (cwd) => {
+ seen.cwds.push(cwd);
+ return { ...cfg, cwd };
+ },
+ input: { read: async () => raw, ...input },
+ envelope: (envelope) => seen.envelopes.push(envelope),
+ onSkip: (reason, stage) => { seen.skips.push(reason); seen.skipStages.push(stage); },
+ ...rest,
+ }, run);
+ return { seen, value };
+}
+
+test("the hook stage reloads the config for the payload's directory", async () => {
+ const stages = [];
+ const { seen, value } = await stageRun(
+ { raw: JSON.stringify({ session_id: "s1", cwd: "/w/one" }), cfg: { autoCapture: true } },
+ async (stage) => { stages.push(stage); return "captured 1 turn"; },
+ );
+
+ assert.equal(value, "captured 1 turn");
+ assert.deepEqual(seen.cwds, ["/w/one"]);
+ assert.equal(stages[0].cfg.cwd, "/w/one");
+ assert.equal(stages[0].sessionId, "s1");
+ assert.equal(stages[0].bypassed, false);
+ assert.deepEqual(seen.envelopes, ["captured 1 turn"], "the callback's value is the envelope");
+});
+
+test("a closed gate answers with an empty envelope and never runs the callback", async () => {
+ const payload = JSON.stringify({ session_id: "s1", cwd: "/w" });
+ const cases = [
+ ["bad_stdin", { raw: "{not json" }],
+ ["disabled", { raw: payload, gates: { enabled: (cfg) => cfg.autoRecall } }],
+ ["bypass", { raw: payload, cfg: { bypassSession: true } }],
+ ];
+ for (const [reason, options] of cases) {
+ let ran = false;
+ const { seen, value } = await stageRun(options, () => { ran = true; });
+
+ assert.equal(value, undefined);
+ assert.equal(ran, false, `${reason} must not reach the callback`);
+ assert.deepEqual(seen.skips, [reason]);
+ assert.deepEqual(seen.envelopes, [undefined]);
+ // Every skip hands back the same stage, so an entry that records one does
+ // not have to know which gate closed to read the payload off it.
+ assert.deepEqual(
+ Object.keys(seen.skipStages[0]).sort(),
+ ["bypassed", "cfg", "cwd", "emit", "input", "raw", "sessionId"],
+ `${reason} passes the stage`,
+ );
+ }
+});
+
+test("a tolerant reader carries on with an empty payload", async () => {
+ const { seen, value } = await stageRun(
+ { raw: "{not json", input: { tolerant: true } },
+ async ({ input }) => (Object.keys(input).length === 0 ? "empty" : "payload"),
+ );
+
+ assert.equal(value, "empty");
+ assert.deepEqual(seen.skips, []);
+});
+
+test("a bypassed session still reaches a callback that turned the gate off", async () => {
+ const stages = [];
+ const { seen } = await stageRun(
+ {
+ raw: JSON.stringify({ session_id: "s1", cwd: "/w" }),
+ cfg: { bypassSession: true },
+ gates: { bypass: () => false },
+ },
+ async (stage) => { stages.push(stage); },
+ );
+
+ assert.equal(stages[0].bypassed, true, "the verdict is still on the stage");
+ assert.deepEqual(seen.skips, []);
+});
+
+/**
+ * The thin harnesses spell the session id four ways, so the gate that reads it
+ * has to be given their resolver rather than switched off and rebuilt inside
+ * the callback.
+ */
+test("a host resolver decides which session the bypass gate is looking at", async () => {
+ const options = {
+ raw: JSON.stringify({ conversation_id: "scratch-123", cwd: "/w" }),
+ cfg: { bypassSessionPatterns: ["scratch-*"] },
+ };
+
+ const narrow = await stageRun(options, () => "ran");
+ assert.equal(narrow.value, "ran", "the default lookup never sees conversation_id");
+
+ const resolved = await stageRun({ ...options, sessionId: resolveNativeSessionId }, () => "ran");
+ assert.equal(resolved.value, undefined);
+ assert.deepEqual(resolved.seen.skips, ["bypass"]);
+ assert.equal(resolved.seen.skipStages[0].sessionId, "scratch-123");
+});
+
+test("the envelope is written once when the callback answers early", async () => {
+ const { seen } = await stageRun(
+ { raw: JSON.stringify({ session_id: "s1", cwd: "/w" }) },
+ async ({ emit }) => { emit("detached"); return "worker value"; },
+ );
+
+ assert.deepEqual(seen.envelopes, ["detached"]);
+});
diff --git a/examples/memory-plugin-shared/capture-utils.test.mjs b/examples/memory-plugin-shared/capture-utils.test.mjs
index d0f310396..7a2fd4d2e 100644
--- a/examples/memory-plugin-shared/capture-utils.test.mjs
+++ b/examples/memory-plugin-shared/capture-utils.test.mjs
@@ -1,12 +1,21 @@
import test from "node:test"
import assert from "node:assert/strict"
import {
+ collectToolNamesByIdFromEntries,
extractCaptureTurns,
extractPartsFromPayload,
+ findLastHumanTurnIndex,
filterCaptureParts,
+ sanitizeCapturedText,
shouldCaptureText,
} from "./lib/capture-utils.mjs"
+const CAPTURE_CONFIG = {
+ captureAssistantTurns: true,
+ captureToolMaxChars: 1000000,
+ captureMaxLength: 24000,
+}
+
function toolPart(parts) {
return parts.find((part) => part?.type === "tool")
}
@@ -63,6 +72,119 @@ test("toolStatus stays completed for a successful camelCase result", () => {
assert.equal(toolPart(parts).tool_status, "completed")
})
+test("a tool result is labelled with the name of the call it answers", () => {
+ const entries = [
+ { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "Read", input: {} }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", output: "ok" }] },
+ ]
+ const parts = extractPartsFromPayload(entries[1], {
+ toolNameById: collectToolNamesByIdFromEntries(entries),
+ })
+ assert.equal(toolPart(parts).tool_name, "Read")
+})
+
+test("a host system reminder is not part of the conversation", () => {
+ assert.equal(
+ sanitizeCapturedText("before\n<system-reminder>never store this</system-reminder>\nafter"),
+ "before\n\nafter",
+ )
+})
+
+test("a subagent context line is not part of the conversation", () => {
+ assert.equal(
+ sanitizeCapturedText("[Subagent Context] parent session cc-1\nthe real question"),
+ "the real question",
+ )
+})
+
+test("a turn that is only a system reminder never reaches the extractor", () => {
+ const decision = shouldCaptureText(
+ "<system-reminder>the user opened a new file</system-reminder>",
+ "user",
+ )
+ assert.equal(decision.shouldCapture, false)
+ assert.equal(decision.reason, "empty")
+})
+
+test("findLastHumanTurnIndex skips tool results mapped onto the user role", () => {
+ const turns = extractCaptureTurns(
+ [
+ { payload: { message: { role: "user", content: "compacted historical summary" } } },
+ { payload: { message: { role: "user", content: "current user request" } } },
+ { payload: { type: "function_call", id: "call-1", name: "shell", arguments: "{}" } },
+ { payload: { type: "function_call_output", call_id: "call-1", output: "tool result" } },
+ { payload: { message: { role: "assistant", content: "current assistant response" } } },
+ ],
+ CAPTURE_CONFIG,
+ )
+
+ const index = findLastHumanTurnIndex(turns)
+ assert.equal(turns[index].text, "current user request")
+ assert.equal(turns.at(-2).role, "user")
+ assert.equal(turns.at(-2).parts[0].type, "tool")
+})
+
+test("findLastHumanTurnIndex reports -1 when no human turn survives", () => {
+ const turns = extractCaptureTurns(
+ [
+ { payload: { type: "function_call", id: "call-1", name: "shell", arguments: "{}" } },
+ { payload: { type: "function_call_output", call_id: "call-1", output: "tool result" } },
+ { payload: { message: { role: "assistant", content: "assistant only" } } },
+ ],
+ CAPTURE_CONFIG,
+ )
+
+ assert.equal(findLastHumanTurnIndex(turns), -1)
+ assert.equal(findLastHumanTurnIndex([]), -1)
+})
+
+/**
+ * Claude Code and Codex each wrap this module in an adapter that reads their
+ * own transcript shape and exports it under the same name. `export *` beside a
+ * same-named local export lets the local one win with no diagnostic, so a
+ * reader of the import cannot tell which function they hold; these two are the
+ * adapters, and the shared names beside them are the shared ones. Each adapter
+ * re-exports from its own vendored copy of this module, so the comparison is
+ * against that copy rather than against lib/.
+ */
+test("the Claude Code adapter is the extractCaptureTurns its callers import", async () => {
+ const cc = await import("../claude-code-memory-plugin/scripts/cc-transcript.mjs")
+ const vendored = await import("../claude-code-memory-plugin/scripts/shared/capture-utils.mjs")
+
+ assert.notEqual(cc.extractCaptureTurns, vendored.extractCaptureTurns)
+ assert.equal(cc.sanitizeCapturedText, vendored.sanitizeCapturedText)
+
+ // Claude nests a tool result in a content array; only the adapter flattens it.
+ const anthropic = [{
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "tool_result", tool_use_id: "t1", content: [{ type: "text", text: "tool output" }] }],
+ },
+ }]
+ assert.equal(cc.extractCaptureTurns(anthropic, CAPTURE_CONFIG)[0].parts[0].tool_output, "tool output")
+ assert.equal(
+ vendored.extractCaptureTurns(anthropic, CAPTURE_CONFIG)[0].parts[0].tool_output,
+ JSON.stringify([{ type: "text", text: "tool output" }]),
+ )
+})
+
+test("the Codex adapter is the extractCaptureTurns its callers import", async () => {
+ const codex = await import("../codex-memory-plugin/scripts/capture-utils.mjs")
+ const vendored = await import("../codex-memory-plugin/scripts/shared/capture-utils.mjs")
+
+ assert.notEqual(codex.extractCaptureTurns, vendored.extractCaptureTurns)
+ assert.equal(codex.findLastHumanTurnIndex, vendored.findLastHumanTurnIndex)
+
+ // Codex's newer tool events carry no role at all until the adapter maps them.
+ const rollout = [
+ { type: "response_item", payload: { type: "custom_tool_call", call_id: "c1", name: "shell", input: "ls" } },
+ { type: "response_item", payload: { type: "custom_tool_call_output", call_id: "c1", output: "file.txt" } },
+ ]
+ assert.equal(codex.extractCaptureTurns(rollout, CAPTURE_CONFIG).length, 2)
+ assert.deepEqual(extractCaptureTurns(rollout, CAPTURE_CONFIG), [])
+})
+
const TOOL_PART = { type: "tool", tool_name: "bash", tool_input: "ls" }
function userEntry(text) {
diff --git a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs b/examples/memory-plugin-shared/credentials.test.mjs
similarity index 57%
rename from examples/codex-memory-plugin/scripts/ov-credentials.test.mjs
rename to examples/memory-plugin-shared/credentials.test.mjs
index b45972474..b06ff608a 100644
--- a/examples/codex-memory-plugin/scripts/ov-credentials.test.mjs
+++ b/examples/memory-plugin-shared/credentials.test.mjs
@@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { resolveOpenVikingCredentials } from "./ov-credentials.mjs";
+import { resolveOpenVikingCredentials } from "./lib/credentials.mjs";
async function tempJson(prefix, value) {
const dir = await mkdtemp(join(tmpdir(), prefix));
@@ -118,3 +118,73 @@ test("credentialPath names the file that supplied the api_key", async () => {
await rm(dir, { recursive: true, force: true });
}
});
+
+test("each harness reads its own ov.conf section, not codex's", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ov-creds-harness-"));
+ const ovPath = join(dir, "ov.conf");
+ await writeFile(ovPath, JSON.stringify({
+ server: { root_api_key: "root-key" },
+ codex: { apiKey: "sk-codex", accountId: "acct-codex", userId: "user-codex", peerId: "peer-codex" },
+ opencode: { apiKey: "sk-opencode", accountId: "acct-opencode", userId: "user-opencode", peerId: "peer-opencode" },
+ trae_cn: { apiKey: "sk-trae-cn" },
+ }));
+ const env = {
+ OPENVIKING_CONFIG_FILE: ovPath,
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "absent-ovcli.conf"),
+ };
+ try {
+ const codex = resolveOpenVikingCredentials(env);
+ assert.equal(codex.apiKey, "sk-codex");
+ assert.equal(codex.account, "acct-codex");
+ assert.equal(codex.user, "user-codex");
+ assert.equal(codex.peerId, "peer-codex");
+
+ const opencode = resolveOpenVikingCredentials(env, "opencode");
+ assert.equal(opencode.apiKey, "sk-opencode");
+ assert.equal(opencode.account, "acct-opencode");
+ assert.equal(opencode.user, "user-opencode");
+ assert.equal(opencode.peerId, "peer-opencode");
+
+ // Either spelling of a harness name reaches the snake_case section.
+ assert.equal(resolveOpenVikingCredentials(env, "trae-cn").apiKey, "sk-trae-cn");
+
+ // A harness with no section of its own inherits nothing from codex's; the
+ // chain carries on to server.root_api_key as it always did.
+ const cursor = resolveOpenVikingCredentials(env, "cursor");
+ assert.equal(cursor.apiKey, "root-key");
+ assert.equal(cursor.account, "");
+ assert.equal(cursor.user, "");
+ assert.equal(cursor.peerId, "");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("ovcli.conf still outranks the harness section, which outranks the root key", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ov-creds-order-"));
+ const ovPath = join(dir, "ov.conf");
+ const cliPath = join(dir, "ovcli.conf");
+ await writeFile(ovPath, JSON.stringify({
+ server: { root_api_key: "root-key" },
+ opencode: { apiKey: "sk-opencode", peerId: "peer-opencode" },
+ }));
+ await writeFile(cliPath, JSON.stringify({ url: "http://127.0.0.1:1933", actor_peer_id: "cli-peer" }));
+ const env = { OPENVIKING_CONFIG_FILE: ovPath, OPENVIKING_CLI_CONFIG_FILE: cliPath };
+ try {
+ // ovcli.conf carries credential fields, so this is the pinned-file mode:
+ // ov.conf is not consulted at all and the harness section stays out.
+ const pinned = resolveOpenVikingCredentials(env, "opencode");
+ assert.equal(pinned.credentialSource, "ovcli");
+ assert.equal(pinned.apiKey, "");
+ assert.equal(pinned.peerId, "cli-peer");
+
+ // With ovcli.conf holding tuning only, the harness section supplies the key
+ // and still sits ahead of server.root_api_key.
+ await writeFile(cliPath, JSON.stringify({ plugin: { recallCompress: "off" } }));
+ const layered = resolveOpenVikingCredentials(env, "opencode");
+ assert.equal(layered.apiKey, "sk-opencode");
+ assert.equal(layered.credentialPath, ovPath);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/memory-plugin-shared/doctor-core.test.mjs b/examples/memory-plugin-shared/doctor-core.test.mjs
index f62a9e8d0..8f8cd4311 100644
--- a/examples/memory-plugin-shared/doctor-core.test.mjs
+++ b/examples/memory-plugin-shared/doctor-core.test.mjs
@@ -1,8 +1,9 @@
import assert from "node:assert/strict";
-import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
+import { fileURLToPath } from "node:url";
import {
assessProbes,
@@ -10,6 +11,7 @@ import {
checkWorkspace,
classifyFetchError,
createReport,
+ credentialSources,
describeApiKey,
inspectJsonFile,
lintBaseUrl,
@@ -158,6 +160,18 @@ test("lintServerConf flags the plugin-only ov.conf keys a server refuses to star
assert.deepEqual(lintServerConf(null), []);
});
+test("lintServerConf covers every harness, not just the two with a legacy ov.conf layer", () => {
+ const findings = lintServerConf({ cursor: {}, pi: {} });
+ assert.deepEqual(
+ findings.map((f) => f.level),
+ ["warn", "warn"],
+ );
+ assert.match(findings[0].message, /'cursor' block/);
+ assert.match(findings[0].fix, /ovcli\.conf plugin\.cursor/);
+ assert.match(findings[1].message, /'pi' block/);
+ assert.match(findings[1].fix, /ovcli\.conf plugin\.pi/);
+});
+
test("assessReady interprets the readiness checks", () => {
const ok = { ok: true, status: 200, json: { status: "ready", checks: { agfs: { status: "ok", checks: { filesystem: "ok", multiwrite_sync: "not_supported" } }, vectordb: "ok", api_key_manager: "not_configured", embedding: "ok", ollama: "not_configured" } } };
let report = createReport();
@@ -220,3 +234,160 @@ test("checkWorkspace tells a directory that is no workspace what to create", ()
assert.equal(found.rootKind, "config");
assert.match(marked.render(), /workspace {2}/);
});
+
+// `min_client_version` warns and never blocks, so the only way it can be wrong
+// is by never being read: every loader used to leave the client version behind.
+test("checkWorkspace warns when the workspace asks for a newer client", () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "ov-doctor-minver-")));
+ const env = { HOME: "/nonexistent-home", OPENVIKING_STATE_DIR: join(dir, ".state") };
+ mkdirSync(join(dir, ".openviking"), { recursive: true });
+ writeFileSync(
+ join(dir, ".openviking", "config.json"),
+ '{"version":1,"min_client_version":"9.9.9","peer":{"id":"demo"}}',
+ );
+
+ const quiet = createReport();
+ checkWorkspace(quiet, { cwd: dir, env });
+ assert.ok(!quiet.render().includes("asks for OpenViking plugin"), "no version, no verdict");
+
+ const warned = createReport();
+ checkWorkspace(warned, { cwd: dir, env, clientVersion: "0.1.0" });
+ assert.match(warned.render(), /asks for OpenViking plugin 9\.9\.9 and this one is 0\.1\.0/);
+});
+
+test("no doctor wrapper redefines a name doctor-core already exports", () => {
+ const read = (rel) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf-8");
+ const exported = new Set(
+ [...read("./lib/doctor-core.mjs").matchAll(/^export (?:async function|function|const) (\w+)/gm)].map((m) => m[1]),
+ );
+ assert.ok(exported.has("runDoctor"));
+ assert.ok(exported.has("inspectConfigFiles"));
+ for (const rel of [
+ "../claude-code-memory-plugin/scripts/ov-memory-doctor.mjs",
+ "../codex-memory-plugin/scripts/ov-memory-doctor.mjs",
+ "../agent-hook-plugin/scripts/ov-memory-doctor.mjs",
+ ]) {
+ const declared = [...read(rel).matchAll(/^(?:export )?(?:async function|function|const) (\w+)\s*[(=]/gm)].map((m) => m[1]);
+ const clashes = declared.filter((name) => exported.has(name));
+ assert.deepEqual(clashes, [], `${rel} redeclares doctor-core exports: ${clashes.join(", ")}`);
+ }
+});
+
+const CLI_PATH = "/nowhere/.openviking/ovcli.conf";
+const OV_PATH = "/nowhere/.openviking/ov.conf";
+const cliConf = (data) => ({ ok: true, path: CLI_PATH, data });
+const ovConf = (data) => ({ ok: true, path: OV_PATH, data });
+
+const CREDENTIAL_ENV = [
+ "OPENVIKING_URL",
+ "OPENVIKING_BASE_URL",
+ "OPENVIKING_API_KEY",
+ "OPENVIKING_BEARER_TOKEN",
+ "OPENVIKING_ACCOUNT",
+ "OPENVIKING_USER",
+];
+
+function withEnv(vars, fn) {
+ const saved = Object.fromEntries(CREDENTIAL_ENV.map((key) => [key, process.env[key]]));
+ try {
+ for (const key of CREDENTIAL_ENV) delete process.env[key];
+ Object.assign(process.env, vars);
+ return fn();
+ } finally {
+ for (const key of CREDENTIAL_ENV) {
+ if (saved[key] === undefined) delete process.env[key];
+ else process.env[key] = saved[key];
+ }
+ }
+}
+
+/**
+ * These labels are what a user reads when the key is not the one they meant, so
+ * they have to describe the chain that actually ran — which is why the key's
+ * layer comes off the config rather than being walked a second time here.
+ */
+test("credentialSources names the field inside the layer the chain reported", () => {
+ const cli = cliConf({
+ url: "http://cli:1933",
+ plugin: { claude_code: { apiKey: "sk-plugin-cc" }, apiKey: "sk-plugin" },
+ });
+ const ov = ovConf({
+ server: { url: "http://ov:1933", root_api_key: "sk-root" },
+ claude_code: { apiKey: "sk-section" },
+ });
+ const label = (cfg, files = cli) => credentialSources(
+ { harness: "claude-code", ...cfg },
+ files,
+ ov,
+ ).apiKey;
+
+ withEnv({ OPENVIKING_API_KEY: "sk-env" }, () => {
+ assert.equal(label({ credentialSource: "env", apiKeySource: "env" }), "env OPENVIKING_API_KEY");
+ });
+ withEnv({ OPENVIKING_BEARER_TOKEN: "sk-env" }, () => {
+ assert.equal(label({ credentialSource: "env", apiKeySource: "env" }), "env OPENVIKING_BEARER_TOKEN");
+ });
+
+ const pinned = { credentialSource: "ovcli", apiKeySource: "ovcli" };
+ assert.equal(label(pinned), `${CLI_PATH} plugin.claude_code.apiKey`);
+ assert.equal(label(pinned, cliConf({ url: "http://cli:1933", plugin: { apiKey: "sk-plugin" } })), `${CLI_PATH} plugin.apiKey`);
+ assert.equal(label(pinned, cliConf({ url: "http://cli:1933", api_key: "sk-cli" })), CLI_PATH);
+
+ assert.equal(label({ credentialSource: "auto", apiKeySource: "ov" }), `${OV_PATH} claude_code.apiKey`);
+ assert.equal(
+ credentialSources({ harness: "claude-code", credentialSource: "auto", apiKeySource: "ov" }, cli, ovConf({ server: { root_api_key: "sk-root" } })).apiKey,
+ `${OV_PATH} server.root_api_key`,
+ );
+
+ assert.equal(label({ credentialSource: "ovcli", apiKeySource: "none" }), "(none — ovcli.conf mode ignores env)");
+ assert.equal(label({ credentialSource: "auto", apiKeySource: "none" }), "(none)");
+});
+
+test("credentialSources reads the block named after the calling harness", () => {
+ const cli = cliConf({ plugin: { codex: { accountId: "acct-plugin-codex" } } });
+ const ov = ovConf({ codex: { accountId: "acct-ov-codex" }, cursor: { accountId: "acct-ov-cursor" } });
+ const cfg = { credentialSource: "auto", apiKeySource: "none" };
+
+ withEnv({}, () => {
+ assert.equal(credentialSources({ ...cfg, harness: "codex" }, cli, ov).account, `${CLI_PATH} plugin.codex.accountId`);
+ assert.equal(credentialSources({ ...cfg, harness: "cursor" }, cli, ov).account, `${OV_PATH} cursor.accountId`);
+ assert.equal(
+ credentialSources({ ...cfg, harness: "cursor" }, cli, ov, { section: "codex" }).account,
+ `${CLI_PATH} plugin.codex.accountId`,
+ );
+ });
+});
+
+test("credentialSources ranks the identity the way the credential chain does", () => {
+ const ov = ovConf({ server: { url: "http://ov:1933" }, codex: { accountId: "acct-ov", userId: "usr-ov" } });
+ const rows = (cfg, cli) => credentialSources({ harness: "codex", apiKeySource: "none", ...cfg }, cli, ov);
+ const full = cliConf({
+ url: "http://cli:1933",
+ account: "acct-cli",
+ plugin: { codex: { accountId: "acct-plugin" }, userId: "usr-plugin" },
+ });
+
+ withEnv({ OPENVIKING_URL: "http://env:1933", OPENVIKING_ACCOUNT: "acct-env", OPENVIKING_USER: "usr-env" }, () => {
+ const auto = rows({ credentialSource: "auto" }, full);
+ assert.equal(auto.url, "env");
+ assert.equal(auto.account, "env");
+ assert.equal(auto.user, "env");
+
+ // Pinned to ovcli.conf, neither the environment nor ov.conf is consulted.
+ const pinned = rows({ credentialSource: "ovcli" }, full);
+ assert.equal(pinned.url, CLI_PATH);
+ assert.equal(pinned.account, CLI_PATH);
+ assert.equal(pinned.user, `${CLI_PATH} plugin.userId`);
+ assert.equal(rows({ credentialSource: "ovcli" }, cliConf({ url: "http://cli:1933" })).account, "(unset)");
+ });
+
+ withEnv({}, () => {
+ // ovcli.conf's own field first, then its plugin section, then ov.conf —
+ // the identity ranks the way the key does.
+ assert.equal(rows({ credentialSource: "auto" }, full).account, CLI_PATH);
+ const noAccount = cliConf({ plugin: { codex: { accountId: "acct-plugin" } } });
+ assert.equal(rows({ credentialSource: "auto" }, noAccount).account, `${CLI_PATH} plugin.codex.accountId`);
+ assert.equal(rows({ credentialSource: "auto" }, cliConf({})).account, `${OV_PATH} codex.accountId`);
+ assert.equal(rows({ credentialSource: "auto" }, cliConf({})).url, OV_PATH);
+ });
+});
diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
index da6c2e848..70e7ec71f 100644
--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs
+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs
@@ -1,22 +1,48 @@
import assert from "node:assert/strict";
-import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join, resolve } from "node:path";
+import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import test from "node:test";
-const installer = join(dirname(fileURLToPath(import.meta.url)), "install.sh");
+// `--source dev` installs out of the checkout the installer sits in, and the
+// rest of the suite reads that tree while these installs run, so the installs
+// here get a copy of their own. The `.git` marker is a file, the way a linked
+// worktree keeps it: enough for the installer to recognise a checkout, not
+// enough for it to re-run the marketplace tests, which read repo-root files
+// this copy does not carry.
+const checkout = mkdtempSync(join(tmpdir(), "openviking-checkout-"));
+process.on("exit", () => rmSync(checkout, { recursive: true, force: true }));
+cpSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."), join(checkout, "examples"), {
+ recursive: true,
+ filter: (source) => basename(source) !== "node_modules",
+});
+writeFileSync(join(checkout, ".git"), "gitdir: .\n");
+
+const installer = join(checkout, "examples", "memory-plugin-shared", "install.sh");
const installedNode = spawnSync("bash", ["-c", "command -v node"], { encoding: "utf8" }).stdout.trim();
+/** Every `command` string a hooks configuration holds, at any depth. */
+function hookCommands(value, out = []) {
+ if (Array.isArray(value)) for (const item of value) hookCommands(item, out);
+ else if (value && typeof value === "object") {
+ for (const [key, child] of Object.entries(value)) {
+ if (key === "command" && typeof child === "string") out.push(child);
+ else hookCommands(child, out);
+ }
+ }
+ return out;
+}
+
function writeJson(file, value) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
}
-function runInstaller(home, args, extraEnv = {}) {
- return spawnSync("bash", [installer, ...args], {
- cwd: resolve(dirname(installer), "..", ".."),
+function runInstaller(home, args, extraEnv = {}, script = installer) {
+ return spawnSync("bash", [script, ...args], {
+ cwd: checkout,
env: {
...process.env,
HOME: home,
@@ -27,7 +53,7 @@ function runInstaller(home, args, extraEnv = {}) {
});
}
-function runInstall(home, harnesses = "cursor,trae,trae-cn") {
+function runInstall(home, harnesses = "cursor,trae,trae-cn,zcode") {
const result = runInstaller(home, [
"--harness", harnesses,
"--source", "dev",
@@ -39,9 +65,9 @@ function runInstall(home, harnesses = "cursor,trae,trae-cn") {
assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
}
-function runUninstall(home) {
+function runUninstall(home, harnesses = "cursor,trae,trae-cn,zcode") {
const result = runInstaller(home, [
- "--harness", "cursor,trae,trae-cn",
+ "--harness", harnesses,
"--uninstall",
"--yes",
]);
@@ -231,13 +257,14 @@ exit 0
}
});
-test("combined Cursor and TRAE install preserves unrelated hooks and is idempotent", () => {
+test("combined hook-host install preserves unrelated hooks and is idempotent", () => {
const home = mkdtempSync(join(tmpdir(), "openviking-agent-hooks-"));
try {
const cursorHooks = join(home, ".cursor", "hooks.json");
const cursorMcpPath = join(home, ".cursor", "mcp.json");
const traeHooks = join(home, ".trae", "hooks.json");
const traeCnHooks = join(home, ".trae-cn", "hooks.json");
+ const zcodeConfig = join(home, ".zcode", "cli", "config.json");
writeJson(cursorHooks, { version: 1, hooks: {
stop: [{ command: "third-party stop" }],
postToolUse: [{ command: "node /tmp/openviking/cursor-hook.mjs postToolUse # openviking-memory" }],
@@ -267,7 +294,7 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
runInstall(home);
const cursor = JSON.parse(readFileSync(cursorHooks, "utf8"));
- assert.equal(cursor.hooks.stop.filter((entry) => entry.command.includes("auto-capture.mjs")).length, 1);
+ assert.equal(cursor.hooks.stop.filter((entry) => entry.command.includes("scripts/hook.mjs")).length, 1);
assert.ok(cursor.hooks.stop.some((entry) => entry.command === "third-party stop"));
assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes(installedNode)));
assert.ok(cursor.hooks.stop.some((entry) => entry.command.includes("OPENVIKING_INTEGRATION_ID='openviking-memory'")));
@@ -278,7 +305,7 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
for (const [file, label] of [[traeHooks, "trae"], [traeCnHooks, "trae-cn"]]) {
const config = JSON.parse(readFileSync(file, "utf8"));
- assert.equal(config.hooks.Stop.filter((entry) => JSON.stringify(entry).includes("auto-capture.mjs")).length, 1, label);
+ assert.equal(config.hooks.Stop.filter((entry) => JSON.stringify(entry).includes("scripts/hook.mjs")).length, 1, label);
assert.ok(config.hooks.Stop.some((entry) => JSON.stringify(entry).includes(`third-party ${label}`)), label);
assert.equal(config.hooks.Stop.some((entry) => JSON.stringify(entry).includes("trae-auto-capture.mjs")), false, label);
assert.ok(config.hooks.Stop.some((entry) => JSON.stringify(entry).includes(`OPENVIKING_HOOK_SOURCE='${label}'`)), label);
@@ -288,6 +315,11 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
label,
);
}
+ const zcodeEvents = JSON.parse(readFileSync(zcodeConfig, "utf8")).hooks.events;
+ assert.equal(
+ zcodeEvents.PreToolUse.filter((entry) => JSON.stringify(entry).includes("uri-guard.mjs")).length,
+ 1,
+ );
const cursorServers = JSON.parse(readFileSync(cursorMcpPath, "utf8")).mcpServers;
const cursorMcp = cursorServers.openviking;
@@ -300,11 +332,13 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
assert.match(readFileSync(join(home, ".cursor", "skills", "openviking-memory", "SKILL.md"), "utf8"), /OpenViking Memory/);
const shared = join(home, ".openviking", "agent-integrations", "memory-plugin-shared", "lib");
assert.ok(existsSync(join(shared, "agent-hook-runtime.mjs")));
- assert.ok(existsSync(join(shared, "agent-uri-guard.mjs")));
assert.ok(existsSync(join(shared, "batch-send.mjs")));
assert.ok(existsSync(join(shared, "mcp-proxy-core.mjs")));
assert.ok(existsSync(join(shared, "uri-guard.mjs")));
for (const client of ["cursor", "trae", "trae-cn"]) {
+ const root = join(home, ".openviking", "agent-integrations", client);
+ assert.ok(existsSync(join(root, "plugin.json")), `${client}: host-neutral plugin manifest is missing`);
+ assert.equal(existsSync(join(root, ".claude-plugin")), false, `${client}: stale Claude manifest directory`);
const manifest = JSON.parse(readFileSync(join(home, ".openviking", "agent-integrations", client, "integration.json"), "utf8"));
assert.equal(manifest.id, "openviking-memory");
assert.equal(manifest.client, client);
@@ -316,18 +350,34 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
`${client} manifest must be idempotent`,
);
}
- for (const [client, args] of [
- ["cursor", []],
- ["trae", ["trae"]],
- ["trae-cn", ["trae-cn"]],
- ]) {
- const hook = join(home, ".openviking", "agent-integrations", client, "scripts", "session-start.mjs");
- const smoke = spawnSync(process.execPath, [hook, ...args], {
+ const doctor = spawnSync(
+ process.execPath,
+ [join(home, ".openviking", "agent-integrations", "cursor", "scripts", "ov-memory-doctor.mjs"), "cursor", "--offline", "--no-color"],
+ { env: { ...process.env, HOME: home }, encoding: "utf8" },
+ );
+ assert.match(doctor.stdout, /version 0\.3\.0, client cursor/);
+ // A hooks.json entry that names a script the install did not put on disk
+ // fails only when the host first runs it, so the rendered commands are
+ // checked against the tree they were rendered for.
+ for (const [file, label] of [[cursorHooks, "cursor"], [traeHooks, "trae"], [traeCnHooks, "trae-cn"]]) {
+ const commands = hookCommands(JSON.parse(readFileSync(file, "utf8")))
+ .filter((command) => command.includes("# openviking-memory"));
+ assert.ok(commands.length > 0, `${label}: no OpenViking hook commands were installed`);
+ for (const command of commands) {
+ const script = /'([^']*\.mjs)'/u.exec(command)?.[1];
+ assert.ok(script, `${label}: ${command} names no script`);
+ assert.ok(existsSync(script), `${label}: ${script} is missing after install`);
+ }
+ }
+ for (const [client, event] of [["cursor", "sessionStart"], ["trae", "session-start"], ["trae-cn", "session-start"]]) {
+ const hook = join(home, ".openviking", "agent-integrations", client, "scripts", "hook.mjs");
+ const smoke = spawnSync(process.execPath, [hook, event, client], {
env: { ...process.env, HOME: home, OPENVIKING_MEMORY_ENABLED: "0" },
input: "{}",
encoding: "utf8",
});
assert.equal(smoke.status, 0, `${client}: ${smoke.stderr}`);
+ assert.equal(smoke.stderr, "", client);
}
for (const client of ["cursor", "trae", "trae-cn"]) {
const guard = join(
@@ -341,7 +391,7 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
const input = client === "cursor"
? { file_path: "viking://resources/project/file.md" }
: { tool_name: "Read", tool_input: { file_path: "viking://resources/project/file.md" } };
- const guarded = spawnSync(process.execPath, [guard], {
+ const guarded = spawnSync(process.execPath, [guard, client], {
env: { ...process.env, HOME: home },
input: JSON.stringify(input),
encoding: "utf8",
@@ -362,7 +412,7 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
runUninstall(home);
assert.ok(JSON.parse(readFileSync(cursorHooks, "utf8")).hooks.stop.some((entry) => entry.command === "third-party stop"));
- assert.equal(JSON.parse(readFileSync(cursorHooks, "utf8")).hooks.stop.some((entry) => entry.command.includes("auto-capture.mjs")), false);
+ assert.equal(JSON.parse(readFileSync(cursorHooks, "utf8")).hooks.stop.some((entry) => entry.command.includes("scripts/hook.mjs")), false);
const cursorServersAfterUninstall = JSON.parse(readFileSync(cursorMcpPath, "utf8")).mcpServers;
assert.ok(cursorServersAfterUninstall["ov-mcp-server"]);
assert.ok(cursorServersAfterUninstall["third-party"]);
@@ -372,30 +422,81 @@ test("combined Cursor and TRAE install preserves unrelated hooks and is idempote
assert.equal(Boolean(JSON.parse(readFileSync(traeMcp, "utf8")).mcpServers.openviking), false);
assert.equal(Boolean(JSON.parse(readFileSync(traeCnMcp, "utf8")).mcpServers.openviking), false);
assert.ok(JSON.parse(readFileSync(traeCnMcp, "utf8")).mcpServers["third-party"]);
+ // Every event the installer wrote has to come back empty, the URI guard's
+ // included: a surviving entry runs a script the uninstall just deleted.
+ const cursorEventsAfter = JSON.parse(readFileSync(cursorHooks, "utf8")).hooks;
+ for (const event of ["beforeReadFile", "beforeShellExecution"]) {
+ assert.deepEqual(cursorEventsAfter[event] || [], [], event);
+ }
+ for (const [file, label] of [[traeHooks, "trae"], [traeCnHooks, "trae-cn"]]) {
+ assert.deepEqual(JSON.parse(readFileSync(file, "utf8")).hooks.PreToolUse || [], [], label);
+ }
+ assert.deepEqual(
+ JSON.parse(readFileSync(zcodeConfig, "utf8")).hooks?.events?.PreToolUse || [],
+ [],
+ "zcode",
+ );
+ // A backup taken while removing entries would keep a copy of them, so the
+ // uninstall writes none and reclaims the one the install left.
+ for (const file of [cursorHooks, cursorMcpPath, traeHooks, traeMcp, traeCnHooks, traeCnMcp]) {
+ assert.equal(existsSync(`${file}.bak`), false, `${file}.bak`);
+ }
assert.equal(existsSync(join(home, ".openviking", "agent-integrations", "memory-plugin-shared")), false);
} finally {
rmSync(home, { recursive: true, force: true });
}
});
-test("Cursor-only install does not clean Claude or Codex shell configuration", () => {
- const home = mkdtempSync(join(tmpdir(), "openviking-agent-scope-"));
+// Installing the thin harnesses together lets one client's verification pass
+// against a directory another client happened to create, so each is installed
+// into a HOME of its own.
+for (const client of ["cursor", "trae", "trae-cn", "zcode"]) {
+ test(`${client} installs and verifies on its own`, () => {
+ const home = mkdtempSync(join(tmpdir(), `openviking-solo-${client}-`));
+ try {
+ const result = runInstaller(home, [
+ "--harness", client,
+ "--source", "dev",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:1933",
+ "--api-key", "",
+ "--yes",
+ ]);
+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
+ assert.doesNotMatch(result.stdout, new RegExp(`^!!\\s+${client}:`, "mu"), result.stdout);
+ assert.ok(existsSync(join(home, ".openviking", "agent-integrations", client, "scripts", "hook.mjs")));
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+}
+
+// The documented uninstall pipes install.sh from a URL, so the running script
+// has no lib/ sibling, and the first uninstall drops the assembled copy under
+// $OV_HOME. Nothing left to read is not a reason to abort — and never a reason
+// to fetch sources.
+test("uninstall with no installer runtime on disk removes what it can and fetches nothing", () => {
+ const home = mkdtempSync(join(tmpdir(), "openviking-uninstall-sourceless-"));
try {
- const rc = join(home, ".zshrc");
- writeFileSync(rc, [
- "before",
- "# >>> openviking claude-code memory plugin >>>",
- "legacy claude",
- "# <<< openviking claude-code memory plugin <<<",
- "# >>> openviking-codex-plugin >>>",
- "legacy codex",
- "# <<< openviking-codex-plugin <<<",
- "after",
- "",
- ].join("\n"));
runInstall(home, "cursor");
- assert.match(readFileSync(rc, "utf8"), /legacy claude/);
- assert.match(readFileSync(rc, "utf8"), /legacy codex/);
+ const detached = join(home, "install.sh");
+ cpSync(installer, detached);
+ rmSync(join(home, ".openviking", "agent-integrations", "memory-plugin-shared"), {
+ recursive: true,
+ force: true,
+ });
+ const result = runInstaller(home, ["--harness", "cursor", "--uninstall", "--lang", "en", "--yes"], {
+ OPENVIKING_REPO_URL: "file:///nonexistent/openviking.git",
+ OPENVIKING_REPO_DIR: join(home, "openviking-repo"),
+ }, detached);
+ const output = `${result.stdout}\n${result.stderr}`;
+ assert.equal(result.status, 0, output);
+ assert.doesNotMatch(output, /Cloning|Refreshing checkout/u, output);
+ assert.equal(existsSync(join(home, "openviking-repo")), false);
+ assert.equal(existsSync(join(home, ".openviking", "agent-integrations", "cursor")), false);
+ assert.equal(existsSync(join(home, ".cursor", "rules", "openviking-memory.mdc")), false);
+ // The host's own files could not be edited, so the uninstall has to name them.
+ assert.match(result.stdout, /by hand from:.*\.cursor\/hooks\.json/u, output);
} finally {
rmSync(home, { recursive: true, force: true });
}
diff --git a/examples/memory-plugin-shared/install-lib-closure.test.mjs b/examples/memory-plugin-shared/install-lib-closure.test.mjs
index 419b5d4cf..db1852581 100644
--- a/examples/memory-plugin-shared/install-lib-closure.test.mjs
+++ b/examples/memory-plugin-shared/install-lib-closure.test.mjs
@@ -1,59 +1,51 @@
/**
* What the installer ships must equal what the shipped code imports.
*
- * cursor, trae and trae-cli have no vendored copy of the shared runtime: the
- * installer assembles one by copying a hand-written list into
- * `$OV_HOME/agent-integrations/memory-plugin-shared/lib`. A module that list
- * forgets is an ERR_MODULE_NOT_FOUND on the first hook of a fresh install, and
- * one it carries that nothing imports is dead weight nobody notices. Both sides
- * are derived here so neither can drift.
+ * cursor, trae and zcode have no vendored copy of the shared runtime: the
+ * installer assembles one in `$OV_HOME/agent-integrations/memory-plugin-shared/lib`
+ * by copying the modules `lib/MANIFEST` names. A module the manifest forgets is
+ * an ERR_MODULE_NOT_FOUND on the first hook of a fresh install, and one it
+ * carries that nothing imports is dead weight nobody notices. The manifest is
+ * generated from those sources by the same code that decides what the vendoring
+ * targets ship, so it can only drift by not being regenerated — which is what
+ * this asserts.
*/
import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { readFileSync, readdirSync } from "node:fs";
+import { dirname, join, relative } from "node:path";
import test from "node:test";
-import { fileURLToPath } from "node:url";
-const HERE = dirname(fileURLToPath(import.meta.url));
-const LIB = join(HERE, "lib");
+import { MANIFEST_PATH, ROOT, assembledClosure, resolveTargets } from "./sync.mjs";
-/** The entrypoints cursor, trae and trae-cli import from the assembled lib. */
-const ENTRYPOINTS = ["agent-hook-runtime.mjs", "agent-uri-guard.mjs", "mcp-proxy-core.mjs"];
-
-const RELATIVE_IMPORT_RE = /(?:^|[\s;(])(?:import|export)\s[^;]*?from\s*["'](\.\/[^"']+)["']/g;
-const DYNAMIC_IMPORT_RE = /\bimport\s*\(\s*["'](\.\/[^"']+)["']\s*\)/g;
-
-function installedFiles() {
- const script = readFileSync(join(HERE, "install.sh"), "utf8");
- const block = /shared_dest\.tmp[\s\S]*?\n\s*for file in\s*((?:[^\n]*\\\n)*[^\n]*?);\s*do/.exec(script);
- assert.ok(block, "install.sh no longer has the `for file in ...; do` list of shared modules");
- return new Set(block[1].replace(/\\\n/g, " ").trim().split(/\s+/).filter(Boolean));
-}
-
-function importedFiles() {
- const seen = new Set();
- const pending = [...ENTRYPOINTS];
- while (pending.length) {
- const file = pending.pop();
- if (seen.has(file)) continue;
- seen.add(file);
- const source = readFileSync(join(LIB, file), "utf8");
- for (const re of [RELATIVE_IMPORT_RE, DYNAMIC_IMPORT_RE]) {
- for (const match of source.matchAll(re)) pending.push(match[1].slice(2));
- }
- }
- return seen;
-}
-
-test("the installer ships exactly the closure of what cursor and trae import", () => {
- const installed = installedFiles();
- const imported = importedFiles();
+test("lib/MANIFEST holds the closure of what cursor, trae and zcode import", async () => {
+ const manifest = readFileSync(MANIFEST_PATH, "utf8");
+ assert.ok(manifest.endsWith("\n"), "the installer reads the manifest a line at a time");
+ assert.deepEqual(
+ manifest.split("\n").filter(Boolean),
+ await assembledClosure(),
+ "lib/MANIFEST is stale; run node examples/memory-plugin-shared/sync.mjs",
+ );
+});
- for (const file of [...installed].sort()) {
- assert.ok(imported.has(file), `install.sh ships ${file}, which no assembled entrypoint imports`);
- }
- for (const file of [...imported].sort()) {
- assert.ok(installed.has(file), `${file} is imported but install.sh never copies it`);
- }
+// `lib/install/` is the installer's own code — the JSONC editor and the
+// hooks/mcp merge — and no hook imports it. One `./install/...` import from a
+// module that hooks do import would put it in the closure, and from there into
+// the manifest and into every vendored copy: installer-time JavaScript shipped
+// to every harness, out of reach of a reviewer who reads the diff as runtime.
+test("the installer's own modules stay out of what the plugins ship", async () => {
+ const installerOnly = readdirSync(join(dirname(MANIFEST_PATH), "install"))
+ .filter((file) => file.endsWith(".mjs"));
+ assert.ok(installerOnly.length > 0, "expected installer-only modules under lib/install");
+
+ const shipped = [
+ ...(await assembledClosure()).map((file) => ({ file, where: "lib/MANIFEST" })),
+ ...(await resolveTargets()).flatMap((target) =>
+ target.files.map((file) => ({ file, where: relative(ROOT, target.dir) }))),
+ ];
+ assert.deepEqual(
+ shipped.filter((entry) => entry.file.startsWith("install/")),
+ [],
+ "a shipped module imports lib/install; the installer-only code must not be part of the runtime",
+ );
});
diff --git a/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
index 8f4881826..50c13027d 100644
--- a/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
+++ b/examples/memory-plugin-shared/install-opencode-jsonc.test.mjs
@@ -1,88 +1,226 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import { execFile } from "node:child_process"
-import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
-import { tmpdir } from "node:os"
-import { dirname, join, resolve } from "node:path"
-import { fileURLToPath } from "node:url"
-
-const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..")
-const installer = join(repoRoot, "examples", "memory-plugin-shared", "install.sh")
-
-async function withTempDir(prefix, fn) {
- const dir = await mkdtemp(join(tmpdir(), prefix))
- try {
- return await fn(dir)
- } finally {
- await rm(dir, { recursive: true, force: true })
- }
+/**
+ * OpenCode's config is a file people write by hand.
+ *
+ * The installer adds a plugin and an MCP server to it without reserializing it,
+ * because reserializing would eat every comment and every formatting choice the
+ * user made. That means walking JSONC the way editors do — over comments, past
+ * trailing commas, through single-quoted strings — and splicing the new value
+ * into the original text. Each of those is a thing `JSON.parse` refuses and a
+ * naive scanner mis-reads, so each gets a case here.
+ */
+
+import assert from "node:assert/strict";
+import { execFile, execFileSync } from "node:child_process";
+import { copyFileSync, mkdirSync } from "node:fs";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { stripJsonc, updateOpencodeConfig } from "./lib/install/jsonc-edit.mjs";
+import { expectExit, runHookScript } from "./testing/support.mjs";
+
+const PROXY = "/home/u/.openviking/opencode-mcp-proxy/openviking/servers/mcp-proxy.mjs";
+const SPEC = "@openviking/opencode-plugin";
+
+/** What the config parses to once the comments and trailing commas are gone. */
+function parse(raw) {
+ return JSON.parse(stripJsonc(raw));
}
-function runInstaller(args, options) {
- return new Promise((resolve, reject) => {
- execFile("bash", [installer, ...args], options, (error, stdout, stderr) => {
+test("comments survive the edit, wherever they sit", () => {
+ const next = updateOpencodeConfig([
+ "{",
+ " // keep this user note",
+ ' "theme": "system",',
+ " /* keep this block note */",
+ ' "mcp": {',
+ " // keep this mcp note",
+ ' "other": { "type": "local", "command": ["node", "other.js"] }',
+ " }",
+ "}",
+ "",
+ ].join("\n"), { pluginSpec: SPEC, mcpProxy: PROXY });
+
+ assert.match(next, /\/\/ keep this user note/);
+ assert.match(next, /\/\* keep this block note \*\//);
+ assert.match(next, /\/\/ keep this mcp note/);
+ assert.match(next, /"theme": "system"/);
+ assert.match(next, /"other": \{ "type": "local"/);
+ assert.deepEqual(parse(next).plugin, [SPEC]);
+ assert.equal(parse(next).mcp.openviking.command[1], PROXY);
+});
+
+test("a trailing comma is not doubled", () => {
+ const next = updateOpencodeConfig([
+ "{",
+ ' "plugin": [',
+ ' "some-other-plugin",',
+ " ],",
+ ' "mcp": {',
+ ' "other": { "type": "local", "command": ["node", "other.js"] },',
+ " },",
+ "}",
+ "",
+ ].join("\n"), { pluginSpec: SPEC, mcpProxy: PROXY });
+
+ assert.doesNotMatch(next, /,\s*,/);
+ assert.deepEqual(parse(next).plugin, ["some-other-plugin", SPEC]);
+ assert.deepEqual(Object.keys(parse(next).mcp), ["other", "openviking"]);
+});
+
+// A single quote makes the whole file unparseable, so this is the one case the
+// editor gets through on the text walk alone: nothing tells it where "mcp" is
+// except the scan, and the brace and the `//` inside the string would end the
+// object and start a comment for a scanner that does not know it is in a quote.
+test("a single-quoted value is stepped over, not scanned into", () => {
+ const next = updateOpencodeConfig([
+ "{",
+ " 'theme': 'dark } // not a comment',",
+ ' "mcp": {',
+ ' "other": { "type": "local", "command": ["node", "other.js"] }',
+ " }",
+ "}",
+ "",
+ ].join("\n"), { pluginSpec: SPEC, mcpProxy: PROXY });
+
+ assert.match(next, /'dark \} \/\/ not a comment'/);
+ assert.match(next, /"openviking": \{/);
+ assert.ok(
+ next.indexOf('"openviking"') > next.indexOf('"other"'),
+ "the server belongs inside the mcp object the scan had to find",
+ );
+ assert.match(next, /"plugin": \[\n\s+"@openviking\/opencode-plugin"\n\s+\]/);
+});
+
+test("the MCP server lands inside an existing mcp object, beside its siblings", () => {
+ const next = updateOpencodeConfig([
+ "{",
+ ' "mcp": {',
+ ' "other": {',
+ ' "type": "local",',
+ ' "command": ["node", "other.js"],',
+ ' "environment": { "NESTED": { "deeper": true } }',
+ " }",
+ " }",
+ "}",
+ "",
+ ].join("\n"), { pluginSpec: "", mcpProxy: PROXY });
+
+ const data = parse(next);
+ assert.deepEqual(data.mcp.other.environment, { NESTED: { deeper: true } });
+ assert.deepEqual(data.mcp.openviking, {
+ type: "local",
+ command: ["node", PROXY],
+ enabled: true,
+ timeout: 15000,
+ });
+ assert.equal(data.openviking, undefined, "the server must not be added at the top level");
+});
+
+test("an empty config is filled in, and a second run changes nothing", () => {
+ const first = updateOpencodeConfig("", { pluginSpec: SPEC, mcpProxy: PROXY });
+ assert.deepEqual(parse(first).plugin, [SPEC]);
+ assert.equal(updateOpencodeConfig(first, { pluginSpec: SPEC, mcpProxy: PROXY }), first);
+});
+
+test("a server the user disabled stays disabled", () => {
+ const raw = [
+ "{",
+ ' "mcp": {',
+ ' "openviking": { "type": "local", "command": ["node", "old.js"], "enabled": false }',
+ " }",
+ "}",
+ "",
+ ].join("\n");
+ assert.equal(updateOpencodeConfig(raw, { pluginSpec: "", mcpProxy: PROXY }), raw);
+});
+
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const installer = join(repoRoot, "examples", "memory-plugin-shared", "install.sh");
+
+function runInstaller(args, options, script = installer) {
+ return new Promise((resolvePromise, reject) => {
+ execFile("bash", [script, ...args], options, (error, stdout, stderr) => {
if (error) {
- error.stdout = stdout
- error.stderr = stderr
- reject(error)
+ error.stdout = stdout;
+ error.stderr = stderr;
+ reject(error);
} else {
- resolve({ stdout, stderr })
+ resolvePromise({ stdout, stderr });
}
- })
- })
+ });
+ });
}
-test("OpenCode installer preserves JSONC comments while adding MCP config", async () => {
- await withTempDir("ov-opencode-jsonc-", async (dir) => {
- const home = join(dir, "home")
- const bin = join(dir, "bin")
- const configDir = join(home, ".config", "opencode")
- await mkdir(bin, { recursive: true })
- await mkdir(configDir, { recursive: true })
-
- const opencode = join(bin, "opencode")
- await writeFile(opencode, "#!/usr/bin/env sh\nprintf 'opencode 0.0.0-test\\n'\n")
- await chmod(opencode, 0o755)
-
- const configPath = join(configDir, "opencode.jsonc")
- await writeFile(configPath, [
- "{",
- " // keep this user note",
- " \"theme\": \"system\",",
- " /* keep this block note */",
- " \"mcp\": {",
- " // keep this mcp note",
- " \"other\": { \"type\": \"local\", \"command\": [\"node\", \"other.js\"] }",
- " }",
- "}",
- "",
- ].join("\n"))
-
- await runInstaller([
- "--harness", "opencode",
- "--source", "dev",
- "--dist", "github",
- "--lang", "en",
- "--url", "http://127.0.0.1:1933",
- "--api-key", "",
- "--yes",
- ], {
- cwd: repoRoot,
- env: {
- ...process.env,
- HOME: home,
- OPENVIKING_HOME: join(home, ".openviking"),
- PATH: `${bin}:${process.env.PATH}`,
- },
- })
-
- const raw = await readFile(configPath, "utf8")
- assert.match(raw, /keep this user note/)
- assert.match(raw, /keep this block note/)
- assert.match(raw, /keep this mcp note/)
- assert.match(raw, /"theme": "system"/)
- assert.match(raw, /"other": \{ "type": "local"/)
- assert.match(raw, /"openviking"/)
- assert.match(raw, /servers\/mcp-proxy\.mjs/)
- })
-})
+// The cases above are the editor; this is the wiring. It is the only thing that
+// proves install.sh still finds the module and hands it the right three
+// arguments now that the editor no longer lives inside the script.
+for (const sourceMode of ["dev", "archive", "remote"]) {
+ test(`the OpenCode ${sourceMode} install loads its entries from clean sources`, async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ov-opencode-jsonc-"));
+ try {
+ const home = join(dir, "home");
+ const bin = join(dir, "bin");
+ const configDir = join(home, ".config", "opencode");
+ await mkdir(bin, { recursive: true });
+ await mkdir(configDir, { recursive: true });
+
+ const opencode = join(bin, "opencode");
+ await writeFile(opencode, "#!/usr/bin/env sh\nprintf 'opencode 0.0.0-test\\n'\n");
+ await chmod(opencode, 0o755);
+
+ const configPath = join(configDir, "opencode.jsonc");
+ await writeFile(configPath, '{\n // keep this user note\n "theme": "system"\n}\n');
+
+ // Copy only tracked paths from the working tree: no ignored generated
+ // runtime or node_modules may hide a missing installation step.
+ const source = join(dir, "source");
+ const files = execFileSync("git", ["ls-files", "-z", "--", "examples", "agent-plugins"], { cwd: repoRoot, encoding: "utf8" }).split("\0").filter(Boolean);
+ for (const file of files) {
+ mkdirSync(dirname(join(source, file)), { recursive: true });
+ copyFileSync(join(repoRoot, file), join(source, file));
+ }
+ await mkdir(join(source, ".git"));
+ if (sourceMode === "archive") {
+ execFileSync("zip", ["-rq", join(dir, "source.zip"), "source"], { cwd: dir });
+ }
+
+ await runInstaller([
+ "--harness", "opencode",
+ "--source", sourceMode,
+ "--dist", "github",
+ "--lang", "en",
+ "--url", "http://127.0.0.1:1933",
+ "--api-key", "",
+ "--yes",
+ ], {
+ cwd: source,
+ env: {
+ ...process.env,
+ HOME: home,
+ OPENVIKING_HOME: join(home, ".openviking"),
+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: "",
+ OPENVIKING_REPO_ARCHIVE_URL: `file://${join(dir, "source.zip")}`,
+ PATH: `${bin}:${process.env.PATH}`,
+ },
+ }, join(source, "examples/memory-plugin-shared/install.sh"));
+
+ const raw = await readFile(configPath, "utf8");
+ assert.match(raw, /keep this user note/);
+ assert.match(raw, /"theme": "system"/);
+ assert.match(parse(raw).mcp.openviking.command[1], /servers\/mcp-proxy\.mjs$/);
+ const installedRoot = join(configDir, "plugins/openviking");
+ const env = { HOME: home, OPENVIKING_HOME: join(home, ".openviking") };
+ expectExit(await runHookScript(parse(raw).mcp.openviking.command[1], { cwd: home, env }));
+ if (sourceMode !== "remote") {
+ expectExit(await runHookScript(join(installedRoot, "index.mjs"), { cwd: home, env }));
+ } else {
+ assert.deepEqual(parse(raw).plugin, [SPEC]);
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+}
diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.sh
index 61bbb7a39..35317580c 100644
--- a/examples/memory-plugin-shared/install.sh
+++ b/examples/memory-plugin-shared/install.sh
@@ -64,12 +64,6 @@ PLUGIN_NAME="openviking-memory"
DSH_PACKAGE="@openviking/dsh-memory-plugin"
PLUGIN_ID="${PLUGIN_NAME}@${MARKETPLACE_NAME}"
-# Pre-unification names, cleaned up on upgrade.
-OLD_MARKETPLACE_NAME='openviking-plugins-local'
-CC_OLD_IDS="claude-code-memory-plugin@${OLD_MARKETPLACE_NAME} ${PLUGIN_NAME}@${OLD_MARKETPLACE_NAME}"
-CODEX_OLD_ID="${PLUGIN_NAME}@${OLD_MARKETPLACE_NAME}"
-CODEX_OLD_MARKETPLACE_ROOT="$HOME/.codex/${OLD_MARKETPLACE_NAME}-marketplace"
-
CODEX_CONFIG="${CODEX_CONFIG_FILE:-$HOME/.codex/config.toml}"
CC_SETTINGS="$HOME/.claude/settings.json"
CC_KNOWN_MARKETPLACES="$HOME/.claude/plugins/known_marketplaces.json"
@@ -1414,6 +1408,42 @@ plugin_dir_on_disk() { # plugin_dir_on_disk <plugin-subdir>
return 1
}
+# The installer's own JavaScript: the JSONC editor OpenCode's config needs and
+# the hooks/mcp merge every config-driven host installs through. It is not part
+# of the runtime the plugins ship, so it travels with whatever copy of this
+# script is running rather than with `lib/MANIFEST`.
+#
+# `--uninstall` runs before any source is resolved, and the documented uninstall
+# pipes this script from a URL, where there is no sibling directory to read. So
+# this only ever looks at what is already on disk — the running script's
+# sibling, the assembled runtime, and a marketplace or source root an earlier
+# step resolved. Never plugin_dir_on_disk: it would clone a repository, or exit
+# for want of git, just to remove hooks.
+install_lib_dir() {
+ local src self candidate
+ src="${BASH_SOURCE[0]:-}"
+ self=""
+ if [ -n "$src" ]; then
+ self="$(cd "$(dirname "$src")" >/dev/null 2>&1 && pwd -P)" || self=""
+ fi
+ for candidate in \
+ "${self:+$self/lib/install}" \
+ "$OV_HOME/agent-integrations/memory-plugin-shared/lib/install" \
+ "${MKT_DIR:+$MKT_DIR/memory-plugin-shared/lib/install}" \
+ "${SRC_ROOT:+$SRC_ROOT/examples/memory-plugin-shared/lib/install}"; do
+ [ -n "$candidate" ] && [ -d "$candidate" ] || continue
+ printf '%s' "$candidate"
+ return 0
+ done
+ return 1
+}
+
+require_install_lib_dir() {
+ install_lib_dir && return 0
+ err "$(t 'Installer runtime not found:' '未找到安装器运行时:') memory-plugin-shared/lib/install"
+ return 1
+}
+
prepare_marketplace_dir() {
case "$SOURCE_MODE" in
dev)
@@ -1442,38 +1472,6 @@ prepare_marketplace_dir() {
fi
}
-# ---------------------------------------------------------------------------
-# Legacy wrapper cleanup (pre-stdio installs)
-# ---------------------------------------------------------------------------
-
-strip_rc_block() {
- local rc="$1" begin="$2" end="$3"
- [ -n "$rc" ] && [ -f "$rc" ] || return 0
- grep -qF "$begin" "$rc" || return 0
- if ! grep -qF "$end" "$rc"; then
- warn "Found $begin in $rc but missing end marker; leaving it untouched."
- return 0
- fi
- awk -v b="$begin" -v e="$end" '
- $0 == b {skip=1; next}
- $0 == e {skip=0; next}
- !skip
- ' "$rc" > "$rc.tmp" && mv "$rc.tmp" "$rc"
- info "$(t 'Removed legacy rc block from' '已移除旧的 rc 注入块:') $rc"
-}
-
-cleanup_rc_wrappers() {
- local rc
- for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
- if contains_harness claude; then
- strip_rc_block "$rc" '# >>> openviking claude-code memory plugin >>>' '# <<< openviking claude-code memory plugin <<<'
- fi
- if contains_harness codex; then
- strip_rc_block "$rc" '# >>> openviking-codex-plugin >>>' '# <<< openviking-codex-plugin <<<'
- fi
- done
-}
-
# ---------------------------------------------------------------------------
# Claude Code
# ---------------------------------------------------------------------------
@@ -1521,22 +1519,6 @@ claude_marketplace_current_source() {
' "$CC_KNOWN_MARKETPLACES" "$MARKETPLACE_NAME" 2>/dev/null || true
}
-migrate_claude_legacy_marketplace() {
- local id plugin_list marketplace_list
- plugin_list="$(claude_cmd plugin list 2>/dev/null || true)"
- for id in $CC_OLD_IDS; do
- if str_contains "$plugin_list" "$id"; then
- info "$(t 'Removing pre-unification plugin install' '移除旧命名的插件安装') ($id)"
- claude_cmd plugin uninstall "$id" >/dev/null 2>&1 || true
- fi
- done
- marketplace_list="$(claude_cmd plugin marketplace list 2>/dev/null || true)"
- if str_contains "$marketplace_list" "$OLD_MARKETPLACE_NAME"; then
- info "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"
- claude_cmd plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true
- fi
-}
-
write_claude_remote_manifest() {
mkdir -p "$(dirname "$CC_REMOTE_MANIFEST")"
# Pre-directory-layout leftover (a bare .json registered as a file-type
@@ -1708,7 +1690,6 @@ install_claude() {
return 0
}
if has_plugin_subcommand; then
- migrate_claude_legacy_marketplace
install_claude_modern || return 1
else
warn "$(t "This Claude-format CLI doesn't expose 'plugin'." '当前 Claude 格式 CLI 没有 plugin 子命令。') ($CLAUDE_BIN)"
@@ -1796,36 +1777,6 @@ codex_marketplace_current_source() {
' "$MARKETPLACE_NAME" 2>/dev/null || true
}
-migrate_codex_legacy_marketplace() {
- codex_cmd plugin remove "$CODEX_OLD_ID" >/dev/null 2>&1 || true
- codex_cmd plugin uninstall "$CODEX_OLD_ID" >/dev/null 2>&1 || true
- if str_contains "$(codex_cmd plugin marketplace list 2>/dev/null || true)" "$OLD_MARKETPLACE_NAME"; then
- info "$(t 'Removing pre-unification marketplace' '移除旧命名的 marketplace') ($OLD_MARKETPLACE_NAME)"
- codex_cmd plugin marketplace remove "$OLD_MARKETPLACE_NAME" >/dev/null 2>&1 || true
- fi
- if is_native_codex_bin; then
- [ -d "$CODEX_OLD_MARKETPLACE_ROOT" ] && rm -rf "$CODEX_OLD_MARKETPLACE_ROOT"
- [ -d "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME" ] && rm -rf "$HOME/.codex/plugins/cache/$OLD_MARKETPLACE_NAME"
- fi
- # Drop the old plugin id's config.toml section; the unified id gets its own.
- if is_native_codex_bin && [ -f "$CODEX_CONFIG" ] && grep -qF "plugins.\"$CODEX_OLD_ID\"" "$CODEX_CONFIG"; then
- node - "$CODEX_CONFIG" "$CODEX_OLD_ID" <<'NODE' || true
-const fs = require("node:fs");
-const [path, oldId] = process.argv.slice(2);
-const lines = fs.readFileSync(path, "utf8").split(/\n/);
-const out = [];
-let skip = false;
-for (const line of lines) {
- const trimmed = line.trim();
- if (/^\[/.test(trimmed)) skip = trimmed.startsWith(`[plugins."${oldId}"`);
- if (!skip) out.push(line);
-}
-fs.writeFileSync(path, out.join("\n").replace(/\n*$/, "\n"));
-NODE
- info "Removed old config.toml section for $CODEX_OLD_ID"
- fi
-}
-
codex_marketplace_sync() { # codex_marketplace_sync <expected-source> <add-args...>
local needle="$1" current
shift
@@ -1896,7 +1847,6 @@ install_codex() {
warn "$(t 'Codex-format CLI not found; skipping:' '未找到 Codex 格式 CLI,跳过:') $CODEX_BIN"
return 0
}
- migrate_codex_legacy_marketplace
case "$SOURCE_MODE" in
remote)
# Codex doesn't expose which --ref a registered git marketplace is
@@ -1978,10 +1928,12 @@ install_codex_tos_git() {
# Cursor / TRAE lifecycle hooks
# ---------------------------------------------------------------------------
-copy_agent_integration() { # copy_agent_integration <source-subdir> <dest-name>
- local source_subdir="$1" dest_name="$2" source dest tmp
- source="$(plugin_dir_on_disk "$source_subdir")" || {
- err "$(t 'Agent integration sources not found:' '未找到 Agent 接入源码:') $source_subdir"
+AGENT_HOOK_HOSTS="cursor trae zcode"
+
+copy_agent_integration() { # copy_agent_integration <host> <dest-name>
+ local host="$1" dest_name="$2" source dest tmp other
+ source="$(plugin_dir_on_disk agent-hook-plugin)" || {
+ err "$(t 'Agent integration sources not found:' '未找到 Agent 接入源码:') agent-hook-plugin"
return 1
}
dest="$OV_HOME/agent-integrations/$dest_name"
@@ -1989,6 +1941,11 @@ copy_agent_integration() { # copy_agent_integration <source-subdir> <dest-name>
rm -rf "$tmp"
mkdir -p "$tmp"
(cd "$source" && tar --exclude node_modules --exclude .git -cf - .) | (cd "$tmp" && tar -xf -)
+ # One plugin serves every config-driven host; an installation is for one
+ # client, so the other hosts' configuration directories do not travel with it.
+ for other in $AGENT_HOOK_HOSTS; do
+ [ "$other" = "$host" ] || rm -rf "$tmp/hosts/$other"
+ done
# Preserve the first-install timestamp across managed upgrades. The package
# descriptor is copied from source; integration.json records this machine's
# installation and must survive replacing the runtime directory.
@@ -1999,27 +1956,35 @@ copy_agent_integration() { # copy_agent_integration <source-subdir> <dest-name>
printf '%s' "$dest"
}
-# Cursor and TRAE keep only their client-specific adapters in the repository.
+# Cursor, TRAE and ZCode keep only their client-specific adapters in the repository.
# Assemble a self-contained installation by adding the canonical shared runtime
# at install time instead of committing generated copies for every client.
-assemble_agent_integration() { # assemble_agent_integration <source-subdir> <dest-name>
- local source_subdir="$1" dest_name="$2" root shared shared_dest file
- root="$(copy_agent_integration "$source_subdir" "$dest_name")" || return 1
+assemble_agent_integration() { # assemble_agent_integration <host> <dest-name>
+ local host="$1" dest_name="$2" root shared shared_dest manifest file
+ root="$(copy_agent_integration "$host" "$dest_name")" || return 1
shared="$(plugin_dir_on_disk memory-plugin-shared)" || {
err "$(t 'Shared agent runtime not found.' '未找到共享 Agent 运行时。')"
return 1
}
shared_dest="$OV_HOME/agent-integrations/memory-plugin-shared/lib"
+ # The closure of what cursor, trae and zcode import, written by sync.mjs and
+ # shipped beside the modules. Regenerating it here is not an option: the
+ # generator finds no plugin sources in a flat marketplace archive.
+ manifest="$shared/lib/MANIFEST"
+ [ -s "$manifest" ] || {
+ err "$(t 'Shared runtime manifest is missing or empty:' '共享运行时清单缺失或为空:') $manifest"
+ return 1
+ }
rm -rf "$shared_dest.tmp"
mkdir -p "$shared_dest.tmp"
- for file in \
- agent-hook-runtime.mjs agent-uri-guard.mjs credentials.mjs debug-log.mjs \
- batch-send.mjs mcp-proxy-core.mjs pending-queue.mjs profile-inject.mjs \
- retryable.mjs \
- recall-compress-core.mjs recall-core.mjs \
- session-model.mjs uri-guard.mjs workspace-identity.mjs workspace-peer.mjs; do
- cp "$shared/lib/$file" "$shared_dest.tmp/$file"
- done
+ while read -r file || [ -n "$file" ]; do
+ [ -n "$file" ] || continue
+ cp "$shared/lib/$file" "$shared_dest.tmp/$file" || return 1
+ done < "$manifest"
+ cp "$manifest" "$shared_dest.tmp/MANIFEST"
+ # Not part of the closure and never imported by a hook; it is here so that an
+ # uninstall piped from a URL can reclaim this host's entries without a source.
+ cp -R "$shared/lib/install" "$shared_dest.tmp/install" || return 1
rm -rf "$shared_dest"
mkdir -p "$(dirname "$shared_dest")"
mv "$shared_dest.tmp" "$shared_dest"
@@ -2027,445 +1992,44 @@ assemble_agent_integration() { # assemble_agent_integration <source-subdir> <des
}
agent_write_json_configs() { # agent_write_json_configs <kind> <hooks> <mcp> <root> <client-id> <node-bin>
- local kind="$1" hooks_path="$2" mcp_path="$3" root="$4" client_id="$5" node_bin="$6"
- "$NODE_BIN" - "$kind" "$hooks_path" "$mcp_path" "$root" "$client_id" "$node_bin" "$SOURCE_MODE" <<'NODE'
-const fs = require("node:fs");
-const path = require("node:path");
-const [kind, hooksPath, mcpPath, root, clientId, nodeBin, sourceMode] = process.argv.slice(2);
-
-function readJson(file) {
- if (!fs.existsSync(file)) return {};
- try {
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- throw new Error("top-level value must be an object");
- }
- return parsed;
- } catch (error) {
- throw new Error(`Cannot safely update ${file}: ${error.message}`);
- }
-}
-
-function atomicWrite(file, value) {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- const next = JSON.stringify(value, null, 2) + "\n";
- let previous = "";
- try { previous = fs.readFileSync(file, "utf8"); } catch {}
- if (previous === next) return;
- if (previous) fs.writeFileSync(`${file}.bak`, previous, { mode: 0o600 });
- const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, next, { mode: 0o600 });
- fs.renameSync(tmp, file);
-}
-
-function shellArg(value) {
- return `'${String(value).replace(/'/g, `'"'"'`)}'`;
-}
-
-function isOpenVikingHook(value) {
- const text = JSON.stringify(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",
- "pre-compact.mjs",
- "session-end.mjs",
- "trae-auto-recall.mjs",
- "trae-auto-capture.mjs",
- "claude-code-memory-plugin/scripts/session-start.mjs",
- ].some((name) => text.includes(name)));
-}
-
-const packageManifest = readJson(path.join(root, "openviking.integration.json"));
-if (packageManifest.id !== "openviking-memory" || !Array.isArray(packageManifest.clients)
- || !packageManifest.clients.includes(clientId)) {
- throw new Error(`Invalid OpenViking integration manifest for ${clientId}`);
-}
-const integrationEnv = {
- OPENVIKING_INTEGRATION_ID: packageManifest.id,
- OPENVIKING_INTEGRATION_VERSION: packageManifest.version,
- OPENVIKING_HOOK_SOURCE: clientId,
-};
-const envPrefix = Object.entries(integrationEnv)
- .map(([key, value]) => `${key}=${shellArg(value)}`)
- .join(" ");
-
-function renderHookCommand(command) {
- let rendered = command;
- const cursorMatch = /^node\s+\$\{CURSOR_PLUGIN_ROOT\}\/(.+)$/u.exec(rendered);
- if (cursorMatch) {
- rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, cursorMatch[1]))}`;
- } else {
- 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`;
-}
-
-function renderHookValue(value) {
- if (Array.isArray(value)) return value.map(renderHookValue);
- if (!value || typeof value !== "object") return value;
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [
- key,
- key === "command" && typeof child === "string" ? renderHookCommand(child) : renderHookValue(child),
- ]));
-}
-
-const hookTemplate = readJson(path.join(root, "hooks", "hooks.json"));
-if (!hookTemplate.hooks || typeof hookTemplate.hooks !== "object" || Array.isArray(hookTemplate.hooks)) {
- throw new Error(`Invalid ${clientId} hooks template`);
-}
-const hooksConfig = readJson(hooksPath);
-hooksConfig.version = Number.isFinite(Number(hooksConfig.version)) ? Number(hooksConfig.version) : 1;
-hooksConfig.hooks = hooksConfig.hooks && typeof hooksConfig.hooks === "object" && !Array.isArray(hooksConfig.hooks)
- ? hooksConfig.hooks : {};
-
-for (const [event, entries] of Object.entries(hookTemplate.hooks)) {
- if (!Array.isArray(entries)) throw new Error(`Invalid ${clientId} hook entries for ${event}`);
- const current = Array.isArray(hooksConfig.hooks[event]) ? hooksConfig.hooks[event] : [];
- hooksConfig.hooks[event] = [
- ...current.filter((item) => !isOpenVikingHook(item)),
- ...renderHookValue(entries),
- ];
-}
-if (kind === "cursor") {
- if (Array.isArray(hooksConfig.hooks.postToolUse)) {
- const remaining = hooksConfig.hooks.postToolUse.filter((item) => !isOpenVikingHook(item));
- if (remaining.length) hooksConfig.hooks.postToolUse = remaining;
- else delete hooksConfig.hooks.postToolUse;
- }
-}
-atomicWrite(hooksPath, hooksConfig);
-
-const mcpTemplate = readJson(path.join(root, ".mcp.json"));
-const templateServer = mcpTemplate.mcpServers?.openviking;
-if (!templateServer || typeof templateServer !== "object" || Array.isArray(templateServer)) {
- throw new Error(`Invalid ${clientId} MCP template`);
-}
-const mcp = readJson(mcpPath);
-mcp.mcpServers = mcp.mcpServers && typeof mcp.mcpServers === "object" && !Array.isArray(mcp.mcpServers)
- ? mcp.mcpServers : {};
-function isKnownLegacyOpenVikingServer(value) {
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
- if (value.env?.OPENVIKING_INTEGRATION_ID === "openviking-memory") return true;
- if (typeof value.url !== "string") return false;
- try {
- const url = new URL(value.url);
- const local = ["127.0.0.1", "localhost", "::1"].includes(url.hostname)
- && url.port === "1933" && url.pathname.replace(/\/$/u, "") === "/mcp";
- const cloud = url.hostname === "api.vikingdb.cn-beijing.volces.com"
- && url.pathname.replace(/\/$/u, "") === "/openviking/mcp";
- return local || cloud;
- } catch {
- return false;
- }
-}
-// Migrate only the exact OpenViking endpoints published by the earlier manual
-// guides. A coincidentally named third-party server must remain untouched.
-if (isKnownLegacyOpenVikingServer(mcp.mcpServers["ov-mcp-server"])) {
- delete mcp.mcpServers["ov-mcp-server"];
-}
-const server = {
- ...templateServer,
- command: nodeBin,
- args: [path.join(root, "servers", "mcp-proxy.mjs")],
- env: { ...(templateServer.env || {}), ...integrationEnv },
-};
-mcp.mcpServers.openviking = server;
-atomicWrite(mcpPath, mcp);
-
-const installedManifestPath = path.join(root, "integration.json");
-const previousManifest = readJson(installedManifestPath);
-const now = new Date().toISOString();
-const unchangedInstall = previousManifest.version === packageManifest.version
- && previousManifest.source === sourceMode
- && previousManifest.hooksConfig === hooksPath
- && previousManifest.mcpConfig === mcpPath;
-atomicWrite(installedManifestPath, {
- schemaVersion: 1,
- id: packageManifest.id,
- version: packageManifest.version,
- client: clientId,
- installMode: "managed-native",
- source: sourceMode,
- capabilities: packageManifest.capabilities,
- hooksConfig: hooksPath,
- mcpConfig: mcpPath,
- installedAt: previousManifest.installedAt || now,
- updatedAt: unchangedInstall ? previousManifest.updatedAt || previousManifest.installedAt || now : now,
-});
-NODE
-}
-
-agent_write_trae_cli_configs() { # agent_write_trae_cli_configs <hooks> <traecli.toml> <root> <node-bin>
- local hooks_path="$1" config_path="$2" root="$3" node_bin="$4"
- "$NODE_BIN" - "$hooks_path" "$config_path" "$root" "$node_bin" "$SOURCE_MODE" <<'NODE'
-const fs = require("node:fs");
-const path = require("node:path");
-const [hooksPath, configPath, root, nodeBin, sourceMode] = process.argv.slice(2);
-const clientId = "trae-cli";
-const serverName = "openviking-memory";
-
-function readJson(file) {
- if (!fs.existsSync(file)) return {};
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- throw new Error(`${file} top-level value must be an object`);
- }
- return parsed;
-}
-
-function atomicWrite(file, content) {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- let previous = "";
- try { previous = fs.readFileSync(file, "utf8"); } catch {}
- if (previous === content) return;
- if (previous) fs.writeFileSync(`${file}.bak`, previous, { mode: 0o600 });
- const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, content, { mode: 0o600 });
- fs.renameSync(tmp, file);
-}
-
-function shellArg(value) {
- return `'${String(value).replace(/'/g, `'"'"'`)}'`;
-}
-
-function isOpenVikingHook(value) {
- const text = JSON.stringify(value || {}).toLowerCase();
- return text.includes("openviking_integration_id")
- || (text.includes("openviking") && [
- "trae-cli-hook.mjs",
- "session-start.mjs",
- "auto-recall.mjs",
- "auto-capture.mjs",
- "uri-guard.mjs",
- ].some((name) => text.includes(name)));
-}
-
-function stripTomlSections(content, prefix) {
- const lines = String(content || "").split(/\r?\n/u);
- const out = [];
- let skipping = false;
- for (const line of lines) {
- const match = /^\s*\[([^\]]+)\]\s*$/u.exec(line);
- if (match) skipping = match[1] === prefix || match[1].startsWith(`${prefix}.`);
- if (!skipping) out.push(line);
- }
- return out.join("\n").replace(/\n{3,}/gu, "\n\n").trimEnd();
-}
-
-function stripLegacyOpenVikingServer(content) {
- const lines = String(content || "").split(/\r?\n/u);
- for (let index = 0; index < lines.length; index += 1) {
- const match = /^\s*\[([^\]]+)\]\s*$/u.exec(lines[index]);
- if (!match || !["mcp_servers.openviking", 'mcp_servers."openviking"'].includes(match[1])) continue;
- let end = index + 1;
- while (end < lines.length && !/^\s*\[[^\]]+\]\s*$/u.test(lines[end])) end += 1;
- const block = lines.slice(index, end).join("\n").toLowerCase();
- if (block.includes("mcp-proxy.mjs") && block.includes("openviking")) {
- return stripTomlSections(content, match[1]);
- }
+ local lib
+ lib="$(require_install_lib_dir)" || return 1
+ "$NODE_BIN" "$lib/host-json-config.mjs" write "$1" "$2" "$3" "$4" "$5" "$6" "$SOURCE_MODE"
+}
+
+agent_remove_json_configs() { # agent_remove_json_configs <hooks> [mcp]
+ local lib
+ # An uninstall that cannot find the runtime still has to remove everything it
+ # can and tell the user what it left behind; aborting here would leave both
+ # the host's entries and the integration directory they point at.
+ lib="$(install_lib_dir)" || {
+ warn "$(t 'Installer runtime not found; remove the OpenViking hook and MCP entries by hand from:' '未找到安装器运行时,请手动移除以下文件中的 OpenViking hook 与 MCP 条目:') $1${2:+, $2}"
+ return 0
}
- return content;
-}
-
-const manifest = readJson(path.join(root, "openviking.integration.json"));
-if (manifest.id !== "openviking-memory" || !manifest.clients?.includes(clientId)) {
- throw new Error("Invalid OpenViking TRAE CLI integration manifest");
-}
-const integrationEnv = {
- OPENVIKING_INTEGRATION_ID: manifest.id,
- OPENVIKING_INTEGRATION_VERSION: manifest.version,
- OPENVIKING_HOOK_SOURCE: clientId,
-};
-const envPrefix = Object.entries(integrationEnv)
- .map(([key, value]) => `${key}=${shellArg(value)}`)
- .join(" ");
-
-function renderHookValue(value) {
- if (Array.isArray(value)) return value.map(renderHookValue);
- if (!value || typeof value !== "object") return value;
- return Object.fromEntries(Object.entries(value).map(([key, child]) => {
- if (key !== "command" || typeof child !== "string") {
- return [key, renderHookValue(child)];
- }
- const match = /^node\s+__OPENVIKING_TRAE_CLI_ROOT__\/(\S+)$/u.exec(child);
- if (!match) throw new Error(`Unsupported TRAE CLI hook command template: ${child}`);
- const command = `${shellArg(nodeBin)} ${shellArg(path.join(root, match[1]))}`;
- return [key, `${envPrefix} ${command} # openviking-memory`];
- }));
-}
-
-const hookTemplate = readJson(path.join(root, "hooks", "hooks.json"));
-const hooksConfig = readJson(hooksPath);
-hooksConfig.version = Number.isFinite(Number(hooksConfig.version)) ? Number(hooksConfig.version) : 1;
-hooksConfig.hooks = hooksConfig.hooks && typeof hooksConfig.hooks === "object"
- ? hooksConfig.hooks : {};
-for (const [event, entries] of Object.entries(hookTemplate.hooks || {})) {
- const current = Array.isArray(hooksConfig.hooks[event]) ? hooksConfig.hooks[event] : [];
- hooksConfig.hooks[event] = [
- ...current.filter((item) => !isOpenVikingHook(item)),
- ...renderHookValue(entries),
- ];
-}
-atomicWrite(hooksPath, `${JSON.stringify(hooksConfig, null, 2)}\n`);
-
-let toml = "";
-try { toml = fs.readFileSync(configPath, "utf8"); } catch {}
-toml = stripLegacyOpenVikingServer(toml);
-toml = stripTomlSections(toml, `mcp_servers."${serverName}"`);
-const envToml = Object.entries(integrationEnv)
- .map(([key, value]) => `${key} = ${JSON.stringify(value)}`)
- .join(", ");
-const section = [
- `[mcp_servers."${serverName}"]`,
- `command = ${JSON.stringify(nodeBin)}`,
- `args = [${JSON.stringify(path.join(root, "servers", "mcp-proxy.mjs"))}]`,
- `env = { ${envToml} }`,
-].join("\n");
-atomicWrite(configPath, `${toml ? `${toml}\n\n` : ""}${section}\n`);
-
-const manifestPath = path.join(root, "integration.json");
-const previous = readJson(manifestPath);
-const now = new Date().toISOString();
-const unchanged = previous.version === manifest.version
- && previous.source === sourceMode
- && previous.hooksConfig === hooksPath
- && previous.mcpConfig === configPath;
-atomicWrite(manifestPath, `${JSON.stringify({
- schemaVersion: 1,
- id: manifest.id,
- version: manifest.version,
- client: clientId,
- installMode: "managed-native",
- source: sourceMode,
- capabilities: manifest.capabilities,
- hooksConfig: hooksPath,
- mcpConfig: configPath,
- installedAt: previous.installedAt || now,
- updatedAt: unchanged ? previous.updatedAt || previous.installedAt || now : now,
-}, null, 2)}\n`);
-NODE
+ "$NODE_BIN" "$lib/host-json-config.mjs" remove "$1" "${2:-}"
}
agent_remove_trae_cli_configs() { # agent_remove_trae_cli_configs <hooks> <traecli.toml>
local hooks_path="$1" config_path="$2"
- "$NODE_BIN" - "$hooks_path" "$config_path" <<'NODE'
-const fs = require("node:fs");
-const path = require("node:path");
-const [hooksPath, configPath] = process.argv.slice(2);
-
-function atomicWrite(file, content) {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, content, { mode: 0o600 });
- fs.renameSync(tmp, file);
-}
-
-function ownsHook(value) {
- const text = JSON.stringify(value || {}).toLowerCase();
- return text.includes("openviking_integration_id")
- || (text.includes("openviking") && [
- "trae-cli-hook.mjs",
- "session-start.mjs",
- "auto-recall.mjs",
- "auto-capture.mjs",
- "uri-guard.mjs",
- ].some((name) => text.includes(name)));
-}
-
-if (fs.existsSync(hooksPath)) {
- const hooks = JSON.parse(fs.readFileSync(hooksPath, "utf8"));
- for (const event of Object.keys(hooks.hooks || {})) {
- if (!Array.isArray(hooks.hooks[event])) continue;
- hooks.hooks[event] = hooks.hooks[event].filter((item) => !ownsHook(item));
- if (hooks.hooks[event].length === 0) delete hooks.hooks[event];
- }
- atomicWrite(hooksPath, `${JSON.stringify(hooks, null, 2)}\n`);
-}
-
-if (fs.existsSync(configPath)) {
- const lines = fs.readFileSync(configPath, "utf8").split(/\r?\n/u);
- const prefix = 'mcp_servers."openviking-memory"';
- const out = [];
- let skipping = false;
- for (const line of lines) {
- const match = /^\s*\[([^\]]+)\]\s*$/u.exec(line);
- if (match) skipping = match[1] === prefix || match[1].startsWith(`${prefix}.`);
- if (!skipping) out.push(line);
- }
- atomicWrite(configPath, `${out.join("\n").replace(/\n{3,}/gu, "\n\n").trimEnd()}\n`);
-}
-NODE
-}
-
-agent_remove_json_configs() { # agent_remove_json_configs <hooks> <mcp>
- local hooks_path="$1" mcp_path="$2"
- "$NODE_BIN" - "$hooks_path" "$mcp_path" <<'NODE'
-const fs = require("node:fs");
-const [hooksPath, mcpPath] = process.argv.slice(2);
-function read(file) {
- if (!fs.existsSync(file)) return null;
- try {
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- throw new Error("top-level value must be an object");
+ # The hooks file answers to the same "is this entry ours" the other hosts use;
+ # only the TOML this host keeps its MCP servers in is its own problem.
+ agent_remove_json_configs "$hooks_path"
+ [ -f "$config_path" ] || return 0
+ local stripped tmp="$config_path.$$.tmp"
+ stripped="$(awk -v target='mcp_servers."openviking-memory"' '
+ BEGIN { prefix = target "." }
+ /^[[:space:]]*\[[^]]+\][[:space:]]*$/ {
+ name = $0
+ sub(/^[[:space:]]*\[/, "", name)
+ sub(/\][[:space:]]*$/, "", name)
+ skip = (name == target || index(name, prefix) == 1)
}
- return parsed;
- } catch (error) {
- throw new Error(`Cannot safely update ${file}: ${error.message}`);
- }
-}
-function write(file, value) {
- const next = JSON.stringify(value, null, 2) + "\n";
- const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, next, { mode: 0o600 });
- fs.renameSync(tmp, file);
-}
-function ownsHook(value) {
- const text = JSON.stringify(value || {});
- return text.includes("openviking") && [
- "cursor-hook.mjs",
- "trae-hook.mjs",
- "zcode-hook.mjs",
- "session-start.mjs",
- "auto-recall.mjs",
- "auto-capture.mjs",
- "pre-compact.mjs",
- "session-end.mjs",
- "trae-auto-recall.mjs",
- "trae-auto-capture.mjs",
- "claude-code-memory-plugin/scripts/session-start.mjs",
- ].some((name) => text.includes(name));
-}
-const hooks = read(hooksPath);
-const mcp = read(mcpPath);
-if (hooks?.hooks && typeof hooks.hooks === "object") {
- for (const event of Object.keys(hooks.hooks)) {
- if (!Array.isArray(hooks.hooks[event])) continue;
- hooks.hooks[event] = hooks.hooks[event].filter((item) => !ownsHook(item));
- if (hooks.hooks[event].length === 0) delete hooks.hooks[event];
- }
- write(hooksPath, hooks);
-}
-if (mcp?.mcpServers?.openviking) {
- const text = JSON.stringify(mcp.mcpServers.openviking);
- if (text.includes("agent-integrations") && text.includes("mcp-proxy.mjs")) {
- delete mcp.mcpServers.openviking;
- write(mcpPath, mcp);
- }
-}
-NODE
+ skip { next }
+ /^[[:space:]]*$/ { blank = 1; next }
+ { if (started && blank) print ""; print; started = 1; blank = 0 }
+ ' "$config_path")"
+ ( umask 077; printf '%s\n' "$stripped" >"$tmp" )
+ mv "$tmp" "$config_path"
}
uninstall_agent_integrations() {
@@ -2579,15 +2143,15 @@ trae_mcp_path() { # trae_mcp_path <client-id>
install_cursor() {
heading "$(t '4. Cursor integration' '4. Cursor 集成')"
local root hooks_path mcp_path skill_tmp legacy_plugins
- root="$(assemble_agent_integration cursor-memory-plugin cursor)" || return 1
+ root="$(assemble_agent_integration cursor cursor)" || return 1
hooks_path="$HOME/.cursor/hooks.json"
mcp_path="$(cursor_mcp_path)"
agent_write_json_configs cursor "$hooks_path" "$mcp_path" "$root" cursor "$NODE_BIN"
mkdir -p "$HOME/.cursor/rules" "$HOME/.cursor/skills"
- cp "$root/rules/openviking-memory.mdc" "$HOME/.cursor/rules/openviking-memory.mdc"
+ cp "$root/hosts/cursor/rules/openviking-memory.mdc" "$HOME/.cursor/rules/openviking-memory.mdc"
skill_tmp="$HOME/.cursor/skills/openviking-memory.tmp"
rm -rf "$skill_tmp"
- cp -R "$root/skills/openviking-memory" "$skill_tmp"
+ cp -R "$root/hosts/cursor/skills/openviking-memory" "$skill_tmp"
rm -rf "$HOME/.cursor/skills/openviking-memory"
mv "$skill_tmp" "$HOME/.cursor/skills/openviking-memory"
info "$(t 'Cursor hooks installed:' 'Cursor hooks 已安装:') $hooks_path"
@@ -2605,83 +2169,15 @@ zcode_mcp_path() {
}
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
+ local lib
+ lib="$(require_install_lib_dir)" || return 1
+ "$NODE_BIN" "$lib/host-json-config.mjs" merge-zcode "$1" "$2" "$3"
}
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
+ root="$(assemble_agent_integration zcode zcode)" || return 1
hooks_path="$HOME/.zcode/hooks.json"
mcp_path="$(zcode_mcp_path)"
config_path="$HOME/.zcode/cli/config.json"
@@ -2697,7 +2193,7 @@ install_zcode() {
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
+ root="$(assemble_agent_integration trae "$client_id")" || return 1
hooks_path="$HOME/.$client_id/hooks.json"
mcp_path="$(trae_mcp_path "$client_id")"
agent_write_json_configs trae "$hooks_path" "$mcp_path" "$root" "$client_id" "$NODE_BIN"
@@ -2705,19 +2201,6 @@ install_trae_variant() { # install_trae_variant <trae|trae-cn>
info "$client_id MCP: $mcp_path"
}
-install_trae_cli() {
- heading "$(t 'TRAE CLI integration' 'TRAE CLI 集成')"
- local root trae_home trae_cli_home hooks_path config_path
- root="$(assemble_agent_integration trae-cli-memory-hooks trae-cli)" || return 1
- trae_home="${TRAE_HOME:-$HOME/.trae}"
- trae_cli_home="${TRAECLI_HOME:-$trae_home/cli}"
- hooks_path="$trae_cli_home/hooks.json"
- config_path="$trae_home/traecli.toml"
- agent_write_trae_cli_configs "$hooks_path" "$config_path" "$root" "$NODE_BIN"
- info "$(t 'TRAE CLI hooks installed:' 'TRAE CLI hooks 已安装:') $hooks_path"
- info "$(t 'TRAE CLI MCP installed:' 'TRAE CLI MCP 已安装:') $config_path (mcp_servers.openviking-memory)"
-}
-
# ---------------------------------------------------------------------------
# OpenCode
# ---------------------------------------------------------------------------
@@ -2762,6 +2245,7 @@ opencode_register_npm_plugin() {
opencode_install_mcp_proxy_snapshot() {
local plugin_dir="$1" dest="$2"
+ prepare_opencode_runtime "$plugin_dir" || return 1
rm -rf "$dest.tmp"
mkdir -p "$dest.tmp"
(cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - package.json lib servers) | (cd "$dest.tmp" && tar -xf -)
@@ -2772,340 +2256,12 @@ opencode_install_mcp_proxy_snapshot() {
}
opencode_write_config() {
- local cfg="$1" plugin_spec="$2" mcp_proxy="$3"
+ local cfg="$1" plugin_spec="$2" mcp_proxy="$3" lib
+ lib="$(require_install_lib_dir)" || return 1
mkdir -p "$(dirname "$cfg")"
[ -f "$cfg" ] || printf '{\n}\n' > "$cfg"
cp "$cfg" "$cfg.bak.$(date +%Y%m%d-%H%M%S)"
- node - "$cfg" "$plugin_spec" "$mcp_proxy" <<'NODE'
-const fs = require("node:fs");
-const file = process.argv[2];
-const pluginSpec = process.argv[3] || "";
-const mcpProxy = process.argv[4] || "";
-let raw = "";
-try { raw = fs.readFileSync(file, "utf8"); } catch {}
-
-function stripJsonc(s) {
- let out = "";
- let i = 0;
- while (i < s.length) {
- const ch = s[i];
- const next = s[i + 1];
- if (ch === '"' || ch === "'") {
- const end = readStringEnd(s, i);
- out += s.slice(i, end);
- i = end;
- } else if (ch === "/" && next === "/") {
- i += 2;
- while (i < s.length && s[i] !== "\n") i++;
- } else if (ch === "/" && next === "*") {
- i += 2;
- while (i < s.length && !(s[i] === "*" && s[i + 1] === "/")) i++;
- i = Math.min(s.length, i + 2);
- } else {
- out += ch;
- i++;
- }
- }
- return out.replace(/,\s*([}\]])/g, "$1");
-}
-
-function readStringEnd(s, start) {
- const quote = s[start];
- let i = start + 1;
- while (i < s.length) {
- if (s[i] === "\\") {
- i += 2;
- } else if (s[i] === quote) {
- return i + 1;
- } else {
- i++;
- }
- }
- return s.length;
-}
-
-function skipTrivia(s, i, end = s.length) {
- while (i < end) {
- if (/\s/.test(s[i])) {
- i++;
- } else if (s[i] === "/" && s[i + 1] === "/") {
- i += 2;
- while (i < end && s[i] !== "\n") i++;
- } else if (s[i] === "/" && s[i + 1] === "*") {
- i += 2;
- while (i < end && !(s[i] === "*" && s[i + 1] === "/")) i++;
- i = Math.min(end, i + 2);
- } else {
- break;
- }
- }
- return i;
-}
-
-function parseStringLiteral(s, start) {
- const end = readStringEnd(s, start);
- try {
- return { value: JSON.parse(s.slice(start, end)), end };
- } catch {
- return { value: "", end };
- }
-}
-
-function findTopLevelObject(s) {
- const start = skipTrivia(s, 0);
- if (s[start] !== "{") return null;
- let depth = 0;
- let i = start;
- while (i < s.length) {
- if (s[i] === '"' || s[i] === "'") {
- i = readStringEnd(s, i);
- continue;
- }
- if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
- i = skipTrivia(s, i);
- continue;
- }
- if (s[i] === "{" || s[i] === "[") depth++;
- if (s[i] === "}" || s[i] === "]") {
- depth--;
- if (depth === 0 && s[i] === "}") return { start, end: i };
- }
- i++;
- }
- return null;
-}
-
-function findObjectRangeAt(s, start, end = s.length) {
- const objectStart = skipTrivia(s, start, end);
- if (s[objectStart] !== "{") return null;
- let depth = 0;
- let i = objectStart;
- while (i < end) {
- if (s[i] === '"' || s[i] === "'") {
- i = readStringEnd(s, i);
- continue;
- }
- if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
- i = skipTrivia(s, i, end);
- continue;
- }
- if (s[i] === "{" || s[i] === "[") depth++;
- if (s[i] === "}" || s[i] === "]") {
- depth--;
- if (depth === 0 && s[i] === "}") return { start: objectStart, end: i };
- }
- i++;
- }
- return null;
-}
-
-function findArrayRangeAt(s, start, end = s.length) {
- const arrayStart = skipTrivia(s, start, end);
- if (s[arrayStart] !== "[") return null;
- let depth = 0;
- let i = arrayStart;
- while (i < end) {
- if (s[i] === '"' || s[i] === "'") {
- i = readStringEnd(s, i);
- continue;
- }
- if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
- i = skipTrivia(s, i, end);
- continue;
- }
- if (s[i] === "{" || s[i] === "[") depth++;
- if (s[i] === "}" || s[i] === "]") {
- depth--;
- if (depth === 0 && s[i] === "]") return { start: arrayStart, end: i };
- }
- i++;
- }
- return null;
-}
-
-function findTopLevelProperty(s, objectRange, name) {
- let depth = 1;
- let i = objectRange.start + 1;
- while (i < objectRange.end) {
- if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
- i = skipTrivia(s, i, objectRange.end);
- continue;
- }
- if (s[i] === '"' || s[i] === "'") {
- const keyStart = i;
- const parsed = parseStringLiteral(s, i);
- i = parsed.end;
- const afterKey = skipTrivia(s, i, objectRange.end);
- if (depth === 1 && parsed.value === name && s[afterKey] === ":") {
- const valueStart = skipTrivia(s, afterKey + 1, objectRange.end);
- return {
- keyStart,
- valueStart,
- replaceEnd: findPropertyReplaceEnd(s, valueStart, objectRange.end),
- };
- }
- continue;
- }
- if (s[i] === "{" || s[i] === "[") depth++;
- if (s[i] === "}" || s[i] === "]") depth--;
- i++;
- }
- return null;
-}
-
-function findPropertyReplaceEnd(s, valueStart, objectEnd) {
- let depth = 0;
- let i = skipTrivia(s, valueStart, objectEnd);
- let lastTokenEnd = i;
- while (i < objectEnd) {
- if (s[i] === '"' || s[i] === "'") {
- i = readStringEnd(s, i);
- lastTokenEnd = i;
- continue;
- }
- if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
- i = skipTrivia(s, i, objectEnd);
- continue;
- }
- if (depth === 0 && s[i] === ",") return lastTokenEnd;
- if (s[i] === "{" || s[i] === "[") depth++;
- if (s[i] === "}" || s[i] === "]") depth--;
- if (!/\s/.test(s[i])) lastTokenEnd = i + 1;
- i++;
- }
- return lastTokenEnd;
-}
-
-function findLineIndent(s, index) {
- const lineStart = s.lastIndexOf("\n", index - 1) + 1;
- const prefix = s.slice(lineStart, index);
- return /^[ \t]*$/.test(prefix) ? prefix : "";
-}
-
-function detectPropertyIndent(s, objectRange) {
- let i = objectRange.start + 1;
- while (i < objectRange.end) {
- i = skipTrivia(s, i, objectRange.end);
- if (s[i] === '"' || s[i] === "'") return findLineIndent(s, i) || " ";
- if (s[i] === "{" || s[i] === "[") break;
- i++;
- }
- const closeIndent = findLineIndent(s, objectRange.end);
- return `${closeIndent} `;
-}
-
-function hasTopLevelProperty(s, objectRange) {
- let i = objectRange.start + 1;
- while (i < objectRange.end) {
- i = skipTrivia(s, i, objectRange.end);
- if (s[i] === '"' || s[i] === "'") return true;
- i++;
- }
- return false;
-}
-
-function objectEndsWithComma(s, objectRange) {
- const body = s.slice(objectRange.start + 1, objectRange.end);
- return body.trimEnd().endsWith(",");
-}
-
-function rangeHasValue(s, range) {
- let i = range.start + 1;
- while (i < range.end) {
- i = skipTrivia(s, i, range.end);
- if (i < range.end) return true;
- }
- return false;
-}
-
-function formatProperty(name, value, indent) {
- const json = JSON.stringify(value, null, 2);
- const formatted = json.split("\n").map((line, idx) => idx === 0 ? line : `${indent}${line}`).join("\n");
- return `${JSON.stringify(name)}: ${formatted}`;
-}
-
-function setPropertyInObject(s, objectRange, name, value) {
- const existing = findTopLevelProperty(s, objectRange, name);
- if (existing) {
- const indent = findLineIndent(s, existing.keyStart) || detectPropertyIndent(s, objectRange);
- return `${s.slice(0, existing.keyStart)}${formatProperty(name, value, indent)}${s.slice(existing.replaceEnd)}`;
- }
-
- const indent = detectPropertyIndent(s, objectRange);
- const closeIndent = findLineIndent(s, objectRange.end);
- const needsComma = hasTopLevelProperty(s, objectRange) && !objectEndsWithComma(s, objectRange);
- const prefix = needsComma ? "," : "";
- const insertion = `${prefix}\n${indent}${formatProperty(name, value, indent)}\n${closeIndent}`;
- return `${s.slice(0, objectRange.end)}${insertion}${s.slice(objectRange.end)}`;
-}
-
-function setTopLevelProperty(s, name, value) {
- let objectRange = findTopLevelObject(s);
- if (!objectRange) {
- s = "{\n}\n";
- objectRange = findTopLevelObject(s);
- }
- return setPropertyInObject(s, objectRange, name, value);
-}
-
-function setNestedObjectProperty(s, parentName, childName, childValue, fallbackParentValue) {
- let objectRange = findTopLevelObject(s);
- if (!objectRange) {
- s = "{\n}\n";
- objectRange = findTopLevelObject(s);
- }
- const parent = findTopLevelProperty(s, objectRange, parentName);
- if (!parent) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);
- const parentRange = findObjectRangeAt(s, parent.valueStart, parent.replaceEnd);
- if (!parentRange) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);
- return setPropertyInObject(s, parentRange, childName, childValue);
-}
-
-function appendStringToTopLevelArray(s, name, value) {
- let objectRange = findTopLevelObject(s);
- if (!objectRange) {
- s = "{\n}\n";
- objectRange = findTopLevelObject(s);
- }
- const prop = findTopLevelProperty(s, objectRange, name);
- if (!prop) return setPropertyInObject(s, objectRange, name, [value]);
- const arrayRange = findArrayRangeAt(s, prop.valueStart, prop.replaceEnd);
- if (!arrayRange) return setPropertyInObject(s, objectRange, name, [value]);
- const propIndent = findLineIndent(s, prop.keyStart) || detectPropertyIndent(s, objectRange);
- const itemIndent = `${propIndent} `;
- const closeIndent = findLineIndent(s, arrayRange.end) || propIndent;
- const needsComma = rangeHasValue(s, arrayRange) && !s.slice(arrayRange.start + 1, arrayRange.end).trimEnd().endsWith(",");
- const prefix = needsComma ? "," : "";
- const insertion = `${prefix}\n${itemIndent}${JSON.stringify(value)}\n${closeIndent}`;
- return `${s.slice(0, arrayRange.end)}${insertion}${s.slice(arrayRange.end)}`;
-}
-
-let data = {};
-try { data = raw.trim() ? JSON.parse(stripJsonc(raw)) : {}; } catch { data = {}; }
-let nextRaw = raw.trim() ? raw : "{\n}\n";
-if (pluginSpec) {
- const next = Array.isArray(data.plugin) ? data.plugin.slice() : [];
- if (!next.includes(pluginSpec)) {
- next.push(pluginSpec);
- nextRaw = appendStringToTopLevelArray(nextRaw, "plugin", pluginSpec);
- }
- data.plugin = next;
-}
-if (mcpProxy) {
- data.mcp = data.mcp && typeof data.mcp === "object" && !Array.isArray(data.mcp) ? data.mcp : {};
- if (!data.mcp.openviking || data.mcp.openviking.enabled !== false) {
- data.mcp.openviking = {
- type: "local",
- command: ["node", mcpProxy],
- enabled: true,
- timeout: 15000,
- };
- nextRaw = setNestedObjectProperty(nextRaw, "mcp", "openviking", data.mcp.openviking, data.mcp);
- }
-}
-if (!nextRaw.endsWith("\n")) nextRaw += "\n";
-fs.writeFileSync(file, nextRaw);
-NODE
+ "$NODE_BIN" "$lib/jsonc-edit.mjs" "$cfg" "$plugin_spec" "$mcp_proxy"
}
opencode_install_file_plugin() {
@@ -3114,6 +2270,7 @@ opencode_install_file_plugin() {
warn "$(t 'OpenCode plugin sources not found; skipping.' '未找到 OpenCode 插件源码,跳过。')"
return 0
}
+ prepare_opencode_runtime "$plugin_dir" || return 1
dest="$HOME/.config/opencode/plugins/openviking"
mkdir -p "$(dirname "$dest")"
if [ "$SOURCE_MODE" = "dev" ]; then
@@ -3138,27 +2295,46 @@ opencode_install_file_plugin() {
# pi
# ---------------------------------------------------------------------------
+# Whole-directory installs need generated dependencies before copying. Flat
+# marketplace archives already contain them and have no source generator.
+sync_shared_runtime() {
+ local shared root
+ shared="$(plugin_dir_on_disk memory-plugin-shared)" || return 0
+ shared="$(cd "$shared" && pwd -P)" || return 1
+ root="$(cd "$shared/../.." 2>/dev/null && pwd)" || return 0
+ [ -f "$shared/sync.mjs" ] && [ -d "$root/examples/memory-plugin-shared" ] || return 0
+ "$NODE_BIN" "$shared/sync.mjs" >/dev/null
+}
+
+prepare_opencode_runtime() {
+ local plugin_dir="$1"
+ sync_shared_runtime || return 1
+ # Import resolves the complete dependency graph; node --check only parses.
+ "$NODE_BIN" --input-type=module -e 'import { pathToFileURL } from "node:url"; await import(pathToFileURL(process.argv[2]));' \
+ check-runtime "$plugin_dir/servers/mcp-proxy.mjs" || return 1
+}
+
install_pi() {
heading "$(t '4. pi extension' '4. pi 扩展')"
if ! command -v pi >/dev/null 2>&1; then
warn "$(t 'pi CLI not found; skipping pi extension install.' '未找到 pi 命令,跳过 pi 扩展安装。')"
return 0
fi
- local plugin_dir dest tmp keep_config
+ local plugin_dir dest tmp
plugin_dir="$(plugin_dir_on_disk pi-coding-agent-extension)" || {
warn "$(t 'pi extension sources not found; skipping.' '未找到 pi 扩展源码,跳过。')"
return 0
}
+ sync_shared_runtime
+ if [ ! -f "$plugin_dir/shared/credentials.mjs" ]; then
+ warn "$(t 'pi extension shared runtime is missing; run node examples/memory-plugin-shared/sync.mjs and retry.' '未找到 pi 扩展的共享运行时;请先运行 node examples/memory-plugin-shared/sync.mjs 再重试。')"
+ return 0
+ fi
dest="$HOME/.pi/agent/extensions/openviking"
tmp="$dest.tmp"
- keep_config=""
- [ -f "$dest/config.json" ] && keep_config="$dest/config.json"
rm -rf "$tmp"
mkdir -p "$tmp"
(cd "$plugin_dir" && tar --exclude node_modules --exclude .git -cf - .) | (cd "$tmp" && tar -xf -)
- if [ -n "$keep_config" ]; then
- cp "$keep_config" "$tmp/config.json"
- fi
rm -rf "$dest"
mkdir -p "$(dirname "$dest")"
mv "$tmp" "$dest"
@@ -3214,25 +2390,24 @@ $CODEX_BINS
EOF
fi
if contains_harness cursor; then
- if grep -q 'scripts/session-start.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-recall.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-capture.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
+ if grep -q 'scripts/hook.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
&& grep -q 'scripts/uri-guard.mjs' "$HOME/.cursor/hooks.json" 2>/dev/null \
&& grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.cursor/hooks.json" 2>/dev/null \
&& grep -q 'mcp-proxy.mjs' "$HOME/.cursor/mcp.json" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/cursor/scripts/cursor-hook.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" ] \
&& [ -f "$OV_HOME/agent-integrations/cursor/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/cursor/.cursor-plugin/plugin.json" ] \
+ && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/uri-guard.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/cursor/plugin.json" ] \
&& [ -f "$OV_HOME/agent-integrations/cursor/integration.json" ] \
&& [ -f "$HOME/.cursor/rules/openviking-memory.mdc" ] \
&& [ -f "$HOME/.cursor/skills/openviking-memory/SKILL.md" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/cursor/scripts/cursor-hook.mjs" \
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" \
|| { ok=0; agent_fatal=1; }
"$NODE_BIN" --check "$OV_HOME/agent-integrations/cursor/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/cursor/scripts/session-start.mjs" >/dev/null; then
+ "$NODE_BIN" "$OV_HOME/agent-integrations/cursor/scripts/hook.mjs" sessionStart cursor >/dev/null; then
info "cursor: $(t 'installed Hook runtime passed its smoke test' '已安装的 Hook 运行时通过 smoke test')"
else
warn "cursor: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
@@ -3247,21 +2422,20 @@ EOF
if contains_harness trae; then
local trae_mcp
trae_mcp="$(trae_mcp_path trae)"
- if grep -q 'scripts/session-start.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-recall.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-capture.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
+ if grep -q 'scripts/hook.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
&& grep -q 'scripts/uri-guard.mjs' "$HOME/.trae/hooks.json" 2>/dev/null \
&& grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.trae/hooks.json" 2>/dev/null \
&& grep -q 'mcp-proxy.mjs' "$trae_mcp" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/trae/scripts/trae-hook.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" ] \
&& [ -f "$OV_HOME/agent-integrations/trae/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae/integration.json" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae/scripts/trae-hook.mjs" \
+ && [ -f "$OV_HOME/agent-integrations/trae/integration.json" ] \
+ && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" \
|| { ok=0; agent_fatal=1; }
"$NODE_BIN" --check "$OV_HOME/agent-integrations/trae/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/trae/scripts/session-start.mjs" trae >/dev/null; then
+ "$NODE_BIN" "$OV_HOME/agent-integrations/trae/scripts/hook.mjs" session-start trae >/dev/null; then
warn "trae: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
ok=0; agent_fatal=1
fi
@@ -3274,21 +2448,20 @@ EOF
if contains_harness trae-cn; then
local trae_cn_mcp
trae_cn_mcp="$(trae_mcp_path trae-cn)"
- if grep -q 'scripts/session-start.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-recall.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
- && grep -q 'scripts/auto-capture.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
+ if grep -q 'scripts/hook.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
&& grep -q 'scripts/uri-guard.mjs' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
&& grep -q 'OPENVIKING_INTEGRATION_ID' "$HOME/.trae-cn/hooks.json" 2>/dev/null \
&& grep -q 'mcp-proxy.mjs' "$trae_cn_mcp" 2>/dev/null \
- && [ -f "$OV_HOME/agent-integrations/trae-cn/scripts/trae-hook.mjs" ] \
+ && [ -f "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" ] \
&& [ -f "$OV_HOME/agent-integrations/trae-cn/scripts/uri-guard.mjs" ] \
- && [ -f "$OV_HOME/agent-integrations/trae-cn/integration.json" ]; then
- "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cn/scripts/trae-hook.mjs" \
+ && [ -f "$OV_HOME/agent-integrations/trae-cn/integration.json" ] \
+ && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" \
|| { ok=0; agent_fatal=1; }
"$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cn/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/trae-cn/scripts/session-start.mjs" trae-cn >/dev/null; then
+ "$NODE_BIN" "$OV_HOME/agent-integrations/trae-cn/scripts/hook.mjs" session-start trae-cn >/dev/null; then
warn "trae-cn: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
ok=0; agent_fatal=1
fi
@@ -3330,21 +2503,20 @@ EOF
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 \
+ if grep -q 'scripts/hook.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/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" \
+ && [ -f "$OV_HOME/agent-integrations/zcode/integration.json" ] \
+ && [ -f "$OV_HOME/agent-integrations/memory-plugin-shared/lib/agent-hook-runtime.mjs" ]; then
+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/zcode/scripts/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
+ "$NODE_BIN" "$OV_HOME/agent-integrations/zcode/scripts/hook.mjs" session-start zcode >/dev/null; then
warn "zcode: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"
ok=0; agent_fatal=1
fi
@@ -3469,7 +2641,6 @@ select_dist
configure_ovcli
resolve_source_mode
prepare_marketplace_dir
-cleanup_rc_wrappers
if contains_harness claude; then
while IFS= read -r CLAUDE_BIN; do
diff --git a/examples/memory-plugin-shared/lib/MANIFEST b/examples/memory-plugin-shared/lib/MANIFEST
new file mode 100644
index 000000000..fdb9638c5
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/MANIFEST
@@ -0,0 +1,24 @@
+agent-hook-runtime.mjs
+async-writer.mjs
+batch-send.mjs
+capture-utils.mjs
+config-schema.mjs
+credentials.mjs
+debug-log.mjs
+doctor-core.mjs
+input-filters.mjs
+mcp-proxy-config.mjs
+mcp-proxy-core.mjs
+ov-http.mjs
+pending-queue.mjs
+plugin-config.mjs
+profile-inject.mjs
+recall-compress-core.mjs
+recall-core.mjs
+retryable.mjs
+session-model.mjs
+uri-guard.mjs
+workspace-config.mjs
+workspace-identity.mjs
+workspace-peer.mjs
+workspace-registry.mjs
diff --git a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
index 1a646b767..dff433cc8 100644
--- a/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
+++ b/examples/memory-plugin-shared/lib/agent-hook-runtime.mjs
@@ -3,12 +3,13 @@ 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 { createOvHttp } from "./ov-http.mjs";
import { enqueue, replayPending } from "./pending-queue.mjs";
import { buildProfileBlock } from "./profile-inject.mjs";
-import { buildRecallBlock } from "./recall-core.mjs";
+import { buildRecallBlock, isRecallEnabled } from "./recall-core.mjs";
+import { buildPluginConfig } from "./plugin-config.mjs";
import { isRetryableFailure } from "./retryable.mjs";
import { deriveHarnessSessionId, isBypassed } from "./session-model.mjs";
import { resolveEffectivePeerId } from "./workspace-peer.mjs";
@@ -17,59 +18,39 @@ 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, "-");
}
-function responseTraceId(body) {
- return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
-}
-
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`);
+/**
+ * The config for one of the thin hook harnesses.
+ *
+ * These four used to read the environment and nothing else, so `ov config
+ * switch` moved their credentials and left their behaviour behind, and an
+ * `ovcli.conf` `plugin` entry named after them was inert. They resolve through
+ * the same layers as every other harness now; only the client's own name for
+ * itself stays local.
+ *
+ * `cwd` selects the workspace layer. It defaults to this process's directory,
+ * which is all a hook knows before the payload on stdin names the session's
+ * own — the caller re-resolves once it has it. That is safe because a workspace
+ * file may not carry connection or credential keys, so the base URL and API key
+ * cannot move under a logger or fetch helper already built from the first load.
+ */
+export function loadAgentHookConfig(clientId, cwd = process.cwd()) {
return {
- ...credentials,
+ ...buildPluginConfig(clientId, {
+ cwd,
+ version: process.env.OPENVIKING_INTEGRATION_VERSION,
+ logFile: `${clientId}-hooks.log`,
+ }),
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", 10, 1),
- recallLimitConfigured: Boolean(process.env.OPENVIKING_RECALL_LIMIT),
- 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),
- writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC", true),
- debug: envBool("OPENVIKING_DEBUG", false),
- debugLogPath,
};
}
@@ -77,10 +58,14 @@ export function createAgentLogger(clientId, hookName, cfg) {
return createLogger(`${clientId}:${hookName}`, cfg);
}
-export async function readHookInput() {
+export async function readRawHookInput() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
- const raw = Buffer.concat(chunks).toString();
+ return Buffer.concat(chunks).toString();
+}
+
+export async function readHookInput() {
+ const raw = await readRawHookInput();
if (!raw.trim()) return {};
try { return JSON.parse(raw); } catch { return {}; }
}
@@ -171,34 +156,58 @@ export async function writeHookState(clientId, nativeSessionId, value) {
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 timeoutMs = Math.max(1000, Number(options.timeoutMs) || cfg.timeoutMs);
- const timer = setTimeout(() => controller.abort(), 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(() => ({}));
- const traceId = responseTraceId(body);
- if (!response.ok || body.status === "error") {
- return { ok: false, status: response.status, error: body.error || body, traceId };
- }
- return { ok: true, result: body.result ?? body, traceId };
- } catch (error) {
- return { ok: false, status: 0, error: { message: error?.message || String(error) } };
- } finally {
- clearTimeout(timer);
- }
- };
- return { fetchJSON, effectivePeer };
+/**
+ * The `fetchJSON` a hook talks through.
+ *
+ * `getActorPeerId` is a getter rather than a value because Codex only knows its
+ * peer after loading session state under the session lock, and because a stack
+ * whose every call names its own peer answers with the empty string. The
+ * workspace peer behind the default is resolved on demand so those callers do
+ * not pay for a lookup they never read.
+ */
+export function makeAgentFetchJSON(cfg, cwd = process.cwd(), {
+ defaultTimeoutMs,
+ getActorPeerId,
+ requireJsonBody = false,
+} = {}) {
+ let resolved = null;
+ const workspacePeer = () => (resolved ??= resolveEffectivePeerId({ cfg, cwd }));
+ const fetchJSON = createOvHttp(cfg, {
+ defaultTimeoutMs: defaultTimeoutMs ?? cfg.timeoutMs,
+ resolveActorPeerId: getActorPeerId || (() => workspacePeer().peerId),
+ requireJsonBody,
+ });
+ return { fetchJSON, get effectivePeer() { return workspacePeer(); } };
+}
+
+/** Park a write for the next hook to replay. Never throws: the caller is a hook. */
+export async function enqueueAgentPending(type, sessionId, payload = {}) {
+ try {
+ return await enqueue(type, sessionId, payload);
+ } catch {
+ return { ok: false };
+ }
+}
+
+/**
+ * What became of a write that failed: parked for replay, or reported once on
+ * stderr when no retry can help. `pendingQueued` / `pendingEnqueueFailed` are
+ * what the capture hooks log and what decides whether a turn is lost.
+ */
+async function notePendingWrite(type, sessionId, payload, result) {
+ if (result.ok) return result;
+ if (!isRetryableFailure(result)) {
+ const detail = result.error?.message || result.error?.code || "";
+ process.stderr.write(
+ `[ov] ${type} failed with non-retryable status ${result.status || "unknown"};`
+ + ` not enqueuing pending retry${detail ? ` (${detail})` : ""}\n`,
+ );
+ return result;
+ }
+ const pending = await enqueueAgentPending(type, sessionId, payload);
+ if (pending.ok) result.pendingQueued = true;
+ else result.pendingEnqueueFailed = true;
+ return result;
}
export async function addAgentMessage(fetchJSON, sessionId, payload) {
@@ -206,41 +215,52 @@ export async function addAgentMessage(fetchJSON, sessionId, payload) {
method: "POST",
body: JSON.stringify(payload),
});
- if (!result.ok && isRetryableFailure(result)) await enqueue("addMessage", sessionId, payload);
- return result;
+ return notePendingWrite("addMessage", sessionId, payload, result);
}
export async function addAgentMessages(fetchJSON, sessionId, payloads) {
return sendSessionMessages(fetchJSON, sessionId, payloads, { enqueueOnRetryable: true });
}
-export async function commitAgentSession(fetchJSON, sessionId, log = () => {}) {
+export async function commitAgentSession(fetchJSON, sessionId, log = () => {}, payload = {}) {
+ const body = payload || {};
const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
method: "POST",
- body: "{}",
+ body: JSON.stringify(body),
});
- let queued = false;
- if (!result.ok && isRetryableFailure(result)) {
- const pending = await enqueue("commitSession", sessionId, {});
- queued = Boolean(pending.ok);
- }
+ await notePendingWrite("commitSession", sessionId, body, result);
log("commit", {
sessionId,
ok: result.ok,
status: result.result?.status || result.status,
trace_id: result.traceId || result.result?.trace_id,
- queued,
+ queued: Boolean(result.pendingQueued),
error: result.ok ? undefined : result.error?.message || result.error?.code,
});
return result;
}
+/** Session meta, or null when the session does not exist and `autoCreate` is off. */
+export async function getAgentSession(fetchJSON, sessionId, { autoCreate = false } = {}) {
+ const query = autoCreate ? "?auto_create=true" : "";
+ const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}${query}`);
+ return result.ok ? result.result : null;
+}
+
+/** Assembled session context (includes latest_archive_overview), or null. */
+export async function getAgentSessionContext(fetchJSON, sessionId, tokenBudget = 128000) {
+ const result = await fetchJSON(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,
+ );
+ return result.ok ? result.result : null;
+}
+
export async function replayAgentPending(fetchJSON, log = () => {}) {
return replayPending(fetchJSON, log);
}
export async function recallForPrompt(fetchJSON, cfg, prompt, cwd, log = () => {}, options = {}) {
- if (!cfg.autoRecall || !String(prompt || "").trim()) return null;
+ if (!isRecallEnabled(cfg) || !String(prompt || "").trim()) return null;
const peer = resolveEffectivePeerId({ cfg, cwd });
return buildRecallBlock(fetchJSON, cfg, prompt, {
actorPeerId: peer.peerId,
@@ -261,3 +281,86 @@ export async function buildAgentProfile(fetchJSON, cfg, cwd) {
export function shouldBypassAgent(cfg, input = {}) {
return isBypassed(cfg, { sessionId: resolveNativeSessionId(input), cwd: resolveAgentCwd(input) });
}
+
+/**
+ * The opening every hook entry shares: read the payload, re-resolve the config
+ * against the session's directory, answer the two gates, then run the hook's
+ * own work and emit one envelope.
+ *
+ * `run` receives the resolved stage and returns the envelope's payload — a
+ * systemMessage, a context block, or nothing. A closed gate calls
+ * `onSkip(reason, stage)` with `"bad_stdin"`, `"disabled"` or `"bypass"`, emits
+ * an empty envelope and never runs the callback. `run` may emit early through
+ * `stage.emit` (a detaching hook has to answer before its worker starts); the
+ * envelope is written once.
+ *
+ * Both gates are predicates over `(cfg, stage)`: `enabled` says whether this
+ * hook runs at all, `bypass` whether this session is one the plugin stays out
+ * of. `sessionId` reads the session out of the payload — the default is the key
+ * Claude Code and Codex send, and a host that spells it differently, or derives
+ * it, hands over its own resolver rather than turning the gate off.
+ *
+ * The write-path preamble — the enabled gate against this process's directory,
+ * then `maybeDetach` — stays in the entry. A worker has to be spawned before
+ * stdin is consumed, and its response is the host's own.
+ */
+export async function runHookStage({
+ clientId,
+ loadConfig = (cwd) => loadAgentHookConfig(clientId, cwd),
+ input: { read = readRawHookInput, tolerant = false } = {},
+ sessionId: resolveSessionId = (payload) => payload.session_id ?? payload.sessionId,
+ gates: { enabled = null, bypass = (cfg, stage) => stage.bypassed } = {},
+ envelope = () => {},
+ onSkip = () => {},
+} = {}, run = () => undefined) {
+ let emitted = false;
+ const emit = (value) => {
+ if (emitted) return;
+ emitted = true;
+ envelope(value);
+ };
+
+ let badStdin = false;
+ const raw = await read();
+ let payload;
+ try {
+ payload = JSON.parse(tolerant ? raw || "{}" : raw);
+ } catch {
+ badStdin = !tolerant;
+ payload = {};
+ }
+ if (!payload || typeof payload !== "object") payload = {};
+
+ const cwd = resolveAgentCwd(payload);
+ const cfg = loadConfig(cwd);
+ const sessionId = resolveSessionId(payload);
+ const stage = {
+ cfg,
+ input: payload,
+ raw,
+ cwd,
+ sessionId,
+ bypassed: isBypassed(cfg, { sessionId, cwd }),
+ emit,
+ };
+
+ if (badStdin) {
+ onSkip("bad_stdin", stage);
+ emit();
+ return undefined;
+ }
+ if (cfg.enabled === false || (enabled && !enabled(cfg, stage))) {
+ onSkip("disabled", stage);
+ emit();
+ return undefined;
+ }
+ if (bypass && bypass(cfg, stage)) {
+ onSkip("bypass", stage);
+ emit();
+ return undefined;
+ }
+
+ const result = await run(stage);
+ emit(result);
+ return result;
+}
diff --git a/examples/memory-plugin-shared/lib/agent-uri-guard.mjs b/examples/memory-plugin-shared/lib/agent-uri-guard.mjs
deleted file mode 100644
index 6b98bb17a..000000000
--- a/examples/memory-plugin-shared/lib/agent-uri-guard.mjs
+++ /dev/null
@@ -1,46 +0,0 @@
-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/pi-coding-agent-extension/shared/batch-send.d.mts b/examples/memory-plugin-shared/lib/batch-send.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/batch-send.d.mts
rename to examples/memory-plugin-shared/lib/batch-send.d.mts
diff --git a/examples/pi-coding-agent-extension/shared/capture-utils.d.mts b/examples/memory-plugin-shared/lib/capture-utils.d.mts
similarity index 68%
rename from examples/pi-coding-agent-extension/shared/capture-utils.d.mts
rename to examples/memory-plugin-shared/lib/capture-utils.d.mts
index 70c40abd3..4da3e3306 100644
--- a/examples/pi-coding-agent-extension/shared/capture-utils.d.mts
+++ b/examples/memory-plugin-shared/lib/capture-utils.d.mts
@@ -1,3 +1,5 @@
+export function collectToolNamesByIdFromEntries(entries: any[]): Record<string, string>;
+export function findLastHumanTurnIndex(turns: any[]): number;
export function extractPartsFromPayload(payload: any, options?: Record<string, any>): any[];
export function extractTextFromPayload(payload: any, options?: Record<string, any>): string;
export function shouldCaptureText(text: string, role: string, cfg?: Record<string, any>): {
@@ -7,3 +9,5 @@ export function shouldCaptureText(text: string, role: string, cfg?: Record<strin
};
export function sanitizeCapturedText(text: string): string;
export function truncateCaptureText(text: string, maxChars?: number): string;
+
+export function isCaptureEnabled(cfg?: Record<string, any>): boolean;
diff --git a/examples/memory-plugin-shared/lib/capture-utils.mjs b/examples/memory-plugin-shared/lib/capture-utils.mjs
index 74e886e46..e707b2ec5 100644
--- a/examples/memory-plugin-shared/lib/capture-utils.mjs
+++ b/examples/memory-plugin-shared/lib/capture-utils.mjs
@@ -265,7 +265,13 @@ export function extractTextFromPayload(payload, options = {}) {
return chunks.join("\n\n");
}
-function collectToolNamesByIdFromEntries(entries) {
+/**
+ * Map every tool call id in a transcript to the name of the tool it invoked.
+ *
+ * A result block names the call by id only, so the name has to come from the
+ * call that preceded it. Pass the map as `toolNameById` to the extractors.
+ */
+export function collectToolNamesByIdFromEntries(entries) {
const map = {};
for (const entry of entries || []) {
const payload = entry?.payload && typeof entry.payload === "object" ? entry.payload : entry;
@@ -432,6 +438,24 @@ export function extractCaptureTurns(rolloutEntries, cfg = {}) {
return turns;
}
+/**
+ * Index of the last turn that came from a human prompt, or -1.
+ *
+ * `role === "user"` alone is not enough: normalizeCaptureRole() maps tool
+ * results onto the user role too, and those carry `tool` parts rather than
+ * `text` parts. Used by the post-compact shrink path to find where the current
+ * interaction starts.
+ */
+export function findLastHumanTurnIndex(turns) {
+ const list = Array.isArray(turns) ? turns : [];
+ for (let i = list.length - 1; i >= 0; i -= 1) {
+ const turn = list[i];
+ if (turn?.role !== "user") continue;
+ if (turn.parts?.some((part) => part?.type === "text")) return i;
+ }
+ return -1;
+}
+
export function normalizeCaptureRole(role) {
const value = normalizeType(role);
if (value === "user") return "user";
@@ -510,12 +534,24 @@ function stripInjectedDigestBlocks(text) {
return out.join("\n");
}
+/**
+ * Drop everything in a turn that the conversation did not put there.
+ *
+ * Recall injects a context block into the prompt, and the host adds notes of
+ * its own; captured back unchanged, this turn's injection becomes next turn's
+ * memory and the loop feeds on itself. Formatting the conversation did author
+ * — newlines, code fences — survives.
+ */
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, " ")
+ // Claude Code wraps its own out-of-band notes to the model in these two
+ // shapes. They are the host talking to itself, not the conversation.
+ .replace(/<system-reminder\b[^>]*>[\s\S]*?<\/system-reminder>/gi, " ")
+ .replace(/^[ \t]*\[Subagent Context\][^\n]*$/gim, " ")
.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, "")
@@ -539,6 +575,23 @@ function isPunctuationOnly(text) {
return !/[a-z0-9\u3400-\u9fff]/i.test(text);
}
+/**
+ * Is capture on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoCapture`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables capture under an older name still disables it.
+ */
+export function isCaptureEnabled(cfg = {}) {
+ for (const value of [cfg.enabled, cfg.autoCapture, cfg.capture, cfg.syncTurns]) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {}) {
const maxLength = cfg.captureMaxLength || 24000;
const sanitized = sanitizeCapturedText(text);
@@ -575,3 +628,26 @@ export function shouldCaptureText(text, role, cfg = {}, { filters = true } = {})
return { shouldCapture: true, reason: "ok", text: capped };
}
+
+/**
+ * Apply the capture filter to a list of `{ role, content }` turns.
+ *
+ * The harnesses that compose `agent-hook-runtime` used to send whatever their
+ * transcript parser produced: an acknowledgement, a slash command, a stray
+ * `ok`, or a turn far past `captureMaxLength` all reached the extractor
+ * verbatim. This is the same decision every other harness makes, in one place,
+ * so a thin harness gets it by calling rather than by reimplementing it.
+ *
+ * Returns the surviving turns with `content` replaced by the sanitized and
+ * capped text, and the dropped ones with the reason, for the debug log.
+ */
+export function filterCaptureTurns(turns, cfg = {}) {
+ const kept = [];
+ const dropped = [];
+ for (const turn of Array.isArray(turns) ? turns : []) {
+ const decision = shouldCaptureText(turn?.content, turn?.role, cfg);
+ if (decision.shouldCapture) kept.push({ ...turn, content: decision.text });
+ else dropped.push({ role: turn?.role, reason: decision.reason });
+ }
+ return { kept, dropped };
+}
diff --git a/examples/memory-plugin-shared/lib/config-schema.d.mts b/examples/memory-plugin-shared/lib/config-schema.d.mts
new file mode 100644
index 000000000..e232edbbb
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/config-schema.d.mts
@@ -0,0 +1,34 @@
+export interface Knob {
+ name: string;
+ type: "bool" | "int" | "number" | "enum" | "string" | "template" | "list";
+ default: any;
+ harness?: Record<string, any>;
+ min?: number;
+ max?: number;
+ values?: string[];
+ env?: string;
+ aliases?: string[];
+ workspace?: string;
+ sendOnlyWhenConfigured?: boolean;
+ capability: string;
+}
+
+export const CAPABILITIES: string[];
+export const KNOBS: readonly Knob[];
+export const KNOB_BY_NAME: Map<string, Knob>;
+export const KNOB_BY_KEY: Map<string, Knob>;
+export const WORKSPACE_KNOB_MAP: Record<string, string>;
+export const WORKSPACE_ENUMS: Record<string, string[] | null>;
+export const WORKSPACE_RANGES: Record<string, { min: number; max: number; integer: boolean }>;
+export const HARNESS_KEYS: Record<string, string>;
+export const HARNESS_CONFIG_KEYS: Set<string>;
+
+export function pluginConfigKeys(): Set<string>;
+export function harnessKey(harness: string): string;
+export function knobDefault(knob: Knob, harness?: string): any;
+export function coerceKnobValue(knob: Knob, raw: unknown, fallback: any): any;
+export function resolveKnobs(options?: {
+ harness?: string;
+ layers?: Array<{ name?: string; data?: Record<string, any> }>;
+ env?: Record<string, string | undefined>;
+}): { settings: Record<string, any>; configured: Set<string>; sources: Record<string, string> };
diff --git a/examples/memory-plugin-shared/lib/config-schema.mjs b/examples/memory-plugin-shared/lib/config-schema.mjs
new file mode 100644
index 000000000..5cd9f7c11
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/config-schema.mjs
@@ -0,0 +1,358 @@
+/**
+ * Every knob a memory plugin reads, declared once.
+ *
+ * A setting stayed uniform across harnesses only when a shared module read it
+ * on the hot path: `recallLimit`, `scoreThreshold` and `captureMaxLength` agree
+ * everywhere because `recall-core` and `capture-utils` read them. Everything
+ * else drifted — the same switch is `autoRecall` in three loaders, an
+ * `autoRecall` *object* in opencode, `syncTurns` in dsh and pi, and absent from
+ * the thin hook runtime — because each loader hand-wrote its own list and the
+ * author picked a name. Three more lists then had to be kept in step by hand:
+ * the doctor's known-knob set, the workspace file's dotted-key map, and the
+ * implicit inventory inside `loadAgentHookConfig`.
+ *
+ * This module is the one list. The others are projections of it:
+ * `pluginConfigKeys()` for the doctor, `WORKSPACE_KNOB_MAP` for the workspace
+ * file, and `resolveKnobs()` for every loader. A knob added here reaches all of
+ * them; a knob spelled wrong reaches none.
+ *
+ * Declaration fields:
+ * name canonical key, and the property the loaders read
+ * type bool | int | number | enum | string | list
+ * default value when no layer supplies one
+ * harness per-harness default, where one genuinely differs
+ * min/max clamped, not rejected: a config file must not kill a hook
+ * values the enum's members; anything else falls back to the default
+ * env OPENVIKING_* variable, the highest-priority layer
+ * aliases older spellings, honoured forever; the doctor names them
+ * workspace dotted key in `.openviking/config.json`
+ * capability which capability owns it, for the switches in recall/capture
+ * sendOnlyWhenConfigured
+ * the request omits this field unless a layer actually set it,
+ * so the server's own default stands. Loaders project the flag
+ * as `<name>Configured` and `recall-core` reads it from there.
+ */
+
+export const CAPABILITIES = ["connection", "peer", "recall", "capture", "session", "debug"];
+
+/** @type {ReadonlyArray<object>} */
+export const KNOBS = [
+ // ── connection and identity ────────────────────────────────────────────
+ // Credentials resolve through `credentials.mjs`; these entries exist so the
+ // doctor recognises them inside `plugin` and so ov.conf's harness section
+ // keeps working.
+ { name: "enabled", type: "bool", default: true, env: "OPENVIKING_MEMORY_ENABLED", capability: "connection" },
+ { name: "apiKey", type: "string", default: "", capability: "connection" },
+ { name: "accountId", type: "string", default: "", capability: "connection" },
+ { name: "userId", type: "string", default: "", capability: "connection" },
+ { name: "authMode", type: "enum", values: ["trusted", "api_key"], default: "", env: "OPENVIKING_AUTH_MODE", aliases: ["auth_mode"], capability: "connection" },
+ {
+ name: "timeoutMs",
+ type: "int",
+ default: 15000,
+ // opencode drives an editor session that tolerates a slower call; dsh runs
+ // inside a chat host that does not.
+ harness: { opencode: 30000, dsh: 10000 },
+ min: 1000,
+ max: 300000,
+ env: "OPENVIKING_TIMEOUT_MS",
+ aliases: ["requestTimeoutMs"],
+ capability: "connection",
+ },
+ { name: "mcpEnabled", type: "bool", default: true, capability: "connection" },
+ { name: "mcpToolCallTimeoutMs", type: "int", default: 60000, min: 1000, max: 600000, capability: "connection" },
+ { name: "dataDir", type: "string", default: "", capability: "connection" },
+
+ { name: "peerId", type: "string", default: "", env: "OPENVIKING_PEER_ID", aliases: ["peer_id"], workspace: "peer.id", capability: "peer" },
+ { name: "peerSource", type: "template", default: "", env: "OPENVIKING_PEER_SOURCE", workspace: "peer.source", capability: "peer" },
+ { name: "workspacePeer", type: "bool", default: true, env: "OPENVIKING_WORKSPACE_PEER", capability: "peer" },
+
+ // ── recall ────────────────────────────────────────────────────────────
+ {
+ name: "autoRecall",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_RECALL",
+ workspace: "recall.enabled",
+ capability: "recall",
+ },
+ { name: "recallLimit", type: "int", default: 10, min: 1, max: 50, env: "OPENVIKING_RECALL_LIMIT", workspace: "recall.max_items", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "scoreThreshold", type: "number", default: 0.35, min: 0, max: 1, env: "OPENVIKING_SCORE_THRESHOLD", aliases: ["recallScoreThreshold"], workspace: "recall.score_threshold", capability: "recall" },
+ { name: "minQueryLength", type: "int", default: 3, min: 1, max: 64, env: "OPENVIKING_MIN_QUERY_LENGTH", aliases: ["recallMinQueryLength"], capability: "recall" },
+ { name: "recallTokenBudget", type: "int", default: 2000, min: 200, max: 50000, env: "OPENVIKING_RECALL_TOKEN_BUDGET", aliases: ["recallBudget"], capability: "recall" },
+ { name: "recallMaxContentChars", type: "int", default: 500, min: 100, max: 5000, env: "OPENVIKING_RECALL_MAX_CONTENT_CHARS", capability: "recall" },
+ { name: "recallPreferAbstract", type: "bool", default: true, env: "OPENVIKING_RECALL_PREFER_ABSTRACT", capability: "recall" },
+ { name: "recallPeerScope", type: "enum", values: ["all", "actor"], default: "all", env: "OPENVIKING_RECALL_PEER_SCOPE", workspace: "recall.peer_scope", capability: "recall" },
+ { name: "recallDedupTurns", type: "int", default: 5, min: 0, max: 20, env: "OPENVIKING_RECALL_DEDUP_TURNS", workspace: "recall.dedup_turns", capability: "recall" },
+ { name: "recallMaxTokens", type: "int", default: 1600, min: 64, max: 200000, env: "OPENVIKING_RECALL_MAX_TOKENS", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallQueryExpansion", type: "enum", values: ["auto", "off"], default: "auto", env: "OPENVIKING_RECALL_QUERY_EXPANSION", sendOnlyWhenConfigured: true, capability: "recall" },
+ { name: "recallTimeoutMs", type: "int", default: 120000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_TIMEOUT_MS", capability: "recall" },
+ // 0 keeps the built-in default, which outlasts the server's rewrite fuse.
+ { name: "recallContextTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_CONTEXT_TIMEOUT_MS", capability: "recall" },
+ { name: "logRankingDetails", type: "bool", default: false, env: "OPENVIKING_LOG_RANKING_DETAILS", capability: "recall" },
+ { name: "recallLedger", type: "bool", default: true, env: "OPENVIKING_RECALL_LEDGER", capability: "recall" },
+ { name: "recallQueryFilters", type: "list", default: [], env: "OPENVIKING_RECALL_QUERY_FILTERS", capability: "recall" },
+
+ // Digest compression. Claude Code reads this as the tri-state
+ // off/client/server/auto through `normalizeRewriteMode`; Codex reads the same
+ // key as on/off. Both spellings stay declared so neither harness's users are
+ // told their config is a typo.
+ { name: "recallCompress", type: "string", default: "auto", env: "OPENVIKING_RECALL_COMPRESS", aliases: ["recallRewrite"], capability: "recall" },
+ { name: "recallCompressModel", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_MODEL", capability: "recall" },
+ { name: "recallCompressBaseUrl", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_BASE_URL", capability: "recall" },
+ { name: "recallCompressThinking", type: "string", default: "", env: "OPENVIKING_RECALL_COMPRESS_THINKING", aliases: ["recallCompressReasoningEffort"], capability: "recall" },
+ // 0 means "derive from recallTimeoutMs" — the loader that owns the fallback
+ // is the one that knows the request budget it has to fit inside.
+ { name: "recallCompressTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectOnStartup", type: "bool", default: true, env: "OPENVIKING_RECALL_COMPRESS_DETECT_ON_STARTUP", capability: "recall" },
+ { name: "recallCompressDetectTimeoutMs", type: "int", default: 15000, min: 1000, max: 600000, env: "OPENVIKING_RECALL_COMPRESS_DETECT_TIMEOUT_MS", capability: "recall" },
+ { name: "recallCompressDetectTtlMs", type: "int", default: 604800000, min: 0, capability: "recall", env: "OPENVIKING_RECALL_COMPRESS_DETECT_TTL_MS" },
+ { name: "recallCompressMinInputChars", type: "int", default: 1500, min: 0, max: 100000, env: "OPENVIKING_RECALL_COMPRESS_MIN_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxInputChars", type: "int", default: 18000, min: 1000, max: 200000, env: "OPENVIKING_RECALL_COMPRESS_MAX_INPUT_CHARS", capability: "recall" },
+ { name: "recallCompressMaxBullets", type: "int", default: 6, min: 1, max: 50, env: "OPENVIKING_RECALL_COMPRESS_MAX_BULLETS", sendOnlyWhenConfigured: true, capability: "recall" },
+
+ // ── capture ───────────────────────────────────────────────────────────
+ // `syncTurns` is dsh and pi's spelling of the same switch. It stays an alias
+ // rather than a second knob so `ov config switch` moves both.
+ {
+ name: "autoCapture",
+ type: "bool",
+ default: true,
+ env: "OPENVIKING_AUTO_CAPTURE",
+ aliases: ["syncTurns"],
+ workspace: "capture.enabled",
+ capability: "capture",
+ },
+ { name: "captureMode", type: "enum", values: ["semantic", "keyword"], default: "semantic", env: "OPENVIKING_CAPTURE_MODE", capability: "capture" },
+ { name: "captureMaxLength", type: "int", default: 24000, min: 200, max: 100000, env: "OPENVIKING_CAPTURE_MAX_LENGTH", capability: "capture" },
+ // Tool output is reported verbatim; the server owns truncation via
+ // tool_output_externalization. This cap only guards pathological payloads.
+ { name: "captureToolMaxChars", type: "int", default: 1000000, min: 200, max: 1000000, env: "OPENVIKING_CAPTURE_TOOL_MAX_CHARS", capability: "capture" },
+ // Default true: a memory plugin that only sees the user's half of the
+ // conversation extracts noticeably worse.
+ { name: "captureAssistantTurns", type: "bool", default: true, env: "OPENVIKING_CAPTURE_ASSISTANT_TURNS", capability: "capture" },
+ { name: "captureLastAssistantOnStop", type: "bool", default: true, env: "OPENVIKING_CAPTURE_LAST_ASSISTANT_ON_STOP", capability: "capture" },
+ { name: "captureToolResults", type: "bool", default: false, env: "OPENVIKING_CAPTURE_TOOL_RESULTS", capability: "capture" },
+ { name: "captureFilters", type: "list", default: [], env: "OPENVIKING_CAPTURE_FILTERS", capability: "capture" },
+ // 0 means "derive from timeoutMs": a write gets a longer budget than a read.
+ { name: "captureTimeoutMs", type: "int", default: 0, min: 0, max: 600000, env: "OPENVIKING_CAPTURE_TIMEOUT_MS", capability: "capture" },
+ { name: "commitTokenThreshold", type: "int", default: 20000, min: 1000, max: 1000000, env: "OPENVIKING_COMMIT_TOKEN_THRESHOLD", workspace: "capture.commit_token_threshold", capability: "capture" },
+ { name: "commitKeepRecentCount", type: "int", default: 10, min: 0, max: 1000, env: "OPENVIKING_COMMIT_KEEP_RECENT_COUNT", capability: "capture" },
+ { name: "commitTurnThreshold", type: "int", default: 8, min: 1, max: 1000, env: "OPENVIKING_COMMIT_TURN_THRESHOLD", capability: "capture" },
+ { name: "autoCommitOnCompact", type: "bool", default: true, env: "OPENVIKING_AUTO_COMMIT_ON_COMPACT", capability: "capture" },
+ { name: "writePathAsync", type: "bool", default: true, env: "OPENVIKING_WRITE_PATH_ASYNC", capability: "capture" },
+
+ // ── session lifecycle ─────────────────────────────────────────────────
+ { name: "noAutoInject", type: "bool", default: false, env: "OPENVIKING_NO_AUTO_INJECT", capability: "session" },
+ { name: "profileTokenBudget", type: "int", default: 10000, min: 500, max: 50000, env: "OPENVIKING_PROFILE_TOKEN_BUDGET", aliases: ["profileBudget"], capability: "session" },
+ { name: "resumeContextBudget", type: "int", default: 32000, min: 1024, max: 128000, env: "OPENVIKING_RESUME_CONTEXT_BUDGET", capability: "session" },
+ { name: "resumeArchiveInject", type: "bool", default: true, env: "OPENVIKING_RESUME_ARCHIVE_INJECT", capability: "session" },
+ { name: "resumeArchiveTokenBudget", type: "int", default: 32000, min: 0, max: 128000, env: "OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET", capability: "session" },
+ { name: "resumeArchiveMaxChars", type: "int", default: 6000, min: 1000, max: 200000, env: "OPENVIKING_RESUME_ARCHIVE_MAX_CHARS", capability: "session" },
+ { name: "skillExperience", type: "bool", default: false, env: "OPENVIKING_SKILL_EXPERIENCE", capability: "session" },
+ { name: "skillExperienceLimit", type: "int", default: 3, min: 1, max: 50, env: "OPENVIKING_SKILL_EXPERIENCE_LIMIT", capability: "session" },
+ { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" },
+ { name: "repoContext", type: "bool", default: true, capability: "session" },
+ { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" },
+
+ { name: "takeoverEnabled", type: "bool", default: true, env: "OPENVIKING_TAKEOVER", capability: "session" },
+ { name: "takeoverTokenThreshold", type: "int", default: 30000, min: 1, max: 1000000, capability: "session" },
+ { name: "takeoverKeepRecentTurns", type: "int", default: 3, min: 0, max: 100, capability: "session" },
+ { name: "takeoverOverviewBudget", type: "int", default: 3000, min: 100, max: 50000, capability: "session" },
+ { name: "takeoverOverviewPollMs", type: "int", default: 2000, min: 0, max: 60000, capability: "session" },
+ { name: "takeoverOverviewPollMax", type: "int", default: 15, min: 1, max: 120, capability: "session" },
+
+ { name: "bypassSession", type: "bool", default: false, env: "OPENVIKING_BYPASS_SESSION", capability: "session" },
+ {
+ name: "bypassSessionPatterns",
+ type: "list",
+ default: [],
+ env: "OPENVIKING_BYPASS_SESSION_PATTERNS",
+ // pi shipped this under its own name before the shared matcher existed.
+ aliases: ["bypassPatterns"],
+ workspace: "bypass.session_patterns",
+ capability: "session",
+ },
+
+ // ── debug ─────────────────────────────────────────────────────────────
+ { name: "debug", type: "bool", default: false, env: "OPENVIKING_DEBUG", capability: "debug" },
+ // The default path is per-harness and built from a log directory the loader
+ // owns, so the schema only carries what a user set.
+ { name: "debugLogPath", type: "string", default: "", env: "OPENVIKING_DEBUG_LOG", capability: "debug" },
+ { name: "logLevel", type: "enum", values: ["silent", "error", "info"], default: "error", env: "OPENVIKING_LOG_LEVEL", capability: "debug" },
+];
+
+export const KNOB_BY_NAME = new Map(KNOBS.map((knob) => [knob.name, knob]));
+
+/** Every accepted spelling → the canonical knob it means. */
+export const KNOB_BY_KEY = new Map();
+for (const knob of KNOBS) {
+ KNOB_BY_KEY.set(knob.name, knob);
+ for (const alias of knob.aliases || []) KNOB_BY_KEY.set(alias, knob);
+}
+
+/** Every key a user may legitimately write in `ovcli.conf`'s plugin section. */
+export function pluginConfigKeys() {
+ return new Set(KNOB_BY_KEY.keys());
+}
+
+/** The workspace file's dotted keys → the knob each one sets. */
+export const WORKSPACE_KNOB_MAP = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.name]),
+);
+
+/** The enum members and clamps the workspace validator reports on. */
+export const WORKSPACE_ENUMS = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace).map((knob) => [knob.workspace, knob.values || null]),
+);
+
+export const WORKSPACE_RANGES = Object.fromEntries(
+ KNOBS.filter((knob) => knob.workspace && knob.min !== undefined && knob.max !== undefined)
+ .map((knob) => [knob.workspace, {
+ min: knob.min,
+ max: knob.max,
+ integer: knob.type === "int",
+ }]),
+);
+
+/**
+ * The harnesses that may appear as a per-harness object inside `plugin`.
+ *
+ * The key is snake_case because that is what ov.conf's own sections use; the
+ * hyphenated spelling a host calls itself (`claude-code`, `trae-cn`) is
+ * accepted too, so a user who copies the harness name out of the installer
+ * lands on the right override instead of on a silent no-op.
+ */
+export const HARNESS_KEYS = {
+ claudeCode: "claude_code",
+ codex: "codex",
+ cursor: "cursor",
+ trae: "trae",
+ traeCn: "trae_cn",
+ zcode: "zcode",
+ opencode: "opencode",
+ dsh: "dsh",
+ pi: "pi",
+ openclaw: "openclaw",
+};
+
+export function harnessKey(harness) {
+ return String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+}
+
+/** Both accepted spellings of every harness, for the `plugin` section. */
+export const HARNESS_CONFIG_KEYS = new Set(
+ Object.values(HARNESS_KEYS).flatMap((key) => [key, key.replace(/_/g, "-")]),
+);
+
+export function knobDefault(knob, harness = "") {
+ if (harness && knob.harness && knob.harness[harness] !== undefined) return knob.harness[harness];
+ return Array.isArray(knob.default) ? [...knob.default] : knob.default;
+}
+
+const TRUE_WORDS = ["1", "true", "yes", "on"];
+const FALSE_WORDS = ["0", "false", "no", "off"];
+
+/**
+ * Coerce one raw value to the knob's type.
+ *
+ * A value out of range is clamped and a value of the wrong shape falls back to
+ * the default: a hook that dies because someone typed a letter into a number
+ * would take the host's session down with it.
+ */
+export function coerceKnobValue(knob, raw, fallback) {
+ if (raw === undefined || raw === null) return fallback;
+ switch (knob.type) {
+ case "bool": {
+ if (typeof raw === "boolean") return raw;
+ const word = String(raw).trim().toLowerCase();
+ if (TRUE_WORDS.includes(word)) return true;
+ if (FALSE_WORDS.includes(word)) return false;
+ return fallback;
+ }
+ case "int":
+ case "number": {
+ if (typeof raw === "string" && !raw.trim()) return fallback;
+ const value = knob.type === "int" ? Math.round(Number(raw)) : Number(raw);
+ if (!Number.isFinite(value)) return fallback;
+ const floored = knob.min === undefined ? value : Math.max(knob.min, value);
+ return knob.max === undefined ? floored : Math.min(knob.max, floored);
+ }
+ case "enum": {
+ const word = String(raw ?? "").trim();
+ return (knob.values || []).includes(word) ? word : fallback;
+ }
+ // A peer template may be one string or an ordered list of fallbacks, and
+ // `String([a, b])` would quietly turn the list into one bogus template.
+ case "template": {
+ if (Array.isArray(raw)) {
+ const items = raw.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ return items.length ? items : fallback;
+ }
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ case "list": {
+ const items = Array.isArray(raw)
+ ? raw
+ : typeof raw === "string" ? raw.split(",") : null;
+ if (!items) return fallback;
+ return items.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
+ }
+ default: {
+ const text = String(raw ?? "").trim();
+ return text ? text : fallback;
+ }
+ }
+}
+
+/**
+ * Resolve every knob through the layers, lowest priority first.
+ *
+ * `layers` is `[{ name, data }]`; `env` is the top layer and needs no entry.
+ * Returns the settings plus the names a layer actually supplied, which is what
+ * the `*Configured` flags report — several call sites send a field to the
+ * server only when the user asked for it, and a default must not look asked-for.
+ */
+export function resolveKnobs({ harness = "", layers = [], env = {} } = {}) {
+ const settings = {};
+ const configured = new Set();
+ const sources = {};
+ // A value that would not parse is not a configuration: without this sentinel
+ // `recallLimit: "abc"` would report as configured and send a default to the
+ // server dressed up as the user's choice.
+ const UNPARSEABLE = Symbol("unparseable");
+
+ const take = (knob, raw, source, current) => {
+ const value = coerceKnobValue(knob, raw, UNPARSEABLE);
+ if (value === UNPARSEABLE) return current;
+ configured.add(knob.name);
+ sources[knob.name] = source;
+ return value;
+ };
+
+ for (const knob of KNOBS) {
+ let value = knobDefault(knob, harness);
+ for (const layer of layers) {
+ const data = layer?.data;
+ if (!data || typeof data !== "object") continue;
+ // Aliases first so the canonical name wins when one layer carries both:
+ // a file with `recallCompressThinking` beside its older
+ // `recallCompressReasoningEffort` means the newer one.
+ for (const key of [...(knob.aliases || []), knob.name]) {
+ if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
+ if (data[key] === undefined) continue;
+ value = take(knob, data[key], layer.name || "file", value);
+ }
+ }
+ if (knob.env) {
+ const raw = env[knob.env];
+ if (raw !== undefined && raw !== null && String(raw) !== "") {
+ value = take(knob, raw, "env", value);
+ }
+ }
+ settings[knob.name] = value;
+ }
+
+ return { settings, configured, sources };
+}
diff --git a/examples/memory-plugin-shared/lib/credentials.d.mts b/examples/memory-plugin-shared/lib/credentials.d.mts
new file mode 100644
index 000000000..e45ac93c4
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/credentials.d.mts
@@ -0,0 +1,60 @@
+export function buildUserAgent(harness: string, version?: string): string;
+
+export function readManifestVersion(manifest: string | URL): string;
+
+export function resolveAuthMode(input?: {
+ settings?: Record<string, unknown>;
+ ovFile?: Record<string, unknown>;
+ account?: string;
+ user?: string;
+}): { authMode: string; sendIdentityHeaders: boolean };
+
+export function resolveOpenVikingCredentials(
+ env?: Record<string, string | undefined>,
+ harness?: string,
+ plugin?: { apiKey?: string },
+): {
+ credentialSource: string;
+ apiKeySource: string;
+ credentialPath: string;
+ cliPath: string;
+ cliPathCandidate: string;
+ ovPath: string;
+ cliFile: Record<string, unknown>;
+ ovFile: Record<string, unknown>;
+ baseUrl: string;
+ mcpUrl: string;
+ apiKey: string;
+ account: string;
+ user: string;
+ peerId: string;
+ hasApiKey: boolean;
+};
+
+export function buildProxyConnection(
+ harness: string,
+ options?: {
+ env?: Record<string, string | undefined>;
+ manifestUrl?: string | URL;
+ version?: string;
+ },
+): {
+ harness: string;
+ userAgent: string;
+ baseUrl: string;
+ mcpUrl: string;
+ apiKey: string;
+ account: string;
+ user: string;
+ peerId: string;
+ authMode: string;
+ sendIdentityHeaders: boolean;
+ credentialSource: string;
+ apiKeySource: string;
+ credentialPath: string;
+ hasApiKey: boolean;
+ watchedPaths: string[];
+ timeoutMs: number;
+ debug: boolean;
+ debugLogPath: string;
+};
diff --git a/examples/memory-plugin-shared/lib/credentials.mjs b/examples/memory-plugin-shared/lib/credentials.mjs
index 7d6000a8b..593bf08a4 100644
--- a/examples/memory-plugin-shared/lib/credentials.mjs
+++ b/examples/memory-plugin-shared/lib/credentials.mjs
@@ -6,6 +6,8 @@ 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";
+const DEFAULT_TIMEOUT_MS = 15000;
+const MIN_TIMEOUT_MS = 1000;
function str(val, fallback = "") {
if (typeof val === "string" && val.trim()) return val.trim();
@@ -107,6 +109,45 @@ export function loadCredentialFiles(env = process.env) {
};
}
+/**
+ * The calling harness's own section of ov.conf.
+ *
+ * ov.conf spells its sections snake_case while a host may call itself
+ * `claude-code` or `trae-cn`, so both spellings land on the same block. The
+ * normalization stays inline rather than importing `config-schema.mjs`, which
+ * the portable agent-plugins bundle would then have to ship as well.
+ */
+function harnessSection(ovFile, harness) {
+ const key = String(harness || "").trim().toLowerCase().replace(/-/g, "_");
+ const section = key ? ovFile[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+const AUTH_MODES = ["trusted", "api_key"];
+
+function normalizeAuthMode(value) {
+ const mode = str(value, "").toLowerCase();
+ return AUTH_MODES.includes(mode) ? mode : "";
+}
+
+/**
+ * Which auth mode the server is in, and with it whether the identity headers
+ * may go on the wire.
+ *
+ * An `api_key` server reads the account and the user out of the key and ignores
+ * `X-OpenViking-Account` / `X-OpenViking-User`, so sending them there tells
+ * every proxy on the path who the operator is and buys nothing. A named mode
+ * wins; ov.conf's server block answers next; failing both, a credential layer
+ * that supplied an identity at all means the deployment expects one.
+ */
+export function resolveAuthMode({ settings = {}, ovFile = {}, account = "", user = "" } = {}) {
+ const server = ovFile.server || {};
+ const authMode = normalizeAuthMode(settings.authMode)
+ || normalizeAuthMode(server.auth_mode)
+ || ((account || user) ? "trusted" : "api_key");
+ return { authMode, sendIdentityHeaders: authMode === "trusted" };
+}
+
function sourceMode(env) {
const raw = str(env.OPENVIKING_CREDENTIAL_SOURCE, str(env.OPENVIKING_CREDENTIALS_SOURCE, "auto"))
.toLowerCase();
@@ -143,40 +184,58 @@ function deriveBaseUrl({ env, cliFile, ovFile, mode, useCli }) {
return `http://${host}:${port}`;
}
-export function resolveOpenVikingCredentials(env = process.env) {
+/**
+ * `harness` names whose ov.conf section supplies the legacy fallback. It sits
+ * where it always did — after ovcli.conf, before `server.root_api_key` — but a
+ * harness now reads its own section instead of every one of them reading
+ * codex's. The default keeps codex, the only caller that never passes one.
+ *
+ * `plugin` carries the `apiKey`, `accountId` and `userId` ovcli.conf's `plugin`
+ * section named, which this module cannot read for itself: resolving that
+ * section needs the knob schema, and the portable bundles would then have to
+ * ship it. All three rank where the file they come from ranks — under
+ * ovcli.conf's own fields, over ov.conf.
+ */
+export function resolveOpenVikingCredentials(env = process.env, harness = "codex", plugin = {}) {
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 cx = harnessSection(files.ovFile, harness);
const server = files.ovFile.server || {};
const baseUrl = deriveBaseUrl({ env, ...files, mode, useCli });
+ const pluginApiKey = str(plugin?.apiKey, "");
const apiKey = useCli
- ? str(files.cliFile.api_key, "")
+ ? (str(files.cliFile.api_key, "") || pluginApiKey)
: (
str(env.OPENVIKING_BEARER_TOKEN, "") ||
str(env.OPENVIKING_API_KEY, "") ||
str(files.cliFile.api_key, "") ||
+ pluginApiKey ||
str(cx.apiKey, "") ||
str(server.root_api_key, "")
);
+ const pluginAccount = str(plugin?.accountId, "");
const account = useCli
- ? str(files.cliFile.account, str(files.cliFile.account_id, ""))
+ ? (str(files.cliFile.account, str(files.cliFile.account_id, "")) || pluginAccount)
: (
str(env.OPENVIKING_ACCOUNT, "") ||
str(files.cliFile.account, str(files.cliFile.account_id, "")) ||
+ pluginAccount ||
str(cx.accountId, "")
);
+ const pluginUser = str(plugin?.userId, "");
const user = useCli
- ? str(files.cliFile.user, str(files.cliFile.user_id, ""))
+ ? (str(files.cliFile.user, str(files.cliFile.user_id, "")) || pluginUser)
: (
str(env.OPENVIKING_USER, "") ||
str(files.cliFile.user, str(files.cliFile.user_id, "")) ||
+ pluginUser ||
str(cx.userId, "")
);
@@ -191,19 +250,31 @@ export function resolveOpenVikingCredentials(env = process.env) {
const explicitMcpUrl = str(env.OPENVIKING_MCP_URL, "");
const mcpUrl = (mode !== "cli" && explicitMcpUrl) ? explicitMcpUrl : `${baseUrl.replace(/\/+$/, "")}/mcp`;
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
+ // Which layer actually supplied the api_key, following the same chain, and
+ // the file behind it — empty when the key came from the environment or was
+ // never found. `apiKeySource` is what a doctor and a 401 hint report; the
+ // credential *source* beside it is the mode the chain ran in, not a file.
+ let apiKeySource = "none";
let credentialPath = "";
if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
+ if (useCli) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) {
+ apiKeySource = "env";
+ } else if (str(files.cliFile.api_key, "") || pluginApiKey) {
+ apiKeySource = "ovcli";
+ credentialPath = files.cliPath;
+ } else {
+ apiKeySource = "ov";
+ credentialPath = files.ovPath;
+ }
}
return {
...files,
credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
+ apiKeySource,
credentialPath,
baseUrl,
mcpUrl,
@@ -215,6 +286,71 @@ export function resolveOpenVikingCredentials(env = process.env) {
};
}
+function envFlag(env, name) {
+ const raw = str(env[name], "").toLowerCase();
+ return raw === "1" || raw === "true" || raw === "yes";
+}
+
+function clampTimeout(value) {
+ const raw = str(value, "");
+ const parsed = raw ? Number(raw) : NaN;
+ return Math.max(MIN_TIMEOUT_MS, Math.floor(Number.isFinite(parsed) ? parsed : DEFAULT_TIMEOUT_MS));
+}
+
+/**
+ * Everything a stdio MCP proxy needs, for a package that ships no hooks.
+ *
+ * `buildPluginConfig` answers the same question one layer up, but reaching it
+ * means vendoring the knob schema and the workspace layers — a closure the
+ * portable agent-plugins bundle would carry in git to send one HTTP header.
+ * This is the connection half alone: the credential chain, the auth mode that
+ * decides whether the identity headers may go on the wire, the User-Agent, the
+ * request timeout, and the debug log.
+ *
+ * The api_key ends at `server.root_api_key` even when ovcli.conf pinned the
+ * chain to itself. A portable package has no installer to migrate anyone, so
+ * an install that names only a `url` there keeps the key it has always used.
+ */
+export function buildProxyConnection(harness, { env = process.env, manifestUrl = "", version = "" } = {}) {
+ const name = str(harness);
+ const credentials = resolveOpenVikingCredentials(env, name);
+
+ let { apiKey, apiKeySource, credentialPath } = credentials;
+ if (!apiKey) {
+ apiKey = str(credentials.ovFile?.server?.root_api_key);
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+
+ return {
+ harness: name,
+ userAgent: buildUserAgent(name, str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "")),
+ baseUrl: credentials.baseUrl,
+ mcpUrl: credentials.mcpUrl,
+ apiKey,
+ account: credentials.account,
+ user: credentials.user,
+ peerId: credentials.peerId,
+ ...resolveAuthMode({
+ settings: { authMode: env.OPENVIKING_AUTH_MODE },
+ ovFile: credentials.ovFile,
+ account: credentials.account,
+ user: credentials.user,
+ }),
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ watchedPaths: [credentials.cliPath, credentials.ovPath, credentials.cliPathCandidate],
+ timeoutMs: clampTimeout(env.OPENVIKING_TIMEOUT_MS),
+ debug: envFlag(env, "OPENVIKING_DEBUG"),
+ debugLogPath: str(env.OPENVIKING_DEBUG_LOG)
+ || join(homedir(), ".openviking", "logs", `${name}.log`),
+ };
+}
+
function main() {
const cmd = process.argv[2] || "";
if (cmd === "mcp-url") {
@@ -229,7 +365,7 @@ function main() {
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.stderr.write("usage: credentials.mjs <mcp-url|has-api-key|has-peer-id>\n");
process.exitCode = 2;
}
diff --git a/examples/pi-coding-agent-extension/shared/debug-log.d.mts b/examples/memory-plugin-shared/lib/debug-log.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/debug-log.d.mts
rename to examples/memory-plugin-shared/lib/debug-log.d.mts
diff --git a/examples/memory-plugin-shared/lib/doctor-core.mjs b/examples/memory-plugin-shared/lib/doctor-core.mjs
index 8045a47f0..6d596af77 100644
--- a/examples/memory-plugin-shared/lib/doctor-core.mjs
+++ b/examples/memory-plugin-shared/lib/doctor-core.mjs
@@ -6,7 +6,9 @@
* state directory) and delegates everything that is the same everywhere to
* this module: config-file inspection, API key display, base URL linting,
* environment sweep, server probes and their interpretation, state/log
- * inspection, and report rendering.
+ * inspection, and report rendering. `runDoctor(hostSpec)` owns the run itself:
+ * the argument parsing, the section order, the `--json` envelope and the exit
+ * code, calling back into the host for the sections only it can produce.
*
* Nothing here reads harness config; callers pass a resolved connection
* `{ baseUrl, apiKey, account, user, peerId, userAgent }`.
@@ -15,12 +17,15 @@
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { join, resolve as resolvePath } from "node:path";
+import { HARNESS_CONFIG_KEYS, HARNESS_KEYS, harnessKey, KNOB_BY_NAME, pluginConfigKeys } from "./config-schema.mjs";
+import { buildOvHeaders } from "./ov-http.mjs";
import { resolveWorkspaceSettings } from "./plugin-config.mjs";
import { peerScopeMemoPath } from "./recall-core.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE, workspaceConfigPaths } from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId } from "./workspace-peer.mjs";
import { entryPath } from "./workspace-registry.mjs";
/**
@@ -310,32 +315,13 @@ export function unknownOvcliKeys(data) {
*
* `plugin` is on the allowlist above, which used to mean everything inside it
* went unchecked — so `peerSorce` sat there doing nothing with no complaint.
- * `plugin-known-keys.test.mjs` derives this set from the two loaders and fails
- * when they diverge, so it cannot rot into a list that rejects a real knob.
+ * The set is the schema's own key list, aliases included, so it cannot rot into
+ * a list that rejects a real knob.
*/
-export const KNOWN_PLUGIN_KEYS = new Set([
- "apiKey", "accountId", "userId", "auth_mode", "authMode", "enabled", "debug", "timeoutMs",
- "peerId", "peer_id", "peerSource", "workspacePeer",
- "autoRecall", "autoCapture", "noAutoInject", "writePathAsync", "minQueryLength",
- "bypassSessionPatterns",
- "recallLimit", "recallMaxTokens", "recallMaxContentChars", "recallTokenBudget",
- "recallPeerScope", "recallDedupTurns", "recallQueryExpansion", "recallPreferAbstract",
- "recallRewrite", "recallContextTimeoutMs", "recallTimeoutMs", "scoreThreshold",
- "recallCompress", "recallCompressMaxBullets", "recallCompressMaxInputChars",
- "recallCompressMinInputChars", "recallCompressBaseUrl", "recallCompressModel",
- "recallCompressThinking", "recallCompressReasoningEffort", "recallCompressTimeoutMs",
- "recallCompressDetectOnStartup", "recallCompressDetectTimeoutMs", "recallCompressDetectTtlMs",
- "recallQueryFilters", "captureFilters",
- "captureMode", "captureMaxLength", "captureTimeoutMs", "captureToolMaxChars",
- "captureAssistantTurns", "captureLastAssistantOnStop", "logRankingDetails",
- "commitTokenThreshold", "commitKeepRecentCount", "autoCommitOnCompact",
- "profileTokenBudget", "resumeContextBudget", "resumeArchiveInject",
- "resumeArchiveMaxChars", "resumeArchiveTokenBudget",
- "skillExperience", "skillExperienceLimit",
-]);
+export const KNOWN_PLUGIN_KEYS = pluginConfigKeys();
/** Nested objects in `plugin` are per-harness overrides, not knobs. */
-const PLUGIN_HARNESS_KEYS = new Set(["claude_code", "codex"]);
+const PLUGIN_HARNESS_KEYS = HARNESS_CONFIG_KEYS;
function nearestKnownKey(key) {
// Levenshtein would be overkill; a typo that matters is almost always one
@@ -501,14 +487,10 @@ export async function httpProbe({ url, method = "GET", headers = {}, body, timeo
return out;
}
+// A connection record carries no `sendIdentityHeaders`: the doctor asks with
+// the identity and reports whatever the server echoes back.
function authHeaders(conn, { identity = true } = {}) {
- const headers = { "Content-Type": "application/json" };
- if (conn.apiKey) headers["Authorization"] = `Bearer ${conn.apiKey}`;
- if (identity && conn.account) headers["X-OpenViking-Account"] = conn.account;
- if (identity && conn.user) headers["X-OpenViking-User"] = conn.user;
- if (conn.peerId) headers["X-OpenViking-Actor-Peer"] = conn.peerId;
- if (conn.userAgent) headers["User-Agent"] = conn.userAgent;
- return headers;
+ return buildOvHeaders(conn, { actorPeerId: conn.peerId, identityHeaders: identity });
}
export function serverErrorMessage(probe) {
@@ -779,7 +761,7 @@ export function gitignoreHidesWorkspaceConfig(root) {
* provenance is how a user finds out which layer actually won, the way
* `git config --show-origin --show-scope` does.
*/
-export function checkWorkspace(report, { cwd = process.cwd(), env = process.env } = {}) {
+export function checkWorkspace(report, { cwd = process.cwd(), env = process.env, clientVersion = "" } = {}) {
report.section("Workspace");
const { root, rootKind, git } = findWorkspaceRoot(cwd, env);
@@ -793,7 +775,7 @@ export function checkWorkspace(report, { cwd = process.cwd(), env = process.env
const foundBy = rootKind === "git" ? git.kind : `${TEAM_FILE}${git ? ` inside ${git.kind}` : ""}`;
report.ok(`workspace ${homeShort(root)} ← ${foundBy}`);
- const resolved = resolveWorkspaceSettings(cwd, env);
+ const resolved = resolveWorkspaceSettings(cwd, env, { clientVersion });
summary.settings = resolved.settings;
summary.provenance = resolved.provenance;
const identity = resolveWorkspaceIdentity({ cwd, env });
@@ -914,7 +896,13 @@ export function existsPath(path) {
// `openviking-server doctor`, which runs in the server's Python environment.
// ---------------------------------------------------------------------------
-const PLUGIN_ONLY_OV_CONF_KEYS = { claude_code: "ovcli.conf plugin.claude_code", codex: "ovcli.conf plugin.codex" };
+// Every harness reads the ov.conf section named after it, so every one of
+// those names is a block a user may have written and the server refuses.
+const PLUGIN_ONLY_OV_CONF_KEYS = Object.fromEntries(
+ Object.values(HARNESS_KEYS)
+ .filter((key) => key !== "openclaw")
+ .map((key) => [key, `ovcli.conf plugin.${key}`]),
+);
const READY_OK_VALUES = new Set(["ok", "not_configured", "not_supported"]);
const READY_FIXES = {
embedding: "the server cannot embed with the configured provider — check embedding.dense.{provider,model,api_key,api_base} in ov.conf; `openviking-server doctor` shows the provider's reply",
@@ -1093,3 +1081,363 @@ export async function checkServerHealth(report, { baseUrl, ovConf, health, offli
else summary.ready = assessReady(report, await probeReady(baseUrl, { timeoutMs })).ready;
return summary;
}
+
+// ---------------------------------------------------------------------------
+// Configuration segments
+//
+// The "Configuration" section is host-composed: these are the parts every
+// harness reports identically, called in order, with the host slotting its own
+// lines in between (Claude Code's enable verdict, Codex's credential-source
+// block). Each segment takes the harness spec `runDoctor` already carries.
+// ---------------------------------------------------------------------------
+
+/** ovcli.conf and ov.conf: where they are, whether they parse, what sits in them. */
+export function inspectConfigFiles(report, { harness = "", launcherHint = "this harness" } = {}) {
+ const key = harnessKey(harness);
+ const cliConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CLI_CONFIG_FILE || join(homedir(), ".openviking", "ovcli.conf")));
+ const ovConf = inspectJsonFile(expandHome(process.env.OPENVIKING_CONFIG_FILE || join(homedir(), ".openviking", "ov.conf")));
+
+ for (const [label, conf] of [["ovcli.conf", cliConf], ["ov.conf", ovConf]]) {
+ if (!conf.exists) {
+ report.info(`${label}: ${homeShort(conf.path)} not present`);
+ continue;
+ }
+ if (!conf.ok) {
+ report.fail(`${label} cannot be parsed — the plugin treats it as absent`, `${homeShort(conf.path)}: ${conf.error}`, "fix the JSON (a trailing comma or comment is enough to break it)");
+ continue;
+ }
+ report.ok(`${label}: ${homeShort(conf.path)} (mode ${conf.mode}, ${fmtBytes(conf.size)})`);
+ if (label === "ov.conf") {
+ if (key && conf.data[key]) report.info(`ov.conf has a legacy ${key} block (still honoured; prefer ovcli.conf plugin.${key} or env vars)`);
+ continue;
+ }
+ if (conf.mode !== "600" && conf.mode !== "400") report.warn("ovcli.conf is not private", `mode ${conf.mode}; it holds the api key`, `chmod 600 ${homeShort(conf.path)}`);
+ const unknown = unknownOvcliKeys(conf.data);
+ if (unknown.length) report.warn("ovcli.conf has keys nobody reads", unknown.join(", "), "typos such as apiKey/base_url/token are silently ignored — use url, api_key, account, user");
+ // `plugin` is on the ovcli allowlist, so nothing inside it is checked
+ // there — a misspelled knob would just sit doing nothing.
+ for (const { key: knob, suggestion } of unknownPluginKeys(conf.data.plugin)) {
+ report.warn(`ovcli.conf ${knob} is not a knob any plugin reads`, "", suggestion ? `did you mean ${suggestion}?` : "remove it, or check the plugin README for the knob you meant");
+ }
+ if (conf.data.extra_headers && Object.keys(conf.data.extra_headers).some((h) => /^x-api-key$/i.test(h))) {
+ report.warn("ovcli.conf extra_headers sets X-API-Key", "the server prefers X-API-Key over Authorization: Bearer, so it shadows api_key");
+ }
+ const sections = Object.keys(conf.data.plugin || {}).filter((k) => HARNESS_CONFIG_KEYS.has(k));
+ const others = sections.filter((k) => harnessKey(k) !== key);
+ if (key && others.length && !sections.some((k) => harnessKey(k) === key)) {
+ report.info(`ovcli.conf ${others.map((k) => `plugin.${k}`).join(", ")} settings do not apply to ${launcherHint} (use plugin.${key})`);
+ }
+ }
+ return { cliConf, ovConf };
+}
+
+/**
+ * Where each resolved credential came from, as one label per field.
+ *
+ * The key's layer is not re-derived here: `buildPluginConfig` already answered
+ * it in `apiKeySource`, and three doctors reconstructing that walk by hand is
+ * three chances to describe a chain nobody runs. What the files are still asked
+ * is which field inside the winning layer holds the value, because the layer
+ * alone cannot tell `plugin.<harness>.apiKey` from `api_key`, or a harness
+ * block from `server.root_api_key`.
+ *
+ * The identity has no such answer to read, so account and user follow the chain
+ * in `resolveOpenVikingCredentials` step for step: pinned to ovcli.conf it ends
+ * at that file's `plugin` section, and otherwise the environment wins and
+ * ov.conf's harness block is last.
+ */
+export function credentialSources(cfg, cliConf, ovConf, { section = harnessKey(cfg.harness || "") } = {}) {
+ const env = process.env;
+ const cliShort = homeShort(cliConf.path);
+ const ovShort = homeShort(ovConf.path);
+ const cli = cliConf.ok ? cliConf.data : {};
+ const ov = ovConf.ok ? ovConf.data : {};
+ const plugin = cli.plugin || {};
+ const scoped = (section && plugin[section]) || {};
+ const block = (section && ov[section]) || {};
+ const server = ov.server || {};
+ // Pinned to ovcli.conf, the chain never looks at the environment.
+ const pinned = cfg.credentialSource === "ovcli";
+
+ const envUrl = env.OPENVIKING_URL || env.OPENVIKING_BASE_URL;
+ const url = (!pinned && envUrl) ? "env"
+ : cli.url ? cliShort
+ : server.url ? ovShort
+ : (server.host || server.port) ? `${ovShort} server.host/port` : "default (http://127.0.0.1:1933)";
+
+ let apiKey;
+ if (cfg.apiKeySource === "env") {
+ apiKey = env.OPENVIKING_BEARER_TOKEN ? "env OPENVIKING_BEARER_TOKEN" : "env OPENVIKING_API_KEY";
+ } else if (cfg.apiKeySource === "ovcli") {
+ apiKey = cli.api_key ? cliShort
+ : scoped.apiKey ? `${cliShort} plugin.${section}.apiKey`
+ : plugin.apiKey ? `${cliShort} plugin.apiKey` : cliShort;
+ } else if (cfg.apiKeySource === "ov") {
+ apiKey = block.apiKey ? `${ovShort} ${section}.apiKey`
+ : server.root_api_key ? `${ovShort} server.root_api_key` : ovShort;
+ } else if (cfg.apiKeySource === "host") {
+ apiKey = "the host application";
+ } else {
+ apiKey = pinned ? "(none — ovcli.conf mode ignores env)" : "(none)";
+ }
+
+ const identity = (envName, cliValue, name) => (
+ (!pinned && env[envName]) ? "env"
+ : cliValue ? cliShort
+ : scoped[name] ? `${cliShort} plugin.${section}.${name}`
+ : plugin[name] ? `${cliShort} plugin.${name}`
+ : (!pinned && block[name]) ? `${ovShort} ${section}.${name}` : "(unset)"
+ );
+ return {
+ url,
+ apiKey,
+ account: identity("OPENVIKING_ACCOUNT", cli.account || cli.account_id, "accountId"),
+ user: identity("OPENVIKING_USER", cli.user || cli.user_id, "userId"),
+ };
+}
+
+/**
+ * The resolved url, key and identity, each with the source it came from.
+ * `sources` is the host's own credential chain rendered as one label per field.
+ */
+export function reportCredentials(report, cfg, sources, { account = "", user = "" } = {}) {
+ report.info(`url ${cfg.baseUrl} ← ${sources.url}`);
+ for (const p of lintBaseUrl(cfg.baseUrl)) report[p.level](p.message, "", p.fix);
+ if (sources.url.startsWith("default") && !isLoopbackUrl(cfg.baseUrl)) report.info("url fell back to the built-in default");
+ else if (sources.url.startsWith("default")) report.warn("no url configured — using the built-in default http://127.0.0.1:1933", "only right when the server runs on this machine", "set url in ovcli.conf or OPENVIKING_URL");
+
+ const keyInfo = describeApiKey(cfg.apiKey);
+ report.info(`api_key ${keyInfo.display} ← ${sources.apiKey}`);
+ for (const p of keyInfo.problems) report.warn(`api key ${p}`, "", "re-copy the key exactly as issued");
+ if (sources.apiKey.includes("root_api_key")) {
+ report.warn("api key falls back to ov.conf server.root_api_key", "the root key is refused on tenant data APIs and /mcp in api_key mode; against a remote server it is simply the wrong key",
+ "put a user/admin key in ovcli.conf api_key (or OPENVIKING_API_KEY)");
+ }
+ if (!keyInfo.present && !isLoopbackUrl(cfg.baseUrl)) report.warn("no api key configured for a non-local server", "", "set api_key in ovcli.conf or OPENVIKING_API_KEY");
+ report.info(`account ${account || "(unset)"} ← ${sources.account}`);
+ report.info(`user ${user || "(unset)"} ← ${sources.user}`);
+ if (keyInfo.format === "v2") {
+ if (account && keyInfo.account && account !== keyInfo.account) report.warn(`configured account '${account}' differs from the key's account '${keyInfo.account}'`, "in api_key mode the key wins");
+ if (user && keyInfo.user && user !== keyInfo.user) report.warn(`configured user '${user}' differs from the key's user '${keyInfo.user}'`, "in api_key mode the key wins");
+ }
+ return keyInfo;
+}
+
+/** The peer this directory sends, where it came from, and what it costs when there is none. */
+export function reportPeer(report, cfg, { cwd = process.cwd() } = {}) {
+ const peer = resolveEffectivePeerId({ cfg, cwd });
+ report.info(`peer ${peer.peerId || "(none)"} ← ${peer.source} (${peer.origin})`);
+ if (peer.origin === "unresolved") {
+ report.info(
+ "no peer is sent: this directory is in no git repository, so its memories go to your user-level space",
+ `to give it a memory of its own, create .openviking/config.json here with ${WORKSPACE_PEER_HINT}`,
+ );
+ } else if (peer.source === "none") {
+ report.warn(
+ "no peer is sent, so recall defaults to every memory under this user",
+ "sending a peer narrows the search to this workspace",
+ 'unset OPENVIKING_WORKSPACE_PEER, or set peer.source to "git"',
+ );
+ }
+ if (peer.legacyPeerId) {
+ report.info(
+ `previous peer ${peer.legacyPeerId}`,
+ cfg.recallPeerScope === "actor"
+ ? "recall asks it separately, because peer_scope actor turns off the server's cross-peer sweep"
+ : "already covered by the server's cross-peer sweep under peer_scope all",
+ );
+ }
+ for (const p of lintPeerScopeDowngrade()) report[p.level](p.message, p.detail, p.fix);
+ return peer;
+}
+
+const TIMEOUT_LABELS = { timeoutMs: "request", recallTimeoutMs: "recall", captureTimeoutMs: "capture" };
+
+/**
+ * The timeouts line and the hook-budget check. `timeoutBudgets` maps a hook
+ * event to the knob that governs the request inside it, so each harness names
+ * the knob its own recall and capture paths actually read — a request that
+ * outlives its hook is killed by the host before it can answer.
+ *
+ * `hooksTemplate` names the template when it does not sit at the plugin root,
+ * and an entry states its timeout either directly or one nesting level down.
+ */
+export function reportTimeouts(report, cfg, { pluginRoot = "", hooksTemplate = "", launcherHint = "the harness", timeoutBudgets = {} } = {}) {
+ const knobs = [...new Set(["timeoutMs", ...Object.values(timeoutBudgets)])];
+ report.info(`timeouts ${knobs.map((knob) => `${cfg[knob]}ms ${TIMEOUT_LABELS[knob] || knob}`).join(", ")}; recall limit ${cfg.recallLimit}, threshold ${cfg.scoreThreshold}`);
+
+ const hooks = tryJson(hooksTemplate || join(pluginRoot, "hooks", "hooks.json"))?.hooks || {};
+ for (const [event, knob] of Object.entries(timeoutBudgets)) {
+ const entry = hooks[event]?.[0];
+ const budget = Number(entry?.hooks?.[0]?.timeout ?? entry?.timeout) * 1000 || 0;
+ if (!budget || !(cfg[knob] > budget)) continue;
+ report.warn(`${TIMEOUT_LABELS[knob] || knob} timeout ${cfg[knob]}ms exceeds the ${event} hook budget ${budget}ms`,
+ `${launcherHint} kills the hook before the request can finish`,
+ `lower ${KNOB_BY_NAME.get(knob)?.env || knob}`);
+ }
+}
+
+/** The switches that decide whether anything is injected at all. */
+export function reportToggles(report, cfg, { harness = "" } = {}, toggles = []) {
+ report.info(`toggles ${toggles.join(", ")}`);
+ if (!cfg.autoRecall || !cfg.autoCapture || cfg.noAutoInject) {
+ report.warn("one or more injection paths are switched off", toggles.join(", "),
+ `check OPENVIKING_AUTO_RECALL / OPENVIKING_AUTO_CAPTURE / OPENVIKING_NO_AUTO_INJECT and ovcli.conf plugin.${harnessKey(harness)}`);
+ }
+}
+
+/**
+ * Where the hooks log, and what the environment does to them. `extra` adds the
+ * host's own reading of the OPENVIKING_* vars it found.
+ */
+export function sweepEnv(report, cfg, { launcherHint = "the harness" } = {}, extra) {
+ report.info(`debug log ${cfg.debug ? "on" : "off"} → ${homeShort(cfg.debugLogPath)}${cfg.debug ? "" : ` (set OPENVIKING_DEBUG=1 in ${launcherHint}'s environment to record hook errors)`}`);
+
+ const env = collectEnv();
+ if (env.openviking.length) {
+ report.info("OPENVIKING_* in this environment", env.openviking.map((e) => `${e.name}=${e.value}`).join("\n"));
+ if (extra) extra(report, env);
+ } else {
+ report.info("no OPENVIKING_* environment variables set");
+ }
+ if (env.proxy.length) {
+ report.warn(`proxy variables set: ${env.proxy.map((e) => e.name).join(", ")}`,
+ "Node's fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY=1 (Node 24+); curl honours them, so curl may succeed while hooks fail",
+ isLoopbackUrl(cfg.baseUrl) ? "harmless for a local server" : `set NODE_USE_ENV_PROXY=1 (or reach the server without the proxy) in the environment that launches ${launcherHint}`);
+ }
+ if (env.node.length) report.info(`node TLS/proxy env: ${env.node.map((e) => `${e.name}=${e.value}`).join(", ")}`);
+ if (/^https:/i.test(cfg.baseUrl) && env.node.some((e) => e.name === "NODE_TLS_REJECT_UNAUTHORIZED" && e.value === "0")) {
+ report.warn("NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate checks", "", "prefer NODE_EXTRA_CA_CERTS=<ca.pem>");
+ }
+ return env;
+}
+
+// ---------------------------------------------------------------------------
+// The run
+// ---------------------------------------------------------------------------
+
+export function parseArgs(argv) {
+ const opts = { json: false, offline: false, timeoutMs: 5000, color: process.stdout.isTTY && !process.env.NO_COLOR };
+ for (let i = 0; i < argv.length; i += 1) {
+ const arg = argv[i];
+ if (arg === "--json") opts.json = true;
+ else if (arg === "--offline" || arg === "--no-network") opts.offline = true;
+ else if (arg === "--no-color") opts.color = false;
+ else if (arg === "--timeout") opts.timeoutMs = Math.max(1000, Number(argv[++i]) || 5000);
+ else if (arg === "-h" || arg === "--help") {
+ console.log("usage: ov-memory-doctor.mjs [--json] [--offline] [--timeout <ms>] [--no-color]");
+ process.exit(0);
+ }
+ }
+ if (opts.json) opts.color = false;
+ return opts;
+}
+
+export function expandHome(p) {
+ return p ? resolvePath(p.replace(/^~(?=$|\/)/, homedir())) : p;
+}
+
+export function tryJson(path) {
+ try {
+ return JSON.parse(readFileSync(path, "utf-8"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The "Environment" section. `launcherHint` names the host in the prose ("the
+ * environment that launches Claude Code"); `onCliFound` lets a host report its
+ * CLI its own way and add probes of its own between the version line and the
+ * platform line.
+ */
+export function checkEnvironment(report, { cliName, cliVersionArgs = ["--version"], launcherHint, nodePathFix, onCliFound } = {}) {
+ report.section("Environment");
+ const nodeMajor = parseNodeMajor(process.version);
+ const nodePath = process.execPath;
+ if (nodeMajor >= 18) report.ok(`node ${process.version} (${nodePath})`);
+ else report.fail(`node ${process.version} is too old`, "hooks and the MCP proxy need Node.js 18+ (global fetch)", "install Node.js 18 or newer and make sure it is first on PATH");
+ const nodeOnPath = whichCommand("node");
+ if (!nodeOnPath) {
+ report.warn("`node` is not on PATH for this process",
+ `hooks and .mcp.json invoke the bare command \`node\`; if ${launcherHint} was launched without your shell profile (nvm/volta/fnm), hooks never start`,
+ nodePathFix || `put node on PATH for the environment that launches ${launcherHint}`);
+ } else if (resolvePath(nodeOnPath) !== resolvePath(nodePath)) {
+ report.info(`PATH resolves node to ${nodeOnPath} (this run used ${nodePath})`);
+ }
+
+ const cli = runCommand(cliName, cliVersionArgs, { timeoutMs: 15000 });
+ if (cli.ok) {
+ if (onCliFound) onCliFound(report, cli);
+ else report.ok(cli.stdout.split("\n")[0]);
+ } else {
+ report.info(`${cliName} CLI not found on PATH (${cli.error || "?"}) — install checks that need it are skipped`);
+ }
+ report.info(`platform ${process.platform} ${process.arch}, cwd ${homeShort(process.cwd())}`);
+ return { cliOnPath: cli.ok };
+}
+
+/**
+ * The "Connection" section. `account`/`user` are the configured identity: they
+ * only reach the wire when the harness sends identity headers, but the probe
+ * report compares them against what the key claims either way. `onSummary`
+ * carries the host's verdict on the answer (Codex compares auth modes).
+ */
+export async function checkConnection(report, cfg, { keyInfo, peer, account = "", user = "" }, opts, { onSummary } = {}) {
+ report.section("Connection");
+ if (opts.offline) {
+ report.info("skipped (--offline)");
+ return null;
+ }
+ const conn = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey, account: cfg.sendIdentityHeaders ? account : "", user: cfg.sendIdentityHeaders ? user : "", peerId: peer.peerId, userAgent: cfg.userAgent };
+ const probes = await probeOpenViking(conn, { timeoutMs: opts.timeoutMs });
+ const summary = assessProbes(report, probes, { ...conn, account, user }, keyInfo);
+ if (onSummary) onSummary(report, summary, cfg);
+ return { probes, summary };
+}
+
+/**
+ * Run one harness's doctor. `host` is the harness spec: the `checkEnvironment`
+ * fields above, `loadConfig()`, the three sections only the host can produce
+ * (`checkInstall`, `checkConfig`, `checkActivity`), `resolveIdentity(cfg)` for
+ * the account/user spelling that harness uses, and optionally `onSummary` and
+ * `extraResolved(cfg)` for extra `--json` fields. `checkConfig` is handed the
+ * spec back, because the configuration segments it composes are driven by it.
+ */
+export async function runDoctor(host) {
+ const opts = parseArgs(process.argv.slice(2));
+ const report = createReport({ color: opts.color });
+ const envInfo = checkEnvironment(report, host);
+ host.checkInstall(report, envInfo);
+ const cfg = host.loadConfig();
+ const configInfo = host.checkConfig(report, cfg, host);
+ const workspace = checkWorkspace(report, { clientVersion: cfg.clientVersion });
+ const identity = host.resolveIdentity(cfg);
+ const connection = await checkConnection(report, cfg, { ...configInfo, ...identity }, opts, host);
+ const serverHealth = await checkServerHealth(report, { baseUrl: cfg.baseUrl, ovConf: configInfo.ovConf, health: connection?.probes?.health, offline: opts.offline, timeoutMs: opts.timeoutMs });
+ host.checkActivity(report, cfg, connection);
+
+ if (opts.json) {
+ console.log(JSON.stringify({
+ harness: host.harness,
+ pluginRoot: host.pluginRoot,
+ generatedAt: new Date().toISOString(),
+ resolved: {
+ baseUrl: cfg.baseUrl,
+ apiKey: configInfo.keyInfo.display,
+ apiKeyFormat: configInfo.keyInfo.format,
+ account: identity.account,
+ user: identity.user,
+ peerId: configInfo.peer.peerId,
+ ...(host.extraResolved ? host.extraResolved(cfg) : {}),
+ },
+ workspace,
+ server: connection?.summary || null,
+ serverHealth,
+ ...report.toJSON(),
+ }, null, 2));
+ } else {
+ console.log(report.render());
+ }
+ process.exitCode = report.exitCode();
+}
diff --git a/examples/memory-plugin-shared/lib/install/host-json-config.mjs b/examples/memory-plugin-shared/lib/install/host-json-config.mjs
new file mode 100644
index 000000000..b75180b62
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/install/host-json-config.mjs
@@ -0,0 +1,302 @@
+#!/usr/bin/env node
+/**
+ * The hooks/mcp merge behind every config-driven host.
+ *
+ * cursor, trae, trae-cn and zcode keep their hooks and MCP servers in JSON the
+ * user edits too, so installing, uninstalling and folding the two files into
+ * zcode's single config are the same three problems each time: read a file
+ * without clobbering what could not be parsed, decide which entries are this
+ * installer's, and write back atomically. Three copies of that had already
+ * drifted — the uninstall side learned to reclaim the URI-guard entries and the
+ * install side never did, so a rename left a stale guard hook behind.
+ *
+ * Installer-only: nothing under lib/ imports it, so it stays out of the runtime
+ * closure sync.mjs vendors into the plugins.
+ */
+
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+/**
+ * The file's top-level object, `{}` when it is absent or empty.
+ *
+ * Anything else — unreadable, malformed, not an object — throws, because the
+ * only thing every caller does next is write the file back.
+ */
+export function readJson(file) {
+ let raw;
+ try {
+ raw = fs.readFileSync(file, "utf8");
+ } catch (error) {
+ if (error.code === "ENOENT") return {};
+ throw new Error(`Cannot safely update ${file}: ${error.message}`);
+ }
+ if (!raw.trim()) return {};
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (error) {
+ throw new Error(`Cannot safely update ${file}: ${error.message}`);
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new Error(`Cannot safely update ${file}: top-level value must be an object`);
+ }
+ return parsed;
+}
+
+function atomicWrite(file, value, { backup = true } = {}) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const next = JSON.stringify(value, null, 2) + "\n";
+ let previous = "";
+ try { previous = fs.readFileSync(file, "utf8"); } catch {}
+ if (previous === next) return;
+ if (previous && backup) fs.writeFileSync(`${file}.bak`, previous, { mode: 0o600 });
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, next, { mode: 0o600 });
+ fs.renameSync(tmp, file);
+}
+
+function shellArg(value) {
+ return `'${String(value).replace(/'/g, `'"'"'`)}'`;
+}
+
+// Everything this installer writes today carries the integration id. The script
+// names are how an entry from an older install, written before that env prefix
+// existed, still gets reclaimed instead of accumulating beside the new one.
+const OPENVIKING_HOOK_SCRIPTS = [
+ "hook.mjs",
+ "hook-entry.mjs",
+ "session-start.mjs",
+ "auto-recall.mjs",
+ "auto-capture.mjs",
+ "pre-compact.mjs",
+ "session-end.mjs",
+ "trae-auto-recall.mjs",
+ "trae-auto-capture.mjs",
+ "trae-cli-hook.mjs",
+ "uri-guard.mjs",
+ "claude-code-memory-plugin/scripts/session-start.mjs",
+];
+
+/** Whether a host's hook entry is one this installer owns. */
+export function ownsHook(value) {
+ const text = JSON.stringify(value || {});
+ return text.includes("OPENVIKING_INTEGRATION_ID")
+ || (text.includes("openviking") && OPENVIKING_HOOK_SCRIPTS.some((name) => text.includes(name)));
+}
+
+function isKnownLegacyOpenVikingServer(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ if (value.env?.OPENVIKING_INTEGRATION_ID === "openviking-memory") return true;
+ if (typeof value.url !== "string") return false;
+ try {
+ const url = new URL(value.url);
+ const local = ["127.0.0.1", "localhost", "::1"].includes(url.hostname)
+ && url.port === "1933" && url.pathname.replace(/\/$/u, "") === "/mcp";
+ const cloud = url.hostname === "api.vikingdb.cn-beijing.volces.com"
+ && url.pathname.replace(/\/$/u, "") === "/openviking/mcp";
+ return local || cloud;
+ } catch {
+ return false;
+ }
+}
+
+/** Render the host's hook and MCP templates into the user's own config files. */
+export function writeHostJsonConfigs({ kind, hooksPath, mcpPath, root, clientId, nodeBin, sourceMode }) {
+ // One plugin serves every config-driven host; `kind` names the host directory
+ // this client's configuration templates live in.
+ const hostDir = path.join(root, "hosts", kind);
+ const packageManifest = readJson(path.join(hostDir, "openviking.integration.json"));
+ if (packageManifest.id !== "openviking-memory" || !Array.isArray(packageManifest.clients)
+ || !packageManifest.clients.includes(clientId)) {
+ throw new Error(`Invalid OpenViking integration manifest for ${clientId}`);
+ }
+ const integrationEnv = {
+ OPENVIKING_INTEGRATION_ID: packageManifest.id,
+ OPENVIKING_INTEGRATION_VERSION: packageManifest.version,
+ OPENVIKING_HOOK_SOURCE: clientId,
+ };
+ const envPrefix = Object.entries(integrationEnv)
+ .map(([key, value]) => `${key}=${shellArg(value)}`)
+ .join(" ");
+
+ function renderHookCommand(command) {
+ const match = /^node\s+"?__OPENVIKING_PLUGIN_ROOT__\/([^\s"]+)"?(\s.*)?$/u.exec(command);
+ if (!match) throw new Error(`Unsupported ${clientId} hook command template: ${command}`);
+ const args = (match[2] || "").replaceAll("__OPENVIKING_CLIENT_ID__", clientId);
+ const rendered = `${shellArg(nodeBin)} ${shellArg(path.join(root, match[1]))}${args}`;
+ return `${envPrefix} ${rendered} # openviking-memory`;
+ }
+
+ function renderHookValue(value) {
+ if (Array.isArray(value)) return value.map(renderHookValue);
+ if (!value || typeof value !== "object") return value;
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [
+ key,
+ key === "command" && typeof child === "string" ? renderHookCommand(child) : renderHookValue(child),
+ ]));
+ }
+
+ const hookTemplate = readJson(path.join(hostDir, "hooks.json"));
+ if (!hookTemplate.hooks || typeof hookTemplate.hooks !== "object" || Array.isArray(hookTemplate.hooks)) {
+ throw new Error(`Invalid ${clientId} hooks template`);
+ }
+ const hooksConfig = readJson(hooksPath);
+ hooksConfig.version = Number.isFinite(Number(hooksConfig.version)) ? Number(hooksConfig.version) : 1;
+ hooksConfig.hooks = hooksConfig.hooks && typeof hooksConfig.hooks === "object" && !Array.isArray(hooksConfig.hooks)
+ ? hooksConfig.hooks : {};
+
+ for (const [event, entries] of Object.entries(hookTemplate.hooks)) {
+ if (!Array.isArray(entries)) throw new Error(`Invalid ${clientId} hook entries for ${event}`);
+ const current = Array.isArray(hooksConfig.hooks[event]) ? hooksConfig.hooks[event] : [];
+ hooksConfig.hooks[event] = [
+ ...current.filter((item) => !ownsHook(item)),
+ ...renderHookValue(entries),
+ ];
+ }
+ if (kind === "cursor") {
+ if (Array.isArray(hooksConfig.hooks.postToolUse)) {
+ const remaining = hooksConfig.hooks.postToolUse.filter((item) => !ownsHook(item));
+ if (remaining.length) hooksConfig.hooks.postToolUse = remaining;
+ else delete hooksConfig.hooks.postToolUse;
+ }
+ }
+ atomicWrite(hooksPath, hooksConfig);
+
+ const mcpTemplate = readJson(path.join(hostDir, ".mcp.json"));
+ const templateServer = mcpTemplate.mcpServers?.openviking;
+ if (!templateServer || typeof templateServer !== "object" || Array.isArray(templateServer)) {
+ throw new Error(`Invalid ${clientId} MCP template`);
+ }
+ const mcp = readJson(mcpPath);
+ mcp.mcpServers = mcp.mcpServers && typeof mcp.mcpServers === "object" && !Array.isArray(mcp.mcpServers)
+ ? mcp.mcpServers : {};
+ // Migrate only the exact OpenViking endpoints published by the earlier manual
+ // guides. A coincidentally named third-party server must remain untouched.
+ if (isKnownLegacyOpenVikingServer(mcp.mcpServers["ov-mcp-server"])) {
+ delete mcp.mcpServers["ov-mcp-server"];
+ }
+ mcp.mcpServers.openviking = {
+ ...templateServer,
+ command: nodeBin,
+ args: [path.join(root, "servers", "mcp-proxy.mjs")],
+ env: { ...(templateServer.env || {}), ...integrationEnv },
+ };
+ atomicWrite(mcpPath, mcp);
+
+ const installedManifestPath = path.join(root, "integration.json");
+ const previousManifest = readJson(installedManifestPath);
+ const now = new Date().toISOString();
+ const unchangedInstall = previousManifest.version === packageManifest.version
+ && previousManifest.source === sourceMode
+ && previousManifest.hooksConfig === hooksPath
+ && previousManifest.mcpConfig === mcpPath;
+ atomicWrite(installedManifestPath, {
+ schemaVersion: 1,
+ id: packageManifest.id,
+ version: packageManifest.version,
+ client: clientId,
+ installMode: "managed-native",
+ source: sourceMode,
+ capabilities: packageManifest.capabilities,
+ hooksConfig: hooksPath,
+ mcpConfig: mcpPath,
+ installedAt: previousManifest.installedAt || now,
+ updatedAt: unchangedInstall ? previousManifest.updatedAt || previousManifest.installedAt || now : now,
+ });
+}
+
+/**
+ * Drop this installer's hook entries and MCP server from the user's config files.
+ *
+ * The one caller with nothing to protect: a backup taken here would hold the
+ * entries the uninstall just removed, so these writes take none and the copy an
+ * install left behind goes too. `mcpPath` may be empty for a host that keeps no
+ * MCP file of its own.
+ */
+export function removeHostJsonConfigs({ hooksPath, mcpPath }) {
+ const hooks = fs.existsSync(hooksPath) ? readJson(hooksPath) : null;
+ const mcp = mcpPath && fs.existsSync(mcpPath) ? readJson(mcpPath) : null;
+ if (hooks?.hooks && typeof hooks.hooks === "object") {
+ for (const event of Object.keys(hooks.hooks)) {
+ if (!Array.isArray(hooks.hooks[event])) continue;
+ hooks.hooks[event] = hooks.hooks[event].filter((item) => !ownsHook(item));
+ if (hooks.hooks[event].length === 0) delete hooks.hooks[event];
+ }
+ atomicWrite(hooksPath, hooks, { backup: false });
+ }
+ if (mcp?.mcpServers?.openviking) {
+ const text = JSON.stringify(mcp.mcpServers.openviking);
+ if (text.includes("agent-integrations") && text.includes("mcp-proxy.mjs")) {
+ delete mcp.mcpServers.openviking;
+ atomicWrite(mcpPath, mcp, { backup: false });
+ }
+ }
+ for (const file of [hooksPath, mcpPath]) {
+ if (file) fs.rmSync(`${file}.bak`, { force: true });
+ }
+}
+
+/**
+ * Fold the rendered hooks.json and mcp.json into zcode's single config.json.
+ *
+ * ZCode reads hooks from `config.json` → `hooks.events` and MCP servers from
+ * `mcp.servers`, so the files `writeHostJsonConfigs` produced are an
+ * intermediate step for this host rather than the thing it loads.
+ */
+export function mergeZcodeConfig({ configPath, hooksPath, mcpPath }) {
+ const config = readJson(configPath);
+
+ if (fs.existsSync(hooksPath)) {
+ const hooks = readJson(hooksPath);
+ config.hooks = config.hooks || {};
+ config.hooks.enabled = true;
+ config.hooks.events = config.hooks.events || {};
+ for (const [event, handlers] of Object.entries(hooks.hooks || {})) {
+ const existing = (config.hooks.events[event] || []).filter((group) => !ownsHook(group));
+ config.hooks.events[event] = [...existing, ...handlers];
+ }
+ }
+
+ if (fs.existsSync(mcpPath) && fs.statSync(mcpPath).size > 0) {
+ const mcp = readJson(mcpPath);
+ const incoming = { ...(mcp.mcpServers || {}) };
+ if (mcp.openviking) incoming.openviking = mcp.openviking;
+ config.mcp = config.mcp || {};
+ config.mcp.servers = config.mcp.servers || {};
+ for (const [name, server] of Object.entries(incoming)) {
+ const existing = config.mcp.servers[name];
+ // Only replace an entry that does not exist yet or is already ours.
+ 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;
+ }
+ }
+
+ atomicWrite(configPath, config);
+}
+
+const COMMANDS = {
+ write: ([kind, hooksPath, mcpPath, root, clientId, nodeBin, sourceMode]) =>
+ writeHostJsonConfigs({ kind, hooksPath, mcpPath, root, clientId, nodeBin, sourceMode }),
+ remove: ([hooksPath, mcpPath]) => removeHostJsonConfigs({ hooksPath, mcpPath }),
+ "merge-zcode": ([configPath, hooksPath, mcpPath]) => mergeZcodeConfig({ configPath, hooksPath, mcpPath }),
+};
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
+ const [command, ...argv] = process.argv.slice(2);
+ const run = COMMANDS[command];
+ if (!run) {
+ process.stderr.write(`usage: host-json-config.mjs <${Object.keys(COMMANDS).join("|")}> ...\n`);
+ process.exit(2);
+ }
+ try {
+ run(argv);
+ } catch (error) {
+ process.stderr.write(`${error?.message || error}\n`);
+ process.exit(1);
+ }
+}
diff --git a/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs b/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs
new file mode 100644
index 000000000..ddbcb9a92
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/install/jsonc-edit.mjs
@@ -0,0 +1,355 @@
+#!/usr/bin/env node
+/**
+ * Comment-preserving edits to OpenCode's config file.
+ *
+ * OpenCode reads `opencode.jsonc`, and people keep notes in it. Reparsing and
+ * reserializing the file would silently eat every comment and every hand-made
+ * formatting choice, so the value is parsed only to decide what to change and
+ * the change itself is spliced into the original text. That means walking JSONC
+ * by hand: comments, trailing commas and single-quoted strings are all things
+ * `JSON.parse` refuses and the splice has to step over.
+ *
+ * Installer-only, and deliberately outside the runtime closure `sync.mjs`
+ * vendors into the plugins: no hook imports it, so no plugin ships it.
+ */
+
+import fs from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+function stripJsonc(s) {
+ let out = "";
+ let i = 0;
+ while (i < s.length) {
+ const ch = s[i];
+ const next = s[i + 1];
+ if (ch === '"' || ch === "'") {
+ const end = readStringEnd(s, i);
+ out += s.slice(i, end);
+ i = end;
+ } else if (ch === "/" && next === "/") {
+ i += 2;
+ while (i < s.length && s[i] !== "\n") i++;
+ } else if (ch === "/" && next === "*") {
+ i += 2;
+ while (i < s.length && !(s[i] === "*" && s[i + 1] === "/")) i++;
+ i = Math.min(s.length, i + 2);
+ } else {
+ out += ch;
+ i++;
+ }
+ }
+ return out.replace(/,\s*([}\]])/g, "$1");
+}
+
+function readStringEnd(s, start) {
+ const quote = s[start];
+ let i = start + 1;
+ while (i < s.length) {
+ if (s[i] === "\\") {
+ i += 2;
+ } else if (s[i] === quote) {
+ return i + 1;
+ } else {
+ i++;
+ }
+ }
+ return s.length;
+}
+
+function skipTrivia(s, i, end = s.length) {
+ while (i < end) {
+ if (/\s/.test(s[i])) {
+ i++;
+ } else if (s[i] === "/" && s[i + 1] === "/") {
+ i += 2;
+ while (i < end && s[i] !== "\n") i++;
+ } else if (s[i] === "/" && s[i + 1] === "*") {
+ i += 2;
+ while (i < end && !(s[i] === "*" && s[i + 1] === "/")) i++;
+ i = Math.min(end, i + 2);
+ } else {
+ break;
+ }
+ }
+ return i;
+}
+
+function parseStringLiteral(s, start) {
+ const end = readStringEnd(s, start);
+ try {
+ return { value: JSON.parse(s.slice(start, end)), end };
+ } catch {
+ return { value: "", end };
+ }
+}
+
+function findTopLevelObject(s) {
+ const start = skipTrivia(s, 0);
+ if (s[start] !== "{") return null;
+ let depth = 0;
+ let i = start;
+ while (i < s.length) {
+ if (s[i] === '"' || s[i] === "'") {
+ i = readStringEnd(s, i);
+ continue;
+ }
+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
+ i = skipTrivia(s, i);
+ continue;
+ }
+ if (s[i] === "{" || s[i] === "[") depth++;
+ if (s[i] === "}" || s[i] === "]") {
+ depth--;
+ if (depth === 0 && s[i] === "}") return { start, end: i };
+ }
+ i++;
+ }
+ return null;
+}
+
+function findObjectRangeAt(s, start, end = s.length) {
+ const objectStart = skipTrivia(s, start, end);
+ if (s[objectStart] !== "{") return null;
+ let depth = 0;
+ let i = objectStart;
+ while (i < end) {
+ if (s[i] === '"' || s[i] === "'") {
+ i = readStringEnd(s, i);
+ continue;
+ }
+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
+ i = skipTrivia(s, i, end);
+ continue;
+ }
+ if (s[i] === "{" || s[i] === "[") depth++;
+ if (s[i] === "}" || s[i] === "]") {
+ depth--;
+ if (depth === 0 && s[i] === "}") return { start: objectStart, end: i };
+ }
+ i++;
+ }
+ return null;
+}
+
+function findArrayRangeAt(s, start, end = s.length) {
+ const arrayStart = skipTrivia(s, start, end);
+ if (s[arrayStart] !== "[") return null;
+ let depth = 0;
+ let i = arrayStart;
+ while (i < end) {
+ if (s[i] === '"' || s[i] === "'") {
+ i = readStringEnd(s, i);
+ continue;
+ }
+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
+ i = skipTrivia(s, i, end);
+ continue;
+ }
+ if (s[i] === "{" || s[i] === "[") depth++;
+ if (s[i] === "}" || s[i] === "]") {
+ depth--;
+ if (depth === 0 && s[i] === "]") return { start: arrayStart, end: i };
+ }
+ i++;
+ }
+ return null;
+}
+
+function findTopLevelProperty(s, objectRange, name) {
+ let depth = 1;
+ let i = objectRange.start + 1;
+ while (i < objectRange.end) {
+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
+ i = skipTrivia(s, i, objectRange.end);
+ continue;
+ }
+ if (s[i] === '"' || s[i] === "'") {
+ const keyStart = i;
+ const parsed = parseStringLiteral(s, i);
+ i = parsed.end;
+ const afterKey = skipTrivia(s, i, objectRange.end);
+ if (depth === 1 && parsed.value === name && s[afterKey] === ":") {
+ const valueStart = skipTrivia(s, afterKey + 1, objectRange.end);
+ return {
+ keyStart,
+ valueStart,
+ replaceEnd: findPropertyReplaceEnd(s, valueStart, objectRange.end),
+ };
+ }
+ continue;
+ }
+ if (s[i] === "{" || s[i] === "[") depth++;
+ if (s[i] === "}" || s[i] === "]") depth--;
+ i++;
+ }
+ return null;
+}
+
+function findPropertyReplaceEnd(s, valueStart, objectEnd) {
+ let depth = 0;
+ let i = skipTrivia(s, valueStart, objectEnd);
+ let lastTokenEnd = i;
+ while (i < objectEnd) {
+ if (s[i] === '"' || s[i] === "'") {
+ i = readStringEnd(s, i);
+ lastTokenEnd = i;
+ continue;
+ }
+ if (s[i] === "/" && (s[i + 1] === "/" || s[i + 1] === "*")) {
+ i = skipTrivia(s, i, objectEnd);
+ continue;
+ }
+ if (depth === 0 && s[i] === ",") return lastTokenEnd;
+ if (s[i] === "{" || s[i] === "[") depth++;
+ if (s[i] === "}" || s[i] === "]") depth--;
+ if (!/\s/.test(s[i])) lastTokenEnd = i + 1;
+ i++;
+ }
+ return lastTokenEnd;
+}
+
+function findLineIndent(s, index) {
+ const lineStart = s.lastIndexOf("\n", index - 1) + 1;
+ const prefix = s.slice(lineStart, index);
+ return /^[ \t]*$/.test(prefix) ? prefix : "";
+}
+
+function detectPropertyIndent(s, objectRange) {
+ let i = objectRange.start + 1;
+ while (i < objectRange.end) {
+ i = skipTrivia(s, i, objectRange.end);
+ if (s[i] === '"' || s[i] === "'") return findLineIndent(s, i) || " ";
+ if (s[i] === "{" || s[i] === "[") break;
+ i++;
+ }
+ const closeIndent = findLineIndent(s, objectRange.end);
+ return `${closeIndent} `;
+}
+
+function hasTopLevelProperty(s, objectRange) {
+ let i = objectRange.start + 1;
+ while (i < objectRange.end) {
+ i = skipTrivia(s, i, objectRange.end);
+ if (s[i] === '"' || s[i] === "'") return true;
+ i++;
+ }
+ return false;
+}
+
+function objectEndsWithComma(s, objectRange) {
+ const body = s.slice(objectRange.start + 1, objectRange.end);
+ return body.trimEnd().endsWith(",");
+}
+
+function rangeHasValue(s, range) {
+ let i = range.start + 1;
+ while (i < range.end) {
+ i = skipTrivia(s, i, range.end);
+ if (i < range.end) return true;
+ }
+ return false;
+}
+
+function formatProperty(name, value, indent) {
+ const json = JSON.stringify(value, null, 2);
+ const formatted = json.split("\n").map((line, idx) => idx === 0 ? line : `${indent}${line}`).join("\n");
+ return `${JSON.stringify(name)}: ${formatted}`;
+}
+
+function setPropertyInObject(s, objectRange, name, value) {
+ const existing = findTopLevelProperty(s, objectRange, name);
+ if (existing) {
+ const indent = findLineIndent(s, existing.keyStart) || detectPropertyIndent(s, objectRange);
+ return `${s.slice(0, existing.keyStart)}${formatProperty(name, value, indent)}${s.slice(existing.replaceEnd)}`;
+ }
+
+ const indent = detectPropertyIndent(s, objectRange);
+ const closeIndent = findLineIndent(s, objectRange.end);
+ const needsComma = hasTopLevelProperty(s, objectRange) && !objectEndsWithComma(s, objectRange);
+ const prefix = needsComma ? "," : "";
+ const insertion = `${prefix}\n${indent}${formatProperty(name, value, indent)}\n${closeIndent}`;
+ return `${s.slice(0, objectRange.end)}${insertion}${s.slice(objectRange.end)}`;
+}
+
+function setTopLevelProperty(s, name, value) {
+ let objectRange = findTopLevelObject(s);
+ if (!objectRange) {
+ s = "{\n}\n";
+ objectRange = findTopLevelObject(s);
+ }
+ return setPropertyInObject(s, objectRange, name, value);
+}
+
+function setNestedObjectProperty(s, parentName, childName, childValue, fallbackParentValue) {
+ let objectRange = findTopLevelObject(s);
+ if (!objectRange) {
+ s = "{\n}\n";
+ objectRange = findTopLevelObject(s);
+ }
+ const parent = findTopLevelProperty(s, objectRange, parentName);
+ if (!parent) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);
+ const parentRange = findObjectRangeAt(s, parent.valueStart, parent.replaceEnd);
+ if (!parentRange) return setPropertyInObject(s, objectRange, parentName, fallbackParentValue);
+ return setPropertyInObject(s, parentRange, childName, childValue);
+}
+
+function appendStringToTopLevelArray(s, name, value) {
+ let objectRange = findTopLevelObject(s);
+ if (!objectRange) {
+ s = "{\n}\n";
+ objectRange = findTopLevelObject(s);
+ }
+ const prop = findTopLevelProperty(s, objectRange, name);
+ if (!prop) return setPropertyInObject(s, objectRange, name, [value]);
+ const arrayRange = findArrayRangeAt(s, prop.valueStart, prop.replaceEnd);
+ if (!arrayRange) return setPropertyInObject(s, objectRange, name, [value]);
+ const propIndent = findLineIndent(s, prop.keyStart) || detectPropertyIndent(s, objectRange);
+ const itemIndent = `${propIndent} `;
+ const closeIndent = findLineIndent(s, arrayRange.end) || propIndent;
+ const needsComma = rangeHasValue(s, arrayRange) && !s.slice(arrayRange.start + 1, arrayRange.end).trimEnd().endsWith(",");
+ const prefix = needsComma ? "," : "";
+ const insertion = `${prefix}\n${itemIndent}${JSON.stringify(value)}\n${closeIndent}`;
+ return `${s.slice(0, arrayRange.end)}${insertion}${s.slice(arrayRange.end)}`;
+}
+
+/** The config text with the plugin registered and the MCP fallback pointed at `mcpProxy`. */
+export function updateOpencodeConfig(raw, { pluginSpec = "", mcpProxy = "" } = {}) {
+ let data = {};
+ try { data = raw.trim() ? JSON.parse(stripJsonc(raw)) : {}; } catch { data = {}; }
+ let nextRaw = raw.trim() ? raw : "{\n}\n";
+ if (pluginSpec) {
+ const next = Array.isArray(data.plugin) ? data.plugin.slice() : [];
+ if (!next.includes(pluginSpec)) {
+ next.push(pluginSpec);
+ nextRaw = appendStringToTopLevelArray(nextRaw, "plugin", pluginSpec);
+ }
+ data.plugin = next;
+ }
+ if (mcpProxy) {
+ data.mcp = data.mcp && typeof data.mcp === "object" && !Array.isArray(data.mcp) ? data.mcp : {};
+ if (!data.mcp.openviking || data.mcp.openviking.enabled !== false) {
+ data.mcp.openviking = {
+ type: "local",
+ command: ["node", mcpProxy],
+ enabled: true,
+ timeout: 15000,
+ };
+ nextRaw = setNestedObjectProperty(nextRaw, "mcp", "openviking", data.mcp.openviking, data.mcp);
+ }
+ }
+ if (!nextRaw.endsWith("\n")) nextRaw += "\n";
+ return nextRaw;
+}
+
+export { stripJsonc };
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
+ const file = process.argv[2];
+ let raw = "";
+ try { raw = fs.readFileSync(file, "utf8"); } catch {}
+ fs.writeFileSync(file, updateOpencodeConfig(raw, {
+ pluginSpec: process.argv[3] || "",
+ mcpProxy: process.argv[4] || "",
+ }));
+}
diff --git a/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs b/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
index 7251147a1..ea34f1746 100644
--- a/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
+++ b/examples/memory-plugin-shared/lib/mcp-proxy-config.mjs
@@ -85,7 +85,9 @@ function uniq(values) {
* `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
* user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
* harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
+ * deduplicated. `sendIdentityHeaders` carries the harness's resolved auth mode
+ * so an `api_key` server, which reads the identity out of the key and ignores
+ * the headers, never sees the operator's account and user on the wire.
*/
export function buildMcpProxyConfig({
baseUrl = "",
@@ -93,6 +95,7 @@ export function buildMcpProxyConfig({
apiKey = "",
account = "",
user = "",
+ sendIdentityHeaders = false,
peerId = "",
userAgent = "",
timeoutMs,
@@ -108,6 +111,7 @@ export function buildMcpProxyConfig({
apiKey: apiKey || "",
account: account || "",
user: user || "",
+ sendIdentityHeaders: sendIdentityHeaders === true,
peerId: peerId || "",
userAgent: userAgent || "",
timeoutMs: Math.max(
diff --git a/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs b/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs
index 25e1f7198..d2019b559 100644
--- a/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs
+++ b/examples/memory-plugin-shared/lib/mcp-proxy-core.mjs
@@ -8,6 +8,8 @@
import { statSync } from "node:fs";
import { createInterface } from "node:readline";
+import { buildOvHeaders } from "./ov-http.mjs";
+
const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
const DELETE_TIMEOUT_MS = 2000;
const MAX_CONCURRENT_REQUESTS = 16;
@@ -239,21 +241,17 @@ export function createOpenVikingMcpProxy({
}
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;
+ return buildOvHeaders(proxyConfig, {
+ actorPeerId: proxyConfig.peerId,
+ extraHeaders: {
+ "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,
+ ...(includeSession && sessionId ? { "Mcp-Session-Id": sessionId } : {}),
+ },
+ });
}
function writeMessage(obj) {
diff --git a/examples/memory-plugin-shared/lib/ov-http.d.mts b/examples/memory-plugin-shared/lib/ov-http.d.mts
new file mode 100644
index 000000000..50d86c524
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/ov-http.d.mts
@@ -0,0 +1,47 @@
+export interface OvHttpConfig {
+ baseUrl?: string;
+ endpoint?: string;
+ apiKey?: string;
+ account?: string;
+ user?: string;
+ sendIdentityHeaders?: boolean;
+ userAgent?: string;
+ [key: string]: unknown;
+}
+
+export interface OvHttpRequestOptions {
+ timeoutMs?: number;
+ actorPeerId?: string;
+}
+
+export interface OvHttpEnvelope {
+ ok: boolean;
+ status: number;
+ result: any;
+ error?: any;
+ traceId?: string;
+}
+
+export function buildOvHeaders(
+ cfg?: OvHttpConfig,
+ options?: {
+ actorPeerId?: string;
+ identityHeaders?: boolean;
+ extraHeaders?: Record<string, string>;
+ },
+): Record<string, string>;
+
+export function createOvHttp(
+ cfg?: OvHttpConfig,
+ options?: {
+ defaultTimeoutMs?: number;
+ resolveActorPeerId?: () => string;
+ identityHeaders?: boolean;
+ extraHeaders?: Record<string, string>;
+ requireJsonBody?: boolean;
+ },
+): (
+ path: string,
+ init?: RequestInit,
+ options?: OvHttpRequestOptions,
+) => Promise<OvHttpEnvelope>;
diff --git a/examples/memory-plugin-shared/lib/ov-http.mjs b/examples/memory-plugin-shared/lib/ov-http.mjs
new file mode 100644
index 000000000..09c34e54f
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/ov-http.mjs
@@ -0,0 +1,111 @@
+/**
+ * The one path from a hook to the OpenViking server.
+ *
+ * Every harness used to own its own AbortController, header block and envelope
+ * parser, and they drifted: one sent the api key twice, one named the operator
+ * to every proxy on the path whether or not the server was trusted with it, one
+ * read a different field for the same account. A server-side change now lands
+ * in one place instead of eight.
+ *
+ * `X-API-Key` is deliberately absent. The server takes `Authorization: Bearer`,
+ * and the identity headers go out only when the resolved config says this
+ * server is trusted with the operator's name.
+ */
+
+// A request that aborts the instant it starts reads as a dead server. A config
+// that asks for less than a second gets a second.
+const MIN_TIMEOUT_MS = 1000;
+
+/**
+ * The headers every harness puts on every OpenViking request.
+ *
+ * `identityHeaders` overrides `cfg.sendIdentityHeaders` for the callers that
+ * decide per request rather than per config — the doctor probes both ways.
+ */
+export function buildOvHeaders(cfg = {}, { actorPeerId = "", identityHeaders, extraHeaders } = {}) {
+ const identity = identityHeaders === undefined ? Boolean(cfg.sendIdentityHeaders) : Boolean(identityHeaders);
+ const headers = { "Content-Type": "application/json" };
+ if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;
+ if (identity && cfg.account) headers["X-OpenViking-Account"] = cfg.account;
+ if (identity && cfg.user) headers["X-OpenViking-User"] = cfg.user;
+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;
+ if (cfg.userAgent) headers["User-Agent"] = cfg.userAgent;
+ return { ...headers, ...extraHeaders };
+}
+
+function responseTraceId(body) {
+ return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
+}
+
+/**
+ * Build the `fetchJSON(path, init, { timeoutMs, actorPeerId })` a harness talks
+ * through. It resolves to `{ ok, status, result, error, traceId }` and never
+ * throws: a hook that crashes on a closed port would take its host's turn with
+ * it, so a network error is `{ ok: false, status: 0 }` and the retry rules in
+ * `retryable.mjs` decide what happens next.
+ *
+ * `resolveActorPeerId` is a callback because Codex only knows its peer after
+ * loading session state under the lock, well after the client is built.
+ * `requireJsonBody` is for the capture hooks, which would rather retry a body
+ * they cannot parse than record the turn as sent.
+ */
+export function createOvHttp(cfg = {}, {
+ defaultTimeoutMs = 0,
+ resolveActorPeerId = () => "",
+ identityHeaders,
+ extraHeaders,
+ requireJsonBody = false,
+} = {}) {
+ // dsh and pi name this field `endpoint`; every other harness names it `baseUrl`.
+ const baseUrl = cfg.baseUrl || cfg.endpoint || "";
+ return async function fetchJSON(path, init = {}, options = {}) {
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, Number(options.timeoutMs) || Number(defaultTimeoutMs) || 0);
+ const controller = new AbortController();
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, timeoutMs);
+ try {
+ const headers = {
+ ...buildOvHeaders(cfg, {
+ actorPeerId: options.actorPeerId ?? resolveActorPeerId(),
+ identityHeaders,
+ extraHeaders,
+ }),
+ ...(init.headers || {}),
+ };
+ const response = await fetch(`${baseUrl}${path}`, { ...init, headers, signal: controller.signal });
+ const body = await response.json().catch(() => null);
+ if (requireJsonBody && !body) {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: { message: "empty or invalid JSON response" },
+ };
+ }
+ const traceId = responseTraceId(body);
+ if (!response.ok || body?.status === "error") {
+ return {
+ ok: false,
+ status: response.status,
+ result: null,
+ error: body?.error || { message: `HTTP ${response.status}` },
+ traceId,
+ };
+ }
+ return { ok: true, status: response.status, result: body?.result ?? body ?? {}, traceId };
+ } catch (error) {
+ const message = error?.message || String(error);
+ // This module owns the controller, so it says a timeout was a timeout
+ // rather than leaving callers to guess it from whatever fetch threw.
+ const failure = timedOut
+ ? { name: "AbortError", aborted: true, message }
+ : { message };
+ return { ok: false, status: 0, result: null, error: failure };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+}
diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.d.mts b/examples/memory-plugin-shared/lib/pending-queue.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/pending-queue.d.mts
rename to examples/memory-plugin-shared/lib/pending-queue.d.mts
diff --git a/examples/memory-plugin-shared/lib/plugin-config.d.mts b/examples/memory-plugin-shared/lib/plugin-config.d.mts
new file mode 100644
index 000000000..0b3346ec6
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/plugin-config.d.mts
@@ -0,0 +1,61 @@
+export const HARNESS_KEYS: Record<string, string>;
+
+export function harnessKey(harness: string): string;
+
+export function loadPluginSettings(
+ harness: string,
+ env?: Record<string, string | undefined>,
+ options?: { cwd?: string; clientVersion?: string; cliFile?: Record<string, any> | null },
+): Record<string, any>;
+
+export function resolveSettings(
+ harness: string,
+ options?: {
+ env?: Record<string, string | undefined>;
+ cwd?: string;
+ legacy?: Record<string, any>;
+ clientVersion?: string;
+ cliFile?: Record<string, any> | null;
+ },
+): {
+ settings: Record<string, any>;
+ configured: Set<string>;
+ sources: Record<string, string>;
+ plugin: Record<string, any>;
+};
+
+export function buildPluginConfig(
+ harness: string,
+ options?: {
+ cwd?: string;
+ env?: Record<string, string | undefined>;
+ legacy?: Record<string, any> | null;
+ manifestUrl?: string | URL;
+ version?: string;
+ hostInput?: {
+ peerId?: string;
+ account?: string;
+ user?: string;
+ apiKey?: string;
+ baseUrl?: string;
+ };
+ logFile?: string;
+ rootKeyFallback?: boolean;
+ deriveEffectivePeer?: boolean;
+ },
+): Record<string, any>;
+
+export function resolveWorkspaceSettings(
+ cwd: string,
+ env?: Record<string, string | undefined>,
+ options?: { clientVersion?: string },
+): {
+ settings: Record<string, any>;
+ root: string;
+ provenance: Record<string, any>;
+ warnings: string[];
+ announced: string[];
+ value?: Record<string, any>;
+};
+
+export function normalizeRewriteMode(value: unknown, fallback?: string): string;
diff --git a/examples/memory-plugin-shared/lib/plugin-config.mjs b/examples/memory-plugin-shared/lib/plugin-config.mjs
index 58b1b3d0f..99cbbea89 100644
--- a/examples/memory-plugin-shared/lib/plugin-config.mjs
+++ b/examples/memory-plugin-shared/lib/plugin-config.mjs
@@ -18,18 +18,24 @@
* Resolution stays env → ovcli.conf plugin.<harness> → ovcli.conf plugin →
* ov.conf harness section (legacy) → defaults.
*
- * Consumers: Claude Code and Codex only. The other harnesses ship this module
- * through `sync.mjs` but still read their knobs from the environment, so a
- * `plugin` entry named after them is inert. `HARNESS_KEYS` lists what a harness
- * loader actually consumes today — add a key here as its loader starts calling
- * `loadPluginSettings`, not before, so the section never promises a knob that
- * silently does nothing.
+ * Every harness resolves through `resolveSettings()` below, and assembles its
+ * whole configuration through `buildPluginConfig()`, so one `plugin` section
+ * configures all of them and `ov config switch` moves behaviour along with
+ * credentials. The knobs themselves are declared once in `config-schema.mjs`;
+ * this module decides which files supply them and what is derived from them.
*/
-import { readFileSync } from "node:fs";
import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
+import { join } from "node:path";
+import { HARNESS_KEYS, KNOBS, harnessKey, resolveKnobs } from "./config-schema.mjs";
+import {
+ buildUserAgent,
+ loadCredentialFiles,
+ readManifestVersion,
+ resolveAuthMode,
+ resolveOpenVikingCredentials,
+} from "./credentials.mjs";
import {
announcedOverrides,
loadWorkspaceLayers,
@@ -38,33 +44,27 @@ import {
projectWorkspaceSettings,
} from "./workspace-config.mjs";
import { findWorkspaceRoot, resolveWorkspaceIdentity } from "./workspace-identity.mjs";
+import { resolveEffectivePeerId, resolvePluginPeerId } from "./workspace-peer.mjs";
import { readEntry } from "./workspace-registry.mjs";
-const DEFAULT_OVCLI_CONF_PATH = join(homedir(), ".openviking", "ovcli.conf");
-
-export const HARNESS_KEYS = {
- claudeCode: "claude_code",
- codex: "codex",
-};
+const OVCLI_LAYER = "ovcli.conf";
+const OV_CONF_LAYER = "ov.conf";
-function tryLoadJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return null;
- }
-}
+export { HARNESS_KEYS, harnessKey };
/**
* Merge the shared plugin section with the harness-specific override.
* Returns a flat settings object; unknown keys pass through untouched so a
* harness can add its own knobs without touching this module.
+ *
+ * `cliFile` is ovcli.conf already parsed. Callers that have it hand it over so
+ * the file is read once per build and, more importantly, so the `plugin`
+ * section comes out of the same file the credential chain read — an
+ * `OPENVIKING_CONFIG_FILE` that is ovcli-shaped is ovcli.conf, and only
+ * `loadCredentialFiles` knows that.
*/
export function loadPluginSettings(harness, env = process.env, options = {}) {
- const path = resolvePath(
- (env.OPENVIKING_CLI_CONFIG_FILE || DEFAULT_OVCLI_CONF_PATH).replace(/^~/, homedir()),
- );
- const file = tryLoadJson(path);
+ const file = options.cliFile || loadCredentialFiles(env).cliFile;
const plugin = file && typeof file.plugin === "object" && file.plugin ? file.plugin : {};
const shared = {};
@@ -72,9 +72,14 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
if (value && typeof value === "object" && !Array.isArray(value)) continue;
shared[key] = value;
}
- const scoped = harness && plugin[harness] && typeof plugin[harness] === "object"
- ? plugin[harness]
- : {};
+ // Both spellings of the harness name find the same override, so copying
+ // `claude-code` out of the installer is not a silent no-op.
+ const key = harnessKey(harness);
+ const scoped = {};
+ for (const candidate of [key, key.replace(/_/g, "-")]) {
+ const value = candidate && plugin[candidate];
+ if (value && typeof value === "object" && !Array.isArray(value)) Object.assign(scoped, value);
+ }
const settings = { ...shared, ...scoped };
const cwd = String(options.cwd || "").trim();
@@ -82,6 +87,32 @@ export function loadPluginSettings(harness, env = process.env, options = {}) {
return { ...settings, ...resolveWorkspaceSettings(cwd, env, options).settings };
}
+/**
+ * Every knob for one harness, resolved through the whole layer stack.
+ *
+ * `legacy` is that harness's section in ov.conf, which is where tuning used to
+ * live: it stays the lowest configured layer so an existing deployment keeps
+ * working, and everything above it comes from files a client may edit.
+ *
+ * Returns the settings, the names some layer actually supplied (what the
+ * `*Configured` flags report), and the raw ovcli.conf merge — a couple of
+ * callers still need to know a value came from ovcli.conf rather than ov.conf.
+ */
+export function resolveSettings(harness, options = {}) {
+ const { env = process.env, cwd = "", legacy = {}, clientVersion = "", cliFile = null } = options;
+ const key = harnessKey(harness);
+ const plugin = loadPluginSettings(key, env, { cwd, clientVersion, cliFile });
+ const { settings, configured, sources } = resolveKnobs({
+ harness: key,
+ layers: [
+ { name: OV_CONF_LAYER, data: legacy },
+ { name: OVCLI_LAYER, data: plugin },
+ ],
+ env,
+ });
+ return { settings, configured, sources, plugin };
+}
+
/**
* The workspace layers for one cwd, flattened into harness knobs.
*
@@ -121,6 +152,169 @@ export function resolveWorkspaceSettings(cwd, env = process.env, { clientVersion
}
}
+const SEND_ONLY_WHEN_CONFIGURED = KNOBS.filter((knob) => knob.sendOnlyWhenConfigured);
+
+function str(value) {
+ return typeof value === "string" && value.trim() ? value.trim() : "";
+}
+
+/** The ov.conf block named after this harness, the lowest layer of every chain. */
+function ovConfSection(ovFile, key) {
+ const section = key ? ovFile?.[key] : null;
+ return section && typeof section === "object" && !Array.isArray(section) ? section : {};
+}
+
+/**
+ * A connection value ovcli.conf's `plugin` section supplied, as opposed to
+ * ov.conf's harness block or the environment — the credential chain ranks
+ * those two itself, and would rank a `plugin` value wrong.
+ */
+function fromPluginSection(settings, sources, name) {
+ return sources[name] === OVCLI_LAYER ? str(settings[name]) : "";
+}
+
+/**
+ * One harness's whole configuration: the files, the knobs, the peer, and the
+ * handful of fields derived from them.
+ *
+ * Every loader used to write this sequence out by hand and each wrote a
+ * slightly different subset, which is how ov.conf's `<harness>.authMode` came
+ * to apply on three harnesses only, and why two of the four knobs the server
+ * defaults for itself were reported as configured on two harnesses and nowhere
+ * else. What is left in a loader after this call is what only that harness
+ * knows.
+ *
+ * `legacy` replaces the ov.conf block this harness would otherwise get (dsh's
+ * host hands it one of its own); `hostInput` is what an embedding host named
+ * for this process, which is the more specific answer and outranks every file;
+ * `logFile` is the log basename this harness has always used, and a harness
+ * that never had a default log path does not get one invented for it;
+ * `rootKeyFallback` is for the harnesses whose chain predates the ovcli.conf
+ * pinning and has always ended at `server.root_api_key`.
+ */
+export function buildPluginConfig(harness, {
+ cwd = "",
+ env = process.env,
+ legacy = null,
+ manifestUrl = "",
+ version = "",
+ hostInput = {},
+ logFile = "",
+ rootKeyFallback = false,
+ deriveEffectivePeer = false,
+} = {}) {
+ const name = String(harness || "");
+ const key = harnessKey(name);
+ const workspaceCwd = str(cwd) || process.cwd();
+ const files = loadCredentialFiles(env);
+ // The version answers two questions: what the User-Agent reports, and whether
+ // a workspace file asking for a newer client gets to say so.
+ const clientVersion = str(version) || (manifestUrl ? readManifestVersion(manifestUrl) : "");
+ const { settings, configured, sources } = resolveSettings(key, {
+ env,
+ cwd: workspaceCwd,
+ legacy: legacy || ovConfSection(files.ovFile, key),
+ cliFile: files.cliFile,
+ clientVersion,
+ });
+ const credentials = resolveOpenVikingCredentials(env, key, {
+ apiKey: fromPluginSection(settings, sources, "apiKey"),
+ accountId: fromPluginSection(settings, sources, "accountId"),
+ userId: fromPluginSection(settings, sources, "userId"),
+ });
+
+ // Pinned to ovcli.conf, the credential chain stops at that file. The layers
+ // under it still answer: ov.conf's harness block is where tuning used to
+ // live, and `server.root_api_key` is where a harness that predates the
+ // pinning has always ended its chain.
+ let apiKey = credentials.apiKey;
+ let apiKeySource = credentials.apiKeySource;
+ let credentialPath = credentials.credentialPath;
+ if (!apiKey) {
+ apiKey = sources.apiKey === OV_CONF_LAYER
+ ? str(settings.apiKey)
+ : (rootKeyFallback ? str(credentials.ovFile?.server?.root_api_key) : "");
+ if (apiKey) {
+ apiKeySource = "ov";
+ credentialPath = credentials.ovPath;
+ }
+ }
+ const hostApiKey = str(hostInput.apiKey);
+ if (hostApiKey) {
+ apiKey = hostApiKey;
+ apiKeySource = "host";
+ credentialPath = "";
+ }
+
+ const hostBaseUrl = str(hostInput.baseUrl).replace(/\/+$/, "");
+ const baseUrl = hostBaseUrl || credentials.baseUrl;
+ const account = str(hostInput.account) || credentials.account;
+ const user = str(hostInput.user) || credentials.user;
+ const timeoutMs = settings.timeoutMs;
+ const peerId = resolvePluginPeerId({
+ settings,
+ configured,
+ sources,
+ credentials,
+ hostInput: hostInput.peerId,
+ env,
+ });
+
+ const config = {
+ ...settings,
+ harness: name,
+ clientVersion,
+ userAgent: buildUserAgent(name, clientVersion),
+
+ baseUrl,
+ mcpUrl: hostBaseUrl ? `${hostBaseUrl}/mcp` : credentials.mcpUrl,
+ apiKey,
+ account,
+ user,
+ ...resolveAuthMode({ settings, ovFile: credentials.ovFile, account, user }),
+
+ credentialSource: credentials.credentialSource,
+ apiKeySource,
+ credentialPath,
+ hasApiKey: Boolean(apiKey),
+ configPath: credentials.cliPath || credentials.ovPath || null,
+ cliConfigPath: credentials.cliPath,
+ ovConfigPath: credentials.ovPath,
+ cliPath: credentials.cliPath,
+ ovPath: credentials.ovPath,
+
+ peerId,
+ explicitPeerId: peerId,
+
+ // A write gets a longer budget than a read, and a digest has to finish
+ // inside the recall request it belongs to, so both fall back to a knob.
+ captureTimeoutMs: settings.captureTimeoutMs || Math.max(timeoutMs * 2, 30000),
+ recallCompressTimeoutMs: settings.recallCompressTimeoutMs
+ || Math.max(1000, settings.recallTimeoutMs - 10000),
+ debugLogPath: settings.debugLogPath
+ || (logFile ? join(homedir(), ".openviking", "logs", logFile) : ""),
+
+ // The spellings these fields carried before every harness shared a loader.
+ endpoint: baseUrl,
+ accountId: account,
+ userId: user,
+ requestTimeoutMs: timeoutMs,
+ };
+ for (const knob of SEND_ONLY_WHEN_CONFIGURED) {
+ config[`${knob.name}Configured`] = configured.has(knob.name);
+ }
+
+ // Only for the harnesses that resolve the peer once at load. The rest derive
+ // it per session, against the directory the payload names, and an MCP proxy
+ // must not derive one from wherever it happened to be launched.
+ if (deriveEffectivePeer) {
+ const effectivePeer = resolveEffectivePeerId({ cfg: config, cwd: workspaceCwd });
+ config.effectivePeer = effectivePeer;
+ config.legacyPeerId = effectivePeer.legacyPeerId;
+ }
+ return config;
+}
+
const REWRITE_MODES = new Set(["off", "client", "server", "auto"]);
/**
diff --git a/examples/pi-coding-agent-extension/shared/profile-inject.d.mts b/examples/memory-plugin-shared/lib/profile-inject.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/profile-inject.d.mts
rename to examples/memory-plugin-shared/lib/profile-inject.d.mts
diff --git a/examples/memory-plugin-shared/lib/recall-core.d.mts b/examples/memory-plugin-shared/lib/recall-core.d.mts
new file mode 100644
index 000000000..1b91f025b
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/recall-core.d.mts
@@ -0,0 +1,80 @@
+import type { OvHttpRequestOptions } from "./ov-http.mjs";
+
+export type ContextSearchBody = {
+ query: string;
+ mode: "context";
+ purpose: "coding";
+ score_threshold: number;
+ quotas?: Record<string, number>;
+ max_tokens?: number;
+ peer_scope?: "actor";
+ session_id?: string;
+ query_expansion?: "off" | "auto";
+ dedup_turns?: number;
+ exclude_uris?: string[];
+ rewrite?: boolean | "auto";
+ rewrite_max_bullets?: number;
+};
+
+export type NormalizedContextEntry = {
+ uri: string;
+ category: string;
+ detail: string;
+ score: number;
+ text: string;
+};
+
+export function buildContextSearchBody(
+ cfg?: Record<string, unknown>,
+ options?: {
+ sessionId?: string;
+ excludeUris?: string[];
+ localCompressorAvailable?: boolean;
+ },
+): ContextSearchBody;
+
+export function contextRequestTimeoutMs(
+ cfg?: Record<string, unknown>,
+ body?: Record<string, unknown>,
+): number | undefined;
+
+export function normalizeContextEntry(entry?: unknown): NormalizedContextEntry;
+
+export type RecallFetchJSON = (
+ path: string,
+ init?: RequestInit,
+ options?: OvHttpRequestOptions,
+) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>;
+
+export type RecallOptions = {
+ actorPeerId?: string;
+ legacyPeerId?: string;
+ sessionId?: string;
+ log?: (stage: string, data?: any) => void;
+};
+
+export type DetailedRecall = {
+ block: string;
+ contentCount: number;
+ hintCount: number;
+ budgetUsed: number;
+ stage: "server_assembled" | "ranked" | "no_results" | "filtered_out";
+};
+
+export function buildRecallBlockDetailed(
+ fetchJSON: RecallFetchJSON,
+ cfg: Record<string, any>,
+ query: string,
+ options?: RecallOptions,
+): Promise<DetailedRecall>;
+
+export function buildRecallBlock(
+ fetchJSON: RecallFetchJSON,
+ cfg: Record<string, any>,
+ query: string,
+ options?: RecallOptions,
+): Promise<string | null>;
+
+export function buildRecallEndpointBody(cfg?: Record<string, any>): Record<string, any>;
+export function estimateTokens(text: string): number;
+export function isRecallEnabled(cfg?: Record<string, any>): boolean;
diff --git a/examples/memory-plugin-shared/lib/recall-core.mjs b/examples/memory-plugin-shared/lib/recall-core.mjs
index f7d10d35a..5f9b2f4ec 100644
--- a/examples/memory-plugin-shared/lib/recall-core.mjs
+++ b/examples/memory-plugin-shared/lib/recall-core.mjs
@@ -30,6 +30,28 @@ const CODING_QUOTA_WEIGHTS = {
let userSpaceCache = "";
+/**
+ * Is recall on for this config?
+ *
+ * The switch has four spellings in the wild: a boolean `autoRecall`, opencode's
+ * `{ enabled }` object, dsh and pi's `syncTurns`, and the global `enabled`
+ * that turns the whole plugin off. Reading it here rather than in each loader
+ * is what keeps it from drifting a fifth time — and any spelling that says off
+ * wins, so a config that disables recall under an older name still disables it.
+ */
+export function isRecallEnabled(cfg = {}) {
+ return isSwitchOn([cfg.enabled, cfg.autoRecall, cfg.recall, cfg.syncRecall]);
+}
+
+/** Any recognised spelling that says off wins; everything else means on. */
+function isSwitchOn(values) {
+ for (const value of values) {
+ if (value === false) return false;
+ if (value && typeof value === "object" && !Array.isArray(value) && value.enabled === false) return false;
+ }
+ return true;
+}
+
export function estimateTokens(text) {
return text ? Math.ceil(String(text).length / 4) : 0;
}
@@ -337,9 +359,8 @@ async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
}
async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
- if (items.length === 0) return null;
-
- let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const budgetTotal = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ let budgetRemaining = budgetTotal;
const lines = [
"<openviking-context>",
"Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
@@ -372,15 +393,15 @@ async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId =
lines.push("</openviking-context>");
- const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ const budgetUsed = budgetTotal - budgetRemaining;
log("recall_injection_built", {
contentItems: contentCount,
hintItems: hintCount,
budgetUsed,
- budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ budgetTotal,
});
- return lines.join("\n");
+ return { block: lines.join("\n"), contentCount, hintCount, budgetUsed, stage: "ranked" };
}
const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
@@ -625,8 +646,13 @@ export async function postRecall(fetchJSON, body, opts = {}) {
* `"actor"` that sweep is off by definition, so the old peer is asked for
* separately — as itself, which is both cheaper and wider than a bare
* cross-peer read (that would need the user id, and reaches memories only).
+ *
+ * `stage` names the path the block came from, which is what a host needs to
+ * tell "the server had nothing" (`no_results`) from "the score threshold
+ * dropped everything" (`filtered_out`) when the block is empty, and a
+ * `server_assembled` block from a `ranked` one when it is not.
*/
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+export async function buildRecallBlockDetailed(fetchJSON, cfg, query, options = {}) {
const primary = await recallForPeer(fetchJSON, cfg, query, options);
const legacyPeerId = String(options.legacyPeerId || "").trim();
@@ -635,16 +661,32 @@ export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
const log = options.log || (() => {});
const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
+ if (!legacy.block) return primary;
log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
+ return {
+ block: primary.block ? `${primary.block}\n${legacy.block}` : legacy.block,
+ contentCount: primary.contentCount + legacy.contentCount,
+ hintCount: primary.hintCount + legacy.hintCount,
+ budgetUsed: primary.budgetUsed + legacy.budgetUsed,
+ stage: primary.block ? primary.stage : legacy.stage,
+ };
+}
+
+/** The block alone, or null when nothing was injectable. */
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const { block } = await buildRecallBlockDetailed(fetchJSON, cfg, query, options);
+ return block || null;
+}
+
+function emptyRecall(stage) {
+ return { block: "", contentCount: 0, hintCount: 0, budgetUsed: 0, stage };
}
async function recallForPeer(fetchJSON, cfg, query, options = {}) {
const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
const log = options.log || (() => {});
const trimmed = String(query || "").trim();
- if (!trimmed) return null;
+ if (!trimmed) return emptyRecall("no_results");
// Assembly happens server-side when the deployment offers the context face;
// older servers fall through to /recall, then to raw find.
@@ -653,12 +695,23 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
actorPeerId,
log,
});
- if (serverBlock !== null) return serverBlock || null;
+ if (serverBlock !== null) {
+ if (!serverBlock) return emptyRecall("no_results");
+ // The server rendered one budgeted unit, so nothing here degraded to a
+ // URI-only hint and the block's own estimate is what it cost.
+ return {
+ block: serverBlock,
+ contentCount: 1,
+ hintCount: 0,
+ budgetUsed: estimateTokens(serverBlock),
+ stage: "server_assembled",
+ };
+ }
const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
const perSourceLimit = Math.max(recallLimit * 2, 8);
const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
- if (raw.length === 0) return null;
+ if (raw.length === 0) return emptyRecall("no_results");
const profile = buildQueryProfile(trimmed);
const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
@@ -672,6 +725,6 @@ async function recallForPeer(fetchJSON, cfg, query, options = {}) {
items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
});
- if (picked.length === 0) return null;
+ if (picked.length === 0) return emptyRecall("filtered_out");
return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
}
diff --git a/examples/pi-coding-agent-extension/shared/session-model.d.mts b/examples/memory-plugin-shared/lib/session-model.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/session-model.d.mts
rename to examples/memory-plugin-shared/lib/session-model.d.mts
diff --git a/examples/memory-plugin-shared/lib/uri-guard.mjs b/examples/memory-plugin-shared/lib/uri-guard.mjs
index f897d7f9c..2912ae77d 100644
--- a/examples/memory-plugin-shared/lib/uri-guard.mjs
+++ b/examples/memory-plugin-shared/lib/uri-guard.mjs
@@ -1,3 +1,7 @@
+import { readFileSync, realpathSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
const DEFAULT_URI_KEYS = [
"filePath",
"file_path",
@@ -75,3 +79,109 @@ export function buildGuardMessage(uri, hint = {}) {
if (example) lines.push(`Example: ${example}`);
return lines.join("\n");
}
+
+/** The hints a host gets when it names no table of its own. */
+export const DEFAULT_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}")`,
+ },
+};
+
+/**
+ * The guard decision for one tool call, or null when the call may proceed.
+ *
+ * `hints` carries the host's replacement tool names and example calls; `guarded`
+ * narrows which tool names the host guards at all, because the set is not the
+ * same everywhere — claude-code and opencode leave the shell alone (their
+ * matchers never see it), pi guards it.
+ */
+export function evaluateUriGuard(toolName, input = {}, { hints = DEFAULT_TOOL_HINTS, guarded } = {}) {
+ const name = normalizeToolName(toolName);
+ if (guarded && !guarded.has(name)) return null;
+ const hint = hints[name];
+ if (!hint) return null;
+ const uri = findVikingUri(input);
+ if (!uri) return null;
+ return {
+ uri,
+ reason: buildGuardMessage(uri, {
+ tool: hint.tool,
+ example: typeof hint.example === "function" ? hint.example(uri, input) : hint.example,
+ }),
+ };
+}
+
+/** The PreToolUse deny envelope claude-code, trae and zcode all read. */
+export function denyHookSpecificOutput(reason) {
+ return {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: reason,
+ },
+ };
+}
+
+/** Cursor's deny envelope; its shell hook also wants the reason for the agent. */
+export function denyCursorPermission(reason, { agentMessage = false } = {}) {
+ const output = { permission: "deny", user_message: reason };
+ if (agentMessage) output.agent_message = reason;
+ return output;
+}
+
+function readHookInput() {
+ try {
+ const raw = readFileSync(0, "utf8").trim();
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Run a guard as a hook process: read the event off stdin, print the envelope.
+ *
+ * A guard is also imported by its harness tests, so the body only runs when the
+ * module is the process entrypoint. An empty envelope prints nothing — every
+ * host treats unrecognized or empty output as "no opinion", and one of them
+ * rejects any key it does not know.
+ */
+function isEntrypoint(moduleUrl) {
+ if (!process.argv[1]) return false;
+ try {
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(moduleUrl));
+ } catch {
+ return resolve(process.argv[1]) === fileURLToPath(moduleUrl);
+ }
+}
+
+export function runUriGuardHook(moduleUrl, evaluate) {
+ if (!isEntrypoint(moduleUrl)) return;
+ const output = evaluate(readHookInput());
+ if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);
+}
diff --git a/examples/memory-plugin-shared/lib/workspace-config.mjs b/examples/memory-plugin-shared/lib/workspace-config.mjs
index 527bef3e3..8f45b1338 100644
--- a/examples/memory-plugin-shared/lib/workspace-config.mjs
+++ b/examples/memory-plugin-shared/lib/workspace-config.mjs
@@ -23,6 +23,7 @@
import { readFileSync, realpathSync, statSync } from "node:fs";
import { isAbsolute, join, relative } from "node:path";
+import { WORKSPACE_ENUMS, WORKSPACE_KNOB_MAP, WORKSPACE_RANGES } from "./config-schema.mjs";
import { CONFIG_DIR_NAME, LOCAL_FILE, TEAM_FILE } from "./workspace-identity.mjs";
/**
@@ -94,37 +95,14 @@ export const FORBIDDEN_KEYS = [
*/
export const FREE_FORM_SECTIONS = ["labels"];
-const ENUMS = {
- "recall.peer_scope": ["all", "actor"],
- "peer.source": null, // free-form: preset name, template, or template array
-};
-
-const RANGES = {
- "recall.dedup_turns": { min: 0, max: 20, integer: true },
- "recall.max_items": { min: 1, max: 100, integer: true },
- "recall.score_threshold": { min: 0, max: 1, integer: false },
- "capture.commit_token_threshold": { min: 1000, max: 1_000_000, integer: true },
-};
-
/**
- * The workspace schema in the vocabulary the harness loaders already speak.
- *
- * Only knobs a loader actually reads appear here — the same rule the ovcli
- * `plugin` section follows, so the schema never advertises a setting that
- * silently does nothing. `labels` is metadata for humans and is not projected.
+ * The workspace schema is a projection of `config-schema.mjs`: the dotted key,
+ * its enum members and its range all come from the one knob declaration, so a
+ * knob cannot be spelled one way here and another way in the loaders.
*/
-const KNOB_MAP = {
- "peer.id": "peerId",
- "peer.source": "peerSource",
- "recall.enabled": "autoRecall",
- "recall.peer_scope": "recallPeerScope",
- "recall.dedup_turns": "recallDedupTurns",
- "recall.max_items": "recallLimit",
- "recall.score_threshold": "scoreThreshold",
- "capture.enabled": "autoCapture",
- "capture.commit_token_threshold": "commitTokenThreshold",
- "bypass.session_patterns": "bypassSessionPatterns",
-};
+const ENUMS = WORKSPACE_ENUMS;
+const RANGES = WORKSPACE_RANGES;
+const KNOB_MAP = WORKSPACE_KNOB_MAP;
export const WORKSPACE_SCHEMA_KEYS = Object.keys(KNOB_MAP);
diff --git a/examples/memory-plugin-shared/lib/workspace-peer.d.mts b/examples/memory-plugin-shared/lib/workspace-peer.d.mts
new file mode 100644
index 000000000..26d37fbae
--- /dev/null
+++ b/examples/memory-plugin-shared/lib/workspace-peer.d.mts
@@ -0,0 +1,23 @@
+export function deriveWorkspacePeerId(cwd: unknown): string;
+export function resolvePluginPeerId(input?: {
+ settings?: { peerId?: string };
+ configured?: { has(name: string): boolean } | null;
+ /** Which layer supplied each knob, as `resolveSettings()` reports it. */
+ sources?: Record<string, string>;
+ credentials?: { peerId?: string; credentialSource?: string };
+ /** A peer the host handed the plugin directly. */
+ hostInput?: string;
+ env?: Record<string, string | undefined>;
+ credentialSource?: string;
+}): string;
+export function resolveEffectivePeerId(input?: {
+ cfg?: { peerId?: string; workspacePeer?: boolean; peerSource?: unknown };
+ cwd?: string;
+ onWarn?: ((message: string) => void) | null;
+}): {
+ peerId: string;
+ source: "explicit" | "workspace" | "none";
+ origin: string;
+ /** The pre-git id, when it differs from `peerId`; otherwise empty. */
+ legacyPeerId: string;
+};
diff --git a/examples/memory-plugin-shared/lib/workspace-peer.mjs b/examples/memory-plugin-shared/lib/workspace-peer.mjs
index 1e6f26a77..080894d7e 100644
--- a/examples/memory-plugin-shared/lib/workspace-peer.mjs
+++ b/examples/memory-plugin-shared/lib/workspace-peer.mjs
@@ -39,6 +39,69 @@ export const DEFAULT_PEER_SOURCE = "git";
const VARIABLE_RE = /\{([a-z_]+)\}/g;
+/**
+ * Layers `resolvePluginPeerId` must not read off the merged settings, because
+ * each has a rank of its own: the environment ranks above every file, and
+ * ov.conf's harness block ranks below all of them.
+ */
+const PEER_LAYERS_RANKED_SEPARATELY = new Set(["env", "ov.conf"]);
+
+function trimmed(value) {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+/**
+ * The peer some layer named, in the one order every harness follows.
+ *
+ * Both halves of a loader's configuration carry a peer: `resolveSettings()`
+ * reads the workspace file, the machine registry and ovcli.conf's `plugin`
+ * section, while the credential chain ends in ovcli.conf's `actor_peer_id`. The
+ * more specific layer wins, so a `peerId` written for this harness outranks the
+ * account-wide actor peer — codex resolved it that way and opencode and pi
+ * resolved it the other way round, which meant one ovcli.conf produced two
+ * different peers depending on which host read it.
+ *
+ * ov.conf's harness block, where this tuning used to live, stays at the bottom.
+ * It gets its own rank rather than riding the credential chain, which drops it
+ * entirely once the credentials are pinned to ovcli.conf.
+ *
+ * `OPENVIKING_PEER_ID` still outranks every file, except when the credentials
+ * are pinned to ovcli.conf, where the environment is meant not to apply at all.
+ * A host that names a peer itself (dsh's cordis patch) outranks all of them.
+ *
+ * Returns "" when nobody named one, which is what makes
+ * `resolveEffectivePeerId()` derive one from `peer.source`.
+ */
+export function resolvePluginPeerId({
+ settings = {},
+ configured = null,
+ sources = {},
+ credentials = {},
+ hostInput = "",
+ env = process.env,
+ credentialSource = credentials?.credentialSource || "",
+} = {}) {
+ const host = trimmed(hostInput);
+ if (host) return host;
+
+ if (credentialSource !== "ovcli") {
+ const fromEnv = trimmed(env?.OPENVIKING_PEER_ID);
+ if (fromEnv) return fromEnv;
+ }
+
+ if (configured?.has?.("peerId") && !PEER_LAYERS_RANKED_SEPARATELY.has(sources?.peerId)) {
+ const named = trimmed(settings?.peerId);
+ if (named) return named;
+ }
+
+ const fromCredentials = trimmed(credentials?.peerId);
+ if (fromCredentials) return fromCredentials;
+
+ if (sources?.peerId === "ov.conf") return trimmed(settings?.peerId);
+
+ return "";
+}
+
export function deriveWorkspacePeerId(cwd) {
return legacySanitize(cwd);
}
diff --git a/examples/memory-plugin-shared/mcp-proxy-config.test.mjs b/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
index 22664a640..e4136dbdb 100644
--- a/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
+++ b/examples/memory-plugin-shared/mcp-proxy-config.test.mjs
@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
-import { homedir } from "node:os";
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
+import { buildProxyConnection } from "./lib/credentials.mjs";
import {
buildMcpProxyConfig,
DEFAULT_PROXY_TIMEOUT_MS,
@@ -10,10 +13,26 @@ import {
resolveMcpActorPeerId,
trimSlash,
} from "./lib/mcp-proxy-config.mjs";
+import { createOpenVikingMcpProxy } from "./lib/mcp-proxy-core.mjs";
+import { ROOT } from "./sync.mjs";
const OVCLI = join(homedir(), ".openviking", "ovcli.conf");
const OV = join(homedir(), ".openviking", "ov.conf");
+// Every stdio MCP entrypoint in the tree, discovered rather than listed so a
+// new harness cannot ship a proxy that skips the shared shaping. The count is
+// pinned because a renamed directory would otherwise empty the loop and turn
+// the assertions below into a no-op.
+const MCP_PROXY_COUNT = 6;
+
+const MCP_PROXIES = [
+ ...readdirSync(join(ROOT, "examples"), { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => `examples/${entry.name}/servers/mcp-proxy.mjs`)
+ .filter((rel) => existsSync(join(ROOT, rel))),
+ "agent-plugins/servers/mcp-proxy.mjs",
+].map((rel) => ({ rel, source: readFileSync(join(ROOT, rel), "utf-8") }));
+
test("a base URL becomes the /mcp endpoint exactly once", () => {
assert.equal(buildMcpProxyConfig({ baseUrl: "http://x:1933" }).mcpUrl, "http://x:1933/mcp");
assert.equal(buildMcpProxyConfig({ baseUrl: "http://x:1933/" }).mcpUrl, "http://x:1933/mcp");
@@ -98,23 +117,179 @@ test("path and URL helpers stay exported for entrypoints that need them", () =>
assert.equal(defaultCredentialPaths({}).length, 2);
});
-test("no MCP proxy derives its peer from the launch directory", async () => {
- const { readFile } = await import("node:fs/promises");
- const { dirname, join } = await import("node:path");
- const { fileURLToPath } = await import("node:url");
- const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
+test("every MCP proxy shapes its config through the shared builder", () => {
+ assert.equal(
+ MCP_PROXIES.length,
+ MCP_PROXY_COUNT,
+ `expected ${MCP_PROXY_COUNT} proxies, found ${MCP_PROXIES.map((p) => p.rel).join(", ")}`,
+ );
+ for (const { rel, source } of MCP_PROXIES) {
+ assert.match(
+ source,
+ /buildMcpProxyConfig\(/,
+ `${rel} must shape its config through buildMcpProxyConfig`,
+ );
+ }
+});
+test("no MCP proxy derives its peer from the launch directory", () => {
// A proxy is long-lived and may start anywhere, so unlike a hook it cannot
// re-derive a peer per turn. Codex already had this rule; it holds for all.
- for (const proxy of [
- "examples/claude-code-memory-plugin/servers/mcp-proxy.mjs",
- "examples/codex-memory-plugin/servers/mcp-proxy.mjs",
- "examples/opencode-plugin/servers/mcp-proxy.mjs",
- "examples/dsh-memory-plugin/servers/mcp-proxy.mjs",
- "agent-plugins/servers/mcp-proxy.mjs",
- ]) {
- const source = await readFile(join(root, proxy), "utf-8");
- assert.doesNotMatch(source, /resolveEffectivePeerId/, `${proxy} must not derive a peer`);
- assert.doesNotMatch(source, /cwd:\s*process\.cwd\(\)/, `${proxy} must not key a peer off its cwd`);
+ for (const { rel, source } of MCP_PROXIES) {
+ assert.doesNotMatch(source, /resolveEffectivePeerId/, `${rel} must not derive a peer`);
+ assert.doesNotMatch(source, /cwd:\s*process\.cwd\(\)/, `${rel} must not key a peer off its cwd`);
+ }
+});
+
+test("the default peer scope puts no actor-peer header on the wire", async () => {
+ const sent = [];
+ const proxyFor = (harnessConfig) => createOpenVikingMcpProxy({
+ stdout: { write(_line, cb) { if (cb) cb(); return true; } },
+ fetchImpl: (_url, init) => {
+ sent.push(init.headers);
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ headers: { get: () => null },
+ text: async () => JSON.stringify({ jsonrpc: "2.0", id: 1, result: {} }),
+ });
+ },
+ readConfig: () => buildMcpProxyConfig({
+ mcpUrl: "http://127.0.0.1:1933/mcp",
+ peerId: resolveMcpActorPeerId(harnessConfig),
+ }),
+ loggerFactory: () => ({ log() {}, logError() {} }),
+ });
+ const initialize = { jsonrpc: "2.0", id: 1, method: "initialize", params: {} };
+
+ await proxyFor({ peerId: "workspace-a" }).handleMessage({ ...initialize });
+ assert.equal(
+ sent[0]["X-OpenViking-Actor-Peer"],
+ undefined,
+ "the default scope is broad recall, so pinning an actor would narrow it behind the user's back",
+ );
+
+ await proxyFor({ peerId: "workspace-a", recallPeerScope: "actor" }).handleMessage({ ...initialize });
+ assert.equal(sent[1]["X-OpenViking-Actor-Peer"], "workspace-a");
+});
+
+test("the identity headers follow the auth mode, not a resolved account", async () => {
+ const sent = [];
+ const proxyFor = (extra) => createOpenVikingMcpProxy({
+ stdout: { write(_line, cb) { if (cb) cb(); return true; } },
+ fetchImpl: (_url, init) => {
+ sent.push(init.headers);
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ headers: { get: () => null },
+ text: async () => JSON.stringify({ jsonrpc: "2.0", id: 1, result: {} }),
+ });
+ },
+ readConfig: () => buildMcpProxyConfig({
+ mcpUrl: "http://127.0.0.1:1933/mcp",
+ account: "acme",
+ user: "alice",
+ ...extra,
+ }),
+ loggerFactory: () => ({ log() {}, logError() {} }),
+ });
+ const initialize = { jsonrpc: "2.0", id: 1, method: "initialize", params: {} };
+
+ await proxyFor({}).handleMessage({ ...initialize });
+ assert.equal(
+ sent[0]["X-OpenViking-Account"],
+ undefined,
+ "an api_key server reads the identity out of the key and every proxy on the path would see it",
+ );
+ assert.equal(sent[0]["X-OpenViking-User"], undefined);
+
+ await proxyFor({ sendIdentityHeaders: true }).handleMessage({ ...initialize });
+ assert.equal(sent[1]["X-OpenViking-Account"], "acme");
+ assert.equal(sent[1]["X-OpenViking-User"], "alice");
+});
+
+async function credentialFiles(prefix, { ovcli, ov }) {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ const cliPath = join(dir, "ovcli.conf");
+ const ovPath = join(dir, "ov.conf");
+ await writeFile(cliPath, JSON.stringify(ovcli, null, 2) + "\n");
+ await writeFile(ovPath, JSON.stringify(ov, null, 2) + "\n");
+ return {
+ dir,
+ cliPath,
+ ovPath,
+ env: { OPENVIKING_CLI_CONFIG_FILE: cliPath, OPENVIKING_CONFIG_FILE: ovPath },
+ };
+}
+
+// The portable bundle ships without an installer, so nobody moves a working
+// install's key out of ov.conf for it. ovcli.conf naming only a url pins the
+// credential chain to that file, and the chain has to keep going anyway.
+test("a portable proxy keeps the server key when ovcli.conf names only a url", async () => {
+ const files = await credentialFiles("ov-proxy-rootkey-", {
+ ovcli: { url: "https://ov.example.com" },
+ ov: { server: { root_api_key: "root-key" } },
+ });
+ try {
+ const cfg = buildProxyConnection("agent-plugins", { env: files.env });
+ assert.equal(cfg.baseUrl, "https://ov.example.com");
+ assert.equal(cfg.mcpUrl, "https://ov.example.com/mcp");
+ assert.equal(cfg.apiKey, "root-key");
+ assert.equal(cfg.hasApiKey, true);
+ assert.equal(cfg.apiKeySource, "ov");
+ assert.equal(cfg.credentialPath, files.ovPath);
+ assert.equal(cfg.credentialSource, "ovcli", "the mode is still what the chain ran in");
+ } finally {
+ await rm(files.dir, { recursive: true, force: true });
+ }
+});
+
+test("a portable proxy reports the auth mode, its own log path, and the files to watch", async () => {
+ const files = await credentialFiles("ov-proxy-shape-", {
+ ovcli: { url: "https://ov.example.com", api_key: "cli-key", account: "acme", user: "alice" },
+ ov: {},
+ });
+ try {
+ const cfg = buildProxyConnection("agent-plugins", { env: files.env, version: "1.2.3" });
+ assert.equal(cfg.apiKeySource, "ovcli");
+ assert.equal(cfg.authMode, "trusted", "a credential layer supplied an identity");
+ assert.equal(cfg.sendIdentityHeaders, true);
+ assert.equal(cfg.userAgent, "openviking-memory-agent-plugins/1.2.3");
+ assert.equal(cfg.timeoutMs, DEFAULT_PROXY_TIMEOUT_MS);
+ assert.equal(cfg.debug, false);
+ assert.equal(
+ cfg.debugLogPath,
+ join(homedir(), ".openviking", "logs", "agent-plugins.log"),
+ );
+ assert.deepEqual(
+ buildMcpProxyConfig({ watchedPaths: cfg.watchedPaths, env: files.env }).watchedPaths,
+ [files.cliPath, files.ovPath, OVCLI, OV],
+ );
+
+ const named = buildProxyConnection("agent-plugins", {
+ env: { ...files.env, OPENVIKING_DEBUG: "1", OPENVIKING_DEBUG_LOG: "/tmp/ov.log", OPENVIKING_TIMEOUT_MS: "60000" },
+ });
+ assert.equal(named.debug, true);
+ assert.equal(named.debugLogPath, "/tmp/ov.log");
+ assert.equal(named.timeoutMs, 60000);
+ } finally {
+ await rm(files.dir, { recursive: true, force: true });
+ }
+});
+
+test("an api_key deployment keeps the operator's identity off the wire", async () => {
+ const files = await credentialFiles("ov-proxy-apikey-", {
+ ovcli: { url: "https://ov.example.com", api_key: "cli-key", account: "acme" },
+ ov: { server: { auth_mode: "api_key" } },
+ });
+ try {
+ const cfg = buildProxyConnection("agent-plugins", { env: files.env });
+ assert.equal(cfg.authMode, "api_key");
+ assert.equal(cfg.sendIdentityHeaders, false);
+ } finally {
+ await rm(files.dir, { recursive: true, force: true });
}
});
diff --git a/examples/memory-plugin-shared/mcp-proxy-core.test.mjs b/examples/memory-plugin-shared/mcp-proxy-core.test.mjs
index 2b59de6ab..1887ad131 100644
--- a/examples/memory-plugin-shared/mcp-proxy-core.test.mjs
+++ b/examples/memory-plugin-shared/mcp-proxy-core.test.mjs
@@ -1,42 +1,463 @@
import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Writable } from "node:stream";
import test from "node:test";
+
import { createOpenVikingMcpProxy } from "./lib/mcp-proxy-core.mjs";
+import { readRequestBody } from "./testing/support.mjs";
+
+function jsonRpc(id, result = {}) {
+ return { jsonrpc: "2.0", id, result };
+}
+
+function sseMessage(obj) {
+ return `event: message\r\ndata: ${JSON.stringify(obj)}\r\n\r\n`;
+}
-function buildHarness({ fetchImpl, timeoutMs = 40 }) {
- const lines = [];
- const stdout = {
- write(line, cb) {
- lines.push(line);
- if (cb) cb();
- return true;
+/**
+ * Run `fn` against a real HTTP upstream on loopback.
+ *
+ * Unlike the mock in testing/support.mjs this one reads each request body
+ * before the handler runs: the proxy's contract is mostly about what it puts
+ * in a JSON-RPC envelope, so every case here needs the body.
+ */
+async function withServer(handler, fn) {
+ const requests = [];
+ const server = createServer(async (req, res) => {
+ const entry = {
+ method: req.method,
+ url: req.url,
+ headers: req.headers,
+ body: await readRequestBody(req),
+ };
+ requests.push(entry);
+ await handler(req, res, entry);
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const { port } = server.address();
+ return await fn({ url: `http://127.0.0.1:${port}/mcp`, requests });
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+function makeProxy({ url, fetchImpl, configOverrides = {}, localToolProvider, readConfig } = {}) {
+ const out = [];
+ const stdout = new Writable({
+ write(chunk, _encoding, callback) {
+ out.push(chunk.toString("utf-8"));
+ callback();
},
- };
+ });
const proxy = createOpenVikingMcpProxy({
- stdin: process.stdin,
stdout,
fetchImpl,
- readConfig: () => ({
- mcpUrl: "http://127.0.0.1:1933/mcp",
- timeoutMs,
+ readConfig: readConfig || (() => ({
+ mcpUrl: url,
+ apiKey: "test-key",
+ account: "default",
+ user: "zeus",
+ sendIdentityHeaders: true,
+ peerId: "peer-a",
+ userAgent: "openviking-memory-test/9.9.9",
+ timeoutMs: 5000,
+ debug: false,
+ debugLogPath: "",
+ credentialSource: "test",
+ credentialPath: "",
watchedPaths: [],
- }),
+ ...configOverrides,
+ })),
loggerFactory: () => ({ log() {}, logError() {} }),
+ localToolProvider,
});
- const responses = () => lines.map((l) => JSON.parse(l));
- const send = (obj) => proxy.handleMessage(obj);
- const waitFor = async (predicate, label) => {
- for (let i = 0; i < 100; i++) {
- const found = responses().find(predicate);
- if (found) return found;
- await new Promise((r) => setTimeout(r, 20));
- }
- throw new Error(`timed out waiting for ${label}; got: ${lines.join("|")}`);
+ return {
+ proxy,
+ out,
+ async messages() {
+ await new Promise((resolve) => setImmediate(resolve));
+ return out.join("").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
+ },
};
- return { proxy, send, waitFor, responses };
}
+test("captures initialize session id and forwards SSE JSON-RPC response", async () => {
+ await withServer((_req, res, entry) => {
+ assert.equal(entry.method, "POST");
+ assert.equal(entry.headers.authorization, "Bearer test-key");
+ assert.equal(entry.headers["x-openviking-account"], "default");
+ assert.equal(entry.headers["x-openviking-user"], "zeus");
+ assert.equal(entry.headers["x-openviking-actor-peer"], "peer-a");
+ assert.equal(entry.headers["user-agent"], "openviking-memory-test/9.9.9");
+ assert.equal(entry.headers["mcp-protocol-version"], "2025-06-18");
+ assert.equal(entry.headers["mcp-session-id"], undefined);
+ res.writeHead(200, {
+ "content-type": "text/event-stream",
+ "mcp-session-id": "sid-1",
+ });
+ res.end(`: keepalive\r\n${sseMessage(jsonRpc(1, { protocolVersion: "2025-06-18" }))}`);
+ }, async ({ url, requests }) => {
+ const { proxy, messages } = makeProxy({ url });
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: "2025-06-18" },
+ });
+ assert.deepEqual(await messages(), [jsonRpc(1, { protocolVersion: "2025-06-18" })]);
+ assert.equal(requests.length, 1);
+ });
+});
+
+test("never forwards the client's un-negotiated protocol version header", async () => {
+ await withServer((_req, res, entry) => {
+ // Strict upstreams 400 on unsupported MCP-Protocol-Version before
+ // negotiation runs, so the header must stay on a proxy-known version
+ // even when the client asks for a newer spec (Trae sends 2025-11-25).
+ assert.equal(entry.headers["mcp-protocol-version"], "2025-06-18");
+ res.writeHead(200, {
+ "content-type": "application/json",
+ "mcp-session-id": "sid-np",
+ });
+ if (entry.body.method === "initialize") {
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { protocolVersion: "2025-06-18" })));
+ return;
+ }
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { tools: [] })));
+ }, async ({ url, requests }) => {
+ const { proxy } = makeProxy({ url });
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: "2025-11-25" },
+ });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ assert.equal(requests.length, 2);
+ // The initialize body still carries the client's ask end-to-end; only the
+ // transport header is pinned until the server negotiates.
+ assert.equal(requests[0].body.params.protocolVersion, "2025-11-25");
+ });
+});
+
+test("adopts the server-negotiated protocol version for subsequent requests", async () => {
+ await withServer((_req, res, entry) => {
+ if (entry.body.method === "initialize") {
+ res.writeHead(200, {
+ "content-type": "application/json",
+ "mcp-session-id": "sid-nv",
+ });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { protocolVersion: "2025-03-26" })));
+ return;
+ }
+ assert.equal(entry.headers["mcp-protocol-version"], "2025-03-26");
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { tools: [] })));
+ }, async ({ url, requests }) => {
+ const { proxy } = makeProxy({ url });
+ // Client asks 2025-06-18 but the server negotiates down: follow-up
+ // requests must carry the response's version, not the request's.
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: { protocolVersion: "2025-06-18" },
+ });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ assert.equal(requests.length, 2);
+ });
+});
+
+test("forwards notifications and writes no stdout for HTTP 202", async () => {
+ await withServer((_req, res, entry) => {
+ assert.equal(entry.body.method, "notifications/initialized");
+ res.writeHead(202, { "content-type": "application/json" });
+ res.end("");
+ }, async ({ url }) => {
+ const { proxy, messages } = makeProxy({ url });
+ await proxy.handleMessage({ jsonrpc: "2.0", method: "notifications/initialized" });
+ assert.deepEqual(await messages(), []);
+ });
+});
+
+test("uses independent POST requests for concurrent calls", async () => {
+ await withServer(async (_req, res, entry) => {
+ const delay = entry.body.id === 1 ? 50 : 5;
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { name: entry.body.method })));
+ }, async ({ url, requests }) => {
+ const { proxy, messages } = makeProxy({ url });
+ await Promise.all([
+ proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
+ proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/call" }),
+ ]);
+ const ids = (await messages()).map((m) => m.id).sort();
+ assert.deepEqual(ids, [1, 2]);
+ assert.equal(requests.length, 2);
+ });
+});
+
+test("appends local tools to the upstream tools/list result", async () => {
+ const localTools = [
+ { name: "local_probe", description: "Probe locally", inputSchema: { type: "object" } },
+ { name: "local_echo", description: "Echo locally", inputSchema: { type: "object" } },
+ ];
+ await withServer((_req, res, entry) => {
+ assert.equal(entry.body.method, "tools/list");
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, {
+ tools: [{ name: "find", description: "Find context", inputSchema: { type: "object" } }],
+ })));
+ }, async ({ url, requests }) => {
+ const { proxy, messages } = makeProxy({
+ url,
+ localToolProvider: {
+ listTools: () => localTools,
+ async callTool() { return null; },
+ },
+ });
+
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 20, method: "tools/list" });
+
+ const [response] = await messages();
+ assert.deepEqual(response.result.tools.map((tool) => tool.name), [
+ "find",
+ "local_probe",
+ "local_echo",
+ ]);
+ assert.equal(requests.length, 1);
+ });
+});
+
+test("replaces an upstream tool definition when the local tool has the same name", async () => {
+ const localTool = {
+ name: "local_probe",
+ description: "Local probe",
+ inputSchema: { type: "object", required: ["query"] },
+ };
+ await withServer((_req, res, entry) => {
+ assert.equal(entry.body.method, "tools/list");
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, {
+ tools: [
+ { name: "find", description: "Find context", inputSchema: { type: "object" } },
+ {
+ name: "local_probe",
+ description: "Upstream probe",
+ inputSchema: { type: "object", required: ["text"] },
+ },
+ ],
+ })));
+ }, async ({ url }) => {
+ const { proxy, messages } = makeProxy({
+ url,
+ localToolProvider: {
+ listTools: () => [localTool],
+ async callTool() { return null; },
+ },
+ });
+
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 22, method: "tools/list" });
+
+ const [response] = await messages();
+ assert.deepEqual(response.result.tools, [
+ { name: "find", description: "Find context", inputSchema: { type: "object" } },
+ localTool,
+ ]);
+ });
+});
+
+test("handles local tools without forwarding tools/call upstream", async () => {
+ const calls = [];
+ const { proxy, messages } = makeProxy({
+ url: "http://127.0.0.1:1/mcp",
+ localToolProvider: {
+ listTools: () => [{ name: "local_probe" }],
+ async callTool(params, context) {
+ calls.push({ params, context });
+ return { content: [{ type: "text", text: '{"results":[]}' }] };
+ },
+ },
+ });
+
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 21,
+ method: "tools/call",
+ params: { name: "local_probe", arguments: { query: "test" } },
+ });
+
+ assert.equal(calls.length, 1);
+ assert.deepEqual(calls[0].params, {
+ name: "local_probe",
+ arguments: { query: "test" },
+ });
+ assert.equal(calls[0].context.config.user, "zeus");
+ assert.deepEqual(await messages(), [
+ jsonRpc(21, { content: [{ type: "text", text: '{"results":[]}' }] }),
+ ]);
+});
+
+test("a proxy with no local tool provider passes both tool methods through", async () => {
+ // Most harnesses run the proxy without one, so the local-tool branches must
+ // stay invisible: the listing is the upstream's, and a call named like a
+ // local tool is still the upstream's to answer.
+ await withServer((_req, res, entry) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ if (entry.body.method === "tools/list") {
+ res.end(JSON.stringify(jsonRpc(entry.body.id, {
+ tools: [{ name: "find", description: "Find context", inputSchema: { type: "object" } }],
+ })));
+ return;
+ }
+ res.end(JSON.stringify(jsonRpc(entry.body.id, { content: [{ type: "text", text: "upstream" }] })));
+ }, async ({ url, requests }) => {
+ const { proxy, messages } = makeProxy({ url });
+
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 30, method: "tools/list" });
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 31,
+ method: "tools/call",
+ params: { name: "local_probe", arguments: { query: "test" } },
+ });
+
+ const [listed, called] = await messages();
+ assert.deepEqual(listed.result.tools, [
+ { name: "find", description: "Find context", inputSchema: { type: "object" } },
+ ]);
+ assert.deepEqual(called.result, { content: [{ type: "text", text: "upstream" }] });
+ assert.equal(requests.length, 2);
+ assert.equal(requests[1].body.params.name, "local_probe");
+ });
+});
+
+test("reloads changed credential files before calling a local tool", async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "openviking-mcp-proxy-"));
+ const credentialPath = join(dir, "ovcli.conf");
+ writeFileSync(credentialPath, "old-key", "utf-8");
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+
+ let apiKey = "old-key";
+ const receivedKeys = [];
+ const readConfig = () => ({
+ mcpUrl: "http://127.0.0.1:1/mcp",
+ apiKey,
+ account: "default",
+ user: "zeus",
+ peerId: "peer-a",
+ timeoutMs: 5000,
+ debug: false,
+ debugLogPath: "",
+ credentialSource: "ovcli",
+ credentialPath,
+ watchedPaths: [credentialPath],
+ });
+ const { proxy, messages } = makeProxy({
+ readConfig,
+ localToolProvider: {
+ listTools: () => [{ name: "local_probe" }],
+ async callTool(_params, context) {
+ receivedKeys.push(context.config.apiKey);
+ return { content: [{ type: "text", text: '{"results":[]}' }] };
+ },
+ },
+ });
+
+ apiKey = "new-key";
+ writeFileSync(credentialPath, "new-key-with-different-size", "utf-8");
+ await proxy.handleMessage({
+ jsonrpc: "2.0",
+ id: 22,
+ method: "tools/call",
+ params: { name: "local_probe", arguments: { query: "test" } },
+ });
+
+ assert.deepEqual(receivedKeys, ["new-key"]);
+ assert.equal((await messages())[0].id, 22);
+});
+
+test("reinitializes after 404 and retries the original request once", async () => {
+ let call = 0;
+ await withServer((_req, res, entry) => {
+ call += 1;
+ if (call === 1) {
+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-old" });
+ res.end(JSON.stringify(jsonRpc(1, {})));
+ return;
+ }
+ if (call === 2) {
+ assert.equal(entry.headers["mcp-session-id"], "sid-old");
+ res.writeHead(404, { "content-type": "application/json" });
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: entry.body.id, error: { code: -32000, message: "session missing" } }));
+ return;
+ }
+ if (call === 3) {
+ assert.equal(entry.body.method, "initialize");
+ assert.match(String(entry.body.id), /^openviking-proxy-reinit-/);
+ assert.equal(entry.headers["mcp-session-id"], undefined);
+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-new" });
+ res.end(JSON.stringify(jsonRpc(entry.body.id, {})));
+ return;
+ }
+ assert.equal(entry.headers["mcp-session-id"], "sid-new");
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(jsonRpc(2, { ok: true })));
+ }, async ({ url, requests }) => {
+ const { proxy, messages } = makeProxy({ url });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ const responses = await messages();
+ assert.equal(responses.at(-1).id, 2);
+ assert.deepEqual(responses.at(-1).result, { ok: true });
+ assert.equal(requests.length, 4);
+ });
+});
+
+test("maps 401/403 to actionable JSON-RPC auth errors", async () => {
+ await withServer((_req, res) => {
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32001, message: "bad token" } }));
+ }, async ({ url }) => {
+ const { proxy, messages } = makeProxy({ url });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 7, method: "tools/list" });
+ const [msg] = await messages();
+ assert.equal(msg.id, 7);
+ assert.equal(msg.error.code, -32001);
+ assert.match(msg.error.message, /authentication failed/i);
+ assert.equal(msg.error.data.status, 401);
+ assert.equal(msg.error.data.serverMessage, "bad token");
+ });
+});
+
+test("DELETEs the upstream MCP session on close", async () => {
+ await withServer((_req, res, entry) => {
+ if (entry.method === "POST") {
+ res.writeHead(200, { "content-type": "application/json", "mcp-session-id": "sid-close" });
+ res.end(JSON.stringify(jsonRpc(1, {})));
+ return;
+ }
+ assert.equal(entry.method, "DELETE");
+ assert.equal(entry.headers["mcp-session-id"], "sid-close");
+ res.writeHead(204);
+ res.end("");
+ }, async ({ url, requests }) => {
+ const { proxy } = makeProxy({ url });
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
+ await proxy.closeSession();
+ assert.equal(requests.at(-1).method, "DELETE");
+ });
+});
+
test("an aborted request maps to -32004 naming the timeout budget", async () => {
- const harness = buildHarness({
+ const { proxy, messages } = makeProxy({
+ url: "http://127.0.0.1:1933/mcp",
+ configOverrides: { timeoutMs: 40 },
// Stalls until aborted, like a real signal-aware fetch against a slow server.
fetchImpl: (_url, { signal } = {}) =>
new Promise((_resolve, reject) => {
@@ -46,13 +467,10 @@ test("an aborted request maps to -32004 naming the timeout budget", async () =>
reject(err);
});
}),
- timeoutMs: 40,
});
- harness.send({ jsonrpc: "2.0", id: 7, method: "initialize", params: {} });
- const res = await harness.waitFor(
- (m) => m.id === 7 && m.error,
- "timeout error response",
- );
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 7, method: "initialize", params: {} });
+ const [res] = await messages();
+ assert.equal(res.id, 7);
assert.equal(res.error.code, -32004);
assert.match(res.error.message, /timed out after 40ms/);
assert.match(res.error.message, /OPENVIKING_TIMEOUT_MS/);
@@ -61,16 +479,15 @@ test("an aborted request maps to -32004 naming the timeout budget", async () =>
});
test("a genuine connection failure still maps to -32001", async () => {
- const harness = buildHarness({
+ const { proxy, messages } = makeProxy({
+ url: "http://127.0.0.1:1933/mcp",
fetchImpl: () => {
throw new TypeError("fetch failed");
},
});
- harness.send({ jsonrpc: "2.0", id: 8, method: "initialize", params: {} });
- const res = await harness.waitFor(
- (m) => m.id === 8 && m.error,
- "connection error response",
- );
+ await proxy.handleMessage({ jsonrpc: "2.0", id: 8, method: "initialize", params: {} });
+ const [res] = await messages();
+ assert.equal(res.id, 8);
assert.equal(res.error.code, -32001);
assert.match(res.error.message, /reachable/);
});
diff --git a/examples/memory-plugin-shared/one-header-builder.test.mjs b/examples/memory-plugin-shared/one-header-builder.test.mjs
new file mode 100644
index 000000000..38116bbe8
--- /dev/null
+++ b/examples/memory-plugin-shared/one-header-builder.test.mjs
@@ -0,0 +1,73 @@
+/**
+ * One module writes the OpenViking request headers.
+ *
+ * Every harness used to spell the header block out for itself, and they
+ * drifted: one named the operator to every proxy on the path whether or not the
+ * server was trusted with it, one sent the api key twice, one read a different
+ * field for the same account. `wire-headers.test.mjs` pins what goes out;
+ * this pins that there is only one place left that can change it.
+ *
+ * `X-OpenViking-Actor-Peer` stands in for the whole block: it is the header a
+ * hand-rolled stack cannot avoid writing, so a new one shows up here the day it
+ * is added. Prose may name it freely — this reads source only.
+ *
+ * openclaw is deliberately out of scope; it does not share this stack yet.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync, readdirSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+import test from "node:test";
+
+import { ASSEMBLED_ROOTS, ROOT, SHARED_DIR, TARGETS } from "./sync.mjs";
+
+const PEER_HEADER = "X-OpenViking-Actor-Peer";
+const BUILDER = join(SHARED_DIR, "ov-http.mjs");
+const OPENCLAW = join(ROOT, "examples", "openclaw-plugin");
+
+// Whoever the sync ships to is who this covers, so a new harness is guarded
+// the day it is added rather than the day someone remembers this file.
+const ROOTS = [...TARGETS.map((target) => target.root), ...ASSEMBLED_ROOTS, SHARED_DIR]
+ .filter((root) => root !== OPENCLAW);
+
+const SOURCE_EXTENSIONS = [".mjs", ".js", ".cjs", ".ts", ".mts"];
+const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "coverage"]);
+// The vendored copies are byte copies of lib/, so they carry whatever lib/ does.
+const VENDORED = TARGETS.map((target) => target.dir);
+
+function isSource(name) {
+ return SOURCE_EXTENSIONS.some((ext) => name.endsWith(ext)) && !/\.test\.[^.]+$/.test(name);
+}
+
+function sourceFiles(dir, out = []) {
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return out;
+ }
+ for (const entry of entries) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (!SKIP_DIRS.has(entry.name) && !VENDORED.includes(path)) sourceFiles(path, out);
+ } else if (isSource(entry.name)) {
+ out.push(path);
+ }
+ }
+ return out;
+}
+
+test("only the shared HTTP module writes the OpenViking request headers", () => {
+ const files = ROOTS.flatMap((dir) => sourceFiles(dir));
+ assert.ok(files.length > 100, `expected the plugin family's sources, found ${files.length}`);
+
+ const offenders = files
+ .filter((file) => file !== BUILDER && readFileSync(file, "utf-8").includes(PEER_HEADER))
+ .map((file) => relative(ROOT, file).split(sep).join("/"));
+
+ assert.deepEqual(
+ offenders,
+ [],
+ `${PEER_HEADER} belongs to lib/ov-http.mjs; these build their own headers: ${offenders.join(", ")}`,
+ );
+});
diff --git a/examples/memory-plugin-shared/ov-http.test.mjs b/examples/memory-plugin-shared/ov-http.test.mjs
new file mode 100644
index 000000000..00d7fdba3
--- /dev/null
+++ b/examples/memory-plugin-shared/ov-http.test.mjs
@@ -0,0 +1,261 @@
+/**
+ * The wire shape lives in one module now, so it is pinned in one place too.
+ * `wire-headers.test.mjs` proves each harness still sends what this builds;
+ * this proves what it builds.
+ */
+
+import assert from "node:assert/strict";
+import { afterEach, test } from "node:test";
+
+import { buildOvHeaders, createOvHttp } from "./lib/ov-http.mjs";
+
+const CFG = {
+ baseUrl: "http://127.0.0.1:1933",
+ apiKey: "secret",
+ account: "acct-a",
+ user: "user-a",
+ sendIdentityHeaders: true,
+ userAgent: "openviking-memory-test/9.9.9",
+};
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+function respond(status, body, { json = true } = {}) {
+ const calls = [];
+ globalThis.fetch = async (url, init) => {
+ calls.push({ url, init });
+ return new Response(json ? JSON.stringify(body) : body, {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ return calls;
+}
+
+test("a successful response unwraps result and carries the trace id", async () => {
+ const calls = respond(200, { status: "ok", result: { session_id: "s-1", trace_id: "trace-ok" } });
+ const fetchJSON = createOvHttp(CFG, { defaultTimeoutMs: 5000 });
+
+ const res = await fetchJSON("/api/v1/sessions/s-1");
+
+ assert.equal(calls[0].url, "http://127.0.0.1:1933/api/v1/sessions/s-1");
+ assert.equal(res.ok, true);
+ assert.equal(res.status, 200);
+ assert.deepEqual(res.result, { session_id: "s-1", trace_id: "trace-ok" });
+ assert.equal(res.traceId, "trace-ok");
+});
+
+test("a body without a result envelope is returned whole", async () => {
+ respond(200, { status: "healthy", version: "1.2.3" });
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/health");
+
+ assert.equal(res.ok, true);
+ assert.deepEqual(res.result, { status: "healthy", version: "1.2.3" });
+});
+
+test("a non-2xx response keeps the server's error and trace id", async () => {
+ respond(503, { status: "error", error: { code: "FAILED", message: "nope", trace_id: "trace-err" } });
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/api/v1/sessions/s-1/commit");
+
+ assert.equal(res.ok, false);
+ assert.equal(res.status, 503);
+ assert.equal(res.result, null);
+ assert.equal(res.error.code, "FAILED");
+ assert.equal(res.traceId, "trace-err");
+});
+
+test("an error envelope inside a 200 is still a failure", async () => {
+ respond(200, { status: "error", error: { message: "nope" } });
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/api/v1/sessions/s-1/commit");
+
+ assert.equal(res.ok, false);
+ assert.equal(res.status, 200);
+ assert.equal(res.error.message, "nope");
+});
+
+test("a non-2xx with no error field is described by its status", async () => {
+ respond(404, { detail: "Not Found" });
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/api/v1/sessions/missing");
+
+ assert.equal(res.ok, false);
+ assert.equal(res.error.message, "HTTP 404");
+});
+
+test("a network error is an envelope, not a throw", async () => {
+ globalThis.fetch = async () => {
+ throw new Error("connect ECONNREFUSED 127.0.0.1:1933");
+ };
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/health");
+
+ // Status 0 is what retryable.mjs reads as "the server never answered".
+ assert.deepEqual(res, {
+ ok: false,
+ status: 0,
+ result: null,
+ error: { message: "connect ECONNREFUSED 127.0.0.1:1933" },
+ });
+});
+
+test("an unparseable body is an empty result, or a failure when the caller requires JSON", async () => {
+ respond(200, "not json at all", { json: false });
+ const lenient = await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/health");
+ assert.equal(lenient.ok, true);
+ assert.deepEqual(lenient.result, {});
+
+ respond(200, "not json at all", { json: false });
+ const strict = await createOvHttp(CFG, { defaultTimeoutMs: 5000, requireJsonBody: true })("/health");
+ assert.equal(strict.ok, false);
+ assert.equal(strict.status, 200);
+ assert.equal(strict.error.message, "empty or invalid JSON response");
+});
+
+test("the request aborts on the configured timeout", async () => {
+ let seenSignal = null;
+ globalThis.fetch = (_url, init) => new Promise((_resolve, reject) => {
+ seenSignal = init.signal;
+ init.signal.addEventListener("abort", () => reject(new Error("The operation was aborted.")));
+ });
+
+ const started = Date.now();
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 1000 })("/health");
+
+ assert.equal(seenSignal.aborted, true);
+ assert.ok(Date.now() - started < 5000, "the default timeout did not fire");
+ assert.equal(res.ok, false);
+ assert.equal(res.status, 0);
+});
+
+test("a per-call timeout overrides the default", async () => {
+ globalThis.fetch = (_url, init) => new Promise((_resolve, reject) => {
+ init.signal.addEventListener("abort", () => reject(new Error("The operation was aborted.")));
+ });
+
+ const started = Date.now();
+ // The default would outlast this test; the per-call budget is what fires.
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 600000 })("/health", {}, { timeoutMs: 1000 });
+
+ assert.equal(res.ok, false);
+ assert.ok(Date.now() - started < 5000, "the per-call timeout did not fire");
+});
+
+test("a budget below the floor is raised to it", async () => {
+ let aborted = false;
+ globalThis.fetch = (_url, init) => new Promise((_resolve, reject) => {
+ init.signal.addEventListener("abort", () => {
+ aborted = true;
+ reject(new Error("The operation was aborted."));
+ });
+ });
+
+ const started = Date.now();
+ const pending = createOvHttp(CFG, { defaultTimeoutMs: 10 })("/health");
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ // A request that gives up in milliseconds reads a busy server as a dead one.
+ assert.equal(aborted, false, "the request gave up before the floor");
+
+ const res = await pending;
+ const elapsed = Date.now() - started;
+
+ assert.equal(res.ok, false);
+ assert.ok(elapsed >= 900, `aborted after ${elapsed}ms, well short of the floor`);
+ assert.ok(elapsed < 5000, "the floor did not fire");
+});
+
+test("a timed-out request says so in the envelope, not in its message", async () => {
+ globalThis.fetch = (_url, init) => new Promise((_resolve, reject) => {
+ // Whatever fetch throws on abort is the runtime's business, not a contract.
+ init.signal.addEventListener("abort", () => reject(new Error("terminated")));
+ });
+
+ const res = await createOvHttp(CFG, { defaultTimeoutMs: 1000 })("/health");
+
+ assert.equal(res.status, 0);
+ assert.equal(res.error.name, "AbortError");
+ assert.equal(res.error.aborted, true);
+});
+
+test("a trusted server is told who the operator is; an untrusted one only gets the key", async () => {
+ const trusted = respond(200, { status: "ok", result: {} });
+ await createOvHttp(CFG, { defaultTimeoutMs: 5000, resolveActorPeerId: () => "peer-a" })("/health");
+ assert.deepEqual(trusted[0].init.headers, {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer secret",
+ "X-OpenViking-Account": "acct-a",
+ "X-OpenViking-User": "user-a",
+ "X-OpenViking-Actor-Peer": "peer-a",
+ "User-Agent": "openviking-memory-test/9.9.9",
+ });
+
+ const apiKeyOnly = respond(200, { status: "ok", result: {} });
+ await createOvHttp({ ...CFG, sendIdentityHeaders: false }, {
+ defaultTimeoutMs: 5000,
+ resolveActorPeerId: () => "peer-a",
+ })("/health");
+ assert.deepEqual(apiKeyOnly[0].init.headers, {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer secret",
+ "X-OpenViking-Actor-Peer": "peer-a",
+ "User-Agent": "openviking-memory-test/9.9.9",
+ });
+});
+
+test("the api key rides on Authorization alone", () => {
+ const headers = buildOvHeaders(CFG, { actorPeerId: "peer-a" });
+
+ assert.equal(headers["Authorization"], "Bearer secret");
+ assert.equal(headers["X-API-Key"], undefined);
+});
+
+test("identityHeaders overrides what the config says about trust", () => {
+ assert.equal(buildOvHeaders(CFG, { identityHeaders: false })["X-OpenViking-Account"], undefined);
+ assert.equal(
+ buildOvHeaders({ ...CFG, sendIdentityHeaders: false }, { identityHeaders: true })["X-OpenViking-Account"],
+ "acct-a",
+ );
+});
+
+test("extraHeaders are added to every request", async () => {
+ const calls = respond(200, { status: "ok", result: {} });
+ await createOvHttp(CFG, { defaultTimeoutMs: 5000, extraHeaders: { Accept: "text/event-stream" } })("/mcp");
+
+ assert.equal(calls[0].init.headers.Accept, "text/event-stream");
+});
+
+test("the actor peer header is absent until something names a peer", async () => {
+ const anonymous = respond(200, { status: "ok", result: {} });
+ await createOvHttp(CFG, { defaultTimeoutMs: 5000 })("/health");
+ assert.equal("X-OpenViking-Actor-Peer" in anonymous[0].init.headers, false);
+
+ const empty = respond(200, { status: "ok", result: {} });
+ await createOvHttp(CFG, { defaultTimeoutMs: 5000, resolveActorPeerId: () => "" })("/health");
+ assert.equal("X-OpenViking-Actor-Peer" in empty[0].init.headers, false);
+});
+
+test("a per-call peer beats the resolver, which is read per request", async () => {
+ let peer = "first-peer";
+ const calls = respond(200, { status: "ok", result: {} });
+ const fetchJSON = createOvHttp(CFG, { defaultTimeoutMs: 5000, resolveActorPeerId: () => peer });
+
+ await fetchJSON("/health");
+ await fetchJSON("/health", {}, { actorPeerId: "session-peer" });
+ // Codex only learns its peer after loading state under the session lock.
+ peer = "second-peer";
+ await fetchJSON("/health");
+
+ assert.deepEqual(calls.map((call) => call.init.headers["X-OpenViking-Actor-Peer"]), [
+ "first-peer",
+ "session-peer",
+ "second-peer",
+ ]);
+});
+
+test("dsh and pi name the base url `endpoint`", async () => {
+ const calls = respond(200, { status: "ok", result: {} });
+ await createOvHttp({ endpoint: "http://127.0.0.1:1934" }, { defaultTimeoutMs: 5000 })("/health");
+
+ assert.equal(calls[0].url, "http://127.0.0.1:1934/health");
+});
diff --git a/examples/memory-plugin-shared/pending-queue.test.mjs b/examples/memory-plugin-shared/pending-queue.test.mjs
new file mode 100644
index 000000000..10f922bfb
--- /dev/null
+++ b/examples/memory-plugin-shared/pending-queue.test.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { readdir } from "node:fs/promises";
+import test from "node:test";
+
+import {
+ claimForReplay,
+ enqueue,
+ listPending,
+ replayPending,
+} from "./lib/pending-queue.mjs";
+import { withPendingDir } from "./testing/support.mjs";
+
+test("replayPending sends queued entries and removes them after success", async () => {
+ await withPendingDir(async () => {
+ const payload = { role: "assistant", content: "queued response" };
+ await enqueue("addMessage", "queue-replay", payload);
+
+ const calls = [];
+ const result = await replayPending(async (path, init) => {
+ calls.push({ path, init });
+ return { ok: true };
+ }, () => {});
+
+ assert.deepEqual(result, { replayed: 1, failed: 0, skipped: 0, deferred: 0 });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].path, "/api/v1/sessions/queue-replay/messages");
+ assert.deepEqual(JSON.parse(calls[0].init.body), payload);
+ assert.deepEqual(await listPending(), []);
+ });
+});
+
+test("enqueue deduplicates identical payloads", async () => {
+ await withPendingDir(async () => {
+ const payload = { role: "user", parts: [{ type: "text", text: "same" }] };
+ const first = await enqueue("addMessage", "queue-dedup", payload);
+ const second = await enqueue("addMessage", "queue-dedup", payload);
+
+ assert.equal(first.ok, true);
+ assert.equal(second.ok, true);
+ assert.equal(second.deduped, true);
+ assert.equal((await listPending()).length, 1);
+ });
+});
+
+test("replayPending honors the per-run replay limit", async () => {
+ await withPendingDir(async () => {
+ process.env.OPENVIKING_PENDING_REPLAY_LIMIT = "1";
+ await enqueue("addMessage", "queue-limit", { role: "user", content: "one" });
+ await enqueue("addMessage", "queue-limit", { role: "user", content: "two" });
+
+ const calls = [];
+ const result = await replayPending(async (path, init) => {
+ calls.push({ path, init });
+ return { ok: true };
+ }, () => {});
+
+ assert.equal(result.replayed, 1);
+ assert.equal(result.deferred, 1);
+ assert.equal(calls.length, 1);
+ assert.equal((await listPending()).length, 1);
+ });
+});
+
+test("claimForReplay atomically claims a file only once", async () => {
+ await withPendingDir(async (dir) => {
+ await enqueue("commitSession", "queue-claim", {});
+ const [{ filename }] = await listPending();
+
+ const firstClaim = await claimForReplay(filename);
+ const secondClaim = await claimForReplay(filename);
+
+ assert.match(firstClaim, /\.processing$/);
+ assert.equal(secondClaim, null);
+ assert.deepEqual(await readdir(dir), [firstClaim]);
+ });
+});
diff --git a/examples/memory-plugin-shared/plugin-config.test.mjs b/examples/memory-plugin-shared/plugin-config.test.mjs
new file mode 100644
index 000000000..9c4905270
--- /dev/null
+++ b/examples/memory-plugin-shared/plugin-config.test.mjs
@@ -0,0 +1,351 @@
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { HARNESS_KEYS, KNOBS } from "./lib/config-schema.mjs";
+import { buildPluginConfig } from "./lib/plugin-config.mjs";
+import { loadAgentHookConfig } from "./lib/agent-hook-runtime.mjs";
+import { loadConfig as loadClaudeCode } from "../claude-code-memory-plugin/scripts/config.mjs";
+import { loadConfig as loadCodex } from "../codex-memory-plugin/scripts/config.mjs";
+import { loadConfig as loadOpencode } from "../opencode-plugin/lib/config.mjs";
+import { resolveConfig as loadDsh } from "../dsh-memory-plugin/config.mjs";
+import { loadConfig as loadPi } from "../pi-coding-agent-extension/config.ts";
+
+/**
+ * Every harness's loader, and the fields it is allowed to answer differently
+ * from `buildPluginConfig`. That list is the whole of what stays local: a
+ * loader that starts reinterpreting anything else fails this file.
+ */
+const LOADERS = {
+ claude_code: {
+ harness: "claude-code",
+ load: (cwd) => loadClaudeCode(cwd),
+ options: { manifestUrl: new URL("../claude-code-memory-plugin/.claude-plugin/plugin.json", import.meta.url), logFile: "cc-hooks.log", rootKeyFallback: true },
+ owns: ["configPath", "credentialPath"],
+ },
+ codex: {
+ harness: "codex",
+ load: (cwd) => loadCodex(cwd),
+ options: { manifestUrl: new URL("../codex-memory-plugin/.codex-plugin/plugin.json", import.meta.url), logFile: "codex-hooks.log" },
+ owns: ["recallCompress"],
+ },
+ opencode: {
+ harness: "opencode",
+ load: (cwd) => loadOpencode("", cwd),
+ options: { manifestUrl: new URL("../opencode-plugin/package.json", import.meta.url), logFile: "opencode-plugin.log", deriveEffectivePeer: true },
+ // This plugin reads the repo-context switch as a section, not a flag.
+ owns: ["repoContext"],
+ },
+ dsh: {
+ harness: "dsh",
+ load: (cwd) => loadDsh({}, process.env, cwd),
+ options: { version: "0.4.0", deriveEffectivePeer: true },
+ owns: ["peerId"],
+ },
+ pi: {
+ harness: "pi",
+ load: (cwd) => loadPi(cwd),
+ options: { version: "0.3.0", deriveEffectivePeer: true },
+ owns: ["peerId"],
+ },
+ cursor: { harness: "cursor", load: (cwd) => loadAgentHookConfig("cursor", cwd), options: { logFile: "cursor-hooks.log" }, owns: [] },
+ trae: { harness: "trae", load: (cwd) => loadAgentHookConfig("trae", cwd), options: { logFile: "trae-hooks.log" }, owns: [] },
+ trae_cn: { harness: "trae-cn", load: (cwd) => loadAgentHookConfig("trae-cn", cwd), options: { logFile: "trae-cn-hooks.log" }, owns: [] },
+ zcode: { harness: "zcode", load: (cwd) => loadAgentHookConfig("zcode", cwd), options: { logFile: "zcode-hooks.log" }, owns: [] },
+};
+
+// openclaw declares its own settings in TypeScript and still resolves them
+// itself; it joins this table when it moves onto the shared loader.
+const WITHOUT_A_SHARED_LOADER = new Set(["openclaw"]);
+
+const SEND_ONLY_WHEN_CONFIGURED = KNOBS.filter((knob) => knob.sendOnlyWhenConfigured);
+
+const CONNECTION = {
+ url: "http://127.0.0.1:1933",
+ api_key: "sk-cli",
+ account: "acct",
+ user: "usr",
+ actor_peer_id: "cli-peer",
+};
+
+/**
+ * Run `fn` against a throwaway ~/.openviking pair plus two directories: a
+ * workspace root (a bare `.git` is what makes it one, and `workspace` is
+ * written to `.openviking/config.json`) and one that is neither.
+ */
+function withFixture({ ov = { server: {} }, cli = CONNECTION, workspace = null }, fn) {
+ const dir = mkdtempSync(join(tmpdir(), "ov-plugin-config-"));
+ const workspaceDir = join(dir, "workspace");
+ const otherDir = join(dir, "other");
+ const saved = Object.fromEntries(
+ Object.keys(process.env).filter((key) => key.startsWith("OPENVIKING_") || key === "OV_DEBUG_LOG")
+ .map((key) => [key, process.env[key]]),
+ );
+ try {
+ for (const key of Object.keys(saved)) delete process.env[key];
+ writeFileSync(join(dir, "ov.conf"), JSON.stringify(ov));
+ writeFileSync(join(dir, "ovcli.conf"), JSON.stringify(cli));
+ mkdirSync(join(workspaceDir, ".git"), { recursive: true });
+ mkdirSync(join(workspaceDir, ".openviking"), { recursive: true });
+ mkdirSync(otherDir, { recursive: true });
+ if (workspace) {
+ writeFileSync(join(workspaceDir, ".openviking", "config.json"), JSON.stringify(workspace));
+ }
+ process.env.OPENVIKING_CONFIG_FILE = join(dir, "ov.conf");
+ process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf");
+ // Keeps the identity cache and the workspace registry out of the real home.
+ process.env.OPENVIKING_HOME = join(dir, "home");
+ return fn({ workspaceDir, otherDir });
+ } finally {
+ for (const key of Object.keys(process.env)) {
+ if (key.startsWith("OPENVIKING_") || key === "OV_DEBUG_LOG") delete process.env[key];
+ }
+ Object.assign(process.env, saved);
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/**
+ * The files every loader is checked against. The first names every connection
+ * field plus all four knobs the request omits unless configured, so a harness
+ * that drops one shows up; the second puts a workspace file over them.
+ */
+const FIXTURES = [
+ {
+ ov: { server: { host: "127.0.0.1", port: 1933, root_api_key: "sk-root" } },
+ cli: {
+ ...CONNECTION,
+ plugin: {
+ recallLimit: 3,
+ recallMaxTokens: 900,
+ recallQueryExpansion: "off",
+ recallCompressMaxBullets: 4,
+ },
+ },
+ },
+ {
+ ov: { server: { root_api_key: "sk-root" } },
+ cli: { ...CONNECTION, plugin: { recallLimit: 5 } },
+ workspace: {
+ version: 1,
+ peer: { id: "team-a" },
+ capture: { enabled: false },
+ recall: { max_items: 8 },
+ },
+ },
+];
+
+test("the table covers every harness that has a shared loader", () => {
+ const covered = new Set(Object.keys(LOADERS));
+ for (const key of Object.values(HARNESS_KEYS)) {
+ if (WITHOUT_A_SHARED_LOADER.has(key)) continue;
+ assert.ok(covered.delete(key), `${key} has no entry in this file`);
+ }
+ assert.deepEqual([...covered], [], "an entry names a harness the schema does not");
+});
+
+for (const [key, entry] of Object.entries(LOADERS)) {
+ test(`${key} answers what buildPluginConfig answers`, () => {
+ for (const files of FIXTURES) {
+ withFixture(files, ({ workspaceDir, otherDir }) => {
+ for (const cwd of [workspaceDir, otherDir]) {
+ const built = buildPluginConfig(entry.harness, { cwd, ...entry.options });
+ const loaded = entry.load(cwd);
+
+ const differing = Object.keys(built)
+ .filter((field) => !entry.owns.includes(field))
+ .filter((field) => JSON.stringify(built[field]) !== JSON.stringify(loaded[field]))
+ .sort();
+ assert.deepEqual(differing, [], `a loader answers a shared field itself (${cwd})`);
+ }
+ });
+ }
+ });
+
+ test(`${key} tells a configured knob from a default`, () => {
+ withFixture(FIXTURES[0], ({ otherDir }) => {
+ const loaded = entry.load(otherDir);
+ for (const knob of SEND_ONLY_WHEN_CONFIGURED) {
+ assert.equal(loaded[`${knob.name}Configured`], true, `${knob.name} on ${key}`);
+ }
+ });
+
+ // Several fields reach the server only when configured, so a default that
+ // reported as configured would send this plugin's opinion as the user's.
+ withFixture({}, ({ otherDir }) => {
+ const loaded = entry.load(otherDir);
+ for (const knob of SEND_ONLY_WHEN_CONFIGURED) {
+ assert.equal(loaded[`${knob.name}Configured`], false, `${knob.name} on ${key}`);
+ assert.equal(loaded[knob.name], knob.default, `${knob.name} on ${key}`);
+ }
+ });
+ });
+
+ test(`${key} resolves a knob through every layer`, () => {
+ // Bottom up, dropping one rung at a time: a layer only wins because the one
+ // above it is absent, which asserting on the winner alone cannot tell apart.
+ const ov = { server: {}, [key]: { recallLimit: 2 } };
+ withFixture({ ov }, ({ otherDir }) => {
+ assert.equal(entry.load(otherDir).recallLimit, 2, "ov.conf's harness block outranks the default");
+ });
+ withFixture({ ov, cli: { ...CONNECTION, plugin: { recallLimit: 5 } } }, ({ otherDir }) => {
+ assert.equal(entry.load(otherDir).recallLimit, 5, "ovcli.conf's shared plugin block outranks ov.conf");
+ });
+ withFixture({
+ ov,
+ cli: { ...CONNECTION, plugin: { recallLimit: 5, [key]: { recallLimit: 6 } } },
+ workspace: { version: 1, recall: { max_items: 8 } },
+ }, ({ workspaceDir, otherDir }) => {
+ assert.equal(entry.load(otherDir).recallLimit, 6, "the per-harness block covers the shared one, which covers ov.conf");
+ assert.equal(entry.load(workspaceDir).recallLimit, 8, "the workspace file outranks ovcli.conf");
+ process.env.OPENVIKING_RECALL_LIMIT = "9";
+ assert.equal(entry.load(workspaceDir).recallLimit, 9, "the environment outranks every file");
+ });
+ });
+
+ test(`${key} reads the workspace layer of the cwd it is handed, not the process's`, () => {
+ withFixture({
+ workspace: { version: 1, capture: { enabled: false }, recall: { max_items: 8 } },
+ }, ({ workspaceDir, otherDir }) => {
+ const inside = entry.load(workspaceDir);
+ assert.equal(inside.autoCapture, false);
+ assert.equal(inside.recallLimit, 8);
+
+ // Same process, another directory: the workspace file does not follow.
+ const outside = entry.load(otherDir);
+ assert.equal(outside.autoCapture, true);
+ assert.equal(outside.recallLimit, 10);
+
+ // A hook loads its config before the payload names a directory, so an
+ // absent cwd has to mean this process's own.
+ const origin = process.cwd();
+ try {
+ process.chdir(workspaceDir);
+ assert.equal(entry.load(undefined).recallLimit, 8);
+ assert.equal(entry.load("").recallLimit, 8);
+ } finally {
+ process.chdir(origin);
+ }
+ });
+ });
+}
+
+// The version reaches the workspace layers as well as the User-Agent, which is
+// what lets a `min_client_version` be compared against anything.
+test("the assembler reports the client version it stamps on the User-Agent", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-plugin-config-version-"));
+ try {
+ const cfg = buildPluginConfig("codex", {
+ cwd: dir,
+ version: "1.2.3",
+ env: { OPENVIKING_HOME: join(dir, "home") },
+ });
+ assert.equal(cfg.clientVersion, "1.2.3");
+ assert.equal(cfg.userAgent, "openviking-memory-codex/1.2.3");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// An older install pointed OPENVIKING_CONFIG_FILE at ovcli.conf, and the
+// credential chain still honours that. The knobs have to come out of the same
+// file, or a `plugin` section supplies credentials and no behaviour.
+test("the plugin section is read from the file the credential chain accepted", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-plugin-config-compat-"));
+ const file = join(dir, "ovcli.conf");
+ try {
+ writeFileSync(file, JSON.stringify({
+ url: "http://legacy:1933",
+ api_key: "sk-legacy",
+ plugin: { recallLimit: 3, codex: { recallLimit: 4 } },
+ }));
+ const cfg = buildPluginConfig("codex", {
+ cwd: dir,
+ env: { OPENVIKING_CONFIG_FILE: file, OPENVIKING_HOME: join(dir, "home") },
+ });
+
+ assert.equal(cfg.apiKeySource, "ovcli");
+ assert.equal(cfg.cliPath, file);
+ assert.equal(cfg.recallLimit, 4);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// The chain the doctors and both reference tables describe, end to end.
+test("ovcli.conf's plugin section outranks ov.conf, under ovcli.conf's own key", () => {
+ const dir = mkdtempSync(join(tmpdir(), "ov-plugin-config-key-"));
+ const env = {
+ OPENVIKING_CONFIG_FILE: join(dir, "ov.conf"),
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "ovcli.conf"),
+ OPENVIKING_HOME: join(dir, "home"),
+ };
+ try {
+ writeFileSync(join(dir, "ov.conf"), JSON.stringify({
+ server: { root_api_key: "sk-root" },
+ codex: { apiKey: "sk-ov-section", accountId: "acct-ov", userId: "usr-ov" },
+ }));
+ const write = (cli) => writeFileSync(join(dir, "ovcli.conf"), JSON.stringify(cli));
+ const build = () => buildPluginConfig("codex", { cwd: dir, env });
+ const connection = (cfg) => ({ apiKey: cfg.apiKey, account: cfg.account, user: cfg.user });
+
+ write({
+ plugin: {
+ codex: { apiKey: "sk-plugin-codex", accountId: "acct-plugin-codex", userId: "usr-plugin-codex" },
+ apiKey: "sk-plugin",
+ accountId: "acct-plugin",
+ userId: "usr-plugin",
+ },
+ });
+ assert.deepEqual(connection(build()), {
+ apiKey: "sk-plugin-codex",
+ account: "acct-plugin-codex",
+ user: "usr-plugin-codex",
+ });
+
+ write({ plugin: { apiKey: "sk-plugin", accountId: "acct-plugin", userId: "usr-plugin" } });
+ assert.deepEqual(connection(build()), {
+ apiKey: "sk-plugin",
+ account: "acct-plugin",
+ user: "usr-plugin",
+ });
+
+ write({
+ url: "http://127.0.0.1:1933",
+ api_key: "sk-cli",
+ account: "acct-cli",
+ user: "usr-cli",
+ plugin: { apiKey: "sk-plugin", accountId: "acct-plugin", userId: "usr-plugin" },
+ });
+ assert.deepEqual(connection(build()), {
+ apiKey: "sk-cli",
+ account: "acct-cli",
+ user: "usr-cli",
+ });
+
+ write({ plugin: {} });
+ assert.deepEqual(connection(build()), {
+ apiKey: "sk-ov-section",
+ account: "acct-ov",
+ user: "usr-ov",
+ });
+ assert.equal(build().apiKeySource, "ov");
+
+ assert.deepEqual(
+ connection(buildPluginConfig("codex", {
+ cwd: dir,
+ env: {
+ ...env,
+ OPENVIKING_API_KEY: "sk-env",
+ OPENVIKING_ACCOUNT: "acct-env",
+ OPENVIKING_USER: "usr-env",
+ },
+ })),
+ { apiKey: "sk-env", account: "acct-env", user: "usr-env" },
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/memory-plugin-shared/plugin-known-keys.test.mjs b/examples/memory-plugin-shared/plugin-known-keys.test.mjs
index 108c3fb1b..eaa07c2d7 100644
--- a/examples/memory-plugin-shared/plugin-known-keys.test.mjs
+++ b/examples/memory-plugin-shared/plugin-known-keys.test.mjs
@@ -4,32 +4,112 @@ import { readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import { HARNESS_KEYS, KNOBS, KNOB_BY_KEY, WORKSPACE_KNOB_MAP, resolveKnobs } from "./lib/config-schema.mjs";
import { KNOWN_PLUGIN_KEYS, unknownPluginKeys } from "./lib/doctor-core.mjs";
+import { buildConfigForTest } from "./testing/support.mjs";
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
-/**
- * Both harness loaders read their knobs off one merged object — `cc` in Claude
- * Code, `cx` in Codex — so every `cc.<key>` / `cx.<key>` in those files is a
- * knob a user may legitimately set in ovcli.conf's `plugin` section.
- */
-async function knobsReadBy(file, receiver) {
- const source = await readFile(join(ROOT, file), "utf-8");
- return new Set([...source.matchAll(new RegExp(`\\b${receiver}\\.([a-zA-Z_][a-zA-Z0-9_]*)`, "g"))].map((m) => m[1]));
-}
-
-test("the doctor's known-knob list matches what the loaders actually read", async () => {
- const read = new Set([
- ...(await knobsReadBy("examples/claude-code-memory-plugin/scripts/config.mjs", "cc")),
- ...(await knobsReadBy("examples/codex-memory-plugin/scripts/config.mjs", "cx")),
+// Every knob reaches a loader through the object `buildPluginConfig` returns,
+// and the modules below are the ones that still read knobs off the settings
+// they were resolved from: a `settings.<key>` here is a key the schema has to
+// declare, and a key the doctor therefore has to accept inside `plugin`.
+const KNOB_READERS = [
+ "examples/memory-plugin-shared/lib/plugin-config.mjs",
+ "examples/claude-code-memory-plugin/scripts/config.mjs",
+ "examples/codex-memory-plugin/scripts/config.mjs",
+ "examples/opencode-plugin/lib/config.mjs",
+ "examples/dsh-memory-plugin/config.mjs",
+ "examples/pi-coding-agent-extension/config.ts",
+ "examples/memory-plugin-shared/lib/agent-hook-runtime.mjs",
+];
+
+test("every knob a loader reads is declared in the schema", async () => {
+ const built = buildConfigForTest("codex");
+ for (const knob of KNOBS) {
+ assert.ok(knob.name in built, `${knob.name} never reaches a loader`);
+ }
+
+ const read = new Set();
+ for (const file of KNOB_READERS) {
+ const source = await readFile(join(ROOT, file), "utf-8");
+ for (const match of source.matchAll(/\bsettings\.([a-zA-Z_][a-zA-Z0-9_]*)/g)) read.add(match[1]);
+ }
+ const undeclared = [...read].filter((key) => !KNOB_BY_KEY.has(key)).sort();
+ assert.deepEqual(undeclared, [], "a loader reads a key the schema never declares");
+});
+
+test("the doctor's known-knob list is the schema's own key list", () => {
+ const declared = new Set(KNOB_BY_KEY.keys());
+ assert.deepEqual([...KNOWN_PLUGIN_KEYS].sort(), [...declared].sort());
+});
+
+// Marking a knob `sendOnlyWhenConfigured` is a wire-protocol decision: the
+// request omits the field so the server's default stands. The set therefore has
+// to match the fields `recall-core` actually gates, in both directions.
+test("exactly the knobs recall-core gates are marked send-only-when-configured", async () => {
+ const marked = KNOBS.filter((knob) => knob.sendOnlyWhenConfigured).map((knob) => knob.name);
+ assert.deepEqual(marked.sort(), [
+ "recallCompressMaxBullets",
+ "recallLimit",
+ "recallMaxTokens",
+ "recallQueryExpansion",
]);
- assert.ok(read.size > 20, `expected to find the knobs, got ${read.size}`);
- const missing = [...read].filter((key) => !KNOWN_PLUGIN_KEYS.has(key)).sort();
- assert.deepEqual(missing, [], "a knob a loader reads but doctor would flag as a typo");
+ const source = await readFile(join(ROOT, "examples/memory-plugin-shared/lib/recall-core.mjs"), "utf-8");
+ const gated = new Set();
+ for (const match of source.matchAll(/\bcfg\.([a-zA-Z0-9_]+)Configured\b/g)) gated.add(match[1]);
+ assert.deepEqual([...gated].sort(), marked.sort());
+});
- const stale = [...KNOWN_PLUGIN_KEYS].filter((key) => !read.has(key)).sort();
- assert.deepEqual(stale, [], "a knob doctor accepts that no loader reads any more");
+test("the schema is internally consistent", () => {
+ const names = new Set();
+ const envVars = new Map();
+ for (const knob of KNOBS) {
+ assert.ok(knob.name, "every knob needs a name");
+ assert.ok(!names.has(knob.name), `duplicate knob ${knob.name}`);
+ names.add(knob.name);
+ assert.ok(knob.capability, `${knob.name} needs a capability`);
+ if (knob.type === "enum") assert.ok(Array.isArray(knob.values), `${knob.name} needs its enum members`);
+ if (knob.env) {
+ // Two knobs sharing an environment variable would make one of them
+ // unreachable, and which one depends on declaration order.
+ assert.ok(!envVars.has(knob.env), `${knob.env} is claimed by ${envVars.get(knob.env)} and ${knob.name}`);
+ envVars.set(knob.env, knob.name);
+ assert.match(knob.env, /^OPENVIKING_/, `${knob.name}'s env var needs the shared prefix`);
+ }
+ for (const alias of knob.aliases || []) {
+ assert.ok(!names.has(alias), `${alias} is both a knob and an alias`);
+ }
+ }
+
+ // The workspace file names knobs by dotted path; a path pointing at nothing
+ // would be a setting a repository could write that no loader ever reads.
+ for (const [path, name] of Object.entries(WORKSPACE_KNOB_MAP)) {
+ assert.ok(names.has(name), `${path} maps to unknown knob ${name}`);
+ }
+});
+
+// A file may carry both spellings — a plugin that renamed a knob leaves the old
+// one behind — and which one wins has to be the newer, not whichever the loop
+// happened to reach last.
+test("the canonical spelling wins over its own alias in the same layer", () => {
+ const { settings } = resolveKnobs({
+ layers: [{
+ name: "file",
+ data: {
+ autoCapture: true,
+ syncTurns: false,
+ recallCompressThinking: "high",
+ recallCompressReasoningEffort: "low",
+ bypassSessionPatterns: ["/keep"],
+ bypassPatterns: ["/stale"],
+ },
+ }],
+ });
+ assert.equal(settings.autoCapture, true);
+ assert.equal(settings.recallCompressThinking, "high");
+ assert.deepEqual(settings.bypassSessionPatterns, ["/keep"]);
});
test("a misspelled knob is caught, with the key it was probably meant to be", () => {
@@ -39,6 +119,7 @@ test("a misspelled knob is caught, with the key it was probably meant to be", ()
RecallLimit: 10,
claude_code: { autoRecal: false },
codex: { recallPeerScope: "actor" },
+ opencode: { captureMode: "keyword" },
});
assert.deepEqual(found.map((f) => f.key).sort(), [
@@ -51,6 +132,14 @@ test("a misspelled knob is caught, with the key it was probably meant to be", ()
assert.equal(found.find((f) => f.key === "plugin.claude_code.autoRecal").suggestion, "autoRecall");
});
+test("every harness gets a per-harness override, under either spelling", () => {
+ const overrides = Object.fromEntries(
+ Object.values(HARNESS_KEYS).map((key) => [key, { recallLimit: 3 }]),
+ );
+ overrides["trae-cn"] = { recallLimit: 3 };
+ assert.deepEqual(unknownPluginKeys(overrides), []);
+});
+
test("an empty or absent plugin section reports nothing", () => {
for (const value of [undefined, null, {}, [], "text", 3]) {
assert.deepEqual(unknownPluginKeys(value), [], `should be empty for ${JSON.stringify(value)}`);
diff --git a/examples/memory-plugin-shared/recall-core.test.mjs b/examples/memory-plugin-shared/recall-core.test.mjs
index 6a79221f4..e3565d5f2 100644
--- a/examples/memory-plugin-shared/recall-core.test.mjs
+++ b/examples/memory-plugin-shared/recall-core.test.mjs
@@ -7,7 +7,9 @@ import {
buildContextSearchBody,
buildRecallEndpointBody,
buildRecallBlock,
+ buildRecallBlockDetailed,
contextRequestTimeoutMs,
+ estimateTokens,
isContextFaceLegacy,
postRecall,
readPeerScopeDowngrade,
@@ -137,6 +139,15 @@ test("the deadline follows the stages the request actually asks for", async () =
assert.ok(withRewrite > withSession, "a digest must outlast a plain expanded request");
});
+test("explicit recall context timeout applies without rewrite or expansion", () => {
+ const timeout = contextRequestTimeoutMs(
+ { recallContextTimeoutMs: 25000, timeoutMs: 15000 },
+ { session_id: "s1", query_expansion: "off" },
+ );
+
+ assert.equal(timeout, 25000);
+});
+
test("buildRecallBlock prefers a cited server digest", async () => {
const legacyCachePath = await tempPath("context-face.json");
const block = await buildRecallBlock(async () => ({
@@ -408,3 +419,53 @@ test("a legacy id equal to the effective one is not asked twice", async () => {
assert.deepEqual(asked, ["same"]);
});
+
+function fallbackFetch(memories) {
+ return async (path) => {
+ if (path === "/api/v1/search/search") return { ok: false, status: 503 };
+ if (path === "/api/v1/search/recall") return { ok: false, status: 404 };
+ if (path === "/api/v1/search/find") return { ok: true, result: { memories, skills: [] } };
+ return { ok: false, status: 404 };
+ };
+}
+
+test("a server-assembled block reports itself as one budgeted unit", async () => {
+ const detailed = await buildRecallBlockDetailed(async () => ({
+ ok: true,
+ result: { rendered: "- viking://a/b.md — body", entries: [{ uri: "viking://a/b.md" }], stats: {} },
+ }), {}, "hello", { legacyCachePath: await tempPath("context-face.json") });
+
+ assert.equal(detailed.stage, "server_assembled");
+ assert.equal(detailed.contentCount, 1);
+ assert.equal(detailed.hintCount, 0);
+ assert.equal(detailed.budgetUsed, estimateTokens(detailed.block));
+});
+
+test("the ranked fallback reports what fitted the budget and what degraded", async () => {
+ const detailed = await buildRecallBlockDetailed(fallbackFetch([
+ { uri: "viking://user/default/memories/entities/a.md", score: 0.9, abstract: "x".repeat(500), level: 1 },
+ { uri: "viking://user/default/memories/entities/b.md", score: 0.9, abstract: "y".repeat(500), level: 1 },
+ ]), {
+ recallTokenBudget: 200,
+ recallMaxContentChars: 500,
+ recallPreferAbstract: true,
+ }, "what happened", { legacyCachePath: await tempPath("context-face.json") });
+
+ assert.equal(detailed.stage, "ranked");
+ assert.equal(detailed.contentCount, 1);
+ assert.equal(detailed.hintCount, 1);
+ assert.equal(detailed.budgetUsed, estimateTokens(`- [memory 90%] ${"x".repeat(500)}`));
+});
+
+test("an empty recall says whether the server had nothing or the threshold took it", async () => {
+ const legacyCachePath = await tempPath("context-face.json");
+ const nothing = await buildRecallBlockDetailed(fallbackFetch([]), {}, "hello", { legacyCachePath });
+ const belowThreshold = await buildRecallBlockDetailed(fallbackFetch([
+ { uri: "viking://user/default/memories/entities/a.md", score: 0.1, abstract: "barely related", level: 1 },
+ ]), {}, "hello", { legacyCachePath: await tempPath("context-face.json") });
+
+ assert.equal(nothing.stage, "no_results");
+ assert.equal(nothing.block, "");
+ assert.equal(belowThreshold.stage, "filtered_out");
+ assert.equal(await buildRecallBlock(fallbackFetch([]), {}, "hello", { legacyCachePath }), null);
+});
diff --git a/examples/memory-plugin-shared/recall-session-wiring.test.mjs b/examples/memory-plugin-shared/recall-session-wiring.test.mjs
index 8fd61d29a..500df0b89 100644
--- a/examples/memory-plugin-shared/recall-session-wiring.test.mjs
+++ b/examples/memory-plugin-shared/recall-session-wiring.test.mjs
@@ -14,8 +14,8 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
// wiring so a harness cannot silently fall back to stateless recall again.
const CALL_SITES = [
{
- name: "ZCode hook forwards its derived session id",
- file: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "zcode-hook.mjs"),
+ name: "the thin-harness hook forwards its derived session id",
+ file: join(ROOT, "examples", "agent-hook-plugin", "scripts", "hook.mjs"),
pattern: /recallForPrompt\([^)]*\{[^}]*\bsessionId\b/s,
},
{
@@ -28,6 +28,13 @@ const CALL_SITES = [
file: join(ROOT, "examples", "pi-coding-agent-extension", "recall.ts"),
pattern: /sessionId:\s*this\.sessionId\(\)/,
},
+ // Under `actor` scope the effective peer is the only one asked, so dropping
+ // the pre-git id here makes every memory written before it unreachable.
+ {
+ name: "pi recall forwards the pre-git peer for the actor-scope dual read",
+ file: join(ROOT, "examples", "pi-coding-agent-extension", "recall.ts"),
+ pattern: /legacyPeerId:\s*this\.config\.legacyPeerId/,
+ },
];
for (const { name, file, pattern } of CALL_SITES) {
@@ -64,11 +71,6 @@ const TIMEOUT_PASSTHROUGH = [
file: join(ROOT, "examples", "opencode-plugin", "lib", "memory-recall.mjs"),
pattern: /timeoutMs:\s*options\.timeoutMs\s*\?\?\s*\d+/,
},
- {
- name: "pi keeps the per-request deadline the helper hands down",
- file: join(ROOT, "examples", "pi-coding-agent-extension", "recall.ts"),
- pattern: /fetchJSON\(path,\s*init,\s*options\?\.timeoutMs\s*\?\?\s*\d+\)/,
- },
];
for (const { name, file, pattern } of TIMEOUT_PASSTHROUGH) {
@@ -78,23 +80,17 @@ for (const { name, file, pattern } of TIMEOUT_PASSTHROUGH) {
});
}
-const QUERY_EXPANSION_OPT_OUT = [
- {
- name: "OpenCode exposes the query-expansion opt-out",
- file: join(ROOT, "examples", "opencode-plugin", "lib", "config.mjs"),
- },
- {
- name: "pi exposes the query-expansion opt-out",
- file: join(ROOT, "examples", "pi-coding-agent-extension", "config.ts"),
- },
-];
+// The env var alone is not enough: buildContextSearchBody only emits
+// `query_expansion` when the harness also marks it as configured. Both halves
+// are declared once now — the knob in the schema, the flag in the one builder
+// every loader calls — and `plugin-config.test.mjs` checks each harness gets it.
+test("the query-expansion opt-out is declared once and reported for every harness", async () => {
+ const { KNOB_BY_NAME } = await import("./lib/config-schema.mjs");
+ const knob = KNOB_BY_NAME.get("recallQueryExpansion");
+ assert.equal(knob.env, "OPENVIKING_RECALL_QUERY_EXPANSION");
+ assert.deepEqual(knob.values, ["auto", "off"]);
+ assert.equal(knob.sendOnlyWhenConfigured, true);
-for (const { name, file } of QUERY_EXPANSION_OPT_OUT) {
- test(name, async () => {
- const source = await readFile(file, "utf-8");
- // The env var alone is not enough: buildContextSearchBody only emits
- // `query_expansion` when the harness also marks it as configured.
- assert.match(source, /OPENVIKING_RECALL_QUERY_EXPANSION/);
- assert.match(source, /recallQueryExpansionConfigured/);
- });
-}
+ const builder = join(ROOT, "examples", "memory-plugin-shared", "lib", "plugin-config.mjs");
+ assert.match(await readFile(builder, "utf-8"), /`\$\{knob\.name\}Configured`/);
+});
diff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjs
index 898cf1c07..5e4e3eef9 100644
--- a/examples/memory-plugin-shared/release-marketplace.test.mjs
+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs
@@ -1,14 +1,15 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
-import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join, resolve } from "node:path";
+import { dirname, join, resolve, sep } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const installer = join(ROOT, "examples", "memory-plugin-shared", "install.sh");
const stageScript = join(ROOT, ".github", "scripts", "stage-memory-plugin-marketplace.sh");
+const archiveCheck = join(ROOT, ".github", "scripts", "check-marketplace-archive.mjs");
function run(command, args, options = {}) {
return spawnSync(command, args, {
@@ -25,6 +26,11 @@ test("release marketplace archive supports a ZCode TOS install", () => {
const staged = run("bash", [stageScript, stage]);
assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);
+ const bundled = readdirSync(stage, { recursive: true, encoding: "utf8" }).filter((entry) =>
+ entry.split(sep).includes("node_modules"),
+ );
+ assert.deepEqual(bundled.slice(0, 3), [], "marketplace archive carries development dependencies");
+
const zipped = run("zip", ["-rq", join(tmp, "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], {
cwd: tmp,
});
@@ -52,9 +58,22 @@ test("release marketplace archive supports a ZCode TOS install", () => {
assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);
const integrationRoot = join(home, ".openviking", "agent-integrations", "zcode");
- assert.ok(existsSync(join(integrationRoot, "scripts", "zcode-hook.mjs")));
- assert.ok(existsSync(join(integrationRoot, "scripts", "zcode-capture.mjs")));
- assert.ok(existsSync(join(integrationRoot, "scripts", "shared", "async-writer.mjs")));
+ assert.ok(existsSync(join(integrationRoot, "plugin.json")));
+ assert.equal(existsSync(join(integrationRoot, ".claude-plugin")), false);
+ assert.ok(existsSync(join(integrationRoot, "scripts", "hook.mjs")));
+ assert.ok(existsSync(join(integrationRoot, "hosts", "zcode.mjs")));
+ assert.ok(existsSync(join(integrationRoot, "hosts", "zcode-capture.mjs")));
+ // An installation is for one client: the other hosts' configuration
+ // directories are not copied with it.
+ assert.equal(existsSync(join(integrationRoot, "hosts", "zcode", "hooks.json")), true);
+ assert.equal(existsSync(join(integrationRoot, "hosts", "cursor")), false);
+ // ZCode imports the runtime the installer assembles beside it, the way
+ // cursor and trae do, rather than a copy committed into its own tree.
+ const sharedRoot = join(home, ".openviking", "agent-integrations", "memory-plugin-shared", "lib");
+ assert.ok(existsSync(join(sharedRoot, "async-writer.mjs")));
+ assert.ok(existsSync(join(sharedRoot, "capture-utils.mjs")));
+ assert.ok(existsSync(join(sharedRoot, "mcp-proxy-config.mjs")));
+ assert.equal(existsSync(join(integrationRoot, "scripts", "shared")), false);
const config = JSON.parse(readFileSync(join(home, ".zcode", "cli", "config.json"), "utf8"));
assert.equal(config.hooks.enabled, true);
@@ -65,30 +84,57 @@ test("release marketplace archive supports a ZCode TOS install", () => {
"Stop",
]);
assert.ok(config.mcp.servers.openviking);
+
+ // The hook commands point across the plugin boundary at the runtime the
+ // installer assembles from the archive, so an entry the manifest forgot to
+ // carry is a hooks.json naming a script that is not there.
+ const commands = JSON.stringify(config.hooks.events)
+ .split(/"/u)
+ .filter((part) => part.includes("# openviking-memory"));
+ assert.ok(commands.length > 0, "no OpenViking hook commands were installed");
+ for (const command of commands) {
+ const script = /'([^']*\.mjs)'/u.exec(command)?.[1];
+ assert.ok(script, `${command} names no script`);
+ assert.ok(existsSync(script), `${script} is missing after install`);
+ }
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
-test("release marketplace archive retains the deprecated TRAE CLI integration for cleanup compatibility", () => {
- const tmp = mkdtempSync(join(tmpdir(), "openviking-trae-cli-release-"));
+// The archive's contents are derived from the plugins' manifests and the shared
+// sync, so nothing here restates them. What this pins is that the derivation is
+// wired up at all: an archive missing a copy only the generator produces has to
+// fail the stage, not ship.
+test("staging rejects an archive missing a generated shared copy", () => {
+ const tmp = mkdtempSync(join(tmpdir(), "openviking-marketplace-check-"));
try {
const stage = join(tmp, "memory-plugin-marketplace");
const staged = run("bash", [stageScript, stage]);
assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);
+ const stagedDirs = readdirSync(stage, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name);
- const zipped = run("zip", ["-rq", join(tmp, "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], {
- cwd: tmp,
- });
- assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);
+ const generated = [
+ join("opencode-plugin", "lib", "shared", "plugin-config.mjs"),
+ join("pi-coding-agent-extension", "shared", "plugin-config.mjs"),
+ ];
+ for (const file of generated) {
+ assert.ok(existsSync(join(stage, file)), `${file} is not in the staged tree`);
+ }
+
+ rmSync(join(stage, generated[0]));
+ const rechecked = run("node", [archiveCheck, stage, ...stagedDirs]);
+ assert.equal(rechecked.status, 1, `${rechecked.stdout}\n${rechecked.stderr}`);
+ assert.match(rechecked.stderr, /opencode-plugin\/lib\/shared\/plugin-config\.mjs/);
- const integrationRoot = join(stage, "trae-cli-memory-hooks");
- const manifest = JSON.parse(readFileSync(join(integrationRoot, "openviking.integration.json"), "utf8"));
- assert.equal(manifest.deprecated, true);
- assert.match(manifest.replacement, /codex-memory-plugin/u);
- assert.ok(existsSync(join(integrationRoot, "scripts", "trae-cli-hook.mjs")));
- assert.ok(existsSync(join(integrationRoot, "scripts", "uri-guard.mjs")));
- assert.ok(existsSync(join(integrationRoot, "servers", "mcp-proxy.mjs")));
+ const restaged = run("bash", [stageScript, stage]);
+ assert.equal(restaged.status, 0, `${restaged.stdout}\n${restaged.stderr}`);
+ rmSync(join(stage, "agent-hook-plugin", "plugin.json"));
+ const missingManifest = run("node", [archiveCheck, stage, ...stagedDirs]);
+ assert.equal(missingManifest.status, 1, `${missingManifest.stdout}\n${missingManifest.stderr}`);
+ assert.match(missingManifest.stderr, /agent-hook-plugin\/plugin\.json/);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index 98e236c27..4612bfced 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -1,112 +1,284 @@
#!/usr/bin/env node
-import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
-import { dirname, join, relative, resolve as resolvePath } from "node:path";
+import { access, mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
+import { dirname, join, relative, resolve as resolvePath, sep } from "node:path";
import { fileURLToPath } from "node:url";
export const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
export const SHARED_DIR = join(ROOT, "examples", "memory-plugin-shared", "lib");
-// What a plugin ships must equal what it imports. The groups below are
-// capabilities, and every target composes the ones it actually uses — no list
-// is named after a harness and then spread into another, because that is how a
-// module nobody imports ends up vendored into four directories.
-
-/** The files every hook-driven harness plugin imports. */
-const HOOK_SHARED_FILES = [
- "credentials.mjs",
- "capture-utils.mjs",
- "input-filters.mjs",
- "session-model.mjs",
- "pending-queue.mjs",
- "debug-log.mjs",
- "recall-compress-core.mjs",
- "recall-core.mjs",
- "retryable.mjs",
- "workspace-peer.mjs",
- "workspace-identity.mjs",
- "profile-inject.mjs",
- "uri-guard.mjs",
-];
-/** The interactive installer, for the plugins that ship a `scripts/setup.mjs`. */
-const SETUP_WIZARD_SHARED_FILES = ["setup-wizard.mjs"];
-/** The stdio MCP proxy, for the plugins that bundle one. */
-const MCP_PROXY_SHARED_FILES = ["mcp-proxy-core.mjs", "mcp-proxy-config.mjs"];
-/** Batched session sends, for the plugins that flush off the hook's hot path. */
-const BATCH_SHARED_FILES = ["batch-send.mjs"];
-/** The detached write path, for the plugins whose hooks are short-lived subprocesses. */
-const ASYNC_WRITE_SHARED_FILES = ["async-writer.mjs"];
-/** The layered workspace config, its per-machine registry, and the loader over both. */
-const WORKSPACE_CONFIG_SHARED_FILES = ["plugin-config.mjs", "workspace-config.mjs", "workspace-registry.mjs"];
-
-const DOCTOR_SHARED_FILES = [
- ...HOOK_SHARED_FILES,
- ...SETUP_WIZARD_SHARED_FILES,
- ...MCP_PROXY_SHARED_FILES,
- ...BATCH_SHARED_FILES,
- ...ASYNC_WRITE_SHARED_FILES,
- ...WORKSPACE_CONFIG_SHARED_FILES,
- "doctor-core.mjs",
-];
-// opencode is imported in-process by its host, so it has no hook subprocess to
-// detach from: it takes the batch sender without the async write path.
-const OPENCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...SETUP_WIZARD_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES];
-// dsh and zcode ship no setup entry point, so nothing there calls the wizard.
-const ZCODE_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES, ...BATCH_SHARED_FILES, ...ASYNC_WRITE_SHARED_FILES, "agent-hook-runtime.mjs", "agent-uri-guard.mjs"];
-const DSH_SHARED_FILES = [...HOOK_SHARED_FILES, ...MCP_PROXY_SHARED_FILES];
-const PI_SHARED_FILES = [...HOOK_SHARED_FILES, ...SETUP_WIZARD_SHARED_FILES, ...BATCH_SHARED_FILES];
-// Agent Plugins 1.0 has no hooks: it is the proxy and nothing else.
-const AGENT_PLUGINS_SHARED_FILES = ["credentials.mjs", "debug-log.mjs", ...MCP_PROXY_SHARED_FILES];
-// openclaw assembles recall server-side, so it takes the recall pair alone.
-const OPENCLAW_SHARED_FILES = ["recall-compress-core.mjs", "recall-core.mjs"];
+
+// What a plugin ships equals what it imports, and neither side is written down.
+// Hand-kept lists were the drift: a group named after one harness got spread
+// into another's, and modules nobody imported ended up vendored into four
+// directories while a module somebody did import went missing and became an
+// ERR_MODULE_NOT_FOUND on the first hook of a fresh install. Each target below
+// only says where its code lives, where its copies go, and whether the copies
+// have to be committed; the file set is the transitive closure of what that
+// code actually imports.
+//
+// `committed` is about how the plugin is delivered, not about taste. A host
+// that installs by pointing at a directory in this repository can only see
+// files git has, so those copies are committed and a bot regenerates them on
+// main. A plugin published as an npm package or assembled into a tarball builds
+// its copies at pack time, so committing them would only tax every review diff.
export const TARGETS = [
- { dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
- { dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
- { dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"), files: OPENCODE_SHARED_FILES },
- { dir: join(ROOT, "examples", "dsh-memory-plugin", "shared"), files: DSH_SHARED_FILES },
- { dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: PI_SHARED_FILES },
- { dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") , files: ZCODE_SHARED_FILES },
- { dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
- { dir: join(ROOT, "examples", "openclaw-plugin", "shared"), files: OPENCLAW_SHARED_FILES },
+ {
+ root: join(ROOT, "examples", "claude-code-memory-plugin"),
+ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"),
+ committed: true,
+ },
+ {
+ root: join(ROOT, "examples", "codex-memory-plugin"),
+ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"),
+ committed: true,
+ },
+ {
+ root: join(ROOT, "agent-plugins"),
+ dir: join(ROOT, "agent-plugins", "servers", "shared"),
+ committed: true,
+ },
+ {
+ root: join(ROOT, "examples", "opencode-plugin"),
+ dir: join(ROOT, "examples", "opencode-plugin", "lib", "shared"),
+ committed: false,
+ },
+ {
+ root: join(ROOT, "examples", "dsh-memory-plugin"),
+ dir: join(ROOT, "examples", "dsh-memory-plugin", "shared"),
+ committed: false,
+ },
+ {
+ root: join(ROOT, "examples", "pi-coding-agent-extension"),
+ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"),
+ committed: false,
+ },
+ {
+ root: join(ROOT, "examples", "openclaw-plugin"),
+ dir: join(ROOT, "examples", "openclaw-plugin", "shared"),
+ committed: false,
+ },
+];
+
+// cursor, trae, trae-cn and zcode vendor nothing: the installer copies the
+// canonical runtime to `$OV_HOME/agent-integrations/memory-plugin-shared/lib`
+// and they import it by the relative path that resolves both there and here.
+export const ASSEMBLED_ROOTS = [
+ join(ROOT, "examples", "agent-hook-plugin"),
];
export const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
// Skills are copied verbatim — a generated-from banner ahead of the `---`
// frontmatter would break every skill loader.
+//
+// One entry per copy, the shape TARGETS uses, so the same assertions reach both
+// kinds of generated file. `committed` is true for every skill copy: .gitignore
+// covers the vendored shared/ directories only, and each host installs a skill
+// by copying its path out of this repository, so a copy git does not hold ships
+// nothing. Being a skill under examples/skills is not what ships it — an entry
+// here is.
export const SKILLS_DIR = join(ROOT, "examples", "skills");
export const SKILL_TARGETS = [
+ // Not shipped to openclaw-plugin: its REST tool surface has its own operator
+ // skill (openviking-context-database) with different tool names. Nor to
+ // agent-plugins, whose copy is a deliberately different hook-free variant.
{
- // Not shipped to openclaw-plugin: its REST tool surface has its own
- // operator skill (openviking-context-database) with different tool names.
skill: "openviking-memory",
- dirs: [
- join(ROOT, "examples", "codex-memory-plugin", "skills"),
- join(ROOT, "examples", "claude-code-memory-plugin", "skills"),
- join(ROOT, "examples", "cursor-memory-plugin", "skills"),
- join(ROOT, "examples", "dsh-memory-plugin", "skills"),
- ],
+ dir: join(ROOT, "examples", "codex-memory-plugin", "skills"),
+ committed: true,
},
{
- // Only the two harnesses that ship the experience workflow today.
+ skill: "openviking-memory",
+ dir: join(ROOT, "examples", "claude-code-memory-plugin", "skills"),
+ committed: true,
+ },
+ {
+ skill: "openviking-memory",
+ dir: join(ROOT, "examples", "agent-hook-plugin", "hosts", "cursor", "skills"),
+ committed: true,
+ },
+ {
+ skill: "openviking-memory",
+ dir: join(ROOT, "examples", "dsh-memory-plugin", "skills"),
+ committed: true,
+ },
+ // Only the two harnesses that ship the experience workflow today.
+ {
skill: "ov-experience-memory",
- dirs: [
- join(ROOT, "examples", "codex-memory-plugin", "skills"),
- join(ROOT, "examples", "claude-code-memory-plugin", "skills"),
- ],
+ dir: join(ROOT, "examples", "codex-memory-plugin", "skills"),
+ committed: true,
+ },
+ {
+ skill: "ov-experience-memory",
+ dir: join(ROOT, "examples", "claude-code-memory-plugin", "skills"),
+ committed: true,
},
];
-async function listSharedFiles() {
- const files = await readdir(SHARED_DIR);
- return files.filter((file) => file.endsWith(".mjs")).sort();
+const SOURCE_EXTENSIONS = new Set([".mjs", ".js", ".cjs", ".ts", ".mts"]);
+const SKIPPED_DIRS = new Set(["node_modules", ".git", "dist", "coverage"]);
+
+const STATIC_IMPORT_RE = /(?:^|[\s;(=])(?:import|export)\b[^;'"]*?from\s*["']([^"']+)["']/g;
+const DYNAMIC_IMPORT_RE = /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g;
+const SIDE_EFFECT_IMPORT_RE = /(?:^|[\s;])import\s*["']([^"']+)["']/g;
+
+/** Every module specifier a source file names, in any of the three forms. */
+export function importSpecifiers(source) {
+ const found = [];
+ for (const re of [STATIC_IMPORT_RE, DYNAMIC_IMPORT_RE, SIDE_EFFECT_IMPORT_RE]) {
+ for (const match of source.matchAll(re)) found.push(match[1]);
+ }
+ return found;
}
-async function copySharedFile(file, targetDir) {
+async function sourceFilesUnder(dir, skip, out = []) {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return out;
+ }
+ for (const entry of entries) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKIPPED_DIRS.has(entry.name) || path === skip) continue;
+ await sourceFilesUnder(path, skip, out);
+ continue;
+ }
+ const dot = entry.name.lastIndexOf(".");
+ if (dot > 0 && SOURCE_EXTENSIONS.has(entry.name.slice(dot))) out.push(path);
+ }
+ return out;
+}
+
+async function exists(path) {
+ try {
+ await access(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The shared modules a target's own code imports directly.
+ *
+ * Everything under `root` except the vendored directory itself is the target's
+ * own code — including re-export shims like claude-code's `scripts/lib/`, which
+ * are the only importer of several modules.
+ */
+export async function directSharedImports({ root, dir }) {
+ const seeds = new Set();
+ const missing = [];
+ for (const file of await sourceFilesUnder(root, dir)) {
+ const source = await readFile(file, "utf-8");
+ for (const spec of importSpecifiers(source)) {
+ if (!spec.startsWith(".")) continue;
+ const resolved = resolvePath(dirname(file), spec);
+ if (!resolved.startsWith(dir + sep)) continue;
+ const name = resolved.slice(dir.length + 1);
+ seeds.add(name);
+ // A module this sync has not generated yet is not missing — it is the
+ // reason to run the sync. What is missing is a module that exists
+ // neither in lib/ nor beside the copies as a plugin-local file.
+ if (!(await exists(join(SHARED_DIR, name))) && !(await exists(resolved))) {
+ missing.push({ name, importer: relative(ROOT, file) });
+ }
+ }
+ }
+ return { seeds: [...seeds].sort(), missing };
+}
+
+/**
+ * The transitive closure of `seeds` inside lib/.
+ *
+ * A seed that lib/ does not have is a plugin-local module living in the same
+ * directory (pi's recall-ledger), not an error: it is simply not generated.
+ */
+export async function sharedClosure(seeds) {
+ const generated = new Set();
+ const pending = [...seeds];
+ while (pending.length) {
+ const name = pending.pop();
+ if (generated.has(name)) continue;
+ const source = await readFile(join(SHARED_DIR, name), "utf-8").catch(() => null);
+ if (source === null) continue;
+ generated.add(name);
+ for (const spec of importSpecifiers(source)) {
+ if (spec.startsWith("./")) pending.push(spec.slice(2));
+ }
+ }
+ return [...generated].sort();
+}
+
+// The installer reads this file instead of computing the closure itself: it
+// runs against a marketplace archive, a flat layout where this generator finds
+// no plugin sources and would silently resolve an empty list.
+export const MANIFEST_PATH = join(SHARED_DIR, "MANIFEST");
+
+/** The closure the installer has to assemble for the harnesses that vendor nothing. */
+export async function assembledClosure() {
+ const seeds = new Set();
+ for (const root of ASSEMBLED_ROOTS) {
+ const { seeds: found, missing } = await directSharedImports({ root, dir: SHARED_DIR });
+ if (missing.length) {
+ const detail = missing.map((m) => `${m.name} (imported by ${m.importer})`).join(", ");
+ throw new Error(`the assembled runtime is missing: ${detail}`);
+ }
+ for (const seed of found) seeds.add(seed);
+ }
+ return sharedClosure([...seeds]);
+}
+
+/** Every target with the file set its own imports resolve to. */
+export async function resolveTargets() {
+ const resolved = [];
+ for (const target of TARGETS) {
+ const { seeds, missing } = await directSharedImports(target);
+ if (missing.length) {
+ const detail = missing.map((m) => `${m.name} (imported by ${m.importer})`).join(", ");
+ throw new Error(`${relative(ROOT, target.dir)}: imports a module that exists nowhere: ${detail}`);
+ }
+ const own = await sourceFilesUnder(target.root, target.dir);
+ resolved.push({
+ ...target,
+ files: await sharedClosure(seeds),
+ typed: own.some((file) => file.endsWith(".ts") || file.endsWith(".mts")),
+ });
+ }
+ return resolved;
+}
+
+/**
+ * Copy one module, plus its type declaration for a target written in
+ * TypeScript.
+ *
+ * The `.d.mts` files used to live in the vendored directories, hand-written and
+ * hand-kept in step with modules they sat beside — two harnesses had two
+ * different, both incomplete, declarations of the same module. They are part of
+ * the module now. A JavaScript target has no use for them, so `typed` says
+ * whether this one imports from TypeScript.
+ */
+async function copySharedFile(file, targetDir, typed) {
await mkdir(targetDir, { recursive: true });
- const source = join(SHARED_DIR, file);
- const target = join(targetDir, file);
- const body = await readFile(source, "utf-8");
- await writeFile(target, `${GENERATED_HEADER}${body}`, "utf-8");
+ const names = typed ? [file, `${file.slice(0, -4)}.d.mts`] : [file];
+ for (const name of names) {
+ const body = await readFile(join(SHARED_DIR, name), "utf-8").catch(() => null);
+ if (body === null) continue;
+ // Written through a rename so a reader never sees half a module: the
+ // marketplace staging script runs this generator, and it can run while a
+ // test is byte-comparing the copies.
+ const target = join(targetDir, name);
+ const staging = `${target}.${process.pid}.tmp`;
+ await writeFile(staging, `${GENERATED_HEADER}${body}`, "utf-8");
+ await rename(staging, target);
+ }
+}
+
+async function writeManifest(files) {
+ const staging = `${MANIFEST_PATH}.${process.pid}.tmp`;
+ await writeFile(staging, files.map((file) => `${file}\n`).join(""), "utf-8");
+ await rename(staging, MANIFEST_PATH);
}
async function copySkill(skill, targetDir) {
@@ -114,28 +286,56 @@ async function copySkill(skill, targetDir) {
for (const file of (await readdir(sourceDir)).sort()) {
const target = join(targetDir, skill);
await mkdir(target, { recursive: true });
- await writeFile(join(target, file), await readFile(join(sourceDir, file), "utf-8"), "utf-8");
+ // Through a rename, for the reason the module copies are: a test can be
+ // byte-comparing this file while the staging script runs the generator.
+ const path = join(target, file);
+ const staging = `${path}.${process.pid}.tmp`;
+ await writeFile(staging, await readFile(join(sourceDir, file), "utf-8"), "utf-8");
+ await rename(staging, path);
+ }
+}
+
+/** Vendored copies the target no longer imports; the sync would never touch them again. */
+async function staleCopies(target, keep) {
+ const stale = [];
+ for (const name of (await readdir(target.dir).catch(() => [])).sort()) {
+ const module = name.endsWith(".d.mts") ? `${name.slice(0, -6)}.mjs` : name;
+ if (!module.endsWith(".mjs") || keep.includes(module)) continue;
+ const body = await readFile(join(target.dir, name), "utf-8");
+ if (body.startsWith(GENERATED_HEADER)) stale.push(name);
}
+ return stale;
}
async function main() {
- const allFiles = await listSharedFiles();
- for (const target of TARGETS) {
- const files = target.files ?? allFiles;
- for (const file of files) {
- if (!allFiles.includes(file)) {
- throw new Error(`shared file not found: ${file}`);
- }
- await copySharedFile(file, target.dir);
+ const claimed = new Set();
+ for (const target of await resolveTargets()) {
+ for (const file of target.files) {
+ await copySharedFile(file, target.dir, target.typed);
+ claimed.add(file);
process.stdout.write(`synced ${file} -> ${relative(ROOT, target.dir)}\n`);
}
- }
- for (const { skill, dirs } of SKILL_TARGETS) {
- for (const dir of dirs) {
- await copySkill(skill, dir);
- process.stdout.write(`synced ${skill}/ -> ${relative(ROOT, dir)}\n`);
+ for (const file of await staleCopies(target, target.files)) {
+ process.stdout.write(`stale ${file} in ${relative(ROOT, target.dir)} — nothing imports it; delete it\n`);
}
}
+
+ const assembled = await assembledClosure();
+ await writeManifest(assembled);
+ process.stdout.write(`wrote ${relative(ROOT, MANIFEST_PATH)}\n`);
+ for (const file of assembled) claimed.add(file);
+
+ const unclaimed = (await readdir(SHARED_DIR))
+ .filter((file) => file.endsWith(".mjs") && !claimed.has(file))
+ .sort();
+ for (const file of unclaimed) {
+ process.stdout.write(`unused lib/${file} — no target imports it\n`);
+ }
+
+ for (const { skill, dir } of SKILL_TARGETS) {
+ await copySkill(skill, dir);
+ process.stdout.write(`synced ${skill}/ -> ${relative(ROOT, dir)}\n`);
+ }
}
// Guard the sync behind the entrypoint check so sync.test.mjs can import the
diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjs
index aa3899ab1..82e3a6810 100644
--- a/examples/memory-plugin-shared/sync.test.mjs
+++ b/examples/memory-plugin-shared/sync.test.mjs
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
import { readFile, readdir } from "node:fs/promises";
import { join, relative } from "node:path";
import test from "node:test";
@@ -6,16 +7,15 @@ import test from "node:test";
// Imported, not re-declared: the copies kept here had drifted from sync.mjs
// (dsh, opencode and agent-plugins were all missing modules the sync actually
// ships), so a stale vendored file went unnoticed by this very test.
-import { GENERATED_HEADER, ROOT, SHARED_DIR, SKILLS_DIR, SKILL_TARGETS, TARGETS } from "./sync.mjs";
+import { GENERATED_HEADER, ROOT, SHARED_DIR, SKILLS_DIR, SKILL_TARGETS, assembledClosure, resolveTargets } from "./sync.mjs";
test("vendored shared modules are synchronized", async () => {
const files = (await readdir(SHARED_DIR)).filter((file) => file.endsWith(".mjs")).sort();
assert.ok(files.length > 0, "expected shared modules");
- for (const target of TARGETS) {
- const targetFiles = target.files ?? files;
- for (const file of targetFiles) {
- assert.ok(files.includes(file), `${file} is listed for ${relative(ROOT, target.dir)} but missing from lib/`);
+ for (const target of await resolveTargets()) {
+ for (const file of target.files) {
+ assert.ok(files.includes(file), `${file} is in ${relative(ROOT, target.dir)}'s closure but missing from lib/`);
const expected = `${GENERATED_HEADER}${await readFile(join(SHARED_DIR, file), "utf-8")}`;
const actual = await readFile(join(target.dir, file), "utf-8");
assert.equal(
@@ -27,55 +27,103 @@ test("vendored shared modules are synchronized", async () => {
}
});
-// A module that lib/ ships but no target lists is dead weight nobody consumes;
-// one that a target dir holds but no list names is an orphan the sync will
-// never refresh again. Both drift silently without this.
-test("every shared module is claimed by a target, and no target holds an orphan", async () => {
+// The two directions the hand-kept lists used to get wrong: a module a plugin
+// imports but does not ship is ERR_MODULE_NOT_FOUND on the first hook of a
+// fresh install, and one it ships but never imports is dead weight that still
+// lands in every review diff. Both sides are derived from the imports now, so
+// this asserts what is on disk agrees with them.
+test("what each plugin ships equals the closure of what it imports", async () => {
+ for (const target of await resolveTargets()) {
+ const onDisk = [];
+ for (const name of (await readdir(target.dir)).filter((file) => file.endsWith(".mjs")).sort()) {
+ // A target dir may also hold plugin-local modules; only a file carrying
+ // the banner is a generated copy this sync owns.
+ const body = await readFile(join(target.dir, name), "utf-8");
+ if (body.startsWith(GENERATED_HEADER)) onDisk.push(name);
+ }
+ assert.deepEqual(
+ onDisk,
+ target.files,
+ `${relative(ROOT, target.dir)} does not hold the closure of its imports; run node examples/memory-plugin-shared/sync.mjs`,
+ );
+ }
+});
+
+// Which copies git holds is a delivery decision, and getting it backwards fails
+// in a way nobody sees until an install breaks: a committed plugin whose copies
+// were ignored ships nothing, and a packaged plugin whose copies were committed
+// taxes every review diff with 12,000 generated lines.
+test("git holds the copies the directory-installed plugins need, and no others", async () => {
+ const targets = [
+ ...(await resolveTargets()),
+ // A skill copy is delivered by path, never regenerated by the host, so
+ // every one of them is committed; the flag is here to be asserted on.
+ ...SKILL_TARGETS.map((target) => ({ ...target, dir: join(target.dir, target.skill) })),
+ ];
+ for (const target of targets) {
+ const dir = relative(ROOT, target.dir);
+ const tracked = execFileSync("git", ["ls-files", "--", dir], { cwd: ROOT, encoding: "utf-8" })
+ .split("\n")
+ .filter(Boolean);
+ if (target.committed) {
+ assert.ok(tracked.length > 0, `${dir} is installed from this repository, so its copies must be committed`);
+ } else {
+ assert.deepEqual(tracked, [], `${dir} is generated at pack time; it must not be committed`);
+ }
+ }
+});
+
+// The portable bundle is the one target whose copies are both committed and
+// carried by hosts that install it as a plain directory, so every module it
+// reaches is committed code a reviewer reads. It has no hooks and no knobs; the
+// connection half of the shared loader (`buildProxyConnection`) is what keeps
+// it at five modules instead of the whole schema-and-workspace closure.
+test("the portable agent-plugins bundle stays connection-only", async () => {
+ const target = (await resolveTargets())
+ .find((entry) => relative(ROOT, entry.dir) === join("agent-plugins", "servers", "shared"));
+ assert.ok(target, "the agent-plugins bundle must stay a sync target");
+ assert.deepEqual(target.files, [
+ "credentials.mjs",
+ "debug-log.mjs",
+ "mcp-proxy-config.mjs",
+ "mcp-proxy-core.mjs",
+ "ov-http.mjs",
+ ]);
+});
+
+// A module lib/ carries that no plugin reaches is a capability with no consumer:
+// either a harness lost its wiring, or the module should go.
+test("every shared module is reachable from some plugin", async () => {
+ const targets = await resolveTargets();
+ const claimed = new Set(targets.flatMap((target) => target.files));
+ // cursor, trae and zcode vendor nothing: the installer assembles their
+ // runtime instead, so they claim through the manifest it reads.
+ for (const entry of await assembledClosure()) claimed.add(entry);
const files = (await readdir(SHARED_DIR)).filter((file) => file.endsWith(".mjs")).sort();
- const claimed = new Set(TARGETS.flatMap((target) => target.files ?? files));
assert.deepEqual(
files.filter((file) => !claimed.has(file)),
[],
- "shared modules that no sync target ships",
+ "shared modules that no plugin imports",
);
-
- for (const target of TARGETS) {
- const expected = new Set(target.files ?? files);
- const orphans = [];
- for (const file of (await readdir(target.dir)).filter((name) => name.endsWith(".mjs")).sort()) {
- if (expected.has(file)) continue;
- // A target dir may also hold plugin-local modules; only a file still
- // carrying the banner is a copy the sync has stopped refreshing.
- const body = await readFile(join(target.dir, file), "utf-8");
- if (body.startsWith(GENERATED_HEADER)) orphans.push(file);
- }
- assert.deepEqual(
- orphans,
- [],
- `${relative(ROOT, target.dir)} holds vendored modules that sync.mjs no longer ships; delete them`,
- );
- }
});
test("vendored skills are byte-identical to examples/skills", async () => {
- for (const { skill, dirs } of SKILL_TARGETS) {
+ for (const { skill, dir } of SKILL_TARGETS) {
const files = (await readdir(join(SKILLS_DIR, skill))).sort();
assert.ok(files.includes("SKILL.md"), `${skill} must ship a SKILL.md`);
- for (const dir of dirs) {
- const target = join(dir, skill);
- assert.deepEqual(
- (await readdir(target)).sort(),
- files,
- `${relative(ROOT, target)} has a different file set; run node examples/memory-plugin-shared/sync.mjs`,
+ const target = join(dir, skill);
+ assert.deepEqual(
+ (await readdir(target)).sort(),
+ files,
+ `${relative(ROOT, target)} has a different file set; run node examples/memory-plugin-shared/sync.mjs`,
+ );
+ for (const file of files) {
+ assert.equal(
+ await readFile(join(target, file), "utf-8"),
+ await readFile(join(SKILLS_DIR, skill, file), "utf-8"),
+ `${relative(ROOT, join(target, file))} is out of sync; run node examples/memory-plugin-shared/sync.mjs`,
);
- for (const file of files) {
- assert.equal(
- await readFile(join(target, file), "utf-8"),
- await readFile(join(SKILLS_DIR, skill, file), "utf-8"),
- `${relative(ROOT, join(target, file))} is out of sync; run node examples/memory-plugin-shared/sync.mjs`,
- );
- }
}
}
});
diff --git a/examples/memory-plugin-shared/testing/support.mjs b/examples/memory-plugin-shared/testing/support.mjs
new file mode 100644
index 000000000..200ecf96e
--- /dev/null
+++ b/examples/memory-plugin-shared/testing/support.mjs
@@ -0,0 +1,158 @@
+/**
+ * Helpers shared by the plugin test files.
+ *
+ * They live outside `lib/` on purpose: `sync.mjs` copies that directory into
+ * every plugin, and nothing here belongs in a shipped plugin. Importing a
+ * helper from a `*.test.mjs` file would also register that file's own tests a
+ * second time in whichever runner picked it up.
+ */
+
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, rm } from "node:fs/promises";
+import http from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildPluginConfig } from "../lib/plugin-config.mjs";
+
+/**
+ * A built config resolved against nothing at all, for callers that only need
+ * the shape of the object a loader receives.
+ */
+export function buildConfigForTest(harness) {
+ const dir = join(tmpdir(), "ov-plugin-config-absent");
+ return buildPluginConfig(harness, {
+ cwd: dir,
+ env: {
+ OPENVIKING_CLI_CONFIG_FILE: join(dir, "ovcli.conf"),
+ OPENVIKING_CONFIG_FILE: join(dir, "ov.conf"),
+ OPENVIKING_HOME: dir,
+ },
+ });
+}
+
+const PENDING_ENV_KEYS = [
+ "OPENVIKING_PENDING_DIR",
+ "OPENVIKING_PENDING_MAX_RETRIES",
+ "OPENVIKING_PENDING_REPLAY_LIMIT",
+ "OPENVIKING_PENDING_TTL_DAYS",
+];
+
+/**
+ * Run `fn` against an empty pending queue in a throwaway directory.
+ *
+ * The queue reads its directory and its limits from the environment, so the
+ * knobs are cleared for the duration and every one of them is restored after,
+ * whether or not the test set it.
+ */
+export async function withPendingDir(fn) {
+ const saved = PENDING_ENV_KEYS.map((key) => [key, process.env[key]]);
+ const dir = await mkdtemp(join(tmpdir(), "openviking-pending-test-"));
+ for (const key of PENDING_ENV_KEYS) delete process.env[key];
+ process.env.OPENVIKING_PENDING_DIR = dir;
+ try {
+ return await fn(dir);
+ } finally {
+ for (const [key, value] of saved) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+/** The JSON body of a request, or `null` when the request carried no body. */
+export function readRequestBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => {
+ const raw = Buffer.concat(chunks).toString("utf-8");
+ try {
+ resolve(raw ? JSON.parse(raw) : null);
+ } catch (error) {
+ reject(error);
+ }
+ });
+ req.on("error", reject);
+ });
+}
+
+/** Answer with a JSON body, 200 unless the caller names another status. */
+export function writeJson(res, value, statusCode = 200) {
+ res.writeHead(statusCode, { "Content-Type": "application/json" });
+ res.end(JSON.stringify(value));
+}
+
+/**
+ * Run `fn` against a mock OpenViking listening on loopback.
+ *
+ * `handler` may be sync or async; whatever it throws becomes a 500 rather than
+ * an unhandled rejection that outlives the test. `fn` receives the base URL and
+ * a live log of every request the mock saw, so a test that only cares about
+ * which endpoints were hit does not have to record them inside its handler.
+ */
+export async function withMockOpenViking(handler, fn) {
+ const requests = [];
+ const server = http.createServer((req, res) => {
+ requests.push({
+ method: req.method,
+ path: new URL(req.url, "http://127.0.0.1").pathname,
+ url: req.url,
+ headers: req.headers,
+ });
+ Promise.resolve(handler(req, res)).catch((error) => {
+ writeJson(res, { status: "error", error: String(error?.stack || error) }, 500);
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ try {
+ const { port } = server.address();
+ return await fn(`http://127.0.0.1:${port}`, requests);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+}
+
+/**
+ * Run a hook script as its host runs it, and never reject.
+ *
+ * A hook that exits non-zero is a result a test may well be asserting on, so
+ * the exit code comes back like any other output; call `expectExit` where a
+ * clean exit is part of the expectation.
+ */
+export function runHookScript(scriptPath, { argv = [], input, env, cwd } = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, [scriptPath, ...argv], {
+ cwd,
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ let spawnError = null;
+ let settled = false;
+ const settle = (code, signal) => {
+ if (settled) return;
+ settled = true;
+ resolve({ code, signal, stdout, stderr, error: spawnError });
+ };
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("error", (error) => { spawnError = error; settle(null, null); });
+ child.on("close", settle);
+ // A hook that answers without draining stdin makes this write fail EPIPE.
+ child.stdin.on("error", () => {});
+ child.stdin.end(
+ input === undefined || typeof input === "string" ? (input ?? "") : JSON.stringify(input),
+ );
+ });
+}
+
+/** Assert a `runHookScript` result exited with `code`, and return the result. */
+export function expectExit(result, code = 0) {
+ const detail = result.stderr.trim() || String(result.error || "");
+ assert.equal(result.code, code, detail || `expected exit ${code}, got ${result.code}`);
+ return result;
+}
diff --git a/examples/memory-plugin-shared/uri-guard.test.mjs b/examples/memory-plugin-shared/uri-guard.test.mjs
index 238dcec6a..449ae3c5c 100644
--- a/examples/memory-plugin-shared/uri-guard.test.mjs
+++ b/examples/memory-plugin-shared/uri-guard.test.mjs
@@ -1,6 +1,14 @@
import test from "node:test"
import assert from "node:assert/strict"
-import { buildGuardMessage, findVikingUri, findVikingUriInValue, normalizeToolName } from "./lib/uri-guard.mjs"
+import {
+ buildGuardMessage,
+ denyCursorPermission,
+ denyHookSpecificOutput,
+ evaluateUriGuard,
+ findVikingUri,
+ findVikingUriInValue,
+ normalizeToolName,
+} from "./lib/uri-guard.mjs"
test("findVikingUri detects common path and URI argument keys", () => {
assert.equal(findVikingUri({ filePath: "viking://resources/a.md" }), "viking://resources/a.md")
@@ -31,6 +39,53 @@ test("buildGuardMessage names replacement tool and example", () => {
assert.match(message, /Example:/)
})
+test("evaluateUriGuard denies a guarded tool and passes everything else", () => {
+ const denied = evaluateUriGuard("Read", { file_path: "viking://resources/a.md" })
+ assert.equal(denied?.uri, "viking://resources/a.md")
+ assert.match(denied?.reason ?? "", /Use OpenViking MCP read instead/)
+ assert.match(denied?.reason ?? "", /Example: read\(uris="viking:\/\/resources\/a\.md"\)/)
+
+ assert.equal(evaluateUriGuard("Read", { file_path: "/tmp/a.md" }), null)
+ assert.equal(evaluateUriGuard("Task", { file_path: "viking://resources/a.md" }), null)
+})
+
+// The guarded set is per host: claude-code and opencode never see the shell in
+// their matchers, pi does. Each of them pins its own half in its own tests.
+test("evaluateUriGuard only guards the tools the host names", () => {
+ const call = ["bash", { command: "cat viking://resources/a.md" }]
+ assert.equal(evaluateUriGuard(...call, { guarded: new Set(["read", "glob", "grep"]) }), null)
+ assert.equal(
+ evaluateUriGuard(...call, { guarded: new Set(["read", "bash"]) })?.uri,
+ "viking://resources/a.md",
+ )
+})
+
+test("evaluateUriGuard takes the host's own replacement tools and examples", () => {
+ const hints = {
+ read: { tool: "viking_read", example: (uri) => `viking_read(uri="${uri}", level="overview")` },
+ }
+ const decision = evaluateUriGuard("read", { path: "viking://resources/a.md" }, { hints })
+ assert.match(decision?.reason ?? "", /Use viking_read instead/)
+ assert.match(decision?.reason ?? "", /level="overview"/)
+ assert.equal(evaluateUriGuard("glob", { pattern: "viking://resources/**" }, { hints }), null)
+})
+
+test("deny envelopes carry only the keys their host recognizes", () => {
+ assert.deepEqual(denyHookSpecificOutput("because"), {
+ hookSpecificOutput: {
+ hookEventName: "PreToolUse",
+ permissionDecision: "deny",
+ permissionDecisionReason: "because",
+ },
+ })
+ assert.deepEqual(denyCursorPermission("because"), { permission: "deny", user_message: "because" })
+ assert.deepEqual(denyCursorPermission("because", { agentMessage: true }), {
+ permission: "deny",
+ user_message: "because",
+ agent_message: "because",
+ })
+})
+
test("normalizeToolName trims and lowercases", () => {
assert.equal(normalizeToolName(" Read "), "read")
})
diff --git a/examples/memory-plugin-shared/wire-headers.test.mjs b/examples/memory-plugin-shared/wire-headers.test.mjs
new file mode 100644
index 000000000..f5c06892f
--- /dev/null
+++ b/examples/memory-plugin-shared/wire-headers.test.mjs
@@ -0,0 +1,145 @@
+import assert from "node:assert/strict";
+import { afterEach, test } from "node:test";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildPluginConfig } from "./lib/plugin-config.mjs";
+import { buildProxyConnection } from "./lib/credentials.mjs";
+import { createOvHttp } from "./lib/ov-http.mjs";
+import { withMockOpenViking, writeJson } from "./testing/support.mjs";
+
+import { makeAgentFetchJSON } from "./lib/agent-hook-runtime.mjs";
+import { makeFetchJSON as ccMakeFetchJSON } from "../claude-code-memory-plugin/scripts/lib/ov-session.mjs";
+import { makeFetchJSON as codexMakeFetchJSON } from "../codex-memory-plugin/scripts/ov-session.mjs";
+import { OpenVikingClient } from "../dsh-memory-plugin/client.mjs";
+import { fetchJSON as opencodeFetchJSON } from "../opencode-plugin/lib/utils.mjs";
+import { OVClient } from "../pi-coding-agent-extension/client.ts";
+
+/**
+ * Every harness talks to the same server, so every harness has to put the same
+ * thing on the wire. They did not: Codex sent the api key twice (`Authorization`
+ * and `X-API-Key`), Claude Code read `accountId` where the rest read `account`,
+ * and only Codex asked whether the server was in trusted mode before naming the
+ * operator to every proxy on the path.
+ *
+ * These assertions pin the one shape. They are also what makes the later merge
+ * into a single HTTP module provable as a no-op on the wire: if the merged
+ * builder drifts, six harnesses fail here at once.
+ */
+
+const BASE_URL = "http://127.0.0.1:1933";
+
+const CFG = {
+ apiKey: "secret",
+ account: "acct-a",
+ user: "user-a",
+ peerId: "peer-a",
+ userAgent: "openviking-memory-test/9.9.9",
+ timeoutMs: 2000,
+ captureTimeoutMs: 2000,
+ requestTimeoutMs: 2000,
+ baseUrl: BASE_URL,
+ endpoint: BASE_URL,
+};
+
+const TRUSTED = {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer secret",
+ "X-OpenViking-Account": "acct-a",
+ "X-OpenViking-User": "user-a",
+ "X-OpenViking-Actor-Peer": "peer-a",
+ "User-Agent": "openviking-memory-test/9.9.9",
+};
+
+const API_KEY_ONLY = {
+ "Content-Type": "application/json",
+ "Authorization": "Bearer secret",
+ "X-OpenViking-Actor-Peer": "peer-a",
+ "User-Agent": "openviking-memory-test/9.9.9",
+};
+
+const STACKS = [
+ {
+ name: "claude-code session helper",
+ send: (cfg) => ccMakeFetchJSON(cfg)("/health", {}, { actorPeerId: cfg.peerId }),
+ },
+ {
+ name: "codex session helper",
+ send: (cfg) => codexMakeFetchJSON(cfg, { getActorPeerId: () => cfg.peerId }).fetchJSONRes("/health"),
+ },
+ {
+ name: "thin agent hook runtime",
+ send: (cfg) => makeAgentFetchJSON(cfg, process.cwd()).fetchJSON("/health"),
+ },
+ {
+ name: "opencode client",
+ send: (cfg) => opencodeFetchJSON(cfg, "/health", {}, { actorPeerId: cfg.peerId }),
+ },
+ {
+ name: "dsh client",
+ send: (cfg) => new OpenVikingClient(cfg).fetchJSON("/health"),
+ },
+ {
+ name: "pi client",
+ send: (cfg) => new OVClient(cfg).fetchJSON("/health"),
+ },
+];
+
+const originalFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+async function captureHeaders(stack, cfg) {
+ let seen = null;
+ globalThis.fetch = async (_url, init) => {
+ seen = init.headers;
+ return new Response(JSON.stringify({ status: "ok", result: {} }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ await stack.send(cfg);
+ assert.ok(seen, `${stack.name} made no request`);
+ return { ...seen };
+}
+
+for (const stack of STACKS) {
+ test(`${stack.name} sends the same headers as every other stack`, async () => {
+ assert.deepEqual(
+ await captureHeaders(stack, { ...CFG, authMode: "trusted", sendIdentityHeaders: true }),
+ TRUSTED,
+ );
+ assert.deepEqual(
+ await captureHeaders(stack, { ...CFG, authMode: "api_key", sendIdentityHeaders: false }),
+ API_KEY_ONLY,
+ );
+ });
+}
+
+test("auth mode environment overrides file modes on the wire", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ov-auth-mode-wire-"));
+ try {
+ const cli = join(dir, "ovcli.conf");
+ const ov = join(dir, "ov.conf");
+ await withMockOpenViking((_req, res) => writeJson(res, { status: "ok", result: {} }), async (baseUrl, requests) => {
+ for (const [mode, fileMode] of [["api_key", "trusted"], ["trusted", "api_key"]]) {
+ await writeFile(cli, JSON.stringify({ url: baseUrl, api_key: "test-key", account: "acct", user: "usr", plugin: { authMode: fileMode } }));
+ await writeFile(ov, JSON.stringify({ server: { auth_mode: fileMode }, codex: { authMode: fileMode } }));
+ const env = {
+ OPENVIKING_HOME: dir, OPENVIKING_CLI_CONFIG_FILE: cli, OPENVIKING_CONFIG_FILE: ov, OPENVIKING_AUTH_MODE: mode,
+ };
+ for (const cfg of [buildPluginConfig("codex", { cwd: dir, env }), buildProxyConnection("agent-plugins", { env })]) {
+ await createOvHttp(cfg)("/health");
+ const headers = requests.at(-1).headers;
+ assert.equal(headers.authorization, "Bearer test-key");
+ assert.equal(headers["x-openviking-account"], mode === "trusted" ? "acct" : undefined);
+ assert.equal(headers["x-openviking-user"], mode === "trusted" ? "usr" : undefined);
+ }
+ }
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/examples/memory-plugin-shared/workspace-peer.test.mjs b/examples/memory-plugin-shared/workspace-peer.test.mjs
index 11999a72a..2ff275c3a 100644
--- a/examples/memory-plugin-shared/workspace-peer.test.mjs
+++ b/examples/memory-plugin-shared/workspace-peer.test.mjs
@@ -11,6 +11,7 @@ import {
peerSourceTemplates,
renderPeerTemplate,
resolveEffectivePeerId,
+ resolvePluginPeerId,
} from "./lib/workspace-peer.mjs";
import { resolveWorkspaceIdentity } from "./lib/workspace-identity.mjs";
@@ -220,3 +221,105 @@ test("a fork keeps its own peer, and every clone of one repo shares one", async
assert.equal(resolve(upstream.root, upstream.env).peerId, resolve(secondClone.root, secondClone.env).peerId);
assert.notEqual(resolve(fork.root, fork.env).peerId, resolve(upstream.root, upstream.env).peerId);
});
+
+/**
+ * Every layer that can name a peer, most specific first. Each entry writes its
+ * own field into the same input, bottom-up — ov.conf's harness block and
+ * ovcli.conf's `plugin` section both arrive as `settings.peerId`, so the higher
+ * one overwrites the lower exactly as `resolveSettings()` does. An input built
+ * from entry `i` downwards must resolve to entry `i`'s peer: the walk pins the
+ * whole order at once.
+ */
+const PEER_ORDER = [
+ {
+ name: "the host's own input",
+ apply: (input) => { input.hostInput = "host-peer"; },
+ peerId: "host-peer",
+ },
+ {
+ name: "OPENVIKING_PEER_ID",
+ apply: (input) => { input.env = { OPENVIKING_PEER_ID: "env-peer" }; },
+ peerId: "env-peer",
+ },
+ {
+ name: "the workspace file, the registry and ovcli.conf's plugin section",
+ apply: (input) => {
+ input.settings = { peerId: "plugin-peer" };
+ input.configured = new Set(["peerId"]);
+ input.sources = { peerId: "ovcli.conf" };
+ },
+ peerId: "plugin-peer",
+ },
+ {
+ name: "the credential chain",
+ apply: (input) => { input.credentials = { peerId: "cli-peer", credentialSource: "auto" }; },
+ peerId: "cli-peer",
+ },
+ {
+ name: "ov.conf's harness block",
+ apply: (input) => {
+ input.settings = { peerId: "ov-peer" };
+ input.configured = new Set(["peerId"]);
+ input.sources = { peerId: "ov.conf" };
+ },
+ peerId: "ov-peer",
+ },
+];
+
+test("resolvePluginPeerId walks one order, whichever harness is asking", () => {
+ for (let i = 0; i < PEER_ORDER.length; i += 1) {
+ // Only the entry that tests the environment gets one, so the walk cannot
+ // pick up an OPENVIKING_PEER_ID the machine running it happens to export.
+ const input = { env: {} };
+ for (const layer of PEER_ORDER.slice(i).reverse()) layer.apply(input);
+ assert.equal(resolvePluginPeerId(input), PEER_ORDER[i].peerId, `${PEER_ORDER[i].name} must win`);
+ }
+ assert.equal(
+ resolvePluginPeerId({ env: {} }),
+ "",
+ "nothing named a peer, so one is derived instead",
+ );
+});
+
+test("ov.conf's harness block survives credentials pinned to ovcli.conf", () => {
+ // Pinning drops ov.conf out of the credential chain entirely, so this layer
+ // has to have a rank of its own or it disappears the moment ovcli.conf
+ // carries a url — which is every install that has run `ov login`.
+ assert.equal(
+ resolvePluginPeerId({
+ settings: { peerId: "ov-peer" },
+ configured: new Set(["peerId"]),
+ sources: { peerId: "ov.conf" },
+ credentials: { peerId: "", credentialSource: "ovcli" },
+ env: {},
+ }),
+ "ov-peer",
+ );
+});
+
+test("credentials pinned to ovcli.conf ignore the env peer but not a configured one", () => {
+ const env = { OPENVIKING_PEER_ID: "env-peer" };
+ const credentials = { peerId: "cli-peer", credentialSource: "ovcli" };
+ assert.equal(
+ resolvePluginPeerId({
+ // The env layer already won inside `settings`; suppressing the variable
+ // has to suppress it there too, or it comes back under another name.
+ settings: { peerId: "env-peer" },
+ configured: new Set(["peerId"]),
+ sources: { peerId: "env" },
+ credentials,
+ env,
+ }),
+ "cli-peer",
+ );
+ assert.equal(
+ resolvePluginPeerId({
+ settings: { peerId: "plugin-peer" },
+ configured: new Set(["peerId"]),
+ sources: { peerId: "ovcli.conf" },
+ credentials,
+ env,
+ }),
+ "plugin-peer",
+ );
+});
diff --git a/examples/openclaw-plugin/.clawhubignore b/examples/openclaw-plugin/.clawhubignore
index 24f01badb..b10ace1b8 100644
--- a/examples/openclaw-plugin/.clawhubignore
+++ b/examples/openclaw-plugin/.clawhubignore
@@ -1,6 +1,5 @@
setup-helper/
tests/
-__tests__/
health_check_tools/
upgrade_scripts/
INSTALL*.md
diff --git a/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md b/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md
deleted file mode 100644
index 36578462a..000000000
--- a/examples/openclaw-plugin/docs/oc-resource-skill-import-design.md
+++ /dev/null
@@ -1,574 +0,0 @@
-# [RFC] OpenClaw Plugin 支持通过 OpenViking 导入/查询 Resource 与 Skill
-
-> 当前实现已调整:Agent 可见工具不再使用统一的 `ov_import(kind=...)`;`add_skill` 默认可用,`add_resource` 默认禁用并只能通过 `enableAddResourceTool=true` 显式开启。手动 slash command 保留 `/add-resource` 和 `/add-skill`,不再保留 `/ov-import`。
-
-## 背景
-
-当前 `examples/openclaw-plugin` 已经承担 OpenClaw 与 OpenViking 的 context-engine 集成,包括 session context、memory recall/store/forget、archive expand,以及 local/remote OpenViking runtime 管理。
-
-随着 OpenViking 的 resource 和 skill 能力完善,OpenClaw 侧也需要一个自然入口,让用户可以在 OpenClaw 对话或显式命令中把外部资料导入到 OpenViking:
-
-- Resource:项目文档、代码仓库、网页、PDF、Markdown、本地目录等,落到 `viking://resources/...`
-- Skill:`SKILL.md`、skill 目录、raw skill 内容或 MCP tool dict,落到 `viking://user/skills/...`
-
-本 RFC 讨论 OpenClaw plugin 侧的导入入口、HTTP 对接方式、安全边界和测试方案。
-
-## 目标
-
-1. 在 OpenClaw 中支持通过插件导入 OpenViking resource。
-2. 在 OpenClaw 中支持通过插件导入 OpenViking skill。
-3. 对外拆成两个明确入口:
- - resource:默认使用手动 slash command `/add-resource`;LLM tool `add_resource` 仅在 `enableAddResourceTool=true` 时暴露
- - skill:LLM tool `add_skill`,slash command `/add-skill`
-4. 不再通过 `kind: "resource" | "skill"` 在一个入口里分流。
-5. 保持 HTTP server 的本地路径安全边界:不把本地路径直接发给 OpenViking 服务端。
-6. 底层仍复用 `OpenVikingClient.addResource()` / `OpenVikingClient.addSkill()`,避免在 resource 和 skill 之间复制上传逻辑。
-7. 导入后提供检索入口,让用户能在 OpenClaw 内确认和消费已导入 resource 与 skill。
-
-## 非目标
-
-- 不改变 OpenViking 服务端 resource/skill API。
-- 不新增 OpenViking parser 类型。
-- 不依赖插件侧自动猜测所有输入类型。
-- slash command 暂不支持复杂 raw `SKILL.md` 多行内容或 MCP dict JSON;这些能力通过 LLM tool 的 `data` 参数支持。
-
-## 当前 OpenViking 支持的 Resource 输入
-
-OpenViking resource 侧当前支持多类输入源:
-
-- 远程 URL:`http://`、`https://`
-- Git 仓库 URL:`git@`、`ssh://`、`git://`,以及常见 Git hosting URL
-- 飞书/Lark 文档 URL
-- 本地文件、本地目录、`.zip`
-- raw text content
-
-常见文件 parser 覆盖:
-
-- 文档/文本:`.txt`、`.text`、`.md`、`.markdown`、`.mdown`、`.mkd`、`.pdf`、`.html`、`.htm`
-- Office/电子书:`.docx`、`.doc`、`.pptx`、`.xlsx`、`.xls`、`.xlsm`、`.epub`
-- 图片:`.png`、`.jpg`、`.jpeg`、`.gif`、`.bmp`、`.webp`、`.svg`
-- 音频:`.mp3`、`.wav`、`.ogg`、`.flac`、`.aac`、`.m4a`、`.opus`
-- 视频:`.mp4`、`.avi`、`.mov`、`.mkv`、`.webm`、`.flv`、`.wmv`
-- 目录导入还会把常见代码、文档、配置扩展名作为 text 处理,例如 `.py`、`.js`、`.ts`、`.go`、`.rs`、`.java`、`.cpp`、`.json`、`.yaml`、`.toml`、`.csv`、`.rst`、`.proto`、`.tf`、`.vue`
-
-补充说明:media parser 当前主要复制原始文件并提取基础元数据;后续向量化主要依赖摘要。
-
-## 当前 OpenViking 支持的 Skill 输入
-
-OpenViking 当前已经有独立的 skill 导入链路:
-
-- HTTP API:`POST /api/v1/skills`
-- Service 层:`ResourceService.add_skill(...)`
-- Processor:`SkillProcessor.process_skill(...)`
-- 存储位置:`viking://user/skills/{skill_name}`
-
-支持的输入形态包括:
-
-- 本地 `SKILL.md` 文件
-- 包含 `SKILL.md` 的 skill 目录
-- zip 包,解压后按目录/文件处理
-- raw `SKILL.md` 字符串内容
-- dict 格式的 skill 数据
-- MCP tool dict,会通过 `mcp_to_skill()` 转成 skill
-
-HTTP 安全边界是:直接通过 HTTP 调 `/api/v1/skills` 时,不能传宿主本地路径;本地文件/目录需要先上传到 `/api/v1/resources/temp_upload`,再把返回的 `temp_file_id` 传给 `/api/v1/skills`。
-
-## 设计方案
-
-### 1. 对外拆成两个入口
-
-Resource 和 skill 的落点、参数和服务端 API 不同,对外暴露两个入口:
-
-- resource:默认使用手动 slash command `/add-resource`;LLM tool `add_resource` 仅在 `enableAddResourceTool=true` 时暴露
-- skill:LLM tool `add_skill`,slash command `/add-skill`
-
-Resource 导入:
-
-```text
-/add-resource ./README.md --to viking://resources/openviking-readme --wait
-```
-
-Skill 导入:
-
-```text
-/add-skill ./skills/install-openviking-memory --wait
-```
-
-### 2. 为什么拆成两个入口
-
-- 工具名直接对应 OV 已有能力名:`add_resource` / `add_skill`;其中 `add_resource` 是 opt-in agent tool,默认不注册,避免搜索阶段误触发导入
-- schema 不再混入 `kind`、`data`、`to`、`parent` 这类互斥参数
-- 用户手动命令也不再靠 `--kind skill` 切换语义
-- 底层仍复用 `OpenVikingClient.addResource()` / `addSkill()`,不复制上传逻辑
-
-换句话说:对外和对内都保持 resource / skill 分离。
-
-### 3. LLM Tool 参数设计
-
-新增工具:
-
-```text
-add_skill # 默认注册
-add_resource # 默认禁用;仅 enableAddResourceTool=true 时注册
-```
-
-`add_resource` 禁用默认值是安全边界:搜索、检索、URI 读取和搜索结果优化阶段只能使用 `ov_search` / `ov_read`,不能为了“补齐召回”自动导入新资源。
-
-参数:
-
-```ts
-{
- // resource 或 skill path 模式共用
- source?: string; // local path, directory path, public URL, Git URL
-
- // skill 专用:raw SKILL.md 或 MCP tool dict
- data?: unknown;
-
- // resource 专用
- to?: string;
- parent?: string;
- reason?: string;
- instruction?: string;
-
- // 通用
- wait?: boolean;
- timeout?: number;
-}
-```
-
-校验规则:
-
-- `add_resource`:
- - 必须提供 `source`
- - `source` 可为本地路径、目录、远程 URL 或 Git URL
- - `to` 与 `parent` 互斥
- - 忽略或拒绝 `data`
-- `add_skill`:
- - 必须提供 `source` 或 `data`
- - `source` 可为本地 `SKILL.md`、skill 目录或 zip
- - `data` 可为 raw `SKILL.md` 或 MCP tool dict
- - 拒绝 resource-only 参数:`to`、`parent`、`reason`、`instruction`
-
-工具描述中应明确:只有当用户明确要求导入、添加或索引 OpenViking resource/skill 时才调用,避免模型误触发。
-
-### 4. Resource 导入路径设置
-
-Resource 的导入路径由 `to` 或 `parent` 控制,二者互斥:
-
-- `to`:精确指定最终 resource URI。
-- `parent`:只指定父目录,由 OpenViking 根据源文件名、目录名、URL 或仓库名生成子路径。
-- 二者都不传:由 OpenViking 在 `viking://resources/...` 下按默认规则生成路径。
-
-推荐用户在希望得到稳定引用 URI 时使用 `to`:
-
-```text
-/add-resource ./README.md --to viking://resources/openviking-readme --wait
-```
-
-结果会尽量落到:
-
-```text
-viking://resources/openviking-readme
-```
-
-如果只想把资源放到某个集合下,可使用 `parent`:
-
-```text
-/add-resource ./README.md --parent viking://resources/docs --wait
-```
-
-结果会落在类似:
-
-```text
-viking://resources/docs/README
-```
-
-### 5. Slash Command 参数设计
-
-新增命令:
-
-```text
-/add-resource <source> [--to URI] [--parent URI] [--reason TEXT] [--instruction TEXT] [--wait] [--timeout SEC]
-/add-skill <source> [--wait] [--timeout SEC]
-```
-
-导入 resource:
-
-```text
-/add-resource ./README.md --to viking://resources/openviking-readme --wait
-```
-
-导入远程 resource:
-
-```text
-/add-resource https://github.com/volcengine/OpenViking --to viking://resources/openviking-repo --reason "OpenViking source docs"
-```
-
-导入 skill:
-
-```text
-/add-skill ./skills/install-openviking-memory --wait
-/add-skill ./SKILL.md --wait
-```
-
-Slash command 暂不支持 raw multi-line `SKILL.md` 或 MCP dict JSON;如果需要导入这些结构化数据,使用 LLM tool 的 `data` 参数。
-
-目录导入的高级过滤参数暂不放进 v1 对外入口。后续可以按需增加:
-
-```ts
-strict?: boolean;
-ignoreDirs?: string;
-include?: string;
-exclude?: string;
-preserveStructure?: boolean;
-```
-
-### 6. Client 层实现
-
-在 `OpenVikingClient` 增加底层方法:
-
-- `uploadTempFile(filePath)`
-- `zipDirectoryForUpload(dirPath)`
-- `addResource(input)`
-- `addSkill(input)`
-
-`add_resource` 和 `add_skill` 分别调用底层 client 方法:
-
-```ts
-add_resource -> client.addResource(...)
-add_skill -> client.addSkill(...)
-```
-
-本地文件/目录流程:
-
-```text
-local file/dir
- -> if dir: zip locally
- -> POST /api/v1/resources/temp_upload
- -> POST /api/v1/resources or /api/v1/skills with temp_file_id
-```
-
-远程 resource 流程:
-
-```text
-remote URL / Git URL
- -> POST /api/v1/resources with path
-```
-
-Skill raw data 流程:
-
-```text
-raw SKILL.md or MCP dict
- -> POST /api/v1/skills with data
-```
-
-### 7. 安全边界
-
-保持 OpenViking HTTP server 当前安全模型:
-
-- 插件不把本地文件系统路径直接发送给服务端。
-- 本地文件必须先走 `/api/v1/resources/temp_upload`。
-- 本地目录先在插件侧打 zip,再上传。
-- zip 使用纯 JavaScript 实现,避免依赖系统 `zip` 命令。
-- resource 的 `to` 与 `parent` 保持互斥,沿用服务端约束。
-
-### 8. 导入后的检索入口:ov_search
-
-只提供导入工具会让体验不闭环:用户可以把 resource 或 skill 导入 OpenViking,但在 OpenClaw 内不一定知道如何检索、读取或验证导入结果。
-
-因此建议同时讨论一个轻量检索入口:
-
-- LLM tool:`ov_search`
-- slash command:`/ov-search`
-
-`ov_search` 的目标不是替代 OpenViking CLI 的全部能力,而是提供最小闭环:
-
-1. 导入 resource 或 skill。
-2. 返回 resource 的 `root_uri` 或 skill 的 `uri`。
-3. 用户或 LLM 可以立刻按返回 URI 检索。
-
-#### add_resource 返回建议
-
-`add_resource` 导入 resource 后,结果中应包含:
-
-- `root_uri`
-- `status`
-- `queue_status`(如果 `wait=true`)
-- warnings/errors
-- 下一步检索建议
-
-示例:
-
-```text
-Imported OpenViking resource: viking://resources/openviking-readme
-Processing: completed
-Try: /ov-search "OpenViking install" --uri viking://resources/openviking-readme
-```
-
-`add_skill` 导入 skill 后也应返回 skill URI,并给出 skill 检索建议:
-
-```text
-Imported OpenViking skill: viking://user/skills/install-openviking-memory
-Processing: completed
-Try: /ov-search "<query>" --uri viking://user/skills
-```
-
-#### ov_search 参数设计
-
-v1 建议保持简洁:
-
-```ts
-{
- query: string;
- uri?: string; // default: search resources and skills
- limit?: number; // default: plugin config or 10
-}
-```
-
-示例命令:
-
-```text
-/ov-search "OpenViking install" --uri viking://resources/openviking-readme
-/ov-search "API usage" --uri viking://resources
-/ov-search "<query>" --uri viking://user/skills
-```
-
-对应 LLM tool 示例:
-
-```ts
-{
- query: "OpenViking install",
- uri: "viking://resources/openviking-readme",
- limit: 5
-}
-```
-
-#### ov_search 返回结果
-
-`ov_search` 应尽量贴近 OpenViking 当前 `/api/v1/search/find` 的返回结构。OpenViking find 的 raw HTTP 返回外层是:
-
-```ts
-{
- status: "ok",
- result: {
- memories: MatchedContext[];
- resources: MatchedContext[];
- skills: MatchedContext[];
- total: number;
- query_plan?: unknown;
- provenance?: unknown; // include_provenance=true 时才可能出现
- }
-}
-```
-
-其中 `MatchedContext` 当前包含:
-
-```ts
-{
- context_type: "memory" | "resource" | "skill";
- uri: string;
- level: number;
- score: number;
- category: string;
- match_reason: string;
- abstract: string;
- overview?: string | null;
-}
-```
-
-因此 `ov_search` 建议也返回两层结果:
-
-1. 用户可读的 `content.text`
-2. 保留 OpenViking 分桶结构的 `details`
-
-有结果时的用户可见文本示例:
-
-```text
-Found 4 OpenViking results for "OpenViking install"
-
-Resources
-1. viking://resources/openviking-readme/README.md
- OpenViking installation guide and setup commands...
- score: 0.82
-
-2. viking://resources/openviking-readme/INSTALL.md
- Plugin install flow for OpenClaw and OpenViking...
- score: 0.76
-
-Skills
-1. viking://user/skills/install-openviking-memory
- Install and operate OpenViking memory integration...
- score: 0.69
-```
-
-对应结构化返回建议:
-
-```ts
-{
- content: [
- {
- type: "text",
- text: "Found 4 OpenViking results..."
- }
- ],
- details: {
- action: "searched",
- query: "OpenViking install",
- uri: "viking://resources/openviking-readme",
- total: 4,
- memories: [],
- resources: [
- {
- context_type: "resource",
- uri: "viking://resources/openviking-readme/README.md",
- level: 2,
- score: 0.82,
- category: "",
- match_reason: "...",
- abstract: "OpenViking installation guide and setup commands...",
- overview: "..."
- }
- ],
- skills: [
- {
- context_type: "skill",
- uri: "viking://user/skills/install-openviking-memory",
- level: 0,
- score: 0.69,
- category: "",
- match_reason: "...",
- abstract: "Install and operate OpenViking memory integration...",
- overview: "..."
- }
- ]
- }
-}
-```
-
-无结果时:
-
-```text
-No OpenViking resource or skill results found for "OpenViking install".
-```
-
-对应结构化返回:
-
-```ts
-{
- action: "searched",
- query: "OpenViking install",
- uri: "viking://resources/openviking-readme",
- total: 0,
- memories: [],
- resources: [],
- skills: []
-}
-```
-
-v1 应检索 `resources` 和 `skills`,所以用户可见文本按分桶展示 `resources` 和 `skills`;`details` 中保留 OpenViking 原始的 `memories/resources/skills/total` 结构。由于 v1 不检索 memory,`memories` 通常为空数组。
-
-v1 建议只返回检索结果摘要和 URI,不直接返回完整文件内容。原因:
-
-- 避免把大文档直接塞进上下文。
-- 用户或 LLM 可以基于 URI 再决定是否需要通过 `ov_read` 读取完整内容。
-- 保持 `ov_search` 作为导入后的最小消费闭环,而不是完整文件浏览器。
-
-#### 是否同时检索 memory/resource/skill
-
-`memory_recall` 当前偏向长期记忆,不适合作为 resource/skill 导入后的默认消费入口。`ov_search` v1 应检索:
-
-```ts
-uris = ["viking://resources", "viking://user/skills"]
-```
-
-后续如果希望统一上下文检索 memory/resource/skill,可扩展:
-
-```ts
-targetTypes?: Array<"memory" | "resource" | "skill">;
-```
-
-但 v1 不建议一开始加入 memory,避免和既有 `memory_recall` 职责重叠。
-
-#### 读取与树形查看
-
-`ov_search` 只解决“查到相关上下文”的问题。当前实现增加了轻量 `ov_read` tool,用来读取精确 `viking://...` 命中 URI 的完整内容,避免模型把 OpenViking 虚拟 URI 当成本地文件路径。若用户需要更完整的文件浏览能力,后续可以再讨论:
-
-- `/ov-tree <uri>`
-
-暂不加入通用 tree/list/move 等能力,避免把导入 RFC 扩展成完整 OpenViking CLI replica。
-
-## 测试计划
-
-### Unit tests
-
-覆盖 `OpenVikingClient`:
-
-- `addResource`
- - 远程 URL 直接 POST `path`
- - 本地文件先 temp upload
- - 本地目录先 zip 再 temp upload
- - `wait=true` 保留 `queue_status`
- - OpenViking error response 透传为可读错误
-- `addSkill`
- - 本地 `SKILL.md` 先 temp upload
- - skill 目录先 zip 再 temp upload
- - raw `SKILL.md` 通过 `data` 直传
- - MCP tool dict 通过 `data` 直传
-
-覆盖 `add_resource` / `add_skill`:
-
-- 默认只注册 tool:`add_skill`;`add_resource` 仅在 `enableAddResourceTool=true` 时注册
-- 注册 command:`/add-resource` / `/add-skill`
-- quoted args
-- `--flag`
-- `--key value`
-- `--key=value`
-- `--to` 与 `--parent` 冲突
-- `/add-skill` 拒绝 `to`、`parent`、`reason`、`instruction`
-
-覆盖 `ov_search` / `ov_read`:
-
-- 注册单个 tool:`ov_search`
-- 注册单个 command:`/ov-search`
-- 未指定 `uri` 时默认检索 `viking://resources` 和 `viking://user/skills`
-- 指定 `--uri` 时只检索该范围
-- `ov_search` 文本结果明确说明 `viking://...` 是 OpenViking 虚拟 URI,不是本地路径
-- 搜索、检索、URI 读取和搜索结果优化阶段不得调用 `add_resource`
-- 注册 `ov_read` tool,并验证它通过 `/api/v1/content/read?uri=...` 读取精确 `viking://...` URI
-- OpenViking error response 透传为可读错误
-- 查询为空时返回 usage error
-
-### Manual smoke
-
-```text
-/add-resource ./README.md --to viking://resources/openviking-readme --wait
-/ov-search "OpenViking install" --uri viking://resources/openviking-readme
-/add-skill ./skills/install-openviking-memory --wait
-/ov-search "install OpenViking memory" --uri viking://user/skills
-```
-
-以及自然语言触发:
-
-```text
-把 ./README.md 导入 OpenViking resource,目标是 viking://resources/openviking-readme,并等待处理完成。
-```
-
-```text
-把 ./skills/install-openviking-memory 作为 OpenViking skill 导入。
-```
-
-## 待讨论问题
-
-1. `add_resource` / `add_skill` 是否应默认 `wait=false`?
- - 当前建议默认不等待,只有用户显式要求“等待处理完成”或传 `wait=true` 时才等待。
-2. `/add-skill` 遇到 resource-only 参数应直接报错,还是静默忽略?
- - 当前建议直接报错,避免用户误以为 `to/parent` 对 skill 生效。
-3. 是否需要插件侧自动识别 skill?
- - 可选增强:当本地文件名为 `SKILL.md` 或目录包含 `SKILL.md` 时提示用户使用 `/add-skill` 或 agent tool `add_skill`。
- - 当前建议先使用显式 `/add-skill`,避免在 `/add-resource` 中自动猜测并改变用户意图。
-4. 导入本地大目录前是否需要确认机制?
- - 当前方案先不加确认;后续可基于文件数量/zip 大小增加保护。
-5. `ov_search` v1 是否默认检索 `viking://resources` 和 `viking://user/skills`?
- - 当前建议是。memory 仍交给既有 `memory_recall`,避免职责重叠。
-6. 是否需要在 v1 同时提供 `/ov-read` 或 `/ov-tree`?
- - 当前实现提供 `ov_read` tool 解决 LLM 读取 OpenViking 命中 URI 的歧义;暂不加 `/ov-tree` 或通用文件浏览器能力。
diff --git a/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.md b/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.md
deleted file mode 100644
index 632b63b4f..000000000
--- a/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.md
+++ /dev/null
@@ -1,405 +0,0 @@
-# OpenViking 动态查询配置变更与测试报告
-
-> 日期:2026-06-04
-> 分支:`feat/sharClawWithOpenViKing`
-> 仓库:`iaasng/arkclaw-openviking-plugin`
-> 结论:本次动态查询配置能力、URI 详情 API、最近 ov_search 简化清单 API 已完成实现与二次验收;全量测试、类型检查、生产构建、生产风格稳定性模拟均通过。
-
-## 1. 本次变更总结
-
-本次变更围绕 OpenViking 插件的“查询参数运行期动态配置”展开,目标是支持不重启 OpenClaw 即可调整召回数量、候选数量、阈值、资源范围和排序权重,并支持 claw 与 session 两级粒度。整体能力由新增运行期配置存储、召回链路接入、命令入口、Gateway 查询接口和测试保障共同组成。
-
-### 1.1 核心能力
-
-| 能力 | 说明 | 关键实现位置 |
-|---|---|---|
-| 运行期动态配置 | 新增 `RuntimeQueryConfigStore`,负责参数归一化、分层合并、持久化、热加载、异常容错 | `query-config.ts:173` |
-| 分层优先级 | 合并顺序为 request > session > claw > static config > default,并输出字段来源 `sources` | `query-config.ts:263` |
-| claw / session 粒度 | claw 以 `agentId` 为 key;session 优先 `ovSessionId`,其次 `sessionId`,再次 `sessionKey` | `query-config.ts:158`、`query-config.ts:367` |
-| 自动召回接入 | assemble 阶段获取有效查询配置,传入自动召回链路 | `context-engine.ts:891` |
-| 显式工具接入 | `memory_recall`、`ov_search` 使用运行期有效配置作为默认值,请求参数仍可覆盖 | `index.ts:1218` |
-| 排序权重参数化 | `rankingWeights`、`categoryWeights`、`resourceTypeWeights` 参与客户端侧排序 | `memory-ranking.ts` |
-| CLI 管理入口 | 新增 `/ov-query-config` get/set/unset/reset | `index.ts:1225`、`index.ts:1748` |
-| Gateway URI 详情 | 新增只读详情接口,不重新触发搜索 | `index.ts:945`、`index.ts:1132` |
-| Gateway 最近 ov_search 清单 | 从 recall trace 中扁平化最近一次 `ov_search` 结果 | `index.ts:1019`、`index.ts:1133` |
-| 安装脚本修复 | 修复 resource-only recall 自动配置的 JSON 传参,以及 env 单引号转义 | `scripts/install.sh:242`、`scripts/install.sh:404` |
-
-### 1.2 本次重点修复
-
-| 问题 | 影响 | 修复说明 | 测试覆盖 |
-|---|---|---|---|
-| session 只设置 `recallLimit` 时错误覆盖 claw 显式 `candidateLimit` | 低优先级显式候选数被高优先级派生值覆盖 | `applyLayer()` 增加 `candidateLimitExplicit` 跟踪 | `tests/ut/query-config.test.ts:78` |
-| `/ov-query-config` 不能设置权重参数 | 用户无法运行期调整排序权重 | 增加 `--weight`、`--categoryWeight`、`--resourceTypeWeight`、`--recallPreferAbstract` 解析 | `tests/ut/tools.test.ts:415` |
-| 空 patch 覆盖已有配置 | 用户传未知参数会把已有 scope 配置清空 | 空归一化结果直接报错,不落库 | `tests/ut/tools.test.ts:443` |
-| install.sh JSON 转义错误 | `openclaw config set` 收到非法 JSON 字符串 | 改为传入 `'["resource"]'` 的实际 JSON 文本 | `tests/ut/package-install-contract.test.ts` |
-| 初始 load 与 set 并发竞态 | 插件注册后首次写入可能被旧文件覆盖 | 写操作等待 in-flight initial load | `tests/ut/query-config.test.ts:116` |
-| 持久化队列失败后不可恢复 | 一次磁盘/权限错误会让后续写入永久失败 | rejected queue 自动恢复,当前失败仍向调用方抛出 | `tests/ut/query-config.test.ts:141` |
-| env 文件单引号转义错误 | 包含单引号的 API key / URL 可能生成不可 source 的 env 文件 | 使用 shell 单引号规范转义 `'\\''` 等价片段(实际输出为 ` '\'' `) | `tests/ut/package-install-contract.test.ts` |
-
-## 2. 新增动态配置规则
-
-### 2.1 生效优先级
-
-每次自动召回、`memory_recall`、`ov_search` 执行前都会生成一次有效配置。字段级优先级如下:
-
-```text
-request 覆盖参数
- > session 运行期配置
- > claw 运行期配置
- > plugins.entries.openviking.config 静态配置
- > 代码默认值
-```
-
-说明:
-
-- request 级参数只影响当前调用,不写入运行期配置。
-- session 级配置只影响当前会话,优先匹配 `ovSessionId`,再匹配 `sessionId`,最后匹配 `sessionKey`。
-- claw 级配置以当前 `agentId` 为作用域,影响该 claw 下后续所有 session。
-- `sources` 会标记字段来源,便于排查“为什么当前召回数量/阈值/权重是这个值”。
-
-### 2.2 字段合并规则
-
-| 类型 | 规则 |
-|---|---|
-| 标量字段 | 高优先级覆盖低优先级,如 `recallLimit`、`scoreThreshold` |
-| 数组字段 | 整体覆盖,不拼接,如 `resourceTypes` |
-| 对象字段 | 浅合并,如 `rankingWeights`、`categoryWeights`、`resourceTypeWeights` |
-| `candidateLimit` | 显式设置优先于 `recallLimit * candidateMultiplier` 派生值;且最终保证 `candidateLimit >= recallLimit` |
-| 非法数值 | 归一化时 clamp 到允许范围;非法 `targetUri` 会报错 |
-| 持久化文件损坏 | 保留 last known-good 内存配置,不阻断查询链路 |
-
-### 2.3 支持字段与范围
-
-| 字段 | 语义 | 范围/约束 | 默认来源 |
-|---|---|---|---|
-| `recallLimit` | 最终注入或展示结果数 | 1-50 | 静态 `recallLimit` |
-| `candidateLimit` | 每个 target URI 的候选检索数 | 1-200 | 派生值 |
-| `candidateMultiplier` | 候选数倍数,候选数 = `recallLimit * candidateMultiplier` | 1-20 | 4 |
-| `scoreThreshold` | 客户端后处理分数阈值 | 0-1 | 静态 `recallScoreThreshold` |
-| `maxInjectedChars` | 自动召回注入字符预算 | 100-50000 | 静态 `recallMaxInjectedChars` |
-| `recallPreferAbstract` | 是否优先使用 abstract 注入 | boolean | 静态 `recallPreferAbstract` |
-| `resourceTypes` | 默认搜索范围 | `resource` / `user` / `agent` | 静态 `recallTargetTypes` |
-| `targetUri` | 强制搜索单一 URI | 必须以 `viking://` 开头 | 无 |
-| `ovSearchLimit` | `ov_search` 默认返回数 | 1-100 | 10 |
-| `rankingWeights.baseScore` | 语义分权重 | 0-2 | 1 |
-| `rankingWeights.leaf` | 叶子节点加权 | 0-2 | 0.12 |
-| `rankingWeights.event` | 事件类加权 | 0-2 | 0.1 |
-| `rankingWeights.preference` | 偏好类加权 | 0-2 | 0.08 |
-| `rankingWeights.lexicalOverlapMax` | 词面重叠最大加权 | 0-2 | 0.2 |
-| `resourceTypeWeights` | 按资源类型加权 | -1 到 2 | 空对象 |
-| `categoryWeights` | 按 category 加权 | -1 到 2 | 空对象 |
-
-### 2.4 持久化与热加载
-
-运行期配置可以配置持久化路径:
-
-```json
-{
- "plugins": {
- "entries": {
- "openviking": {
- "config": {
- "runtimeQueryConfigPath": "/path/to/runtime-query-config.json"
- }
- }
- }
- }
-}
-```
-
-文件结构:
-
-```json
-{
- "schemaVersion": "1.0",
- "updatedAt": 1780520000000,
- "claws": {
- "main": {
- "params": { "recallLimit": 8, "candidateLimit": 80 },
- "updatedAt": 1780520000000,
- "updatedBy": "command",
- "agentId": "main"
- }
- },
- "sessions": {
- "session:oc-session-123": {
- "params": { "scoreThreshold": 0.08 },
- "updatedAt": 1780520000000,
- "updatedBy": "command",
- "agentId": "main"
- }
- }
-}
-```
-
-## 3. 使用方式
-
-### 3.1 查看当前有效配置
-
-```text
-/ov-query-config get --scope session
-```
-
-返回内容包含:
-
-- `scope`:当前查看的作用域。
-- `effective`:合并后的最终配置。
-- `effective.sources`:字段来源,如 `session` / `claw` / `static` / `default`。
-- `effective.warnings`:归一化或降级警告。
-
-### 3.2 设置 claw 级默认召回策略
-
-```text
-/ov-query-config set --scope claw \
- --recallLimit 4 \
- --candidateLimit 40 \
- --scoreThreshold 0.2 \
- --resourceTypes user,agent
-```
-
-效果:当前 claw 下所有 session 默认继承该配置;session 级配置仍可覆盖。
-
-### 3.3 设置 session 级临时策略
-
-```text
-/ov-query-config set --scope session \
- --recallLimit 10 \
- --candidateLimit 80 \
- --scoreThreshold 0.08 \
- --resourceTypes resource,user
-```
-
-效果:仅当前 session 生效,不影响同 claw 下其他 session。
-
-### 3.4 调整排序权重
-
-```text
-/ov-query-config set --scope claw \
- --weight baseScore=0.8,leaf=0.2,preference=0.18,event=0.04,lexicalOverlapMax=0.25 \
- --categoryWeight preferences=0.3,events=-0.1 \
- --resourceTypeWeight user=0.2,resource=0.1
-```
-
-说明:
-
-- `--weight` 对应 `rankingWeights`。
-- `--categoryWeight` 对应 `categoryWeights`。
-- `--resourceTypeWeight` 对应 `resourceTypeWeights`。
-- 权重只影响插件客户端侧排序,不改变 OpenViking 服务端搜索算法。
-
-### 3.5 清理字段覆盖
-
-```text
-/ov-query-config unset recallLimit scoreThreshold rankingWeights --scope session
-```
-
-效果:删除当前 session 的指定字段覆盖,下一次查询回退到 claw 或静态配置。
-
-### 3.6 重置作用域配置
-
-```text
-/ov-query-config reset --scope session
-/ov-query-config reset --scope claw
-```
-
-效果:删除该作用域整条运行期配置。
-
-## 4. API 接口整理
-
-### 4.1 `GET /api/openviking/uri-detail`
-
-用途:按完整 `viking://` URI 查询详情和正文片段。该接口只调用读取能力,不重新发起搜索。
-
-#### 请求示例
-
-```bash
-curl --get 'http://127.0.0.1:<gateway-port>/api/openviking/uri-detail' \
- --data-urlencode 'uri=viking://resources/project/spec.md' \
- --data 'includeContent=true' \
- --data 'contentLimit=12000' \
- --data 'offset=0'
-```
-
-#### Query 参数
-
-| 参数 | 类型 | 必填 | 默认值 | 说明 |
-|---|---|---|---|---|
-| `uri` | string | 是 | 无 | 完整 `viking://` URI,必须 URL encode |
-| `includeContent` | boolean | 否 | `true` | 是否读取正文 |
-| `offset` | number | 否 | 0 | 内容分页起始偏移 |
-| `contentLimit` | number | 否 | 20000 | 返回正文最大字符数,范围 1-100000 |
-| `agentId` | string | 否 | 当前上下文 agent | 读取时的 agent 路由 |
-| `sessionId` | string | 否 | 当前上下文 session | trace / session 上下文关联 |
-| `sessionKey` | string | 否 | 当前上下文 sessionKey | trace / session 上下文关联 |
-| `ovSessionId` | string | 否 | 当前上下文 ovSessionId | trace / session 上下文关联 |
-| `traceId` | string | 否 | 无 | 用于从指定 trace 补充摘要、分数、category 等元信息 |
-| `preferTracePreview` | boolean | 否 | `true` | 是否优先复用 trace 预览信息 |
-
-#### 响应字段
-
-| 字段 | 说明 |
-|---|---|
-| `ok` | 是否成功 |
-| `uri` | 请求的完整 URI |
-| `uriType` | URI 类型,如 `resource` / `session` / `user_memory` / `agent_memory` / `skill` / `archive` / `unknown` |
-| `abstractPreview` | trace 或读取结果摘要预览 |
-| `metadata` | category、score、level、resultType、sourceTraceId、source 等展示元信息 |
-| `content.text` | 正文片段 |
-| `content.offset` | 本次分页起始偏移 |
-| `content.limit` | 本次分页限制 |
-| `content.returnedChars` | 本次返回字符数 |
-| `content.totalChars` | 正文总字符数 |
-| `content.hasMore` | 是否还有后续内容 |
-| `readStatus` | `not_requested` / `ok` / `read_failed` |
-| `warnings` | 非致命警告 |
-| `error` | 错误码和错误消息 |
-
-#### 状态码
-
-| 状态码 | 场景 |
-|---|---|
-| 200 | URI 合法且读取成功,或 `includeContent=false` 只返回元信息 |
-| 400 | URI 缺失、非 `viking://`、URI 被展示截断、分页参数非法 |
-| 502 | OpenViking read 调用失败 |
-
-### 4.2 `GET /api/openviking/recall-traces/latest-ov-search-list`
-
-用途:获取当前会话最近一次 `ov_search` trace 的扁平化 URI 清单,方便前端展示“上次搜索到了哪些资源”。该接口不会重新发起 `ov_search`。
-
-#### 请求示例
-
-```bash
-curl --get 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/latest-ov-search-list' \
- --data-urlencode 'sessionId=oc-session-123' \
- --data 'limit=20' \
- --data 'includeSelected=true' \
- --data 'dedupe=true'
-```
-
-#### Query 参数
-
-| 参数 | 类型 | 必填 | 默认值 | 说明 |
-|---|---|---|---|---|
-| `sessionId` | string | 否 | 当前上下文 session | OpenClaw sessionId |
-| `sessionKey` | string | 否 | 当前上下文 sessionKey | OpenClaw sessionKey |
-| `ovSessionId` | string | 否 | 当前上下文 ovSessionId | OpenViking storage session id |
-| `agentId` | string | 否 | 当前上下文 agent | 过滤同 session 下不同 agent 的 trace |
-| `limit` | number | 否 | 20 | 返回条数,范围 1-100 |
-| `lookup` | string | 否 | `auto` | 当前响应会回显;trace 查询走内存/持久化 fallback |
-| `includeSelected` | boolean | 否 | `true` | 是否合并 selected/displayed 结果 |
-| `dedupe` | boolean | 否 | `true` | 是否按 URI 去重;selected 优先 |
-| `includeSkills` | boolean | 否 | `true` | 是否包含 skill 结果 |
-| `strict` | boolean | 否 | `false` | 未找到 trace 时是否返回 404 |
-
-#### 响应字段
-
-| 字段 | 说明 |
-|---|---|
-| `ok` | 是否成功;非 strict 且无 trace 时仍为 true |
-| `lookupLayer` | 查询来源:`memory` / `persistent` / `none` |
-| `fallbackUsed` | 是否使用持久化 fallback |
-| `query` | 回显查询条件 |
-| `trace.traceId` | 命中的 trace ID |
-| `trace.ts` / `trace.isoTime` | trace 时间 |
-| `trace.triggerQuery` | 触发 ov_search 的 query |
-| `items[]` | 扁平化条目 |
-| `items[].uri` | 完整 URI |
-| `items[].abstractPreview` | 摘要预览 |
-| `items[].resourceType` | 资源类型 |
-| `items[].resultType` | `memory` / `resource` / `skill` / `archive_match` |
-| `items[].category` | 记忆或资源 category |
-| `items[].score` | 相关性分数 |
-| `items[].source` | `search_result` / `selected` |
-| `items[].targetUri` | 来源搜索 target URI |
-| `items[].detailUrl` | 可直接打开 URI 详情的 Gateway URL |
-| `totalItems` | 返回条目数 |
-| `warnings` | 非致命警告 |
-
-#### 状态码
-
-| 状态码 | 场景 |
-|---|---|
-| 200 | 查询成功;默认未找到 trace 也返回空列表加 warning |
-| 400 | `limit` 等参数非法 |
-| 404 | `strict=true` 且未找到最近 `ov_search` trace |
-
-## 5. 本次测试范围
-
-### 5.1 覆盖范围
-
-| 范围 | 覆盖内容 |
-|---|---|
-| 单元测试 | 参数归一化、clamp、分层合并、字段来源、持久化、热加载、unset/reset、session alias 匹配 |
-| 命令测试 | `/ov-query-config` set/get/unset/reset、权重参数、空 patch 拒绝 |
-| 工具链路测试 | session 配置影响后续 `memory_recall`、`ov_search` 默认 limit/targetUri |
-| 自动召回场景测试 | context engine assemble 阶段使用 session 有效配置 |
-| 排序测试 | rankingWeights、categoryWeights、resourceTypeWeights 对入选排序生效 |
-| Gateway API 测试 | URI detail route、latest ov_search list route、skill 过滤、detailUrl 生成 |
-| 安装脚本契约测试 | standalone package contract、resource-only recall 配置、JSON 传参、env 单引号转义 |
-| 类型检查 | `tsc -p tsconfig.json` |
-| 生产构建 | `tsc -p tsconfig.build.json` |
-| 稳定性模拟 | in-flight load serialization、100 session 并发写入、配置文件损坏恢复、写队列失败恢复 |
-
-### 5.2 未执行范围说明
-
-仓库中的 Python e2e 脚本依赖真实 OpenClaw Gateway、OpenViking 服务、LLM 后端和有效 token。当前本地验收环境未提供这些外部运行前提,因此本次未执行会访问真实外部服务的 Python e2e。对应风险已通过全量 Vitest、真实 server 单测、生产风格稳定性模拟和 install dry-run 覆盖本次变更相关链路。
-
-## 6. 测试用例执行情况
-
-### 6.1 聚焦回归测试
-
-| 命令 | 结果 |
-|---|---|
-| `npm test -- tests/ut/query-config.test.ts` | 通过:9 tests passed |
-| `npm test -- tests/ut/tools.test.ts -t "ov-query-config"` | 通过:4 tests passed |
-| `npm test -- tests/ut/package-install-contract.test.ts` | 通过:6 tests passed |
-| `bash -n scripts/install.sh` | 通过:无语法错误 |
-
-### 6.2 全量测试 / 类型 / 构建
-
-| 命令 | 结果 |
-|---|---|
-| `npm test` | 通过:29 test files passed,562 tests passed |
-| `npm run typecheck` | 通过 |
-| `npm run build` | 通过 |
-
-### 6.3 生产风格稳定性模拟
-
-验证命令覆盖以下行为:
-
-1. `load()` 与 `set()` 并发时,写操作等待初始加载,不会被旧文件覆盖。
-2. 100 个 session 并发写入后,session 与 claw 配置仍按优先级正确合并。
-3. 配置文件被破坏为非法 JSON 后,`reloadIfChanged({ force: true })` 保留 last known-good 内存配置。
-4. 持久化路径临时不可写导致一次写入失败后,修复路径后下一次写入可以恢复。
-5. install.sh dry-run 对包含单引号的 URL/API key 不崩溃,resource-only recall 配置输出正确。
-
-执行结果:
-
-```text
-production-style runtime config stability check passed: in-flight load serialization + 100 concurrent session writes + corrupt-file recovery + write-queue recovery
-```
-
-## 7. 质量与风险结论
-
-### 7.1 已关闭风险
-
-- 动态配置优先级已通过单测与场景测试验证。
-- `candidateLimit` 显式配置优先级已修复并回归。
-- 权重参数 CLI 设置已补齐。
-- 空 patch 不再覆盖已有配置。
-- 持久化写入采用临时文件 + rename,写队列失败后可恢复。
-- 配置文件损坏时保留 last known-good,不影响查询链路。
-- install.sh 的 JSON 参数与 env 单引号转义均已覆盖。
-
-### 7.2 后续建议
-
-| 建议 | 优先级 | 说明 |
-|---|---|---|
-| 增加 Gateway query-config 写接口 | P2 | 当前已实现 CLI 与内部 store;如前端需要可继续补齐 `GET/PUT/DELETE /api/openviking/query-config` |
-| 支持 TTL/过期清理 | P2 | 设计文档预留 `expiresAt`,当前主要覆盖 set/unset/reset,不做自动 TTL 管理 |
-| 增加真实环境 e2e 流水线 | P2 | 需要 OpenClaw Gateway、OpenViking、LLM、token 的稳定测试环境 |
-| 多实例集中配置 | P3 | 当前为单进程/本地文件模型;多 gateway 实例可后续接远程配置服务 |
-
-## 8. 最终结论
-
-本次变更已完成“OpenViking 查询参数动态配置”主链路:支持 claw/session 粒度、支持运行期即时生效、支持配置持久化与热加载、支持召回数量/候选数量/阈值/资源类型/排序权重调整,并新增 URI 详情与最近 ov_search 简化清单 API。经过二次验收和追加复审后,发现的问题均已修复,当前自动化验证全部通过,可以进入提测/评审阶段。
diff --git a/examples/openclaw-plugin/docs/openviking-install-real-scenario-verification-report.md b/examples/openclaw-plugin/docs/openviking-install-real-scenario-verification-report.md
deleted file mode 100644
index d419c8705..000000000
--- a/examples/openclaw-plugin/docs/openviking-install-real-scenario-verification-report.md
+++ /dev/null
@@ -1,427 +0,0 @@
-# OpenViking 本机安装真实场景验证报告
-
-> 日期:2026-06-05
-> 分支:`feat/sharClawWithOpenViKing`
-> 仓库:`iaasng/arkclaw-openviking-plugin`
-> 本机 OpenClaw:`OpenClaw 2026.5.28 (e932160)`
-> 安装插件版本:`2026.6.2`
-> OpenViking 服务:`https://api.vikingdb.cn-beijing.volces.com/openviking`,健康检查版本 `v0.3.21`
-> 结论:安装、配置、真实 agent 调用、HTTP 接口、WebSocket RPC、JSONL 召回轨迹、边界用例均已完成验证;发现并修复了 HTTP route 注册兼容问题与 Gateway 查询参数大小写/别名问题。
-
-## 1. 验证目标
-
-本次验证基于本机已安装的 `openclaw` 和本仓库构建出的 OpenViking 插件包,覆盖以下目标:
-
-1. 安装包能真实安装到 `~/.openclaw/extensions/openviking`,并被 OpenClaw Gateway 加载。
-2. 插件配置符合预期:remote 模式、API key 可用、`traceRecall` 和 `traceRecallPersist` 开启、资源召回范围配置正确。
-3. OpenClaw agent 真实场景可调用 `ov_search`,返回 OpenViking `viking://` URI。
-4. Recall Trace HTTP API 注册并可访问,成功响应和边界错误响应符合预期。
-5. OpenClaw Gateway WebSocket RPC 能发现 OpenViking 工具,并可通过 `tools.invoke` 调用 `ov_search`、`ov_read`、`memory_recall` 等插件工具。
-6. Recall trace JSONL 能写入本地磁盘,结构符合 `RecallTraceEntry` schema,条数符合配置上限。
-7. 单测、类型检查、构建流程通过,避免回归。
-
-## 2. 关键实现与修复位置
-
-| 项目 | 说明 | 代码位置 |
-|---|---|---|
-| 兼容 OpenClaw 新 HTTP route API | 同时支持 legacy `registerRoute` 与现代 `registerHttpRoute` | `index.ts:885`、`index.ts:887`、`index.ts:888` |
-| HTTP route 注册 | 注册 `/api/openviking/recall-traces`、`:traceId`、`uri-detail`、`latest-ov-search-list` | `index.ts:1144`、`index.ts:1187`、`index.ts:1198` |
-| HTTP 响应包装 | 统一 `Content-Type: application/json`,非 GET 返回 405 | `index.ts:1164`、`index.ts:1173` |
-| Gateway session key 参数别名 | 兼容 `sessionkey`、`session_key`、`session-key`,避免 HTTP 层对 camelCase/保留字段处理导致查不到 trace | `index.ts:917`、`index.ts:1049`、`index.ts:1135` |
-| Gateway RPC trace 默认身份 | `ov_recall_trace` 默认使用外层 `params.sessionKey` 查询当前 session trace;仅显式传 `args.sessionKey/sessionId/ovSessionId/traceId` 时按显式过滤条件查询 | `index.ts:829`、`index.ts:855`、`index.ts:893` |
-| 历史 JSONL 身份兼容 | 默认 `sessionKey` 查询未命中时,fallback 到当前 session 的 `sessionId/ovSessionId`,兼容旧版本或 web session 只按 UUID 落盘的 trace | `index.ts:901`、`index.ts:908`、`index.ts:911` |
-| JSONL 持久化 | 每天一个 JSONL 文件,按 schema 写入并支持查询回退 | `recall-trace.ts:256`、`recall-trace.ts:284`、`recall-trace.ts:431` |
-| 配置归一化 | `traceRecall`、`traceRecallPersist`、`traceRecallDir`、`traceRecallMaxEntries` 等配置归一化 | `config.ts:525`、`config.ts:526`、`config.ts:527`、`config.ts:543` |
-| 回归测试 | HTTP route 注册、session key alias 查询新增测试覆盖 | `tests/ut/tools.test.ts:1317`、`tests/ut/tools.test.ts:1446` |
-
-## 3. 安装与配置验证
-
-### 3.1 构建与安装
-
-执行:
-
-```bash
-./build.sh
-./output/install.sh --source local --tarball ./output/openviking.tgz --openclaw-state-dir "$HOME/.openclaw"
-```
-
-结果:
-
-- `./build.sh` 成功生成:
- - `output/openviking.tgz`
- - `output/install.sh`
- - `output/volcengine-install.sh`
-- 安装脚本成功部署到:`/Users/bytedance/.openclaw/extensions/openviking`
-- `openclaw openviking status --json` 返回健康:
- - `health.ok=true`
- - `health.version=v0.3.21`
- - `health.pluginVersion=2026.6.2`
- - `slotActive=true`
-
-### 3.2 插件运行时注册
-
-执行:
-
-```bash
-openclaw plugins inspect openviking --runtime --json
-```
-
-结果:
-
-- `status=loaded`
-- `contextEngineIds=["openviking"]`
-- `services=["openviking"]`
-- `commands=["add-resource","add-skill","ov-search","ov-query-config","ov-recall-trace"]`
-- `toolNames` 包含 `ov_search`、`ov_read`、`memory_recall`、`ov_recall_trace`
-- `httpRouteCount=4`,符合预期。
-
-### 3.3 验证配置
-
-执行:
-
-```bash
-openclaw config get plugins.entries.openviking.config --json
-```
-
-关键配置已恢复并验证:
-
-```json
-{
- "mode": "remote",
- "traceRecall": true,
- "traceRecallPersist": true,
- "traceRecallDir": "/Users/bytedance/.openclaw/openviking/recall-traces",
- "traceRecallMaxEntries": 200,
- "traceRecallMaxResultsPerSearch": 20,
- "recallTargetTypes": ["resource"],
- "autoRecall": true,
- "autoCapture": true,
- "logFindRequests": true,
- "emitStandardDiagnostics": true,
- "commitTokenThresholdRatio": 0
-}
-```
-
-## 4. 测试用例与结果
-
-| ID | 测试项 | 步骤 | 预期 | 结果 |
-|---|---|---|---|---|
-| TC-01 | 插件包构建 | 执行 `./build.sh` | typecheck、全量单测、build、tgz 生成成功 | 通过:29 个测试文件、564 个测试通过 |
-| TC-02 | 本地安装 | `output/install.sh --source local --tarball ./output/openviking.tgz` | 安装到 `~/.openclaw/extensions/openviking`,Gateway 重启 | 通过 |
-| TC-03 | 健康检查 | 安装脚本内执行 setup/status | OpenViking 服务连接成功 | 通过:`version=v0.3.21` |
-| TC-04 | Runtime 注册 | `openclaw plugins inspect openviking --runtime --json` | tools/services/context engine/routes 均注册 | 通过:`httpRouteCount=4` |
-| TC-05 | 真实 agent 场景 | `openclaw agent --agent main --session-key agent:main:ov-install-verify-jsonl-20260605 --message ... --json` | agent 调用 `ov_search` 并返回 URI | 通过:返回 `viking://resources/openclaw-plugin-config/.abstract.md` |
-| TC-06 | Recall traces 列表 API | `GET /api/openviking/recall-traces?turn=all&limit=10` | 返回 JSON,包含 trace entries | 通过 |
-| TC-07 | traceId 查询 API | `GET /api/openviking/recall-traces/<traceId>?limit=1` | 返回指定 trace | 通过:返回 `ov_search-1780628249097-lpxfpu9b` |
-| TC-08 | latest ov_search 清单 API | `GET /api/openviking/recall-traces/latest-ov-search-list?limit=5` | 返回最近 ov_search 的扁平 item 列表 | 通过:返回 5 个 item |
-| TC-09 | URI detail API | `GET /api/openviking/uri-detail?uri=...&includeContent=true&contentLimit=120` | 返回内容片段和分页元数据 | 通过:`readStatus=ok`、`returnedChars=120` |
-| TC-10 | 无效 URI 边界 | `GET /api/openviking/uri-detail?uri=not-viking` | HTTP 400,`error.code=invalid_uri` | 通过 |
-| TC-11 | 无效 limit 边界 | `GET /latest-ov-search-list?limit=0` | HTTP 400,`error.code=invalid_param` | 通过 |
-| TC-12 | 非 GET 边界 | `POST /api/openviking/recall-traces` | HTTP 405,`error.code=method_not_allowed` | 通过 |
-| TC-13 | JSONL 文件存在 | 检查 `~/.openclaw/openviking/recall-traces/2026-06-05.jsonl` | 文件存在并有新增 trace | 通过:7 行 |
-| TC-14 | JSONL schema | 逐行校验 required fields、source、operationType、stats、selected URI | 0 个 schema 错误 | 通过 |
-| TC-15 | JSONL 配置上限 | line count <= `traceRecallMaxEntries=200` | 不超过上限 | 通过:7 <= 200 |
-| TC-16 | session key HTTP alias | 使用 `sessionkey`/`session_key` 查询 trace | 可从 persistent layer 查到对应 session trace | 通过;并新增单测覆盖 |
-| TC-17 | Gateway RPC health | `openclaw gateway call health --json` | Gateway 返回健康状态 | 通过:`ok=true`、`runtimeVersion=2026.5.28` |
-| TC-18 | Gateway RPC status | `openclaw gateway call status --json` | 返回运行时版本、默认 agent、session 状态 | 通过:`defaultAgentId=main`、`eventLoop.degraded=false` |
-| TC-19 | Gateway RPC system-presence | `openclaw gateway call system-presence --json` | 返回 Gateway/CLI 节点 presence | 通过:返回 macOS gateway 节点与 CLI probe 节点 |
-| TC-20 | Gateway RPC tools.catalog | `openclaw gateway call tools.catalog --params '{"agentId":"main"}' --json` | 工具目录包含 OpenViking 插件工具 | 通过:14 个 group,12 个 OpenViking 工具 |
-| TC-21 | Gateway RPC tools.effective | 使用已存在 sessionKey `agent:main:ov-install-verify-jsonl-20260605` | 当前 session 可用工具包含 OpenViking 工具 | 通过:2 个 group,12 个 OpenViking 工具 |
-| TC-22 | Gateway RPC tools.invoke/ov_search | `tools.invoke` 调用 `ov_search` 搜索 `openclaw plugin config` | 返回 `ok=true` 与 `viking://` URI | 通过:返回 2 条资源,首条为 `viking://resources/openclaw-plugin-config/.abstract.md` |
-| TC-23 | Gateway RPC tools.invoke/ov_read | `tools.invoke` 调用 `ov_read` 读取首条 URI | 返回完整内容文本 | 通过:`ok=true`、返回 335 字符内容 |
-| TC-24 | Gateway RPC tools.invoke/memory_recall | `tools.invoke` 调用 `memory_recall` | 返回召回结果且工具执行成功 | 通过:`ok=true`、`total=19` |
-| TC-25 | Gateway RPC 未知 method 边界 | `openclaw gateway call does.not.exist --params '{}' --json` | Gateway 拒绝未知 RPC 方法 | 通过:`unknown method: does.not.exist` |
-| TC-26 | Gateway RPC 无效 session 边界 | `tools.effective` 传不存在 sessionKey | Gateway 返回 unknown session key | 通过:`unknown session key` |
-| TC-27 | Gateway RPC 未知工具边界 | `tools.invoke` 调用 `not_a_tool` | `payload.ok=false`/`ok=false`,错误码 `not_found` | 通过:`Tool not available: not_a_tool` |
-| TC-28 | Gateway RPC 工具参数边界 | `ov_search` 缺少必填 `query`;`ov_read` 传 `not-viking` | 工具调用失败且不影响 Gateway | 通过:均返回 `ok=false`、`error.code=internal_error` |
-| TC-29 | Gateway RPC trace 最新查询 | `tools.invoke` 调用 `ov_recall_trace`,`args={"turn":"latest","limit":5}` | 返回最近 trace | 通过:`count=1`,返回 `memory_recall-1780635643409-v243scn9` |
-| TC-30 | Gateway RPC trace source 过滤 | `ov_recall_trace`,`turn=all`、`source=ov_search`、`limit=10` | 返回 ov_search trace | 通过:返回 `ov_search-1780635606119-h2fl11l5` |
-| TC-31 | Gateway RPC traceId 精确查询 | `ov_recall_trace`,`traceId=ov_search-1780635606119-h2fl11l5` | 返回指定 trace | 通过:`count=1`、`source=ov_search` |
-| TC-32 | Gateway RPC trace includeContent | `ov_recall_trace`,`traceId=...`、`includeContent=true` | selected 条目带内容预览 | 通过:`selected[0]` 包含 `contentPreview` |
-| TC-33 | Gateway RPC trace sessionKey 过滤 | `ov_recall_trace`,`turn=all`、`sessionKey=agent:main:ov-install-verify-jsonl-20260605` | 返回该 session 的 trace | 通过:`count=1`、`lookupLayer=memory` |
-| TC-34 | Gateway RPC trace 空结果边界 | `ov_recall_trace` 查询不存在 traceId / 不匹配 sessionKey / 不匹配 source | 返回空结果而非错误 | 通过:`ok=true`、`count=0`、`entries=[]` |
-| TC-35 | Gateway RPC trace limit 边界 | `ov_recall_trace`,`turn=all`、`limit=0` | 参数被安全归一化或回退,不影响 Gateway | 通过:返回最近 1 条,`ok=true` |
-
-## 5. 真实场景验证记录
-
-### 5.1 Agent 调用结果
-
-执行:
-
-```bash
-openclaw agent \
- --agent main \
- --session-key agent:main:ov-install-verify-jsonl-20260605 \
- --message "请使用 OpenViking 的 ov_search 搜索 openclaw plugin config 相关资源,并返回最相关的 viking URI;这是安装验收测试。" \
- --json \
- --timeout 600
-```
-
-结果摘要:
-
-- `status=ok`
-- `toolSummary.calls=1`
-- `toolSummary.tools=["ov_search"]`
-- `toolSummary.failures=0`
-- agent 返回:`viking://resources/openclaw-plugin-config/.abstract.md`
-
-### 5.2 JSONL 验证结果
-
-目标文件:
-
-```text
-/Users/bytedance/.openclaw/openviking/recall-traces/2026-06-05.jsonl
-```
-
-校验输出摘要:
-
-```text
-line_count 7
-within_max_entries True
-latest_traceId memory_recall-1780635643409-v243scn9
-latest_source memory_recall
-latest_sessionId null
-latest_sessionKey agent:main:ov-install-verify-jsonl-20260605
-latest_searches 1
-latest_selected 2
-source_counts {"auto_recall":3,"ov_search":3,"memory_recall":1}
-errors 0
-```
-
-## 6. 接口边界验证记录
-
-| API | 场景 | 状态码 | 关键字段 | 结论 |
-|---|---|---:|---|---|
-| `/api/openviking/recall-traces/<traceId>` | 指定 traceId | 200 | `ok=true`、`entries.length=1` | 通过 |
-| `/api/openviking/recall-traces/latest-ov-search-list` | 最近 ov_search | 200 | `ok=true`、`items.length=5` | 通过 |
-| `/api/openviking/uri-detail` | 正常 URI + content | 200 | `readStatus=ok`、`uriType=resource` | 通过 |
-| `/api/openviking/uri-detail` | 非 `viking://` URI | 400 | `error.code=invalid_uri` | 通过 |
-| `/api/openviking/recall-traces/latest-ov-search-list` | `limit=0` | 400 | `error.code=invalid_param` | 通过 |
-| `/api/openviking/recall-traces` | POST | 405 | `error.code=method_not_allowed` | 通过 |
-
-备注:HTTP Gateway 对 `sessionKey` 这类 camelCase/query 保留字段的转发存在不稳定表现,真实 HTTP 验证中 `sessionkey` 和 `session_key` 可稳定命中。已在插件中加入 alias 兼容,并新增回归单测。
-
-## 7. WebSocket RPC 协议验证记录
-
-### 7.1 Gateway RPC 基础接口
-
-本轮使用 `openclaw gateway call <method> --params '<json>' --json` 覆盖 OpenClaw Gateway WebSocket RPC。该 CLI 底层连接 Gateway WebSocket,使用与外部客户端一致的 RPC 方法与参数对象。
-
-| 方法 | 参数 | 结果摘要 | 结论 |
-|---|---|---|---|
-| `health` | `{}` | `ok=true`、`runtimeVersion=2026.5.28`、`eventLoop.degraded=false` | 通过 |
-| `status` | `{}` | `runtimeVersion=2026.5.28`、`defaultAgentId=main`、`mainHeartbeatEnabled=true`、`eventLoopDegraded=false` | 通过 |
-| `system-presence` | `{}` | 返回 `SuperOpsByteDance.local` gateway 节点与 `cli` probe 节点 | 通过 |
-| `tools.catalog` | `{"agentId":"main"}` | `group_count=14`,OpenViking 工具 12 个 | 通过 |
-| `tools.effective` | `{"sessionKey":"agent:main:ov-install-verify-jsonl-20260605"}` | `agentId=main`、`profile=full`、`group_count=2`,OpenViking 工具 12 个 | 通过 |
-
-`tools.catalog` 与 `tools.effective` 均确认 OpenViking 插件工具已经进入 Gateway 工具系统,工具清单包括:
-
-```text
-add_skill, memory_forget, memory_recall, memory_store,
-openviking_tool_result_list, openviking_tool_result_read, openviking_tool_result_search,
-ov_archive_expand, ov_archive_search, ov_read, ov_recall_trace, ov_search
-```
-
-### 7.2 OpenViking 工具 RPC 调用
-
-| 方法 | 工具 | 参数摘要 | 结果摘要 | 结论 |
-|---|---|---|---|---|
-| `tools.invoke` | `ov_search` | `query="openclaw plugin config"`、`limit=2`、`sessionKey=agent:main:ov-install-verify-jsonl-20260605` | `ok=true`,返回 2 条 resource,首条 URI 为 `viking://resources/openclaw-plugin-config/.abstract.md` | 通过 |
-| `tools.invoke` | `ov_read` | 读取 `viking://resources/openclaw-plugin-config/.abstract.md` | `ok=true`,返回 OpenViking content,文本长度 335 | 通过 |
-| `tools.invoke` | `memory_recall` | `query="openclaw plugin config"`、`limit=2`、`resourceTypes=["resource"]` | `ok=true`,`toolName=memory_recall`,`total=19` | 通过 |
-| `tools.invoke` | `ov_recall_trace` | `turn="latest"`、`limit=5` | `ok=true`,返回最近 1 条 trace:`memory_recall-1780635643409-v243scn9` | 通过 |
-
-`ov_search` 返回内容示例:
-
-```text
-Found 2 OpenViking results for "openclaw plugin config"
-1 resource viking://resources/openclaw-plugin-config/.abstract.md score=0.61
-2 resource viking://resources/大模型研究/Agent调研/01_OpenClaw生态与最佳实践/openclaw_codex_report/.abstract.md score=0.57
-```
-
-### 7.3 RPC 边界用例
-
-| 场景 | 命令/参数 | 实际结果 | 结论 |
-|---|---|---|---|
-| 未知 RPC method | `openclaw gateway call does.not.exist --params '{}' --json` | `GatewayClientRequestError: unknown method: does.not.exist` | 通过:Gateway 层拒绝未知方法 |
-| `tools.effective` 使用不存在 sessionKey | `sessionKey=agent:main:not-exists-openviking-rpc-20260605` | `GatewayClientRequestError: unknown session key ...` | 通过:sessionKey 必须存在 |
-| `tools.invoke` 调用不存在工具 | `name=not_a_tool` | `ok=false`、`error.code=not_found`、`Tool not available: not_a_tool` | 通过:工具层返回结构化错误 |
-| `ov_search` 缺少必填 query | `args={"limit":2}` | `ok=false`、`toolName=ov_search`、`error.code=internal_error` | 通过:工具失败被包装为失败响应,Gateway 未崩溃 |
-| `ov_read` 传非 `viking://` URI | `args={"uri":"not-viking"}` | `ok=false`、`toolName=ov_read`、`error.code=internal_error` | 通过:工具失败被包装为失败响应,Gateway 未崩溃 |
-
-### 7.4 Trace RPC 接口专项验证
-
-通过 WebSocket RPC 调用 trace 相关能力时,统一入口是 `tools.invoke` + `name="ov_recall_trace"`,与 HTTP route 的 `/api/openviking/recall-traces` 系列接口覆盖同一批 trace 数据。专项验证使用 session key:`agent:main:ov-install-verify-jsonl-20260605`。
-
-本机可直接粘贴执行的 OpenClaw 命令如下:
-
-```bash
-# 1. 查询最新 trace
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"latest","limit":5}}' \
- --json
-
-# 2. 按 source 查询 ov_search trace
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"all","source":"ov_search","limit":10}}' \
- --json
-
-# 3. 按 traceId 精确查询
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"traceId":"ov_search-1780635606119-h2fl11l5","limit":1}}' \
- --json
-
-# 4. 按 traceId 查询并展开 selected 内容预览
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"traceId":"ov_search-1780635606119-h2fl11l5","includeContent":true,"limit":1}}' \
- --json
-
-# 5. 按 sessionKey 过滤 trace
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"all","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","limit":20}}' \
- --json
-
-# 6. 查询不存在的 traceId,验证空结果边界
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"traceId":"not-exist-trace-20260605","limit":1}}' \
- --json
-
-# 7. 查询不匹配的 sessionKey,验证空结果边界
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"all","sessionKey":"agent:main:no-trace-session-20260605","limit":5}}' \
- --json
-
-# 8. 查询不匹配的 source,验证空结果边界
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"all","source":"not_a_source","limit":5}}' \
- --json
-
-# 9. limit=0 边界验证
-openclaw gateway call tools.invoke \
- --params '{"name":"ov_recall_trace","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","args":{"turn":"all","limit":0}}' \
- --json
-```
-
-| 场景 | 参数摘要 | 实际结果 | 结论 |
-|---|---|---|---|
-| 查询最新 trace | `args={"turn":"latest","limit":5}` | `ok=true`、`count=1`、`lookupLayer=memory`,返回 `memory_recall-1780635643409-v243scn9` | 通过 |
-| 按 source 查询 `ov_search` | `args={"turn":"all","source":"ov_search","limit":10}` | `ok=true`、`count=1`、返回 `ov_search-1780635606119-h2fl11l5` | 通过 |
-| 按 traceId 精确查询 | `args={"traceId":"ov_search-1780635606119-h2fl11l5","limit":1}` | `ok=true`、`count=1`、`source=ov_search`、`stats.selectedCount=2` | 通过 |
-| 查询并展开内容预览 | `args={"traceId":"ov_search-1780635606119-h2fl11l5","includeContent":true,"limit":1}` | `ok=true`、`lookupLayer=persistent`,`selected[0]` 包含 `contentPreview` 字段 | 通过 |
-| 按 sessionKey 查询 | `args={"turn":"all","sessionKey":"agent:main:ov-install-verify-jsonl-20260605","limit":20}` | `ok=true`、`count=1`,返回当前 session 最近 trace | 通过 |
-| 不存在 traceId | `args={"traceId":"not-exist-trace-20260605","limit":1}` | `ok=true`、`count=0`、`entries=[]`,文本提示 `No OpenViking recall traces found` | 通过 |
-| 不匹配 sessionKey | `args={"turn":"all","sessionKey":"agent:main:no-trace-session-20260605","limit":5}` | `ok=true`、`count=0`、`entries=[]` | 通过 |
-| 不匹配 source | `args={"turn":"all","source":"not_a_source","limit":5}` | `ok=true`、`count=0`、`entries=[]` | 通过 |
-| `limit=0` 边界 | `args={"turn":"all","limit":0}` | `ok=true`,返回最近 1 条 trace;Gateway 与插件均未异常 | 通过 |
-
-Trace RPC 返回结构关键字段:
-
-```json
-{
- "ok": true,
- "toolName": "ov_recall_trace",
- "output": {
- "details": {
- "action": "queried",
- "count": 1,
- "lookupLayer": "memory|persistent",
- "warnings": [],
- "entries": ["RecallTraceEntry"]
- }
- },
- "source": "plugin"
-}
-```
-
-结论:trace 相关能力通过 WebSocket RPC 路径验证通过。`ov_recall_trace` 支持 latest/all、source、traceId、sessionKey、includeContent 等查询场景;无匹配数据时返回 `ok=true` + 空 `entries`,工具参数边界不会导致 Gateway 异常。
-
-结论:OpenClaw Gateway WebSocket RPC 可用于自动化发现和调用 OpenViking 插件工具;`tools.effective` 需要传入已存在的 session key,`tools.catalog` 可用于按 agent 查看完整工具目录,OpenViking 工具调用成功与失败均能通过 RPC 返回可识别结果。
-
-## 8. 自动化回归验证
-
-### 8.1 针对性测试
-
-```bash
-npm run typecheck
-npm test -- --run tests/ut/recall-trace.test.ts tests/ut/tools.test.ts tests/ut/config.test.ts tests/ut/manifest-contracts.test.ts
-npm run build
-```
-
-结果:
-
-- TypeScript typecheck:通过
-- targeted tests:4 个测试文件、143 个测试通过
-- build:通过
-
-### 8.2 全量构建验证
-
-`./build.sh` 已执行完整流程:
-
-- `npm install`:通过
-- `npm run typecheck`:通过
-- `npm test`:通过,29 个测试文件、564 个测试全部通过
-- `npm run build`:通过
-- package staging + production dependencies:通过
-- `output/openviking.tgz` 生成:通过
-
-### 8.3 2026-06-08 追加验证:真实 sessionKey trace 查询修复
-
-背景:线上下载的 JSONL trace 文件 `/Users/bytedance/Downloads/2026-06-08.jsonl` 中,每条记录都包含真实 `sessionKey`,同时 `sessionId/ovSessionId` 为同一个 web session UUID。旧版查询逻辑在 `tools.invoke` 只传外层 `params.sessionKey` 时,可能退化为使用由 `sessionKey` 派生出的 `sha256` 作为 `ovSessionId` 查询;该派生值与线上 JSONL 中保存的 UUID 不一致,导致返回空。
-
-本次修复后验证:
-
-```bash
-npm run lint --if-present
-npm run typecheck
-npm test
-npm run build
-```
-
-结果:
-
-- lint:项目未配置 lint script,`npm run lint --if-present` 正常退出。
-- TypeScript typecheck:通过。
-- 全量测试:29 个测试文件、567 个测试全部通过。
-- build:通过。
-
-新增/覆盖场景:
-
-| 场景 | 期望 | 结果 |
-|---|---|---|
-| `ov_recall_trace` 默认查询当前 session | 外层 `params.sessionKey` 作为默认 trace 身份过滤条件 | 通过 |
-| 显式 `args.sessionKey` 查询历史 session | 只按显式 `entry.sessionKey` 过滤,不叠加派生 `ovSessionId` | 通过 |
-| 历史 JSONL 只有 `ovSessionId`、缺少 `sessionKey` | 默认查询未命中时 fallback 到当前 session 的 `sessionId/ovSessionId` | 通过 |
-| 线上 JSONL 回放 | 用真实 `sessionKey=agent:main:web-c6592a8e-5448-4622-9e7f-31a07447eee7` 可查询到 10 条 | 通过 |
-
-发布验证:
-
-- 版本:`2026.6.5`
-- 日期路径:`2026.6.8/`
-- TOS 对象:`install.sh`、`openviking.tgz`、`manifest.json` 已上传并 head 校验通过。
-- `latest/`:未更新。
-
-## 9. 发现的问题与处理
-
-| 问题 | 影响 | 处理 | 状态 |
-|---|---|---|---|
-| 初始 runtime inspect 不带 `--runtime` 时 `httpRouteCount=0` | 容易误判未注册 | 使用 `--runtime` 加载插件后验证;真实 runtime 为 4 | 已澄清 |
-| OpenClaw v2026.5.28 使用 `registerHttpRoute`,旧插件只注册 legacy route 时 HTTP API 不可见 | Recall Trace HTTP API 无法访问 | 插件兼容 `registerHttpRoute`,并保留 legacy `registerRoute` | 已修复 |
-| 安装脚本执行 setup 后会重置部分高级配置 | `traceRecall`/JSONL 验证配置被清空 | 安装后重新写入验证配置并重启 Gateway | 已处理 |
-| HTTP Gateway camelCase `sessionKey` 查询不稳定 | 按 session key 查询 trace 可能返回 0 | 增加 `sessionkey`、`session_key`、`session-key` alias;真实验证使用 alias | 已修复并测试 |
-| `tools.effective` 传不存在的 session key | Gateway 返回 `unknown session key`,无法列出有效工具 | 使用真实已存在 session key `agent:main:ov-install-verify-jsonl-20260605`;文档中补充前置条件 | 已澄清 |
-| Gateway RPC 只传外层 `params.sessionKey` 时 trace 查询为空 | 旧版查询没有默认使用外层 `sessionKey`,而是可能按派生 `ovSessionId` 查询;派生值与线上 UUID 不一致 | 默认按外层 `params.sessionKey` 查询;未命中时兼容 fallback 到当前 session 的 `sessionId/ovSessionId` | 已修复并测试 |
-
-## 10. 最终结论
-
-本机安装测试验证通过:
-
-- 插件包可构建、可本地安装、可被 OpenClaw Gateway 加载。
-- OpenViking remote 配置、健康检查、slot active 均符合预期。
-- 真实 agent 场景中 `ov_search` 能正常调用并返回资源 URI。
-- OpenClaw Gateway WebSocket RPC 能发现并调用 OpenViking 插件工具,`tools.catalog`、`tools.effective`、`tools.invoke`、`ov_recall_trace` 正向与边界用例均符合预期。
-- Recall Trace HTTP APIs 可访问,成功和错误边界响应符合预期。
-- JSONL trace 文件已落盘,schema 校验 0 错误,配置上限符合预期。
-- 新增/相关回归测试均通过,全量构建测试通过。
-
-建议后续发布前将 `output/openviking.tgz` 与 `output/install.sh` 作为当前验收产物重新上传到目标 TOS release path,避免线上安装包仍停留在旧版本或旧配置行为。
diff --git a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
index 5b3a1ec85..33333e80d 100644
--- a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
+++ b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
@@ -1617,5 +1617,4 @@ openclaw gateway restart
- `INSTALL-ZH.md`:安装、升级、卸载指南。
- `INSTALL-AGENT.md`:Agent 自动安装说明。
- `docs/workmemory-v2-design.md`:Working Memory v2 设计。
-- `docs/workmemory-v2-test-report.md`:Working Memory v2 测试报告。
- `health_check_tools/HEALTHCHECK-ZH.md`:健康检查脚本说明。
diff --git a/examples/openclaw-plugin/docs/workmemory-v2-test-report.md b/examples/openclaw-plugin/docs/workmemory-v2-test-report.md
deleted file mode 100644
index 3e53b5b3a..000000000
--- a/examples/openclaw-plugin/docs/workmemory-v2-test-report.md
+++ /dev/null
@@ -1,146 +0,0 @@
-# OpenViking Working Memory v2 — 测试报告
-
-> 数据集:locomo10 · MemoryArena group_travel_planner · 模型:doubao-seed-2-0-code-preview
-> 创建:2026-05-02
-
----
-
-## 核心结论
-
-1. **LoCoMo 长对话事实召回**:WM v2 在 152Q 上达 **79.61%**(旧版 23.68%,**+55.93pp**);35Q 上达 **94.29%**(旧版 28.57%,**+65.7pp**)。
-2. **Token 效率**:
- - **35Q**:WM v2 总 QA tokens **184,497**(旧版 144,797,**多 27.4%**);但准确率涨 +65.7pp,单题成本(tok/correct)从 14,480 降到 **5,591**(约 **1/2.6**)。
- - **152Q**:WM v2 总 QA tokens **1,510,190**(旧版 2,280,098,**节省 33.8%**);准确率涨 +55.93pp,单题成本从 63,336 降到 **12,481**(约 **1/5.1**)。
- - 整体趋势:35Q 是「以 token 换准确率」(总量略增 + 单题大幅降本),152Q 是**双向收益**(总量降 + 单题降)。
-3. **纯工作记忆是主体收益**:关闭长期记忆向量召回仍能达 **73.03%**(152Q),autoRecall 在此基础上再补 **+6.58pp**。
-4. **MemoryArena 跨会话规划任务**:跟 OV 主分支无 WM 严格 A/B 大体持平(**QA +3.06pp / Action −2.04pp**);跟 MC 原生比 WM v2 显著领先(**QA +35.03pp / token −21.76%**)。该任务不直接验证工作记忆,结论不外推到 LoCoMo。
-
----
-
-## 一、测试目标
-
-验证 WM v2(结构化 7 段模板 + tool_call 增量更新 + 服务端 Guards + `keep_recent_count`)相比旧版(`compression.structured_summary` v1)的实际效果。重点回答 3 个问题:
-
-1. WM v2 在小样本(35Q)和大样本(152Q)下相对 Main 的准确率提升
-2. WM v2 结构化 overview 的独立贡献(关闭向量召回)
-3. WM v2 + autoRecall 联合方案的最佳效果
-
----
-
-## 二、测试环境
-
-| 项 | 值 |
-|---|---|
-| LLM | doubao-seed-2-0-code-preview |
-| Embedding | doubao-embedding-vision-251215 |
-| Gateway | OpenClaw 2026.4.27 |
-| Main 分支 | OpenViking @ `origin/main`,commit `4d6f5b65` |
-| WM2 分支 | 工作记忆代码 |
-| Judge | doubao-seed-2-0-code-preview-260215 |
-
----
-
-## 三、LoCoMo 测试结果
-
-### 3.1 测试组
-
-| 测试组 | 说明 | autoRecall | 设计目的 |
-|---|---|---|---|
-| **WM2** | 工作记忆 + 长期记忆 + 工具回溯 | on | WM v2 全功能端到端测试 |
-| WM2-NOREC | 工作记忆 + 工具回溯(关闭长期记忆) | off | 隔离工作记忆 + 工具回溯的独立贡献,看不靠向量召回时还能拿多少分 |
-| MAIN | 原 overview + 长期记忆 + 老版工具回溯(仓库主分支代码) | on | 旧版基线 |
-| MC | OpenClaw 原生记忆(关闭 OpenViking) | — | 横向对比 OpenClaw 原生记忆方案 |
-
-### 3.2 数据集
-
-| 数据集 | session 数 | QA 数 | 说明 |
-|---|---|---|---|
-| locomo-small | 19 | 35 | LoCoMo sample 0 前 35 题,小样本快速对照 |
-| locomo10 case0 | 19 | 152 | LoCoMo sample 0 完整 |
-
-> Ingest 和 QA 同会话(QA 会话连续,复用前题上下文)——目的是测试工作记忆。
-
-### 3.3 locomo-small(35Q)
-
-| 测试组 | 准确率 | QA tokens | tok/correct |
-|---|---|---|---|
-| MAIN | 28.57% (10/35) | 144,797 | 14,480 |
-| **WM2** | **94.29% (33/35)** | **184,497** | **5,591** |
-| WM2-NOREC | 88.57% (31/35) | 124,246 | **4,008** |
-| MC | 42.86% (15/35) | 2,352,395 | 156,826 |
-
-**对比**:
-
-- **纯工作记忆(WM2-NOREC 测试组,关闭长期记忆向量召回)相比旧版 MAIN**:准确率从 28.57% 提升到 88.57%,**+60.0pp**;QA tokens 反而下降 14.2%(144,797 → 124,246),单题成本从 14,480 降到 **4,008**(**3.6× 效率**)。仅靠结构化 7 段 overview + 工具回溯,无需任何向量召回,已经能拿到大部分提升,且 token 同时节省。
-- **叠加长期记忆向量召回(WM2 测试组)相比纯工作记忆**:准确率再升 **+5.7pp**(88.57% → 94.29%);代价是 QA tokens 增加 48.5%(124,246 → 184,497),单题成本从 4,008 升到 **5,591**。长期记忆是用 token 换最后一段准确率的细节召回,边际收益递减但仍正向。
-- **OpenClaw 原生记忆(MC 测试组,关闭 OpenViking 改由 LLM 主动 memorySearch)横向对照**:仅 42.86%,单题成本 156,826(是 WM2 的 **28 倍**)——准确率比 WM2 低 **51.4pp**,无竞争力。
-
-### 3.4 locomo10 case0(152Q)
-
-将 §3.3 对照扩展到 locomo10 case0 全量 152 道 QA:
-
-| 测试组 | 准确率 | QA tokens | tok/correct |
-|---|---|---|---|
-| MAIN | 23.68% (36/152) | 2,280,098 | 63,336 |
-| **WM2** | **79.61% (121/152)** | **1,510,190** | **12,481** |
-| WM2-NOREC | 73.03% (111/152) | 1,622,319 | 14,615 |
-
-**对比**:
-
-- **纯工作记忆(WM2-NOREC 测试组,关闭长期记忆向量召回)相比旧版 MAIN**:准确率从 23.68% 提升到 73.03%,**+49.35pp**;QA tokens 同时下降 28.8%(2,280,098 → 1,622,319),单题成本从 63,336 降到 **14,615**(**4.3× 效率**)。在大样本上,纯结构化工作记忆已贡献整体提升的约 88%(49.35 / 55.93),且 token 大幅节省。
-- **叠加长期记忆向量召回(WM2 测试组)相比纯工作记忆**:准确率再升 **+6.58pp**(73.03% → 79.61%);QA tokens **再节省 6.9%**(1,622,319 → 1,510,190),单题成本从 14,615 降到 **12,481**。与 35Q 的「以 token 换准确率」不同,长样本上长期记忆是**双向收益**——既提升准确率,又因更高效答题而节省 token。
-
----
-
-## 四、MemoryArena Group Travel 对比测试
-
-MemoryArena `group_travel_planner` 是跨会话的旅行规划任务(slot-filling + 后续 QA),**不直接验证工作记忆能力**——每个 task 是独立 session,没有跨题上下文累积。本节把它作为另一个测试场景,从两个角度看 WM v2 的表现:
-
-1. **跟 MC 原生比**(§4.2):WM v2 相对「OpenClaw 自带 memorySearch」的整体能力差距
-2. **严格 A/B**(§4.3):跟 OV 主分支无 WM(OV-noWM)做同源对比,单变量评估 WM 改造对此类任务有无副作用
-
-### 4.1 数据集与方法
-
-| 维度 | 说明 |
-|---|---|
-| 数据集 | MemoryArena `group_travel_planner`(270 task / 1869 subtask 的多日多人旅行规划) |
-| 子样本 | sample0 / sample1 / sample2 共 **294 道 slot-level QA** |
-| 任务结构 | slot-filling 旅行规划 + 后续 QA(跨 task 独立 session) |
-
-**指标说明**:
-
-- **Action**:slot-filling 规划阶段的执行准确率——agent 在多步规划过程(订机票、订酒店、选餐厅等)中正确填充 expected slot(如 flight number / departure time / arrival time)的比例。衡量 agent 在规划**执行阶段**的动作准确性。
-- **QA**:slot-filling 完成后问答阶段的答题准确率——agent 基于 task 上下文回答 slot-level 问题的正确率。衡量 agent 在**记忆/检索阶段**的能力。
-- **Combined Tokens**:规划阶段(run)+ 问答阶段(QA)两阶段消耗的总 token。
-
-### 4.2 WM v2 vs MC 原生
-
-把 WM v2 跟 MC 原生(关闭 OpenViking、由 LLM 主动调 `memorySearch`)放在同一数据集上对比:
-
-| 方案 | sample0 Action | sample1 Action | sample2 Action | **Agg Action** | **Agg QA** | Combined Tokens |
-|---|---|---|---|---|---|---|
-| MC memorySearch | 8/104 | 24/70 | 26/120 | 58/294 (19.73%) | 74/294 (25.17%) | 7,158,830 |
-| **WM v2** | **66/104** | **38/70** | **79/120** | **183/294 (62.24%)** | **177/294 (60.20%)** | 5,601,097 |
-
-WM v2 相比 MC 原生:**Action +42.52pp**,**QA +35.03pp**,Combined Tokens **−21.76%**。
-
-### 4.3 严格 A/B(WM v2 vs OV-noWM)
-
-| Sample | OV-noWM Action | OV-noWM QA | WM v2 Action | WM v2 QA |
-|---|---|---|---|---|
-| sample0 | 71/104 (**68.27%**) | 65/104 (**62.50%**) | 66/104 (63.46%) | 60/104 (57.69%) |
-| sample1 | 52/70 (**74.29%**) | 45/70 (**64.29%**) | 38/70 (54.29%) | 38/70 (54.29%) |
-| sample2 | 66/120 (55.00%) | 58/120 (48.33%) | **79/120 (65.83%)** | **79/120 (65.83%)** |
-| **Aggregate** | **189/294 (64.29%)** | 168/294 (57.14%) | 183/294 (62.24%) | **177/294 (60.20%)** |
-
-WM v2 vs OV-noWM:**Action −2.04pp**(OV-noWM 略胜),**QA +3.06pp**(WM 略胜),token +2.75%。per-sample 异质性较高(sample1 OV-noWM 大幅领先、sample2 WM v2 大幅领先),aggregate 大体持平。
-
-### 4.4 观察
-
-- **跟 MC 原生比**:WM v2 在 QA 准确率上 **+35.03pp**(25.17% → 60.20%),同时 token 节省 **21.76%**——在 slot-filling 任务上 OpenViking + 工作记忆的整体表现远胜 MC 自检索方案。
-- **跟 OV-noWM 严格 A/B**:QA 略胜(**+3.06pp**)/ Action 略输(**−2.04pp**)/ token 略增(**+2.75%**)——没有显著退化也没有显著提升,符合预期(slot-filling 不直接受工作记忆改造影响)。
-- **任务定位**:MemoryArena 是跨会话规划任务,每个 task 独立 session,**不直接测工作记忆**;以上两组对比说明 WM v2 在此类任务上**没有副作用**,且仍显著优于 MC 自检索方案。
-
----
-
-> **创建**:2026-05-02
diff --git a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md
deleted file mode 100644
index e869f02d6..000000000
--- a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# OpenClaw 多租与身份透传测试报告
-
-## 1. 测试目标
-
-本轮测试围绕 `examples/openclaw-plugin` 的多租户与会话身份透传能力展开,重点验证以下目标:
-
-1. 验证插件在 `api_key` 与 `trusted` 两种服务认证模式下的请求头行为是否正确。
-2. 验证插件是否在 account/user 租户身份外,按 `peer_role` / `peer_prefix` 生成一致的 `peer_id` 与 `X-OpenViking-Actor-Peer`。
-3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `role_id`。
-4. 验证 `afterTurn` 与 `memory_store` 两条写会话路径的身份语义是否一致。
-5. 验证多租户场景下默认用户空间与不同 actor peer 视角下的召回行为是否符合预期。
-
-## 2. 测试方法
-
-### 2.1 服务端直连验证
-
-在 OpenClaw 之前,先通过 OpenViking HTTP API 直接验证服务端状态与数据面:
-
-- 使用 `curl` 调用 `/health`、`/api/v1/system/status`、`/api/v1/search/find`
-- 直接验证显式 URI,例如:
- - `viking://user/default/memories`
- - `viking://resources`
- - `viking://user/skills`
- - `viking://session/<session_id>/history`
-- 通过结构化 seed 与分层 `reindex`,确保召回验证基线可用
-
-### 2.2 插件端到端验证
-
-通过真实 OpenClaw gateway 与 OpenViking 后端联调验证:
-
-- 远端 `19950`:用于 `api_key` 模式与命名空间矩阵验证
-- 远端 `19960`:用于 `trusted` 模式与 `role_id` 验证
-- 使用真实 Feishu 机器人入口验证真实 sender 映射
-- 结合以下日志进行判定:
- - `before_prompt_build`
- - `find POST`
- - `session message POST`
- - `session commit POST`
-
-### 2.3 真实机器人验证
-
-针对 `role_id` 透传行为,使用真实机器人私聊/群聊场景复核:
-
-- 私聊验证真实 sender 到 `role_id` 的稳定映射
-- 群聊验证不同成员写入不同 `role_id`
-- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `role_id`
-
-## 3. 测试范围
-
-### 3.1 认证模式
-
-- `api_key`
-- `trusted`
-- `trusted + root_api_key`
-
-### 3.2 命名空间策略
-
-- `ff`:user 不按 actor peer 归因,agent 不按 user 隔离
-- `tf`:user 按 actor peer 归因,agent 不按 user 隔离
-- `tt`:user 按 actor peer 归因,agent 按 user 隔离
-- 兼容路径:
- - `legacy peer scope mode=agent`
- - 新 policy 覆盖旧 alias
-
-### 3.3 身份透传
-
-- `afterTurn.runtimeContext.senderId -> role_id`
-- `memory_store.requesterSenderId -> role_id`
-- assistant message 不传 `role_id`
-
-## 4. 测试结果
-
-### 4.1 通过项
-
-| 维度 | case | 结果 | 说明 |
-|---|---|---|---|
-| `api_key` | `api_key_without_key_dev` | 通过 | 不再合成 `default/default` 租户 header |
-| `api_key` | `personal_token_default` | 通过 | 命中 `DEFAULT_USER_TOKEN_19950` |
-| `api_key` | `peer_prefix_worker` | 通过 | 实际 agent 值为 `worker_main` |
-| 兼容 | `deprecated_agent_alias` | 通过 | `legacy peer scope mode=agent` 兼容正常 |
-| 覆盖优先级 | `new_policy_overrides_deprecated` | 通过 | 新 policy 覆盖旧 alias |
-| namespace | `ff_user_token` | 通过 | user 共享空间命中正确 |
-| namespace | `ff_agent_token` | 通过 | agent 共享空间命中正确 |
-| namespace | `tf_user_token` | 通过 | user 按 actor peer 归因命中正确 |
-| namespace | `tf_agent_token` | 通过 | agent 共享空间命中正确 |
-| namespace | `tt_user_token` | 通过 | user/agent 双隔离命中正确 |
-| namespace | `tt_agent_token` | 通过 | agent/user 双隔离命中正确 |
-| `trusted` | `trusted_without_key` | 通过 | 无 key trusted 路径正常 |
-| `trusted` | `trusted_with_key` | 通过 | 带 key trusted 路径正常 |
-| `trusted` | `trusted_root_key_required` | 通过 | 不带 key 被服务侧拒绝 |
-| `trusted` | `trusted_root_key_optional_ok` | 通过 | 带 root key 正常 |
-| `senderId -> role_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |
-| `senderId -> role_id` | `senderid_trusted_blank` | 通过 | `role_id:null` |
-| `senderId -> role_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |
-| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `role_id` |
-| 真实机器人 | 群聊多成员 `role_id` | 通过 | 不同成员落不同 `role_id` |
-| `memory_store` | `requesterSenderId -> role_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `role_id` |
-
-### 4.2 已知说明
-
-| 项目 | 状态 | 说明 |
-|---|---|---|
-| `agent_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 |
-| 真实机器人最终回复 | 非插件问题 | 群聊/私聊中出现的 `Something went wrong...` 已定位在 OpenClaw 工具结果回填阶段,与 OpenViking 插件链路无关 |
-
-## 5. 关键结论
-
-1. 插件侧 peer identity routing、显式租户 header 与 `role_id` 透传能力已完成联调验证。
-2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `role_id`。
-3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `role_id`。
-4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `role_id`,且 assistant message 保持 `role_id:null`。
-5. 当前 OpenViking 插件链路已满足多租户、命名空间与 sender 身份透传的测试目标。
-
-## 6. 建议
-
-1. 若后续服务端对 `api_key + USER` 的 `role_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。
-2. 如需继续扩大矩阵,可追加:
- - 更多账号/用户组合
- - 不同群聊成员的稳定性回归
- - `memory_store` 与 `afterTurn` 跨会话一致性复测
-3. 若要沉淀为长期回归用例,建议将当前已验证的矩阵继续脚本化,但保留真实机器人场景作为最终回归验证补充。
diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.json
index 91fbb7c92..f821bc6bb 100644
--- a/examples/openclaw-plugin/package.json
+++ b/examples/openclaw-plugin/package.json
@@ -42,7 +42,7 @@
],
"scripts": {
"build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
- "prepack": "npm run build",
+ "prepack": "node ../memory-plugin-shared/sync.mjs && npm run build",
"test": "vitest run",
"typecheck": "tsc -p tsconfig.json",
"test:watch": "vitest"
diff --git a/examples/openclaw-plugin/shared/recall-compress-core.mjs b/examples/openclaw-plugin/shared/recall-compress-core.mjs
deleted file mode 100644
index 1ced4cf4d..000000000
--- a/examples/openclaw-plugin/shared/recall-compress-core.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
-
-export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
-export const DIGEST_HEADER = "OpenViking memory digest:";
-const COMPRESS_OK = "ok";
-const COMPRESS_EMPTY = "empty";
-const COMPRESS_FAILED = "failed";
-
-// Medium-constraint prompt: state the goal and two structural floors, but no hard
-// bullet-length contract. Hard per-bullet limits pin the digest to headline
-// density; leaving it unconstrained lets small models rewrite long URIs into dead
-// links, which the URI repair below cleans up.
-export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
- return `You are a memory relevance compressor utility.
-Do not use any tools. Do not investigate. Only transform the given text.
-
-User query:
-${query}
-
-Retrieved OpenViking context fragments:
-${rendered}
-
-Write a memory digest for a coding agent about to answer that query. Keep the
-concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
-and conversational filler.
-
-Format rules:
-- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
-- Start every bullet with "- ".
-- End every bullet with its source, copied verbatim from the fragments above:
- "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
-- Output the digest body only. No preamble, no closing remark.
-
-If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
-}
-
-function editDistance(a, b) {
- if (a === b) return 0;
- const rows = a.length + 1;
- const cols = b.length + 1;
- let prev = Array.from({ length: cols }, (_, i) => i);
- for (let i = 1; i < rows; i += 1) {
- const cur = [i];
- for (let j = 1; j < cols; j += 1) {
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
- cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
- }
- prev = cur;
- }
- return prev[cols - 1];
-}
-
-function nearestUri(candidate, validUris) {
- let best = "";
- let bestDistance = Infinity;
- for (const uri of validUris) {
- const distance = editDistance(candidate, uri);
- if (distance < bestDistance) {
- best = uri;
- bestDistance = distance;
- }
- }
- // Only repair near-misses; an unrelated hallucination is dropped instead.
- const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
- return bestDistance <= tolerance ? best : "";
-}
-
-/**
- * Small models occasionally mangle long URIs. Snap every cited URI back onto the
- * set the server actually returned, and drop bullets whose citation cannot be
- * recovered so the digest never carries a dead link.
- */
-export function repairDigestUris(digest, validUris = []) {
- const text = String(digest || "");
- if (!text) return "";
- const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
- if (!valid.length) return text;
- const validSet = new Set(valid);
-
- const lines = [];
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim().startsWith("- ")) {
- lines.push(line);
- continue;
- }
- let tokenized = line;
- for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
- if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
- }
- let dropped = false;
- const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
- let decoded = uri;
- try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
- if (validSet.has(decoded)) return decoded;
- const nearest = nearestUri(decoded, valid);
- if (nearest) return nearest;
- dropped = true;
- return uri;
- });
- if (!dropped) lines.push(repaired);
- }
- return lines.join("\n").trim();
-}
-
-export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
- const text = String(raw || "").trim();
- if (!text) return null;
- if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
- const bullets = text.split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
- .slice(0, Math.max(1, maxBullets))
- .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
- if (!bullets.length) return null;
- return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
-}
-
-export function recallDigestCacheKey({
- query = "",
- rendered = "",
- entries = [],
- maxInputChars = 18000,
- maxBullets = 6,
-} = {}) {
- const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
- const source = JSON.stringify({
- version: 2,
- query: String(query),
- rendered: String(rendered).slice(0, maxInputChars),
- uris,
- maxInputChars,
- maxBullets,
- });
- return createHash("sha256").update(source).digest("hex");
-}
-
-async function readCache(path) {
- if (!path) return null;
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeCache(path, value) {
- if (!path) return;
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-export async function compressRecallContext({
- query,
- rendered,
- shortContext = rendered,
- entries = [],
- cfg = {},
- runCompressor,
- cachePath = "",
- now = 0,
-}) {
- const input = String(rendered || "").trim();
- if (!input) return { status: COMPRESS_EMPTY, context: "" };
- const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
- if (input.length < minChars) {
- return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
- }
-
- const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
- const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
- const key = recallDigestCacheKey({
- query,
- rendered: input,
- entries,
- maxInputChars,
- maxBullets,
- });
- const cached = await readCache(cachePath);
- if (cached?.key === key && typeof cached.digest === "string") {
- const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
- if (digest) return { status: COMPRESS_OK, context: digest };
- }
-
- const prompt = buildRecallCompressionPrompt({
- query,
- rendered: input.slice(0, maxInputChars),
- maxBullets,
- });
- const raw = await runCompressor(prompt);
- const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
- if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
- if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
-
- const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
- const repaired = repairDigestUris(normalized, validUris.length
- ? validUris
- : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
- const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
- if (!digest) return { status: COMPRESS_FAILED, context: "" };
-
- await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
- return { status: COMPRESS_OK, context: digest };
-}
diff --git a/examples/openclaw-plugin/shared/recall-core.d.mts b/examples/openclaw-plugin/shared/recall-core.d.mts
deleted file mode 100644
index cdddc3260..000000000
--- a/examples/openclaw-plugin/shared/recall-core.d.mts
+++ /dev/null
@@ -1,39 +0,0 @@
-export type ContextSearchBody = {
- query: string;
- mode: "context";
- purpose: "coding";
- score_threshold: number;
- quotas?: Record<string, number>;
- max_tokens?: number;
- peer_scope?: "actor";
- session_id?: string;
- query_expansion?: "off" | "auto";
- dedup_turns?: number;
- exclude_uris?: string[];
- rewrite?: boolean | "auto";
- rewrite_max_bullets?: number;
-};
-
-export type NormalizedContextEntry = {
- uri: string;
- category: string;
- detail: string;
- score: number;
- text: string;
-};
-
-export function buildContextSearchBody(
- cfg?: Record<string, unknown>,
- options?: {
- sessionId?: string;
- excludeUris?: string[];
- localCompressorAvailable?: boolean;
- },
-): ContextSearchBody;
-
-export function contextRequestTimeoutMs(
- cfg?: Record<string, unknown>,
- body?: Record<string, unknown>,
-): number | undefined;
-
-export function normalizeContextEntry(entry?: unknown): NormalizedContextEntry;
diff --git a/examples/openclaw-plugin/shared/recall-core.mjs b/examples/openclaw-plugin/shared/recall-core.mjs
deleted file mode 100644
index 72835de8f..000000000
--- a/examples/openclaw-plugin/shared/recall-core.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-
-import { compressRecallContext } from "./recall-compress-core.mjs";
-
-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://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-const DEFAULT_CONTEXT_LIMIT = 10;
-const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
-const DEFAULT_REWRITE_MAX_BULLETS = 6;
-const CODING_QUOTA_WEIGHTS = {
- events: 1,
- entities: 2,
- preferences: 1,
- experiences: 1,
- resources: 3,
- skills: 2,
-};
-
-let userSpaceCache = "";
-
-export function estimateTokens(text) {
- return text ? Math.ceil(String(text).length / 4) : 0;
-}
-
-function scaleQuotas(limit, weights) {
- const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
- const order = Object.keys(weights);
- const quotas = Object.fromEntries(order.map((key) => [key, 0]));
- if (slots < order.length) {
- for (const key of order) quotas[key] = 1;
- return quotas;
- }
-
- for (const key of order) quotas[key] = 1;
- const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
- const ideals = Object.fromEntries(
- order.map((key) => [key, slots * weights[key] / totalWeight]),
- );
- while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
- const key = order.reduce((best, candidate) => (
- ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
- ? candidate
- : best
- ));
- quotas[key] += 1;
- }
- return quotas;
-}
-
-function legacyMemoryQuotas(limit) {
- return {
- ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
- experiences: 0,
- };
-}
-
-function codingQuotas(limit) {
- return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
-}
-
-export function buildRecallEndpointBody(cfg = {}) {
- const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
- const body = {
- query: "",
- quotas: legacyMemoryQuotas(limit),
- 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;
-}
-
-/**
- * Body for the server-side context face. The plugin declares intent (coding
- * purpose, budget, session) and leaves the mechanics — quota ratios, tier
- * degradation, cross-turn dedup — to the server's defaults.
- */
-export function buildContextSearchBody(cfg = {}, options = {}) {
- const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
- const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
- const maxTokens = Math.max(
- 64,
- Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
- );
- const body = {
- query: "",
- mode: "context",
- purpose: "coding",
- score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
- };
- const limitConfigured = cfg.recallLimitConfigured === true;
- const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
- if (limitConfigured) body.quotas = codingQuotas(limit);
- if (maxTokensConfigured) body.max_tokens = maxTokens;
- if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
-
- const sessionId = String(options.sessionId || "").trim();
- if (sessionId) {
- body.session_id = sessionId;
- const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
- if (queryExpansionConfigured) {
- body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
- }
- const dedupTurns = Number(cfg.recallDedupTurns);
- const resolvedDedupTurns = Number.isFinite(dedupTurns)
- ? Math.max(0, Math.floor(dedupTurns))
- : 5;
- if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
- }
-
- const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
- if (excludeUris.length) body.exclude_uris = excludeUris;
-
- if (rewriteMode === "server") body.rewrite = true;
- else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
- const rewriteMaxBullets = Math.max(
- 1,
- Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
- );
- const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
- if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
- body.rewrite_max_bullets = rewriteMaxBullets;
- }
- return body;
-}
-
-// The server pipeline is serial and each optional stage has its own fuse. A
-// request is aborted client-side unless its deadline covers every stage it
-// asked for, and aborting discards the whole response rather than just the
-// stage that ran long.
-//
-// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
-// always -> retrieval, body reads, budget planning
-// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
-//
-// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
-// a quarter to spare.
-const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
-const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
-
-/**
- * HTTP deadline for one context request, or undefined to keep the caller's own.
- *
- * Derived from the request body, because the body is what states which server
- * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
- * that also spends the expansion or rewrite fuse.
- */
-export function contextRequestTimeoutMs(cfg = {}, body = {}) {
- const wantsRewrite = body.rewrite !== undefined;
- // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
- // takes the expansion fuse back out of the budget.
- const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
- const configured = Number(cfg.recallContextTimeoutMs);
- if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
- if (!wantsRewrite && !wantsExpansion) return undefined;
- const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
- return Math.max(Number(cfg.timeoutMs) || 0, floor);
-}
-
-/**
- * Strip the context-face fields a pre-context server rejects, converting the
- * token budget back to v1's character budget.
- */
-export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
- const body = buildRecallEndpointBody(cfg);
- body.query = contextBody.query || "";
- body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
- if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
- 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(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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");
-}
-
-const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
-
-function stateFile(name) {
- const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
- return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
-}
-
-async function readJsonFile(path) {
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeJsonFile(path, value) {
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Hooks are one-shot processes, so "this server has no context face" has to be
- * remembered on disk or every turn pays for a rejected request.
- */
-export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- const cached = await readJsonFile(path);
- return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
-}
-
-export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
-}
-
-/**
- * A `peer_scope` the server rejects is remembered the same way, but unlike the
- * context face this one is not a silent capability probe: dropping the field
- * widens recall from the caller's own peer to the whole user root, so doctor
- * reads this file back and warns.
- */
-export function peerScopeMemoPath() {
- return stateFile("peer-scope.json");
-}
-
-export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
- const cached = await readJsonFile(path);
- if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
- return cached;
-}
-
-export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
- await writeJsonFile(path, {
- legacyUntil: now + LEGACY_CACHE_TTL_MS,
- scope: String(scope || ""),
- status: Number(status) || 0,
- at: now,
- });
-}
-
-function looksLikeUnknownField(res) {
- const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
- return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
-}
-
-function wrapContext(body) {
- return [
- "<openviking-context>",
- "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
- body,
- "</openviking-context>",
- ].join("\n");
-}
-
-/**
- * Server-assembled context: the context face when the deployment has it, else
- * the deprecated /recall preset. Returns the injection block, "" when there was
- * nothing relevant, or null when no server-side path was usable at all.
- */
-export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
-
- const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
- if (block !== null) return block;
- return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
-}
-
-/**
- * Raw server-assembled context, or null when the deployment has no context face.
- * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
- * (their own compression, their own envelope) use this instead of the block
- * builders below.
- */
-export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId || "";
- const log = options.log || (() => {});
- if (await isContextFaceLegacy(options.legacyCachePath)) return null;
-
- const body = buildContextSearchBody(cfg, options);
- body.query = query;
- const res = await fetchJSON("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
-
- if (!res.ok) {
- const status = res.status || 0;
- if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
- await markContextFaceLegacy(options.legacyCachePath);
- log("recall_context_face_unsupported", { status });
- } else {
- log("recall_context_face_error", { status });
- }
- return null;
- }
-
- const result = res.result || {};
- const stats = result.stats || {};
- log("recall_context_assembled", {
- entries: Array.isArray(result.entries) ? result.entries.length : 0,
- usedTokens: stats.used_tokens || 0,
- tiers: stats.tier_counts || {},
- rewrite: stats.rewrite || "off",
- });
- return {
- rendered: String(result.rendered || "").trim(),
- entries: Array.isArray(result.entries) ? result.entries : [],
- digest: String(result.digest || "").trim(),
- stats,
- };
-}
-
-/**
- * Entry field compatibility: the context face returns `category`/`text`, while
- * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
- */
-export function normalizeContextEntry(entry = {}) {
- return {
- uri: String(entry.uri || "").trim(),
- category: String(entry.category || entry.type || "memory").trim() || "memory",
- detail: String(entry.detail || entry.mode || "").trim(),
- score: Number(entry.score) || 0,
- text: String(
- entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
- ).trim(),
- };
-}
-
-async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
- const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
- if (assembled === null) return null;
-
- const { rendered, entries } = assembled;
- let digest = assembled.digest;
- const mode = String(cfg.recallRewrite || "off").toLowerCase();
- if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
- log("recall_server_compression", { status: "empty" });
- return "";
- }
- const wantsLocal = mode === "client" || (mode === "auto" && !digest);
- if (wantsLocal && rendered && typeof options.runCompressor === "function") {
- try {
- const compression = await compressRecallContext({
- query,
- rendered,
- entries,
- cfg,
- runCompressor: options.runCompressor,
- cachePath: options.digestCachePath || stateFile("recall-digest.json"),
- now: Date.now(),
- });
- log("recall_local_compression", { status: compression.status });
- if (compression.status === "ok") digest = compression.context;
- if (compression.status === "empty") return "";
- } catch (err) {
- log("recall_local_compression_failed", { error: String(err?.message || err) });
- }
- }
-
- const injected = digest || rendered;
- if (!injected) return "";
- return wrapContext(injected);
-}
-
-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 wrapContext(rendered);
-}
-
-export async function postRecall(fetchJSON, body, opts = {}) {
- const actorPeerId = opts.actorPeerId || "";
- const log = opts.log || (() => {});
- const memoPath = opts.peerScopeMemoPath;
- const request = { ...body };
-
- // A remembered downgrade is still a downgrade: recall runs wider than the
- // caller asked for, so the memo doubles as the doctor's evidence.
- if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
- delete request.peer_scope;
- }
-
- 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;
- }
- // Only an unknown-field rejection means "this server predates peer_scope".
- // Retrying every other 400/422 without it silently widens the search from
- // the caller's own peer to the whole user root.
- if (!looksLikeUnknownField(res)) {
- log("recall_peer_scope_error", { status: res.status || 0 });
- return res;
- }
-
- const downgraded = { ...request };
- delete downgraded.peer_scope;
- await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
- log("recall_peer_scope_downgrade", { status: res.status || 0 });
- return fetchJSON("/api/v1/search/recall", {
- method: "POST",
- body: JSON.stringify(downgraded),
- }, { actorPeerId });
-}
-
-/**
- * Recall, plus whatever is still filed under the peer this workspace used
- * before the identity rule changed.
- *
- * Under the default `peer_scope: "all"` this costs nothing: the server's own
- * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
- * `"actor"` that sweep is off by definition, so the old peer is asked for
- * separately — as itself, which is both cheaper and wider than a bare
- * cross-peer read (that would need the user id, and reaches memories only).
- */
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
- const primary = await recallForPeer(fetchJSON, cfg, query, options);
-
- const legacyPeerId = String(options.legacyPeerId || "").trim();
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
-
- const log = options.log || (() => {});
- const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
-}
-
-async function recallForPeer(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
- const trimmed = String(query || "").trim();
- if (!trimmed) return null;
-
- // Assembly happens server-side when the deployment offers the context face;
- // older servers fall through to /recall, then to raw find.
- const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
- ...options,
- actorPeerId,
- log,
- });
- if (serverBlock !== null) return serverBlock || null;
-
- const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
- 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/openclaw-plugin/tests/context-bloat-730.test.ts b/examples/openclaw-plugin/tests/context-bloat-730.test.ts
deleted file mode 100644
index 456eda3d1..000000000
--- a/examples/openclaw-plugin/tests/context-bloat-730.test.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import type { FindResultItem } from "../client.js";
-import { postProcessMemories, pickMemoriesForInjection } from "../memory-ranking.js";
-import { memoryOpenVikingConfigSchema } from "../config.js";
-import {
- buildMemoryLines,
- buildMemoryLinesWithBudget,
- estimateTokenCount,
-} from "../auto-recall.js";
-
-/** Helper: create a mock FindResultItem */
-function mockMemory(overrides: Partial<FindResultItem> & { uri: string }): FindResultItem {
- return {
- level: 2,
- score: 0.5,
- category: "memory",
- ...overrides,
- };
-}
-
-describe("context-bloat #730 — placeholder", () => {
- it("mockMemory helper returns expected shape", () => {
- const m = mockMemory({ uri: "mem://test/1" });
- expect(m.uri).toBe("mem://test/1");
- expect(m.level).toBe(2);
- });
-});
-
-describe("Slice A: recallScoreThreshold default", () => {
- it("should filter memories below 0.15 threshold with default config", () => {
- const cfg = memoryOpenVikingConfigSchema.parse({});
-
- const memories = [
- mockMemory({ uri: "viking://user/memories/1", score: 0.05 }),
- mockMemory({ uri: "viking://user/memories/2", score: 0.10 }),
- mockMemory({ uri: "viking://user/memories/3", score: 0.20 }),
- mockMemory({ uri: "viking://user/memories/4", score: 0.50 }),
- ];
-
- const result = postProcessMemories(memories, {
- limit: 10,
- scoreThreshold: cfg.recallScoreThreshold,
- });
-
- // Only scores >= 0.15 should pass
- expect(result).toHaveLength(2);
- expect(result.map((m) => m.uri)).toEqual([
- "viking://user/memories/4",
- "viking://user/memories/3",
- ]);
- });
-
- it("should respect explicit recallScoreThreshold: 0.01 for backward compat", () => {
- const cfg = memoryOpenVikingConfigSchema.parse({ recallScoreThreshold: 0.01 });
- expect(cfg.recallScoreThreshold).toBe(0.01);
- });
-});
-
-describe("Slice B: prefer abstract over full content fetch", () => {
- it("should use abstract when available instead of calling read()", async () => {
- const mockRead = vi.fn().mockResolvedValue("Full long content from read()");
-
- const memories: FindResultItem[] = [
- mockMemory({
- uri: "viking://user/memories/1",
- abstract: "Short abstract text",
- level: 2,
- score: 0.8,
- }),
- mockMemory({
- uri: "viking://user/memories/2",
- abstract: "",
- level: 2,
- score: 0.7,
- }),
- ];
-
- const lines = await buildMemoryLines(memories, mockRead, {
- recallPreferAbstract: true,
- });
-
- // Item 1 has abstract — read() should NOT be called for it
- // Item 2 has empty abstract — read() SHOULD be called
- expect(mockRead).toHaveBeenCalledTimes(1);
- expect(mockRead).toHaveBeenCalledWith("viking://user/memories/2");
- expect(lines[0]).toContain("Short abstract text");
- });
-});
-
-describe("Slice D: individual memory integrity", () => {
- it("should keep full memory content intact", async () => {
- const longContent = "A".repeat(2000);
- const mockRead = vi.fn().mockResolvedValue(longContent);
-
- const memories: FindResultItem[] = [
- mockMemory({
- uri: "viking://user/memories/1",
- abstract: "",
- level: 2,
- score: 0.8,
- }),
- ];
-
- const lines = await buildMemoryLines(memories, mockRead, {
- recallPreferAbstract: false,
- });
-
- const contentPart = lines[0]!.replace("- [memory] ", "");
- expect(contentPart).toBe(longContent);
- });
-});
-
-describe("Slice E: character budget enforcement", () => {
- it("should stop injecting before the character budget is exceeded", async () => {
- // Each memory ~200 chars -> ~50 tokens per line (200 chars + "- [memory] " prefix)
- const memories: FindResultItem[] = Array.from({ length: 10 }, (_, i) =>
- mockMemory({
- uri: `viking://user/memories/${i}`,
- abstract: "A".repeat(200),
- level: 2,
- score: 0.8 - i * 0.01,
- }),
- );
-
- const mockRead = vi.fn().mockResolvedValue("should not be called");
-
- const { lines, estimatedTokens } = await buildMemoryLinesWithBudget(
- memories,
- mockRead,
- {
- recallPreferAbstract: true,
- recallMaxInjectedChars: 400,
- },
- );
-
- expect(lines).toHaveLength(1);
- expect(lines.join("\n").length).toBeLessThanOrEqual(400);
- expect(estimatedTokens).toBeLessThanOrEqual(53);
- });
-
- it("should estimate tokens as ceil(chars/4)", async () => {
- expect(estimateTokenCount("")).toBe(0);
- expect(estimateTokenCount("abcd")).toBe(1);
- expect(estimateTokenCount("abcde")).toBe(2);
- expect(estimateTokenCount("A".repeat(100))).toBe(25);
- });
-
- it("should have recallMaxInjectedChars in parsed config with default 4000-character budget", () => {
- const cfg = memoryOpenVikingConfigSchema.parse({});
- expect(cfg.recallMaxInjectedChars).toBe(4000);
- expect(cfg.recallTokenBudget).toBe(4000);
- });
-});
-
-describe("Slice C: isLeafLikeMemory narrowing", () => {
- it("should NOT boost .md URI items that are not level 2", () => {
- const mdButNotLeaf = mockMemory({
- uri: "viking://user/resources/notes.md",
- level: 1,
- score: 0.30,
- abstract: "Some notes file",
- });
- const actualLeaf = mockMemory({
- uri: "viking://user/memories/real-memory",
- level: 2,
- score: 0.30,
- abstract: "Actual leaf memory",
- });
-
- const result = pickMemoriesForInjection(
- [mdButNotLeaf, actualLeaf],
- 2,
- "test query",
- );
-
- // The level-2 item should rank higher (gets boost), .md non-leaf should not
- expect(result[0]!.uri).toBe("viking://user/memories/real-memory");
- });
-});
diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
deleted file mode 100644
index 80c4643ab..000000000
--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
+++ /dev/null
@@ -1,360 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import type { OpenVikingClient } from "../client.js";
-import { memoryOpenVikingConfigSchema } from "../config.js";
-import { createMemoryOpenVikingContextEngine } from "../context-engine.js";
-
-const cfg = memoryOpenVikingConfigSchema.parse({
- mode: "remote",
- baseUrl: "http://127.0.0.1:1933",
- autoCapture: false,
- autoRecall: false,
- ingestReplyAssist: false,
- emitStandardDiagnostics: true,
-});
-
-function roughEstimate(messages: unknown[]): number {
- return Math.ceil(JSON.stringify(messages).length / 4);
-}
-
-function systemPromptTokens(text?: string): number {
- return text ? Math.ceil(text.length / 4) : 0;
-}
-
-function makeLogger() {
- return {
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- };
-}
-
-function makeStats() {
- return {
- totalArchives: 0,
- includedArchives: 0,
- droppedArchives: 0,
- failedArchives: 0,
- activeTokens: 0,
- archiveTokens: 0,
- };
-}
-
-function makeEngine(contextResult: unknown) {
- const logger = makeLogger();
- const client = {
- getSessionContext: vi.fn().mockResolvedValue(contextResult),
- } as unknown as OpenVikingClient;
- const getClient = vi.fn().mockResolvedValue(client);
- const resolveAgentId = vi.fn((sessionId: string) => `agent:${sessionId}`);
-
- const engine = createMemoryOpenVikingContextEngine({
- id: "openviking",
- name: "Context Engine (OpenViking)",
- version: "test",
- cfg,
- logger,
- getClient,
- resolveAgentId,
- });
-
- return {
- engine,
- client: client as unknown as { getSessionContext: ReturnType<typeof vi.fn> },
- getClient,
- logger,
- resolveAgentId,
- };
-}
-
-describe("context-engine assemble()", () => {
- it("assembles summary archive and completed tool parts into agent messages", async () => {
- const { engine, client, resolveAgentId } = makeEngine({
- latest_archive_overview: "# Session Summary\nPreviously discussed repository setup.",
- pre_archive_abstracts: [
- {
- archive_id: "archive_001",
- abstract: "Previously discussed repository setup.",
- },
- ],
- messages: [
- {
- id: "msg_1",
- role: "assistant",
- created_at: "2026-03-24T00:00:00Z",
- parts: [
- { type: "text", text: "I checked the latest context." },
- { type: "context", abstract: "User prefers concise answers." },
- {
- type: "tool",
- tool_id: "tool_123",
- tool_name: "read_file",
- tool_input: { path: "src/app.ts" },
- tool_output: "export const value = 1;",
- tool_status: "completed",
- },
- ],
- },
- ],
- estimatedTokens: 321,
- stats: {
- ...makeStats(),
- totalArchives: 1,
- includedArchives: 1,
- archiveTokens: 40,
- activeTokens: 281,
- },
- });
-
- const liveMessages = [{ role: "user", content: "fallback live message" }];
- const result = await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-1",
- messages: liveMessages,
- tokenBudget: 4096,
- });
-
- expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096);
- expect(result.estimatedTokens).toBe(
- roughEstimate(result.messages) + systemPromptTokens(result.systemPromptAddition),
- );
- expect(result.systemPromptAddition).toContain("Session Context Guide");
- expect(result.messages).toEqual([
- {
- role: "user",
- content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
- },
- {
- role: "assistant",
- content: [
- { type: "text", text: "I checked the latest context." },
- { type: "text", text: "User prefers concise answers." },
- {
- type: "toolCall",
- id: "tool_123",
- name: "read_file",
- arguments: { path: "src/app.ts" },
- },
- ],
- },
- {
- role: "toolResult",
- toolCallId: "tool_123",
- toolName: "read_file",
- content: [{ type: "text", text: "export const value = 1;" }],
- isError: false,
- },
- ]);
- });
-
- it("emits a non-error toolResult for a running tool (not a synthetic error)", async () => {
- const { engine } = makeEngine({
- latest_archive_overview: "",
- pre_archive_abstracts: [],
- messages: [
- {
- id: "msg_2",
- role: "assistant",
- created_at: "2026-03-24T00:00:00Z",
- parts: [
- {
- type: "tool",
- tool_id: "tool_running",
- tool_name: "bash",
- tool_input: { command: "npm test" },
- tool_output: "",
- tool_status: "running",
- },
- ],
- },
- ],
- estimatedTokens: 88,
- stats: {
- ...makeStats(),
- activeTokens: 88,
- },
- });
-
- const result = await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-running",
- messages: [],
- });
-
- expect(result.systemPromptAddition).toBeUndefined();
- expect(result.messages).toHaveLength(2);
- expect(result.messages[0]).toEqual({
- role: "assistant",
- content: [
- {
- type: "toolCall",
- id: "tool_running",
- name: "bash",
- arguments: { command: "npm test" },
- },
- ],
- });
- expect(result.messages[1]).toMatchObject({
- role: "toolResult",
- toolCallId: "tool_running",
- toolName: "bash",
- isError: false,
- });
- const text = (result.messages[1] as any).content?.[0]?.text ?? "";
- expect(text).toContain("interrupted");
- expect((result.messages[1] as { content: Array<{ text: string }> }).content[0]?.text).not.toContain(
- "missing tool result",
- );
- });
-
- it("degrades tool parts without tool_id into assistant text blocks", async () => {
- const { engine } = makeEngine({
- latest_archive_overview: "",
- pre_archive_abstracts: [],
- messages: [
- {
- id: "msg_3",
- role: "assistant",
- created_at: "2026-03-24T00:00:00Z",
- parts: [
- { type: "text", text: "Tool state snapshot:" },
- {
- type: "tool",
- tool_id: "",
- tool_name: "grep",
- tool_input: { pattern: "TODO" },
- tool_output: "src/app.ts:17 TODO refine this",
- tool_status: "completed",
- },
- ],
- },
- ],
- estimatedTokens: 71,
- stats: {
- ...makeStats(),
- activeTokens: 71,
- },
- });
-
- const result = await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-missing-id",
- messages: [],
- });
-
- expect(result.messages).toEqual([
- {
- role: "assistant",
- content: [
- { type: "text", text: "Tool state snapshot:" },
- {
- type: "text",
- text: "[grep] (completed)\nInput: {\"pattern\":\"TODO\"}\nOutput: src/app.ts:17 TODO refine this",
- },
- ],
- },
- ]);
- });
-
- it("records senderId from runtimeContext in assemble diagnostics", async () => {
- const { engine, logger } = makeEngine({
- latest_archive_overview: "",
- pre_archive_abstracts: [],
- messages: [],
- estimatedTokens: 0,
- stats: makeStats(),
- });
-
- await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-with-sender",
- messages: [{ role: "user", content: "hello" }],
- runtimeContext: { senderId: "telegram:12345" },
- });
-
- expect(logger.info).toHaveBeenCalledWith(
- expect.stringContaining("\"senderIdFound\":true"),
- );
- expect(logger.info).toHaveBeenCalledWith(
- expect.stringContaining("\"senderId\":\"telegram:12345\""),
- );
- });
-
- it("falls back to live messages when assembled active messages look truncated", async () => {
- const { engine } = makeEngine({
- latest_archive_overview: "",
- pre_archive_abstracts: [],
- messages: [
- {
- id: "msg_4",
- role: "user",
- created_at: "2026-03-24T00:00:00Z",
- parts: [{ type: "text", text: "Only one stored message" }],
- },
- ],
- estimatedTokens: 12,
- stats: {
- ...makeStats(),
- activeTokens: 12,
- },
- });
-
- const liveMessages = [
- { role: "user", content: "message one" },
- { role: "assistant", content: [{ type: "text", text: "message two" }] },
- ];
-
- const result = await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-fallback",
- messages: liveMessages,
- tokenBudget: 1024,
- });
-
- expect(result).toEqual({
- messages: liveMessages,
- estimatedTokens: roughEstimate(liveMessages),
- });
- });
-
- it("keeps assembled output within the requested token budget", async () => {
- const longText = "A".repeat(2500);
- const { engine } = makeEngine({
- latest_archive_overview: "# Session Summary\nA short overview",
- pre_archive_abstracts: [],
- messages: [
- {
- id: "msg_long_1",
- role: "user",
- created_at: "2026-03-24T00:00:00Z",
- parts: [{ type: "text", text: longText }],
- },
- {
- id: "msg_long_2",
- role: "assistant",
- created_at: "2026-03-24T00:00:01Z",
- parts: [{ type: "text", text: longText }],
- },
- ],
- estimatedTokens: 2000,
- stats: {
- ...makeStats(),
- totalArchives: 1,
- includedArchives: 1,
- activeTokens: 2000,
- archiveTokens: 10,
- },
- });
-
- const result = await engine.assemble({
- prompt: "current user prompt",
- sessionId: "session-budgeted",
- messages: [],
- tokenBudget: 1024,
- });
-
- expect(result.estimatedTokens).toBeLessThanOrEqual(1024);
- expect(result.messages.length).toBeGreaterThan(0);
- expect(result.systemPromptAddition).toContain("Session Context Guide");
- });
-});
diff --git a/examples/openclaw-plugin/tests/demo-memory-ajie.py b/examples/openclaw-plugin/tests/demo-memory-ajie.py
deleted file mode 100644
index 5d006160d..000000000
--- a/examples/openclaw-plugin/tests/demo-memory-ajie.py
+++ /dev/null
@@ -1,258 +0,0 @@
-#!/usr/bin/env python3
-"""
-OpenClaw Plugin 演示脚本 — 用户: 阿杰(后端开发)
-
-通过 OpenClaw Gateway 的 Responses API (/v1/responses) 进行多轮对话,
-验证 OpenViking 记忆插件的端到端能力。消息经过完整 agent 流水线,
-插件的 before_prompt_build(记忆注入)和 afterTurn(记忆抽取)自动触发。
-
-前提: OpenClaw 配置中需开启 Responses API。在 openclaw.config.json 的 gateways 中添加:
-
- {
- "type": "openresponses-http",
- "port": 18789
- }
-
-然后启动 OpenClaw 即可在该端口使用 /v1/responses 端点。
-
-用法:
- python demo-memory-ajie.py
- python demo-memory-ajie.py --gateway http://127.0.0.1:18789
- python demo-memory-ajie.py --phase chat # 只跑对话
- python demo-memory-ajie.py --phase verify # 只跑验证(需先跑 chat)
-
-依赖:
- pip install requests rich
-"""
-
-import argparse
-import time
-
-import requests
-from rich.console import Console
-from rich.markdown import Markdown
-from rich.panel import Panel
-from rich.table import Table
-
-# ── 常量 ───────────────────────────────────────────────────────────────────
-
-USER_ID = "ajie"
-DISPLAY_NAME = "阿杰"
-DEFAULT_GATEWAY = "http://127.0.0.1:18789"
-
-console = Console()
-
-# ── 对话数据 (10 轮) ──────────────────────────────────────────────────────
-
-CHAT_MESSAGES = [
- # 第1轮 — 开场介绍
- "嗨,我是阿杰,是个后端开发工程师,最近在优化我们系统的性能。想找个助手帮我记录一下平时遇到的技术问题和解决方案,你能帮帮我吗?",
- # 第2轮 — Redis 缓存问题
- "说到问题,前几天刚遇到一个 Redis 缓存击穿的情况。热门商品的缓存过期了,瞬间大量请求打到数据库,差点把 DB 搞挂了。后来我加了互斥锁,只有一个请求去查 DB 并刷新缓存,才解决了问题。",
- # 第3轮 — MySQL 慢查询
- "还有个 MySQL 的问题,之前有个订单列表查询特别慢,看了一下慢查询日志,发现是没加索引。给 create_time 和 user_id 加了联合索引之后,查询时间从 2 秒降到了 50 毫秒,效果特别明显。",
- # 第4轮 — Kafka 削峰填谷
- "对了,我们还用 Kafka 做了削峰填谷。订单创建成功后先写入 Kafka,然后消费者慢慢处理,这样即使是秒杀活动也不怕了。我们还在 Kafka 里做了订单超时检查,30 分钟未支付的订单自动取消。",
- # 第5轮 — 技术栈介绍
- "说一下我们的技术栈吧:后端用的是 Spring Boot,缓存用 Redis,数据库是 MySQL,消息队列是 Kafka。部署在 Kubernetes 上,用 Prometheus + Grafana 做监控。你对这套技术栈熟悉吗?",
- # 第6轮 — 工作习惯
- "我一般早上 9 点到公司,先花 15 分钟看一下监控面板和告警信息,确保系统正常运行。然后上午写代码,下午开会或者帮同事 review code。对了,我用 IntelliJ IDEA 写代码,快捷键超好用!",
- # 第7轮 — 踩过的坑
- "说起踩过的坑,那可多了!比如有一次把 Redis 的过期时间设成了 10 秒而不是 10 分钟,结果缓存频繁失效;还有一次 MySQL 连接池满了,是因为有个地方连接没释放。每次踩坑我都会记下来,避免再犯。",
- # 第8轮 — 最近在学习
- "最近在看《Redis 设计与实现》这本书,讲得真好,终于理解 Redis 的数据结构底层是怎么实现的了。之前还看过《高性能 MySQL》,收获也很大。你有什么技术书推荐吗?",
- # 第9轮 — 今天的任务
- "今天的任务:晚上要优化一下 Kafka 消费者的配置,现在消费速度有点慢,想把批量消费参数调大一点。还有,要帮新来的同事小林搭建一下开发环境,他对 Kafka 不太熟。",
- # 第10轮 — 对话偏好
- "好的,以后跟我聊技术问题的时候,先讲一下原理,再给具体的代码示例,这样我理解得更透彻。另外,多提一些最佳实践,我想写出更健壮的代码。谢谢啦!",
-]
-
-# ── 验证数据 (5 轮) ──────────────────────────────────────────────────────
-
-VERIFY_QUESTIONS = [
- {
- "question": "帮我回忆一下最近遇到的技术问题和解决方案,请简洁回答",
- "expected": "Redis 缓存击穿加互斥锁、MySQL 加索引、Kafka 削峰填谷",
- },
- {
- "question": "我们的技术栈是什么?请简洁回答",
- "expected": "Spring Boot、Redis、MySQL、Kafka、K8s、Prometheus + Grafana",
- },
- {
- "question": "我踩过哪些技术坑?请简洁回答",
- "expected": "Redis 过期时间设错、MySQL 连接池满了",
- },
- {
- "question": "我的工作习惯是怎样的?请简洁回答",
- "expected": "早上看监控、上午写代码、下午开会/review,用 IDEA",
- },
- {"question": "最近在看什么技术书?请简洁回答", "expected": "Redis 设计与实现、高性能 MySQL"},
-]
-
-
-# ── 辅助函数 ───────────────────────────────────────────────────────────────
-
-
-def send_message(gateway_url, message, user_id, previous_messages=None):
- """通过 OpenClaw Responses API 发送消息。"""
- # OpenClaw Responses API 只接受单条消息作为输入,不接受历史消息数组
- input_data = message
- resp = requests.post(
- f"{gateway_url}/v1/responses",
- json={"model": "openclaw", "input": input_data, "user": user_id},
- timeout=300,
- )
- resp.raise_for_status()
- return resp.json()
-
-
-def extract_reply_text(data):
- """从 Responses API 响应中提取助手回复文本。"""
- for item in data.get("output", []):
- if item.get("type") == "message" and item.get("role") == "assistant":
- for part in item.get("content", []):
- if part.get("type") in ("text", "output_text"):
- return part.get("text", "")
- return "(无回复)"
-
-
-def render_reply(text):
- """用 rich 渲染助手回复。"""
- lines = text.split("\n")
- if len(lines) > 30:
- text = "\n".join(lines[:30]) + f"\n\n... (共 {len(lines)} 行,已截断)"
- console.print(Panel(Markdown(text), title="[green]回复[/green]", border_style="green"))
-
-
-# ── 主流程 ─────────────────────────────────────────────────────────────────
-
-
-def run_chat(gateway_url, delay):
- console.print()
- console.rule(f"[bold]Phase 1: 多轮对话 — {DISPLAY_NAME} ({len(CHAT_MESSAGES)} 轮)[/bold]")
- console.print(f"[yellow]用户:[/yellow] {DISPLAY_NAME} (user={USER_ID})")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
- console.print(f"[yellow]轮次间隔:[/yellow] {delay}s")
-
- total = len(CHAT_MESSAGES)
- ok = fail = 0
- messages = [] # 维护对话历史
-
- for i, msg in enumerate(CHAT_MESSAGES, 1):
- console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
- console.print(
- Panel(msg, title=f"[bold cyan]用户 [{i}/{total}][/bold cyan]", border_style="cyan")
- )
- try:
- data = send_message(gateway_url, msg, USER_ID, messages if messages else None)
- reply = extract_reply_text(data)
- messages.append({"role": "user", "content": msg})
- messages.append({"role": "assistant", "content": reply})
- render_reply(reply)
- ok += 1
- except Exception as e:
- console.print(f"[red][ERROR][/red] {e}")
- fail += 1
- if i < total:
- time.sleep(delay)
-
- console.print()
- console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
-
- wait = max(delay * 2, 5)
- console.print(f"[yellow]等待 {wait:.0f}s 让记忆抽取完成...[/yellow]")
- time.sleep(wait)
-
-
-def run_verify(gateway_url, delay):
- console.print()
- console.rule(
- f"[bold]Phase 2: 验证记忆召回 — {DISPLAY_NAME} 新 Session ({len(VERIFY_QUESTIONS)} 轮)[/bold]"
- )
-
- # 用不同的 user 后缀确保 Gateway 派生出新 session
- verify_user = f"{USER_ID}-verify"
- console.print(f"[yellow]验证用户:[/yellow] {verify_user} (新 session,不带对话历史)")
-
- results = []
- total = len(VERIFY_QUESTIONS)
-
- for i, item in enumerate(VERIFY_QUESTIONS, 1):
- q, expected = item["question"], item["expected"]
- console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
- console.print(
- Panel(
- f"{q}\n[dim]期望召回: {expected}[/dim]",
- title=f"[bold cyan]验证 [{i}/{total}][/bold cyan]",
- border_style="cyan",
- )
- )
-
- try:
- # 每题独立发送,不带历史 → 回答正确 = 记忆召回生效
- data = send_message(gateway_url, q, verify_user)
- reply = extract_reply_text(data)
- render_reply(reply)
- results.append({"expected": expected, "success": True})
- except Exception as e:
- console.print(f"[red][ERROR][/red] {e}")
- results.append({"expected": expected, "success": False})
-
- if i < total:
- time.sleep(delay)
-
- # 汇总表格
- console.print()
- console.rule(f"[bold]结果汇总 — {DISPLAY_NAME}[/bold]")
-
- table = Table(title=f"记忆召回验证 — {DISPLAY_NAME} ({USER_ID})")
- table.add_column("#", style="bold", width=4)
- table.add_column("状态", width=6)
- table.add_column("期望召回", style="dim")
-
- for i, r in enumerate(results, 1):
- status = "[green]OK[/green]" if r.get("success") else "[red]FAIL[/red]"
- table.add_row(str(i), status, r["expected"])
-
- console.print(table)
-
- ok = sum(1 for r in results if r.get("success"))
- console.print(f"\n[yellow]成功: {ok}/{total}[/yellow]")
- console.print(
- "[yellow]验证方式: 每个问题在新 session 中独立发送(无对话历史),回答正确说明 before_prompt_build 阶段成功召回了记忆。[/yellow]"
- )
-
-
-# ── 入口 ───────────────────────────────────────────────────────────────────
-
-
-def main():
- parser = argparse.ArgumentParser(description=f"Memory 演示 — {DISPLAY_NAME}")
- parser.add_argument(
- "--gateway",
- default=DEFAULT_GATEWAY,
- help=f"OpenClaw Gateway 地址 (默认: {DEFAULT_GATEWAY})",
- )
- parser.add_argument(
- "--phase",
- choices=["all", "chat", "verify"],
- default="all",
- help="all=全部, chat=仅对话, verify=仅验证 (默认: all)",
- )
- parser.add_argument("--delay", type=float, default=3.0, help="轮次间等待秒数 (默认: 3)")
- args = parser.parse_args()
-
- gateway_url = args.gateway.rstrip("/")
- console.print(f"[bold]OpenClaw Plugin 演示 — {DISPLAY_NAME}[/bold]")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
-
- if args.phase in ("all", "chat"):
- run_chat(gateway_url, args.delay)
- if args.phase in ("all", "verify"):
- run_verify(gateway_url, args.delay)
-
- console.print("\n[yellow]演示完成。[/yellow]")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/openclaw-plugin/tests/demo-memory-xiaomei.py b/examples/openclaw-plugin/tests/demo-memory-xiaomei.py
deleted file mode 100644
index 2c3967763..000000000
--- a/examples/openclaw-plugin/tests/demo-memory-xiaomei.py
+++ /dev/null
@@ -1,258 +0,0 @@
-#!/usr/bin/env python3
-"""
-OpenClaw Plugin 演示脚本 — 用户: 小美(日常生活记录)
-
-通过 OpenClaw Gateway 的 Responses API (/v1/responses) 进行多轮对话,
-验证 OpenViking 记忆插件的端到端能力。消息经过完整 agent 流水线,
-插件的 before_prompt_build(记忆注入)和 afterTurn(记忆抽取)自动触发。
-
-前提: OpenClaw 配置中需开启 Responses API。在 openclaw.config.json 的 gateways 中添加:
-
- {
- "type": "openresponses-http",
- "port": 18790
- }
-
-然后启动 OpenClaw 即可在该端口使用 /v1/responses 端点。
-
-用法:
- python demo-memory-xiaomei.py
- python demo-memory-xiaomei.py --gateway http://127.0.0.1:2026
- python demo-memory-xiaomei.py --phase chat # 只跑对话
- python demo-memory-xiaomei.py --phase verify # 只跑验证(需先跑 chat)
-
-依赖:
- pip install requests rich
-"""
-
-import argparse
-import time
-
-import requests
-from rich.console import Console
-from rich.markdown import Markdown
-from rich.panel import Panel
-from rich.table import Table
-
-# ── 常量 ───────────────────────────────────────────────────────────────────
-
-USER_ID = "xiaomei"
-DISPLAY_NAME = "小美"
-DEFAULT_GATEWAY = "http://127.0.0.1:18790"
-
-console = Console()
-
-# ── 对话数据 (10 轮) ──────────────────────────────────────────────────────
-
-CHAT_MESSAGES = [
- # 第1轮 — 开场介绍
- "嗨!我是小美,刚毕业不久,现在在一家互联网公司做运营。我想找个能帮我记录日常生活的小助手,比如记一下每天发生的事情、我的想法、还有想做的事情。你能帮帮我吗?",
- # 第2轮 — 今天的心情和工作
- "今天心情还不错!早上在地铁上看到了一个超级可爱的小猫咪,它主人带着它坐车,只露出个小脑袋,太萌了!对了,今天部门开会说下个月要做 618 大促,我负责写活动文案,有点紧张,这是我第一次独立负责这么重要的项目。",
- # 第3轮 — 饮食习惯
- "说到吃,中午我跟同事小丽一起去吃了楼下那家麻辣烫,超级好吃!我喜欢多放醋和麻酱,不太能吃辣。不过最近在减肥,不敢吃太多主食。你有没有什么好吃又不胖的推荐呀?",
- # 第4轮 — 运动计划
- "对了,我办了一张健身卡,就在我家小区旁边。上周去了一次,跑了 30 分钟步,还练了会儿瑜伽。结果第二天腿酸得不行,下楼都费劲。教练说让我每周去三次,我怕坚持不下来...",
- # 第5轮 — 周末的计划
- "这个周末你有什么建议吗?我想跟我男朋友一起出去。我们之前想过去看樱花,但好像花期快过了。要不看电影?最近有什么好看的电影吗?或者去探店?我知道有一家咖啡馆好像很不错。",
- # 第6轮 — 我的爱好
- "说起来,我平时喜欢追剧,尤其是那种甜宠剧,最近在看《归路》,太甜了!我还喜欢画画,虽然画得不太好,但挺解压的。偶尔也会看看书,最近在看《被讨厌的勇气》,挺有启发的。",
- # 第7轮 — 过敏和小习惯
- "哎呀,我差点忘了提醒你!我对芒果过敏,吃了会起疹子。上次在公司同事给了我一个芒果蛋糕,我不知道,吃了一口就进医院了,还好不严重。还有,我每天晚上睡觉前都要喝一杯热牛奶,不然会失眠。",
- # 第8轮 — 想买的东西
- "最近我种草了一个拍立得,就是富士的 mini12,粉色那款,颜值超级高!但有点贵,要 700 多块钱,还在犹豫要不要买。对了,我还想买一个投影仪,这样周末可以在家看电影。",
- # 第9轮 — 同事和朋友
- "说到同事,小丽人超好,她说会帮我一起想 618 的文案点子。还有,我闺蜜下周要结婚了!她是我们宿舍第一个结婚的,真为她开心。我还在想送什么礼物好呢,红包肯定要包,但想再加点特别的。",
- # 第10轮 — 对话风格偏好
- "好的,谢谢你听我说了这么多!以后跟我聊天的时候,轻松一点就好,像朋友一样。如果我不开心了,多安慰安慰我;如果我开心,就跟我一起开心。对了,多给我推荐好吃的好玩的,谢谢啦!",
-]
-
-# ── 验证数据 (5 轮) ──────────────────────────────────────────────────────
-
-VERIFY_QUESTIONS = [
- {
- "question": "帮我回忆一下我最近的生活和工作情况,请简洁回答",
- "expected": "618 活动文案、同事小丽、健身计划、减肥中",
- },
- {
- "question": "周末想跟男朋友出去,有什么建议吗?请简洁回答",
- "expected": "樱花花期快过了,看电影或探店,喜欢咖啡馆",
- },
- {
- "question": "想吃点东西,有什么要注意的吗?请简洁回答",
- "expected": "对芒果过敏,喜欢麻辣烫多放醋和麻酱,减肥中少吃主食",
- },
- {
- "question": "我平时有什么爱好?请简洁回答",
- "expected": "追甜宠剧、画画、看书(被讨厌的勇气)",
- },
- {"question": "我最近想买什么东西?请简洁回答", "expected": "富士 mini12 粉色拍立得、投影仪"},
-]
-
-
-# ── 辅助函数 ───────────────────────────────────────────────────────────────
-
-
-def send_message(gateway_url, message, user_id, previous_messages=None):
- """通过 OpenClaw Responses API 发送消息。"""
- # OpenClaw Responses API 只接受单条消息作为输入,不接受历史消息数组
- input_data = message
- resp = requests.post(
- f"{gateway_url}/v1/responses",
- json={"model": "openclaw", "input": input_data, "user": user_id},
- timeout=300,
- )
- resp.raise_for_status()
- return resp.json()
-
-
-def extract_reply_text(data):
- """从 Responses API 响应中提取助手回复文本。"""
- for item in data.get("output", []):
- if item.get("type") == "message" and item.get("role") == "assistant":
- for part in item.get("content", []):
- if part.get("type") in ("text", "output_text"):
- return part.get("text", "")
- return "(无回复)"
-
-
-def render_reply(text):
- """用 rich 渲染助手回复。"""
- lines = text.split("\n")
- if len(lines) > 30:
- text = "\n".join(lines[:30]) + f"\n\n... (共 {len(lines)} 行,已截断)"
- console.print(Panel(Markdown(text), title="[green]回复[/green]", border_style="green"))
-
-
-# ── 主流程 ─────────────────────────────────────────────────────────────────
-
-
-def run_chat(gateway_url, delay):
- console.print()
- console.rule(f"[bold]Phase 1: 多轮对话 — {DISPLAY_NAME} ({len(CHAT_MESSAGES)} 轮)[/bold]")
- console.print(f"[yellow]用户:[/yellow] {DISPLAY_NAME} (user={USER_ID})")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
- console.print(f"[yellow]轮次间隔:[/yellow] {delay}s")
-
- total = len(CHAT_MESSAGES)
- ok = fail = 0
- messages = [] # 维护对话历史
-
- for i, msg in enumerate(CHAT_MESSAGES, 1):
- console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
- console.print(
- Panel(msg, title=f"[bold cyan]用户 [{i}/{total}][/bold cyan]", border_style="cyan")
- )
- try:
- data = send_message(gateway_url, msg, USER_ID, messages if messages else None)
- reply = extract_reply_text(data)
- messages.append({"role": "user", "content": msg})
- messages.append({"role": "assistant", "content": reply})
- render_reply(reply)
- ok += 1
- except Exception as e:
- console.print(f"[red][ERROR][/red] {e}")
- fail += 1
- if i < total:
- time.sleep(delay)
-
- console.print()
- console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
-
- wait = max(delay * 2, 5)
- console.print(f"[yellow]等待 {wait:.0f}s 让记忆抽取完成...[/yellow]")
- time.sleep(wait)
-
-
-def run_verify(gateway_url, delay):
- console.print()
- console.rule(
- f"[bold]Phase 2: 验证记忆召回 — {DISPLAY_NAME} 新 Session ({len(VERIFY_QUESTIONS)} 轮)[/bold]"
- )
-
- # 用不同的 user 后缀确保 Gateway 派生出新 session
- verify_user = f"{USER_ID}-verify"
- console.print(f"[yellow]验证用户:[/yellow] {verify_user} (新 session,不带对话历史)")
-
- results = []
- total = len(VERIFY_QUESTIONS)
-
- for i, item in enumerate(VERIFY_QUESTIONS, 1):
- q, expected = item["question"], item["expected"]
- console.rule(f"[dim]{i}/{total}[/dim]", style="dim")
- console.print(
- Panel(
- f"{q}\n[dim]期望召回: {expected}[/dim]",
- title=f"[bold cyan]验证 [{i}/{total}][/bold cyan]",
- border_style="cyan",
- )
- )
-
- try:
- # 每题独立发送,不带历史 → 回答正确 = 记忆召回生效
- data = send_message(gateway_url, q, verify_user)
- reply = extract_reply_text(data)
- render_reply(reply)
- results.append({"expected": expected, "success": True})
- except Exception as e:
- console.print(f"[red][ERROR][/red] {e}")
- results.append({"expected": expected, "success": False})
-
- if i < total:
- time.sleep(delay)
-
- # 汇总表格
- console.print()
- console.rule(f"[bold]结果汇总 — {DISPLAY_NAME}[/bold]")
-
- table = Table(title=f"记忆召回验证 — {DISPLAY_NAME} ({USER_ID})")
- table.add_column("#", style="bold", width=4)
- table.add_column("状态", width=6)
- table.add_column("期望召回", style="dim")
-
- for i, r in enumerate(results, 1):
- status = "[green]OK[/green]" if r.get("success") else "[red]FAIL[/red]"
- table.add_row(str(i), status, r["expected"])
-
- console.print(table)
-
- ok = sum(1 for r in results if r.get("success"))
- console.print(f"\n[yellow]成功: {ok}/{total}[/yellow]")
- console.print(
- "[yellow]验证方式: 每个问题在新 session 中独立发送(无对话历史),回答正确说明 before_prompt_build 阶段成功召回了记忆。[/yellow]"
- )
-
-
-# ── 入口 ───────────────────────────────────────────────────────────────────
-
-
-def main():
- parser = argparse.ArgumentParser(description=f"Memory 演示 — {DISPLAY_NAME}")
- parser.add_argument(
- "--gateway",
- default=DEFAULT_GATEWAY,
- help=f"OpenClaw Gateway 地址 (默认: {DEFAULT_GATEWAY})",
- )
- parser.add_argument(
- "--phase",
- choices=["all", "chat", "verify"],
- default="all",
- help="all=全部, chat=仅对话, verify=仅验证 (默认: all)",
- )
- parser.add_argument("--delay", type=float, default=3.0, help="轮次间等待秒数 (默认: 3)")
- args = parser.parse_args()
-
- gateway_url = args.gateway.rstrip("/")
- console.print(f"[bold]OpenClaw Plugin 演示 — {DISPLAY_NAME}[/bold]")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
-
- if args.phase in ("all", "chat"):
- run_chat(gateway_url, args.delay)
- if args.phase in ("all", "verify"):
- run_verify(gateway_url, args.delay)
-
- console.print("\n[yellow]演示完成。[/yellow]")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/openclaw-plugin/tests/test-memory-chain.py b/examples/openclaw-plugin/tests/test-memory-chain.py
deleted file mode 100644
index 0b114525d..000000000
--- a/examples/openclaw-plugin/tests/test-memory-chain.py
+++ /dev/null
@@ -1,934 +0,0 @@
-#!/usr/bin/env python3
-"""
-OpenClaw 记忆链路完整测试脚本
-
-验证 OpenViking 记忆插件重构后的端到端链路:
-1. afterTurn: 本轮消息无损写入 OpenViking session,sessionId 一致
-2. commit: 归档消息 + 提取长期记忆 + .meta.json 写入
-3. assemble: 同用户继续对话时, 从 latest_archive_overview + active messages 重组上下文
-4. assemble budget trimming: 小 token budget 下 latest_archive_overview 被裁剪
-5. sessionId 一致性: 整条链路使用统一的 sessionId (无 sessionKey)
-6. 新用户记忆召回: 验证 before_prompt_build auto-recall
-
-测试流程:
-Phase 1: 多轮对话 (12 轮) — afterTurn 写入
-Phase 2: afterTurn 验证 — 检查 OV session 内部状态
-Phase 3: Commit 验证 — 触发 commit, 检查归档结构
-Phase 4: Assemble 验证 — 同用户继续对话, 验证上下文重组
-Phase 5: SessionId 一致性验证
-Phase 6: 新用户记忆召回
-
-前提:
-- OpenViking 服务已启动 (默认 http://127.0.0.1:8000)
-- OpenClaw Gateway 已启动并配置了 OpenViking 插件
-
-用法:
- python test-memory-chain.py
- python test-memory-chain.py --gateway http://127.0.0.1:18790 --openviking http://127.0.0.1:8000
- python test-memory-chain.py --phase chat
- python test-memory-chain.py --phase afterTurn
- python test-memory-chain.py --phase commit
- python test-memory-chain.py --phase assemble
- python test-memory-chain.py --phase session-id
- python test-memory-chain.py --phase recall
- python test-memory-chain.py --verbose
-
-依赖:
- pip install requests rich
-"""
-
-import argparse
-import json
-import time
-import uuid
-from datetime import datetime
-from typing import Any
-
-import requests
-from rich.console import Console
-from rich.markdown import Markdown
-from rich.panel import Panel
-from rich.table import Table
-from rich.tree import Tree
-
-# ── 常量 ───────────────────────────────────────────────────────────────────
-
-USER_ID = f"test-chain-{uuid.uuid4().hex[:8]}"
-DISPLAY_NAME = "测试用户"
-DEFAULT_GATEWAY = "http://127.0.0.1:18790"
-DEFAULT_OPENVIKING = "http://127.0.0.1:8000"
-AGENT_ID = "openclaw"
-
-console = Console()
-
-# ── 测试结果收集 ──────────────────────────────────────────────────────────
-
-assertions: list[dict] = []
-
-
-def check(label: str, condition: bool, detail: str = ""):
- """记录一个断言结果。"""
- assertions.append({"label": label, "ok": condition, "detail": detail})
- icon = "[green]✓[/green]" if condition else "[red]✗[/red]"
- msg = f" {icon} {label}"
- if detail:
- msg += f" [dim]({detail})[/dim]"
- console.print(msg)
-
-
-# ── 对话数据 ──────────────────────────────────────────────────────────────
-
-CHAT_MESSAGES = [
- "你好,我是一个软件工程师,我叫张明,在一家科技公司工作。我主要负责后端服务开发,使用的技术栈是 Python 和 Go。最近我们在重构一个订单系统,遇到了不少挑战。",
- "关于订单系统的问题,主要是性能瓶颈。我们发现在高峰期,数据库连接池经常被耗尽。目前用的是 PostgreSQL,连接池大小设置的是100,但每秒峰值请求量有5000。你有什么建议吗?",
- "谢谢你的建议。我还想问一下,我们目前的缓存策略用的是 Redis,但缓存击穿的问题很严重。热点数据过期后,大量请求直接打到数据库。我们尝试过加互斥锁,但性能下降很多。",
- "对了,关于代码风格,我们团队更倾向于使用函数式编程的思想,尽量避免副作用。变量命名用 snake_case,文档用中文写。代码审查很严格,每个 PR 至少需要两人 review。",
- "说到工作流程,我们每天早上9点站会,周三下午技术分享会。我一般上午写代码,下午处理 code review 和会议。晚上如果不加班,会看看技术书籍或者写写博客。",
- "我最近在学习分布式系统的设计,正在看《数据密集型应用系统设计》这本书。之前看完了《深入理解计算机系统》,收获很大。你有什么好的分布式系统学习资料推荐吗?",
- "目前订单系统重构的进度大概完成了60%,还剩下支付模块和库存同步模块。支付模块比较复杂,需要对接多个支付渠道。我们打算用消息队列来解耦库存同步。",
- "消息队列我们在 Kafka 和 RabbitMQ 之间犹豫。Kafka 吞吐量高,但运维复杂;RabbitMQ 功能丰富,但性能稍差。我们的消息量大概每天1000万条,你觉得选哪个好?",
- "我们团队有8个人,3个后端、2个前端、1个测试、1个运维,还有1个产品经理。后端老王经验最丰富,遇到难题都找他。测试小李很细心,bug检出率很高。",
- "对了,跟我聊天的时候注意几点:我喜欢简洁直接的回答,不要太啰嗦;技术问题最好带代码示例;如果不确定的问题要说明,不要瞎编。谢谢!",
- "补充一下,我们的监控用的是 Prometheus + Grafana,日志用 ELK Stack。最近在考虑引入链路追踪,OpenTelemetry 看起来不错,但不知道跟现有系统集成麻不麻烦。",
- "昨天线上出了个诡异的 bug,某个接口偶发超时,但日志里看不出什么问题。后来发现是下游服务的连接数满了,但监控指标没配好,没报警。这种问题怎么预防比较好?",
-]
-
-# assemble 阶段: 同用户继续对话,用于验证 assemble 是否携带了摘要上下文
-ASSEMBLE_FOLLOWUP_MESSAGES = [
- {
- "question": "对了,我之前提到的订单系统重构进展到哪了?支付模块开始了吗?",
- "anchor_keywords": ["订单系统", "支付模块", "60%"],
- "hook": "assemble — latest_archive_overview 重组",
- },
- {
- "question": "我们团队消息队列最终选了什么?之前我跟你讨论过 Kafka 和 RabbitMQ 的取舍。",
- "anchor_keywords": ["Kafka", "RabbitMQ", "消息队列"],
- "hook": "assemble — latest_archive_overview 重组",
- },
-]
-
-# 新用户记忆召回
-RECALL_QUESTIONS = [
- {
- "question": "我是做什么工作的?用什么技术栈?请简洁回答",
- "expected_keywords": ["软件工程师", "Python", "Go"],
- },
- {
- "question": "我最近在做什么项目?遇到了什么技术挑战?请简洁回答",
- "expected_keywords": ["订单系统", "性能瓶颈", "缓存"],
- },
- {
- "question": "跟我聊天有什么注意事项?请简洁回答",
- "expected_keywords": ["简洁", "代码示例"],
- },
-]
-
-
-# ── Gateway / OpenViking API ─────────────────────────────────────────────
-
-
-def send_message(gateway_url: str, message: str, user_id: str) -> dict:
- """通过 OpenClaw Responses API 发送消息。"""
- resp = requests.post(
- f"{gateway_url}/v1/responses",
- json={"model": "openclaw", "input": message, "user": user_id},
- timeout=300,
- )
- resp.raise_for_status()
- return resp.json()
-
-
-def extract_reply_text(data: dict) -> str:
- """从 Responses API 响应中提取助手回复文本。"""
- for item in data.get("output", []):
- if item.get("type") == "message" and item.get("role") == "assistant":
- for part in item.get("content", []):
- if part.get("type") in ("text", "output_text"):
- return part.get("text", "")
- return "(无回复)"
-
-
-class OpenVikingInspector:
- """OpenViking 内部状态检查器。"""
-
- def __init__(self, base_url: str, api_key: str = "", agent_id: str = AGENT_ID):
- self.base_url = base_url.rstrip("/")
- self.api_key = api_key
- self.agent_id = agent_id
-
- def _headers(self) -> dict:
- h: dict[str, str] = {"Content-Type": "application/json"}
- if self.api_key:
- h["X-API-Key"] = self.api_key
- if self.agent_id:
- h["X-OpenViking-Actor-Peer"] = self.agent_id
- return h
-
- def _get(self, path: str, timeout: int = 10) -> dict | None:
- try:
- resp = requests.get(f"{self.base_url}{path}", headers=self._headers(), timeout=timeout)
- if resp.status_code == 200:
- data = resp.json()
- return data.get("result", data)
- return None
- except Exception as e:
- console.print(f"[dim]GET {path} 失败: {e}[/dim]")
- return None
-
- def _post(self, path: str, body: dict | None = None, timeout: int = 30) -> dict | None:
- try:
- resp = requests.post(
- f"{self.base_url}{path}",
- headers=self._headers(),
- json=body or {},
- timeout=timeout,
- )
- if resp.status_code == 200:
- data = resp.json()
- return data.get("result", data)
- return None
- except Exception as e:
- console.print(f"[dim]POST {path} 失败: {e}[/dim]")
- return None
-
- def health_check(self) -> bool:
- try:
- resp = requests.get(f"{self.base_url}/health", timeout=5)
- return resp.status_code == 200
- except Exception:
- return False
-
- def get_session(self, session_id: str) -> dict | None:
- return self._get(f"/api/v1/sessions/{session_id}")
-
- def get_session_messages(self, session_id: str) -> list | None:
- result = self._get(f"/api/v1/sessions/{session_id}/messages")
- if isinstance(result, list):
- return result
- if isinstance(result, dict):
- return result.get("messages", [])
- return None
-
- def get_session_context(self, session_id: str, token_budget: int = 128000) -> dict | None:
- return self._get(f"/api/v1/sessions/{session_id}/context?token_budget={token_budget}")
-
- def commit_session(self, session_id: str, wait: bool = True) -> dict | None:
- result = self._post(f"/api/v1/sessions/{session_id}/commit", timeout=120)
- if not result:
- return None
-
- if wait and result.get("task_id"):
- task_id = result["task_id"]
- deadline = time.time() + 120
- while time.time() < deadline:
- time.sleep(0.5)
- task = self._get(f"/api/v1/tasks/{task_id}")
- if not task:
- continue
- if task.get("status") == "completed":
- result["status"] = "completed"
- result["memories_extracted"] = task.get("result", {}).get(
- "memories_extracted", {}
- )
- return result
- if task.get("status") == "failed":
- result["status"] = "failed"
- result["error"] = task.get("error")
- return result
-
- return result
-
- def search_memories(
- self, query: str, target_uri: str = "viking://~/memories", limit: int = 10
- ) -> list:
- result = self._post(
- "/api/v1/search/find",
- {"query": query, "target_uri": target_uri, "limit": limit},
- )
- if isinstance(result, dict):
- return result.get("memories", [])
- return []
-
- def list_fs(self, uri: str) -> list:
- result = self._get(f"/api/v1/fs/ls?uri={uri}&output=original")
- return result if isinstance(result, list) else []
-
- def read_fs(self, uri: str) -> str | None:
- """读取 fs 中某个文件的内容。"""
- result = self._get(f"/api/v1/content/read?uri={uri}")
- if isinstance(result, str):
- return result
- if isinstance(result, dict):
- return result.get("content")
- return None
-
-
-# ── 渲染函数 ──────────────────────────────────────────────────────────────
-
-
-def render_reply(text: str, title: str = "回复"):
- lines = text.split("\n")
- if len(lines) > 25:
- text = "\n".join(lines[:25]) + f"\n\n... (共 {len(lines)} 行,已截断)"
- console.print(Panel(Markdown(text), title=f"[green]{title}[/green]", border_style="green"))
-
-
-def render_json(data: Any, title: str = "JSON"):
- console.print(
- Panel(json.dumps(data, indent=2, ensure_ascii=False, default=str)[:2000], title=title)
- )
-
-
-def render_session_info(info: dict, title: str = "Session 信息"):
- table = Table(title=title, show_header=True)
- table.add_column("属性", style="cyan")
- table.add_column("值", style="green")
- for key, value in info.items():
- if isinstance(value, (dict, list)):
- value = json.dumps(value, ensure_ascii=False)
- table.add_row(str(key), str(value)[:120])
- console.print(table)
-
-
-# ── Phase 1: 多轮对话 ────────────────────────────────────────────────────
-
-
-def run_phase_chat(gateway_url: str, user_id: str, delay: float, verbose: bool) -> tuple[int, int]:
- """Phase 1: 多轮对话 — 测试 afterTurn 写入。"""
- console.print()
- console.rule(f"[bold]Phase 1: 多轮对话 ({len(CHAT_MESSAGES)} 轮) — afterTurn 写入[/bold]")
- console.print(f"[yellow]用户ID:[/yellow] {user_id}")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
- console.print()
-
- total = len(CHAT_MESSAGES)
- ok = fail = 0
-
- for i, msg in enumerate(CHAT_MESSAGES, 1):
- console.rule(f"[dim]Turn {i}/{total}[/dim]", style="dim")
- console.print(
- Panel(
- msg[:200] + ("..." if len(msg) > 200 else ""),
- title=f"[bold cyan]用户 [{i}/{total}][/bold cyan]",
- border_style="cyan",
- )
- )
- try:
- data = send_message(gateway_url, msg, user_id)
- reply = extract_reply_text(data)
- render_reply(reply[:500] + ("..." if len(reply) > 500 else ""))
- ok += 1
- except Exception as e:
- console.print(f"[red][ERROR][/red] {e}")
- fail += 1
-
- if i < total:
- time.sleep(delay)
-
- console.print()
- console.print(f"[yellow]对话完成:[/yellow] {ok} 成功, {fail} 失败")
-
- wait = max(delay * 2, 5)
- console.print(f"[yellow]等待 {wait:.0f}s 让 afterTurn 处理完成...[/yellow]")
- time.sleep(wait)
-
- return ok, fail
-
-
-# ── Phase 2: afterTurn 验证 ──────────────────────────────────────────────
-
-
-def run_phase_after_turn(openviking_url: str, user_id: str, verbose: bool) -> bool:
- """Phase 2: afterTurn 验证 — 检查 OV session 内部状态确认消息已写入。"""
- console.print()
- console.rule("[bold]Phase 2: afterTurn 验证 — 检查 OV session 消息写入[/bold]")
- console.print()
- console.print("[dim]验证点:[/dim]")
- console.print("[dim]- afterTurn 应将每轮消息写入 OV session[/dim]")
- console.print("[dim]- session.message_count > 0[/dim]")
- console.print("[dim]- pending_tokens > 0 (消息尚未 commit)[/dim]")
- console.print("[dim]- sessionId 应为 OpenClaw 传入的 user_id[/dim]")
- console.print()
-
- inspector = OpenVikingInspector(openviking_url)
-
- # 2.1 健康检查
- console.print("[bold]2.1 OpenViking 健康检查[/bold]")
- healthy = inspector.health_check()
- check("OpenViking 服务可达", healthy)
- if not healthy:
- return False
-
- # 2.2 Session 存在且有消息
- console.print("\n[bold]2.2 Session 存在性 & 消息计数[/bold]")
- session_info = inspector.get_session(user_id)
- check("Session 存在", session_info is not None, f"session_id={user_id}")
-
- if not session_info:
- console.print("[red]Session 不存在,无法继续验证[/red]")
- return False
-
- if verbose:
- render_session_info(session_info, f"Session: {user_id}")
-
- msg_count = session_info.get("message_count", 0)
- check(
- "message_count > 0 (afterTurn 写入成功)",
- msg_count > 0,
- f"message_count={msg_count}",
- )
-
- # pending_tokens 表示尚未 commit 的 token 数
- pending = session_info.get("pending_tokens", 0)
- check(
- "pending_tokens > 0 (有待 commit 的内容)",
- pending > 0,
- f"pending_tokens={pending}",
- )
-
- # 2.3 检查消息内容: 至少部分对话内容能在 OV 消息中找到
- console.print("\n[bold]2.3 消息内容抽样校验[/bold]")
- messages = inspector.get_session_messages(user_id)
- if messages is not None:
- check("能获取到 session 消息列表", True, f"共 {len(messages)} 条消息")
-
- # 取第一条用户消息的特征文本做匹配
- sample_text = "张明"
- all_text = json.dumps(messages, ensure_ascii=False)
- check(
- f"消息内容包含特征文本「{sample_text}」",
- sample_text in all_text,
- "验证 afterTurn 写入的内容与发送一致",
- )
-
- sample_text_2 = "PostgreSQL"
- check(
- f"消息内容包含特征文本「{sample_text_2}」",
- sample_text_2 in all_text,
- "验证多轮消息写入",
- )
- else:
- check("能获取到 session 消息列表", False, "GET messages 返回 None")
-
- # 2.4 context 在 commit 前应返回 messages
- console.print("\n[bold]2.4 Commit 前 context[/bold]")
- ctx = inspector.get_session_context(user_id)
- if ctx:
- ctx_msg_count = len(ctx.get("messages", []))
- has_summary_archive = bool(ctx.get("latest_archive_overview"))
- check(
- "context 返回 messages > 0",
- ctx_msg_count > 0,
- f"messages={ctx_msg_count}",
- )
- check(
- "commit 前 latest_archive_overview 为空",
- not has_summary_archive,
- f"latest_archive_overview={ctx.get('latest_archive_overview')}",
- )
- if verbose and ctx.get("stats"):
- console.print(f" [dim]stats: {ctx['stats']}[/dim]")
- else:
- check("context 可调用", False, "返回 None")
-
- return True
-
-
-# ── Phase 3: Commit 验证 ─────────────────────────────────────────────────
-
-
-def run_phase_commit(openviking_url: str, user_id: str, verbose: bool) -> bool:
- """Phase 3: Commit 验证 — 触发 commit, 检查归档结构和记忆提取。"""
- console.print()
- console.rule("[bold]Phase 3: Commit 验证 — 触发 session.commit()[/bold]")
- console.print()
- console.print("[dim]验证点:[/dim]")
- console.print("[dim]- commit 返回 status=completed/accepted[/dim]")
- console.print("[dim]- 消息被归档 (archived=true)[/dim]")
- console.print("[dim]- 提取出记忆 (memories_extracted > 0)[/dim]")
- console.print("[dim]- 归档目录含 .overview.md 和 .meta.json[/dim]")
- console.print()
-
- inspector = OpenVikingInspector(openviking_url)
-
- # 3.1 执行 commit
- console.print("[bold]3.1 执行 session.commit()[/bold]")
- console.print("[dim]正在等待 commit 完成 (可能需要 1-2 分钟)...[/dim]")
-
- commit_result = inspector.commit_session(user_id, wait=True)
- check("commit 返回结果", commit_result is not None)
-
- if not commit_result:
- console.print("[red]Commit 失败,无法继续[/red]")
- return False
-
- if verbose:
- render_json(commit_result, "Commit 结果")
-
- status = commit_result.get("status", "unknown")
- check(
- "commit status 为 completed 或 accepted",
- status in ("completed", "accepted"),
- f"status={status}",
- )
-
- archived = commit_result.get("archived", False)
- check("archived=true (消息已归档)", archived is True, f"archived={archived}")
-
- memories = commit_result.get("memories_extracted", {})
- total_mem = sum(memories.values()) if memories else 0
- check(
- "memories_extracted > 0 (提取出记忆)",
- total_mem > 0,
- f"total={total_mem}, categories={memories}",
- )
-
- # 3.2 commit 后 session 状态
- console.print("\n[bold]3.2 Commit 后 session 状态[/bold]")
- post_session = inspector.get_session(user_id)
- if post_session:
- commit_count = post_session.get("commit_count", 0)
- check(
- "commit_count >= 1",
- commit_count >= 1,
- f"commit_count={commit_count}",
- )
-
- post_pending = post_session.get("pending_tokens", 0)
- # commit 后 pending_tokens 应该很低 (归档后清空了旧消息)
- console.print(f" [dim]commit 后 pending_tokens={post_pending}[/dim]")
-
- # 3.3 检查归档目录结构
- console.print("\n[bold]3.3 归档目录结构检查[/bold]")
- # 尝试用 context 来间接确认 latest_archive_overview 存在
- ctx_after = inspector.get_session_context(user_id)
- if ctx_after:
- has_summary_archive = bool(ctx_after.get("latest_archive_overview"))
- check(
- "commit 后 context 返回 latest_archive_overview",
- has_summary_archive,
- f"latest_archive_overview={ctx_after.get('latest_archive_overview')}",
- )
-
- if has_summary_archive:
- overview = ctx_after.get("latest_archive_overview", "")
- check(
- "latest_archive_overview 非空 (摘要已生成)",
- len(overview) > 10,
- f"overview 长度={len(overview)} chars",
- )
- if verbose:
- console.print(f" [dim]overview 前 200 字: {overview[:200]}...[/dim]")
- else:
- check("commit 后 context 可调用", False)
-
- # 3.4 检查 estimatedTokens 合理性
- if ctx_after:
- stats = ctx_after.get("stats", {})
- archive_tokens = stats.get("archiveTokens", 0)
- check(
- "archiveTokens > 0 (归档 token 计数合理)",
- archive_tokens > 0,
- f"archiveTokens={archive_tokens}",
- )
-
- return True
-
-
-# ── Phase 4: Assemble 验证 ───────────────────────────────────────────────
-
-
-def run_phase_assemble(
- gateway_url: str, openviking_url: str, user_id: str, delay: float, verbose: bool
-) -> bool:
- """Phase 4: Assemble 验证 — 同用户继续对话,验证上下文从 latest archive overview 重组。"""
- console.print()
- console.rule("[bold]Phase 4: Assemble 验证 — 同用户继续对话[/bold]")
- console.print()
- console.print("[dim]验证点:[/dim]")
- console.print(
- "[dim]- 同用户对话触发 assemble(): 从 OV latest_archive_overview + active messages 重组上下文[/dim]"
- )
- console.print("[dim]- 回复应能引用 Phase 1 中已被归档的信息[/dim]")
- console.print("[dim]- context 应返回 latest_archive_overview (证明 assemble 有数据源)[/dim]")
- console.print()
-
- inspector = OpenVikingInspector(openviking_url)
-
- # 4.1 确认 assemble 的数据源 (latest_archive_overview) 就绪
- console.print("[bold]4.1 确认 assemble 数据源[/bold]")
- ctx = inspector.get_session_context(user_id)
- if ctx:
- has_summary_archive = bool(ctx.get("latest_archive_overview"))
- check(
- "context 返回 latest_archive_overview",
- has_summary_archive,
- f"latest_archive_overview={ctx.get('latest_archive_overview')}",
- )
- else:
- check("context 可用", False)
- return False
-
- # 4.2 assemble budget trimming: 用极小 budget 验证裁剪
- console.print("\n[bold]4.2 Assemble budget trimming[/bold]")
- tiny_ctx = inspector.get_session_context(user_id, token_budget=1)
- if tiny_ctx:
- stats = tiny_ctx.get("stats", {})
- total_archives = stats.get("totalArchives", 0)
- included = stats.get("includedArchives", 0)
- dropped = stats.get("droppedArchives", 0)
- check(
- "budget=1 时 latest_archive_overview 被裁剪",
- included == 0 or dropped > 0,
- f"total={total_archives}, included={included}, dropped={dropped}",
- )
- active_tokens = stats.get("activeTokens", 0)
- console.print(
- f" [dim]activeTokens={active_tokens}, archiveTokens={stats.get('archiveTokens', 0)}[/dim]"
- )
- else:
- check("tiny budget context 可调用", False)
-
- # 4.3 同用户继续对话 — assemble 应重组归档上下文
- console.print("\n[bold]4.3 同用户继续对话 — 验证 assemble 重组归档内容[/bold]")
- console.print(f"[yellow]用户ID:[/yellow] {user_id} (同一用户,继续对话)")
- console.print()
-
- total = len(ASSEMBLE_FOLLOWUP_MESSAGES)
- for i, item in enumerate(ASSEMBLE_FOLLOWUP_MESSAGES, 1):
- q = item["question"]
- keywords = item["anchor_keywords"]
-
- console.rule(f"[dim]Assemble 验证 {i}/{total}[/dim]", style="dim")
- console.print(
- Panel(
- f"{q}\n\n[dim]锚点关键词: {', '.join(keywords)}[/dim]\n[dim]Hook: {item['hook']}[/dim]",
- title=f"[bold cyan]Assemble Q{i}[/bold cyan]",
- border_style="cyan",
- )
- )
-
- try:
- data = send_message(gateway_url, q, user_id)
- reply = extract_reply_text(data)
- render_reply(reply)
-
- reply_lower = reply.lower()
- hits = [kw for kw in keywords if kw.lower() in reply_lower]
- hit_rate = len(hits) / len(keywords) if keywords else 0
- check(
- f"Assemble Q{i}: 回复包含归档内容 (命中率 >= 50%)",
- hit_rate >= 0.5,
- f"命中={hits}, 未命中={[k for k in keywords if k not in hits]}, rate={hit_rate:.0%}",
- )
- except Exception as e:
- check(f"Assemble Q{i}: 发送成功", False, str(e))
-
- if i < total:
- time.sleep(delay)
-
- # 4.4 对话后验证 afterTurn 继续写入 (新消息进入 active messages)
- console.print("\n[bold]4.4 Assemble 后 afterTurn 继续写入[/bold]")
- time.sleep(3)
- post_ctx = inspector.get_session_context(user_id)
- if post_ctx:
- post_msg_count = len(post_ctx.get("messages", []))
- check(
- "继续对话后 active messages 增加",
- post_msg_count > 0,
- f"active messages={post_msg_count}",
- )
-
- return True
-
-
-# ── Phase 5: SessionId 一致性验证 ────────────────────────────────────────
-
-
-def run_phase_session_id(openviking_url: str, user_id: str, verbose: bool) -> bool:
- """Phase 5: SessionId 一致性验证 — 确认整条链路使用统一的 sessionId。"""
- console.print()
- console.rule("[bold]Phase 5: SessionId 一致性验证[/bold]")
- console.print()
- console.print("[dim]验证点:[/dim]")
- console.print("[dim]- 重构后 sessionId 统一为 OpenClaw 传入的 user_id[/dim]")
- console.print("[dim]- OV session_id == user_id (无 sessionKey 前缀/后缀)[/dim]")
- console.print("[dim]- context 用同一 sessionId 可查到数据[/dim]")
- console.print()
-
- inspector = OpenVikingInspector(openviking_url)
-
- # 5.1 session_id 就是 user_id
- console.print("[bold]5.1 SessionId == UserId[/bold]")
- session = inspector.get_session(user_id)
- check(
- f"OV session 以 user_id={user_id} 为 ID 可查到",
- session is not None,
- "sessionId 统一: 插件直接用 user_id 作为 OV session_id",
- )
-
- # 5.2 不存在以 sessionKey 变体为 ID 的 session
- console.print("\n[bold]5.2 无 sessionKey 残留[/bold]")
- # 如果旧代码有 sessionKey 逻辑, 可能会创建带前缀的 session
- stale_variants = [
- f"sk:{user_id}",
- f"sessionKey:{user_id}",
- f"key:{user_id}",
- ]
- for variant in stale_variants:
- stale = inspector.get_session(variant)
- is_absent = stale is None or stale.get("message_count", 0) == 0
- check(
- f"不存在残留 session「{variant}」",
- is_absent,
- "旧 sessionKey 映射应已移除" if is_absent else f"发现残留: {stale}",
- )
-
- # 5.3 context 用 user_id 能查到数据
- console.print("\n[bold]5.3 同一 sessionId 查询归档[/bold]")
- ctx = inspector.get_session_context(user_id)
- if ctx:
- has_data = bool(ctx.get("latest_archive_overview")) or len(ctx.get("messages", [])) > 0
- check(
- "context(user_id) 返回数据",
- has_data,
- f"latest_archive_overview={ctx.get('latest_archive_overview')}, messages={len(ctx.get('messages', []))}",
- )
- else:
- check("context(user_id) 可调用", False)
-
- # 5.4 验证 commit 也是用同一 sessionId (session 有 commit_count > 0)
- console.print("\n[bold]5.4 Commit 使用同一 sessionId[/bold]")
- if session:
- cc = session.get("commit_count", 0)
- check(
- "session(user_id) 有 commit 记录",
- cc > 0,
- f"commit_count={cc}, 说明 commit 也走 user_id 而非 sessionKey",
- )
-
- return True
-
-
-# ── Phase 6: 新用户记忆召回 ──────────────────────────────────────────────
-
-
-def run_phase_recall(gateway_url: str, user_id: str, delay: float, verbose: bool) -> list:
- """Phase 6: 新用户记忆召回 — 验证 before_prompt_build auto-recall。"""
- console.print()
- console.rule(f"[bold]Phase 6: 新用户记忆召回 ({len(RECALL_QUESTIONS)} 轮) — auto-recall[/bold]")
- console.print()
- console.print("[dim]验证点:[/dim]")
- console.print("[dim]- 新用户 (新 session) 发送问题[/dim]")
- console.print("[dim]- before_prompt_build 通过 memory search 注入相关记忆[/dim]")
- console.print("[dim]- 回复应包含 Phase 1 对话中的关键信息[/dim]")
- console.print()
-
- verify_user = f"{user_id}-recall-{uuid.uuid4().hex[:4]}"
- console.print(f"[yellow]验证用户:[/yellow] {verify_user} (新 session)")
- console.print()
-
- results = []
- total = len(RECALL_QUESTIONS)
-
- for i, item in enumerate(RECALL_QUESTIONS, 1):
- q = item["question"]
- expected = item["expected_keywords"]
-
- console.rule(f"[dim]Recall {i}/{total}[/dim]", style="dim")
- console.print(
- Panel(
- f"{q}\n\n[dim]期望关键词: {', '.join(expected)}[/dim]",
- title=f"[bold cyan]Recall Q{i}[/bold cyan]",
- border_style="cyan",
- )
- )
-
- try:
- data = send_message(gateway_url, q, verify_user)
- reply = extract_reply_text(data)
- render_reply(reply)
-
- reply_lower = reply.lower()
- hits = [kw for kw in expected if kw.lower() in reply_lower]
- hit_rate = len(hits) / len(expected) if expected else 0
- success = hit_rate >= 0.5
-
- check(
- f"Recall Q{i}: 关键词命中率 >= 50%",
- success,
- f"命中={hits}, rate={hit_rate:.0%}",
- )
- results.append({"question": q, "hits": hits, "hit_rate": hit_rate, "success": success})
- except Exception as e:
- check(f"Recall Q{i}: 发送成功", False, str(e))
- results.append({"question": q, "hits": [], "hit_rate": 0, "success": False})
-
- if i < total:
- time.sleep(delay)
-
- return results
-
-
-# ── 完整测试 ──────────────────────────────────────────────────────────────
-
-
-def run_full_test(gateway_url: str, openviking_url: str, user_id: str, delay: float, verbose: bool):
- console.print()
- console.print(
- Panel.fit(
- f"[bold]OpenClaw 记忆链路完整测试[/bold]\n\n"
- f"Gateway: {gateway_url}\n"
- f"OpenViking: {openviking_url}\n"
- f"User ID: {user_id}\n"
- f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
- title="测试信息",
- )
- )
-
- # Phase 1: Chat
- chat_ok, chat_fail = run_phase_chat(gateway_url, user_id, delay, verbose)
-
- # Phase 2: afterTurn
- run_phase_after_turn(openviking_url, user_id, verbose)
-
- # Phase 3: Commit
- run_phase_commit(openviking_url, user_id, verbose)
-
- console.print("\n[yellow]等待 10s 让记忆提取完成...[/yellow]")
- time.sleep(10)
-
- # Phase 4: Assemble (同用户继续)
- run_phase_assemble(gateway_url, openviking_url, user_id, delay, verbose)
-
- # Phase 5: SessionId 一致性
- run_phase_session_id(openviking_url, user_id, verbose)
-
- # Phase 6: 新用户召回
- run_phase_recall(gateway_url, user_id, delay, verbose)
-
- # ── 汇总报告 ──────────────────────────────────────────────────────────
- console.print()
- console.rule("[bold]测试报告[/bold]")
-
- passed = sum(1 for a in assertions if a["ok"])
- failed = sum(1 for a in assertions if not a["ok"])
- total = len(assertions)
-
- table = Table(title=f"断言结果: {passed}/{total} 通过")
- table.add_column("#", style="bold", width=4)
- table.add_column("状态", width=6)
- table.add_column("断言", max_width=60)
- table.add_column("详情", style="dim", max_width=50)
-
- for i, a in enumerate(assertions, 1):
- status = "[green]PASS[/green]" if a["ok"] else "[red]FAIL[/red]"
- table.add_row(str(i), status, a["label"][:60], (a.get("detail") or "")[:50])
-
- console.print(table)
-
- # 按阶段汇总
- tree = Tree(f"[bold]通过: {passed}/{total}, 失败: {failed}[/bold]")
- tree.add(f"Phase 1: 多轮对话 — {chat_ok} 成功 / {chat_fail} 失败")
-
- fail_list = [a for a in assertions if not a["ok"]]
- if fail_list:
- fail_branch = tree.add(f"[red]失败断言 ({len(fail_list)})[/red]")
- for a in fail_list:
- fail_branch.add(f"[red]✗[/red] {a['label']}")
-
- console.print(tree)
-
- if failed == 0:
- console.print("\n[green bold]全部通过!端到端链路验证成功。[/green bold]")
- else:
- console.print(f"\n[red bold]有 {failed} 个断言失败,请检查上方详情。[/red bold]")
-
-
-# ── 入口 ───────────────────────────────────────────────────────────────────
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="OpenClaw 记忆链路完整测试",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-示例:
- python test-memory-chain.py
- python test-memory-chain.py --gateway http://127.0.0.1:18790
- python test-memory-chain.py --phase chat
- python test-memory-chain.py --phase afterTurn --user-id test-chain-abc123
- python test-memory-chain.py --phase assemble --user-id test-chain-abc123
- python test-memory-chain.py --verbose
- """,
- )
- parser.add_argument(
- "--gateway",
- default=DEFAULT_GATEWAY,
- help=f"OpenClaw Gateway 地址 (默认: {DEFAULT_GATEWAY})",
- )
- parser.add_argument(
- "--openviking",
- default=DEFAULT_OPENVIKING,
- help=f"OpenViking 服务地址 (默认: {DEFAULT_OPENVIKING})",
- )
- parser.add_argument(
- "--user-id",
- default=USER_ID,
- help="测试用户ID (默认: 随机生成)",
- )
- parser.add_argument(
- "--phase",
- choices=["all", "chat", "afterTurn", "commit", "assemble", "session-id", "recall"],
- default="all",
- help="运行阶段 (默认: all)",
- )
- parser.add_argument(
- "--delay",
- type=float,
- default=2.0,
- help="轮次间等待秒数 (默认: 2)",
- )
- parser.add_argument(
- "--verbose",
- "-v",
- action="store_true",
- help="详细输出",
- )
- args = parser.parse_args()
-
- gateway_url = args.gateway.rstrip("/")
- openviking_url = args.openviking.rstrip("/")
- user_id = args.user_id
-
- console.print("[bold]OpenClaw 记忆链路测试[/bold]")
- console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")
- console.print(f"[yellow]OpenViking:[/yellow] {openviking_url}")
- console.print(f"[yellow]User ID:[/yellow] {user_id}")
-
- if args.phase == "all":
- run_full_test(gateway_url, openviking_url, user_id, args.delay, args.verbose)
- elif args.phase == "chat":
- run_phase_chat(gateway_url, user_id, args.delay, args.verbose)
- elif args.phase == "afterTurn":
- run_phase_after_turn(openviking_url, user_id, args.verbose)
- elif args.phase == "commit":
- run_phase_commit(openviking_url, user_id, args.verbose)
- elif args.phase == "assemble":
- run_phase_assemble(gateway_url, openviking_url, user_id, args.delay, args.verbose)
- elif args.phase == "session-id":
- run_phase_session_id(openviking_url, user_id, args.verbose)
- elif args.phase == "recall":
- run_phase_recall(gateway_url, user_id, args.delay, args.verbose)
-
- # 打印最终断言统计
- if assertions:
- passed = sum(1 for a in assertions if a["ok"])
- total = len(assertions)
- console.print(f"\n[yellow]断言统计: {passed}/{total} 通过[/yellow]")
-
- console.print("\n[yellow]测试结束。[/yellow]")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/openclaw-plugin/tests/test-tool-capture.py b/examples/openclaw-plugin/tests/test-tool-capture.py
deleted file mode 100644
index dc3b0b627..000000000
--- a/examples/openclaw-plugin/tests/test-tool-capture.py
+++ /dev/null
@@ -1,444 +0,0 @@
-#!/usr/bin/env python3
-"""
-测试 extractNewTurnTexts 改动:验证 toolUse/toolResult 内容是否被正确捕获到 OV session 中。
-
-测试策略:
-1. 发送一条消息,触发模型使用工具(如 native_tool / code_execution)
-2. 等待 afterTurn 完成
-3. 从 OV session 中读取已存储的消息
-4. 断言存储的消息中包含 toolUse 和 toolResult 相关内容
-
-用法:
- python test-tool-capture.py
- python test-tool-capture.py --verbose
- python test-tool-capture.py --gateway http://127.0.0.1:18789 --openviking http://127.0.0.1:1933
-
-依赖:
- pip install requests rich
-"""
-
-import argparse
-import json
-import re
-import time
-import uuid
-from datetime import datetime
-
-import requests
-from rich.console import Console
-from rich.panel import Panel
-from rich.table import Table
-
-# ── 常量 ──────────────────────────────────────────────────────────────────
-
-GATEWAY_URL = "http://127.0.0.1:18789"
-OPENVIKING_URL = "http://127.0.0.1:1933"
-AGENT_ID = "openclaw"
-
-console = Console()
-assertions: list[dict] = []
-
-
-def check(label: str, condition: bool, detail: str = ""):
- assertions.append({"label": label, "ok": condition, "detail": detail})
- icon = "[green]✓[/green]" if condition else "[red]✗[/red]"
- msg = f" {icon} {label}"
- if detail:
- msg += f" [dim]({detail})[/dim]"
- console.print(msg)
-
-
-def load_gateway_token() -> str:
- """从 openclaw.json 读取 gateway auth token。"""
- try:
- import pathlib
-
- cfg_path = pathlib.Path.home() / ".openclaw" / "openclaw.json"
- cfg = json.loads(cfg_path.read_text())
- return cfg.get("gateway", {}).get("auth", {}).get("token", "")
- except Exception:
- return ""
-
-
-# ── API helpers ──────────────────────────────────────────────────────────
-
-
-def send_message(gateway_url: str, message: str, user_id: str, token: str) -> dict:
- """通过 OpenClaw Responses API 发送消息。"""
- headers = {"Content-Type": "application/json"}
- if token:
- headers["Authorization"] = f"Bearer {token}"
- resp = requests.post(
- f"{gateway_url}/v1/responses",
- headers=headers,
- json={"model": "openclaw", "input": message, "user": user_id},
- timeout=300,
- )
- resp.raise_for_status()
- return resp.json()
-
-
-def extract_reply_text(data: dict) -> str:
- for item in data.get("output", []):
- if item.get("type") == "message" and item.get("role") == "assistant":
- for part in item.get("content", []):
- if part.get("type") in ("text", "output_text"):
- return part.get("text", "")
- return "(无回复)"
-
-
-def has_tool_use_in_output(data: dict) -> bool:
- """检查 Responses API 返回中是否有 tool_use / function_call。"""
- for item in data.get("output", []):
- item_type = item.get("type", "")
- if item_type in ("function_call", "tool_use", "computer_call"):
- return True
- if item.get("role") == "assistant":
- for part in item.get("content", []):
- if part.get("type") in ("tool_use", "toolUse"):
- return True
- return False
-
-
-class OVInspector:
- def __init__(self, base_url: str, agent_id: str = AGENT_ID):
- self.base_url = base_url.rstrip("/")
- self.agent_id = agent_id
-
- def _headers(self) -> dict:
- h: dict[str, str] = {"Content-Type": "application/json"}
- if self.agent_id:
- h["X-OpenViking-Actor-Peer"] = self.agent_id
- return h
-
- def _get(self, path: str, timeout: int = 10):
- try:
- resp = requests.get(f"{self.base_url}{path}", headers=self._headers(), timeout=timeout)
- if resp.status_code == 200:
- data = resp.json()
- return data.get("result", data)
- return None
- except Exception as e:
- console.print(f"[dim]GET {path} 失败: {e}[/dim]")
- return None
-
- def list_sessions(self) -> list:
- result = self._get("/api/v1/sessions")
- if isinstance(result, list):
- return result
- return []
-
- def get_session(self, session_id: str):
- return self._get(f"/api/v1/sessions/{session_id}")
-
- def get_session_context(self, session_id: str, token_budget: int = 128000):
- return self._get(f"/api/v1/sessions/{session_id}/context?token_budget={token_budget}")
-
- def find_latest_session(self) -> str | None:
- """找到最近更新的 session ID(gateway 内部使用 UUID,非 user_id)。
- 通过检查每个 session 的 updated_at 来找到最新的。"""
- sessions = self.list_sessions()
- real_sessions = [
- s
- for s in sessions
- if isinstance(s, dict) and not s.get("session_id", "").startswith("memory-store-")
- ]
- if not real_sessions:
- return None
-
- best_id = None
- best_time = ""
- for s in real_sessions:
- sid = s.get("session_id", "")
- if not sid:
- continue
- detail = self.get_session(sid)
- if not detail:
- continue
- updated = detail.get("updated_at", "")
- if updated > best_time:
- best_time = updated
- best_id = sid
-
- return best_id or real_sessions[-1].get("session_id")
-
-
-# ── 核心测试 ──────────────────────────────────────────────────────────────
-
-
-TOOL_TRIGGER_MESSAGES = [
- {
- "input": "请帮我计算 factorial(7) 的结果,用代码算一下",
- "description": "触发代码执行工具",
- "expect_keywords": ["5040", "factorial"],
- },
- {
- "input": "我叫李明,记住我是一名数据工程师,擅长 Spark 和 Flink,偏好用 Scala 写代码。请同时告诉我今天星期几。",
- "description": "信息存储 + 可能触发工具",
- "expect_keywords": ["李明", "数据工程师"],
- },
- {
- "input": "帮我写一段 Python 代码计算斐波那契数列前10个数,并运行它告诉我结果",
- "description": "触发代码执行并返回结果",
- "expect_keywords": ["斐波那契", "fibonacci"],
- },
-]
-
-
-def run_test(
- gateway_url: str,
- openviking_url: str,
- user_id: str,
- delay: float,
- verbose: bool,
-):
- token = load_gateway_token()
- inspector = OVInspector(openviking_url)
-
- console.print(
- Panel(
- f"[bold]Tool Capture 测试[/bold]\n\n"
- f"Gateway: {gateway_url}\n"
- f"OpenViking: {openviking_url}\n"
- f"User ID: {user_id}\n"
- f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
- title="测试信息",
- )
- )
-
- # ── Phase 1: 发送消息 ────────────────────────────────────────────────
-
- console.rule("[bold]Phase 1: 发送消息触发 afterTurn[/bold]")
-
- gateway_responses = []
- for i, msg_cfg in enumerate(TOOL_TRIGGER_MESSAGES):
- console.print(
- f"\n[cyan]消息 {i + 1}/{len(TOOL_TRIGGER_MESSAGES)}:[/cyan] {msg_cfg['description']}"
- )
- console.print(f" [dim]> {msg_cfg['input'][:80]}...[/dim]")
-
- try:
- data = send_message(gateway_url, msg_cfg["input"], user_id, token)
- reply = extract_reply_text(data)
- has_tool = has_tool_use_in_output(data)
-
- console.print(f" [green]回复:[/green] {reply[:120]}...")
- if has_tool:
- console.print(" [yellow]检测到 tool_use 在响应中[/yellow]")
-
- if verbose:
- console.print(
- f" [dim]完整响应: {json.dumps(data, ensure_ascii=False)[:500]}[/dim]"
- )
-
- gateway_responses.append(
- {
- "index": i,
- "msg": msg_cfg,
- "response": data,
- "reply": reply,
- "has_tool": has_tool,
- }
- )
-
- check(
- f"消息 {i + 1} 发送成功",
- True,
- f"reply_len={len(reply)}",
- )
- except Exception as e:
- console.print(f" [red]发送失败: {e}[/red]")
- check(f"消息 {i + 1} 发送成功", False, str(e))
-
- if i < len(TOOL_TRIGGER_MESSAGES) - 1:
- time.sleep(delay)
-
- # ── Phase 2: 等待 afterTurn 写入 ───────────────────────────────────
-
- console.rule("[bold]Phase 2: 检查 OV session 中的存储内容[/bold]")
- console.print("[yellow]等待 afterTurn 写入 OV session...[/yellow]")
- time.sleep(8)
-
- # Gateway 使用内部 UUID 作为 session ID,需要从 OV 列表中找到最新的
- ov_session_id = inspector.find_latest_session()
- if not ov_session_id:
- console.print("[red] OV 中没有找到任何 session[/red]")
- check("OV session 存在", False, "no sessions found")
- print_summary()
- return
-
- console.print(f" [cyan]OV session ID: {ov_session_id}[/cyan]")
-
- session_info = inspector.get_session(ov_session_id)
- if session_info:
- msg_count = session_info.get("message_count", "?")
- console.print(f" Session found: message_count={msg_count}")
- check("OV session 存在", True, f"id={ov_session_id[:16]}...")
- else:
- console.print("[red] OV session 详情获取失败[/red]")
- check("OV session 存在", False, "session detail failed")
- print_summary()
- return
-
- # 通过 context API 获取消息(包含 parts)
- ctx = inspector.get_session_context(ov_session_id)
- messages = ctx.get("messages", []) if ctx else []
- if not messages:
- console.print("[red] OV session 消息为空[/red]")
- check("OV session 有消息", False, "context messages empty")
- print_summary()
- return
-
- console.print(f" [green]OV session 消息数: {len(messages)}[/green]")
- check("OV session 有消息", len(messages) > 0, f"count={len(messages)}")
-
- # ── Phase 3: 分析存储的内容是否包含 tool 信息 ──────────────────────
-
- console.rule("[bold]Phase 3: 验证 toolUse/toolResult 内容被捕获[/bold]")
-
- all_stored_text = ""
- for msg in messages:
- if not isinstance(msg, dict):
- continue
- parts = msg.get("parts", [])
- for part in parts:
- if isinstance(part, dict) and part.get("type") == "text":
- all_stored_text += (part.get("text", "") or "") + "\n"
-
- if verbose:
- console.print(
- Panel(
- all_stored_text[:3000] + ("..." if len(all_stored_text) > 3000 else ""),
- title="OV 存储的全部文本",
- )
- )
-
- # 检查 toolUse 标记是否存在
- has_tool_use_marker = bool(re.search(r"\[toolUse:", all_stored_text, re.IGNORECASE))
- check(
- "存储文本包含 [toolUse:] 标记",
- has_tool_use_marker,
- f"found={has_tool_use_marker}",
- )
-
- # 检查 toolResult 标记是否存在
- has_tool_result_marker = bool(re.search(r"result\]:", all_stored_text, re.IGNORECASE))
- check(
- "存储文本包含 tool result 标记",
- has_tool_result_marker,
- f"found={has_tool_result_marker}",
- )
-
- # 检查 assistant 标记
- has_assistant = bool(re.search(r"\[assistant\]:", all_stored_text, re.IGNORECASE))
- check(
- "存储文本包含 [assistant] 标记",
- has_assistant,
- f"found={has_assistant}",
- )
-
- # 检查 user 标记
- has_user = bool(re.search(r"\[user\]:", all_stored_text, re.IGNORECASE))
- check(
- "存储文本包含 [user] 标记",
- has_user,
- f"found={has_user}",
- )
-
- # 检查关键内容是否保留
- for msg_cfg in TOOL_TRIGGER_MESSAGES:
- for kw in msg_cfg.get("expect_keywords", []):
- found = kw.lower() in all_stored_text.lower()
- check(
- f"存储文本包含关键词: {kw}",
- found,
- f"keyword='{kw}' found={found}",
- )
-
- # ── Phase 4: 对比改动前后的行为 ──────────────────────────────────────
-
- console.rule("[bold]Phase 4: 改动前后对比分析[/bold]")
-
- # 旧版本:只有 [user] 和 [assistant] 的文本
- # 新版本:应该额外包含 [toolUse: xxx] 和 [xxx result] 的内容
- tool_related_lines = []
- for line in all_stored_text.split("\n"):
- stripped = line.strip()
- if re.search(r"\[toolUse:", stripped, re.IGNORECASE):
- tool_related_lines.append(("toolUse", stripped[:150]))
- elif re.search(r"result\]:", stripped, re.IGNORECASE):
- tool_related_lines.append(("toolResult", stripped[:150]))
-
- if tool_related_lines:
- table = Table(title="捕获到的 Tool 相关内容")
- table.add_column("类型", style="cyan", width=12)
- table.add_column("内容预览", max_width=120)
- for kind, preview in tool_related_lines:
- table.add_row(kind, preview)
- console.print(table)
-
- check(
- "tool 相关行数 > 0(新逻辑生效)",
- len(tool_related_lines) > 0,
- f"tool_lines={len(tool_related_lines)}",
- )
-
- # ── 汇总 ─────────────────────────────────────────────────────────────
-
- print_summary()
-
-
-def print_summary():
- console.print()
- console.rule("[bold]测试汇总[/bold]")
-
- passed = sum(1 for a in assertions if a["ok"])
- failed = sum(1 for a in assertions if not a["ok"])
- total = len(assertions)
-
- table = Table(title=f"断言结果: {passed}/{total} 通过")
- table.add_column("#", style="bold", width=4)
- table.add_column("状态", width=6)
- table.add_column("断言", max_width=60)
- table.add_column("详情", style="dim", max_width=50)
-
- for i, a in enumerate(assertions, 1):
- status = "[green]PASS[/green]" if a["ok"] else "[red]FAIL[/red]"
- table.add_row(str(i), status, a["label"][:60], (a.get("detail") or "")[:50])
-
- console.print(table)
-
- if failed == 0:
- console.print("\n[green bold]全部通过!toolUse/toolResult 捕获验证成功。[/green bold]")
- else:
- console.print(f"\n[red bold]有 {failed} 个断言失败。[/red bold]")
- console.print(
- "[yellow]注: 如果模型没有调用工具,toolUse/toolResult 标记可能不存在 — 这不代表代码有 bug。[/yellow]"
- )
- console.print("[yellow]可以在 gateway 日志中确认 afterTurn 的存储内容。[/yellow]")
-
-
-# ── 入口 ──────────────────────────────────────────────────────────────────
-
-
-def main():
- parser = argparse.ArgumentParser(description="测试 toolUse/toolResult 捕获")
- parser.add_argument("--gateway", default=GATEWAY_URL, help="Gateway 地址")
- parser.add_argument("--openviking", default=OPENVIKING_URL, help="OpenViking 地址")
- parser.add_argument("--delay", type=float, default=3.0, help="消息间延迟秒数")
- parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
- args = parser.parse_args()
-
- user_id = f"test-tool-{uuid.uuid4().hex[:8]}"
-
- run_test(
- gateway_url=args.gateway.rstrip("/"),
- openviking_url=args.openviking.rstrip("/"),
- user_id=user_id,
- delay=args.delay,
- verbose=args.verbose,
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/README.md b/examples/openclaw-plugin/tests/toolresult_compression_tests/README.md
deleted file mode 100644
index 7fba0ddb3..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/README.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Tool Result Compression Bench Tests
-
-这个目录放的是用于手工回归 OpenClaw + OpenViking 工具结果压缩链路的轻量 benchmark 脚本和测试用例。
-
-## 前置依赖
-
-运行前需要先把下面 3 个仓库下载到 OpenClaw workspace 中,并保证路径和测试用例里的 prompt 一致:
-
-| 仓库 | 用例 | 期望路径 |
-| --- | --- | --- |
-| Kubernetes | `test1.json`, `test2.json` | `/root/.openclaw/workspace/kubernetes` |
-| OpenViking | `test3.json`, `test4.json` | `/root/.openclaw/workspace/OpenViking` |
-| openclaw | `test5.json` | `/root/.openclaw/workspace/openclaw` |
-
-如果本机 workspace 根目录不同,可以创建软链接到上述路径,或只在本地修改对应 `test*.json` 中的路径后再运行。
-
-同时需要确保:
-
-- `openclaw` 命令可用,且已安装/启用当前 OpenViking openclaw plugin。
-- OpenViking 服务和 OpenClaw 配置已指向同一个可用的 OV 实例。
-- 运行账号能读取 workspace 中的 3 个仓库。
-
-## 运行单个用例
-
-在本目录执行:
-
-```bash
-node run-sccs-bench.mjs run \
- --prompts test1.json \
- --label test1 \
- --session-id "bench-quick-$(date +%s)-ov-01-test1" \
- --timeout-sec 600 \
- --out-dir "bench-results-quick/test1-ov-01"
-```
-
-可将 `test1.json` 替换为 `test2.json` 到 `test5.json`。
-
-## 批量运行示例
-
-下面是一个可复制的最小 wrapper。将占位路径替换为当前机器上的 OV session 存储目录;如果只有一个存储目录,保留一个即可。
-
-```bash
-#!/bin/bash
-set -euo pipefail
-
-cd "<OpenViking>/examples/openclaw-plugin/tests/toolresult_compression_tests"
-
-OUT_ROOT="bench-results-quick"
-OV_SESSION_DIR_A="<ov-session-store-dir-a>"
-OV_SESSION_DIR_B="<ov-session-store-dir-b>"
-OPENCLAW_STATE_DIR="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
-
-run_test() {
- local test_name="$1"
- local mode="$2"
- local i="$3"
-
- rm -rf "${OV_SESSION_DIR_A:?}/"*
- rm -rf "${OV_SESSION_DIR_B:?}/"*
-
- node run-sccs-bench.mjs run \
- --prompts "${test_name}.json" \
- --label "$test_name" \
- --session-id "bench-quick-$(date +%s)-${mode}-${i}-${test_name}" \
- --timeout-sec 600 \
- --out-dir "${OUT_ROOT}/${test_name}-${mode}-$(printf '%02d' "$i")"
-
- rm -rf "${OPENCLAW_STATE_DIR}/memory"
-}
-
-run_test "test1" ov 1
-```
-
-## 输出
-
-每次运行会在 `--out-dir` 下生成本轮的 JSON/CSV 报告和 OpenClaw session 产物。`bench-results-*` 目录是本地运行产物,不需要提交。
-
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/run-sccs-bench.mjs b/examples/openclaw-plugin/tests/toolresult_compression_tests/run-sccs-bench.mjs
deleted file mode 100644
index eafdfef3a..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/run-sccs-bench.mjs
+++ /dev/null
@@ -1,685 +0,0 @@
-#!/usr/bin/env node
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import process from "node:process";
-import { spawnSync } from "node:child_process";
-
-function fail(message) {
- console.error(`[sccs-bench] ${message}`);
- process.exit(1);
-}
-
-function nowIso() {
- return new Date().toISOString();
-}
-
-function asNumber(value) {
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
-}
-
-function numOrZero(value) {
- return asNumber(value) ?? 0;
-}
-
-function percentile(sortedValues, p) {
- if (!sortedValues.length) {
- return 0;
- }
- const rank = (p / 100) * (sortedValues.length - 1);
- const lo = Math.floor(rank);
- const hi = Math.ceil(rank);
- if (lo === hi) {
- return sortedValues[lo];
- }
- const weight = rank - lo;
- return sortedValues[lo] * (1 - weight) + sortedValues[hi] * weight;
-}
-
-function toCsv(rows, headers) {
- const escape = (value) => {
- const raw =
- value === undefined || value === null
- ? ""
- : typeof value === "string"
- ? value
- : JSON.stringify(value);
- if (/[",\n]/.test(raw)) {
- return `"${raw.replace(/"/g, "\"\"")}"`;
- }
- return raw;
- };
- const lines = [headers.join(",")];
- for (const row of rows) {
- lines.push(headers.map((h) => escape(row[h])).join(","));
- }
- return `${lines.join("\n")}\n`;
-}
-
-function parseArgs(argv) {
- const args = {
- cmd: "run",
- openclawBin: "openclaw",
- prompts: "",
- outDir: path.resolve(process.cwd(), "bench-results"),
- label: "run",
- agent: "main",
- to: "+15555550123",
- sessionId: `sccs-bench-${Date.now()}`,
- timeoutSec: 600,
- stateDir: process.env.OPENCLAW_STATE_DIR
- ? path.resolve(process.env.OPENCLAW_STATE_DIR)
- : path.join(os.homedir(), ".openclaw"),
- continueOnError: false,
- baseline: "",
- candidate: "",
- out: "",
- };
-
- const positional = [];
- for (let i = 0; i < argv.length; i += 1) {
- const token = argv[i];
- if (!token.startsWith("--")) {
- positional.push(token);
- continue;
- }
- const [key, maybeValue] = token.split("=", 2);
- const nextValue = maybeValue ?? argv[i + 1];
- const takeNext = maybeValue === undefined;
- const set = (field, valueRequired = true) => {
- if (valueRequired && (nextValue === undefined || nextValue.startsWith("--"))) {
- fail(`missing value for ${key}`);
- }
- if (takeNext && valueRequired) {
- i += 1;
- }
- args[field] = valueRequired ? nextValue : true;
- };
-
- switch (key) {
- case "--help":
- args.cmd = "help";
- break;
- case "--openclaw":
- set("openclawBin");
- break;
- case "--prompts":
- set("prompts");
- break;
- case "--out-dir":
- set("outDir");
- break;
- case "--label":
- set("label");
- break;
- case "--agent":
- set("agent");
- break;
- case "--to":
- set("to");
- break;
- case "--session-id":
- set("sessionId");
- break;
- case "--timeout-sec":
- set("timeoutSec");
- break;
- case "--state-dir":
- set("stateDir");
- break;
- case "--continue-on-error":
- set("continueOnError", false);
- break;
- case "--baseline":
- set("baseline");
- break;
- case "--candidate":
- set("candidate");
- break;
- case "--out":
- set("out");
- break;
- default:
- fail(`unknown flag: ${key}`);
- }
- }
-
- if (positional.length > 0) {
- args.cmd = positional[0];
- }
- args.outDir = path.resolve(args.outDir);
- args.stateDir = path.resolve(args.stateDir);
- args.timeoutSec = Number.parseInt(String(args.timeoutSec), 10);
- if (!Number.isFinite(args.timeoutSec) || args.timeoutSec <= 0) {
- fail("--timeout-sec must be a positive integer");
- }
- return args;
-}
-
-function loadPrompts(promptsPath) {
- if (!promptsPath) {
- fail("run mode requires --prompts");
- }
- const resolved = path.resolve(promptsPath);
- if (!fs.existsSync(resolved)) {
- fail(`prompts file not found: ${resolved}`);
- }
- const raw = fs.readFileSync(resolved, "utf8");
- let prompts = [];
- if (resolved.endsWith(".json")) {
- const parsed = JSON.parse(raw);
- if (!Array.isArray(parsed)) {
- fail("prompts JSON must be an array");
- }
- prompts = parsed.map((item, index) => {
- if (typeof item === "string") {
- return { id: `turn-${index + 1}`, prompt: item };
- }
- if (
- item &&
- typeof item === "object" &&
- typeof item.prompt === "string" &&
- item.prompt.trim()
- ) {
- return {
- id: typeof item.id === "string" && item.id.trim() ? item.id.trim() : `turn-${index + 1}`,
- prompt: item.prompt,
- };
- }
- fail(`invalid prompt entry at index ${index}`);
- });
- } else {
- prompts = raw
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter(Boolean)
- .map((line, index) => ({ id: `turn-${index + 1}`, prompt: line }));
- }
-
- if (prompts.length === 0) {
- fail("no prompts found");
- }
- return { prompts, path: resolved };
-}
-
-function loadSessionStore(stateDir, agentId) {
- const storePath = path.join(stateDir, "agents", agentId, "sessions", "sessions.json");
- if (!fs.existsSync(storePath)) {
- return { storePath, store: {} };
- }
- try {
- const parsed = JSON.parse(fs.readFileSync(storePath, "utf8"));
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- return { storePath, store: {} };
- }
- return { storePath, store: parsed };
- } catch {
- return { storePath, store: {} };
- }
-}
-
-function pickSessionEntryById(store, sessionId) {
- const matches = Object.entries(store)
- .filter(([, entry]) => entry)
- .map(([key, entry]) => ({ key, entry }));
- if (matches.length === 0) {
- return undefined;
- }
- matches.sort((a, b) => (asNumber(b.entry.updatedAt) ?? 0) - (asNumber(a.entry.updatedAt) ?? 0));
- return matches[0];
-}
-
-function extractUsageInfo(parsed) {
- const root = parsed && typeof parsed === "object" ? parsed : {};
- const result = root.result && typeof root.result === "object" ? root.result : null;
- const metaCandidate =
- (result?.meta && typeof result.meta === "object" ? result.meta : null) ||
- (root.meta && typeof root.meta === "object" ? root.meta : null);
- const agentMeta =
- metaCandidate?.agentMeta && typeof metaCandidate.agentMeta === "object"
- ? metaCandidate.agentMeta
- : null;
- const usage = agentMeta?.usage && typeof agentMeta.usage === "object" ? agentMeta.usage : null;
- const readNumber = (obj, keys) => {
- if (!obj || typeof obj !== "object") {
- return undefined;
- }
- for (const key of keys) {
- const value = asNumber(obj[key]);
- if (value !== undefined) {
- return value;
- }
- }
- return undefined;
- };
-
- const inputTokens = readNumber(usage, [
- "input",
- "inputTokens",
- "input_tokens",
- "promptTokens",
- "prompt_tokens",
- ]);
- const outputTokens = readNumber(usage, ["output", "outputTokens", "output_tokens", "completion_tokens"]);
- const cacheRead = readNumber(usage, ["cacheRead", "cache_read", "cache_read_input_tokens"]);
- const cacheWrite = readNumber(usage, ["cacheWrite", "cache_write", "cache_creation_input_tokens"]);
- const promptTokens =
- asNumber(agentMeta?.promptTokens) ??
- (inputTokens !== undefined || cacheRead !== undefined || cacheWrite !== undefined
- ? (inputTokens ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0)
- : undefined);
- const totalUsageTokens =
- readNumber(usage, ["total", "totalTokens", "total_tokens"]) ??
- (inputTokens !== undefined ||
- outputTokens !== undefined ||
- cacheRead !== undefined ||
- cacheWrite !== undefined
- ? (inputTokens ?? 0) + (outputTokens ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0)
- : undefined);
- const compactionCount = asNumber(agentMeta?.compactionCount);
- const sessionId =
- typeof agentMeta?.sessionId === "string" && agentMeta.sessionId.trim()
- ? agentMeta.sessionId.trim()
- : undefined;
-
- return {
- inputTokens,
- outputTokens,
- cacheRead,
- cacheWrite,
- promptTokens,
- totalUsageTokens,
- compactionCount,
- sessionId,
- };
-}
-
-function extractReplyInfo(resultPayload) {
- const payloads = Array.isArray(resultPayload?.payloads) ? resultPayload.payloads : [];
- const textParts = [];
- let mediaCount = 0;
- for (const payload of payloads) {
- if (payload && typeof payload.text === "string" && payload.text.trim()) {
- textParts.push(payload.text);
- }
- if (payload && Array.isArray(payload.mediaUrls)) {
- mediaCount += payload.mediaUrls.length;
- }
- if (payload && typeof payload.mediaUrl === "string" && payload.mediaUrl.trim()) {
- mediaCount += 1;
- }
- }
- const text = textParts.join("\n").trim();
- return {
- textChars: text.length,
- mediaCount,
- payloadCount: payloads.length,
- };
-}
-
-function computeSummary(rows) {
- const durations = rows.map((r) => r.durationMs).filter((v) => typeof v === "number").sort((a, b) => a - b);
- const sum = (field) => rows.reduce((acc, row) => acc + (numOrZero(row[field]) || 0), 0);
- const count = rows.length;
- const totals = {
- inputTokens: sum("inputTokens"),
- outputTokens: sum("outputTokens"),
- cacheRead: sum("cacheRead"),
- cacheWrite: sum("cacheWrite"),
- promptTokens: sum("promptTokens"),
- totalUsageTokens: sum("totalUsageTokens"),
- replyChars: sum("replyChars"),
- };
- const avg = (value) => (count > 0 ? value / count : 0);
- const promptBase = totals.inputTokens + totals.cacheRead + totals.cacheWrite;
- const cacheReadShare = promptBase > 0 ? totals.cacheRead / promptBase : 0;
- return {
- turns: count,
- totals,
- averages: {
- inputTokens: avg(totals.inputTokens),
- outputTokens: avg(totals.outputTokens),
- cacheRead: avg(totals.cacheRead),
- cacheWrite: avg(totals.cacheWrite),
- promptTokens: avg(totals.promptTokens),
- totalUsageTokens: avg(totals.totalUsageTokens),
- durationMs: avg(sum("durationMs")),
- replyChars: avg(totals.replyChars),
- },
- latencyMs: {
- p50: percentile(durations, 50),
- p90: percentile(durations, 90),
- max: durations.length ? durations[durations.length - 1] : 0,
- },
- cacheReadShare,
- compactionTriggeredTurns: rows.filter((r) => numOrZero(r.compactionCountDelta) > 0).length,
- };
-}
-
-function moveSessionJsonlFiles(stateDir, agentId, outDir, sessionStorePath) {
- const sessionsDir = path.join(stateDir, "agents", agentId, "sessions");
- if (!fs.existsSync(sessionsDir)) {
- return 0;
- }
- const names = fs.readdirSync(sessionsDir).filter((name) => name.endsWith(".jsonl"));
- if (names.length === 0) {
- return 0;
- }
- fs.mkdirSync(outDir, { recursive: true });
- let moved = 0;
- for (const name of names) {
- const source = path.join(sessionsDir, name);
- // const target = path.join(outDir, name);
- const target = sessionStorePath;
- try {
- fs.renameSync(source, target);
- moved += 1;
- } catch (err) {
- if (err && typeof err === "object" && "code" in err && err.code === "EXDEV") {
- fs.copyFileSync(source, target);
- fs.unlinkSync(source);
- moved += 1;
- } else {
- throw err;
- }
- }
- }
- return moved;
-}
-
-function runBench(args) {
- const loaded = loadPrompts(args.prompts);
- const startedAt = nowIso();
- const rows = [];
- let prevCompactionCount;
- let failures = 0;
- fs.mkdirSync(args.outDir, { recursive: true });
-
- console.log(`[sccs-bench] started at ${startedAt}`);
- console.log(`[sccs-bench] prompts: ${loaded.path} (${loaded.prompts.length} turns)`);
- console.log(`[sccs-bench] target: agent=${args.agent} to=${args.to} sessionId=${args.sessionId}`);
-
- for (let i = 0; i < loaded.prompts.length; i += 1) {
- const turn = loaded.prompts[i];
- const cmdArgs = [
- "agent",
- "--agent",
- String(args.agent),
- // "--to",
- // String(args.to),
- // "--session-id",
- // String(args.sessionId),
- "--timeout",
- String(args.timeoutSec),
- "--message",
- turn.prompt,
- "--json",
- ];
-
- const begin = Date.now();
- const result = spawnSync(String(args.openclawBin), cmdArgs, {
- encoding: "utf8",
- maxBuffer: 10 * 1024 * 1024,
- });
- const durationMs = Date.now() - begin;
-
- let parsed;
- let errorMessage = "";
- if (result.status !== 0) {
- errorMessage = `exit=${result.status} stderr=${(result.stderr || "").trim()}`;
- } else {
- try {
- parsed = JSON.parse((result.stdout || "").trim() || "{}");
- } catch (err) {
- errorMessage = `json parse failed: ${String(err)}`;
- }
- }
-
- const usageInfo = extractUsageInfo(parsed);
- console.log(`[sccs-bench] usageInfo: ${JSON.stringify(usageInfo)}`);
- const { storePath, store } = loadSessionStore(args.stateDir, args.agent);
- const match =
- pickSessionEntryById(store, usageInfo.sessionId ?? args.sessionId) ??
- pickSessionEntryById(store, args.sessionId);
- const entry = match?.entry ?? {};
-
- const inputTokens = usageInfo.inputTokens ?? numOrZero(entry.inputTokens);
- const outputTokens = usageInfo.outputTokens ?? numOrZero(entry.outputTokens);
- const cacheRead = usageInfo.cacheRead ?? numOrZero(entry.cacheRead);
- const cacheWrite = usageInfo.cacheWrite ?? numOrZero(entry.cacheWrite);
- const promptTokens = usageInfo.promptTokens ?? inputTokens + cacheRead + cacheWrite;
- const totalUsageTokens =
- usageInfo.totalUsageTokens ?? inputTokens + outputTokens + cacheRead + cacheWrite;
- const compactionCount = usageInfo.compactionCount ?? numOrZero(entry.compactionCount);
- const compactionCountDelta =
- prevCompactionCount === undefined ? 0 : Math.max(0, compactionCount - prevCompactionCount);
- prevCompactionCount = compactionCount;
- const replyInfo = extractReplyInfo(parsed?.result ?? parsed);
-
- const row = {
- turn: i + 1,
- turnId: turn.id,
- prompt: turn.prompt,
- status: parsed?.status ?? (errorMessage ? "error" : "unknown"),
- runId: parsed?.runId ?? "",
- durationMs,
- sessionStorePath: storePath,
- sessionKey: match?.key ?? "",
- sessionId: usageInfo.sessionId ?? args.sessionId,
- inputTokens,
- outputTokens,
- cacheRead,
- cacheWrite,
- promptTokens,
- totalUsageTokens,
- contextSnapshotTokens: asNumber(entry.totalTokens) ?? null,
- contextTokensLimit: asNumber(entry.contextTokens) ?? null,
- totalTokensFresh: entry.totalTokensFresh !== false,
- compactionCount,
- compactionCountDelta,
- replyChars: replyInfo.textChars,
- replyPayloadCount: replyInfo.payloadCount,
- replyMediaCount: replyInfo.mediaCount,
- error: errorMessage,
- };
- rows.push(row);
-
- const basic = `turn ${i + 1}/${loaded.prompts.length} status=${row.status} dur=${durationMs}ms in=${inputTokens} out=${outputTokens} cacheR=${cacheRead}`;
- if (errorMessage) {
- failures += 1;
- console.error(`[sccs-bench] ${basic} error=${errorMessage}`);
- if (!args.continueOnError) {
- break;
- }
- } else {
- console.log(`[sccs-bench] ${basic}`);
- }
- }
-
- const endedAt = nowIso();
- const summary = computeSummary(rows);
- const report = {
- metadata: {
- label: args.label,
- startedAt,
- endedAt,
- promptsPath: loaded.path,
- openclawBin: args.openclawBin,
- agent: args.agent,
- to: args.to,
- sessionId: args.sessionId,
- stateDir: args.stateDir,
- failures,
- turnsExecuted: rows.length,
- },
- summary,
- rows,
- };
-
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
- const baseName = `${args.label}-${stamp}`;
- const jsonPath = path.join(args.outDir, `${baseName}.json`);
- const csvPath = path.join(args.outDir, `${baseName}.csv`);
- const sessionStorePath = path.join(args.outDir, `${baseName}-sessions.json`);
-
- fs.writeFileSync(jsonPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
- const headers = [
- "turn",
- "turnId",
- "status",
- "runId",
- "durationMs",
- "inputTokens",
- "outputTokens",
- "cacheRead",
- "cacheWrite",
- "promptTokens",
- "totalUsageTokens",
- "contextSnapshotTokens",
- "contextTokensLimit",
- "totalTokensFresh",
- "compactionCount",
- "compactionCountDelta",
- "replyChars",
- "replyPayloadCount",
- "replyMediaCount",
- "sessionKey",
- "sessionId",
- "error",
- ];
- fs.writeFileSync(csvPath, toCsv(rows, headers), "utf8");
- const movedSessions = moveSessionJsonlFiles(args.stateDir, args.agent, args.outDir, sessionStorePath);
- if (movedSessions > 0) {
- console.log(`[sccs-bench] archived ${movedSessions} session jsonl file(s) to ${args.outDir}`);
- }
-
- console.log(`[sccs-bench] finished at ${endedAt}`);
- console.log(`[sccs-bench] report json: ${jsonPath}`);
- console.log(`[sccs-bench] report csv : ${csvPath}`);
- console.log(
- `[sccs-bench] totals: input=${summary.totals.inputTokens} output=${summary.totals.outputTokens} cacheRead=${summary.totals.cacheRead} cacheWrite=${summary.totals.cacheWrite} usageTotal=${summary.totals.totalUsageTokens}`,
- );
-}
-
-function ratioDiff(base, cand) {
- if (base === 0) {
- return null;
- }
- return (cand - base) / base;
-}
-
-function compareReports(args) {
- if (!args.baseline || !args.candidate) {
- fail("compare mode requires --baseline and --candidate");
- }
- const basePath = path.resolve(args.baseline);
- const candPath = path.resolve(args.candidate);
- if (!fs.existsSync(basePath) || !fs.existsSync(candPath)) {
- fail("baseline/candidate report file not found");
- }
- const base = JSON.parse(fs.readFileSync(basePath, "utf8"));
- const cand = JSON.parse(fs.readFileSync(candPath, "utf8"));
-
- const pick = (obj, pathExpr) =>
- pathExpr.split(".").reduce((acc, key) => (acc && key in acc ? acc[key] : undefined), obj);
- const metrics = [
- "summary.totals.inputTokens",
- "summary.totals.outputTokens",
- "summary.totals.cacheRead",
- "summary.totals.cacheWrite",
- "summary.totals.totalUsageTokens",
- "summary.averages.durationMs",
- "summary.latencyMs.p50",
- "summary.latencyMs.p90",
- "summary.compactionTriggeredTurns",
- ];
- const rows = metrics.map((name) => {
- const baseline = numOrZero(pick(base, name));
- const candidate = numOrZero(pick(cand, name));
- const diff = candidate - baseline;
- const pct = ratioDiff(baseline, candidate);
- return {
- metric: name,
- baseline,
- candidate,
- diff,
- diffPercent: pct,
- };
- });
-
- const report = {
- comparedAt: nowIso(),
- baseline: {
- path: basePath,
- label: base?.metadata?.label ?? "baseline",
- turns: base?.summary?.turns ?? 0,
- },
- candidate: {
- path: candPath,
- label: cand?.metadata?.label ?? "candidate",
- turns: cand?.summary?.turns ?? 0,
- },
- metrics: rows,
- };
-
- const outPath = args.out
- ? path.resolve(args.out)
- : path.join(
- path.dirname(candPath),
- `compare-${Date.now()}.json`,
- );
- fs.writeFileSync(outPath, `${JSON.stringify(report, null, 2)}\n`, "utf8");
-
- console.log(`[sccs-bench] compare report: ${outPath}`);
- for (const row of rows) {
- const pctText =
- row.diffPercent === null ? "n/a" : `${(row.diffPercent * 100).toFixed(2)}%`;
- console.log(
- `[sccs-bench] ${row.metric}: baseline=${row.baseline} candidate=${row.candidate} diff=${row.diff} (${pctText})`,
- );
- }
-}
-
-function printHelp() {
- console.log(`Usage:
- node bench/run-sccs-bench.mjs run \\
- --prompts bench/prompts-realistic-24.json \\
- --label baseline --agent main --to +15555550123 --session-id bench-baseline
-
- node bench/run-sccs-bench.mjs compare \\
- --baseline bench-results/baseline.json \\
- --candidate bench-results/sccs.json
-
-Run options:
- --openclaw <bin> openclaw binary path (default: openclaw)
- --prompts <file> prompts file (.json array or .txt line-by-line)
- --out-dir <dir> output directory (default: ./bench-results)
- --label <name> run label for output files
- --agent <id> agent id (default: main)
- --to <E.164> fixed sender/recipient for stable session key
- --session-id <id> fixed session id for this benchmark
- --timeout-sec <sec> agent timeout seconds (default: 600)
- --state-dir <dir> OpenClaw state dir (default: ~/.openclaw)
- --continue-on-error continue remaining turns on failures
-
-Compare options:
- --baseline <json> baseline report path
- --candidate <json> candidate report path
- --out <json> output path for compare report
-`);
-}
-
-const args = parseArgs(process.argv.slice(2));
-if (args.cmd === "help" || args.cmd === "--help" || args.cmd === "-h") {
- printHelp();
- process.exit(0);
-}
-if (args.cmd === "run") {
- runBench(args);
- process.exit(0);
-}
-if (args.cmd === "compare") {
- compareReports(args);
- process.exit(0);
-}
-fail(`unknown command: ${args.cmd}`);
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/test1.json b/examples/openclaw-plugin/tests/toolresult_compression_tests/test1.json
deleted file mode 100644
index bbd81af92..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/test1.json
+++ /dev/null
@@ -1,14 +0,0 @@
-[
- {
- "id": "t1-heavy-ingest",
- "prompt": "严格执行:你必须且只允许调用4次 read 工具,按以下顺序读取,不允许读取其他文件,不允许 exec/rg。\n1) /root/.openclaw/workspace/kubernetes/pkg/kubelet/kubelet.go\n2) /root/.openclaw/workspace/kubernetes/pkg/scheduler/schedule_one.go\n3) /root/.openclaw/workspace/kubernetes/staging/src/k8s.io/apiserver/pkg/endpoints/handlers/create.go\n4) /root/.openclaw/workspace/kubernetes/staging/src/k8s.io/apimachinery/pkg/util/version/version.go\n读取后输出固定格式:\nMODULE_MAP:\n- module: <name>\n file: <path>\n responsibilities: [3条]\n key_functions: [3个]\nCROSS_MODULE_RISKS:\n- [5条,每条1行]\n禁止输出其他章节。"
- },
- {
- "id": "t2-no-tool-design",
- "prompt": "禁止调用任何工具(如果调用则任务失败)。仅基于上一轮已有内容,输出固定格式:\nDESIGN_V1:\n- target_module: <1个>\n- problem_statement: <3行内>\n- minimal_change_scope: <最多2文件,允许只写方案不改代码>\n- behavior_invariants: [3条]\n- rollback_plan: [2条]\n不要新增章节。"
- },
- {
- "id": "t3-no-tool-delivery",
- "prompt": "禁止调用任何工具。输出固定模板(每项1-2行):\nFILES_TOUCHED_PLAN\nBEFORE_BEHAVIOR\nAFTER_BEHAVIOR\nRISK\nNEXT_ACTION\n不要输出其他内容。"
- }
-]
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/test2.json b/examples/openclaw-plugin/tests/toolresult_compression_tests/test2.json
deleted file mode 100644
index e03643cb8..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/test2.json
+++ /dev/null
@@ -1,19 +0,0 @@
-[
- {
- "id": "t1-module-ingest",
- "prompt": "你在做一次真实的模块接手分析。目标:理解 kubelet 中“Pod 处理与状态更新”主链路。仅允许读取以下文件,不允许读取其他文件,不允许测试:\n1) /root/.openclaw/workspace/kubernetes/pkg/kubelet/kubelet.go\n2) /root/.openclaw/workspace/kubernetes/pkg/kubelet/pod_workers.go\n3) /root/.openclaw/workspace/kubernetes/pkg/kubelet/status/status_manager.go\n4) /root/.openclaw/workspace/kubernetes/pkg/kubelet/pleg/generic.go\n输出固定格式:\nCHAIN_MAP(5-8条)\nHOTSPOTS(3条)\nOBSERVABILITY_GAPS(3条)\n禁止额外章节。"
- },
- {
- "id": "t2-design-no-tools",
- "prompt": "禁止调用任何工具。基于上一轮内容,选择1个最有价值的 hotspot,给出最小改造方案(偏设计,不改代码)。输出固定格式:\nTARGET\nPROBLEM\nMINIMAL_SCOPE(最多2个文件)\nINVARIANTS(3条)\nROLLBACK(2条)"
- },
- {
- "id": "t3-patch-plan-no-tools",
- "prompt": "禁止调用任何工具。把方案细化成可执行改动计划,输出固定格式:\nEDIT_PLAN(按文件列出函数级改动)\nPSEUDO_DIFF(10-20行伪代码)\nRISK_CHECKLIST(5条)"
- },
- {
- "id": "t4-delivery-no-tools",
- "prompt": "禁止调用任何工具。输出可直接贴到 PR 描述的交付摘要,固定格式:\nCONTEXT\nROOT_CAUSE_HYPOTHESIS\nPROPOSED_CHANGE\nEXPECTED_IMPACT\nKNOWN_RISKS\nNEXT_STEP"
- }
-]
-
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/test3.json b/examples/openclaw-plugin/tests/toolresult_compression_tests/test3.json
deleted file mode 100644
index 2a59aad55..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/test3.json
+++ /dev/null
@@ -1,19 +0,0 @@
-[
- {
- "id": "t1-retrieval-ingest",
- "prompt": "你在做一次真实的检索链路评审。目标:梳理 OpenViking 从 API/Client 到 index engine 的检索契约。请只读取以下文件,每个只读一次:\n1) /root/.openclaw/workspace/OpenViking/docs/en/api/06-retrieval.md\n2) /root/.openclaw/workspace/OpenViking/openviking_cli/client/sync_http.py\n3) /root/.openclaw/workspace/OpenViking/openviking_cli/retrieve/types.py\n4) /root/.openclaw/workspace/OpenViking/src/index/index_engine.cpp\n输出 JSON:\n{api_contract:{inputs:[...],outputs:[...],error_shapes:[...]},pipeline:[{stage,file,function,contract}],mismatch_candidates:[{name,where_detected,why}],evidence:[{file,function,line,why}]}"
- },
- {
- "id": "t2-contract-design",
- "prompt": "基于上轮结果,优先使用已整理的上下文;只有在关键信息缺失时,才补充一次原文回查并说明原因。选 1 个最重要 mismatch,设计最小契约收敛方案(不改代码)。输出 JSON:\n{target_mismatch,proposed_contract_delta:{before,after},affected_components:[{file,owner_role}],compatibility_strategy:[{consumer,impact,mitigation}],rollout_plan:[{phase,goal,exit_criteria}]}"
- },
- {
- "id": "t3-implementation-outline",
- "prompt": "基于前两轮内容,给出实施大纲(函数级,不改代码)。输出 JSON:\n{change_outline:[{file,functions:[{name,action,expected_result}]}],data_validation_rules:[{rule,reason}],observability_additions:[{signal,location,why}],verification_matrix:[{scenario,expected_result}]}"
- },
- {
- "id": "t4-rfc-summary",
- "prompt": "基于前 3 轮内容,输出 RFC 风格摘要。输出 JSON:\n{problem,decision,alternatives_considered:[{option,reject_reason}],impact_assessment:{correctness,latency,operability},risk_register:[{risk,level,owner,mitigation}],go_no_go_criteria:[{criterion,measure}]}"
- }
-]
-
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/test4.json b/examples/openclaw-plugin/tests/toolresult_compression_tests/test4.json
deleted file mode 100644
index 7de994c1a..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/test4.json
+++ /dev/null
@@ -1,19 +0,0 @@
-[
- {
- "id": "t1-pipeline-ingest",
- "prompt": "你在做一次真实的集成链路评审。目标:梳理 openclaw-plugin 到 OpenViking 的记忆写入与回忆链路。请只读取以下文件,每个只读一次:\n1) /root/.openclaw/workspace/OpenViking/examples/openclaw-plugin/index.ts\n2) /root/.openclaw/workspace/OpenViking/examples/openclaw-plugin/context-engine.ts\n3) /root/.openclaw/workspace/OpenViking/examples/openclaw-plugin/client.js\n4) /root/.openclaw/workspace/OpenViking/docs/en/concepts/06-extraction.md\n输出 JSON:\n{pipeline_map:[{stage,component,file,function,input,output}],failure_points:[{name,where,symptom,severity}],consistency_requirements:[{requirement,why}],evidence:[{file,function,line,why}]}"
- },
- {
- "id": "t2-reliability-design",
- "prompt": "基于上轮结果,优先使用已整理的上下文;只有在关键信息缺失时,才补充一次原文回查并说明原因。针对 1 个最高优先 failure point,提出最小可靠性增强设计(不改代码)。输出 JSON:\n{target_failure_point,design_delta:{before,after},minimal_scope:[{file,change_intent}],failure_handling_policy:[{case,policy}],rollback:[{step,when_to_use}]}"
- },
- {
- "id": "t3-implementation-guide",
- "prompt": "基于前两轮内容,输出实施指引(函数级,不改代码)。输出 JSON:\n{implementation_guide:[{file,functions:[{name,planned_change,expected_effect}]}],observability_plan:[{signal,location,alert_condition}],verification_checklist:[{item,pass_condition}],known_tradeoffs:[{tradeoff,accepted_reason}]}"
- },
- {
- "id": "t4-handoff-summary",
- "prompt": "基于前 3 轮内容,输出交接摘要。输出 JSON:\n{problem_statement,proposed_solution,expected_reliability_gain,risk_register:[{risk,level,mitigation}],handoff_todo:[{owner,task,done_definition}],traceability:[{claim,evidence_file,evidence_function,evidence_line}]}"
- }
-]
-
diff --git a/examples/openclaw-plugin/tests/toolresult_compression_tests/test5.json b/examples/openclaw-plugin/tests/toolresult_compression_tests/test5.json
deleted file mode 100644
index e7434e6bb..000000000
--- a/examples/openclaw-plugin/tests/toolresult_compression_tests/test5.json
+++ /dev/null
@@ -1,18 +0,0 @@
-[
- {
- "id": "t1-structured-ingest",
- "prompt": "你在做一次会话链路接手。请只读取以下文件,并只关注指定函数:\n1) /root/.openclaw/workspace/openclaw/src/agents/command/session.ts -> resolveSession\n2) /root/.openclaw/workspace/openclaw/src/agents/command/session-store.ts -> updateSessionStoreAfterAgentRun\n3) /root/.openclaw/workspace/openclaw/src/agents/command/delivery.ts -> deliverAgentCommandResult\n4) /root/.openclaw/workspace/openclaw/src/agents/agent-command.ts -> prepareAgentCommandExecution, agentCommandInternal\n输出严格 JSON(仅此结构,不要额外字段):\n{\n \"chain_map\": [\n {\"id\":\"S1\",\"stage\":\"session_resolve\",\"file\":\"\",\"function\":\"resolveSession\",\"input\":\"\",\"output\":\"\"},\n {\"id\":\"S2\",\"stage\":\"session_store_update\",\"file\":\"\",\"function\":\"updateSessionStoreAfterAgentRun\",\"input\":\"\",\"output\":\"\"},\n {\"id\":\"S3\",\"stage\":\"delivery\",\"file\":\"\",\"function\":\"deliverAgentCommandResult\",\"input\":\"\",\"output\":\"\"}\n ],\n \"evidence_index\": [\n {\"evidence_id\":\"E1\",\"claim\":\"session key/session id resolution occurs before run\",\"file\":\"\",\"function\":\"\",\"line_hint\":\"\"},\n {\"evidence_id\":\"E2\",\"claim\":\"usage and token fields are persisted in session store\",\"file\":\"\",\"function\":\"\",\"line_hint\":\"\"},\n {\"evidence_id\":\"E3\",\"claim\":\"json response envelope is formed at delivery stage\",\"file\":\"\",\"function\":\"\",\"line_hint\":\"\"}\n ]\n}"
- },
- {
- "id": "t2-fixed-design",
- "prompt": "基于上轮内容,做最小改造设计(不改代码),并固定目标为 E2 对应问题。输出严格 JSON(仅此结构):\n{\n \"target_evidence_id\": \"E2\",\n \"problem_statement\": \"\",\n \"minimal_scope\": [\n {\"file\":\"/root/.openclaw/workspace/openclaw/src/agents/command/session-store.ts\",\"planned_change\":\"\"},\n {\"file\":\"/root/.openclaw/workspace/openclaw/src/agents/agent-command.ts\",\"planned_change\":\"\"}\n ],\n \"invariants\": [\"\", \"\", \"\"],\n \"rollback\": [\"\", \"\"]\n}"
- },
- {
- "id": "t3-review-evidence-pack",
- "prompt": "现在要提交设计评审材料。请为 E2 和 E3 各提供一段精确代码证据(每段 8-12 行,保留缩进)。优先基于前文;如果需要精确原文,请从第一轮已采集引用中回取。输出严格 JSON:\n{\n \"evidence_pack\": [\n {\"evidence_id\":\"E2\",\"file\":\"\",\"function\":\"\",\"line_range_hint\":\"\",\"code_snippet\":\"\"},\n {\"evidence_id\":\"E3\",\"file\":\"\",\"function\":\"\",\"line_range_hint\":\"\",\"code_snippet\":\"\"}\n ]\n}"
- },
- {
- "id": "t4-final-summary",
- "prompt": "输出交付摘要,严格 JSON(仅此结构):\n{\n \"context\": \"\",\n \"root_cause_hypothesis\": \"\",\n \"proposed_change\": \"\",\n \"expected_impact\": \"\",\n \"known_risks\": \"\",\n \"next_step\": \"\",\n \"traceability\": [\n {\"claim\":\"session resolution\",\"evidence_id\":\"E1\"},\n {\"claim\":\"usage persistence\",\"evidence_id\":\"E2\"},\n {\"claim\":\"delivery envelope\",\"evidence_id\":\"E3\"}\n ]\n}"
- }
-]
\ No newline at end of file
diff --git a/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts b/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts
index 6143efafe..1069f0fd4 100644
--- a/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts
+++ b/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts
@@ -870,7 +870,6 @@ describe("architecture boundaries", () => {
it("keeps auto-recall helper tests off the index compatibility facade", () => {
const violations = [
"tests/ut/build-memory-lines.test.ts",
- "tests/context-bloat-730.test.ts",
"tests/ut/index-utils.test.ts",
].flatMap((file) => {
const source = readFileSync(join(rootDir, file), "utf8");
diff --git a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
index 55feac24a..bb616ef14 100644
--- a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
+++ b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
@@ -148,7 +148,9 @@ describe("OpenClaw 5.5 package runtime contract", () => {
it("builds and publishes compiled runtime output for TypeScript entries", () => {
expect(packageJson.scripts?.build).toContain("rmSync('dist'");
expect(packageJson.scripts?.build).toContain("tsc -p tsconfig.build.json");
- expect(packageJson.scripts?.prepack).toBe("npm run build");
+ expect(packageJson.scripts?.prepack).toBe(
+ "node ../memory-plugin-shared/sync.mjs && npm run build",
+ );
expect(packageJson.files).toContain("dist/");
expect(packageJson.files).toContain("shared/");
expect(packageJson.files).toContain("install-manifest.json");
diff --git a/examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts b/examples/openclaw-plugin/tests/ut/text-utils-bypass-session-patterns.test.ts
similarity index 95%
rename from examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts
rename to examples/openclaw-plugin/tests/ut/text-utils-bypass-session-patterns.test.ts
index 2871563b7..65d84dd97 100644
--- a/examples/openclaw-plugin/__tests__/bypass-session-patterns.test.ts
+++ b/examples/openclaw-plugin/tests/ut/text-utils-bypass-session-patterns.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
-import { memoryOpenVikingConfigSchema } from "../config.js";
+import { memoryOpenVikingConfigSchema } from "../../config.js";
import {
compileSessionPatterns,
matchesSessionPattern,
shouldBypassSession,
-} from "../text-utils.js";
+} from "../../text-utils.js";
describe("bypass session patterns", () => {
it("parses bypass session patterns from config", () => {
diff --git a/examples/openclaw-plugin/tsconfig.build.json b/examples/openclaw-plugin/tsconfig.build.json
index 3798c11e3..e5fefc21a 100644
--- a/examples/openclaw-plugin/tsconfig.build.json
+++ b/examples/openclaw-plugin/tsconfig.build.json
@@ -15,7 +15,6 @@
"dist",
"node_modules",
"tests",
- "__tests__",
"vitest.config.ts"
]
}
diff --git a/examples/openclaw-plugin/vitest.config.ts b/examples/openclaw-plugin/vitest.config.ts
index 3f824fb95..133bc403b 100644
--- a/examples/openclaw-plugin/vitest.config.ts
+++ b/examples/openclaw-plugin/vitest.config.ts
@@ -4,5 +4,6 @@ export default defineConfig({
test: {
globals: true,
environment: "node",
+ include: ["tests/ut/**/*.test.ts"],
},
});
diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.md
index 400a3ce44..d02d56b20 100644
--- a/examples/opencode-plugin/INSTALL-ZH.md
+++ b/examples/opencode-plugin/INSTALL-ZH.md
@@ -81,37 +81,44 @@ export { OpenVikingPlugin, default } from "./openviking/index.mjs"
## 配置
-创建用户级配置文件:
+行为旋钮写在共享的客户端配置文件里:
```bash
-~/.config/opencode/openviking-config.json
+~/.openviking/ovcli.conf
```
示例配置:
```json
{
- "enabled": true,
- "mcp": { "enabled": true },
- "timeoutMs": 30000,
- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },
- "autoRecall": {
- "enabled": true,
- "limit": 6,
- "scoreThreshold": 0.35,
- "maxContentChars": 500,
- "preferAbstract": true,
- "tokenBudget": 2000,
- "minQueryLength": 3
- },
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000
+ "url": "http://127.0.0.1:1933",
+ "api_key": "your-api-key-here",
+ "plugin": {
+ "recallLimit": 6,
+ "opencode": {
+ "enabled": true,
+ "mcpEnabled": true,
+ "timeoutMs": 30000,
+ "repoContext": true,
+ "repoContextCacheTtlMs": 60000,
+ "autoRecall": true,
+ "scoreThreshold": 0.35,
+ "recallMaxContentChars": 500,
+ "recallPreferAbstract": true,
+ "recallTokenBudget": 2000,
+ "minQueryLength": 3,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000
+ }
+ }
}
```
-`autoRecall.limit` 是遗留的配额缩放输入,不是最终结果上限。显式设置为
+`plugin` 里的键对所有 harness 生效;`plugin.opencode` 里的键只对本插件生效,并覆盖前者。解析顺序是 `OPENVIKING_*` 环境变量 → 工作区的 `.openviking/config.json`、`.openviking/config.local.json` 和本机 registry 条目 → `plugin.opencode` → `plugin` → 内置默认值。每个旋钮的类型、默认值、取值范围、环境变量名和兼容的旧拼写都声明在 [`examples/memory-plugin-shared/lib/config-schema.mjs`](../memory-plugin-shared/lib/config-schema.mjs)。
+
+`recallLimit` 是遗留的配额缩放输入,不是最终结果上限。显式设置为
1 到 5 时,有效总配额仍为 6,因为六个 coding 分类会各保留一个检索槽位。
推荐通过环境变量提供 API Key,而不是写入配置文件:
@@ -121,15 +128,15 @@ export OPENVIKING_API_KEY="your-api-key-here"
```
API key 会从环境变量或 `~/.openviking/ovcli.conf` 读取,并由 hooks 和 MCP proxy 作为 `Authorization: Bearer ...` 发送。`account` 和 `user` 是 trusted mode
-身份头,会作为 `X-OpenViking-Account`、`X-OpenViking-User` 发送;使用
-user/admin API key 的 API_KEY mode 时应留空。
+身份头,会作为 `X-OpenViking-Account`、`X-OpenViking-User` 发送;`api_key`
+模式的服务端从 key 里取身份,插件在那里不发这两个头。
`peerId` 会作为 `X-OpenViking-Actor-Peer` 用于数据面的 memory/resource 请求;捕获 session message 时仍写入 body `peer_id`。需要 peer 维度路由时请显式配置。
`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、
`OPENVIKING_PEER_ID`
-优先级高于 `openviking-config.json` 里的同名配置。
+优先级高于 `ovcli.conf` 里的同名配置。
-高级场景可以用 `OPENVIKING_PLUGIN_CONFIG` 指向其他配置文件路径。
+高级场景可以用 `OPENVIKING_CLI_CONFIG_FILE` 指向其他路径的 `ovcli.conf`。
### 仅 Hooks 模式
@@ -137,7 +144,9 @@ user/admin API key 的 API_KEY mode 时应留空。
```json
{
- "mcp": { "enabled": false }
+ "plugin": {
+ "opencode": { "mcpEnabled": false }
+ }
}
```
@@ -229,7 +238,7 @@ openviking_add_resource(path="file:///home/alice/project/notes.md", description=
- `openviking-memory.log`
- `openviking-session-state.json`
-可以通过配置里的 `runtime.dataDir` 修改这个目录。
+可以通过 `plugin.opencode` 里的 `dataDir` 修改这个目录。
这些是本地运行时文件,不建议提交到版本库。
@@ -238,7 +247,7 @@ openviking_add_resource(path="file:///home/alice/project/notes.md", description=
| 问题 | 排查方向 |
|------|----------|
| 插件没有加载 | package 安装检查 `~/.config/opencode/opencode.json` 是否包含 `@openviking/opencode-plugin`;源码安装检查 `~/.config/opencode/plugins/openviking.js` 是否存在 |
-| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量 / `OPENVIKING_PLUGIN_CONFIG` 指向正确配置 |
+| MCP tools 连到了错误的 server | 检查 `~/.openviking/ovcli.conf`,或用 `OPENVIKING_*` 环境变量 / `OPENVIKING_CLI_CONFIG_FILE` 指向正确配置 |
| OpenViking 返回 401 / 403 | 检查 `OPENVIKING_API_KEY`;trusted-mode 部署还要检查 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER` |
-| recall 为空 | 确认 OpenViking 中已有 memories/resources,并且 `autoRecall.enabled` 为 `true` |
+| recall 为空 | 确认 OpenViking 中已有 memories/resources,并且 `autoRecall` 为 `true` |
| 本地 `openviking_add_resource` 失败 | 传入文件路径而不是目录;目前还不支持自动上传本地目录 |
diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.md
index c7679eff9..cc4b24469 100644
--- a/examples/opencode-plugin/INSTALL.md
+++ b/examples/opencode-plugin/INSTALL.md
@@ -81,37 +81,44 @@ If you install through an npm package, you can also use `examples/opencode-plugi
## Configuration
-Create the user-level configuration file:
+Behaviour knobs live in the shared client configuration file:
```bash
-~/.config/opencode/openviking-config.json
+~/.openviking/ovcli.conf
```
Example configuration:
```json
{
- "enabled": true,
- "mcp": { "enabled": true },
- "timeoutMs": 30000,
- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },
- "autoRecall": {
- "enabled": true,
- "limit": 6,
- "scoreThreshold": 0.35,
- "maxContentChars": 500,
- "preferAbstract": true,
- "tokenBudget": 2000,
- "minQueryLength": 3
- },
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000
+ "url": "http://127.0.0.1:1933",
+ "api_key": "your-api-key-here",
+ "plugin": {
+ "recallLimit": 6,
+ "opencode": {
+ "enabled": true,
+ "mcpEnabled": true,
+ "timeoutMs": 30000,
+ "repoContext": true,
+ "repoContextCacheTtlMs": 60000,
+ "autoRecall": true,
+ "scoreThreshold": 0.35,
+ "recallMaxContentChars": 500,
+ "recallPreferAbstract": true,
+ "recallTokenBudget": 2000,
+ "minQueryLength": 3,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000
+ }
+ }
}
```
-`autoRecall.limit` is a legacy quota-scaling input, not a final result cap.
+Keys in `plugin` apply to every harness; keys in `plugin.opencode` apply to this one and override them. Resolution is `OPENVIKING_*` environment variables → the workspace's `.openviking/config.json`, `.openviking/config.local.json` and machine registry entry → `plugin.opencode` → `plugin` → built-in defaults. Every knob, with its type, default, range, environment variable and accepted older spellings, is declared in [`examples/memory-plugin-shared/lib/config-schema.mjs`](../memory-plugin-shared/lib/config-schema.mjs).
+
+`recallLimit` is a legacy quota-scaling input, not a final result cap.
Explicit values from 1 through 5 produce an effective total quota of 6 because
each coding category keeps one retrieval slot.
@@ -121,11 +128,11 @@ It is recommended to provide the API key through an environment variable instead
export OPENVIKING_API_KEY="your-api-key-here"
```
-API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`.
+API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; an `api_key` server reads both out of the key, so the plugin withholds them there. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`.
-`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `openviking-config.json`.
+`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `ovcli.conf`.
-For advanced setups, use `OPENVIKING_PLUGIN_CONFIG` to point to another configuration file path.
+For advanced setups, use `OPENVIKING_CLI_CONFIG_FILE` to point to an `ovcli.conf` at another path.
### Hook-only mode
@@ -134,7 +141,9 @@ keeping this plugin's lifecycle hooks active:
```json
{
- "mcp": { "enabled": false }
+ "plugin": {
+ "opencode": { "mcpEnabled": false }
+ }
}
```
@@ -226,7 +235,7 @@ Possible files include:
- `openviking-memory.log`
- `openviking-session-state.json`
-You can change this directory with `runtime.dataDir` in the configuration.
+You can change this directory with `dataDir` in `plugin.opencode`.
These are local runtime files and should not be committed to the repository.
@@ -235,7 +244,7 @@ These are local runtime files and should not be committed to the repository.
| Issue | What to check |
|-------|---------------|
| Plugin does not load | For package installs, confirm `~/.config/opencode/opencode.json` contains `@openviking/opencode-plugin`; for source installs, confirm `~/.config/opencode/plugins/openviking.js` exists |
-| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_PLUGIN_CONFIG` to the intended config path |
+| MCP tools call the wrong server | Check `~/.openviking/ovcli.conf`, or set `OPENVIKING_*` env vars / `OPENVIKING_CLI_CONFIG_FILE` to the intended config path |
| 401 / 403 from OpenViking | Verify `OPENVIKING_API_KEY`; for trusted-mode deployments, also verify `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` |
-| Recall is empty | Confirm OpenViking has indexed memories/resources and `autoRecall.enabled` is `true` |
+| Recall is empty | Confirm OpenViking has indexed memories/resources and `autoRecall` is `true` |
| Local `openviking_add_resource` fails | Pass a file path, not a directory; local directories are not uploaded automatically yet |
diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.md
index fb037909b..e9f3662a1 100644
--- a/examples/opencode-plugin/README.md
+++ b/examples/opencode-plugin/README.md
@@ -113,39 +113,46 @@ Use the `.js` wrapper for source installs; OpenCode's local plugin scanner disco
## Configuration
-Create `~/.config/opencode/openviking-config.json`:
+Behaviour knobs live in `~/.openviking/ovcli.conf` beside the connection fields, in the shared `plugin` section or in the `plugin.opencode` override:
```json
{
- "enabled": true,
- "mcp": { "enabled": true },
- "timeoutMs": 30000,
- "repoContext": { "enabled": true, "cacheTtlMs": 60000 },
- "autoRecall": {
- "enabled": true,
- "limit": 6,
- "scoreThreshold": 0.35,
- "maxContentChars": 500,
- "preferAbstract": true,
- "tokenBudget": 2000,
- "minQueryLength": 3
- },
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000
+ "url": "http://127.0.0.1:1933",
+ "api_key": "your-api-key-here",
+ "plugin": {
+ "recallLimit": 6,
+ "opencode": {
+ "enabled": true,
+ "mcpEnabled": true,
+ "timeoutMs": 30000,
+ "repoContext": true,
+ "repoContextCacheTtlMs": 60000,
+ "autoRecall": true,
+ "scoreThreshold": 0.35,
+ "recallMaxContentChars": 500,
+ "recallPreferAbstract": true,
+ "recallTokenBudget": 2000,
+ "minQueryLength": 3,
+ "commitTokenThreshold": 20000,
+ "commitKeepRecentCount": 10,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000
+ }
+ }
}
```
-`autoRecall.limit` is a legacy quota-scaling input, not a final result cap.
+Keys in `plugin` apply to every harness; keys in `plugin.opencode` apply to this one and override them. Resolution is `OPENVIKING_*` environment variables → the workspace's `.openviking/config.json`, `.openviking/config.local.json` and machine registry entry → `plugin.opencode` → `plugin` → built-in defaults. Every knob, with its type, default, range, environment variable and accepted older spellings, is declared in [`examples/memory-plugin-shared/lib/config-schema.mjs`](../memory-plugin-shared/lib/config-schema.mjs).
+
+`recallLimit` is a legacy quota-scaling input, not a final result cap.
Explicit values from 1 through 5 produce an effective total quota of 6 because
each coding category keeps one retrieval slot. Use Context `quotas` directly
when exact category ceilings are required.
API keys are resolved from environment variables or `~/.openviking/ovcli.conf` and sent as `Authorization: Bearer ...` by both hooks and the MCP proxy. Recall goes through the server-side context face (`POST /api/v1/search/search` with `mode="context"`), falling back to the deprecated `/api/v1/search/recall` on older deployments. `account` and `user` are trusted-mode identity
-headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty
-when using API-key mode with user/admin API keys.
-By default the plugin derives a peer from the git identity of the project directory: the normalized `origin` URL, else the repository root path. Outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space `viking://user/<you>/memories`. `[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`; the path fallback keeps the older naming rule where every non-letter-or-digit character becomes `-`, so `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. One repository therefore keeps one peer across subdirectories, worktrees, clones and machines, while a fork's different origin keeps it separate. Derivation reads `.git` directly, so no `git` binary is needed. The plugin does not read workspace `.openviking/config.json` files, so a `peer.id` written there has no effect. Data-plane memory/resource requests send the effective peer as `X-OpenViking-Actor-Peer`; captured session messages store it as body `peer_id`. Configure `peerId` or `OPENVIKING_PEER_ID` to override the derived peer, or set `workspacePeer=false` / `OPENVIKING_WORKSPACE_PEER=0` to send no peer at all. Memories written under the older directory-derived peer stay reachable: the default broad recall sweeps every peer under the user, and `recallPeerScope="actor"` asks that previous peer separately.
+headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; an `api_key`
+server reads both out of the key, so the plugin withholds them there.
+By default the plugin derives a peer from the git identity of the project directory: the normalized `origin` URL, else the repository root path. Outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space `viking://user/<you>/memories`. `[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`; the path fallback keeps the older naming rule where every non-letter-or-digit character becomes `-`, so `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. One repository therefore keeps one peer across subdirectories, worktrees, clones and machines, while a fork's different origin keeps it separate. Derivation reads `.git` directly, so no `git` binary is needed. The plugin reads the workspace's `.openviking/config.json`, so a `peer.id` or `peer.source` written there applies. Data-plane memory/resource requests send the effective peer as `X-OpenViking-Actor-Peer`; captured session messages store it as body `peer_id`. Configure `peerId` in the `plugin` section or `OPENVIKING_PEER_ID` to override the derived peer, or set `workspacePeer` to `false` / `OPENVIKING_WORKSPACE_PEER=0` to send no peer at all. Memories written under the older directory-derived peer stay reachable: the default broad recall sweeps every peer under the user, and `recallPeerScope="actor"` asks that previous peer separately.
Recall defaults to the broad mode: global memory, the current workspace, and
other workspace memories can all be recalled, with other workspaces penalized
@@ -157,13 +164,12 @@ with an explicit actor peer so one person's memories are not recalled into
another person's session.
`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`,
-and `OPENVIKING_PEER_ID` take precedence over values in this file. The config
-file's `peerId` still applies whenever shared credentials (ovcli.conf or
-environment variables) do not carry a peer of their own, so an authenticated
-setup keeps writing peer-scoped data instead of dropping into the shared user
-tree.
+and `OPENVIKING_PEER_ID` take precedence over `ovcli.conf`. Below the
+environment, the `plugin` section's `peerId` takes precedence over
+`ovcli.conf`'s `actor_peer_id`: a peer written for this harness is the more
+specific answer, and this is the order every memory plugin follows.
-For advanced setups, `OPENVIKING_PLUGIN_CONFIG` can point to another config file path.
+`OPENVIKING_CLI_CONFIG_FILE` points the plugin at an `ovcli.conf` somewhere other than `~/.openviking/ovcli.conf`.
### Hook-only mode
@@ -172,7 +178,9 @@ skipping this plugin's bundled MCP registration:
```json
{
- "mcp": { "enabled": false }
+ "plugin": {
+ "opencode": { "mcpEnabled": false }
+ }
}
```
@@ -211,12 +219,12 @@ The plugin writes runtime files to `~/.config/opencode/openviking/` by default:
- `openviking-memory.log`
- `openviking-session-state.json`
-Set `runtime.dataDir` in config to override this directory.
+Set `dataDir` in `plugin.opencode` to override this directory.
## Automated npm releases
Changes merged into upstream `main` under `examples/opencode-plugin/` trigger
-`.github/workflows/opencode-plugin-release.yml`. Releases use the same calendar
+`.github/workflows/plugin-npm-release.yml`. Releases use the same calendar
version convention as the OpenClaw plugin: `YYYY.M.D`, then `YYYY.M.D-N` for
subsequent releases on that date (Asia/Shanghai). No manual source version bump
is required. The workflow changes the version only in the package being published;
diff --git a/examples/opencode-plugin/index.mjs b/examples/opencode-plugin/index.mjs
index bc5934588..ade8d93e0 100644
--- a/examples/opencode-plugin/index.mjs
+++ b/examples/opencode-plugin/index.mjs
@@ -8,6 +8,7 @@ import { createSessionInject } from "./lib/session-inject.mjs"
import { createVikingUriGuard } from "./lib/viking-uri-guard.mjs"
import { injectOpenVikingMcpConfig } from "./lib/mcp-config.mjs"
import { loadConfig, resolveDataDir } from "./lib/config.mjs"
+import { isRecallEnabled } from "./lib/shared/recall-core.mjs"
import { initLogger, log, makeToast } from "./lib/utils.mjs"
const pluginRoot = dirname(fileURLToPath(import.meta.url))
@@ -30,13 +31,6 @@ export async function OpenVikingPlugin({ client, directory }) {
await sessionManager.init()
const toast = makeToast(client)
- if (config.legacyCredentialsUsed) {
- log("WARN", "config", "Legacy OpenCode credential fields are still in use; run node scripts/setup.mjs to migrate to ovcli.conf", {
- configPath: config.configPath,
- })
- await toast("OpenViking credentials in openviking-config.json are deprecated. Run node scripts/setup.mjs to migrate.", "warning")
- }
-
Promise.resolve().then(async () => {
const ready = await initializeRuntime(config, client)
if (ready) await repoContext.refreshRepos({ force: true })
@@ -72,7 +66,7 @@ export async function OpenVikingPlugin({ client, directory }) {
"chat.message": async (input, output) => {
try {
await sessionInject.injectSessionContext(input, output)
- if (!config.autoRecall?.enabled) return
+ if (!isRecallEnabled(config)) return
await recall.injectRelevantMemories(input, output)
} catch (error) {
log("WARN", "recall", "Auto recall failed", { error: error?.message ?? String(error) })
diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjs
index a2bc17060..f6e2152e6 100644
--- a/examples/opencode-plugin/lib/config.mjs
+++ b/examples/opencode-plugin/lib/config.mjs
@@ -1,84 +1,20 @@
-import fs from "fs"
import path from "path"
import { homedir } from "os"
-import { buildUserAgent, readManifestVersion, resolveOpenVikingCredentials } from "./shared/credentials.mjs"
-import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs"
-
-const USER_AGENT = buildUserAgent(
- "opencode",
- readManifestVersion(new URL("../package.json", import.meta.url)),
-)
-
-const DEFAULT_CONFIG = {
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- workspacePeer: true,
- recallPeerScope: "all",
- // Server-side query expansion costs a model call before retrieval starts, so
- // it has to be switchable from the client that pays the latency.
- recallQueryExpansion: "auto",
- enabled: true,
- mcp: {
- enabled: true,
- },
- timeoutMs: 30000,
- runtime: {
- dataDir: "",
- },
- repoContext: {
- enabled: true,
- cacheTtlMs: 60000,
- },
- autoRecall: {
- enabled: true,
- limit: 10,
- scoreThreshold: 0.35,
- maxContentChars: 500,
- preferAbstract: true,
- tokenBudget: 2000,
- minQueryLength: 3,
- },
- autoCapture: true,
- captureMode: "semantic",
- captureMaxLength: 24000,
- captureAssistantTurns: true,
- captureToolMaxChars: 1000000,
- commitTokenThreshold: 20000,
- commitKeepRecentCount: 10,
- profileTokenBudget: 10000,
- resumeContextBudget: 32000,
- noAutoInject: false,
- bypassSession: false,
- bypassSessionPatterns: [],
- debug: false,
- debugLogPath: path.join(homedir(), ".openviking", "logs", "opencode-plugin.log"),
-}
-
-function cloneDefaultConfig() {
- return JSON.parse(JSON.stringify(DEFAULT_CONFIG))
-}
-
-function normalizeNumber(value, fallback, min, max) {
- const next = Number(value)
- if (!Number.isFinite(next)) return fallback
- return Math.max(min, Math.min(max, next))
-}
-
-function envBool(name) {
- const value = process.env[name]
- if (value == null || value === "") return undefined
- const lower = String(value).trim().toLowerCase()
- if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false
- if (lower === "1" || lower === "true" || lower === "yes" || lower === "on") return true
- return undefined
-}
-
-function str(value, fallback = "") {
- return typeof value === "string" && value.trim() ? value.trim() : fallback
-}
+import { buildPluginConfig } from "./shared/plugin-config.mjs"
+
+/**
+ * Configuration for the opencode plugin.
+ *
+ * This plugin used to keep its own `openviking-config.json`, looked up along
+ * four candidate paths. Every knob now comes from the same place as every other
+ * harness — `ovcli.conf`'s `plugin` section, overridden by `plugin.opencode`,
+ * by the workspace file, and by the environment — so `ov config switch` moves
+ * behaviour along with credentials instead of only half of it.
+ *
+ * What stays here is the three knobs this plugin's own code reads as sections
+ * rather than as flat keys.
+ */
+const MANIFEST_URL = new URL("../package.json", import.meta.url)
function expandHome(value) {
if (!value || typeof value !== "string") return value
@@ -87,236 +23,22 @@ function expandHome(value) {
return value
}
-function readConfigFile(pluginRoot, projectDirectory) {
- for (const configPath of getConfigPaths(pluginRoot, projectDirectory)) {
- try {
- if (!fs.existsSync(configPath)) continue
- return { path: configPath, data: JSON.parse(fs.readFileSync(configPath, "utf8")) }
- } catch (error) {
- console.warn(`Failed to load OpenViking config from ${configPath}:`, error)
- }
- }
- return { path: "", data: {} }
-}
-
-function getConfigPaths(pluginRoot, projectDirectory) {
- const paths = []
- if (process.env.OPENVIKING_PLUGIN_CONFIG) paths.push(expandHome(process.env.OPENVIKING_PLUGIN_CONFIG))
- if (projectDirectory) paths.push(path.join(projectDirectory, ".opencode", "openviking-config.json"))
- paths.push(path.join(homedir(), ".config", "opencode", "openviking-config.json"))
- paths.push(path.join(pluginRoot, "openviking-config.json"))
- return paths
-}
-
-function applyLegacyConnection(config, fileConfig) {
- const hasLegacyCredentials = ["endpoint", "apiKey", "account", "user", "peerId"]
- .some((key) => fileConfig[key] !== undefined && fileConfig[key] !== "")
- if (!hasLegacyCredentials) return false
-
- if (fileConfig.endpoint !== undefined) config.endpoint = fileConfig.endpoint
- if (fileConfig.apiKey !== undefined) config.apiKey = fileConfig.apiKey
- if (fileConfig.account !== undefined) config.account = fileConfig.account
- if (fileConfig.user !== undefined) config.user = fileConfig.user
- if (fileConfig.peerId !== undefined) config.peerId = fileConfig.peerId
- return true
-}
-
-function applyBehaviorConfig(config, fileConfig = {}) {
- if (fileConfig.enabled !== undefined) config.enabled = fileConfig.enabled !== false
- const mcp = fileConfig.mcp && typeof fileConfig.mcp === "object" ? fileConfig.mcp : {}
- config.mcp = {
- ...DEFAULT_CONFIG.mcp,
- ...mcp,
- enabled: mcp.enabled !== false,
- }
- if (fileConfig.timeoutMs !== undefined) config.timeoutMs = fileConfig.timeoutMs
- config.runtime = {
- ...DEFAULT_CONFIG.runtime,
- ...(fileConfig.runtime ?? {}),
- }
- config.repoContext = {
- ...DEFAULT_CONFIG.repoContext,
- ...(fileConfig.repoContext ?? {}),
- }
-
- const autoRecall = fileConfig.autoRecall ?? {}
- config.recallLimitConfigured = autoRecall.limit !== undefined ||
- fileConfig.recallLimit !== undefined
- config.autoRecall = {
- ...DEFAULT_CONFIG.autoRecall,
- ...autoRecall,
- enabled: autoRecall.enabled !== false,
- limit: autoRecall.limit ?? fileConfig.recallLimit ?? DEFAULT_CONFIG.autoRecall.limit,
- scoreThreshold: autoRecall.scoreThreshold ?? fileConfig.scoreThreshold ?? DEFAULT_CONFIG.autoRecall.scoreThreshold,
- maxContentChars: autoRecall.maxContentChars ?? fileConfig.recallMaxContentChars ?? DEFAULT_CONFIG.autoRecall.maxContentChars,
- preferAbstract: autoRecall.preferAbstract ?? fileConfig.recallPreferAbstract ?? DEFAULT_CONFIG.autoRecall.preferAbstract,
- tokenBudget: autoRecall.tokenBudget ?? fileConfig.recallTokenBudget ?? DEFAULT_CONFIG.autoRecall.tokenBudget,
- minQueryLength: autoRecall.minQueryLength ?? fileConfig.minQueryLength ?? DEFAULT_CONFIG.autoRecall.minQueryLength,
- }
-
- for (const key of [
- "autoCapture",
- "captureMode",
- "captureMaxLength",
- "captureAssistantTurns",
- "captureToolMaxChars",
- "commitTokenThreshold",
- "commitKeepRecentCount",
- "profileTokenBudget",
- "resumeContextBudget",
- "noAutoInject",
- "bypassSession",
- "bypassSessionPatterns",
- "debug",
- "debugLogPath",
- "workspacePeer",
- "recallPeerScope",
- "recallQueryExpansion",
- ]) {
- if (fileConfig[key] !== undefined) config[key] = fileConfig[key]
- }
- config.recallQueryExpansionConfigured = fileConfig.recallQueryExpansion !== undefined
-}
-
-function applyEnv(config) {
- if (process.env.OPENVIKING_TIMEOUT_MS) config.timeoutMs = process.env.OPENVIKING_TIMEOUT_MS
- if (process.env.OPENVIKING_AUTO_RECALL !== undefined) {
- config.autoRecall.enabled = envBool("OPENVIKING_AUTO_RECALL") ?? config.autoRecall.enabled
- }
- if (process.env.OPENVIKING_RECALL_LIMIT) {
- config.autoRecall.limit = process.env.OPENVIKING_RECALL_LIMIT
- config.recallLimitConfigured = true
- }
- if (process.env.OPENVIKING_SCORE_THRESHOLD) config.autoRecall.scoreThreshold = process.env.OPENVIKING_SCORE_THRESHOLD
- if (process.env.OPENVIKING_RECALL_MAX_CONTENT_CHARS) {
- config.autoRecall.maxContentChars = process.env.OPENVIKING_RECALL_MAX_CONTENT_CHARS
- }
- if (process.env.OPENVIKING_RECALL_TOKEN_BUDGET) config.autoRecall.tokenBudget = process.env.OPENVIKING_RECALL_TOKEN_BUDGET
- if (process.env.OPENVIKING_RECALL_PREFER_ABSTRACT !== undefined) {
- config.autoRecall.preferAbstract = envBool("OPENVIKING_RECALL_PREFER_ABSTRACT") ?? config.autoRecall.preferAbstract
- }
- if (process.env.OPENVIKING_RECALL_PEER_SCOPE) config.recallPeerScope = process.env.OPENVIKING_RECALL_PEER_SCOPE
- if (process.env.OPENVIKING_RECALL_QUERY_EXPANSION) {
- config.recallQueryExpansion = process.env.OPENVIKING_RECALL_QUERY_EXPANSION
- config.recallQueryExpansionConfigured = true
- }
- if (process.env.OPENVIKING_WORKSPACE_PEER !== undefined) {
- config.workspacePeer = envBool("OPENVIKING_WORKSPACE_PEER") ?? config.workspacePeer
- }
- if (process.env.OPENVIKING_MIN_QUERY_LENGTH) config.autoRecall.minQueryLength = process.env.OPENVIKING_MIN_QUERY_LENGTH
- if (process.env.OPENVIKING_AUTO_CAPTURE !== undefined) {
- config.autoCapture = envBool("OPENVIKING_AUTO_CAPTURE") ?? config.autoCapture
- }
- if (process.env.OPENVIKING_CAPTURE_MODE) config.captureMode = process.env.OPENVIKING_CAPTURE_MODE
- if (process.env.OPENVIKING_CAPTURE_MAX_LENGTH) config.captureMaxLength = process.env.OPENVIKING_CAPTURE_MAX_LENGTH
- if (process.env.OPENVIKING_CAPTURE_ASSISTANT_TURNS !== undefined) {
- config.captureAssistantTurns = envBool("OPENVIKING_CAPTURE_ASSISTANT_TURNS") ?? config.captureAssistantTurns
- }
- if (process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS) {
- config.captureToolMaxChars = process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS
- }
- if (process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD) {
- config.commitTokenThreshold = process.env.OPENVIKING_COMMIT_TOKEN_THRESHOLD
- }
- if (process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT) {
- config.commitKeepRecentCount = process.env.OPENVIKING_COMMIT_KEEP_RECENT_COUNT
- }
- if (process.env.OPENVIKING_PROFILE_TOKEN_BUDGET) config.profileTokenBudget = process.env.OPENVIKING_PROFILE_TOKEN_BUDGET
- if (process.env.OPENVIKING_RESUME_CONTEXT_BUDGET) config.resumeContextBudget = process.env.OPENVIKING_RESUME_CONTEXT_BUDGET
- if (process.env.OPENVIKING_NO_AUTO_INJECT !== undefined) {
- config.noAutoInject = envBool("OPENVIKING_NO_AUTO_INJECT") ?? config.noAutoInject
- }
- if (process.env.OPENVIKING_BYPASS_SESSION !== undefined) {
- config.bypassSession = envBool("OPENVIKING_BYPASS_SESSION") ?? config.bypassSession
- }
- if (process.env.OPENVIKING_BYPASS_SESSION_PATTERNS) {
- config.bypassSessionPatterns = process.env.OPENVIKING_BYPASS_SESSION_PATTERNS
- .split(",")
- .map((item) => item.trim())
- .filter(Boolean)
- }
- if (process.env.OPENVIKING_DEBUG !== undefined) config.debug = envBool("OPENVIKING_DEBUG") ?? config.debug
- if (process.env.OPENVIKING_DEBUG_LOG) config.debugLogPath = process.env.OPENVIKING_DEBUG_LOG
-}
-
-function normalizeConfig(config) {
- config.endpoint = str(config.endpoint, DEFAULT_CONFIG.endpoint).replace(/\/+$/, "")
- config.baseUrl = config.endpoint
- config.accountId = config.account
- config.userId = config.user
- config.userAgent = USER_AGENT
- config.harness = "opencode"
- config.timeoutMs = normalizeNumber(config.timeoutMs, DEFAULT_CONFIG.timeoutMs, 1000, 300000)
- config.repoContext.cacheTtlMs = normalizeNumber(
- config.repoContext.cacheTtlMs,
- DEFAULT_CONFIG.repoContext.cacheTtlMs,
- 1000,
- 60 * 60 * 1000,
- )
- config.autoRecall.limit = Math.max(1, Math.min(50, Math.round(Number(config.autoRecall.limit) || 10)))
- config.autoRecall.scoreThreshold = Math.max(0, Math.min(1, Number(config.autoRecall.scoreThreshold) || 0))
- config.autoRecall.maxContentChars = Math.max(100, Math.min(5000, Math.round(Number(config.autoRecall.maxContentChars) || 500)))
- config.autoRecall.tokenBudget = Math.max(200, Math.min(50000, Math.round(Number(config.autoRecall.tokenBudget) || 2000)))
- config.autoRecall.minQueryLength = Math.max(1, Math.min(64, Math.round(Number(config.autoRecall.minQueryLength) || 3)))
- config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic"
- config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all"
- config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto"
- config.captureMaxLength = Math.max(200, Math.min(100000, Math.round(Number(config.captureMaxLength) || 24000)))
- config.captureToolMaxChars = Math.max(200, Math.min(1000000, Math.round(Number(config.captureToolMaxChars) || 1000000)))
- config.commitTokenThreshold = Math.max(1000, Math.round(Number(config.commitTokenThreshold) || 20000))
- const rawCommitKeepRecentCount = config.commitKeepRecentCount
- const commitKeepRecentCount = rawCommitKeepRecentCount == null ||
- (typeof rawCommitKeepRecentCount === "string" && rawCommitKeepRecentCount.trim() === "")
- ? Number.NaN
- : Number(rawCommitKeepRecentCount)
- config.commitKeepRecentCount = Number.isFinite(commitKeepRecentCount)
- ? Math.max(0, Math.round(commitKeepRecentCount))
- : DEFAULT_CONFIG.commitKeepRecentCount
- config.profileTokenBudget = Math.max(500, Math.round(Number(config.profileTokenBudget) || 10000))
- config.resumeContextBudget = Math.max(1024, Math.round(Number(config.resumeContextBudget) || 32000))
- if (!Array.isArray(config.bypassSessionPatterns)) config.bypassSessionPatterns = []
-
- config.recallLimit = config.autoRecall.limit
- config.scoreThreshold = config.autoRecall.scoreThreshold
- config.recallMaxContentChars = config.autoRecall.maxContentChars
- config.recallPreferAbstract = config.autoRecall.preferAbstract !== false
- config.recallTokenBudget = config.autoRecall.tokenBudget
- config.minQueryLength = config.autoRecall.minQueryLength
- return config
-}
-
export function loadConfig(pluginRoot, projectDirectory) {
- const config = cloneDefaultConfig()
- const { path: configPath, data: fileConfig } = readConfigFile(pluginRoot, projectDirectory)
- applyBehaviorConfig(config, fileConfig)
-
- const creds = resolveOpenVikingCredentials()
- config.endpoint = creds.baseUrl
- config.apiKey = creds.apiKey
- config.account = creds.account
- config.user = creds.user
- // Shared credentials only carry a peer when ovcli.conf sets actor_peer_id
- // (or OPENVIKING_PEER_ID is exported); without one the project config's
- // peerId still applies so authenticated setups keep writing peer-scoped
- // data instead of silently dropping into the shared user tree (#4487).
- config.peerId = creds.peerId || str(fileConfig.peerId, "")
- config.mcpUrl = creds.mcpUrl
- config.credentialSource = creds.credentialSource
- config.credentialPath = creds.cliPath || creds.ovPath || ""
-
- const mayUseLegacyCredentials = creds.credentialSource !== "env" &&
- creds.credentialSource !== "ovcli" &&
- !creds.apiKey &&
- !creds.account &&
- !creds.user &&
- !creds.peerId
- const legacyUsed = mayUseLegacyCredentials ? applyLegacyConnection(config, fileConfig) : false
- applyEnv(config)
- config.configPath = configPath
- config.legacyCredentialsUsed = legacyUsed && creds.credentialSource !== "env"
- const normalized = normalizeConfig(config)
- normalized.effectivePeer = resolveEffectivePeerId({ cfg: normalized, cwd: projectDirectory })
- return normalized
+ const config = buildPluginConfig("opencode", {
+ cwd: projectDirectory,
+ manifestUrl: MANIFEST_URL,
+ logFile: "opencode-plugin.log",
+ deriveEffectivePeer: true,
+ })
+
+ return {
+ ...config,
+ // The MCP registration, the runtime data directory, and the repo context
+ // cache.
+ mcp: { enabled: config.mcpEnabled },
+ runtime: { dataDir: config.dataDir },
+ repoContext: { enabled: config.repoContext, cacheTtlMs: config.repoContextCacheTtlMs },
+ }
}
export function resolveDataDir(pluginRoot, config) {
diff --git a/examples/opencode-plugin/lib/memory-recall.mjs b/examples/opencode-plugin/lib/memory-recall.mjs
index 3f6b3b9d6..6708d7c64 100644
--- a/examples/opencode-plugin/lib/memory-recall.mjs
+++ b/examples/opencode-plugin/lib/memory-recall.mjs
@@ -1,10 +1,10 @@
-import { buildRecallBlock } from "./shared/recall-core.mjs"
+import { buildRecallBlock, isRecallEnabled } from "./shared/recall-core.mjs"
import { isBypassed } from "./shared/session-model.mjs"
import { effectivePeerId, fetchJSON, log } from "./utils.mjs"
export function createMemoryRecall({ config, sessionManager }) {
async function injectRelevantMemories(input, output) {
- if (!config.autoRecall?.enabled) return
+ if (!isRecallEnabled(config)) return
const query = extractCurrentUserText(output.parts ?? [])
if (!query) return
if (query.length < config.minQueryLength) return
diff --git a/examples/opencode-plugin/lib/memory-session.mjs b/examples/opencode-plugin/lib/memory-session.mjs
index becb35e34..28ae4eea1 100644
--- a/examples/opencode-plugin/lib/memory-session.mjs
+++ b/examples/opencode-plugin/lib/memory-session.mjs
@@ -3,6 +3,7 @@ import path from "path"
import {
extractPartsFromPayload,
extractTextFromPayload,
+ isCaptureEnabled,
shouldCaptureText,
} from "./shared/capture-utils.mjs"
import {
@@ -46,7 +47,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {
}
async function init() {
- if (config.autoCapture) await migrateLegacySessionMap()
+ if (isCaptureEnabled(config)) await migrateLegacySessionMap()
await loadState()
const health = await fetchJSON(config, "/health", {}, { timeoutMs: 5000 })
if (health.ok) {
@@ -157,9 +158,9 @@ export function createMemorySessionManager({ config, pluginRoot }) {
await handleSessionCompacted(event)
} else if (event.type === "session.idle") {
await handleSessionIdle(event)
- } else if (event.type === "message.updated" && config.autoCapture) {
+ } else if (event.type === "message.updated" && isCaptureEnabled(config)) {
await handleMessageUpdated(event)
- } else if (event.type === "message.part.updated" && config.autoCapture) {
+ } else if (event.type === "message.part.updated" && isCaptureEnabled(config)) {
await handleMessagePartUpdated(event)
}
}
@@ -286,7 +287,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {
if (!state) return false
const added = await flushPendingMessages(opencodeSessionId, state)
- if (commit && config.autoCapture) {
+ if (commit && isCaptureEnabled(config)) {
await commitOvSession(state.ovSessionId, { force: true, reason })
} else if (added > 0) {
await maybeCommitByThreshold(state)
@@ -388,7 +389,7 @@ export function createMemorySessionManager({ config, pluginRoot }) {
}
async function flushPendingMessages(opencodeSessionId, state) {
- if (!config.autoCapture) return 0
+ if (!isCaptureEnabled(config)) return 0
const toSend = []
for (const [messageId, message] of state.messages.entries()) {
if (message.captured) continue
diff --git a/examples/opencode-plugin/lib/repo-context.mjs b/examples/opencode-plugin/lib/repo-context.mjs
index 600930475..b3a4f8127 100644
--- a/examples/opencode-plugin/lib/repo-context.mjs
+++ b/examples/opencode-plugin/lib/repo-context.mjs
@@ -1,4 +1,4 @@
-import { effectivePeerId, log, makeRequest, unwrapResponse } from "./utils.mjs"
+import { effectivePeerId, log, makeRequest } from "./utils.mjs"
export function createRepoContext({ config }) {
let cachedRepos = null
@@ -14,13 +14,12 @@ export function createRepoContext({ config }) {
}
try {
- const response = await makeRequest(config, {
+ const result = await makeRequest(config, {
method: "GET",
endpoint: `/api/v1/fs/ls?uri=${encodeURIComponent("viking://resources/")}&recursive=false&simple=false`,
timeoutMs: 8000,
actorPeerId: effectivePeerId(config),
})
- const result = unwrapResponse(response)
const items = Array.isArray(result) ? result : []
const repos = items
.filter((item) => item?.uri?.startsWith("viking://resources/") && item.uri !== "viking://resources/")
diff --git a/examples/opencode-plugin/lib/runtime.mjs b/examples/opencode-plugin/lib/runtime.mjs
index 298949c22..78031681a 100644
--- a/examples/opencode-plugin/lib/runtime.mjs
+++ b/examples/opencode-plugin/lib/runtime.mjs
@@ -1,24 +1,17 @@
-import { log, makeToast, normalizeEndpoint } from "./utils.mjs"
+import { fetchJSON, getResponseErrorMessage, log, makeToast } from "./utils.mjs"
+// The probe used to send a User-Agent and nothing else, so a server that wants
+// a key reported itself as down and the plugin disabled itself on startup.
export async function checkServiceHealth(config, timeoutMs = 3000) {
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), timeoutMs)
- try {
- const response = await fetch(`${normalizeEndpoint(config.endpoint)}/health`, {
- method: "GET",
- headers: config.userAgent ? { "User-Agent": config.userAgent } : undefined,
- signal: controller.signal,
- })
- return response.ok
- } catch (error) {
- log("WARN", "health", "OpenViking health check failed", {
- endpoint: config.endpoint,
- error: error?.message,
- })
- return false
- } finally {
- clearTimeout(timeout)
- }
+ const res = await fetchJSON(config, "/health", { method: "GET" }, { timeoutMs })
+ if (res.ok) return true
+
+ log("WARN", "health", "OpenViking health check failed", {
+ endpoint: config.endpoint,
+ status: res.status,
+ error: getResponseErrorMessage(res.error),
+ })
+ return false
}
export async function initializeRuntime(config, client) {
diff --git a/examples/opencode-plugin/lib/shared/batch-send.mjs b/examples/opencode-plugin/lib/shared/batch-send.mjs
deleted file mode 100644
index d7ec355cc..000000000
--- a/examples/opencode-plugin/lib/shared/batch-send.mjs
+++ /dev/null
@@ -1,121 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { enqueue } from "./pending-queue.mjs";
-import { isRetryableFailure } from "./retryable.mjs";
-
-export const BATCH_LIMIT = 100;
-
-export function isRetryableSendFailure(res) {
- return isRetryableFailure(res);
-}
-
-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/opencode-plugin/lib/shared/capture-utils.mjs b/examples/opencode-plugin/lib/shared/capture-utils.mjs
deleted file mode 100644
index 22bc1b63c..000000000
--- a/examples/opencode-plugin/lib/shared/capture-utils.mjs
+++ /dev/null
@@ -1,578 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { applyInputFilters, compileInputFilters } from "./input-filters.mjs";
-
-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",
-]);
-
-// Tool output is reported verbatim; the server owns truncation via
-// tool_output_externalization (threshold_chars, default 20000). This cap only
-// guards against pathological payloads.
-const DEFAULT_TOOL_MAX_CHARS = 1000000;
-
-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?.tool ||
- block?.function?.name ||
- block?.call?.name ||
- "",
- );
-}
-
-function toolPayload(block, kind) {
- if (!block || typeof block !== "object") return "";
- if (kind === "call") {
- return block.input ??
- block.state?.input ??
- block.arguments ??
- block.args ??
- block.params ??
- block.function?.arguments ??
- block.command ??
- block.call?.input ??
- block.call?.arguments ??
- "";
- }
- return block.output ??
- block.state?.output ??
- block.result ??
- block.error ??
- block.state?.error ??
- block.data ??
- block.content ??
- block.text ??
- "";
-}
-
-function toolId(block) {
- return oneLine(
- block?.call_id ||
- block?.callId ||
- 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?.isError || block?.state?.isError || block?.error || block?.state?.error) return "error";
- const status = oneLine(block?.status || block?.state?.status || "");
- return status || "completed";
-}
-
-function setToolInput(part, payload) {
- const input = parseMaybeJson(payload);
- if (input === "" || input == null) return;
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
-}
-
-function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, 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") {
- setToolInput(part, payload);
- } else {
- if (block?.state?.input !== undefined) {
- setToolInput(part, block.state.input);
- }
- 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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, 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: DEFAULT_TOOL_MAX_CHARS, 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;
-}
-
-/**
- * Prune blank text parts and run `cfg.captureFilters` over the ones that remain.
- *
- * One drop verdict is taken per turn, on the aggregate of its text parts; the
- * individual parts are then rewritten with the substitutions only, so a rule can
- * never both keep and drop the same turn. Tool call/result parts are carried
- * through untouched — filters match conversation text, not tool payloads — but a
- * turn dropped on its text takes its tool parts with it.
- */
-export function filterCaptureParts(parts, role, cfg = {}) {
- const kept = [];
- for (const part of parts || []) {
- if (!part) continue;
- if (part.type !== "text") {
- kept.push(part);
- continue;
- }
- const text = typeof part.text === "string" ? part.text.trim() : "";
- if (!text) continue;
- kept.push(text === part.text ? part : { ...part, text });
- }
-
- const blank = { parts: kept, dropped: false };
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (!compiled.rules.length || kept.length === 0) return blank;
-
- const textParts = kept.filter((part) => part.type === "text");
- if (textParts.length === 0) return blank;
-
- const verdict = applyInputFilters(textParts.map((part) => part.text).join("\n\n"), compiled.rules, {
- role,
- });
- if (verdict.dropped) return { parts: [], dropped: true };
-
- const out = [];
- for (const part of kept) {
- if (part.type !== "text") {
- out.push(part);
- continue;
- }
- const shaped = applyInputFilters(part.text, compiled.rules, { role, substituteOnly: true });
- if (!shaped.text) continue;
- out.push(shaped.text === part.text ? part : { ...part, text: shaped.text });
- }
- return { parts: out, dropped: out.length === 0 };
-}
-
-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 shaped = filterCaptureParts(parts, role, cfg);
- if (shaped.dropped) continue;
- // With parts on the wire the drop decision was already taken above, so the
- // text path only runs the filters for the `content` fallback. That also
- // keeps `turn.text` faithful for callers that scan it for trigger words.
- const decision = shouldCaptureText(rawText, role, cfg, { filters: shaped.parts.length === 0 });
- if (!decision.shouldCapture && shaped.parts.length === 0) continue;
- const text = decision.shouldCapture ? decision.text : "";
- turns.push({ role, text, parts: shaped.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 = {}, { filters = true } = {}) {
- const maxLength = cfg.captureMaxLength || 24000;
- const sanitized = sanitizeCapturedText(text);
- if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
-
- let capped = truncateCaptureText(sanitized, maxLength);
- if (filters) {
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (compiled.rules.length) {
- const verdict = applyInputFilters(capped, compiled.rules, { role });
- if (verdict.dropped) return { shouldCapture: false, reason: "filtered", text: "" };
- capped = verdict.text;
- if (!capped) return { shouldCapture: false, reason: "empty", text: "" };
- }
- }
- 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/opencode-plugin/lib/shared/credentials.mjs b/examples/opencode-plugin/lib/shared/credentials.mjs
deleted file mode 100644
index ba26a84dc..000000000
--- a/examples/opencode-plugin/lib/shared/credentials.mjs
+++ /dev/null
@@ -1,239 +0,0 @@
-// 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`;
-
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
- let credentialPath = "";
- if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
- }
-
- return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- credentialPath,
- 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/opencode-plugin/lib/shared/debug-log.mjs b/examples/opencode-plugin/lib/shared/debug-log.mjs
deleted file mode 100644
index 73855cf6d..000000000
--- a/examples/opencode-plugin/lib/shared/debug-log.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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/opencode-plugin/lib/shared/input-filters.mjs b/examples/opencode-plugin/lib/shared/input-filters.mjs
deleted file mode 100644
index e20bb03a7..000000000
--- a/examples/opencode-plugin/lib/shared/input-filters.mjs
+++ /dev/null
@@ -1,219 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Ordered, operator-configured regex filters for memory plugin input.
- *
- * Rules are sed-style strings, applied in order to a single piece of text:
- * s/^\s*ultrathink\s+//i substitute (add `g` to replace every match)
- * d|^\s*[/!]| drop the text when the pattern matches
- * k/^\?ov\b/ keep the text only when the pattern matches
- * user:d/^\s*\/clear\b/ apply to one role only
- *
- * A malformed rule becomes an entry in `errors` and is skipped rather than
- * throwing, so a typo in a config file cannot take a hook down.
- */
-
-const OPS = new Set(["s", "d", "k"]);
-const SCOPES = ["user", "assistant"];
-const ALLOWED_FLAGS = "imsug";
-
-export const INPUT_FILTER_KNOBS = [
- {
- key: "recallQueryFilters",
- env: "OPENVIKING_RECALL_QUERY_FILTERS",
- label: "recall query filters",
- },
- {
- key: "captureFilters",
- env: "OPENVIKING_CAPTURE_FILTERS",
- label: "capture filters",
- },
-];
-
-/**
- * Read one delimited field. `\` always consumes the next character, and only
- * `\<delim>` is un-escaped, so `\d` / `\b` / `\x2c` reach RegExp verbatim.
- * Returns the index of the closing delimiter, or -1 when it is missing.
- */
-function scanField(source, start, delim) {
- let out = "";
- let i = start;
- while (i < source.length) {
- const c = source[i];
- if (c === "\\") {
- const next = source[i + 1];
- if (next === undefined) {
- out += "\\";
- i += 1;
- continue;
- }
- out += next === delim ? next : "\\" + next;
- i += 2;
- continue;
- }
- if (c === delim) return { value: out, end: i };
- out += c;
- i += 1;
- }
- return { value: out, end: -1 };
-}
-
-export function parseInputFilterRule(source) {
- if (typeof source !== "string") {
- return { source: String(source ?? ""), error: "rule must be a string" };
- }
- const raw = source.trim();
- if (!raw) return { source: raw, error: "rule is empty" };
-
- let scope = "";
- let rest = raw;
- for (const candidate of SCOPES) {
- if (rest.startsWith(`${candidate}:`)) {
- scope = candidate;
- rest = rest.slice(candidate.length + 1);
- break;
- }
- }
-
- const op = rest[0] || "";
- if (!OPS.has(op)) {
- return {
- source: raw,
- error: `unknown operation "${op}" — expected s (substitute), d (drop) or k (keep)`,
- };
- }
- const delim = rest[1];
- if (delim === undefined) {
- return { source: raw, error: `missing delimiter after "${op}"` };
- }
- if (/[A-Za-z0-9\s\\]/.test(delim)) {
- return {
- source: raw,
- error: `invalid delimiter ${JSON.stringify(delim)} — use punctuation such as / | # or :`,
- };
- }
-
- const first = scanField(rest, 2, delim);
- const pattern = first.value;
- let replacement = null;
- let flagsRaw = "";
- if (op === "s") {
- if (first.end < 0) {
- return { source: raw, error: `missing ${JSON.stringify(delim)} after the pattern` };
- }
- const second = scanField(rest, first.end + 1, delim);
- if (second.end < 0) {
- return {
- source: raw,
- error: `missing ${JSON.stringify(delim)} after the replacement — write s${delim}pattern${delim}replacement${delim}`,
- };
- }
- replacement = second.value;
- flagsRaw = rest.slice(second.end + 1);
- } else {
- flagsRaw = first.end < 0 ? "" : rest.slice(first.end + 1);
- }
-
- if (!pattern) return { source: raw, error: "pattern is empty" };
-
- const flags = new Set();
- for (const flag of flagsRaw) {
- if (!ALLOWED_FLAGS.includes(flag)) {
- return { source: raw, error: `unknown flag "${flag}" — allowed flags are i, m, s, u, g` };
- }
- if (flags.has(flag)) return { source: raw, error: `duplicate flag "${flag}"` };
- flags.add(flag);
- }
- // d/k decide with .test(), which advances lastIndex on a global regex and
- // would then alternate between calls. `g` means nothing there, so drop it.
- if (op !== "s") flags.delete("g");
-
- let re;
- try {
- re = new RegExp(pattern, [...flags].join(""));
- } catch (err) {
- // V8 already says "Invalid regular expression: <pattern>: <why>"; keep that
- // detail without stuttering the prefix the doctors key off.
- const message = err?.message || String(err);
- return {
- source: raw,
- error: /^invalid regular expression/i.test(message)
- ? `invalid${message.slice("Invalid".length)}`
- : `invalid regular expression: ${message}`,
- };
- }
-
- return { op, scope, re, replacement, source: raw };
-}
-
-export function compileInputFilters(rules) {
- const compiled = [];
- const errors = [];
- const list = Array.isArray(rules) ? rules : [];
- list.forEach((entry, index) => {
- if (typeof entry !== "string") {
- errors.push({ index, source: String(entry ?? ""), message: "rule must be a string" });
- return;
- }
- if (!entry.trim()) return;
- const parsed = parseInputFilterRule(entry);
- if (parsed.error) errors.push({ index, source: parsed.source, message: parsed.error });
- else compiled.push({ ...parsed, index });
- });
- return { rules: compiled, errors };
-}
-
-/**
- * Run compiled rules over `text`.
- *
- * `substituteOnly` skips the d/k operations, so a caller that already took one
- * drop decision for a turn can rewrite its individual pieces without taking a
- * second, possibly contradictory one.
- */
-export function applyInputFilters(text, compiled, { role = "", substituteOnly = false } = {}) {
- const original = typeof text === "string" ? text : String(text ?? "");
- let current = original;
- for (const rule of Array.isArray(compiled) ? compiled : []) {
- if (rule.scope && rule.scope !== role) continue;
- if (rule.op === "s") {
- current = current.replace(rule.re, rule.replacement);
- continue;
- }
- if (substituteOnly) continue;
- const matched = rule.re.test(current);
- if ((rule.op === "d" && matched) || (rule.op === "k" && !matched)) {
- return { text: "", changed: false, dropped: true, ruleIndex: rule.index, op: rule.op };
- }
- }
- const finalText = current.trim();
- return {
- text: finalText,
- changed: finalText !== original,
- dropped: false,
- ruleIndex: -1,
- op: "",
- };
-}
-
-/** Doctor-facing summary of both filter knobs on a resolved plugin config. */
-export function describeInputFilters(cfg = {}) {
- return INPUT_FILTER_KNOBS.map(({ key, env, label }) => {
- const configured = Array.isArray(cfg?.[key]) ? cfg[key] : [];
- const compiled = compileInputFilters(configured);
- const ops = { s: 0, d: 0, k: 0 };
- for (const rule of compiled.rules) ops[rule.op] += 1;
- const bits = [];
- if (ops.s) bits.push(`${ops.s} substitute`);
- if (ops.d) bits.push(`${ops.d} drop`);
- if (ops.k) bits.push(`${ops.k} keep-only`);
- const active = compiled.rules.length;
- return {
- key,
- env,
- label,
- total: configured.length,
- active,
- summary: `${active} rule${active === 1 ? "" : "s"}${bits.length ? ` (${bits.join(", ")})` : ""}`,
- errors: compiled.errors,
- };
- });
-}
diff --git a/examples/opencode-plugin/lib/shared/mcp-proxy-config.mjs b/examples/opencode-plugin/lib/shared/mcp-proxy-config.mjs
deleted file mode 100644
index 24d33d9fb..000000000
--- a/examples/opencode-plugin/lib/shared/mcp-proxy-config.mjs
+++ /dev/null
@@ -1,124 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Shared config shaping for the stdio MCP proxy entrypoints.
- *
- * Every harness loads its credentials differently, but the shape
- * `createOpenVikingMcpProxy` consumes is identical everywhere, and so is the
- * set of files whose changes must trigger a credential reload. Keeping that
- * here stops each entrypoint from re-deriving `~` expansion, URL trimming,
- * timeout clamping, and the watch list.
- */
-
-import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
-
-export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
-const MIN_PROXY_TIMEOUT_MS = 1000;
-
-export function trimSlash(value) {
- return String(value || "").replace(/\/+$/, "");
-}
-
-/** Expand a leading `~` and resolve to an absolute path; "" stays "". */
-export function normalizeConfigPath(value) {
- const raw = String(value || "").trim();
- if (!raw) return "";
- if (raw === "~") return homedir();
- if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
- return resolvePath(raw);
-}
-
-/**
- * The credential files every harness must watch: the two `OPENVIKING_*_FILE`
- * overrides and the two default locations under `~/.openviking`.
- */
-export function defaultCredentialPaths(env = process.env) {
- return [
- normalizeConfigPath(env.OPENVIKING_CLI_CONFIG_FILE),
- normalizeConfigPath(env.OPENVIKING_CONFIG_FILE),
- join(homedir(), ".openviking", "ovcli.conf"),
- join(homedir(), ".openviking", "ov.conf"),
- ].filter(Boolean);
-}
-
-/**
- * Resolve the actor peer header for a long-lived MCP proxy process.
- *
- * MCP servers may start in the plugin directory rather than the active
- * workspace, so their process cwd is not a reliable peer identity — and unlike
- * a hook, a long-lived proxy cannot re-derive one per turn. Broad recall
- * intentionally spans the authenticated user's peer workspaces and therefore
- * leaves the actor header unset. Actor-scoped recall needs an explicit peer so
- * isolation never depends on the proxy's launch directory.
- *
- * A missing one degrades to broad recall with a warning rather than refusing to
- * start: the proxy is what carries every memory tool, and taking those away
- * because a scope preference cannot be honoured costs the user far more than
- * the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
- */
-export function resolveMcpActorPeerId({
- peerId = "",
- recallPeerScope = "all",
- onWarn = null,
-} = {}) {
- if (recallPeerScope !== "actor") return "";
-
- const explicitPeerId = String(peerId || "").trim();
- if (explicitPeerId) return explicitPeerId;
-
- const message = "OpenViking MCP: actor-scoped recall needs an explicit peer id, which an MCP proxy cannot "
- + "derive from its launch directory. Falling back to broad recall across every peer under this user. "
- + "Set actor_peer_id in ovcli.conf, or OPENVIKING_PEER_ID in the MCP server environment, to scope it.";
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return "";
-}
-
-function uniq(values) {
- return [...new Set(values.filter(Boolean))];
-}
-
-/**
- * Shape a harness's loaded config into the object `createOpenVikingMcpProxy`
- * expects.
- *
- * `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
- * user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
- * harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
- */
-export function buildMcpProxyConfig({
- baseUrl = "",
- mcpUrl = "",
- apiKey = "",
- account = "",
- user = "",
- peerId = "",
- userAgent = "",
- timeoutMs,
- debug = false,
- debugLogPath = "",
- credentialSource = "auto",
- credentialPath = "",
- watchedPaths = [],
- env = process.env,
-} = {}) {
- return {
- mcpUrl: mcpUrl || `${trimSlash(baseUrl)}/mcp`,
- apiKey: apiKey || "",
- account: account || "",
- user: user || "",
- peerId: peerId || "",
- userAgent: userAgent || "",
- timeoutMs: Math.max(
- MIN_PROXY_TIMEOUT_MS,
- Number(timeoutMs) || DEFAULT_PROXY_TIMEOUT_MS,
- ),
- debug: debug === true,
- debugLogPath,
- credentialSource: credentialSource || "auto",
- credentialPath: credentialPath || "",
- watchedPaths: uniq([...watchedPaths, ...defaultCredentialPaths(env)]),
- };
-}
diff --git a/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjs b/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjs
deleted file mode 100644
index 9a8f5ba26..000000000
--- a/examples/opencode-plugin/lib/shared/mcp-proxy-core.mjs
+++ /dev/null
@@ -1,516 +0,0 @@
-// 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);
- if (err && err.name === "AbortError") {
- // Client-side timeout, not an outage: the server may be healthy and
- // still computing (rerank-inclusive find/search can legitimately take
- // longer than the default budget). Keep -32001 for genuine
- // connection failures so the two are not misdiagnosed as each other.
- return errorResponse(
- id,
- -32004,
- `OpenViking MCP request timed out after ${proxyConfig.timeoutMs}ms (${proxyConfig.mcpUrl}). The server may still be processing (rerank can be slow) — check /health or raise OPENVIKING_TIMEOUT_MS.`,
- { timeoutMs: proxyConfig.timeoutMs, mcpUrl: proxyConfig.mcpUrl, cause: msg },
- );
- }
- return errorResponse(
- id,
- -32001,
- `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that the OpenViking server (\`openviking-server\`) is reachable.`,
- { 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/opencode-plugin/lib/shared/pending-queue.mjs b/examples/opencode-plugin/lib/shared/pending-queue.mjs
deleted file mode 100644
index 38dccb1c8..000000000
--- a/examples/opencode-plugin/lib/shared/pending-queue.mjs
+++ /dev/null
@@ -1,487 +0,0 @@
-// 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. The queue is replayed in small
- * batches, either at session-start (consuming retry budgets, with
- * maxRetries/TTL) or by a long-running drainer that passes
- * `consumeRetries: false` so transient failures stay retryable.
- *
- * 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";
-import { isRetryableFailure } from "./retryable.mjs";
-
-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) {
- return isRetryableFailure(res);
-}
-
-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;
- }
-}
-
-/**
- * Release a claimed file back to the queue without consuming a retry. The
- * entry keeps its original filename, retry count, and createdAt position, so a
- * later run retries it as if this attempt never happened.
- */
-export async function releaseClaim(claimedFilename) {
- if (!claimedFilename.endsWith(".processing")) return null;
- const dir = getPendingDir();
- const restored = pendingFromProcessingFilename(claimedFilename);
- try {
- await rename(join(dir, claimedFilename), join(dir, restored));
- return restored;
- } 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
- * @param {object} [options]
- * @param {boolean} [options.consumeRetries=true] - when false, retryable
- * failures release their claim instead of incrementing the retry count, so
- * a background drainer can keep retrying a transient failure without
- * burning the session-start retry budget. Exhausted and non-retryable
- * entries are deleted exactly as in the default mode.
- * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
- */
-export async function replayPending(fetchJSON, log, options = {}) {
- const consumeRetries = options.consumeRetries !== false;
- 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 (entry.type === "commitSession") {
- log("pending-queue", {
- action: "commit-replay",
- sessionId: entry.sessionId,
- ok: Boolean(res?.ok),
- status: res?.result?.status || res?.status,
- trace_id: res?.traceId || res?.result?.trace_id,
- error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
- });
- }
-
- if (res?.ok) {
- await dequeue(claimedFilename);
- replayed++;
- } else if (!isRetryableReplayFailure(res)) {
- await dequeue(claimedFilename);
- skipped++;
- } else {
- if (consumeRetries) {
- await incrementRetry(claimedFilename, entry);
- } else {
- const released = await releaseClaim(claimedFilename);
- log("pending-queue", {
- action: released ? "replay-deferred" : "release-failed",
- sessionId: entry.sessionId,
- type: entry.type,
- status: res?.result?.status || res?.status,
- retries: entry.retries || 0,
- });
- }
- 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/opencode-plugin/lib/shared/profile-inject.mjs b/examples/opencode-plugin/lib/shared/profile-inject.mjs
deleted file mode 100644
index 3f601844a..000000000
--- a/examples/opencode-plugin/lib/shared/profile-inject.mjs
+++ /dev/null
@@ -1,294 +0,0 @@
-// 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/opencode-plugin/lib/shared/recall-compress-core.mjs b/examples/opencode-plugin/lib/shared/recall-compress-core.mjs
deleted file mode 100644
index 1ced4cf4d..000000000
--- a/examples/opencode-plugin/lib/shared/recall-compress-core.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
-
-export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
-export const DIGEST_HEADER = "OpenViking memory digest:";
-const COMPRESS_OK = "ok";
-const COMPRESS_EMPTY = "empty";
-const COMPRESS_FAILED = "failed";
-
-// Medium-constraint prompt: state the goal and two structural floors, but no hard
-// bullet-length contract. Hard per-bullet limits pin the digest to headline
-// density; leaving it unconstrained lets small models rewrite long URIs into dead
-// links, which the URI repair below cleans up.
-export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
- return `You are a memory relevance compressor utility.
-Do not use any tools. Do not investigate. Only transform the given text.
-
-User query:
-${query}
-
-Retrieved OpenViking context fragments:
-${rendered}
-
-Write a memory digest for a coding agent about to answer that query. Keep the
-concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
-and conversational filler.
-
-Format rules:
-- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
-- Start every bullet with "- ".
-- End every bullet with its source, copied verbatim from the fragments above:
- "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
-- Output the digest body only. No preamble, no closing remark.
-
-If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
-}
-
-function editDistance(a, b) {
- if (a === b) return 0;
- const rows = a.length + 1;
- const cols = b.length + 1;
- let prev = Array.from({ length: cols }, (_, i) => i);
- for (let i = 1; i < rows; i += 1) {
- const cur = [i];
- for (let j = 1; j < cols; j += 1) {
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
- cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
- }
- prev = cur;
- }
- return prev[cols - 1];
-}
-
-function nearestUri(candidate, validUris) {
- let best = "";
- let bestDistance = Infinity;
- for (const uri of validUris) {
- const distance = editDistance(candidate, uri);
- if (distance < bestDistance) {
- best = uri;
- bestDistance = distance;
- }
- }
- // Only repair near-misses; an unrelated hallucination is dropped instead.
- const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
- return bestDistance <= tolerance ? best : "";
-}
-
-/**
- * Small models occasionally mangle long URIs. Snap every cited URI back onto the
- * set the server actually returned, and drop bullets whose citation cannot be
- * recovered so the digest never carries a dead link.
- */
-export function repairDigestUris(digest, validUris = []) {
- const text = String(digest || "");
- if (!text) return "";
- const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
- if (!valid.length) return text;
- const validSet = new Set(valid);
-
- const lines = [];
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim().startsWith("- ")) {
- lines.push(line);
- continue;
- }
- let tokenized = line;
- for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
- if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
- }
- let dropped = false;
- const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
- let decoded = uri;
- try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
- if (validSet.has(decoded)) return decoded;
- const nearest = nearestUri(decoded, valid);
- if (nearest) return nearest;
- dropped = true;
- return uri;
- });
- if (!dropped) lines.push(repaired);
- }
- return lines.join("\n").trim();
-}
-
-export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
- const text = String(raw || "").trim();
- if (!text) return null;
- if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
- const bullets = text.split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
- .slice(0, Math.max(1, maxBullets))
- .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
- if (!bullets.length) return null;
- return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
-}
-
-export function recallDigestCacheKey({
- query = "",
- rendered = "",
- entries = [],
- maxInputChars = 18000,
- maxBullets = 6,
-} = {}) {
- const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
- const source = JSON.stringify({
- version: 2,
- query: String(query),
- rendered: String(rendered).slice(0, maxInputChars),
- uris,
- maxInputChars,
- maxBullets,
- });
- return createHash("sha256").update(source).digest("hex");
-}
-
-async function readCache(path) {
- if (!path) return null;
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeCache(path, value) {
- if (!path) return;
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-export async function compressRecallContext({
- query,
- rendered,
- shortContext = rendered,
- entries = [],
- cfg = {},
- runCompressor,
- cachePath = "",
- now = 0,
-}) {
- const input = String(rendered || "").trim();
- if (!input) return { status: COMPRESS_EMPTY, context: "" };
- const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
- if (input.length < minChars) {
- return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
- }
-
- const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
- const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
- const key = recallDigestCacheKey({
- query,
- rendered: input,
- entries,
- maxInputChars,
- maxBullets,
- });
- const cached = await readCache(cachePath);
- if (cached?.key === key && typeof cached.digest === "string") {
- const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
- if (digest) return { status: COMPRESS_OK, context: digest };
- }
-
- const prompt = buildRecallCompressionPrompt({
- query,
- rendered: input.slice(0, maxInputChars),
- maxBullets,
- });
- const raw = await runCompressor(prompt);
- const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
- if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
- if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
-
- const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
- const repaired = repairDigestUris(normalized, validUris.length
- ? validUris
- : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
- const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
- if (!digest) return { status: COMPRESS_FAILED, context: "" };
-
- await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
- return { status: COMPRESS_OK, context: digest };
-}
diff --git a/examples/opencode-plugin/lib/shared/recall-core.mjs b/examples/opencode-plugin/lib/shared/recall-core.mjs
deleted file mode 100644
index 72835de8f..000000000
--- a/examples/opencode-plugin/lib/shared/recall-core.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-
-import { compressRecallContext } from "./recall-compress-core.mjs";
-
-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://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-const DEFAULT_CONTEXT_LIMIT = 10;
-const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
-const DEFAULT_REWRITE_MAX_BULLETS = 6;
-const CODING_QUOTA_WEIGHTS = {
- events: 1,
- entities: 2,
- preferences: 1,
- experiences: 1,
- resources: 3,
- skills: 2,
-};
-
-let userSpaceCache = "";
-
-export function estimateTokens(text) {
- return text ? Math.ceil(String(text).length / 4) : 0;
-}
-
-function scaleQuotas(limit, weights) {
- const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
- const order = Object.keys(weights);
- const quotas = Object.fromEntries(order.map((key) => [key, 0]));
- if (slots < order.length) {
- for (const key of order) quotas[key] = 1;
- return quotas;
- }
-
- for (const key of order) quotas[key] = 1;
- const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
- const ideals = Object.fromEntries(
- order.map((key) => [key, slots * weights[key] / totalWeight]),
- );
- while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
- const key = order.reduce((best, candidate) => (
- ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
- ? candidate
- : best
- ));
- quotas[key] += 1;
- }
- return quotas;
-}
-
-function legacyMemoryQuotas(limit) {
- return {
- ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
- experiences: 0,
- };
-}
-
-function codingQuotas(limit) {
- return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
-}
-
-export function buildRecallEndpointBody(cfg = {}) {
- const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
- const body = {
- query: "",
- quotas: legacyMemoryQuotas(limit),
- 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;
-}
-
-/**
- * Body for the server-side context face. The plugin declares intent (coding
- * purpose, budget, session) and leaves the mechanics — quota ratios, tier
- * degradation, cross-turn dedup — to the server's defaults.
- */
-export function buildContextSearchBody(cfg = {}, options = {}) {
- const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
- const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
- const maxTokens = Math.max(
- 64,
- Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
- );
- const body = {
- query: "",
- mode: "context",
- purpose: "coding",
- score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
- };
- const limitConfigured = cfg.recallLimitConfigured === true;
- const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
- if (limitConfigured) body.quotas = codingQuotas(limit);
- if (maxTokensConfigured) body.max_tokens = maxTokens;
- if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
-
- const sessionId = String(options.sessionId || "").trim();
- if (sessionId) {
- body.session_id = sessionId;
- const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
- if (queryExpansionConfigured) {
- body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
- }
- const dedupTurns = Number(cfg.recallDedupTurns);
- const resolvedDedupTurns = Number.isFinite(dedupTurns)
- ? Math.max(0, Math.floor(dedupTurns))
- : 5;
- if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
- }
-
- const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
- if (excludeUris.length) body.exclude_uris = excludeUris;
-
- if (rewriteMode === "server") body.rewrite = true;
- else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
- const rewriteMaxBullets = Math.max(
- 1,
- Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
- );
- const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
- if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
- body.rewrite_max_bullets = rewriteMaxBullets;
- }
- return body;
-}
-
-// The server pipeline is serial and each optional stage has its own fuse. A
-// request is aborted client-side unless its deadline covers every stage it
-// asked for, and aborting discards the whole response rather than just the
-// stage that ran long.
-//
-// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
-// always -> retrieval, body reads, budget planning
-// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
-//
-// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
-// a quarter to spare.
-const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
-const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
-
-/**
- * HTTP deadline for one context request, or undefined to keep the caller's own.
- *
- * Derived from the request body, because the body is what states which server
- * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
- * that also spends the expansion or rewrite fuse.
- */
-export function contextRequestTimeoutMs(cfg = {}, body = {}) {
- const wantsRewrite = body.rewrite !== undefined;
- // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
- // takes the expansion fuse back out of the budget.
- const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
- const configured = Number(cfg.recallContextTimeoutMs);
- if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
- if (!wantsRewrite && !wantsExpansion) return undefined;
- const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
- return Math.max(Number(cfg.timeoutMs) || 0, floor);
-}
-
-/**
- * Strip the context-face fields a pre-context server rejects, converting the
- * token budget back to v1's character budget.
- */
-export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
- const body = buildRecallEndpointBody(cfg);
- body.query = contextBody.query || "";
- body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
- if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
- 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(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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");
-}
-
-const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
-
-function stateFile(name) {
- const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
- return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
-}
-
-async function readJsonFile(path) {
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeJsonFile(path, value) {
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Hooks are one-shot processes, so "this server has no context face" has to be
- * remembered on disk or every turn pays for a rejected request.
- */
-export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- const cached = await readJsonFile(path);
- return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
-}
-
-export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
-}
-
-/**
- * A `peer_scope` the server rejects is remembered the same way, but unlike the
- * context face this one is not a silent capability probe: dropping the field
- * widens recall from the caller's own peer to the whole user root, so doctor
- * reads this file back and warns.
- */
-export function peerScopeMemoPath() {
- return stateFile("peer-scope.json");
-}
-
-export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
- const cached = await readJsonFile(path);
- if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
- return cached;
-}
-
-export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
- await writeJsonFile(path, {
- legacyUntil: now + LEGACY_CACHE_TTL_MS,
- scope: String(scope || ""),
- status: Number(status) || 0,
- at: now,
- });
-}
-
-function looksLikeUnknownField(res) {
- const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
- return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
-}
-
-function wrapContext(body) {
- return [
- "<openviking-context>",
- "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
- body,
- "</openviking-context>",
- ].join("\n");
-}
-
-/**
- * Server-assembled context: the context face when the deployment has it, else
- * the deprecated /recall preset. Returns the injection block, "" when there was
- * nothing relevant, or null when no server-side path was usable at all.
- */
-export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
-
- const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
- if (block !== null) return block;
- return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
-}
-
-/**
- * Raw server-assembled context, or null when the deployment has no context face.
- * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
- * (their own compression, their own envelope) use this instead of the block
- * builders below.
- */
-export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId || "";
- const log = options.log || (() => {});
- if (await isContextFaceLegacy(options.legacyCachePath)) return null;
-
- const body = buildContextSearchBody(cfg, options);
- body.query = query;
- const res = await fetchJSON("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
-
- if (!res.ok) {
- const status = res.status || 0;
- if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
- await markContextFaceLegacy(options.legacyCachePath);
- log("recall_context_face_unsupported", { status });
- } else {
- log("recall_context_face_error", { status });
- }
- return null;
- }
-
- const result = res.result || {};
- const stats = result.stats || {};
- log("recall_context_assembled", {
- entries: Array.isArray(result.entries) ? result.entries.length : 0,
- usedTokens: stats.used_tokens || 0,
- tiers: stats.tier_counts || {},
- rewrite: stats.rewrite || "off",
- });
- return {
- rendered: String(result.rendered || "").trim(),
- entries: Array.isArray(result.entries) ? result.entries : [],
- digest: String(result.digest || "").trim(),
- stats,
- };
-}
-
-/**
- * Entry field compatibility: the context face returns `category`/`text`, while
- * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
- */
-export function normalizeContextEntry(entry = {}) {
- return {
- uri: String(entry.uri || "").trim(),
- category: String(entry.category || entry.type || "memory").trim() || "memory",
- detail: String(entry.detail || entry.mode || "").trim(),
- score: Number(entry.score) || 0,
- text: String(
- entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
- ).trim(),
- };
-}
-
-async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
- const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
- if (assembled === null) return null;
-
- const { rendered, entries } = assembled;
- let digest = assembled.digest;
- const mode = String(cfg.recallRewrite || "off").toLowerCase();
- if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
- log("recall_server_compression", { status: "empty" });
- return "";
- }
- const wantsLocal = mode === "client" || (mode === "auto" && !digest);
- if (wantsLocal && rendered && typeof options.runCompressor === "function") {
- try {
- const compression = await compressRecallContext({
- query,
- rendered,
- entries,
- cfg,
- runCompressor: options.runCompressor,
- cachePath: options.digestCachePath || stateFile("recall-digest.json"),
- now: Date.now(),
- });
- log("recall_local_compression", { status: compression.status });
- if (compression.status === "ok") digest = compression.context;
- if (compression.status === "empty") return "";
- } catch (err) {
- log("recall_local_compression_failed", { error: String(err?.message || err) });
- }
- }
-
- const injected = digest || rendered;
- if (!injected) return "";
- return wrapContext(injected);
-}
-
-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 wrapContext(rendered);
-}
-
-export async function postRecall(fetchJSON, body, opts = {}) {
- const actorPeerId = opts.actorPeerId || "";
- const log = opts.log || (() => {});
- const memoPath = opts.peerScopeMemoPath;
- const request = { ...body };
-
- // A remembered downgrade is still a downgrade: recall runs wider than the
- // caller asked for, so the memo doubles as the doctor's evidence.
- if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
- delete request.peer_scope;
- }
-
- 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;
- }
- // Only an unknown-field rejection means "this server predates peer_scope".
- // Retrying every other 400/422 without it silently widens the search from
- // the caller's own peer to the whole user root.
- if (!looksLikeUnknownField(res)) {
- log("recall_peer_scope_error", { status: res.status || 0 });
- return res;
- }
-
- const downgraded = { ...request };
- delete downgraded.peer_scope;
- await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
- log("recall_peer_scope_downgrade", { status: res.status || 0 });
- return fetchJSON("/api/v1/search/recall", {
- method: "POST",
- body: JSON.stringify(downgraded),
- }, { actorPeerId });
-}
-
-/**
- * Recall, plus whatever is still filed under the peer this workspace used
- * before the identity rule changed.
- *
- * Under the default `peer_scope: "all"` this costs nothing: the server's own
- * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
- * `"actor"` that sweep is off by definition, so the old peer is asked for
- * separately — as itself, which is both cheaper and wider than a bare
- * cross-peer read (that would need the user id, and reaches memories only).
- */
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
- const primary = await recallForPeer(fetchJSON, cfg, query, options);
-
- const legacyPeerId = String(options.legacyPeerId || "").trim();
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
-
- const log = options.log || (() => {});
- const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
-}
-
-async function recallForPeer(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
- const trimmed = String(query || "").trim();
- if (!trimmed) return null;
-
- // Assembly happens server-side when the deployment offers the context face;
- // older servers fall through to /recall, then to raw find.
- const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
- ...options,
- actorPeerId,
- log,
- });
- if (serverBlock !== null) return serverBlock || null;
-
- const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
- 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/opencode-plugin/lib/shared/retryable.mjs b/examples/opencode-plugin/lib/shared/retryable.mjs
deleted file mode 100644
index 8be4b14e8..000000000
--- a/examples/opencode-plugin/lib/shared/retryable.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-export function isRetryableFailure(result) {
- if (!result || result.ok) return false;
- const status = Number(result.status || 0);
- if (!status || status === 408 || status === 429 || status >= 500) {
- return true;
- }
- return status === 409 && result.error?.details?.retryable === true;
-}
diff --git a/examples/opencode-plugin/lib/shared/session-model.mjs b/examples/opencode-plugin/lib/shared/session-model.mjs
deleted file mode 100644
index b6496a113..000000000
--- a/examples/opencode-plugin/lib/shared/session-model.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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/opencode-plugin/lib/shared/setup-wizard.mjs b/examples/opencode-plugin/lib/shared/setup-wizard.mjs
deleted file mode 100644
index a49dbe7db..000000000
--- a/examples/opencode-plugin/lib/shared/setup-wizard.mjs
+++ /dev/null
@@ -1,114 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.
- *
- * Lets a pure-marketplace install (no installer script) configure the server
- * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:
- *
- * node <plugin>/scripts/setup.mjs
- *
- * Conventions: show current values, keep existing secrets on empty input,
- * merge-write (never drop unknown fields), back up the previous file, 0600.
- */
-
-import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
-import { dirname } from "node:path";
-import { createInterface } from "node:readline/promises";
-import { loadCredentialFiles } from "./credentials.mjs";
-
-const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";
-const LOCAL_URL = "http://127.0.0.1:1933";
-
-function maskSecret(value) {
- const s = String(value || "");
- if (!s) return "(not set)";
- if (s.length <= 8) return "****";
- return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;
-}
-
-function readJsonSafe(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return {};
- }
-}
-
-export async function runSetupWizard({
- input = process.stdin,
- output = process.stdout,
- env = process.env,
-} = {}) {
- // cliPath is empty until the file exists; first-run writes go to the candidate
- // path (OPENVIKING_CLI_CONFIG_FILE, else ~/.openviking/ovcli.conf).
- const { cliPath, cliPathCandidate } = loadCredentialFiles(env);
- const targetPath = cliPath || cliPathCandidate;
- const current = readJsonSafe(targetPath);
- const rl = createInterface({ input, output });
- const say = (line = "") => output.write(`${line}\n`);
-
- try {
- say("OpenViking memory plugin setup");
- say(`Config file: ${targetPath}`);
- say("");
- say("Current values:");
- say(` url: ${current.url || "(not set)"}`);
- say(` api_key: ${maskSecret(current.api_key)}`);
- if (current.account) say(` account: ${current.account}`);
- if (current.user) say(` user: ${current.user}`);
- say("");
-
- const defaultUrl = current.url || LOCAL_URL;
- say("Where do you connect to OpenViking?");
- say(` 1) Self-hosted / local [${LOCAL_URL}]`);
- say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);
- say(` 3) Custom URL / keep current [${defaultUrl}]`);
- const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();
- let url = defaultUrl;
- if (mode === "1") {
- url = LOCAL_URL;
- } else if (mode === "2") {
- url = CLOUD_URL;
- } else {
- const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();
- if (answer) url = answer;
- }
-
- const keyPrompt = current.api_key
- ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `
- : "API key (leave empty for unauthenticated local mode): ";
- const keyAnswer = await rl.question(keyPrompt);
- let apiKey = current.api_key || "";
- if (keyAnswer === "-") apiKey = "";
- else if (keyAnswer.trim()) apiKey = keyAnswer.trim();
- else if (!current.api_key) apiKey = "";
-
- const next = { ...current, url, api_key: apiKey };
-
- say("");
- say("Changes:");
- say(` url: ${current.url || "(not set)"} -> ${next.url}`);
- say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);
- const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();
- if (confirm === "n" || confirm === "no") {
- say("Aborted; nothing written.");
- return { written: false, path: targetPath };
- }
-
- mkdirSync(dirname(targetPath), { recursive: true });
- if (existsSync(targetPath)) {
- copyFileSync(targetPath, `${targetPath}.bak.${Date.now()}`);
- }
- writeFileSync(targetPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
- try {
- chmodSync(targetPath, 0o600);
- } catch {
- /* best effort on platforms without chmod semantics */
- }
- say(`Written: ${targetPath}`);
- say("The stdio MCP proxy and hooks pick this up on the next harness start.");
- return { written: true, path: targetPath };
- } finally {
- rl.close();
- }
-}
diff --git a/examples/opencode-plugin/lib/shared/uri-guard.mjs b/examples/opencode-plugin/lib/shared/uri-guard.mjs
deleted file mode 100644
index cf57bf406..000000000
--- a/examples/opencode-plugin/lib/shared/uri-guard.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// 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();
-}
-
-// Arguments that carry file CONTENT rather than a location. The sweep below
-// looks past the known path keys so an unusual one (`paths`, a nested target)
-// is still caught, but text a tool is asked to WRITE is not a path: a local
-// `write` whose body merely mentions viking://user/default/ was denied, and no
-// file was created. Skipped by name at any depth.
-const DEFAULT_CONTENT_KEYS = [
- "content",
- "contents",
- "text",
- "body",
- "old_string",
- "oldString",
- "new_string",
- "newString",
- "old_str",
- "new_str",
- "file_text",
- "insert_line",
- "replacement",
-];
-
-export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_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, new Set(contentKeys));
-}
-
-export function findVikingUriInValue(value, skipKeys) {
- 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, skipKeys);
- if (uri) return uri;
- }
- return null;
- }
- if (value && typeof value === "object") {
- for (const [key, item] of Object.entries(value)) {
- if (skipKeys?.has(key)) continue;
- const uri = findVikingUriInValue(item, skipKeys);
- 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/opencode-plugin/lib/shared/workspace-identity.mjs b/examples/opencode-plugin/lib/shared/workspace-identity.mjs
deleted file mode 100644
index 76922cb03..000000000
--- a/examples/opencode-plugin/lib/shared/workspace-identity.mjs
+++ /dev/null
@@ -1,334 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Workspace identity: where the workspace root is, and what git calls it.
- *
- * Every hook is a fresh Node process and this runs on prompt-level paths, so
- * the derivation is pure filesystem work — no `git` subprocess. That keeps it
- * inside the tightest hook budget (Codex allows SessionEnd 3s against
- * SessionStart's 70s), and it keeps working where git is absent from PATH or
- * would refuse the repo over dubious ownership.
- *
- * The result is cached per cwd under the state dir so the several hooks of one
- * turn pay for the walk once.
- */
-
-import { createHash } from "node:crypto";
-import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
-
-// The workspace config file names live here, and `workspace-config.mjs`
-// re-exports them: the walk below needs the filenames to recognise a directory
-// someone marked as a workspace, and it must not pull in the config layer to
-// learn them.
-export const CONFIG_DIR_NAME = ".openviking";
-export const TEAM_FILE = "config.json";
-export const LOCAL_FILE = "config.local.json";
-
-const IDENTITY_CACHE_TTL_MS = 60_000;
-// 255 is the AGFS path-segment limit; stopping well short leaves room for the
-// hash suffix and for anything that later prefixes a peer id.
-const MAX_PEER_ID_LENGTH = 100;
-
-export function stateDir(env = process.env) {
- const explicit = String(env.OPENVIKING_STATE_DIR || "").trim();
- if (explicit) return explicit;
- const home = String(env.OPENVIKING_HOME || "").trim();
- const base = home ? home.replace(/^~(?=$|\/)/, homedir()) : join(homedir(), ".openviking");
- return join(base, "state");
-}
-
-function shortHash(value) {
- return createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
-}
-
-/**
- * Legacy peer sanitation: one byte in, one byte out, no collapsing and no
- * trimming, so a leading `/` still becomes a leading `-`. Kept byte-exact
- * because `peer.source: "cwd"` and the legacy id that dual-read recomputes both
- * depend on it — do not "improve" it.
- */
-export function legacySanitize(value) {
- return String(value || "").replace(/[^A-Za-z0-9]/g, "-");
-}
-
-/**
- * Readable sanitation for values that were never path-shaped — a normalized
- * remote, a directory name. Mirrors the server's own `_sanitize_component`
- * (`openviking/ingest/peer.py:32`) so both languages agree on the id, then
- * enforces what `validate_identifier_part` additionally requires.
- */
-export function sanitizePeerId(value) {
- const raw = String(value || "").trim();
- let cleaned = raw.replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
- if (!cleaned) return "";
- // The server accepts at most one `@` in an identifier part.
- const at = cleaned.indexOf("@");
- if (at !== -1) cleaned = cleaned.slice(0, at + 1) + cleaned.slice(at + 1).replace(/@/g, "-");
- // `ext-` is the server's namespace for base64-encoded external identities,
- // and `__self` its operation-target sentinel. Neither is ours to occupy.
- if (cleaned.startsWith("ext-")) cleaned = `x-${cleaned}`;
- if (cleaned === "__self") cleaned = "self";
- if (cleaned === "." || cleaned === "..") return "";
- if (cleaned.length > MAX_PEER_ID_LENGTH) {
- cleaned = `${cleaned.slice(0, MAX_PEER_ID_LENGTH - 13).replace(/[-.]+$/, "")}-${shortHash(raw)}`;
- }
- return cleaned;
-}
-
-/**
- * Normalize a remote URL to `host/path`, lowercased.
- *
- * Both spellings of the same repo converge, and userinfo is dropped — so a
- * remote with an embedded token cannot leak it into a peer id. The cost of
- * case folding is that two repos differing only in case share one namespace on
- * the rare case-sensitive forge.
- */
-export function normalizeGitRemote(url) {
- const raw = String(url || "").trim();
- if (!raw) return "";
-
- // `C:\src\repo` and `C:/src/repo` are one machine's directory, not a shared
- // identity — and the scp pattern would happily read the drive as a host.
- if (/^[A-Za-z]:[\\/]/.test(raw)) return "";
-
- let host = "";
- let path = "";
- const scp = /^(?:[^@/\\]+@)?([^:/\\]+):(?!\/)(.+)$/.exec(raw);
- if (scp && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {
- host = scp[1];
- path = scp[2];
- } else {
- let parsed;
- try {
- parsed = new URL(raw);
- } catch {
- return "";
- }
- // A local clone has no stable shared identity — fall through to the path
- // rules instead of minting one from `file://` or a bare directory.
- if (parsed.protocol === "file:" || !parsed.hostname) return "";
- host = parsed.hostname;
- path = parsed.pathname;
- }
-
- host = host.toLowerCase().replace(/^\[|\]$/g, "");
- path = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
- if (!host || !path) return "";
- return `${host}/${path}`;
-}
-
-function readFileOrEmpty(path) {
- try {
- return readFileSync(path, "utf-8");
- } catch {
- return "";
- }
-}
-
-/**
- * Read `[remote "origin"] url` out of a git config with a minimal INI parse.
- *
- * `include` / `includeIf` are deliberately not followed: resolving them means
- * more filesystem walking for a value the fallback chain already covers, so an
- * unreadable remote just falls through to the next template.
- */
-export function readGitRemoteUrl(commonDir, remote = "origin") {
- const text = readFileOrEmpty(join(commonDir, "config"));
- if (!text) return "";
-
- let inSection = false;
- for (const line of text.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;
- const section = /^\[([^\]]+)\]/.exec(trimmed);
- if (section) {
- const header = section[1].trim();
- // git folds section and key names to lower case but keeps a quoted
- // subsection exact, so `[Remote "origin"]` is the same section and
- // `[remote "Origin"]` is not.
- const quoted = /^remote\s+"(.*)"$/i.exec(header);
- inSection = Boolean(quoted && quoted[1] === remote);
- continue;
- }
- if (!inSection) continue;
- const pair = /^url\s*=\s*(.*)$/i.exec(trimmed);
- // git treats an unquoted `#` or `;` as starting a comment anywhere on the
- // line, so a trailing note is not part of the URL.
- if (pair) return pair[1].split(/[#;]/)[0].trim().replace(/^["']|["']$/g, "");
- }
- return "";
-}
-
-function resolveGitDir(root) {
- const dotGit = join(root, ".git");
- let stat;
- try {
- stat = statSync(dotGit);
- } catch {
- return null;
- }
- if (stat.isDirectory()) return { gitDir: dotGit, commonDir: dotGit, kind: "repo" };
- if (!stat.isFile()) return null;
-
- const pointer = /^gitdir:\s*(.+)$/m.exec(readFileOrEmpty(dotGit));
- if (!pointer) return null;
- const gitDir = resolve(root, pointer[1].trim());
-
- // `commondir` is the worktree signal, so it is read first — a repository
- // that merely lives under a directory called `modules` is not a submodule.
- const commonRef = readFileOrEmpty(join(gitDir, "commondir")).trim();
- const commonDir = commonRef
- ? (isAbsolute(commonRef) ? commonRef : resolve(gitDir, commonRef))
- : gitDir;
-
- // A submodule keeps its own remote under the superproject's
- // `.git/modules/<name>`; converging it onto the superproject would merge two
- // repositories that release, and are reviewed, separately. Only the segment
- // right after a `.git` directory means that, which is also why a worktree of
- // a submodule resolves here through its own commondir.
- const kind = /[/\\]\.git[/\\]modules[/\\]/.test(`${commonDir}${sep}`)
- ? "submodule"
- : (commonRef ? "worktree" : "repo");
- return { gitDir, commonDir, kind };
-}
-
-/** A directory the user made a workspace on purpose, by giving it a config file. */
-function hasWorkspaceMarker(dir) {
- for (const name of [TEAM_FILE, LOCAL_FILE]) {
- try {
- if (statSync(join(dir, CONFIG_DIR_NAME, name)).isFile()) return true;
- } catch { /* not marked here */ }
- }
- return false;
-}
-
-const NO_ROOT = Object.freeze({ root: "", rootKind: "", git: null, gitRoot: "" });
-
-/**
- * Walk up from `cwd` to the nearest workspace root.
- *
- * A workspace is a git repository, or a directory someone marked as one by
- * creating `.openviking/config.json` (or `config.local.json`) in it. Nearest
- * wins. Above a marked directory the walk continues to the enclosing
- * repository, if any, so the git-shaped variables still resolve there.
- * Anything else — a scratch folder, a download, an app's per-task directory —
- * is not a workspace and gets no peer of its own.
- *
- * `$HOME` and the filesystem root are never workspace roots: a stray `.git`
- * in either would silently make every unrelated directory one workspace.
- */
-export function findWorkspaceRoot(cwd, env = process.env) {
- const start = String(cwd || "").trim();
- if (!start) return NO_ROOT;
-
- let absolute;
- try {
- // A relative `start` makes `resolve` read process.cwd(), which throws when
- // the directory is gone — the very case the catch below is meant to cover.
- absolute = resolve(start);
- } catch {
- return NO_ROOT;
- }
-
- // `current` and `stopAt` are compared as strings, so they must be
- // canonicalized together. A `$HOME` reached through a symlink plus an
- // unresolvable cwd would otherwise walk straight past the guard.
- const home = String(env.HOME || "").trim() || homedir();
- let current;
- let stopAt;
- try {
- current = realpathSync(absolute);
- stopAt = realpathSync(home);
- } catch {
- current = absolute;
- stopAt = home;
- }
- const filesystemRoot = parse(current).root;
- if (current === stopAt || current === filesystemRoot) return NO_ROOT;
-
- let root = "";
- let rootKind = "";
- while (current && current !== filesystemRoot && current !== stopAt) {
- const git = resolveGitDir(current);
- if (git) return { root: root || current, rootKind: rootKind || "git", git, gitRoot: current };
- if (!root && hasWorkspaceMarker(current)) {
- root = current;
- rootKind = "config";
- }
- const parent = dirname(current);
- if (parent === current) break;
- current = parent;
- }
- return root ? { root, rootKind, git: null, gitRoot: "" } : NO_ROOT;
-}
-
-function cachePath(cwd, env) {
- return join(stateDir(env), `ws-identity-${shortHash(cwd)}.json`);
-}
-
-function readCache(path, now) {
- try {
- const cached = JSON.parse(readFileSync(path, "utf-8"));
- // Bounded on both sides: an entry stamped in the future — a clock that ran
- // fast, or `Infinity` — would otherwise pin a stale identity indefinitely.
- if (typeof cached?.ts !== "number" || cached.ts > now || now - cached.ts > IDENTITY_CACHE_TTL_MS) return null;
- const identity = cached.identity;
- if (identity && typeof identity === "object" && identity.vars && typeof identity.vars === "object") {
- return identity;
- }
- } catch { /* a cold or corrupt cache just costs one walk */ }
- return null;
-}
-
-function writeCache(path, identity, now) {
- try {
- mkdirSync(dirname(path), { recursive: true });
- const tmp = `${path}.${process.pid}.tmp`;
- writeFileSync(tmp, JSON.stringify({ ts: now, identity }), { mode: 0o600 });
- renameSync(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Everything the peer templates can substitute, for one cwd.
- *
- * `git_remote` and `dir` are already sanitized; `git_root` and `cwd` carry the
- * legacy byte-for-byte rule, because they are the two that must reproduce a
- * peer minted before any of this existed.
- */
-export function resolveWorkspaceIdentity({ cwd = "", env = process.env, cache = true, now = Date.now() } = {}) {
- const key = String(cwd || "");
- const path = cachePath(key, env);
- if (cache) {
- const hit = readCache(path, now);
- if (hit) return hit;
- }
-
- const { root, rootKind, git, gitRoot } = findWorkspaceRoot(key, env);
- // Only the normalized form is kept. The raw URL may carry a token, and this
- // file outlives the process — writing it here would undo the care
- // `normalizeGitRemote` takes to drop userinfo.
- const remote = git ? normalizeGitRemote(readGitRemoteUrl(git.commonDir)) : "";
- const identity = {
- cwd: key,
- root,
- rootKind,
- isGit: Boolean(git),
- gitKind: git?.kind || "",
- gitCommonDir: git?.commonDir || "",
- gitRoot,
- remote,
- vars: {
- git_remote: sanitizePeerId(remote),
- // The enclosing repository's root, which is not the workspace root when a
- // marker file below it won. Empty outside a repository, so the `git`
- // preset resolves to nothing there rather than to a bare path.
- git_root: git ? legacySanitize(gitRoot) : "",
- cwd: legacySanitize(key),
- dir: root ? sanitizePeerId(root.split(/[/\\]/).filter(Boolean).pop() || "") : "",
- },
- };
- if (cache) writeCache(path, identity, now);
- return identity;
-}
diff --git a/examples/opencode-plugin/lib/shared/workspace-peer.mjs b/examples/opencode-plugin/lib/shared/workspace-peer.mjs
deleted file mode 100644
index 89df30793..000000000
--- a/examples/opencode-plugin/lib/shared/workspace-peer.mjs
+++ /dev/null
@@ -1,134 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Which peer a workspace writes its memories under.
- *
- * The peer used to be the working directory with every non-alphanumeric byte
- * turned into a dash, which made the identity an accident of where the
- * repository happened to sit: a clone on another machine, a rename, a worktree
- * or simply `cd examples/` each minted a separate, empty namespace. The default
- * is now git's own idea of the repository, so one project keeps one memory
- * wherever it is checked out.
- *
- * `peer.source` decides the rule. Presets cover the three answers most people
- * want; a template — or a list of templates tried in order — covers the rest.
- * The old behaviour is still one word away, byte for byte.
- */
-
-import { legacySanitize, resolveWorkspaceIdentity, sanitizePeerId } from "./workspace-identity.mjs";
-
-/**
- * `git` is the default, and it resolves only inside a repository: the remote
- * first, because that is the one name every clone agrees on, then the
- * repository root for a repo that has none. Anywhere else it resolves to
- * nothing and no peer is sent — a scratch folder or an app's per-task
- * directory would otherwise mint a fresh, empty namespace each time, so those
- * memories go to the user-level space instead. Naming such a directory is what
- * `peer.id` is for, and deriving one from a bare path is what `cwd` is for;
- * both are opt-in.
- *
- * No preset adds a prefix. A path-derived id starts with `-` on POSIX, so it
- * cannot collide with a remote-derived one; anyone who wants a prefix writes
- * their own template.
- */
-export const PEER_SOURCE_PRESETS = {
- git: ["{git_remote}", "{git_root}"],
- cwd: ["{cwd}"],
- none: [],
-};
-
-export const DEFAULT_PEER_SOURCE = "git";
-
-const VARIABLE_RE = /\{([a-z_]+)\}/g;
-
-export function deriveWorkspacePeerId(cwd) {
- return legacySanitize(cwd);
-}
-
-/**
- * Normalize `peer.source` — a preset name, a template, or a list — to templates.
- *
- * A bare string with no `{` is a misspelled preset, not a template: `Git` or
- * `gti` would otherwise become a peer literally named `Git`, quietly stranding
- * the workspace's memories in a namespace nobody meant to create. Such a value
- * warns and falls back to the default chain. An array is left alone — writing a
- * list is explicit enough to mean the constant it contains.
- */
-export function peerSourceTemplates(source, onWarn = null) {
- if (Array.isArray(source)) return source.map(String).filter(Boolean);
- const raw = String(source ?? "").trim();
- if (!raw) return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
- if (Object.hasOwn(PEER_SOURCE_PRESETS, raw)) return PEER_SOURCE_PRESETS[raw];
- if (raw.includes("{")) return [raw];
-
- const message = `OpenViking: ignored peer.source ${JSON.stringify(raw)}: it is neither a preset `
- + `(${Object.keys(PEER_SOURCE_PRESETS).join(", ")}) nor a template such as "team-{dir}". `
- + `Falling back to ${DEFAULT_PEER_SOURCE}.`;
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
-}
-
-/**
- * Substitute one template, or return "" when any variable it names is empty.
- *
- * All-or-nothing on purpose: a half-resolved template like `git-` would be a
- * silently shared identity, so an empty variable falls through to the next
- * template instead.
- */
-export function renderPeerTemplate(template, vars) {
- const text = String(template || "");
- if (!text) return "";
- let empty = false;
- const rendered = text.replace(VARIABLE_RE, (match, name) => {
- if (!Object.hasOwn(vars, name)) {
- empty = true;
- return "";
- }
- const value = String(vars[name] ?? "");
- if (!value) empty = true;
- return value;
- });
- return empty ? "" : rendered;
-}
-
-/**
- * The peer this process should send, and where it came from.
- *
- * `source` keeps its three values — call sites compare it against the literal
- * `"workspace"` to decide whether a session pin may be reused — while `origin`
- * names the template that actually produced the id, and `legacyPeerId` carries
- * the pre-git id whenever it differs, so recall can still reach memories
- * written under it.
- */
-export function resolveEffectivePeerId({ cfg = {}, cwd = "", identity = null, env = process.env, onWarn = null } = {}) {
- const explicit = String(cfg.peerId || "").trim();
- if (explicit) return { peerId: explicit, source: "explicit", origin: "explicit", legacyPeerId: "" };
-
- // `OPENVIKING_WORKSPACE_PEER=0` predates `peer.source` and still means "none".
- if (cfg.workspacePeer === false) return { peerId: "", source: "none", origin: "disabled", legacyPeerId: "" };
-
- const templates = peerSourceTemplates(cfg.peerSource, onWarn);
- if (!templates.length) return { peerId: "", source: "none", origin: "none", legacyPeerId: "" };
-
- // `harness` is composed here rather than in the identity, whose result is
- // cached on disk under a cwd-only key — two harnesses in one directory would
- // otherwise read each other's peer back out of that cache.
- const vars = {
- ...((identity || resolveWorkspaceIdentity({ cwd, env })).vars || {}),
- harness: sanitizePeerId(cfg.harness || cfg.clientId || ""),
- };
- const legacyPeerId = deriveWorkspacePeerId(cwd);
- for (const template of templates) {
- const peerId = renderPeerTemplate(template, vars);
- if (!peerId) continue;
- return {
- peerId,
- source: "workspace",
- origin: template,
- legacyPeerId: peerId === legacyPeerId ? "" : legacyPeerId,
- };
- }
- // No peer, but the pre-git id is still what earlier sessions in this
- // directory wrote under, so recall keeps reaching it.
- return { peerId: "", source: "none", origin: "unresolved", legacyPeerId };
-}
diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjs
index 8d4c365cc..24c264c93 100644
--- a/examples/opencode-plugin/lib/utils.mjs
+++ b/examples/opencode-plugin/lib/utils.mjs
@@ -1,6 +1,8 @@
import fs from "fs"
import path from "path"
+import { createOvHttp } from "./shared/ov-http.mjs"
+
let logFilePath = null
export function initLogger(dataDir) {
@@ -68,167 +70,49 @@ export function effectivePeerId(config) {
return String(config.effectivePeer?.peerId || config.peerId || "").trim() || null
}
-function responseTraceId(payload) {
- return payload?.result?.trace_id || payload?.error?.trace_id || payload?.trace_id || undefined
+// The config travels with every call here, so the client is built per call —
+// a closure next to a network round-trip costs nothing.
+function ovHttp(config) {
+ return createOvHttp(
+ { ...config, baseUrl: normalizeEndpoint(config.endpoint) },
+ { defaultTimeoutMs: config.timeoutMs },
+ )
}
export async function fetchJSON(config, endpoint, init = {}, options = {}) {
- const url = `${normalizeEndpoint(config.endpoint)}${endpoint}`
- const headers = makeAuthHeaders(
- config,
- { "Content-Type": "application/json", ...(init.headers ?? {}) },
- options.actorPeerId,
- )
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)
- try {
- const response = await fetch(url, {
- ...init,
- headers,
- signal: controller.signal,
- })
- const text = await response.text()
- const payload = text ? parseJsonOrText(text) : {}
- const traceId = responseTraceId(payload)
- if (!response.ok || payload?.status === "error") {
- return {
- ok: false,
- status: response.status,
- error: payload?.error || payload?.message || { message: `HTTP ${response.status}` },
- traceId,
- }
- }
- return { ok: true, status: response.status, result: payload?.result ?? payload, traceId }
- } catch (error) {
- return { ok: false, status: 0, error: { message: error?.message ?? String(error) } }
- } finally {
- clearTimeout(timeout)
- }
+ return ovHttp(config)(endpoint, init, options)
}
+/**
+ * `fetchJSON` for the callers that would rather catch than branch: it resolves
+ * to the unwrapped result and turns every failure into an Error whose message
+ * is what the user can act on.
+ */
export async function makeRequest(config, options) {
- const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`
- const headers = makeAuthHeaders(
- config,
- { "Content-Type": "application/json", ...(options.headers ?? {}) },
- options.actorPeerId,
- )
-
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)
- let onAbort = null
-
- if (options.abortSignal) {
- if (options.abortSignal.aborted) controller.abort()
- onAbort = () => controller.abort()
- options.abortSignal.addEventListener("abort", onAbort, { once: true })
- }
-
- try {
- const response = await fetch(url, {
- method: options.method,
- headers,
- body: options.body === undefined ? undefined : JSON.stringify(options.body),
- signal: controller.signal,
- })
-
- const text = await response.text()
- const payload = text ? parseJsonOrText(text) : {}
-
- if (!response.ok) {
- const rawError = typeof payload === "object" ? payload.error ?? payload.message : payload
- const errorMessage = typeof rawError === "string" ? rawError : JSON.stringify(rawError)
- if (response.status === 401 || response.status === 403) {
- throw new Error("Authentication failed. Please check apiKey/account/user in openviking-config.json or OPENVIKING_* environment variables.")
- }
- throw new Error(`Request failed (${response.status}): ${errorMessage}`)
- }
-
- return payload
- } catch (error) {
- if (error?.name === "AbortError") {
- throw new Error(`Request timeout after ${options.timeoutMs ?? config.timeoutMs}ms`)
- }
- if (error?.message?.includes("fetch failed") || error?.code === "ECONNREFUSED") {
- throw new Error(`OpenViking service unavailable at ${config.endpoint}. Start it with: openviking-server --config ~/.openviking/ov.conf`)
- }
- throw error
- } finally {
- clearTimeout(timeout)
- if (options.abortSignal && onAbort) {
- options.abortSignal.removeEventListener("abort", onAbort)
- }
- }
-}
-
-export async function makeMultipartRequest(config, options) {
- const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`
- const headers = makeAuthHeaders(config, options.headers ?? {}, options.actorPeerId)
-
- const controller = new AbortController()
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)
- let onAbort = null
-
- if (options.abortSignal) {
- if (options.abortSignal.aborted) controller.abort()
- onAbort = () => controller.abort()
- options.abortSignal.addEventListener("abort", onAbort, { once: true })
- }
-
- try {
- const response = await fetch(url, {
- method: options.method,
- headers,
- body: options.body,
- signal: controller.signal,
- })
-
- const text = await response.text()
- const payload = text ? parseJsonOrText(text) : {}
-
- if (!response.ok) {
- const rawError = typeof payload === "object" ? payload.error ?? payload.message : payload
- const errorMessage = typeof rawError === "string" ? rawError : JSON.stringify(rawError)
- if (response.status === 401 || response.status === 403) {
- throw new Error("Authentication failed. Please check apiKey/account/user in openviking-config.json or OPENVIKING_* environment variables.")
- }
- throw new Error(`Request failed (${response.status}): ${errorMessage}`)
+ const timeoutMs = options.timeoutMs ?? config.timeoutMs
+ const response = await fetchJSON(config, options.endpoint, {
+ method: options.method,
+ headers: options.headers,
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
+ }, { timeoutMs, actorPeerId: options.actorPeerId })
+ if (response.ok) return response.result
+
+ const message = getResponseErrorMessage(response.error)
+ // Status 0 is the transport: nothing answered, so the message is ours, not
+ // the server's, and it says what the user has to go fix.
+ if (response.status === 0) {
+ if (response.error?.aborted) {
+ throw new Error(`Request timeout after ${timeoutMs}ms`)
}
-
- return payload
- } catch (error) {
- if (error?.name === "AbortError") {
- throw new Error(`Request timeout after ${options.timeoutMs ?? config.timeoutMs}ms`)
- }
- if (error?.message?.includes("fetch failed") || error?.code === "ECONNREFUSED") {
+ if (message.includes("fetch failed") || message.includes("ECONNREFUSED")) {
throw new Error(`OpenViking service unavailable at ${config.endpoint}. Start it with: openviking-server --config ~/.openviking/ov.conf`)
}
- throw error
- } finally {
- clearTimeout(timeout)
- if (options.abortSignal && onAbort) {
- options.abortSignal.removeEventListener("abort", onAbort)
- }
+ throw new Error(message)
}
-}
-
-function makeAuthHeaders(config, headers = {}, actorPeerId = "") {
- const result = { ...headers }
- if (config.apiKey) result["Authorization"] = `Bearer ${config.apiKey}`
- if (config.account) result["X-OpenViking-Account"] = config.account
- if (config.user) result["X-OpenViking-User"] = config.user
- const peerId = String(actorPeerId || "").trim()
- if (peerId) result["X-OpenViking-Actor-Peer"] = peerId
- if (config.userAgent) result["User-Agent"] = config.userAgent
- return result
-}
-
-function parseJsonOrText(text) {
- try {
- return JSON.parse(text)
- } catch {
- return text
+ if (response.status === 401 || response.status === 403) {
+ throw new Error("Authentication failed. Check api_key/account/user in ~/.openviking/ovcli.conf, or the OPENVIKING_* environment variables.")
}
+ throw new Error(`Request failed (${response.status}): ${message}`)
}
export function getResponseErrorMessage(error) {
@@ -236,30 +120,3 @@ export function getResponseErrorMessage(error) {
if (typeof error === "string") return error
return error.message || error.code || "Unknown OpenViking error"
}
-
-export function unwrapResponse(response) {
- if (!response || typeof response !== "object") {
- throw new Error("OpenViking returned an invalid response")
- }
- if (response.status && response.status !== "ok") {
- throw new Error(getResponseErrorMessage(response.error))
- }
- return response.result
-}
-
-export function validateVikingUri(uri, toolName = "tool") {
- if (typeof uri !== "string" || !uri.startsWith("viking://")) {
- log("ERROR", toolName, "Invalid Viking URI", { uri })
- return 'Error: Invalid URI format. Must start with "viking://".'
- }
- return null
-}
-
-export function ensureRemoteUrl(value) {
- try {
- const url = new URL(value)
- return url.protocol === "http:" || url.protocol === "https:"
- } catch {
- return false
- }
-}
diff --git a/examples/opencode-plugin/lib/viking-uri-guard.mjs b/examples/opencode-plugin/lib/viking-uri-guard.mjs
index aa242faa1..5f3bc297e 100644
--- a/examples/opencode-plugin/lib/viking-uri-guard.mjs
+++ b/examples/opencode-plugin/lib/viking-uri-guard.mjs
@@ -1,5 +1,5 @@
import { log } from "./utils.mjs"
-import { buildGuardMessage, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs"
+import { evaluateUriGuard, findVikingUri, normalizeToolName } from "./shared/uri-guard.mjs"
const FILESYSTEM_TOOL_HINTS = {
read: {
@@ -19,18 +19,15 @@ const FILESYSTEM_TOOL_HINTS = {
export function createVikingUriGuard() {
return async (input, output) => {
const toolName = normalizeToolName(input?.tool ?? input?.name)
- const hint = FILESYSTEM_TOOL_HINTS[toolName]
- if (!hint) return
-
const args = output?.args ?? input?.args ?? {}
- const uri = findVikingUri(args)
- if (!uri) return
+ const decision = evaluateUriGuard(toolName, args, { hints: FILESYSTEM_TOOL_HINTS })
+ if (!decision) return
log("INFO", "viking-uri-guard", "Blocked filesystem tool for viking URI", {
tool: toolName,
- uri,
+ uri: decision.uri,
})
- throw new Error(buildGuardMessage(uri, { ...hint, example: hint.example(uri, args) }))
+ throw new Error(decision.reason)
}
}
diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json
index 56788b21c..5d3e04c46 100644
--- a/examples/opencode-plugin/package.json
+++ b/examples/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
- "version": "0.2.4",
+ "version": "0.3.0",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
@@ -23,8 +23,9 @@
"INSTALL-ZH.md"
],
"scripts": {
+ "prepack": "node ../memory-plugin-shared/sync.mjs",
"check": "node --check index.mjs && node --check lib/config.mjs && node --check lib/mcp-config.mjs && node --check lib/runtime.mjs && node --check lib/repo-context.mjs && node --check lib/memory-session.mjs && node --check lib/memory-recall.mjs && node --check lib/session-inject.mjs && node --check lib/viking-uri-guard.mjs && node --check lib/utils.mjs && node --check lib/shared/*.mjs && node --check servers/mcp-proxy.mjs && node --check scripts/setup.mjs && node --check tests/*.test.mjs",
- "test": "node --test tests/*.test.mjs servers/*.test.mjs"
+ "test": "node --test tests/*.test.mjs"
},
"dependencies": {},
"publishConfig": {
diff --git a/examples/opencode-plugin/servers/mcp-proxy.mjs b/examples/opencode-plugin/servers/mcp-proxy.mjs
index d33dc1357..5523be8d4 100644
--- a/examples/opencode-plugin/servers/mcp-proxy.mjs
+++ b/examples/opencode-plugin/servers/mcp-proxy.mjs
@@ -8,16 +8,13 @@
* requests to the server's /mcp endpoint, and keeps stdout protocol-clean.
*/
-import { homedir } from "node:os"
-import { join, resolve as resolvePath } from "node:path"
+import { resolve as resolvePath } from "node:path"
import { fileURLToPath } from "node:url"
import { loadConfig } from "../lib/config.mjs"
import { createLogger } from "../lib/shared/debug-log.mjs"
import { buildMcpProxyConfig, resolveMcpActorPeerId } from "../lib/shared/mcp-proxy-config.mjs"
import { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"
-export { createOpenVikingMcpProxy } from "../lib/shared/mcp-proxy-core.mjs"
-
function readProxyConfig() {
const cfg = loadConfig(resolvePath(fileURLToPath(import.meta.url), "..", ".."))
return buildMcpProxyConfig({
@@ -26,6 +23,7 @@ function readProxyConfig() {
apiKey: cfg.apiKey,
account: cfg.account,
user: cfg.user,
+ sendIdentityHeaders: cfg.sendIdentityHeaders,
peerId: resolveMcpActorPeerId(cfg),
userAgent: cfg.userAgent,
timeoutMs: cfg.timeoutMs,
@@ -33,11 +31,7 @@ function readProxyConfig() {
debugLogPath: cfg.debugLogPath,
credentialSource: cfg.credentialSource,
credentialPath: cfg.credentialPath || cfg.configPath,
- watchedPaths: [
- cfg.credentialPath,
- cfg.configPath,
- join(homedir(), ".config", "opencode", "openviking-config.json"),
- ],
+ watchedPaths: [cfg.credentialPath, cfg.configPath],
})
}
diff --git a/examples/opencode-plugin/servers/mcp-proxy.test.mjs b/examples/opencode-plugin/servers/mcp-proxy.test.mjs
deleted file mode 100644
index bdeb4f981..000000000
--- a/examples/opencode-plugin/servers/mcp-proxy.test.mjs
+++ /dev/null
@@ -1,102 +0,0 @@
-import test from "node:test"
-import assert from "node:assert/strict"
-import { createServer } from "node:http"
-import { Writable } from "node:stream"
-import { createOpenVikingMcpProxy } from "./mcp-proxy.mjs"
-
-function jsonRpc(id, result = {}) {
- return { jsonrpc: "2.0", id, result }
-}
-
-function sseMessage(obj) {
- return `event: message\r\ndata: ${JSON.stringify(obj)}\r\n\r\n`
-}
-
-async function readBody(req) {
- const chunks = []
- for await (const chunk of req) chunks.push(chunk)
- return Buffer.concat(chunks).toString("utf-8")
-}
-
-async function withServer(handler, fn) {
- const requests = []
- const server = createServer(async (req, res) => {
- const body = await readBody(req)
- const entry = {
- method: req.method,
- url: req.url,
- headers: req.headers,
- body: body ? JSON.parse(body) : null,
- }
- requests.push(entry)
- await handler(req, res, entry)
- })
- await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
- try {
- const { port } = server.address()
- return await fn({ url: `http://127.0.0.1:${port}/mcp`, requests })
- } finally {
- await new Promise((resolve) => server.close(resolve))
- }
-}
-
-function makeProxy(url) {
- const out = []
- const stdout = new Writable({
- write(chunk, _encoding, callback) {
- out.push(chunk.toString("utf-8"))
- callback()
- },
- })
- const proxy = createOpenVikingMcpProxy({
- stdout,
- readConfig: () => ({
- mcpUrl: url,
- apiKey: "test-key",
- account: "acct",
- user: "user",
- peerId: "peer",
- userAgent: "openviking-memory-opencode/9.9.9",
- timeoutMs: 5000,
- debug: false,
- debugLogPath: "",
- credentialSource: "test",
- credentialPath: "",
- watchedPaths: [],
- }),
- loggerFactory: () => ({ log() {}, logError() {} }),
- })
- return {
- proxy,
- async messages() {
- await new Promise((resolve) => setImmediate(resolve))
- return out.join("").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line))
- },
- }
-}
-
-test("OpenCode MCP proxy forwards initialize with auth and identity headers", async () => {
- await withServer((_req, res, entry) => {
- assert.equal(entry.method, "POST")
- assert.equal(entry.headers.authorization, "Bearer test-key")
- assert.equal(entry.headers["x-openviking-account"], "acct")
- assert.equal(entry.headers["x-openviking-user"], "user")
- assert.equal(entry.headers["x-openviking-actor-peer"], "peer")
- assert.equal(entry.headers["user-agent"], "openviking-memory-opencode/9.9.9")
- res.writeHead(200, {
- "content-type": "text/event-stream",
- "mcp-session-id": "sid-oc",
- })
- res.end(sseMessage(jsonRpc(1, { protocolVersion: "2025-06-18" })))
- }, async ({ url, requests }) => {
- const { proxy, messages } = makeProxy(url)
- await proxy.handleMessage({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: { protocolVersion: "2025-06-18" },
- })
- assert.deepEqual(await messages(), [jsonRpc(1, { protocolVersion: "2025-06-18" })])
- assert.equal(requests.length, 1)
- })
-})
diff --git a/examples/opencode-plugin/tests/config.test.mjs b/examples/opencode-plugin/tests/config.test.mjs
index d0987b205..c0a167b62 100644
--- a/examples/opencode-plugin/tests/config.test.mjs
+++ b/examples/opencode-plugin/tests/config.test.mjs
@@ -1,12 +1,17 @@
import test from "node:test"
import assert from "node:assert/strict"
import { createServer } from "node:http"
-import { mkdtemp, rm, writeFile, mkdir } from "node:fs/promises"
+import { mkdtemp, rm, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { loadConfig } from "../lib/config.mjs"
import { OpenVikingPlugin } from "../index.mjs"
+// The layers, the knobs and the peer are the shared loader's, and
+// memory-plugin-shared/plugin-config.test.mjs holds this harness to them. What
+// is left here is hook-only mode, which is this plugin's alone: it is the only
+// harness that registers an MCP server from inside the host's own config.
+
async function withTempDir(prefix, fn) {
const dir = await mkdtemp(join(tmpdir(), prefix))
try {
@@ -44,150 +49,20 @@ function restoreOpenVikingEnv(snapshot) {
}
}
-test("loadConfig prefers env credentials over ovcli and legacy config", async () => {
+test("loadConfig supports hook-only mode without registering the bundled MCP server", async () => {
const snapshot = { ...process.env }
- await withTempDir("ov-oc-config-", async (dir) => {
+ await withTempDir("ov-oc-hook-only-", async (dir) => {
try {
for (const key of Object.keys(process.env)) {
if (key.startsWith("OPENVIKING_")) delete process.env[key]
}
- const ovcli = join(dir, "ovcli.conf")
const project = join(dir, "project")
- await mkdir(join(project, ".opencode"), { recursive: true })
+ const ovcli = join(dir, "ovcli.conf")
await writeFile(ovcli, JSON.stringify({
url: "https://cli.example.com",
- api_key: "cli-key",
- account: "cli-account",
- user: "cli-user",
- actor_peer_id: "cli-peer",
- }))
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- endpoint: "https://legacy.example.com",
- apiKey: "legacy-key",
- account: "legacy-account",
- user: "legacy-user",
- peerId: "legacy-peer",
+ plugin: { opencode: { mcpEnabled: false } },
}))
process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
- process.env.OPENVIKING_URL = "https://env.example.com"
- process.env.OPENVIKING_API_KEY = "env-key"
- process.env.OPENVIKING_ACCOUNT = "env-account"
- process.env.OPENVIKING_USER = "env-user"
- process.env.OPENVIKING_PEER_ID = "env-peer"
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.endpoint, "https://env.example.com")
- assert.equal(cfg.apiKey, "env-key")
- assert.equal(cfg.account, "env-account")
- assert.equal(cfg.user, "env-user")
- assert.equal(cfg.peerId, "env-peer")
- assert.equal(cfg.effectivePeer.peerId, "env-peer")
- assert.equal(cfg.effectivePeer.source, "explicit")
- assert.equal(cfg.legacyCredentialsUsed, false)
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig reads legacy credentials as fallback and marks deprecation", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-legacy-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- const project = join(dir, "project")
- process.env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "missing-ovcli.conf")
- process.env.OPENVIKING_CONFIG_FILE = join(dir, "missing-ov.conf")
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- endpoint: "https://legacy.example.com",
- apiKey: "legacy-key",
- account: "legacy-account",
- user: "legacy-user",
- peerId: "legacy-peer",
- }))
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.endpoint, "https://legacy.example.com")
- assert.equal(cfg.apiKey, "legacy-key")
- assert.equal(cfg.account, "legacy-account")
- assert.equal(cfg.user, "legacy-user")
- assert.equal(cfg.peerId, "legacy-peer")
- assert.equal(cfg.effectivePeer.peerId, "legacy-peer")
- assert.equal(cfg.effectivePeer.source, "explicit")
- assert.equal(cfg.legacyCredentialsUsed, true)
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig derives workspace peer by default", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-ws-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"
- process.env.OPENVIKING_URL = "https://env.example.com"
- const project = join(dir, "Project A")
- await mkdir(join(project, ".git"), { recursive: true })
- await writeFile(join(project, ".git", "config"), '[remote "origin"]\n\turl = [email protected]:acme/project-a.git\n')
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.effectivePeer.peerId, "github.com-acme-project-a")
- assert.equal(cfg.effectivePeer.source, "workspace")
- assert.equal(cfg.effectivePeer.origin, "{git_remote}")
-
- // Outside a repository the default derives nothing, so a scratch
- // directory writes to the user-level space instead of a peer of its own.
- const scratch = join(dir, "Scratch B")
- await mkdir(scratch, { recursive: true })
- const plain = loadConfig(dir, scratch)
- assert.equal(plain.effectivePeer.peerId, "")
- assert.equal(plain.effectivePeer.origin, "unresolved")
- assert.equal(plain.effectivePeer.legacyPeerId, scratch.replace(/[^A-Za-z0-9]/g, "-"))
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig can disable workspace peer", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-ws-off-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"
- process.env.OPENVIKING_URL = "https://env.example.com"
- process.env.OPENVIKING_WORKSPACE_PEER = "0"
-
- const cfg = loadConfig(dir, join(dir, "project"))
- assert.equal(cfg.effectivePeer.peerId, "")
- assert.equal(cfg.effectivePeer.source, "none")
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig supports hook-only mode without registering the bundled MCP server", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-hook-only-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- const project = join(dir, "project")
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- mcp: { enabled: false },
- }))
const cfg = loadConfig(dir, project)
assert.equal(cfg.enabled, true)
@@ -206,15 +81,20 @@ test("OpenVikingPlugin keeps lifecycle hooks without mutating MCP config in hook
for (const key of Object.keys(process.env)) {
if (key.startsWith("OPENVIKING_")) delete process.env[key]
}
- const configPath = join(dir, "openviking-config.json")
- await writeFile(configPath, JSON.stringify({
- mcp: { enabled: false },
- runtime: { dataDir: join(dir, "runtime") },
- repoContext: { enabled: false },
- autoRecall: { enabled: false },
- autoCapture: false,
+ const ovcli = join(dir, "ovcli.conf")
+ await writeFile(ovcli, JSON.stringify({
+ url: endpoint,
+ plugin: {
+ opencode: {
+ mcpEnabled: false,
+ dataDir: join(dir, "runtime"),
+ repoContext: false,
+ autoRecall: false,
+ autoCapture: false,
+ },
+ },
}))
- process.env.OPENVIKING_PLUGIN_CONFIG = configPath
+ process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
process.env.OPENVIKING_URL = endpoint
const plugin = await OpenVikingPlugin({ client: {}, directory: dir })
@@ -245,10 +125,12 @@ test("loadConfig preserves an explicit zero commit keep recent count", async ()
const project = join(dir, "project")
process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"
process.env.OPENVIKING_URL = "https://env.example.com"
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- commitKeepRecentCount: 0,
+ const ovcli = join(dir, "ovcli.conf")
+ await writeFile(ovcli, JSON.stringify({
+ url: "https://env.example.com",
+ plugin: { commitKeepRecentCount: 0 },
}))
+ process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
const cfg = loadConfig(dir, project)
assert.equal(cfg.commitKeepRecentCount, 0)
@@ -268,105 +150,15 @@ test("loadConfig defaults an invalid commit keep recent count", async () => {
const project = join(dir, "project")
process.env.OPENVIKING_CREDENTIAL_SOURCE = "env"
process.env.OPENVIKING_URL = "https://env.example.com"
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- commitKeepRecentCount: null,
- }))
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.commitKeepRecentCount, 10)
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig falls back to config peerId when shared credentials define none (#4487)", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-peer-fallback-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
const ovcli = join(dir, "ovcli.conf")
- const project = join(dir, "project")
- await mkdir(join(project, ".opencode"), { recursive: true })
await writeFile(ovcli, JSON.stringify({
- url: "https://cli.example.com",
- api_key: "cli-key",
- account: "cli-account",
- user: "cli-user",
- }))
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- enabled: true,
- peerId: "atomic-city",
- workspacePeer: false,
- recallPeerScope: "actor",
+ url: "https://env.example.com",
+ plugin: { commitKeepRecentCount: null },
}))
process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
const cfg = loadConfig(dir, project)
- assert.equal(cfg.peerId, "atomic-city")
- assert.deepEqual(cfg.effectivePeer, { peerId: "atomic-city", source: "explicit", origin: "explicit", legacyPeerId: "" })
- assert.equal(cfg.legacyCredentialsUsed, false)
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig keeps ovcli actor_peer_id over config peerId", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-peer-cli-wins-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- const ovcli = join(dir, "ovcli.conf")
- const project = join(dir, "project")
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(ovcli, JSON.stringify({
- url: "https://cli.example.com",
- api_key: "cli-key",
- actor_peer_id: "cli-peer",
- }))
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- peerId: "config-peer",
- }))
- process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.peerId, "cli-peer")
- assert.deepEqual(cfg.effectivePeer, { peerId: "cli-peer", source: "explicit", origin: "explicit", legacyPeerId: "" })
- } finally {
- restoreOpenVikingEnv(snapshot)
- }
- })
-})
-
-test("loadConfig keeps env peer over config peerId when ovcli has none", async () => {
- const snapshot = { ...process.env }
- await withTempDir("ov-oc-peer-env-wins-", async (dir) => {
- try {
- for (const key of Object.keys(process.env)) {
- if (key.startsWith("OPENVIKING_")) delete process.env[key]
- }
- const ovcli = join(dir, "ovcli.conf")
- const project = join(dir, "project")
- await mkdir(join(project, ".opencode"), { recursive: true })
- await writeFile(ovcli, JSON.stringify({
- url: "https://cli.example.com",
- api_key: "cli-key",
- }))
- await writeFile(join(project, ".opencode", "openviking-config.json"), JSON.stringify({
- peerId: "config-peer",
- }))
- process.env.OPENVIKING_CLI_CONFIG_FILE = ovcli
- process.env.OPENVIKING_PEER_ID = "env-peer"
-
- const cfg = loadConfig(dir, project)
- assert.equal(cfg.peerId, "env-peer")
- assert.deepEqual(cfg.effectivePeer, { peerId: "env-peer", source: "explicit", origin: "explicit", legacyPeerId: "" })
+ assert.equal(cfg.commitKeepRecentCount, 10)
} finally {
restoreOpenVikingEnv(snapshot)
}
diff --git a/examples/opencode-plugin/tests/runtime.test.mjs b/examples/opencode-plugin/tests/runtime.test.mjs
new file mode 100644
index 000000000..4aa81d5fb
--- /dev/null
+++ b/examples/opencode-plugin/tests/runtime.test.mjs
@@ -0,0 +1,44 @@
+import test from "node:test"
+import assert from "node:assert/strict"
+import { checkServiceHealth } from "../lib/runtime.mjs"
+
+const CONFIG = {
+ endpoint: "http://127.0.0.1:1933/",
+ apiKey: "sk-opencode",
+ account: "acct-a",
+ user: "user-a",
+ sendIdentityHeaders: true,
+ userAgent: "openviking-opencode/9.9.9",
+ timeoutMs: 5000,
+}
+
+test("the health probe presents the same credentials as every other call", async (t) => {
+ const calls = []
+ t.mock.method(globalThis, "fetch", async (url, init) => {
+ calls.push({ url, init })
+ return new Response(JSON.stringify({ status: "healthy" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ })
+ })
+
+ assert.equal(await checkServiceHealth(CONFIG), true)
+ assert.equal(calls[0].url, "http://127.0.0.1:1933/health")
+ assert.equal(calls[0].init.headers["Authorization"], "Bearer sk-opencode")
+ assert.equal(calls[0].init.headers["X-OpenViking-Account"], "acct-a")
+ assert.equal(calls[0].init.headers["User-Agent"], "openviking-opencode/9.9.9")
+})
+
+test("a rejected or unreachable probe is not a healthy server", async (t) => {
+ t.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({
+ status: "error",
+ error: { message: "missing credentials" },
+ }), { status: 401, headers: { "Content-Type": "application/json" } }))
+ assert.equal(await checkServiceHealth(CONFIG), false)
+
+ t.mock.restoreAll()
+ t.mock.method(globalThis, "fetch", async () => {
+ throw new Error("fetch failed")
+ })
+ assert.equal(await checkServiceHealth(CONFIG), false)
+})
diff --git a/examples/opencode-plugin/tests/utils-logger.test.mjs b/examples/opencode-plugin/tests/utils-logger.test.mjs
index 4f89a8420..c47decddb 100644
--- a/examples/opencode-plugin/tests/utils-logger.test.mjs
+++ b/examples/opencode-plugin/tests/utils-logger.test.mjs
@@ -3,7 +3,7 @@ import assert from "node:assert/strict"
import { mkdtemp, readFile, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
-import { fetchJSON, initLogger, log } from "../lib/utils.mjs"
+import { fetchJSON, initLogger, log, makeRequest } from "../lib/utils.mjs"
test("initLogger creates the OpenViking log file path and log writes JSONL", async () => {
const dir = await mkdtemp(join(tmpdir(), "ov-oc-log-"))
@@ -54,3 +54,15 @@ test("fetchJSON preserves commit trace_id on success and error", async (t) => {
assert.equal(failure.traceId, "trace-opencode-error")
assert.equal(failure.error.trace_id, "trace-opencode-error")
})
+
+test("makeRequest reads the timeout off the envelope, not off the error text", async (t) => {
+ t.mock.method(globalThis, "fetch", (_url, init) => new Promise((_resolve, reject) => {
+ // What the runtime throws on abort says nothing about a timeout.
+ init.signal.addEventListener("abort", () => reject(new Error("terminated")))
+ }))
+
+ await assert.rejects(
+ makeRequest({ endpoint: "http://127.0.0.1:1933", timeoutMs: 1000 }, { endpoint: "/health" }),
+ /^Error: Request timeout after 1000ms$/,
+ )
+})
diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.md
index aca8e65e5..1020021af 100644
--- a/examples/pi-coding-agent-extension/DESIGN.md
+++ b/examples/pi-coding-agent-extension/DESIGN.md
@@ -1,911 +1,209 @@
-# Pi OpenViking Extension — Implementation Spec
+# Pi OpenViking Extension — Design
-> Current implementation note: this historical design has been superseded by the Claude Code/Codex-aligned SPEC retrofit. Legacy sections below are retained as background, not as current behavior.
+The extension gives a [pi](https://github.com/earendil-works/pi) session long-term memory and, when takeover is on, lets OpenViking own the session's committed history. It is a directory of TypeScript modules loaded directly by pi's `jiti` transpiler: no build step, no dependencies beyond what pi already provides, no MCP server. Everything reaches OpenViking over its REST API.
-## Design Philosophy
+README.md is the operator's document — installation, every configuration knob, the tool list. This one is the maintainer's: what each module is responsible for, how the pieces meet at pi's event boundaries, and the reasons behind the choices that the code cannot state for itself.
-**Informed by all three existing OV plugins** — OpenClaw, Claude Code, and Hermes. The Claude Code plugin is the most mature and production-hardened; its patterns take precedence where they differ from OpenClaw. Key design ancestors:
+## Design ancestry
-- **OpenClaw**: Synchronous recall, threshold commit, memory stripping, dual-scope search
-- **Claude Code plugin** (newest, most mature): Pre-compact commit, subagent isolation, comprehensive stripping, session-resume rehydration, score threshold, bypass patterns
-- **Hermes** (anti-pattern): Stale prefetch, session-end-only commit, no stripping
+Three earlier OpenViking integrations shaped this one. OpenClaw contributed synchronous recall against the current turn and threshold-triggered commits. The Claude Code plugin, the most production-hardened of the three, contributed the capture pipeline — sanitize injected blocks before capture, keep tool inputs, drop raw tool output — along with score-thresholded ranking, the pre-compact commit and session-resume rehydration. Hermes contributed the anti-pattern: it prefetched recall for the *previous* turn's query, so the first turn of a session got nothing and a topic switch got the wrong memories.
-Design comparison:
+| Concern | Hermes | OpenClaw | Claude Code | This extension |
+|---|---|---|---|---|
+| Recall query | previous turn | current turn | current turn | current turn |
+| Injection point | user message | user message | user message | `context` hook, newest user message |
+| Commit trigger | session end | token threshold | threshold + pre-compact + session end | threshold + pre-compact + session end |
+| Capture sanitization | none | its own recall block | every injected block | shared `capture-utils` |
+| Committed history | owned by the agent | replaced by OV archives | owned by the agent | replaced by OV archives (default on) |
-| Concern | Hermes (rejected) | OpenClaw (adopted) | This extension |
-|---------|-------------------|--------------------|----|
-| Recall timing | Stale prefetch (N-1 turn) | Synchronous current-turn | ✅ Synchronous via `context` event |
-| Recall relevance | Wrong topic | Right topic | ✅ Right topic |
-| First turn | Gets nothing | Gets relevant context | ✅ Gets relevant context |
-| Injection target | User message (stale cache) | User message (fresh search) | ✅ User message via `context` event |
-| Commit trigger | Session-end only | Token threshold mid-session | Token threshold mid-session + session-end + pre-compact | ✅ Threshold + session-end |
-| Memory stripping | None | Strip injected blocks before sync | Strip `<relevant-memories>` + `<system-reminder>` + `<openviking-context>` + `[Subagent Context]` + null bytes | ✅ Strip all 5 + null bytes |
-| History compression | None | OV archives replace transcript | Pi compaction (pre-compact commit preserves content in OV) | ❌ Pi has its own compaction |
-| Tools | 5 | 8 | 9 (via MCP) | 7 (no `add_skill` — pi has its own skill system) |
-| Profile injection | None | None | ✅ profile.md + preferences + entities at session start | ✅ Same |
+What the Claude Code plugin proved is no longer copied here — it is imported. `shared/` is a generated copy of `examples/memory-plugin-shared/lib`, produced by that directory's `sync.mjs`. Recall assembly, capture sanitization, profile building, the disk pending queue, batched sending, credential and settings resolution, and bypass matching all live there and behave identically in every harness. What stays local is the pi-shaped part: how a pi branch becomes capture payloads, how the `context` hook is rewritten, and how state survives `pi -c`.
-## Architecture
+## Layout
```
-~/.pi/agent/extensions/openviking/
-├── index.ts # Entry point — registers events, tools, commands
-├── client.ts # HTTP client for OV REST API (zero npm deps)
-├── index_builder.ts # Build memory index (viking:// tree + archive abstracts)
-├── recall.ts # Synchronous search, reranking, <relevant-memories> formatting
-├── sync.ts # Turn archival, memory stripping, commit management
-└── tools.ts # 7 tool schemas + handlers
+pi-coding-agent-extension/
+├── config.ts # settings, credentials, peer resolution
+├── client.ts # HTTP client for the OpenViking REST API
+├── recall.ts # per-prompt recall search and injection
+├── sync.ts # capture, delivery, pending queue, commit
+├── takeover.ts # binds the takeover state machine to pi
+├── tools.ts # the seven model-facing viking_* tools
+├── index.ts # entry point: event handlers and the /viking command
+├── package.json # name and version; pi loads index.ts regardless
+├── lib/ # pi-specific logic kept out of the event handlers
+├── shared/ # generated copy of memory-plugin-shared/lib
+├── scripts/ # live e2e harness
+└── tests/ # node --test suites
```
-6 files. ~1000-1200 lines total.
-
-## Config
-
-Inline in `index.ts`. Loaded from `~/.pi/agent/extensions/openviking/config.json`.
-
-```typescript
-interface OVConfig {
- enabled: boolean; // Master switch (default: true)
- endpoint: string; // OV server URL (default: "http://127.0.0.1:1933")
- apiKey: string; // API key (default: "" — dev mode)
- account: string; // Multi-tenant account (default: "")
- user: string; // Multi-tenant user (default: "")
- peerId: string; // Actor peer identity for X-OpenViking-Actor-Peer
- syncTurns: boolean; // Auto-sync conversation turns (default: true)
- recallBudget: number; // Max tokens for <relevant-memories> block (default: 2000)
- recallMaxContentChars: number; // Max chars per recall result before truncation (default: 500)
- recallPreferAbstract: boolean; // Prefer abstract/overview over full content (default: true)
- recallLimit: number; // Legacy input scaled into six coding quotas (default: 10)
- recallScoreThreshold: number; // Min relevance score for recall results (default: 0.35)
- recallMinQueryLength: number; // Skip recall for queries shorter than this (default: 3)
- profileBudget: number; // Max tokens for user profile injection at session start (default: 10000)
- resumeContextBudget: number; // Max tokens for archive overview on resume/compact (default: 2000)
- indexBudget: number; // Max tokens for memory index in system prompt (default: 2000)
- captureToolResults: boolean; // Include tool result output in capture (default: false — agent inputs kept, results dropped)
- captureMode: "semantic" | "keyword"; // "semantic" = always capture, "keyword" = only when trigger phrases match (default: "semantic")
- captureMaxLength: number; // Max sanitized text length for capture decision (default: 24000)
- captureAssistantTurns: boolean; // Include assistant turns in capture (default: true — memory extraction needs both sides)
- commitTokenThreshold: number; // Commit after N pending tokens synced (default: 20000, 0 = session-end only)
- commitOnShutdown: boolean; // Commit session on session_shutdown (default: true)
- mirrorMemoryWrites: boolean; // Mirror MEMORY.md to OV at commit time (default: true)
- writeQueueFlushInterval: number; // Write queue flush interval in ms (default: 5000)
- writeQueueFlushThreshold: number; // Write queue flush after N queued turns (default: 5)
- bypassPatterns: string[]; // Glob patterns for cwd to skip (default: [])
- logLevel: "silent" | "error" | "info"; // default: "error"
-}
-```
-
-`recallLimit` is not a final result cap. Explicit values from 1 through 5 yield
-an effective total quota of 6 because every coding category keeps one slot.
-Callers that require exact category ceilings should use Context `quotas`.
-
-Config resolution: `config.json` → env vars (`OPENVIKING_URL`, `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, `OPENVIKING_AGENT_ID`, etc.) → defaults. Follows the Claude Code plugin's priority chain.
-
-## File Details
-
-### client.ts (~250 lines)
-
-HTTP client for the OpenViking REST API. Uses Node.js built-in `fetch`. Zero npm dependencies.
-
-Wraps these endpoints:
-
-| Method | Endpoint | Purpose |
-|--------|----------|---------|
-| GET | `/health` | Health check |
-| POST | `/api/v1/sessions` | Create session |
-| GET | `/api/v1/sessions/{id}` | Get session metadata (including pending_tokens) |
-| POST | `/api/v1/sessions/{id}/messages` | Add message |
-| POST | `/api/v1/sessions/{id}/commit` | Commit (triggers memory extraction) |
-| POST | `/api/v1/search/find` | Quick retrieval (accepts `target_uri` for scope, `top_k`, `score_threshold`) |
-| GET | `/api/v1/content/read` | Read full content (L2) |
-| GET | `/api/v1/content/abstract` | Read abstract (L0) |
-| GET | `/api/v1/content/overview` | Read overview (L1) |
-| GET | `/api/v1/fs/ls` | List directory |
-| GET | `/api/v1/fs/stat` | Stat entry |
-| DELETE | `/api/v1/content` | Delete by URI |
-| POST | `/api/v1/resources` | Add resource |
-
-All methods are async. All catch errors internally and return `null`/empty on failure. Timeouts: 5s health, 10s reads, 30s writes.
-
-Headers include `X-OpenViking-Account`, `X-OpenViking-User`, and `X-OpenViking-Actor-Peer` for multi-tenant routing and peer scope.
-
-```typescript
-class OVClient {
- private baseUrl: string;
- private apiKey: string;
- private account: string;
- private user: string;
- private agent: string; // always "pi"
- private connected: boolean;
-
- constructor(config: OVConfig);
-
- async health(): Promise<boolean>;
- async createSession(sessionId: string): Promise<boolean>;
- async addMessage(sessionId: string, role: string, content: string): Promise<boolean>;
- async getSession(sessionId: string): Promise<OVSessionMeta | null>;
- async commitSession(sessionId: string, wait?: boolean): Promise<string | null>;
- async find(query: string, opts?: { targetUri?: string; topK?: number; scoreThreshold?: number }): Promise<OVSearchResult[]>;
- async readContent(uri: string): Promise<string | null>;
- async abstract(uri: string): Promise<string | null>;
- async overview(uri: string): Promise<string | null>;
- async ls(uri: string): Promise<OVDirEntry[]>;
- async stat(uri: string): Promise<OVEntryInfo | null>;
- async deleteByUri(uri: string): Promise<boolean>;
- async addResource(path: string, opts?: { to?: string }): Promise<any>;
-
- // URI space resolution (from Claude Code plugin's resolveScopeSpace/resolveTargetUri)
- // Multi-tenant OV deployments namespace memories under viking://user/<space>/memories/.
- // The space is NOT always "default" — it's the first non-reserved, non-hidden directory
- // under viking://user/ that matches the configured user identity.
- private resolvedSpaces: Map<string, string>; // cache: scope → space name
-
- // Discover the actual namespace for a given scope ("user" or "agent").
- // Probes /api/v1/system/status for the user identity, then ls viking://<scope>
- // to find a matching space. Falls back to "default".
- async resolveScopeSpace(scope: "user" | "agent"): Promise<string>;
-
- // Expand a bare viking:// URI (e.g., viking://user/memories) to its fully-qualified
- // form with the resolved space inserted (e.g., viking://user/alice/memories).
- // Reserved directory names (memories, skills, instructions, workspaces) trigger space
- // insertion; non-reserved paths pass through unchanged.
- async resolveTargetUri(targetUri: string): Promise<string>;
-}
-```
-
-### index_builder.ts (~80 lines)
-
-**The table of contents.** Builds a browsable memory index that tells the model *what OV knows*, so it can make informed decisions about when to search deeper. Inspired by OpenClaw's preflight `assemble()` which provides `latest_archive_overview` and `pre_archive_abstracts` to the model.
-
-Without this index, the model is flying blind — it can only retrieve what it thinks to ask for, with no topical overview to guide its queries. The index is the map; recall is the flashlight.
-
-#### What goes into the index
-
-The index has three parts, built from OV's filesystem and session APIs:
-
-1. **Directory listing**: `client.ls("viking://")` → visible resources, the current user's namespace, and optional account-shared skills. Shows *what categories of knowledge exist*.
-2. **Abstract summaries**: For each leaf memory in `viking://user/memories/`, fetch L0 abstracts. These are ~100 tokens each and give the model a one-line summary of each stored memory.
-3. **Archive overview**: If the current session has a previous archive, its L1 overview (~2k tokens) is included as `[Session History Summary]`.
-
-#### When the index is built
-
-- **Session start** (`session_start`): build once, cache in memory.
-- **After commit** (threshold or shutdown): rebuild if new memories were extracted. The commit callback triggers a rebuild.
-
-The index is NOT rebuilt on every prompt — that would be wasteful. It's a relatively stable snapshot that refreshes only when the knowledge base actually changes (after commits).
-
-#### Index format
-
-The index is injected into the system prompt (via `before_agent_start`'s `systemPrompt` return). Capped at `indexBudget` tokens (~2000 default).
-
-```
-## OpenViking Knowledge Index
-[Showing what's in your long-term memory]
-
-### viking://user/memories/ (12 memories)
-- Prefers local/self-hosted solutions over cloud services
-- Project X uses SQLite, not PostgreSQL, pool size 5
-- Chrome DevTools MCP gets stuck on closed tabs; pkill to fix
-- pip "Successfully installed" can lie — verify with import
-- (8 more — use viking_search to find specific memories)
-
-### viking://resources/ (3 resources)
-- OpenViking reference doc (viking://resources/openviking-reference)
-- Project X architecture diagram (viking://resources/projx-arch)
-- (1 more — use viking_browse to explore)
-
-### viking://user/sessions/{session_id}/history/ (2 archives)
-- Archive 2026-05-25: 15-turn session about pi extension design
-- (1 more — use viking_archive_expand for detail)
-
-Tools: viking_search | viking_read | viking_browse | viking_remember | viking_forget | viking_add_resource | viking_archive_expand
-```
-
-#### Why not include full memory content
-
-The index is intentionally a *table of contents*, not the full encyclopedia. Reasons:
-- Token budget: full content of all memories would blow past system prompt limits.
-- Relevance: most memories are irrelevant to the current task — that's what recall is for.
-- Freshness: the index refreshes after commits, but recall is always current-turn.
-
-The model sees the index and knows "OV knows about X, Y, Z." When a task touches those topics, it uses `viking_search` for depth or relies on automatic `<relevant-memories>` injection.
-
-```typescript
-class IndexBuilder {
- private client: OVClient;
- private cachedIndex: string | null;
-
- constructor(client: OVClient);
-
- // Build index from scratch — called at session_start and after commits
- async buildIndex(): Promise<string>;
-
- // Get cached index (returns empty string if not built or OV is down)
- getIndex(): string;
-}
-```
+## Modules
-### recall.ts (~150 lines)
-
-Synchronous recall that runs on every user prompt, injecting relevant OV context into the user message before the LLM sees it. This is the *flashlight* — targeted retrieval for the current query. The *index* (from `index_builder.ts`) is the *map* that helps the model know when to use it.
-
-#### How it works
-
-1. Extract query text from the user's prompt (plain text, no tool calls/images)
-2. **Short-circuit**: if query length < `recallMinQueryLength` (default 3), skip recall — queries like "y", "ok", "go" don't carry enough signal for useful retrieval (from Claude Code plugin)
-3. **Server-side context assembly**: call `/api/v1/search/search` with
- `mode="context"` and `purpose="coding"`. The server applies the six-domain
- preset (`events/entities/preferences/experiences/resources/skills`), ownership
- scopes, budgeting and dedup. On older servers the extension falls back to
- `/recall`, then to the legacy memory/skill `find` path.
-4. **Query profiling**: analyze the query for intent signals before ranking (from Claude Code plugin):
- ```typescript
- function buildQueryProfile(query: string): QueryProfile {
- return {
- tokens: extractContentTokens(query), // content words minus stopwords
- wantsPreference: /prefer|favorite|like|want|usually|always|never/i.test(query),
- wantsTemporal: /when|yesterday|last |recent|ago|last week/i.test(query),
- };
- }
- ```
- This gates the category boosts — preference memories only get boosted when the query has preference intent, event memories only when the query has temporal intent. Without this, boosting everything on every query dilutes the signal.
-5. **Score filter**: discard any results below `recallScoreThreshold` (default 0.35) — irrelevant results are worse than no results (from Claude Code plugin). Filtering is client-side, not server-side.
-6. **Deduplication** with category-specific strategies (from Claude Code plugin):
- - Events/cases → dedupe by URI (same event can appear with different abstracts)
- - Everything else → dedupe by abstract text (lowercased), fall back to URI
-
- Without this, vector search can return near-duplicate results that waste the token budget.
-7. **Rerank** beyond pure vector score using the query profile:
- - Leaf preference boost (+0.12): item level == 2 or URI ends in `.md`
- - Event boost (+0.10): query has temporal intent AND item is in events/cases category
- - Preference boost (+0.08): query has preference intent AND item is in preferences category
- - Lexical overlap boost (up to +0.20): query tokens found in item URI + abstract, normalized by min(tokens.length, 4)
-8. **Content resolution** for each ranked item (from Claude Code plugin):
- - If `recallPreferAbstract` is true (default): use abstract/overview text from search results
- - If level is 2 (full content): fetch full body from `/api/v1/content/read`
- - Content capped per-item to `recallMaxContentChars` (default 500 chars) — prevents a single verbose memory from consuming the entire budget
-9. **Token-budgeted formatting with graceful degradation** (from Claude Code plugin):
- - Process items in ranked order
- - Items within the total `recallBudget` (default 2000 tokens) get full content lines
- - Items beyond the budget are **degraded to URI + score hints** rather than dropped — the model can call `viking_read` to expand them
- - The first item is always included even if it exceeds the remaining budget
-10. Format as `<relevant-memories>` block
-
-#### Reranking
-
-See step 7 above for exact boost values. The boosts are gated by the query profile — preference/event boosts only fire when the query has matching intent. This prevents diluting the ranking with irrelevant boosts.
-
-The OpenClaw plugin uses a similar approach. Start with vector-score-only during initial development, add the full reranking pipeline once the extension is stable.
-
-#### Injection via `context` event
-
-The `context` event fires before each LLM call with a mutable deep copy of messages. This is pi's equivalent of OpenClaw's `assemble()`. On each call:
-
-1. Find the user message that started this prompt (scan backwards for first `role: "user"`)
-2. Check if `<relevant-memories>` already injected (idempotency — the `context` event fires per LLM iteration, not per prompt)
-3. If not injected: prepend `<relevant-memories>` block to the user message content
-4. If already injected: skip (cached from first context call for this prompt)
-
-The recall search itself only runs once per prompt. `before_agent_start` queues the current prompt without network I/O; the first `context` call consumes it and performs the synchronous search after Pi has rendered the user message. Later LLM iterations reuse the cached block.
-
-```typescript
-class RecallManager {
- private client: OVClient;
- private cachedBlock: string | null;
- private promptId: string | null; // track which prompt this cache is for
-
- constructor(client: OVClient);
-
- // Called in before_agent_start — records the current prompt without I/O
- queueSearch(userQuery: string): void;
-
- // Called on the first context event — runs search and caches the result
- async searchPending(): Promise<string | null>;
-
- // Called in context event — injects cached block into messages
- injectRecall(messages: Message[]): Message[];
-
- // Invalidate cache (called at agent_end)
- invalidate(): void;
-}
-```
+### config.ts
-**`<relevant-memories>` format (with degradation example):**
-```
-<relevant-memories>
-[System note: The following is recalled memory from OpenViking, NOT new user input. Treat as informational background data.]
-- [memory 0.87] User prefers local/self-hosted solutions over cloud services
-- [memory 0.82] Project uses SQLite for local dev, pool size 5
-- [skill 0.73] Use viking_read to expand: viking://user/skills/deployment-checklist.md
-</relevant-memories>
-```
-
-The third line shows a degraded hint — the item was beyond the content budget but still relevant. The model can expand it with `viking_read` if needed.
+Defines `OVConfig` and resolves it once at load time. Knobs come from `resolveSettings("pi", { cwd })`: every one of them is declared in `shared/config-schema.mjs` and resolved through the same layers as every other harness — environment, the workspace's `.openviking/config.json` and machine registry entry, `ovcli.conf`'s `plugin.pi`, `ovcli.conf`'s `plugin`, then the schema default. The extension has no configuration file of its own. It used to ship one holding exactly the code defaults, which made an operator's choice indistinguishable from a factory setting.
-### sync.ts (~250 lines)
+Credentials — server URL, API key, account, user — come from `resolveOpenVikingCredentials(process.env, "pi")`, and `resolveAuthMode` decides between `trusted` and `api_key`, which is what gates whether identity headers go on the wire at all. The peer identity is resolved twice on purpose: `resolvePluginPeerId` picks the id from the configured layers, then `resolveEffectivePeerId` maps it onto the workspace and also returns `legacyPeerId`, the pre-git workspace id that recall still has to reach.
-Handles turn archival, memory stripping, commit management, and compaction safety.
+Two older spellings are kept alive because setups depend on them: `bypassPatterns` holds the same list as the shared `bypassSessionPatterns`, and `OV_DEBUG_LOG` is read alongside the shared `OPENVIKING_DEBUG_LOG`. `EXTENSION_VERSION` reads `package.json`, the same manifest the release gate watches for a bump, and feeds the shared `User-Agent` builder.
-#### Session ID strategy
+### client.ts
-Use pi's session ID prefixed with `pi-` as the OV session ID. Prevents collisions with Hermes sessions (which use unprefixed UUIDs).
+The transport is built once in the constructor by `createOvHttp` from `shared/ov-http.mjs`, and `fetchJSON(path, init, timeoutMs)` is the thin call into it. Nothing throws: callers branch on `ok` over the same `{ ok, result, status, error, traceId }` envelope every harness reads, and a transport failure arrives as `status: 0`. The trace id is lifted out of whichever place the server put it so that failures can be correlated in the server's own logs.
-**Subagent isolation is natural, not managed.** Pi extensions don't have SubagentStart/SubagentStop events (those are Claude Code-specific hooks). Instead, when `task-tool` spawns a subagent, it's a separate pi process that loads extensions normally. The subagent's OV extension instance creates its own session with `pi-<subagentSessionId>` — inherently isolated because each pi process gets a unique session ID via `getSessionId()`. No parent management or special prefix needed. This is actually *better* than CC's approach: process-level isolation with zero coordination overhead, vs explicit hook-based session management.
+Headers are built per request: `Authorization: Bearer` when a key is configured, `X-OpenViking-Actor-Peer` for peer scoping, the shared `User-Agent`, and `X-OpenViking-Account` / `X-OpenViking-User` only when `sendIdentityHeaders` says the deployment is in trusted mode. Timeouts follow the class of call — 5s for health and session metadata, 10s for reads and message writes, 30s for commit and resource ingestion.
-The only requirement: subagents spawned for internal extension work (e.g., the learning extension's reviewer) pass `--no-extensions`, which prevents the OV extension from loading in the reviewer subprocess.
+Above that sit thin methods for the endpoints this extension and its tools need: health, session metadata, session context, message append, commit, `search/find`, the three content tiers (abstract, overview, read), `fs/ls`, `fs/stat`, delete, and resource ingestion. Commit is exposed twice because two callers need different things from it: `commitSessionResponse` returns the whole envelope so a failure can be logged with its status and trace id, `commitSession` returns just the result.
-#### Turn archival
+### recall.ts
-On each `turn_end`:
-1. Extract user text + assistant text from the turn
-2. **Strip all injected blocks** from both before sending to OV (see Memory Stripping below)
-3. **Preserve tool USE inputs, drop tool RESULTS** (from Claude Code plugin): format each turn's tool interactions as `[tool: <name>]\n<input>`. Tool use inputs are agent-authored and carry signal ("the agent chose to read file X, run command Y"). Tool results are typically noise for memory extraction (file contents, command stdout). If `captureToolResults` is true, include tool results up to a reasonable cap.
-4. **Add tool summary line** to assistant turn: `[assistant used tools: read, edit, bash]`. This gives OV's memory extractor context about what the agent *did* beyond prose — "ran bash, edited a file, then read another file" is more signal than just the assistant's text response (from Claude Code plugin).
-5. Estimate token count for the stripped content (using CJK-aware estimator — see Token Estimation below)
-6. Fire-and-forget batch add to OV session (non-blocking)
-7. Track cumulative `pendingTokens`; check against threshold
+`RecallManager` runs one search per prompt and injects its block into the provider's view of the conversation.
-#### Capture filtering (from Claude Code plugin)
+The split between queueing and searching is what keeps recall off the UI path. `queueSearch(prompt)` runs in `before_agent_start` and only records the text. The first `context` hook of the turn calls `searchPending()`, which performs the search — by then pi has already rendered the user's message, so recall latency delays the model request but never the screen. Later LLM iterations within the same turn reuse the cached block, and `agent_end` invalidates it.
-Not every turn should be archived. One-word acknowledgments, slash commands, pure questions without substance, and punctuation-only turns carry zero signal for memory extraction and pollute the OV session. The Claude Code plugin's `shouldCapture()` filter pipeline prevents this noise from reaching OV (ported from `auto-capture.mjs`).
+The search itself is `buildRecallBlock` from the shared `recall-core.mjs`; quotas, scopes, budgeting and formatting are shared with every other harness. The extension supplies three things of its own: the actor peer id, the legacy peer id (under `actor` scope the effective peer is the only one asked, so a workspace whose id changed would otherwise lose everything written before the change), and the OV session id, which is what turns on server-side query expansion and the cross-turn dedup ledger. A query shorter than `minQueryLength` skips the round trip entirely.
-**Filter pipeline** (applied to each user turn before syncing):
+Injection is two-pass, and that is the interesting part. Historical user messages get back the exact block the recall ledger says was sent with them; only the newest user message receives this turn's fresh block, which is then recorded. The result is a request prefix that stays byte-identical across turns, so the provider's prompt cache keeps hitting instead of being invalidated by every new memory. The ledger keys on pi's entry id plus the message's original text — entry ids survive compaction and branch navigation, where an ordinal would not. When the host does not expose entry ids the pass fails closed: fresh recall still reaches the newest message, but nothing historical is replayed or recorded under an unstable key. A message that already contains `<openviking-context` is never injected into twice.
-1. **Empty check**: strip + trim → skip if empty.
-2. **Length bounds**: skip if compact text < 4 chars (CJK) / 10 chars (Latin) or > `captureMaxLength` (default 24000). CJK uses a higher min-density because CJK chars carry more meaning per character.
-3. **Command detection**: skip if text starts with `/` followed by a command name (e.g., `/help`, `/compact`). These are framework directives, not conversational content.
-4. **Non-content detection**: skip if text is entirely punctuation/symbols/whitespace (no semantic content).
-5. **Question-only detection**: skip if text matches the pattern `/^(who|what|when|where|why|how|...)...?[??]$/i` — pure interrogatives with no substance beyond the question itself.
-6. **Keyword/semantic mode gate**: in `"keyword"` mode, skip unless at least one user turn matches a `MEMORY_TRIGGERS` regex. In `"semantic"` mode (default), skip this gate — always capture.
+### sync.ts
-```typescript
-const MEMORY_TRIGGERS = [
- /remember|preference|prefer|important|decision|decided|always|never/i,
- /[\w.-]+@[\w.-]+\.\w+/, // email patterns
- /(?:my)\s*(?:name|live|from|birthday|phone|email)/i, // identity signals
- /(?:i)\s*(?:like|hate|love|want|need|think|believe)/i, // preference signals
- /(?:favorite|favourite|love|hate|enjoy|dislike)/i,
-];
+`SyncManager` owns the OV session id, the capture watermark, and everything between a pi branch and a committed archive.
-function shouldCapture(text: string, mode: "semantic" | "keyword"): { capture: boolean; reason: string } {
- const normalized = stripAndTrim(text);
- if (!normalized) return { capture: false, reason: "empty" };
+The OV session id is `pi-<pi session id>`, derived locally by the shared `deriveHarnessSessionId`. Nothing round-trips to open a session: the id is deterministic, so the first write can carry it.
- const compact = normalized.replace(/\s+/g, "");
- const isCJK = /[぀-ヿ㐀-鿿豈-﫿가-힯]/.test(compact);
- const minLen = isCJK ? 4 : 10;
- if (compact.length < minLen || normalized.length > config.captureMaxLength)
- return { capture: false, reason: "length_out_of_range" };
+**Capture.** `turn_end` hands the whole branch to `extractBranchCapturePayloads` (`lib/capture-adapter.mjs`), which takes the entries past `syncedEntryCount`, normalizes roles, renders tool parts with bounded input and output, and decides entry by entry whether to capture. There are two decision modes. Normally it is the shared `shouldCaptureText` heuristic. Under takeover it is a faithful mode that drops only empty text, slash commands and OpenViking's own status messages: once the boundary advances, a short acknowledgement may be represented to the model *only* through the archive overview, so discarding it as low-signal would lose it outright. A branch shorter than the watermark means pi navigated to a different branch, so the watermark resets to zero and the branch is re-extracted from the start.
- if (/^\/[a-z0-9_-]{1,64}\b/i.test(normalized))
- return { capture: false, reason: "command" };
+**Delivery.** Payloads leave in one batched request through the shared `sendSessionMessages`. Retryable failures are written to the shared disk pending queue and replayed later. A non-retryable rejection counts as accepted, so the watermark advances past payloads the server will never take rather than re-sending them every turn. The watermark only moves when the whole extraction was accepted.
- if (/^[\p{P}\p{S}\s]+$/u.test(normalized))
- return { capture: false, reason: "non_content" };
+**Backlog drain.** `flushForTakeover` is the barrier takeover waits on, and it needs the queue empty for this session. The shared `replayPending` sends one request per entry and stops after a single replay window, which is what let a large offline backlog hold the barrier closed for many turns, so sync drains this session's own queued `addMessage` entries through the batch endpoint, `BATCH_LIMIT` per request, claiming one batch at a time so a failed batch costs only the retries of the entries it held. The drain is bounded by wall time (`OPENVIKING_PENDING_DRAIN_BUDGET_MS`, 60s by default) and optionally by batch count, so a huge backlog cannot block `turn_end` indefinitely; the remainder drains on later turns.
- if (/^(who|what|when|where|why|how|is|are|does|did|can|could|would|should)\b.{0,200}[??]$/i.test(normalized))
- return { capture: false, reason: "question_only" };
+**Commit.** Outside takeover, sync asks the server for `pending_tokens` after each accepted turn and commits when it crosses `commitTokenThreshold` — server-side accounting, not a local estimate. A failed commit is queued for replay unless the caller passes `queueOnFailure: false`, which takeover always does, because a commit that lands later cannot justify a boundary that moved now.
- if (mode === "keyword") {
- const hasTrigger = MEMORY_TRIGGERS.some(re => re.test(normalized));
- return { capture: hasTrigger, reason: hasTrigger ? "trigger_matched" : "no_trigger" };
- }
+### takeover.ts
- // semantic mode — always capture (default)
- return { capture: true, reason: "semantic" };
-}
-```
+A binding, not a mechanism. The state machine lives in `lib/takeover-core.mjs`, which is pure and unit-tested; `takeover.ts` supplies its I/O: flush and commit go to `SyncManager`, the archive overview comes from the session context endpoint, state is persisted through `pi.appendEntry`, and the watermark is read back from sync.
-**Batch-level caveat** (from CC plugin): `shouldCapture()` is designed for single user messages. When applied to a concatenated multi-turn batch, it misfires (combined text exceeds max length → entire batch dropped, or a leading `/cmd` flips the whole batch to "command"). For pi's `turn_end` event, each turn is evaluated individually, so this problem doesn't arise. The filter runs per-turn before the dedup guard.
+Context takeover makes OpenViking the authoritative long-term store for a pi session. Pi still keeps recent turns locally; committed history is represented to the model by OpenViking's archive overview through pi's `context` hook.
-**Integration into turn archival**: `shouldCapture()` runs on the user's stripped text after step 2 (strip injected blocks). If the decision is `capture: false`, the turn is skipped entirely — no OV message push, no token count. The `syncedTurnCount` still advances so the dedup guard stays correct.
+#### Model
-#### Memory stripping (critical)
+| Field | Meaning |
+|---|---|
+| `coveredUserTurns` | Real user turns already covered by the archive overview |
+| `overview` | Latest archive overview returned by the session context endpoint |
+| `fingerprint` | Fingerprint of the last covered message, for branch-mismatch detection |
+| `pendingTokens` | Estimated synced token pressure since the last successful advance |
+| `lastSeenUserTurns` | User turns counted in the most recent `context` hook |
+| `syncedEntryCount` | Pi branch watermark, restored across `pi -p` / `pi -c` processes |
-Before syncing any content to OV, strip **all** injected/synthetic blocks — not just `<relevant-memories>`. The Claude Code plugin strips `<openviking-context>`, `<system-reminder>`, `<relevant-memories>`, and `[Subagent Context]` blocks. Without comprehensive stripping, OV indexes injected context as conversation, creating a feedback loop that pollutes future recall quality.
+State is persisted as a pi custom entry:
-```typescript
-function stripInjectedBlocks(text: string): string {
- // Strip all blocks that OV or the agent framework injects
- text = text.replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/g, "");
- text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "");
- text = text.replace(/<openviking-context>[\s\S]*?<\/openviking-context>/g, "");
- text = text.replace(/\[Subagent Context\][\s\S]*?(?=\n\n|$)/g, "");
- text = text.replace(/\x00/g, ""); // null bytes from encoding issues
- return text.trim();
-}
+```ts
+pi.appendEntry("ov-takeover", state)
```
-#### Token estimation (CJK-aware)
-
-All token budgets in the spec use a CJK-aware estimator, not flat chars/4. The Claude Code plugin discovered that chars/4 silently undercounts CJK content by 4-6× — a "5000 token budget" with chars/4 becomes ~500 real tokens for Chinese text (from `profile-inject.mjs`).
+At startup the extension scans the branch from the end for the newest such entry and restores both the boundary and `SyncManager`'s watermark, so a `pi -c` continuation does not resend branch entries OpenViking already has.
-```typescript
-function estimateTokens(text: string): number {
- 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);
-}
-```
-
-Rule: codepoint >= 0x3000 (CJK / Hiragana / Katakana / Hangul / fullwidth) counts at 1.5 tokens/char. Everything else at chars/4. Errs on the side of overcounting CJK by ~10-20% — safe direction for budget enforcement.
-
-This affects: recall budget (`recallBudget`), profile budget (`profileBudget`), index budget (`indexBudget`), and per-item content cap (`recallMaxContentChars`). The per-item cap is in chars but should be validated against the CJK-aware estimator for content known to be CJK-heavy.
-
-#### Commit management
-
-Three commit triggers (matching Claude Code plugin's three-way approach):
-
-1. **Threshold commit**: When cumulative `pendingTokens` crosses `commitTokenThreshold` (default 20000), trigger `commit(wait=false)`. Token-based is more accurate than turn-based — a 1-line ack and a 10-tool-call turn are very different content volumes. Archive generation and memory extraction happen asynchronously on the OV server. If the session crashes at turn 80, memories from turns 1-70 are already committed.
-
-2. **Pre-compact commit**: When pi fires `compaction` event (before it rewrites the transcript), trigger `commit(wait=true)`. This is critical — without it, content that gets compacted away is lost to OV forever. The Claude Code plugin's `PreCompact` hook does the same thing.
-
-3. **Shutdown commit**: On `session_shutdown`, trigger `commit(wait=true)`. Blocks until extraction completes (with timeout). The safety net for the final turns.
-
-```typescript
-class SyncManager {
- private client: OVClient;
- private ovSessionId: string | null;
- private pendingTokens: number;
- private commitTokenThreshold: number;
- private syncedTurnCount: number; // incremental counter — prevents duplicate pushes
- private writeQueue: WriteQueue; // batches turns for efficient OV delivery
- private initialized: boolean;
-
- constructor(client: OVConfig, piSessionId: string, commitTokenThreshold: number);
-
- async ensureSession(): Promise<boolean>;
- async syncTurn(userMsg: string, assistantMsg: string, turnIndex: number): Promise<void>;
- // syncTurn runs shouldCapture() on userMsg, enqueues to writeQueue if passing,
- // checks turnIndex > syncedTurnCount before enqueuing (dedup guard),
- // estimates tokens (CJK-aware), adds to pendingTokens, checks threshold
- async commit(wait?: boolean): Promise<string | null>; // returns archive ID if committed
- async getPendingTokens(): Promise<number>; // fetches pending_tokens from session metadata
- async flushQueue(): Promise<void>; // flush write queue + check commit threshold
-}
-
-The `syncedTurnCount` counter prevents duplicate pushes if `turn_end` fires multiple times for the same turn (retries, errors). Each call checks `turnIndex > syncedTurnCount` before enqueuing; after successful enqueue, advances the counter. Persisted to a state file alongside the OV session so it survives across compactions within a session.
-```
+#### Runtime flow
-#### Write queue (async batching)
+1. `turn_end` captures new branch entries into the OpenViking session, falling back to the disk pending queue when the server is unreachable.
+2. When `pendingTokens` reaches `takeoverTokenThreshold`, and there are more user turns than `takeoverKeepRecentTurns`, takeover tries to advance.
+3. Advancing requires the flush barrier: every `addMessage` entry queued for *this* session must be delivered. Queued `commitSession` entries and entries belonging to other sessions do not hold it closed.
+4. The commit runs with `queueOnFailure: false`.
+5. The session context endpoint is polled until `latest_archive_overview` is available — `takeoverOverviewPollMax` attempts, `takeoverOverviewPollMs` apart. An empty overview is never injected; the boundary stays where it is and the token pressure resets so the next threshold crossing retries instead of re-committing every turn.
+6. On success the boundary advances to `lastSeenUserTurns - takeoverKeepRecentTurns`.
+7. The `context` hook then replaces every covered message with one synthetic user message beginning `[OpenViking Session Context]`, keeps the recent tail verbatim, and recall is injected into the newest kept user turn as usual.
-**Why pi doesn't need CC's detached-worker pattern.** CC hooks have strict timeouts (Stop = 45s, SessionEnd = 30s). If an HTTP call takes 20s, the user waits 20s. CC's `async-writer.mjs` solves this by draining stdin, approving immediately, and spawning a detached child process to do the HTTP work.
+The overview message's timestamp is derived from the first kept message, so the provider payload stays byte-stable between commits and can benefit from prompt caching.
-Pi extensions don't have this problem — event handlers are naturally async. `turn_end` handlers return promises; pi's event loop doesn't block the user on them. The spec already says "fire-and-forget" for turn additions.
+#### Compaction
-**But pi benefits from batching.** Instead of one HTTP call per turn (CC's approach — `addMessage()` in a loop), a write queue accumulates turns locally and flushes them in a single batch. This reduces HTTP overhead from N round-trips to 1 per flush.
+When pi emits `session_before_compact`, takeover runs the same flush → commit → overview sequence. On success it hands pi the overview as the compaction summary and resets the boundary, because pi's own compaction has absorbed it:
-```typescript
-class WriteQueue {
- private client: OVClient;
- private ovSessionId: string;
- private queue: { role: string; content: string }[];
- private flushTimer: NodeJS.Timeout | null;
- private flushIntervalMs: number; // default: 5000 (5 seconds)
- private flushThreshold: number; // default: 5 turns
- private flushing: boolean; // guard against concurrent flushes
-
- constructor(client: OVClient, ovSessionId: string);
-
- // Add a turn to the queue. Triggers flush if threshold reached.
- enqueue(role: string, content: string): void;
-
- // Flush all queued turns to OV in a single batch. Called automatically
- // at threshold or interval, and manually at pre-compact/shutdown.
- async flush(): Promise<void>;
-
- // Cancel any pending timer (called at shutdown).
- cancelPending(): void;
-}
-```
-
-**Flush triggers:**
-1. **Threshold**: when `queue.length >= flushThreshold` (default 5 turns), flush immediately.
-2. **Interval**: a `setInterval` timer flushes every `flushIntervalMs` (default 5000ms). Catches the case where the user sends a few turns then pauses.
-3. **Pre-compact**: `session_before_compact` calls `queue.flush()` synchronously before commit.
-4. **Shutdown**: `session_shutdown` calls `queue.flush()` before final commit.
-
-**Error handling**: if a flush fails (OV unreachable), the turns stay in the queue. The next flush attempt will retry them. This is a deliberate improvement over CC's approach, which advances the turn counter regardless of per-turn failures.
-
-**Config additions for write queue:**
-```typescript
-writeQueueFlushInterval: number; // Flush interval in ms (default: 5000)
-writeQueueFlushThreshold: number; // Flush after N queued turns (default: 5)
-```
-
-### tools.ts (~200 lines)
-
-7 tools for agent-initiated OV operations. All tools use the shared `OVClient` instance.
-
-#### `viking_search`
-```typescript
+```ts
{
- name: "viking_search",
- description: "Semantic search over the OpenViking knowledge base. Returns ranked results with viking:// URIs and abstracts. Use when you need to recall past decisions, user preferences, or project-specific knowledge not in current context.",
- promptSnippet: "Search OpenViking knowledge base for past decisions, preferences, and project knowledge",
- promptGuidelines: [
- "Use viking_search when you need information from previous sessions that may not be in MEMORY.md.",
- "Use viking_search before making decisions that might conflict with established patterns or past decisions.",
- ],
- parameters: Type.Object({
- query: Type.String({ description: "Search query" }),
- scope: Type.Optional(Type.String({ description: "Viking URI prefix to scope search (e.g., 'viking://resources/')" })),
- limit: Type.Optional(Type.Number({ description: "Max results (default: 10)" })),
- }),
-}
-```
-
-#### `viking_read`
-```typescript
-{
- name: "viking_read",
- description: "Read content at a viking:// URI. Three detail levels: 'abstract' (~100 tokens), 'overview' (~2k tokens), 'full' (complete). Start with abstract, escalate to overview/full when needed.",
- promptSnippet: "Read OpenViking content at a viking:// URI with tiered detail levels",
- parameters: Type.Object({
- uri: Type.String({ description: "viking:// URI to read" }),
- level: StringEnum(["abstract", "overview", "full"] as const),
- }),
-}
-```
-
-#### `viking_browse`
-```typescript
-{
- name: "viking_browse",
- description: "Browse the OpenViking knowledge store like a filesystem. List directory contents, get metadata, or view the hierarchy tree.",
- promptSnippet: "Browse the viking:// directory tree in OpenViking",
- parameters: Type.Object({
- action: StringEnum(["list", "stat"] as const),
- uri: Type.Optional(Type.String({ description: "viking:// URI (default: 'viking://')" })),
- }),
-}
-```
-
-#### `viking_remember`
-```typescript
-{
- name: "viking_remember",
- description: "Store a fact or memory in OpenViking. Stored as a session message and extracted into long-term memory on commit. Use for important information the agent should remember: preferences, decisions, gotchas, lessons learned.",
- promptSnippet: "Store a fact in OpenViking for cross-session persistence",
- promptGuidelines: [
- "Use viking_remember for facts that should survive across sessions but don't belong in MEMORY.md.",
- "Good for: user preferences, architectural decisions, gotchas, environment details.",
- ],
- parameters: Type.Object({
- content: Type.String({ description: "The fact or observation to store" }),
- category: Type.Optional(Type.String({ description: "Category hint: 'preference', 'entity', 'event', 'case', 'pattern'" })),
- }),
-}
-```
-
-#### `viking_forget`
-```typescript
-{
- name: "viking_forget",
- description: "Delete a memory by URI or search for a specific memory and remove it. Use to correct outdated or wrong information in the knowledge base.",
- promptSnippet: "Delete a memory from OpenViking by URI or query",
- parameters: Type.Object({
- uri: Type.Optional(Type.String({ description: "Exact viking:// URI to delete" })),
- query: Type.Optional(Type.String({ description: "Search query — deletes the strongest match if score > 0.8" })),
- }),
-}
-```
-
-#### `viking_add_resource`
-```typescript
-{
- name: "viking_add_resource",
- description: "Ingest a URL, file path, or document into the OpenViking knowledge base. OV auto-processes it into L0/L1/L2 tiers and indexes it for semantic search. Use for bootstrapping knowledge or adding reference documentation.",
- promptSnippet: "Ingest a URL or document into OpenViking for indexed retrieval",
- parameters: Type.Object({
- url: Type.String({ description: "URL or file path to ingest" }),
- reason: Type.Optional(Type.String({ description: "Why this resource is relevant (improves indexing)" })),
- }),
-}
-```
-
-#### `viking_archive_expand`
-```typescript
-{
- name: "viking_archive_expand",
- description: "Expand an archived session back into raw messages. Use when the archive summary is too coarse and you need the detailed conversation history. Returns the full message transcript for that archive.",
- promptSnippet: "Expand an archived session to see raw conversation messages",
- parameters: Type.Object({
- archive_id: Type.Optional(Type.String({ description: "Archive ID to expand (from session context)" })),
- session_id: Type.Optional(Type.String({ description: "OV session ID to expand" })),
- }),
+ compaction: {
+ summary: "[OpenViking Session Context]\n...",
+ firstKeptEntryId,
+ tokensBefore,
+ details: { source: "openviking" },
+ }
}
```
-### index.ts (~200 lines)
+If any step fails the handler returns nothing and pi's default compaction runs. Fail-open is deliberate: a failed takeover must never leave the session without a compaction.
-Main entry point. Wires everything together.
+#### Failure modes
-#### Event registrations
+| Failure | Behavior |
+|---|---|
+| Health check fails | Extension stays disconnected; pi runs normally |
+| Pending `addMessage` replay incomplete | Barrier stays closed, boundary is not advanced, full local history remains visible |
+| Commit fails | Boundary is not advanced; pending token pressure is retained |
+| Overview not ready | Boundary is not advanced; retried at the next threshold or by `/viking commit` |
+| Branch fingerprint mismatch | Boundary resets to 0 and full history is shown until the next successful advance |
+| Compaction takeover fails | Returns nothing; pi's default compaction proceeds |
-| Event | Handler | What it does |
-|-------|---------|-------------|
-| `session_start` | Init + Resume + Profile | Health check OV, check bypass, create/reuse session, **inject user profile** (profile.md + preferences/ + entities/ listing, capped at `profileBudget`), on resume: fetch archive overview, build memory index, register tools |
-| `before_agent_start` | Recall queue + System prompt | Queue current prompt without I/O, inject memory index + tool ad into system prompt |
-| `context` | Recall search + injection | Search after user-message rendering, then prepend `<relevant-memories>` (reuse cached block on later LLM iterations) |
-| `turn_end` | Sync | Strip all injected blocks, **capture filter (shouldCapture)**, **preserve tool USE inputs + tool summary line**, drop tool RESULTS, **enqueue to write queue** (auto-flushes at threshold/interval), track pending tokens, check commit threshold |
-| `session_before_compact` | Pre-compact commit + rehydration | Synchronous `commit(wait=true)` before pi rewrites the transcript, then fetch new archive overview and cache for next `before_agent_start` injection — content about to be compacted is preserved in OV and rehydrated after compaction |
-| `session_shutdown` | Final commit | Commit OV session (blocking), rebuild index, optionally mirror MEMORY.md |
-| `agent_end` | Cleanup | Invalidate recall cache |
+#### Live gate
-#### Guard pattern
+`scripts/e2e-live.sh` drives a real pi binary, a real OpenViking server and a real LLM endpoint (its required and optional environment variables are documented at the top of `scripts/e2e-live.mjs`). It runs three `pi -p` / `pi -c` turns with a tiny takeover threshold and asserts that the third provider payload carries `[OpenViking Session Context]` while the padding from the first turn is gone from the raw conversation history. Nothing in the unit suites covers that end to end, so it stays a manual gate.
-Two-level guard:
+### tools.ts
-1. **Health check**: At `session_start`, ping OV health. If unreachable: set `connected = false`, log once, all subsequent operations become no-ops. No retrying, no spamming. Tools return "OpenViking server is not reachable."
+Seven tools registered on pi's model, all sharing the one `OVClient`. Each handler answers "OpenViking server is not reachable." when the startup health check never succeeded, so a down server degrades to a message rather than an error.
-2. **Bypass check**: Before any OV operation, check `config.bypassPatterns` against `process.cwd()`. If the cwd matches any pattern (e.g., `/tmp/**`, `**/scratch/**`), skip all OV operations for this session. This prevents throwaway experiments from polluting long-term memory (from Claude Code plugin's `OPENVIKING_BYPASS_SESSION_PATTERNS`).
+| Tool | Purpose |
+|---|---|
+| `viking_search` | Semantic search, optionally scoped to a `viking://` prefix |
+| `viking_read` | Read one URI at `abstract`, `overview` or `full` detail |
+| `viking_browse` | List a directory or stat an entry |
+| `viking_remember` | Store a fact for cross-session persistence |
+| `viking_forget` | Delete by URI, or by query when the match is strong |
+| `viking_add_resource` | Ingest a URL into the knowledge base |
+| `viking_archive_expand` | Expand an archived session back into detail |
-#### Session resume rehydration
+Two of them are less direct than they look. `viking_remember` does not write a memory: it appends a `[Remember — <category>]` message to the live OV session, so extraction treats it like any other turn and the fact goes through the same pipeline as everything else. `viking_forget` by query deletes only when the top match scores above 0.8; below that it reports no strong match rather than guessing which memory to destroy. There is no `add_skill` tool — pi has a skill system of its own.
-When `session_start` fires with `reason: "resume"`, the session may have previous OV archives from a prior run. Fetch the latest archive overview (L1, ~2k tokens) and inject it alongside the memory index. This rehydrates the model's context with "what happened in the previous session" (from Claude Code plugin's SessionStart resume behavior).
+### index.ts
-#### System prompt injection
+The entry point. It loads the config, returns immediately when disabled, constructs the modules, and registers handlers.
-Via `before_agent_start`'s `systemPrompt` return field. Composes up to four things:
+| Event | Action |
+|---|---|
+| `session_start` | Kick off startup without awaiting it |
+| `before_agent_start` | Await startup, queue the prompt for recall, compose system-prompt additions |
+| `context` | Run the pending recall, apply the takeover transform, inject recall |
+| `tool_call` | Redirect host file tools that were handed a `viking://` URI |
+| `turn_end` | Sync the branch, feed the token estimate to takeover, update the status line |
+| `session_before_compact` | Takeover compaction, or a commit plus a fresh overview |
+| `session_shutdown` | Persist takeover state, or a final commit |
+| `agent_end` | Invalidate the recall cache |
-1. **Profile block** (from session_start cache) — user identity + preferences + entities. Capped at `profileBudget`. Only present if OV has a user profile.
-2. **Archive overview** (from session_start resume OR pre-compact rehydration) — "what happened in previous sessions" or "what happened before compaction". Capped at `resumeContextBudget` tokens.
-3. **Memory index** (from `index_builder.ts`) — a browsable table of contents showing what OV knows. Refreshed at session start and after commits.
-4. **Tool advertisement** — the standard tool usage instructions.
+**Two guards.** The bypass check runs the shared `isBypassed` against the cwd, so a scratch directory never pollutes long-term memory; the pattern syntax is the shared one, identical across harnesses. The health check runs once — if the server is unreachable the extension stays disconnected for the whole session, every handler returns early, and the tools say so. No retries, no repeated warnings.
-```
-## OpenViking Context
-<openviking-context source="session-start">
-<user-profile uri="viking://user/default/memories/profile.md">
-User prefers local/self-hosted solutions...
-</user-profile>
-<available-memories>
- viking://user/default/memories/preferences/
- - dark_mode.md — prefers dark mode in all editors
- viking://user/default/memories/entities/
- - project_x.md — Project X uses SQLite
-</available-memories>
-</openviking-context>
-
-[Session History Summary]
-Archive 2026-05-27: 15-turn session about pi extension design...
-
-## OpenViking Knowledge Index
-[Showing what's in your long-term memory]
-
-### viking://user/memories/ (12 memories)
-- Prefers local/self-hosted solutions over cloud services
-- ...
-
-### viking://resources/ (3 resources)
-- ...
-
-Tools: viking_search | viking_read | viking_browse | viking_remember | viking_forget | viking_add_resource | viking_archive_expand
-```
+**Startup is memoized, not awaited.** The startup chain — health check, session derivation, pending replay, profile build, takeover restore, tool registration — costs a couple of seconds against a remote server, and `session_start` does not await it, because that delay would land on every pi launch. `before_agent_start` awaits the same in-flight promise, so the first turn still gets its profile and recall. That is also the only startup path a `pi -c` continuation has: pi does not fire `session_start` for one.
-This is a key difference from Hermes (tool ad only, model is blind) and closer to OpenClaw's preflight `assemble()` (model sees archive overview + abstract index before deciding to search).
+**System prompt.** `before_agent_start` appends the profile block built by the shared `profile-inject.mjs` and capped at `profileTokenBudget`; outside takeover, the archive overview cached at resume or after a pre-compact commit; and one line naming the seven tools. Under takeover the overview reaches the model through the `context` hook instead, so it is not appended twice.
-#### Memory mirroring at commit time
+**Tool guard.** `guardVikingUriToolCall` (`lib/uri-guard-adapter.mjs`) watches for a `viking://` URI handed to a host tool that cannot read one — `read`, `grep`, `find`, `ls`, `bash` — and blocks the call with the equivalent `viking_*` invocation spelled out. Without it the model burns turns on a file path that does not exist on disk.
-Don't intercept individual `write`/`edit` tool calls (fragile, complex). Instead, at `session_shutdown` commit time:
-1. Read `.memory/MEMORY.md` if it exists
-2. Write it to OV as `viking://user/memories/memory-md` (or append as a session message tagged `[Memory mirror]`)
-3. OV's extraction picks it up during commit
+**Surface.** The status line reports connection, entries added on the last turn, and either takeover coverage against its threshold or the plain commit threshold. `/viking` prints that same state; `/viking commit` forces a flush and commit, which under takeover also advances the boundary.
-Simple, correct, handles all edge cases (external edits, multiple writes, etc.).
+## Event flow
-#### Manual commit command
+**Session start.** Bypass check, then health check; on failure everything after this is a no-op. Open the recall ledger, derive the OV session id, replay anything the pending queue still holds. Build the profile block. With takeover on, restore the boundary from the branch and hand `SyncManager` its watermark; with takeover off, fetch the archive overview for resume rehydration instead. Register the tools.
-A `/viking commit` command (or a `viking_commit` tool) triggers a synchronous `commit(wait=true)`. This is the equivalent of OpenClaw's `compact()` — the user or agent can force a memory extraction mid-session without waiting for the token threshold. Useful when the user says "remember this" and wants immediate assurance that the memory was archived.
+**Per prompt.** `before_agent_start` awaits startup, records the prompt for recall without any I/O, and returns the composed system prompt. Pi renders the user message. Then, for each LLM iteration, the `context` hook fires: the first one runs the search, the takeover transform replaces covered history with the overview message, and recall is injected — fresh into the newest user message, replayed from the ledger into the older ones. `agent_end` clears the cache.
-## Event Flow (Detailed)
+**Per turn.** `turn_end` extracts everything past the watermark from the branch, sanitizes and filters it, sends it as one batch (or queues it), advances the watermark, and estimates the tokens it just synced. Outside takeover, that is followed by a threshold check against the server's `pending_tokens`. Under takeover, the estimate is added to the pending pressure, which may trigger a flush, commit and boundary advance.
-### Session Start
-```
-1. session_start fires
-2. Load config
-3. Check bypassPatterns against cwd
- └── MATCH → set bypassed = true, skip all OV ops, return
-4. client.health()
- ├── OK → connected = true, continue
- └── FAIL → connected = false, log once, return
-5. sync.ensureSession() → create or reuse OV session "pi-{sessionId}"
-6. **Profile injection** (all sessions, from Claude Code plugin):
- a. Resolve user space: `client.resolveScopeSpace("user")` → discover namespace via /api/v1/system/status + fs/ls
- b. Read profile.md from viking://user/<space>/memories/profile.md
- c. List preferences/ and entities/ directories with abstracts
- d. **Profile elision** (from Claude Code plugin): if profile exceeds `profileBudget` tokens, keep head (identity block, first 8 lines) + tail (most-recent events, fits remaining budget), drop noisy middle. Preserves both stable identity facts (top of file) and recent activity (bottom of file) — only the noisy middle timeline is sacrificed. Falls back to head-only truncate when file is too short to elide.
- e. Compose <openviking-context> block with user-profile + available-memories
- f. Capped at profileBudget tokens (default 10000) using CJK-aware estimator
- g. Cached for system prompt injection in before_agent_start
-7. If event.reason == "resume":
- a. Fetch latest archive overview from OV (L1)
- b. Inject as [Session History Summary] alongside memory index
-8. index_builder.buildIndex() → build memory index (viking:// tree + abstracts)
-9. Register 7 tools
-```
+**Pre-compact.** Under takeover, pi is handed the OV overview as its compaction summary, or nothing at all if any step failed. Outside takeover, the extension commits so that content pi is about to rewrite is preserved as an archive, then caches the new overview for the next system prompt.
-### Per Prompt (User sends message)
-```
-1. before_agent_start fires
- a. Extract user prompt text
- b. recall.queueSearch(prompt) ← no network I/O
- c. Compose system prompt: event.systemPrompt + profileBlock + archiveOverview + indexBuilder.getIndex() + toolAdBlock
- - Profile block: cached from session_start (or empty if OV has no profile)
- - Archive overview: cached from session_start resume, or from pre-compact rehydration
- d. Return { systemPrompt: composed }
-
-2. Pi renders the submitted user message.
-
-3. [For each LLM iteration within this prompt:]
- a. context event fires
- b. recall.searchPending() ← first iteration only; synchronous OV search for the current prompt
- c. recall.injectRecall(event.messages) ← prepend cached <relevant-memories> to user message
- d. Return { messages: modified }
-
-4. [Turns execute — LLM may call viking_search, etc.]
-
-5. agent_end fires
- a. recall.invalidate() ← clear cached block
-```
+**Shutdown.** Flush, then persist takeover state, or commit one last time when takeover is off.
-### Per Turn
-```
-1. turn_end fires
-2. Extract user text + assistant text from event
-3. Strip ALL injected blocks (<relevant-memories>, <system-reminder>, <openviking-context>, [Subagent Context], null bytes) from both
-4. Preserve tool USE inputs as [tool: <name>]\n<input> — drop tool RESULTS (unless captureToolResults is true)
-5. Add tool summary line to assistant turn: `[assistant used tools: read, edit, bash]`
-6. **Capture filter**: shouldCapture(strippedUserText, captureMode)
- └── SKIP → advance syncedTurnCount, return (no OV push)
-7. If captureAssistantTurns is false: only push user message, skip assistant
-8. sync.syncTurn(strippedUser, strippedAssistant, turnIndex)
- a. Dedup guard: if turnIndex <= syncedTurnCount, skip (prevents duplicate pushes on retries)
- b. Enqueue turn to write queue (queue auto-flushes at threshold or interval)
- c. Estimate token count for stripped content (CJK-aware)
- d. pendingTokens += estimatedTokens
- e. If pendingTokens >= commitTokenThreshold: writeQueue.flush() then sync.commit(wait=false)
- f. syncedTurnCount = turnIndex + 1
-```
+## Two decisions worth recording
-### Pre-Compact
-```
-1. session_before_compact event fires (pi is about to rewrite the transcript)
-2. writeQueue.flush() ← flush any queued turns before committing
-3. sync.commit(wait=true) ← BLOCKING: archive all pending content before pi mutates it
-3. Content about to be compacted away is now preserved in OV as an archive
-4. **Post-compact rehydration**: fetch the newly-committed archive overview (L1) and cache it
-5. On the next before_agent_start, inject the cached archive overview alongside the memory index
- → The model gets rehydrated with "what happened before compaction" from OV's long-term record
- → This mirrors CC's SessionStart(source="compact") dual injection pattern
-```
+**The memory index was superseded, the reasoning behind it was not.** An earlier draft of this design specified an `index_builder.ts` that would keep a browsable table of contents of `viking://` in the system prompt; it was superseded by `shared/profile-inject.mjs`, whose profile block is folded into `systemPrompt` instead. The block stays a listing rather than memory content for the reasons the index was a listing: a map costs a fixed, small token budget, stays relevant to every turn instead of one, and is never stale in the way a copied memory is. Recall is the flashlight that fetches content for the turn at hand; the block is the map that tells the model what there is to fetch.
-### Session Shutdown
-```
-1. session_shutdown fires
-2. writeQueue.cancelPending() ← cancel any pending flush timer
-3. writeQueue.flush() ← flush remaining queued turns
-4. If mirrorMemoryWrites: read .memory/MEMORY.md → send to OV as session message
-5. sync.commit(wait=true) ← blocking, with timeout
-6. index_builder.buildIndex() ← refresh index after commit (new memories extracted)
-7. Cleanup
-```
+**Capture works on whole turns, not on individual tool calls.** `turn_end` hands `sync.ts` the finished branch, and that is what gets mirrored; `tool_call` is only ever consulted by the URI guard. A turn carries the user's intent and the assistant's conclusion together, which is what a memory needs, while a single tool call carries neither, so intercepting them one by one would have produced many fragments and no memories.
-## Comparison: Hermes vs OpenClaw vs Claude Code vs This Extension
-
-| Aspect | Hermes | OpenClaw | Claude Code | Pi Extension |
-|--------|--------|----------|-------------|------------- |
-| Plugin type | Built-in memory provider | Context engine plugin | CC hooks + MCP | pi extension |
-| Recall mechanism | Stale background prefetch | Synchronous `assemble()` | Synchronous `UserPromptSubmit` hook | Synchronous `context` event |
-| Recall timing | N-1 turn (wrong topic) | Current turn | Current turn | Current turn |
-| First turn recall | Nothing | Relevant context | Relevant context | Relevant context + user profile |
-| Search scope | Unscoped | Dual (user + agent) | Triple (user + agent + skills) | ✅ Triple (user + agent + skills) |
-| Query profiling | None | None | ✅ Intent detection (preference/temporal) | ✅ Intent detection (preference/temporal) |
-| Score threshold | None | None | 0.35 | ✅ 0.35 |
-| Min query filter | None | None | 3 chars | ✅ 3 chars |
-| Deduplication | None | None | ✅ By URI (events) + by abstract (others) | ✅ By URI (events) + by abstract (others) |
-| Content resolution | None (abstracts only) | None | ✅ Tiered (abstract → overview → full) | ✅ Tiered (abstract preferred, full on demand) |
-| Result degradation | None | None | ✅ URI hints beyond budget | ✅ URI hints beyond budget |
-| Per-item content cap | None | None | ✅ 500 chars | ✅ 500 chars |
-| Memory index in prompt | None (model blind) | Archive overview + abstracts | Archive overview on resume | ✅ viking:// tree + memory abstracts |
-| Profile injection | None | None | ✅ profile.md + preferences + entities | ✅ profile.md + preferences + entities |
-| Commit trigger | Session-end only | Token threshold | Token threshold + pre-compact + session-end | ✅ Token threshold + pre-compact + session-end |
-| Memory stripping | None | Strip `<relevant-memories>` | Strip all injected blocks (5+ tag types + null bytes) | ✅ Strip all injected blocks (5+ tag types + null bytes) |
-| Capture: tool use inputs | Not captured | Not captured | ✅ Preserved verbatim | ✅ Preserved verbatim |
-| Capture: tool results | Not captured | Not captured | ✅ Dropped by default | ✅ Dropped by default (configurable) |
-| Capture dedup | None | None | ✅ Incremental turn counter | ✅ Incremental turn counter |
-| Pre-compact commit | N/A | N/A | ✅ `PreCompact` hook | ✅ `session_before_compact` event |
-| Post-compact rehydration | N/A | N/A | ✅ SessionStart(source="compact") | ✅ Archive overview cached at pre-compact, injected at next before_agent_start |
-| Token estimation | N/A | N/A | ✅ CJK-aware (1.5 tokens/char for CJK, chars/4 otherwise) | ✅ CJK-aware |
-| Subagent isolation | None | None | ✅ Isolated OV sessions via hooks | ✅ Natural process-level isolation (separate pi process = separate session) |
-| Session resume | N/A | Archive overview | ✅ Archive overview rehydration | ✅ Archive overview rehydration |
-| Bypass patterns | None | None | ✅ Glob on cwd/session | ✅ Glob on cwd |
-| Capture filtering | None | None | ✅ shouldCapture (length, command, question-only, keyword/semantic modes) | ✅ shouldCapture (length, command, question-only, keyword/semantic modes) |
-| URI space resolution | None | None | ✅ resolveScopeSpace + resolveTargetUri | ✅ resolveScopeSpace + resolveTargetUri |
-| Async write path | None | None | ✅ Detached-worker (hook timeout avoidance) | ✅ Write queue (batching, not timeout avoidance — pi events are async) |
-| Tools | 5 | 8 | 9 (via MCP) | 7 |
-| Dependencies | httpx (Python) | Pure HTTP client | Plain .mjs scripts, no deps | Zero npm deps (built-in `fetch`) |
-
-## Why a Memory Index?
-
-The spec has two complementary context mechanisms:
-
-1. **Memory index** (from `index_builder.ts`) — a *map*. "Here's what OV knows about." Injected into the system prompt. Rebuilt at session start and after commits. Always visible to the model. ~2000 tokens.
-
-2. **Recall** (from `recall.ts`) — a *flashlight*. "Here's what's relevant to the current query." Injected into the user message per-turn. Always current. ~2000 tokens.
-
-Without the index, the model has no idea what categories of knowledge exist in OV. It can only retrieve what it thinks to ask for — the Hermes problem. With the index, the model sees "OV knows about my preferences, project X architecture, and debugging gotchas" and can proactively decide to search deeper when a task touches those topics.
-
-This mirrors OpenClaw's preflight `assemble()` which provides `latest_archive_overview` (archive summary) and `pre_archive_abstracts` (memory abstracts) to the model. The index is the pi equivalent.
-
-## Dependencies
-
-**Zero npm dependencies.** Uses:
-- Node.js built-in `fetch` (Node 18+, pi requires 18+)
-- `@mariozechner/pi-coding-agent` (types, `isToolCallEventType`, `StringEnum`, `truncateHead`)
-- `typebox` (tool parameter schemas)
-- `@mariozechner/pi-ai` (`StringEnum` for Google-compatible enums)
-
-## Implementation Order
-
-1. **client.ts** — HTTP wrapper, testable independently against running OV
-2. **sync.ts** — depends on client
-3. **index_builder.ts** — depends on client
-4. **recall.ts** — depends on client
-5. **tools.ts** — depends on client
-6. **index.ts** — wires everything, registers tools and events
-
-## Testing Strategy
-
-- **Unit test `client.ts`**: Run against live OV server at `127.0.0.1:1933`
-- **Integration**: Start pi with extension, have a conversation, verify in OV studio that messages synced, recall blocks stripped, commit triggered
-- **Recall accuracy**: Ask a question about a topic from a previous session, verify `<relevant-memories>` appears in context
-- **Index visibility**: Start a new session, verify the system prompt contains the memory index with correct counts and abstracts
-- **Tool test**: Call each of the 7 tools manually in a pi session
-- **Pre-compact commit**: Have a 20+ turn conversation (triggering threshold commits), then trigger compaction. Verify that pre-compact commit fires and content is archived before compaction mutates the transcript.
-- **Bypass**: Start pi in `/tmp`, verify no OV operations fire.
-- **Session resume**: End a session with committed content, start new session with resume, verify archive overview appears in context.
-- **Post-compact rehydration**: Trigger compaction in a long session (after threshold commit fires), verify that pre-compact commit archives content, and the next before_agent_start includes the new archive overview.
-- **Capture filtering**: Send one-word turns ("ok", "y", "/help"), pure questions ("what is X?"), and substantive turns. Verify that noise turns are skipped and only substantive turns reach OV.
-- **Keyword mode**: Set captureMode to "keyword", send turns with and without trigger phrases, verify only triggered turns are captured.
-- **URI space resolution**: On a multi-user OV setup, verify that viking://user/memories resolves to viking://user/<alice>/memories correctly.
-- **Write queue batching**: Send 3 turns quickly, verify they're queued and flushed as a batch at the threshold. Verify the flush timer fires after the interval if threshold isn't reached.
-
-## Config File
-
-Default: `~/.pi/agent/extensions/openviking/config.json`
-
-```json
-{
- "enabled": true,
- "endpoint": "http://127.0.0.1:1933",
- "apiKey": "",
- "account": "",
- "user": "",
- "peerId": "",
- "syncTurns": true,
- "recallBudget": 2000,
- "recallMaxContentChars": 500,
- "recallPreferAbstract": true,
- "recallScoreThreshold": 0.35,
- "recallMinQueryLength": 3,
- "profileBudget": 10000,
- "resumeContextBudget": 2000,
- "indexBudget": 2000,
- "commitTokenThreshold": 20000,
- "commitOnShutdown": true,
- "captureToolResults": false,
- "captureMode": "semantic",
- "captureMaxLength": 24000,
- "captureAssistantTurns": true,
- "mirrorMemoryWrites": true,
- "writeQueueFlushInterval": 5000,
- "writeQueueFlushThreshold": 5,
- "bypassPatterns": [],
- "logLevel": "error"
-}
-```
+**Token estimates are CJK-aware.** `estimateTokens` counts codepoints at or above U+3000 as 1.5 tokens and everything else at a quarter of a token. Flat chars/4 undercounts CJK by four to six times, which silently turns a 3000-token overview budget into a few hundred real tokens of Chinese. It overcounts CJK slightly, which is the safe direction for a budget.
diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.md
index 12e605fba..697cbc7ce 100644
--- a/examples/pi-coding-agent-extension/README.md
+++ b/examples/pi-coding-agent-extension/README.md
@@ -6,7 +6,7 @@ Long-term semantic memory and context takeover for [pi](https://github.com/earen
> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
> `viking://user/memories` shorthand is rejected by newer servers.
-> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the base design and [TAKEOVER.md](./TAKEOVER.md) for the context-takeover layer.
+> Design informed by lessons from all three OpenViking agent plugins: synchronous recall from OpenClaw, production-hardened capture/ranking from Claude Code, and anti-patterns dodged from Hermes's stale prefetch approach. See [DESIGN.md](./DESIGN.md) for the module-by-module design, including the context-takeover layer.
## Quick Start
@@ -44,32 +44,39 @@ Credentials are resolved from `OPENVIKING_*` environment variables, `~/.openviki
node ~/.pi/agent/extensions/openviking/scripts/setup.mjs
```
-`~/.pi/agent/extensions/openviking/config.json` is for behavior and peer-scoping knobs. Connection and authentication credentials still come from the shared sources above:
+Behaviour and peer-scoping knobs live in `~/.openviking/ovcli.conf` beside the credentials, in the shared `plugin` section or in the `plugin.pi` override. The extension has no configuration file of its own:
```json
{
- "enabled": true,
- "syncTurns": true,
- "peerId": "",
- "workspacePeer": true,
- "recallPeerScope": "all",
- "recallTokenBudget": 2000,
- "scoreThreshold": 0.35,
- "minQueryLength": 3,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000,
- "commitTokenThreshold": 20000,
- "takeover": {
- "enabled": true,
- "tokenThreshold": 30000,
- "keepRecentTurns": 3,
- "overviewBudget": 3000,
- "overviewPollMs": 2000,
- "overviewPollMax": 15
+ "url": "http://127.0.0.1:1933",
+ "api_key": "your-api-key-here",
+ "plugin": {
+ "recallLimit": 6,
+ "pi": {
+ "enabled": true,
+ "autoCapture": true,
+ "peerId": "",
+ "workspacePeer": true,
+ "recallPeerScope": "all",
+ "recallTokenBudget": 2000,
+ "scoreThreshold": 0.35,
+ "minQueryLength": 3,
+ "profileTokenBudget": 10000,
+ "resumeContextBudget": 32000,
+ "commitTokenThreshold": 20000,
+ "takeoverEnabled": true,
+ "takeoverTokenThreshold": 30000,
+ "takeoverKeepRecentTurns": 3,
+ "takeoverOverviewBudget": 3000,
+ "takeoverOverviewPollMs": 2000,
+ "takeoverOverviewPollMax": 15
+ }
}
}
```
+Keys in `plugin` apply to every harness; keys in `plugin.pi` apply to this extension and override them. Resolution is `OPENVIKING_*` environment variables → the workspace's `.openviking/config.json`, `.openviking/config.local.json` and machine registry entry → `plugin.pi` → `plugin` → built-in defaults. Every knob, with its type, default, range, environment variable and accepted older spellings, is declared in [`examples/memory-plugin-shared/lib/config-schema.mjs`](../memory-plugin-shared/lib/config-schema.mjs); `syncTurns` still works wherever `autoCapture` is written above.
+
Credential environment variables:
| Env Var | Meaning |
@@ -89,7 +96,7 @@ tiers and cross-turn dedup are shared with every other harness. Deployments
without that endpoint fall back to `/api/v1/search/recall`, and that outcome is
cached so only the first turn pays for the probe.
-API keys are sent as `Authorization: Bearer ...`. By default the extension derives a peer from the git identity of the process workspace path: the normalized `origin` URL of the repository the workspace sits in, else that repository's root path. Outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space `viking://user/<you>/memories`. `[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`; the path fallback keeps the older naming rule where every non-letter-or-digit character becomes `-`, so `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. One repository therefore keeps one peer across subdirectories, worktrees, clones and machines, while a fork's different origin keeps it separate. The extension does not read workspace `.openviking/config.json` files, so a `peer.id` written there has no effect. The effective peer is sent as `X-OpenViking-Actor-Peer` and stored as `peer_id` on captured session messages. An explicit peer from the shared credential sources (`OPENVIKING_PEER_ID`, `ovcli.conf`, or `ov.conf`) takes precedence over `config.json`'s `peerId`; the local `peerId` in turn takes precedence over workspace derivation. Memories written under the older path-derived peer stay reachable under the default broad recall, which sweeps every peer under the user.
+API keys are sent as `Authorization: Bearer ...`. By default the extension derives a peer from the git identity of the process workspace path: the normalized `origin` URL of the repository the workspace sits in, else that repository's root path. Outside a git repository no peer is sent at all, and what is remembered there goes to the user-level space `viking://user/<you>/memories`. `[email protected]:volcengine/OpenViking.git` becomes `github.com-volcengine-openviking`; the path fallback keeps the older naming rule where every non-letter-or-digit character becomes `-`, so `/Users/x/Dev/OpenViking` becomes `-Users-x-Dev-OpenViking`. One repository therefore keeps one peer across subdirectories, worktrees, clones and machines, while a fork's different origin keeps it separate. The extension reads the workspace's `.openviking/config.json`, so a `peer.id` or `peer.source` written there applies. The effective peer is sent as `X-OpenViking-Actor-Peer` and stored as `peer_id` on captured session messages. `OPENVIKING_PEER_ID` takes precedence over every file; below it, a workspace `peer.id` or the `plugin` section's `peerId` takes precedence over `ovcli.conf`'s `actor_peer_id` and `ov.conf`'s `pi.peerId`; and a peer from any of those takes precedence over workspace derivation. Memories written under the older path-derived peer stay reachable under the default broad recall, which sweeps every peer under the user.
Recall defaults to the broad mode: global memory, the current workspace, and other workspace memories can all be recalled, with other workspaces penalized and rendered later. Set `OPENVIKING_RECALL_PEER_SCOPE=actor` for the isolation mode, which only sees global memory plus the current workspace. In deployments where one bot serves multiple real people, such as zouk, vikingbot, or AstrBot, use the isolation mode with an explicit actor peer so one person's memories are not recalled into another person's session.
@@ -105,12 +112,12 @@ The extension shows an `[OpenViking]` status line on startup. Tools (`viking_sea
### Tuning fields
-All fields below live in `config.json`. Defaults are shown.
+All fields below live in `ovcli.conf`'s `plugin` section, or in the `plugin.pi` override. Defaults are shown.
| Field | Default | Description |
|--------------------------|------------|--------------------------------------------------------------------------|
| `enabled` | `true` | Set `false` to disable the extension entirely |
-| `syncTurns` | `true` | Enable auto-capture of conversation turns |
+| `autoCapture` | `true` | Enable auto-capture of conversation turns. `syncTurns` is the older name and still works |
### Peer scoping
@@ -174,12 +181,12 @@ recent live tail.
| Field | Default | Description |
|--------------------------|------------|--------------------------------------------------------------------------|
-| `takeover.enabled` | `true` | Let OpenViking own long-term context through the `context` hook |
-| `takeover.tokenThreshold`| `30000` | Synced-token pressure that triggers commit and boundary advance |
-| `takeover.keepRecentTurns`| `3` | Recent user turns retained in full fidelity |
-| `takeover.overviewBudget`| `3000` | Token budget for the injected archive overview |
-| `takeover.overviewPollMs`| `2000` | Delay between overview polling attempts after commit |
-| `takeover.overviewPollMax`| `15` | Max overview polling attempts before fail-open |
+| `takeoverEnabled` | `true` | Let OpenViking own long-term context through the `context` hook. Env: `OPENVIKING_TAKEOVER` |
+| `takeoverTokenThreshold` | `30000` | Synced-token pressure that triggers commit and boundary advance |
+| `takeoverKeepRecentTurns`| `3` | Recent user turns retained in full fidelity |
+| `takeoverOverviewBudget` | `3000` | Token budget for the injected archive overview |
+| `takeoverOverviewPollMs` | `2000` | Delay between overview polling attempts after commit |
+| `takeoverOverviewPollMax`| `15` | Max overview polling attempts before fail-open |
### Injection tuning
@@ -192,10 +199,12 @@ recent live tail.
| Field | Default | Description |
|--------------------------|------------|--------------------------------------------------------------------------|
-| `bypassPatterns` | `[]` | Glob patterns to skip extension processing |
+| `bypassSessionPatterns` | `[]` | Glob patterns matched against the cwd; a hit skips all OpenViking work for the session. `bypassPatterns` is the older name and still works. Env: `OPENVIKING_BYPASS_SESSION_PATTERNS` (CSV), `OPENVIKING_BYPASS_SESSION=1` |
| `logLevel` | `"error"` | `"silent"`, `"error"`, or `"info"` |
| `debugLogPath` | `""` | Write JSON Lines debug records to this path; empty disables the log |
+Bypass now runs through the same matcher every other OpenViking harness uses, so the patterns are real globs: `*` stops at a path separator and `**` crosses them. A bare path used to match its subdirectories as a prefix, and no longer does — write `"/tmp/scratch**"` where `"/tmp/scratch"` used to be enough.
+
## Architecture
```
@@ -296,20 +305,21 @@ Both plugins share the same core design (informed by each other):
## Extension Structure
-See [DESIGN.md](./DESIGN.md) for the full design specification — comparison of all three OV plugins, detailed event flow, design rationale, and implementation guidance useful for building OV extensions for any agent harness.
+See [DESIGN.md](./DESIGN.md) for what each module is responsible for, how the modules meet pi's events, and the design ancestry shared with the other OpenViking plugins.
```
pi-coding-agent-extension/
-├── config.json # Default configuration (edit to customize)
-├── config.ts # Config loader (defaults + config.json merge)
+├── config.ts # Config loader (shared schema + ovcli.conf layers)
├── client.ts # OpenViking HTTP client (fetch + response envelope)
├── sync.ts # Turn capture, write queue, session lifecycle
├── recall.ts # Synchronous recall with ranking + budget
├── takeover.ts # Thin pi binding around lib/takeover-core.mjs
├── tools.ts # 7 registered LLM tools + /viking command
├── lib/takeover-core.mjs # Pure context-takeover state machine
+├── lib/recall-ledger.mjs # Injected recall blocks, replayed to keep prompt caches warm
├── index.ts # Extension entry point (event handlers)
-├── TAKEOVER.md # Context-takeover design
+├── package.json # Name and version (the User-Agent's, and the release gate's)
+├── DESIGN.md # Module-by-module design, including context takeover
└── README.md
```
@@ -319,7 +329,7 @@ All TypeScript files are loaded directly by pi's built-in `jiti` transpiler —
| Symptom | Cause | Fix |
|-----------------------------------------|------------------------------------------------------|-------------------------------------------------------------|
-| Extension not loading | `enabled: false` in config.json | Set `"enabled": true` |
+| Extension not loading | `enabled: false` in `ovcli.conf`'s `plugin` section | Set `"enabled": true` |
| No recall on first prompt | OpenViking server not running or wrong URL | `curl http://localhost:1933/health` |
| Tools not showing after `pi -c` resume | Known pi issue (tools not re-registered on resume) | Workaround built in — tools register in `before_agent_start`|
| Extension crashes on load | Wrong OV server URL or network issue | Check `logLevel` and server accessibility |
diff --git a/examples/pi-coding-agent-extension/TAKEOVER.md b/examples/pi-coding-agent-extension/TAKEOVER.md
deleted file mode 100644
index e89a9c55f..000000000
--- a/examples/pi-coding-agent-extension/TAKEOVER.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# OpenViking Context Takeover for Pi
-
-Context takeover makes OpenViking the authoritative long-term context store for
-pi sessions. Pi still keeps recent active turns locally, but committed history
-is represented to the model by OpenViking's archive overview through pi's
-`context` hook.
-
-## Model
-
-The extension tracks:
-
-| Field | Meaning |
-|-------|---------|
-| `coveredUserTurns` | Number of real user turns already covered by the OV archive overview |
-| `overview` | Latest archive overview returned by `GET /sessions/{id}/context` |
-| `fingerprint` | Stable fingerprint of the last covered message for branch mismatch detection |
-| `pendingTokens` | Estimated synced token pressure since the last successful boundary advance |
-| `syncedEntryCount` | Pi branch watermark restored across `pi -p` / `pi -c` processes |
-
-State is persisted as a pi custom entry:
-
-```ts
-pi.appendEntry("ov-takeover", state)
-```
-
-On startup the extension scans the branch from the end, restores the latest
-entry, and restores `SyncManager`'s watermark so `pi -c` does not resend the
-same branch entries to OpenViking.
-
-## Runtime Flow
-
-1. `turn_end` captures new branch entries into the OpenViking session.
-2. The capture path uses a disk pending queue when OpenViking is temporarily
- unreachable.
-3. When `pendingTokens >= takeover.tokenThreshold`, takeover tries to advance.
-4. Advance requires a successful flush barrier: all current-session
- `addMessage` queue entries must be delivered. Pending `commitSession`
- entries and entries for other sessions do not block the barrier.
-5. The extension commits with `queueOnFailure: false`; a delayed commit cannot
- safely advance the local context boundary.
-6. The extension polls session context until `latest_archive_overview` is
- available, then advances to `lastSeenUserTurns - keepRecentTurns`.
-7. The `context` hook replaces covered conversation messages with a synthetic
- user message beginning with `[OpenViking Session Context]`, then recall is
- injected into the remaining latest user turn.
-
-The overview message timestamp is derived from the first kept message, so the
-provider payload remains byte-stable between commits and can benefit from
-prompt caching.
-
-## Compaction
-
-When pi emits `session_before_compact`, takeover attempts the same
-flush-commit-overview sequence. If it succeeds, the extension returns:
-
-```ts
-{
- compaction: {
- summary: "[OpenViking Session Context]\\n...",
- firstKeptEntryId,
- tokensBefore,
- details: { source: "openviking" }
- }
-}
-```
-
-If any step fails, the handler returns `undefined` and pi's default compaction
-runs. This is intentional fail-open behavior.
-
-## Capture Fidelity
-
-Takeover mode enables faithful capture in the pi adapter. Short acknowledgments,
-punctuation-only turns, and other low-signal text are still captured because
-those turns may later disappear from the live model context. Empty text,
-slash commands, and OpenViking status messages remain filtered.
-
-## Configuration
-
-```json
-{
- "takeover": {
- "enabled": true,
- "tokenThreshold": 30000,
- "keepRecentTurns": 3,
- "overviewBudget": 3000,
- "overviewPollMs": 2000,
- "overviewPollMax": 15
- }
-}
-```
-
-| Field | Default | Meaning |
-|-------|---------|---------|
-| `takeover.enabled` | `true` | Enable context takeover |
-| `takeover.tokenThreshold` | `30000` | Synced-token pressure required before commit and boundary advance |
-| `takeover.keepRecentTurns` | `3` | Recent user turns kept in full fidelity |
-| `takeover.overviewBudget` | `3000` | Token budget for the injected archive overview |
-| `takeover.overviewPollMs` | `2000` | Delay between overview polling attempts |
-| `takeover.overviewPollMax` | `15` | Max overview polling attempts after commit |
-
-## Failure Modes
-
-| Failure | Behavior |
-|---------|----------|
-| OpenViking health check fails | Extension stays disconnected; pi runs normally |
-| Pending addMessage replay fails | Boundary is not advanced; full local history remains visible |
-| Commit fails | Boundary is not advanced; pending token pressure remains |
-| Overview is not ready | Boundary is not advanced; retry on the next threshold or manual `/viking commit` |
-| Branch fingerprint mismatch | Boundary resets to 0 and full history is shown until the next successful advance |
-| Compaction takeover fails | Returns `undefined`; pi default compaction proceeds |
-
-## Live E2E
-
-The manual live gate is:
-
-```bash
-OPENVIKING_URL=... \
-OPENVIKING_API_KEY=... \
-E2E_LLM_API_KEY=... \
-bash examples/pi-coding-agent-extension/scripts/e2e-live.sh
-```
-
-Any OpenAI- or Anthropic-compatible endpoint works: override `E2E_LLM_BASE_URL`,
-`E2E_LLM_MODEL`, and `E2E_LLM_API` (pi provider api type, e.g.
-`anthropic-messages`; defaults to `openai-completions`).
-
-It runs three real `pi -p` / `pi -c` turns, sets a tiny takeover threshold, and
-asserts that the third provider payload contains `[OpenViking Session Context]`
-while old padding from the first turn is no longer present in raw conversation
-history.
diff --git a/examples/pi-coding-agent-extension/client.ts b/examples/pi-coding-agent-extension/client.ts
index 0dce212e3..25e4b62ec 100644
--- a/examples/pi-coding-agent-extension/client.ts
+++ b/examples/pi-coding-agent-extension/client.ts
@@ -1,4 +1,6 @@
import type { OVConfig } from "./config.js";
+import type { OvHttpRequestOptions } from "./shared/ov-http.mjs";
+import { createOvHttp } from "./shared/ov-http.mjs";
// --- OV API Response Shapes ---
// All OV responses wrap in: { status: "ok"|"error", result: T, error?: {...}, ... }
@@ -83,93 +85,41 @@ export interface OVResponse<T> {
}
export class OVClient {
- private baseUrl: string;
- private apiKey: string;
- private account: string;
- private user: string;
- private peerId: string;
+ private http: ReturnType<typeof createOvHttp>;
connected: boolean = false;
- private resolvedSpaces: Map<string, string> = new Map();
-
- private static RESERVED_USER = new Set(["memories"]);
- private static RESERVED_AGENT = new Set(["memories", "skills", "instructions", "workspaces"]);
-
/** Read-only access to config (for value access across modules). */
readonly cfg: OVConfig;
constructor(config: OVConfig) {
this.cfg = config;
- this.baseUrl = config.endpoint.replace(/\/+$/, "");
- this.apiKey = config.apiKey;
- this.account = config.account;
- this.user = config.user;
- this.peerId = config.peerId;
- }
-
- private headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
- if (this.apiKey) h["Authorization"] = `Bearer ${this.apiKey}`;
- if (this.account) h["X-OpenViking-Account"] = this.account;
- if (this.user) h["X-OpenViking-User"] = this.user;
- if (this.peerId) h["X-OpenViking-Actor-Peer"] = this.peerId;
- if (this.cfg.userAgent) h["User-Agent"] = this.cfg.userAgent;
- return h;
+ this.http = createOvHttp(
+ { ...config, baseUrl: config.endpoint.replace(/\/+$/, "") },
+ { defaultTimeoutMs: 10000, resolveActorPeerId: () => config.peerId },
+ );
}
/** Core fetch wrapper. Returns { ok, result } after parsing OV's { status, result } envelope. */
- async fetchJSON<T>(path: string, init?: RequestInit, timeoutMs = 10000): Promise<OVResponse<T>> {
- try {
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeoutMs);
- const resp = await fetch(`${this.baseUrl}${path}`, {
- ...init,
- headers: { ...this.headers(), ...(init?.headers as Record<string, string> || {}) },
- signal: controller.signal,
- });
- clearTimeout(timer);
- const body = await resp.json().catch(() => ({}));
- const traceId = body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
- if (!resp.ok || body.status === "error") {
- return {
- ok: false,
- result: null,
- status: resp.status,
- error: body.error || { message: `HTTP ${resp.status}` },
- traceId,
- };
- }
- return { ok: true, result: (body.result ?? body) as T, traceId };
- } catch (err: any) {
- return { ok: false, result: null, status: 0, error: { message: err?.message || String(err) } };
- }
+ async fetchJSON<T>(path: string, init?: RequestInit, options?: OvHttpRequestOptions): Promise<OVResponse<T>> {
+ return this.http(path, init, options);
}
// ========== Health ==========
async health(): Promise<boolean> {
- const res = await this.fetchJSON<any>("/health", undefined, 5000);
+ const res = await this.fetchJSON<any>("/health", undefined, { timeoutMs: 5000 });
this.connected = res.ok;
return res.ok;
}
// ========== Sessions ==========
- /** POST /api/v1/sessions — create or reuse session */
- async createSession(sessionId: string): Promise<boolean> {
- const res = await this.fetchJSON<any>("/api/v1/sessions", {
- method: "POST",
- body: JSON.stringify({ session_id: sessionId }),
- });
- return res.ok;
- }
-
/** GET /api/v1/sessions/{id} — session metadata */
async getSession(sessionId: string, autoCreate = false): Promise<OVSessionMeta | null> {
const q = autoCreate ? "?auto_create=true" : "";
const res = await this.fetchJSON<OVSessionMeta>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}${q}`,
- undefined, 5000,
+ undefined, { timeoutMs: 5000 },
);
return res.ok ? res.result : null;
}
@@ -178,7 +128,7 @@ export class OVClient {
async getSessionContext(sessionId: string, tokenBudget = 128000): Promise<OVSessionContext | null> {
const res = await this.fetchJSON<OVSessionContext>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
return res.ok ? res.result : null;
}
@@ -188,26 +138,7 @@ export class OVClient {
const res = await this.fetchJSON<any>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
{ method: "POST", body: JSON.stringify({ role, content }) },
- 10000,
- );
- return res.ok;
- }
-
- /** POST /api/v1/sessions/{id}/messages — add a message with parts */
- async addMessageParts(sessionId: string, role: string, parts: any[]): Promise<boolean> {
- const res = await this.fetchJSON<any>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
- { method: "POST", body: JSON.stringify({ role, parts }) },
- 10000,
- );
- return res.ok;
- }
-
- async addMessagePayload(sessionId: string, payload: any): Promise<boolean> {
- const res = await this.fetchJSON<any>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
- { method: "POST", body: JSON.stringify(payload) },
- 10000,
+ { timeoutMs: 10000 },
);
return res.ok;
}
@@ -220,7 +151,7 @@ export class OVClient {
const res = await this.fetchJSON<OVCommitResult>(
`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,
{ method: "POST", body: JSON.stringify({ keep_recent_count: keepRecentCount }) },
- 30000,
+ { timeoutMs: 30000 },
);
if (res.ok && res.result && !res.result.trace_id && res.traceId) {
res.result.trace_id = res.traceId;
@@ -240,16 +171,6 @@ export class OVClient {
return (await this.commitSessionResponse(sessionId, keepRecentCount)).result;
}
- /** DELETE /api/v1/sessions/{id} */
- async deleteSession(sessionId: string): Promise<boolean> {
- const res = await this.fetchJSON<any>(
- `/api/v1/sessions/${encodeURIComponent(sessionId)}`,
- { method: "DELETE" },
- 10000,
- );
- return res.ok;
- }
-
// ========== Search ==========
/** POST /api/v1/search/find — basic vector search */
@@ -264,7 +185,7 @@ export class OVClient {
const res = await this.fetchJSON<any>("/api/v1/search/find", {
method: "POST", body: JSON.stringify(body),
- }, 10000);
+ }, { timeoutMs: 10000 });
if (!res.ok || !res.result) return [];
// OV returns { memories: [...], resources: [...], skills: [...], total }
@@ -295,7 +216,7 @@ export class OVClient {
async abstract(uri: string): Promise<string | null> {
const res = await this.fetchJSON<string>(
`/api/v1/content/abstract?uri=${encodeURIComponent(uri)}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
return res.ok ? res.result : null;
}
@@ -304,7 +225,7 @@ export class OVClient {
async overview(uri: string): Promise<string | null> {
const res = await this.fetchJSON<string>(
`/api/v1/content/overview?uri=${encodeURIComponent(uri)}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
return res.ok ? res.result : null;
}
@@ -313,7 +234,7 @@ export class OVClient {
async readContent(uri: string): Promise<string | null> {
const res = await this.fetchJSON<string>(
`/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
return res.ok ? res.result : null;
}
@@ -324,7 +245,7 @@ export class OVClient {
async ls(uri: string): Promise<OVDirEntry[]> {
const res = await this.fetchJSON<any[]>(
`/api/v1/fs/ls?uri=${encodeURIComponent(uri)}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
if (!res.ok || !Array.isArray(res.result)) return [];
return res.result.map(e => ({
@@ -342,7 +263,7 @@ export class OVClient {
async stat(uri: string): Promise<OVStatInfo | null> {
const res = await this.fetchJSON<OVStatInfo>(
`/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,
- undefined, 10000,
+ undefined, { timeoutMs: 10000 },
);
return res.ok ? res.result : null;
}
@@ -352,7 +273,7 @@ export class OVClient {
const res = await this.fetchJSON<any>(
`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=${recursive}`,
{ method: "DELETE" },
- 10000,
+ { timeoutMs: 10000 },
);
return res.ok;
}
@@ -368,60 +289,10 @@ export class OVClient {
const res = await this.fetchJSON<{ root_uri: string }>(
"/api/v1/resources",
{ method: "POST", body: JSON.stringify(body) },
- 30000,
+ { timeoutMs: 30000 },
);
return res.ok ? res.result : null;
}
-
- // ========== URI Space Resolution ==========
-
- async resolveScopeSpace(scope: "user" | "agent"): Promise<string> {
- const cached = this.resolvedSpaces.get(scope);
- if (cached) return cached;
-
- // Probe system status for user identity fallback
- let fallbackSpace = "default";
- const statusRes = await this.fetchJSON<any>("/api/v1/system/status", undefined, 5000);
- if (statusRes.ok && typeof statusRes.result?.user === "string" && statusRes.result.user.trim()) {
- fallbackSpace = statusRes.result.user.trim();
- }
-
- // List scope root for actual namespaces
- const reserved = scope === "user" ? OVClient.RESERVED_USER : OVClient.RESERVED_AGENT;
- const entries = await this.ls(`viking://${scope}/`);
- const spaces = entries
- .filter(e => e.isDir && !e.name.startsWith(".") && !reserved.has(e.name))
- .map(e => e.name);
-
- if (spaces.length > 0) {
- // Prefer the fallback space if it exists, then "default", then first available
- let chosen = spaces[0];
- if (spaces.includes(fallbackSpace)) chosen = fallbackSpace;
- else if (spaces.includes("default")) chosen = "default";
- this.resolvedSpaces.set(scope, chosen);
- return chosen;
- }
-
- this.resolvedSpaces.set(scope, fallbackSpace);
- return fallbackSpace;
- }
-
- async resolveTargetUri(targetUri: string): Promise<string> {
- const trimmed = targetUri.trim().replace(/\/+$/, "");
- const m = trimmed.match(/^viking:\/\/(user|agent)(?:\/(.*))?$/);
- if (!m) return trimmed;
- const scope = m[1] as "user" | "agent";
- const rawRest = (m[2] ?? "").trim();
- if (!rawRest) return trimmed;
- const parts = rawRest.split("/").filter(Boolean);
- if (parts.length === 0) return trimmed;
-
- const reserved = scope === "user" ? OVClient.RESERVED_USER : OVClient.RESERVED_AGENT;
- if (!reserved.has(parts[0])) return trimmed; // already has space
-
- const space = await this.resolveScopeSpace(scope);
- return `viking://${scope}/${space}/${parts.join("/")}`;
- }
}
function uriBasename(uri: string): string {
diff --git a/examples/pi-coding-agent-extension/config.json b/examples/pi-coding-agent-extension/config.json
deleted file mode 100644
index b557602db..000000000
--- a/examples/pi-coding-agent-extension/config.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "enabled": true,
- "syncTurns": true,
- "recallTokenBudget": 2000,
- "recallMaxContentChars": 500,
- "recallPreferAbstract": true,
- "scoreThreshold": 0.35,
- "minQueryLength": 3,
- "profileTokenBudget": 10000,
- "resumeContextBudget": 32000,
- "commitTokenThreshold": 20000,
- "commitKeepRecentCount": 10,
- "takeover": {
- "enabled": true,
- "tokenThreshold": 30000,
- "keepRecentTurns": 3,
- "overviewBudget": 3000,
- "overviewPollMs": 2000,
- "overviewPollMax": 15
- },
- "captureToolResults": false,
- "captureMode": "semantic",
- "captureMaxLength": 24000,
- "captureToolMaxChars": 1000000,
- "captureAssistantTurns": true,
- "bypassPatterns": [],
- "logLevel": "error"
-}
diff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.ts
index 5d5fa432e..aaf811b3b 100644
--- a/examples/pi-coding-agent-extension/config.ts
+++ b/examples/pi-coding-agent-extension/config.ts
@@ -1,11 +1,8 @@
-import { readFileSync, existsSync } from "node:fs";
-import { join, dirname } from "node:path";
-import { fileURLToPath } from "node:url";
-import { buildUserAgent, resolveOpenVikingCredentials } from "./shared/credentials.mjs";
-import { resolveEffectivePeerId } from "./shared/workspace-peer.mjs";
+import { readManifestVersion } from "./shared/credentials.mjs";
+import { buildPluginConfig } from "./shared/plugin-config.mjs";
-/** Hand-maintained: this extension ships no manifest to read a version from. */
-export const EXTENSION_VERSION = "0.1.0";
+/** The version the User-Agent reports, read from the manifest the gate checks. */
+export const EXTENSION_VERSION = readManifestVersion(new URL("./package.json", import.meta.url));
export interface OVConfig {
enabled: boolean;
@@ -13,14 +10,19 @@ export interface OVConfig {
apiKey: string;
account: string;
user: string;
+ /** `trusted` or `api_key`; only the former puts the identity on the wire. */
+ authMode: string;
+ sendIdentityHeaders: boolean;
peerId: string;
+ /** The pre-git workspace id, when it differs — recall still reaches it. */
+ legacyPeerId: string;
userAgent: string;
harness: string;
workspacePeer: boolean;
recallPeerScope: "actor" | "all";
recallQueryExpansion: "auto" | "off";
recallQueryExpansionConfigured: boolean;
- syncTurns: boolean;
+ autoCapture: boolean;
recallTokenBudget: number;
recallMaxContentChars: number;
recallPreferAbstract: boolean;
@@ -44,165 +46,39 @@ export interface OVConfig {
captureMaxLength: number;
captureToolMaxChars: number;
captureAssistantTurns: boolean;
+ /** Kept as this extension's original spelling; projected onto the shared one. */
bypassPatterns: string[];
+ bypassSession: boolean;
+ bypassSessionPatterns: string[];
logLevel: "silent" | "error" | "info";
debugLogPath: string;
}
-const DEFAULT_CONFIG: OVConfig = {
- enabled: true,
- endpoint: "http://127.0.0.1:1933",
- apiKey: "",
- account: "",
- user: "",
- peerId: "",
- userAgent: "",
- harness: "pi",
- workspacePeer: true,
- recallPeerScope: "all",
- // Server-side query expansion costs a model call before retrieval starts, so
- // it has to be switchable from the client that pays the latency.
- recallQueryExpansion: "auto",
- recallQueryExpansionConfigured: false,
- syncTurns: true,
- recallTokenBudget: 2000,
- recallMaxContentChars: 500,
- recallPreferAbstract: true,
- recallLimit: 10,
- recallLimitConfigured: false,
- // Persist injected recall blocks and re-apply them to historical user
- // messages so provider prompt-prefix caches keep hitting (#4137).
- recallLedger: true,
- scoreThreshold: 0.35,
- minQueryLength: 3,
- profileTokenBudget: 10000,
- resumeContextBudget: 32000,
- commitTokenThreshold: 20000,
- commitKeepRecentCount: 10,
- takeoverEnabled: true,
- takeoverTokenThreshold: 30000,
- takeoverKeepRecentTurns: 3,
- takeoverOverviewBudget: 3000,
- takeoverOverviewPollMs: 2000,
- takeoverOverviewPollMax: 15,
- captureToolResults: false,
- captureMode: "semantic",
- captureMaxLength: 24000,
- captureToolMaxChars: 1000000,
- captureAssistantTurns: true,
- bypassPatterns: [],
- logLevel: "error",
- debugLogPath: "",
-};
+/**
+ * Load the extension's configuration.
+ *
+ * The extension used to keep a `config.json` beside itself. It shipped with the
+ * extension holding exactly the code defaults, so nothing could tell an
+ * operator's choice from the factory setting. Every knob is declared in
+ * `shared/config-schema.mjs` now and resolved from the same layers as every
+ * other harness: env → the workspace file → `ovcli.conf`'s `plugin.pi` →
+ * `ovcli.conf`'s `plugin` → defaults.
+ */
+export function loadConfig(cwd: string = process.cwd()): OVConfig {
+ const config = buildPluginConfig("pi", { cwd, version: EXTENSION_VERSION, deriveEffectivePeer: true });
-export function loadConfigFromModuleUrl(moduleUrl: string): OVConfig {
- return loadConfig(dirname(fileURLToPath(moduleUrl)));
-}
-
-export function loadConfig(extensionDir: string): OVConfig {
- const configPath = join(extensionDir, "config.json");
- let file: any = {};
- try {
- if (existsSync(configPath)) file = JSON.parse(readFileSync(configPath, "utf8"));
- } catch {
- file = {};
- }
-
- const takeover = file.takeover && typeof file.takeover === "object" ? file.takeover : {};
- const creds = resolveOpenVikingCredentials();
- const config: OVConfig = {
- ...DEFAULT_CONFIG,
- ...file,
- endpoint: creds.baseUrl,
- apiKey: creds.apiKey,
- account: creds.account,
- user: creds.user,
- peerId: creds.peerId || (typeof file.peerId === "string" ? file.peerId : DEFAULT_CONFIG.peerId),
- userAgent: buildUserAgent("pi", EXTENSION_VERSION),
- harness: "pi",
- recallLimitConfigured: Object.prototype.hasOwnProperty.call(file, "recallLimit"),
- recallQueryExpansionConfigured: Object.prototype.hasOwnProperty.call(file, "recallQueryExpansion"),
- recallTokenBudget: file.recallTokenBudget ?? file.recallBudget ?? DEFAULT_CONFIG.recallTokenBudget,
- scoreThreshold: file.scoreThreshold ?? file.recallScoreThreshold ?? DEFAULT_CONFIG.scoreThreshold,
- minQueryLength: file.minQueryLength ?? file.recallMinQueryLength ?? DEFAULT_CONFIG.minQueryLength,
- profileTokenBudget: file.profileTokenBudget ?? file.profileBudget ?? DEFAULT_CONFIG.profileTokenBudget,
- takeoverEnabled: takeover.enabled ?? file.takeoverEnabled ?? DEFAULT_CONFIG.takeoverEnabled,
- takeoverTokenThreshold: takeover.tokenThreshold ?? file.takeoverTokenThreshold ?? DEFAULT_CONFIG.takeoverTokenThreshold,
- takeoverKeepRecentTurns: takeover.keepRecentTurns ?? file.takeoverKeepRecentTurns ?? DEFAULT_CONFIG.takeoverKeepRecentTurns,
- takeoverOverviewBudget: takeover.overviewBudget ?? file.takeoverOverviewBudget ?? DEFAULT_CONFIG.takeoverOverviewBudget,
- takeoverOverviewPollMs: takeover.overviewPollMs ?? file.takeoverOverviewPollMs ?? DEFAULT_CONFIG.takeoverOverviewPollMs,
- takeoverOverviewPollMax: takeover.overviewPollMax ?? file.takeoverOverviewPollMax ?? DEFAULT_CONFIG.takeoverOverviewPollMax,
- };
-
- if (process.env.OPENVIKING_URL || process.env.OPENVIKING_BASE_URL) config.endpoint = creds.baseUrl;
- if (process.env.OPENVIKING_API_KEY || process.env.OPENVIKING_BEARER_TOKEN) config.apiKey = creds.apiKey;
- if (process.env.OPENVIKING_ACCOUNT) config.account = creds.account;
- if (process.env.OPENVIKING_USER) config.user = creds.user;
- if (process.env.OPENVIKING_PEER_ID) config.peerId = creds.peerId;
- if (process.env.OPENVIKING_WORKSPACE_PEER !== undefined) {
- config.workspacePeer = envBool(process.env.OPENVIKING_WORKSPACE_PEER, config.workspacePeer);
- }
- if (process.env.OPENVIKING_RECALL_PEER_SCOPE) {
- config.recallPeerScope = process.env.OPENVIKING_RECALL_PEER_SCOPE === "actor" ? "actor" : "all";
- }
- if (process.env.OPENVIKING_RECALL_LIMIT) {
- config.recallLimit = Number(process.env.OPENVIKING_RECALL_LIMIT);
- config.recallLimitConfigured = true;
- }
- if (process.env.OPENVIKING_RECALL_QUERY_EXPANSION) {
- config.recallQueryExpansion = process.env.OPENVIKING_RECALL_QUERY_EXPANSION === "off" ? "off" : "auto";
- config.recallQueryExpansionConfigured = true;
- }
- if (process.env.OPENVIKING_RECALL_LEDGER !== undefined) {
- config.recallLedger = envBool(process.env.OPENVIKING_RECALL_LEDGER, config.recallLedger);
- }
- // OPENVIKING_DEBUG_LOG is the shared spelling; OV_DEBUG_LOG is pi's older
- // name, kept working so existing setups still log.
- const debugLogEnv = process.env.OPENVIKING_DEBUG_LOG || process.env.OV_DEBUG_LOG;
- if (debugLogEnv) config.debugLogPath = debugLogEnv;
-
- config.recallLimit = clampInt(config.recallLimit, 1, 50, DEFAULT_CONFIG.recallLimit);
- config.recallMaxContentChars = clampInt(config.recallMaxContentChars, 100, 5000, DEFAULT_CONFIG.recallMaxContentChars);
- config.recallTokenBudget = clampInt(config.recallTokenBudget, 200, 50000, DEFAULT_CONFIG.recallTokenBudget);
- config.scoreThreshold = clampNumber(config.scoreThreshold, 0, 1, DEFAULT_CONFIG.scoreThreshold);
- config.minQueryLength = clampInt(config.minQueryLength, 1, 64, DEFAULT_CONFIG.minQueryLength);
- config.profileTokenBudget = clampInt(config.profileTokenBudget, 500, 50000, DEFAULT_CONFIG.profileTokenBudget);
- config.resumeContextBudget = clampInt(config.resumeContextBudget, 1024, 128000, DEFAULT_CONFIG.resumeContextBudget);
- config.commitTokenThreshold = clampInt(config.commitTokenThreshold, 1000, 1000000, DEFAULT_CONFIG.commitTokenThreshold);
- config.commitKeepRecentCount = clampInt(config.commitKeepRecentCount, 0, 1000, DEFAULT_CONFIG.commitKeepRecentCount);
- config.takeoverEnabled = config.takeoverEnabled !== false;
- config.takeoverTokenThreshold = clampInt(config.takeoverTokenThreshold, 1, 1000000, DEFAULT_CONFIG.takeoverTokenThreshold);
- config.takeoverKeepRecentTurns = clampInt(config.takeoverKeepRecentTurns, 0, 100, DEFAULT_CONFIG.takeoverKeepRecentTurns);
- config.takeoverOverviewBudget = clampInt(config.takeoverOverviewBudget, 100, 50000, DEFAULT_CONFIG.takeoverOverviewBudget);
- config.takeoverOverviewPollMs = clampInt(config.takeoverOverviewPollMs, 0, 60000, DEFAULT_CONFIG.takeoverOverviewPollMs);
- config.takeoverOverviewPollMax = clampInt(config.takeoverOverviewPollMax, 1, 120, DEFAULT_CONFIG.takeoverOverviewPollMax);
- config.captureMaxLength = clampInt(config.captureMaxLength, 200, 100000, DEFAULT_CONFIG.captureMaxLength);
- config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 1000000, DEFAULT_CONFIG.captureToolMaxChars);
- config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";
- config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all";
- config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto";
- config.recallLedger = config.recallLedger !== false;
- if (!Array.isArray(config.bypassPatterns)) config.bypassPatterns = [];
- config.debugLogPath = typeof config.debugLogPath === "string" ? config.debugLogPath.trim() : "";
- config.peerId = resolveEffectivePeerId({ cfg: config as any, cwd: process.cwd() }).peerId;
- return config;
-}
-
-function envBool(value: string, fallback: boolean): boolean {
- const lower = String(value || "").trim().toLowerCase();
- if (lower === "0" || lower === "false" || lower === "no" || lower === "off") return false;
- if (lower === "1" || lower === "true" || lower === "yes" || lower === "on") return true;
- return fallback;
-}
-
-function clampInt(value: unknown, min: number, max: number, fallback: number): number {
- const next = Math.round(Number(value));
- if (!Number.isFinite(next)) return fallback;
- return Math.max(min, Math.min(max, next));
-}
-
-function clampNumber(value: unknown, min: number, max: number, fallback: number): number {
- const next = Number(value);
- if (!Number.isFinite(next)) return fallback;
- return Math.max(min, Math.min(max, next));
+ return {
+ ...config,
+ // `bypassSessionPatterns` is the name the shared matcher reads and every
+ // other harness spells; `bypassPatterns` was this extension's own and is
+ // still accepted. Both hold the same list so either can be inspected.
+ bypassPatterns: config.bypassSessionPatterns,
+ // OPENVIKING_DEBUG_LOG is the shared spelling and lands in the schema;
+ // OV_DEBUG_LOG is pi's older name, kept working so existing setups log.
+ debugLogPath: config.debugLogPath || String(process.env.OV_DEBUG_LOG || "").trim(),
+ // The whole resolution, not just the id: `legacyPeerId` is what lets recall
+ // under `actor` scope still reach memories written before the git-derived
+ // peer replaced the path-derived one.
+ peerId: config.effectivePeer.peerId,
+ } as OVConfig;
}
diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.ts
index 0c6222d50..c5d6c8fdb 100644
--- a/examples/pi-coding-agent-extension/index.ts
+++ b/examples/pi-coding-agent-extension/index.ts
@@ -10,20 +10,22 @@
* (most mature, production-hardened), Hermes (anti-pattern: stale prefetch).
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
+import { isCaptureEnabled } from "./shared/capture-utils.mjs";
import { createLogger } from "./shared/debug-log.mjs";
-import { loadConfigFromModuleUrl, type OVConfig } from "./config.js";
+import { loadConfig, type OVConfig } from "./config.js";
import { OVClient } from "./client.js";
import { RecallManager } from "./recall.js";
-import { RecallLedger } from "./shared/recall-ledger.mjs";
+import { RecallLedger } from "./lib/recall-ledger.mjs";
import { SyncManager } from "./sync.js";
import { buildProfileBlock } from "./shared/profile-inject.mjs";
+import { isBypassed } from "./shared/session-model.mjs";
import { guardVikingUriToolCall } from "./lib/uri-guard-adapter.mjs";
import { registerTools } from "./tools.js";
import { createTakeoverManager } from "./takeover.js";
export default async function (pi: ExtensionAPI) {
// --- Load config ---
- const config = loadConfigFromModuleUrl(import.meta.url);
+ const config = loadConfig();
if (!config.enabled) return;
// Env overrides
@@ -68,13 +70,10 @@ export default async function (pi: ExtensionAPI) {
startPromise = (async () => {
// Bypass check
- const cwd = process.cwd();
- for (const pattern of config.bypassPatterns) {
- if (matchBypass(cwd, pattern)) {
- bypassed = true;
- started = true;
- return;
- }
+ if (isBypassed(config, { cwd: process.cwd() })) {
+ bypassed = true;
+ started = true;
+ return;
}
// Health check
@@ -228,7 +227,7 @@ export default async function (pi: ExtensionAPI) {
// --- turn_end ---
pi.on("turn_end", async (event, ctx) => {
- if (!connected || bypassed || !config.syncTurns) return;
+ if (!connected || bypassed || !isCaptureEnabled(config)) return;
const branch = ctx.sessionManager.getBranch();
const result = await sync.syncBranch(branch);
@@ -326,24 +325,13 @@ export default async function (pi: ExtensionAPI) {
// Helper Functions
// ================================================================
-/** Simple bypass pattern matching (prefix and glob). */
-function matchBypass(cwd: string, pattern: string): boolean {
- if (pattern.startsWith("*")) {
- return cwd.endsWith(pattern.slice(1));
- }
- if (pattern.endsWith("*")) {
- return cwd.startsWith(pattern.slice(0, -1));
- }
- return cwd === pattern || cwd.startsWith(pattern + "/");
-}
-
/** Build the <openviking-context> profile block. */
async function buildSessionProfileBlock(
client: OVClient, config: OVConfig,
): Promise<string> {
try {
const profile = await buildProfileBlock(
- (path: string, init?: any, options?: any) => client.fetchJSON(path, init, 10000),
+ (path, init, options) => client.fetchJSON(path, init, options),
config.profileTokenBudget,
config.peerId,
);
diff --git a/examples/pi-coding-agent-extension/shared/recall-ledger.d.mts b/examples/pi-coding-agent-extension/lib/recall-ledger.d.mts
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/recall-ledger.d.mts
rename to examples/pi-coding-agent-extension/lib/recall-ledger.d.mts
diff --git a/examples/pi-coding-agent-extension/shared/recall-ledger.mjs b/examples/pi-coding-agent-extension/lib/recall-ledger.mjs
similarity index 100%
rename from examples/pi-coding-agent-extension/shared/recall-ledger.mjs
rename to examples/pi-coding-agent-extension/lib/recall-ledger.mjs
diff --git a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs
index e1bd58c36..bf08df2ed 100644
--- a/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs
+++ b/examples/pi-coding-agent-extension/lib/uri-guard-adapter.mjs
@@ -1,4 +1,4 @@
-import { buildGuardMessage, findVikingUri, normalizeToolName } from "../shared/uri-guard.mjs";
+import { evaluateUriGuard } from "../shared/uri-guard.mjs";
const VIKING_URI_TOOL_HINTS = {
read: {
@@ -24,19 +24,8 @@ const VIKING_URI_TOOL_HINTS = {
};
export function guardVikingUriToolCall(event) {
- const toolName = normalizeToolName(event?.toolName ?? event?.tool_name ?? event?.name);
- const hint = VIKING_URI_TOOL_HINTS[toolName];
- if (!hint) return null;
-
+ const toolName = event?.toolName ?? event?.tool_name ?? event?.name;
const input = event?.input ?? event?.args ?? event?.params ?? {};
- const uri = findVikingUri(input);
- if (!uri) return null;
-
- return {
- block: true,
- reason: buildGuardMessage(uri, {
- tool: hint.tool,
- example: hint.example(uri, input),
- }),
- };
+ const decision = evaluateUriGuard(toolName, input, { hints: VIKING_URI_TOOL_HINTS });
+ return decision ? { block: true, reason: decision.reason } : null;
}
diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json
new file mode 100644
index 000000000..9a5801222
--- /dev/null
+++ b/examples/pi-coding-agent-extension/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "openviking-pi-extension",
+ "version": "0.3.0",
+ "description": "OpenViking memory and context extension for the pi coding agent",
+ "private": true,
+ "type": "module"
+}
diff --git a/examples/pi-coding-agent-extension/recall.ts b/examples/pi-coding-agent-extension/recall.ts
index 70a701e04..7af3b0a6d 100644
--- a/examples/pi-coding-agent-extension/recall.ts
+++ b/examples/pi-coding-agent-extension/recall.ts
@@ -1,7 +1,7 @@
import type { OVClient } from "./client.js";
import type { OVConfig } from "./config.js";
-import { buildRecallBlock } from "./shared/recall-core.mjs";
-import { RecallLedger, ledgerKey } from "./shared/recall-ledger.mjs";
+import { buildRecallBlock, isRecallEnabled } from "./shared/recall-core.mjs";
+import { RecallLedger, ledgerKey } from "./lib/recall-ledger.mjs";
export interface RecallCache {
block: string | null;
@@ -44,6 +44,10 @@ export class RecallManager {
const userQuery = this.pendingPrompt;
this.pendingPrompt = "";
+ if (!isRecallEnabled(this.config)) {
+ this.cache = { block: null, promptText: userQuery };
+ return null;
+ }
if (userQuery.trim().length < this.config.minQueryLength) {
this.cache = { block: null, promptText: userQuery };
return null;
@@ -53,12 +57,14 @@ export class RecallManager {
// 10s is this extension's own budget for a bare retrieval; when the
// request also spends a server fuse the helper hands down a longer
// deadline, and ignoring it would abort a request still inside its fuse.
- (path: string, init?: any, options?: any) =>
- this.client.fetchJSON(path, init, options?.timeoutMs ?? 10000),
- this.config as any,
+ (path, init, options) => this.client.fetchJSON(path, init, options),
+ this.config,
userQuery,
{
actorPeerId: this.config.peerId,
+ // Under `actor` scope the effective peer is the only one asked, so a
+ // workspace whose id changed would lose everything written before it.
+ legacyPeerId: this.config.legacyPeerId,
// Passing the OV session id is what turns on server-side query
// expansion and the cross-turn dedup ledger.
sessionId: this.sessionId() ?? "",
diff --git a/examples/pi-coding-agent-extension/scripts/e2e-live.mjs b/examples/pi-coding-agent-extension/scripts/e2e-live.mjs
index dd5a31679..7f83a383f 100755
--- a/examples/pi-coding-agent-extension/scripts/e2e-live.mjs
+++ b/examples/pi-coding-agent-extension/scripts/e2e-live.mjs
@@ -107,31 +107,38 @@ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ defaultProjectTr
function copyExtension() {
for (const name of readdirSync(EXT_SRC)) {
- if (name === "config.json") continue;
const src = join(EXT_SRC, name);
const dst = join(extDir, basename(name));
- if (name.endsWith(".ts") || name === "README.md" || name === "DESIGN.md" || name === "TAKEOVER.md") {
+ if (name.endsWith(".ts") || name === "README.md" || name === "DESIGN.md") {
copyFileSync(src, dst);
} else if (["lib", "shared", "scripts"].includes(name)) {
cpSync(src, dst, { recursive: true });
}
}
- writeFileSync(join(extDir, "config.json"), JSON.stringify({
- enabled: true,
- syncTurns: true,
- logLevel: "info",
- takeover: {
- enabled: true,
- tokenThreshold: 600,
- keepRecentTurns: 1,
- overviewBudget: 3000,
- overviewPollMs: 3000,
- overviewPollMax: 30,
- },
- }, null, 2));
}
copyExtension();
+// The extension has no config file of its own; its knobs live in ovcli.conf's
+// plugin section like every other harness's.
+const OVCLI_CONF = join(agentDir, "ovcli.conf");
+writeFileSync(OVCLI_CONF, JSON.stringify({
+ url: OV_URL,
+ api_key: OV_KEY,
+ plugin: {
+ pi: {
+ enabled: true,
+ autoCapture: true,
+ logLevel: "info",
+ takeoverEnabled: true,
+ takeoverTokenThreshold: 600,
+ takeoverKeepRecentTurns: 1,
+ takeoverOverviewBudget: 3000,
+ takeoverOverviewPollMs: 3000,
+ takeoverOverviewPollMax: 30,
+ },
+ },
+}, null, 2));
+
const PAD1 = `PADDING-T1 ${"lorem ipsum dolor sit amet consectetur ".repeat(60)}`;
const PAD2 = `PADDING-T2 ${"vestibulum ante ipsum primis in faucibus ".repeat(60)}`;
@@ -153,6 +160,7 @@ function runTurn(turn, prompt, extraArgs = []) {
PI_CODING_AGENT_DIR: agentDir,
OPENVIKING_URL: OV_URL,
OPENVIKING_API_KEY: OV_KEY,
+ OPENVIKING_CLI_CONFIG_FILE: OVCLI_CONF,
SUPER_RELAY_API_KEY: RELAY_KEY,
OV_E2E_OUT: outDir,
OV_E2E_TURN: String(turn),
diff --git a/examples/pi-coding-agent-extension/shared/batch-send.mjs b/examples/pi-coding-agent-extension/shared/batch-send.mjs
deleted file mode 100644
index d7ec355cc..000000000
--- a/examples/pi-coding-agent-extension/shared/batch-send.mjs
+++ /dev/null
@@ -1,121 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { enqueue } from "./pending-queue.mjs";
-import { isRetryableFailure } from "./retryable.mjs";
-
-export const BATCH_LIMIT = 100;
-
-export function isRetryableSendFailure(res) {
- return isRetryableFailure(res);
-}
-
-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/pi-coding-agent-extension/shared/capture-utils.mjs b/examples/pi-coding-agent-extension/shared/capture-utils.mjs
deleted file mode 100644
index 22bc1b63c..000000000
--- a/examples/pi-coding-agent-extension/shared/capture-utils.mjs
+++ /dev/null
@@ -1,578 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { applyInputFilters, compileInputFilters } from "./input-filters.mjs";
-
-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",
-]);
-
-// Tool output is reported verbatim; the server owns truncation via
-// tool_output_externalization (threshold_chars, default 20000). This cap only
-// guards against pathological payloads.
-const DEFAULT_TOOL_MAX_CHARS = 1000000;
-
-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?.tool ||
- block?.function?.name ||
- block?.call?.name ||
- "",
- );
-}
-
-function toolPayload(block, kind) {
- if (!block || typeof block !== "object") return "";
- if (kind === "call") {
- return block.input ??
- block.state?.input ??
- block.arguments ??
- block.args ??
- block.params ??
- block.function?.arguments ??
- block.command ??
- block.call?.input ??
- block.call?.arguments ??
- "";
- }
- return block.output ??
- block.state?.output ??
- block.result ??
- block.error ??
- block.state?.error ??
- block.data ??
- block.content ??
- block.text ??
- "";
-}
-
-function toolId(block) {
- return oneLine(
- block?.call_id ||
- block?.callId ||
- 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?.isError || block?.state?.isError || block?.error || block?.state?.error) return "error";
- const status = oneLine(block?.status || block?.state?.status || "");
- return status || "completed";
-}
-
-function setToolInput(part, payload) {
- const input = parseMaybeJson(payload);
- if (input === "" || input == null) return;
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
-}
-
-function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, 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") {
- setToolInput(part, payload);
- } else {
- if (block?.state?.input !== undefined) {
- setToolInput(part, block.state.input);
- }
- 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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, 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: DEFAULT_TOOL_MAX_CHARS, 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;
-}
-
-/**
- * Prune blank text parts and run `cfg.captureFilters` over the ones that remain.
- *
- * One drop verdict is taken per turn, on the aggregate of its text parts; the
- * individual parts are then rewritten with the substitutions only, so a rule can
- * never both keep and drop the same turn. Tool call/result parts are carried
- * through untouched — filters match conversation text, not tool payloads — but a
- * turn dropped on its text takes its tool parts with it.
- */
-export function filterCaptureParts(parts, role, cfg = {}) {
- const kept = [];
- for (const part of parts || []) {
- if (!part) continue;
- if (part.type !== "text") {
- kept.push(part);
- continue;
- }
- const text = typeof part.text === "string" ? part.text.trim() : "";
- if (!text) continue;
- kept.push(text === part.text ? part : { ...part, text });
- }
-
- const blank = { parts: kept, dropped: false };
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (!compiled.rules.length || kept.length === 0) return blank;
-
- const textParts = kept.filter((part) => part.type === "text");
- if (textParts.length === 0) return blank;
-
- const verdict = applyInputFilters(textParts.map((part) => part.text).join("\n\n"), compiled.rules, {
- role,
- });
- if (verdict.dropped) return { parts: [], dropped: true };
-
- const out = [];
- for (const part of kept) {
- if (part.type !== "text") {
- out.push(part);
- continue;
- }
- const shaped = applyInputFilters(part.text, compiled.rules, { role, substituteOnly: true });
- if (!shaped.text) continue;
- out.push(shaped.text === part.text ? part : { ...part, text: shaped.text });
- }
- return { parts: out, dropped: out.length === 0 };
-}
-
-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 shaped = filterCaptureParts(parts, role, cfg);
- if (shaped.dropped) continue;
- // With parts on the wire the drop decision was already taken above, so the
- // text path only runs the filters for the `content` fallback. That also
- // keeps `turn.text` faithful for callers that scan it for trigger words.
- const decision = shouldCaptureText(rawText, role, cfg, { filters: shaped.parts.length === 0 });
- if (!decision.shouldCapture && shaped.parts.length === 0) continue;
- const text = decision.shouldCapture ? decision.text : "";
- turns.push({ role, text, parts: shaped.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 = {}, { filters = true } = {}) {
- const maxLength = cfg.captureMaxLength || 24000;
- const sanitized = sanitizeCapturedText(text);
- if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
-
- let capped = truncateCaptureText(sanitized, maxLength);
- if (filters) {
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (compiled.rules.length) {
- const verdict = applyInputFilters(capped, compiled.rules, { role });
- if (verdict.dropped) return { shouldCapture: false, reason: "filtered", text: "" };
- capped = verdict.text;
- if (!capped) return { shouldCapture: false, reason: "empty", text: "" };
- }
- }
- 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/pi-coding-agent-extension/shared/credentials.d.mts b/examples/pi-coding-agent-extension/shared/credentials.d.mts
deleted file mode 100644
index aa46700cf..000000000
--- a/examples/pi-coding-agent-extension/shared/credentials.d.mts
+++ /dev/null
@@ -1,14 +0,0 @@
-export function buildUserAgent(harness: string, version?: string): string;
-
-export function readManifestVersion(manifest: string | URL): string;
-
-export function resolveOpenVikingCredentials(env?: Record<string, string | undefined>): {
- credentialSource: string;
- baseUrl: string;
- mcpUrl: string;
- apiKey: string;
- account: string;
- user: string;
- peerId: string;
- hasApiKey: boolean;
-};
diff --git a/examples/pi-coding-agent-extension/shared/credentials.mjs b/examples/pi-coding-agent-extension/shared/credentials.mjs
deleted file mode 100644
index ba26a84dc..000000000
--- a/examples/pi-coding-agent-extension/shared/credentials.mjs
+++ /dev/null
@@ -1,239 +0,0 @@
-// 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`;
-
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
- let credentialPath = "";
- if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
- }
-
- return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- credentialPath,
- 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/pi-coding-agent-extension/shared/debug-log.mjs b/examples/pi-coding-agent-extension/shared/debug-log.mjs
deleted file mode 100644
index 73855cf6d..000000000
--- a/examples/pi-coding-agent-extension/shared/debug-log.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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/pi-coding-agent-extension/shared/input-filters.mjs b/examples/pi-coding-agent-extension/shared/input-filters.mjs
deleted file mode 100644
index e20bb03a7..000000000
--- a/examples/pi-coding-agent-extension/shared/input-filters.mjs
+++ /dev/null
@@ -1,219 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Ordered, operator-configured regex filters for memory plugin input.
- *
- * Rules are sed-style strings, applied in order to a single piece of text:
- * s/^\s*ultrathink\s+//i substitute (add `g` to replace every match)
- * d|^\s*[/!]| drop the text when the pattern matches
- * k/^\?ov\b/ keep the text only when the pattern matches
- * user:d/^\s*\/clear\b/ apply to one role only
- *
- * A malformed rule becomes an entry in `errors` and is skipped rather than
- * throwing, so a typo in a config file cannot take a hook down.
- */
-
-const OPS = new Set(["s", "d", "k"]);
-const SCOPES = ["user", "assistant"];
-const ALLOWED_FLAGS = "imsug";
-
-export const INPUT_FILTER_KNOBS = [
- {
- key: "recallQueryFilters",
- env: "OPENVIKING_RECALL_QUERY_FILTERS",
- label: "recall query filters",
- },
- {
- key: "captureFilters",
- env: "OPENVIKING_CAPTURE_FILTERS",
- label: "capture filters",
- },
-];
-
-/**
- * Read one delimited field. `\` always consumes the next character, and only
- * `\<delim>` is un-escaped, so `\d` / `\b` / `\x2c` reach RegExp verbatim.
- * Returns the index of the closing delimiter, or -1 when it is missing.
- */
-function scanField(source, start, delim) {
- let out = "";
- let i = start;
- while (i < source.length) {
- const c = source[i];
- if (c === "\\") {
- const next = source[i + 1];
- if (next === undefined) {
- out += "\\";
- i += 1;
- continue;
- }
- out += next === delim ? next : "\\" + next;
- i += 2;
- continue;
- }
- if (c === delim) return { value: out, end: i };
- out += c;
- i += 1;
- }
- return { value: out, end: -1 };
-}
-
-export function parseInputFilterRule(source) {
- if (typeof source !== "string") {
- return { source: String(source ?? ""), error: "rule must be a string" };
- }
- const raw = source.trim();
- if (!raw) return { source: raw, error: "rule is empty" };
-
- let scope = "";
- let rest = raw;
- for (const candidate of SCOPES) {
- if (rest.startsWith(`${candidate}:`)) {
- scope = candidate;
- rest = rest.slice(candidate.length + 1);
- break;
- }
- }
-
- const op = rest[0] || "";
- if (!OPS.has(op)) {
- return {
- source: raw,
- error: `unknown operation "${op}" — expected s (substitute), d (drop) or k (keep)`,
- };
- }
- const delim = rest[1];
- if (delim === undefined) {
- return { source: raw, error: `missing delimiter after "${op}"` };
- }
- if (/[A-Za-z0-9\s\\]/.test(delim)) {
- return {
- source: raw,
- error: `invalid delimiter ${JSON.stringify(delim)} — use punctuation such as / | # or :`,
- };
- }
-
- const first = scanField(rest, 2, delim);
- const pattern = first.value;
- let replacement = null;
- let flagsRaw = "";
- if (op === "s") {
- if (first.end < 0) {
- return { source: raw, error: `missing ${JSON.stringify(delim)} after the pattern` };
- }
- const second = scanField(rest, first.end + 1, delim);
- if (second.end < 0) {
- return {
- source: raw,
- error: `missing ${JSON.stringify(delim)} after the replacement — write s${delim}pattern${delim}replacement${delim}`,
- };
- }
- replacement = second.value;
- flagsRaw = rest.slice(second.end + 1);
- } else {
- flagsRaw = first.end < 0 ? "" : rest.slice(first.end + 1);
- }
-
- if (!pattern) return { source: raw, error: "pattern is empty" };
-
- const flags = new Set();
- for (const flag of flagsRaw) {
- if (!ALLOWED_FLAGS.includes(flag)) {
- return { source: raw, error: `unknown flag "${flag}" — allowed flags are i, m, s, u, g` };
- }
- if (flags.has(flag)) return { source: raw, error: `duplicate flag "${flag}"` };
- flags.add(flag);
- }
- // d/k decide with .test(), which advances lastIndex on a global regex and
- // would then alternate between calls. `g` means nothing there, so drop it.
- if (op !== "s") flags.delete("g");
-
- let re;
- try {
- re = new RegExp(pattern, [...flags].join(""));
- } catch (err) {
- // V8 already says "Invalid regular expression: <pattern>: <why>"; keep that
- // detail without stuttering the prefix the doctors key off.
- const message = err?.message || String(err);
- return {
- source: raw,
- error: /^invalid regular expression/i.test(message)
- ? `invalid${message.slice("Invalid".length)}`
- : `invalid regular expression: ${message}`,
- };
- }
-
- return { op, scope, re, replacement, source: raw };
-}
-
-export function compileInputFilters(rules) {
- const compiled = [];
- const errors = [];
- const list = Array.isArray(rules) ? rules : [];
- list.forEach((entry, index) => {
- if (typeof entry !== "string") {
- errors.push({ index, source: String(entry ?? ""), message: "rule must be a string" });
- return;
- }
- if (!entry.trim()) return;
- const parsed = parseInputFilterRule(entry);
- if (parsed.error) errors.push({ index, source: parsed.source, message: parsed.error });
- else compiled.push({ ...parsed, index });
- });
- return { rules: compiled, errors };
-}
-
-/**
- * Run compiled rules over `text`.
- *
- * `substituteOnly` skips the d/k operations, so a caller that already took one
- * drop decision for a turn can rewrite its individual pieces without taking a
- * second, possibly contradictory one.
- */
-export function applyInputFilters(text, compiled, { role = "", substituteOnly = false } = {}) {
- const original = typeof text === "string" ? text : String(text ?? "");
- let current = original;
- for (const rule of Array.isArray(compiled) ? compiled : []) {
- if (rule.scope && rule.scope !== role) continue;
- if (rule.op === "s") {
- current = current.replace(rule.re, rule.replacement);
- continue;
- }
- if (substituteOnly) continue;
- const matched = rule.re.test(current);
- if ((rule.op === "d" && matched) || (rule.op === "k" && !matched)) {
- return { text: "", changed: false, dropped: true, ruleIndex: rule.index, op: rule.op };
- }
- }
- const finalText = current.trim();
- return {
- text: finalText,
- changed: finalText !== original,
- dropped: false,
- ruleIndex: -1,
- op: "",
- };
-}
-
-/** Doctor-facing summary of both filter knobs on a resolved plugin config. */
-export function describeInputFilters(cfg = {}) {
- return INPUT_FILTER_KNOBS.map(({ key, env, label }) => {
- const configured = Array.isArray(cfg?.[key]) ? cfg[key] : [];
- const compiled = compileInputFilters(configured);
- const ops = { s: 0, d: 0, k: 0 };
- for (const rule of compiled.rules) ops[rule.op] += 1;
- const bits = [];
- if (ops.s) bits.push(`${ops.s} substitute`);
- if (ops.d) bits.push(`${ops.d} drop`);
- if (ops.k) bits.push(`${ops.k} keep-only`);
- const active = compiled.rules.length;
- return {
- key,
- env,
- label,
- total: configured.length,
- active,
- summary: `${active} rule${active === 1 ? "" : "s"}${bits.length ? ` (${bits.join(", ")})` : ""}`,
- errors: compiled.errors,
- };
- });
-}
diff --git a/examples/pi-coding-agent-extension/shared/pending-queue.mjs b/examples/pi-coding-agent-extension/shared/pending-queue.mjs
deleted file mode 100644
index 38dccb1c8..000000000
--- a/examples/pi-coding-agent-extension/shared/pending-queue.mjs
+++ /dev/null
@@ -1,487 +0,0 @@
-// 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. The queue is replayed in small
- * batches, either at session-start (consuming retry budgets, with
- * maxRetries/TTL) or by a long-running drainer that passes
- * `consumeRetries: false` so transient failures stay retryable.
- *
- * 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";
-import { isRetryableFailure } from "./retryable.mjs";
-
-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) {
- return isRetryableFailure(res);
-}
-
-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;
- }
-}
-
-/**
- * Release a claimed file back to the queue without consuming a retry. The
- * entry keeps its original filename, retry count, and createdAt position, so a
- * later run retries it as if this attempt never happened.
- */
-export async function releaseClaim(claimedFilename) {
- if (!claimedFilename.endsWith(".processing")) return null;
- const dir = getPendingDir();
- const restored = pendingFromProcessingFilename(claimedFilename);
- try {
- await rename(join(dir, claimedFilename), join(dir, restored));
- return restored;
- } 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
- * @param {object} [options]
- * @param {boolean} [options.consumeRetries=true] - when false, retryable
- * failures release their claim instead of incrementing the retry count, so
- * a background drainer can keep retrying a transient failure without
- * burning the session-start retry budget. Exhausted and non-retryable
- * entries are deleted exactly as in the default mode.
- * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
- */
-export async function replayPending(fetchJSON, log, options = {}) {
- const consumeRetries = options.consumeRetries !== false;
- 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 (entry.type === "commitSession") {
- log("pending-queue", {
- action: "commit-replay",
- sessionId: entry.sessionId,
- ok: Boolean(res?.ok),
- status: res?.result?.status || res?.status,
- trace_id: res?.traceId || res?.result?.trace_id,
- error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
- });
- }
-
- if (res?.ok) {
- await dequeue(claimedFilename);
- replayed++;
- } else if (!isRetryableReplayFailure(res)) {
- await dequeue(claimedFilename);
- skipped++;
- } else {
- if (consumeRetries) {
- await incrementRetry(claimedFilename, entry);
- } else {
- const released = await releaseClaim(claimedFilename);
- log("pending-queue", {
- action: released ? "replay-deferred" : "release-failed",
- sessionId: entry.sessionId,
- type: entry.type,
- status: res?.result?.status || res?.status,
- retries: entry.retries || 0,
- });
- }
- 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/pi-coding-agent-extension/shared/profile-inject.mjs b/examples/pi-coding-agent-extension/shared/profile-inject.mjs
deleted file mode 100644
index 3f601844a..000000000
--- a/examples/pi-coding-agent-extension/shared/profile-inject.mjs
+++ /dev/null
@@ -1,294 +0,0 @@
-// 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/pi-coding-agent-extension/shared/recall-compress-core.mjs b/examples/pi-coding-agent-extension/shared/recall-compress-core.mjs
deleted file mode 100644
index 1ced4cf4d..000000000
--- a/examples/pi-coding-agent-extension/shared/recall-compress-core.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
-
-export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
-export const DIGEST_HEADER = "OpenViking memory digest:";
-const COMPRESS_OK = "ok";
-const COMPRESS_EMPTY = "empty";
-const COMPRESS_FAILED = "failed";
-
-// Medium-constraint prompt: state the goal and two structural floors, but no hard
-// bullet-length contract. Hard per-bullet limits pin the digest to headline
-// density; leaving it unconstrained lets small models rewrite long URIs into dead
-// links, which the URI repair below cleans up.
-export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
- return `You are a memory relevance compressor utility.
-Do not use any tools. Do not investigate. Only transform the given text.
-
-User query:
-${query}
-
-Retrieved OpenViking context fragments:
-${rendered}
-
-Write a memory digest for a coding agent about to answer that query. Keep the
-concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
-and conversational filler.
-
-Format rules:
-- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
-- Start every bullet with "- ".
-- End every bullet with its source, copied verbatim from the fragments above:
- "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
-- Output the digest body only. No preamble, no closing remark.
-
-If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
-}
-
-function editDistance(a, b) {
- if (a === b) return 0;
- const rows = a.length + 1;
- const cols = b.length + 1;
- let prev = Array.from({ length: cols }, (_, i) => i);
- for (let i = 1; i < rows; i += 1) {
- const cur = [i];
- for (let j = 1; j < cols; j += 1) {
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
- cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
- }
- prev = cur;
- }
- return prev[cols - 1];
-}
-
-function nearestUri(candidate, validUris) {
- let best = "";
- let bestDistance = Infinity;
- for (const uri of validUris) {
- const distance = editDistance(candidate, uri);
- if (distance < bestDistance) {
- best = uri;
- bestDistance = distance;
- }
- }
- // Only repair near-misses; an unrelated hallucination is dropped instead.
- const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
- return bestDistance <= tolerance ? best : "";
-}
-
-/**
- * Small models occasionally mangle long URIs. Snap every cited URI back onto the
- * set the server actually returned, and drop bullets whose citation cannot be
- * recovered so the digest never carries a dead link.
- */
-export function repairDigestUris(digest, validUris = []) {
- const text = String(digest || "");
- if (!text) return "";
- const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
- if (!valid.length) return text;
- const validSet = new Set(valid);
-
- const lines = [];
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim().startsWith("- ")) {
- lines.push(line);
- continue;
- }
- let tokenized = line;
- for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
- if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
- }
- let dropped = false;
- const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
- let decoded = uri;
- try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
- if (validSet.has(decoded)) return decoded;
- const nearest = nearestUri(decoded, valid);
- if (nearest) return nearest;
- dropped = true;
- return uri;
- });
- if (!dropped) lines.push(repaired);
- }
- return lines.join("\n").trim();
-}
-
-export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
- const text = String(raw || "").trim();
- if (!text) return null;
- if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
- const bullets = text.split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
- .slice(0, Math.max(1, maxBullets))
- .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
- if (!bullets.length) return null;
- return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
-}
-
-export function recallDigestCacheKey({
- query = "",
- rendered = "",
- entries = [],
- maxInputChars = 18000,
- maxBullets = 6,
-} = {}) {
- const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
- const source = JSON.stringify({
- version: 2,
- query: String(query),
- rendered: String(rendered).slice(0, maxInputChars),
- uris,
- maxInputChars,
- maxBullets,
- });
- return createHash("sha256").update(source).digest("hex");
-}
-
-async function readCache(path) {
- if (!path) return null;
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeCache(path, value) {
- if (!path) return;
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-export async function compressRecallContext({
- query,
- rendered,
- shortContext = rendered,
- entries = [],
- cfg = {},
- runCompressor,
- cachePath = "",
- now = 0,
-}) {
- const input = String(rendered || "").trim();
- if (!input) return { status: COMPRESS_EMPTY, context: "" };
- const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
- if (input.length < minChars) {
- return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
- }
-
- const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
- const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
- const key = recallDigestCacheKey({
- query,
- rendered: input,
- entries,
- maxInputChars,
- maxBullets,
- });
- const cached = await readCache(cachePath);
- if (cached?.key === key && typeof cached.digest === "string") {
- const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
- if (digest) return { status: COMPRESS_OK, context: digest };
- }
-
- const prompt = buildRecallCompressionPrompt({
- query,
- rendered: input.slice(0, maxInputChars),
- maxBullets,
- });
- const raw = await runCompressor(prompt);
- const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
- if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
- if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
-
- const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
- const repaired = repairDigestUris(normalized, validUris.length
- ? validUris
- : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
- const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
- if (!digest) return { status: COMPRESS_FAILED, context: "" };
-
- await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
- return { status: COMPRESS_OK, context: digest };
-}
diff --git a/examples/pi-coding-agent-extension/shared/recall-core.d.mts b/examples/pi-coding-agent-extension/shared/recall-core.d.mts
deleted file mode 100644
index e470aa237..000000000
--- a/examples/pi-coding-agent-extension/shared/recall-core.d.mts
+++ /dev/null
@@ -1,13 +0,0 @@
-export function buildRecallBlock(
- fetchJSON: (path: string, init?: any, options?: any) => Promise<{ ok: boolean; status?: number; result?: any; error?: any }>,
- cfg: Record<string, any>,
- query: string,
- options?: {
- actorPeerId?: string;
- sessionId?: string;
- log?: (stage: string, data?: any) => void;
- },
-): Promise<string | null>;
-
-export function buildRecallEndpointBody(cfg?: Record<string, any>): Record<string, any>;
-export function estimateTokens(text: string): number;
diff --git a/examples/pi-coding-agent-extension/shared/recall-core.mjs b/examples/pi-coding-agent-extension/shared/recall-core.mjs
deleted file mode 100644
index 72835de8f..000000000
--- a/examples/pi-coding-agent-extension/shared/recall-core.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-
-import { compressRecallContext } from "./recall-compress-core.mjs";
-
-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://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-const DEFAULT_CONTEXT_LIMIT = 10;
-const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
-const DEFAULT_REWRITE_MAX_BULLETS = 6;
-const CODING_QUOTA_WEIGHTS = {
- events: 1,
- entities: 2,
- preferences: 1,
- experiences: 1,
- resources: 3,
- skills: 2,
-};
-
-let userSpaceCache = "";
-
-export function estimateTokens(text) {
- return text ? Math.ceil(String(text).length / 4) : 0;
-}
-
-function scaleQuotas(limit, weights) {
- const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
- const order = Object.keys(weights);
- const quotas = Object.fromEntries(order.map((key) => [key, 0]));
- if (slots < order.length) {
- for (const key of order) quotas[key] = 1;
- return quotas;
- }
-
- for (const key of order) quotas[key] = 1;
- const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
- const ideals = Object.fromEntries(
- order.map((key) => [key, slots * weights[key] / totalWeight]),
- );
- while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
- const key = order.reduce((best, candidate) => (
- ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
- ? candidate
- : best
- ));
- quotas[key] += 1;
- }
- return quotas;
-}
-
-function legacyMemoryQuotas(limit) {
- return {
- ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
- experiences: 0,
- };
-}
-
-function codingQuotas(limit) {
- return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
-}
-
-export function buildRecallEndpointBody(cfg = {}) {
- const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
- const body = {
- query: "",
- quotas: legacyMemoryQuotas(limit),
- 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;
-}
-
-/**
- * Body for the server-side context face. The plugin declares intent (coding
- * purpose, budget, session) and leaves the mechanics — quota ratios, tier
- * degradation, cross-turn dedup — to the server's defaults.
- */
-export function buildContextSearchBody(cfg = {}, options = {}) {
- const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
- const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
- const maxTokens = Math.max(
- 64,
- Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
- );
- const body = {
- query: "",
- mode: "context",
- purpose: "coding",
- score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
- };
- const limitConfigured = cfg.recallLimitConfigured === true;
- const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
- if (limitConfigured) body.quotas = codingQuotas(limit);
- if (maxTokensConfigured) body.max_tokens = maxTokens;
- if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
-
- const sessionId = String(options.sessionId || "").trim();
- if (sessionId) {
- body.session_id = sessionId;
- const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
- if (queryExpansionConfigured) {
- body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
- }
- const dedupTurns = Number(cfg.recallDedupTurns);
- const resolvedDedupTurns = Number.isFinite(dedupTurns)
- ? Math.max(0, Math.floor(dedupTurns))
- : 5;
- if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
- }
-
- const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
- if (excludeUris.length) body.exclude_uris = excludeUris;
-
- if (rewriteMode === "server") body.rewrite = true;
- else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
- const rewriteMaxBullets = Math.max(
- 1,
- Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
- );
- const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
- if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
- body.rewrite_max_bullets = rewriteMaxBullets;
- }
- return body;
-}
-
-// The server pipeline is serial and each optional stage has its own fuse. A
-// request is aborted client-side unless its deadline covers every stage it
-// asked for, and aborting discards the whole response rather than just the
-// stage that ran long.
-//
-// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
-// always -> retrieval, body reads, budget planning
-// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
-//
-// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
-// a quarter to spare.
-const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
-const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
-
-/**
- * HTTP deadline for one context request, or undefined to keep the caller's own.
- *
- * Derived from the request body, because the body is what states which server
- * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
- * that also spends the expansion or rewrite fuse.
- */
-export function contextRequestTimeoutMs(cfg = {}, body = {}) {
- const wantsRewrite = body.rewrite !== undefined;
- // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
- // takes the expansion fuse back out of the budget.
- const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
- const configured = Number(cfg.recallContextTimeoutMs);
- if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
- if (!wantsRewrite && !wantsExpansion) return undefined;
- const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
- return Math.max(Number(cfg.timeoutMs) || 0, floor);
-}
-
-/**
- * Strip the context-face fields a pre-context server rejects, converting the
- * token budget back to v1's character budget.
- */
-export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
- const body = buildRecallEndpointBody(cfg);
- body.query = contextBody.query || "";
- body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
- if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
- 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(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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");
-}
-
-const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
-
-function stateFile(name) {
- const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
- return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
-}
-
-async function readJsonFile(path) {
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeJsonFile(path, value) {
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Hooks are one-shot processes, so "this server has no context face" has to be
- * remembered on disk or every turn pays for a rejected request.
- */
-export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- const cached = await readJsonFile(path);
- return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
-}
-
-export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
-}
-
-/**
- * A `peer_scope` the server rejects is remembered the same way, but unlike the
- * context face this one is not a silent capability probe: dropping the field
- * widens recall from the caller's own peer to the whole user root, so doctor
- * reads this file back and warns.
- */
-export function peerScopeMemoPath() {
- return stateFile("peer-scope.json");
-}
-
-export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
- const cached = await readJsonFile(path);
- if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
- return cached;
-}
-
-export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
- await writeJsonFile(path, {
- legacyUntil: now + LEGACY_CACHE_TTL_MS,
- scope: String(scope || ""),
- status: Number(status) || 0,
- at: now,
- });
-}
-
-function looksLikeUnknownField(res) {
- const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
- return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
-}
-
-function wrapContext(body) {
- return [
- "<openviking-context>",
- "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
- body,
- "</openviking-context>",
- ].join("\n");
-}
-
-/**
- * Server-assembled context: the context face when the deployment has it, else
- * the deprecated /recall preset. Returns the injection block, "" when there was
- * nothing relevant, or null when no server-side path was usable at all.
- */
-export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
-
- const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
- if (block !== null) return block;
- return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
-}
-
-/**
- * Raw server-assembled context, or null when the deployment has no context face.
- * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
- * (their own compression, their own envelope) use this instead of the block
- * builders below.
- */
-export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId || "";
- const log = options.log || (() => {});
- if (await isContextFaceLegacy(options.legacyCachePath)) return null;
-
- const body = buildContextSearchBody(cfg, options);
- body.query = query;
- const res = await fetchJSON("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
-
- if (!res.ok) {
- const status = res.status || 0;
- if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
- await markContextFaceLegacy(options.legacyCachePath);
- log("recall_context_face_unsupported", { status });
- } else {
- log("recall_context_face_error", { status });
- }
- return null;
- }
-
- const result = res.result || {};
- const stats = result.stats || {};
- log("recall_context_assembled", {
- entries: Array.isArray(result.entries) ? result.entries.length : 0,
- usedTokens: stats.used_tokens || 0,
- tiers: stats.tier_counts || {},
- rewrite: stats.rewrite || "off",
- });
- return {
- rendered: String(result.rendered || "").trim(),
- entries: Array.isArray(result.entries) ? result.entries : [],
- digest: String(result.digest || "").trim(),
- stats,
- };
-}
-
-/**
- * Entry field compatibility: the context face returns `category`/`text`, while
- * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
- */
-export function normalizeContextEntry(entry = {}) {
- return {
- uri: String(entry.uri || "").trim(),
- category: String(entry.category || entry.type || "memory").trim() || "memory",
- detail: String(entry.detail || entry.mode || "").trim(),
- score: Number(entry.score) || 0,
- text: String(
- entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
- ).trim(),
- };
-}
-
-async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
- const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
- if (assembled === null) return null;
-
- const { rendered, entries } = assembled;
- let digest = assembled.digest;
- const mode = String(cfg.recallRewrite || "off").toLowerCase();
- if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
- log("recall_server_compression", { status: "empty" });
- return "";
- }
- const wantsLocal = mode === "client" || (mode === "auto" && !digest);
- if (wantsLocal && rendered && typeof options.runCompressor === "function") {
- try {
- const compression = await compressRecallContext({
- query,
- rendered,
- entries,
- cfg,
- runCompressor: options.runCompressor,
- cachePath: options.digestCachePath || stateFile("recall-digest.json"),
- now: Date.now(),
- });
- log("recall_local_compression", { status: compression.status });
- if (compression.status === "ok") digest = compression.context;
- if (compression.status === "empty") return "";
- } catch (err) {
- log("recall_local_compression_failed", { error: String(err?.message || err) });
- }
- }
-
- const injected = digest || rendered;
- if (!injected) return "";
- return wrapContext(injected);
-}
-
-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 wrapContext(rendered);
-}
-
-export async function postRecall(fetchJSON, body, opts = {}) {
- const actorPeerId = opts.actorPeerId || "";
- const log = opts.log || (() => {});
- const memoPath = opts.peerScopeMemoPath;
- const request = { ...body };
-
- // A remembered downgrade is still a downgrade: recall runs wider than the
- // caller asked for, so the memo doubles as the doctor's evidence.
- if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
- delete request.peer_scope;
- }
-
- 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;
- }
- // Only an unknown-field rejection means "this server predates peer_scope".
- // Retrying every other 400/422 without it silently widens the search from
- // the caller's own peer to the whole user root.
- if (!looksLikeUnknownField(res)) {
- log("recall_peer_scope_error", { status: res.status || 0 });
- return res;
- }
-
- const downgraded = { ...request };
- delete downgraded.peer_scope;
- await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
- log("recall_peer_scope_downgrade", { status: res.status || 0 });
- return fetchJSON("/api/v1/search/recall", {
- method: "POST",
- body: JSON.stringify(downgraded),
- }, { actorPeerId });
-}
-
-/**
- * Recall, plus whatever is still filed under the peer this workspace used
- * before the identity rule changed.
- *
- * Under the default `peer_scope: "all"` this costs nothing: the server's own
- * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
- * `"actor"` that sweep is off by definition, so the old peer is asked for
- * separately — as itself, which is both cheaper and wider than a bare
- * cross-peer read (that would need the user id, and reaches memories only).
- */
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
- const primary = await recallForPeer(fetchJSON, cfg, query, options);
-
- const legacyPeerId = String(options.legacyPeerId || "").trim();
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
-
- const log = options.log || (() => {});
- const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
-}
-
-async function recallForPeer(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
- const trimmed = String(query || "").trim();
- if (!trimmed) return null;
-
- // Assembly happens server-side when the deployment offers the context face;
- // older servers fall through to /recall, then to raw find.
- const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
- ...options,
- actorPeerId,
- log,
- });
- if (serverBlock !== null) return serverBlock || null;
-
- const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
- 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/pi-coding-agent-extension/shared/retryable.mjs b/examples/pi-coding-agent-extension/shared/retryable.mjs
deleted file mode 100644
index 8be4b14e8..000000000
--- a/examples/pi-coding-agent-extension/shared/retryable.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-export function isRetryableFailure(result) {
- if (!result || result.ok) return false;
- const status = Number(result.status || 0);
- if (!status || status === 408 || status === 429 || status >= 500) {
- return true;
- }
- return status === 409 && result.error?.details?.retryable === true;
-}
diff --git a/examples/pi-coding-agent-extension/shared/session-model.mjs b/examples/pi-coding-agent-extension/shared/session-model.mjs
deleted file mode 100644
index b6496a113..000000000
--- a/examples/pi-coding-agent-extension/shared/session-model.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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/pi-coding-agent-extension/shared/setup-wizard.mjs b/examples/pi-coding-agent-extension/shared/setup-wizard.mjs
deleted file mode 100644
index a49dbe7db..000000000
--- a/examples/pi-coding-agent-extension/shared/setup-wizard.mjs
+++ /dev/null
@@ -1,114 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Interactive ovcli.conf setup wizard shared by the OpenViking memory plugins.
- *
- * Lets a pure-marketplace install (no installer script) configure the server
- * URL and API key that both the lifecycle hooks and the stdio MCP proxy read:
- *
- * node <plugin>/scripts/setup.mjs
- *
- * Conventions: show current values, keep existing secrets on empty input,
- * merge-write (never drop unknown fields), back up the previous file, 0600.
- */
-
-import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
-import { dirname } from "node:path";
-import { createInterface } from "node:readline/promises";
-import { loadCredentialFiles } from "./credentials.mjs";
-
-const CLOUD_URL = "https://api.vikingdb.cn-beijing.volces.com/openviking";
-const LOCAL_URL = "http://127.0.0.1:1933";
-
-function maskSecret(value) {
- const s = String(value || "");
- if (!s) return "(not set)";
- if (s.length <= 8) return "****";
- return `${s.slice(0, 4)}…${s.slice(-4)} (${s.length} chars)`;
-}
-
-function readJsonSafe(path) {
- try {
- return JSON.parse(readFileSync(path, "utf-8"));
- } catch {
- return {};
- }
-}
-
-export async function runSetupWizard({
- input = process.stdin,
- output = process.stdout,
- env = process.env,
-} = {}) {
- // cliPath is empty until the file exists; first-run writes go to the candidate
- // path (OPENVIKING_CLI_CONFIG_FILE, else ~/.openviking/ovcli.conf).
- const { cliPath, cliPathCandidate } = loadCredentialFiles(env);
- const targetPath = cliPath || cliPathCandidate;
- const current = readJsonSafe(targetPath);
- const rl = createInterface({ input, output });
- const say = (line = "") => output.write(`${line}\n`);
-
- try {
- say("OpenViking memory plugin setup");
- say(`Config file: ${targetPath}`);
- say("");
- say("Current values:");
- say(` url: ${current.url || "(not set)"}`);
- say(` api_key: ${maskSecret(current.api_key)}`);
- if (current.account) say(` account: ${current.account}`);
- if (current.user) say(` user: ${current.user}`);
- say("");
-
- const defaultUrl = current.url || LOCAL_URL;
- say("Where do you connect to OpenViking?");
- say(` 1) Self-hosted / local [${LOCAL_URL}]`);
- say(` 2) Volcengine OpenViking Cloud [${CLOUD_URL}]`);
- say(` 3) Custom URL / keep current [${defaultUrl}]`);
- const mode = (await rl.question("Choice [1/2/3, default 3]: ")).trim();
- let url = defaultUrl;
- if (mode === "1") {
- url = LOCAL_URL;
- } else if (mode === "2") {
- url = CLOUD_URL;
- } else {
- const answer = (await rl.question(`Server URL [${defaultUrl}]: `)).trim();
- if (answer) url = answer;
- }
-
- const keyPrompt = current.api_key
- ? `API key [enter = keep ${maskSecret(current.api_key)}, '-' = clear]: `
- : "API key (leave empty for unauthenticated local mode): ";
- const keyAnswer = await rl.question(keyPrompt);
- let apiKey = current.api_key || "";
- if (keyAnswer === "-") apiKey = "";
- else if (keyAnswer.trim()) apiKey = keyAnswer.trim();
- else if (!current.api_key) apiKey = "";
-
- const next = { ...current, url, api_key: apiKey };
-
- say("");
- say("Changes:");
- say(` url: ${current.url || "(not set)"} -> ${next.url}`);
- say(` api_key: ${maskSecret(current.api_key)} -> ${maskSecret(next.api_key)}`);
- const confirm = (await rl.question("Write config? [Y/n] ")).trim().toLowerCase();
- if (confirm === "n" || confirm === "no") {
- say("Aborted; nothing written.");
- return { written: false, path: targetPath };
- }
-
- mkdirSync(dirname(targetPath), { recursive: true });
- if (existsSync(targetPath)) {
- copyFileSync(targetPath, `${targetPath}.bak.${Date.now()}`);
- }
- writeFileSync(targetPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
- try {
- chmodSync(targetPath, 0o600);
- } catch {
- /* best effort on platforms without chmod semantics */
- }
- say(`Written: ${targetPath}`);
- say("The stdio MCP proxy and hooks pick this up on the next harness start.");
- return { written: true, path: targetPath };
- } finally {
- rl.close();
- }
-}
diff --git a/examples/pi-coding-agent-extension/shared/uri-guard.mjs b/examples/pi-coding-agent-extension/shared/uri-guard.mjs
deleted file mode 100644
index cf57bf406..000000000
--- a/examples/pi-coding-agent-extension/shared/uri-guard.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// 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();
-}
-
-// Arguments that carry file CONTENT rather than a location. The sweep below
-// looks past the known path keys so an unusual one (`paths`, a nested target)
-// is still caught, but text a tool is asked to WRITE is not a path: a local
-// `write` whose body merely mentions viking://user/default/ was denied, and no
-// file was created. Skipped by name at any depth.
-const DEFAULT_CONTENT_KEYS = [
- "content",
- "contents",
- "text",
- "body",
- "old_string",
- "oldString",
- "new_string",
- "newString",
- "old_str",
- "new_str",
- "file_text",
- "insert_line",
- "replacement",
-];
-
-export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_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, new Set(contentKeys));
-}
-
-export function findVikingUriInValue(value, skipKeys) {
- 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, skipKeys);
- if (uri) return uri;
- }
- return null;
- }
- if (value && typeof value === "object") {
- for (const [key, item] of Object.entries(value)) {
- if (skipKeys?.has(key)) continue;
- const uri = findVikingUriInValue(item, skipKeys);
- 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/pi-coding-agent-extension/shared/workspace-identity.mjs b/examples/pi-coding-agent-extension/shared/workspace-identity.mjs
deleted file mode 100644
index 76922cb03..000000000
--- a/examples/pi-coding-agent-extension/shared/workspace-identity.mjs
+++ /dev/null
@@ -1,334 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Workspace identity: where the workspace root is, and what git calls it.
- *
- * Every hook is a fresh Node process and this runs on prompt-level paths, so
- * the derivation is pure filesystem work — no `git` subprocess. That keeps it
- * inside the tightest hook budget (Codex allows SessionEnd 3s against
- * SessionStart's 70s), and it keeps working where git is absent from PATH or
- * would refuse the repo over dubious ownership.
- *
- * The result is cached per cwd under the state dir so the several hooks of one
- * turn pay for the walk once.
- */
-
-import { createHash } from "node:crypto";
-import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
-
-// The workspace config file names live here, and `workspace-config.mjs`
-// re-exports them: the walk below needs the filenames to recognise a directory
-// someone marked as a workspace, and it must not pull in the config layer to
-// learn them.
-export const CONFIG_DIR_NAME = ".openviking";
-export const TEAM_FILE = "config.json";
-export const LOCAL_FILE = "config.local.json";
-
-const IDENTITY_CACHE_TTL_MS = 60_000;
-// 255 is the AGFS path-segment limit; stopping well short leaves room for the
-// hash suffix and for anything that later prefixes a peer id.
-const MAX_PEER_ID_LENGTH = 100;
-
-export function stateDir(env = process.env) {
- const explicit = String(env.OPENVIKING_STATE_DIR || "").trim();
- if (explicit) return explicit;
- const home = String(env.OPENVIKING_HOME || "").trim();
- const base = home ? home.replace(/^~(?=$|\/)/, homedir()) : join(homedir(), ".openviking");
- return join(base, "state");
-}
-
-function shortHash(value) {
- return createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
-}
-
-/**
- * Legacy peer sanitation: one byte in, one byte out, no collapsing and no
- * trimming, so a leading `/` still becomes a leading `-`. Kept byte-exact
- * because `peer.source: "cwd"` and the legacy id that dual-read recomputes both
- * depend on it — do not "improve" it.
- */
-export function legacySanitize(value) {
- return String(value || "").replace(/[^A-Za-z0-9]/g, "-");
-}
-
-/**
- * Readable sanitation for values that were never path-shaped — a normalized
- * remote, a directory name. Mirrors the server's own `_sanitize_component`
- * (`openviking/ingest/peer.py:32`) so both languages agree on the id, then
- * enforces what `validate_identifier_part` additionally requires.
- */
-export function sanitizePeerId(value) {
- const raw = String(value || "").trim();
- let cleaned = raw.replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
- if (!cleaned) return "";
- // The server accepts at most one `@` in an identifier part.
- const at = cleaned.indexOf("@");
- if (at !== -1) cleaned = cleaned.slice(0, at + 1) + cleaned.slice(at + 1).replace(/@/g, "-");
- // `ext-` is the server's namespace for base64-encoded external identities,
- // and `__self` its operation-target sentinel. Neither is ours to occupy.
- if (cleaned.startsWith("ext-")) cleaned = `x-${cleaned}`;
- if (cleaned === "__self") cleaned = "self";
- if (cleaned === "." || cleaned === "..") return "";
- if (cleaned.length > MAX_PEER_ID_LENGTH) {
- cleaned = `${cleaned.slice(0, MAX_PEER_ID_LENGTH - 13).replace(/[-.]+$/, "")}-${shortHash(raw)}`;
- }
- return cleaned;
-}
-
-/**
- * Normalize a remote URL to `host/path`, lowercased.
- *
- * Both spellings of the same repo converge, and userinfo is dropped — so a
- * remote with an embedded token cannot leak it into a peer id. The cost of
- * case folding is that two repos differing only in case share one namespace on
- * the rare case-sensitive forge.
- */
-export function normalizeGitRemote(url) {
- const raw = String(url || "").trim();
- if (!raw) return "";
-
- // `C:\src\repo` and `C:/src/repo` are one machine's directory, not a shared
- // identity — and the scp pattern would happily read the drive as a host.
- if (/^[A-Za-z]:[\\/]/.test(raw)) return "";
-
- let host = "";
- let path = "";
- const scp = /^(?:[^@/\\]+@)?([^:/\\]+):(?!\/)(.+)$/.exec(raw);
- if (scp && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {
- host = scp[1];
- path = scp[2];
- } else {
- let parsed;
- try {
- parsed = new URL(raw);
- } catch {
- return "";
- }
- // A local clone has no stable shared identity — fall through to the path
- // rules instead of minting one from `file://` or a bare directory.
- if (parsed.protocol === "file:" || !parsed.hostname) return "";
- host = parsed.hostname;
- path = parsed.pathname;
- }
-
- host = host.toLowerCase().replace(/^\[|\]$/g, "");
- path = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
- if (!host || !path) return "";
- return `${host}/${path}`;
-}
-
-function readFileOrEmpty(path) {
- try {
- return readFileSync(path, "utf-8");
- } catch {
- return "";
- }
-}
-
-/**
- * Read `[remote "origin"] url` out of a git config with a minimal INI parse.
- *
- * `include` / `includeIf` are deliberately not followed: resolving them means
- * more filesystem walking for a value the fallback chain already covers, so an
- * unreadable remote just falls through to the next template.
- */
-export function readGitRemoteUrl(commonDir, remote = "origin") {
- const text = readFileOrEmpty(join(commonDir, "config"));
- if (!text) return "";
-
- let inSection = false;
- for (const line of text.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;
- const section = /^\[([^\]]+)\]/.exec(trimmed);
- if (section) {
- const header = section[1].trim();
- // git folds section and key names to lower case but keeps a quoted
- // subsection exact, so `[Remote "origin"]` is the same section and
- // `[remote "Origin"]` is not.
- const quoted = /^remote\s+"(.*)"$/i.exec(header);
- inSection = Boolean(quoted && quoted[1] === remote);
- continue;
- }
- if (!inSection) continue;
- const pair = /^url\s*=\s*(.*)$/i.exec(trimmed);
- // git treats an unquoted `#` or `;` as starting a comment anywhere on the
- // line, so a trailing note is not part of the URL.
- if (pair) return pair[1].split(/[#;]/)[0].trim().replace(/^["']|["']$/g, "");
- }
- return "";
-}
-
-function resolveGitDir(root) {
- const dotGit = join(root, ".git");
- let stat;
- try {
- stat = statSync(dotGit);
- } catch {
- return null;
- }
- if (stat.isDirectory()) return { gitDir: dotGit, commonDir: dotGit, kind: "repo" };
- if (!stat.isFile()) return null;
-
- const pointer = /^gitdir:\s*(.+)$/m.exec(readFileOrEmpty(dotGit));
- if (!pointer) return null;
- const gitDir = resolve(root, pointer[1].trim());
-
- // `commondir` is the worktree signal, so it is read first — a repository
- // that merely lives under a directory called `modules` is not a submodule.
- const commonRef = readFileOrEmpty(join(gitDir, "commondir")).trim();
- const commonDir = commonRef
- ? (isAbsolute(commonRef) ? commonRef : resolve(gitDir, commonRef))
- : gitDir;
-
- // A submodule keeps its own remote under the superproject's
- // `.git/modules/<name>`; converging it onto the superproject would merge two
- // repositories that release, and are reviewed, separately. Only the segment
- // right after a `.git` directory means that, which is also why a worktree of
- // a submodule resolves here through its own commondir.
- const kind = /[/\\]\.git[/\\]modules[/\\]/.test(`${commonDir}${sep}`)
- ? "submodule"
- : (commonRef ? "worktree" : "repo");
- return { gitDir, commonDir, kind };
-}
-
-/** A directory the user made a workspace on purpose, by giving it a config file. */
-function hasWorkspaceMarker(dir) {
- for (const name of [TEAM_FILE, LOCAL_FILE]) {
- try {
- if (statSync(join(dir, CONFIG_DIR_NAME, name)).isFile()) return true;
- } catch { /* not marked here */ }
- }
- return false;
-}
-
-const NO_ROOT = Object.freeze({ root: "", rootKind: "", git: null, gitRoot: "" });
-
-/**
- * Walk up from `cwd` to the nearest workspace root.
- *
- * A workspace is a git repository, or a directory someone marked as one by
- * creating `.openviking/config.json` (or `config.local.json`) in it. Nearest
- * wins. Above a marked directory the walk continues to the enclosing
- * repository, if any, so the git-shaped variables still resolve there.
- * Anything else — a scratch folder, a download, an app's per-task directory —
- * is not a workspace and gets no peer of its own.
- *
- * `$HOME` and the filesystem root are never workspace roots: a stray `.git`
- * in either would silently make every unrelated directory one workspace.
- */
-export function findWorkspaceRoot(cwd, env = process.env) {
- const start = String(cwd || "").trim();
- if (!start) return NO_ROOT;
-
- let absolute;
- try {
- // A relative `start` makes `resolve` read process.cwd(), which throws when
- // the directory is gone — the very case the catch below is meant to cover.
- absolute = resolve(start);
- } catch {
- return NO_ROOT;
- }
-
- // `current` and `stopAt` are compared as strings, so they must be
- // canonicalized together. A `$HOME` reached through a symlink plus an
- // unresolvable cwd would otherwise walk straight past the guard.
- const home = String(env.HOME || "").trim() || homedir();
- let current;
- let stopAt;
- try {
- current = realpathSync(absolute);
- stopAt = realpathSync(home);
- } catch {
- current = absolute;
- stopAt = home;
- }
- const filesystemRoot = parse(current).root;
- if (current === stopAt || current === filesystemRoot) return NO_ROOT;
-
- let root = "";
- let rootKind = "";
- while (current && current !== filesystemRoot && current !== stopAt) {
- const git = resolveGitDir(current);
- if (git) return { root: root || current, rootKind: rootKind || "git", git, gitRoot: current };
- if (!root && hasWorkspaceMarker(current)) {
- root = current;
- rootKind = "config";
- }
- const parent = dirname(current);
- if (parent === current) break;
- current = parent;
- }
- return root ? { root, rootKind, git: null, gitRoot: "" } : NO_ROOT;
-}
-
-function cachePath(cwd, env) {
- return join(stateDir(env), `ws-identity-${shortHash(cwd)}.json`);
-}
-
-function readCache(path, now) {
- try {
- const cached = JSON.parse(readFileSync(path, "utf-8"));
- // Bounded on both sides: an entry stamped in the future — a clock that ran
- // fast, or `Infinity` — would otherwise pin a stale identity indefinitely.
- if (typeof cached?.ts !== "number" || cached.ts > now || now - cached.ts > IDENTITY_CACHE_TTL_MS) return null;
- const identity = cached.identity;
- if (identity && typeof identity === "object" && identity.vars && typeof identity.vars === "object") {
- return identity;
- }
- } catch { /* a cold or corrupt cache just costs one walk */ }
- return null;
-}
-
-function writeCache(path, identity, now) {
- try {
- mkdirSync(dirname(path), { recursive: true });
- const tmp = `${path}.${process.pid}.tmp`;
- writeFileSync(tmp, JSON.stringify({ ts: now, identity }), { mode: 0o600 });
- renameSync(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Everything the peer templates can substitute, for one cwd.
- *
- * `git_remote` and `dir` are already sanitized; `git_root` and `cwd` carry the
- * legacy byte-for-byte rule, because they are the two that must reproduce a
- * peer minted before any of this existed.
- */
-export function resolveWorkspaceIdentity({ cwd = "", env = process.env, cache = true, now = Date.now() } = {}) {
- const key = String(cwd || "");
- const path = cachePath(key, env);
- if (cache) {
- const hit = readCache(path, now);
- if (hit) return hit;
- }
-
- const { root, rootKind, git, gitRoot } = findWorkspaceRoot(key, env);
- // Only the normalized form is kept. The raw URL may carry a token, and this
- // file outlives the process — writing it here would undo the care
- // `normalizeGitRemote` takes to drop userinfo.
- const remote = git ? normalizeGitRemote(readGitRemoteUrl(git.commonDir)) : "";
- const identity = {
- cwd: key,
- root,
- rootKind,
- isGit: Boolean(git),
- gitKind: git?.kind || "",
- gitCommonDir: git?.commonDir || "",
- gitRoot,
- remote,
- vars: {
- git_remote: sanitizePeerId(remote),
- // The enclosing repository's root, which is not the workspace root when a
- // marker file below it won. Empty outside a repository, so the `git`
- // preset resolves to nothing there rather than to a bare path.
- git_root: git ? legacySanitize(gitRoot) : "",
- cwd: legacySanitize(key),
- dir: root ? sanitizePeerId(root.split(/[/\\]/).filter(Boolean).pop() || "") : "",
- },
- };
- if (cache) writeCache(path, identity, now);
- return identity;
-}
diff --git a/examples/pi-coding-agent-extension/shared/workspace-peer.d.mts b/examples/pi-coding-agent-extension/shared/workspace-peer.d.mts
deleted file mode 100644
index 9a920fcc5..000000000
--- a/examples/pi-coding-agent-extension/shared/workspace-peer.d.mts
+++ /dev/null
@@ -1,5 +0,0 @@
-export function deriveWorkspacePeerId(cwd: unknown): string;
-export function resolveEffectivePeerId(input?: {
- cfg?: { peerId?: string; workspacePeer?: boolean };
- cwd?: string;
-}): { peerId: string; source: "explicit" | "workspace" | "none" };
diff --git a/examples/pi-coding-agent-extension/shared/workspace-peer.mjs b/examples/pi-coding-agent-extension/shared/workspace-peer.mjs
deleted file mode 100644
index 89df30793..000000000
--- a/examples/pi-coding-agent-extension/shared/workspace-peer.mjs
+++ /dev/null
@@ -1,134 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Which peer a workspace writes its memories under.
- *
- * The peer used to be the working directory with every non-alphanumeric byte
- * turned into a dash, which made the identity an accident of where the
- * repository happened to sit: a clone on another machine, a rename, a worktree
- * or simply `cd examples/` each minted a separate, empty namespace. The default
- * is now git's own idea of the repository, so one project keeps one memory
- * wherever it is checked out.
- *
- * `peer.source` decides the rule. Presets cover the three answers most people
- * want; a template — or a list of templates tried in order — covers the rest.
- * The old behaviour is still one word away, byte for byte.
- */
-
-import { legacySanitize, resolveWorkspaceIdentity, sanitizePeerId } from "./workspace-identity.mjs";
-
-/**
- * `git` is the default, and it resolves only inside a repository: the remote
- * first, because that is the one name every clone agrees on, then the
- * repository root for a repo that has none. Anywhere else it resolves to
- * nothing and no peer is sent — a scratch folder or an app's per-task
- * directory would otherwise mint a fresh, empty namespace each time, so those
- * memories go to the user-level space instead. Naming such a directory is what
- * `peer.id` is for, and deriving one from a bare path is what `cwd` is for;
- * both are opt-in.
- *
- * No preset adds a prefix. A path-derived id starts with `-` on POSIX, so it
- * cannot collide with a remote-derived one; anyone who wants a prefix writes
- * their own template.
- */
-export const PEER_SOURCE_PRESETS = {
- git: ["{git_remote}", "{git_root}"],
- cwd: ["{cwd}"],
- none: [],
-};
-
-export const DEFAULT_PEER_SOURCE = "git";
-
-const VARIABLE_RE = /\{([a-z_]+)\}/g;
-
-export function deriveWorkspacePeerId(cwd) {
- return legacySanitize(cwd);
-}
-
-/**
- * Normalize `peer.source` — a preset name, a template, or a list — to templates.
- *
- * A bare string with no `{` is a misspelled preset, not a template: `Git` or
- * `gti` would otherwise become a peer literally named `Git`, quietly stranding
- * the workspace's memories in a namespace nobody meant to create. Such a value
- * warns and falls back to the default chain. An array is left alone — writing a
- * list is explicit enough to mean the constant it contains.
- */
-export function peerSourceTemplates(source, onWarn = null) {
- if (Array.isArray(source)) return source.map(String).filter(Boolean);
- const raw = String(source ?? "").trim();
- if (!raw) return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
- if (Object.hasOwn(PEER_SOURCE_PRESETS, raw)) return PEER_SOURCE_PRESETS[raw];
- if (raw.includes("{")) return [raw];
-
- const message = `OpenViking: ignored peer.source ${JSON.stringify(raw)}: it is neither a preset `
- + `(${Object.keys(PEER_SOURCE_PRESETS).join(", ")}) nor a template such as "team-{dir}". `
- + `Falling back to ${DEFAULT_PEER_SOURCE}.`;
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
-}
-
-/**
- * Substitute one template, or return "" when any variable it names is empty.
- *
- * All-or-nothing on purpose: a half-resolved template like `git-` would be a
- * silently shared identity, so an empty variable falls through to the next
- * template instead.
- */
-export function renderPeerTemplate(template, vars) {
- const text = String(template || "");
- if (!text) return "";
- let empty = false;
- const rendered = text.replace(VARIABLE_RE, (match, name) => {
- if (!Object.hasOwn(vars, name)) {
- empty = true;
- return "";
- }
- const value = String(vars[name] ?? "");
- if (!value) empty = true;
- return value;
- });
- return empty ? "" : rendered;
-}
-
-/**
- * The peer this process should send, and where it came from.
- *
- * `source` keeps its three values — call sites compare it against the literal
- * `"workspace"` to decide whether a session pin may be reused — while `origin`
- * names the template that actually produced the id, and `legacyPeerId` carries
- * the pre-git id whenever it differs, so recall can still reach memories
- * written under it.
- */
-export function resolveEffectivePeerId({ cfg = {}, cwd = "", identity = null, env = process.env, onWarn = null } = {}) {
- const explicit = String(cfg.peerId || "").trim();
- if (explicit) return { peerId: explicit, source: "explicit", origin: "explicit", legacyPeerId: "" };
-
- // `OPENVIKING_WORKSPACE_PEER=0` predates `peer.source` and still means "none".
- if (cfg.workspacePeer === false) return { peerId: "", source: "none", origin: "disabled", legacyPeerId: "" };
-
- const templates = peerSourceTemplates(cfg.peerSource, onWarn);
- if (!templates.length) return { peerId: "", source: "none", origin: "none", legacyPeerId: "" };
-
- // `harness` is composed here rather than in the identity, whose result is
- // cached on disk under a cwd-only key — two harnesses in one directory would
- // otherwise read each other's peer back out of that cache.
- const vars = {
- ...((identity || resolveWorkspaceIdentity({ cwd, env })).vars || {}),
- harness: sanitizePeerId(cfg.harness || cfg.clientId || ""),
- };
- const legacyPeerId = deriveWorkspacePeerId(cwd);
- for (const template of templates) {
- const peerId = renderPeerTemplate(template, vars);
- if (!peerId) continue;
- return {
- peerId,
- source: "workspace",
- origin: template,
- legacyPeerId: peerId === legacyPeerId ? "" : legacyPeerId,
- };
- }
- // No peer, but the pre-git id is still what earlier sessions in this
- // directory wrote under, so recall keeps reaching it.
- return { peerId: "", source: "none", origin: "unresolved", legacyPeerId };
-}
diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.ts
index 50a66b958..6a19ad2ee 100644
--- a/examples/pi-coding-agent-extension/sync.ts
+++ b/examples/pi-coding-agent-extension/sync.ts
@@ -55,7 +55,7 @@ export class SyncManager {
async replayPending(): Promise<void> {
if (!this.client.connected) return;
await replayPending(
- (path: string, init?: any) => this.client.fetchJSON(path, init, 10000),
+ (path: string, init?: any) => this.client.fetchJSON(path, init),
(stage: string, data: unknown) => this.logger.log(stage, data),
);
}
@@ -143,7 +143,7 @@ export class SyncManager {
}
}
- private fetchJSON = (path: string, init?: any) => this.client.fetchJSON(path, init, 10000);
+ private fetchJSON = (path: string, init?: any) => this.client.fetchJSON(path, init);
async syncBranch(branch: any[]): Promise<SyncBranchResult> {
if (!this.ovSessionId) return { added: 0, tokens: 0, allDelivered: true };
diff --git a/examples/pi-coding-agent-extension/tests/config.test.mjs b/examples/pi-coding-agent-extension/tests/config.test.mjs
index 1fbd66d2a..1824ba8a9 100644
--- a/examples/pi-coding-agent-extension/tests/config.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/config.test.mjs
@@ -3,10 +3,20 @@ import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
-import { pathToFileURL } from "node:url";
-import { loadConfig, loadConfigFromModuleUrl } from "../config.ts";
-
-async function withConfigFile(body, fn, env = {}, cliConfig = null) {
+import { loadConfig } from "../config.ts";
+import { isBypassed } from "../shared/session-model.mjs";
+
+// The layers, the knobs and the peer order are the shared loader's, and
+// memory-plugin-shared/plugin-config.test.mjs holds this harness to them. What
+// is left here is what this extension answers itself: the takeover knobs, the
+// peer it reports from the workspace resolution, and the two names it kept from
+// before it shared a loader.
+
+/**
+ * Run `loadConfig()` with `body` as the extension's `plugin.pi` section of a
+ * throwaway ovcli.conf. `cliConfig` adds the connection fields around it.
+ */
+async function withPluginSection(body, fn, env = {}, cliConfig = null) {
const dir = await mkdtemp(join(tmpdir(), "ov-pi-config-用户-"));
const oldEnv = {
OPENVIKING_URL: process.env.OPENVIKING_URL,
@@ -21,6 +31,8 @@ async function withConfigFile(body, fn, env = {}, cliConfig = null) {
OPENVIKING_CONFIG_FILE: process.env.OPENVIKING_CONFIG_FILE,
OPENVIKING_DEBUG_LOG: process.env.OPENVIKING_DEBUG_LOG,
OV_DEBUG_LOG: process.env.OV_DEBUG_LOG,
+ OPENVIKING_BYPASS_SESSION: process.env.OPENVIKING_BYPASS_SESSION,
+ OPENVIKING_BYPASS_SESSION_PATTERNS: process.env.OPENVIKING_BYPASS_SESSION_PATTERNS,
};
process.env.OPENVIKING_CREDENTIAL_SOURCE = "env";
process.env.OPENVIKING_URL = "http://127.0.0.1:1933";
@@ -34,17 +46,20 @@ async function withConfigFile(body, fn, env = {}, cliConfig = null) {
delete process.env.OPENVIKING_RECALL_PEER_SCOPE;
delete process.env.OPENVIKING_DEBUG_LOG;
delete process.env.OV_DEBUG_LOG;
+ delete process.env.OPENVIKING_BYPASS_SESSION;
+ delete process.env.OPENVIKING_BYPASS_SESSION_PATTERNS;
for (const [key, value] of Object.entries(env)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
try {
- await writeFile(join(dir, "config.json"), JSON.stringify(body), "utf8");
- if (cliConfig !== null) {
- await writeFile(join(dir, "ovcli.conf"), JSON.stringify(cliConfig), "utf8");
- }
- return await fn(loadConfig(dir), dir);
+ await writeFile(
+ join(dir, "ovcli.conf"),
+ JSON.stringify({ ...(cliConfig || {}), plugin: { pi: body } }),
+ "utf8",
+ );
+ return await fn(loadConfig(), dir);
} finally {
for (const [key, value] of Object.entries(oldEnv)) {
if (value === undefined) delete process.env[key];
@@ -55,7 +70,7 @@ async function withConfigFile(body, fn, env = {}, cliConfig = null) {
}
test("loadConfig defaults takeover on", async () => {
- await withConfigFile({}, (cfg) => {
+ await withPluginSection({}, (cfg) => {
assert.equal(cfg.takeoverEnabled, true);
assert.equal(cfg.takeoverTokenThreshold, 30000);
assert.equal(cfg.takeoverKeepRecentTurns, 3);
@@ -65,16 +80,14 @@ test("loadConfig defaults takeover on", async () => {
});
});
-test("loadConfig maps nested takeover block", async () => {
- await withConfigFile({
- takeover: {
- enabled: false,
- tokenThreshold: 600,
- keepRecentTurns: 1,
- overviewBudget: 1200,
- overviewPollMs: 10,
- overviewPollMax: 2,
- },
+test("loadConfig reads the takeover knobs", async () => {
+ await withPluginSection({
+ takeoverEnabled: false,
+ takeoverTokenThreshold: 600,
+ takeoverKeepRecentTurns: 1,
+ takeoverOverviewBudget: 1200,
+ takeoverOverviewPollMs: 10,
+ takeoverOverviewPollMax: 2,
}, (cfg) => {
assert.equal(cfg.takeoverEnabled, false);
assert.equal(cfg.takeoverTokenThreshold, 600);
@@ -85,40 +98,16 @@ test("loadConfig maps nested takeover block", async () => {
});
});
-test("loadConfigFromModuleUrl decodes Unicode paths", async () => {
- await withConfigFile({
- takeover: {
- tokenThreshold: 2000,
- },
- }, (_cfg, dir) => {
- const moduleUrl = pathToFileURL(join(dir, "index.ts")).href;
- const cfg = loadConfigFromModuleUrl(moduleUrl);
- assert.equal(cfg.takeoverTokenThreshold, 2000);
- });
-});
-
-test("loadConfig keeps top-level takeover aliases for compatibility", async () => {
- await withConfigFile({
- takeoverTokenThreshold: 42,
- takeoverKeepRecentTurns: 4,
- }, (cfg) => {
- assert.equal(cfg.takeoverTokenThreshold, 42);
- assert.equal(cfg.takeoverKeepRecentTurns, 4);
- });
-});
-
test("loadConfig clamps invalid takeover values", async () => {
- await withConfigFile({
- takeover: {
- enabled: "no",
- tokenThreshold: -1,
- keepRecentTurns: -5,
- overviewBudget: 1,
- overviewPollMs: -2,
- overviewPollMax: 0,
- },
+ await withPluginSection({
+ takeoverEnabled: "no",
+ takeoverTokenThreshold: -1,
+ takeoverKeepRecentTurns: -5,
+ takeoverOverviewBudget: 1,
+ takeoverOverviewPollMs: -2,
+ takeoverOverviewPollMax: 0,
}, (cfg) => {
- assert.equal(cfg.takeoverEnabled, true);
+ assert.equal(cfg.takeoverEnabled, false, "\"no\" is a recognised off");
assert.equal(cfg.takeoverTokenThreshold, 1);
assert.equal(cfg.takeoverKeepRecentTurns, 0);
assert.equal(cfg.takeoverOverviewBudget, 100);
@@ -133,15 +122,17 @@ test("loadConfig derives workspace peer by default", async () => {
// remote, and outside one it is still the old working-directory id.
const { resolveEffectivePeerId } = await import("../shared/workspace-peer.mjs");
const expected = resolveEffectivePeerId({ cfg: {}, cwd: process.cwd() });
- await withConfigFile({}, (cfg) => {
+ await withPluginSection({}, (cfg) => {
assert.equal(cfg.peerId, expected.peerId);
assert.equal(cfg.workspacePeer, true);
assert.equal(cfg.recallPeerScope, "all");
});
});
-test("loadConfig prefers config peer over workspace derivation", async () => {
- await withConfigFile({
+// This extension reports the whole workspace resolution's peer rather than the
+// one the layers named, so both directions of that have to hold.
+test("loadConfig prefers the plugin section peer over workspace derivation", async () => {
+ await withPluginSection({
peerId: " pi ",
workspacePeer: true,
}, (cfg) => {
@@ -149,48 +140,14 @@ test("loadConfig prefers config peer over workspace derivation", async () => {
});
});
-test("loadConfig keeps config peer when workspace derivation is disabled", async () => {
- await withConfigFile({
- peerId: "pi",
- workspacePeer: false,
- }, (cfg) => {
- assert.equal(cfg.peerId, "pi");
- assert.equal(cfg.workspacePeer, false);
- });
-});
-
-test("loadConfig gives environment peer precedence over config peer", async () => {
- await withConfigFile({
- peerId: "config-peer",
- recallPeerScope: "actor",
- workspacePeer: false,
- }, (cfg) => {
- assert.equal(cfg.peerId, "explicit-peer");
- assert.equal(cfg.workspacePeer, false);
- assert.equal(cfg.recallPeerScope, "actor");
- }, { OPENVIKING_PEER_ID: "explicit-peer" });
-});
-
-test("loadConfig leaves the debug log off when nothing asks for it", async () => {
- await withConfigFile({}, (cfg) => {
- assert.equal(cfg.debugLogPath, "");
- });
-});
-
-test("loadConfig reads the debug log path from OPENVIKING_DEBUG_LOG", async () => {
- await withConfigFile({}, (cfg) => {
- assert.equal(cfg.debugLogPath, "/tmp/ov-pi-shared.log");
- }, { OPENVIKING_DEBUG_LOG: "/tmp/ov-pi-shared.log" });
-});
-
test("loadConfig still honours the deprecated OV_DEBUG_LOG", async () => {
- await withConfigFile({}, (cfg) => {
+ await withPluginSection({}, (cfg) => {
assert.equal(cfg.debugLogPath, "/tmp/ov-pi-legacy.log");
}, { OV_DEBUG_LOG: "/tmp/ov-pi-legacy.log" });
});
test("loadConfig prefers OPENVIKING_DEBUG_LOG over the deprecated alias", async () => {
- await withConfigFile({ debugLogPath: "/tmp/ov-pi-file.log" }, (cfg) => {
+ await withPluginSection({ debugLogPath: "/tmp/ov-pi-file.log" }, (cfg) => {
assert.equal(cfg.debugLogPath, "/tmp/ov-pi-shared.log");
}, {
OPENVIKING_DEBUG_LOG: "/tmp/ov-pi-shared.log",
@@ -198,22 +155,32 @@ test("loadConfig prefers OPENVIKING_DEBUG_LOG over the deprecated alias", async
});
});
-test("loadConfig falls back to the config file debug log path", async () => {
- await withConfigFile({ debugLogPath: " /tmp/ov-pi-file.log " }, (cfg) => {
+test("loadConfig falls back to the plugin section debug log path", async () => {
+ await withPluginSection({ debugLogPath: " /tmp/ov-pi-file.log " }, (cfg) => {
assert.equal(cfg.debugLogPath, "/tmp/ov-pi-file.log");
});
});
-test("loadConfig gives ovcli peer precedence over config peer", async () => {
- await withConfigFile({
- peerId: "config-peer",
- }, (cfg) => {
- assert.equal(cfg.peerId, "ovcli-peer");
- }, {
- OPENVIKING_CREDENTIAL_SOURCE: "cli",
- OPENVIKING_URL: undefined,
+test("loadConfig projects bypassPatterns onto the name the shared matcher reads", async () => {
+ await withPluginSection({ bypassPatterns: ["/tmp/scratch*", " "] }, (cfg) => {
+ assert.deepEqual(cfg.bypassSessionPatterns, ["/tmp/scratch*"]);
+ assert.deepEqual(cfg.bypassPatterns, ["/tmp/scratch*"]);
+ assert.equal(isBypassed(cfg, { cwd: "/tmp/scratch-1" }), true);
+ assert.equal(isBypassed(cfg, { cwd: "/tmp/keep" }), false);
+ });
+});
+
+test("loadConfig reads bypassSessionPatterns directly and lets the env override it", async () => {
+ await withPluginSection({ bypassSessionPatterns: ["/from/file"] }, (cfg) => {
+ assert.deepEqual(cfg.bypassSessionPatterns, ["/from/file"]);
+ });
+
+ await withPluginSection({ bypassSessionPatterns: ["/from/file"] }, (cfg) => {
+ assert.deepEqual(cfg.bypassSessionPatterns, ["/from/env", "/also/env"]);
+ assert.equal(cfg.bypassSession, true);
+ assert.equal(isBypassed(cfg, { cwd: "/anywhere" }), true, "the switch wins regardless of cwd");
}, {
- url: "http://127.0.0.1:1933",
- actor_peer_id: "ovcli-peer",
+ OPENVIKING_BYPASS_SESSION_PATTERNS: "/from/env, /also/env ,",
+ OPENVIKING_BYPASS_SESSION: "1",
});
});
diff --git a/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs b/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs
index 49a10bb07..f48642fe3 100644
--- a/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs
@@ -1,6 +1,54 @@
-import test from "node:test";
+import test, { before, after } from "node:test";
import assert from "node:assert/strict";
import { RecallManager } from "../recall.ts";
+import { OVClient } from "../client.ts";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { withMockOpenViking, writeJson } from "../../memory-plugin-shared/testing/support.mjs";
+
+let testHome;
+const savedHome = process.env.OPENVIKING_STATE_DIR;
+before(async () => {
+ testHome = await mkdtemp(join(tmpdir(), "ov-pi-recall-tests-"));
+ process.env.OPENVIKING_STATE_DIR = testHome;
+});
+after(async () => {
+ if (savedHome === undefined) delete process.env.OPENVIKING_STATE_DIR;
+ else process.env.OPENVIKING_STATE_DIR = savedHome;
+ await rm(testHome, { recursive: true, force: true });
+});
+
+test("actor recall preserves peers and the server request budget", async (t) => {
+ const home = await mkdtemp(join(tmpdir(), "ov-pi-peer-recall-"));
+ const previousHome = process.env.OPENVIKING_STATE_DIR;
+ process.env.OPENVIKING_STATE_DIR = home;
+ const delays = [];
+ const realSetTimeout = globalThis.setTimeout;
+ t.mock.method(globalThis, "setTimeout", (fn, ms, ...args) => {
+ delays.push(ms);
+ return realSetTimeout(fn, ms, ...args);
+ });
+ try {
+ await withMockOpenViking((req, res) => {
+ const peer = req.headers["x-openviking-actor-peer"];
+ writeJson(res, { status: "ok", result: { rendered: `- memory for ${peer}` } });
+ }, async (baseUrl, requests) => {
+ const cfg = config({ endpoint: baseUrl, peerId: "new-git-peer", legacyPeerId: "old-cwd-peer", recallPeerScope: "actor", timeoutMs: 123456 });
+ const recall = new RecallManager(new OVClient(cfg), cfg, () => "pi-session");
+ recall.queueSearch("project conventions");
+ const block = await recall.searchPending();
+ assert.deepEqual(requests.map((r) => r.headers["x-openviking-actor-peer"]), ["new-git-peer", "old-cwd-peer"]);
+ assert.match(block, /memory for new-git-peer/);
+ assert.match(block, /memory for old-cwd-peer/);
+ assert.equal(delays.filter((ms) => ms === 123456).length, 2, "both HTTP requests must retain the helper budget");
+ });
+ } finally {
+ if (previousHome === undefined) delete process.env.OPENVIKING_STATE_DIR;
+ else process.env.OPENVIKING_STATE_DIR = previousHome;
+ await rm(home, { recursive: true, force: true });
+ }
+});
function config(overrides = {}) {
return {
diff --git a/examples/pi-coding-agent-extension/tests/recall-ledger.test.mjs b/examples/pi-coding-agent-extension/tests/recall-ledger.test.mjs
index 93b9daef7..3e5938812 100644
--- a/examples/pi-coding-agent-extension/tests/recall-ledger.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/recall-ledger.test.mjs
@@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, writeFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { RecallManager } from "../recall.ts";
-import { RecallLedger, ledgerKey } from "../shared/recall-ledger.mjs";
+import { RecallLedger, ledgerKey } from "../lib/recall-ledger.mjs";
function config(overrides = {}) {
return {
diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
index 541aaa57f..e0d01ce69 100644
--- a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
@@ -21,7 +21,6 @@ function config(overrides = {}) {
function client(overrides = {}) {
return {
connected: true,
- addMessagePayload: async () => true,
getSession: async () => ({ pending_tokens: 0 }),
commitSession: async () => ({ task_id: "t-1", archive_uri: "viking://archive/1" }),
commitSessionResponse: async () => ({
@@ -120,7 +119,6 @@ test("queued addMessage makes takeover flush barrier false until replay succeeds
await withPendingDir(async () => {
let replayOk = false;
const c = client({
- addMessagePayload: async () => false,
fetchJSON: async () => ({ ok: replayOk, status: replayOk ? 200 : 500, result: {} }),
});
const sync = new SyncManager(c, config());
@@ -144,7 +142,6 @@ test("queued addMessage makes takeover flush barrier false until replay succeeds
test("current-session addMessage 500 remains queued and keeps barrier closed", async () => {
await withPendingDir(async () => {
const c = client({
- addMessagePayload: async () => false,
fetchJSON: async () => ({ ok: false, status: 500 }),
});
const sync = new SyncManager(c, config());
diff --git a/examples/trae-cli-memory-hooks/.mcp.json b/examples/trae-cli-memory-hooks/.mcp.json
deleted file mode 100644
index 30ab7661c..000000000
--- a/examples/trae-cli-memory-hooks/.mcp.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "mcpServers": {
- "openviking-memory": {
- "command": "node",
- "args": [
- "servers/mcp-proxy.mjs"
- ],
- "cwd": ".",
- "startup_timeout_sec": 30,
- "env_vars": [
- "OPENVIKING_CLI_CONFIG_FILE",
- "OPENVIKING_CONFIG_FILE",
- "OPENVIKING_URL",
- "OPENVIKING_BASE_URL",
- "OPENVIKING_MCP_URL",
- "OPENVIKING_API_KEY",
- "OPENVIKING_BEARER_TOKEN",
- "OPENVIKING_ACCOUNT",
- "OPENVIKING_USER",
- "OPENVIKING_PEER_ID",
- "OPENVIKING_CREDENTIAL_SOURCE",
- "OPENVIKING_CREDENTIALS_SOURCE",
- "OPENVIKING_TIMEOUT_MS",
- "OPENVIKING_INTEGRATION_VERSION",
- "OPENVIKING_DEBUG",
- "OPENVIKING_DEBUG_LOG"
- ]
- }
- }
-}
diff --git a/examples/trae-cli-memory-hooks/README.md b/examples/trae-cli-memory-hooks/README.md
deleted file mode 100644
index 4419b0623..000000000
--- a/examples/trae-cli-memory-hooks/README.md
+++ /dev/null
@@ -1,155 +0,0 @@
-# OpenViking Memory Hooks for TRAE CLI
-
-> **Deprecated.** TraeCode CLI 2.0 supports Codex-format plugins directly. New
-> installations use [`examples/codex-memory-plugin`](../codex-memory-plugin)
-> through the `trae-cli` command alias, so this adapter is retained only for
-> compatibility tests and removal of existing managed installations.
-
-This directory provides the TRAE CLI lifecycle adapter for OpenViking memory:
-three lifecycle hooks, a `PreToolUse` URI guard, and the `openviking-memory`
-MCP server.
-
-## Installation
-
-Install the supported TraeCode CLI 2.0 plugin through the shared installer:
-
-```bash
-bash examples/memory-plugin-shared/install.sh --harness trae-cli
-```
-
-The installer keeps `trae-cli` as the user-facing harness name and resolves it
-internally to the Codex-format plugin installation. The deprecated component is
-this standalone Hooks adapter, not the `trae-cli` harness.
-
-It no longer installs this adapter. The previous installer behavior was to:
-
-- assemble the shared runtime under
- `$OPENVIKING_HOME/agent-integrations/memory-plugin-shared/lib`;
-- install this adapter under
- `$OPENVIKING_HOME/agent-integrations/trae-cli`;
-- merge hooks into `${TRAECLI_HOME:-${TRAE_HOME:-~/.trae}/cli}/hooks.json`;
-- register `openviking-memory` in `${TRAE_HOME:-~/.trae}/traecli.toml`.
-
-Uninstall with:
-
-```bash
-bash examples/memory-plugin-shared/install.sh --harness trae-cli --uninstall --yes
-```
-
-## Hook and MCP Surface
-
-The draft registers four hook events:
-
-| Event | Entry | Reuse assessment |
-| --- | --- | --- |
-| `SessionStart` | `scripts/session-start.mjs` | Reuses the shared thin-harness profile injection path. Requires TRAE CLI to provide a stable session id or equivalent cwd fallback. |
-| `UserPromptSubmit` | `scripts/auto-recall.mjs` | Reuses the shared recall path. Requires TRAE CLI prompt input to be exposed as `prompt`, `user_prompt`, `message`, or `text`. |
-| `Stop` | `scripts/auto-capture.mjs` | Reuses shared session append and commit helpers. Requires TRAE CLI stop input to expose the assistant response as `last_assistant_message`, `assistant_message`, `response`, `output`, or `text_content`. |
-| `PreToolUse` | `scripts/uri-guard.mjs` | Follows the Codex hook output style for `permissionDecision: "deny"` and reuses the shared `agent-uri-guard` evaluator. |
-
-TRAE CLI lifecycle hooks do not use TRAE / TRAE CN's `decision: "approve"`
-output. No-op lifecycle hooks emit `{}`; context injection emits only
-`hookSpecificOutput.hookEventName` plus `hookSpecificOutput.additionalContext`.
-Tool-call allow/deny decisions belong to `PreToolUse` via
-`hookSpecificOutput.permissionDecision`, and permission approval belongs to
-`PermissionRequest` via `hookSpecificOutput.decision.behavior`.
-
-The MCP server is named `openviking-memory`, matching the Codex memory plugin
-name. The package keeps the same `.mcp.json` source shape as the other native
-hook integrations; the shared installer writes the equivalent Node proxy entry
-into TRAE CLI's configured `traecli.toml`:
-
-```json
-{
- "mcpServers": {
- "openviking-memory": {
- "command": "node",
- "args": ["servers/mcp-proxy.mjs"],
- "cwd": ".",
- "startup_timeout_sec": 30
- }
- }
-}
-```
-
-## Runtime Boundary
-
-This package follows the same source layout as `examples/trae-memory-hooks`:
-the repository directory contains only TRAE CLI-specific adapters. The shared
-runtime is assembled by the installer at install time.
-
-- `examples/memory-plugin-shared/lib/agent-hook-runtime.mjs` handles profile
- injection, recall, capture, commit, session state, locking, credential
- loading, and pending retry replay.
-- `examples/memory-plugin-shared/lib/mcp-proxy-core.mjs` handles the stdio to
- OpenViking `/mcp` proxy.
-- `examples/memory-plugin-shared/lib/agent-uri-guard.mjs` handles `PreToolUse`
- blocking when local file or shell tools receive `viking://` virtual paths.
-
-The source package intentionally does not carry a vendored `lib/` directory.
-The installer should copy `examples/trae-cli-memory-hooks` into
-`$OV_HOME/agent-integrations/trae-cli` and assemble the shared runtime into
-`$OV_HOME/agent-integrations/memory-plugin-shared/lib`, matching the existing
-TRAE installation model.
-
-## What Is Not Reused From Codex
-
-- Codex plugin marketplace metadata and install commands.
-- Codex-specific `${PLUGIN_ROOT}` substitution.
-- Codex-specific `PreCompact` commit flow.
-- Codex transcript JSONL parsing and `cx-<session_id>` session prefix.
-- Codex local compressor startup detection.
-
-## Current Compatibility Notes
-
-The three hook entries are intended to be reusable if TRAE CLI sends hook input
-JSON close to the existing thin harness conventions:
-
-- Session identity: `conversation_id`, `session_id`, `sessionId`, or
- `generation_id`.
-- Workspace: `cwd`, `workspace_roots`, or `workspaceRoots`.
-- User prompt: `prompt`, `user_prompt`, `userPrompt`, `message`, or `text`.
-- Assistant response on stop: `last_assistant_message`,
- `lastAssistantMessage`, `assistant_message`, `assistantMessage`, `response`,
- `output`, or `text_content`.
-- Tool call: `tool_name`, `toolName`, `name`, or `tool`; input under
- `tool_input`, `toolInput`, `input`, or `arguments`.
-
-The three lifecycle wrappers enter `scripts/trae-cli-hook.mjs`, a CLI-only
-adapter that uses the fixed `trae-cli` client id and `trcli-` OpenViking
-session prefix. It intentionally does not carry the TRAE / TRAE CN `tr-` and
-`trcn-` branches.
-
-If TRAE CLI uses different field names, adapt `scripts/trae-cli-hook.mjs` or
-the local text cleanup / turn parsing in `scripts/trae-cli-turns.mjs`. The
-shared OpenViking runtime and MCP proxy can remain unchanged.
-
-## User-Level Install Shape
-
-An installer should render `hooks/hooks.json` by replacing
-`__OPENVIKING_TRAE_CLI_ROOT__` with this directory's absolute path, then merge
-the rendered hooks into the current `TRAECLI_HOME/hooks.json`. In the common
-local setup this is:
-
-```text
-~/.trae/cli/hooks.json
-```
-
-TRAE CLI also supports hooks in the active `traecli.toml` under `[hooks]`, but
-the source shown by the TUI `/hooks` command is the source of truth. Prefer the
-user-level hooks file when installing this integration so the setup is not tied
-to one workspace.
-
-MCP should be added to the active `traecli.toml` under
-`[mcp_servers."openviking-memory"]`. Project-level MCP files such as
-`<workspace>/.trae/.mcp.json` or `<workspace>/.trae/mcp.json` are supported by
-TRAE CLI, but they are not the recommended target for this integration. Confirm
-the effective MCP source with `/mcp` or `traecli mcp list`.
-
-If an existing OpenViking TRAE hook set is already installed, replace or disable
-the old OpenViking entries rather than adding this draft beside them. Running
-both will duplicate recall and capture.
-
-The installer validates the installed hook entrypoints and MCP configuration.
-Use `/hooks`, `/mcp`, or `traecli mcp list` to inspect the effective runtime
-configuration.
diff --git a/examples/trae-cli-memory-hooks/hooks/hooks.json b/examples/trae-cli-memory-hooks/hooks/hooks.json
deleted file mode 100644
index 797e1c08c..000000000
--- a/examples/trae-cli-memory-hooks/hooks/hooks.json
+++ /dev/null
@@ -1,52 +0,0 @@
-{
- "hooks": {
- "SessionStart": [
- {
- "matcher": "clear|startup|resume",
- "hooks": [
- {
- "type": "command",
- "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/session-start.mjs",
- "timeout": 70
- }
- ]
- }
- ],
- "UserPromptSubmit": [
- {
- "matcher": "*",
- "hooks": [
- {
- "type": "command",
- "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/auto-recall.mjs",
- "timeout": 130
- }
- ]
- }
- ],
- "Stop": [
- {
- "matcher": "*",
- "hooks": [
- {
- "type": "command",
- "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/auto-capture.mjs",
- "timeout": 30
- }
- ]
- }
- ],
- "PreToolUse": [
- {
- "matcher": "Read|Glob|Grep|Bash|RunCommand|Shell",
- "hooks": [
- {
- "type": "command",
- "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/uri-guard.mjs",
- "timeout": 5
- }
- ]
- }
- ]
- }
-}
diff --git a/examples/trae-cli-memory-hooks/openviking.integration.json b/examples/trae-cli-memory-hooks/openviking.integration.json
deleted file mode 100644
index 87fdb9bba..000000000
--- a/examples/trae-cli-memory-hooks/openviking.integration.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "schemaVersion": 1,
- "id": "openviking-memory",
- "version": "0.1.0",
- "deprecated": true,
- "replacement": "examples/codex-memory-plugin (install through the trae-cli Codex-format alias)",
- "clients": ["trae-cli"],
- "capabilities": ["hooks", "mcp"]
-}
diff --git a/examples/trae-cli-memory-hooks/scripts/auto-capture.mjs b/examples/trae-cli-memory-hooks/scripts/auto-capture.mjs
deleted file mode 100755
index 3186f7e11..000000000
--- a/examples/trae-cli-memory-hooks/scripts/auto-capture.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "stop";
-await import("./trae-cli-hook.mjs");
diff --git a/examples/trae-cli-memory-hooks/scripts/auto-recall.mjs b/examples/trae-cli-memory-hooks/scripts/auto-recall.mjs
deleted file mode 100755
index d39cdae78..000000000
--- a/examples/trae-cli-memory-hooks/scripts/auto-recall.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "user-prompt-submit";
-await import("./trae-cli-hook.mjs");
diff --git a/examples/trae-cli-memory-hooks/scripts/session-start.mjs b/examples/trae-cli-memory-hooks/scripts/session-start.mjs
deleted file mode 100755
index cffb6b07b..000000000
--- a/examples/trae-cli-memory-hooks/scripts/session-start.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "session-start";
-await import("./trae-cli-hook.mjs");
diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjs
deleted file mode 100644
index 6e1a1997e..000000000
--- a/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjs
+++ /dev/null
@@ -1,142 +0,0 @@
-#!/usr/bin/env node
-
-import {
- addAgentMessages,
- buildAgentProfile,
- commitAgentSession,
- createAgentLogger,
- deriveAgentSessionId,
- loadAgentHookConfig,
- makeAgentFetchJSON,
- readHookInput,
- readHookState,
- recallForPrompt,
- replayAgentPending,
- resolveAgentCwd,
- resolveNativeSessionId,
- shouldBypassAgent,
- stableHash,
- withAgentHookLock,
- writeHookState,
-} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { buildTraeCliTurns, resolveTraeCliPrompt } from "./trae-cli-turns.mjs";
-
-const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
-const clientId = "trae-cli";
-const prefix = "trcli-";
-const cfg = loadAgentHookConfig(clientId);
-const { log, logError } = createAgentLogger(clientId, eventName, cfg);
-
-function output(value = {}) {
- process.stdout.write(`${JSON.stringify(value)}\n`);
-}
-
-function emitLifecycleOutput(additionalContext = "") {
- const value = {};
- if (additionalContext) {
- value.hookSpecificOutput = {
- hookEventName: eventName === "session-start" ? "SessionStart" : "UserPromptSubmit",
- additionalContext,
- };
- }
- output(value);
-}
-
-const input = await readHookInput();
-const nativeSessionId = resolveNativeSessionId(input);
-const sessionId = deriveAgentSessionId(prefix, input);
-const cwd = resolveAgentCwd(input);
-const { fetchJSON } = makeAgentFetchJSON(cfg, cwd);
-
-async function main() {
- if (!cfg.enabled || shouldBypassAgent(cfg, input)) { emitLifecycleOutput(); return; }
- let state = await readHookState(clientId, nativeSessionId);
-
- if (eventName === "session-start") {
- const profile = await withAgentHookLock(clientId, nativeSessionId, async () => {
- state = await readHookState(clientId, nativeSessionId);
- const now = Date.now();
- if (now - Number(state.lastSessionStartAt || 0) < 2000) return null;
- state = { ...state, lastSessionStartAt: now };
- await writeHookState(clientId, nativeSessionId, state);
- await replayAgentPending(fetchJSON, log).catch((error) => logError("pending", error));
- return buildAgentProfile(fetchJSON, cfg, cwd).catch((error) => {
- logError("profile", error);
- return null;
- });
- });
- emitLifecycleOutput(profile ? `<openviking-context source="session-start">\n${profile}\n</openviking-context>` : "");
- return;
- }
-
- if (eventName === "user-prompt-submit") {
- const prompt = resolveTraeCliPrompt(input);
- if (!prompt) { emitLifecycleOutput(); return; }
- const recallBlock = await withAgentHookLock(clientId, nativeSessionId, async () => {
- state = await readHookState(clientId, 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, { sessionId }).catch((error) => {
- logError("recall", error);
- return null;
- });
- await writeHookState(clientId, nativeSessionId, {
- ...state,
- promptHash,
- promptEventId,
- promptAt: now,
- recallBlock: block,
- pendingPrompt: { prompt, hash: promptHash, at: now },
- });
- return block;
- });
- emitLifecycleOutput(recallBlock || "");
- return;
- }
-
- if (eventName === "stop") {
- if (!cfg.autoCapture) { emitLifecycleOutput(); return; }
- await withAgentHookLock(clientId, nativeSessionId, async () => {
- state = await readHookState(clientId, nativeSessionId);
- const hashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
- const turnKey = state.pendingPrompt?.at || state.lastTurnKey || state.promptHash || "unknown-turn";
- const toSend = [];
- for (const turn of buildTraeCliTurns(input, state)) {
- const hash = stableHash(turnKey, turn.role, turn.content);
- if (hashes.has(hash)) continue;
- toSend.push({ hash, turn });
- }
- const result = await addAgentMessages(fetchJSON, sessionId, toSend.map((item) => item.turn));
- const captured = result.sent + result.queued;
- for (const item of toSend.slice(0, captured)) hashes.add(item.hash);
- let nextCount = Number(state.capturedSinceCommit || 0) + captured;
- if (captured > 0) {
- const committed = await commitAgentSession(fetchJSON, sessionId, log);
- if (committed.ok) nextCount = 0;
- }
- await writeHookState(clientId, nativeSessionId, {
- ...state,
- capturedHashes: [...hashes].slice(-1000),
- capturedSinceCommit: nextCount,
- pendingPrompt: null,
- lastTurnKey: turnKey,
- });
- });
- emitLifecycleOutput();
- return;
- }
-
- emitLifecycleOutput();
-}
-
-main().catch((error) => {
- logError("uncaught", error);
- emitLifecycleOutput();
-});
diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs
deleted file mode 100644
index 4b3b0ba21..000000000
--- a/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs
+++ /dev/null
@@ -1,102 +0,0 @@
-import assert from "node:assert/strict";
-import { spawn } from "node:child_process";
-import { createServer } from "node:http";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import test from "node:test";
-
-import { buildTraeCliTurns } from "./trae-cli-turns.mjs";
-
-const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
-
-function runHook(entrypoint, input, env) {
- return new Promise((resolveRun, reject) => {
- const child = spawn(process.execPath, [join(pluginRoot, "scripts", entrypoint)], {
- env: { ...process.env, ...env },
- stdio: ["pipe", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => { stdout += chunk; });
- child.stderr.on("data", (chunk) => { stderr += chunk; });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code !== 0) reject(new Error(stderr || `hook exited ${code}`));
- else resolveRun(JSON.parse(stdout.trim() || "{}"));
- });
- child.stdin.end(JSON.stringify(input));
- });
-}
-
-test("TRAE CLI turn parsing supports every documented prompt and response alias", () => {
- const promptFields = ["prompt", "user_prompt", "userPrompt", "message", "text"];
- const responseFields = [
- "last_assistant_message",
- "lastAssistantMessage",
- "assistant_message",
- "assistantMessage",
- "response",
- "output",
- "text_content",
- ];
-
- for (const field of promptFields) {
- assert.deepEqual(buildTraeCliTurns({ [field]: "user question", last_assistant_message: "assistant answer" }), [
- { role: "user", content: "user question" },
- { role: "assistant", content: "assistant answer" },
- ], `prompt field ${field}`);
- }
- for (const field of responseFields) {
- assert.deepEqual(buildTraeCliTurns({ prompt: "user question", [field]: "assistant answer" }), [
- { role: "user", content: "user question" },
- { role: "assistant", content: "assistant answer" },
- ], `response field ${field}`);
- }
-});
-
-test("TRAE CLI lifecycle hooks recall and capture message/output payloads", async () => {
- const messages = [];
- const server = createServer((request, response) => {
- let body = "";
- request.on("data", (chunk) => { body += chunk; });
- request.on("end", () => {
- if (request.url === "/api/v1/search/search" || request.url === "/api/v1/search/recall") {
- response.end(JSON.stringify({ result: { rendered: "TRAE CLI memory", entries: [], stats: {} } }));
- } else if (request.url?.includes("/messages")) {
- const parsed = JSON.parse(body);
- messages.push(...(parsed.messages ?? [parsed]));
- response.end(JSON.stringify({ result: { ok: true } }));
- } else {
- response.end(JSON.stringify({ result: { ok: true } }));
- }
- });
- });
- await new Promise((resolveListen) => server.listen(0, "127.0.0.1", resolveListen));
- const home = mkdtempSync(join(tmpdir(), "openviking-trae-cli-hooks-"));
- const env = {
- HOME: home,
- OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,
- OPENVIKING_HOOK_STATE_DIR: join(home, "state"),
- OPENVIKING_MEMORY_ENABLED: "1",
- };
- try {
- const base = { session_id: "same-session", cwd: "/workspace" };
- const recalled = await runHook("auto-recall.mjs", {
- ...base,
- message: "remember this TRAE CLI question",
- generation_id: "prompt-1",
- }, env);
- assert.match(recalled.hookSpecificOutput?.additionalContext || "", /TRAE CLI memory/);
-
- await runHook("auto-capture.mjs", { ...base, output: "TRAE CLI answer" }, env);
- assert.deepEqual(messages.map((message) => message.content), [
- "remember this TRAE CLI question",
- "TRAE CLI answer",
- ]);
- } finally {
- await new Promise((resolveClose) => server.close(resolveClose));
- rmSync(home, { recursive: true, force: true });
- }
-});
diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjs
deleted file mode 100644
index b210b33b4..000000000
--- a/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjs
+++ /dev/null
@@ -1,37 +0,0 @@
-export function cleanTraeCliText(value) {
- return String(value || "")
- .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, "")
- .replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/gi, "")
- .trim();
-}
-
-function firstTraeCliText(input, fields) {
- for (const field of fields) {
- const text = cleanTraeCliText(input?.[field]);
- if (text) return text;
- }
- return "";
-}
-
-export function resolveTraeCliPrompt(input = {}) {
- return firstTraeCliText(input, ["prompt", "user_prompt", "userPrompt", "message", "text"]);
-}
-
-export function resolveTraeCliResponse(input = {}) {
- return firstTraeCliText(input, [
- "last_assistant_message",
- "lastAssistantMessage",
- "assistant_message",
- "assistantMessage",
- "response",
- "output",
- "text_content",
- ]);
-}
-
-export function buildTraeCliTurns(input = {}, state = {}) {
- return [
- { role: "user", content: resolveTraeCliPrompt(input) || cleanTraeCliText(state.pendingPrompt?.prompt) },
- { role: "assistant", content: resolveTraeCliResponse(input) },
- ].filter((turn) => turn.content);
-}
diff --git a/examples/trae-cli-memory-hooks/scripts/uri-guard.mjs b/examples/trae-cli-memory-hooks/scripts/uri-guard.mjs
deleted file mode 100755
index d30850b7a..000000000
--- a/examples/trae-cli-memory-hooks/scripts/uri-guard.mjs
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env node
-
-import { readFileSync, realpathSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import {
- evaluateAgentUriGuard,
-} from "../../memory-plugin-shared/lib/agent-uri-guard.mjs";
-
-function readInput() {
- try {
- const raw = readFileSync(0, "utf8").trim();
- return raw ? JSON.parse(raw) : {};
- } catch {
- return {};
- }
-}
-
-export function evaluateTraeCliUriGuard(input = {}) {
- const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;
- const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? input.arguments ?? {};
- 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 = evaluateTraeCliUriGuard(readInput());
- if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);
-}
diff --git a/examples/trae-memory-hooks/.mcp.json b/examples/trae-memory-hooks/.mcp.json
deleted file mode 100644
index 5e54185bc..000000000
--- a/examples/trae-memory-hooks/.mcp.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "mcpServers": {
- "openviking": {
- "command": "node",
- "args": ["servers/mcp-proxy.mjs"]
- }
- }
-}
diff --git a/examples/trae-memory-hooks/README.md b/examples/trae-memory-hooks/README.md
deleted file mode 100644
index 298998f1d..000000000
--- a/examples/trae-memory-hooks/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# OpenViking Memory Hooks for TRAE
-
-This package provides dedicated TRAE and TRAE CN lifecycle adapters. It does not reuse Claude Code transcript parsing: TRAE capture reads `prompt`, `text_content`, and `last_assistant_message` from the `Stop` event and stores sessions with `tr-` or `trcn-` prefixes.
-
-Its `PreToolUse` guard prevents `viking://` virtual paths from being passed to local file or shell tools and points the Agent back to OpenViking MCP tools.
-
-Use the shared installer:
-
-```bash
-bash examples/memory-plugin-shared/install.sh --harness trae,trae-cn
-```
-
-See the [TRAE integration guide](../../docs/en/agent-integrations/13-trae.md).
diff --git a/examples/trae-memory-hooks/openviking.integration.json b/examples/trae-memory-hooks/openviking.integration.json
deleted file mode 100644
index b1a3a2190..000000000
--- a/examples/trae-memory-hooks/openviking.integration.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "schemaVersion": 1,
- "id": "openviking-memory",
- "version": "0.1.3",
- "clients": ["trae", "trae-cn"],
- "capabilities": ["hooks", "mcp"]
-}
diff --git a/examples/trae-memory-hooks/scripts/auto-capture.mjs b/examples/trae-memory-hooks/scripts/auto-capture.mjs
deleted file mode 100644
index a72c82f79..000000000
--- a/examples/trae-memory-hooks/scripts/auto-capture.mjs
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "stop";
-process.env.OPENVIKING_HOOK_SOURCE ||= process.argv[2] || "trae";
-await import("./trae-hook.mjs");
diff --git a/examples/trae-memory-hooks/scripts/auto-recall.mjs b/examples/trae-memory-hooks/scripts/auto-recall.mjs
deleted file mode 100644
index c3057a8d9..000000000
--- a/examples/trae-memory-hooks/scripts/auto-recall.mjs
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "user-prompt-submit";
-process.env.OPENVIKING_HOOK_SOURCE ||= process.argv[2] || "trae";
-await import("./trae-hook.mjs");
diff --git a/examples/trae-memory-hooks/scripts/session-start.mjs b/examples/trae-memory-hooks/scripts/session-start.mjs
deleted file mode 100644
index ce6b993a3..000000000
--- a/examples/trae-memory-hooks/scripts/session-start.mjs
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/usr/bin/env node
-
-process.env.OPENVIKING_HOOK_EVENT = "session-start";
-process.env.OPENVIKING_HOOK_SOURCE ||= process.argv[2] || "trae";
-await import("./trae-hook.mjs");
diff --git a/examples/trae-memory-hooks/scripts/trae-hook.mjs b/examples/trae-memory-hooks/scripts/trae-hook.mjs
deleted file mode 100644
index 690673ef4..000000000
--- a/examples/trae-memory-hooks/scripts/trae-hook.mjs
+++ /dev/null
@@ -1,143 +0,0 @@
-#!/usr/bin/env node
-
-import {
- addAgentMessages,
- buildAgentProfile,
- commitAgentSession,
- createAgentLogger,
- deriveAgentSessionId,
- loadAgentHookConfig,
- makeAgentFetchJSON,
- readHookInput,
- readHookState,
- recallForPrompt,
- replayAgentPending,
- resolveAgentCwd,
- resolveNativeSessionId,
- shouldBypassAgent,
- stableHash,
- withAgentHookLock,
- writeHookState,
-} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { buildTraeTurns, cleanTraeText } from "./trae-turns.mjs";
-
-const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
-const requestedSource = process.env.OPENVIKING_HOOK_SOURCE || process.argv[3];
-const requestedClient = requestedSource === "trae-cn" ? "trae-cn" : "trae";
-const prefix = requestedClient === "trae-cn" ? "trcn-" : "tr-";
-const cfg = loadAgentHookConfig(requestedClient);
-const { log, logError } = createAgentLogger(requestedClient, eventName, cfg);
-
-function output(value = {}) {
- process.stdout.write(`${JSON.stringify(value)}\n`);
-}
-
-function approve(additionalContext = "") {
- const value = { decision: "approve" };
- if (additionalContext) {
- value.hookSpecificOutput = {
- hookEventName: eventName === "session-start" ? "SessionStart" : "UserPromptSubmit",
- additionalContext,
- };
- }
- output(value);
-}
-
-const input = await readHookInput();
-const nativeSessionId = resolveNativeSessionId(input);
-const sessionId = deriveAgentSessionId(prefix, input);
-const cwd = resolveAgentCwd(input);
-const { fetchJSON } = makeAgentFetchJSON(cfg, cwd);
-
-async function main() {
- if (!cfg.enabled || shouldBypassAgent(cfg, input)) { approve(); return; }
- let state = await readHookState(requestedClient, nativeSessionId);
-
- if (eventName === "session-start") {
- const profile = await withAgentHookLock(requestedClient, nativeSessionId, async () => {
- state = await readHookState(requestedClient, nativeSessionId);
- const now = Date.now();
- if (now - Number(state.lastSessionStartAt || 0) < 2000) return null;
- state = { ...state, lastSessionStartAt: now };
- await writeHookState(requestedClient, nativeSessionId, state);
- await replayAgentPending(fetchJSON, log).catch((error) => logError("pending", error));
- return buildAgentProfile(fetchJSON, cfg, cwd).catch((error) => {
- logError("profile", error);
- return null;
- });
- });
- approve(profile ? `<openviking-context source="session-start">\n${profile}\n</openviking-context>` : "");
- return;
- }
-
- if (eventName === "user-prompt-submit") {
- const prompt = cleanTraeText(input.prompt);
- if (!prompt) { approve(); return; }
- const recallBlock = await withAgentHookLock(requestedClient, nativeSessionId, async () => {
- state = await readHookState(requestedClient, 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, { sessionId }).catch((error) => {
- logError("recall", error);
- return null;
- });
- await writeHookState(requestedClient, nativeSessionId, {
- ...state,
- promptHash,
- promptEventId,
- promptAt: now,
- recallBlock: block,
- pendingPrompt: { prompt, hash: promptHash, at: now },
- });
- return block;
- });
- approve(recallBlock || "");
- return;
- }
-
- if (eventName === "stop") {
- if (!cfg.autoCapture) { approve(); return; }
- await withAgentHookLock(requestedClient, nativeSessionId, async () => {
- state = await readHookState(requestedClient, nativeSessionId);
- const hashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);
- const turnKey = state.pendingPrompt?.at || state.lastTurnKey || state.promptHash || "unknown-turn";
- const toSend = [];
- for (const turn of buildTraeTurns(input, state)) {
- const hash = stableHash(turnKey, turn.role, turn.content);
- if (hashes.has(hash)) continue;
- toSend.push({ hash, turn });
- }
- const result = await addAgentMessages(fetchJSON, sessionId, toSend.map((item) => item.turn));
- const captured = result.sent + result.queued;
- for (const item of toSend.slice(0, captured)) hashes.add(item.hash);
- let nextCount = Number(state.capturedSinceCommit || 0) + captured;
- if (captured > 0) {
- const committed = await commitAgentSession(fetchJSON, sessionId, log);
- if (committed.ok) nextCount = 0;
- }
- await writeHookState(requestedClient, nativeSessionId, {
- ...state,
- capturedHashes: [...hashes].slice(-1000),
- capturedSinceCommit: nextCount,
- pendingPrompt: null,
- lastTurnKey: turnKey,
- });
- });
- approve();
- return;
- }
-
- approve();
-}
-
-main().catch((error) => {
- logError("uncaught", error);
- approve();
-});
diff --git a/examples/trae-memory-hooks/scripts/uri-guard.mjs b/examples/trae-memory-hooks/scripts/uri-guard.mjs
deleted file mode 100644
index b07785833..000000000
--- a/examples/trae-memory-hooks/scripts/uri-guard.mjs
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env node
-
-import { readFileSync, realpathSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import {
- evaluateAgentUriGuard,
-} from "../../memory-plugin-shared/lib/agent-uri-guard.mjs";
-
-function readInput() {
- try {
- const raw = readFileSync(0, "utf8").trim();
- return raw ? JSON.parse(raw) : {};
- } catch {
- return {};
- }
-}
-
-export function evaluateTraeUriGuard(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 = evaluateTraeUriGuard(readInput());
- if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);
-}
diff --git a/examples/trae-memory-hooks/servers/mcp-proxy.mjs b/examples/trae-memory-hooks/servers/mcp-proxy.mjs
deleted file mode 100644
index 4e5016a82..000000000
--- a/examples/trae-memory-hooks/servers/mcp-proxy.mjs
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/usr/bin/env node
-
-import { fileURLToPath } from "node:url";
-import { resolve as resolvePath } from "node:path";
-
-import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";
-import { createLogger } from "../../memory-plugin-shared/lib/debug-log.mjs";
-import { createOpenVikingMcpProxy } from "../../memory-plugin-shared/lib/mcp-proxy-core.mjs";
-
-function readConfig() {
- const clientId = process.env.OPENVIKING_HOOK_SOURCE === "trae-cn" ? "trae-cn" : "trae";
- const cfg = loadAgentHookConfig(clientId);
- 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();
-}
diff --git a/examples/zcode-memory-plugin/README.md b/examples/zcode-memory-plugin/README.md
deleted file mode 100644
index a2f5d113f..000000000
--- a/examples/zcode-memory-plugin/README.md
+++ /dev/null
@@ -1,40 +0,0 @@
-# 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.
-
-> **Requires an OpenViking server with `viking://~` home-alias support.** Recall targets the
-> caller's own context space through `viking://~/memories` and `viking://~/skills`; the uid-less
-> `viking://user/memories` shorthand is rejected by newer servers.
-
-## 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** — returns immediately, then captures incremental user/assistant turns and commits the OpenViking session in a detached worker.
-
-ZCode does not support `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`, so the commit-on-`Stop` strategy compensates for the absence of compact/end-of-session signals. The rollout file is the authoritative incremental transcript: stable host `turnId` values drive deduplication and allow a later Stop to recover missed turns. Hook stdin is only a fallback when the rollout file is unavailable.
-
-> Invariant: hook groups must OMIT the matcher key rather than writing `"matcher": ""`. Strict parsers treat an empty string as invalid and may silently drop the entire configuration source.
-
-## 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; three thin shim scripts set an environment variable and import the dispatcher, while the URI guard has its own entry point. Shared runtime modules provide recall, batching, pending queue, credential resolution, and MCP proxying; `zcode-capture.mjs` owns the ZCode-specific acknowledgement and cursor state transition.
-
-See [DESIGN.md](./DESIGN.md) for verified ZCode extension-surface facts and decision provenance.
-
-## Tests
-
-```bash
-node --test scripts/*.test.mjs
-```
diff --git a/examples/zcode-memory-plugin/README_CN.md b/examples/zcode-memory-plugin/README_CN.md
deleted file mode 100644
index 40381da9d..000000000
--- a/examples/zcode-memory-plugin/README_CN.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# OpenViking ZCode 记忆插件
-
-本包为 ZCode 提供 OpenViking 长期记忆的生命周期适配器。复用 `memory-plugin-shared` 共享运行时——不重复任何记忆逻辑,仅新增一个 ZCode 薄适配层。
-
-## 功能
-
-- **SessionStart** — 注入用户画像和偏好/实体到上下文。
-- **UserPromptSubmit** — 搜索 OpenViking 相关记忆并注入。
-- **PreToolUse**(`Read|Glob|Grep`)— 拦截 `viking://` 虚拟路径的直接访问,引导使用 MCP 工具。
-- **Stop** — 立即返回,并在 detached worker 中捕获增量用户/助手对话、提交 OpenViking 会话。
-
-ZCode 不支持 `PreCompact`/`SessionEnd`/`SubagentStart`/`SubagentStop`,因此通过 Stop 时 commit 补足 compact/会话结束信号。Rollout 文件是权威增量对话源:稳定的 host `turnId` 用于去重,也让后续 Stop 能恢复漏掉的回合;只有 rollout 文件不可用时才回退到 Hook stdin。
-
-## 安装
-
-使用共享安装脚本:
-
-```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 设置环境变量并导入调度器,URI guard 使用独立入口。共享运行时提供召回、批量写入、待处理队列、凭据解析和 MCP 代理;`zcode-capture.mjs` 负责 ZCode 特有的确认与游标状态转换。
-
-详见 [DESIGN.md](./DESIGN.md) 了解已验证的 ZCode 扩展面事实和设计决策来源。
-
-## 测试
-
-```bash
-node --test scripts/*.test.mjs
-```
diff --git a/examples/zcode-memory-plugin/openviking.integration.json b/examples/zcode-memory-plugin/openviking.integration.json
deleted file mode 100644
index 5bd99e47a..000000000
--- a/examples/zcode-memory-plugin/openviking.integration.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "schemaVersion": 1,
- "id": "openviking-memory",
- "version": "0.1.2",
- "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
deleted file mode 100644
index b753af31b..000000000
--- a/examples/zcode-memory-plugin/scripts/auto-capture.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/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
deleted file mode 100644
index d9cc9c2ed..000000000
--- a/examples/zcode-memory-plugin/scripts/auto-recall.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/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
deleted file mode 100644
index 6c8bb3c5b..000000000
--- a/examples/zcode-memory-plugin/scripts/session-start.mjs
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/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
deleted file mode 100644
index 6c4a984c1..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/agent-hook-runtime.mjs
+++ /dev/null
@@ -1,264 +0,0 @@
-// 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 { isRetryableFailure } from "./retryable.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, "-");
-}
-
-function responseTraceId(body) {
- return body?.result?.trace_id || body?.error?.trace_id || body?.trace_id || undefined;
-}
-
-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", 10, 1),
- recallLimitConfigured: Boolean(process.env.OPENVIKING_RECALL_LIMIT),
- 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),
- writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC", true),
- 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 timeoutMs = Math.max(1000, Number(options.timeoutMs) || cfg.timeoutMs);
- const timer = setTimeout(() => controller.abort(), 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(() => ({}));
- const traceId = responseTraceId(body);
- if (!response.ok || body.status === "error") {
- return { ok: false, status: response.status, error: body.error || body, traceId };
- }
- return { ok: true, result: body.result ?? body, traceId };
- } catch (error) {
- return { ok: false, status: 0, error: { message: error?.message || String(error) } };
- } finally {
- clearTimeout(timer);
- }
- };
- return { fetchJSON, effectivePeer };
-}
-
-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 && isRetryableFailure(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, log = () => {}) {
- const result = await fetchJSON(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
- method: "POST",
- body: "{}",
- });
- let queued = false;
- if (!result.ok && isRetryableFailure(result)) {
- const pending = await enqueue("commitSession", sessionId, {});
- queued = Boolean(pending.ok);
- }
- log("commit", {
- sessionId,
- ok: result.ok,
- status: result.result?.status || result.status,
- trace_id: result.traceId || result.result?.trace_id,
- queued,
- error: result.ok ? undefined : result.error?.message || result.error?.code,
- });
- return result;
-}
-
-export async function replayAgentPending(fetchJSON, log = () => {}) {
- return replayPending(fetchJSON, log);
-}
-
-export async function recallForPrompt(fetchJSON, cfg, prompt, cwd, log = () => {}, options = {}) {
- if (!cfg.autoRecall || !String(prompt || "").trim()) return null;
- const peer = resolveEffectivePeerId({ cfg, cwd });
- return buildRecallBlock(fetchJSON, cfg, prompt, {
- actorPeerId: peer.peerId,
- legacyPeerId: peer.legacyPeerId,
- // Passing the OV session id is what turns on server-side query expansion
- // and the cross-turn dedup ledger for these thin harnesses.
- sessionId: options.sessionId || "",
- 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
deleted file mode 100644
index d0dada027..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/agent-uri-guard.mjs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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
deleted file mode 100644
index 8ffc71468..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/async-writer.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Async write-path helper for hook-based memory plugins.
- *
- * When `cfg.writePathAsync` is true and we're not already the worker, we:
- * 1. Drain the parent's stdin (the hook payload)
- * 2. Emit the harness-specific approve/no-op response on stdout immediately
- * 3. Spawn a detached clone of ourselves with env OV_HOOK_WORKER=1
- * 4. Feed the drained payload to the worker's stdin, unref, and exit
- *
- * The worker re-enters the same script, maybeDetach returns false (because
- * OV_HOOK_WORKER=1), and the hook's normal synchronous code path reads its
- * own stdin and runs the OV HTTP work with nobody waiting.
- *
- * Call this BEFORE the hook reads stdin itself. When it returns true, the
- * caller must `return` out of main() immediately.
- */
-
-import { spawn } from "node:child_process";
-
-const WORKER_ENV = "OV_HOOK_WORKER";
-
-export async function maybeDetach(cfg, { approve }) {
- if (!cfg.writePathAsync) return false;
- if (process.env[WORKER_ENV] === "1") return false;
-
- // Drain parent stdin so we can forward to the worker.
- let raw;
- try {
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- raw = Buffer.concat(chunks);
- } catch {
- // stdin read failed - let the synchronous path handle it.
- return false;
- }
-
- let child;
- try {
- child = spawn(process.execPath, [process.argv[1]], {
- detached: true,
- stdio: ["pipe", "ignore", "ignore"],
- env: { ...process.env, [WORKER_ENV]: "1" },
- });
- } catch {
- // spawn failed - fall through to sync mode, but we've already drained
- // stdin so hand the payload back via env var path below.
- process.env.OPENVIKING_HOOK_STDIN_CACHE = raw.toString();
- return false;
- }
-
- // Approve first, then write to the detached child. Ordering matters for
- // harnesses that read stdout before waiting for the hook process to exit.
- approve();
-
- try {
- child.stdin.write(raw);
- child.stdin.end();
- } catch { /* worker may have already exited; nothing useful to recover */ }
- child.unref();
- return true;
-}
-
-/**
- * Fallback stdin reader used when the async path drained stdin but spawn
- * failed; hooks should call this instead of reading stdin directly when
- * possible so the sync fallback still works after a failed detach.
- */
-export async function readHookStdin() {
- if (process.env.OPENVIKING_HOOK_STDIN_CACHE) {
- const cached = process.env.OPENVIKING_HOOK_STDIN_CACHE;
- delete process.env.OPENVIKING_HOOK_STDIN_CACHE;
- return cached;
- }
- const chunks = [];
- for await (const chunk of process.stdin) chunks.push(chunk);
- return Buffer.concat(chunks).toString();
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/batch-send.mjs b/examples/zcode-memory-plugin/scripts/shared/batch-send.mjs
deleted file mode 100644
index d7ec355cc..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/batch-send.mjs
+++ /dev/null
@@ -1,121 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { enqueue } from "./pending-queue.mjs";
-import { isRetryableFailure } from "./retryable.mjs";
-
-export const BATCH_LIMIT = 100;
-
-export function isRetryableSendFailure(res) {
- return isRetryableFailure(res);
-}
-
-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
deleted file mode 100644
index 22bc1b63c..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
+++ /dev/null
@@ -1,578 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { applyInputFilters, compileInputFilters } from "./input-filters.mjs";
-
-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",
-]);
-
-// Tool output is reported verbatim; the server owns truncation via
-// tool_output_externalization (threshold_chars, default 20000). This cap only
-// guards against pathological payloads.
-const DEFAULT_TOOL_MAX_CHARS = 1000000;
-
-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?.tool ||
- block?.function?.name ||
- block?.call?.name ||
- "",
- );
-}
-
-function toolPayload(block, kind) {
- if (!block || typeof block !== "object") return "";
- if (kind === "call") {
- return block.input ??
- block.state?.input ??
- block.arguments ??
- block.args ??
- block.params ??
- block.function?.arguments ??
- block.command ??
- block.call?.input ??
- block.call?.arguments ??
- "";
- }
- return block.output ??
- block.state?.output ??
- block.result ??
- block.error ??
- block.state?.error ??
- block.data ??
- block.content ??
- block.text ??
- "";
-}
-
-function toolId(block) {
- return oneLine(
- block?.call_id ||
- block?.callId ||
- 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?.isError || block?.state?.isError || block?.error || block?.state?.error) return "error";
- const status = oneLine(block?.status || block?.state?.status || "");
- return status || "completed";
-}
-
-function setToolInput(part, payload) {
- const input = parseMaybeJson(payload);
- if (input === "" || input == null) return;
- part.tool_input = typeof input === "object" && !Array.isArray(input)
- ? input
- : { value: input };
-}
-
-function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, 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") {
- setToolInput(part, payload);
- } else {
- if (block?.state?.input !== undefined) {
- setToolInput(part, block.state.input);
- }
- 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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, ...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: DEFAULT_TOOL_MAX_CHARS, 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: DEFAULT_TOOL_MAX_CHARS, 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;
-}
-
-/**
- * Prune blank text parts and run `cfg.captureFilters` over the ones that remain.
- *
- * One drop verdict is taken per turn, on the aggregate of its text parts; the
- * individual parts are then rewritten with the substitutions only, so a rule can
- * never both keep and drop the same turn. Tool call/result parts are carried
- * through untouched — filters match conversation text, not tool payloads — but a
- * turn dropped on its text takes its tool parts with it.
- */
-export function filterCaptureParts(parts, role, cfg = {}) {
- const kept = [];
- for (const part of parts || []) {
- if (!part) continue;
- if (part.type !== "text") {
- kept.push(part);
- continue;
- }
- const text = typeof part.text === "string" ? part.text.trim() : "";
- if (!text) continue;
- kept.push(text === part.text ? part : { ...part, text });
- }
-
- const blank = { parts: kept, dropped: false };
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (!compiled.rules.length || kept.length === 0) return blank;
-
- const textParts = kept.filter((part) => part.type === "text");
- if (textParts.length === 0) return blank;
-
- const verdict = applyInputFilters(textParts.map((part) => part.text).join("\n\n"), compiled.rules, {
- role,
- });
- if (verdict.dropped) return { parts: [], dropped: true };
-
- const out = [];
- for (const part of kept) {
- if (part.type !== "text") {
- out.push(part);
- continue;
- }
- const shaped = applyInputFilters(part.text, compiled.rules, { role, substituteOnly: true });
- if (!shaped.text) continue;
- out.push(shaped.text === part.text ? part : { ...part, text: shaped.text });
- }
- return { parts: out, dropped: out.length === 0 };
-}
-
-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 shaped = filterCaptureParts(parts, role, cfg);
- if (shaped.dropped) continue;
- // With parts on the wire the drop decision was already taken above, so the
- // text path only runs the filters for the `content` fallback. That also
- // keeps `turn.text` faithful for callers that scan it for trigger words.
- const decision = shouldCaptureText(rawText, role, cfg, { filters: shaped.parts.length === 0 });
- if (!decision.shouldCapture && shaped.parts.length === 0) continue;
- const text = decision.shouldCapture ? decision.text : "";
- turns.push({ role, text, parts: shaped.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 = {}, { filters = true } = {}) {
- const maxLength = cfg.captureMaxLength || 24000;
- const sanitized = sanitizeCapturedText(text);
- if (!sanitized) return { shouldCapture: false, reason: "empty", text: "" };
-
- let capped = truncateCaptureText(sanitized, maxLength);
- if (filters) {
- const compiled = compileInputFilters(cfg?.captureFilters);
- if (compiled.rules.length) {
- const verdict = applyInputFilters(capped, compiled.rules, { role });
- if (verdict.dropped) return { shouldCapture: false, reason: "filtered", text: "" };
- capped = verdict.text;
- if (!capped) return { shouldCapture: false, reason: "empty", text: "" };
- }
- }
- 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
deleted file mode 100644
index ba26a84dc..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/credentials.mjs
+++ /dev/null
@@ -1,239 +0,0 @@
-// 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`;
-
- // The file that actually supplied the api_key, following the same chain —
- // empty when the key came from the environment or was never found.
- let credentialPath = "";
- if (apiKey) {
- if (useCli) credentialPath = files.cliPath;
- else if (str(env.OPENVIKING_BEARER_TOKEN, str(env.OPENVIKING_API_KEY, ""))) credentialPath = "";
- else if (str(files.cliFile.api_key, "")) credentialPath = files.cliPath;
- else credentialPath = files.ovPath;
- }
-
- return {
- ...files,
- credentialSource: useCli ? "ovcli" : ((mode === "env" || envHasCredentials) ? "env" : "auto"),
- credentialPath,
- 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
deleted file mode 100644
index 73855cf6d..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/debug-log.mjs
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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/input-filters.mjs b/examples/zcode-memory-plugin/scripts/shared/input-filters.mjs
deleted file mode 100644
index e20bb03a7..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/input-filters.mjs
+++ /dev/null
@@ -1,219 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Ordered, operator-configured regex filters for memory plugin input.
- *
- * Rules are sed-style strings, applied in order to a single piece of text:
- * s/^\s*ultrathink\s+//i substitute (add `g` to replace every match)
- * d|^\s*[/!]| drop the text when the pattern matches
- * k/^\?ov\b/ keep the text only when the pattern matches
- * user:d/^\s*\/clear\b/ apply to one role only
- *
- * A malformed rule becomes an entry in `errors` and is skipped rather than
- * throwing, so a typo in a config file cannot take a hook down.
- */
-
-const OPS = new Set(["s", "d", "k"]);
-const SCOPES = ["user", "assistant"];
-const ALLOWED_FLAGS = "imsug";
-
-export const INPUT_FILTER_KNOBS = [
- {
- key: "recallQueryFilters",
- env: "OPENVIKING_RECALL_QUERY_FILTERS",
- label: "recall query filters",
- },
- {
- key: "captureFilters",
- env: "OPENVIKING_CAPTURE_FILTERS",
- label: "capture filters",
- },
-];
-
-/**
- * Read one delimited field. `\` always consumes the next character, and only
- * `\<delim>` is un-escaped, so `\d` / `\b` / `\x2c` reach RegExp verbatim.
- * Returns the index of the closing delimiter, or -1 when it is missing.
- */
-function scanField(source, start, delim) {
- let out = "";
- let i = start;
- while (i < source.length) {
- const c = source[i];
- if (c === "\\") {
- const next = source[i + 1];
- if (next === undefined) {
- out += "\\";
- i += 1;
- continue;
- }
- out += next === delim ? next : "\\" + next;
- i += 2;
- continue;
- }
- if (c === delim) return { value: out, end: i };
- out += c;
- i += 1;
- }
- return { value: out, end: -1 };
-}
-
-export function parseInputFilterRule(source) {
- if (typeof source !== "string") {
- return { source: String(source ?? ""), error: "rule must be a string" };
- }
- const raw = source.trim();
- if (!raw) return { source: raw, error: "rule is empty" };
-
- let scope = "";
- let rest = raw;
- for (const candidate of SCOPES) {
- if (rest.startsWith(`${candidate}:`)) {
- scope = candidate;
- rest = rest.slice(candidate.length + 1);
- break;
- }
- }
-
- const op = rest[0] || "";
- if (!OPS.has(op)) {
- return {
- source: raw,
- error: `unknown operation "${op}" — expected s (substitute), d (drop) or k (keep)`,
- };
- }
- const delim = rest[1];
- if (delim === undefined) {
- return { source: raw, error: `missing delimiter after "${op}"` };
- }
- if (/[A-Za-z0-9\s\\]/.test(delim)) {
- return {
- source: raw,
- error: `invalid delimiter ${JSON.stringify(delim)} — use punctuation such as / | # or :`,
- };
- }
-
- const first = scanField(rest, 2, delim);
- const pattern = first.value;
- let replacement = null;
- let flagsRaw = "";
- if (op === "s") {
- if (first.end < 0) {
- return { source: raw, error: `missing ${JSON.stringify(delim)} after the pattern` };
- }
- const second = scanField(rest, first.end + 1, delim);
- if (second.end < 0) {
- return {
- source: raw,
- error: `missing ${JSON.stringify(delim)} after the replacement — write s${delim}pattern${delim}replacement${delim}`,
- };
- }
- replacement = second.value;
- flagsRaw = rest.slice(second.end + 1);
- } else {
- flagsRaw = first.end < 0 ? "" : rest.slice(first.end + 1);
- }
-
- if (!pattern) return { source: raw, error: "pattern is empty" };
-
- const flags = new Set();
- for (const flag of flagsRaw) {
- if (!ALLOWED_FLAGS.includes(flag)) {
- return { source: raw, error: `unknown flag "${flag}" — allowed flags are i, m, s, u, g` };
- }
- if (flags.has(flag)) return { source: raw, error: `duplicate flag "${flag}"` };
- flags.add(flag);
- }
- // d/k decide with .test(), which advances lastIndex on a global regex and
- // would then alternate between calls. `g` means nothing there, so drop it.
- if (op !== "s") flags.delete("g");
-
- let re;
- try {
- re = new RegExp(pattern, [...flags].join(""));
- } catch (err) {
- // V8 already says "Invalid regular expression: <pattern>: <why>"; keep that
- // detail without stuttering the prefix the doctors key off.
- const message = err?.message || String(err);
- return {
- source: raw,
- error: /^invalid regular expression/i.test(message)
- ? `invalid${message.slice("Invalid".length)}`
- : `invalid regular expression: ${message}`,
- };
- }
-
- return { op, scope, re, replacement, source: raw };
-}
-
-export function compileInputFilters(rules) {
- const compiled = [];
- const errors = [];
- const list = Array.isArray(rules) ? rules : [];
- list.forEach((entry, index) => {
- if (typeof entry !== "string") {
- errors.push({ index, source: String(entry ?? ""), message: "rule must be a string" });
- return;
- }
- if (!entry.trim()) return;
- const parsed = parseInputFilterRule(entry);
- if (parsed.error) errors.push({ index, source: parsed.source, message: parsed.error });
- else compiled.push({ ...parsed, index });
- });
- return { rules: compiled, errors };
-}
-
-/**
- * Run compiled rules over `text`.
- *
- * `substituteOnly` skips the d/k operations, so a caller that already took one
- * drop decision for a turn can rewrite its individual pieces without taking a
- * second, possibly contradictory one.
- */
-export function applyInputFilters(text, compiled, { role = "", substituteOnly = false } = {}) {
- const original = typeof text === "string" ? text : String(text ?? "");
- let current = original;
- for (const rule of Array.isArray(compiled) ? compiled : []) {
- if (rule.scope && rule.scope !== role) continue;
- if (rule.op === "s") {
- current = current.replace(rule.re, rule.replacement);
- continue;
- }
- if (substituteOnly) continue;
- const matched = rule.re.test(current);
- if ((rule.op === "d" && matched) || (rule.op === "k" && !matched)) {
- return { text: "", changed: false, dropped: true, ruleIndex: rule.index, op: rule.op };
- }
- }
- const finalText = current.trim();
- return {
- text: finalText,
- changed: finalText !== original,
- dropped: false,
- ruleIndex: -1,
- op: "",
- };
-}
-
-/** Doctor-facing summary of both filter knobs on a resolved plugin config. */
-export function describeInputFilters(cfg = {}) {
- return INPUT_FILTER_KNOBS.map(({ key, env, label }) => {
- const configured = Array.isArray(cfg?.[key]) ? cfg[key] : [];
- const compiled = compileInputFilters(configured);
- const ops = { s: 0, d: 0, k: 0 };
- for (const rule of compiled.rules) ops[rule.op] += 1;
- const bits = [];
- if (ops.s) bits.push(`${ops.s} substitute`);
- if (ops.d) bits.push(`${ops.d} drop`);
- if (ops.k) bits.push(`${ops.k} keep-only`);
- const active = compiled.rules.length;
- return {
- key,
- env,
- label,
- total: configured.length,
- active,
- summary: `${active} rule${active === 1 ? "" : "s"}${bits.length ? ` (${bits.join(", ")})` : ""}`,
- errors: compiled.errors,
- };
- });
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-config.mjs b/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-config.mjs
deleted file mode 100644
index 24d33d9fb..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-config.mjs
+++ /dev/null
@@ -1,124 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Shared config shaping for the stdio MCP proxy entrypoints.
- *
- * Every harness loads its credentials differently, but the shape
- * `createOpenVikingMcpProxy` consumes is identical everywhere, and so is the
- * set of files whose changes must trigger a credential reload. Keeping that
- * here stops each entrypoint from re-deriving `~` expansion, URL trimming,
- * timeout clamping, and the watch list.
- */
-
-import { homedir } from "node:os";
-import { join, resolve as resolvePath } from "node:path";
-
-export const DEFAULT_PROXY_TIMEOUT_MS = 15000;
-const MIN_PROXY_TIMEOUT_MS = 1000;
-
-export function trimSlash(value) {
- return String(value || "").replace(/\/+$/, "");
-}
-
-/** Expand a leading `~` and resolve to an absolute path; "" stays "". */
-export function normalizeConfigPath(value) {
- const raw = String(value || "").trim();
- if (!raw) return "";
- if (raw === "~") return homedir();
- if (raw.startsWith("~/")) return resolvePath(join(homedir(), raw.slice(2)));
- return resolvePath(raw);
-}
-
-/**
- * The credential files every harness must watch: the two `OPENVIKING_*_FILE`
- * overrides and the two default locations under `~/.openviking`.
- */
-export function defaultCredentialPaths(env = process.env) {
- return [
- normalizeConfigPath(env.OPENVIKING_CLI_CONFIG_FILE),
- normalizeConfigPath(env.OPENVIKING_CONFIG_FILE),
- join(homedir(), ".openviking", "ovcli.conf"),
- join(homedir(), ".openviking", "ov.conf"),
- ].filter(Boolean);
-}
-
-/**
- * Resolve the actor peer header for a long-lived MCP proxy process.
- *
- * MCP servers may start in the plugin directory rather than the active
- * workspace, so their process cwd is not a reliable peer identity — and unlike
- * a hook, a long-lived proxy cannot re-derive one per turn. Broad recall
- * intentionally spans the authenticated user's peer workspaces and therefore
- * leaves the actor header unset. Actor-scoped recall needs an explicit peer so
- * isolation never depends on the proxy's launch directory.
- *
- * A missing one degrades to broad recall with a warning rather than refusing to
- * start: the proxy is what carries every memory tool, and taking those away
- * because a scope preference cannot be honoured costs the user far more than
- * the wider search does. Only the harness whose parent process injects the peer
- * (dsh, `mcp.mjs:27`) can satisfy this without the user setting it.
- */
-export function resolveMcpActorPeerId({
- peerId = "",
- recallPeerScope = "all",
- onWarn = null,
-} = {}) {
- if (recallPeerScope !== "actor") return "";
-
- const explicitPeerId = String(peerId || "").trim();
- if (explicitPeerId) return explicitPeerId;
-
- const message = "OpenViking MCP: actor-scoped recall needs an explicit peer id, which an MCP proxy cannot "
- + "derive from its launch directory. Falling back to broad recall across every peer under this user. "
- + "Set actor_peer_id in ovcli.conf, or OPENVIKING_PEER_ID in the MCP server environment, to scope it.";
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return "";
-}
-
-function uniq(values) {
- return [...new Set(values.filter(Boolean))];
-}
-
-/**
- * Shape a harness's loaded config into the object `createOpenVikingMcpProxy`
- * expects.
- *
- * `mcpUrl` wins over `baseUrl` when both are given, so a harness that lets the
- * user pin an explicit MCP URL keeps that behavior. `watchedPaths` are the
- * harness's own extra files; the shared defaults are appended and the result
- * deduplicated.
- */
-export function buildMcpProxyConfig({
- baseUrl = "",
- mcpUrl = "",
- apiKey = "",
- account = "",
- user = "",
- peerId = "",
- userAgent = "",
- timeoutMs,
- debug = false,
- debugLogPath = "",
- credentialSource = "auto",
- credentialPath = "",
- watchedPaths = [],
- env = process.env,
-} = {}) {
- return {
- mcpUrl: mcpUrl || `${trimSlash(baseUrl)}/mcp`,
- apiKey: apiKey || "",
- account: account || "",
- user: user || "",
- peerId: peerId || "",
- userAgent: userAgent || "",
- timeoutMs: Math.max(
- MIN_PROXY_TIMEOUT_MS,
- Number(timeoutMs) || DEFAULT_PROXY_TIMEOUT_MS,
- ),
- debug: debug === true,
- debugLogPath,
- credentialSource: credentialSource || "auto",
- credentialPath: credentialPath || "",
- watchedPaths: uniq([...watchedPaths, ...defaultCredentialPaths(env)]),
- };
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs b/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs
deleted file mode 100644
index 9a8f5ba26..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/mcp-proxy-core.mjs
+++ /dev/null
@@ -1,516 +0,0 @@
-// 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);
- if (err && err.name === "AbortError") {
- // Client-side timeout, not an outage: the server may be healthy and
- // still computing (rerank-inclusive find/search can legitimately take
- // longer than the default budget). Keep -32001 for genuine
- // connection failures so the two are not misdiagnosed as each other.
- return errorResponse(
- id,
- -32004,
- `OpenViking MCP request timed out after ${proxyConfig.timeoutMs}ms (${proxyConfig.mcpUrl}). The server may still be processing (rerank can be slow) — check /health or raise OPENVIKING_TIMEOUT_MS.`,
- { timeoutMs: proxyConfig.timeoutMs, mcpUrl: proxyConfig.mcpUrl, cause: msg },
- );
- }
- return errorResponse(
- id,
- -32001,
- `OpenViking MCP request failed. Check the configured URL (${proxyConfig.mcpUrl}) and that the OpenViking server (\`openviking-server\`) is reachable.`,
- { 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
deleted file mode 100644
index 38dccb1c8..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/pending-queue.mjs
+++ /dev/null
@@ -1,487 +0,0 @@
-// 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. The queue is replayed in small
- * batches, either at session-start (consuming retry budgets, with
- * maxRetries/TTL) or by a long-running drainer that passes
- * `consumeRetries: false` so transient failures stay retryable.
- *
- * 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";
-import { isRetryableFailure } from "./retryable.mjs";
-
-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) {
- return isRetryableFailure(res);
-}
-
-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;
- }
-}
-
-/**
- * Release a claimed file back to the queue without consuming a retry. The
- * entry keeps its original filename, retry count, and createdAt position, so a
- * later run retries it as if this attempt never happened.
- */
-export async function releaseClaim(claimedFilename) {
- if (!claimedFilename.endsWith(".processing")) return null;
- const dir = getPendingDir();
- const restored = pendingFromProcessingFilename(claimedFilename);
- try {
- await rename(join(dir, claimedFilename), join(dir, restored));
- return restored;
- } 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
- * @param {object} [options]
- * @param {boolean} [options.consumeRetries=true] - when false, retryable
- * failures release their claim instead of incrementing the retry count, so
- * a background drainer can keep retrying a transient failure without
- * burning the session-start retry budget. Exhausted and non-retryable
- * entries are deleted exactly as in the default mode.
- * @returns {{ replayed: number, failed: number, skipped: number, deferred: number }}
- */
-export async function replayPending(fetchJSON, log, options = {}) {
- const consumeRetries = options.consumeRetries !== false;
- 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 (entry.type === "commitSession") {
- log("pending-queue", {
- action: "commit-replay",
- sessionId: entry.sessionId,
- ok: Boolean(res?.ok),
- status: res?.result?.status || res?.status,
- trace_id: res?.traceId || res?.result?.trace_id,
- error: res?.ok ? undefined : res?.error?.message || res?.error?.code,
- });
- }
-
- if (res?.ok) {
- await dequeue(claimedFilename);
- replayed++;
- } else if (!isRetryableReplayFailure(res)) {
- await dequeue(claimedFilename);
- skipped++;
- } else {
- if (consumeRetries) {
- await incrementRetry(claimedFilename, entry);
- } else {
- const released = await releaseClaim(claimedFilename);
- log("pending-queue", {
- action: released ? "replay-deferred" : "release-failed",
- sessionId: entry.sessionId,
- type: entry.type,
- status: res?.result?.status || res?.status,
- retries: entry.retries || 0,
- });
- }
- 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
deleted file mode 100644
index 3f601844a..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/profile-inject.mjs
+++ /dev/null
@@ -1,294 +0,0 @@
-// 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-compress-core.mjs b/examples/zcode-memory-plugin/scripts/shared/recall-compress-core.mjs
deleted file mode 100644
index 1ced4cf4d..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/recall-compress-core.mjs
+++ /dev/null
@@ -1,206 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
-
-export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
-export const DIGEST_HEADER = "OpenViking memory digest:";
-const COMPRESS_OK = "ok";
-const COMPRESS_EMPTY = "empty";
-const COMPRESS_FAILED = "failed";
-
-// Medium-constraint prompt: state the goal and two structural floors, but no hard
-// bullet-length contract. Hard per-bullet limits pin the digest to headline
-// density; leaving it unconstrained lets small models rewrite long URIs into dead
-// links, which the URI repair below cleans up.
-export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
- return `You are a memory relevance compressor utility.
-Do not use any tools. Do not investigate. Only transform the given text.
-
-User query:
-${query}
-
-Retrieved OpenViking context fragments:
-${rendered}
-
-Write a memory digest for a coding agent about to answer that query. Keep the
-concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
-and conversational filler.
-
-Format rules:
-- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
-- Start every bullet with "- ".
-- End every bullet with its source, copied verbatim from the fragments above:
- "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
-- Output the digest body only. No preamble, no closing remark.
-
-If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
-}
-
-function editDistance(a, b) {
- if (a === b) return 0;
- const rows = a.length + 1;
- const cols = b.length + 1;
- let prev = Array.from({ length: cols }, (_, i) => i);
- for (let i = 1; i < rows; i += 1) {
- const cur = [i];
- for (let j = 1; j < cols; j += 1) {
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
- cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
- }
- prev = cur;
- }
- return prev[cols - 1];
-}
-
-function nearestUri(candidate, validUris) {
- let best = "";
- let bestDistance = Infinity;
- for (const uri of validUris) {
- const distance = editDistance(candidate, uri);
- if (distance < bestDistance) {
- best = uri;
- bestDistance = distance;
- }
- }
- // Only repair near-misses; an unrelated hallucination is dropped instead.
- const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
- return bestDistance <= tolerance ? best : "";
-}
-
-/**
- * Small models occasionally mangle long URIs. Snap every cited URI back onto the
- * set the server actually returned, and drop bullets whose citation cannot be
- * recovered so the digest never carries a dead link.
- */
-export function repairDigestUris(digest, validUris = []) {
- const text = String(digest || "");
- if (!text) return "";
- const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
- if (!valid.length) return text;
- const validSet = new Set(valid);
-
- const lines = [];
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim().startsWith("- ")) {
- lines.push(line);
- continue;
- }
- let tokenized = line;
- for (const uri of [...valid].sort((a, b) => b.length - a.length)) {
- if (/\s/.test(uri)) tokenized = tokenized.split(uri).join(encodeURI(uri));
- }
- let dropped = false;
- const repaired = tokenized.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
- let decoded = uri;
- try { decoded = decodeURI(uri); } catch { /* keep the original candidate */ }
- if (validSet.has(decoded)) return decoded;
- const nearest = nearestUri(decoded, valid);
- if (nearest) return nearest;
- dropped = true;
- return uri;
- });
- if (!dropped) lines.push(repaired);
- }
- return lines.join("\n").trim();
-}
-
-export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
- const text = String(raw || "").trim();
- if (!text) return null;
- if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
- const bullets = text.split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
- .slice(0, Math.max(1, maxBullets))
- .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
- if (!bullets.length) return null;
- return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
-}
-
-export function recallDigestCacheKey({
- query = "",
- rendered = "",
- entries = [],
- maxInputChars = 18000,
- maxBullets = 6,
-} = {}) {
- const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
- const source = JSON.stringify({
- version: 2,
- query: String(query),
- rendered: String(rendered).slice(0, maxInputChars),
- uris,
- maxInputChars,
- maxBullets,
- });
- return createHash("sha256").update(source).digest("hex");
-}
-
-async function readCache(path) {
- if (!path) return null;
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeCache(path, value) {
- if (!path) return;
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-export async function compressRecallContext({
- query,
- rendered,
- shortContext = rendered,
- entries = [],
- cfg = {},
- runCompressor,
- cachePath = "",
- now = 0,
-}) {
- const input = String(rendered || "").trim();
- if (!input) return { status: COMPRESS_EMPTY, context: "" };
- const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
- if (input.length < minChars) {
- return { status: COMPRESS_OK, context: String(shortContext ?? input).trim() };
- }
-
- const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
- const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
- const key = recallDigestCacheKey({
- query,
- rendered: input,
- entries,
- maxInputChars,
- maxBullets,
- });
- const cached = await readCache(cachePath);
- if (cached?.key === key && typeof cached.digest === "string") {
- const digest = normalizeCompressedContext(cached.digest, 4000, maxBullets);
- if (digest) return { status: COMPRESS_OK, context: digest };
- }
-
- const prompt = buildRecallCompressionPrompt({
- query,
- rendered: input.slice(0, maxInputChars),
- maxBullets,
- });
- const raw = await runCompressor(prompt);
- const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
- if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
- if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
-
- const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
- const repaired = repairDigestUris(normalized, validUris.length
- ? validUris
- : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
- const digest = normalizeCompressedContext(repaired, 4000, maxBullets);
- if (!digest) return { status: COMPRESS_FAILED, context: "" };
-
- await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
- return { status: COMPRESS_OK, context: digest };
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs b/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
deleted file mode 100644
index 72835de8f..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/recall-core.mjs
+++ /dev/null
@@ -1,678 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-
-import { compressRecallContext } from "./recall-compress-core.mjs";
-
-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://~/memories", bucket: "memories" },
- { type: "skill", uri: "viking://~/skills", bucket: "skills" },
-];
-const DEFAULT_CONTEXT_LIMIT = 10;
-const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
-const DEFAULT_REWRITE_MAX_BULLETS = 6;
-const CODING_QUOTA_WEIGHTS = {
- events: 1,
- entities: 2,
- preferences: 1,
- experiences: 1,
- resources: 3,
- skills: 2,
-};
-
-let userSpaceCache = "";
-
-export function estimateTokens(text) {
- return text ? Math.ceil(String(text).length / 4) : 0;
-}
-
-function scaleQuotas(limit, weights) {
- const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
- const order = Object.keys(weights);
- const quotas = Object.fromEntries(order.map((key) => [key, 0]));
- if (slots < order.length) {
- for (const key of order) quotas[key] = 1;
- return quotas;
- }
-
- for (const key of order) quotas[key] = 1;
- const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
- const ideals = Object.fromEntries(
- order.map((key) => [key, slots * weights[key] / totalWeight]),
- );
- while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
- const key = order.reduce((best, candidate) => (
- ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
- ? candidate
- : best
- ));
- quotas[key] += 1;
- }
- return quotas;
-}
-
-function legacyMemoryQuotas(limit) {
- return {
- ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
- experiences: 0,
- };
-}
-
-function codingQuotas(limit) {
- return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
-}
-
-export function buildRecallEndpointBody(cfg = {}) {
- const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
- const body = {
- query: "",
- quotas: legacyMemoryQuotas(limit),
- 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;
-}
-
-/**
- * Body for the server-side context face. The plugin declares intent (coding
- * purpose, budget, session) and leaves the mechanics — quota ratios, tier
- * degradation, cross-turn dedup — to the server's defaults.
- */
-export function buildContextSearchBody(cfg = {}, options = {}) {
- const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
- const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
- const maxTokens = Math.max(
- 64,
- Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
- );
- const body = {
- query: "",
- mode: "context",
- purpose: "coding",
- score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
- };
- const limitConfigured = cfg.recallLimitConfigured === true;
- const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
- if (limitConfigured) body.quotas = codingQuotas(limit);
- if (maxTokensConfigured) body.max_tokens = maxTokens;
- if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
-
- const sessionId = String(options.sessionId || "").trim();
- if (sessionId) {
- body.session_id = sessionId;
- const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
- if (queryExpansionConfigured) {
- body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
- }
- const dedupTurns = Number(cfg.recallDedupTurns);
- const resolvedDedupTurns = Number.isFinite(dedupTurns)
- ? Math.max(0, Math.floor(dedupTurns))
- : 5;
- if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
- }
-
- const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
- if (excludeUris.length) body.exclude_uris = excludeUris;
-
- if (rewriteMode === "server") body.rewrite = true;
- else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
- const rewriteMaxBullets = Math.max(
- 1,
- Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
- );
- const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
- if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
- body.rewrite_max_bullets = rewriteMaxBullets;
- }
- return body;
-}
-
-// The server pipeline is serial and each optional stage has its own fuse. A
-// request is aborted client-side unless its deadline covers every stage it
-// asked for, and aborting discards the whole response rather than just the
-// stage that ran long.
-//
-// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
-// always -> retrieval, body reads, budget planning
-// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
-//
-// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
-// a quarter to spare.
-const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
-const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
-
-/**
- * HTTP deadline for one context request, or undefined to keep the caller's own.
- *
- * Derived from the request body, because the body is what states which server
- * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
- * that also spends the expansion or rewrite fuse.
- */
-export function contextRequestTimeoutMs(cfg = {}, body = {}) {
- const wantsRewrite = body.rewrite !== undefined;
- // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
- // takes the expansion fuse back out of the budget.
- const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
- const configured = Number(cfg.recallContextTimeoutMs);
- if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
- if (!wantsRewrite && !wantsExpansion) return undefined;
- const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
- return Math.max(Number(cfg.timeoutMs) || 0, floor);
-}
-
-/**
- * Strip the context-face fields a pre-context server rejects, converting the
- * token budget back to v1's character budget.
- */
-export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
- const body = buildRecallEndpointBody(cfg);
- body.query = contextBody.query || "";
- body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
- if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
- 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(/\/+$/, "");
- // viking://~ is the home alias: the server expands it to the caller's own user
- // space, so it needs no client-side rewrite.
- if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
- // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
- // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
- 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");
-}
-
-const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
-
-function stateFile(name) {
- const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
- return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
-}
-
-async function readJsonFile(path) {
- try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
-}
-
-async function writeJsonFile(path, value) {
- try {
- await mkdir(dirname(path), { recursive: true });
- const tmp = `${path}.tmp`;
- await writeFile(tmp, JSON.stringify(value));
- await rename(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Hooks are one-shot processes, so "this server has no context face" has to be
- * remembered on disk or every turn pays for a rejected request.
- */
-export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- const cached = await readJsonFile(path);
- return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
-}
-
-export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
- await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
-}
-
-/**
- * A `peer_scope` the server rejects is remembered the same way, but unlike the
- * context face this one is not a silent capability probe: dropping the field
- * widens recall from the caller's own peer to the whole user root, so doctor
- * reads this file back and warns.
- */
-export function peerScopeMemoPath() {
- return stateFile("peer-scope.json");
-}
-
-export async function readPeerScopeDowngrade(path = peerScopeMemoPath(), now = Date.now()) {
- const cached = await readJsonFile(path);
- if (!cached?.legacyUntil || Number(cached.legacyUntil) <= now) return null;
- return cached;
-}
-
-export async function markPeerScopeDowngrade(scope, status, path = peerScopeMemoPath(), now = Date.now()) {
- await writeJsonFile(path, {
- legacyUntil: now + LEGACY_CACHE_TTL_MS,
- scope: String(scope || ""),
- status: Number(status) || 0,
- at: now,
- });
-}
-
-function looksLikeUnknownField(res) {
- const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
- return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
-}
-
-function wrapContext(body) {
- return [
- "<openviking-context>",
- "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
- body,
- "</openviking-context>",
- ].join("\n");
-}
-
-/**
- * Server-assembled context: the context face when the deployment has it, else
- * the deprecated /recall preset. Returns the injection block, "" when there was
- * nothing relevant, or null when no server-side path was usable at all.
- */
-export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
-
- const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
- if (block !== null) return block;
- return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
-}
-
-/**
- * Raw server-assembled context, or null when the deployment has no context face.
- * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
- * (their own compression, their own envelope) use this instead of the block
- * builders below.
- */
-export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId || "";
- const log = options.log || (() => {});
- if (await isContextFaceLegacy(options.legacyCachePath)) return null;
-
- const body = buildContextSearchBody(cfg, options);
- body.query = query;
- const res = await fetchJSON("/api/v1/search/search", {
- method: "POST",
- body: JSON.stringify(body),
- }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
-
- if (!res.ok) {
- const status = res.status || 0;
- if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
- await markContextFaceLegacy(options.legacyCachePath);
- log("recall_context_face_unsupported", { status });
- } else {
- log("recall_context_face_error", { status });
- }
- return null;
- }
-
- const result = res.result || {};
- const stats = result.stats || {};
- log("recall_context_assembled", {
- entries: Array.isArray(result.entries) ? result.entries.length : 0,
- usedTokens: stats.used_tokens || 0,
- tiers: stats.tier_counts || {},
- rewrite: stats.rewrite || "off",
- });
- return {
- rendered: String(result.rendered || "").trim(),
- entries: Array.isArray(result.entries) ? result.entries : [],
- digest: String(result.digest || "").trim(),
- stats,
- };
-}
-
-/**
- * Entry field compatibility: the context face returns `category`/`text`, while
- * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
- */
-export function normalizeContextEntry(entry = {}) {
- return {
- uri: String(entry.uri || "").trim(),
- category: String(entry.category || entry.type || "memory").trim() || "memory",
- detail: String(entry.detail || entry.mode || "").trim(),
- score: Number(entry.score) || 0,
- text: String(
- entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
- ).trim(),
- };
-}
-
-async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
- const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
- if (assembled === null) return null;
-
- const { rendered, entries } = assembled;
- let digest = assembled.digest;
- const mode = String(cfg.recallRewrite || "off").toLowerCase();
- if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
- log("recall_server_compression", { status: "empty" });
- return "";
- }
- const wantsLocal = mode === "client" || (mode === "auto" && !digest);
- if (wantsLocal && rendered && typeof options.runCompressor === "function") {
- try {
- const compression = await compressRecallContext({
- query,
- rendered,
- entries,
- cfg,
- runCompressor: options.runCompressor,
- cachePath: options.digestCachePath || stateFile("recall-digest.json"),
- now: Date.now(),
- });
- log("recall_local_compression", { status: compression.status });
- if (compression.status === "ok") digest = compression.context;
- if (compression.status === "empty") return "";
- } catch (err) {
- log("recall_local_compression_failed", { error: String(err?.message || err) });
- }
- }
-
- const injected = digest || rendered;
- if (!injected) return "";
- return wrapContext(injected);
-}
-
-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 wrapContext(rendered);
-}
-
-export async function postRecall(fetchJSON, body, opts = {}) {
- const actorPeerId = opts.actorPeerId || "";
- const log = opts.log || (() => {});
- const memoPath = opts.peerScopeMemoPath;
- const request = { ...body };
-
- // A remembered downgrade is still a downgrade: recall runs wider than the
- // caller asked for, so the memo doubles as the doctor's evidence.
- if (request.peer_scope && await readPeerScopeDowngrade(memoPath)) {
- delete request.peer_scope;
- }
-
- 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;
- }
- // Only an unknown-field rejection means "this server predates peer_scope".
- // Retrying every other 400/422 without it silently widens the search from
- // the caller's own peer to the whole user root.
- if (!looksLikeUnknownField(res)) {
- log("recall_peer_scope_error", { status: res.status || 0 });
- return res;
- }
-
- const downgraded = { ...request };
- delete downgraded.peer_scope;
- await markPeerScopeDowngrade(String(request.peer_scope), res.status || 0, memoPath);
- log("recall_peer_scope_downgrade", { status: res.status || 0 });
- return fetchJSON("/api/v1/search/recall", {
- method: "POST",
- body: JSON.stringify(downgraded),
- }, { actorPeerId });
-}
-
-/**
- * Recall, plus whatever is still filed under the peer this workspace used
- * before the identity rule changed.
- *
- * Under the default `peer_scope: "all"` this costs nothing: the server's own
- * sweep of `{user_root}/peers` already reaches the old peer's memories. Under
- * `"actor"` that sweep is off by definition, so the old peer is asked for
- * separately — as itself, which is both cheaper and wider than a bare
- * cross-peer read (that would need the user id, and reaches memories only).
- */
-export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
- const primary = await recallForPeer(fetchJSON, cfg, query, options);
-
- const legacyPeerId = String(options.legacyPeerId || "").trim();
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- if (cfg.recallPeerScope !== "actor" || !legacyPeerId || legacyPeerId === actorPeerId) return primary;
-
- const log = options.log || (() => {});
- const legacy = await recallForPeer(fetchJSON, cfg, query, { ...options, actorPeerId: legacyPeerId });
- if (!legacy) return primary;
- log("recall_legacy_peer_hit", { legacyPeerId });
- return primary ? `${primary}\n${legacy}` : legacy;
-}
-
-async function recallForPeer(fetchJSON, cfg, query, options = {}) {
- const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
- const log = options.log || (() => {});
- const trimmed = String(query || "").trim();
- if (!trimmed) return null;
-
- // Assembly happens server-side when the deployment offers the context face;
- // older servers fall through to /recall, then to raw find.
- const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
- ...options,
- actorPeerId,
- log,
- });
- if (serverBlock !== null) return serverBlock || null;
-
- const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
- 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/retryable.mjs b/examples/zcode-memory-plugin/scripts/shared/retryable.mjs
deleted file mode 100644
index 8be4b14e8..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/retryable.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-export function isRetryableFailure(result) {
- if (!result || result.ok) return false;
- const status = Number(result.status || 0);
- if (!status || status === 408 || status === 429 || status >= 500) {
- return true;
- }
- return status === 409 && result.error?.details?.retryable === true;
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/session-model.mjs b/examples/zcode-memory-plugin/scripts/shared/session-model.mjs
deleted file mode 100644
index b6496a113..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/session-model.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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/uri-guard.mjs b/examples/zcode-memory-plugin/scripts/shared/uri-guard.mjs
deleted file mode 100644
index cf57bf406..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/uri-guard.mjs
+++ /dev/null
@@ -1,78 +0,0 @@
-// 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();
-}
-
-// Arguments that carry file CONTENT rather than a location. The sweep below
-// looks past the known path keys so an unusual one (`paths`, a nested target)
-// is still caught, but text a tool is asked to WRITE is not a path: a local
-// `write` whose body merely mentions viking://user/default/ was denied, and no
-// file was created. Skipped by name at any depth.
-const DEFAULT_CONTENT_KEYS = [
- "content",
- "contents",
- "text",
- "body",
- "old_string",
- "oldString",
- "new_string",
- "newString",
- "old_str",
- "new_str",
- "file_text",
- "insert_line",
- "replacement",
-];
-
-export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = DEFAULT_CONTENT_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, new Set(contentKeys));
-}
-
-export function findVikingUriInValue(value, skipKeys) {
- 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, skipKeys);
- if (uri) return uri;
- }
- return null;
- }
- if (value && typeof value === "object") {
- for (const [key, item] of Object.entries(value)) {
- if (skipKeys?.has(key)) continue;
- const uri = findVikingUriInValue(item, skipKeys);
- 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-identity.mjs b/examples/zcode-memory-plugin/scripts/shared/workspace-identity.mjs
deleted file mode 100644
index 76922cb03..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/workspace-identity.mjs
+++ /dev/null
@@ -1,334 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Workspace identity: where the workspace root is, and what git calls it.
- *
- * Every hook is a fresh Node process and this runs on prompt-level paths, so
- * the derivation is pure filesystem work — no `git` subprocess. That keeps it
- * inside the tightest hook budget (Codex allows SessionEnd 3s against
- * SessionStart's 70s), and it keeps working where git is absent from PATH or
- * would refuse the repo over dubious ownership.
- *
- * The result is cached per cwd under the state dir so the several hooks of one
- * turn pay for the walk once.
- */
-
-import { createHash } from "node:crypto";
-import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
-
-// The workspace config file names live here, and `workspace-config.mjs`
-// re-exports them: the walk below needs the filenames to recognise a directory
-// someone marked as a workspace, and it must not pull in the config layer to
-// learn them.
-export const CONFIG_DIR_NAME = ".openviking";
-export const TEAM_FILE = "config.json";
-export const LOCAL_FILE = "config.local.json";
-
-const IDENTITY_CACHE_TTL_MS = 60_000;
-// 255 is the AGFS path-segment limit; stopping well short leaves room for the
-// hash suffix and for anything that later prefixes a peer id.
-const MAX_PEER_ID_LENGTH = 100;
-
-export function stateDir(env = process.env) {
- const explicit = String(env.OPENVIKING_STATE_DIR || "").trim();
- if (explicit) return explicit;
- const home = String(env.OPENVIKING_HOME || "").trim();
- const base = home ? home.replace(/^~(?=$|\/)/, homedir()) : join(homedir(), ".openviking");
- return join(base, "state");
-}
-
-function shortHash(value) {
- return createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
-}
-
-/**
- * Legacy peer sanitation: one byte in, one byte out, no collapsing and no
- * trimming, so a leading `/` still becomes a leading `-`. Kept byte-exact
- * because `peer.source: "cwd"` and the legacy id that dual-read recomputes both
- * depend on it — do not "improve" it.
- */
-export function legacySanitize(value) {
- return String(value || "").replace(/[^A-Za-z0-9]/g, "-");
-}
-
-/**
- * Readable sanitation for values that were never path-shaped — a normalized
- * remote, a directory name. Mirrors the server's own `_sanitize_component`
- * (`openviking/ingest/peer.py:32`) so both languages agree on the id, then
- * enforces what `validate_identifier_part` additionally requires.
- */
-export function sanitizePeerId(value) {
- const raw = String(value || "").trim();
- let cleaned = raw.replace(/[^a-zA-Z0-9_.@-]+/g, "-").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
- if (!cleaned) return "";
- // The server accepts at most one `@` in an identifier part.
- const at = cleaned.indexOf("@");
- if (at !== -1) cleaned = cleaned.slice(0, at + 1) + cleaned.slice(at + 1).replace(/@/g, "-");
- // `ext-` is the server's namespace for base64-encoded external identities,
- // and `__self` its operation-target sentinel. Neither is ours to occupy.
- if (cleaned.startsWith("ext-")) cleaned = `x-${cleaned}`;
- if (cleaned === "__self") cleaned = "self";
- if (cleaned === "." || cleaned === "..") return "";
- if (cleaned.length > MAX_PEER_ID_LENGTH) {
- cleaned = `${cleaned.slice(0, MAX_PEER_ID_LENGTH - 13).replace(/[-.]+$/, "")}-${shortHash(raw)}`;
- }
- return cleaned;
-}
-
-/**
- * Normalize a remote URL to `host/path`, lowercased.
- *
- * Both spellings of the same repo converge, and userinfo is dropped — so a
- * remote with an embedded token cannot leak it into a peer id. The cost of
- * case folding is that two repos differing only in case share one namespace on
- * the rare case-sensitive forge.
- */
-export function normalizeGitRemote(url) {
- const raw = String(url || "").trim();
- if (!raw) return "";
-
- // `C:\src\repo` and `C:/src/repo` are one machine's directory, not a shared
- // identity — and the scp pattern would happily read the drive as a host.
- if (/^[A-Za-z]:[\\/]/.test(raw)) return "";
-
- let host = "";
- let path = "";
- const scp = /^(?:[^@/\\]+@)?([^:/\\]+):(?!\/)(.+)$/.exec(raw);
- if (scp && !/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(raw)) {
- host = scp[1];
- path = scp[2];
- } else {
- let parsed;
- try {
- parsed = new URL(raw);
- } catch {
- return "";
- }
- // A local clone has no stable shared identity — fall through to the path
- // rules instead of minting one from `file://` or a bare directory.
- if (parsed.protocol === "file:" || !parsed.hostname) return "";
- host = parsed.hostname;
- path = parsed.pathname;
- }
-
- host = host.toLowerCase().replace(/^\[|\]$/g, "");
- path = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "").toLowerCase();
- if (!host || !path) return "";
- return `${host}/${path}`;
-}
-
-function readFileOrEmpty(path) {
- try {
- return readFileSync(path, "utf-8");
- } catch {
- return "";
- }
-}
-
-/**
- * Read `[remote "origin"] url` out of a git config with a minimal INI parse.
- *
- * `include` / `includeIf` are deliberately not followed: resolving them means
- * more filesystem walking for a value the fallback chain already covers, so an
- * unreadable remote just falls through to the next template.
- */
-export function readGitRemoteUrl(commonDir, remote = "origin") {
- const text = readFileOrEmpty(join(commonDir, "config"));
- if (!text) return "";
-
- let inSection = false;
- for (const line of text.split("\n")) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) continue;
- const section = /^\[([^\]]+)\]/.exec(trimmed);
- if (section) {
- const header = section[1].trim();
- // git folds section and key names to lower case but keeps a quoted
- // subsection exact, so `[Remote "origin"]` is the same section and
- // `[remote "Origin"]` is not.
- const quoted = /^remote\s+"(.*)"$/i.exec(header);
- inSection = Boolean(quoted && quoted[1] === remote);
- continue;
- }
- if (!inSection) continue;
- const pair = /^url\s*=\s*(.*)$/i.exec(trimmed);
- // git treats an unquoted `#` or `;` as starting a comment anywhere on the
- // line, so a trailing note is not part of the URL.
- if (pair) return pair[1].split(/[#;]/)[0].trim().replace(/^["']|["']$/g, "");
- }
- return "";
-}
-
-function resolveGitDir(root) {
- const dotGit = join(root, ".git");
- let stat;
- try {
- stat = statSync(dotGit);
- } catch {
- return null;
- }
- if (stat.isDirectory()) return { gitDir: dotGit, commonDir: dotGit, kind: "repo" };
- if (!stat.isFile()) return null;
-
- const pointer = /^gitdir:\s*(.+)$/m.exec(readFileOrEmpty(dotGit));
- if (!pointer) return null;
- const gitDir = resolve(root, pointer[1].trim());
-
- // `commondir` is the worktree signal, so it is read first — a repository
- // that merely lives under a directory called `modules` is not a submodule.
- const commonRef = readFileOrEmpty(join(gitDir, "commondir")).trim();
- const commonDir = commonRef
- ? (isAbsolute(commonRef) ? commonRef : resolve(gitDir, commonRef))
- : gitDir;
-
- // A submodule keeps its own remote under the superproject's
- // `.git/modules/<name>`; converging it onto the superproject would merge two
- // repositories that release, and are reviewed, separately. Only the segment
- // right after a `.git` directory means that, which is also why a worktree of
- // a submodule resolves here through its own commondir.
- const kind = /[/\\]\.git[/\\]modules[/\\]/.test(`${commonDir}${sep}`)
- ? "submodule"
- : (commonRef ? "worktree" : "repo");
- return { gitDir, commonDir, kind };
-}
-
-/** A directory the user made a workspace on purpose, by giving it a config file. */
-function hasWorkspaceMarker(dir) {
- for (const name of [TEAM_FILE, LOCAL_FILE]) {
- try {
- if (statSync(join(dir, CONFIG_DIR_NAME, name)).isFile()) return true;
- } catch { /* not marked here */ }
- }
- return false;
-}
-
-const NO_ROOT = Object.freeze({ root: "", rootKind: "", git: null, gitRoot: "" });
-
-/**
- * Walk up from `cwd` to the nearest workspace root.
- *
- * A workspace is a git repository, or a directory someone marked as one by
- * creating `.openviking/config.json` (or `config.local.json`) in it. Nearest
- * wins. Above a marked directory the walk continues to the enclosing
- * repository, if any, so the git-shaped variables still resolve there.
- * Anything else — a scratch folder, a download, an app's per-task directory —
- * is not a workspace and gets no peer of its own.
- *
- * `$HOME` and the filesystem root are never workspace roots: a stray `.git`
- * in either would silently make every unrelated directory one workspace.
- */
-export function findWorkspaceRoot(cwd, env = process.env) {
- const start = String(cwd || "").trim();
- if (!start) return NO_ROOT;
-
- let absolute;
- try {
- // A relative `start` makes `resolve` read process.cwd(), which throws when
- // the directory is gone — the very case the catch below is meant to cover.
- absolute = resolve(start);
- } catch {
- return NO_ROOT;
- }
-
- // `current` and `stopAt` are compared as strings, so they must be
- // canonicalized together. A `$HOME` reached through a symlink plus an
- // unresolvable cwd would otherwise walk straight past the guard.
- const home = String(env.HOME || "").trim() || homedir();
- let current;
- let stopAt;
- try {
- current = realpathSync(absolute);
- stopAt = realpathSync(home);
- } catch {
- current = absolute;
- stopAt = home;
- }
- const filesystemRoot = parse(current).root;
- if (current === stopAt || current === filesystemRoot) return NO_ROOT;
-
- let root = "";
- let rootKind = "";
- while (current && current !== filesystemRoot && current !== stopAt) {
- const git = resolveGitDir(current);
- if (git) return { root: root || current, rootKind: rootKind || "git", git, gitRoot: current };
- if (!root && hasWorkspaceMarker(current)) {
- root = current;
- rootKind = "config";
- }
- const parent = dirname(current);
- if (parent === current) break;
- current = parent;
- }
- return root ? { root, rootKind, git: null, gitRoot: "" } : NO_ROOT;
-}
-
-function cachePath(cwd, env) {
- return join(stateDir(env), `ws-identity-${shortHash(cwd)}.json`);
-}
-
-function readCache(path, now) {
- try {
- const cached = JSON.parse(readFileSync(path, "utf-8"));
- // Bounded on both sides: an entry stamped in the future — a clock that ran
- // fast, or `Infinity` — would otherwise pin a stale identity indefinitely.
- if (typeof cached?.ts !== "number" || cached.ts > now || now - cached.ts > IDENTITY_CACHE_TTL_MS) return null;
- const identity = cached.identity;
- if (identity && typeof identity === "object" && identity.vars && typeof identity.vars === "object") {
- return identity;
- }
- } catch { /* a cold or corrupt cache just costs one walk */ }
- return null;
-}
-
-function writeCache(path, identity, now) {
- try {
- mkdirSync(dirname(path), { recursive: true });
- const tmp = `${path}.${process.pid}.tmp`;
- writeFileSync(tmp, JSON.stringify({ ts: now, identity }), { mode: 0o600 });
- renameSync(tmp, path);
- } catch { /* best effort */ }
-}
-
-/**
- * Everything the peer templates can substitute, for one cwd.
- *
- * `git_remote` and `dir` are already sanitized; `git_root` and `cwd` carry the
- * legacy byte-for-byte rule, because they are the two that must reproduce a
- * peer minted before any of this existed.
- */
-export function resolveWorkspaceIdentity({ cwd = "", env = process.env, cache = true, now = Date.now() } = {}) {
- const key = String(cwd || "");
- const path = cachePath(key, env);
- if (cache) {
- const hit = readCache(path, now);
- if (hit) return hit;
- }
-
- const { root, rootKind, git, gitRoot } = findWorkspaceRoot(key, env);
- // Only the normalized form is kept. The raw URL may carry a token, and this
- // file outlives the process — writing it here would undo the care
- // `normalizeGitRemote` takes to drop userinfo.
- const remote = git ? normalizeGitRemote(readGitRemoteUrl(git.commonDir)) : "";
- const identity = {
- cwd: key,
- root,
- rootKind,
- isGit: Boolean(git),
- gitKind: git?.kind || "",
- gitCommonDir: git?.commonDir || "",
- gitRoot,
- remote,
- vars: {
- git_remote: sanitizePeerId(remote),
- // The enclosing repository's root, which is not the workspace root when a
- // marker file below it won. Empty outside a repository, so the `git`
- // preset resolves to nothing there rather than to a bare path.
- git_root: git ? legacySanitize(gitRoot) : "",
- cwd: legacySanitize(key),
- dir: root ? sanitizePeerId(root.split(/[/\\]/).filter(Boolean).pop() || "") : "",
- },
- };
- if (cache) writeCache(path, identity, now);
- return identity;
-}
diff --git a/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs b/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs
deleted file mode 100644
index 89df30793..000000000
--- a/examples/zcode-memory-plugin/scripts/shared/workspace-peer.mjs
+++ /dev/null
@@ -1,134 +0,0 @@
-// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
-/**
- * Which peer a workspace writes its memories under.
- *
- * The peer used to be the working directory with every non-alphanumeric byte
- * turned into a dash, which made the identity an accident of where the
- * repository happened to sit: a clone on another machine, a rename, a worktree
- * or simply `cd examples/` each minted a separate, empty namespace. The default
- * is now git's own idea of the repository, so one project keeps one memory
- * wherever it is checked out.
- *
- * `peer.source` decides the rule. Presets cover the three answers most people
- * want; a template — or a list of templates tried in order — covers the rest.
- * The old behaviour is still one word away, byte for byte.
- */
-
-import { legacySanitize, resolveWorkspaceIdentity, sanitizePeerId } from "./workspace-identity.mjs";
-
-/**
- * `git` is the default, and it resolves only inside a repository: the remote
- * first, because that is the one name every clone agrees on, then the
- * repository root for a repo that has none. Anywhere else it resolves to
- * nothing and no peer is sent — a scratch folder or an app's per-task
- * directory would otherwise mint a fresh, empty namespace each time, so those
- * memories go to the user-level space instead. Naming such a directory is what
- * `peer.id` is for, and deriving one from a bare path is what `cwd` is for;
- * both are opt-in.
- *
- * No preset adds a prefix. A path-derived id starts with `-` on POSIX, so it
- * cannot collide with a remote-derived one; anyone who wants a prefix writes
- * their own template.
- */
-export const PEER_SOURCE_PRESETS = {
- git: ["{git_remote}", "{git_root}"],
- cwd: ["{cwd}"],
- none: [],
-};
-
-export const DEFAULT_PEER_SOURCE = "git";
-
-const VARIABLE_RE = /\{([a-z_]+)\}/g;
-
-export function deriveWorkspacePeerId(cwd) {
- return legacySanitize(cwd);
-}
-
-/**
- * Normalize `peer.source` — a preset name, a template, or a list — to templates.
- *
- * A bare string with no `{` is a misspelled preset, not a template: `Git` or
- * `gti` would otherwise become a peer literally named `Git`, quietly stranding
- * the workspace's memories in a namespace nobody meant to create. Such a value
- * warns and falls back to the default chain. An array is left alone — writing a
- * list is explicit enough to mean the constant it contains.
- */
-export function peerSourceTemplates(source, onWarn = null) {
- if (Array.isArray(source)) return source.map(String).filter(Boolean);
- const raw = String(source ?? "").trim();
- if (!raw) return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
- if (Object.hasOwn(PEER_SOURCE_PRESETS, raw)) return PEER_SOURCE_PRESETS[raw];
- if (raw.includes("{")) return [raw];
-
- const message = `OpenViking: ignored peer.source ${JSON.stringify(raw)}: it is neither a preset `
- + `(${Object.keys(PEER_SOURCE_PRESETS).join(", ")}) nor a template such as "team-{dir}". `
- + `Falling back to ${DEFAULT_PEER_SOURCE}.`;
- if (typeof onWarn === "function") onWarn(message);
- else process.stderr.write(`${message}\n`);
- return PEER_SOURCE_PRESETS[DEFAULT_PEER_SOURCE];
-}
-
-/**
- * Substitute one template, or return "" when any variable it names is empty.
- *
- * All-or-nothing on purpose: a half-resolved template like `git-` would be a
- * silently shared identity, so an empty variable falls through to the next
- * template instead.
- */
-export function renderPeerTemplate(template, vars) {
- const text = String(template || "");
- if (!text) return "";
- let empty = false;
- const rendered = text.replace(VARIABLE_RE, (match, name) => {
- if (!Object.hasOwn(vars, name)) {
- empty = true;
- return "";
- }
- const value = String(vars[name] ?? "");
- if (!value) empty = true;
- return value;
- });
- return empty ? "" : rendered;
-}
-
-/**
- * The peer this process should send, and where it came from.
- *
- * `source` keeps its three values — call sites compare it against the literal
- * `"workspace"` to decide whether a session pin may be reused — while `origin`
- * names the template that actually produced the id, and `legacyPeerId` carries
- * the pre-git id whenever it differs, so recall can still reach memories
- * written under it.
- */
-export function resolveEffectivePeerId({ cfg = {}, cwd = "", identity = null, env = process.env, onWarn = null } = {}) {
- const explicit = String(cfg.peerId || "").trim();
- if (explicit) return { peerId: explicit, source: "explicit", origin: "explicit", legacyPeerId: "" };
-
- // `OPENVIKING_WORKSPACE_PEER=0` predates `peer.source` and still means "none".
- if (cfg.workspacePeer === false) return { peerId: "", source: "none", origin: "disabled", legacyPeerId: "" };
-
- const templates = peerSourceTemplates(cfg.peerSource, onWarn);
- if (!templates.length) return { peerId: "", source: "none", origin: "none", legacyPeerId: "" };
-
- // `harness` is composed here rather than in the identity, whose result is
- // cached on disk under a cwd-only key — two harnesses in one directory would
- // otherwise read each other's peer back out of that cache.
- const vars = {
- ...((identity || resolveWorkspaceIdentity({ cwd, env })).vars || {}),
- harness: sanitizePeerId(cfg.harness || cfg.clientId || ""),
- };
- const legacyPeerId = deriveWorkspacePeerId(cwd);
- for (const template of templates) {
- const peerId = renderPeerTemplate(template, vars);
- if (!peerId) continue;
- return {
- peerId,
- source: "workspace",
- origin: template,
- legacyPeerId: peerId === legacyPeerId ? "" : legacyPeerId,
- };
- }
- // No peer, but the pre-git id is still what earlier sessions in this
- // directory wrote under, so recall keeps reaching it.
- return { peerId: "", source: "none", origin: "unresolved", legacyPeerId };
-}
diff --git a/examples/zcode-memory-plugin/scripts/uri-guard.mjs b/examples/zcode-memory-plugin/scripts/uri-guard.mjs
deleted file mode 100644
index a415c537f..000000000
--- a/examples/zcode-memory-plugin/scripts/uri-guard.mjs
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/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
deleted file mode 100644
index f6f14c9c3..000000000
--- a/examples/zcode-memory-plugin/scripts/zcode-hook.mjs
+++ /dev/null
@@ -1,193 +0,0 @@
-#!/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,
- readHookState,
- recallForPrompt,
- replayAgentPending,
- resolveAgentCwd,
- resolveNativeSessionId,
- shouldBypassAgent,
- stableHash,
- withAgentHookLock,
- writeHookState,
-} from "./shared/agent-hook-runtime.mjs";
-import { maybeDetach, readHookStdin } from "./shared/async-writer.mjs";
-import { applyZcodeCaptureResult, buildZcodeCapturePlan } from "./zcode-capture.mjs";
-import { buildZcodeTurns, cleanZcodeText } from "./zcode-turns.mjs";
-
-const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";
-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",
- );
-}
-
-let input = {};
-let nativeSessionId = "";
-let sessionId = "";
-let cwd = "";
-let fetchJSON;
-
-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, { sessionId }).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 plan = buildZcodeCapturePlan(buildZcodeTurns(input, state), state, cfg);
-
- // Fail-closed: if no turns and no dedup keys, skip silently (not an error —
- // could be a Stop with no new content, or a race with UserPromptSubmit).
- if (plan.toSend.length === 0) return;
-
- const result = await addAgentMessages(fetchJSON, sessionId, plan.payloads);
- const { captured, ...nextState } = applyZcodeCaptureResult(state, plan, result);
- let nextCount = Number(state.capturedSinceCommit || 0) + captured;
- if (captured > 0) {
- const committed = await commitAgentSession(fetchJSON, sessionId, log);
- if (committed.ok) nextCount = 0;
- }
- await writeHookState("zcode", nativeSessionId, {
- ...nextState,
- capturedSinceCommit: nextCount,
- });
- });
- // Stop: no output needed (pass-through)
- return;
- }
-
- // Unknown event: pass-through silently
-}
-
-async function run() {
- if (eventName === "stop" && cfg.enabled && cfg.autoCapture) {
- const detached = await maybeDetach(cfg, { approve: () => {} });
- if (detached) return;
- }
-
- try {
- input = JSON.parse(await readHookStdin());
- } catch {
- input = {};
- }
-
- // ZCode may pass sessionId in camelCase or snake_case. Ensure both are present
- // so resolveNativeSessionId() finds it via the direct lookup path — avoids the
- // cwd fallback that would collide for two windows in the same directory.
- if (!input.session_id && input.sessionId) input.session_id = input.sessionId;
-
- nativeSessionId = resolveNativeSessionId(input);
- sessionId = deriveAgentSessionId("zc-", input);
- cwd = resolveAgentCwd(input);
- ({ fetchJSON } = makeAgentFetchJSON(cfg, cwd));
- await main();
-}
-
-run().catch((error) => {
- logError("uncaught", error);
- // Pass-through on error — never block the session
-});
diff --git a/examples/zcode-memory-plugin/servers/mcp-proxy.mjs b/examples/zcode-memory-plugin/servers/mcp-proxy.mjs
deleted file mode 100644
index 3e4f508a2..000000000
--- a/examples/zcode-memory-plugin/servers/mcp-proxy.mjs
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/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 { buildMcpProxyConfig, resolveMcpActorPeerId } from "../scripts/shared/mcp-proxy-config.mjs";
-import { createOpenVikingMcpProxy } from "../scripts/shared/mcp-proxy-core.mjs";
-
-function readConfig() {
- const cfg = loadAgentHookConfig("zcode");
- return buildMcpProxyConfig({
- mcpUrl: cfg.mcpUrl,
- apiKey: cfg.apiKey,
- account: cfg.account,
- user: cfg.user,
- peerId: resolveMcpActorPeerId(cfg),
- 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],
- });
-}
-
-if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {
- createOpenVikingMcpProxy({ readConfig, loggerFactory: createLogger }).start();
-}